Skip to content

fix(flow): global state collision and leakage#6281

Closed
dwisiswant0 wants to merge 3 commits intodevfrom
dwisiswant0/fix/flow/global-state-collision-and-leakage
Closed

fix(flow): global state collision and leakage#6281
dwisiswant0 wants to merge 3 commits intodevfrom
dwisiswant0/fix/flow/global-state-collision-and-leakage

Conversation

@dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented Jun 26, 2025

Proposed changes

Fixes #6263

Benchmark

Local Scoping v. Namespacing

Note

Local scoping == clean state (this patch).
Namespacing == runtime shared/reuse (old / prior to this PR/patch).

Local scoping:

// ...
let uniq = Dedupe();
// ...
for (let path of iterate(template["imports"])) {
  // ...
  uniq.Add(finalUrl);
}
// ...
for (let url of iterate(uniq.Values())) {
  // ...
}

Namespacing:

template["{{BaseURL}}_results"] = Dedupe();
// ...
for (let path of iterate(template["imports"])) {
  // ...
  template["{{BaseURL}}_results"].Add(finalUrl);
}
// ...
for (let url of iterate(template["{{BaseURL}}_results"].Values())) {
  // ...
}

old (runtime shared/reuse):

$ go test -benchmem -run=^$ -bench ^BenchmarkGetJSRuntime$ ./pkg/tmplexec/flow
goos: linux
goarch: amd64
pkg: github.com/projectdiscovery/nuclei/v3/pkg/tmplexec/flow
cpu: 11th Gen Intel(R) Core(TM) i9-11900H @ 2.50GHz
BenchmarkGetJSRuntime-16    	14630804	        80.35 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/projectdiscovery/nuclei/v3/pkg/tmplexec/flow	1.386s

patch (clean state):

$ go test -benchmem -run=^$ -bench ^BenchmarkGetJSRuntime$ ./pkg/tmplexec/flow
goos: linux
goarch: amd64
pkg: github.com/projectdiscovery/nuclei/v3/pkg/tmplexec/flow
cpu: 11th Gen Intel(R) Core(TM) i9-11900H @ 2.50GHz
BenchmarkGetJSRuntime-16    	  143451	      8376 ns/op	    8552 B/op	      66 allocs/op
PASS
ok  	github.com/projectdiscovery/nuclei/v3/pkg/tmplexec/flow	1.396s

benchstat:

$ benchstat namespacing.txt local-scoping.txt
goos: linux
goarch: amd64
pkg: github.com/projectdiscovery/nuclei/v3/cmd/nuclei
cpu: 11th Gen Intel(R) Core(TM) i9-11900H @ 2.50GHz
                       │ namespacing.txt │       local-scoping.txt       │
                       │     sec/op      │   sec/op     vs base          │
RunEnumeration/Flow-16       17.70 ± 33%   19.13 ± 25%  ~ (p=0.912 n=10)

                       │ namespacing.txt │       local-scoping.txt        │
                       │      B/op       │     B/op      vs base          │
RunEnumeration/Flow-16     73.31Mi ± 20%   70.11Mi ± 6%  ~ (p=0.052 n=10)

                       │ namespacing.txt │       local-scoping.txt       │
                       │    allocs/op    │  allocs/op   vs base          │
RunEnumeration/Flow-16      251.4k ± 16%   245.5k ± 5%  ~ (p=0.739 n=10)

Strange that the benchstat results show no statistically significant difference between the two approaches on a real-world task.

Steps to Test

$ gh pr checkout <this_pr_num>
$ make build-test
$ go test -benchmem -run=^$ -bench ^BenchmarkGetJSRuntime$ ./pkg/tmplexec/flow | tee BenchmarkGetJSRuntime-patch.txt # patch (clean state)
$ ./bin/nuclei.test -test.run - -test.bench="^BenchmarkRunEnumeration/Flow/Local-Scoping$" -test.benchmem -test.count=10 ./cmd/nuclei/ | tee local-scoping.txt # patch (clean state)
$ git revert b8631c52
$ make build-test
$ go test -benchmem -run=^$ -bench ^BenchmarkGetJSRuntime$ ./pkg/tmplexec/flow | tee BenchmarkGetJSRuntime-old.txt # runtime shared/reuse
$ ./bin/nuclei.test -test.run - -test.bench="^BenchmarkRunEnumeration/Flow/Namespacing$" -test.benchmem -test.count=10 ./cmd/nuclei/ | tee namespacing.txt # runtime shared/reuse
$ sed -i -e 's|/Local-Scoping||g' -e 's|/Namespacing||g' local-scoping.txt namespacing.txt 

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features

    • Added new benchmark tests to improve coverage for multi-target and template-based flow scenarios.
    • Introduced a benchmark to measure JavaScript runtime creation and release performance.
  • Refactor

    • Changed JavaScript runtime handling to create a new runtime instance for each use, eliminating pooling and reuse.
  • Bug Fixes

    • Ensured that updates to the template context during protocol execution are accurately reflected in the JavaScript runtime.

Signed-off-by: Dwi Siswanto <git@dw1.io>
Signed-off-by: Dwi Siswanto <git@dw1.io>
Signed-off-by: Dwi Siswanto <git@dw1.io>
@auto-assign auto-assign bot requested a review from dogancanbakir June 26, 2025 05:09
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 26, 2025

Walkthrough

The changes remove JavaScript runtime pooling in the flow executor, ensuring each scan gets a fresh runtime instance. The flow protocol's execution callback now updates the JS "template" variable after each protocol run, reflecting the current template context. Benchmark tests are updated and expanded to measure these behaviors.

Changes

File(s) Change Summary
pkg/tmplexec/flow/vm.go Removed JS runtime pooling; now creates a new runtime per call; PutJSRuntime is now a no-op.
pkg/tmplexec/flow/flow_executor.go Protocol execution callback now updates JS "template" variable with current context.
cmd/nuclei/main_benchmark_test.go Enabled and expanded benchmark subtests for enumeration and flow scenarios.
pkg/tmplexec/flow/vm_benchmark_test.go Added benchmark to measure JS runtime creation and release performance.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Nuclei
    participant FlowExecutor
    participant JSRuntime

    User->>Nuclei: Start scan with flow protocol
    Nuclei->>FlowExecutor: Compile flow
    FlowExecutor->>JSRuntime: GetJSRuntime()
    JSRuntime-->>FlowExecutor: New runtime instance
    FlowExecutor->>JSRuntime: Register protocol callback
    Nuclei->>FlowExecutor: Execute protocol step
    FlowExecutor->>JSRuntime: Execute requestExecutor
    JSRuntime-->>FlowExecutor: Protocol result
    FlowExecutor->>JSRuntime: Update "template" variable with context
    FlowExecutor-->>Nuclei: Return execution result
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure flow protocol JS runtime is not shared across targets to prevent template context confusion (#6263)
Update JS "template" variable after protocol execution to reflect current context (#6263)

Possibly related PRs

Poem

A bunny hops through code anew,
Each scan gets its own JS view!
No more pooled confusion,
Context stays in fusion,
With fresh runtimes, results ring true!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c3df33 and 5f9dccc.

⛔ Files ignored due to path filters (2)
  • cmd/nuclei/testdata/benchmark/flow/wordpress-readme-local-scoping.yaml is excluded by !**/*.yaml
  • cmd/nuclei/testdata/benchmark/flow/wordpress-readme-namespacing.yaml is excluded by !**/*.yaml
📒 Files selected for processing (4)
  • cmd/nuclei/main_benchmark_test.go (2 hunks)
  • pkg/tmplexec/flow/flow_executor.go (1 hunks)
  • pkg/tmplexec/flow/vm.go (1 hunks)
  • pkg/tmplexec/flow/vm_benchmark_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
pkg/tmplexec/flow/vm_benchmark_test.go (1)
pkg/tmplexec/flow/vm.go (2)
  • GetJSRuntime (20-24)
  • PutJSRuntime (29-31)
pkg/tmplexec/flow/vm.go (1)
pkg/types/types.go (1)
  • Options (30-452)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (ubuntu-latest)
🔇 Additional comments (6)
pkg/tmplexec/flow/vm.go (2)

16-24: LGTM! Runtime pooling removal addresses state leakage issue.

The change from pooled to fresh runtime creation effectively eliminates global state collision and leakage between executions. The updated documentation clearly explains the rationale for creating a new runtime per call.


26-31: Good backward compatibility approach.

Making PutJSRuntime a no-op with clear deprecation notice maintains API compatibility while transitioning to the new non-pooled approach.

pkg/tmplexec/flow/vm_benchmark_test.go (1)

10-19: Well-structured benchmark for measuring runtime creation impact.

The benchmark follows Go testing best practices with proper timer management and allocation reporting. This will provide valuable insights into the performance implications of switching from pooled to fresh runtime creation.

cmd/nuclei/main_benchmark_test.go (2)

120-125: Good addition of default benchmark case.

Enabling the default benchmark provides baseline performance measurements for comparison with the flow-specific tests.


137-183: Comprehensive flow benchmarking with realistic targets.

The flow benchmark suite provides valuable performance comparison between local-scoping and namespacing approaches. Using multiple well-known target URLs creates realistic testing conditions that should accurately reflect real-world performance implications.

Note that these benchmarks depend on external network connectivity. Consider documenting this dependency or providing fallback mechanisms for offline testing environments.

pkg/tmplexec/flow/flow_executor.go (1)

174-186: Essential template context synchronization for fresh runtimes.

This change correctly addresses a critical issue introduced by the switch to fresh runtime instances. Since the JS runtime no longer shares state between executions, explicitly updating the "template" variable after protocol execution ensures that extractor results and other context changes are properly reflected in the runtime.

The implementation is robust with proper null checking and clear documentation explaining the necessity of this update.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tarunKoyalwar
Copy link
Member

superceded by #https://github.com/projectdiscovery/nuclei/pull/6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Template context confusion when using the flow protocol while mass-scanning

2 participants