Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion architecture/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
> - **[RELEASE_GATE.md](./RELEASE_GATE.md)** — how GO / CONDITIONAL_GO / NO_GO is decided: input signals, policy layer, band floor, council synthesis, overrides.
> - **[AI_QUALITY.md](./AI_QUALITY.md)** — the mechanisms that keep the AI layer honest: semantic cache, the human-correction learning loop, evidence grading, cluster integrity.
> - **[INGESTION_SCALE.md](./INGESTION_SCALE.md)** — ingestion under load: admission gates, shard queues, buffer caps + the drainer, DLQ/recovery, and AI cost controls.
> - **[SECURITY.md](./SECURITY.md)** — identity, the authz guard family + HMAC-signed membership cache, tenancy layers, secure-by-default deployment, offline-first, audit.
> - **[SECURITY.md](./SECURITY.md)** — identity, the authz guard family + PostgreSQL-authoritative membership reads (Redis deletion is legacy cleanup), tenancy layers, secure-by-default deployment, offline-first, audit.
> - **[DEPLOYMENT.md](./DEPLOYMENT.md)** — the topologies: compose variants, the release-image path, k8s base + per-target overlays, CI/CD pipelines, environment gotchas. Step-by-step install guides per mode: [docs/operations/deployment.md](../docs/operations/deployment.md).
> - **[FRONTEND.md](./FRONTEND.md)** — the SPA: pages→hooks→services→one-Axios layering, Zustand client-state model, the six-theme token system, and the enforcing ratchets.
> - **[VISUALIZATION_ENGINES_ADR.md](./VISUALIZATION_ENGINES_ADR.md)** — why charts use Recharts + per-type ECharts + three.js: the CSP, bundle-budget and air-gap constraints, the measured spike, and the tooltip-XSS rule.
Expand Down
52 changes: 31 additions & 21 deletions architecture/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ session is. Note that `IdentityEventType.ADMIN_FALLBACK_LOGIN` is **not** this
— that is the SSO fallback in `routers/auth.py` and says nothing about a second
factor.

## 2. Authorization — the guard family and the signed cache
## 2. Authorization — the guard family and PostgreSQL authority

Every router whose path carries a resource id (`{project_id}`, `{run_id}`,
`{release_id}`, …) depends on the matching `require_*_access` guard from
Expand All @@ -114,33 +114,41 @@ gates "no id supplied" leaves the direct-object reference wide open. The IDOR
sweeps hit exactly this on several routers; the convention plus its
architectural test now enforce the correct shape.)

Membership lookups are cached in Redis — and because an authorization cache is
itself an attack surface, entries are **HMAC-signed**:
Project membership is authorization state. For user membership scopes,
`get_accessible_project_ids` queries the current `project_members` rows in
PostgreSQL on every request; no Redis value is accepted as authority. The
existing ADMIN bypass, project-bound API-key confinement, and project-role
floors still apply before the selected project scope reaches a report or other
tenant query.

```mermaid
sequenceDiagram
participant RQ as Request ({project_id})
participant G as require_project_access
participant R as Redis (membership cache)
participant PG as Postgres
participant G as Authorization guard
participant PG as PostgreSQL (membership authority)
participant M as Membership change / erasure
participant R as Redis (legacy cleanup only)

RQ->>G: id + JWT/API key
G->>R: get membership entry
alt cache hit
R-->>G: entry + HMAC
G->>G: verify HMAC (forged/tampered entry fails → treated as miss)
G-->>RQ: allow / 403
else miss or bad signature
G->>PG: real membership query
PG-->>G: project ids
G->>R: store entry signed with _sign_membership_cache
G-->>RQ: allow / 403
G->>G: apply ADMIN, API-key binding, and role-floor rules
alt user membership must be resolved
G->>PG: SELECT current project_members rows
PG-->>G: current project ids / roles
end
G-->>RQ: allow with scoped query / 403

M->>PG: commit membership mutation or erasure
M->>R: delete membership:{user_id}
Note over M,R: This cleanup serves older replicas. New authorization reads ignore the key.
```

A Redis compromise (or a bug writing to the wrong key) therefore cannot mint
authorization: an unsigned or mis-signed entry simply fails HMAC and falls
through to the database.
`invalidate_membership_cache` remains best-effort so membership mutations and
subject erasure can remove keys written by an older replica during a rolling
deployment. That deletion is compatibility cleanup, not an access control: a
failed delete or a stale writer cannot widen the scope returned by new code.
Deploy this change to **all read-serving replicas before relying on the new
authorization path**; until then, an older replica can still accept its legacy
Redis membership cache.


### The ratchet's blind spot — ids that don't arrive in the path
Expand Down Expand Up @@ -209,8 +217,10 @@ produce an insecure install:
random local secrets and re-enable dev conveniences deliberately.
- **Dev auto-login** is a 404 unless explicitly enabled — the endpoint that
mints an admin JWT for local demos cannot exist in a default deployment.
- **Redis is authenticated** and the authz cache signed (above), closing the
"internal service, no auth needed" gap.
- **Redis is authenticated**, closing the "internal service, no auth needed"
gap, but it is not project-membership authority. PostgreSQL supplies current
membership on authorization reads; `membership:*` deletion is legacy cleanup
for rolling deployments and erasure.

## 5. Offline-first as a security property

Expand Down
125 changes: 9 additions & 116 deletions backend/app/core/deps.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Dependencies for FastAPI (authentication, authorisation, webhook security)."""
import hashlib
import hmac
import json
import logging
import uuid
from dataclasses import dataclass
Expand All @@ -21,8 +20,6 @@

logger = logging.getLogger(__name__)

# P3-2: Redis cache TTL for project membership lookups (seconds)
_MEMBERSHIP_CACHE_TTL = 300 # 5 minutes
_API_KEY_BOUND_PROJECT_ATTR = "_testlookup_api_key_project_id"

# Which credential authenticated *this* request. Stashed on the loaded ``User``
Expand Down Expand Up @@ -1183,8 +1180,9 @@ async def get_accessible_project_ids(

Non-admin users can only access projects they are a member of.

P3-2: Results are cached in Redis for 5 minutes to avoid a DB query on
every request. Invalidated by ``invalidate_membership_cache()``.
Membership is authorization state, so Postgres is consulted on every
request. Redis entries are never accepted as authority: a failed cache
invalidation or a stale in-flight writer must not preserve revoked access.
"""
from app.models.postgres import ProjectMember

Expand All @@ -1202,120 +1200,14 @@ async def get_accessible_project_ids(

if floor is not None:
# A write on a route with a role minimum reaches only the projects in
# which the caller holds that role. Asked of the database each time:
# the cache below holds membership, not roles, and writes are rare
# next to reads.
# which the caller holds that role. Asked of the database each time,
# like the membership-only read below.
return await _project_ids_with_role(db, user, floor)

# P3-2: Check Redis cache first. A persistent Redis failure would silently
# cascade into every request hitting the DB; log the first occurrence per
# process so ops can see the dependency degrade instead of only noticing
# the tail-latency symptom.
cache_key = f"membership:{user.id}"
try:
from app.db.redis_client import get_redis
redis = get_redis()
cached = await redis.get(cache_key)
if cached is not None:
verified = _verify_membership_cache(user.id, cached)
if verified is not None:
return verified
# Signature missing/invalid → treat as a cache miss and fall
# through to the DB (the authoritative source). Defence-in-depth
# for tenant isolation: even if Redis is writable by an attacker
# (or a stale/plain legacy entry survives a deploy), a poisoned or
# forged ``membership:*`` value cannot widen a user's project scope
# — it just fails the HMAC and is ignored. See the signing helpers.
_warn_membership_cache_tampered(user.id)
except Exception as exc:
_warn_membership_cache_degraded("read", exc)

result = await db.execute(
select(ProjectMember.project_id).where(ProjectMember.user_id == user.id)
)
project_ids = {row[0] for row in result.all()}

try:
from app.db.redis_client import get_redis
redis = get_redis()
await redis.set(
cache_key,
_sign_membership_cache(user.id, project_ids),
ex=_MEMBERSHIP_CACHE_TTL,
)
except Exception as exc:
_warn_membership_cache_degraded("write", exc)

return project_ids


def _membership_signature(user_id, payload: str) -> str:
"""HMAC-SHA256 of the cached membership payload, keyed by APP_SECRET_KEY and
bound to the user id so a valid blob can't be replayed under another user's
cache key."""
msg = f"{user_id}:{payload}".encode("utf-8")
key = (settings.APP_SECRET_KEY or "").encode("utf-8")
return hmac.new(key, msg, hashlib.sha256).hexdigest()


def _sign_membership_cache(user_id, project_ids: set) -> str:
"""Serialise + sign a user's accessible project-id set for Redis storage."""
payload = json.dumps(sorted(str(pid) for pid in project_ids))
return json.dumps({"p": payload, "s": _membership_signature(user_id, payload)})


def _verify_membership_cache(user_id, cached):
"""Return the cached project-id set iff the value carries a valid HMAC for
this user; ``None`` on any decode/format error or signature mismatch (the
caller then treats it as a miss and re-reads from the DB)."""
try:
if isinstance(cached, (bytes, bytearray)):
cached = cached.decode("utf-8")
blob = json.loads(cached)
payload = blob["p"]
sig = blob["s"]
except (ValueError, TypeError, KeyError, AttributeError):
return None
if not isinstance(sig, str) or not hmac.compare_digest(sig, _membership_signature(user_id, payload)):
return None
try:
return {uuid.UUID(pid) for pid in json.loads(payload)}
except (ValueError, TypeError):
return None


# Throttle noisy warnings — log once per hour per op if Redis is down.
_last_cache_warn_ts: dict[str, float] = {}


def _warn_membership_cache_degraded(op: str, exc: Exception) -> None:
import time as _time
now = _time.monotonic()
last = _last_cache_warn_ts.get(op, 0.0)
if now - last < 3600:
return
_last_cache_warn_ts[op] = now
logger.warning(
"membership cache %s failed — falling back to DB on every request: %s",
op, exc,
)


def _warn_membership_cache_tampered(user_id) -> None:
"""A ``membership:*`` entry failed HMAC verification — either tampering or a
legacy/plain value from before signing. Throttled like the degraded warner;
security-relevant, so it's logged rather than silently swallowed."""
import time as _time
now = _time.monotonic()
last = _last_cache_warn_ts.get("tamper", 0.0)
if now - last < 3600:
return
_last_cache_warn_ts["tamper"] = now
logger.warning(
"membership cache entry failed signature verification for user=%s — "
"ignoring cache and reading membership from DB (possible tampering or "
"a pre-signing legacy value)", user_id,
)
return {row[0] for row in result.all()}


async def resolve_project_scope(
Expand Down Expand Up @@ -1370,9 +1262,10 @@ async def resolve_project_scope(


async def invalidate_membership_cache(user_id: uuid.UUID) -> None:
"""Invalidate the cached project membership set for a user.
"""Delete a legacy cached project membership set for a user.

Call after adding/removing/updating project members.
Authorization reads Postgres directly. This cleanup remains for rolling
deployments and subject erasure, but its success is not an access control.
"""
try:
from app.db.redis_client import get_redis
Expand Down
1 change: 0 additions & 1 deletion backend/mypy-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
6 app/agents/release_risk_agent.py
1 app/agents/summary_agent.py
7 app/agents/workflow.py
1 app/core/deps.py
1 app/core/scim_errors.py
1 app/db/mongo.py
3 app/routers/agents.py
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
* cache isolation: the admin's All Projects reads go FIRST (they warm the
shared ``all`` entries and count A + B + C), and the member's reads that
follow still return A + B, never the admin's entry;
* ``/reports/summary`` allows the member to read A, then returns 403 on a new
request after A's membership is removed in a separate committed transaction;
the administrator remains able to read the same report;
* the member naming C, and a user with no project at all, get the empty body.

Uses ``tests/integration/defect_w06_world.py`` (projects, users, the ASGI
Expand All @@ -26,6 +29,7 @@
from types import SimpleNamespace

import pytest
from sqlalchemy import delete

from tests.integration.defect_w06_world import defect_world

Expand Down Expand Up @@ -159,6 +163,37 @@ async def test_a_cold_member_read_counts_only_their_projects(world):
assert _trend_sums(await _get(w, "/api/v1/metrics/trends", w.mine, days=7)).total == MEMBER_TOTAL


async def test_report_read_rechecks_membership_after_committed_removal(world):
"""A new report request observes revocation while an administrator retains access."""
from app.models.postgres import ProjectMember

w = world
path = "/api/v1/reports/summary"
params = {"project_id": str(w.A), "days": 7}

allowed = await w.client.get(path, params=params, headers=w.mine)
assert allowed.status_code == 200, allowed.text
assert allowed.json()["project_id"] == str(w.A)

# This transaction is independent of both HTTP request sessions and commits
# before the second read begins, matching an ordinary membership removal.
async with w.sessions.begin() as revocation:
removed = await revocation.execute(
delete(ProjectMember).where(
ProjectMember.project_id == w.A,
ProjectMember.user_id == w.mine_id,
)
)
assert removed.rowcount == 1

denied = await w.client.get(path, params=params, headers=w.mine)
assert denied.status_code == 403, denied.text

retained = await w.client.get(path, params=params, headers=w.admin)
assert retained.status_code == 200, retained.text
assert retained.json()["project_id"] == str(w.A)


async def test_the_readiness_p0_count_never_sees_the_foreign_critical(world):
"""The hard-cap input, directly: C's open CRITICAL is the admin's, not the member's."""
from app.services.metrics_service import count_open_critical_defects
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@
LARGE_RUN_CASES = 60
SUITES = ("perf-api", "perf-ui", "perf-db")

# Observed at the pin (75a61f6a). A per-row lookup added to any of these reads raises the count with the
# page size (caught by the equal-count assertions); any other added statement moves the pin.
# list: token revocation x2, user, COUNT, page, release map, run-number pairs, run numbers, suite map.
LIST_STATEMENTS = 9
# A per-row lookup raises the count with the page size and fails the equal-count assertions.
# The exact counts also catch added statements that run once per request.
# list: token revocation x2, user, current membership, COUNT, page, release map, run-number pairs,
# run numbers, suite map.
LIST_STATEMENTS = 10
# detail: token revocation x2, user, run access (run project, membership), run, release map, project name,
# run-number pairs, run numbers, suite map.
DETAIL_STATEMENTS = 11
Expand Down Expand Up @@ -271,8 +272,7 @@ def _shape(statements: list[str]) -> str:


async def _counted(world, path: str, **params):
# The same request once unmeasured first: the membership lookup is cached in Redis for 5 minutes, so
# every measured request starts from the same warm state whatever ran before it.
# Warm the other request caches before measuring. Membership is read from PostgreSQL on every request.
await world.client.get(path, params=params, headers=world.headers)
with StatementCounter(world.engine) as counter:
response = await world.client.get(path, params=params, headers=world.headers)
Expand Down
4 changes: 2 additions & 2 deletions backend/tests/integration/test_subject_erasure_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,8 +651,8 @@ async def _prove(sessions: Any, storage: Any, redis: Any, P: SimpleNamespace, id
assert dispatched == [str(job_id)] and response.json()["phase"] == "lockout"
pseudonym = svc.pseudonym_for(ids.subject)
assert preview.json()["pseudonym"] == pseudonym
# the lock-out dropped the membership cache after its commit; a request in flight may refill it before the
# worker runs — the redis phase is that backstop, so the cache is refilled here and must be counted there
# The lock-out drops any legacy membership cache after its commit. Seed a residual value, as an older worker
# in a rolling deployment might, to prove the Redis erasure phase remains a cleanup backstop and counts it.
membership = f"membership:{ids.subject}"
assert not await redis.exists(membership), "the lock-out drops the membership cache"
await redis.set(membership, json.dumps([str(uuid.uuid4())]), ex=300)
Expand Down
Loading
Loading