Skip to content

fix(backend): relax CORS regex and add debugging logs#26

Open
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-regex-issue-7501668948331363069
Open

fix(backend): relax CORS regex and add debugging logs#26
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-regex-issue-7501668948331363069

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Feb 1, 2026

This PR addresses a CORS issue reported in production where the frontend origin was being blocked.

Changes:

  1. Regex Update: The cloud_origin_regex in backend/main.py has been updated to r"https://query-craft-frontend.*\.run\.app/?" to allow for an optional trailing slash. This ensures that even if the browser or a proxy appends a slash to the Origin header (an edge case), it will still be matched correctly.
  2. Debug Logging: Added logic to log_errors_middleware to log the Origin header for requests from *.run.app domains. This will provide visibility into exactly what Origin header is reaching the backend in production, facilitating faster debugging if the issue persists.
  3. Test Coverage: Added a new test case test_cors_origin_with_trailing_slash to tests/test_cors_config.py to verify the regex fix. Existing tests were also run and passed.

This change is safe as it only relaxes the regex slightly to cover valid variations of the frontend URL and adds harmless logging.


PR created automatically by Jules for task 7501668948331363069 started by @KnellBalm

Summary by Sourcery

Relax CORS origin matching and add CORS-focused diagnostics for Cloud Run traffic.

Bug Fixes:

  • Allow Cloud Run frontend origins with an optional trailing slash to pass CORS validation.

Enhancements:

  • Log incoming Origin headers for run.app requests to aid CORS debugging in production.

Documentation:

  • Update the implementation plan document to describe the CORS issue resolution steps instead of the previous incident.
  • Document the addition of CORS regex changes, Origin logging, and test coverage in the implementation plan.

Tests:

  • Add a CORS test to verify that origins with a trailing slash are accepted by the regex and keep disallowed-origin coverage intact.

- Update cloud_origin_regex in backend/main.py to allow `/?` at the end
- Add Origin header logging in log_errors_middleware for better production debugging
- Add test case for trailing slash origin in tests/test_cors_config.py
- Update docs/IMPLEMENTATION_PLAN.md with status

Co-authored-by: KnellBalm <90038472+KnellBalm@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Feb 1, 2026

Reviewer's Guide

Relaxes the Cloud Run CORS origin regex to accept an optional trailing slash, adds targeted Origin-header logging for run.app traffic to aid CORS debugging, and extends CORS test coverage and documentation to cover the new behavior.

Sequence diagram for CORS request handling with new Origin logging

sequenceDiagram
    actor Browser
    participant Frontend_run_app
    participant CloudRun_Ingress
    participant Backend_FastAPI
    participant log_errors_middleware
    participant CORS_Middleware
    participant App_Handlers

    Browser->>Frontend_run_app: Fetch API request with Origin https://query-craft-frontendXYZ.run.app/
    Frontend_run_app->>CloudRun_Ingress: Forward request
    CloudRun_Ingress->>Backend_FastAPI: HTTP request with Origin header

    Backend_FastAPI->>log_errors_middleware: Process incoming request
    log_errors_middleware->>log_errors_middleware: Read Origin header
    alt Origin header contains run.app
        log_errors_middleware->>Logging_backend_middleware_cors_debug: info Incoming Request Origin: {origin}
    else Origin header missing_or_non_run_app
        log_errors_middleware->>log_errors_middleware: Skip Origin logging
    end

    log_errors_middleware->>CORS_Middleware: Call next middleware

    alt Origin matches cloud_origin_regex https://query-craft-frontend.*\.run\.app/?
        CORS_Middleware->>App_Handlers: Allow request and forward to route handler
        App_Handlers-->>CORS_Middleware: Response
        CORS_Middleware-->>Browser: Response with CORS headers
    else Origin does not match regex
        CORS_Middleware-->>Browser: CORS error response
    end
Loading

Flow diagram for Cloud Run frontend to backend CORS and logging path

flowchart LR
    Browser[Browser] --> Frontend_run_app[Frontend Cloud Run service]
    Frontend_run_app --> CloudRun_Ingress[Cloud Run ingress]
    CloudRun_Ingress --> Backend_FastAPI[Backend FastAPI service]

    Backend_FastAPI --> log_errors_middleware[log_errors_middleware]
    log_errors_middleware --> CORS_Middleware[CORS middleware]

    CORS_Middleware -->|Origin_matches_cloud_origin_regex_https_query_craft_frontend_run_app_optional_slash| App_Handlers[Application route handlers]
    CORS_Middleware -->|Origin_does_not_match_regex| CORS_Error_Response[CORS error response]

    log_errors_middleware -->|Origin_header_contains_run_app| Logging_backend_middleware_cors_debug[Logger backend_middleware_cors_debug]
    log_errors_middleware -->|Origin_missing_or_not_run_app| CORS_Middleware
Loading

File-Level Changes

Change Details Files
Relax CORS Cloud Run origin regex to allow origins with an optional trailing slash.
  • Update cloud_origin_regex to include an optional trailing slash using '/?' in the pattern.
  • Ensure production CORS configuration continues to use the updated regex for Cloud Run origins.
backend/main.py
Add CORS-focused Origin header debug logging for Cloud Run traffic.
  • Extend log_errors_middleware to read the Origin header from incoming requests.
  • Create a dedicated logger (backend.middleware.cors_debug) and log Origin values only when they contain 'run.app' to reduce noise.
backend/main.py
Tighten and extend CORS test coverage and docs to cover trailing-slash origins and updated plan.
  • Add test_cors_origin_with_trailing_slash to verify that an origin with a trailing slash is allowed and CORS headers are set.
  • Remove overly verbose comments in existing CORS tests while preserving behavior.
  • Update IMPLEMENTATION_PLAN documentation to describe the CORS regex fix, logging addition, and related testing, replacing outdated incident content.
tests/test_cors_config.py
docs/IMPLEMENTATION_PLAN.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • The relaxed cloud_origin_regex (https://query-craft-frontend.*\.run\.app/?) would be safer and more precise if it were anchored at the end (e.g. r"https://query-craft-frontend.*\.run\.app/?$") to avoid accidentally matching origins that only contain .run.app as a substring in a longer host.
  • Consider moving the get_logger("backend.middleware.cors_debug") call outside log_errors_middleware (e.g. module-level) so the logger isn’t re-fetched on every request, reducing per-request overhead.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The relaxed `cloud_origin_regex` (`https://query-craft-frontend.*\.run\.app/?`) would be safer and more precise if it were anchored at the end (e.g. `r"https://query-craft-frontend.*\.run\.app/?$"`) to avoid accidentally matching origins that only contain `.run.app` as a substring in a longer host.
- Consider moving the `get_logger("backend.middleware.cors_debug")` call outside `log_errors_middleware` (e.g. module-level) so the logger isn’t re-fetched on every request, reducing per-request overhead.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

- Update cloud_origin_regex to allow trailing slash
- Add Origin logging in log_errors_middleware
- Refactor tests/test_cors_config.py to use mock.patch.dict for environment isolation to fix CI failures in test_integration.py

Co-authored-by: KnellBalm <90038472+KnellBalm@users.noreply.github.com>
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