Skip to content

Fix CORS issues: Add logging middleware and relax origin regex#29

Open
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-logging-regex-3287224115208316547
Open

Fix CORS issues: Add logging middleware and relax origin regex#29
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-logging-regex-3287224115208316547

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Feb 4, 2026

Resolved a reported CORS issue where the backend was allegedly stripping Access-Control-Allow-Origin headers.
Since local reproduction showed correct behavior, I added CORSLoggingMiddleware to the backend to log Origin headers and response headers in production, enabling better diagnosis.
I also updated the CORS regex to be slightly more permissive (allowing HTTP) to rule out protocol mismatches.
Verified with new and existing tests.


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

Summary by Sourcery

Add CORS logging middleware and relax allowed origin patterns to aid debugging of reported CORS issues.

New Features:

  • Introduce CORSLoggingMiddleware to record request origins and corresponding CORS response headers for debugging.

Enhancements:

  • Broaden the CORS origin regex to accept both HTTP and HTTPS Cloud Run frontend domains.
  • Apply the new CORS logging middleware globally so CORS behavior can be inspected in all environments.

Tests:

  • Add tests verifying that the CORS logging middleware records logs when an Origin header is present and remains silent when it is absent.

- Added `CORSLoggingMiddleware` to `backend/common/middleware.py` and registered it in `backend/main.py` to facilitate debugging of CORS issues in production.
- Updated `cloud_origin_regex` in `backend/main.py` to allow both HTTP and HTTPS (`https?://`) for robustness.
- Added `tests/test_cors_logging.py` to verify the new logging middleware.
- Verified that existing CORS configuration tests pass.

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 4, 2026

Reviewer's Guide

Adds a CORS-specific logging middleware to trace origins and response headers, relaxes the CORS origin regex to allow both HTTP and HTTPS Cloud Run frontend URLs, wires the middleware into the FastAPI app, and introduces tests to validate logging behavior without requiring real DB/scheduler dependencies.

Sequence diagram for request flow with CORSLoggingMiddleware and CORSMiddleware

sequenceDiagram
  actor Browser
  participant BackendApp
  participant CORSLoggingMiddleware
  participant CORSMiddleware
  participant Endpoint

  Browser->>BackendApp: HTTP request with Origin header
  BackendApp->>CORSLoggingMiddleware: dispatch(request, call_next)
  CORSLoggingMiddleware->>CORSLoggingMiddleware: log CORS Request Origin
  CORSLoggingMiddleware->>CORSMiddleware: call_next(request)
  CORSMiddleware->>Endpoint: call_next(request)
  Endpoint-->>CORSMiddleware: Response
  CORSMiddleware->>CORSMiddleware: apply CORS rules using cloud_origin_regex
  CORSMiddleware-->>CORSLoggingMiddleware: Response with access-control-allow-origin
  CORSLoggingMiddleware->>CORSLoggingMiddleware: log CORS Response headers and status
  CORSLoggingMiddleware-->>BackendApp: Response
  BackendApp-->>Browser: HTTP response with CORS headers
Loading

Class diagram for new CORSLoggingMiddleware integration

classDiagram

class BaseHTTPMiddleware {
  +dispatch(request, call_next)
}

class CORSLoggingMiddleware {
  +dispatch(request, call_next)
}

class CORSMiddleware {
  +__init__(allow_origins, allow_origin_regex, allow_credentials, allow_methods, allow_headers)
  +dispatch(request, call_next)
}

class FastAPIApp {
  +add_middleware(middleware_class)
}

CORSLoggingMiddleware --|> BaseHTTPMiddleware
CORSMiddleware --|> BaseHTTPMiddleware
FastAPIApp ..> CORSMiddleware : uses
FastAPIApp ..> CORSLoggingMiddleware : uses
Loading

File-Level Changes

Change Details Files
Introduce CORSLoggingMiddleware to trace CORS request/response details.
  • Add CORSLoggingMiddleware class extending BaseHTTPMiddleware that logs request Origin, path, and method when an Origin header is present.
  • Log the corresponding Access-Control-Allow-Origin response header and status code for requests with an Origin header.
  • Ensure middleware is a no-op for requests lacking an Origin header.
backend/common/middleware.py
Wire CORS logging into the FastAPI app and relax allowed Cloud Run origins.
  • Broaden cloud_origin_regex from HTTPS-only to allow both HTTP and HTTPS for query-craft-frontend*.run.app.
  • Register CORSMiddleware as before and then add CORSLoggingMiddleware globally after CORS configuration so it can observe final headers.
  • Maintain existing production vs. non-production origin whitelisting behavior while adding logging on all environments.
backend/main.py
Add tests to validate CORS logging middleware behavior and isolate app from real infrastructure.
  • Create pytest tests using TestClient to assert that CORSLoggingMiddleware logs both request origin and response headers when Origin is present and allowed.
  • Verify that no CORS logging occurs when the Origin header is absent.
  • Mock environment variables and critical modules (db_init, scheduler) so importing backend.main in tests does not trigger real DB connections or background threads.
tests/test_cors_logging.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 CORSLoggingMiddleware, you're calling get_logger on every request; consider instantiating the logger once at module or class level to avoid per-request logger lookup overhead.
  • The CORS logging tests manipulate sys.path, environment variables, and sys.modules at import time; it would be more robust to move this setup into pytest fixtures (and cleanly restore env/module state) rather than mutating global process state in the test module body.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `CORSLoggingMiddleware`, you're calling `get_logger` on every request; consider instantiating the logger once at module or class level to avoid per-request logger lookup overhead.
- The CORS logging tests manipulate `sys.path`, environment variables, and `sys.modules` at import time; it would be more robust to move this setup into pytest fixtures (and cleanly restore env/module state) rather than mutating global process state in the test module body.

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.

- Added `CORSLoggingMiddleware` to `backend/common/middleware.py` and registered it in `backend/main.py`.
- Updated `cloud_origin_regex` to allow both HTTP and HTTPS.
- Added `tests/test_cors_logging.py` to verify logging middleware.
- Fixed environment pollution in `tests/test_cors_config.py` and `tests/test_cors_logging.py` ensuring `ENV` is restored after tests, preventing 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