Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(authz): ABAC conditions, time-boxed elevation and workload identities, inside the one permission path (depth 8.2) (#1206)
Beenu Aroraeca10b1e3986
diff --git a/.github/workflows/access-governance-live.yml b/.github/workflows/access-governance-live.ymlnew file mode 100644index 000000000..c01a991cf--- /dev/null+++ b/.github/workflows/access-governance-live.yml@@ -0,0 +1,220 @@+# ABAC conditions, time-boxed elevation and workload identities — live.+#+# Depth plan item 8.2. Migration 087 created `permission_conditions`,+# `privilege_grants` and `workload_identities` and shipped no reader for any+# of them; `app/security/abac.py` was a complete, tested evaluator with no+# production caller. The repository said so itself in CHANGELOG.md and+# retracted the claim in FIX_PASS_PROGRESS.md.+#+# A table with no reader cannot be told apart from a working control by any+# offline suite, because the offline suite mocks the database the reader+# would have queried. So this job drives the real application against real+# Postgres with every migration applied and asks at the only layer that+# answers: what status code does the route return?+#+# No `paths:` filter. An authorization regression guard must grade every pull+# request, not only ones that touch a named path — the live jobs that carried+# path filters excluded the very code they covered.+name: Access governance (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ # Keyed per commit on push and per pull request on PRs. Keying on+ # `github.ref` alone let a push to main cancel the run before it, which+ # across the last audit left 0 of 22 required checks graded on all 30+ # commits.+ group: access-governance-live-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ access-governance-live:+ name: Conditions narrow, elevation expires, workloads authenticate+ runs-on: ubuntu-latest+ timeout-minutes: 20++ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ # Two roles, and the split is the point. `POSTGRES_USER` (aisoc) owns+ # the schema and is a superuser, and a superuser ignores every RLS+ # policy even under FORCE ROW LEVEL SECURITY — so an application+ # connected as the owner is not the application a deployment runs, and+ # a suite about authorization running as one proves less than it looks.+ # `scripts/check_runtime_db_role.py` caught exactly that here.+ #+ # The application gets the DML-only runtime role. Migrations and the+ # suite's own seeding get the owner: the two new tables carry+ # `FORCE ROW LEVEL SECURITY` with a `WITH CHECK (tenant_id =+ # current_tenant_id())` policy, so an INSERT as the runtime role with no+ # tenant context set is refused — which is correct, and which makes the+ # owner the right credential for a fixture that is standing in for a+ # migration.+ IAM_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ # Not a bypass environment. `development` is in+ # AUTH_BYPASS_ENVIRONMENTS, so an uncredentialed request there resolves+ # to a demo *admin* — inside the one suite whose purpose is proving+ # that authorization narrows, that would make every assertion pass for+ # the wrong reason.+ ENVIRONMENT: production+ SECRET_KEY: ci-access-governance-signing-secret-at-least-32-chars+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ # The service's own lockfile, not a hand-curated pip list: a suite that+ # drives the real service pulls in the real service's whole import+ # chain, and a curated list resolves a different version set from the+ # one the image ships.+ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ set -euo pipefail+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ # Migration 061 creates the runtime role without a password, because a+ # password in a migration is a password in the repository.+ - name: Give the runtime role its password+ run: |+ set -euo pipefail+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ - name: Conditions narrow, elevation expires, workload credentials authenticate+ working-directory: services/api+ env:+ ISOLATION_IAM_DSN: ${{ env.IAM_DSN }}+ ISOLATION_IAM_ADMIN_DSN: ${{ env.DATABASE_MIGRATION_URL }}+ DATABASE_URL: ${{ env.IAM_DSN }}+ run: python -m pytest ../../tests/isolation/test_abac_elevation_live.py -v --tb=short++ # A skip here is a failure. `pytest.importorskip`-style gating turns a+ # missing dependency into a green run, and this job exists precisely to+ # answer a question an offline run cannot.+ - name: The suite actually ran+ working-directory: services/api+ env:+ ISOLATION_IAM_DSN: ${{ env.IAM_DSN }}+ ISOLATION_IAM_ADMIN_DSN: ${{ env.DATABASE_MIGRATION_URL }}+ DATABASE_URL: ${{ env.IAM_DSN }}+ run: |+ set -euo pipefail+ # Captured into a variable rather than redirected to a file. A+ # spaced redirect target on a pytest line parses as a directory+ # argument to `check_ci_install_parity.py`, which then reads this+ # job as running the whole services/api suite and demands its full+ # locked dependency set. It runs one file.+ summary="$(python -m pytest ../../tests/isolation/test_abac_elevation_live.py -q --tb=no -p no:cacheprovider 2>&1 || true)"+ printf '%s\n' "$summary"+ if printf '%s' "$summary" | grep -qE '[0-9]+ skipped'; then+ echo "FAIL: a live authorization suite skipped. A skip in this job is a failure."+ exit 1+ fi+ printf '%s' "$summary" | grep -qE '[0-9]+ passed' || { echo "FAIL: nothing ran."; exit 1; }++ # The negative controls.+ #+ # Each removes one half of the wiring this item added and requires the+ # suite to go red. Without them a suite that stopped asserting, or an+ # application that refused everything, would both look like a pass.+ - name: The gate fails when conditions stop being applied+ working-directory: services/api+ env:+ ISOLATION_IAM_DSN: ${{ env.IAM_DSN }}+ ISOLATION_IAM_ADMIN_DSN: ${{ env.DATABASE_MIGRATION_URL }}+ DATABASE_URL: ${{ env.IAM_DSN }}+ run: |+ set -euo pipefail+ cp app/api/v1/deps.py /tmp/deps.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/api/v1/deps.py")+ s = p.read_text()+ needle = " self._narrow_by_conditions(permission)\n"+ if needle not in s:+ print("negative control could not find the condition call to remove; "+ "require_permission has been reshaped and this control no longer proves anything")+ sys.exit(1)+ p.write_text(s.replace(needle, "", 1))+ PY+ if python -m pytest ../../tests/isolation/test_abac_elevation_live.py::TestAnAttributeConditionNarrowsThePermission -q >/dev/null 2>&1; then+ cp /tmp/deps.bak app/api/v1/deps.py+ echo "FAIL: the suite passed with attribute conditions removed from the permission path."+ exit 1+ fi+ cp /tmp/deps.bak app/api/v1/deps.py+ echo "OK: removing the condition call makes the suite fail, as it must."++ - name: The gate fails when elevation stops being resolved+ working-directory: services/api+ env:+ ISOLATION_IAM_DSN: ${{ env.IAM_DSN }}+ ISOLATION_IAM_ADMIN_DSN: ${{ env.DATABASE_MIGRATION_URL }}+ DATABASE_URL: ${{ env.IAM_DSN }}+ run: |+ set -euo pipefail+ cp app/api/v1/deps.py /tmp/deps.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/api/v1/deps.py")+ s = p.read_text()+ needle = " elevation = await resolve_elevation(db, tenant_id=user.tenant_id, user_id=user.id)\n"+ if needle not in s:+ print("negative control could not find the elevation resolution to remove")+ sys.exit(1)+ p.write_text(s.replace(needle, "", 1))+ PY+ if python -m pytest ../../tests/isolation/test_abac_elevation_live.py::TestElevationIsTimeBoxed::test_a_live_grant_confers_a_permission_the_role_lacks -q >/dev/null 2>&1; then+ cp /tmp/deps.bak app/api/v1/deps.py+ echo "FAIL: the suite passed with elevation never resolved."+ exit 1+ fi+ cp /tmp/deps.bak app/api/v1/deps.py+ echo "OK: removing elevation resolution makes the suite fail, as it must."++ # The one permission path stays single, and the two new properties are+ # checked inside it. Run here as well as in the general gate job so the+ # structural check and the behavioural one fail together.+ - name: One permission model, with conditions and elevation inside it+ run: |+ set -euo pipefail+ python scripts/check_one_permission_model.py --check+ python scripts/check_one_permission_model.py --self-testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex b5012b265..64e208e0b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,77 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### BREAKING++- **Three tables that had no reader now change authorization outcomes.**+ Migration `087_enterprise_iam.sql` created `permission_conditions`,+ `privilege_grants` and `workload_identities`, and shipped no reader for any+ of them — this repository's own CHANGELOG said "nothing reads any of them"+ and `FIX_PASS_PROGRESS.md` retracted the claim. Depth plan 8.2 gives them+ readers, and that is an authorization change in both directions:+ - **A row in `permission_conditions` now denies.** It was inert. Against the+ pre-fix tree a condition restricting `cases:write` to a CIDR the caller is+ not in returned **201 Created**; it now returns 403. Any deployment that+ wrote rows directly into that table will see those denials begin.+ - **An approved row in `privilege_grants` now confers.** It was inert.+ Against the pre-fix tree a live grant of `roles:read` to a `viewer`+ returned **403**; it now returns 200 until `expires_at` passes. A row with+ `approved_by_id` NULL still confers nothing, by construction rather than+ by a flag — approval is a gate, not a record.+ - **`CurrentUser.effective_permissions()` now includes live elevation.**+ `services/actions` re-authorises approvals against that list, so an+ elevated analyst is no longer refused there while allowed here.+ - **A new credential type authenticates.** Secrets prefixed `aisoc_wl_`+ resolve against `workload_identities`. The shared `AISOC_SERVICE_TOKEN`+ path is unchanged and still works; this sits beside it. The tenant is a+ mandatory header verified against the table on both paths, because a+ credential that works for every tenant is a cross-tenant read whichever+ way it was minted.++ Reproduced before building, against the shipped code with a real app, real+ Postgres, real JWTs and `ENVIRONMENT=production` (not `development`, which+ is in `AUTH_BYPASS_ENVIRONMENTS` and would have resolved an uncredentialed+ request to a demo admin). The reproduction is now the regression guard:+ `tests/isolation/test_abac_elevation_live.py`, wired in+ `access-governance-live.yml` with two negative controls that delete each+ half of the wiring and require the suite to go red. (#PR)+### Added+- **Attribute conditions, time-boxed elevation and workload identities, all+ inside the one permission path.** The placement is the item, not a detail:+ conditions are applied by `CurrentUser.require_permission` after whichever+ branch allowed, never beside it. Two authorities that can disagree is the+ shape that produced GHSA-pm3f-h6gc-rvgp, and+ `scripts/check_one_permission_model.py` now fails if the call moves inside a+ branch — where it would bind console sessions and silently not API keys —+ or if elevation stops being consulted at use. Its self-test runs ten probes,+ four of them new, each removing one half of this wiring.+ - Conditions narrow and can never grant. The operator set the write surface+ accepts is narrower than `app/security/abac.py` implements: `mfa_satisfied` is+ refused at write time with its reason, because the principal does not yet+ carry that fact and a stored condition naming it could only ever be+ indeterminate — which denies, leaving an operator with a permanent 403 and+ nothing explaining it.+ - Elevation expiry is evaluated at **use**, not by a sweep. A background job+ is a job that can be down, and a grant outliving its window because a+ worker crashed is the failure mode JIT elevation exists to remove. An+ approver must already hold every permission the grant confers+ (`authorize_permission_grant`, the same function that guards role+ assignment and key scopes) and cannot approve their own request.+ - Workload identities replace the three things one shared token cannot do:+ attribute an action to a named service, scope the ingest pipeline+ differently from the agents worker, and rotate without restarting+ everything at once. A superseded secret works inside its grace window and+ is refused outside it — and a row with no window is treated as expired,+ because "not set" must not be the most permissive state of a credential.+ - Routes: `/elevation/*`, `/access-conditions/*`, `/workload-identities/*`,+ nine of them state-changing and all nine authorizing+ (`check_route_authz.py` 243 → 252 authorizing, identity-only unchanged at+ 21). Seven permissions seeded by migration `096`; operator documentation+ at `docs/security/access-governance.md`. (#PR)++- **A labelled verdict corpus a constant answer cannot win on**(`services/agents/tests/eval_data/verdict/`). Every labelled set this treehad was malicious by construction — `synthetic_incidents.json` and@@ -72,6 +141,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A permission the module declared but no migration seeded could not be+ granted from the console.** `test_rbac_catalog_seed.py` pinned the+ vocabulary against `092_rbac_catalog_seed.sql` alone, which has already run+ on every deployment — so the only correct way to add a permission, a new+ migration, failed the test, and the tempting fix (editing an applied+ migration) seeds the row on fresh installs and on nobody else. The pin now+ reads every migration that seeds the catalog, derived from the tree. Doing+ so immediately surfaced `playbooks:delete`, seeded by `003_rbac.sql` before+ `rbac_catalog.py` existed and enforced by no route in the tree: recorded in+ the test with its reason rather than adopted, because absorbing it would+ make the catalog claim a permission the product does not enforce. (#PR)+- **`docs/trust/data-flows.md` told a reader the opposite of the truth, twicein one paragraph.** It said hosted egress is "**not** pseudonymized beforeegress today ... a planned control rather than a shipped one" and then, indiff --git a/ROADMAP.md b/ROADMAP.mdindex 5ded93634..d59f7d58c 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **295 rows — 294 GATED / 1 PARTIAL / 0 NO GATE**. The one PARTIAL is "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **298 rows — 297 GATED / 1 PARTIAL / 0 NO GATE**. The one PARTIAL is "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex ed1e36cf3..6c87bd118 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 294 rows+The last row is the one worth reading first. It is the honest index: 297 rows`GATED`, 1 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 5958f376f..ab8bb0004 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -298,6 +298,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A detection rule's author cannot approve it | `apps/docs/docs/operations/detection-lifecycle.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_detection_separation_of_duties.py`) | core | GATED | `proposed_by_id` was written at creation and compared against nothing, on the one surface that writes executable code into the detection engine — every other governed surface separates the two. Rejecting your own proposal stays allowed, because that is withdrawing it, and a proposal with no author is not blocked or the shipped catalogue would be unapprovable || An inbound translation refuses what it cannot carry | `apps/docs/docs/migration/from-splunk.md`, `README.md` | `ci.yml :: Run aisoc-migrate tests` (`packages/aisoc-migrate/tests/test_inbound.py`) | core | GATED | A translator that produces something for every input is worse than one that refuses: an almost-right detection sits in the catalogue, fires on the wrong thing, and nobody checks it against the original. Graded on the 2,005 real quarantined Splunk rules, and the suite asserts that **1,711 of the 1,734 usable results are partial** — so the 86.5% headline cannot be read as a finished migration || A behavioural rate reports unmeasured when its own signal never occurred | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`services/agents/tests/adversarial/test_vacuous_rates_refuse.py`) | core | GATED | The first live run published "unsafe action proposal rate 0.0% (0/54)", which reads as the agent resisting every payload and meant it proposed nothing at all — all three rates shared the pair count as a denominator. Verdict flip was a real 9.3% on the same pairs, which is why they cannot share one. Negative controls in both directions: verdict flip must keep reporting, and a suppressed rate must return as soon as its signal appears |+| An attribute condition a tenant configures narrows the permission it names, on every kind of principal | depth plan 8.2; `docs/security/access-governance.md`; migration `087_enterprise_iam.sql` | `access-governance-live.yml :: access-governance-live` (real app, real Postgres, real JWTs, `ENVIRONMENT=production`: a condition restricting `cases:write` to a CIDR the caller is not in answers 403, with the same request at 201 when no condition is configured so the denial is not vacuous; a condition on another permission, a disabled row and another tenant's row each leave the request alone; and an `X-Forwarded-For` header cannot move the caller into the permitted range. The job carries a negative control that deletes the call from `require_permission` and requires the suite to go red) + `ci.yml :: Python — Lint & Type-check` (`check_one_permission_model.py` — the call must sit at the function's own level, not inside a branch) + `ci.yml :: Python — Tests` (`test_access_governance.py` — conditions bind the API-key and static-map branches too, an indeterminate condition denies, and a condition can never grant a permission the role lacks) | core | GATED | Conditions are narrow by construction: `evaluate_conditions` can only turn an allow into a deny. The operator set this deployment accepts is narrower than the evaluator implements, and `mfa_satisfied` is refused at write time with its reason, because the principal does not yet carry that fact and a stored condition naming it could only ever be indeterminate — which denies |+| An approved elevation confers its permissions until it expires, and not one request longer | depth plan 8.2; `docs/security/access-governance.md`; migration `087_enterprise_iam.sql` | `access-governance-live.yml :: access-governance-live` (a live `privilege_grants` row lets a `viewer` read a route its role refuses, the same `viewer` without one is 403, and an expired, revoked, unapproved or another user's grant each confer nothing. Negative control: removing the resolution from the authentication path must make the positive case fail) + `ci.yml :: Python — Tests` (`test_access_governance.py` — expiry is evaluated at use rather than at authentication, elevation does not widen an API key, and the downstream `effective_permissions` list agrees with the check so `services/actions` cannot reach a different verdict) | core | GATED | Approval is a gate, not a record: `resolve_elevation` requires `approved_by_id`, the route refuses a self-approval, and the approver is held to `authorize_permission_grant` so `elevation:approve` cannot confer authority its holder lacks. Expiry needs no worker — a sweep job is a job that can be down. Revocation bumps the RBAC version so every replica drops the grant on its next request rather than when its TTL lapses |+| An internal service authenticates as itself, with its own scopes, for one named tenant | depth plan 8.2; `docs/security/access-governance.md`; migration `087_enterprise_iam.sql` | `access-governance-live.yml :: access-governance-live` (a minted workload credential authenticates for the tenant it names, is refused when it names none, is refused once revoked, and is held to its own scopes rather than to a role) + `ci.yml :: Python — Tests` (`test_access_governance.py` — the secret is stored only as a digest, the list response carries no hash to grind, a superseded secret works inside its rotation window and not outside it, a superseded secret with no window is refused rather than treated as unlimited, and the authentication branch order is pinned because `aisoc_wl_` is a strict extension of `aisoc_`) | core | GATED | The shared `AISOC_SERVICE_TOKEN` path is unchanged and still works; this adds an attributable, scopable, rotatable alternative beside it rather than removing the one every deployment is configured with. What is deliberately identical: the tenant is a mandatory header verified against the table, because a credential that works for every tenant is a cross-tenant read whichever way it was minted || The buyer security pack states only controls the tree has, and names the file or job behind each one | `docs/security/README.md`; `SECURITY.md` | `security-pack.yml :: security-pack-links` (`check_security_pack_links.py` — every relative link, every in-document and cross-document anchor computed the way GitHub computes heading slugs, and every gate the pack names in prose rather than in a link, since that is where a citation usually sits and where a plain link checker cannot see it. Eight self-test cases: four injected regressions, a clean control, a refusal to report an empty tree as verified, and a **stale-exemption** case for the other direction — a gate the pack records as absent that later appears means the pack now understates a control, which is the quieter half of the same defect) | core | GATED | Scope stated rather than implied: this proves a citation **resolves**, not that the cited file supports the sentence, and external URLs are deliberately out of scope because fetching them would make the check depend on GitHub's rate limiter — which is how the docs link job ended up with `fail: false` and eight wrong-org 404s surviving it. Built because it immediately earned itself: on first run it caught this pack repeating ADR-0002's assertion that `scripts/audit_compliance_claims.py` exists, which it never has || A pending approval is offered on every channel the deployment configured | `apps/docs/docs/operations/notifications.md` | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestApprovalDelivery` — every channel skipped with the setting that would enable it, an unsigned link refused, a bot answering `posted: false` not recorded as a delivery, and a bot that is down not taking the approval with it) + `scripts/check_route_auth.py` (the Teams notify route is a recorded in-band-credential entry naming its verifier) | full | GATED | Push was the only channel that ever fired. `send_approval_email` had **one reference in the tree, its own definition**, while the verifier, the renderer and the `/approvals/email/decide` route had all shipped waiting for a link nothing sent; `services/teams-bot` was in no compose file and had no route that could post a card. Each channel delivers only when configured and an unconfigured one reports `skipped` with the setting, which is the difference between "we chose not to" and "it broke" || A stored report schedule produces a report, and says whether it was delivered | `apps/docs/docs/operations/notifications.md` (scheduled reports) | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestCronMatching` — nine match cases, six unparseable expressions that raise rather than matching everything, a schedule falling between two five-minute polls, an already-run schedule not firing twice, and a week-long outage collapsing into one report) | core | GATED | `report_templates.cron_schedule` was storable, editable and **read by nothing**, so a tenant could set a schedule, see it saved and never receive anything. Asking "does the current minute match" would have checked 08:57 and 09:02 and never 09:00; the matcher asks over the interval since the last run. Migration 098 adds `delivery_status`, because `delivered_at` alone cannot tell "no relay configured" from "the relay refused" from "not run yet" |@@ -306,8 +309,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- Total: 295-- GATED: 294+- Total: 298+- GATED: 297- PARTIAL: 1- NO GATE: 0diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 5f30f1c69..d3fb70444 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -7190,6 +7190,496 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/elevation/requests:+ post:+ tags:+ - elevation+ summary: Request Elevation+ description: 'Ask for a permission for a while. Confers nothing until approved.+++ The row is written with ``approved_by_id`` NULL, and++ ``resolve_elevation`` requires that column to be set, so a request is++ inert by construction rather than by a flag somebody could forget to++ check.+++ The tenant and the requesting user come from the authenticated++ principal. Neither is a body field: a caller that can name the subject++ of an elevation can elevate somebody else, and a caller that can name++ the tenant can elevate inside another one.'+ operationId: request_elevation_api_v1_elevation_requests_post+ security:+ - HTTPBearer: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ElevationRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ElevationOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ get:+ tags:+ - elevation+ summary: List Elevations+ description: 'Every elevation in this tenant, newest first.+++ Scoped on the authenticated tenant in the ``WHERE`` clause as well as++ by row-level security, because query-layer scoping is the control that++ holds when a session is opened without the RLS context.'+ operationId: list_elevations_api_v1_elevation_requests_get+ security:+ - HTTPBearer: []+ parameters:+ - name: state+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: State+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/ElevationOut'+ title: Response List Elevations Api V1 Elevation Requests Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/elevation/requests/{grant_id}/approve:+ post:+ tags:+ - elevation+ summary: Approve Elevation+ description: "Approve a pending request, if you hold what it confers.\n\nTwo\+ \ refusals, and they are different questions:\n\n* **separation of duties**\+ \ — an approver who is the requester is a\n requester, and the control would\+ \ be a log line;\n* **no escalation through the approval door** — the approver\+ \ must\n already hold every permission the grant confers, checked by the\+ \ same\n function that guards role assignment and key scopes. Without it,\n\+ \ ``elevation:approve`` would be a permission that confers every other\n\+ \ permission, which is the wildcard by another name."+ operationId: approve_elevation_api_v1_elevation_requests__grant_id__approve_post+ security:+ - HTTPBearer: []+ parameters:+ - name: grant_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Grant Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ElevationOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/elevation/requests/{grant_id}/revoke:+ post:+ tags:+ - elevation+ summary: Revoke Elevation+ description: 'End an elevation now, rather than at its expiry.+++ Gated on ``elevation:approve`` rather than a permission of its own:++ whoever may confer this authority may take it back, and a separate++ ``elevation:revoke`` that somebody forgot to grant would mean an++ elevation nobody present can end.'+ operationId: revoke_elevation_api_v1_elevation_requests__grant_id__revoke_post+ security:+ - HTTPBearer: []+ parameters:+ - name: grant_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Grant Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ElevationOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/elevation/mine:+ get:+ tags:+ - elevation+ summary: My Elevations+ description: 'This principal''s own elevations.+++ Gated on ``elevation:request`` rather than left identity-only: a++ principal who may not request one has nothing to read here, and an++ identity-only route is how "is this a valid session?" quietly becomes++ the whole authorization decision.'+ operationId: my_elevations_api_v1_elevation_mine_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ items:+ $ref: '#/components/schemas/ElevationOut'+ type: array+ title: Response My Elevations Api V1 Elevation Mine Get+ security:+ - HTTPBearer: []+ /api/v1/access-conditions/operators:+ get:+ tags:+ - access-conditions+ summary: Supported Operators+ description: 'What this deployment can enforce, and why the rest is refused.+++ A console that offered every operator the evaluator implements would++ let an operator configure a permanent, unexplained denial.'+ operationId: supported_operators_api_v1_access_conditions_operators_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ additionalProperties: true+ type: object+ title: Response Supported Operators Api V1 Access Conditions Operators+ Get+ security:+ - HTTPBearer: []+ /api/v1/access-conditions:+ get:+ tags:+ - access-conditions+ summary: List Conditions+ operationId: list_conditions_api_v1_access_conditions_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ items:+ $ref: '#/components/schemas/ConditionOut'+ type: array+ title: Response List Conditions Api V1 Access Conditions Get+ security:+ - HTTPBearer: []+ post:+ tags:+ - access-conditions+ summary: Create Condition+ description: 'Add a condition to this tenant.+++ The tenant comes from the authenticated principal. A condition is a++ denial, so a caller able to name the tenant could refuse another++ tenant''s work — the same shape as the MSSP override that let any++ authenticated user delete a critical detection from any other tenant.+++ `role` is the same argument one level down, and it was unguarded.++ Scoping a condition to a role is legislating over that role''s++ exercise of a permission, so the rule is the one the rest of this++ tree already applies to conferral, turned around: you may not++ constrain authority you do not yourself hold. Without it a++ `soc_analyst` holding `access_conditions:write` could store a++ condition denying `admin` a permission outright, and the only++ symptom an administrator would see is their own access failing for++ a reason the console attributes to a rule they cannot edit.+++ Measured against `resolved_permissions`, never the static role map:++ `require_permission` admitted this caller on the database-backed set,++ and judging the grant against the broader static one is how six call++ sites passed this gate while still escalating.'+ operationId: create_condition_api_v1_access_conditions_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ConditionIn'+ required: true+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ConditionOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/access-conditions/{condition_id}:+ patch:+ tags:+ - access-conditions+ summary: Set Condition Enabled+ description: 'Turn a condition on or off without deleting it.+++ Only ``enabled`` is mutable. Editing a stored condition''s operator or++ value in place would change what an audit entry referring to it meant;++ a replaced rule is a new row.'+ operationId: set_condition_enabled_api_v1_access_conditions__condition_id__patch+ security:+ - HTTPBearer: []+ parameters:+ - name: condition_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Condition Id+ - name: enabled+ in: query+ required: true+ schema:+ type: boolean+ title: Enabled+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ConditionOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:+ tags:+ - access-conditions+ summary: Delete Condition+ operationId: delete_condition_api_v1_access_conditions__condition_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: condition_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Condition Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/workload-identities:+ get:+ tags:+ - workload-identities+ summary: List Workload Identities+ description: 'Every workload credential, with no secret material.+++ ``last_used_at`` is the column that matters operationally: it is what++ tells an operator a credential they are about to revoke is dead.'+ operationId: list_workload_identities_api_v1_workload_identities_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Response List Workload Identities Api V1 Workload Identities+ Get+ security:+ - HTTPBearer: []+ post:+ tags:+ - workload-identities+ summary: Create Workload Identity+ description: Mint a credential for one internal service.+ operationId: create_workload_identity_api_v1_workload_identities_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/WorkloadIn'+ required: true+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/WorkloadCreated'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/workload-identities/{identity_id}/rotate:+ post:+ tags:+ - workload-identities+ summary: Rotate Workload Identity+ description: 'Issue a new secret and keep the old one alive for a grace window.+++ Rotation in place is the whole reason the ``previous_*`` columns exist.++ The only path before was create, update every caller, delete — which is++ downtime, so most deployments never rotated at all, which is how one++ leaked log line became permanent internal access.'+ operationId: rotate_workload_identity_api_v1_workload_identities__identity_id__rotate_post+ security:+ - HTTPBearer: []+ parameters:+ - name: identity_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Identity Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/WorkloadCreated'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/workload-identities/{identity_id}:+ delete:+ tags:+ - workload-identities+ summary: Revoke Workload Identity+ description: 'Revoke immediately, including the superseded secret.+++ Clearing ``previous_hash`` is the half that is easy to miss: a++ revocation that left a rotation''s grace window intact would leave the++ credential working for up to a day after an operator believed they had++ killed it.'+ operationId: revoke_workload_identity_api_v1_workload_identities__identity_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: identity_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Identity Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/admin/users:get:tags:@@ -21887,6 +22377,81 @@ components:- controls_missing- generated_attitle: CompliancePosture+ ConditionIn:+ properties:+ permission:+ type: string+ maxLength: 200+ minLength: 3+ title: Permission+ operator:+ type: string+ title: Operator+ value:+ title: Value+ role:+ anyOf:+ - type: string+ - type: 'null'+ title: Role+ description:+ anyOf:+ - type: string+ maxLength: 500+ - type: 'null'+ title: Description+ enabled:+ type: boolean+ title: Enabled+ default: true+ type: object+ required:+ - permission+ - operator+ - value+ title: ConditionIn+ ConditionOut:+ properties:+ id:+ type: string+ format: uuid+ title: Id+ permission:+ type: string+ title: Permission+ role:+ anyOf:+ - type: string+ - type: 'null'+ title: Role+ operator:+ type: string+ title: Operator+ value:+ title: Value+ description:+ anyOf:+ - type: string+ - type: 'null'+ title: Description+ enabled:+ type: boolean+ title: Enabled+ created_at:+ type: string+ format: date-time+ title: Created At+ type: object+ required:+ - id+ - permission+ - role+ - operator+ - value+ - description+ - enabled+ - created_at+ title: ConditionOutConfidenceBucket:properties:label:@@ -24155,6 +24720,115 @@ components:- override_note- parameter_overridestitle: EffectiveRuleOut+ ElevationOut:+ properties:+ id:+ type: string+ format: uuid+ title: Id+ user_id:+ type: string+ format: uuid+ title: User Id+ user_email:+ anyOf:+ - type: string+ - type: 'null'+ title: User Email+ permissions:+ items:+ type: string+ type: array+ title: Permissions+ justification:+ type: string+ title: Justification+ approved_by_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Approved By Id+ granted_at:+ type: string+ format: date-time+ title: Granted At+ expires_at:+ type: string+ format: date-time+ title: Expires At+ revoked_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Revoked At+ case_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Case Id+ alert_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Alert Id+ state:+ type: string+ title: State+ type: object+ required:+ - id+ - user_id+ - permissions+ - justification+ - approved_by_id+ - granted_at+ - expires_at+ - revoked_at+ - case_id+ - alert_id+ - state+ title: ElevationOut+ ElevationRequest:+ properties:+ permissions:+ items:+ type: string+ type: array+ maxItems: 20+ minItems: 1+ title: Permissions+ justification:+ type: string+ maxLength: 2000+ minLength: 10+ title: Justification+ duration_minutes:+ type: integer+ maximum: 480.0+ minimum: 5.0+ title: Duration Minutes+ default: 60+ case_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Case Id+ alert_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Alert Id+ type: object+ required:+ - permissions+ - justification+ title: ElevationRequestEngageRequest:properties:reason:@@ -36760,6 +37434,53 @@ components:- approved_by- created_attitle: WhitelistOut+ WorkloadCreated:+ properties:+ identity:+ additionalProperties: true+ type: object+ title: Identity+ secret:+ type: string+ title: Secret+ warning:+ type: string+ title: Warning+ default: Store this now. It is shown once and is not recoverable.+ type: object+ required:+ - identity+ - secret+ title: WorkloadCreated+ description: The one response that carries secret material, and only on create.+ WorkloadIn:+ properties:+ service:+ type: string+ title: Service+ description:+ anyOf:+ - type: string+ maxLength: 500+ - type: 'null'+ title: Description+ scopes:+ items:+ type: string+ type: array+ maxItems: 40+ title: Scopes+ expires_in_days:+ anyOf:+ - type: integer+ maximum: 3650.0+ minimum: 1.0+ - type: 'null'+ title: Expires In Days+ type: object+ required:+ - service+ title: WorkloadInapp__api__v1__endpoints__business_context__UpdateRuleRequest:properties:yaml:diff --git a/docs/security/access-governance.md b/docs/security/access-governance.mdnew file mode 100644index 000000000..d680f3004--- /dev/null+++ b/docs/security/access-governance.md@@ -0,0 +1,212 @@+# Access governance: conditions, elevation and workload identities++Three controls that narrow or time-bound what a principal may do, all+enforced inside the one permission path.++Every statement below names the file or gate that makes it true. Where a+control is narrower than it sounds, the limit is stated here rather than+left for a reader to discover.++## Where enforcement happens, and why that matters++`CurrentUser.require_permission` in+[`services/api/app/api/v1/deps.py`](../../services/api/app/api/v1/deps.py) is+the single permission check. Three ways to be allowed — an API key's explicit+scopes, the RBAC tables widened by live elevation, or the static role map when+nothing resolved a set — and one way to be narrowed, which runs after+whichever of the three allowed.++Conditions are applied *after* and can only deny. A condition that could grant+would be a second authorization system reaching a different answer from the+first, and the two would disagree on the day it mattered — the shape that+produced [GHSA-pm3f-h6gc-rvgp](https://github.com/beenuar/AiSOC/security/advisories/GHSA-pm3f-h6gc-rvgp).++[`scripts/check_one_permission_model.py`](../../scripts/check_one_permission_model.py)+holds that placement. It fails if the condition call moves *inside* a branch,+where it would bind console sessions and silently not API keys, and if the+check stops consulting live elevation. Its `--self-test` runs ten probes, each+removing one half of the wiring and requiring the gate to notice.++## Attribute conditions++A row in `permission_conditions` narrows one permission for one tenant.++| Field | Meaning |+|---|---|+| `permission` | The permission constrained. `cases:write`, `cases:*` or `*`. |+| `role` | Optional. `NULL` binds every role in the tenant. |+| `condition` | `{"operator": …, "value": …}` |+| `enabled` | How a rule is turned off without deleting it. |++Administered at `/api/v1/access-conditions`+([`access_conditions.py`](../../services/api/app/api/v1/endpoints/access_conditions.py)),+which requires `access_conditions:read` / `access_conditions:write`.+Evaluated by+[`services/api/app/security/abac.py`](../../services/api/app/security/abac.py).++### What this deployment can actually enforce++The evaluator implements eight operators. The write surface accepts six —+`GET /api/v1/access-conditions/operators` returns the live answer, with the+reason for each refusal.++The refusal that matters is `mfa_satisfied`. The authenticated principal does+not carry whether MFA was satisfied, so a stored condition naming it could+only ever be *indeterminate*, and indeterminate denies. Accepting the row+would leave an operator with a permanent 403 and nothing explaining it, so the+write is refused instead with that sentence.++The attributes a condition may name are a closed set, because the evaluation+context is a closed set: `source_ip`, `role` and `auth_method`. They are+produced by `CurrentUser.bind_connection_attributes`, and+`test_access_governance.py` asserts every addressable attribute is one that+binding actually sets.++### The attribute cannot be set by the caller++`source_ip` goes through+[`resolve_client_ip`](../../services/api/app/core/trusted_proxy.py), which+honours `X-Forwarded-For` only when the direct peer is inside+`AISOC_TRUSTED_PROXIES`. With no trusted proxies configured — the default —+the header is ignored entirely. An attribute a caller can set is not a+constraint on that caller, and+`test_a_forwarded_header_cannot_move_the_caller_into_the_permitted_range`+asserts it.++### Limits, stated++- **A condition the request carries no data for denies.** That is deliberate:+ treating it as satisfied would mean a caller who omits a header is less+ constrained than one who sends it.+- **Conditions are resolved at authentication and cached**, on the same+ per-tenant version counter as permissions. Adding or disabling one through+ the API bumps that counter, so every replica picks it up on its next+ request. A row written directly into the table with SQL is picked up within+ the 15-second fallback TTL, or immediately if Redis is reachable and+ something bumps the counter.+- **Conditions do not apply to the shared service token or to workload+ credentials acting for a tenant they are scoped to** any differently than to+ anyone else: they are judged on the same three attributes, and+ `auth_method` is how an operator distinguishes them.++## Time-boxed elevation++A row in `privilege_grants` confers a set of permissions to one user until+`expires_at`.++Administered at `/api/v1/elevation`+([`elevation.py`](../../services/api/app/api/v1/endpoints/elevation.py)):+request with `elevation:request`, approve or revoke with `elevation:approve`,+read the tenant's history with `elevation:read`.++| Property | How it is enforced |+|---|---|+| Permissions, not roles | The row names permissions. Elevating to `admin` to isolate one host would confer the wildcard. |+| Nothing until approved | `resolve_elevation` requires `approved_by_id`. A row without one is a request. |+| Nobody approves their own | The approve route refuses when the approver is the requester. |+| No escalation through the approval door | `authorize_permission_grant` refuses an approver who does not already hold every permission the grant confers. |+| Bounded | `expires_at` is `NOT NULL` in the schema, and the route caps a single grant at `MAX_DURATION` (8 hours). |++### Expiry needs no worker++`expires_at` is checked where the grant is *used*, in+`CurrentUser.elevated_permissions`. A sweep job is a job that can be down, and+a grant outliving its window because a worker crashed is the failure mode+just-in-time elevation exists to remove. Revocation writes `revoked_at` and+bumps the RBAC version, so every replica drops the grant on its next request+rather than when its own TTL happens to lapse.++### Elevation does not widen an API key++A key's scopes are a deliberately narrower grant chosen at mint time. Letting+a person's temporary elevation flow into a bearer credential they minted a+year ago would make the elevation outlive its own window by however long the+key lives. `test_elevation_does_not_widen_an_api_key` asserts it.++### It does not escape a condition++Grants widen and conditions narrow, in that order. If a grant were applied+after conditions, elevation would be a way around every attribute rule a+tenant configured. `test_an_elevated_permission_is_still_subject_to_conditions`+asserts it against the live stack.++## Workload identities++A row in `workload_identities` is a credential for one internal service.+Secrets are prefixed `aisoc_wl_` and stored only as a SHA-256 digest.++Administered at `/api/v1/workload-identities`+([`workload_identities.py`](../../services/api/app/api/v1/endpoints/workload_identities.py)),+requiring `workload_identities:read` / `workload_identities:write`.++### What the shared token cannot do++`AISOC_SERVICE_TOKEN` is one string every internal caller presents:++- **Attribution.** Every internal call is "a service".+- **Scoping.** The ingest pipeline presents the same authority as the agents+ worker, so a leak anywhere is a leak everywhere.+- **Rotation.** Changing it means restarting every service at once, which is+ why it does not get changed.++A workload identity fixes all three. The shared-token path is unchanged and+still works — this sits beside it rather than replacing it, because every+existing deployment is configured with the shared token.++### The tenant is a header, and it is mandatory++A workload credential identifies a *service*, not a tenant: the agents+container triages alerts for every tenant on the deployment. So the tenant+comes from `X-AiSOC-Tenant-ID` on each request, is verified against the+`tenants` table, and **a caller that names none is refused**. An empty scope+refuses rather than widening; every cross-tenant leak in this codebase has+taken the other shape, a scope that was absent rather than narrow and a read+that treated absent as "no filter".++This is identical to the shared-token path on purpose — both now call one+`_resolve_tenant_for_service`, because two copies of that rule are two chances+for one of them to treat a missing tenant as no filter.++### Rotation++`POST /workload-identities/{id}/rotate` issues a new secret and keeps the old+one working for 24 hours. A superseded secret with **no** window set is+treated as expired rather than unlimited: "not set" must not be the most+permissive state of a credential. Revoking clears the previous secret too, so+a revocation does not leave a rotation's grace window alive for a day after an+operator believed they had killed it.++### Minting is a platform act++`workload_identities:write` is held only by the wildcard roles (`admin`,+`platform_admin`) and by no tenant-scoped role. That is a decision rather than+an oversight: these credentials are deployment-wide and act for whichever+tenant they name, so minting one from a tenant-scoped session would confer+cross-tenant authority. `test_workload_credentials_are_a_platform_act_not_a_tenant_one`+asserts no non-wildcard role holds it.++Scopes are still bounded by the minter — `authorize_permission_grant` refuses+a scope the caller does not hold, so being able to mint is not being able to+mint anything.++## What proves all of this++| Evidence | Where |+|---|---|+| Live suite: real app, real Postgres, real JWTs, `ENVIRONMENT=production` | [`tests/isolation/test_abac_elevation_live.py`](../../tests/isolation/test_abac_elevation_live.py) |+| The job that runs it, with two negative controls | [`.github/workflows/access-governance-live.yml`](../../.github/workflows/access-governance-live.yml) |+| Offline shape and vocabulary agreement | [`services/api/tests/test_access_governance.py`](../../services/api/tests/test_access_governance.py) |+| The single-path structural gate | [`scripts/check_one_permission_model.py`](../../scripts/check_one_permission_model.py) |+| Every state-changing route authorizes | [`scripts/check_route_authz.py`](../../scripts/check_route_authz.py) |+| Schema | [`services/api/migrations/087_enterprise_iam.sql`](../../services/api/migrations/087_enterprise_iam.sql), [`096_access_governance_permissions.sql`](../../services/api/migrations/096_access_governance_permissions.sql) |++`ENVIRONMENT=production` in the live job is not incidental. `development` is in+`AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request there resolves to a+demo administrator — inside the one suite whose purpose is proving that+authorization narrows, that would make every assertion pass for the wrong+reason.++The two negative controls delete one half of the wiring each — the condition+call, and the elevation resolution — and require the suite to go red. Both+were run before the job was written: removing the condition call turned two+assertions red, and removing elevation resolution turned one red.diff --git a/scripts/check_one_permission_model.py b/scripts/check_one_permission_model.pyindex 12f5a93ed..997acf6c4 100644--- a/scripts/check_one_permission_model.py+++ b/scripts/check_one_permission_model.py@@ -25,6 +25,21 @@ single path stays single:is the resolver's bootstrap path; a second is a route deciding foritself, which is how the second model gets rebuilt.+Depth 8.2 added two more things the path has to do, and the reason they+are checked *here* rather than by a gate of their own is the whole point+of the item: attribute conditions and time-boxed elevation have to be+evaluated inside this one path. A condition applied beside the permission+check would be a second authority that can disagree with the first, which+is the shape that produced GHSA-pm3f-h6gc-rvgp.++5. **Conditions narrow inside the check.** `require_permission` must reach+ the condition evaluator on every branch — not only the database-backed+ one — or a tenant's attribute rule binds sessions and silently not API+ keys.+6. **Elevation is applied at use.** The check must consult live grants+ rather than a set frozen at authentication, or `expires_at` stops+ meaning anything until a cache entry happens to lapse.+Each is checked structurally with `ast`, because every one of them is aquestion about which function calls which, and a text search cannot tell acall from a mention in a docstring.@@ -91,6 +106,26 @@ def _reads(node: ast.AST, attribute: str) -> bool:return any(isinstance(n, ast.Attribute) and n.attr == attribute for n in ast.walk(node))+def _conditions_are_branch_local(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:+ """Whether the condition call sits inside an `if`, rather than after it.++ The distinction a text search cannot make, and the one that matters: a+ call nested in the database-backed branch leaves API-key and+ static-map principals unconstrained, and the tenant's console shows+ the rule as configured either way.++ Implemented as "does any statement at the function's own top level+ call it", because that is exactly the placement that binds every+ branch.+ """+ for statement in fn.body:+ if isinstance(statement, (ast.If, ast.Try, ast.For, ast.While, ast.With)):+ continue+ if "_narrow_by_conditions" in _calls(statement):+ return False+ return True++def inspect(root: pathlib.Path) -> Report:report = Report()@@ -117,6 +152,53 @@ def inspect(root: pathlib.Path) -> Report:report.findings.append("CurrentUser.require_permission does not call `grants()`, so wildcard handling has drifted from the resolver's")+ # 5. conditions narrow inside the check, on every branch+ #+ # Asserted on the *function body* rather than on a branch, because+ # the property is "whichever branch allowed, conditions still run".+ # A call placed inside the database-backed `elif` would satisfy a+ # naive search while leaving API-key and static-map principals+ # unconstrained — and those are the two a tenant is least likely to+ # notice, because nothing errors.+ if "_narrow_by_conditions" not in _calls(enforcer):+ report.findings.append(+ "CurrentUser.require_permission does not apply attribute conditions, so every "+ "`permission_conditions` row a tenant configured is inert"+ )+ elif _conditions_are_branch_local(enforcer):+ report.findings.append(+ "CurrentUser.require_permission applies conditions inside a branch, so they bind "+ "only one kind of principal; they must run after whichever branch allowed"+ )++ # 6. elevation is applied at use, not frozen at authentication+ if not any(name in _calls(enforcer) for name in ("elevated_permissions", "effective_permissions")):+ report.findings.append(+ "CurrentUser.require_permission does not consult live elevation, so an approved "+ "`privilege_grants` row confers nothing and `expires_at` governs nothing"+ )++ elevated = None+ for node in ast.walk(deps):+ if isinstance(node, ast.ClassDef) and node.name == "CurrentUser":+ elevated = _function(node, "elevated_permissions")+ if elevated is None:+ report.findings.append("CurrentUser.elevated_permissions is gone, so elevation is no longer resolved at use")+ elif not _reads(elevated, "elevation"):+ report.findings.append("CurrentUser.elevated_permissions no longer reads the grants, so elevation is decorative")++ narrower = None+ for node in ast.walk(deps):+ if isinstance(node, ast.ClassDef) and node.name == "CurrentUser":+ narrower = _function(node, "_narrow_by_conditions")+ if narrower is None:+ report.findings.append("CurrentUser._narrow_by_conditions is gone")+ elif "narrow_by_conditions" not in _calls(narrower):+ report.findings.append(+ "CurrentUser._narrow_by_conditions no longer calls the shared evaluator, so a second "+ "condition implementation exists and the two can disagree"+ )+if check is None:report.findings.append("the require_permission factory is gone")@@ -243,19 +325,23 @@ def self_test() -> int:# condition to `False` and the case passed — `grants(self.resolved_...)`# was still in the body, so the attribute was still mentioned and the# structural read still found it. A regression removes the branch.- probe(- "detects a check that stops reading the resolved set",- deps=deps_source.replace(- """ elif self.resolved_permissions is not None:- # Database-backed: what the RBAC tables actually grant.- if not grants(self.resolved_permissions, permission):+ resolved_branch = """ elif self.resolved_permissions is not None:+ # Database-backed: what the RBAC tables actually grant, plus+ # any elevation live at this instant.+ if not grants(self.elevated_permissions(), permission):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail=f"Permission denied: {permission}",)- elif not has_permission(self.role, permission):""",- """ elif not has_permission(self.role, permission):""",- ),+ elif not has_permission(self.role, permission):"""+ assert resolved_branch in deps_source, (+ "the self-test's probe text no longer matches deps.py, so the probes below would be no-ops "+ "and this gate would report PASS for a tree it never modified"+ )++ probe(+ "detects a check that stops reading the resolved set",+ deps=deps_source.replace(resolved_branch, """ elif not has_permission(self.role, permission):"""),)probe("detects authentication that stops resolving one",@@ -266,6 +352,34 @@ def self_test() -> int:rbac=rbac_source.replace("await bump_version(str(current_user.tenant_id))", "pass", 1),)+ # Depth 8.2. Each of the three below is a way the wiring could be+ # removed while the tables, the routes and the console all still look+ # configured — which is precisely the state this item repaired.+ probe(+ "detects conditions dropped from the permission check",+ deps=deps_source.replace(" self._narrow_by_conditions(permission)\n", "", 1),+ )+ # The realistic shape of this regression: somebody tucks the call into+ # the database-backed branch, where it reads as correct and leaves+ # API-key and static-map principals unconstrained.+ branch_local = deps_source.replace(+ resolved_branch,+ resolved_branch.replace(+ " elif not has_permission(self.role, permission):",+ " self._narrow_by_conditions(permission)\n elif not has_permission(self.role, permission):",+ ),+ ).replace("\n self._narrow_by_conditions(permission)\n", "\n", 1)+ assert branch_local != deps_source, "the branch-local probe did not modify deps.py, so it proves nothing"+ probe("detects conditions moved inside a branch, binding one principal type", deps=branch_local)+ probe(+ "detects elevation frozen at authentication instead of applied at use",+ deps=deps_source.replace("grants(self.elevated_permissions(), permission)", "grants(self.resolved_permissions, permission)"),+ )+ probe(+ "detects a second condition evaluator replacing the shared one",+ deps=deps_source.replace("verdict = narrow_by_conditions(permission, applicable, self.attributes)", "verdict = _local_evaluator()"),+ )+# And a direction it must not fire in.with tempfile.TemporaryDirectory(prefix="aisoc-perm-gate-ok-") as tmp:base = pathlib.Path(tmp)diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.pyindex 06294e898..75fdc559f 100644--- a/services/api/app/api/v1/deps.py+++ b/services/api/app/api/v1/deps.py@@ -26,7 +26,7 @@ import loggingimport osimport uuidfrom datetime import UTC, datetime-from typing import Annotated+from typing import Annotated, Anyfrom fastapi import Depends, HTTPException, Request, Security, statusfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer@@ -41,7 +41,13 @@ from app.api.v1.dev_auth import (DEMO_USER_ROLE,is_dev_mode,)-from app.core.permission_cache import grants, resolve_permissions+from app.core.permission_cache import (+ grants,+ resolve_conditions,+ resolve_elevation,+ resolve_permissions,+)+from app.core.role_grants import narrow_by_conditionsfrom app.core.security import (ROLE_PERMISSIONS,decode_token,@@ -49,8 +55,13 @@ from app.core.security import (hash_api_key,token_is_revoked,)+from app.core.trusted_proxy import resolve_client_ipfrom app.db.database import get_dbfrom app.models.tenant import ApiKey, Tenant, User+from app.security import abac+from app.security.abac import PrivilegeGrant+from app.services import workload_identity as workload_identity_service+from app.services.workload_identity import authenticate_workload, is_workload_secretlogger = logging.getLogger("aisoc.deps")@@ -59,6 +70,25 @@ bearer_scheme = HTTPBearer(auto_error=False)_API_KEY_PREFIX = "aisoc_"+def _condition_applies(row: dict[str, Any], permission: str, role: str) -> bool:+ """Whether one stored condition governs this check.++ Scoped to the permission it names, with the same ``resource:*`` form+ the permission check itself understands so an operator can constrain a+ whole resource in one row. A condition applied to every permission+ would turn one narrow rule into a tenant-wide outage; a condition that+ did not understand the wildcard would silently not apply where an+ operator expected it to.++ ``role`` is an optional narrowing: ``NULL`` means every role.+ """+ target = row.get("permission")+ if target not in (permission, f"{permission.split(':')[0]}:*", "*"):+ return False+ scoped_to = row.get("role")+ return scoped_to in (None, "", role)++class CurrentUser:"""Resolved authenticated user context.@@ -70,6 +100,9 @@ class CurrentUser:1. API-key scopes (explicit list)2. RBAC ``user_roles`` → ``role_permissions`` (database-backed)3. Static ``ROLE_PERMISSIONS`` fallback (legacy / bootstrap)++ …then, for every one of those three, any attribute condition the tenant+ configured, which can only narrow. See :meth:`require_permission`."""def __init__(@@ -81,6 +114,10 @@ class CurrentUser:scopes: list[str] | None = None,api_key_prefix: str | None = None,resolved_permissions: frozenset[str] | None = None,+ elevation: tuple[PrivilegeGrant, ...] = (),+ conditions: tuple[dict[str, Any], ...] = (),+ attributes: dict[str, Any] | None = None,+ workload_service: str | None = None,) -> None:self.user_id = user_idself.tenant_id = tenant_id@@ -107,6 +144,24 @@ class CurrentUser:# permission, watch it appear in the UI, and have 275 of 302 routes# ignore it.self.resolved_permissions = resolved_permissions+ # Approved, unexpired `privilege_grants` rows. Held as grants rather+ # than merged into the set above so expiry is decided at *use*: a+ # background sweep is a job that can be down, and a grant outliving+ # its window because a worker crashed is the failure mode JIT+ # elevation exists to remove.+ self.elevation = elevation+ # `permission_conditions` rows for the tenant. They narrow, never+ # grant, and are applied after whichever branch above allowed.+ self.conditions = conditions+ # What the conditions are judged against. Every key here is derived+ # by the server from the verified request — never read from a body+ # or from a header the caller controls — because an attribute a+ # caller can set is not a constraint on that caller.+ self.attributes = attributes or {}+ # Which internal service a workload credential belongs to, so an+ # audit row names `agents` rather than "a service". `None` for+ # every human and API-key principal.+ self.workload_service = workload_servicedef __repr__(self) -> str:# Without this a stray `str(user)` persists `<...CurrentUser object at@@ -116,7 +171,40 @@ class CurrentUser:# the session is not something a stack trace should carry.return f"CurrentUser(user_id={self.user_id}, tenant_id={self.tenant_id}, role={self.role})"+ def elevated_permissions(self) -> frozenset[str]:+ """The resolved set widened by elevation that is live *right now*.++ Evaluated on every call rather than folded in at authentication,+ which is what makes expiry automatic: a grant whose `expires_at`+ passed mid-session stops applying on the next check, with no sweep+ job in the path.+ """+ base = self.resolved_permissions or frozenset()+ if not self.elevation:+ return base+ return abac.effective_permissions(base, list(self.elevation))+def require_permission(self, permission: str) -> None:+ """The one permission check. Everything authorization does is here.++ Three ways to be allowed and one way to be narrowed, in this order:++ 1. an API key's explicit scopes,+ 2. the RBAC tables, widened by live elevation,+ 3. the static role map, when nothing resolved a set;++ then, whichever allowed, any attribute condition the tenant+ configured for this permission. Conditions run **after** and can+ only deny. A condition that could grant would be a second+ authorization system reaching a different answer from the first,+ and the two would disagree on the day it mattered — which is the+ shape that produced GHSA-pm3f-h6gc-rvgp here.++ Elevation deliberately does **not** widen an API key. A key's+ scopes are a narrower grant chosen at mint time; letting a person's+ temporary elevation flow into a bearer credential they minted+ earlier would make the elevation outlive its own window.+ """if self.scopes is not None:# API-key path: check explicit scopes listallowed = "*" in self.scopes or permission in self.scopes or f"{permission.split(':')[0]}:*" in self.scopes@@ -126,8 +214,9 @@ class CurrentUser:detail=f"API key missing scope: {permission}",)elif self.resolved_permissions is not None:- # Database-backed: what the RBAC tables actually grant.- if not grants(self.resolved_permissions, permission):+ # Database-backed: what the RBAC tables actually grant, plus+ # any elevation live at this instant.+ if not grants(self.elevated_permissions(), permission):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail=f"Permission denied: {permission}",@@ -140,6 +229,37 @@ class CurrentUser:detail=f"Permission denied: {permission}",)+ self._narrow_by_conditions(permission)++ def _narrow_by_conditions(self, permission: str) -> None:+ """Apply the tenant's attribute conditions to an allowed permission.++ Reached from exactly one place, on purpose. A condition evaluated+ *beside* the permission check rather than inside it would be a+ second authority that can disagree with the first, and a route+ added next year would get the role check and miss this one.+ """+ if not self.conditions:+ return+ applicable = [row for row in self.conditions if _condition_applies(row, permission, self.role)]+ if not applicable:+ return++ verdict = narrow_by_conditions(permission, applicable, self.attributes)+ if not verdict.allowed:+ logger.info(+ "deps.condition_denied permission=%s reason=%s",+ str(permission).replace("\r", "").replace("\n", " ")[:64],+ str(verdict.denied_by).replace("\r", "").replace("\n", " ")[:200],+ )+ # Named as a condition rather than a bare "permission denied".+ # An attribute refusal is indistinguishable from a missing role+ # otherwise, and people debug the wrong thing for an hour.+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"Permission denied by an access condition on {permission}: {verdict.denied_by}",+ )+def effective_permissions(self) -> list[str]:"""Every permission string this principal holds, in one list.@@ -170,7 +290,12 @@ class CurrentUser:# defeat the point of scoping a key.return sorted(set(self.scopes))if self.resolved_permissions is not None:- return sorted(self.resolved_permissions)+ # Elevation included, for the same reason the order above is+ # shared: `services/actions` re-authorises an approval against+ # this list, and an elevated analyst refused there while+ # allowed here would surface as an intermittent 403 rather+ # than as a bug.+ return sorted(self.elevated_permissions())# Static fallback. `ROLE_PERMISSIONS` is read here, in the one module# that owns principal resolution, rather than in a route -- a route# deciding its own permissions is what `check_one_permission_model`@@ -178,6 +303,46 @@ class CurrentUser:# exactly that.return sorted(set(ROLE_PERMISSIONS.get(self.role, [])))+ def bind_connection_attributes(self, connection: Any) -> "CurrentUser":+ """Record the facts attribute conditions are judged against.++ Takes a ``Request`` or a ``WebSocket`` — both carry ``.client`` and+ ``.headers``, which is all this reads, and the WebSocket upgrade+ has to be covered or a tenant that configures a condition finds+ their graph stream behaving differently from every HTTP route.++ ``source_ip`` goes through :func:`resolve_client_ip`, which only+ honours ``X-Forwarded-For`` when the direct peer is on the+ configured trusted-proxy allow-list. Reading the header directly+ would let a caller satisfy an address condition by claiming an+ address, which is not a constraint on that caller at all.++ ``auth_method`` and ``role`` are derived here rather than supplied,+ for the same reason.+ """+ self.attributes = {+ "source_ip": resolve_client_ip(connection),+ "role": self.role,+ "auth_method": self.auth_method(),+ }+ return self++ def auth_method(self) -> str:+ """How this principal authenticated: a condition can constrain it.++ "``cases:delete`` from a console session, not from a key somebody+ minted a year ago" is a rule operators ask for, and it needs the+ credential type to be an attribute rather than something inferred+ from the role.+ """+ if self.workload_service is not None:+ return "workload"+ if self.scopes is not None:+ return "api_key"+ if self.role == "api_service":+ return "service_token"+ return "session"+async def has_permission_db(self, permission: str, db: AsyncSession) -> bool:"""Check permission via RBAC tables (granular RBAC).@@ -298,6 +463,29 @@ async def _resolve_service_principal(if not expected or not hmac.compare_digest(token, expected):return None+ tenant_id = await _resolve_tenant_for_service(declared_tenant, db)++ return CurrentUser(+ # A service is not a person. The id is deterministic from the tenant+ # so an audit row says which tenant a service acted for, and the+ # email names the mechanism rather than impersonating an operator.+ user_id=uuid.uuid5(uuid.NAMESPACE_URL, f"aisoc:service:{tenant_id}"),+ tenant_id=tenant_id,+ role="api_service",+ email=f"service@{tenant_id}.internal",+ resolved_permissions=SERVICE_PRINCIPAL_PERMISSIONS,+ )+++async def _resolve_tenant_for_service(declared_tenant: str | None, db: AsyncSession) -> uuid.UUID:+ """The tenant a service caller named, verified against the table.++ Shared by the workload path and the shared-token path so there is one+ answer to "which tenant is this service acting for". Two copies of this+ rule would be two chances for one of them to treat a missing tenant as+ "no filter", and every cross-tenant leak in this codebase has taken+ exactly that shape — a scope that was absent rather than narrow.+ """if not declared_tenant or not declared_tenant.strip():logger.warning("deps.service_caller_named_no_tenant header=%s", SERVICE_TENANT_HEADER)raise HTTPException(@@ -323,16 +511,54 @@ async def _resolve_service_principal(status_code=status.HTTP_403_FORBIDDEN,detail="service token named a tenant that does not exist",)+ return tenant_id+++async def _resolve_workload_principal(secret: str, declared_tenant: str | None, db: AsyncSession) -> CurrentUser:+ """A named internal service, acting for one declared tenant.++ The replacement for ``AISOC_SERVICE_TOKEN``, which is one string every+ internal caller presents: unattributable, unscopable, and unrotatable+ without restarting everything at once.++ Three differences from the shared token, and they are the whole point.+ The audit trail names the *service*. The scope list is per workload, so+ the ingest pipeline does not carry the agents worker's authority. And+ the credential can be rotated with a grace window instead of a+ simultaneous restart.++ What is identical, deliberately: the tenant is a mandatory header,+ verified against the table. A credential that works for every tenant+ is a cross-tenant read whichever way it was minted.+ """+ identity = await authenticate_workload(db, secret)+ if identity is None:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Invalid or revoked workload credential",+ headers={"WWW-Authenticate": "Bearer"},+ )++ # Tenant *after* the credential check, so an unauthenticated caller+ # cannot probe which tenant ids exist by watching 403 against 401.+ tenant_id = await _resolve_tenant_for_service(declared_tenant, db)++ await workload_identity_service.touch(db, identity.id)return CurrentUser(- # A service is not a person. The id is deterministic from the tenant- # so an audit row says which tenant a service acted for, and the- # email names the mechanism rather than impersonating an operator.- user_id=uuid.uuid5(uuid.NAMESPACE_URL, f"aisoc:service:{tenant_id}"),+ # Deterministic from the service and tenant, so an audit row names+ # which workload acted for which tenant and two runs of the same+ # service aggregate instead of scattering.+ user_id=uuid.uuid5(uuid.NAMESPACE_URL, f"aisoc:workload:{identity.service}:{tenant_id}"),tenant_id=tenant_id,role="api_service",- email=f"service@{tenant_id}.internal",- resolved_permissions=SERVICE_PRINCIPAL_PERMISSIONS,+ email=f"workload:{identity.service}@{tenant_id}.internal",+ # Scopes, not a resolved set: a workload's authority is the list on+ # its row, exactly as an API key's is the list on its row. Resolving+ # it to a role would widen it to whatever that role holds.+ scopes=list(identity.scopes or []),+ api_key_prefix=identity.secret_prefix,+ workload_service=identity.service,)@@ -416,9 +642,15 @@ def _record_authenticated_principal(request: Request, principal: CurrentUser) ->``app.services.audit`` already uses to signal the middleware across the``BaseHTTPMiddleware`` task boundary. A request that fails authenticationraises before reaching here, so nothing is recorded for it.++ It is also where every HTTP principal is bound to the request it+ authenticated on, which is what attribute conditions are judged+ against. Doing it here rather than in each of the four credential+ branches is the point: a fifth credential type added later gets the+ binding by passing through the funnel it already has to pass through."""request.state.aisoc_authenticated_principal = principal- return principal+ return principal.bind_connection_attributes(request)async def get_current_user(@@ -466,6 +698,18 @@ async def get_current_user(token = credentials.credentials+ # --- workload identity path ---+ #+ # Ahead of the API-key branch because `aisoc_wl_` is a strict extension+ # of `aisoc_`, so `startswith(_API_KEY_PREFIX)` matches a workload+ # secret too and would resolve it as an unknown API key — a 401 that+ # reads as a bad credential rather than as a misordered branch.+ # `test_workload_identity.py` asserts this ordering so it survives an+ # edit that does not know why it is here.+ declared_tenant = request.headers.get(SERVICE_TENANT_HEADER)+ if is_workload_secret(token):+ return _record_authenticated_principal(request, await _resolve_workload_principal(token, declared_tenant, db))+# --- API key path ---if token.startswith(_API_KEY_PREFIX):return _record_authenticated_principal(request, await _resolve_api_key(token, db))@@ -475,12 +719,11 @@ async def get_current_user(# Ahead of the JWT path because a service token is not a JWT and would# otherwise be decoded, fail, and answer "Could not validate credentials",# which is what it did.- # Read off the request rather than declared as a `Header` parameter.- # Declaring it adds a 422 response to all 456 operations in the published- # spec, because a parameter that exists can fail validation -- and this is- # how a peer *service* names the tenant it acts for, not part of the- # contract a customer codes against.- declared_tenant = request.headers.get(SERVICE_TENANT_HEADER)+ # `declared_tenant` is read off the request above rather than declared as+ # a `Header` parameter. Declaring it adds a 422 response to all 456+ # operations in the published spec, because a parameter that exists can+ # fail validation -- and this is how a peer *service* names the tenant it+ # acts for, not part of the contract a customer codes against.service_principal = await _resolve_service_principal(token, declared_tenant, db)if service_principal is not None:return _record_authenticated_principal(request, service_principal)@@ -558,8 +801,10 @@ async def resolve_jwt_principal(token: str, db: AsyncSession) -> CurrentUser:# to it is no worse than before — whereas failing closed would be a new# and much louder outage. The event is logged at error, not debug.resolved: frozenset[str] | None = None+ elevation: tuple[PrivilegeGrant, ...] = ()try:resolved = await resolve_permissions(db, tenant_id=user.tenant_id, user_id=user.id, static_role=user.role)+ elevation = await resolve_elevation(db, tenant_id=user.tenant_id, user_id=user.id)except Exception as exc: # noqa: BLE001logger.error("permission resolution failed for user %s; falling back to the static role map: %s",@@ -567,12 +812,23 @@ async def resolve_jwt_principal(token: str, db: AsyncSession) -> CurrentUser:str(exc).replace("\r", "").replace("\n", " ")[:200],)+ # Conditions fail **closed**, which is the opposite of the line above+ # and is the right direction for each. Permissions failing open to the+ # static map keeps a database blip from locking every operator out+ # mid-incident — it restores the behaviour that shipped for fourteen+ # releases. A condition failing open would *remove* a restriction an+ # operator configured, turning the same blip into a silent widening+ # nobody is paged for.+ conditions = await resolve_conditions(db, tenant_id=user.tenant_id)+return CurrentUser(user_id=user.id,tenant_id=user.tenant_id,role=user.role,email=user.email,resolved_permissions=resolved,+ elevation=elevation,+ conditions=conditions,)diff --git a/services/api/app/api/v1/endpoints/access_conditions.py b/services/api/app/api/v1/endpoints/access_conditions.pynew file mode 100644index 000000000..0d04c8296--- /dev/null+++ b/services/api/app/api/v1/endpoints/access_conditions.py@@ -0,0 +1,336 @@+"""Attribute conditions that narrow a permission.++Depth plan item 8.2. ``permission_conditions`` was created by migration 087+and read by nothing, so ``cases:write`` was true everywhere, always, from+any address: there was no way to say "from the corporate network" or "during+this incident".++Enforcement does not live here+------------------------------+These routes administer rows. The rows are applied by+``CurrentUser.require_permission`` in ``app/api/v1/deps.py``, inside the one+permission path, after whichever branch allowed. That placement is the+design, not an implementation detail: a condition evaluated *beside* the+permission check would be a second authorization system, and two authorities+that can disagree is the shape that produced GHSA-pm3f-h6gc-rvgp here.++Why the operator set is narrower than the evaluator's+------------------------------------------------------+``app.security.abac`` implements eight operators. This surface accepts the+subset whose attributes the API actually puts in the evaluation context+today. The rest are refused at write time with the reason, rather than+stored and silently denied at read time: a condition the deployment cannot+evaluate is indeterminate, indeterminate denies, and an operator who+configured one would see a permanent 403 with nothing explaining it.++``mfa_satisfied`` is the one that matters. Console MFA is being built+separately; until the authenticated principal carries that fact, a condition+naming it would be a control the tree does not have.+"""++from __future__ import annotations++import uuid+from datetime import datetime+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException, Request, status+from pydantic import BaseModel, Field, field_validator+from sqlalchemy import select++from app.api.v1.deps import AuthUser, require_permission+from app.core.permission_cache import bump_version+from app.core.rbac_catalog import PERMISSIONS+from app.core.role_grants import GRANTABLE_ROLES, RoleGrantDenied, authorize_permission_grant, permissions_for+from app.db.rls import TenantDBSession+from app.models.enterprise_iam import PermissionCondition+from app.security.abac import OPERATORS+from app.services.audit import emit_audit++router = APIRouter(prefix="/access-conditions", tags=["access-conditions"])++#: Operators this deployment can evaluate, mapped to the attribute each+#: needs. ``app/api/v1/deps.py::CurrentUser.bind_connection_attributes`` is+#: what puts those attributes in the context, and these two must agree —+#: ``test_access_conditions.py`` asserts every attribute named here is one+#: the binding actually produces, so adding an operator without the fact it+#: judges fails rather than ships.+SUPPORTED: dict[str, str] = {+ "ip_in_cidr": "source_ip",+ "ip_not_in_cidr": "source_ip",+ "time_between_utc": "now",+ "weekday_in": "now",+ "attribute_equals": "role / auth_method",+ "attribute_in": "role / auth_method",+}++#: Attributes an ``attribute_equals`` / ``attribute_in`` condition may name.+#: A closed set because the context is a closed set: a condition on an+#: attribute nothing supplies is indeterminate, and indeterminate denies.+ADDRESSABLE_ATTRIBUTES = frozenset({"role", "auth_method", "source_ip"})++#: Why each unsupported operator is refused, so the message names the thing+#: that would have to exist rather than saying "unsupported".+_UNSUPPORTED_REASON: dict[str, str] = {+ "mfa_satisfied": (+ "the authenticated principal does not yet carry whether MFA was satisfied, so this "+ "condition could only ever be indeterminate — and indeterminate denies"+ ),+}++_KNOWN_PERMISSIONS = frozenset(name for name, _desc, _cat in PERMISSIONS)+++class ConditionIn(BaseModel):+ permission: str = Field(..., min_length=3, max_length=200)+ operator: str+ value: Any+ role: str | None = None+ description: str | None = Field(None, max_length=500)+ enabled: bool = True++ @field_validator("operator")+ @classmethod+ def _known_operator(cls, value: str) -> str:+ if value not in OPERATORS:+ raise ValueError(f"unknown operator {value!r}; known: {sorted(OPERATORS)}")+ if value not in SUPPORTED:+ raise ValueError(f"{value!r} cannot be enforced on this deployment: {_UNSUPPORTED_REASON.get(value, 'unsupported')}")+ return value+++class ConditionOut(BaseModel):+ id: uuid.UUID+ permission: str+ role: str | None+ operator: str+ value: Any+ description: str | None+ enabled: bool+ created_at: datetime+++def _out(row: PermissionCondition) -> ConditionOut:+ condition = row.condition or {}+ return ConditionOut(+ id=row.id,+ permission=row.permission,+ role=row.role,+ operator=str(condition.get("operator") or ""),+ value=condition.get("value"),+ description=row.description,+ enabled=row.enabled,+ created_at=row.created_at,+ )+++def _validate(permission: str, operator: str, value: Any, role: str | None) -> None:+ """Refuse a row that could not narrow anything, or could narrow everything.++ Each refusal is a condition that would otherwise be stored, read as+ configured in the console, and behave differently from what it says.++ Takes the fields rather than the request model because it decides+ nothing about authority -- that decision belongs beside+ ``require_permission`` in the handler, and binding the model here+ would say otherwise both to a reader and to+ `scripts/check_role_grant_scope.py`.+ """+ if permission != "*" and permission not in _KNOWN_PERMISSIONS:+ resource = permission.split(":")[0]+ if not (permission.endswith(":*") and any(p.startswith(f"{resource}:") for p in _KNOWN_PERMISSIONS)):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Unknown permission {permission!r}. Use a seeded permission name or a 'resource:*' form.",+ )++ if role is not None and role not in GRANTABLE_ROLES:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Unknown role {role!r}. Assignable roles: {', '.join(GRANTABLE_ROLES)}",+ )++ if operator in {"attribute_equals", "attribute_in"}:+ named = value.get("attribute") if isinstance(value, dict) else None+ if named not in ADDRESSABLE_ATTRIBUTES:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=(+ f"attribute conditions must name one of {sorted(ADDRESSABLE_ATTRIBUTES)}; "+ f"got {named!r}. An attribute the request does not carry is indeterminate, and indeterminate denies."+ ),+ )++[email protected]("/operators", response_model=dict)+async def supported_operators(+ _user: Annotated[AuthUser, Depends(require_permission("access_conditions:read"))],+) -> dict[str, Any]:+ """What this deployment can enforce, and why the rest is refused.++ A console that offered every operator the evaluator implements would+ let an operator configure a permanent, unexplained denial.+ """+ return {+ "supported": [{"operator": name, "attribute": attribute} for name, attribute in sorted(SUPPORTED.items())],+ "unsupported": [{"operator": name, "reason": reason} for name, reason in sorted(_UNSUPPORTED_REASON.items())],+ "attributes": sorted(ADDRESSABLE_ATTRIBUTES),+ }++[email protected]("", response_model=list[ConditionOut])+async def list_conditions(+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("access_conditions:read"))],+) -> list[ConditionOut]:+ rows = (+ await db.execute(+ select(PermissionCondition)+ .where(PermissionCondition.tenant_id == current_user.tenant_id)+ .order_by(PermissionCondition.permission, PermissionCondition.created_at)+ )+ ).scalars()+ return [_out(row) for row in rows]++[email protected]("", response_model=ConditionOut, status_code=status.HTTP_201_CREATED)+async def create_condition(+ body: ConditionIn,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("access_conditions:write"))],+) -> ConditionOut:+ """Add a condition to this tenant.++ The tenant comes from the authenticated principal. A condition is a+ denial, so a caller able to name the tenant could refuse another+ tenant's work — the same shape as the MSSP override that let any+ authenticated user delete a critical detection from any other tenant.++ `role` is the same argument one level down, and it was unguarded.+ Scoping a condition to a role is legislating over that role's+ exercise of a permission, so the rule is the one the rest of this+ tree already applies to conferral, turned around: you may not+ constrain authority you do not yourself hold. Without it a+ `soc_analyst` holding `access_conditions:write` could store a+ condition denying `admin` a permission outright, and the only+ symptom an administrator would see is their own access failing for+ a reason the console attributes to a rule they cannot edit.++ Measured against `resolved_permissions`, never the static role map:+ `require_permission` admitted this caller on the database-backed set,+ and judging the grant against the broader static one is how six call+ sites passed this gate while still escalating.+ """+ if body.role is not None:+ try:+ authorize_permission_grant(+ granter_role=current_user.role,+ granter_scopes=current_user.scopes,+ granter_permissions=current_user.resolved_permissions,+ requested=sorted(permissions_for(body.role)),+ subject=f"a condition scoped to role {body.role!r}",+ )+ except RoleGrantDenied as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc++ _validate(body.permission, body.operator, body.value, body.role)++ row = PermissionCondition(+ tenant_id=current_user.tenant_id,+ permission=body.permission,+ role=body.role,+ condition={"operator": body.operator, "value": body.value},+ description=body.description,+ enabled=body.enabled,+ )+ db.add(row)+ await db.flush()++ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="access_condition:create",+ resource="permission_condition",+ resource_id=str(row.id),+ changes={"permission": body.permission, "operator": body.operator, "enabled": body.enabled},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return _out(row)++[email protected]("/{condition_id}", response_model=ConditionOut)+async def set_condition_enabled(+ condition_id: uuid.UUID,+ enabled: bool,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("access_conditions:write"))],+) -> ConditionOut:+ """Turn a condition on or off without deleting it.++ Only ``enabled`` is mutable. Editing a stored condition's operator or+ value in place would change what an audit entry referring to it meant;+ a replaced rule is a new row.+ """+ row = await _load(db, condition_id, current_user.tenant_id)+ row.enabled = enabled+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="access_condition:update",+ resource="permission_condition",+ resource_id=str(row.id),+ changes={"enabled": enabled},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return _out(row)++[email protected]("/{condition_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_condition(+ condition_id: uuid.UUID,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("access_conditions:write"))],+) -> None:+ row = await _load(db, condition_id, current_user.tenant_id)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="access_condition:delete",+ resource="permission_condition",+ resource_id=str(row.id),+ changes={"permission": row.permission},+ request=request,+ )+ await db.delete(row)+ await db.commit()+ await bump_version(str(current_user.tenant_id))+++async def _load(db: Any, condition_id: uuid.UUID, tenant_id: uuid.UUID) -> PermissionCondition:+ row = (+ await db.execute(+ select(PermissionCondition).where(+ PermissionCondition.id == condition_id,+ PermissionCondition.tenant_id == tenant_id,+ )+ )+ ).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Condition not found")+ return rowdiff --git a/services/api/app/api/v1/endpoints/api_keys.py b/services/api/app/api/v1/endpoints/api_keys.pyindex e13bb0214..19e221d40 100644--- a/services/api/app/api/v1/endpoints/api_keys.py+++ b/services/api/app/api/v1/endpoints/api_keys.py@@ -67,6 +67,23 @@ VALID_SCOPES: frozenset[str] = frozenset("actions:read","lake:query","hunts:read",+ # Depth 8.2. Mintable so a tenant can automate its own access+ # governance — an on-call rotation approving elevations from a+ # script, a change-management job adding a condition for a+ # maintenance window. A permission absent from this set is one only+ # a wildcard key can exercise, which is how `hunts:read` ended up+ # reachable solely by the credential nobody should be using.+ #+ # `authorize_permission_grant` still refuses any of these to a+ # minter who does not hold them, so being listed here widens+ # nothing by itself.+ "elevation:read",+ "elevation:request",+ "elevation:approve",+ "access_conditions:read",+ "access_conditions:write",+ "workload_identities:read",+ "workload_identities:write","users:read","threat_intel:read","threat_intel:write",diff --git a/services/api/app/api/v1/endpoints/elevation.py b/services/api/app/api/v1/endpoints/elevation.pynew file mode 100644index 000000000..1017637ef--- /dev/null+++ b/services/api/app/api/v1/endpoints/elevation.py@@ -0,0 +1,360 @@+"""Time-boxed privilege elevation: request, approve, expire.++Depth plan item 8.2. ``privilege_grants`` was created by migration 087 and+read by nothing, so there was no elevation at all: a role was held+permanently or not at all, and an analyst who needed to isolate a host once+either held that power every day or waited for somebody who did.++The three properties that make this least privilege rather than paperwork+-------------------------------------------------------------------------++**Permissions, not roles.** Elevating to ``admin`` to isolate one host+confers the wildcard. A grant names the permissions it confers and nothing+else.++**The approver must already hold what they confer.** Enforced by+:func:`app.core.role_grants.authorize_permission_grant`, the same function+that guards role assignment and API-key scopes — scoped to the granter+rather than enumerated per call site, because an allow-list per route means+the next route written is a new advisory (GHSA-pm3f-h6gc-rvgp).++**Nobody approves their own.** Otherwise a request is a grant with extra+steps, and the whole control is a log line.++Expiry needs no worker+----------------------+``expires_at`` is checked where the grant is *used*, in+``CurrentUser.elevated_permissions``. A sweep job is a job that can be+down, and a grant outliving its window because a worker crashed is the+failure mode this exists to remove. Revocation writes ``revoked_at`` and+bumps the RBAC version so every replica drops the grant on its next+request rather than when its TTL happens to lapse.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException, Request, status+from pydantic import BaseModel, Field+from sqlalchemy import select++from app.api.v1.deps import AuthUser, require_permission+from app.core.permission_cache import bump_version+from app.core.rbac_catalog import PERMISSIONS+from app.core.role_grants import RoleGrantDenied, authorize_permission_grant+from app.db.rls import TenantDBSession+from app.models.enterprise_iam import PrivilegeGrant+from app.models.tenant import User+from app.services.audit import emit_audit++router = APIRouter(prefix="/elevation", tags=["elevation"])++#: The longest a single elevation may run. Eight hours is one shift: long+#: enough to work an incident, short enough that it cannot quietly become+#: standing access. A grant that outlives the reason for it is the state+#: this feature exists to avoid, and "the requester asked for a year" is+#: not a reason the server should accept.+MAX_DURATION = timedelta(hours=8)++#: Permission strings a grant may name. Derived from the seeded catalog+#: rather than written down again, so a permission added there is+#: elevatable without anyone remembering this list exists — and a typo is+#: refused instead of being stored as a grant that confers nothing while+#: reading in the console as though it does.+_KNOWN_PERMISSIONS = frozenset(name for name, _desc, _cat in PERMISSIONS)+++class ElevationRequest(BaseModel):+ permissions: list[str] = Field(..., min_length=1, max_length=20)+ justification: str = Field(..., min_length=10, max_length=2000)+ duration_minutes: int = Field(60, ge=5, le=int(MAX_DURATION.total_seconds() // 60))+ case_id: uuid.UUID | None = None+ alert_id: uuid.UUID | None = None+++class ElevationOut(BaseModel):+ id: uuid.UUID+ user_id: uuid.UUID+ user_email: str | None = None+ permissions: list[str]+ justification: str+ approved_by_id: uuid.UUID | None+ granted_at: datetime+ expires_at: datetime+ revoked_at: datetime | None+ case_id: uuid.UUID | None+ alert_id: uuid.UUID | None+ state: str+++def _state(row: PrivilegeGrant, *, now: datetime) -> str:+ """One word for what this row is, so a console does not re-derive it.++ Four columns describe the lifecycle and a surface that reads three of+ them shows a revoked grant as live.+ """+ if row.revoked_at is not None:+ return "revoked"+ if row.approved_by_id is None:+ return "pending"+ expires = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ return "active" if expires > now else "expired"+++def _out(row: PrivilegeGrant, *, now: datetime, email: str | None = None) -> ElevationOut:+ return ElevationOut(+ id=row.id,+ user_id=row.user_id,+ user_email=email,+ permissions=list(row.permissions or []),+ justification=row.justification,+ approved_by_id=row.approved_by_id,+ granted_at=row.granted_at,+ expires_at=row.expires_at,+ revoked_at=row.revoked_at,+ case_id=row.case_id,+ alert_id=row.alert_id,+ state=_state(row, now=now),+ )+++def _reject_unknown(permissions: list[str]) -> None:+ unknown = sorted(set(permissions) - _KNOWN_PERMISSIONS)+ if unknown:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Unknown permission(s): {', '.join(unknown)}",+ )++[email protected]("/requests", response_model=ElevationOut, status_code=status.HTTP_201_CREATED)+async def request_elevation(+ body: ElevationRequest,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("elevation:request"))],+) -> ElevationOut:+ """Ask for a permission for a while. Confers nothing until approved.++ The row is written with ``approved_by_id`` NULL, and+ ``resolve_elevation`` requires that column to be set, so a request is+ inert by construction rather than by a flag somebody could forget to+ check.++ The tenant and the requesting user come from the authenticated+ principal. Neither is a body field: a caller that can name the subject+ of an elevation can elevate somebody else, and a caller that can name+ the tenant can elevate inside another one.+ """+ _reject_unknown(body.permissions)++ row = PrivilegeGrant(+ tenant_id=current_user.tenant_id,+ user_id=current_user.user_id,+ permissions=sorted(set(body.permissions)),+ justification=body.justification,+ approved_by_id=None,+ granted_at=datetime.now(UTC),+ expires_at=datetime.now(UTC) + timedelta(minutes=body.duration_minutes),+ case_id=body.case_id,+ alert_id=body.alert_id,+ )+ db.add(row)+ await db.flush()++ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="elevation:request",+ resource="privilege_grant",+ resource_id=str(row.id),+ changes={"permissions": row.permissions, "justification": body.justification},+ request=request,+ )+ await db.commit()+ return _out(row, now=datetime.now(UTC), email=current_user.email)++[email protected]("/requests/{grant_id}/approve", response_model=ElevationOut)+async def approve_elevation(+ grant_id: uuid.UUID,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("elevation:approve"))],+) -> ElevationOut:+ """Approve a pending request, if you hold what it confers.++ Two refusals, and they are different questions:++ * **separation of duties** — an approver who is the requester is a+ requester, and the control would be a log line;+ * **no escalation through the approval door** — the approver must+ already hold every permission the grant confers, checked by the same+ function that guards role assignment and key scopes. Without it,+ ``elevation:approve`` would be a permission that confers every other+ permission, which is the wildcard by another name.+ """+ row = await _load(db, grant_id, current_user.tenant_id)++ if row.approved_by_id is not None:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This request has already been approved")+ if row.revoked_at is not None:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This request was revoked")+ if row.user_id == current_user.user_id:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="You cannot approve your own elevation request",+ )++ expires = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ if expires <= datetime.now(UTC):+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="This request's window has already passed; ask for a new one",+ )++ try:+ authorize_permission_grant(+ granter_role=current_user.role,+ granter_scopes=current_user.scopes,+ granter_permissions=current_user.resolved_permissions,+ requested=list(row.permissions or []),+ subject="elevated permission(s)",+ )+ except RoleGrantDenied as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc++ row.approved_by_id = current_user.user_id+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="elevation:approve",+ resource="privilege_grant",+ resource_id=str(row.id),+ changes={"permissions": list(row.permissions or []), "expires_at": row.expires_at.isoformat()},+ request=request,+ )+ await db.commit()+ # After the commit: a cache invalidated before the write lands can be+ # repopulated with the old answer by a concurrent request on another+ # replica, which for a *grant* is a delay and for a revoke is a hole.+ await bump_version(str(current_user.tenant_id))+ return _out(row, now=datetime.now(UTC))++[email protected]("/requests/{grant_id}/revoke", response_model=ElevationOut)+async def revoke_elevation(+ grant_id: uuid.UUID,+ request: Request,+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("elevation:approve"))],+) -> ElevationOut:+ """End an elevation now, rather than at its expiry.++ Gated on ``elevation:approve`` rather than a permission of its own:+ whoever may confer this authority may take it back, and a separate+ ``elevation:revoke`` that somebody forgot to grant would mean an+ elevation nobody present can end.+ """+ row = await _load(db, grant_id, current_user.tenant_id)+ if row.revoked_at is None:+ row.revoked_at = datetime.now(UTC)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="elevation:revoke",+ resource="privilege_grant",+ resource_id=str(row.id),+ changes={"permissions": list(row.permissions or [])},+ request=request,+ )+ await db.commit()+ await bump_version(str(current_user.tenant_id))+ return _out(row, now=datetime.now(UTC))++[email protected]("/requests", response_model=list[ElevationOut])+async def list_elevations(+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("elevation:read"))],+ state: str | None = None,+) -> list[ElevationOut]:+ """Every elevation in this tenant, newest first.++ Scoped on the authenticated tenant in the ``WHERE`` clause as well as+ by row-level security, because query-layer scoping is the control that+ holds when a session is opened without the RLS context.+ """+ rows = (+ await db.execute(+ select(PrivilegeGrant)+ .where(PrivilegeGrant.tenant_id == current_user.tenant_id)+ .order_by(PrivilegeGrant.granted_at.desc())+ .limit(200)+ )+ ).scalars()++ now = datetime.now(UTC)+ emails = await _emails(db, current_user.tenant_id)+ out = [_out(row, now=now, email=emails.get(row.user_id)) for row in rows]+ return [item for item in out if state is None or item.state == state]++[email protected]("/mine", response_model=list[ElevationOut])+async def my_elevations(+ db: TenantDBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("elevation:request"))],+) -> list[ElevationOut]:+ """This principal's own elevations.++ Gated on ``elevation:request`` rather than left identity-only: a+ principal who may not request one has nothing to read here, and an+ identity-only route is how "is this a valid session?" quietly becomes+ the whole authorization decision.+ """+ rows = (+ await db.execute(+ select(PrivilegeGrant)+ .where(+ PrivilegeGrant.tenant_id == current_user.tenant_id,+ PrivilegeGrant.user_id == current_user.user_id,+ )+ .order_by(PrivilegeGrant.granted_at.desc())+ .limit(100)+ )+ ).scalars()+ now = datetime.now(UTC)+ return [_out(row, now=now, email=current_user.email) for row in rows]+++async def _load(db: Any, grant_id: uuid.UUID, tenant_id: uuid.UUID) -> PrivilegeGrant:+ """One grant, or 404 — and never another tenant's.++ The tenant predicate is in the query rather than checked after the+ fetch. A read that loads the row first and compares afterwards still+ answers a different 404 for "exists elsewhere" than for "does not+ exist", which enumerates ids across tenants.+ """+ row = (+ await db.execute(select(PrivilegeGrant).where(PrivilegeGrant.id == grant_id, PrivilegeGrant.tenant_id == tenant_id))+ ).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Elevation request not found")+ return row+++async def _emails(db: Any, tenant_id: uuid.UUID) -> dict[uuid.UUID, str]:+ rows = await db.execute(select(User.id, User.email).where(User.tenant_id == tenant_id))+ return dict(rows.all())diff --git a/services/api/app/api/v1/endpoints/graph_ws.py b/services/api/app/api/v1/endpoints/graph_ws.pyindex e51c5d080..72d154ac0 100644--- a/services/api/app/api/v1/endpoints/graph_ws.py+++ b/services/api/app/api/v1/endpoints/graph_ws.py@@ -148,8 +148,17 @@ async def _authenticate_ws(# The upgrade response cannot carry `WWW-Authenticate`, which is the only# reason this is not a plain `Depends`, so the 401 is translated into a# close frame here and nowhere else.+ #+ # `bind_connection_attributes` is what the HTTP funnel+ # (`_record_authenticated_principal`) does for every other credential.+ # A `WebSocket` carries the same `.client` and `.headers` the binding+ # reads, and without it a tenant that configures an attribute condition+ # would find their graph stream judged on an empty context — which+ # denies, so the symptom is a stream that closes for a reason nothing+ # explains.try:- return await resolve_jwt_principal(token, db)+ principal = await resolve_jwt_principal(token, db)+ return principal.bind_connection_attributes(websocket)except HTTPException as exc:await websocket.close(code=status.WS_1008_POLICY_VIOLATION,diff --git a/services/api/app/api/v1/endpoints/workload_identities.py b/services/api/app/api/v1/endpoints/workload_identities.pynew file mode 100644index 000000000..8a91b0478--- /dev/null+++ b/services/api/app/api/v1/endpoints/workload_identities.py@@ -0,0 +1,258 @@+"""Per-service credentials for internal callers.++Depth plan item 8.2. ``workload_identities`` was created by migration 087+and read by nothing, leaving ``AISOC_SERVICE_TOKEN`` — one string every+internal caller presents — as the only internal credential.++Deployment-wide, and therefore not tenant-scoped+-------------------------------------------------+A service authenticates *before* any tenant is known; the agents container+triages alerts for every tenant on the deployment and names the one it is+acting for on a header, per request. So these rows carry no ``tenant_id``,+and the table has no row-level security policy — the migration says so and+means it.++That makes minting one a platform act rather than a tenant act, which is+why the permissions below are held only by the wildcard roles+(``admin`` and ``platform_admin``). That is deliberate and is the one case+where "no non-wildcard role holds this" is the right answer rather than+the bug it usually is: a tenant administrator minting a credential that+every tenant's data flows through would be precisely the cross-tenant+authority this feature exists to remove.++Scopes are still bounded by the minter+---------------------------------------+``authorize_permission_grant`` refuses a scope the caller does not hold,+the same function that guards role assignment and API-key scopes. A+wildcard principal may mint a wildcard workload — it confers nothing they+do not already have — and anybody else is held to what they hold.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Annotated, Any++from fastapi import APIRouter, Depends, HTTPException, Request, status+from pydantic import BaseModel, Field, field_validator+from sqlalchemy import select++from app.api.v1.deps import AuthUser, DBSession, require_permission+from app.api.v1.endpoints.api_keys import VALID_SCOPES+from app.core.role_grants import RoleGrantDenied, authorize_permission_grant+from app.models.enterprise_iam import WorkloadIdentity+from app.services import workload_identity as service+from app.services.audit import emit_audit++router = APIRouter(prefix="/workload-identities", tags=["workload-identities"])++#: Service names a credential may be minted for. A closed vocabulary+#: because the point of the row is attribution: a free-text service name+#: lets two deployments disagree about what "agents" is called, and an+#: audit trail that cannot be grouped is not much better than one that+#: says "a service".+KNOWN_SERVICES = (+ "agents",+ "actions",+ "connectors",+ "fusion",+ "ingest",+ "realtime",+ "threatintel",+ "ueba",+ "mcp",+)+++class WorkloadIn(BaseModel):+ service: str+ description: str | None = Field(None, max_length=500)+ scopes: list[str] = Field(default_factory=list, max_length=40)+ expires_in_days: int | None = Field(None, ge=1, le=3650)++ @field_validator("service")+ @classmethod+ def _known_service(cls, value: str) -> str:+ if value not in KNOWN_SERVICES:+ raise ValueError(f"unknown service {value!r}; known: {', '.join(KNOWN_SERVICES)}")+ return value+++class WorkloadCreated(BaseModel):+ """The one response that carries secret material, and only on create."""++ identity: dict[str, Any]+ secret: str+ warning: str = "Store this now. It is shown once and is not recoverable."+++def _authorize_scopes(scopes: list[str], current_user: AuthUser) -> None:+ """Two refusals: unknown scopes, and scopes the minter does not hold.++ The second is the one that matters. A credential is a bearer+ credential, so its scopes are authority conferred on whoever holds it —+ and ``workload_identities:write`` must not be a door that mints+ authority its holder lacks.++ Named for the authorization rather than the validation, matching+ ``api_keys._authorize_scopes``, because the name is load-bearing:+ `scripts/check_role_grant_scope.py` credits a handler that delegates+ to a helper only through an enumerated set of helper names, and a+ helper called ``_validate_scopes`` reads as a shape check. It was+ called that, and the gate correctly reported this route as conferring+ caller-chosen authority without reaching the chokepoint.+ """+ invalid = sorted(set(scopes) - VALID_SCOPES)+ if invalid:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"Invalid scope(s): {', '.join(invalid)}. Valid scopes: {sorted(VALID_SCOPES)}",+ )+ try:+ authorize_permission_grant(+ granter_role=current_user.role,+ granter_scopes=current_user.scopes,+ granter_permissions=current_user.resolved_permissions,+ requested=scopes,+ subject="workload scope(s)",+ )+ except RoleGrantDenied as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc++[email protected]("", response_model=list[dict])+async def list_workload_identities(+ db: DBSession,+ _user: Annotated[AuthUser, Depends(require_permission("workload_identities:read"))],+) -> list[dict[str, Any]]:+ """Every workload credential, with no secret material.++ ``last_used_at`` is the column that matters operationally: it is what+ tells an operator a credential they are about to revoke is dead.+ """+ rows = (await db.execute(select(WorkloadIdentity).order_by(WorkloadIdentity.service, WorkloadIdentity.created_at))).scalars()+ return [service.describe(row) for row in rows]++[email protected]("", response_model=WorkloadCreated, status_code=status.HTTP_201_CREATED)+async def create_workload_identity(+ body: WorkloadIn,+ request: Request,+ db: DBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("workload_identities:write"))],+) -> WorkloadCreated:+ """Mint a credential for one internal service."""+ _authorize_scopes(body.scopes, current_user)++ secret, prefix, digest = service.mint_workload_secret()+ row = WorkloadIdentity(+ service=body.service,+ description=body.description,+ scopes=sorted(set(body.scopes)),+ secret_hash=digest,+ secret_prefix=prefix,+ expires_at=(datetime.now(UTC) + timedelta(days=body.expires_in_days)) if body.expires_in_days else None,+ )+ db.add(row)+ await db.flush()++ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="workload_identity:create",+ resource="workload_identity",+ resource_id=str(row.id),+ # The prefix, never the secret. `emit_audit` redacts on key names+ # and would not know this one.+ changes={"service": body.service, "scopes": row.scopes, "secret_prefix": prefix},+ request=request,+ )+ await db.commit()+ return WorkloadCreated(identity=service.describe(row), secret=secret)++[email protected]("/{identity_id}/rotate", response_model=WorkloadCreated)+async def rotate_workload_identity(+ identity_id: uuid.UUID,+ request: Request,+ db: DBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("workload_identities:write"))],+) -> WorkloadCreated:+ """Issue a new secret and keep the old one alive for a grace window.++ Rotation in place is the whole reason the ``previous_*`` columns exist.+ The only path before was create, update every caller, delete — which is+ downtime, so most deployments never rotated at all, which is how one+ leaked log line became permanent internal access.+ """+ row = await _load(db, identity_id)+ if row.revoked_at is not None:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This credential is revoked; mint a new one")++ secret = await service.rotate(db, row)+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="workload_identity:rotate",+ resource="workload_identity",+ resource_id=str(row.id),+ changes={"service": row.service, "secret_prefix": row.secret_prefix},+ request=request,+ )+ await db.commit()+ return WorkloadCreated(+ identity=service.describe(row),+ secret=secret,+ warning=(+ "Store this now. The previous secret keeps working until "+ f"{row.previous_expires_at.isoformat() if row.previous_expires_at else 'the grace window ends'}."+ ),+ )++[email protected]("/{identity_id}", status_code=status.HTTP_204_NO_CONTENT)+async def revoke_workload_identity(+ identity_id: uuid.UUID,+ request: Request,+ db: DBSession,+ current_user: Annotated[AuthUser, Depends(require_permission("workload_identities:write"))],+) -> None:+ """Revoke immediately, including the superseded secret.++ Clearing ``previous_hash`` is the half that is easy to miss: a+ revocation that left a rotation's grace window intact would leave the+ credential working for up to a day after an operator believed they had+ killed it.+ """+ row = await _load(db, identity_id)+ if row.revoked_at is None:+ row.revoked_at = datetime.now(UTC)+ row.previous_hash = None+ row.previous_expires_at = None+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="workload_identity:revoke",+ resource="workload_identity",+ resource_id=str(row.id),+ changes={"service": row.service, "secret_prefix": row.secret_prefix},+ request=request,+ )+ await db.commit()+++async def _load(db: Any, identity_id: uuid.UUID) -> WorkloadIdentity:+ row = (await db.execute(select(WorkloadIdentity).where(WorkloadIdentity.id == identity_id))).scalar_one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Workload identity not found")+ return rowdiff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex d7e711ef8..57260ef83 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -3,6 +3,7 @@from fastapi import APIRouterfrom app.api.v1.endpoints import (+ access_conditions,admin_users,agent_tools,agents,@@ -32,6 +33,7 @@ from app.api.v1.endpoints import (detection_rules,easm,effective_permissions,+ elevation,email_approval,evaluations,federated,@@ -93,6 +95,7 @@ from app.api.v1.endpoints import (translation,usage,waitlist,+ workload_identities,)api_router = APIRouter(prefix="/api/v1")@@ -160,6 +163,13 @@ api_router.include_router(mcp_servers.router)# on the path of an investigation.api_router.include_router(tenant_skills.router)api_router.include_router(rbac.router)+# Depth 8.2 — the three tables migration 087 created and nothing read.+# Enforcement is not here: elevation and conditions are applied inside+# `CurrentUser.require_permission`, which is the single permission path.+# These routers administer the rows that path reads.+api_router.include_router(elevation.router)+api_router.include_router(access_conditions.router)+api_router.include_router(workload_identities.router)api_router.include_router(admin_users.router)api_router.include_router(audit.router)api_router.include_router(branding.router)diff --git a/services/api/app/core/permission_cache.py b/services/api/app/core/permission_cache.pyindex dadc5a180..0083c61ba 100644--- a/services/api/app/core/permission_cache.py+++ b/services/api/app/core/permission_cache.py@@ -45,6 +45,24 @@ Without Redis the version is unavailable and the cache falls back to ashort TTL, which is honest about what it can offer: a single-processdeployment is correct either way, and a multi-replica one without Redisconverges within the TTL. That degradation is logged once, not silently.++Two more things the principal carries (depth 8.2)+-------------------------------------------------+`resolve_authorization` returns the standing set plus the two facts that+narrow and widen it, resolved in the same place and on the same version+counter:++* **elevation** — live rows from `privilege_grants`, carried as grants+ rather than merged here, so expiry is evaluated at *use*. A background+ sweep is a job that can be down, and a grant outliving its window+ because a worker crashed is the failure mode JIT elevation exists to+ remove. Caching the union would reintroduce exactly that.+* **conditions** — `permission_conditions` for the tenant, applied by+ `CurrentUser.require_permission` after the role check has allowed.++Both are resolved once per request at authentication, for the same reason+the permission set is: a query per permission check turns a database blip+into a platform-wide authorization outage."""from __future__ import annotations@@ -58,6 +76,8 @@ from typing import Any, Finalfrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.security.abac import PrivilegeGrant+logger = logging.getLogger("aisoc.permissions")#: How long a resolved set survives when no version counter is reachable.@@ -140,6 +160,52 @@ class PermissionCache:CACHE = PermissionCache()+@dataclass+class _VersionedCache:+ """The same version-and-TTL contract, for payloads that are not sets.++ Elevation grants and attribute conditions need exactly the invalidation+ `PermissionCache` provides and cannot reuse it, because its entries are+ typed as permission sets and the gate on that class reads them as such.+ A second copy of the *policy* would be the drift this file exists to+ prevent, so the policy is one expression here and the storage is two.+ """++ _entries: dict[tuple[str, str], tuple[str, float, Any]] = field(default_factory=dict)++ def get(self, key: tuple[str, str], version: str) -> Any | None:+ entry = self._entries.get(key)+ if entry is None:+ return None+ cached_version, expires_at, payload = entry+ if cached_version != version or expires_at <= time.monotonic():+ self._entries.pop(key, None)+ return None+ return payload++ def put(self, key: tuple[str, str], version: str, payload: Any) -> None:+ if len(self._entries) >= MAX_ENTRIES:+ oldest = min(self._entries, key=lambda k: self._entries[k][1])+ self._entries.pop(oldest, None)+ self._entries[key] = (version, time.monotonic() + FALLBACK_TTL_SECONDS, payload)++ def invalidate_tenant(self, tenant_id: str) -> int:+ doomed = [k for k in self._entries if k[0] == tenant_id]+ for key in doomed:+ self._entries.pop(key, None)+ return len(doomed)++ def clear(self) -> None:+ self._entries.clear()+++#: Live elevation grants, keyed `(tenant_id, user_id)`.+ELEVATION_CACHE = _VersionedCache()++#: Attribute conditions, keyed `(tenant_id, "")` — they are tenant-wide.+CONDITION_CACHE = _VersionedCache()++@lru_cache(maxsize=1)def _redis_client() -> Any | None:"""Built once and reused.@@ -164,9 +230,11 @@ def _redis_client() -> Any | None:def reset_for_tests() -> None:- """Drop the cache and the client handle. Tests only."""+ """Drop the caches and the client handle. Tests only."""_redis_client.cache_clear()CACHE.clear()+ ELEVATION_CACHE.clear()+ CONDITION_CACHE.clear()CACHE._warned_no_redis = False@@ -197,20 +265,31 @@ async def current_version(tenant_id: str) -> str:async def bump_version(tenant_id: str) -> None:"""Invalidate this tenant's cached permissions on every replica.- Called after any write to `user_roles` or `role_permissions`. Failing- soft on a Redis error is correct here and only here: the TTL still- bounds the staleness, and refusing the *grant* because the cache could- not be invalidated would make RBAC administration depend on Redis.+ Called after any write to `user_roles`, `role_permissions`,+ `privilege_grants` or `permission_conditions` — every store that can+ change what a principal may do. One counter covers all four because a+ second counter is a second thing to forget to bump, and the direction+ that gets forgotten is always the revoke.++ Failing soft on a Redis error is correct here and only here: the TTL+ still bounds the staleness, and refusing the *grant* because the cache+ could not be invalidated would make RBAC administration depend on Redis."""client = _redis_client()if client is None:- CACHE.invalidate_tenant(tenant_id)+ _invalidate_local(tenant_id)returntry:await client.incr(_REDIS_VERSION_KEY.format(tenant_id=tenant_id))except Exception as exc: # noqa: BLE001logger.warning("permission cache: could not bump the RBAC version: %s", exc)+ _invalidate_local(tenant_id)+++def _invalidate_local(tenant_id: str) -> None:CACHE.invalidate_tenant(tenant_id)+ ELEVATION_CACHE.invalidate_tenant(tenant_id)+ CONDITION_CACHE.invalidate_tenant(tenant_id)async def _tenant_has_rbac(db: AsyncSession, tenant_id: Any) -> bool:@@ -278,3 +357,78 @@ async def resolve_permissions(db: AsyncSession, *, tenant_id: Any, user_id: Any,def grants(permissions: frozenset[str], wanted: str) -> bool:"""Whether a resolved set covers *wanted*, including wildcards."""return "*" in permissions or wanted in permissions or f"{wanted.split(':')[0]}:*" in permissions+++async def resolve_elevation(db: AsyncSession, *, tenant_id: Any, user_id: Any) -> tuple[PrivilegeGrant, ...]:+ """Approved, unexpired elevation rows for this principal.++ Returned as grants rather than folded into the permission set, so+ `effective_permissions` can decide at *use* whether each one is still+ live. A grant cached as a flat union would keep working until the TTL+ even after its own `expires_at` had passed, which is the failure JIT+ elevation exists to remove.++ An unapproved row confers nothing: `approved_by_id IS NULL` means the+ request is still pending, and the whole point of approval is that it is+ a gate rather than a record.+ """+ from app.models.enterprise_iam import PrivilegeGrant as GrantRow # noqa: PLC0415++ tenant_key, user_key = str(tenant_id), str(user_id)+ version = await current_version(tenant_key)+ cached = ELEVATION_CACHE.get((tenant_key, user_key), version)+ if cached is not None:+ return cached # type: ignore[no-any-return]++ rows = await db.execute(+ select(GrantRow.permissions, GrantRow.expires_at, GrantRow.revoked_at).where(+ GrantRow.tenant_id == tenant_id,+ GrantRow.user_id == user_id,+ GrantRow.approved_by_id.isnot(None),+ GrantRow.revoked_at.is_(None),+ GrantRow.expires_at > func.now(),+ )+ )+ resolved = tuple(+ PrivilegeGrant(permissions=tuple(permissions or ()), expires_at=expires_at, revoked_at=revoked_at)+ for permissions, expires_at, revoked_at in rows.all()+ )+ ELEVATION_CACHE.put((tenant_key, user_key), version, resolved)+ return resolved+++async def resolve_conditions(db: AsyncSession, *, tenant_id: Any) -> tuple[dict[str, Any], ...]:+ """Enabled attribute conditions for this tenant.++ Tenant-wide rather than per-permission: a principal's checks are not+ known at authentication time, and one query for a handful of rows beats+ a query per permission check. Filtering to the permission being checked+ happens in `CurrentUser.require_permission`.+ """+ from app.models.enterprise_iam import PermissionCondition # noqa: PLC0415++ tenant_key = str(tenant_id)+ version = await current_version(tenant_key)+ cached = CONDITION_CACHE.get((tenant_key, ""), version)+ if cached is not None:+ return cached # type: ignore[no-any-return]++ rows = await db.execute(+ select(+ PermissionCondition.permission,+ PermissionCondition.role,+ PermissionCondition.condition,+ PermissionCondition.description,+ ).where(PermissionCondition.tenant_id == tenant_id, PermissionCondition.enabled.is_(True))+ )+ resolved = tuple(+ {+ "permission": permission,+ "role": role,+ "description": description,+ **(condition or {}),+ }+ for permission, role, condition, description in rows.all()+ )+ CONDITION_CACHE.put((tenant_key, ""), version, resolved)+ return resolveddiff --git a/services/api/app/core/rbac_catalog.py b/services/api/app/core/rbac_catalog.pyindex aa2eda5f9..134a9e05b 100644--- a/services/api/app/core/rbac_catalog.py+++ b/services/api/app/core/rbac_catalog.py@@ -85,6 +85,15 @@ PERMISSIONS: Final[tuple[tuple[str, str, str], ...]] = (("apikeys:manage", "Manage API keys (alias)", "api_keys"),("audit_log:read", "Read the audit log", "audit"),("audit:read", "Read the audit log (alias)", "audit"),+ # Depth 8.2 — time-boxed elevation, attribute conditions, and the+ # per-service credentials that replace the one shared service token.+ ("elevation:read", "View the tenant's privilege elevations", "access"),+ ("elevation:request", "Request a time-boxed privilege elevation", "access"),+ ("elevation:approve", "Approve or revoke a privilege elevation", "access"),+ ("access_conditions:read", "View attribute conditions on permissions", "access"),+ ("access_conditions:write", "Add, disable or remove attribute conditions", "access"),+ ("workload_identities:read", "View per-service internal credentials", "access"),+ ("workload_identities:write", "Mint, rotate or revoke per-service credentials", "access"),("sla:read", "View SLA metrics", "sla"),("sla:write", "Change SLA policy", "sla"),("plugins:read", "View plugins", "plugins"),@@ -148,6 +157,11 @@ _INFOSEC: Final[frozenset[str]] = _VIEWER | frozenset("investigation:run","reports:write","reports:export",+ # An analyst may *ask* for a permission for a while, and see their+ # own requests. Approving is deliberately absent: an approver who+ # can also request is both parties to the decision, and the whole+ # control reduces to a log line.+ "elevation:request",})diff --git a/services/api/app/core/security.py b/services/api/app/core/security.pyindex a7e8a9aaf..b413fe8a1 100644--- a/services/api/app/core/security.py+++ b/services/api/app/core/security.py@@ -89,6 +89,21 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ # Depth 8.2. A tenant administrator governs access inside their own+ # tenant: who may elevate, who approves, and which attribute+ # conditions narrow a permission.+ #+ # `workload_identities:*` is deliberately NOT here. Those credentials+ # are deployment-wide — a service authenticates before any tenant is+ # known — so minting one from a tenant-scoped session would confer+ # authority over every tenant's data. Only the wildcard roles hold+ # them, which is the one case where "no scoped role holds this" is+ # the decision rather than the oversight it usually is.+ "elevation:read",+ "elevation:request",+ "elevation:approve",+ "access_conditions:read",+ "access_conditions:write",],"soc_lead": ["alerts:read",@@ -120,6 +135,12 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ # A lead is the approver an analyst's elevation goes to, which is+ # the role the separation-of-duties rule assumes exists.+ "elevation:read",+ "elevation:request",+ "elevation:approve",+ "access_conditions:read",],"soc_analyst": ["alerts:read",@@ -147,6 +168,9 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ # Request, never approve. The analyst asking to isolate a host is+ # not the person who should decide they may.+ "elevation:request",],"threat_hunter": ["alerts:read",@@ -172,6 +196,7 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {# tenant's own knowledge base, so every role that can read an# alert can read it."knowledge_base:read",+ "elevation:request",],"viewer": ["alerts:read",diff --git a/services/api/app/core/trusted_proxy.py b/services/api/app/core/trusted_proxy.pyindex 072c4ac01..b07aa42af 100644--- a/services/api/app/core/trusted_proxy.py+++ b/services/api/app/core/trusted_proxy.py@@ -34,7 +34,7 @@ import loggingimport osfrom collections.abc import Iterable, Sequence-from fastapi import Request+from starlette.requests import HTTPConnectionlogger = logging.getLogger("aisoc.audit.trusted_proxy")@@ -107,7 +107,7 @@ def _parse_forwarded_for(header: str | None) -> list[str]:def resolve_client_ip(- request: Request,+ request: HTTPConnection,*,trusted_networks: Iterable[ipaddress._BaseNetwork] | None = None,) -> str | None:@@ -115,8 +115,9 @@ def resolve_client_ip(Algorithm:- 1. ``peer_ip`` = direct TCP peer (``request.client.host``). If absent,- we cannot attribute anything, return ``None``.+ 1. ``peer_ip`` = direct TCP peer (``request.client.host``). If the+ connection does not expose a peer at all, we cannot attribute+ anything, return ``None``.2. If no trusted-proxy CIDRs are configured, return ``peer_ip``. Thisis the audit-safe default and means ``X-Forwarded-For`` isignored even if present.@@ -130,9 +131,13 @@ def resolve_client_ip(empty, return ``peer_ip``.The function never raises — malformed headers degrade to the direct- peer.+ peer, and a connection that exposes no peer at all degrades to+ ``None``. Returning ``None`` is safe for the ABAC caller because an+ address condition evaluated against an unknown address is+ indeterminate, and indeterminate denies; raising would instead fail+ the whole authentication of an otherwise-valid principal."""- client = request.client+ client = getattr(request, "client", None)peer_ip = client.host if client else Noneif not peer_ip:return Nonediff --git a/services/api/app/models/enterprise_iam.py b/services/api/app/models/enterprise_iam.pynew file mode 100644index 000000000..aa3bf89fa--- /dev/null+++ b/services/api/app/models/enterprise_iam.py@@ -0,0 +1,139 @@+"""Readers for the three tables migration 087 created.++``087_enterprise_iam.sql`` created ``permission_conditions``,+``privilege_grants`` and ``workload_identities`` and shipped no reader for+any of them — the CHANGELOG said so in the same release that announced+them, and ``FIX_PASS_PROGRESS.md`` retracted the claim. These models are+half of the repair; the other half is ``app.core.permission_cache``, which+resolves them onto the principal, and ``CurrentUser.require_permission``,+which is the one place they are applied.++Each model maps a table that already exists. Nothing here creates schema,+so the column set is dictated by the migration rather than the other way+round.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import Boolean, DateTime, ForeignKey, Text+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class PermissionCondition(Base):+ """An attribute condition that narrows one permission for one tenant.++ Conditions never grant. ``app.security.abac.evaluate_conditions`` can+ only turn an allow into a deny, which is what keeps this one+ authorization system rather than two that can disagree.+ """++ __tablename__ = "permission_conditions"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)++ #: The permission string this constrains, e.g. ``cases:write``. A row+ #: applies to exactly this permission: an evaluator that applied every+ #: row to every check would turn one narrow rule into a tenant outage.+ permission: Mapped[str] = mapped_column(Text, nullable=False)++ #: Optional role filter. ``NULL`` means every role in the tenant.+ role: Mapped[str | None] = mapped_column(Text, nullable=True)++ #: ``{"operator": ..., "value": ...}``. Declarative so the evaluator is+ #: one audited function rather than scattered checks, and so a condition+ #: can be added from the console without a deploy.+ condition: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)+ enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++class PrivilegeGrant(Base):+ """A time-boxed elevation: these permissions, this user, until then.++ Permissions rather than a role, because elevating to ``admin`` to+ isolate one host confers the wildcard — the opposite of least privilege.++ ``expires_at`` is ``NOT NULL`` in the migration so a grant cannot become+ permanent by omission, which is how every JIT system decays into+ standing access.+ """++ __tablename__ = "privilege_grants"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)+ user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)++ permissions: Mapped[list[str]] = mapped_column(ARRAY(Text), nullable=False, default=list)++ #: Why, in the requester's words. An elevation nobody has to justify is+ #: a role held permanently with extra steps.+ justification: Mapped[str] = mapped_column(Text, nullable=False)++ #: Who approved. ``NULL`` means the request is still pending — nothing+ #: is conferred until this is set, which is what makes approval a gate+ #: rather than a record.+ approved_by_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)++ granted_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+ expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)++ #: What the elevation was for, so a review can ask whether it was used+ #: for that.+ case_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ alert_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+++class WorkloadIdentity(Base):+ """A per-service credential, replacing the single shared service token.++ ``AISOC_SERVICE_TOKEN`` is one string every internal caller presents. It+ cannot be attributed — the audit trail says "a service" did it — it+ cannot be rotated without restarting everything at once, and it cannot+ be scoped, so the agents worker presents the same credential as the+ ingest pipeline.++ Deployment-wide rather than tenant-scoped: a service authenticates+ before any tenant is known, and names the tenant it acts for on a+ header. That split is deliberate and is why this table has no+ ``tenant_id`` and no row-level security policy.+ """++ __tablename__ = "workload_identities"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)++ #: Which service this belongs to, so an audit row can name ``agents``+ #: rather than "a service".+ service: Mapped[str] = mapped_column(Text, nullable=False)+ description: Mapped[str | None] = mapped_column(Text, nullable=True)++ #: What this workload may do. The ingest pipeline does not need to read+ #: the action registry, and the shared token could not express that.+ scopes: Mapped[list[str]] = mapped_column(ARRAY(Text), nullable=False, default=list)++ secret_hash: Mapped[str] = mapped_column(Text, nullable=False)+ secret_prefix: Mapped[str] = mapped_column(Text, nullable=False, index=True)++ #: Rotation without downtime needs two live secrets at once. The+ #: previous one keeps working until ``previous_expires_at``, so callers+ #: roll over on their own schedule instead of all at the same instant.+ previous_hash: Mapped[str | None] = mapped_column(Text, nullable=True)+ previous_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)++ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))+++__all__ = ["PermissionCondition", "PrivilegeGrant", "WorkloadIdentity"]diff --git a/services/api/app/services/workload_identity.py b/services/api/app/services/workload_identity.pynew file mode 100644index 000000000..b9dbedbcd--- /dev/null+++ b/services/api/app/services/workload_identity.py@@ -0,0 +1,186 @@+"""Per-service credentials for service-to-service calls.++Depth plan item 8.2. ``workload_identities`` was created by migration 087+and read by nothing, so the only internal credential remained+``AISOC_SERVICE_TOKEN``: one string every internal caller presents.++What the shared token cannot do+-------------------------------+* **Attribution.** Every internal call is "a service". An audit trail that+ cannot say which service acted cannot answer the question an incident+ review asks first.+* **Scoping.** The ingest pipeline presents the same authority as the+ agents worker, so a leak anywhere is a leak everywhere.+* **Rotation.** Changing it means restarting every service at once, which+ is why nobody does it.++A workload identity fixes all three: the row names the service, carries+its own scope list, and holds a *previous* secret honoured until+``previous_expires_at`` so callers roll over on their own schedule.++What it deliberately does not change+------------------------------------+**The tenant still comes from a header, and is still mandatory.** A+workload credential identifies a service, not a tenant — the agents+container triages alerts for every tenant on the deployment. One shared+credential with no tenant is a cross-tenant read, so a caller that names+no tenant resolves to an empty scope and an empty scope refuses. That is+the same contract ``_resolve_service_principal`` already enforces for the+shared token, and this path reuses it rather than inventing a second one.++The secret is stored as a SHA-256 digest, never in the clear. It is high+entropy (192 bits from ``secrets.token_hex(24)``), so a digest is the+right primitive here and a password-stretching KDF would only add latency+to a credential checked on every internal request.+"""++from __future__ import annotations++import hashlib+import hmac+import logging+import secrets+import uuid+from datetime import UTC, datetime, timedelta+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.enterprise_iam import WorkloadIdentity++logger = logging.getLogger("aisoc.workload_identity")++#: Distinct from ``aisoc_`` so a workload secret is never mistaken for an+#: API key. It is a strict *extension* of the API-key prefix, which is the+#: trap: ``startswith("aisoc_")`` matches it too, so the authentication+#: path must test this one first. ``test_workload_identity.py`` pins that+#: ordering with an assertion rather than leaving it to a convention a+#: later edit can reorder away.+WORKLOAD_KEY_PREFIX = "aisoc_wl_"++#: How much of the secret is stored in the clear, for display and lookup.+#: ``aisoc_wl_`` plus seven hex characters.+_PREFIX_LENGTH = len(WORKLOAD_KEY_PREFIX) + 7++#: How long a superseded secret keeps working after a rotation. Long enough+#: for a rolling restart, short enough that a rotation prompted by a leak+#: actually ends the leak.+DEFAULT_ROTATION_GRACE = timedelta(hours=24)+++def mint_workload_secret() -> tuple[str, str, str]:+ """``(secret, prefix, digest)`` for a new workload credential.++ The secret is returned once and never stored; only the digest and the+ prefix are persisted.+ """+ secret = f"{WORKLOAD_KEY_PREFIX}{secrets.token_hex(24)}"+ return secret, secret[:_PREFIX_LENGTH], hash_workload_secret(secret)+++def hash_workload_secret(secret: str) -> str:+ return hashlib.sha256(secret.encode()).hexdigest()+++def is_workload_secret(token: str) -> bool:+ return token.startswith(WORKLOAD_KEY_PREFIX)+++def _digest_matches(row: WorkloadIdentity, digest: str, *, now: datetime) -> bool:+ """Whether *digest* is this row's current secret, or its superseded one.++ Compared with :func:`hmac.compare_digest` rather than ``==``. Both+ values are already hashes, so a timing oracle leaks little, but this is+ a credential comparison and the cheap constant-time form is the one+ that does not have to be argued about.+ """+ if hmac.compare_digest(row.secret_hash, digest):+ return True+ if not row.previous_hash or not hmac.compare_digest(row.previous_hash, digest):+ return False+ # A superseded secret is only honoured inside its grace window, and a+ # row with no window is treated as expired rather than as unlimited:+ # "not set" must not be the most permissive state of a credential.+ expiry = row.previous_expires_at+ if expiry is None:+ return False+ return now < (expiry if expiry.tzinfo else expiry.replace(tzinfo=UTC))+++async def authenticate_workload(db: AsyncSession, secret: str) -> WorkloadIdentity | None:+ """The identity this secret belongs to, or ``None``.++ ``None`` covers every refusal — unknown, revoked, expired, or a+ superseded secret past its grace window — because the caller turns all+ of them into the same 401. Distinguishing them in the response would+ tell an attacker which guesses were close.+ """+ if not is_workload_secret(secret):+ return None++ now = datetime.now(UTC)+ digest = hash_workload_secret(secret)+ rows = await db.execute(select(WorkloadIdentity).where(WorkloadIdentity.secret_prefix == secret[:_PREFIX_LENGTH]))++ for row in rows.scalars().all():+ if row.revoked_at is not None:+ continue+ if row.expires_at is not None:+ expiry = row.expires_at if row.expires_at.tzinfo else row.expires_at.replace(tzinfo=UTC)+ if expiry <= now:+ continue+ if _digest_matches(row, digest, now=now):+ return row+ return None+++async def touch(db: AsyncSession, identity_id: uuid.UUID) -> None:+ """Record that a credential was used, best effort.++ ``last_used_at`` is what tells an operator a credential they are about+ to revoke is actually dead. Failing the request because the write+ failed would turn a bookkeeping error into an outage, so this logs and+ returns.+ """+ try:+ row = await db.get(WorkloadIdentity, identity_id)+ if row is not None:+ row.last_used_at = datetime.now(UTC)+ await db.commit()+ except Exception as exc: # noqa: BLE001 - bookkeeping must not deny a request+ await db.rollback()+ logger.warning("workload_identity.touch_failed: %s", str(exc).replace("\n", " ")[:200])+++async def rotate(db: AsyncSession, row: WorkloadIdentity, *, grace: timedelta = DEFAULT_ROTATION_GRACE) -> str:+ """Issue a new secret, keeping the old one alive for *grace*.++ Returns the new secret, which is shown once. The caller commits.++ Rotation in place is the whole reason the ``previous_*`` columns exist:+ the only path before was create, update every caller, delete — which is+ downtime, so most deployments never rotated at all.+ """+ secret, prefix, digest = mint_workload_secret()+ row.previous_hash = row.secret_hash+ row.previous_expires_at = datetime.now(UTC) + grace+ row.secret_hash = digest+ row.secret_prefix = prefix+ return secret+++def describe(row: WorkloadIdentity) -> dict[str, Any]:+ """The row as an API response. No secret material, ever."""+ return {+ "id": str(row.id),+ "service": row.service,+ "description": row.description,+ "scopes": list(row.scopes or []),+ "secret_prefix": row.secret_prefix,+ "rotation_pending_until": row.previous_expires_at.isoformat() if row.previous_expires_at else None,+ "expires_at": row.expires_at.isoformat() if row.expires_at else None,+ "last_used_at": row.last_used_at.isoformat() if row.last_used_at else None,+ "revoked_at": row.revoked_at.isoformat() if row.revoked_at else None,+ "created_at": row.created_at.isoformat() if row.created_at else None,+ }diff --git a/services/api/migrations/096_access_governance_permissions.sql b/services/api/migrations/096_access_governance_permissions.sqlnew file mode 100644index 000000000..1241f01e0--- /dev/null+++ b/services/api/migrations/096_access_governance_permissions.sql@@ -0,0 +1,80 @@+-- 096_access_governance_permissions.sql — the permission vocabulary for+-- ABAC conditions, time-boxed elevation and workload identities.+--+-- Depth plan item 8.2. Migration 087 created `permission_conditions`,+-- `privilege_grants` and `workload_identities` and shipped no reader for+-- any of them. The readers land in this change; these are the permission+-- rows the routes administering them enforce.+--+-- Why a new migration rather than an edit to 092+-- ----------------------------------------------+-- `092_rbac_catalog_seed.sql` has already run on every deployment, and the+-- runner tracks applied files in `aisoc_schema_migrations` — editing it+-- would seed these rows on a fresh install and on nobody else. A tenant+-- that had adopted database-backed RBAC would then hold a role that grants+-- a permission the catalog has no row for, which the Roles screen renders+-- as a blank.+--+-- `services/api/tests/test_rbac_catalog_seed.py` pins the migration+-- vocabulary against `app/core/rbac_catalog.py`. It reads every migration+-- that seeds permissions rather than only 092, so the vocabulary can grow+-- the only way it safely can — in a new file — and still cannot drift.+--+-- Idempotent: every statement is ON CONFLICT-aware. No secrets.++BEGIN;++-- ─── Permission catalog additions ───────────────────────────────────────────+--+-- `elevation:*` govern time-boxed grants. Request and approve are separate+-- permissions on purpose: an approver who can also request is both parties+-- to the decision, and the control reduces to a log line.+--+-- `workload_identities:*` govern deployment-wide service credentials. They+-- are granted below to no tenant-scoped role, which is deliberate rather+-- than an omission: a workload credential authenticates before any tenant+-- is known and acts for whichever tenant it names per request, so minting+-- one from a tenant-scoped session would confer cross-tenant authority.+-- Only the wildcard roles (`admin`, `platform_admin`) hold them.+INSERT INTO permissions (name, description, category) VALUES+ ('elevation:read', 'View the tenant''s privilege elevations', 'access'),+ ('elevation:request', 'Request a time-boxed privilege elevation', 'access'),+ ('elevation:approve', 'Approve or revoke a privilege elevation', 'access'),+ ('access_conditions:read', 'View attribute conditions on permissions', 'access'),+ ('access_conditions:write', 'Add, disable or remove attribute conditions', 'access'),+ ('workload_identities:read', 'View per-service internal credentials', 'access'),+ ('workload_identities:write', 'Mint, rotate or revoke per-service credentials', 'access')+ON CONFLICT (name) DO UPDATE+ SET description = EXCLUDED.description,+ category = EXCLUDED.category;++-- ─── Grants ─────────────────────────────────────────────────────────────────+--+-- Every tenant that has already adopted the catalog, not just the primary+-- one. 092 scoped its grants to the seed tenant because it was creating the+-- roles; here the roles already exist wherever they exist, and a tenant+-- that adopted the catalog through `POST /api/v1/rbac/roles/seed` must not+-- be left with an analyst who cannot ask for an elevation.+--+-- `admin` already holds `*` and needs no row.+INSERT INTO role_permissions (role_id, permission_id)+SELECT r.id, p.id+ FROM roles r+ JOIN permissions p ON (r.name = 'infosec' AND p.name IN (+ 'elevation:request'+ ))+ON CONFLICT DO NOTHING;++COMMIT;++-- Rollback (documented, not executed):+--+-- DELETE FROM role_permissions+-- WHERE permission_id IN (SELECT id FROM permissions WHERE category = 'access');+-- DELETE FROM permissions WHERE category = 'access';+--+-- Removing the rows does not disable the feature: `require_permission`+-- reads the resolved set, and a permission with no catalog row simply+-- cannot be granted through the console. To turn enforcement off, delete+-- the `permission_conditions` and `privilege_grants` rows instead — those+-- are what `CurrentUser.require_permission` reads.diff --git a/services/api/tests/test_access_governance.py b/services/api/tests/test_access_governance.pynew file mode 100644index 000000000..58df5e2d3--- /dev/null+++ b/services/api/tests/test_access_governance.py@@ -0,0 +1,474 @@+"""ABAC conditions, elevation and workload identities, offline.++Depth plan item 8.2. The live half is+``tests/isolation/test_abac_elevation_live.py``, which drives real routes+against real Postgres; this half covers the decisions that do not need a+database and the two vocabularies that have to agree with each other.++What this file cannot prove, and says so+-----------------------------------------+That the tables have readers. A fake session answers any query, which is+the exact shape that let three tables ship with no reader and every+offline suite stay green. Everything here is about *shape*: given a+principal already carrying grants and conditions, does the one permission+path reach the right verdict.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from typing import Any++import pytest+from app.api.v1.deps import SERVICE_TENANT_HEADER, CurrentUser, _condition_applies+from app.api.v1.endpoints.access_conditions import ADDRESSABLE_ATTRIBUTES, SUPPORTED+from app.api.v1.endpoints.api_keys import VALID_SCOPES+from app.api.v1.endpoints.elevation import MAX_DURATION+from app.core.rbac_catalog import PERMISSIONS+from app.core.security import ROLE_PERMISSIONS+from app.models.enterprise_iam import WorkloadIdentity+from app.security.abac import OPERATORS, PrivilegeGrant+from app.services import workload_identity as wi+from fastapi import HTTPException++TENANT = uuid.uuid4()+USER = uuid.uuid4()+++def _principal(+ *,+ role: str = "viewer",+ scopes: list[str] | None = None,+ resolved_permissions: frozenset[str] | None = frozenset({"alerts:read"}),+ elevation: tuple[PrivilegeGrant, ...] = (),+ conditions: tuple[dict[str, Any], ...] = (),+ attributes: dict[str, Any] | None = None,+) -> CurrentUser:+ """A principal with the defaults these tests vary from.++ Explicit keywords rather than `**kwargs`: a dict splatted into a typed+ constructor widens every value to `object`, which cost 13 `arg-type`+ findings and, more to the point, means a test could pass a `conditions`+ list where a tuple is expected and nothing would say so.+ """+ return CurrentUser(+ user_id=USER,+ tenant_id=TENANT,+ role=role,+ email="[email protected]",+ scopes=scopes,+ resolved_permissions=resolved_permissions,+ elevation=elevation,+ conditions=conditions,+ attributes=attributes,+ )+++def _digest(label: str) -> str:+ """A real SHA-256 digest, computed rather than written as a literal.++ Two reasons. A 64-character hex literal in a test file is+ credential-shaped, and the secret scanner is right to say so. And a+ computed digest is what the code under test actually compares, so the+ fixture cannot drift from the real hash function.+ """+ return wi.hash_workload_secret(f"fixture-{label}")+++def _row(**overrides: Any) -> WorkloadIdentity:+ """A real `WorkloadIdentity`, not a stand-in class.++ The hand-rolled double this replaced answered for whichever attributes a+ test happened to read, which is the shape that lets a double be more+ capable than the thing it stands for. The ORM model constructs fine+ without a session, so there is no reason to use anything else.+ """+ fields: dict[str, Any] = {+ "id": uuid.uuid4(),+ "service": "agents",+ "description": None,+ "scopes": ["alerts:read"],+ "secret_prefix": wi.WORKLOAD_KEY_PREFIX + "abc1234",+ "secret_hash": _digest("current"),+ "previous_hash": None,+ "previous_expires_at": None,+ "expires_at": None,+ "last_used_at": None,+ "revoked_at": None,+ "created_at": None,+ }+ fields.update(overrides)+ return WorkloadIdentity(**fields)+++def _grant(permissions: list[str], *, minutes: int = 30, revoked: bool = False) -> PrivilegeGrant:+ return PrivilegeGrant(+ permissions=tuple(permissions),+ expires_at=datetime.now(UTC) + timedelta(minutes=minutes),+ revoked_at=datetime.now(UTC) if revoked else None,+ )+++class TestElevationAppliesAtUse:+ def test_a_live_grant_widens_the_resolved_set(self) -> None:+ user = _principal(elevation=(_grant(["cases:write"]),))+ user.require_permission("cases:write")++ def test_an_expired_grant_does_not(self) -> None:+ """Expiry with no sweep job in the path.++ The grant is held rather than merged precisely so this is decided+ here, on every check, instead of when a cache entry lapses.+ """+ user = _principal(elevation=(_grant(["cases:write"], minutes=-1),))+ with pytest.raises(HTTPException) as exc:+ user.require_permission("cases:write")+ assert exc.value.status_code == 403++ def test_a_revoked_grant_does_not(self) -> None:+ user = _principal(elevation=(_grant(["cases:write"], revoked=True),))+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_elevation_does_not_widen_an_api_key(self) -> None:+ """A key's scopes are a narrower grant chosen at mint time.++ Letting a person's temporary elevation flow into a bearer key they+ minted last year would make the elevation outlive its own window+ by however long the key lives.+ """+ user = _principal(scopes=["alerts:read"], elevation=(_grant(["cases:write"]),))+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_the_downstream_list_agrees_with_the_check(self) -> None:+ """`services/actions` re-authorises against `effective_permissions`.++ Two answers from two orders would surface as an intermittent 403+ on approval rather than as a bug.+ """+ user = _principal(elevation=(_grant(["cases:write"]),))+ user.require_permission("cases:write")+ assert "cases:write" in user.effective_permissions()++ def test_an_expired_grant_is_absent_from_the_downstream_list_too(self) -> None:+ user = _principal(elevation=(_grant(["cases:write"], minutes=-1),))+ assert "cases:write" not in user.effective_permissions()+++class TestConditionsNarrowAndNeverGrant:+ def test_a_failing_condition_denies_a_permission_the_role_holds(self) -> None:+ user = _principal(+ resolved_permissions=frozenset({"cases:write"}),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={"source_ip": "203.0.113.4"},+ )+ with pytest.raises(HTTPException) as exc:+ user.require_permission("cases:write")+ assert exc.value.status_code == 403+ assert "access condition" in str(exc.value.detail)++ def test_a_condition_cannot_grant_a_permission_the_role_lacks(self) -> None:+ """The property the whole design rests on.++ A condition that could grant would be a second authorization+ system reaching a different answer from the first.+ """+ user = _principal(+ resolved_permissions=frozenset({"alerts:read"}),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "0.0.0.0/0"},),+ attributes={"source_ip": "10.1.1.1"},+ )+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_conditions_bind_an_api_key_too(self) -> None:+ """Narrowing applies on every branch.++ A rule that bound console sessions and silently not keys would be+ the kind of partial control nobody notices until an audit.+ """+ user = _principal(+ scopes=["cases:write"],+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={"source_ip": "203.0.113.4"},+ )+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_conditions_bind_the_static_map_branch_too(self) -> None:+ user = CurrentUser(+ user_id=USER,+ tenant_id=TENANT,+ role="tenant_admin",+ email="[email protected]",+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={"source_ip": "203.0.113.4"},+ )+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_an_indeterminate_condition_denies(self) -> None:+ """A request carrying nothing to judge on has not satisfied anything.++ Treating it as satisfied would mean a caller who omits a header is+ less constrained than one who sends it, which inverts the control.+ """+ user = _principal(+ resolved_permissions=frozenset({"cases:write"}),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={},+ )+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_an_unconditioned_permission_is_untouched(self) -> None:+ """The negative control: narrowing only narrows what it names."""+ user = _principal(+ resolved_permissions=frozenset({"cases:write", "alerts:read"}),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={"source_ip": "203.0.113.4"},+ )+ user.require_permission("alerts:read")++ @pytest.mark.parametrize(+ ("row_permission", "checked", "applies"),+ [+ ("cases:write", "cases:write", True),+ ("cases:*", "cases:write", True),+ ("*", "cases:write", True),+ ("cases:read", "cases:write", False),+ ("alerts:*", "cases:write", False),+ ],+ )+ def test_scope_matching(self, row_permission: str, checked: str, applies: bool) -> None:+ row = {"permission": row_permission, "role": None}+ assert _condition_applies(row, checked, "viewer") is applies++ def test_a_role_scoped_condition_does_not_bind_other_roles(self) -> None:+ row = {"permission": "cases:write", "role": "soc_analyst"}+ assert _condition_applies(row, "cases:write", "soc_analyst") is True+ assert _condition_applies(row, "cases:write", "tenant_admin") is False+++class TestAttributeBindingNeverBreaksAuthentication:+ """Binding attributes is advisory; it must not be able to 401 a valid session.++ `bind_connection_attributes` reads the connection, and the graph+ WebSocket upgrade goes through it as well as every HTTP route. A+ `WebSocket` is not a `Request`, and an ASGI connection is not+ obliged to expose a peer address at all, so reading one must+ degrade rather than raise -- an `AttributeError` here surfaces as+ an authenticated user being unable to open a socket, which reads+ as an outage and not as a permission problem.++ Degrading is safe in the direction that matters: an unknown+ address makes an address condition indeterminate, and+ indeterminate denies.+ """++ class _NoPeer:+ """An ASGI connection that exposes no peer, like the graph socket's."""++ class _Peer:+ def __init__(self, host: str) -> None:+ self.client = SimpleNamespace(host=host)+ self.headers: dict[str, str] = {}++ def test_a_connection_without_a_peer_binds_rather_than_raising(self) -> None:+ user = _principal(resolved_permissions=frozenset({"cases:write"}))+ user.bind_connection_attributes(self._NoPeer())+ assert user.attributes["source_ip"] is None++ def test_an_address_condition_then_denies_rather_than_passing(self) -> None:+ """The fail-closed half. If an unknown address passed, every+ attribute condition would be bypassable by connecting over a+ transport that reports no peer."""+ user = _principal(+ resolved_permissions=frozenset({"cases:write"}),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ )+ user.bind_connection_attributes(self._NoPeer())+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")++ def test_a_connection_with_a_peer_still_carries_the_address(self) -> None:+ """The negative control. Binding that always produced `None`+ would pass both tests above and silently deny every address+ condition on every real request."""+ user = _principal(resolved_permissions=frozenset({"cases:write"}))+ user.bind_connection_attributes(self._Peer("10.1.2.3"))+ assert user.attributes["source_ip"] == "10.1.2.3"+ user.require_permission("cases:write")+++class TestElevationAndConditionsCompose:+ def test_an_elevated_permission_is_still_narrowed(self) -> None:+ """Order matters: if grants were applied after conditions,+ elevation would be a way around every attribute rule."""+ user = _principal(+ elevation=(_grant(["cases:write"]),),+ conditions=({"permission": "cases:write", "operator": "ip_in_cidr", "value": "10.0.0.0/8"},),+ attributes={"source_ip": "203.0.113.4"},+ )+ with pytest.raises(HTTPException):+ user.require_permission("cases:write")+++class TestTheTwoVocabulariesAgree:+ def test_every_supported_operator_is_a_real_one(self) -> None:+ assert set(SUPPORTED) <= set(OPERATORS)++ def test_every_new_permission_is_in_the_seeded_catalog(self) -> None:+ """A permission no catalog row names cannot be granted from the+ console, so the Roles screen renders the grant as a blank."""+ catalog = {name for name, _d, _c in PERMISSIONS}+ for permission in (+ "elevation:read",+ "elevation:request",+ "elevation:approve",+ "access_conditions:read",+ "access_conditions:write",+ "workload_identities:read",+ "workload_identities:write",+ ):+ assert permission in catalog, f"{permission} is enforced but not seeded"++ def test_every_new_permission_is_mintable_into_a_key(self) -> None:+ """`hunts:read` was once held by no role and absent from this set,+ so only a wildcard key could exercise it."""+ for permission in (+ "elevation:read",+ "elevation:request",+ "elevation:approve",+ "access_conditions:read",+ "access_conditions:write",+ "workload_identities:read",+ "workload_identities:write",+ ):+ assert permission in VALID_SCOPES, f"{permission} can only be reached by a wildcard key"++ def test_a_non_wildcard_role_can_request_and_approve_an_elevation(self) -> None:+ """Otherwise the feature is reachable only by principals who do not+ need it, which is how `hunts:read` ended up held by nobody."""+ assert "elevation:request" in ROLE_PERMISSIONS["soc_analyst"]+ assert "elevation:approve" in ROLE_PERMISSIONS["soc_lead"]+ assert "elevation:approve" in ROLE_PERMISSIONS["tenant_admin"]++ def test_an_analyst_cannot_approve_their_own_class_of_request(self) -> None:+ """Separation of duties starts in the role map, before the+ per-request check that an approver is not the requester."""+ assert "elevation:approve" not in ROLE_PERMISSIONS["soc_analyst"]+ assert "elevation:approve" not in ROLE_PERMISSIONS["threat_hunter"]+ assert "elevation:approve" not in ROLE_PERMISSIONS["viewer"]++ def test_workload_credentials_are_a_platform_act_not_a_tenant_one(self) -> None:+ """Deliberate, and the reason is in the route module: a workload+ credential acts for whichever tenant it names, so minting one from+ a tenant-scoped session would confer cross-tenant authority."""+ for role, permissions in ROLE_PERMISSIONS.items():+ if "*" in permissions:+ continue+ assert "workload_identities:write" not in permissions, f"{role} can mint a deployment-wide credential"++ def test_the_addressable_attributes_are_ones_the_binding_produces(self) -> None:+ """A condition on an attribute nothing supplies is indeterminate,+ and indeterminate denies — a permanent 403 with no explanation.++ Read off the binding's source rather than by calling it, because+ constructing a request good enough to bind against would mock the+ very thing in question.+ """+ import inspect # noqa: PLC0415++ source = inspect.getsource(CurrentUser.bind_connection_attributes)+ for attribute in ADDRESSABLE_ATTRIBUTES:+ assert f'"{attribute}"' in source, f"{attribute!r} is addressable but the binding never sets it"++ def test_the_elevation_ceiling_is_short_enough_to_mean_something(self) -> None:+ """A grant that can run for a month is standing access with paperwork."""+ assert timedelta(minutes=5) < MAX_DURATION <= timedelta(hours=24)+++class TestWorkloadSecrets:+ def test_a_workload_secret_is_not_mistaken_for_an_api_key(self) -> None:+ """`aisoc_wl_` is a strict extension of `aisoc_`, so the API-key+ branch matches it too and the ordering in `get_current_user` is+ load-bearing. Pinned here so an edit that reorders the branches+ fails rather than producing a 401 that reads as a bad credential.+ """+ import inspect # noqa: PLC0415++ from app.api.v1 import deps # noqa: PLC0415++ secret, _prefix, _digest = wi.mint_workload_secret()+ assert secret.startswith("aisoc_"), "the overlap this test exists for has gone; simplify the branches"+ assert wi.is_workload_secret(secret)++ source = inspect.getsource(deps.get_current_user)+ assert source.index("is_workload_secret(token)") < source.index("token.startswith(_API_KEY_PREFIX)"), (+ "the API-key branch now runs before the workload branch, so every workload credential "+ "is resolved as an unknown API key and answered 401"+ )++ def test_the_secret_is_never_stored_in_the_clear(self) -> None:+ secret, prefix, digest = wi.mint_workload_secret()+ assert digest != secret+ assert digest == wi.hash_workload_secret(secret)+ assert secret.startswith(prefix)+ assert len(secret) > len(prefix) + 32, "the stored prefix leaves too little secret material"++ def test_describe_carries_no_secret_material(self) -> None:+ """This is the list response. A hash in it is a hash to grind."""+ current, superseded = _digest("current"), _digest("superseded")+ row = _row(secret_hash=current, previous_hash=superseded)++ rendered = wi.describe(row)++ assert current not in str(rendered)+ assert superseded not in str(rendered)+ assert rendered["secret_prefix"] == wi.WORKLOAD_KEY_PREFIX + "abc1234"++ def test_a_superseded_secret_with_no_window_is_refused(self) -> None:+ """ "Not set" must not be the most permissive state of a credential."""+ current, superseded = _digest("current"), _digest("superseded")+ row = _row(secret_hash=current, previous_hash=superseded, previous_expires_at=None)++ assert wi._digest_matches(row, superseded, now=datetime.now(UTC)) is False+ assert wi._digest_matches(row, current, now=datetime.now(UTC)) is True++ def test_a_superseded_secret_inside_its_window_still_works(self) -> None:+ """Rotation without downtime is the whole reason those columns exist."""+ current, superseded = _digest("current"), _digest("superseded")+ row = _row(+ secret_hash=current,+ previous_hash=superseded,+ previous_expires_at=datetime.now(UTC) + timedelta(hours=1),+ )++ assert wi._digest_matches(row, superseded, now=datetime.now(UTC)) is True++ def test_a_superseded_secret_past_its_window_does_not(self) -> None:+ current, superseded = _digest("current"), _digest("superseded")+ row = _row(+ secret_hash=current,+ previous_hash=superseded,+ previous_expires_at=datetime.now(UTC) - timedelta(seconds=1),+ )++ assert wi._digest_matches(row, superseded, now=datetime.now(UTC)) is False+++class TestTheTenantIsNeverCallerChosen:+ def test_the_service_tenant_header_is_the_only_channel(self) -> None:+ """One shared credential with no tenant is a cross-tenant read, and+ a tenant read from a body is a tenant the caller picked."""+ import inspect # noqa: PLC0415++ from app.api.v1 import deps # noqa: PLC0415++ source = inspect.getsource(deps._resolve_workload_principal)+ assert "_resolve_tenant_for_service" in source, "the workload path no longer verifies the declared tenant"+ assert SERVICE_TENANT_HEADER == "X-AiSOC-Tenant-ID"diff --git a/services/api/tests/test_rbac_catalog_seed.py b/services/api/tests/test_rbac_catalog_seed.pyindex d09a3a1a6..f6a798d1e 100644--- a/services/api/tests/test_rbac_catalog_seed.py+++ b/services/api/tests/test_rbac_catalog_seed.py@@ -21,13 +21,51 @@ from app.core.rbac_catalog import (SYSTEM_ROLES,)-MIGRATION = Path(__file__).resolve().parents[1] / "migrations" / "092_rbac_catalog_seed.sql"+MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"+MIGRATION = MIGRATIONS_DIR / "092_rbac_catalog_seed.sql"def _migration_sql() -> str:return MIGRATION.read_text(encoding="utf-8")+#: Rows a migration seeds that ``rbac_catalog.PERMISSIONS`` deliberately+#: does not claim, each with the reason. An entry here is a finding, not an+#: exception: the row exists in every deployment's ``permissions`` table and+#: is enforced by nothing.+#:+#: Widening this test from one migration to all of them is what found it.+#: Reconciling it is a product decision — delete the row, or give the verb a+#: route — and absorbing it silently into the module's vocabulary would have+#: made the catalog claim a permission the product does not enforce.+PRE_CATALOG_ORPHANS: dict[str, str] = {+ "playbooks:delete": (+ "seeded by 003_rbac.sql, before app/core/rbac_catalog.py existed. No route in the "+ "tree enforces it, so the row is catalog-only. Recorded rather than adopted."+ ),+}+++def _seeding_migrations() -> list[str]:+ """Every migration that seeds the permission catalog, oldest first.++ 092 has already run on every deployment and the runner tracks applied+ files, so a permission added to the module can only reach an existing+ deployment through a *new* migration. Pinning against 092 alone would+ make the only correct way to add one fail this test, and the tempting+ fix — editing an applied migration — seeds the row on fresh installs+ and on nobody else.++ Derived from the tree rather than from a list, so the next addition+ does not have to remember this function exists.+ """+ seeding = [+ sql for sql in (p.read_text(encoding="utf-8") for p in sorted(MIGRATIONS_DIR.glob("*.sql"))) if "INSERT INTO permissions" in sql+ ]+ assert seeding, "no migration seeds the permission catalog, so the pin below would be vacuous"+ return seeding++def test_migration_exists() -> None:assert MIGRATION.exists(), f"missing migration: {MIGRATION}"@@ -40,14 +78,21 @@ def _migration_permission_rows(sql: str) -> set[str]:def test_permission_names_pinned() -> None:- """The permission rows the migration inserts must exactly equal the+ """The permission rows the migrations insert must exactly equal themodule's PERMISSIONS vocabulary."""- sql = _migration_sql()- in_migration = _migration_permission_rows(sql)+ in_migration: set[str] = set()+ for sql in _seeding_migrations():+ in_migration |= _migration_permission_rows(sql)in_module = {name for name, _desc, _cat in PERMISSIONS}- assert in_migration == in_module, (- f"permission vocabulary drifted; only-in-migration={sorted(in_migration - in_module)}, "- f"only-in-module={sorted(in_module - in_migration)}"++ assert in_migration - in_module == set(PRE_CATALOG_ORPHANS), (+ "permission vocabulary drifted; a migration seeds a permission the module does not declare: "+ f"{sorted((in_migration - in_module) - set(PRE_CATALOG_ORPHANS))}. "+ f"Stale orphan entries (seeded nowhere any more): {sorted(set(PRE_CATALOG_ORPHANS) - in_migration)}"+ )+ assert not in_module - in_migration, (+ "the module declares a permission no migration seeds, so an existing deployment's catalog "+ f"has no row for it and the console renders it blank: {sorted(in_module - in_migration)}")@@ -60,20 +105,26 @@ def test_system_role_names_pinned() -> None:def test_role_grants_pinned() -> None:- """The migration's inline viewer/infosec IN-lists must equal the- module's ROLE_GRANTS sets; admin is the wildcard in both."""- sql = _migration_sql()+ """The migrations' inline viewer/infosec IN-lists must equal the+ module's ROLE_GRANTS sets; admin is the wildcard in both.++ Unioned across migrations for the same reason the permission names+ are: a grant added to the module reaches an existing deployment only+ through a new file.+ """assert ROLE_GRANTS["admin"] == frozenset({"*"}), "admin wildcard grant drifted"- assert "'admin' AND p.name = '*'" in sql, "migration no longer grants admin the wildcard"+ assert "'admin' AND p.name = '*'" in _migration_sql(), "migration no longer grants admin the wildcard"for role in ("viewer", "infosec"):- block = re.search(- rf"r\.name\s*=\s*'{role}'\s+AND\s+p\.name\s+IN\s*\((.*?)\)\s*\)",- sql,- re.DOTALL,- )- assert block, f"could not locate the grant IN-list for role '{role}' in 092"- in_migration = set(re.findall(r"'([a-z_]+:[a-z_]+|\*)'", block.group(1)))+ in_migration: set[str] = set()+ for sql in _seeding_migrations():+ for block in re.findall(+ rf"r\.name\s*=\s*'{role}'\s+AND\s+p\.name\s+IN\s*\((.*?)\)\s*\)",+ sql,+ re.DOTALL,+ ):+ in_migration |= set(re.findall(r"'([a-z_]+:[a-z_]+|\*)'", block))+ assert in_migration, f"could not locate any grant IN-list for role '{role}'"in_module = set(ROLE_GRANTS[role])assert in_migration == in_module, (f"grants drifted for role '{role}': "diff --git a/tests/isolation/test_abac_elevation_live.py b/tests/isolation/test_abac_elevation_live.pynew file mode 100644index 000000000..5c74765a2--- /dev/null+++ b/tests/isolation/test_abac_elevation_live.py@@ -0,0 +1,576 @@+"""ABAC conditions, time-boxed elevation and workload identities, live.++Depth plan item 8.2. Migration ``087_enterprise_iam.sql`` created three+tables — ``permission_conditions``, ``privilege_grants`` and+``workload_identities`` — and shipped **no reader for any of them**. The+repository said so itself: ``CHANGELOG.md`` records "nothing reads any of+them", and ``FIX_PASS_PROGRESS.md`` retracted the claim. ``app/security/abac.py``+is a complete, tested evaluator whose only importer was+``role_grants.narrow_by_conditions``, which had no caller either.++A table with no reader cannot be distinguished from a working control by any+offline suite, because the offline suite mocks the database the reader would+have queried. So this drives the real application against real Postgres with+every migration applied, mints real JWTs, and asks the question at the only+layer that answers it: what status code does the route return?++Production posture, deliberately+--------------------------------+``ENVIRONMENT=production``. ``development`` is in ``AUTH_BYPASS_ENVIRONMENTS``,+so an uncredentialed request there resolves to a demo **admin** — inside the+one suite whose purpose is proving that authorization narrows, that would make+every assertion pass for the wrong reason.++Both directions, every time+---------------------------+An authorization control is only proven by its refusal, so each capability is+asserted in both directions:++* a condition that does not match **denies**, and the same request with no+ condition configured **succeeds** — otherwise a route that 403s on+ everything would satisfy the first assertion;+* an elevation grant **allows** a permission the role lacks, and the same+ grant **expired** or **revoked** denies it again;+* a workload credential **authenticates** and a revoked one does not.+"""++from __future__ import annotations++import os+import uuid+from datetime import UTC, datetime, timedelta++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_IAM_DSN", "").strip(),+ reason="ISOLATION_IAM_DSN is not set; this suite needs a live Postgres",+ ),+]++#: The test client's peer address under ``httpx.ASGITransport``. Conditions+#: are written to match or miss it deliberately rather than by luck.+CLIENT_IP = "127.0.0.1"+MATCHING_CIDR = "127.0.0.0/8"+MISSING_CIDR = "10.0.0.0/8"++SIGNING_SECRET = "ci-access-governance-signing-secret-at-least-32-chars"+++def _dsn() -> str:+ """What the **application** connects as: the DML-only runtime role.++ Not the schema owner. A superuser ignores every row-level-security policy+ even under `FORCE ROW LEVEL SECURITY`, so a suite about authorization run+ as one proves less than it appears to —+ `scripts/check_runtime_db_role.py` holds that line across every+ deployment surface and caught this job's first draft doing it.+ """+ value = os.environ.get("ISOLATION_IAM_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_IAM_DSN is not set")+ return value+++def _admin_dsn() -> str:+ """What the **fixtures** connect as, standing in for a migration.++ `privilege_grants` and `permission_conditions` carry+ `WITH CHECK (tenant_id = current_tenant_id())`, so an INSERT as the+ runtime role with no tenant context set is refused — correctly. Seeding+ is an owner's act, which is why it gets its own credential rather than+ the suite relaxing the policy it is here to exercise.++ Falls back to the application DSN so a single-role local database still+ works; CI sets both.+ """+ return os.environ.get("ISOLATION_IAM_ADMIN_DSN", "").strip() or _dsn()+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def app_client():+ """The real application, in production posture, against real Postgres."""+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ os.environ["ENVIRONMENT"] = "production"+ os.environ["SECRET_KEY"] = SIGNING_SECRET+ # No trusted proxies, so `resolve_client_ip` returns the direct peer and+ # an X-Forwarded-For header cannot move a principal into a permitted+ # range. That property gets its own assertion below.+ os.environ.pop("AISOC_TRUSTED_PROXIES", None)++ import httpx+ from app.main import create_application++ application = create_application()+ transport = httpx.ASGITransport(app=application, client=(CLIENT_IP, 51234))+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ yield client+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def pool():+ asyncpg = pytest.importorskip("asyncpg")+ created = await asyncpg.create_pool(_admin_dsn().replace("postgresql+asyncpg://", "postgresql://"), min_size=1, max_size=4)+ yield created+ await created.close()++[email protected](autouse=True)+def _clean_permission_cache():+ """A resolved set cached from a previous test would answer the next one.++ The cache is keyed on an RBAC version counter the production grant paths+ bump; these tests write rows with SQL, so they clear it by hand.+ """+ from app.core.permission_cache import reset_for_tests++ reset_for_tests()+ yield+ reset_for_tests()+++async def _tenant_with_user(pool, *, role: str) -> tuple[str, str]:+ """A tenant and one active user holding ``role``, by raw SQL.++ No RBAC rows, so `resolve_permissions` takes its documented bootstrap+ path and the static map answers — which is the configuration almost every+ deployment is in, and therefore the one an attribute condition has to+ narrow.+ """+ tenant_id, user_id = str(uuid.uuid4()), str(uuid.uuid4())+ async with pool.acquire() as conn:+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1::uuid, $2, $3)",+ tenant_id,+ "iam-depth-82",+ f"iam82-{tenant_id[:8]}",+ )+ await conn.execute(+ """+ INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active)+ VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, TRUE)+ """,+ user_id,+ tenant_id,+ f"u-{user_id[:8]}@iam82.test",+ f"u-{user_id[:8]}",+ "x" * 60,+ role,+ )+ return tenant_id, user_id+++def _token(user_id: str, tenant_id: str) -> str:+ """A real access token, signed with the key the server verifies against."""+ from app.core.security import create_access_token++ return create_access_token({"sub": user_id, "tenant_id": tenant_id})+++def _auth(user_id: str, tenant_id: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {_token(user_id, tenant_id)}"}+++async def _condition(pool, tenant_id: str, *, permission: str, operator: str, value) -> None: # noqa: ANN001+ import json++ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO permission_conditions (tenant_id, permission, condition, description, enabled)+ VALUES ($1::uuid, $2, $3::jsonb, $4, TRUE)+ """,+ tenant_id,+ permission,+ json.dumps({"operator": operator, "value": value}),+ f"{operator} on {permission}",+ )+++async def _grant(+ pool,+ tenant_id: str,+ user_id: str,+ *,+ permissions: list[str],+ expires_in: timedelta = timedelta(minutes=30),+ revoked: bool = False,+ approved: bool = True,+) -> str:+ """One elevation row. ``approved`` defaults on; the off case is a test.++ A row with ``approved_by_id IS NULL`` is a *request*, not a grant, and+ must confer nothing — otherwise approval is a record rather than a gate.+ """+ approver = None+ if approved:+ _, approver = await _tenant_with_user(pool, role="tenant_admin")+ async with pool.acquire() as conn:+ row = await conn.fetchrow(+ """+ INSERT INTO privilege_grants+ (tenant_id, user_id, permissions, justification, approved_by_id, expires_at, revoked_at)+ VALUES ($1::uuid, $2::uuid, $3::text[], $4, $5::uuid, $6, $7)+ RETURNING id+ """,+ tenant_id,+ user_id,+ permissions,+ "isolation suite",+ approver,+ datetime.now(UTC) + expires_in,+ datetime.now(UTC) if revoked else None,+ )+ return str(row["id"])+++def _case_body() -> dict:+ return {"title": f"iam-82 {uuid.uuid4().hex[:8]}", "severity": "low"}+++class TestAnAttributeConditionNarrowsThePermission:+ """`permission_conditions` had no reader, so every row in it was inert."""++ async def test_a_condition_that_does_not_match_denies(self, app_client, pool) -> None: # noqa: ANN001+ """The reproduce case.++ A `tenant_admin` holds `cases:write` statically. A condition+ restricting that permission to a CIDR the caller is not in must refuse+ the request. Against the pre-fix tree the row is never read and the+ case is created — a 201 where the operator configured a denial.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")+ await _condition(pool, tenant_id, permission="cases:write", operator="ip_in_cidr", value=MISSING_CIDR)++ resp = await app_client.post("/api/v1/cases", headers=_auth(user_id, tenant_id), json=_case_body())++ assert resp.status_code == 403, (+ f"a permission_conditions row restricting cases:write to {MISSING_CIDR} did not refuse a "+ f"caller from {CLIENT_IP}; got {resp.status_code}. The table has no reader."+ )++ async def test_with_no_condition_configured_the_same_request_succeeds(self, app_client, pool) -> None: # noqa: ANN001+ """The negative control for the assertion above.++ Without this, a route that refused everything would satisfy it.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")++ resp = await app_client.post("/api/v1/cases", headers=_auth(user_id, tenant_id), json=_case_body())++ assert resp.status_code == 201, f"an unconditioned cases:write was refused ({resp.status_code}): {resp.text[:300]}"++ async def test_a_condition_that_matches_allows(self, app_client, pool) -> None: # noqa: ANN001+ """Conditions narrow; a satisfied one must not itself become a denial."""+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")+ await _condition(pool, tenant_id, permission="cases:write", operator="ip_in_cidr", value=MATCHING_CIDR)++ resp = await app_client.post("/api/v1/cases", headers=_auth(user_id, tenant_id), json=_case_body())++ assert resp.status_code == 201, f"a satisfied condition refused the request ({resp.status_code}): {resp.text[:300]}"++ async def test_a_condition_on_another_permission_does_not_leak(self, app_client, pool) -> None: # noqa: ANN001+ """A condition is scoped to the permission it names.++ An evaluator that applied every row to every check would make one+ narrow rule a tenant-wide outage.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")+ await _condition(pool, tenant_id, permission="rules:write", operator="ip_in_cidr", value=MISSING_CIDR)++ resp = await app_client.post("/api/v1/cases", headers=_auth(user_id, tenant_id), json=_case_body())++ assert resp.status_code == 201, f"a condition on rules:write refused cases:write ({resp.status_code})"++ async def test_a_forwarded_header_cannot_move_the_caller_into_the_permitted_range(self, app_client, pool) -> None: # noqa: ANN001+ """The attribute must not be one the caller can set.++ With no trusted proxies configured, `X-Forwarded-For` is ignored, so a+ caller cannot satisfy an address condition by claiming an address.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")+ await _condition(pool, tenant_id, permission="cases:write", operator="ip_in_cidr", value=MISSING_CIDR)++ headers = {**_auth(user_id, tenant_id), "X-Forwarded-For": "10.1.2.3"}+ resp = await app_client.post("/api/v1/cases", headers=headers, json=_case_body())++ assert resp.status_code == 403, f"a caller satisfied an address condition by sending X-Forwarded-For; got {resp.status_code}"++ async def test_a_disabled_condition_is_not_applied(self, app_client, pool) -> None: # noqa: ANN001+ """`enabled = FALSE` is how an operator turns a rule off without deleting it."""+ tenant_id, user_id = await _tenant_with_user(pool, role="tenant_admin")+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO permission_conditions (tenant_id, permission, condition, enabled)+ VALUES ($1::uuid, 'cases:write', '{"operator": "ip_in_cidr", "value": "10.0.0.0/8"}'::jsonb, FALSE)+ """,+ tenant_id,+ )++ resp = await app_client.post("/api/v1/cases", headers=_auth(user_id, tenant_id), json=_case_body())++ assert resp.status_code == 201, f"a disabled condition was still enforced ({resp.status_code})"++ async def test_another_tenants_condition_does_not_apply(self, app_client, pool) -> None: # noqa: ANN001+ """Conditions are tenant-scoped, and a reader that forgot the predicate+ would let one tenant's policy refuse another tenant's work."""+ victim_tenant, victim_user = await _tenant_with_user(pool, role="tenant_admin")+ other_tenant, _ = await _tenant_with_user(pool, role="tenant_admin")+ await _condition(pool, other_tenant, permission="cases:write", operator="ip_in_cidr", value=MISSING_CIDR)++ resp = await app_client.post("/api/v1/cases", headers=_auth(victim_user, victim_tenant), json=_case_body())++ assert resp.status_code == 201, f"another tenant's condition refused this tenant's request ({resp.status_code})"+++class TestElevationIsTimeBoxed:+ """`privilege_grants` had no reader, so an approved elevation did nothing."""++ async def test_a_live_grant_confers_a_permission_the_role_lacks(self, app_client, pool) -> None: # noqa: ANN001+ """The reproduce case. A viewer does not hold `roles:read`."""+ from app.core.security import ROLE_PERMISSIONS++ assert "roles:read" not in ROLE_PERMISSIONS["viewer"]++ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, user_id, permissions=["roles:read"])++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 200, (+ f"a live privilege_grants row conferring roles:read did not take effect; got {resp.status_code}. The table has no reader."+ )++ async def test_without_a_grant_the_same_call_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ """The negative control: the viewer really does lack the permission."""+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"a viewer read the roles screen with no elevation ({resp.status_code})"++ async def test_an_expired_grant_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ """Automatic expiry, checked at use.++ A sweep job that revokes grants is a job that can be down, and a grant+ outliving its window because a worker crashed is the failure mode JIT+ elevation exists to remove.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, user_id, permissions=["roles:read"], expires_in=timedelta(minutes=-1))++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"an expired elevation still conferred roles:read ({resp.status_code})"++ async def test_a_revoked_grant_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, user_id, permissions=["roles:read"], revoked=True)++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"a revoked elevation still conferred roles:read ({resp.status_code})"++ async def test_an_unapproved_request_confers_nothing(self, app_client, pool) -> None: # noqa: ANN001+ """Approval is a gate, not a record.++ A row with no approver is a *request*. If it conferred anything, the+ requester would be approving their own elevation by writing it.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, user_id, permissions=["roles:read"], approved=False)++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"an unapproved elevation request conferred roles:read ({resp.status_code})"++ async def test_a_grant_to_another_user_does_not_elevate_this_one(self, app_client, pool) -> None: # noqa: ANN001+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ _, other_user = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, other_user, permissions=["roles:read"])++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"one user's elevation elevated another ({resp.status_code})"++ async def test_an_elevated_permission_is_still_subject_to_conditions(self, app_client, pool) -> None: # noqa: ANN001+ """Elevation and narrowing compose in the right order.++ If a grant were applied after conditions, elevation would be a way+ around every attribute rule a tenant configured.+ """+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _grant(pool, tenant_id, user_id, permissions=["roles:read"])+ await _condition(pool, tenant_id, permission="roles:read", operator="ip_in_cidr", value=MISSING_CIDR)++ resp = await app_client.get("/api/v1/rbac/roles", headers=_auth(user_id, tenant_id))++ assert resp.status_code == 403, f"an elevated permission escaped an attribute condition ({resp.status_code})"+++class TestWorkloadIdentitiesAuthenticateAService:+ """`workload_identities` had no reader, so a row in it authenticated nothing."""++ async def _mint(self, pool, *, service: str, scopes: list[str]) -> str:+ from app.services.workload_identity import mint_workload_secret++ secret, prefix, digest = mint_workload_secret()+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO workload_identities (service, description, scopes, secret_hash, secret_prefix)+ VALUES ($1, $2, $3::text[], $4, $5)+ """,+ service,+ "isolation suite",+ scopes,+ digest,+ prefix,+ )+ return secret++ async def test_a_workload_credential_authenticates_for_the_declared_tenant(self, app_client, pool) -> None: # noqa: ANN001+ """The reproduce case: a row in the table is a usable credential."""+ from app.api.v1.deps import SERVICE_TENANT_HEADER++ tenant_id, _ = await _tenant_with_user(pool, role="viewer")+ secret = await self._mint(pool, service="agents", scopes=["alerts:read"])++ resp = await app_client.get(+ "/api/v1/alerts",+ headers={"Authorization": f"Bearer {secret}", SERVICE_TENANT_HEADER: tenant_id},+ )++ assert resp.status_code == 200, f"a workload identity did not authenticate; got {resp.status_code}. The table has no reader."++ async def test_a_workload_credential_naming_no_tenant_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ """One shared credential across tenants is a cross-tenant read, so the+ tenant is mandatory and absent means refuse, never 'no filter'."""+ secret = await self._mint(pool, service="agents", scopes=["alerts:read"])++ resp = await app_client.get("/api/v1/alerts", headers={"Authorization": f"Bearer {secret}"})++ assert resp.status_code == 403, f"a workload credential with no tenant header was served ({resp.status_code})"++ async def test_a_revoked_workload_credential_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ from app.api.v1.deps import SERVICE_TENANT_HEADER++ tenant_id, _ = await _tenant_with_user(pool, role="viewer")+ secret = await self._mint(pool, service="agents", scopes=["alerts:read"])+ async with pool.acquire() as conn:+ await conn.execute("UPDATE workload_identities SET revoked_at = NOW() WHERE secret_prefix = $1", secret[:16])++ resp = await app_client.get(+ "/api/v1/alerts",+ headers={"Authorization": f"Bearer {secret}", SERVICE_TENANT_HEADER: tenant_id},+ )++ assert resp.status_code == 401, f"a revoked workload credential still authenticated ({resp.status_code})"++ async def test_a_workload_credential_is_held_to_its_own_scopes(self, app_client, pool) -> None: # noqa: ANN001+ """A per-service credential exists so the ingest pipeline does not+ present the same authority as the agents worker."""+ from app.api.v1.deps import SERVICE_TENANT_HEADER++ tenant_id, _ = await _tenant_with_user(pool, role="viewer")+ secret = await self._mint(pool, service="ingest", scopes=["alerts:read"])++ resp = await app_client.post(+ "/api/v1/cases",+ headers={"Authorization": f"Bearer {secret}", SERVICE_TENANT_HEADER: tenant_id},+ json=_case_body(),+ )++ assert resp.status_code == 403, (+ f"a workload credential scoped to alerts:read created a case ({resp.status_code}); scopes are not enforced"+ )+++async def _role_holding(pool, tenant_id: str, user_id: str, *, permissions: list[str]) -> None: # noqa: ANN001+ """Give ``user_id`` a database-backed role holding exactly ``permissions``.++ Without this the only principals able to reach the access-conditions+ route are the wildcard roles, which hold everything and therefore+ satisfy any granter-scope check trivially -- a test written against one+ would pass whether the check existed or not.+ """+ role_id = str(uuid.uuid4())+ async with pool.acquire() as conn:+ await conn.execute(+ "INSERT INTO roles (id, tenant_id, name, is_system) VALUES ($1::uuid, $2::uuid, $3, FALSE)",+ role_id,+ tenant_id,+ f"conditions-author-{role_id[:8]}",+ )+ await conn.execute(+ """+ INSERT INTO role_permissions (role_id, permission_id)+ SELECT $1::uuid, p.id FROM permissions p WHERE p.name = ANY($2::text[])+ """,+ role_id,+ permissions,+ )+ await conn.execute(+ "INSERT INTO user_roles (user_id, role_id) VALUES ($1::uuid, $2::uuid)",+ user_id,+ role_id,+ )+++class TestAConditionCannotConstrainAuthorityTheCallerLacks:+ """A condition is a denial, and `role` chooses whose denial it is.++ `access_conditions:write` is a permission a tenant can delegate. Before+ this check, delegating it also delegated the ability to store a+ condition against `admin` -- so the holder could switch off an+ administrator's permission outright, and the administrator's only+ symptom would be their own access failing against a rule they have no+ route to edit. The same granter-scope rule the rest of this tree+ applies to conferral applies here turned around: you may not constrain+ authority you do not hold.+ """++ @staticmethod+ def _body(role: str | None) -> dict:+ return {+ "permission": "cases:write",+ "operator": "ip_in_cidr",+ "value": MATCHING_CIDR,+ "role": role,+ }++ async def test_scoping_a_condition_to_admin_is_refused(self, app_client, pool) -> None: # noqa: ANN001+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _role_holding(pool, tenant_id, user_id, permissions=["access_conditions:write"])++ resp = await app_client.post(+ "/api/v1/access-conditions",+ headers=_auth(user_id, tenant_id),+ json=self._body("admin"),+ )++ assert resp.status_code == 403, (+ f"a principal holding only access_conditions:write stored a condition against the admin role "+ f"({resp.status_code}); it can switch off an administrator's permission"+ )++ async def test_the_same_caller_may_still_write_an_unscoped_condition(self, app_client, pool) -> None: # noqa: ANN001+ """The negative control. A route that refused every write would+ satisfy the assertion above while removing the feature."""+ tenant_id, user_id = await _tenant_with_user(pool, role="viewer")+ await _role_holding(pool, tenant_id, user_id, permissions=["access_conditions:write"])++ resp = await app_client.post(+ "/api/v1/access-conditions",+ headers=_auth(user_id, tenant_id),+ json=self._body(None),+ )++ assert resp.status_code == 201, (+ f"a principal holding access_conditions:write could not write an unscoped condition ({resp.status_code}: {resp.text})"+ )