diff --git a/architecture/README.md b/architecture/README.md index 0cbb90a0d..f9f1bb427 100644 --- a/architecture/README.md +++ b/architecture/README.md @@ -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. diff --git a/architecture/SECURITY.md b/architecture/SECURITY.md index 065d31678..9bbdb11e2 100644 --- a/architecture/SECURITY.md +++ b/architecture/SECURITY.md @@ -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 @@ -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 @@ -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 diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py index 1fc4ab370..17b4485d9 100644 --- a/backend/app/core/deps.py +++ b/backend/app/core/deps.py @@ -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 @@ -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`` @@ -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 @@ -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( @@ -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 diff --git a/backend/mypy-baseline.txt b/backend/mypy-baseline.txt index 93b4cb484..8a01bee39 100644 --- a/backend/mypy-baseline.txt +++ b/backend/mypy-baseline.txt @@ -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 diff --git a/backend/tests/integration/test_all_projects_member_scope_postgres.py b/backend/tests/integration/test_all_projects_member_scope_postgres.py index 3775eecee..67fb80cb3 100644 --- a/backend/tests/integration/test_all_projects_member_scope_postgres.py +++ b/backend/tests/integration/test_all_projects_member_scope_postgres.py @@ -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 @@ -26,6 +29,7 @@ from types import SimpleNamespace import pytest +from sqlalchemy import delete from tests.integration.defect_w06_world import defect_world @@ -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 diff --git a/backend/tests/integration/test_perf_runs_statement_counts_postgres.py b/backend/tests/integration/test_perf_runs_statement_counts_postgres.py index bd7a65183..41a51ff68 100644 --- a/backend/tests/integration/test_perf_runs_statement_counts_postgres.py +++ b/backend/tests/integration/test_perf_runs_statement_counts_postgres.py @@ -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 @@ -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) diff --git a/backend/tests/integration/test_subject_erasure_postgres.py b/backend/tests/integration/test_subject_erasure_postgres.py index 6dbfe0531..b54ac698e 100644 --- a/backend/tests/integration/test_subject_erasure_postgres.py +++ b/backend/tests/integration/test_subject_erasure_postgres.py @@ -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) diff --git a/backend/tests/test_membership_cache_signing.py b/backend/tests/test_membership_cache_signing.py deleted file mode 100644 index 47b197c45..000000000 --- a/backend/tests/test_membership_cache_signing.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Regression: the project-membership Redis cache must be tamper-evident. - -Security finding (F3): ``get_accessible_project_ids`` returned the project IDs -read from the ``membership:{user_id}`` Redis key as the request's authorization -scope *without* revalidating against Postgres on a hit. Anyone able to write -Redis could set ``membership:{their_id}`` to arbitrary project UUIDs and read -across tenants, defeating the ``project_id`` WHERE-clause isolation. - -The cache values are now HMAC-signed (keyed by APP_SECRET_KEY, bound to the -user id). A poisoned, forged, cross-user, or legacy/plain entry fails -verification and is treated as a cache miss — the DB stays authoritative — so -the cache can never *widen* a user's scope even if Redis is writable. -""" -from __future__ import annotations - -import json -import uuid - -from app.core.deps import ( - _membership_signature, - _sign_membership_cache, - _verify_membership_cache, -) - - -def test_signed_value_round_trips(): - uid = uuid.uuid4() - pids = {uuid.uuid4(), uuid.uuid4()} - signed = _sign_membership_cache(uid, pids) - assert _verify_membership_cache(uid, signed) == pids - - -def test_signed_value_round_trips_from_bytes(): - """Redis returns bytes — the verifier must decode them.""" - uid = uuid.uuid4() - pids = {uuid.uuid4()} - signed = _sign_membership_cache(uid, pids).encode("utf-8") - assert _verify_membership_cache(uid, signed) == pids - - -def test_tampered_payload_is_rejected(): - """Adding a project id to a validly-signed blob breaks the HMAC.""" - uid = uuid.uuid4() - signed = _sign_membership_cache(uid, {uuid.uuid4()}) - blob = json.loads(signed) - # Attacker widens scope by appending a project id, keeping the old sig. - blob["p"] = json.dumps([str(uuid.uuid4()), str(uuid.uuid4())]) - assert _verify_membership_cache(uid, json.dumps(blob)) is None - - -def test_forged_signature_is_rejected(): - uid = uuid.uuid4() - poisoned = json.dumps({"p": json.dumps([str(uuid.uuid4())]), "s": "deadbeef"}) - assert _verify_membership_cache(uid, poisoned) is None - - -def test_cross_user_replay_is_rejected(): - """A blob validly signed for user A must NOT verify under user B's key — - the signature is bound to the user id.""" - user_a, user_b = uuid.uuid4(), uuid.uuid4() - signed_for_a = _sign_membership_cache(user_a, {uuid.uuid4()}) - assert _verify_membership_cache(user_a, signed_for_a) is not None - assert _verify_membership_cache(user_b, signed_for_a) is None - - -def test_legacy_plain_list_is_rejected(): - """A pre-signing value (a bare JSON array) has no signature → treated as a - miss so the DB re-populates it in the new signed format.""" - legacy = json.dumps([str(uuid.uuid4()), str(uuid.uuid4())]) - assert _verify_membership_cache(uuid.uuid4(), legacy) is None - - -def test_garbage_is_rejected(): - for bad in ("not-json", "", "{}", json.dumps({"p": "not-a-list", "s": "x"})): - assert _verify_membership_cache(uuid.uuid4(), bad) is None - - -def test_signature_is_user_bound(): - """Sanity: the raw signature differs per user for the same payload.""" - payload = json.dumps([str(uuid.uuid4())]) - assert _membership_signature(uuid.uuid4(), payload) != _membership_signature( - uuid.uuid4(), payload - ) diff --git a/backend/tests/test_membership_scope_authority.py b/backend/tests/test_membership_scope_authority.py new file mode 100644 index 000000000..75037e200 --- /dev/null +++ b/backend/tests/test_membership_scope_authority.py @@ -0,0 +1,67 @@ +"""Regression: project membership authorization must come from Postgres. + +Redis membership entries used to remain authoritative for five minutes after +revocation when invalidation failed or an in-flight cache fill raced the +delete. These checks pin the shared authorization boundary to the current +``project_members`` rows and preserve the established member/admin results. +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from app.core.deps import get_accessible_project_ids +from app.models.postgres import UserRole + + +class _Rows: + def __init__(self, rows): + self._rows = rows + + def all(self): + return self._rows + + +def _user(role: UserRole = UserRole.VIEWER): + return SimpleNamespace(id=uuid.uuid4(), role=role) + + +@pytest.mark.asyncio +async def test_removed_membership_ignores_stale_redis(monkeypatch): + """An empty authoritative result cannot be widened by a stale Redis entry.""" + stale_project = uuid.uuid4() + redis = AsyncMock() + redis.get.return_value = f'cached authority for {stale_project}' + monkeypatch.setattr("app.db.redis_client.get_redis", lambda: redis) + db = AsyncMock() + db.execute.return_value = _Rows([]) + + assert await get_accessible_project_ids(db, _user()) == set() + redis.get.assert_not_awaited() + redis.set.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_current_memberships_are_returned(monkeypatch): + """Current Postgres memberships retain the ordinary non-admin read scope.""" + project_id = uuid.uuid4() + redis = AsyncMock() + monkeypatch.setattr("app.db.redis_client.get_redis", lambda: redis) + db = AsyncMock() + db.execute.return_value = _Rows([(project_id,)]) + + assert await get_accessible_project_ids(db, _user()) == {project_id} + redis.get.assert_not_awaited() + redis.set.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_admin_scope_remains_unrestricted(): + """Instance administrators retain the established unrestricted sentinel.""" + db = AsyncMock() + + assert await get_accessible_project_ids(db, _user(UserRole.ADMIN)) is None + db.execute.assert_not_awaited() diff --git a/backend/tests/test_phase3_performance.py b/backend/tests/test_phase3_performance.py index 62eeb3e15..a1d99232d 100644 --- a/backend/tests/test_phase3_performance.py +++ b/backend/tests/test_phase3_performance.py @@ -3,7 +3,7 @@ Covers: P3-1: Parallelized run intelligence queries - P3-2: Redis membership caching + invalidation + P3-2: Legacy Redis membership cleanup P3-3: Composite index existence in ORM model P3-4: Pagination on list endpoints P3-5: Pool configuration @@ -29,13 +29,6 @@ ) -class TestMembershipCacheTTL: - def test_ttl_is_300_seconds(self): - # Lazy import to avoid pulling in bcrypt/PyJWT on systems without them - deps = pytest.importorskip("app.core.deps") - assert deps._MEMBERSHIP_CACHE_TTL == 300 - - class TestInvalidateMembershipCache: @pytest.mark.asyncio async def test_invalidate_calls_redis_delete(self): diff --git a/user-guide/compliance.md b/user-guide/compliance.md index 5dfa8632a..6582d87f4 100644 --- a/user-guide/compliance.md +++ b/user-guide/compliance.md @@ -96,7 +96,7 @@ Three facts apply to almost every row and are stated once here instead of repeat | Criterion | What TestLookup provides | Where to see it | Honest limits | |---|---|---|---| -| **CC6.1** — logical access, least privilege | Five ordered global roles (VIEWER < TESTER < QA_ENGINEER < QA_LEAD < ADMIN), new users default to VIEWER. Project membership is a second boundary on top of the role. Every route carrying a resource id depends on a matching guard, and an architectural test fails CI if a new scoped route is added without one. API keys are stored hashed and can be pinned to a single project. | `UserRole` and `ProjectMember` in `backend/app/models/postgres.py`; `require_role` / `require_project_role` / `require_project_access` / `require_run_access` and the per-resource guards in `backend/app/core/deps.py`; the ratchet in `backend/tests/test_architectural_authorization.py`; `api_keys.key_hash` and `/settings/api-keys`. | TOTP MFA is available in the application (see CC6.1 — authentication strength) but an **API key remains a single-factor path** into an MFA-required account; there is no switch to forbid key creation for privileged roles. ADMIN is a global role and **bypasses the per-project membership check by design**, so ADMIN is your most sensitive grant. The guard ratchet carries three documented exemptions (the SSE stream endpoint and two stream-session routes) that perform the membership check inline instead of via a dependency. | +| **CC6.1** — logical access, least privilege | Five ordered global roles (VIEWER < TESTER < QA_ENGINEER < QA_LEAD < ADMIN), new users default to VIEWER. Project membership in PostgreSQL is a second boundary on top of the role and is read on every user-scope authorization request; Redis membership-key deletion is legacy cleanup, not authority. Every route carrying a resource id depends on a matching guard, and an architectural test fails CI if a new scoped route is added without one. API keys are stored hashed and can be pinned to a single project. | `UserRole` and `ProjectMember` in `backend/app/models/postgres.py`; `get_accessible_project_ids`, `invalidate_membership_cache`, `require_role` / `require_project_role` / `require_project_access` / `require_run_access` and the per-resource guards in `backend/app/core/deps.py`; the ratchet in `backend/tests/test_architectural_authorization.py`; `api_keys.key_hash` and `/settings/api-keys`; [SECURITY.md](../architecture/SECURITY.md) §2. | TOTP MFA is available in the application (see CC6.1 — authentication strength) but an **API key remains a single-factor path** into an MFA-required account; there is no switch to forbid key creation for privileged roles. ADMIN is a global role and **bypasses the per-project membership check by design**, so ADMIN is your most sensitive grant. The guard ratchet carries three documented exemptions (the SSE stream endpoint and two stream-session routes) that perform the membership check inline instead of via a dependency. During a rolling deployment, every read-serving replica must run the PostgreSQL-authoritative code before you rely on this path; legacy Redis deletion exists only to clean up keys that older replicas may leave. | | **CC6.1** — authentication strength | Passwords bcrypt-hashed with a per-password salt, minimum 8 characters enforced at the schema. **TOTP MFA** with single-use hashed recovery codes, enrollment confirmed before it is enabled, and a workspace policy that can require it for a role and every role above it. **Account lockout** after N consecutive failed attempts (default 10, 15-minute cooldown), counted in Postgres so it is global across workers. JWT access + refresh tokens with a revocation denylist in Valkey (the Redis-compatible cache) plus a per-user "valid from" cutoff, so logout and password change invalidate live tokens immediately. Login / register / refresh are rate-limited (10 / 5 / 30 per minute in production). | `backend/app/core/security.py`; `backend/app/services/mfa_service.py`; `/api/v1/auth/mfa/*` and `/api/v1/settings/mfa-policy`; `backend/app/core/token_revocation.py`; `_AUTH_RATE_LIMITS` in `backend/app/main.py`. | No password complexity, history, or expiry policy — length is the only rule; enforce the rest through your IdP. **MFA is off by default** and must be enabled per workspace. SSO-authenticated sessions are exempt from local MFA on the assumption the IdP performs it. Revocation **fails closed**: if Valkey is unavailable requests are refused with 503 rather than accepting a possibly-revoked token, so **a Valkey outage is an authentication outage** (escape hatch: `AUTH_REVOCATION_FAIL_OPEN=true`). Access tokens default to 720 minutes (12 h) — shorten `JWT_ACCESS_TOKEN_EXPIRE_MINUTES` if your policy demands it. Rate limits are per client IP, not per account; lockout is per account. | | **CC6.2 / CC6.3** — provisioning, modification, de-provisioning | Real SAML 2.0 SSO with IdP-group → role mapping, a configurable default role, and JIT provisioning. Real SCIM 2.0 user lifecycle (create / read / list / update / patch / deactivate) authenticated by dedicated SCIM tokens. Every SSO and SCIM event — including failed logins and admin fallback logins — is recorded with actor, IP, success flag, and error. | `/settings/sso`; `sso_configurations` (`role_mapping`, `default_role`, `group_attribute`, `enforcement_mode`); `POST/GET/PUT/PATCH/DELETE /api/v1/scim/v2/Users`, `/api/v1/scim-tokens`, `scim_tokens`; `identity_events` and `GET /api/v1/identity/events`. | SCIM covers **`/Users` only** — there is no `/Groups` endpoint and no SCIM discovery endpoints (`ServiceProviderConfig`, `ResourceTypes`, `Schemas`), so some IdPs need manual configuration and group-driven roles have to go through SAML attribute mapping instead. User accounts are **deactivated, never hard-deleted** (`PATCH /api/v1/users/{id}/status`); the record and its audit history remain. A person can also be **erased — pseudonymised in place — on request** by an administrator; the row stays, as "Erased user", and its audit history is kept (see [Personal data: access, portability and erasure](#personal-data-access-portability-and-erasure)). | | **CC6.6 / CC6.7** — boundary protection and transmission | `AI_OFFLINE_MODE` defaults to true and is a hard kill-switch checked *before* any feature flag in every outbound integration, so a default install sends nothing off-box. Customer-supplied URLs that are fetched when integrations are on go through a domain allowlist. Integration credentials are encrypted at rest with Fernet keys derived from `APP_SECRET_KEY` (PBKDF2-HMAC-SHA256, 100 000 iterations), with rotation via a previous-key slot, failing closed on an empty or default key in production. Kubernetes deploys include a NetworkPolicy. | `AI_OFFLINE_MODE` in `backend/app/core/config.py`; the gates in `services/defect_jira_service.py`, `services/defect_promotion_service.py`, `routers/webhooks_outbound.py`, `services/github_checks_service.py`, `services/codeowners_service.py`, `agents/fixer/pipeline.py`, `agents/investigator/*`; `services/secret_service.py`; `k8s/base/networkpolicy.yaml`. | **TLS is inherited from your deployment target** — the OpenShift overlay uses Routes with edge TLS, others rely on your ingress; there is **no in-cluster mTLS** between backend, workers, and datastores. Encryption covers *secrets only*, not bulk data (see [What TestLookup does NOT provide](#what-testlookup-does-not-provide)). Note the split control surface: LLM egress is gated by the effective AI config, which an in-app override (Settings → AI, QA_LEAD or above) can flip **without an environment change**, whereas the Jira / webhook / GitHub / GitLab kill-switches read the environment setting only. If offline operation is a hard requirement, pin `AI_OFFLINE_MODE=true` in the environment, restrict who holds QA_LEAD/ADMIN, and back it with network egress policy. | @@ -118,7 +118,7 @@ Roles first, because every row depends on them: in a self-hosted deployment **yo | **Art. 5(1)(e)** — storage limitation | The strongest row in this table. Four independent retention clocks (raw events, runs, artifacts, audit) purge across PostgreSQL, MongoDB, and object storage, with a dry-run preview that shows exactly what would go, a nightly sweep at 02:00 UTC for enabled projects, and an audit record of every execution. The audit class is validated to be at least as long as the runs class, so audit records always outlive what they describe. | `/settings/retention`; `POST /api/v1/projects/{id}/retention-policy/preview`; `backend/app/services/retention_service.py`; [Data retention & purge](administration.md#data-retention--purge). | **Disabled by default** — an unconfigured instance keeps everything forever, and an auditor will ask why. Retention is **project-scoped and time-based**, never subject-scoped: it expires old data, it cannot find and remove one person's data. `settings_audit_log` has **no retention window at all** by design. Compliance packs survive until their own expiry (default ~7 years). Some MongoDB pipeline events become unreachable once their parent run has been cascaded away by an earlier sweep — the service documents this as a known v1 limitation. | | **Art. 15 / Art. 20** — access and portability | A **per-person export**: a person downloads everything TestLookup holds about them from **Settings → Profile → Your data**, and an administrator can export any person from **Settings → Users → Personal data**. The archive is a signed ZIP of JSON files (machine-readable, so it also serves portability), available for 72 hours. Audit and identity history for a given actor can still be queried and exported as before. | `POST /api/v1/me/data-export`, `GET /api/v1/me/data-exports`; `POST /api/v1/users/{id}/data-export`, `GET /api/v1/users/{id}/data-jobs`; `GET /api/v1/subject-data-jobs/{id}` and `/download`; `subject_rights_jobs`; requests and downloads recorded in `access_audit_logs`. See [Personal data](#personal-data-access-portability-and-erasure). | The export is the account's data. Text that **names** the person inside other people's records (a comment that mentions them by full name) is not searched for, and CI-supplied handles are not account data. Answering the request — checking who is asking, and sending the archive — is your process; the product sends no mail. | | **Art. 17** — erasure | A **per-person erasure**: an administrator erases a person from **Settings → Users → Personal data** after reading a preview of what changes, what is kept and why, and typing the username to confirm. The person is signed out and disabled at once; their name, username and e-mail become a pseudonym everywhere; their sessions, keys, preferences, inbox and chat history are deleted. Project-level disposal also exists: the retention purge (aging) and the ADMIN-only project reset with typed-name confirmation (`runs` or `full` mode). Archiving a project (`DELETE /api/v1/projects/{id}`) hides it and revokes its credentials. | `GET /api/v1/users/{id}/erasure-preview`, `POST /api/v1/users/{id}/erasure`; `users.erased_at`; `POST /api/v1/projects/{id}/reset`; `/settings/project-data`; `POST /api/v1/projects/{id}/retention-policy/purge`. See [Personal data](#personal-data-access-portability-and-erasure). | Erasure **keeps the audit records**, with the actor's stored name, under Art. 17(3)(b) and (e) — see [what is kept and why](#what-is-kept-and-why); your organisation confirms that basis applies to it. Only an administrator runs it, and it is irreversible; a person may ask for it (`POST /api/v1/me/erasure-request`), and administrators review the requests on **Settings → Users → Erasure requests**. Checking the requester's identity and any legal hold first is your step. Archiving a project removes no data. | -| **Art. 25** — data protection by design and by default | Defaults are the safe ones and are enforced at startup: production environment by default, dev auto-login absent unless explicitly enabled, a boot-time refusal on default or guessable secrets, an authenticated Valkey cache with HMAC-signed authorization cache entries, and offline mode on. Redaction boundaries are named and enforced by a CI gate. | `.env.example` and `Settings.critical_security_failures` in `backend/app/core/config.py`; `_sign_membership_cache` in `core/deps.py`; `services/privacy_service.py`; `scripts/quality_gate.py`; [SECURITY.md](../architecture/SECURITY.md) §4. | By-design is an argument you make about your own processing, not a product feature you can point at alone. These defaults support it; they do not constitute a DPIA. | +| **Art. 25** — data protection by design and by default | Defaults are the safe ones and are enforced at startup: production environment by default, dev auto-login absent unless explicitly enabled, a boot-time refusal on default or guessable secrets, PostgreSQL-authoritative project membership checks, an authenticated Valkey service, and offline mode on. Redis membership-key deletion remains legacy cleanup and is not used to authorize reads. Redaction boundaries are named and enforced by a CI gate. | `.env.example` and `Settings.critical_security_failures` in `backend/app/core/config.py`; `get_accessible_project_ids` and `invalidate_membership_cache` in `core/deps.py`; `services/privacy_service.py`; `scripts/quality_gate.py`; [SECURITY.md](../architecture/SECURITY.md) §§2 and 4. | By-design is an argument you make about your own processing, not a product feature you can point at alone. These defaults support it; they do not constitute a DPIA. Complete a rolling deployment across every read-serving replica before treating the PostgreSQL authorization path as active cluster-wide. | | **Art. 30** — records of processing | Configuration and secret changes, access and role changes, test-management actions, identity events, and release decisions are all recorded with actor and timestamp, queryable and exportable in one place. | `settings_audit_log`, `access_audit_logs`, `test_case_audit_logs`, `identity_events`; `/settings/audit` and `GET /api/v1/audit-dashboard/export`. | These are *activity* logs, not an Art. 30 register — the register itself (purposes, categories, recipients, transfer basis) is a document you maintain. `settings_audit_log` records **field names only, never secret values**, which is right for security and means the log tells you *that* a credential changed, not to what. | | **Art. 32** — security of processing | Encryption of stored credentials, pseudonymised access via role- and project-scoped authorization, resilience through backup/restore with a migration-safety gate, and CI-enforced invariants that stop the security properties regressing. | `services/secret_service.py`; `core/deps.py` guards + `backend/tests/test_architectural_authorization.py`; `scripts/ops/`; `scripts/quality_gate.py`; [SECURITY.md](../architecture/SECURITY.md). | Art. 32 explicitly names encryption of personal data — and **bulk data at rest is not encrypted by the application**. That control belongs to your storage layer and you must configure it. Regular testing of restore (Art. 32(1)(d)) is a process you run; the scripts make it possible, nothing schedules it. | | **Art. 44+** — international transfers | Genuinely strong here. Offline mode is the default and is a hard kill-switch above every feature flag, so a default installation performs **no transfer of any kind** — no LLM API call, no webhook, no external fetch. Local LLM inference runs through Ollama inside your own network, and the air-gapped overlay mirrors every image locally. | `AI_OFFLINE_MODE` and its gate sites (listed under CC6.6 above); [SECURITY.md](../architecture/SECURITY.md) §5; `k8s/overlays/openshift-artifactory/`; [Air-gapped install](air-gapped-install.md) and [Offline model pack](offline-model-pack.md). | The transfer story holds **only while offline mode stays on**. Enabling a cloud LLM provider or an outbound integration creates a transfer you must have a basis for, and the in-app AI override can enable cloud LLM calls without an environment change (see CC6.6). Treat the environment variable plus egress policy as the real control, and the UI toggle as a convenience. |