+ Sign in to the workbench +
++ The evaluation write-up is{' '} + + open to everyone + + . The workbench indexes repositories and calls metered models, so it is not. +
+ + +From ebfb8d02b1877ddf4313c963bb9fde7ff114acbc Mon Sep 17 00:00:00 2001
From: odieyang <520yangziqi@gmail.com>
Date: Sun, 2 Aug 2026 20:30:47 -0700
Subject: [PATCH 1/2] feat(deploy): gate the workbench behind a shared-account
session
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Deploy.md D-2 and D-6: the landing page and the evaluation write-up stay
public, the product does not. One shared account, so no user table and no
migration.
No new dependency. passlib, pyjwt and itsdangerous are all absent from this
workspace and pulling one in to authenticate a single demo account would be
the larger change, so this is stdlib: PBKDF2-HMAC-SHA256 at OWASP's 600k
floor, and an HMAC-signed session cookie that is HttpOnly, Secure and
SameSite=Lax.
The gate is off by default, so local development, every current compose
invocation and the existing tests are unaffected. docker-compose.prod.yml
HARDCODES it on rather than defaulting it — a production gate that can be
switched off by omitting a variable is not a gate — and the API refuses to
start when it is on but unconfigured, because an auth gate that fails open
looks exactly like one that works.
Also closes F-05: /docs, /redoc and /openapi.json enumerate the /internal/*
surface and are now off in production.
A per-session daily query cap sits on /query alone. The login wall removes
anonymous callers; it does nothing about a signed-in one looping a question
through three metered APIs. It is counted before the agent is reached and
it fails open on a Redis error, because a spend guard that takes the
service down when a cache blips has traded a bounded bill for an outage.
Two findings from verifying this, both fixed here and written up in
Deploy.md.
The first is a real trap. Docker Compose interpolates `$VAR` inside
env-file values, so the conventional `pbkdf2_sha256$600000$salt$hash`
reached the container as 22 characters with three of four segments eaten.
Nothing errored: the API booted, the health check passed, and every login
failed forever, indistinguishable from a wrong password. The format now
joins on "." so the character never appears, and the hash is parsed at
startup rather than checked for non-emptiness, so any corruption stops the
boot. This applies to every hand-picked secret containing `$`, not just
this one.
The second is that the test suite reads the developer's .env, so `make
check` is not hermetic. Switching the gate on locally failed four unrelated
tests and the failures pointed nowhere near the cause. A root conftest.py
pins the settings whose defaults tests assert.
Verified live on a gated container: protected routes 401, /healthz and the
session endpoints 200, /openapi.json 404, wrong password 401 with no
cookie, correct password sets the hardened cookie and opens the gate,
switching it back off restores everything. Not verified: the /workbench to
/login redirect in a real browser — it has four unit tests, but headless
screenshots do not work here and that is not a reason to claim otherwise.
Deploy.md says who needs to look at what.
---
.env.production.example | 34 ++
Deploy.md | 71 +++-
apps/api/src/dcode_api/auth.py | 245 +++++++++++
apps/api/src/dcode_api/hash_password.py | 37 ++
apps/api/src/dcode_api/main.py | 77 +++-
apps/api/src/dcode_api/routes/auth.py | 106 +++++
apps/api/src/dcode_api/routes/query.py | 44 +-
apps/api/src/dcode_api/settings.py | 22 +
apps/api/tests/test_auth.py | 382 ++++++++++++++++++
apps/frontend/src/App.tsx | 18 +-
apps/frontend/src/api/client.ts | 62 +++
apps/frontend/src/api/types.ts | 18 +
.../src/components/RequireSession.tsx | 58 +++
apps/frontend/src/pages/LoginPage.tsx | 101 +++++
apps/frontend/tests/App.test.tsx | 30 +-
apps/frontend/tests/LoginPage.test.tsx | 78 ++++
apps/frontend/tests/RequireSession.test.tsx | 96 +++++
conftest.py | 28 ++
docker-compose.prod.yml | 13 +
docker-compose.yml | 11 +
.../shared/tests/test_config_hardening.py | 45 +++
21 files changed, 1538 insertions(+), 38 deletions(-)
create mode 100644 apps/api/src/dcode_api/auth.py
create mode 100644 apps/api/src/dcode_api/hash_password.py
create mode 100644 apps/api/src/dcode_api/routes/auth.py
create mode 100644 apps/api/tests/test_auth.py
create mode 100644 apps/frontend/src/components/RequireSession.tsx
create mode 100644 apps/frontend/src/pages/LoginPage.tsx
create mode 100644 apps/frontend/tests/LoginPage.test.tsx
create mode 100644 apps/frontend/tests/RequireSession.test.tsx
create mode 100644 conftest.py
diff --git a/.env.production.example b/.env.production.example
index f9760a8..b93ae99 100644
--- a/.env.production.example
+++ b/.env.production.example
@@ -35,6 +35,40 @@ REDIS_URL=redis://redis:6379/0
RABBITMQ_URL=amqp://__SET_PROD_RABBITMQ_USER__:__SET_PROD_RABBITMQ_PASSWORD__@rabbitmq:5672/
AGENT_URL=http://agent:8001
+# ============================================================
+# The shared-account gate (Deploy.md D-2 / D-6)
+#
+# docker-compose.prod.yml hardcodes AUTH_ENABLED=true, so production is gated
+# whether or not this file says so, and the API refuses to start if the two
+# required values below are missing. Both are secrets: they belong here, in a
+# gitignored file, and never in a committed one.
+#
+# Generate the hash (prompts without echoing, never takes an argument, so the
+# password stays out of shell history and the process list):
+#
+# python -m dcode_api.hash_password
+#
+# One shared account. There is no user table and no per-person revocation —
+# to remove someone's access, rotate the password. That is the cost of D-6 and
+# it is recorded there rather than discovered here.
+# ============================================================
+AUTH_USERNAME=reviewer
+AUTH_PASSWORD_HASH=__SET_PROD_AUTH_PASSWORD_HASH__
+AUTH_SESSION_SECRET=
+
+# 12 hours. A reviewer session outliving a sitting is the intent.
+# AUTH_SESSION_TTL_SECONDS=43200
+
+# Leave true on Railway and anywhere else serving HTTPS. Set false ONLY for a
+# plain-HTTP staging host: browsers silently drop a Secure cookie over http,
+# so logins there appear to succeed and never stick.
+# AUTH_COOKIE_SECURE=true
+
+# The gate stops anonymous callers; it does nothing about a signed-in one
+# looping a question through three metered APIs. Counted per session per UTC
+# day, checked before the agent is reached.
+# AUTH_DAILY_QUERY_LIMIT=200
+
# --- Internal service auth ---
# Protects every /internal/* retrieval and graph route. The code default is a
# placeholder published in this repository, so this must be set to a real
diff --git a/Deploy.md b/Deploy.md
index d8669e3..163706e 100644
--- a/Deploy.md
+++ b/Deploy.md
@@ -25,7 +25,7 @@ Outstanding Work list in the same PR, not tracked in two places.
is written from an approved plan, and plans outrun implementations. Verify before
relying on a claim here, and correct it when it is wrong.
-**Status: PR 1 and PR 2 landed. PR 3–5 not started.** The pre-deployment state
+**Status: PR 1, PR 2 and PR 3 landed. PR 4–5 not started.** The pre-deployment state
is frozen at tag `v1.0-submission` (`a4612b8`). Nothing is deployed anywhere
yet. Both hosted model APIs have been exercised end to end from a running local
stack — see § 2.1 and § 6 PR 2 for the observed values — but **no index has been
@@ -403,7 +403,7 @@ The capability behind D-1.
83 files, 310 passed / 5 skipped, 73 frontend tests. All four modes in § 5.1
still resolve, and `sidecar` remains the default everywhere.
-### PR 3 — `feat/auth-gate`
+### PR 3 — `feat/auth-gate` — **done**
D-2. Also closes F-01 and F-03.
@@ -420,11 +420,34 @@ D-2. Also closes F-01 and F-03.
- A per-session daily query cap. The login wall removes anonymous abuse; it does
not remove a logged-in user looping a query against a metered API.
-**Acceptance.** An unauthenticated request to each protected route returns 401.
-`/`, `/methodology` and `/healthz` are reachable without a session. The
-`/workbench` redirect is verified **by a human in a browser** — headless
-screenshots do not work in this environment, and that limitation is not a reason
-to claim the check passed.
+**Acceptance — met, except the one item that needs eyes.**
+
+48 tests (35 backend, 13 frontend). Then a live container run with the gate on:
+
+| Without a session | |
+|---|---|
+| `/healthz`, `/api/v1/auth/me`, `/api/v1/auth/logout` | 200 — a login endpoint cannot require a login |
+| `/api/v1/repos` (valid body), `/repos/{id}/status`, `/source`, `/neighbors`, `/query` | **401** |
+| `/docs`, `/openapi.json` | **404** — F-05 closed |
+| Wrong password | 401, no cookie set |
+
+| With a session | |
+|---|---|
+| Cookie flags | `HttpOnly; Max-Age=43200; Path=/; SameSite=lax` (`Secure` was off only because the probe ran over local HTTP) |
+| `/repos/{id}/status` | 200 |
+| Gate switched back off | `auth_required:false`, every route open again |
+
+**Not verified: the `/workbench` → `/login` redirect in a real browser.** Its
+logic has four unit tests covering unknown / denied / allowed / failure, but
+headless screenshots do not work in this environment and that is not a reason to
+claim otherwise. **A human should open `/workbench` signed out and confirm it
+lands on `/login`, then sign in and confirm it lands back on the workbench.**
+
+One behaviour worth knowing rather than fixing: a request body that is not JSON
+at all returns 422 before the gate runs, because Starlette parses the body
+before dependencies resolve. A body that is valid JSON with wrong fields returns
+401. The disclosure is "this endpoint takes JSON", against an endpoint whose
+path the caller already knows, with the OpenAPI schema off.
### PR 4 — `feat/railway-deploy`
@@ -476,11 +499,11 @@ as leads to verify when the PR touches them, not as established fact.
| # | Finding | Where | Severity | PR | Verified |
|---|---|---|---|---|---|
-| F-01 | No authentication of any kind on `/api/v1/*`; no user or tenant concept, so any caller can read any indexed repo by `repo_id` | `apps/api/src/dcode_api/main.py:45-47` | blocker | 3 | audit |
+| F-01 | ~~No authentication of any kind on `/api/v1/*`~~ **— closed in PR 3.** A shared-account session gate now covers repos, query and inspector; `/internal/*` keeps its own shared-key check. Still one principal, not a tenant model (D-6) | `apps/api/src/dcode_api/main.py` | blocker | 3 | **direct** |
| F-02 | ~~The `api` service in the production Compose file has no embedding or reranker configuration~~ **— fixed in PR 1, and it was wider than this row said: `worker` and `agent` were short too. See § 6 PR 1.** | `docker-compose.prod.yml` | blocker | 1 | **direct** |
-| F-03 | No rate limiting, no request-size limit, no quota. `QueryRequest.query` has `min_length` but no `max_length` | `packages/shared/src/dcode_shared/schemas.py:132` | blocker | 3 | audit |
+| F-03 | **Partly closed in PR 3.** Anonymous access is gone and a per-session daily query cap bounds the metered path. **Still open: no request-size limit** — `QueryRequest.query` has `min_length` and no `max_length` | `packages/shared/src/dcode_shared/schemas.py:132` | blocker → medium | 3 → 5 | audit |
| F-04 | `INTERNAL_API_KEY` defaults to a literal published in this repository, with no startup guard outside Compose's `:?` operator — and Railway sets variables per service, so that operator does not protect the deployment | `packages/shared/src/dcode_shared/settings.py:33` | high | 5 | audit |
-| F-05 | `/docs`, `/redoc` and `/openapi.json` are publicly served and advertise the `/internal/*` surface | `apps/api/src/dcode_api/main.py:31-35` | high | 3 | audit |
+| F-05 | ~~`/docs`, `/redoc` and `/openapi.json` are publicly served~~ **— closed in PR 3**, off in production and pinned by a test; observed 404 on a gated container | `apps/api/src/dcode_api/main.py` | high | 3 | **direct** |
| F-06 | SSRF: repository URL validation rejects literal private IPs but has no host allowlist and no resolution check, so a hostname resolving to an internal address passes | `apps/api/src/dcode_api/routes/repos.py:203-224` | high | 5 | audit |
| F-07 | The agent tool cache key omits `index_revision`, so re-indexing a repository does not invalidate cached tool results for up to 24 h | `apps/agent/src/dcode_agent/graph.py:119` | high | 5 | audit |
| F-08 | Cloned workdirs are never cleaned up, for any repository, ever. On a fixed Railway volume this is unbounded growth | `apps/worker/src/dcode_worker/stages/clone.py:17-22` | high | 5 | audit |
@@ -493,12 +516,40 @@ as leads to verify when the PR touches them, not as established fact.
| F-15 | The `grep` tool runs `rg` with no timeout and buffers all output in memory; the pure-Python fallback compiles a user-supplied regex with no timeout | `apps/agent/src/dcode_agent/tools/grep.py:44-58`, `:79-101` | medium | 5 | audit |
| F-16 | nginx serves the bundle uncompressed — gzip is commented out in the base image and not enabled in the site config. Main chunk 752.53 kB / 226.74 kB gzipped | `apps/frontend/nginx.conf` | low | 4 | **direct** |
| F-17 | No `.dockerignore` anywhere; the frontend build context ships 227 MB of `node_modules` | repository root | low | 4 | **direct** |
+| F-19 | ~~A `$` in an env-file value is silently eaten by Compose interpolation, so a `$`-separated password hash reached the container as 22 of ~100 characters and every login failed while the service reported healthy~~ **— fixed in PR 3** (format changed, and the hash is now parsed at startup). Applies to any hand-picked secret containing `$` — see § 2.3 | `apps/api/src/dcode_api/auth.py` | high | 3 | **direct** |
+| F-20 | ~~The test suite reads the developer's `.env`, so `make check` is not hermetic — enabling the gate locally failed four unrelated tests with no hint of the cause~~ **— fixed in PR 3** by a root `conftest.py` pinning the settings whose defaults tests assert | `conftest.py` | medium | 3 | **direct** |
| F-18 | Model sidecars download weights from Hugging Face at runtime with no cache volume | `infra/docker/embedding.Dockerfile`, `infra/docker/reranker.Dockerfile` | low | — | **direct** |
F-18 is recorded but **not scheduled**: D-1 removes the sidecars from the
deployment path, so it only affects local Docker-profile use. It is left as a
known cost of that mode rather than fixed speculatively.
+### 2.3 A `$` in an env-file value is eaten before the container sees it
+
+Found while verifying PR 3, and it had already produced a working-looking
+failure. Docker Compose interpolates `${VAR}` **and bare `$VAR`** inside
+env-file values. A PBKDF2 hash of the conventional
+`pbkdf2_sha256$600000$salt$hash` form therefore reached the container as 22
+characters with three of its four segments gone.
+
+Nothing errored. Compose printed interpolation warnings among its normal
+output, the API booted, the health check passed, and **every login failed
+forever** — indistinguishable from a wrong password.
+
+Two changes, because either alone leaves the trap open:
+
+- the hash format joins its segments with `.` instead of `$`, so the character
+ never appears in the value (base64url contains no `.`, so it stays
+ unambiguous). Escaping as `$$` would also work and would be remembered by
+ nobody;
+- `auth_configuration_error()` now parses the hash rather than checking it is
+ non-empty, so a value corrupted by any means stops the boot instead of
+ producing a service that is up and unopenable.
+
+**This applies to every secret, not just this one.** A Postgres or RabbitMQ
+password containing `$` will be corrupted the same way. `secrets.token_urlsafe`
+output is safe (`A-Za-z0-9_-`); anything hand-picked is not.
+
### Already correct, recorded so nobody "fixes" it
- SSE anti-buffering headers are set on both hops — `Cache-Control: no-cache` and
diff --git a/apps/api/src/dcode_api/auth.py b/apps/api/src/dcode_api/auth.py
new file mode 100644
index 0000000..a535ffe
--- /dev/null
+++ b/apps/api/src/dcode_api/auth.py
@@ -0,0 +1,245 @@
+"""Single shared-account session auth for the gated deployment.
+
+Deploy.md D-6 chose one shared account over per-reviewer accounts: no user
+table, no migration, no account lifecycle. This module is what that decision
+costs — roughly a hundred lines of stdlib and no new dependency. `passlib`,
+`pyjwt` and `itsdangerous` are all absent from this workspace, and pulling one
+in to authenticate a single demo account would be the larger change.
+
+What it is not: an authorization model. There is one principal, a shared secret
+cannot be revoked for one holder, and the daily query cap is therefore per
+*session* rather than per person. Those limits are recorded in Deploy.md rather
+than papered over here.
+
+**Auth is off by default** (`AUTH_ENABLED=false`) so local development, the
+existing test suite and every current compose invocation are unaffected
+(Deploy.md §5.1). Production turns it on, and `docker-compose.prod.yml` hard-
+codes it rather than defaulting it, so a deployment cannot forget. If it is on
+and unconfigured the app refuses to start — an auth gate that fails open is
+worse than none, because it looks like one.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import secrets
+import time
+from dataclasses import dataclass
+from datetime import UTC, datetime
+
+from fastapi import Cookie, Depends, HTTPException, status
+
+from dcode_api.settings import api_settings
+
+SESSION_COOKIE_NAME = "dcode_session"
+
+_HASH_SCHEME = "pbkdf2_sha256"
+# Segments are joined with "." and NOT with passlib's conventional "$".
+#
+# Docker Compose interpolates `${VAR}` *and* bare `$VAR` inside env-file
+# values. A `$`-separated hash therefore arrives at the container mangled:
+# `pbkdf2_sha256$600000$salt$hash` lost three of its four segments in testing
+# and shrank to 22 characters. Nothing errors — the value is still non-empty,
+# the app still boots, and every login just fails forever. Escaping as `$$` in
+# the env file would work and would be remembered by nobody, so the format
+# avoids the character instead. The base64url alphabet has no ".", so this is
+# unambiguous.
+_HASH_SEPARATOR = "."
+# OWASP's 2023 floor for PBKDF2-HMAC-SHA256. Encoded into the hash string, so
+# raising it later does not invalidate credentials already issued.
+_DEFAULT_ITERATIONS = 600_000
+_SALT_BYTES = 16
+
+
+# --- password hashing ----------------------------------------------------
+
+
+def _parse_hash(encoded: str) -> tuple[int, bytes, bytes] | None:
+ """Split an encoded hash, or None if it is not one."""
+ try:
+ scheme, raw_iterations, salt_b64, expected_b64 = encoded.split(_HASH_SEPARATOR)
+ if scheme != _HASH_SCHEME:
+ return None
+ return int(raw_iterations), _b64decode(salt_b64), _b64decode(expected_b64)
+ except (ValueError, TypeError):
+ return None
+
+
+def hash_password(password: str, *, iterations: int = _DEFAULT_ITERATIONS) -> str:
+ """Encode a password as ``pbkdf2_sha256$iterations$salt$hash``."""
+ salt = secrets.token_bytes(_SALT_BYTES)
+ derived = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
+ return _HASH_SEPARATOR.join(
+ [_HASH_SCHEME, str(iterations), _b64encode(salt), _b64encode(derived)]
+ )
+
+
+def verify_password(password: str, encoded: str) -> bool:
+ """Check a password against an encoded hash, in constant time.
+
+ Returns False rather than raising on a malformed hash: a misconfigured
+ `AUTH_PASSWORD_HASH` must deny access, not crash the request handler into
+ a 500 that a caller could tell apart from a wrong password.
+ """
+ parsed = _parse_hash(encoded)
+ if parsed is None:
+ return False
+ iterations, salt, expected = parsed
+
+ derived = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
+ return hmac.compare_digest(derived, expected)
+
+
+# --- session tokens ------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class SessionClaims:
+ """A validated session. `jti` scopes the per-session daily query budget."""
+
+ sub: str
+ jti: str
+ issued_at: int
+ expires_at: int
+
+
+def issue_session(username: str, *, ttl_seconds: int, secret: str) -> str:
+ """Mint a signed ``payload.signature`` token. Not encrypted — only signed.
+
+ The payload is readable by the holder, which is fine: it carries a username
+ they just typed and two timestamps. What matters is that they cannot change
+ it, and that a stolen token expires.
+ """
+ now = int(time.time())
+ payload = {
+ "sub": username,
+ "jti": secrets.token_urlsafe(12),
+ "iat": now,
+ "exp": now + ttl_seconds,
+ }
+ encoded = _b64encode(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
+ return f"{encoded}.{_sign(encoded, secret)}"
+
+
+def read_session(token: str, *, secret: str, now: int | None = None) -> SessionClaims | None:
+ """Validate a token and return its claims, or None for any failure.
+
+ Every rejection collapses to None on purpose. Distinguishing "bad
+ signature" from "expired" in the response would tell an attacker which half
+ of a forgery attempt worked.
+ """
+ encoded, separator, signature = token.partition(".")
+ if not separator or not encoded or not signature:
+ return None
+ if not hmac.compare_digest(signature, _sign(encoded, secret)):
+ return None
+
+ try:
+ payload = json.loads(_b64decode(encoded))
+ except (ValueError, TypeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+
+ sub, jti = payload.get("sub"), payload.get("jti")
+ issued_at, expires_at = payload.get("iat"), payload.get("exp")
+ if not isinstance(sub, str) or not isinstance(jti, str):
+ return None
+ if not isinstance(issued_at, int) or not isinstance(expires_at, int):
+ return None
+ if (now if now is not None else int(time.time())) >= expires_at:
+ return None
+
+ return SessionClaims(sub=sub, jti=jti, issued_at=issued_at, expires_at=expires_at)
+
+
+# --- configuration -------------------------------------------------------
+
+
+def auth_configuration_error() -> str | None:
+ """Return why auth cannot be enforced, or None when it is ready.
+
+ Called at startup so an unconfigured production container dies on boot
+ instead of serving the workbench to anyone who asks.
+ """
+ if not api_settings.auth_enabled:
+ return None
+ if not api_settings.auth_username.strip():
+ return "AUTH_USERNAME is required when AUTH_ENABLED is true"
+ if not api_settings.auth_password_hash.strip():
+ return (
+ "AUTH_PASSWORD_HASH is required when AUTH_ENABLED is true "
+ "(generate one with: python -m dcode_api.hash_password)"
+ )
+ # Checked for shape, not just presence. A hash that arrives corrupted —
+ # the historical case is an env-file interpolation eating it — leaves a
+ # non-empty value that rejects every login while the service reports
+ # healthy. Refusing to boot is the only honest response to that.
+ if _parse_hash(api_settings.auth_password_hash.strip()) is None:
+ return (
+ "AUTH_PASSWORD_HASH is not a valid hash. Regenerate it with "
+ "`python -m dcode_api.hash_password`, and if the value passes "
+ "through an env file check that nothing rewrote it"
+ )
+ if len(api_settings.auth_session_secret.strip()) < 32:
+ return "AUTH_SESSION_SECRET must be at least 32 characters when AUTH_ENABLED is true"
+ return None
+
+
+# --- request dependencies ------------------------------------------------
+
+
+def current_session(
+ dcode_session: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
+) -> SessionClaims | None:
+ """Read and validate the session cookie. None when absent, invalid, or off."""
+ if not api_settings.auth_enabled or not dcode_session:
+ return None
+ return read_session(dcode_session, secret=api_settings.auth_session_secret)
+
+
+def require_session(
+ session: SessionClaims | None = Depends(current_session),
+) -> SessionClaims | None:
+ """Router-level gate. A no-op when auth is disabled, 401 otherwise."""
+ if not api_settings.auth_enabled:
+ return None
+ if session is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail={"code": "NOT_AUTHENTICATED", "message": "sign in to use this endpoint"},
+ )
+ return session
+
+
+# --- per-session daily query budget --------------------------------------
+
+
+def quota_key(session: SessionClaims, *, today: str | None = None) -> str:
+ """Redis key for one session's spend on one UTC day.
+
+ Keyed by `jti`, so the budget is per sign-in rather than per account —
+ which is the only granularity a shared account can offer (D-6).
+ """
+ day = today or datetime.now(UTC).strftime("%Y-%m-%d")
+ return f"authquota:{session.jti}:{day}"
+
+
+# --- helpers -------------------------------------------------------------
+
+
+def _sign(payload: str, secret: str) -> str:
+ digest = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).digest()
+ return _b64encode(digest)
+
+
+def _b64encode(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _b64decode(encoded: str) -> bytes:
+ padding = "=" * (-len(encoded) % 4)
+ return base64.urlsafe_b64decode(encoded + padding)
diff --git a/apps/api/src/dcode_api/hash_password.py b/apps/api/src/dcode_api/hash_password.py
new file mode 100644
index 0000000..23c6f79
--- /dev/null
+++ b/apps/api/src/dcode_api/hash_password.py
@@ -0,0 +1,37 @@
+"""Generate an ``AUTH_PASSWORD_HASH`` value.
+
+ python -m dcode_api.hash_password
+
+Prompts without echoing, confirms, and prints the line to paste. Reading the
+password from an argument was rejected deliberately: it would put the
+credential in shell history and in the process list.
+"""
+
+import getpass
+import sys
+
+from dcode_api.auth import hash_password
+
+
+def main() -> int:
+ password = getpass.getpass("Password: ")
+ if not password:
+ print("empty password refused", file=sys.stderr)
+ return 1
+ if password != getpass.getpass("Confirm: "):
+ print("passwords do not match", file=sys.stderr)
+ return 1
+
+ print()
+ print("Add to .env.production (never to a committed file):")
+ print()
+ print(f"AUTH_PASSWORD_HASH={hash_password(password)}")
+ print()
+ print("And a session secret, at least 32 characters:")
+ print()
+ print("AUTH_SESSION_SECRET=$(python3 -c 'import secrets; print(secrets.token_urlsafe(48))')")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/apps/api/src/dcode_api/main.py b/apps/api/src/dcode_api/main.py
index 95303ab..c84966c 100644
--- a/apps/api/src/dcode_api/main.py
+++ b/apps/api/src/dcode_api/main.py
@@ -8,16 +8,24 @@
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
-from fastapi import FastAPI
+from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from dcode_api import deps
-from dcode_api.routes import inspector, internal, query, repos
+from dcode_api.auth import auth_configuration_error, require_session
+from dcode_api.routes import auth, inspector, internal, query, repos
from dcode_api.settings import api_settings
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
+ # Refuse to start a gate that cannot be enforced. Serving the workbench
+ # openly because a secret was missing is the failure this prevents, and it
+ # is one that looks fine from the outside.
+ misconfigured = auth_configuration_error()
+ if misconfigured is not None:
+ raise RuntimeError(misconfigured)
+
# Own the shared Redis + agent-client lifecycle: warm at startup, release on
# shutdown. (DB uses the shared SQLAlchemy engine pool; RabbitMQ connects per
# publish on the submit path.)
@@ -28,27 +36,52 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
await deps.close_pools()
-app = FastAPI(
- title="Dcode API Gateway",
- version="0.0.0",
- lifespan=lifespan,
-)
+def create_app() -> FastAPI:
+ """Build the gateway. A function so the docs switch is testable.
+
+ `app` below is what uvicorn imports; nothing else should call this except
+ tests that need a second instance under different settings.
+ """
+ application = FastAPI(
+ title="Dcode API Gateway",
+ version="0.0.0",
+ lifespan=lifespan,
+ # /docs, /redoc and /openapi.json enumerate the /internal/* retrieval
+ # and graph surface. Handy locally, an advertisement in production.
+ docs_url="/docs" if api_settings.docs_enabled else None,
+ redoc_url="/redoc" if api_settings.docs_enabled else None,
+ openapi_url="/openapi.json" if api_settings.docs_enabled else None,
+ )
+
+ application.add_middleware(
+ CORSMiddleware,
+ allow_origins=api_settings.cors_origins_list,
+ allow_methods=["GET", "POST", "OPTIONS"],
+ allow_headers=["*"],
+ allow_credentials=False,
+ )
+
+ # The gate. `require_session` is a no-op while AUTH_ENABLED is false, so
+ # the default local stack and the existing tests see no change; with it on,
+ # every route below returns 401 without a valid session cookie.
+ gated = [Depends(require_session)]
+
+ # Not gated: signing in cannot require being signed in.
+ application.include_router(auth.router, prefix="/api/v1")
+
+ application.include_router(repos.router, prefix="/api/v1", dependencies=gated)
+ application.include_router(query.router, prefix="/api/v1", dependencies=gated)
+ application.include_router(inspector.router, prefix="/api/v1", dependencies=gated)
+ # /internal/* is not part of the session gate: it is service-to-service and
+ # carries its own shared-key check, and the agent has no cookie to present.
+ application.include_router(internal.router, prefix="/internal")
-app.add_middleware(
- CORSMiddleware,
- allow_origins=api_settings.cors_origins_list,
- allow_methods=["GET", "POST", "OPTIONS"],
- allow_headers=["*"],
- allow_credentials=False,
-)
+ @application.get("/healthz", tags=["meta"])
+ async def healthz() -> dict[str, str]:
+ """Shallow liveness probe — does not check dependent services."""
+ return {"status": "ok"}
-app.include_router(repos.router, prefix="/api/v1")
-app.include_router(query.router, prefix="/api/v1")
-app.include_router(inspector.router, prefix="/api/v1")
-app.include_router(internal.router, prefix="/internal")
+ return application
-@app.get("/healthz", tags=["meta"])
-async def healthz() -> dict[str, str]:
- """Shallow liveness probe — does not check dependent services."""
- return {"status": "ok"}
+app = create_app()
diff --git a/apps/api/src/dcode_api/routes/auth.py b/apps/api/src/dcode_api/routes/auth.py
new file mode 100644
index 0000000..0290857
--- /dev/null
+++ b/apps/api/src/dcode_api/routes/auth.py
@@ -0,0 +1,106 @@
+"""Session endpoints for the shared-account gate.
+
+These three routes are deliberately **not** behind the gate — a login endpoint
+that requires a login is a locked door with the key inside. Everything else
+under /api/v1 is protected in main.py.
+"""
+
+from fastapi import APIRouter, Depends, HTTPException, Response, status
+from pydantic import BaseModel, Field
+
+from dcode_api.auth import (
+ SESSION_COOKIE_NAME,
+ SessionClaims,
+ current_session,
+ issue_session,
+ verify_password,
+)
+from dcode_api.settings import api_settings
+
+router = APIRouter(tags=["auth"], prefix="/auth")
+
+
+class LoginRequest(BaseModel):
+ """Credentials for the single shared account."""
+
+ username: str = Field(..., min_length=1, max_length=200)
+ password: str = Field(..., min_length=1, max_length=400)
+
+
+class SessionState(BaseModel):
+ """What the SPA needs to decide whether to show a gate.
+
+ `auth_required` is separate from `authenticated` so the frontend behaves
+ correctly in both deployments: with the gate off it must not redirect to a
+ login page that would accept anything.
+ """
+
+ auth_required: bool
+ authenticated: bool
+ username: str | None = None
+
+
+@router.post("/login", response_model=SessionState)
+async def login(body: LoginRequest, response: Response) -> SessionState:
+ """Exchange credentials for a signed session cookie."""
+ if not api_settings.auth_enabled:
+ # Nothing to sign in to. Report the state rather than minting a cookie
+ # that would imply a gate exists.
+ return SessionState(auth_required=False, authenticated=True, username=None)
+
+ username_ok = body.username.strip() == api_settings.auth_username.strip()
+ password_ok = verify_password(body.password, api_settings.auth_password_hash)
+ # Both checks always run. Returning early on an unknown username would let
+ # the response time distinguish "wrong user" from "wrong password".
+ if not (username_ok and password_ok):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail={"code": "INVALID_CREDENTIALS", "message": "incorrect username or password"},
+ )
+
+ token = issue_session(
+ api_settings.auth_username.strip(),
+ ttl_seconds=api_settings.auth_session_ttl_seconds,
+ secret=api_settings.auth_session_secret,
+ )
+ response.set_cookie(
+ SESSION_COOKIE_NAME,
+ token,
+ max_age=api_settings.auth_session_ttl_seconds,
+ httponly=True,
+ secure=api_settings.auth_cookie_secure,
+ samesite="lax",
+ path="/",
+ )
+ return SessionState(
+ auth_required=True, authenticated=True, username=api_settings.auth_username.strip()
+ )
+
+
+@router.post("/logout", response_model=SessionState)
+async def logout(response: Response) -> SessionState:
+ """Clear the session cookie.
+
+ The token stays valid until it expires — there is no server-side session
+ store to revoke it in, which is the cost of D-6 and is recorded there.
+ """
+ response.delete_cookie(SESSION_COOKIE_NAME, path="/")
+ return SessionState(
+ auth_required=api_settings.auth_enabled, authenticated=not api_settings.auth_enabled
+ )
+
+
+@router.get("/me", response_model=SessionState)
+async def me(session: SessionClaims | None = Depends(current_session)) -> SessionState:
+ """Report session state. Always 200 — the SPA decides what to do with it.
+
+ A 401 here would be indistinguishable from a network failure at the point
+ where the frontend is deciding whether to render a gate at all.
+ """
+ if not api_settings.auth_enabled:
+ return SessionState(auth_required=False, authenticated=True, username=None)
+ return SessionState(
+ auth_required=True,
+ authenticated=session is not None,
+ username=session.sub if session else None,
+ )
diff --git a/apps/api/src/dcode_api/routes/query.py b/apps/api/src/dcode_api/routes/query.py
index bfd7ccc..fae0868 100644
--- a/apps/api/src/dcode_api/routes/query.py
+++ b/apps/api/src/dcode_api/routes/query.py
@@ -14,28 +14,35 @@
from dcode_shared.cache import query_cache_key
from dcode_shared.events import ErrorEvent, ThoughtEvent, sse_encode
from dcode_shared.schemas import QueryRequest, QueryTurn
-from fastapi import APIRouter, Depends
+from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from redis.asyncio import Redis
from redis.exceptions import RedisError
+from dcode_api.auth import SessionClaims, current_session, quota_key
from dcode_api.deps import get_agent_client, get_redis
from dcode_api.settings import api_settings
router = APIRouter(tags=["query"])
+# A day, so the counter disappears on its own rather than accumulating a key
+# per session per day forever.
+_QUOTA_TTL_SECONDS = 24 * 60 * 60
+
@router.post("/query")
async def query(
body: QueryRequest,
agent: httpx.AsyncClient = Depends(get_agent_client),
redis: Redis = Depends(get_redis),
+ session: SessionClaims | None = Depends(current_session),
) -> StreamingResponse:
"""Stream SSE events from the agent service back to the client.
Successful streams are cached in Redis under the documented
`query:{repo_id}:{hash(query)}` key for a short replay window.
"""
+ await _enforce_daily_quota(redis, session)
return StreamingResponse(
_stream_query(agent, redis, body),
media_type="text/event-stream",
@@ -46,6 +53,41 @@ async def query(
)
+async def _enforce_daily_quota(redis: Redis, session: SessionClaims | None) -> None:
+ """Bound one session's spend for the day, or 429.
+
+ The login wall removes anonymous callers; it does nothing about a signed-in
+ one looping a question through three metered APIs. Counted before the
+ agent is reached, because the cost is incurred there.
+
+ A Redis failure lets the request through. The counter is a spend guard, not
+ a security control, and refusing every query because a cache is down would
+ trade a bounded bill for a total outage.
+ """
+ if session is None or api_settings.auth_daily_query_limit <= 0:
+ return
+
+ key = quota_key(session)
+ try:
+ used = await redis.incr(key)
+ if used == 1:
+ await redis.expire(key, _QUOTA_TTL_SECONDS)
+ except RedisError:
+ return
+
+ if used > api_settings.auth_daily_query_limit:
+ raise HTTPException(
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ detail={
+ "code": "DAILY_QUERY_LIMIT",
+ "message": (
+ f"this session has used its {api_settings.auth_daily_query_limit} "
+ "queries for today"
+ ),
+ },
+ )
+
+
async def _stream_query(
agent: httpx.AsyncClient,
redis: Redis,
diff --git a/apps/api/src/dcode_api/settings.py b/apps/api/src/dcode_api/settings.py
index c13ff28..67683f9 100644
--- a/apps/api/src/dcode_api/settings.py
+++ b/apps/api/src/dcode_api/settings.py
@@ -16,6 +16,28 @@ class APISettings(SharedSettings):
query_history_max_chars: int = 2000
query_history_max_turn_chars: int = 4000
+ # --- Single shared-account gate (Deploy.md D-6) ---
+ # Off by default so local development, the test suite and every current
+ # compose invocation are unaffected. docker-compose.prod.yml hardcodes it
+ # on, and a config-hardening test pins that, so a deployment cannot forget.
+ # When on but unconfigured the app refuses to start: an auth gate that
+ # fails open is worse than none, because it looks like one.
+ auth_enabled: bool = False
+ auth_username: str = "dcode"
+ auth_password_hash: str = ""
+ auth_session_secret: str = ""
+ auth_session_ttl_seconds: int = 12 * 60 * 60
+ # Browsers treat http://localhost as a trustworthy origin, so a Secure
+ # cookie still works there; this exists for a plain-HTTP staging host.
+ auth_cookie_secure: bool = True
+ # The login wall stops anonymous callers. It does not stop a signed-in one
+ # looping a query against three metered APIs, which is what this bounds.
+ auth_daily_query_limit: int = 200
+
+ # /docs, /redoc and /openapi.json advertise the /internal/* surface.
+ # Useful locally, so on by default; prod compose turns it off.
+ docs_enabled: bool = True
+
@property
def cors_origins_list(self) -> list[str]:
"""Comma-separated CORS_ORIGINS env var → list."""
diff --git a/apps/api/tests/test_auth.py b/apps/api/tests/test_auth.py
new file mode 100644
index 0000000..473b434
--- /dev/null
+++ b/apps/api/tests/test_auth.py
@@ -0,0 +1,382 @@
+"""Tests for the single shared-account gate.
+
+The gate is off by default, so most of these turn it on explicitly. That
+asymmetry is the point: the default path must be unchanged, and the gated path
+must actually refuse.
+
+PBKDF2 runs at a low iteration count here. 600k iterations is right for a login
+endpoint and wrong for a test suite that hashes a dozen times.
+"""
+
+import time
+
+import httpx
+import pytest
+from dcode_api.auth import (
+ SESSION_COOKIE_NAME,
+ auth_configuration_error,
+ hash_password,
+ issue_session,
+ read_session,
+ verify_password,
+)
+from dcode_api.deps import get_agent_client, get_redis
+from dcode_api.main import app, create_app
+from dcode_api.settings import api_settings
+from fastapi.testclient import TestClient
+from redis.exceptions import RedisError
+
+_TEST_ITERATIONS = 10
+_SECRET = "s" * 48
+_PASSWORD = "correct horse battery staple"
+
+
+@pytest.fixture
+def gated(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ """A client with the gate on and a known credential.
+
+ The base URL is https on purpose. The cookie is issued `Secure`, so over
+ plain http a client correctly refuses to send it back and every
+ post-login assertion would fail for a reason that has nothing to do with
+ the gate. Weakening the cookie to make the test pass would delete the
+ property being tested — this is also a real operational note: a
+ plain-HTTP staging host needs `AUTH_COOKIE_SECURE=false` or logins will
+ appear to succeed and never stick.
+ """
+ monkeypatch.setattr(api_settings, "auth_enabled", True)
+ monkeypatch.setattr(api_settings, "auth_username", "reviewer")
+ monkeypatch.setattr(
+ api_settings,
+ "auth_password_hash",
+ hash_password(_PASSWORD, iterations=_TEST_ITERATIONS),
+ )
+ monkeypatch.setattr(api_settings, "auth_session_secret", _SECRET)
+ # Set rather than inherited: a test that asserts the cookie is Secure has
+ # to establish that, or it passes or fails on the developer's .env.
+ monkeypatch.setattr(api_settings, "auth_cookie_secure", True)
+ return TestClient(app, base_url="https://testserver")
+
+
+# --- password hashing ----------------------------------------------------
+
+
+def test_password_roundtrip() -> None:
+ encoded = hash_password(_PASSWORD, iterations=_TEST_ITERATIONS)
+ assert verify_password(_PASSWORD, encoded)
+ assert not verify_password("wrong", encoded)
+
+
+def test_password_hash_is_salted() -> None:
+ """Two hashes of the same password must differ, or the salt is not doing its job."""
+ a = hash_password(_PASSWORD, iterations=_TEST_ITERATIONS)
+ b = hash_password(_PASSWORD, iterations=_TEST_ITERATIONS)
+ assert a != b
+ assert verify_password(_PASSWORD, a) and verify_password(_PASSWORD, b)
+
+
+@pytest.mark.parametrize("encoded", ["", "not-a-hash", "bcrypt$1$x$y", "pbkdf2_sha256$abc$x$y"])
+def test_malformed_hash_denies_rather_than_raises(encoded: str) -> None:
+ """A misconfigured hash must deny access, not 500.
+
+ A crash is distinguishable from a wrong password by the caller, which turns
+ a configuration mistake into an oracle.
+ """
+ assert verify_password(_PASSWORD, encoded) is False
+
+
+# --- session tokens ------------------------------------------------------
+
+
+def test_session_roundtrip() -> None:
+ token = issue_session("reviewer", ttl_seconds=60, secret=_SECRET)
+ claims = read_session(token, secret=_SECRET)
+ assert claims is not None
+ assert claims.sub == "reviewer"
+ assert claims.jti
+
+
+def test_session_rejects_a_tampered_payload() -> None:
+ token = issue_session("reviewer", ttl_seconds=60, secret=_SECRET)
+ payload, _, signature = token.partition(".")
+ forged = f"{payload[:-4]}AAAA.{signature}"
+ assert read_session(forged, secret=_SECRET) is None
+
+
+def test_session_rejects_another_secret() -> None:
+ token = issue_session("reviewer", ttl_seconds=60, secret=_SECRET)
+ assert read_session(token, secret="d" * 48) is None
+
+
+def test_session_expires() -> None:
+ token = issue_session("reviewer", ttl_seconds=1, secret=_SECRET)
+ now = int(time.time())
+ assert read_session(token, secret=_SECRET, now=now) is not None
+ assert read_session(token, secret=_SECRET, now=now + 2) is None
+
+
+@pytest.mark.parametrize("token", ["", "nodot", ".", "a.", ".b"])
+def test_session_rejects_malformed_tokens(token: str) -> None:
+ assert read_session(token, secret=_SECRET) is None
+
+
+# --- fail closed ---------------------------------------------------------
+
+
+def test_configuration_error_is_none_when_disabled() -> None:
+ assert auth_configuration_error() is None
+
+
+def test_enabled_without_a_password_hash_is_a_startup_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(api_settings, "auth_enabled", True)
+ monkeypatch.setattr(api_settings, "auth_password_hash", "")
+ monkeypatch.setattr(api_settings, "auth_session_secret", _SECRET)
+ error = auth_configuration_error()
+ assert error is not None and "AUTH_PASSWORD_HASH" in error
+
+
+def test_a_corrupted_password_hash_is_a_startup_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Presence is not enough — the hash is checked for shape.
+
+ Found live: Docker Compose interpolates `$VAR` inside env-file values, so a
+ `$`-separated hash reached the container as 22 characters with three of its
+ four segments eaten. Nothing errored. The service reported healthy and
+ every login failed forever, with no way to tell that from a wrong password.
+
+ The format now uses "." so the character never appears, and this check is
+ the second line: any hash that will not parse stops the boot.
+ """
+ monkeypatch.setattr(api_settings, "auth_enabled", True)
+ monkeypatch.setattr(api_settings, "auth_session_secret", _SECRET)
+ for corrupted in ("pbkdf2_sha256", "pbkdf2_sha256.600000", "garbage", "a.b.c.d"):
+ monkeypatch.setattr(api_settings, "auth_password_hash", corrupted)
+ error = auth_configuration_error()
+ assert error is not None, f"{corrupted!r} was accepted as a password hash"
+ assert "AUTH_PASSWORD_HASH" in error
+
+
+def test_password_hash_contains_no_dollar_sign() -> None:
+ """The encoded hash must survive an env file unescaped.
+
+ `$` is what Docker Compose expands. A hash carrying one is a credential
+ that silently arrives wrong.
+ """
+ assert "$" not in hash_password(_PASSWORD, iterations=_TEST_ITERATIONS)
+
+
+def test_enabled_with_a_weak_session_secret_is_a_startup_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(api_settings, "auth_enabled", True)
+ monkeypatch.setattr(api_settings, "auth_password_hash", hash_password("x", iterations=10))
+ monkeypatch.setattr(api_settings, "auth_session_secret", "short")
+ error = auth_configuration_error()
+ assert error is not None and "AUTH_SESSION_SECRET" in error
+
+
+# --- the gate ------------------------------------------------------------
+
+
+_PROTECTED = [
+ ("post", "/api/v1/repos", {"json": {"url": "https://github.com/psf/requests.git"}}),
+ (
+ "post",
+ "/api/v1/query",
+ {"json": {"repo_id": "00000000-0000-0000-0000-000000000000", "query": "hi"}},
+ ),
+ ("get", "/api/v1/repos/00000000-0000-0000-0000-000000000000/status", {}),
+ ("get", "/api/v1/repos/00000000-0000-0000-0000-000000000000/source?file_path=a.py", {}),
+ ("get", "/api/v1/repos/00000000-0000-0000-0000-000000000000/neighbors?symbol=x", {}),
+]
+
+
+@pytest.mark.parametrize(("method", "path", "kwargs"), _PROTECTED)
+def test_protected_routes_refuse_without_a_session(
+ gated: TestClient, method: str, path: str, kwargs: dict[str, object]
+) -> None:
+ response = getattr(gated, method)(path, **kwargs)
+ assert response.status_code == 401
+ assert response.json()["detail"]["code"] == "NOT_AUTHENTICATED"
+
+
+def test_open_routes_stay_open_with_the_gate_on(gated: TestClient) -> None:
+ """Liveness and the session endpoints cannot require a session."""
+ assert gated.get("/healthz").status_code == 200
+ assert gated.get("/api/v1/auth/me").status_code == 200
+ assert gated.post("/api/v1/auth/logout").status_code == 200
+
+
+def test_me_reports_unauthenticated_before_login(gated: TestClient) -> None:
+ body = gated.get("/api/v1/auth/me").json()
+ assert body == {"auth_required": True, "authenticated": False, "username": None}
+
+
+def test_me_reports_no_gate_when_disabled() -> None:
+ body = TestClient(app).get("/api/v1/auth/me").json()
+ assert body["auth_required"] is False
+ assert body["authenticated"] is True
+
+
+def test_login_rejects_a_wrong_password(gated: TestClient) -> None:
+ response = gated.post(
+ "/api/v1/auth/login", json={"username": "reviewer", "password": "nope"}
+ )
+ assert response.status_code == 401
+ assert response.json()["detail"]["code"] == "INVALID_CREDENTIALS"
+ assert SESSION_COOKIE_NAME not in response.cookies
+
+
+def test_login_rejects_a_wrong_username(gated: TestClient) -> None:
+ response = gated.post(
+ "/api/v1/auth/login", json={"username": "someone-else", "password": _PASSWORD}
+ )
+ assert response.status_code == 401
+
+
+def test_login_sets_a_hardened_cookie_and_opens_the_gate(gated: TestClient) -> None:
+ response = gated.post(
+ "/api/v1/auth/login", json={"username": "reviewer", "password": _PASSWORD}
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "auth_required": True,
+ "authenticated": True,
+ "username": "reviewer",
+ }
+
+ cookie_header = response.headers["set-cookie"].lower()
+ assert "httponly" in cookie_header
+ assert "secure" in cookie_header
+ assert "samesite=lax" in cookie_header
+
+ # The client keeps the cookie, so a previously-401 route now resolves.
+ assert gated.get("/api/v1/auth/me").json()["authenticated"] is True
+ assert (
+ gated.get("/api/v1/repos/00000000-0000-0000-0000-000000000000/status").status_code
+ != 401
+ )
+
+
+def test_logout_clears_the_session(gated: TestClient) -> None:
+ gated.post("/api/v1/auth/login", json={"username": "reviewer", "password": _PASSWORD})
+ assert gated.get("/api/v1/auth/me").json()["authenticated"] is True
+
+ gated.post("/api/v1/auth/logout")
+ assert gated.get("/api/v1/auth/me").json()["authenticated"] is False
+
+
+def test_an_expired_cookie_is_refused(gated: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(api_settings, "auth_session_ttl_seconds", -1)
+ gated.post("/api/v1/auth/login", json={"username": "reviewer", "password": _PASSWORD})
+ assert gated.get("/api/v1/auth/me").json()["authenticated"] is False
+
+
+# --- per-session daily query budget --------------------------------------
+
+
+class _CountingRedis:
+ """Enough Redis for the quota path, and it fails where asked to."""
+
+ def __init__(self, *, fail: bool = False) -> None:
+ self.counters: dict[str, int] = {}
+ self.expires: list[tuple[str, int]] = []
+ self.fail = fail
+
+ async def incr(self, key: str) -> int:
+ if self.fail:
+ raise RedisError("down")
+ self.counters[key] = self.counters.get(key, 0) + 1
+ return self.counters[key]
+
+ async def expire(self, key: str, ttl: int) -> None:
+ self.expires.append((key, ttl))
+
+ async def get(self, key: str) -> str | None:
+ return None
+
+ async def setex(self, key: str, ttl: int, value: str) -> None:
+ return None
+
+
+def _sign_in(client: TestClient) -> None:
+ response = client.post(
+ "/api/v1/auth/login", json={"username": "reviewer", "password": _PASSWORD}
+ )
+ assert response.status_code == 200
+
+
+def _query(client: TestClient) -> int:
+ return client.post(
+ "/api/v1/query",
+ json={"repo_id": "00000000-0000-0000-0000-000000000000", "query": "hi"},
+ ).status_code
+
+
+def test_daily_query_budget_is_enforced_per_session(
+ gated: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The login wall stops anonymous callers, not a signed-in loop.
+
+ Counted before the agent is reached, because that is where the metered
+ APIs are.
+ """
+ monkeypatch.setattr(api_settings, "auth_daily_query_limit", 2)
+ redis = _CountingRedis()
+ app.dependency_overrides[get_redis] = lambda: redis
+ app.dependency_overrides[get_agent_client] = lambda: _NeverCalledAgent()
+ try:
+ _sign_in(gated)
+ assert _query(gated) != 429
+ assert _query(gated) != 429
+ assert _query(gated) == 429
+ finally:
+ app.dependency_overrides.clear()
+
+ assert len(redis.counters) == 1, "the budget must be one counter per session per day"
+ assert redis.expires and redis.expires[0][1] == 24 * 60 * 60
+
+
+def test_quota_failure_lets_the_request_through(
+ gated: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A spend guard is not a security control.
+
+ Refusing every query because Redis is down trades a bounded bill for a
+ total outage, which is the worse failure.
+ """
+ monkeypatch.setattr(api_settings, "auth_daily_query_limit", 1)
+ app.dependency_overrides[get_redis] = lambda: _CountingRedis(fail=True)
+ app.dependency_overrides[get_agent_client] = lambda: _NeverCalledAgent()
+ try:
+ _sign_in(gated)
+ assert _query(gated) != 429
+ assert _query(gated) != 429
+ finally:
+ app.dependency_overrides.clear()
+
+
+class _NeverCalledAgent:
+ """The quota check runs before the agent, so this only has to exist."""
+
+ def stream(self, method: str, url: str, json: dict[str, object]) -> object:
+ raise httpx.ConnectError("agent not part of this test")
+
+
+# --- docs surface --------------------------------------------------------
+
+
+def test_docs_are_served_by_default() -> None:
+ assert app.openapi_url == "/openapi.json"
+
+
+def test_docs_can_be_switched_off(monkeypatch: pytest.MonkeyPatch) -> None:
+ """F-05: /docs and /openapi.json enumerate the /internal/* surface."""
+ monkeypatch.setattr(api_settings, "docs_enabled", False)
+ closed = create_app()
+ assert closed.openapi_url is None
+ assert closed.docs_url is None
+ assert closed.redoc_url is None
+ assert TestClient(closed).get("/openapi.json").status_code == 404
diff --git a/apps/frontend/src/App.tsx b/apps/frontend/src/App.tsx
index dfa177b..200356e 100644
--- a/apps/frontend/src/App.tsx
+++ b/apps/frontend/src/App.tsx
@@ -1,6 +1,8 @@
import { Route, Routes } from 'react-router-dom';
+import { RequireSession } from '@/components/RequireSession';
import LandingPage from '@/pages/LandingPage';
+import LoginPage from '@/pages/LoginPage';
import MethodologyPage from '@/pages/MethodologyPage';
import PrimitivesGallery from '@/pages/PrimitivesGallery';
import WorkbenchPage from '@/pages/WorkbenchPage';
@@ -10,8 +12,20 @@ export default function App() {
+ The evaluation write-up is{' '}
+
+ open to everyone
+
+ . The workbench indexes repositories and calls metered models, so it is not.
+
+ Sign in to the workbench
+
+
workbench body
+ + } + /> +