Skip to content

fix(auth): detect HTTPS behind TLS-terminating reverse proxy#331

Merged
EnjoyBacon7 merged 3 commits intodevfrom
fix/oidc-secure-cookie-behind-proxy-v2
Apr 22, 2026
Merged

fix(auth): detect HTTPS behind TLS-terminating reverse proxy#331
EnjoyBacon7 merged 3 commits intodevfrom
fix/oidc-secure-cookie-behind-proxy-v2

Conversation

@EnjoyBacon7
Copy link
Copy Markdown
Collaborator

@EnjoyBacon7 EnjoyBacon7 commented Apr 21, 2026

Summary

Narrow-scope revival of #313: extracts only the OIDC cookie fix (9 lines) from that PR, leaving the unrelated feature bundle behind.

When OpenRag runs behind a TLS-terminating reverse proxy (Traefik/Nginx), request.url.scheme is http because TLS is terminated by the proxy. As a result, the OIDC state cookie is set without the Secure flag, the browser drops it on the HTTPS callback, and the Authorization Code + PKCE exchange fails with OIDC code exchange failed.

Fix

_is_request_secure() now checks three indicators:

  1. PREFERRED_URL_SCHEME=https env var (explicit config; already used elsewhere in OpenRag)
  2. X-Forwarded-Proto: https header (standard reverse-proxy header)
  3. request.url.scheme (existing fallback)

Relation to #313

Credit to @etiquet — commit is cherry-picked from #313 with authorship preserved. The other ~3,300 lines in #313 (parallel JWT OIDC module, Drive connector, notifications subsystem, 990-line admin router, two non-idempotent migrations, Linagora-internal deployment notes) are out of scope for this fix and should be discussed separately.

Test plan

  • Deploy behind a TLS-terminating proxy; verify OIDC login completes
  • Verify openrag_session cookie has Secure flag when X-Forwarded-Proto: https is set
  • Verify direct HTTP access still works (Secure=false)

Summary by CodeRabbit

  • Bug Fixes
    • Improved detection of secure connections to better support deployment scenarios with proxies and load balancers.

When OpenRAG runs behind Traefik/Nginx that terminates TLS, the
internal request arrives as HTTP. This causes the OIDC state cookie
to be set without the Secure flag, which prevents the browser from
sending it back on the HTTPS callback — breaking the OIDC flow.

Fix: _is_request_secure() now checks:
1. PREFERRED_URL_SCHEME env var (explicit config)
2. X-Forwarded-Proto header (set by reverse proxies)
3. request.url.scheme (existing check)

Without this fix, OIDC login fails with "OIDC code exchange failed"
when deployed behind any TLS-terminating proxy.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 21, 2026

Warning

Rate limit exceeded

@EnjoyBacon7 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 35 minutes and 27 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 35 minutes and 27 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c81245fa-f0f0-4e30-9d1a-985bde3cbd75

📥 Commits

Reviewing files that changed from the base of the PR and between 1f88f7d and 0bf9f6f.

📒 Files selected for processing (1)
  • openrag/routers/auth.py
📝 Walkthrough

Walkthrough

The _is_request_secure() function in the auth router has been enhanced to detect HTTPS from multiple sources: the PREFERRED_URL_SCHEME environment variable and the X-Forwarded-Proto request header, with fallback to the original URL scheme check. The function now imports os locally.

Changes

Cohort / File(s) Summary
Auth Router Security Enhancement
openrag/routers/auth.py
Updated _is_request_secure() to check PREFERRED_URL_SCHEME environment variable and X-Forwarded-Proto header for HTTPS detection, supporting deployments behind proxies or load balancers.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A padlock's check now triple-blessed,
Through env and headers, schemes are dressed,
HTTPS whispers from proxy's nest,
Security hops with confident zest! 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: fixing HTTPS detection when running behind a TLS-terminating reverse proxy, which directly matches the implementation change in _is_request_secure().
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/oidc-secure-cookie-behind-proxy-v2

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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 (1)
openrag/routers/auth.py (1)

1-1: ⚠️ Potential issue | 🟡 Minor

CI lint failure: ruff format --check reports this file needs reformatting.

Run uv run ruff format openrag/routers/auth.py before pushing so the Linting job passes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openrag/routers/auth.py` at line 1, The file openrag.routers.auth.py fails
ruff formatting; run the formatter and commit the changes so CI passes: run the
project command (e.g., uv run ruff format openrag/routers/auth.py) or apply
ruff/black formatting to the module openrag.routers.auth (the module-level
docstring and any functions/classes in that file such as the OIDC route
handlers) and re-run `ruff format --check` to ensure the file is properly
reformatted before pushing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openrag/routers/auth.py`:
- Around line 118-131: Remove the redundant local "import os" and update
_is_request_secure to handle comma-separated X-Forwarded-Proto values by
splitting request.headers.get("x-forwarded-proto", "") on commas, trimming and
lowercasing, and checking the first non-empty token for "https"; retain the
existing check of os.environ.get("PREFERRED_URL_SCHEME") and the fallback check
of request.url.scheme == "https" so the function uses the module-level os and
correctly detects client-facing HTTPS when proxies append values.

---

Outside diff comments:
In `@openrag/routers/auth.py`:
- Line 1: The file openrag.routers.auth.py fails ruff formatting; run the
formatter and commit the changes so CI passes: run the project command (e.g., uv
run ruff format openrag/routers/auth.py) or apply ruff/black formatting to the
module openrag.routers.auth (the module-level docstring and any
functions/classes in that file such as the OIDC route handlers) and re-run `ruff
format --check` to ensure the file is properly reformatted before pushing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 820f5e57-80bf-4661-a7ae-e63200968915

📥 Commits

Reviewing files that changed from the base of the PR and between c2df02c and 1f88f7d.

📒 Files selected for processing (1)
  • openrag/routers/auth.py

Comment thread openrag/routers/auth.py
os is already imported at module scope. When a request traverses multiple
proxies the header can be a comma-separated list like "https, http"; take
the first (client-most) entry before comparing.
@EnjoyBacon7 EnjoyBacon7 merged commit d984de9 into dev Apr 22, 2026
4 checks passed
@EnjoyBacon7 EnjoyBacon7 deleted the fix/oidc-secure-cookie-behind-proxy-v2 branch April 22, 2026 13:00
@paultranvan
Copy link
Copy Markdown
Collaborator

Thank you @etiquet !

etiquet added a commit to IA-Generative/openrag that referenced this pull request Apr 25, 2026
deploy/.env.example.vm — template .env adapté au déploiement
openrag-01-et (51.159.184.192) :
- LLM/Embedder/Reranker pointant sur LiteLLM Mirai (mistral-small-24b
  + bge-multilingual-gemma2)
- Transcriber commenté en attendant le token audio
- OIDC Keycloak Mirai (sso.mirai.interieur.gouv.fr) avec placeholders
  pour les secrets (jamais commités)
- URLs publiques sur api/indexer.openrag-mirai.fake-domain.name
- VLM vide (aucun VLM exposé par le hub)

deploy/Caddyfile.example — reverse proxy TLS Let's Encrypt :
- 3 vhosts api/indexer/chat -> ports internes 8080/3042/8080
- X-Forwarded-Proto pour la détection HTTPS derrière proxy (cohérent
  avec PR linagora#331 upstream)
- transport http keepalive long pour les WebSocket Chainlit
- catch-all *.openrag-mirai.fake-domain.name -> 404 (le wildcard DNS
  résout tout vers la VM, le proxy sert de garde-fou)
- logs JSON structurés pour ingestion ultérieure

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.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.

4 participants