Skip to content

Fix CORS issues and add Origin logging for debugging#24

Open
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-production-logging-1347566996273756232
Open

Fix CORS issues and add Origin logging for debugging#24
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-production-logging-1347566996273756232

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Jan 30, 2026

This PR addresses the reported CORS issue where the frontend (us-central1 region) was blocked from accessing the backend.

Changes:

  1. Observability: Added LogOriginMiddleware to log the Origin header of incoming requests. This helps verify if the browser is sending the expected origin and if it matches the allowed list/regex in the production environment.
  2. Configuration: Refactored backend/main.py to ensure cloud_origins and cloud_origin_regex are correctly defined and applied. The regex r"https://query-craft-frontend.*\.run\.app" supports various regional subdomains.
  3. Middleware Order: Explicitly ordered middleware (LogOrigin -> CORS -> Exception -> PathRewrite) to ensure proper handling of headers and logging.

Tests:

  • Verified locally with tests/reproduce_cors.py (created and then deleted).
  • Ran existing tests tests/test_cors_config.py and tests/test_auth.py which passed.

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

Summary by Sourcery

Clarify and harden CORS configuration while adding request origin logging for improved CORS debugging and error observability.

Bug Fixes:

  • Correct CORS configuration and middleware ordering to ensure Cloud Run frontend origins are properly allowed in production and development environments.

Enhancements:

  • Centralize Cloud Run origin and regex definitions for reuse across environments.
  • Introduce middleware to log incoming request Origin headers, paths, and methods before CORS handling for easier debugging of CORS issues.
  • Standardize middleware logging by using a shared backend.middleware logger for exception and origin logging.

- Add `LogOriginMiddleware` to `backend/common/middleware.py` to log `Origin` headers for debugging production CORS issues.
- Register `LogOriginMiddleware` in `backend/main.py` as the outermost middleware.
- Clean up `cloud_origins` list and `cloud_origin_regex` to ensure correct CORS configuration for Cloud Run domains (specifically us-central1).
- Verify CORS behavior with local tests.

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 Jan 30, 2026

Reviewer's Guide

Refactors CORS configuration in backend/main.py for clearer environment-specific setup, centralizes Cloud Run origin settings, and introduces a LogOriginMiddleware with explicit middleware ordering to aid CORS debugging and exception handling.

Sequence diagram for updated middleware order and CORS debugging

sequenceDiagram
    participant Client
    participant LogErrorsMiddleware
    participant LogOriginMiddleware
    participant CORSMiddleware
    participant ExceptionHandlingMiddleware
    participant PathRewriteMiddleware
    participant Router

    Client->>LogErrorsMiddleware: HTTP request
    LogErrorsMiddleware->>LogOriginMiddleware: request
    LogOriginMiddleware->>LogOriginMiddleware: Read Origin header
    LogOriginMiddleware->>LogOriginMiddleware: logger.info Origin, Path, Method
    LogOriginMiddleware->>CORSMiddleware: request
    CORSMiddleware->>ExceptionHandlingMiddleware: request
    ExceptionHandlingMiddleware->>PathRewriteMiddleware: request
    PathRewriteMiddleware->>Router: rewritten request
    Router-->>PathRewriteMiddleware: response
    PathRewriteMiddleware-->>ExceptionHandlingMiddleware: response
    ExceptionHandlingMiddleware-->>CORSMiddleware: response
    CORSMiddleware-->>LogOriginMiddleware: response with CORS headers
    LogOriginMiddleware-->>LogErrorsMiddleware: response
    LogErrorsMiddleware-->>Client: HTTP response
Loading

Class diagram for updated middleware structure and logging

classDiagram
    class BaseHTTPMiddleware {
        <<framework>>
        +dispatch(request, call_next)
    }

    class PathRewriteMiddleware {
        +dispatch(request, call_next)
    }

    class ExceptionHandlingMiddleware {
        +dispatch(request, call_next)
    }

    class LogOriginMiddleware {
        +dispatch(request, call_next)
    }

    class Logger {
        <<logging>>
        +info(message)
        +error(message)
    }

    BaseHTTPMiddleware <|-- PathRewriteMiddleware
    BaseHTTPMiddleware <|-- ExceptionHandlingMiddleware
    BaseHTTPMiddleware <|-- LogOriginMiddleware

    Logger <.. ExceptionHandlingMiddleware : uses logger.error
    Logger <.. LogOriginMiddleware : uses logger.info
Loading

File-Level Changes

Change Details Files
Centralize and adjust Cloud Run CORS origin configuration and usage.
  • Move cloud_origins and cloud_origin_regex definitions to the top-level of backend/main.py so they can be reused across environments.
  • Keep and slightly cleanup the explicit list of allowed Cloud Run origins and the flexible regex r"https://query-craft-frontend.*\.run.app" to cover multiple regional/subdomain variants.
  • Use the shared cloud_origins and cloud_origin_regex consistently in both production and non-production CORS middleware configuration blocks.
backend/main.py
Reorder middleware registration to make request processing and CORS debugging behavior explicit.
  • Document the intended middleware execution order (LogOrigin -> CORS -> Exception -> PathRewrite) in comments.
  • Register PathRewriteMiddleware first, then ExceptionHandlingMiddleware, then CORS middleware (production vs non-production branches), and finally LogOriginMiddleware so that it runs outer-most before CORS.
  • Clarify in comments how this order affects CORS handling, exception handling, and logging, including the interaction with the @app.middleware("http") error logging middleware.
backend/main.py
Add origin logging middleware for CORS debugging and standardize middleware logging usage.
  • Create a module-level logger via get_logger("backend.middleware") for reuse across middleware classes.
  • Update ExceptionHandlingMiddleware to use the shared logger instead of instantiating a logger on each exception.
  • Introduce LogOriginMiddleware that logs the Origin header, request path, and HTTP method for incoming requests before delegating to downstream middleware.
backend/common/middleware.py
backend/main.py

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:

  • In production CORS config you only use allow_origins=cloud_origins and never apply cloud_origin_regex, which seems to contradict the intent in the description; consider adding allow_origin_regex=cloud_origin_regex there as well if you want new Cloud Run regional domains to be automatically accepted.
  • The new LogOriginMiddleware will log every request’s origin, path, and method in all environments; you may want to gate this behind an environment flag or lower log level to avoid excessive log volume or unintentionally persisting sensitive request patterns in production.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In production CORS config you only use `allow_origins=cloud_origins` and never apply `cloud_origin_regex`, which seems to contradict the intent in the description; consider adding `allow_origin_regex=cloud_origin_regex` there as well if you want new Cloud Run regional domains to be automatically accepted.
- The new `LogOriginMiddleware` will log every request’s origin, path, and method in all environments; you may want to gate this behind an environment flag or lower log level to avoid excessive log volume or unintentionally persisting sensitive request patterns in production.

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.

- Fix `test_db_config_loads` failure in CI where `ENV` was leaking from other tests as `production`, causing `PostgresEnv` to require `POSTGRES_DSN`.
- Use `mock.patch.dict(os.environ, {"ENV": "development"})` to ensure the test runs in a controlled environment.

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