Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hosterrorscache): add Remove and MarkFailedOrRemove methods #5984

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from

Conversation

dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented Jan 14, 2025

Proposed changes

The decision was made to completely remove the cached entry for the host instead of simply decrementing the error
count (using (atomic.Int32).Swap to update the value to $$N-1$$). This approach was chosen because the error handling logic operates concurrently, and decrementing the count could lead to UB (unexpected behavior) even when the error is nil.

To clarify, consider the following scenario where the error encountered does NOT belong to the permanent network error category (errkit.ErrKindNetworkPermanent):

  1. Iteration 1: A timeout error occurs, and the error count for the host is incremented.
  2. Iteration 2: Another timeout error is encountered, leading to another increment in the host's error count.
  3. Iteration 3: A third timeout error happens, which increments the error count further. At this point, the host is flagged as unresponsive.
  4. Iteration 4: The host becomes reachable (no error or a transient issue resolved). Instead of performing a no-op and leaving the host in the cache, the host entry is removed entirely to reset its state.
  5. Iteration 5: A subsequent timeout error occurs after the host was removed and re-added to the cache. The error count is reset and starts from 1 again.

This removal strategy ensures the cache is updated dynamically to reflect the current state of the host without persisting stale or irrelevant error counts that could interfere with future error handling and tracking logic.

Possibly closes #4266

What's changed

  • hosterrorscache
    • Deprecating *Cache.MarkFailed, now it calls *Cache.MarkFailedOrRemove.
    • Added new *Cache.Remove method.
  • *
    • Invoke *Cache.MarkFailed unconditionally.

Proof

$ go test -v -race -run "^Test(CacheCheck|Remove)$" ./pkg/protocols/common/hosterrorscache/
=== RUN   TestCacheCheck
=== RUN   TestCacheCheck/increment_host_error
=== RUN   TestCacheCheck/flagged
[INF] Skipped TestCacheCheck:80 from target list as found unresponsive 5 times
=== RUN   TestCacheCheck/mark_failed_or_remove
--- PASS: TestCacheCheck (0.00s)
    --- PASS: TestCacheCheck/increment_host_error (0.00s)
    --- PASS: TestCacheCheck/flagged (0.00s)
    --- PASS: TestCacheCheck/mark_failed_or_remove (0.00s)
=== RUN   TestRemove
[INF] Skipped TestRemove:80 from target list as found unresponsive 100 times
--- PASS: TestRemove (0.01s)
PASS
ok  	github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/hosterrorscache	(cached)

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

Release Notes

  • Bug Fixes

    • Improved error handling and tracking for unresponsive hosts across multiple protocol implementations.
    • Enhanced host error caching mechanism to more accurately record and manage host failures.
  • Refactor

    • Streamlined error logging and marking processes in workflow and request execution.
    • Consolidated error handling methods to improve code clarity and consistency.
  • Tests

    • Added new test cases to verify host error caching and removal functionality.
    • Enhanced test coverage for concurrent error handling scenarios.

The updates focus on more robust error tracking and management across different protocol and workflow execution contexts.

@auto-assign auto-assign bot requested a review from dogancanbakir January 14, 2025 12:17
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces comprehensive modifications to error handling and host error caching across multiple packages. The changes focus on refining the logic for marking host failures, removing redundant error checks, and ensuring consistent error tracking. The modifications span several files in the pkg/core, pkg/protocols, pkg/templates, and pkg/tmplexec directories, with a primary emphasis on improving the HostErrorsCache functionality and error marking mechanisms.

Changes

File Change Summary
pkg/core/workflow_execute.go Modified error handling in runWorkflowStep to mark failed host errors immediately after execution.
pkg/protocols/common/hosterrorscache/... Added Remove() method, updated MarkFailed() to call MarkFailedOrRemove(), and added thread-safe mutex to cacheItem.
pkg/protocols/http/request.go Replaced markUnresponsiveAddress() with markHostError(), updated error handling in request methods.
pkg/protocols/network/request.go Renamed markUnresponsiveAddress() to markHostError().
pkg/templates/cluster.go Modified error marking condition in Execute and ExecuteWithResults methods.
pkg/tmplexec/generic/exec.go Replaced conditional error marking with MarkFailedOrRemove in ExecuteWithResults.

Assessment against linked issues

Objective Addressed Explanation
Prevent scanning skipped targets Changes improve host error tracking and removal mechanism.
Stop scanning unresponsive hosts New Remove() method and refined error handling support this goal.

Poem

🐰 In the realm of code, where errors dance,
A rabbit's fix brings a new advance!
Host errors cached with precision bright,
No more scanning when hosts take flight!
Nuclei's logic, now smooth and clean,
A technological rabbit's dream! 🚀


📜 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 d93b9b8 and 2b511d0.

📒 Files selected for processing (7)
  • pkg/core/workflow_execute.go (1 hunks)
  • pkg/protocols/common/hosterrorscache/hosterrorscache.go (4 hunks)
  • pkg/protocols/http/request.go (5 hunks)
  • pkg/protocols/http/request_fuzz.go (1 hunks)
  • pkg/protocols/network/request.go (2 hunks)
  • pkg/templates/cluster.go (2 hunks)
  • pkg/tmplexec/generic/exec.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/protocols/http/request_fuzz.go
  • pkg/tmplexec/generic/exec.go
  • pkg/templates/cluster.go
  • pkg/core/workflow_execute.go
🔇 Additional comments (11)
pkg/protocols/common/hosterrorscache/hosterrorscache.go (5)

24-29: LGTM! Clear and well-documented interface changes.

The interface changes are well-structured with clear method signatures and descriptive comments. The addition of Remove and MarkFailedOrRemove methods aligns with the PR objectives.


52-53: LGTM! Good addition of mutex for thread safety.

The addition of a mutex to cacheItem ensures thread-safe access to the cache fields, which is crucial for concurrent operations.


60-66: LGTM! Improved code formatting.

The reformatting of the New function improves readability while maintaining the same functionality.


152-156: LGTM! Clean implementation of Remove method.

The implementation is straightforward and handles the removal operation correctly, including the case where the key might not exist in the cache.


169-229: LGTM! Excellent implementation with comprehensive documentation.

The implementation is robust with:

  • Clear documentation explaining the rationale and behavior
  • Proper thread safety using mutex
  • Good error handling and state management
  • Well-structured control flow

The detailed comments explaining the concurrent error handling scenario and the removal strategy are particularly valuable for future maintenance.

pkg/protocols/network/request.go (2)

294-295: LGTM! Consistent error handling update.

The change to use markHostError aligns with the new error handling approach while maintaining the same logical flow.


527-531: LGTM! Clean implementation of markHostError.

The implementation correctly uses the new MarkFailedOrRemove method from the cache interface, maintaining consistency with the new error handling strategy.

pkg/protocols/http/request.go (4)

153-153: LGTM! Consistent error handling update.

The change to use markHostError aligns with the new error handling approach while maintaining the same logical flow.


235-235: LGTM! Consistent error handling update.

The change to use markHostError aligns with the new error handling approach while maintaining the same logical flow.


376-376: LGTM! Consistent error handling update.

The change to use markHostError aligns with the new error handling approach while maintaining the same logical flow.


1193-1197: LGTM! Clean implementation of markHostError.

The implementation correctly uses the new MarkFailedOrRemove method from the cache interface, maintaining consistency with the new error handling strategy.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
pkg/protocols/common/hosterrorscache/hosterrorscache.go (1)

147-151: Consider logging cache removal errors in verbose mode.

The implementation is clean, but for debugging purposes, it would be helpful to log removal errors when verbose mode is enabled.

 func (c *Cache) Remove(ctx *contextargs.Context) {
 	key := c.GetKeyFromContext(ctx, nil)
-	_ = c.failedTargets.Remove(key) // remove even the cache is not present
+	if err := c.failedTargets.Remove(key); err != nil && c.verbose {
+		gologger.Verbose().Msgf("Failed to remove %s from cache: %v", key, err)
+	}
 }
pkg/protocols/common/hosterrorscache/hosterrorscache_test.go (2)

22-29: Enhance test readability with descriptive error messages.

The test logic is correct, but the failure messages could be more descriptive.

-			require.Falsef(t, got, "got %v in iteration %d", got, i)
+			require.Falsef(t, got, "expected host not to be flagged after %d failure(s), but it was", i)

89-101: Consider adding edge cases to the Remove test.

While the current test is good, consider adding cases for:

  • Removing a non-existent host
  • Removing a host with permanent error
  • Concurrent removal operations
pkg/tmplexec/generic/exec.go (1)

89-91: Consider extracting common error handling logic.

The error marking logic is duplicated across workflow and generic executors. Consider extracting this into a common helper function to maintain consistency and reduce duplication.

Example helper function:

func markExecutorError(cache CacheInterface, protoType string, input *contextargs.Context, err error) {
    if cache != nil {
        cache.MarkFailed(protoType, input, err)
    }
}
pkg/templates/cluster.go (1)

312-314: Duplicate error handling pattern.

This is a duplicate of the error handling pattern from the Execute method. Consider extracting this common logic into a shared helper method to maintain DRY principles.

Apply this diff to extract the common logic:

+func (request *Request) markHostErrors(input *contextargs.Context, err error) {
+  if request.options.HostErrorsCache != nil {
+    request.options.HostErrorsCache.MarkFailed(request.options.ProtocolType.String(), input, err)
+  }
+}
+
 func (request *Request) Execute(ctx *scan.ScanContext) (bool, error) {
   // ...
-  if request.options.HostErrorsCache != nil {
-    request.options.HostErrorsCache.MarkFailed(request.options.ProtocolType.String(), ctx.Input, err)
-  }
+  request.markHostErrors(ctx.Input, err)
   return results, err
 }

 func (request *Request) ExecuteWithResults(ctx *scan.ScanContext) ([]*output.ResultEvent, error) {
   // ...
-  if request.options.HostErrorsCache != nil {
-    request.options.HostErrorsCache.MarkFailed(request.options.ProtocolType.String(), ctx.Input, err)
-  }
+  request.markHostErrors(ctx.Input, err)
   return scanCtx.GenerateResult(), err
 }
pkg/protocols/network/request.go (1)

294-295: Improve comment accuracy.

The comment "adds it to unresponsive address list if applicable" is outdated and doesn't reflect the new error handling approach.

Apply this diff to update the comment:

-  // adds it to unresponsive address list if applicable
+  // marks host error in cache if applicable
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08c46ff and 17a57f8.

📒 Files selected for processing (8)
  • pkg/core/workflow_execute.go (1 hunks)
  • pkg/protocols/common/hosterrorscache/hosterrorscache.go (4 hunks)
  • pkg/protocols/common/hosterrorscache/hosterrorscache_test.go (5 hunks)
  • pkg/protocols/http/request.go (5 hunks)
  • pkg/protocols/http/request_fuzz.go (1 hunks)
  • pkg/protocols/network/request.go (2 hunks)
  • pkg/templates/cluster.go (2 hunks)
  • pkg/tmplexec/generic/exec.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests (windows-latest)
🔇 Additional comments (7)
pkg/protocols/common/hosterrorscache/hosterrorscache.go (2)

24-29: LGTM! Well-structured interface changes.

The interface changes are clean and maintain backward compatibility while introducing new functionality.


160-223: Excellent implementation with clear documentation and thread-safety!

The implementation is robust with:

  • Comprehensive documentation explaining the removal strategy
  • Proper thread-safety using mutex
  • Clear error handling logic
pkg/core/workflow_execute.go (1)

99-101: LGTM! Consistent error handling implementation.

The error marking is correctly placed after executer execution, maintaining consistency with the new error handling strategy.

pkg/templates/cluster.go (1)

276-278: Verify error handling behavior.

The error handling logic has been updated to mark host errors in the cache regardless of the error's presence. This change aligns with the PR's objective to enhance error handling, but we should verify that this doesn't lead to false positives.

Run the following script to check for similar patterns in other files:

✅ Verification successful

Error handling implementation is correct and safe

The error handling in HostErrorsCache is properly implemented with built-in safeguards:

  • Only tracks errors for HTTP protocol after validation
  • Automatically removes host from cache when error is nil
  • Uses atomic operations for thread-safety
  • Has protection against false positives through error type checking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent error handling patterns across the codebase
# Look for similar patterns where HostErrorsCache.MarkFailed is called

ast-grep --pattern 'if $cache != nil {
  $cache.MarkFailed($_, $_, $_)
}'

Length of output: 75


Script:

#!/bin/bash
# Search for MarkFailed method calls and their context
rg "MarkFailed" -A 3 -B 3

# Find HostErrorsCache type definition and usage
rg "type.*HostErrorsCache" -A 5

# Look for similar error handling patterns with nil checks
ast-grep --pattern 'if $_ != nil {
  $$$
}'

Length of output: 65730


Script:

#!/bin/bash
# Check MarkFailedOrRemove implementation and error handling
rg "MarkFailedOrRemove" -A 10 -B 2

# Look for error handling in cache implementation
rg "func.*Cache" -A 5 pkg/protocols/common/hosterrorscache/

Length of output: 11817

pkg/protocols/http/request_fuzz.go (1)

228-230: Consistent error handling pattern.

The error handling logic follows the same pattern as in cluster.go, marking host errors in the cache regardless of the error's presence. This consistency is good for maintainability.

pkg/protocols/network/request.go (1)

Line range hint 527-532: Consistent method naming and documentation.

The method has been renamed from markUnresponsiveAddress to markHostError to better reflect its purpose. The comment accurately describes the function's behavior.

pkg/protocols/http/request.go (1)

Line range hint 1193-1198: Consistent method implementation.

The implementation of markHostError is consistent with the renamed methods in other files, which is good for maintainability.

pkg/protocols/http/request.go Show resolved Hide resolved
@dwisiswant0 dwisiswant0 marked this pull request as draft January 14, 2025 17:44
@dwisiswant0 dwisiswant0 marked this pull request as ready for review January 15, 2025 05:51
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/protocols/common/hosterrorscache/hosterrorscache_test.go (2)

173-191: Consider enhancing concurrent test coverage.

While the test effectively verifies concurrent marking and checking, consider adding assertions to verify the final error count after all goroutines complete.

 	}
 	wg.Wait()
+
+	// Verify final error count
+	normalizedCacheValue := cache.GetKeyFromContext(ctx, nil)
+	failedTarget, err := cache.failedTargets.Get(normalizedCacheValue)
+	require.Nil(t, err)
+	require.NotNil(t, failedTarget)
+	require.EqualValues(t, 100, failedTarget.errors.Load())
 }

89-89: Consider adding edge case tests for Remove.

Consider adding test cases for edge scenarios of the Remove method, such as:

  • Removing a non-existent host
  • Removing a host multiple times
  • Concurrent removal of the same host
+func TestRemoveEdgeCases(t *testing.T) {
+	cache := New(3, DefaultMaxHostsCount, nil)
+	ctx := newCtxArgs(t.Name())
+
+	// Test removing non-existent host
+	cache.Remove(ctx)
+	require.False(t, cache.Check(protoType, ctx))
+
+	// Test multiple removals
+	cache.MarkFailed(protoType, ctx, errors.New("error"))
+	cache.Remove(ctx)
+	cache.Remove(ctx)
+	require.False(t, cache.Check(protoType, ctx))
+
+	// Test concurrent removal
+	cache.MarkFailed(protoType, ctx, errors.New("error"))
+	wg := sync.WaitGroup{}
+	for i := 0; i < 10; i++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			cache.Remove(ctx)
+		}()
+	}
+	wg.Wait()
+	require.False(t, cache.Check(protoType, ctx))
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 17a57f8 and d93b9b8.

📒 Files selected for processing (2)
  • pkg/protocols/common/hosterrorscache/hosterrorscache.go (4 hunks)
  • pkg/protocols/common/hosterrorscache/hosterrorscache_test.go (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: perf-test (150)
  • GitHub Check: perf-test (100)
  • GitHub Check: perf-test (50)
  • GitHub Check: Tests (windows-latest)
🔇 Additional comments (8)
pkg/protocols/common/hosterrorscache/hosterrorscache.go (6)

24-29: LGTM! Interface changes are well-structured.

The new methods Remove and MarkFailedOrRemove are clearly named and maintain backward compatibility.


53-53: LGTM! Thread-safety improvement.

The addition of sync.Mutex ensures thread-safe access to the cache item's fields.


133-138: LGTM! Thread-safety and logging improvements.

The addition of mutex locking ensures thread-safe access to cache items, and the error message now uses the appropriate verbose level for expected skips.


152-156: LGTM! Clean implementation of Remove method.

The implementation is simple, focused, and handles the cache miss case appropriately.


159-163: LGTM! Clean deprecation approach.

The method is properly marked as deprecated and maintains backward compatibility by delegating to MarkFailedOrRemove.


165-225: LGTM! Well-implemented and thoroughly documented.

The method effectively handles both error and non-error cases, maintains thread-safety, and includes comprehensive documentation explaining the removal strategy rationale.

pkg/protocols/common/hosterrorscache/hosterrorscache_test.go (2)

22-46: LGTM! Comprehensive test coverage.

The new subtests effectively cover the key scenarios: error increment, flagging, and removal functionality.


89-101: LGTM! Clear and focused test.

The test effectively verifies both the marking of failed hosts and their subsequent removal.

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.

Skipped target still getting scanned
1 participant