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

Added filename length restriction for debug mode (-srd flag) Issue-5929 #5931

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

Lercas
Copy link

@Lercas Lercas commented Dec 19, 2024

Proposed changes

Added a file name length restriction in the WriteStoreDebugData function for the debug mode triggered by the -srd flag. This change ensures that file names generated for debugging purposes are truncated. The update addresses the issue where excessively long file names caused by verbose requests could not be created due to operating system file name length limitations.

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 handling of host and templateID parameters by truncating their lengths for better filename management.
  • Bug Fixes

    • Resolved issues with excessively long host and templateID values in debug data storage.
  • Style

    • Minor formatting adjustments made for improved code clarity.

@auto-assign auto-assign bot requested a review from dwisiswant0 December 19, 2024 17:57
Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

The changes modify the WriteStoreDebugData method in the StandardWriter struct to implement length truncation for host and templateID parameters. When these parameters exceed specified character limits (60 for host, 100 for templateID), they are shortened and appended with an ellipsis. This ensures that generated debug data filenames remain within reasonable length constraints, preventing potential file creation issues across different operating systems.

Changes

File Change Summary
pkg/output/output.go - Implemented truncation for host parameter (max 60 chars, truncate to 57 + "...")
- Implemented truncation for templateID parameter (max 100 chars, truncate to 97 + "...")
- Removed extraneous newline at method end

Possibly related issues

  • projectdiscovery/nuclei#5929: Directly addresses the issue of file name length restrictions for debug mode, matching the exact changes implemented in this PR

Poem

🐰 A rabbit's tale of file name grace,
Truncating strings with nimble pace
Ellipsis dancing, characters trim
No system limits can make us dim!
Debug files saved with clever might 🔍


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.

@Lercas Lercas changed the title Added filename length restriction for debug mode (-srd flag) Added filename length restriction for debug mode (-srd flag) Issue-5929 Dec 19, 2024
@Lercas
Copy link
Author

Lercas commented Dec 19, 2024

image

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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 358249b and 6df1058.

📒 Files selected for processing (1)
  • pkg/output/output.go (1 hunks)
🔇 Additional comments (1)
pkg/output/output.go (1)

515-521: Verify the impact on existing debug files.

The changes in filename generation might affect existing debug files and tools that process them. Ensure this change is backward compatible or properly documented.

✅ Verification successful

Let me gather more context about how these fields are used in filename generation.


Let me check how these truncated values are used in the actual file generation.


Based on the gathered context, I can now provide the final response:

The truncation changes are safe and won't impact existing debug files

The truncation of host and templateID values occurs before the filename sanitization process and is only used for new debug file creation. This change:

  • Happens at runtime for new file creation only
  • Doesn't modify existing files
  • Still maintains uniqueness with 57 and 97 characters respectively
  • Occurs before the sanitization process that handles special characters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing debug files that might be affected by the new length restrictions

# Find all .txt files in the store response directory
echo "Checking for existing debug files with long names..."
fd -e txt -x sh -c '
  filename=$(basename "{}")
  if [ ${#filename} -gt 255 ]; then
    echo "Found file exceeding 255 characters: {}"
    echo "Length: ${#filename}"
  fi
'

Length of output: 291


Script:

#!/bin/bash
# Search for code that uses host and templateID in filename generation
rg -U "func.*filename|func.*path" pkg/output/output.go -A 10

# Also check how these fields are used in debug file generation
ast-grep --pattern 'host := $_'
ast-grep --pattern 'templateID := $_'

Length of output: 4693


Script:

#!/bin/bash
# Search for the context around where these values are truncated
rg -U "host\[:57\]|templateID\[:97\]" pkg/output/output.go -B 10 -A 10

# Also check for any file writing or path generation logic
rg "WriteFile|SaveToFile|filepath.Join" pkg/output/output.go

Length of output: 1128

Comment on lines +515 to +521
if len(host) > 60 {
host = host[:57] + "..."
}
if len(templateID) > 100 {
templateID = templateID[:97] + "..."
}

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider total filename length and OS limitations.

The current implementation truncates host and templateID independently, but doesn't consider their combined length along with separators and the file extension. This could still result in exceeding OS filename limits.

+const (
+    // Common OS filename length limits
+    maxFilenameLength = 255 // typical limit for many filesystems
+    // Components
+    separatorLength = 1 // "_" separator
+    extensionLength = 4 // ".txt"
+)

 func (w *StandardWriter) WriteStoreDebugData(host, templateID, eventType string, data string) {
 	if w.storeResponse {
+		// Calculate available space for host and templateID
+		availableLength := maxFilenameLength - separatorLength - extensionLength
+		
+		// Distribute available length proportionally
+		hostRatio := 0.4 // 40% for host
+		templateIDRatio := 0.6 // 60% for templateID
+		
+		maxHostLen := int(float64(availableLength) * hostRatio)
+		maxTemplateIDLen := int(float64(availableLength) * templateIDRatio)
+
 		if len(host) > maxHostLength {
 			host = host[:maxHostLength-ellipsisLength] + ellipsis
 		}
 		if len(templateID) > maxTemplateIDLength {
 			templateID = templateID[:maxTemplateIDLength-ellipsisLength] + ellipsis
 		}
+
+		// Ensure minimum length requirements
+		if len(host) < 1 || len(templateID) < 1 {
+			gologger.Warning().Msgf("Host or templateID too short after truncation: %s_%s", host, templateID)
+		}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +515 to +520
if len(host) > 60 {
host = host[:57] + "..."
}
if len(templateID) > 100 {
templateID = templateID[:97] + "..."
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract magic numbers into named constants.

The hardcoded length limits and truncation points should be defined as package-level constants for better maintainability and clarity.

+const (
+    maxHostLength = 60
+    maxTemplateIDLength = 100
+    ellipsis = "..."
+    ellipsisLength = len(ellipsis)
+)

 func (w *StandardWriter) WriteStoreDebugData(host, templateID, eventType string, data string) {
 	if w.storeResponse {
-		if len(host) > 60 {
-			host = host[:57] + "..."
+		if len(host) > maxHostLength {
+			host = host[:maxHostLength-ellipsisLength] + ellipsis
 		}
-		if len(templateID) > 100 {
-			templateID = templateID[:97] + "..."
+		if len(templateID) > maxTemplateIDLength {
+			templateID = templateID[:maxTemplateIDLength-ellipsisLength] + ellipsis
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if len(host) > 60 {
host = host[:57] + "..."
}
if len(templateID) > 100 {
templateID = templateID[:97] + "..."
}
const (
maxHostLength = 60
maxTemplateIDLength = 100
ellipsis = "..."
ellipsisLength = len(ellipsis)
)
if len(host) > maxHostLength {
host = host[:maxHostLength-ellipsisLength] + ellipsis
}
if len(templateID) > maxTemplateIDLength {
templateID = templateID[:maxTemplateIDLength-ellipsisLength] + ellipsis
}

@GeorginaReeder
Copy link

Thanks for your contribution @Lercas ! :)

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] Restrict file name length for debug mode (-srd flag) to avoid system file creation errors.
2 participants