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

add timestamp to the export filename #366

Merged
merged 1 commit into from
Dec 2, 2024

Conversation

saivishnu725
Copy link
Contributor

@saivishnu725 saivishnu725 commented Dec 2, 2024

What type of PR is this?

  • feature

What this PR does / why we need it:

This PR introduces the ability to include a timestamp in the filenames of exported CSVs in the items export feature. Previously, filenames were static, making it difficult to distinguish between multiple exports. Adding a timestamp ensures that each export is uniquely identifiable and reflects the time of export.

Changes:

  • Modified the HandleItemsExport method to dynamically generate a timestamp using Go’s time formatting.
  • Updated the Content-Disposition header to include the dynamically generated filename.

Special notes for your reviewer:

I am new to contributing to any software and new to the Go language. If I made any mistakes, I would love to be informed and guided. I thought this change was necessary, so I got the timestamp code from StackOverflow and made it work.

Testing

I manually exported files after several minutes and confirmed that the timestamp in the filenames was accurate. I didn’t perform any other tests. Please advise on additional testing methods if necessary.

Summary by CodeRabbit

  • New Features
    • Enhanced item export functionality with dynamically generated filenames that include timestamps.
  • Bug Fixes
    • Improved error handling for item import processes to ensure better logging of issues.

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request enhance the item export feature in the v1_ctrl_items.go file. A new import for the time package allows for dynamic generation of filenames that include a timestamp for exported CSV files. The error handling in the HandleItemsImport function remains unchanged, preserving the overall structure and control flow of the API handlers while improving the uniqueness of exported filenames.

Changes

File Path Change Summary
backend/app/api/handlers/v1/v1_ctrl_items.go - Added import for time package.
- Updated HandleItemsExport to generate a timestamped filename for exports.
- Error handling in HandleItemsImport remains unchanged.

Security Recommendations

  • Ensure that all input files for import are validated to prevent potential injection attacks or processing of malicious data.
  • Implement rate limiting on the export functionality to avoid potential denial-of-service attacks from excessive requests.
  • Consider logging sensitive information carefully to avoid exposing any personal data in the logs.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b48ae25 and 6aa68ca.

📒 Files selected for processing (1)
  • backend/app/api/handlers/v1/v1_ctrl_items.go (2 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
backend/app/api/handlers/v1/v1_ctrl_items.go

349-349: illegal rune literal

(typecheck)

🔇 Additional comments (2)
backend/app/api/handlers/v1/v1_ctrl_items.go (2)

12-12: LGTM: Clean import addition

The time package import is correctly placed and necessary for the timestamp functionality.


Line range hint 344-353: Verify timestamp implementation

Let's verify there are no other timestamp implementations that should follow the same format for consistency.

✅ Verification successful

The previous search might have been too specific. Let's broaden our search to catch different variations of timestamp formatting and CSV operations where timestamps might be used.


Timestamp format implementation is consistent and secure

The timestamp format 2006-01-02_15-04-05 is only used for CSV file naming in the codebase. Other timestamp formats in the codebase serve different purposes:

  • time.ANSIC for entity string representations
  • 2006-01-02 for date-only formatting
  • 2006-01-02 15:04:05 for database queries

Security recommendation: The current implementation is secure as it:

  • Uses safe characters for filenames
  • Doesn't expose sensitive timezone information
  • Maintains consistent format for CSV exports
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other timestamp format implementations
rg -l "time\.Now\(\)\.Format\(" | grep -v "v1_ctrl_items.go"

Length of output: 60


Script:

#!/bin/bash
# Let's try a broader search for timestamp-related patterns
rg -A 2 "time\.Now\(\)" --type go

# Also search for Format specifically
rg -A 2 "\.Format\(" --type go

# And look for any CSV-related operations that might have timestamps
rg -A 2 "\.csv" --type go

Length of output: 14942

🧰 Tools
🪛 golangci-lint (1.62.2)

349-349: illegal rune literal

(typecheck)


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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
backend/app/api/handlers/v1/v1_ctrl_items.go (2)

344-346: Consider sanitizing the filename for additional security

While the current implementation is functional, consider adding filename sanitization to prevent potential header injection attacks. Even though we're generating the filename internally, it's a good security practice.

Consider adding a helper function:

+func sanitizeFilename(filename string) string {
+    // Remove or replace potentially dangerous characters
+    return strings.Map(func(r rune) rune {
+        switch {
+        case r >= 'a' && r <= 'z',
+             r >= 'A' && r <= 'Z',
+             r >= '0' && r <= '9',
+             r == '-' || r == '_' || r == '.':
+            return r
+        default:
+            return '-'
+        }
+    }, filename)
+}

And use it:

-filename := fmt.Sprintf("homebox-items_%s.csv", timestamp)
+filename := sanitizeFilename(fmt.Sprintf("homebox-items_%s.csv", timestamp))

Line range hint 338-354: Consider adding rate limiting for file downloads

The export endpoint could be vulnerable to DoS attacks if users repeatedly request large exports. Consider implementing rate limiting for this endpoint.

Suggestions:

  1. Add a rate limiter middleware
  2. Consider implementing request size limits
  3. Add monitoring for excessive downloads

Would you like assistance in implementing these security measures?

🛑 Comments failed to post (1)
backend/app/api/handlers/v1/v1_ctrl_items.go (1)

349-349: 🛠️ Refactor suggestion

Add quotes to Content-Disposition filename for security

The Content-Disposition header should have the filename properly quoted to prevent potential header injection and ensure proper handling of special characters.

-w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename))
+w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
📝 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.

		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
backend/app/api/handlers/v1/v1_ctrl_items.go (2)

345-345: Consider moving the timestamp format to a constant

The timestamp format string "2006-01-02_15-04-05" should be defined as a constant at package level for better maintainability and reusability.

+const (
+    ExportTimestampFormat = "2006-01-02_15-04-05"
+)

 func (ctrl *V1Controller) HandleItemsExport() errchain.HandlerFunc {

Line range hint 344-353: Security: Add content security headers

Consider adding security headers to prevent content sniffing and force file download.

 		w.Header().Set("Content-Type", "text/csv")
+		w.Header().Set("X-Content-Type-Options", "nosniff")
+		w.Header().Set("Content-Security-Policy", "default-src 'none'")
 		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
🧰 Tools
🪛 golangci-lint (1.62.2)

349-349: illegal rune literal

(typecheck)

🛑 Comments failed to post (1)
backend/app/api/handlers/v1/v1_ctrl_items.go (1)

349-349: ⚠️ Potential issue

Fix string literal syntax and add filename sanitization

There are two issues here:

  1. Using single quotes instead of double quotes for string literal
  2. Missing filename sanitization for security

Apply this fix:

-		w.Header().Set("Content-Disposition", fmt.Sprintf('attachment;filename=%s', filename))
+		// Sanitize filename to prevent header injection
+		sanitizedFilename := strings.ReplaceAll(filename, `"`, `\"`)
+		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", sanitizedFilename))

This change:

  1. Fixes the string literal syntax
  2. Properly escapes quotes in filename
  3. Follows RFC 6266 format for Content-Disposition header
📝 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.

		// Sanitize filename to prevent header injection
		sanitizedFilename := strings.ReplaceAll(filename, `"`, `\"`)
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", sanitizedFilename))
🧰 Tools
🪛 golangci-lint (1.62.2)

349-349: illegal rune literal

(typecheck)

@saivishnu725
Copy link
Contributor Author

I will reset it back to the original double quotes and wait for a human to say what to fix.

@tankerkiller125 tankerkiller125 merged commit 8dca148 into sysadminsmedia:main Dec 2, 2024
1 check passed
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.

2 participants