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

refactor(disk): templates catalog #5914

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

Conversation

dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented Dec 16, 2024

Proposed changes

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

    • Introduced a new error variable ErrNoTemplatesFound for better error handling related to template retrieval.
  • Improvements

    • Enhanced error handling for file opening and cloud upload processes.
    • Improved clarity in template path handling and glob pattern processing.
    • Streamlined logic for collecting and appending new templates and versions.
    • Updated command-line options to reflect new directory structure for template exclusions.
    • Enhanced error reporting with more informative messages when no templates are found.
  • Deprecations

    • Marked the BackwardsCompatiblePaths function as deprecated due to repository restructuring.
  • Bug Fixes

    • Clarified logic for handling ignored files and template management.

Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces modifications to the template path handling and error management in the Nuclei project. Changes primarily focus on the pkg/catalog/disk package, specifically improving wildcard template path processing, error handling, and file discovery mechanisms. The updates refine how template paths are resolved, particularly when using glob patterns, and enhance the clarity of error messages when templates cannot be found. Additionally, the runner.go file sees improvements in template management and error handling.

Changes

File Change Summary
internal/runner/runner.go Updated RunEnumeration and setupPDCPUpload methods with improved error handling and template management.
pkg/catalog/disk/catalog.go Modified OpenFile method to simplify file opening logic.
pkg/catalog/disk/errors.go Added new error variable ErrNoTemplatesFound.
pkg/catalog/disk/find.go Refined template path resolution, glob pattern processing, and error handling.
pkg/catalog/disk/path.go Added deprecation notice for BackwardsCompatiblePaths function.
cmd/functional-test/testcases.txt Updated command-line options to reflect new template paths.
internal/runner/lazy.go Enhanced error reporting for template retrieval failures.
pkg/protocols/common/automaticscan/util.go Improved error handling for missing templates.

Assessment against linked issues

Objective Addressed Explanation
Wildcard template path processing [#5420]
Improve error handling for template path resolution

Poem

🐰 Hop, hop, through template lands so bright,
Wildcards dancing in code's delight,
Paths resolved with rabbit's keen sight,
No more errors to cause our fright,
Nuclei's magic takes its flight! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 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 64bfd3a and 8635b4a.

📒 Files selected for processing (8)
  • cmd/functional-test/testcases.txt (2 hunks)
  • internal/runner/lazy.go (2 hunks)
  • internal/runner/runner.go (0 hunks)
  • pkg/catalog/disk/catalog.go (1 hunks)
  • pkg/catalog/disk/errors.go (1 hunks)
  • pkg/catalog/disk/find.go (6 hunks)
  • pkg/catalog/disk/path.go (1 hunks)
  • pkg/protocols/common/automaticscan/util.go (2 hunks)
💤 Files with no reviewable changes (1)
  • internal/runner/runner.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/catalog/disk/errors.go
  • pkg/catalog/disk/catalog.go
  • pkg/catalog/disk/path.go
🔇 Additional comments (16)
pkg/protocols/common/automaticscan/util.go (3)

4-4: Import of "fmt" looks good.


9-9: Import of "disk" package is consistent with new error handling usage.


34-34: Improved error message enhances clarity.

cmd/functional-test/testcases.txt (3)

39-51: Revised paths enhance consistency with the new folder structure.


56-56: Ensure updated paths match disk-level changes.


68-68: No functional issue detected at this line.

internal/runner/lazy.go (2)

10-10: New import aligns with refactored error handling.


72-72: Context-rich error message uses disk.ErrNoTemplatesFound properly.

pkg/catalog/disk/find.go (8)

4-4: "fmt" import is necessary for wrapping errors.


73-73: convertPathToAbsolute call streamlines path resolution.


79-90: Glob-based path handling is concise and returns a targeted error when empty.


92-97: File matching logic is clearly separated from directory checks.


107-115: Directory traversal properly returns a consistent error if nothing is found.


140-151: Conditional logic in findGlobPathMatches is well-organized; error wrapping is clean.


226-226: Trimming suffix ensures uniform path comparison.


249-253: Deprecation comment is clear and consistent with the removal of backward-compatibility code.


🪧 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.

@dwisiswant0 dwisiswant0 mentioned this pull request Dec 16, 2024
4 tasks
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: 1

🧹 Nitpick comments (2)
pkg/catalog/disk/path.go (1)

75-77: LGTM: Well-documented deprecation notice

The deprecation notice follows Go's standard format and clearly explains the reason for deprecation.

Consider adding a target version for removal in the deprecation notice to help users plan their migration.

pkg/catalog/disk/find.go (1)

79-90: Consider adding error variable for glob pattern errors

While the glob pattern handling is improved, consider defining a custom error variable for glob-specific errors, similar to ErrNoTemplatesFound.

+var ErrGlobPatternFailed = errors.New("failed to process glob pattern")

 if strings.Contains(target, "*") {
 	globMatches, err := c.findGlobPathMatches(target, processed)
 	if err != nil {
-		return nil, errors.Wrap(err, "could not globbing path")
+		return nil, errors.Wrap(err, ErrGlobPatternFailed.Error())
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf334e5 and da13a59.

📒 Files selected for processing (5)
  • internal/runner/runner.go (0 hunks)
  • pkg/catalog/disk/catalog.go (1 hunks)
  • pkg/catalog/disk/errors.go (1 hunks)
  • pkg/catalog/disk/find.go (6 hunks)
  • pkg/catalog/disk/path.go (1 hunks)
💤 Files with no reviewable changes (1)
  • internal/runner/runner.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/catalog/disk/errors.go
🔇 Additional comments (3)
pkg/catalog/disk/find.go (2)

73-76: LGTM: Improved error handling

The error handling is now more specific and informative with proper error wrapping.


249-253: LGTM: Consistent deprecation notice

The deprecation notice aligns well with the BackwardsCompatiblePaths deprecation.

pkg/catalog/disk/catalog.go (1)

Line range hint 75-77: Verify deprecated function usage

Let's verify if there are any remaining usages of the deprecated functions in the codebase.

Also applies to: 249-253

✅ Verification successful

Let me check if these functions are actually being called anywhere in the codebase.


Functions are safe to be removed

The deprecated functions BackwardsCompatiblePaths and PrintDeprecatedPathsMsgIfApplicable are only defined in their respective files (pkg/catalog/disk/path.go and pkg/catalog/disk/find.go) but are not being called anywhere in the codebase. They can be safely removed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of deprecated functions
echo "Checking for BackwardsCompatiblePaths usage..."
rg "BackwardsCompatiblePaths" --type go

echo "Checking for PrintDeprecatedPathsMsgIfApplicable usage..."
rg "PrintDeprecatedPathsMsgIfApplicable" --type go

Length of output: 702


Script:

#!/bin/bash
# Search for actual usage/calls of these functions
echo "Checking for BackwardsCompatiblePaths function calls..."
ast-grep --pattern 'BackwardsCompatiblePaths($$$)'

echo -e "\nChecking for PrintDeprecatedPathsMsgIfApplicable function calls..."
ast-grep --pattern 'PrintDeprecatedPathsMsgIfApplicable($$$)'

Length of output: 386

pkg/catalog/disk/catalog.go Outdated Show resolved Hide resolved
Copy link
Member

@ehsandeep ehsandeep left a comment

Choose a reason for hiding this comment

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

failing functional tests related to this change:

[✓] Test "{{binary}} -tags cve -exclude-templates cves/2020/CVE-2020-9757.yaml -exclude-templates cves/2021/" passed!
[✘] Test "{{binary}} -t cves/" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config,ssrf" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical -author geeknik,pdteam" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical -author geeknik,pdteam -etags sqli" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical -author geeknik,pdteam -etags sqli -exclude-templates cves/2021/" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical -author geeknik,pdteam -etags sqli -exclude-templates cves/2017/CVE-2017-72[69](https://github.com/projectdiscovery/nuclei/actions/runs/12373483567/job/34535007796?pr=5914#step:4:74).yaml" failed: could not run nuclei main test: exit status 1
[✘] Test "{{binary}} -t cves/ -t exposures/ -tags config -severity high,critical -author geeknik,pdteam -etags sqli -include-templates cves/2017/CVE-2017-7269.yaml" failed: could not run nuclei main test: exit status 1
[✓] Test "{{binary}} -tags cve -author geeknik,pdteam  -tc severity=='high'" passed!
[✓] Test "{{binary}} -tc contains(authors,'pdteam')" passed!
[✘] Test "{{binary}} -t cves/ -t exposures/ -tc contains(tags,'cve') -exclude-templates cves/2020/CVE-2020-9757.yaml" failed: could not run nuclei main test: exit status 1

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

🧹 Nitpick comments (1)
cmd/functional-test/testcases.txt (1)

39-56: Consider updating related documentation

The template path changes are consistent and correct. However, since this represents a structural change in how templates are referenced, consider:

  1. Updating the project's documentation to reflect the new path structure
  2. Adding a migration guide for users updating from older versions
  3. Mentioning this change in the changelog
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db8ddc6 and 64bfd3a.

📒 Files selected for processing (1)
  • cmd/functional-test/testcases.txt (2 hunks)
🔇 Additional comments (3)
cmd/functional-test/testcases.txt (3)

42-51: LGTM! Template selection commands are consistently updated

The changes to template paths are applied consistently across all template selection commands, maintaining proper syntax and flag combinations.


56-56: LGTM! Advanced filtering command is correctly updated

The template path update in the advanced filtering command maintains consistency with the overall refactoring pattern.


39-41: Verify backward compatibility for template exclusion paths

The addition of the http/ prefix to template paths is consistent with the refactoring goals. However, we should ensure this change doesn't break existing user configurations.

✅ Verification successful

Path changes are consistent and non-breaking

The addition of the http/ prefix to template paths in the test cases is consistent with the codebase organization. Based on the verification:

  1. No references to the old path format (cves/20XX/) were found in configuration files or documentation
  2. The changes are limited to test cases and appear to be part of a coordinated template reorganization
  3. The test file itself shows consistent usage of the new http/ prefix across all commands
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any references to the old path format in documentation or example files

# Search for old path format in markdown files and examples
rg -g '*.{md,yaml,txt}' 'cves/20[0-9]{2}/' --no-filename

# Search for any migration guides or documentation updates
fd -g '*.md' --exec grep -l -i 'migration\|breaking change\|path change'

Length of output: 1011


Script:

#!/bin/bash
# Let's check the content of the README files for any migration notes
cat README.md lib/README.md

# Also check for any previous versions of these test cases
git log -p -- cmd/functional-test/testcases.txt | head -n 100

Length of output: 60003


Script:

#!/bin/bash
# Let's check if there are any other test files or configuration files that might reference these paths
fd -e yaml -e txt -e json --exec grep -l 'cves/20[0-9]{2}'

# Also check for any template files in the old path structure
fd -g 'cves/20[0-9]{2}/*'

Length of output: 88

@dwisiswant0
Copy link
Member Author

failing functional tests related to this change:

@ehsandeep - since we're deprecating BackwardsCompatiblePaths, we need to update the unit tests accordingly (done at 64bfd3a), and also:

  1. Adding a migration guide for users updating from older versions
  2. Mentioning this change in the changelog

This should increment minor version, as we no longer support backward-compatible paths from the old Nuclei Templates repo structure (v9.Y.Z).

Signed-off-by: Dwi Siswanto <[email protected]>
since `BackwardsCompatiblePaths` func is already
deprecated.

Signed-off-by: Dwi Siswanto <[email protected]>
Signed-off-by: Dwi Siswanto <[email protected]>
@dwisiswant0 dwisiswant0 force-pushed the dwisiswant0/refactor/disk/templates-catalog branch from 64bfd3a to 8635b4a Compare December 31, 2024 15:59
Copy link
Member

@tarunKoyalwar tarunKoyalwar left a comment

Choose a reason for hiding this comment

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

Looks good. I also think we can remove the backward compatibility logic since it's no longer relevant. The main consideration is that -t cves and -t misconfiguration are very common filters. While these can be achieved with -tags, we could also support this feature by updating the file glob matcher to match wildcard prefixes (it currently only matches suffixes of given keywords).

@dwisiswant0
Copy link
Member Author

[...] we could also support this feature by updating the file glob matcher to match wildcard prefixes (it currently only matches suffixes of given keywords).

Can you give an example for that case?

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.

Template Path containing a Wildcard is not working anymore
3 participants