Skip to content

Fix CORS error for query-craft-frontend-758178119666#33

Open
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-origin-issue-11874747566118330029
Open

Fix CORS error for query-craft-frontend-758178119666#33
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-origin-issue-11874747566118330029

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Feb 8, 2026

This PR addresses the CORS policy error reported for https://query-craft-frontend-758178119666.us-central1.run.app.

Changes:

  1. Moved CORS Variables: Moved cloud_origins and cloud_origin_regex to the top of backend/main.py (before lifespan) to ensure they are properly defined and initialized.
  2. Verified Origin: Confirmed and ensured the specific failing origin is present in the cloud_origins list.
  3. Added Debugging Middleware: Added CORSLoggingMiddleware in backend/common/middleware.py and registered it as the outermost middleware in backend/main.py. This middleware logs a warning if a request has an Origin header but the response lacks the Access-Control-Allow-Origin header, aiding in future debugging.

Verified with tests/test_cors_config.py.


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

Summary by Sourcery

Resolve CORS header issues for Cloud Run frontend origins and add logging to diagnose future CORS problems.

Bug Fixes:

  • Ensure Cloud Run frontend origins, including the previously failing domain, are correctly recognized by the CORS configuration.

Enhancements:

  • Introduce CORS logging middleware to detect and log requests with an Origin header that do not receive Access-Control-Allow-Origin in the response.

- Move cloud_origins and cloud_origin_regex to module scope in backend/main.py
- Ensure failing origin is in allow_origins list
- Add CORSLoggingMiddleware to backend/common/middleware.py
- Register CORSLoggingMiddleware in backend/main.py (outermost) to debug missing headers

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

Reviewer's Guide

Adjusts CORS configuration initialization order and adds logging middleware to detect missing CORS headers for Cloud Run origins, specifically covering the failing frontend origin.

Sequence diagram for HTTP request flow with CORSLoggingMiddleware

sequenceDiagram
    actor Browser
    participant FrontendService
    participant BackendService
    participant CORSLoggingMiddleware
    participant CORSMiddleware
    participant ExceptionHandlingMiddleware
    participant FastAPIApp

    Browser->>FrontendService: HTTPS request
    FrontendService->>BackendService: HTTPS request with Origin header

    BackendService->>CORSLoggingMiddleware: Incoming request
    activate CORSLoggingMiddleware
    CORSLoggingMiddleware->>CORSMiddleware: call_next(request)
    activate CORSMiddleware
    CORSMiddleware->>ExceptionHandlingMiddleware: call_next(request)
    activate ExceptionHandlingMiddleware
    ExceptionHandlingMiddleware->>FastAPIApp: call_next(request)
    activate FastAPIApp
    FastAPIApp-->>ExceptionHandlingMiddleware: Response
    deactivate FastAPIApp
    ExceptionHandlingMiddleware-->>CORSMiddleware: Response
    deactivate ExceptionHandlingMiddleware
    CORSMiddleware-->>CORSLoggingMiddleware: Response with CORS headers
    deactivate CORSMiddleware

    CORSLoggingMiddleware->>CORSLoggingMiddleware: Check Origin header
    CORSLoggingMiddleware->>CORSLoggingMiddleware: Check AccessControlAllowOrigin header
    alt Origin present and AccessControlAllowOrigin missing
        CORSLoggingMiddleware->>Logger: warning CORS header missing
    end
    CORSLoggingMiddleware-->>BackendService: Final response
    deactivate CORSLoggingMiddleware

    BackendService-->>FrontendService: HTTP response
    FrontendService-->>Browser: HTTP response with CORS headers
Loading

Updated class diagram for CORSLoggingMiddleware

classDiagram
    class BaseHTTPMiddleware {
        <<external>>
    }

    class CORSLoggingMiddleware {
        +dispatch(request, call_next)
    }

    CORSLoggingMiddleware --|> BaseHTTPMiddleware
Loading

File-Level Changes

Change Details Files
Ensure CORS origin configuration is initialized before application lifespan and middleware setup so Cloud Run origins are correctly allowed.
  • Move cloud_origins and cloud_origin_regex definitions to the top of main.py before lifespan and app/middleware initialization
  • Keep the list of allowed Cloud Run origins including the previously failing origin and regex for query-craft-frontend*.run.app
backend/main.py
Add middleware to log cases where requests with an Origin header are returned without Access-Control-Allow-Origin to aid CORS debugging.
  • Implement CORSLoggingMiddleware that inspects request Origin and response Access-Control-Allow-Origin headers and logs a warning when the CORS header is missing
  • Register CORSLoggingMiddleware as the outermost middleware by adding it after other app.add_middleware calls
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 CORSLoggingMiddleware, you recreate the logger on every request; consider instantiating logger = get_logger("backend.middleware.cors") once at module scope and reusing it inside dispatch to avoid per-request overhead.
  • Since CORSLoggingMiddleware is intended to diagnose missing CORS headers, you might want to log additional context such as request method and query string (e.g., request.method, request.url.query) to make the log entries more actionable when debugging.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `CORSLoggingMiddleware`, you recreate the logger on every request; consider instantiating `logger = get_logger("backend.middleware.cors")` once at module scope and reusing it inside `dispatch` to avoid per-request overhead.
- Since `CORSLoggingMiddleware` is intended to diagnose missing CORS headers, you might want to log additional context such as request method and query string (e.g., `request.method`, `request.url.query`) to make the log entries more actionable when debugging.

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.

- Refactor `tests/test_cors_config.py` to use `mock.patch.dict` and `importlib.reload` instead of setting `os.environ` globally, preventing `ENV='production'` from leaking into other tests.
- Update `tests/test_integration.py` to defensively set `ENV='development'` using `mock.patch.dict` in `test_db_config_loads` and `TestPostgresIntegration` to ensure robustness against environment changes.
- This resolves the `ValueError: POSTGRES_DSN is required in production environment` error in CI.

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