Skip to content

Fix CORS issue for frontend and add CORS logging#35

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

Fix CORS issue for frontend and add CORS logging#35
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-issue-12635860337990726010

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Feb 11, 2026

Explicitly verified and commented the allowed origin for the frontend. Added CORSLoggingMiddleware to catch and log potential CORS misconfigurations in production.


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

Summary by Sourcery

Add logging middleware to detect and report missing CORS headers on responses while clarifying verified frontend origin configuration.

Enhancements:

  • Introduce CORSLoggingMiddleware to log requests with an Origin header when the response lacks an Access-Control-Allow-Origin header.
  • Comment the verified Cloud Run frontend origin in the CORS allowed origins list for clearer configuration intent.

- Added `CORSLoggingMiddleware` to `backend/common/middleware.py` and registered it in `backend/main.py`.
- Verified and commented the allowed origin `https://query-craft-frontend-758178119666.us-central1.run.app` in `backend/main.py`.
- Ran tests to ensure no regressions.

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

Reviewer's Guide

Adds a CORS-focused logging middleware to help detect missing CORS headers in responses, and documents/clarifies a verified allowed frontend origin in the CORS configuration.

Sequence diagram for CORSLoggingMiddleware around CORSMiddleware

sequenceDiagram
    actor Browser
    participant FastAPIApp
    participant CORSLoggingMiddleware
    participant CORSMiddleware
    participant RouteHandler

    Browser->>FastAPIApp: HTTP request with Origin header
    FastAPIApp->>CORSLoggingMiddleware: process request
    CORSLoggingMiddleware->>CORSMiddleware: call_next(request)
    CORSMiddleware->>RouteHandler: forward request
    RouteHandler-->>CORSMiddleware: response
    CORSMiddleware-->>CORSLoggingMiddleware: response with CORS headers
    CORSLoggingMiddleware->>CORSLoggingMiddleware: check Origin and Access-Control-Allow-Origin
    alt missing Access-Control-Allow-Origin
        CORSLoggingMiddleware->>CORSLoggingMiddleware: log CORS warning
    end
    CORSLoggingMiddleware-->>Browser: final HTTP response
Loading

Class diagram for new CORSLoggingMiddleware

classDiagram
    class BaseHTTPMiddleware {
    }

    class CORSLoggingMiddleware {
        +dispatch(request, call_next)
    }

    CORSLoggingMiddleware --|> BaseHTTPMiddleware
Loading

File-Level Changes

Change Details Files
Introduce middleware to log potential CORS configuration issues at runtime.
  • Add CORSLoggingMiddleware subclassing BaseHTTPMiddleware to inspect responses after CORSMiddleware processing
  • Log a warning when a request has an Origin header but the response lacks an Access-Control-Allow-Origin header, including the origin and status code
  • Ensure the middleware returns the original response unchanged after logging
backend/common/middleware.py
Clarify and integrate CORS configuration for the known frontend origin and add the logging middleware to the app stack.
  • Annotate the verified Cloud Run frontend origin in the cloud_origins list with an explanatory comment
  • Register CORSLoggingMiddleware after CORSMiddleware so it can observe final CORS headers for all responses
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 found 1 issue, and left some high level feedback:

  • Consider instantiating the backend.middleware.cors logger at module level instead of inside dispatch to avoid repeated logger lookups on every request.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider instantiating the `backend.middleware.cors` logger at module level instead of inside `dispatch` to avoid repeated logger lookups on every request.

## Individual Comments

### Comment 1
<location> `backend/common/middleware.py:52` </location>
<code_context>
+            if not allow_origin:
+                # If it's a 404/500, sometimes headers are missing if not handled correctly.
+                # But generally CORSMiddleware adds them even for errors.
+                logger = get_logger("backend.middleware.cors")
+                logger.warning(f"CORS Warning: Origin '{origin}' requested but no 'Access-Control-Allow-Origin' header in response. Status: {response.status_code}")
+
</code_context>

<issue_to_address>
**suggestion (performance):** Instantiate the logger once at module or class level instead of per-request.

Looking up the logger inside `dispatch` adds unnecessary overhead in a hot path. Define `logger = get_logger("backend.middleware.cors")` at module scope (or as a class attribute) and reuse it inside `dispatch` instead.

Suggested implementation:

```python
            if not allow_origin:
                # If it's a 404/500, sometimes headers are missing if not handled correctly.
                # But generally CORSMiddleware adds them even for errors.
                logger.warning(f"CORS Warning: Origin '{origin}' requested but no 'Access-Control-Allow-Origin' header in response. Status: {response.status_code}")

```

```python
logger = get_logger("backend.middleware.cors")


class CORSLoggingMiddleware(BaseHTTPMiddleware):

```
</issue_to_address>

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.

if not allow_origin:
# If it's a 404/500, sometimes headers are missing if not handled correctly.
# But generally CORSMiddleware adds them even for errors.
logger = get_logger("backend.middleware.cors")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (performance): Instantiate the logger once at module or class level instead of per-request.

Looking up the logger inside dispatch adds unnecessary overhead in a hot path. Define logger = get_logger("backend.middleware.cors") at module scope (or as a class attribute) and reuse it inside dispatch instead.

Suggested implementation:

            if not allow_origin:
                # If it's a 404/500, sometimes headers are missing if not handled correctly.
                # But generally CORSMiddleware adds them even for errors.
                logger.warning(f"CORS Warning: Origin '{origin}' requested but no 'Access-Control-Allow-Origin' header in response. Status: {response.status_code}")
logger = get_logger("backend.middleware.cors")


class CORSLoggingMiddleware(BaseHTTPMiddleware):

- Modified `tests/test_cors_config.py` to use a `pytest` fixture for environment isolation.
- The fixture now temporarily patches `os.environ` with `ENV=production` and reloads `backend.main`.
- After tests, `backend.main` is reloaded again to restore the original development environment, preventing side effects on `tests/test_integration.py` which failed due to missing `POSTGRES_DSN` in production mode.

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