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

fix(sdk): NoHostErrors not set #5783

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

Conversation

iuliu8899
Copy link
Contributor

@iuliu8899 iuliu8899 commented Oct 29, 2024

Proposed changes

#5782

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

    • Enhanced error handling for host errors, improving control over concurrency limits and caching mechanisms.
    • Conditional management of HostErrorsCache based on user-defined options.
  • Bug Fixes

    • Adjusted initialization logic for host error caching to prevent unnecessary instantiation.
  • Documentation

    • Updated method signatures to reflect new logic in error handling and caching processes.

@GeorginaReeder
Copy link

Thanks so much for your contribution @iuliu8899 ! :)

@dogancanbakir dogancanbakir linked an issue Oct 30, 2024 that may be closed by this pull request
1 task
Copy link

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the handling of host error management within the NucleiEngine and related components. Key updates include the introduction of conditional logic for the MaxHostError and HostErrorsCache fields, ensuring they are only utilized when necessary. This includes adjustments to functions across multiple files, such as WithNetworkConfig, createEphemeralObjects, and methods within NucleiEngine, enhancing the control flow and error handling mechanisms without altering the signatures of most exported entities.

Changes

File Change Summary
lib/config.go Modified WithNetworkConfig to handle DisableMaxHostErr and MaxHostError, adding logic for caching and error handling.
lib/multi.go Updated createEphemeralObjects to conditionally assign HostErrorsCache based on ShouldUseHostError().
lib/sdk_private.go Adjusted applyRequiredDefaults and init methods to include conditions for hostErrCache and HostErrorsCache initialization.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NucleiEngine
    participant Config

    User->>Config: Set Network Config
    Config->>NucleiEngine: WithNetworkConfig(opts)
    NucleiEngine->>NucleiEngine: Check ShouldUseHostError()
    NucleiEngine->>NucleiEngine: Adjust MaxHostError if needed
    NucleiEngine->>NucleiEngine: Initialize hostErrCache
    NucleiEngine->>User: Configuration updated
Loading

🐇 "In the garden where errors play,
Host caches now find their way.
With checks and balances in the light,
Our threads will run both smooth and bright.
So hop along, let’s cheer and say,
Error handling's here to stay!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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

@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

🧹 Outside diff range and nitpick comments (2)
lib/sdk_private.go (2)

164-178: Consider reorganizing the executor options initialization

While the conditional assignment of HostErrorsCache is correct, consider reorganizing the code to determine all fields before creating the ExecutorOptions struct. This would make the initialization more maintainable and easier to understand.

Here's a suggested refactor:

+       // Prepare executor options fields
+       hostErrorsCache := e.hostErrCache
+       if !e.opts.ShouldUseHostError() || e.hostErrCache == nil {
+           hostErrorsCache = nil
+       }
+
        e.executerOpts = protocols.ExecutorOptions{
            Output:       e.customWriter,
            Options:      e.opts,
            Progress:     e.customProgress,
            Catalog:      e.catalog,
            IssuesClient: e.rc,
            RateLimiter:  e.rateLimiter,
            Interactsh:   e.interactshClient,
            Colorizer:    aurora.NewAurora(true),
            ResumeCfg:    types.NewResumeCfg(),
            Browser:      e.browserInstance,
            Parser:       e.parser,
            InputHelper:  input.NewHelper(),
+           HostErrorsCache: hostErrorsCache,
        }
-       if e.opts.ShouldUseHostError() && e.hostErrCache != nil {
-           e.executerOpts.HostErrorsCache = e.hostErrCache
-       }

Line range hint 228-234: Fix error variable shadowing in httpx client initialization

The error variable is shadowed in the if-else statement, which could mask errors from the outer scope. Consider using a separate variable name or restructuring the error handling.

Here's the suggested fix:

        httpxOptions := httpx.DefaultOptions
        httpxOptions.Timeout = 5 * time.Second
-       if client, err := httpx.New(&httpxOptions); err != nil {
+       client, httpxErr := httpx.New(&httpxOptions)
+       if httpxErr != nil {
-           return err
+           return httpxErr
        } else {
            e.httpxClient = nucleiUtils.GetInputLivenessChecker(client)
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3a07fa9 and a010457.

📒 Files selected for processing (3)
  • lib/config.go (1 hunks)
  • lib/multi.go (1 hunks)
  • lib/sdk_private.go (2 hunks)
🔇 Additional comments (5)
lib/multi.go (2)

32-42: LGTM: ExecutorOptions initialization is well-structured

The initialization of ExecutorOptions follows a clear pattern and properly sets all required fields from the base instance.


43-44: LGTM: Proper conditional initialization of HostErrorsCache

The added condition properly ensures that HostErrorsCache is only set when host error handling is enabled and the cache exists. This fix addresses the "NoHostErrors not set" issue (#5782).

Let's verify the fix is complete by checking for any other locations that might need similar conditional handling:

✅ Verification successful

Based on the search results, I can now generate the final response:

Verified: HostErrorsCache initialization is properly handled across the codebase

The conditional initialization of HostErrorsCache in lib/multi.go is consistent with other implementations in the codebase. All usages follow the same pattern:

  • Initialization only occurs when ShouldUseHostError() is true
  • Null checks are performed before using the cache
  • The cache is properly cleaned up when needed

Key verified locations:

  • lib/sdk_private.go: Similar conditional initialization
  • lib/config.go: Consistent error handling setup
  • Protocol implementations (HTTP, Network): Proper null checks before usage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential locations handling HostErrorsCache
rg -A 2 "HostErrorsCache|hostErrCache|ShouldUseHostError"

Length of output: 6177

lib/sdk_private.go (1)

76-78: LGTM: Improved host error cache initialization

The condition for initializing the host error cache has been properly updated to check both if the cache is nil and if host error handling is enabled. This prevents unnecessary resource allocation when host error handling is disabled.

lib/config.go (2)

289-290: LGTM: Proper initialization of host error settings

The code correctly initializes the host error settings from the NetworkConfig options:

  • NoHostErrors is set from DisableMaxHostErr
  • MaxHostError is set from the config

291-302: Verify host error cache initialization logic

The host error cache initialization looks good with proper validation and adjustment of MaxHostError. However, there are a few points to consider:

  1. The warning message about concurrency being higher than max-host-error could be more specific.
  2. The cache initialization should be protected against potential edge cases.

Consider these improvements:

 if e.opts.ShouldUseHostError() {
     maxHostError := opts.MaxHostError
     if e.opts.TemplateThreads > maxHostError {
-        gologger.Print().Msgf("[%v] The concurrency value is higher than max-host-error", e.executerOpts.Colorizer.BrightYellow("WRN"))
-        gologger.Info().Msgf("Adjusting max-host-error to the concurrency value: %d", e.opts.TemplateThreads)
+        gologger.Print().Msgf("[%v] Template concurrency (%d) is higher than max-host-error (%d)", 
+            e.executerOpts.Colorizer.BrightYellow("WRN"), e.opts.TemplateThreads, maxHostError)
+        gologger.Info().Msgf("Adjusting max-host-error to match template concurrency: %d", e.opts.TemplateThreads)
         maxHostError = e.opts.TemplateThreads
         e.opts.MaxHostError = maxHostError
     }
+    if maxHostError <= 0 {
+        maxHostError = hosterrorscache.DefaultMaxHostsCount
+    }
     cache := hosterrorscache.New(maxHostError, hosterrorscache.DefaultMaxHostsCount, e.opts.TrackError)
     cache.SetVerbose(e.opts.Verbose)
     e.hostErrCache = cache
 }

Let's verify the usage of ShouldUseHostError and related host error settings:

✅ Verification successful

Host error cache initialization and validation is properly implemented

The verification shows that the host error handling implementation is robust and consistent across the codebase:

  1. The ShouldUseHostError() function in pkg/types/types.go correctly checks both conditions: MaxHostError > 0 && !NoHostErrors
  2. Default value for MaxHostError is set to 30 in the options
  3. The warning about concurrency being higher than max-host-error is consistently implemented in both lib/config.go and internal/runner/runner.go
  4. The host error cache properly tracks and enforces the error limits through MaxHostError field

The suggested improvements in the review comment, while making the messages more descriptive, aren't strictly necessary as the current implementation is already functionally sound and consistent.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of ShouldUseHostError and related host error settings

# Check for ShouldUseHostError implementation
ast-grep --pattern 'func $_($$) bool {
  $$$
  return !$_.NoHostErrors
  $$$
}'

# Check for other references to NoHostErrors and MaxHostError
rg -A 3 'NoHostErrors|MaxHostError'

Length of output: 4282

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] DisableMaxHostErr not used in sdk
2 participants