Skip to content

Relax CORS regex and add logging middleware#27

Open
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-origin-regex-17524954021399206428
Open

Relax CORS regex and add logging middleware#27
KnellBalm wants to merge 2 commits intomainfrom
fix-cors-origin-regex-17524954021399206428

Conversation

@KnellBalm
Copy link
Copy Markdown
Owner

@KnellBalm KnellBalm commented Feb 2, 2026

Updated the CORS regex in backend/main.py to allow optional trailing slashes for Cloud Run domains, which was likely causing CORS failures for the frontend. Added a new CORSLoggingMiddleware to log Origin and Access-Control-Allow-Origin headers to assist with future debugging. Updated tests/test_cors_config.py to include a test case for trailing slashes.


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

Summary by Sourcery

Relax CORS origin matching and add middleware to improve CORS debugging.

New Features:

  • Introduce CORSLoggingMiddleware to capture CORS-related request and response headers for debugging.

Enhancements:

  • Adjust Cloud Run CORS origin regex to permit optional trailing slashes in allowed origins.

Tests:

  • Extend CORS configuration tests to cover origins with trailing slashes for Cloud Run domains.

…logging

- Updated Cloud Run domain regex to support optional trailing slash (fixes CORS error for some clients).
- Added `CORSLoggingMiddleware` to log CORS headers for easier debugging.
- Updated tests to verify fix.

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

Reviewer's Guide

Adjusts CORS handling to accept Cloud Run origins with optional trailing slashes and introduces a CORS-focused logging middleware, along with a targeted test to verify the updated behavior.

Sequence diagram for CORS logging and handling middleware

sequenceDiagram
    actor Browser
    participant App
    participant CORSLoggingMiddleware
    participant CORSMiddleware
    participant Endpoint

    Browser->>App: HTTP request with Origin header
    App->>CORSLoggingMiddleware: pass request
    CORSLoggingMiddleware->>CORSLoggingMiddleware: read origin from request.headers
    CORSLoggingMiddleware->>CORSLoggingMiddleware: log CORS Request with origin
    CORSLoggingMiddleware->>CORSMiddleware: call_next(request)
    CORSMiddleware->>Endpoint: forward request
    Endpoint-->>CORSMiddleware: response
    CORSMiddleware-->>CORSLoggingMiddleware: response with access-control-allow-origin
    CORSLoggingMiddleware->>CORSLoggingMiddleware: read access-control-allow-origin from response.headers
    alt missing access-control-allow-origin
        CORSLoggingMiddleware->>CORSLoggingMiddleware: log CORS Failed warning
    end
    CORSLoggingMiddleware-->>App: response
    App-->>Browser: HTTP response
Loading

Class diagram for new CORSLoggingMiddleware

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

    class CORSLoggingMiddleware {
        +dispatch(request, call_next) async
    }

    BaseHTTPMiddleware <|-- CORSLoggingMiddleware
Loading

File-Level Changes

Change Details Files
Add CORSLoggingMiddleware to capture and log CORS-related request and response headers for debugging.
  • Introduce CORSLoggingMiddleware subclassing BaseHTTPMiddleware that logs request Origin and URL on CORS requests
  • Log a warning when a CORS request origin is present but the Access-Control-Allow-Origin header is missing on the response
  • Use a dedicated logger namespace for CORS middleware logs
backend/common/middleware.py
Relax CORS origin regex to allow Cloud Run origins with optional trailing slash and register new logging middleware in the app.
  • Update cloud_origin_regex to allow an optional trailing slash on query-craft-frontend*.run.app domains
  • Register CORSLoggingMiddleware on the FastAPI app after configuring CORSMiddleware so it executes early in the middleware chain
backend/main.py
Extend CORS tests to cover origins with trailing slashes.
  • Add a test ensuring an origin with a trailing slash receives matching Access-Control-Allow-Origin and allows credentials for preflight requests
tests/test_cors_config.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:

  • In CORSLoggingMiddleware, you recreate the logger twice; consider instantiating it once at the top of the middleware (or module) to avoid repeated get_logger calls on every request.
  • The new test uses an Origin with a trailing slash, but browsers typically omit the trailing slash in the Origin header; consider normalizing or explicitly handling both forms in the application logic so tests reflect real-world requests.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `CORSLoggingMiddleware`, you recreate the logger twice; consider instantiating it once at the top of the middleware (or module) to avoid repeated `get_logger` calls on every request.
- The new test uses an Origin with a trailing slash, but browsers typically omit the trailing slash in the `Origin` header; consider normalizing or explicitly handling both forms in the application logic so tests reflect real-world requests.

## Individual Comments

### Comment 1
<location> `backend/common/middleware.py:38-47` </location>
<code_context>
                 content={"detail": "Internal Server Error"}
             )
+
+class CORSLoggingMiddleware(BaseHTTPMiddleware):
+    """
+    Middleware to log CORS related headers for debugging.
+    """
+    async def dispatch(self, request: Request, call_next):
+        origin = request.headers.get("origin")
+        if origin:
+            logger = get_logger("backend.middleware.cors")
+            logger.info(f"CORS Request: {request.method} {request.url} - Origin: {origin}")
+
+        response = await call_next(request)
+
+        if origin:
+            acao = response.headers.get("access-control-allow-origin")
+            if not acao:
+                logger = get_logger("backend.middleware.cors")
+                logger.warning(f"CORS Failed? Origin: {origin} - No Access-Control-Allow-Origin in response")
+
+        return response
</code_context>

<issue_to_address>
**suggestion:** Avoid calling `get_logger` multiple times per request and promote a shared logger instance.

`get_logger("backend.middleware.cors")` is called in both branches of `dispatch`, causing repeated lookups per request. Since the name is static, define a module-level logger (e.g. `CORS_LOGGER = get_logger("backend.middleware.cors")`) and reuse it, which reduces overhead and keeps `dispatch` simpler.

Suggested implementation:

```python
            )

CORS_LOGGER = get_logger("backend.middleware.cors")


class CORSLoggingMiddleware(BaseHTTPMiddleware):

```

```python
        origin = request.headers.get("origin")
        if origin:
            CORS_LOGGER.info(f"CORS Request: {request.method} {request.url} - Origin: {origin}")

```

```python
        if origin:
            acao = response.headers.get("access-control-allow-origin")
            if not acao:
                CORS_LOGGER.warning(
                    f"CORS Failed? Origin: {origin} - No Access-Control-Allow-Origin in response"
                )

```
</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.

Comment on lines +38 to +47
class CORSLoggingMiddleware(BaseHTTPMiddleware):
"""
Middleware to log CORS related headers for debugging.
"""
async def dispatch(self, request: Request, call_next):
origin = request.headers.get("origin")
if origin:
logger = get_logger("backend.middleware.cors")
logger.info(f"CORS Request: {request.method} {request.url} - Origin: {origin}")

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: Avoid calling get_logger multiple times per request and promote a shared logger instance.

get_logger("backend.middleware.cors") is called in both branches of dispatch, causing repeated lookups per request. Since the name is static, define a module-level logger (e.g. CORS_LOGGER = get_logger("backend.middleware.cors")) and reuse it, which reduces overhead and keeps dispatch simpler.

Suggested implementation:

            )

CORS_LOGGER = get_logger("backend.middleware.cors")


class CORSLoggingMiddleware(BaseHTTPMiddleware):
        origin = request.headers.get("origin")
        if origin:
            CORS_LOGGER.info(f"CORS Request: {request.method} {request.url} - Origin: {origin}")
        if origin:
            acao = response.headers.get("access-control-allow-origin")
            if not acao:
                CORS_LOGGER.warning(
                    f"CORS Failed? Origin: {origin} - No Access-Control-Allow-Origin in response"
                )

- Updated Cloud Run domain regex to support optional trailing slash (fixes CORS error for some clients).
- Added `CORSLoggingMiddleware` to log CORS headers for easier debugging.
- Fixed `tests/test_integration.py` to temporarily force `ENV=development` to prevent failures caused by global `ENV` modifications in other tests.
- Updated tests to verify fix.

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