Skip to content

Conversation

@gkorland
Copy link
Contributor

@gkorland gkorland commented Aug 31, 2025

Users are getting this error when trying to login with Google

{"detail":"Authentication failed: mismatching_state: CSRF Warning! State not equal in request and response."} 

on staging.queryweaver.ai

Summary by CodeRabbit

  • New Features
    • Environment-aware session cookie security via APP_ENV (development, staging, production) for OAuth-related flows.
  • Documentation
    • Updated setup guidance to include APP_ENV usage for selecting cookie security modes.
    • Added environment-specific OAuth settings and troubleshooting notes.
    • Updated Docker run example with APP_ENV for production deployments.
    • Clarified local development instructions using APP_ENV=development.
    • Expanded testing docs to list APP_ENV as a key variable.
  • Chores
    • Enhanced sample .env with optional APP_ENV and email configuration examples (commented by default).

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

Walkthrough

Introduces APP_ENV-based session cookie HTTPS toggle in the application factory. Updates documentation and example configuration to describe and demonstrate APP_ENV usage, OAuth development settings, and sample email configuration. Adds APP_ENV to E2E testing env notes. No exported/public APIs changed.

Changes

Cohort / File(s) Summary of Changes
Session cookie HTTPS toggle
api/app_factory.py
SessionMiddleware now sets https_only based on APP_ENV (production/staging → True; otherwise False), replacing hard-coded False.
Docs and example configuration updates
.env.example, README.md, .github/copilot-instructions.md, tests/e2e/README.md
Added APP_ENV guidance/examples (development/staging/production), OAuth notes (including optional OAUTHLIB_INSECURE_TRANSPORT for dev), and new commented Email config block. E2E docs list APP_ENV=development. No runtime changes from these files.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Proc as Process Startup
  participant Env as Environment
  participant App as App Factory
  participant MW as SessionMiddleware
  participant Client as Client

  Proc->>Env: Read APP_ENV
  Env-->>App: "production" / "staging" / "development"
  App->>App: Compute is_https = APP_ENV in {production, staging}
  App->>MW: Initialize with https_only = is_https
  note right of MW: https_only=True enforces HTTPS cookies

  rect rgba(230,245,255,0.5)
    Client->>MW: HTTP(S) Request
    MW-->>Client: Set/Send session cookie (HTTPS-only if enabled)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

Poem

I nudge the knobs of ENV with care,
APP_ENV whispers, “secure the air.”
Cookies don cloaks when prod winds blow,
In dev, they lounge where plain streams flow.
A hop, a thunk, OAuth in tune—
Email drafts brew, changes soon.
Thump-thump! Ship by noon.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch APP_ENV

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gkorland
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@gkorland gkorland merged commit bd455cc into staging Aug 31, 2025
5 of 6 checks passed
@gkorland gkorland deleted the APP_ENV branch August 31, 2025 08:50
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
api/app_factory.py (2)

27-31: Silence Pylint R0903 on middleware class.

This class intentionally has a single public method.

-class SecurityMiddleware(BaseHTTPMiddleware):
+class SecurityMiddleware(BaseHTTPMiddleware):  # pylint: disable=too-few-public-methods

115-119: Fix Pylint W0613 and remove FIXMEs.

Rename the unused request parameter and downgrade the TODO to a note to pass lint.

-    async def handle_oauth_error(request: Request, exc: Exception):
+    async def handle_oauth_error(_request: Request, exc: Exception):
         """Handle OAuth-related errors gracefully"""
         # Check if it's an OAuth-related error
-        # TODO check this scenario
+        # Note: consider refining this condition to specific OAuth exceptions
🧹 Nitpick comments (9)
tests/e2e/README.md (1)

118-134: Add a dev-only hint for local OAuth runs.

Include OAUTHLIB_INSECURE_TRANSPORT to reduce confusion when folks try OAuth locally.

 # Required for FastAPI
 FASTAPI_SECRET_KEY=your-secret-key
 APP_ENV=development
 FASTAPI_DEBUG=False
+
+# For local OAuth testing only (NEVER set in staging/production)
+# OAUTHLIB_INSECURE_TRANSPORT=1
api/app_factory.py (2)

58-59: Avoid trusting all proxy headers in production.

Reading trusted proxies from an env var is safer than "*".

-    app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
+    app.add_middleware(
+        ProxyHeadersMiddleware,
+        trusted_hosts=os.getenv("TRUSTED_PROXY_HOSTS", "*")
+    )

Consider documenting TRUSTED_PROXY_HOSTS in .env.example as a comma-separated list (e.g., "127.0.0.1,::1,nginx").


114-129: Narrow the OAuth error catch or add metrics.

Catching Exception may hide unrelated errors containing the words “oauth” or “token”. Consider catching specific exceptions from authlib or emit a metric/structured log to aid debugging.

.github/copilot-instructions.md (1)

140-160: Document dev-only OAuth flag alongside APP_ENV.

Small doc tweak to help contributors succeed locally.

 # Optional: set application environment (development, staging, production)
 # Default: development (affects session cookie security for OAuth)
 APP_ENV=development
+
+# For local OAuth over HTTP only (never in staging/production)
+# OAUTHLIB_INSECURE_TRANSPORT=1
.env.example (2)

23-29: Add proxy hardening knob.

Expose TRUSTED_PROXY_HOSTS to avoid trusting all X-Forwarded-* headers in prod.

 # Default: development
 # APP_ENV=development
+
+# Optional: restrict which reverse proxies' headers are trusted (comma-separated)
+# TRUSTED_PROXY_HOSTS=127.0.0.1,::1,nginx

23-29: Consider documenting cookie domain override.

If you ever need to share cookies across subdomains, a domain override is useful.

 # APP_ENV=development
+
+# Optional: session cookie domain override (e.g., .queryweaver.ai)
+# SESSION_COOKIE_DOMAIN=.queryweaver.ai
README.md (3)

42-51: Good call adding APP_ENV to docker run. Also mention proxy header.

Add a short note reminding operators to set X-Forwarded-Proto at the proxy when terminating TLS.

   -e AZURE_API_KEY=your_azure_api_key \
   falkordb/queryweaver
+
+# Note: If running behind a reverse proxy with TLS termination,
+# ensure it sets X-Forwarded-Proto=https so the app sees HTTPS.

294-307: Tighten the prod OAuth guidance.

Add a reminder to update IdP redirect URIs to https:///... when switching to production/staging.

 **Important**: If you're getting "mismatching_state: CSRF Warning!" errors on staging/production, ensure `APP_ENV` is set to `production` or `staging` to enable secure session handling.
+Also confirm your OAuth app redirect URIs use your HTTPS host
+(e.g., https://staging.queryweaver.ai/login/google/authorized).

363-363: Add a quick cookie-debug tip.

One-liner to help diagnose lost session cookies.

 - **OAuth "mismatching_state: CSRF Warning!" errors**: Set `APP_ENV=production` (or `staging`) in your environment for HTTPS deployments, or `APP_ENV=development` for HTTP development environments. This ensures session cookies are configured correctly for your deployment type.
+ - **OAuth "mismatching_state: CSRF Warning!" errors**: Set `APP_ENV=production` (or `staging`) in your environment for HTTPS deployments, or `APP_ENV=development` for HTTP development environments. This ensures session cookies are configured correctly for your deployment type. In the browser devtools, verify the `qw_session` cookie has `Secure` on HTTPS and is present on the callback response.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d0097a0 and 70815c3.

📒 Files selected for processing (5)
  • .env.example (2 hunks)
  • .github/copilot-instructions.md (2 hunks)
  • README.md (4 hunks)
  • api/app_factory.py (1 hunks)
  • tests/e2e/README.md (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-24T17:15:21.337Z
Learnt from: CR
PR: FalkorDB/QueryWeaver#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-24T17:15:21.337Z
Learning: Applies to .env.example : Ensure `.env.example` includes all required environment variables (FastAPI secret/debug, FalkorDB host/port, OAuth client IDs/secrets) with placeholder values

Applied to files:

  • tests/e2e/README.md
  • .github/copilot-instructions.md
  • README.md
  • .env.example
📚 Learning: 2025-08-24T17:15:21.337Z
Learnt from: CR
PR: FalkorDB/QueryWeaver#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-24T17:15:21.337Z
Learning: Applies to Dockerfile : Keep Docker configuration consistent with documented run commands (exposing port 5000, running uvicorn with `api.index:app`)

Applied to files:

  • README.md
🪛 GitHub Actions: Pylint
api/app_factory.py

[error] 118-118: W0511: TODO check this scenario (fixme)


[error] 27-27: R0903: Too few public methods (1/2) (too-few-public-methods)


[error] 63-63: R1703: The if statement can be replaced with 'var = bool(test)' (simplifiable-if-statement)


[error] 115-115: W0613: Unused argument 'request' (unused-argument)

🔇 Additional comments (4)
api/app_factory.py (1)

72-74: Confirm SameSite policy won’t break OAuth in your deployment.

SameSite="lax" typically works for top-level OAuth GET redirects; if your IdP flow involves cross-site POSTs or if you embed flows, you may need SameSite=None (with https_only=True).

.github/copilot-instructions.md (1)

162-169: LGTM: minimal .env example now includes APP_ENV.

.env.example (1)

78-88: Confirm or remove unused email config variables. I couldn’t find any references to MAIL_SERVER, MAIL_PORT, MAIL_USE_TLS, MAIL_USERNAME, MAIL_PASSWORD, MAIL_DEFAULT_SENDER, or EMAIL_AUTH_ENABLED in the codebase; please implement their consumption or remove them from .env.example.

README.md (1)

255-256: LGTM: clear guidance to set APP_ENV=development locally.

Comment on lines +62 to +67
app_env = os.getenv("APP_ENV", "").lower()
if app_env in ("production", "staging"):
is_https = True
else:
is_https = False

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify boolean and add startup log; fixes Pylint R1703.

Also adds a helpful log for debugging env-related cookie issues.

-    app_env = os.getenv("APP_ENV", "").lower()
-    if app_env in ("production", "staging"):
-        is_https = True
-    else:
-        is_https = False
+    app_env = os.getenv("APP_ENV", "").lower()
+    is_https = app_env in ("production", "staging")
+    logging.info("Session cookie Secure=%s (APP_ENV=%s)", is_https, app_env or "(unset)")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app_env = os.getenv("APP_ENV", "").lower()
if app_env in ("production", "staging"):
is_https = True
else:
is_https = False
app_env = os.getenv("APP_ENV", "").lower()
is_https = app_env in ("production", "staging")
logging.info("Session cookie Secure=%s (APP_ENV=%s)", is_https, app_env or "(unset)")
🧰 Tools
🪛 GitHub Actions: Pylint

[error] 63-63: R1703: The if statement can be replaced with 'var = bool(test)' (simplifiable-if-statement)

🤖 Prompt for AI Agents
In api/app_factory.py around lines 62 to 67, replace the verbose if/else boolean
assignment with a direct boolean expression (is_https = app_env in
("production", "staging")) to address Pylint R1703, and add a startup log
statement that records the resolved APP_ENV and resulting is_https value to help
debug environment/cookie issues (use the module or app logger at startup so this
runs once during app creation).

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.

2 participants