Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Jan 18, 2026

Motivation

  • Prevent unbounded reads when loading a configured favicon file by enforcing a safe maximum asset size and failing fast on oversized files.
  • Simplify size checks to use a single bounded read path instead of multiple stat-based checks and redundant panics.

Description

  • Add MaxBytes int64 to favicon.Config with a default of 1024 * 1024 and apply defaulting in configDefault.
  • Replace the previous os.Stat/fs.Stat pre-checks and direct os.ReadFile/io.ReadAll uses with a single readLimited helper that reads via io.LimitReader and returns an error if the file exceeds MaxBytes.
  • Simplify New to always use the bounded reader path when Config.File is set and remove the extra size-check panics.
  • Update documentation in docs/middleware/favicon.md to document the MaxBytes option and add an entry to docs/whats_new.md noting the favicon size limit change.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 18, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

The favicon middleware adds a configurable MaxBytes (default 1 MiB) and uses a new readLimited helper to limit reads when loading favicon assets, panicking during setup if the asset exceeds the configured limit.

Changes

Cohort / File(s) Summary
Configuration
middleware/favicon/config.go
Added public MaxBytes int64 (json:"max_bytes") to Config, set ConfigDefault.MaxBytes = 1024 * 1024, and defaulted unset/<=0 values in configDefault().
Implementation
middleware/favicon/favicon.go
Added readLimited(io.Reader, int64) to enforce max-size reads, replaced direct file reads with readLimited when loading favicon data, and added fmt import for error messages.
Testing
middleware/favicon/favicon_test.go
Added tests asserting panic when favicon exceeds MaxBytes (Test_Middleware_Favicon_MaxBytes, Test_Middleware_Favicon_MaxBytes_FileSystem) and added bytes import; adjusted an error message expectation.
Documentation
docs/middleware/favicon.md, docs/whats_new.md
Documented new MaxBytes field and described the new limited-reader behavior and default (1 MiB) in the middleware docs and v3 "What's New".

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer/Test
    participant Middleware as FaviconMiddleware
    participant FS as FileSystem / OS
    participant Cache as In-memory Cache

    Dev->>Middleware: create middleware with Config{MaxBytes}
    Middleware->>FS: open favicon file / read from FileSystem
    FS-->>Middleware: io.Reader
    Middleware->>Middleware: readLimited(reader, MaxBytes)
    alt size <= MaxBytes
        Middleware->>Cache: store favicon bytes, content-type, len
        Middleware-->>Dev: middleware created successfully
    else size > MaxBytes
        Middleware-->>Dev: panic during setup (size exceeded)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

📒 Documentation

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 I nibble bytes with careful care,
One-meg cap keeps assets fair.
readLimited guards the stash so sweet,
Panic catches oversized treat —
Hop, cache, and serve with skipping feet! 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description provides clear motivation, implementation details, and documentation updates. However, it does not follow the provided template structure with explicit sections like 'Changes introduced' checklist items, 'Type of change', and 'Checklist'. Restructure the description to match the repository's template format, including explicit sections for changes introduced (with checkboxes), type of change selection, and completion checklist items.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding a MaxBytes configuration field to the favicon middleware, which aligns with the primary objective of the pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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

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

@ReneWerner87 ReneWerner87 added this to v3 Jan 18, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jan 18, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the favicon middleware by introducing a configurable maximum size limit for favicon assets. This change addresses potential security and performance issues by preventing the loading of excessively large files, thereby safeguarding against unbounded reads and simplifying the file size validation process. The update streamlines the internal file reading mechanism and ensures that the middleware operates more securely and efficiently.

Highlights

  • Favicon Asset Size Limit: Introduced a MaxBytes configuration option for the favicon middleware, defaulting to 1MB, to prevent unbounded reads and enforce a safe maximum asset size when loading favicon files.
  • Simplified File Reading Logic: Replaced previous os.Stat/fs.Stat pre-checks and direct os.ReadFile/io.ReadAll calls with a single readLimited helper function that uses io.LimitReader to safely read files and detect oversized assets.
  • Improved Error Handling: The New function now consistently uses the bounded reader path, removing redundant size-check panics and providing a more robust mechanism for handling oversized favicon files.
  • Documentation Updates: Updated the docs/middleware/favicon.md to document the new MaxBytes option and added an entry to docs/whats_new.md to highlight this change.
  • New Test Case: Added Test_Middleware_Favicon_MaxBytes to ensure the middleware correctly panics when attempting to load a favicon file that exceeds the configured MaxBytes limit.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gaby gaby changed the title 🐛 bug: limit favicon asset size 🔥 feat: Add MaxBytes to favicon middleware Jan 18, 2026
@gaby gaby removed the ☢️ Bug label Jan 18, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a potential security vulnerability by introducing a size limit for favicon assets, preventing unbounded memory allocation. The implementation adds a MaxBytes configuration, a readLimited helper for safe file reading, and updates documentation and tests accordingly. The changes are well-structured and clear. I have one suggestion to refactor a small piece of duplicated code to improve maintainability. Overall, this is a valuable and well-executed enhancement.

@codecov
Copy link

codecov bot commented Jan 18, 2026

Codecov Report

❌ Patch coverage is 90.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.14%. Comparing base (1771023) to head (95811e7).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
middleware/favicon/favicon.go 88.88% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4016      +/-   ##
==========================================
- Coverage   91.17%   91.14%   -0.04%     
==========================================
  Files         119      119              
  Lines       10946    10963      +17     
==========================================
+ Hits         9980     9992      +12     
- Misses        609      613       +4     
- Partials      357      358       +1     
Flag Coverage Δ
unittests 91.14% <90.00%> (-0.04%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 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.

@gaby gaby marked this pull request as ready for review January 18, 2026 19:56
@gaby gaby requested a review from a team as a code owner January 18, 2026 19:56
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request adds a configurable size limit to the favicon middleware to prevent unbounded reads when loading favicon files from disk, improving safety and resource management.

Changes:

  • Added MaxBytes configuration field with a default of 1 MiB (1,048,576 bytes)
  • Introduced readLimited helper function that enforces the size limit using io.LimitReader
  • Replaced direct file read operations with bounded reads that fail fast on oversized files

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
middleware/favicon/config.go Adds MaxBytes field to Config struct with default value and validation in configDefault
middleware/favicon/favicon.go Implements readLimited helper and refactors file loading to use bounded reads for both FileSystem and os.Open paths
middleware/favicon/favicon_test.go Adds test case to verify panic behavior when file exceeds MaxBytes limit
docs/middleware/favicon.md Documents the new MaxBytes configuration option with type, description, and default value
docs/whats_new.md Adds Favicon section describing the new size limit feature in both the changes overview and migration guide TOC

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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@middleware/favicon/favicon_test.go`:
- Around line 62-68: The test error messages contain a typo ("cache" instead of
"catch"); update the t.Error calls in Test_Middleware_Favicon_MaxBytes and the
similar message in Test_Middleware_Favicon_Not_Found to read "should catch
panic" (or equivalent) so the assertion text correctly describes the
expectation; search for the string "should cache panic" in those test functions
and replace it with "should catch panic".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants