Files
karaoke-gen/backend/tests/test_edge_auth_middleware.py
T
Andrew Beveridge ☄️andClaude Opus 4.8 fb2bd6b108 Cloudflare edge security (WAF + rate limit + origin lock) for karaoke-backend (#886)
## Summary
Puts `api.nomadkaraoke.com` behind the Cloudflare edge that already
fronts the rest of the domain, after a vuln-scanner hammered the
directly-exposed Cloud Run origin on 2026-07-20 (`/.env`,
`/.ssh/id_rsa`, `wp-config.php`… — all 404'd, but the burst of 404s
tripped the "High Error Rate" alert). The API was the one
internet-facing surface with **no WAF, no rate limiting** — DNS-only
CNAME straight to `ghs.googlehosted.com`, Cloud Run ingress `all`.

**Zero-downtime by construction:** everything is gated behind
`edge:enabled` (default off) and staged via two independent switches
(`edge:rolloutStage` for rule scope, `edge:proxyProdApi` for the DNS
flip). The whole Cloud-Run×Cloudflare interaction is validated on a
throwaway staging host first; the only prod-affecting action is a
single, instantly-reversible DNS proxy flip. Full sequence in
`docs/archive/2026-07-20-edge-security-cutover-runbook.md`.

## Changes
- **`infrastructure/modules/edge_security.py`** (new) —
`pulumi_cloudflare` WAF (exploit-path block), per-IP rate limiting
(excludes `/api/internal/*`), origin-lock header transform, zone
security; staging + prod DNS records. Managed OWASP ruleset gated off
(zone is Free plan).
- **`backend/middleware/edge_auth.py`** (new) — off/warn/enforce origin
lock via a secret header Cloudflare injects; **fails closed (503) in
enforce** when the secret is missing; health/root exempt. +13 unit
tests.
- **`monitoring.py`** — retune the high-error-rate alert to **5xx-only**
(+ fix the rate-vs-ratio naming) so client/bot 404 bursts no longer
page.
- Wiring: `secrets.py` (edge-origin-secret container), `config.py`,
`__main__.py`, pinned `pulumi-cloudflare==6.18.0`, `ci.yml`
(`EDGE_AUTH_MODE=off` + secret ref), `Pulumi.prod.yaml` (encrypted
`edge:originSecret`).
- Docs: hardening plan + cutover runbook in `docs/archive/`.

## Already applied to prod (targeted `pulumi up`)
- ✅ `edge-origin-secret` Secret Manager container + v1 value
- ✅ 5xx error-rate alert retune (fixes the original paging issue
immediately)
- Everything else stays dormant: `edge:enabled=false`, backend
`EDGE_AUTH_MODE=off`.

## Testing
- [x] `make test` — full backend + frontend suite green (1085 frontend
tests; backend incl. 13 new edge-auth tests)
- [x] Cloudflare token verified against live API (DNS create+delete,
rulesets, zone settings)
- [x] `pulumi preview` clean (targeted apply of only the 2 additive
resources)
- [ ] Staging validation + prod cutover — follow the runbook (separate,
gated)

## Review
- [x] CodeRabbit CLI review completed locally; findings addressed
(fail-closed enforce, decoupled cutover, fixed origin-lock test,
threshold wording). One pre-existing PR_TITLE shell-interp finding in
the deploy step left out of scope.

## Notes for reviewer
- Nothing here touches prod behavior until someone sets `edge:enabled
true` and walks the runbook. The prod `api` DNS record must be `pulumi
import`ed (already exists) — documented in runbook step 4a.
- Pre-existing cross-worktree Cloud Function source drift is visible in
a full `pulumi preview`; not introduced here (applied via `--target` to
avoid it).

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 19:12:28 -04:00

140 lines
5.1 KiB
Python

"""
Unit tests for EdgeAuthMiddleware (Cloudflare origin lock).
Exercises the off/warn/enforce modes, header validation, exemptions, and the
fail-open-on-misconfiguration behaviour end-to-end via a minimal ASGI app.
"""
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
from backend.middleware.edge_auth import EdgeAuthMiddleware, EDGE_AUTH_HEADER
SECRET = "s3cr3t-origin-value"
@pytest.fixture
def client():
"""Minimal app with the middleware installed and a few routes."""
app = FastAPI()
app.add_middleware(EdgeAuthMiddleware)
@app.get("/")
async def root():
return {"ok": "root"}
@app.get("/api/health")
async def health():
return {"ok": "health"}
@app.get("/api/test")
async def protected():
return {"ok": "protected"}
@app.post("/api/internal/recover-stuck-jobs")
async def internal():
return {"ok": "internal"}
return TestClient(app)
def _set(monkeypatch, mode=None, secret=None):
for key, val in (("EDGE_AUTH_MODE", mode), ("EDGE_ORIGIN_SECRET", secret)):
if val is None:
monkeypatch.delenv(key, raising=False)
else:
monkeypatch.setenv(key, val)
# --------------------------------------------------------------------------- #
# off mode (default) — pure passthrough
# --------------------------------------------------------------------------- #
def test_off_mode_is_default_passthrough(client, monkeypatch):
_set(monkeypatch, mode=None, secret=SECRET) # unset mode -> defaults to off
assert client.get("/api/test").status_code == 200
def test_invalid_mode_treated_as_off(client, monkeypatch):
_set(monkeypatch, mode="bogus", secret=SECRET)
assert client.get("/api/test").status_code == 200
# --------------------------------------------------------------------------- #
# enforce mode
# --------------------------------------------------------------------------- #
def test_enforce_blocks_missing_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test")
assert resp.status_code == 403
assert resp.json()["detail"] == "Forbidden"
def test_enforce_blocks_wrong_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: "nope"})
assert resp.status_code == 403
def test_enforce_allows_valid_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET})
assert resp.status_code == 200
assert resp.json()["ok"] == "protected"
def test_enforce_internal_path_requires_header(client, monkeypatch):
"""Internal endpoints traverse Cloudflare (public host) so they DO get the
header — they are not exempt from the origin lock."""
_set(monkeypatch, mode="enforce", secret=SECRET)
assert client.post("/api/internal/recover-stuck-jobs").status_code == 403
ok = client.post(
"/api/internal/recover-stuck-jobs", headers={EDGE_AUTH_HEADER: SECRET}
)
assert ok.status_code == 200
# --------------------------------------------------------------------------- #
# exemptions — health/root probes hit the origin directly, no header
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("path", ["/", "/api/health"])
def test_enforce_exempts_health_and_root(client, monkeypatch, path):
_set(monkeypatch, mode="enforce", secret=SECRET)
assert client.get(path).status_code == 200
# --------------------------------------------------------------------------- #
# warn mode — logs but allows
# --------------------------------------------------------------------------- #
def test_warn_allows_missing_header(client, monkeypatch):
_set(monkeypatch, mode="warn", secret=SECRET)
assert client.get("/api/test").status_code == 200
def test_warn_allows_valid_header(client, monkeypatch):
_set(monkeypatch, mode="warn", secret=SECRET)
assert client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET}).status_code == 200
# --------------------------------------------------------------------------- #
# misconfiguration — enforce but no secret set
# --------------------------------------------------------------------------- #
def test_enforce_without_secret_fails_closed(client, monkeypatch):
# A security control must fail closed: enforce with no secret → 503, not open.
_set(monkeypatch, mode="enforce", secret=None)
resp = client.get("/api/test")
assert resp.status_code == 503
assert resp.json()["detail"] == "Origin authentication unavailable"
def test_enforce_without_secret_still_exempts_health(client, monkeypatch):
# Health/root stay reachable even in the misconfigured state (probes).
_set(monkeypatch, mode="enforce", secret=None)
assert client.get("/api/health").status_code == 200
def test_warn_without_secret_allows(client, monkeypatch):
# warn mode is observational only — never blocks, even with no secret.
_set(monkeypatch, mode="warn", secret=None)
assert client.get("/api/test").status_code == 200