Allow Capacitor WebView origins in CORS/CSRF (#22) (#19)
Unit Tests / test (push) Successful in 9s

## Summary
- Supports [chat_web_app#22](ai_ml_operations/chat_web_app#22)
- Always merge Capacitor WebView origins (`https://localhost`, `capacitor://localhost`, `http://localhost`) into `CORS_ALLOWED_ORIGINS` and `CSRF_TRUSTED_ORIGINS`
- Keep `CORS_ALLOW_CREDENTIALS = False` (JWT header-only; no cookie credentials)

## Test plan
- [x] `uv run python manage.py test chat_backend.tests.test_settings_cors`
- [ ] OPTIONS preflight from `https://localhost` / `capacitor://localhost` against prod/beta with `CORS_ORIGIN_ALLOW_ALL=false`
- [ ] Authenticated JWT GET/POST from Capacitor shell after FE #22 landsReviewed-on: #19
This commit was merged in pull request #19.
This commit is contained in:
2026-07-26 14:04:09 -07:00
parent a049e4f685
commit 92aa277a37
3 changed files with 94 additions and 7 deletions
@@ -0,0 +1,61 @@
from django.test import SimpleTestCase
from llm_be.settings import (
CAPACITOR_WEBVIEW_ORIGINS,
build_csrf_trusted_origins,
with_capacitor_webview_origins,
)
class BuildCsrfTrustedOriginsTests(SimpleTestCase):
def test_derives_https_for_public_hosts(self):
origins = build_csrf_trusted_origins(
["chat.aimloperations.com", "chatbackend.aimloperations.com"]
)
self.assertEqual(
origins,
[
"https://chat.aimloperations.com",
"https://chatbackend.aimloperations.com",
],
)
def test_derives_http_for_localhost(self):
origins = build_csrf_trusted_origins(["localhost:8003", "127.0.0.1"])
self.assertEqual(
origins,
["http://localhost:8003", "http://127.0.0.1"],
)
def test_explicit_list_wins(self):
origins = build_csrf_trusted_origins(
["ignored.example"],
["https://chat.aimloperations.com"],
)
self.assertEqual(origins, ["https://chat.aimloperations.com"])
class CapacitorWebviewOriginTests(SimpleTestCase):
def test_appends_capacitor_origins(self):
merged = with_capacitor_webview_origins(["https://chat.aimloperations.com"])
self.assertEqual(merged[0], "https://chat.aimloperations.com")
for origin in CAPACITOR_WEBVIEW_ORIGINS:
self.assertIn(origin, merged)
def test_does_not_duplicate_existing(self):
seed = ["https://localhost", "https://chat.aimloperations.com"]
merged = with_capacitor_webview_origins(seed)
self.assertEqual(merged.count("https://localhost"), 1)
self.assertIn("capacitor://localhost", merged)
def test_settings_include_capacitor_origins(self):
from django.conf import settings
for origin in CAPACITOR_WEBVIEW_ORIGINS:
self.assertIn(origin, settings.CORS_ALLOWED_ORIGINS)
self.assertIn(origin, settings.CSRF_TRUSTED_ORIGINS)
def test_cors_credentials_disabled_for_jwt_only(self):
from django.conf import settings
self.assertFalse(settings.CORS_ALLOW_CREDENTIALS)