Skip to content

🐛 bug: stat the index for directory SendFile ranges and move the path guards into internal/fspath - #4769

Merged
ReneWerner87 merged 4 commits into
gofiber:mainfrom
ninadsutrave:chore/internal-fspath
Oct 19, 2026
Merged

ReneWerner87 merged 4 commits into
gofiber:mainfrom
ninadsutrave:chore/internal-fspath

Conversation

@ninadsutrave

@ninadsutrave ninadsutrave commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

Cluster 12 of #4604: filesystem path guards. internal/fspath now holds the checks between a request and fasthttp's file handler, for the static middleware and SendFile.

  • Valid is static's sanitizePath and its helpers, moved unchanged; static keeps only the call.
  • FSName / OSName give the name fasthttp opens for a SendFile name. sendFileContentLength used to clean only in the fs.FS branch; both branches use them now.
  • The package doc has the layer table: each check, who runs it, and the fasthttp behavior it exists for.
  • Stray % policy, written down: it's a name byte where nothing decodes afterwards (UnescapePath, SendFile), and static's default mode refuses a % that begins no escape the router kept. That's today's behavior.

Behavior change: a 416 from SendFile with ByteRange now has Content-Range: bytes */N when the name has dot segments (/srv/missing/../f.txt, or a/../../f.txt with an fs.FS). Before, the size lookup cleaned a different name than the one served and the header was missing. Covered by Test_SendFile_ByteRange_DotSegments.

It also fixes the 416 for a plain directory: SendFile(root+"/dir/") and an fs.FS "dir/" used to answer Content-Range: bytes */<size> with the directory's own stat size, and now report the size of the index.html they serve.

Left alone: the unhex/isUnreserved copies in path.go and internal/wiretarget are router side (cluster 4).

Related #4604

Changes introduced

  • Benchmarks: benchstat, 10 interleaved runs. Valid, static requests (OS hit, escape miss, rejected, fs.FS hit) and Ctx_SendFile are within noise with unchanged allocations. SendFile with a Range header is +1.7% (416) and +3.0% (206) for the extra clean.
  • Documentation Update: not needed, internal only.

Like #4750, I fuzzed against a verbatim copy of main with throwaway harnesses that aren't in the diff: Valid vs sanitizePath over nil, MapFS and DirFS roots (43.3M execs), and FSName/OSName vs the old cleaning and what fasthttp opens (23.6M execs). No differences apart from the dot-segment fix.

Type of change

  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Added or updated unit tests to validate the effectiveness of the changes or new features. internal/fspath is at 100% coverage.
  • Ensured that new and existing unit tests pass locally with the changes. make test, make lint, make format.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

🤖 Maintainers: /generate re-runs the code generators on this branch

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T07:10:09.195050Z 32c2c4d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ReneWerner87 ReneWerner87 added this to v3 Oct 17, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Oct 17, 2026
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 374b2c8a-7933-46f5-8b2a-777e4d244253
📥 Commits

Reviewing files that changed from the base of the PR and between c2db7a4 and 2c73757.

📒 Files selected for processing: 2
  • middleware/static/static.go
  • middleware/static/static_test.go
💤 Files with no reviewable changes: 1
  • middleware/static/static_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The change adds shared path validation and normalization helpers. Static middleware uses the validator, and SendFile uses normalized names when checking file sizes and directory indexes. Tests cover path handling and byte-range responses, including missing files.

Changes

File Path Handling

Layer / File(s) Summary
Shared path validation and normalization
internal/fspath/fspath.go, internal/fspath/fspath_test.go
The new fspath package validates paths and normalizes names for fs.FS and OS filesystems. Tests cover escape handling, unsafe segments, platform-specific paths, and name normalization.
Static middleware path validation
middleware/static/static.go, middleware/static/static_test.go
requestPath now validates constructed paths with fspath.Valid. The local sanitizer and its tests are removed.
SendFile file-size lookup
res.go, ctx_test.go
sendFileContentLength uses fspath.FSName or fspath.OSName before stat calls and checks directory index files. Tests cover byte-range responses for dot-segment paths, directory indexes, and missing files.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 2c737

The path-validation and byte-range changes appear ready to merge after normal checks; no material unresolved issue was established.

Security architecture risk: 🔵 Low · up to 2c737

Static-file validation remains enforced before file access. However, an unusual empty-filename configuration can report the size of a different file in a range-error response. Exposure is limited to file-size metadata within the application-selected filesystem and requires a particular filesystem layout; file-content disclosure was not established.

Retained concerns

  • Low · security · inferred: SendFile range metadata can identify a different custom-filesystem asset from the served resource. With an empty filename, ByteRange enabled, an existing root index.html, and a regular file at the working-directory-derived name inside the configured filesystem, an unsatisfiable Range can disclose the root index's size through Content-Range. The serving/sizing name divergence already existed, but the new root-directory and index resolution introduces this metadata source. The concern is conditional file-size disclosure, not demonstrated file-content access or filesystem escape.
Security review details

Security Blast Radius

  • inferred — The identified exposure is the length of root index.html in the filesystem selected by the application. It requires an endpoint calling SendFile with an empty filename and byte ranges enabled, plus a distinct regular-file entry matching the process working-directory path. No cross-filesystem escape, added privilege, or file-content disclosure follows from this path.

Security Findings and Attack Paths

  • inferred — For the conditional empty-filename configuration, a client-controlled unsatisfiable Range can cause the handler to reject the working-directory-derived file while Fiber supplies a length obtained from the unrelated root index. Deployment reachability and whether that index's length is sensitive are not established.

Trust Boundaries and Controls

  • observed — The static-path boundary retains validation before filesystem-handler invocation. Existing routed-path tests specify that guarded normalized names remain forbidden, encoded alternate spellings do not reach protected contents, and both OS-backed and custom-filesystem mounts preserve these expectations.

Resilience and Maintainability Implications

  • observed — Failure paths constrain the metadata issue: unsuccessful stat calls leave sizing unavailable, absent served targets return 404, and directory redirects are converted to 404 before the fallback. SendFile also defers restoration of the original request URI. These controls do not repair the successful alternate-file identity mismatch.

Hardening Proposals

  • proposed — Derive the handler URI and metadata lookup from one effective filename after empty-name handling, so range metadata cannot select a different asset. Preserve the existing missing-target behavior and cover the empty custom-filesystem case explicitly.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 64.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies both primary changes: correcting directory SendFile range statistics and moving path guards into internal/fspath.
Description check Passed The description is detailed and on-topic. It explains the problem, implementation changes, behavior fixes, tests, benchmarks, performance impact, and completed checklist items. It does not provide a f…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and on-topic. It explains the problem, implementation changes, behavior fixes, tests, benchmarks, performance impact, and completed checklist items. It does not provide a formal issue value after “Fixes #”, but it references related issue #4604, and the omitted template sections are not critical for this internal change.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks each path with care,
Through slashes, dots, and bytes laid bare.
An index waits where folders end,
And ranges find the file they send.
Missing paths return not found;
The rabbit hops on safer ground.

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.54%. Comparing base (4116498) to head (2c73757).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4769      +/-   ##
==========================================
+ Coverage   95.51%   95.54%   +0.03%     
==========================================
  Files         142      142              
  Lines       18082    18019      -63     
==========================================
- Hits        17271    17217      -54     
+ Misses        509      502       -7     
+ Partials      302      300       -2     
Flag Coverage Δ
unittests 95.54% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 32c2c4da0c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/fspath/fspath.go Resolved
@ReneWerner87 ReneWerner87 changed the title 🧹 chore: move the static and SendFile path guards into internal/fspath 🐛 bug: stat the index for directory SendFile ranges and move the path guards into internal/fspath Oct 19, 2026
@ReneWerner87
ReneWerner87 merged commit b49e7fc into gofiber:main Oct 19, 2026
28 checks passed
@github-project-automation github-project-automation Bot moved this to Done in v3 Oct 19, 2026
@ninadsutrave
ninadsutrave deleted the chore/internal-fspath branch October 21, 2026 08:39
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.7.0 Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants