Skip to content

fix(standard-server): handle empty filename during file deserialization#320

Merged
dinwwwh merged 2 commits intomainfrom
fix/standard-server/deserialzie-empty-filename
Apr 1, 2025
Merged

fix(standard-server): handle empty filename during file deserialization#320
dinwwwh merged 2 commits intomainfrom
fix/standard-server/deserialzie-empty-filename

Conversation

@dinwwwh
Copy link
Copy Markdown
Member

@dinwwwh dinwwwh commented Apr 1, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced file upload processing with improved content disposition headers that now support UTF-8 encoded filenames and default naming when no filename is provided.
  • Chores
    • Removed an external dependency to streamline package management and reduce overhead.

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 1, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
orpc ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 1, 2025 8:28am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2025

Walkthrough

This pull request refactors content disposition handling in both server-fetch and server-node packages. It updates tests to spy on and verify calls to new utility functions for generating and extracting content disposition headers and filenames. The changes adjust file upload test cases to handle JSON content and missing filenames with a default value. Additionally, the implementation files now import in‐house utilities instead of external ones, and the expected headers have been updated to include UTF-8 encoded parameters. A dependency on an external content disposition package has been removed.

Changes

Files Change Summary
packages/standard-server-fetch/…/body.test.ts
packages/standard-server-node/…/body.test.ts
Updated tests for toStandardBody, toFetchBody, and toNodeHttpBody: added spies for generateContentDisposition and getFilenameFromContentDisposition, modified file upload tests (JSON content, default filenames), and adjusted header expectations.
packages/standard-server-fetch/…/body.ts
packages/standard-server-node/…/body.ts
Refactored imports by removing contentDisposition/parseContentDisposition and adding generateContentDisposition, getFilenameFromContentDisposition, and toArray; streamlined content disposition handling and filename extraction.
packages/standard-server-node/…/response.test.ts Updated expected content-disposition header format to include both standard and UTF-8 encoded filename parameters.
packages/standard-server/src/utils.ts
packages/standard-server/src/utils.test.ts
Introduced two new functions, generateContentDisposition and getFilenameFromContentDisposition, along with comprehensive tests covering various input cases and edge scenarios.
packages/standard-server/package.json Removed the dependency on @tinyhttp/content-disposition.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ServerFunction
    participant Utils
    Client->>ServerFunction: Submit file with content-disposition header
    ServerFunction->>Utils: getFilenameFromContentDisposition(header)
    Utils-->>ServerFunction: Return extracted filename (or undefined)
    alt Filename exists
        ServerFunction->>Client: Use extracted filename in response
    else
        ServerFunction->>Utils: generateContentDisposition('blob')
        Utils-->>ServerFunction: Return generated header
        ServerFunction->>Client: Return response with default filename
    end
Loading

Possibly related PRs

  • unnoq/orpc#290: Involved similar modifications to content disposition and filename extraction within the toStandardBody function.
  • unnoq/orpc#176: Addressed tests and implementation changes in toStandardBody and toFetchBody, focusing on file handling and content disposition verification.

Poem

I'm a rabbit hopping through the code,
Spying on headers down each debug road.
Files now sing with proper name and flair,
With UTF-8 tunes dancing in the air.
Hop along, let the neat fixes be bestowed!
🐇✨


📜 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 c0ca4c7 and 6321853.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • packages/standard-server-fetch/src/body.test.ts (3 hunks)
  • packages/standard-server-fetch/src/body.ts (4 hunks)
  • packages/standard-server-node/src/body.test.ts (4 hunks)
  • packages/standard-server-node/src/body.ts (3 hunks)
  • packages/standard-server-node/src/response.test.ts (2 hunks)
  • packages/standard-server/package.json (1 hunks)
  • packages/standard-server/src/utils.test.ts (1 hunks)
  • packages/standard-server/src/utils.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
packages/standard-server/src/utils.test.ts (1)
packages/standard-server/src/utils.ts (2)
  • generateContentDisposition (4-13)
  • getFilenameFromContentDisposition (15-26)
packages/standard-server-fetch/src/body.test.ts (2)
packages/standard-server-fetch/src/body.ts (2)
  • toStandardBody (6-50)
  • toFetchBody (58-102)
packages/standard-server-node/src/body.ts (1)
  • toStandardBody (9-48)
packages/standard-server-node/src/body.ts (4)
packages/standard-server-fetch/src/body.ts (1)
  • toStandardBody (6-50)
packages/standard-server-node/src/types.ts (1)
  • NodeHttpRequest (4-10)
packages/standard-server/src/types.ts (1)
  • StandardBody (5-11)
packages/standard-server/src/utils.ts (2)
  • getFilenameFromContentDisposition (15-26)
  • generateContentDisposition (4-13)
🔇 Additional comments (30)
packages/standard-server/package.json (1)

36-36: Dependency removed appropriately

The removal of the @tinyhttp/content-disposition dependency is consistent with the PR objectives, as this functionality has been replaced with custom implementations in the utils.ts file.

packages/standard-server-node/src/response.test.ts (2)

98-99: Updated content-disposition format with UTF-8 parameter

The test expectation has been correctly updated to match the new content-disposition format that includes UTF-8 encoding for better internationalization support.


109-110: Consistent header assertion

The assertion has been properly updated to match the same content-disposition format used in the spy expectation above, maintaining consistency throughout the test.

packages/standard-server/src/utils.test.ts (3)

1-2: Good test setup

The import statement correctly includes both new utility functions that are being tested in this file.


3-7: Comprehensive tests for content disposition generation

The tests for generateContentDisposition appropriately cover key scenarios:

  • Empty filenames
  • Standard filenames
  • Filenames with special characters requiring escaping and encoding

This ensures the function handles all relevant use cases.


9-27: Thorough filename extraction testing

The tests for getFilenameFromContentDisposition are comprehensive, covering:

  1. Both filename and filename* parameters
  2. Empty filenames
  3. Special characters requiring decoding
  4. Different disposition types (inline/attachment)
  5. Additional parameters in the header
  6. Invalid format handling

This thorough testing should help prevent regressions in filename handling.

packages/standard-server/src/utils.ts (2)

4-13: Well-implemented content disposition generator

The generateContentDisposition function correctly:

  1. Escapes double quotes in filenames
  2. Properly encodes special characters according to RFC standards
  3. Includes both standard and UTF-8 encoded filename parameters
  4. Uses the appropriate format with single quotes for the UTF-8 charset parameter

The implementation follows the MDN recommendations referenced in the comment.


15-26:

Details

❓ Verification inconclusive

Robust filename extraction with proper fallback

The getFilenameFromContentDisposition function properly:

  1. First attempts to extract from the UTF-8 encoded filename* parameter (preferred)
  2. Falls back to the standard filename parameter if needed
  3. Handles escaped quotes in the standard parameter
  4. Returns undefined for invalid or missing parameters

However, there's a potential issue with empty filenames:


🏁 Script executed:

#!/bin/bash
# Search for places in the codebase where getFilenameFromContentDisposition is used
# to see if they handle undefined return values properly

rg -C 5 "getFilenameFromContentDisposition" --type ts

Length of output: 18312


Filename Extraction Fallback Behavior — Verify Empty String Handling

The extraction logic in getFilenameFromContentDisposition is robust: it correctly prioritizes the UTF‑8 encoded filename* and falls back to the standard filename (while unescaping quotes). We verified through usages in both Node (in packages/standard-server-node/src/body.ts) and Fetch (in packages/standard-server-fetch/src/body.ts) modules—and their corresponding tests—that when a filename isn’t provided (i.e. the function returns undefined), a default of "blob" is applied.

However, note that if the header contains an empty filename (for example, filename=""), the function returns an empty string rather than undefined. Because the nullish coalescing operator (?? 'blob') does not trigger on empty strings, this could unintentionally allow an empty filename to propagate. Please verify whether an empty filename should be considered invalid and trigger the fallback or if the current behavior is intended.

  • Location: packages/standard-server/src/utils.ts (lines 15‑26)
  • Usage Impact: Referenced in both Node and Fetch body handlers where fallback logic is applied.
packages/standard-server-fetch/src/body.test.ts (8)

2-2: Good addition of standard server module and test spies.

The code adds proper imports and spies for testing the content disposition functions, which enables effective validation of their behavior in the tests.

Also applies to: 6-7


10-12: Good addition of beforeEach hook to clear mocks.

Adding this hook ensures that each test runs with fresh mocks, preventing test interference.


123-123: Appropriate verification of spy not being called.

This verifies that getFilenameFromContentDisposition isn't called when there's no content-disposition header, which validates the expected behavior.


126-144: Test correctly validates filename extraction from content disposition.

The test now uses JSON data instead of PDF and properly validates that getFilenameFromContentDisposition is called with the correct header value and that its return value is used for the file name.


147-166: Good new test case for missing filename in content-disposition.

This test case verifies the handling of content-disposition headers without a filename parameter, ensuring the default 'blob' value is used when the function returns undefined.


226-239: Proper testing of content disposition generation for blobs.

The test correctly mocks the content disposition generation function and verifies it's called with the default 'blob' name for regular Blob objects.


246-259: Proper testing of content disposition generation for files.

The test correctly mocks the content disposition generation function and verifies it's called with the actual filename when handling File objects.


262-277: Good test for preserving existing content disposition headers.

This test ensures that when a content-disposition header already exists, it's preserved and the generation function isn't called.

packages/standard-server-node/src/body.test.ts (8)

6-6: Good addition of standard server module and test spies.

The code adds proper imports and spies for testing the content disposition functions, providing consistent testing between the fetch and node implementations.

Also applies to: 12-13


15-17: Good addition of beforeEach hook to clear mocks.

Adding this hook ensures that each test runs with fresh mocks, preventing test interference.


142-142: Appropriate verification of spy not being called.

This verifies that getFilenameFromContentDisposition isn't called when there's no content-disposition header, which validates the expected behavior.


148-165: Test correctly validates filename extraction from content disposition.

The test now uses JSON data instead of PDF and properly validates that getFilenameFromContentDisposition is called with the correct header value and that its return value is used for the file name.


168-188: Good new test case for missing filename in content-disposition.

This test case verifies the handling of content-disposition headers without a filename parameter, ensuring the default 'blob' value is used when the function returns undefined.


259-272: Proper testing of content disposition generation for blobs.

The test correctly mocks the content disposition generation function and verifies it's called with the default 'blob' name for regular Blob objects.


287-300: Proper testing of content disposition generation for files.

The test correctly mocks the content disposition generation function and verifies it's called with the actual filename when handling File objects.


311-325: Good test for preserving existing content disposition headers.

This test ensures that when a content-disposition header already exists, it's preserved and the generation function isn't called.

packages/standard-server-fetch/src/body.ts (3)

3-3: Good replacement of external dependency with in-house utilities.

Importing utility functions from @orpc/standard-server instead of external libraries improves maintainability and reduces external dependencies.


13-20: Improved content disposition handling for file extraction.

The code now:

  1. Properly checks that content disposition is a string
  2. Uses the utility function to extract the filename
  3. Provides a fallback to 'blob' when no filename is found

This matches the behavior in the node implementation and handles empty filenames correctly.


63-77: Enhanced content disposition handling for HTTP responses.

The changes preserve any existing content-disposition header and only generate a new one if needed, using the appropriate filename based on the type of blob (File or regular Blob).

packages/standard-server-node/src/body.ts (3)

5-6: Good replacement of external dependency with in-house utilities.

Importing utility functions from @orpc/standard-server and adding toArray from @orpc/shared improves maintainability and reduces external dependencies.


19-22: Improved content disposition handling for file extraction.

The code now:

  1. Properly checks that content disposition is a string
  2. Uses the utility function to extract the filename
  3. Provides a fallback to 'blob' when no filename is found

This matches the behavior in the fetch implementation and handles empty filenames correctly.


62-74: Enhanced content disposition handling for HTTP responses.

The changes properly extract the first value from the content-disposition header (handling Node.js specifics) and preserve any existing header, only generating a new one if needed. This uses the appropriate filename based on the type of blob (File or regular Blob).

🧰 Tools
🪛 Biome (1.9.4)

[error] 64-64: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 65-65: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 1, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Apr 1, 2025

More templates

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@320

@orpc/client

npm i https://pkg.pr.new/@orpc/client@320

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@320

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@320

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@320

@orpc/react

npm i https://pkg.pr.new/@orpc/react@320

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@320

@orpc/server

npm i https://pkg.pr.new/@orpc/server@320

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@320

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@320

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@320

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@320

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@320

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@320

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@320

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@320

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@320

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@320

commit: 6321853

@dinwwwh dinwwwh merged commit 910f96e into main Apr 1, 2025
8 checks 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.

1 participant