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(api): SCIM 2.0 provisioning scoped by its credential (#929)
Beenu Arora1769e1ab3b5a
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex dd6d5a5c1..bcd68293e 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -30,6 +30,7 @@ on:# a gate that stops running exactly when somebody edits what it checks.- "scripts/check_runtime_db_role.py"- "scripts/check_rls_policy_shape.py"+ - "scripts/check_scim_contract.py"- "docker-compose.yml"- "infra/**"- ".env.example"@@ -49,6 +50,7 @@ on:# a gate that stops running exactly when somebody edits what it checks.- "scripts/check_runtime_db_role.py"- "scripts/check_rls_policy_shape.py"+ - "scripts/check_scim_contract.py"- "docker-compose.yml"- "infra/**"- ".env.example"@@ -193,6 +195,17 @@ jobs:- name: Every RLS policy admits an unbound session and reads the GUC the tree setsrun: python scripts/check_rls_policy_shape.py+ # SCIM is an authentication-adjacent write surface whose client decides+ # what to attempt by reading a document this service publishes. The+ # documents, the routes, the audit trail and the group-to-role mapping+ # therefore have to agree, and the self-test proves the gate still+ # notices when they stop agreeing.+ - name: SCIM-contract gate self-test (four injected drifts)+ run: python scripts/check_scim_contract.py --self-test++ - name: The SCIM surface matches what it advertises, audits and grants+ run: python scripts/check_scim_contract.py+- name: Start Redis for the two-tenant route replayrun: |docker run -d --name route-iso-redis -p 6379:6379 redis:7-alpinediff --git a/CHANGELOG.md b/CHANGELOG.mdindex dfa9e3e23..02c9cb917 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -93,6 +93,79 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0expected result and the one worth stating: the synthetic corpus has no tenantskills, so a skill-free deployment behaves byte for byte as it did.`services/agents` 1390 to 1423 tests, `services/api` 2970 to 3007.+### Added++- **SCIM 2.0 provisioning, scoped by its credential and tested against two+ identity providers that disagree with each other** (gap-closure Phase 13.1).++ **The gap.** AiSOC already had OIDC and SAML, so a person could sign in from+ a corporate directory. Nothing created the account first, kept its+ attributes current, or ended its access when the person left. An+ administrator did that by hand, per tenant, and a leaver kept whatever they+ had until somebody remembered.++ **What ships.** `/scim/v2` serves Users, Groups, ServiceProviderConfig,+ ResourceTypes and Schemas with filtering and PATCH, authenticated by a+ per-organisation bearer token stored as a SHA-256 digest and rotatable with+ a grace window so a rotation does not take the integration down while an+ administrator pastes the new secret across. Directory groups map onto the+ roles `ROLE_PERMISSIONS` enforces; a group whose name resolves to nothing is+ recorded, audited and confers no privilege, and no group name can reach+ `platform_admin`, `admin` or `api_service`. Every operation writes to the+ hash-chained audit log naming the credential that performed it, because the+ actor of a SCIM change is a machine.++ **How it was measured.** Not against a paraphrase of RFC 7644. Okta and+ Entra both implement the specification and differ in five places, and+ `test_scim_provisioning.py` carries their request shapes verbatim: `op`+ lowercase against capitalised, a missing `path` with an object value against+ an explicit path, member removal through a path filter against a value+ array, `userName` omitted in favour of `emails`, and a deactivation arriving+ as the string `"False"` rather than the boolean. That last one is the+ consequential difference: `bool("False")` is `True`, so the obvious+ implementation accepts the request, deactivates nothing, and returns 200+ while the provider records the deprovisioning as successful. Both providers'+ full sequences (create, update, group membership, deactivate) run end to+ end, 54 tests in all.++ **The gates that keep it closed.** `scripts/check_scim_contract.py`+ (`isolation.yml`) compares the discovery documents against the route table+ in both directions, so a capability advertised with no route and a route no+ document advertises both fail; it asserts each of the eight mutating+ handlers still reaches the audit helper, and that `main.py` mounts the+ router at all. `test_scim_mounted.py` reads `app.openapi()` from the real+ application, refusing an empty inventory before asserting membership,+ because `include_router` does not populate `app.routes` on the pinned+ FastAPI and an inventory assertion can otherwise measure nothing.+ `docs/decisions/0008-scim-trust-boundary.md` records why the tenant comes+ from the credential and can come from nowhere else.++### Fixed++- **A deactivated user's API keys kept working, so deprovisioning ended+ sessions and not programmatic access** (found while building Phase 13.1).++ **The defect.** `_resolve_api_key` looked up a key's owning user with+ `User.is_active == True` and, when that returned nothing, fell through with+ `role = "api_service"` instead of refusing. A key belonging to a deactivated+ principal therefore went on authenticating indefinitely, under a generic+ role, with nothing in the request or the logs looking wrong. Deactivating an+ account stopped that person's sessions, which is what anyone testing it+ would have checked, and left every credential they had minted for themselves+ live.++ **The half that was already sound, and its limit.** `get_current_user`+ re-reads `is_active` on every request, so a session stops at the next call+ rather than at the next token expiry. What it cannot do is survive+ re-activation: an access token minted before the deactivation is still+ inside its expiry window and resumes working the moment the row flips back.+ Access and refresh tokens now carry `iat`, `users.sessions_revoked_at`+ records the cutoff, and a token issued at or before it is refused however+ active the principal currently is. A token carrying no `iat` predates the+ claim and is treated as revoked whenever a revocation exists, so credentials+ minted before this change fail closed rather than outliving the revocation+ meant to end them. The refresh path checks it too, and matters more there: a+ refresh token outlives an access token by days.### Changeddiff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex 5b933f9d6..48649a402 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -460,7 +460,7 @@ suites' job, and anything at all against a live vendor MCP server.## Phase 13: Enterprise identity and MSSP plumbing-- [ ] **13.1 SCIM 2.0** with Users, Groups, ServiceProviderConfig, ResourceTypes and Schemas, per-organization hashed rotatable tokens, and audited deprovisioning.+- [x] **13.1 SCIM 2.0** with Users, Groups, ServiceProviderConfig, ResourceTypes and Schemas, per-organization hashed rotatable tokens, and audited deprovisioning. Migration `071_scim_provisioning.sql`; router at `/scim/v2` (17 routes); `scripts/check_scim_contract.py` wired into `isolation.yml`; Okta-shaped and Entra-shaped sequences pass in `test_scim_provisioning.py` (54 tests). See D28, D29 and D30.- [ ] **13.2 MSSP white-label** per organization across console, PDF, digests, email approvals and ChatOps, with SVGs sanitized and assets stored locally.- [ ] **13.3 Usage metering** from real rows, exposed through an API and a monthly CSV, with no pricing logic.- [ ] **13.4 Console i18n** with a pilot locale, RTL, locale-aware formatting and a missing-keys gate.@@ -555,6 +555,7 @@ Nothing yet beyond this kickoff. Each entry below will name its PR.178, and the existing "MCP server exposes 13 tools" row was correctedrather than only renumbered, because the gate it named had never read adocument. See D24 and D25.+### D9. A shadow verdict must not reach `alerts.disposition`, and the guard belongs in the SQLRecorded because the obvious implementation of shadow mode is wrong in a way@@ -1172,6 +1173,7 @@ verb, and both nouns are gone. `benign-edr-response-cmdline` still flags andstays recorded: suppressing it needs a rule that reads a containment verb inflag position as a tool invocation, and a suppression rule is the one kindwhose failure mode is silence.+### D21. The credential has to cross the internal network, and the usual dual-mode route is the wrong shape for itThe plan puts the client in `services/agents` and the registry in@@ -1407,3 +1409,75 @@ leaving a note that said what the freeze threw away and never what it kept. Itnow requires `<store>_frozen` and `<store>_dropped_after_split` by exact name.Seven regressions were injected into a detached copy of the tree and all sevenare caught; the seventh is that one.++### D28. The migration number the brief carried was six behind the tree++The kickoff brief for this phase repeated the plan's capture-time note that+`063` was the latest migration. `services/api/migrations/` actually ends at+`069_mcp_servers.sql`, because Phases 1 through 5 landed their own tables+while this brief was being written. Phase 13's tables take **071** and **072**: `070` was taken by 6.1's `070_tenant_skills.sql`, which merged while this branch was in flight, and the collision only surfaced on the rebase.++Recorded because it is the sixth time in this program a handed-down migration+number has been stale, and the failure it causes is a duplicate number that+only shows up when two branches merge.++### D29. The seven-role set the brief described does not exist in this tree++The brief stated that six of seven roles already exist as `viewer`, `hunter`,+`responder`, `detection_engineer`, `tenant_admin` and `platform_admin`, that+`triage_analyst` is missing, and that it should be added as part of 13.1.++The enforced vocabulary is `ROLE_PERMISSIONS` in+`services/api/app/core/security.py`, which `CurrentUser.require_permission`+reads on every guarded request. It holds eight keys: `platform_admin`,+`admin`, `tenant_admin`, `soc_lead`, `soc_analyst`, `threat_hunter`, `viewer`+and `api_service`. Only three of the brief's seven names appear in it.+`hunter` is `threat_hunter`; `responder`, `detection_engineer` and+`triage_analyst` do not exist under any spelling, and `soc_lead` and+`soc_analyst` have no counterpart in the brief's list.++**Resolution: map to the vocabulary that is enforced, and do not add+`triage_analyst`.** The plan itself says only "Groups map to roles in the+existing RBAC" and names no roles, so the plan is satisfied. Adding a seventh+role would mean either a duplicate of `soc_analyst` under a second name, or a+role with no permissions attached: a string in a column that grants nothing+and reads in a console as though it grants something. That is the "exists but+nothing calls it" shape this program has hit five times, and it would be+self-inflicted.++`app/services/scim/roles.py` maps group names onto the real keys, and+`check_scim_contract.py` compares the two in **both** directions, so a role+renamed in `ROLE_PERMISSIONS` cannot leave a mapping pointing at nothing, and+a *new* role must be classified as assignable or recorded as deliberately+unreachable from a directory group.++**Adjacent, unfixed, and worth a separate look:** `packages/types/src/tenant.ts`+declares a `UserRole` union of nine entirely different names+(`security_manager`, `analyst_tier1`, `analyst_tier2`, `analyst_tier3`,+`auditor`, `readonly` and three that overlap). Nothing in the Python enforces+any of them. This is the same shape as the playbook `StepType` drift: a+TypeScript union that looks authoritative, mirrors nothing, and has no gate.+It is out of Phase 13's scope and is left as found rather than half-corrected.++### D30. Deactivating a user did not end the programmatic access they had minted++Found while building 13.1's deprovisioning path, and fixed in the same change+because it is the difference between deprovisioning and the appearance of it.++`_resolve_api_key` in `services/api/app/api/v1/deps.py` looked up the owning+user with `User.is_active == True` and, when that returned nothing, **fell+through** with `role = "api_service"` and the key's own `user_id`. So a key+belonging to a deactivated principal kept authenticating, under a generic+role, indefinitely. Nothing about the request looked wrong and no log said+anything.++The JWT half was already sound: `get_current_user` re-reads `is_active` on+every request, so a session stops at the next call. What it could not do is+survive re-activation, since an access token minted before the deactivation+is still inside its expiry window. Tokens now carry `iat`,+`users.sessions_revoked_at` records the cutoff, and a token issued at or+before it is refused. A token with **no** `iat` is treated as revoked whenever+a revocation exists, so credentials minted before this change fail closed.++Both the access-token path and the refresh path check it. The refresh path+matters more: a refresh token outlives an access token by days.diff --git a/ROADMAP.md b/ROADMAP.mdindex 5bca08d1e..f607df5a6 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 **204 rows — 196 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 **209 rows — 201 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 517d743f8..f63009023 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: 196 rows+The last row is the one worth reading first. It is the honest index: 201 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/operations/scim.md b/apps/docs/docs/operations/scim.mdnew file mode 100644index 000000000..0f3da5268--- /dev/null+++ b/apps/docs/docs/operations/scim.md@@ -0,0 +1,189 @@+---+title: SCIM provisioning+sidebar_label: SCIM provisioning+description: Provision and deprovision AiSOC principals from your identity provider using SCIM 2.0.+---++# SCIM provisioning++AiSOC implements SCIM 2.0 (RFC 7643 and RFC 7644) so your identity provider+can create principals, keep their attributes current, map directory groups+onto AiSOC roles, and end access when somebody leaves.++The base URL is:++```+https://<your-aisoc-host>/scim/v2+```++Your identity provider appends `/Users` and `/Groups` to that itself.++## What is implemented++| Capability | Status |+|---|---|+| `/Users` (list, get, create, replace, patch, delete) | Supported |+| `/Groups` (list, get, create, replace, patch, delete) | Supported |+| `/ServiceProviderConfig`, `/ResourceTypes`, `/Schemas` | Supported |+| PATCH | Supported |+| Filtering | One `attribute eq "value"` comparison |+| Bulk | Not implemented |+| Sorting | Not implemented |+| Password change through SCIM | Not implemented |++`/ServiceProviderConfig` is the authoritative answer and is checked against+the routes in CI, so it cannot advertise something this build does not serve.++Filtering deliberately supports one comparison rather than the full RFC 7644+grammar, because that is the shape provisioning sends: a lookup before a+create. An unsupported filter returns a SCIM error rather than being ignored.+Ignoring it would return every principal in your tenant, and a provider+reading that result may conclude the user it was about to create already+exists.++## Creating a credential++SCIM authenticates with a bearer token scoped to one tenant. Mint one from+the console, or through the API:++```bash+curl -X POST https://<your-aisoc-host>/api/v1/scim-tokens \+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"name": "corporate-directory", "expires_in_days": 365}'+```++The response carries the raw secret once. It is stored as a SHA-256 digest,+so it cannot be recovered afterwards; if it is lost, rotate.++Requires the `settings:write` permission.++## Rotating a credential++```bash+curl -X POST https://<your-aisoc-host>/api/v1/scim-tokens/<id>/rotate \+ -H "Authorization: Bearer $AISOC_SESSION_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"grace_hours": 24}'+```++Both secrets work during the grace window, so you can paste the replacement+into your identity provider without a failed sync in between. The superseded+token expires by itself at the end of the window.++If you are rotating because a secret was disclosed, send `{"grace_hours": 0}`.+That revokes the old secret immediately and your next sync will fail until+the new one is in place, which is the correct trade in that situation.++## Mapping groups to roles++Push the groups you want AiSOC to act on. Each group resolves to one AiSOC+role by name:++| Group name contains | Resolves to |+|---|---|+| `tenant` and `admin` | `tenant_admin` |+| `soc` and `lead`, `soc` and `manager`, or `incident commander` | `soc_lead` |+| `threat hunter`, `threat hunting`, or `hunter` | `threat_hunter` |+| `soc analyst`, `triage`, or `analyst` | `soc_analyst` |+| `viewer`, `read only`, or `auditor` | `viewer` |++Matching ignores case, punctuation and plurals, so `AiSOC-SOC-Analysts`,+`soc analyst` and `SOC_Analysts` all reach `soc_analyst`.++A group whose name matches nothing is still created and its membership is+still tracked, and it confers no privilege at all. The group's resolved role+is returned on the Group resource under+`urn:aisoc:params:scim:schemas:extension:2.0:Group`, so you can confirm what+a group grants by reading the same response your identity provider sees:++```json+{+ "urn:aisoc:params:scim:schemas:extension:2.0:Group": { "mappedRole": "soc_lead" }+}+```++A `null` there means the group grants nothing. Rename the group to match the+table above if that was not what you intended.++When a principal belongs to several mapped groups they hold the highest of+those roles, so the result does not depend on the order your provider happens+to sync in. A principal in no mapped group holds `viewer`.++**No group name can grant `platform_admin`, `admin` or `api_service`.** Those+roles hold wildcard permissions, and the set of people who can create a group+in a corporate directory is usually larger than the set of AiSOC+administrators. Assign them in AiSOC directly.++## What deprovisioning does++Deactivating a principal (`active: false`, or `DELETE /Users/{id}`) does+three things:++1. Marks the account inactive. AiSOC re-reads this on every authenticated+ request, so an open session stops at the next call rather than at the next+ token expiry.+2. Records a session-revocation timestamp. Access and refresh tokens issued+ before that instant are refused permanently, so re-enabling the account+ later does not resurrect a token minted before the person left.+3. Deactivates every API key that principal owns. An API key outlives+ sessions and is not reached by either step above.++`DELETE` deactivates rather than erasing the row, which RFC 7644 permits.+Erasing it would take the principal's audit attribution, case ownership and+approval history with it. Access ends completely either way.++Re-activating a principal restores sign-in and does **not** restore their API+keys. Mint fresh ones; a key whose owner cannot see it was revoked is a key+nobody will rotate.++## Auditing++Every SCIM operation writes to the tamper-evident audit log, under actions+`scim:user:create`, `scim:user:patch`, `scim:user:replace`,+`scim:user:delete`, `scim:group:create`, `scim:group:patch`,+`scim:group:replace` and `scim:group:delete`, plus `scim:token:create`,+`scim:token:rotate` and `scim:token:revoke` for credential administration.++Because the actor is a machine rather than a person, each record carries the+credential that performed it under `provisioned_by`. A deprovisioning record+additionally carries `programmatic_access_revoked`, the number of API keys+that went with it, and `sessions_revoked_at`.++`last_used_at` on each credential is how you find an abandoned integration.+A token nobody has used for months is a standing credential with no owner.++## Tested against++The provisioning flows are tested against request shapes from Okta and+Microsoft Entra ID, which differ from each other in several places that a+single-provider implementation gets wrong:++- deactivation with no `path` and an object value, versus an explicit `path`+ and the string `"False"`+- `op` spelled lowercase versus capitalised+- group member removal through a path filter with no value, versus+ `path: "members"` with the id in a value array+- `userName` omitted in favour of `emails` when the directory's username+ attribute is unset++Both providers' full sequences (create, update, group membership, deactivate)+run in CI.++## Troubleshooting++**Every sync fails with 401.** The credential is wrong, revoked, or expired.+The response does not say which, on purpose. Check `last_used_at` and the+audit log for `scim:token:revoke`, then rotate.++**A group syncs but nobody gains any permission.** The group name did not+resolve. Read `mappedRole` on the Group resource; if it is `null`, rename the+group to match the table above.++**A create returns 409.** A principal with that `userName` already exists in+the tenant. This is the correct answer and your provider will reconcile+against the existing record; AiSOC will not create a second account for the+same address.++**A filter returns 400 with `scimType: "invalidFilter"`.** The filter is+outside the supported comparison. Providers fall back to listing.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex fb91f3a46..58936a253 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -186,6 +186,7 @@ const sidebars: SidebarsConfig = {"compliance/fips-posture","operations/credentials","operations/secrets",+ "operations/scim","operations/ingest-authentication","operations/airgap","operations/air-gapped",diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 4c9d25681..7874ea852 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -212,6 +212,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A skill cannot be activated without a backtest of the exact version being activated | `apps/docs/docs/console/tenant-skills.md` (Lifecycle) | `ci.yml` api job (`test_tenant_skills.py::TestLifecycle`: activation is refused with no backtest, with a backtest of a different version, when expired, and when one evaluation is used as its own baseline; a content edit is asserted to bump the version, drop the row to draft and detach both reports, while a reformat that leaves the parsed body identical keeps them) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the rule in the migration's CHECK, in the store and on the docs page; proven able to fail by weakening the SQL clause) | GATED | Stated in three places on purpose. The CHECK holds against a direct fix-up; the store's refusal is what produces a sentence an operator can act on rather than a constraint name || Every investigation a skill guided records which version guided it, and that version resolves back to its text | `apps/docs/docs/console/tenant-skills.md` (What gets recorded) | `ci.yml` agents job (`test_tenant_skill_investigation.py`: the provenance carries id, version and owner; the investigation pins the version triage already used rather than re-resolving, since the fetch is cached and an activation between the two reads would split them) + `ci.yml` api job (`test_tenant_skills.py`: a content edit leaves both versions in `aisoc_tenant_skill_versions`, and retire keeps the history while delete removes it) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the field on both `DeepInvestigationResult` and `InvestigationState`; proven able to fail by renaming it on either) | GATED | A recorded version with no history row is provenance-shaped and not provenance, so a skill row whose version is absent or zero is refused by the resolver rather than served || Tenant skills are frozen at the split point during a replay, and the backtest bypass is published rather than silent | `apps/docs/docs/console/tenant-skills.md` (What a backtest number does and does not say); `services/agents/app/replay/shadow.py` | `ci.yml` agents job (`test_replay_leakage.py`: a skill activated after the split never reaches the prompt, with a **sensitivity half** that runs the live reader and asserts the same poison does; the backtest candidate is asserted to reach the prompt *and* to be named in the method note with its caveat, with a sensitivity half asserting an ordinary replay of the same instant freezes it out; a skill with no activation stamp is counted the way an undated statement is) + `ci.yml` gates job (`scripts/check_triage_context_freeze.py`: every source `TriageContextReader` declares must be implemented by both readers, and every snapshot store must be filtered by `capture_context` and publish `_frozen` and `_dropped_after_split` in the method note. Proven able to fail by removing the frozen reader's method, by silencing the bypass, and by deleting one kept-count key while a neighbouring key remained, which an earlier substring version of the check missed) | GATED | A skill backtest deliberately applies a candidate authored after the window, which is what a backtest is. The figure is a statement about that window and not a forecast, and the method note says so in those words rather than leaving a reader to infer it |+| A SCIM request's tenant comes from its credential, never from the request | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `docs/decisions/0008-scim-trust-boundary.md`; `apps/docs/docs/operations/scim.md` | `isolation.yml` (`check_route_auth.py` and `check_route_tenant_scope.py` see `ScimPrincipal` as an authenticating dependency, so every one of the 17 SCIM routes is counted as authenticated rather than exempted; `aisoc_scim_tokens.tenant_id` is NOT NULL and RFC 7643 defines no tenant attribute) + `ci.yml` api job (`test_scim_provisioning.py::TestTokens` - a second tenant's credential gets 404 for a principal the first created, and discovery refuses an anonymous caller) | GATED | The credential is the only source of tenancy because the protocol has no field for one. There is nothing to intersect: a SCIM handler that read a tenant from anywhere would be the finding |+| SCIM bearer tokens are hashed at rest and rotate without an outage | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (Rotating a credential) | `ci.yml` api job (`test_scim_provisioning.py::TestTokens` - the stored value is asserted to be the SHA-256 digest and not the secret or its prefix; rotation is asserted to leave **both** secrets working inside the grace window and to refuse the old one after it; a zero grace window revokes immediately for rotation after a disclosure; rotation is asserted never to *extend* an earlier deadline) | GATED | The digest is correct here rather than a password KDF: the token is 192 bits from `secrets`, so there is no low-entropy guess to slow down, and a KDF on the request path would delay every sync an identity provider makes |+| SCIM deprovisioning ends access rather than flagging a row | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `docs/decisions/0008-scim-trust-boundary.md`; `apps/docs/docs/operations/scim.md` (What deprovisioning does) | `ci.yml` api job (`test_scim_provisioning.py::TestDeprovisioning` - a deactivation is asserted to revoke the principal's API keys by **count**, and to stamp `sessions_revoked_at`; `token_is_revoked` is asserted in all four directions including the fail-closed case of a token with no `iat`; minted tokens are asserted to carry `iat`, so the check has something to read; re-activation is asserted **not** to restore revoked API keys; the whole chain is repeated end to end through `DELETE /scim/v2/Users/{id}`) | GATED | DELETE deactivates rather than erasing, which RFC 7644 permits: erasing the row would take the principal's audit attribution and case history with it. A pre-existing fall-through that left a deactivated user's API key working under a generic role is closed in the same change |+| A directory group confers only a role AiSOC enforces, and an unrecognised group confers nothing | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (Mapping groups to roles) | `isolation.yml` (`check_scim_contract.py` compares the group-to-role mapping against `ROLE_PERMISSIONS` in **both** directions, so a role renamed there cannot leave a mapping pointing at a string that grants nothing, and a *new* role must be classified as assignable or recorded as deliberately unreachable; proven able to fail by introducing an unclassified role) + `ci.yml` api job (`test_scim_provisioning.py::TestRoleMapping` - membership is asserted to write `users.role`, which is the column the permission check reads, and removal to take it back; an unmapped group is asserted to confer nothing; no group name resolves to a wildcard role) | GATED | Precedence is a total order, so a principal in several mapped groups holds the same role regardless of the order a provider syncs in |+| The SCIM surface serves what its discovery documents advertise, and audits every write | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (What is implemented) | `isolation.yml` (`check_scim_contract.py` reads `ServiceProviderConfig` and the route table and compares them in both directions, so a capability advertised with no route **and** a route no document advertises both fail; asserts each of the eight mutating handlers still reaches the audit helper; asserts `main.py` includes the router, since a router nobody mounts serves nothing) + `ci.yml` api job (`test_scim_mounted.py` reads `app.openapi()` from the real application and refuses an empty inventory before asserting membership, because `include_router` does not populate `app.routes` on the pinned FastAPI) | GATED | Filtering implements one `attribute eq "value"` comparison and refuses the rest: a dropped filter would return every principal in the tenant, which a provider reads as "this user already exists" |## Summary@@ -219,7 +224,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 196+- GATED: 201- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.mdindex 2840ea3d6..1ec63976f 100644--- a/docs/audit/REPOSITORY_REALITY.md+++ b/docs/audit/REPOSITORY_REALITY.md@@ -165,6 +165,41 @@ These were not visible from the code alone:order rather than as extra map entries, because Go randomises mapiteration and three entries pointing at one destination would pick adifferent winner per process.+5. **A deactivated user's API keys kept authenticating.** Not visible from a+ session test, which is what anyone would have run: `get_current_user`+ re-reads `users.is_active` per request, so deactivating did stop sessions+ immediately. `_resolve_api_key` took a different path. It looked up the+ owning user with `is_active == True` and, when that returned nothing, fell+ through to a generic `api_service` role instead of refusing, so every key+ a departing principal had minted for themselves went on working+ indefinitely. Fixed in Phase 13.1, alongside a session-revocation+ timestamp checked against a new `iat` claim, because the `is_active` check+ is reversible: re-enabling an account resurrected any token minted before+ the deactivation that had not yet expired.++---++## Identity and provisioning++**SCIM 2.0 — WORKING, no external dependency to verify against in CI.**+`/scim/v2` on the API service serves Users, Groups, ServiceProviderConfig,+ResourceTypes and Schemas, authenticated by a per-tenant bearer token held as+a SHA-256 digest. What is proven in CI is that the handlers behave correctly+against request bodies transcribed from Okta and Microsoft Entra ID+provisioning, including the five shapes where the two providers disagree.++What that does **not** prove, and is worth stating plainly: no live identity+provider has been pointed at this build. The payloads are synthetic+reproductions of documented request shapes, not captures from a running+integration, so a provider quirk outside those five would not be caught here.+The honest claim is that the implementation handles both dialects as+documented, not that either vendor's connector has been run against it end to+end.++OIDC (`services/api/app/auth/oidc.py`, PKCE on by default) and SAML+(`services/api/app/auth/saml.py`) handle sign-in and predate this work.+Provisioning and sign-in are separate concerns: SCIM creates and removes the+principal, OIDC or SAML authenticates them.---diff --git a/docs/decisions/0008-scim-trust-boundary.md b/docs/decisions/0008-scim-trust-boundary.mdnew file mode 100644index 000000000..89575b64f--- /dev/null+++ b/docs/decisions/0008-scim-trust-boundary.md@@ -0,0 +1,132 @@+# ADR-0008: SCIM is a third-party write surface into identity, and is scoped by its credential++- **Status**: accepted+- **Date**: 2026-09-27+- **Relates to**: gap-closure plan Phase 13.1++## Context++Every write path in this platform up to now has been driven by a person+holding a session, or by a service token this project issued to its own+workers. SCIM is neither. It is a long-lived bearer credential, pasted into a+configuration screen in somebody else's product, used unattended on that+product's sync schedule, to create principals, change what they may do, and+end their access.++That is a trust boundary, and it moves in three directions at once:++1. **Who may create a principal.** Before SCIM, an account came from a+ sign-up flow or an administrator. After it, an account comes from whoever+ controls the identity provider's assignment rules.+2. **Who may raise a principal's authority.** Group membership decides what+ a person may do. Group names are chosen in the customer's directory, by a+ set of people that is usually larger than the set of platform+ administrators.+3. **What "deprovisioned" means.** An identity provider that reports a+ successful deprovisioning has discharged its duty. If access has not+ actually ended on this side, nobody is looking any further.++There is also a specific, well-documented hazard in the protocol itself. The+two identity providers this platform supports both implement RFC 7644 and+disagree about PATCH in five places. One of those disagreements is that a+deactivation arrives as the JSON string `"False"` rather than the boolean+`false`. In Python, `bool("False")` is `True`, so the obvious implementation+accepts the request, deactivates nothing, and returns 200. The provider+records the deprovisioning as done.++## Decision++**The tenant comes from the credential, and there is no request field that+can influence it.** `aisoc_scim_tokens.tenant_id` is `NOT NULL` and is the+only source of tenancy on the SCIM surface. RFC 7643 defines no tenant+attribute, so this is not a restriction we are imposing on the protocol; it+is the absence of any alternative. `org_id` is nullable beside it, so a+single-tenant deployment can run SCIM with no operator organisation while an+MSSP can still join a provisioning event to the organisation that caused it.++**The credential is stored as a digest and rotates with an overlap window.**+A SHA-256 digest for lookup and a 12-character prefix for display, matching+the convention `api_keys` already uses. The token is 192 bits from `secrets`,+so a digest is correct and a password KDF would be wrong twice over: there is+no low-entropy guess to slow down, and a KDF on the request path would put a+deliberate delay in front of every call a provider makes. Rotation mints a+replacement and puts the superseded row on a clock rather than revoking it,+because a rotation that cuts over instantly takes the integration down for as+long as it takes a person to paste the new secret across, and that is why+rotation gets deferred and secrets get old. A zero grace window is supported+for rotation after a disclosure.++**Deprovisioning ends access rather than marking it.** Three things, and the+second and third are the ones that make it more than a flag:++- `users.is_active = false`, which the request path re-reads on every+ authenticated call, so an in-flight session stops at the next request;+- `users.sessions_revoked_at = now`, checked against a new `iat` claim, so a+ token minted before the deprovisioning stays refused even if the principal+ is later re-activated while that token is still inside its expiry window;+- every `api_keys` row the principal owns is deactivated, because an API key+ outlives sessions entirely and neither of the first two steps reaches it.++**An unrecognised directory group confers nothing.** A pushed group either+resolves to one of the roles `ROLE_PERMISSIONS` actually enforces, or it+resolves to `NULL` and is membership-only: recorded, audited, and granting no+privilege. `platform_admin`, `admin` and `api_service` are unreachable from+any group name at all, so nobody who can create a group in the customer's+directory can mint a wildcard role by choosing its name.++**Every operation is audited against the credential that performed it.** The+actor of a SCIM change is a machine, and an audit trail that cannot say which+machine is not an audit trail. The record carries the credential's name and+id and, for a deprovisioning, the count of programmatic credentials it+revoked.++## Consequences++- New migration `071_scim_provisioning.sql` adds four tenant-scoped tables+ with the standard row-level-security shape and `aisoc_app` grants, plus+ `users.sessions_revoked_at`.+- Access and refresh tokens now carry `iat`. The claim is additive and the+ nine services that verify these tokens ignore unknown claims, so this is+ backward compatible. A token with no `iat` is treated as revoked whenever a+ revocation exists, which fails closed for credentials minted before the+ upgrade.+- A pre-existing defect is closed alongside: `_resolve_api_key` fell through+ when a key named a user who was inactive or gone, leaving the key working+ under a generic `api_service` role. Deprovisioning a user therefore did not+ end the programmatic access they had minted for themselves.+- `scripts/check_scim_contract.py` keeps the discovery documents, the routes,+ the audit calls and the role mapping in agreement, in both directions.+- Filtering implements one comparison shape and refuses everything else.+ Silently dropping an unsupported filter would return every principal in the+ tenant, and a provider reading that concludes the user it was about to+ create already exists.++## Alternatives considered++**Put the tenant in a path segment, `/scim/v2/{tenant}/Users`.** Rejected.+It reintroduces the exact shape this repository has already been burned by:+a boundary that is a request parameter. The credential would still have to be+checked against the segment, so the segment adds a failure mode and no+capability.++**Create a platform role for every pushed group.** Rejected. It manufactures+roles that grant nothing and that read, in a console, as though they grant+something. Mapping to the enforced vocabulary and leaving the rest null makes+"unrecognised" mean powerless rather than unknown.++**Delete the principal on `DELETE /Users/{id}`.** Rejected. A deleted row+takes its audit attribution, case ownership and approval history with it, and+this platform's own records reference the principal. Access ends completely+either way, which is what DELETE means here; RFC 7644 permits deactivation as+the implementation of delete.++**Implement the full RFC 7644 filter grammar.** Rejected for now. It would+mean a parser whose untested branches are reachable from an+authentication-adjacent surface, to serve queries no provisioning client+sends. An unsupported filter is a documented SCIM error and providers handle+it.++**Leave `users.is_active` as the whole of revocation.** Rejected. It is+genuinely effective while the flag is down, which is what makes it+attractive, but it is reversible: re-enabling an account resurrects every+token minted before the deactivation that has not yet expired.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 7cd3596b3..0072a264b 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -21,6 +21,7 @@ ADRs are immutable once accepted. If a decision changes, write a new ADR that su| [ADR-0005](./0005-storage-consolidation.md) | Tiered storage consolidation + a $/TB cost model | accepted | 2026-07-12 || [ADR-0006](./0006-llm-gateway-in-core.md) | The LLM gateway belongs in the CORE profile | accepted | 2026-09-24 || [ADR-0007](./0007-connectors-and-actions-in-core.md) | `connectors` and `actions` belong in the CORE profile | accepted | 2026-09-26 |+| [ADR-0008](./0008-scim-trust-boundary.md) | SCIM is a third-party write surface into identity, and is scoped by its credential | accepted | 2026-09-27 |## Authoring conventionsdiff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 77a776362..cf0dc69ab 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -9174,6 +9174,131 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/scim-tokens:+ get:+ tags:+ - scim+ summary: List Scim Tokens+ description: List this tenant's SCIM credentials. Secrets are never returned.+ operationId: list_scim_tokens_api_v1_scim_tokens_get+ security:+ - HTTPBearer: []+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/ScimTokenOut'+ title: Response List Scim Tokens Api V1 Scim Tokens Get+ post:+ tags:+ - scim+ summary: Create Scim Token+ description: Mint a SCIM credential for this tenant.+ operationId: create_scim_token_api_v1_scim_tokens_post+ parameters:+ - name: current_user+ in: query+ required: true+ schema:+ title: Current User+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateScimTokenRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreatedScimTokenOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/scim-tokens/{token_id}/rotate:+ post:+ tags:+ - scim+ summary: Rotate Scim Token+ description: Replace a credential, leaving the old one working for a grace window.+ operationId: rotate_scim_token_api_v1_scim_tokens__token_id__rotate_post+ parameters:+ - name: token_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Token Id+ - name: current_user+ in: query+ required: true+ schema:+ title: Current User+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RotateScimTokenRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreatedScimTokenOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/scim-tokens/{token_id}:+ delete:+ tags:+ - scim+ summary: Revoke Scim Token+ description: 'Revoke a credential immediately.+++ The row stays, because ``aisoc_scim_users.token_id`` references it and++ the audit trail answers "which integration provisioned this principal"++ through it.'+ operationId: revoke_scim_token_api_v1_scim_tokens__token_id__delete+ parameters:+ - name: token_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Token Id+ - name: current_user+ in: query+ required: true+ schema:+ title: Current User+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/assets:get:tags:@@ -15899,39 +16024,560 @@ paths:description: Return SP SAML metadata XML.operationId: saml_metadata_auth_saml_metadata_getresponses:- '200':+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ /auth/saml/logout:+ get:+ tags:+ - auth-saml+ summary: Saml Logout+ description: Initiate SAML SLO.+ operationId: saml_logout_auth_saml_logout_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ /auth/oidc/login:+ get:+ tags:+ - auth-oidc+ summary: Oidc Login+ description: Initiate OIDC authorization code flow.+ operationId: oidc_login_auth_oidc_login_get+ parameters:+ - name: redirect+ in: query+ required: false+ schema:+ type: string+ default: /+ title: Redirect+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /auth/oidc/callback:+ get:+ tags:+ - auth-oidc+ summary: Oidc Callback+ description: Handle OIDC authorization code callback and issue JWT.+ operationId: oidc_callback_auth_oidc_callback_get+ parameters:+ - name: code+ in: query+ required: true+ schema:+ type: string+ title: Code+ - name: state+ in: query+ required: true+ schema:+ type: string+ title: State+ - name: error+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: Error+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /auth/oidc/userinfo:+ get:+ tags:+ - auth-oidc+ summary: Oidc Userinfo+ description: 'Proxy userinfo from upstream OIDC provider using the stored access+ token.+++ Requires `Authorization: Bearer <aisoc_jwt>` header — the JWT sub is++ used to look up the upstream token (stub: returns claims from AiSOC JWT).'+ operationId: oidc_userinfo_auth_oidc_userinfo_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ /auth/oidc/logout:+ get:+ tags:+ - auth-oidc+ summary: Oidc Logout+ description: RP-initiated logout — clear cookie and redirect to provider end_session.+ operationId: oidc_logout_auth_oidc_logout_get+ parameters:+ - name: post_logout_redirect_uri+ in: query+ required: false+ schema:+ type: string+ default: /+ title: Post Logout Redirect Uri+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/ServiceProviderConfig:+ get:+ tags:+ - scim+ summary: Get Service Provider Config+ operationId: get_service_provider_config_scim_v2_ServiceProviderConfig_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ security:+ - HTTPBearer: []+ /scim/v2/ResourceTypes:+ get:+ tags:+ - scim+ summary: List Resource Types+ operationId: list_resource_types_scim_v2_ResourceTypes_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ security:+ - HTTPBearer: []+ /scim/v2/ResourceTypes/{resource_type_id}:+ get:+ tags:+ - scim+ summary: Get Resource Type+ operationId: get_resource_type_scim_v2_ResourceTypes__resource_type_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: resource_type_id+ in: path+ required: true+ schema:+ type: string+ title: Resource Type Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/Schemas:+ get:+ tags:+ - scim+ summary: List Schemas+ operationId: list_schemas_scim_v2_Schemas_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ security:+ - HTTPBearer: []+ /scim/v2/Schemas/{schema_id}:+ get:+ tags:+ - scim+ summary: Get Schema+ operationId: get_schema_scim_v2_Schemas__schema_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: schema_id+ in: path+ required: true+ schema:+ type: string+ title: Schema Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/Users:+ get:+ tags:+ - scim+ summary: List Users+ description: 'List or look up principals.+++ A provider calls this with a filter before every create, so the++ filter path is the hot one and an unsupported filter must be an error++ rather than a full listing.'+ operationId: list_users_scim_v2_Users_get+ security:+ - HTTPBearer: []+ parameters:+ - name: filter+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: Filter+ - name: startIndex+ in: query+ required: false+ schema:+ type: integer+ minimum: 1+ default: 1+ title: Startindex+ - name: count+ in: query+ required: false+ schema:+ type: integer+ minimum: 0+ default: 100+ title: Count+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ post:+ tags:+ - scim+ summary: Create User+ description: 'Create a principal, or return the existing one.+++ A repeated create for a ``userName`` that already exists is answered++ 409, which is what RFC 7644 specifies and what a provider uses to++ reconcile. Creating a second principal for the same address instead++ would give one person two accounts with two sets of permissions.'+ operationId: create_user_scim_v2_Users_post+ security:+ - HTTPBearer: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Body+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/Users/{user_id}:+ get:+ tags:+ - scim+ summary: Get User+ operationId: get_user_scim_v2_Users__user_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ title: User Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ put:+ tags:+ - scim+ summary: Replace User+ description: 'Replace a principal''s attributes.+++ One provider sends PUT for ordinary profile updates and for++ deactivation, so this path has to handle ``active: false`` with the same++ consequences the PATCH path gives it.'+ operationId: replace_user_scim_v2_Users__user_id__put+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ title: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Body+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ patch:+ tags:+ - scim+ summary: Patch User+ description: 'Apply a PATCH, which is how both providers deactivate a principal.+++ The body shapes differ between providers in five ways, all resolved by++ ``app.services.scim.patch``.'+ operationId: patch_user_scim_v2_Users__user_id__patch+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ title: User Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Body+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:+ tags:+ - scim+ summary: Delete User+ description: 'Deprovision a principal.+++ Deactivates rather than deletes. A deleted row takes its audit++ attribution, case ownership and approval history with it, and this++ platform''s own records reference the principal. Access ends completely++ either way, which is what DELETE means here.'+ operationId: delete_user_scim_v2_Users__user_id__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: user_id+ in: path+ required: true+ schema:+ type: string+ title: User Id+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/Groups:+ get:+ tags:+ - scim+ summary: List Groups+ operationId: list_groups_scim_v2_Groups_get+ security:+ - HTTPBearer: []+ parameters:+ - name: filter+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: Filter+ - name: startIndex+ in: query+ required: false+ schema:+ type: integer+ minimum: 1+ default: 1+ title: Startindex+ - name: count+ in: query+ required: false+ schema:+ type: integer+ minimum: 0+ default: 100+ title: Count+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ post:+ tags:+ - scim+ summary: Create Group+ description: 'Create a directory group and resolve what it confers.+++ The resolved role is recorded at create time and returned in the++ response, so an administrator can see immediately whether the group they++ pushed grants anything.'+ operationId: create_group_scim_v2_Groups_post+ security:+ - HTTPBearer: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Body+ responses:+ '201':description: Successful Responsecontent:application/json:schema: {}- /auth/saml/logout:- get:- tags:- - auth-saml- summary: Saml Logout- description: Initiate SAML SLO.- operationId: saml_logout_auth_saml_logout_get- responses:- '200':- description: Successful Response+ '422':+ description: Validation Errorcontent:application/json:- schema: {}- /auth/oidc/login:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /scim/v2/Groups/{group_id}:get:tags:- - auth-oidc- summary: Oidc Login- description: Initiate OIDC authorization code flow.- operationId: oidc_login_auth_oidc_login_get+ - scim+ summary: Get Group+ operationId: get_group_scim_v2_Groups__group_id__get+ security:+ - HTTPBearer: []parameters:- - name: redirect- in: query- required: false+ - name: group_id+ in: path+ required: trueschema:type: string- default: /- title: Redirect+ title: Group Idresponses:'200':description: Successful Response@@ -15944,34 +16590,34 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'- /auth/oidc/callback:- get:+ put:tags:- - auth-oidc- summary: Oidc Callback- description: Handle OIDC authorization code callback and issue JWT.- operationId: oidc_callback_auth_oidc_callback_get+ - scim+ summary: Replace Group+ description: 'Replace a group, including its entire membership.+++ PUT on a group is a *set* operation: members absent from the body are++ removed. One provider uses it to reconcile a group wholesale.'+ operationId: replace_group_scim_v2_Groups__group_id__put+ security:+ - HTTPBearer: []parameters:- - name: code- in: query+ - name: group_id+ in: pathrequired: trueschema:type: string- title: Code- - name: state- in: query+ title: Group Id+ requestBody:required: true- schema:- type: string- title: State- - name: error- in: query- required: false- schema:- anyOf:- - type: string- - type: 'null'- title: Error+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Bodyresponses:'200':description: Successful Response@@ -15984,46 +16630,66 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'- /auth/oidc/userinfo:- get:+ patch:tags:- - auth-oidc- summary: Oidc Userinfo- description: 'Proxy userinfo from upstream OIDC provider using the stored access- token.+ - scim+ summary: Patch Group+ description: 'Apply a group PATCH, which is how membership changes arrive.- Requires `Authorization: Bearer <aisoc_jwt>` header — the JWT sub is+ Both providers express member removal two ways, and one of those puts- used to look up the upstream token (stub: returns claims from AiSOC JWT).'- operationId: oidc_userinfo_auth_oidc_userinfo_get+ the member id in the path filter rather than the value. Both shapes are++ normalised before they reach this handler.'+ operationId: patch_group_scim_v2_Groups__group_id__patch+ security:+ - HTTPBearer: []+ parameters:+ - name: group_id+ in: path+ required: true+ schema:+ type: string+ title: Group Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Bodyresponses:'200':description: Successful Responsecontent:application/json:schema: {}- /auth/oidc/logout:- get:+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ delete:tags:- - auth-oidc- summary: Oidc Logout- description: RP-initiated logout — clear cookie and redirect to provider end_session.- operationId: oidc_logout_auth_oidc_logout_get+ - scim+ summary: Delete Group+ description: Delete a group and recompute what its members are left holding.+ operationId: delete_group_scim_v2_Groups__group_id__delete+ security:+ - HTTPBearer: []parameters:- - name: post_logout_redirect_uri- in: query- required: false+ - name: group_id+ in: path+ required: trueschema:type: string- default: /- title: Post Logout Redirect Uri+ title: Group Idresponses:- '200':+ '204':description: Successful Response- content:- application/json:- schema: {}'422':description: Validation Errorcontent:@@ -20321,6 +20987,26 @@ components:- view_type- nametitle: CreateSavedViewRequest+ CreateScimTokenRequest:+ properties:+ name:+ type: string+ maxLength: 200+ minLength: 1+ title: Name+ description: Which identity provider this credential is for+ expires_in_days:+ anyOf:+ - type: integer+ maximum: 3650.0+ minimum: 1.0+ - type: 'null'+ title: Expires In Days+ description: Optional lifetime; omit for no expiry+ type: object+ required:+ - name+ title: CreateScimTokenRequestCreateTaskRequest:properties:title:@@ -20372,6 +21058,73 @@ components:- username- passwordtitle: CreateUserRequest+ CreatedScimTokenOut:+ properties:+ id:+ type: string+ format: uuid+ title: Id+ name:+ type: string+ title: Name+ prefix:+ type: string+ title: Prefix+ org_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Org Id+ created_at:+ type: string+ format: date-time+ title: Created At+ last_used_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Last Used At+ expires_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Expires At+ revoked_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Revoked At+ rotated_from_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Rotated From Id+ active:+ type: boolean+ title: Active+ token:+ type: string+ title: Token+ description: The raw credential. Shown once and not recoverable.+ type: object+ required:+ - id+ - name+ - prefix+ - org_id+ - created_at+ - last_used_at+ - expires_at+ - revoked_at+ - rotated_from_id+ - active+ - token+ title: CreatedScimTokenOutCredentialsListResponse:properties:items:@@ -27954,6 +28707,18 @@ components:title: Permission Idstype: objecttitle: RoleUpdate+ RotateScimTokenRequest:+ properties:+ grace_hours:+ type: integer+ maximum: 168.0+ minimum: 0.0+ title: Grace Hours+ description: How long the superseded credential keeps working. Zero revokes+ it at once, for rotation after a disclosure.+ default: 24+ type: object+ title: RotateScimTokenRequestRuleActionWire:properties:set_severity:@@ -29354,6 +30119,68 @@ components:- findings_closed- error_messagetitle: ScanRunOut+ ScimTokenOut:+ properties:+ id:+ type: string+ format: uuid+ title: Id+ name:+ type: string+ title: Name+ prefix:+ type: string+ title: Prefix+ org_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Org Id+ created_at:+ type: string+ format: date-time+ title: Created At+ last_used_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Last Used At+ expires_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Expires At+ revoked_at:+ anyOf:+ - type: string+ format: date-time+ - type: 'null'+ title: Revoked At+ rotated_from_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Rotated From Id+ active:+ type: boolean+ title: Active+ type: object+ required:+ - id+ - name+ - prefix+ - org_id+ - created_at+ - last_used_at+ - expires_at+ - revoked_at+ - rotated_from_id+ - active+ title: ScimTokenOutShadowModeEntry:properties:alert_class:diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex 84fb611cb..d2effd606 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -131,6 +131,13 @@ AUTH_DEPENDENCY_NAMES = {"PortfolioScope","_scope","_admin_scope",+ # SCIM resolves a hashed per-organisation bearer token to a principal+ # carrying the tenant. The credential is the only source of the tenant on+ # that surface: RFC 7643 defines no tenant attribute, so there is no+ # request field for a handler to read one from.+ "ScimPrincipal",+ "scim_principal",+ "ScimAuth",}#: Helpers that intersect a caller-supplied tenant with authorised scope.diff --git a/scripts/check_scim_contract.py b/scripts/check_scim_contract.pynew file mode 100644index 000000000..d7552d1a5--- /dev/null+++ b/scripts/check_scim_contract.py@@ -0,0 +1,453 @@+#!/usr/bin/env python3+"""Keep the SCIM surface honest about itself, in both directions.++Why this gate exists+--------------------+SCIM has an unusual property for a write surface: the client decides what to+attempt by reading a document the server publishes. ``ServiceProviderConfig``+says whether PATCH works, whether filtering works, whether bulk works. An+identity provider reads it once at setup and configures itself accordingly.++That makes the discovery documents a claim, and a claim with no gate behind it+drifts. Two directions, both of which have a concrete failure:++*forward*+ The config advertises something the router does not implement. A provider+ configures itself to use it, and an administrator sees failed syncs whose+ cause is a JSON document rather than the code they are reading.++*reverse*+ The router grows an operation the config does not advertise. The provider+ never attempts it, so the capability is dead on arrival while every test+ for it passes. This is the shape that has repeated across this program:+ the mechanism exists, is tested, and nothing calls it.++Beyond the documents, two more disagreements would each be silent:++*role vocabulary*+ ``app.services.scim.roles`` maps directory groups onto the roles+ ``ROLE_PERMISSIONS`` enforces. Renaming a role there leaves the mapping+ pointing at a string that grants nothing, which reads in a console as+ though it grants something. Checked in both directions, so a *new* role+ must also be classified as assignable or recorded as deliberately not.++*mounting*+ A router nobody includes serves nothing. ``include_router`` does not+ populate ``app.routes`` on the pinned FastAPI, so an inventory assertion+ can measure nothing and pass; this reads the call itself out of+ ``main.py``, and ``test_scim_provisioning.py`` proves reachability by+ sending real requests.++Run: python3 scripts/check_scim_contract.py [--self-test]+"""++from __future__ import annotations++import ast+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402++REPO_ROOT = repo_root()++ROUTER = REPO_ROOT / "services/api/app/api/v1/endpoints/scim.py"+RESOURCES = REPO_ROOT / "services/api/app/services/scim/resources.py"+ROLES = REPO_ROOT / "services/api/app/services/scim/roles.py"+SECURITY = REPO_ROOT / "services/api/app/core/security.py"+MAIN = REPO_ROOT / "services/api/app/main.py"++#: Operations RFC 7644 defines that this deployment intends to serve, mapped+#: to the ``ServiceProviderConfig`` key that advertises them. A key absent+#: from here is one the config declares and no route corresponds to, which is+#: reported rather than assumed harmless.+CAPABILITY_ROUTES: dict[str, tuple[str, ...]] = {+ "patch": ("PATCH",),+}++#: Endpoints every declared ResourceType promises. Checked against the routes+#: that actually exist, because a ResourceType naming an endpoint nobody+#: serves is a 404 a provider discovers during its first sync.+REQUIRED_RESOURCE_ROUTES: dict[str, tuple[str, ...]] = {+ "/Users": ("GET", "POST"),+ "/Users/{user_id}": ("GET", "PUT", "PATCH", "DELETE"),+ "/Groups": ("GET", "POST"),+ "/Groups/{group_id}": ("GET", "PUT", "PATCH", "DELETE"),+ "/ServiceProviderConfig": ("GET",),+ "/ResourceTypes": ("GET",),+ "/Schemas": ("GET",),+}++#: Handlers that change state. Each must reach the audit helper: a SCIM write+#: whose only record is the provider's own log is a change this platform+#: cannot account for.+MUTATING_HANDLERS: frozenset[str] = frozenset(+ {+ "create_user",+ "replace_user",+ "patch_user",+ "delete_user",+ "create_group",+ "replace_group",+ "patch_group",+ "delete_group",+ }+)++AUDIT_HELPER = "_audit"+++def _parse(path: Path) -> ast.Module:+ return ast.parse(path.read_text(encoding="utf-8"))+++def _routes(tree: ast.Module) -> dict[str, set[str]]:+ """Every ``@router.<method>("<path>")`` in the module."""+ found: dict[str, set[str]] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ for dec in node.decorator_list:+ if not isinstance(dec, ast.Call) or not isinstance(dec.func, ast.Attribute):+ continue+ if not isinstance(dec.func.value, ast.Name) or dec.func.value.id != "router":+ continue+ method = dec.func.attr.upper()+ if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:+ continue+ if not dec.args or not isinstance(dec.args[0], ast.Constant):+ continue+ found.setdefault(str(dec.args[0].value), set()).add(method)+ return found+++def _handler_calls(tree: ast.Module) -> dict[str, set[str]]:+ """Names each route handler calls, for the audit check."""+ calls: dict[str, set[str]] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ names: set[str] = set()+ for inner in ast.walk(node):+ if isinstance(inner, ast.Call):+ func = inner.func+ if isinstance(func, ast.Name):+ names.add(func.id)+ elif isinstance(func, ast.Attribute):+ names.add(func.attr)+ calls[node.name] = names+ return calls+++def _module_constants(tree: ast.Module) -> dict[str, object]:+ """Module-level names bound to a literal.++ ``service_provider_config()`` names ``MAX_PAGE_SIZE`` inside the document+ it returns, which is right: a page cap written twice is a page cap that+ disagrees with itself. Resolving the name here is what lets the document+ stay readable to this gate without flattening it in the source.+ """+ constants: dict[str, object] = {}+ for node in tree.body:+ targets: list[str] = []+ value: ast.expr | None = None+ if isinstance(node, ast.Assign):+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]+ value = node.value+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):+ targets = [node.target.id]+ value = node.value+ if not targets or value is None:+ continue+ try:+ constants[targets[0]] = ast.literal_eval(value)+ except (ValueError, TypeError, SyntaxError):+ continue+ return constants+++def _resolve(node: ast.expr, constants: dict[str, object]) -> object:+ """``ast.literal_eval`` that also resolves module-level constant names."""+ if isinstance(node, ast.Name):+ if node.id not in constants:+ raise ValueError(f"unresolved name {node.id!r}")+ return constants[node.id]+ if isinstance(node, ast.Dict):+ return {+ _resolve(key, constants): _resolve(val, constants) for key, val in zip(node.keys, node.values, strict=True) if key is not None+ }+ if isinstance(node, ast.List | ast.Tuple | ast.Set):+ return [_resolve(item, constants) for item in node.elts]+ if isinstance(node, ast.JoinedStr):+ # The documents build their `location` fields from the mount point,+ # so the base path is written once. Without this the whole document+ # reads as unparseable and the gate reports a drift that is really a+ # limitation of the gate.+ parts: list[str] = []+ for piece in node.values:+ if isinstance(piece, ast.Constant):+ parts.append(str(piece.value))+ elif isinstance(piece, ast.FormattedValue):+ parts.append(str(_resolve(piece.value, constants)))+ else:+ raise ValueError("unsupported f-string component")+ return "".join(parts)+ return ast.literal_eval(node)+++def _dict_literal(tree: ast.Module, function: str) -> dict | None:+ """The dict a zero-argument function returns, when it returns a literal."""+ constants = _module_constants(tree)+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) or node.name != function:+ continue+ for inner in ast.walk(node):+ if isinstance(inner, ast.Return) and inner.value is not None:+ try:+ resolved = _resolve(inner.value, constants)+ except (ValueError, TypeError, SyntaxError):+ return None+ return resolved if isinstance(resolved, dict) else None+ return None+++def _assigned_names(tree: ast.Module, variable: str) -> set[str] | None:+ """Keys of a module-level dict, or members of a tuple/set/frozenset."""+ for node in ast.walk(tree):+ if not isinstance(node, ast.Assign):+ continue+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]+ if variable not in targets:+ continue+ try:+ value = ast.literal_eval(node.value)+ except (ValueError, TypeError, SyntaxError):+ return None+ if isinstance(value, dict):+ return set(value)+ if isinstance(value, list | tuple | set | frozenset):+ return set(value)+ for node in ast.walk(tree):+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == variable:+ if node.value is None:+ return None+ try:+ value = ast.literal_eval(node.value)+ except (ValueError, TypeError, SyntaxError):+ return None+ if isinstance(value, dict):+ return set(value)+ if isinstance(value, list | tuple | set | frozenset):+ return set(value)+ return None+++def _group_rule_roles(tree: ast.Module) -> set[str]:+ """Roles the group-name rules can produce."""+ for node in ast.walk(tree):+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "GROUP_NAME_RULES":+ try:+ rules = ast.literal_eval(node.value) if node.value is not None else ()+ except (ValueError, TypeError, SyntaxError):+ return set()+ return {role for _fragments, role in rules}+ return set()+++def audit(root: Path) -> tuple[list[str], dict[str, int]]:+ """Return ``(problems, counts)``. Counts prove the gate read something."""+ problems: list[str] = []+ counts = {"routes": 0, "capabilities": 0, "roles": 0, "mutating_handlers": 0}++ router_path = root / ROUTER.relative_to(REPO_ROOT)+ resources_path = root / RESOURCES.relative_to(REPO_ROOT)+ roles_path = root / ROLES.relative_to(REPO_ROOT)+ security_path = root / SECURITY.relative_to(REPO_ROOT)+ main_path = root / MAIN.relative_to(REPO_ROOT)++ missing = [p for p in (router_path, resources_path, roles_path, security_path, main_path) if not p.is_file()]+ if missing:+ problems.append("SCIM modules are absent: " + ", ".join(str(p.relative_to(root)) for p in missing))+ return problems, counts++ router_tree = _parse(router_path)+ resources_tree = _parse(resources_path)+ roles_tree = _parse(roles_path)+ security_tree = _parse(security_path)++ routes = _routes(router_tree)+ counts["routes"] = sum(len(methods) for methods in routes.values())++ # --- the router is mounted -------------------------------------------+ main_source = main_path.read_text(encoding="utf-8")+ if "include_router(scim_router)" not in main_source:+ problems.append("services/api/app/main.py does not include the SCIM router, so none of these routes are served")++ # --- declared resource endpoints exist --------------------------------+ for path, methods in REQUIRED_RESOURCE_ROUTES.items():+ served = routes.get(path, set())+ for method in methods:+ if method not in served:+ problems.append(f"the SCIM surface promises {method} {path} and the router does not define it")++ # --- ServiceProviderConfig agrees with the router ---------------------+ config = _dict_literal(resources_tree, "service_provider_config")+ if config is None:+ problems.append("service_provider_config() no longer returns a literal this gate can read")+ else:+ counts["capabilities"] = len(CAPABILITY_ROUTES)+ served_methods = {method for methods in routes.values() for method in methods}+ for capability, required in CAPABILITY_ROUTES.items():+ advertised = bool((config.get(capability) or {}).get("supported"))+ implemented = all(method in served_methods for method in required)+ if advertised and not implemented:+ problems.append(f"ServiceProviderConfig advertises {capability!r} and the router serves no {'/'.join(required)} route")+ if implemented and not advertised:+ problems.append(+ f"the router serves {'/'.join(required)} and ServiceProviderConfig does not advertise {capability!r}, "+ "so no identity provider will ever attempt it"+ )+ # Bulk is declared unsupported. If a /Bulk route ever appears, the+ # document has to stop saying otherwise.+ bulk_advertised = bool((config.get("bulk") or {}).get("supported"))+ bulk_served = any(path.rstrip("/").endswith("/Bulk") or path == "/Bulk" for path in routes)+ if bulk_served and not bulk_advertised:+ problems.append("a /Bulk route exists while ServiceProviderConfig declares bulk unsupported")+ if bulk_advertised and not bulk_served:+ problems.append("ServiceProviderConfig advertises bulk and no /Bulk route exists")++ # --- every mutating handler audits ------------------------------------+ calls = _handler_calls(router_tree)+ for handler in sorted(MUTATING_HANDLERS):+ if handler not in calls:+ problems.append(f"{handler}() is named as a mutating SCIM handler and no longer exists")+ continue+ counts["mutating_handlers"] += 1+ if AUDIT_HELPER not in calls[handler]:+ problems.append(f"{handler}() changes state and does not call {AUDIT_HELPER}(), so the change is unaccounted for")++ # --- the role vocabulary agrees, in both directions -------------------+ enforced = _assigned_names(security_tree, "ROLE_PERMISSIONS")+ precedence = _assigned_names(roles_tree, "ROLE_PRECEDENCE")+ unreachable = _assigned_names(roles_tree, "UNREACHABLE_BY_GROUP")+ rule_roles = _group_rule_roles(roles_tree)++ if enforced is None or precedence is None or unreachable is None:+ problems.append("the role vocabulary is no longer a literal this gate can read")+ else:+ counts["roles"] = len(enforced)+ for role in sorted(precedence):+ if role not in enforced:+ problems.append(f"ROLE_PRECEDENCE names {role!r}, which ROLE_PERMISSIONS does not define; it grants nothing")+ for role in sorted(rule_roles):+ if role not in precedence:+ problems.append(f"a group-name rule maps to {role!r}, which is not an assignable role")+ for role in sorted(unreachable):+ if role not in enforced:+ problems.append(f"UNREACHABLE_BY_GROUP names {role!r}, which ROLE_PERMISSIONS no longer defines")+ if role in precedence:+ problems.append(f"{role!r} is both assignable from a group and recorded as unreachable")+ for role in sorted(enforced - precedence - unreachable):+ problems.append(+ f"ROLE_PERMISSIONS defines {role!r} and app/services/scim/roles.py neither makes it assignable "+ "nor records why a directory group may not confer it"+ )++ return problems, counts+++def _self_test_cases() -> list[tuple[str, bool]]:+ """Prove the gate detects each drift it exists to catch.++ Each case mutates a copy of the real tree, because a gate proven only+ against a hand-built fixture is proven against the fixture.+ """+ import shutil+ import tempfile++ cases: list[tuple[str, bool]] = []+ clean, _counts = audit(REPO_ROOT)+ cases.append(("the real tree passes", not clean))++ mutations: list[tuple[str, Path, str, str]] = [+ (+ "an unmounted router is reported",+ MAIN,+ "app.include_router(scim_router)",+ "pass # router not mounted",+ ),+ (+ "a mutating handler that stops auditing is reported",+ ROUTER,+ 'await _audit(\n db,\n principal,\n request,\n action="scim:user:create",',+ 'await _unrecorded(\n db,\n principal,\n request,\n action="scim:user:create",',+ ),+ (+ "a role the mapping does not classify is reported",+ SECURITY,+ 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "platform_admin": ["*"],',+ 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "brand_new_role": ["*"],\n "platform_admin": ["*"],',+ ),+ (+ "a capability advertised with no route is reported",+ ROUTER,+ '@router.patch("/Users/{user_id}")',+ '@router.post("/Users/{user_id}/patched")',+ ),+ ]++ for description, target, old, new in mutations:+ with tempfile.TemporaryDirectory() as tmp:+ tree = Path(tmp) / "tree"+ # Copy only what the gate reads, so the self-test stays fast.+ for source in {ROUTER, RESOURCES, ROLES, SECURITY, MAIN}:+ destination = tree / source.relative_to(REPO_ROOT)+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, destination)+ patched = tree / target.relative_to(REPO_ROOT)+ source_text = patched.read_text(encoding="utf-8")+ if old not in source_text:+ cases.append((f"{description} (self-test anchor missing; case did not run)", False))+ continue+ patched.write_text(source_text.replace(old, new, 1), encoding="utf-8")+ problems, _ = audit(tree)+ cases.append((description, bool(problems)))++ return cases+++def main() -> int:+ if SELF_TEST_FLAG in sys.argv[1:]:+ # The injected cases run alongside the shared empty-tree floor, so one+ # command answers "does this gate still detect what it claims to".+ return self_test_main(Path(__file__).name, extra=_self_test_cases())++ problems, counts = audit(REPO_ROOT)++ print(+ f"check_scim_contract: read {counts['routes']} SCIM route(s), {counts['capabilities']} advertised capability(ies), "+ f"{counts['mutating_handlers']} mutating handler(s) and {counts['roles']} enforced role(s)"+ )++ # "found nothing" and "scanned nothing" must not print the same word.+ if counts["routes"] == 0 or counts["roles"] == 0:+ print(+ "\nFAIL: the SCIM surface or the role map read as empty. A clean result over nothing is indistinguishable from a wrong root.",+ file=sys.stderr,+ )+ return 2++ if problems:+ print(f"\nFAIL: {len(problems)} disagreement(s) between the SCIM surface and what it claims.", file=sys.stderr)+ for problem in problems:+ print(f" - {problem}", file=sys.stderr)+ return 1++ print("OK: the SCIM discovery documents, routes, audit trail and role mapping all agree.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex 7c826a707..b1016410d 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -203,6 +203,10 @@ RATCHET: dict[str, str] = {"services/api/app/api/v1/deps.py::_resolve_api_key::ApiKey": ("API-key hash lookup; the key row is the credential that carries the tenant"),+ "services/api/app/services/scim/tokens.py::verify_token::ScimToken": (+ "SCIM bearer-token digest lookup; the token row is what assigns the tenant, "+ "and RFC 7643 defines no tenant attribute a caller could have supplied"+ ),"services/api/app/api/v1/endpoints/graph_ws.py::_authenticate_ws::User": ("websocket ticket verification, same pre-auth shape as get_current_user"),@@ -299,7 +303,14 @@ RATCHET: dict[str, str] = {#: Raising this is a deliberate act with a diff attached. Appending to RATCHET#: without raising it fails the gate, which is the whole point.-MAX_RATCHET = 32+#:+#: 32 -> 33 for the SCIM bearer-token lookup. It belongs to the first group+#: above, the lookups that *establish* a tenant rather than operate inside one:+#: a SCIM request carries no tenant and RFC 7643 defines no attribute that+#: could carry one, so the token row is the only thing that assigns it. The+#: other seven unscoped statements the SCIM surface introduced were given real+#: predicates instead of entries here.+MAX_RATCHET = 33# ---------------------------------------------------------------------------diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.pyindex b476ba8fd..03a4cf830 100644--- a/services/api/app/api/v1/deps.py+++ b/services/api/app/api/v1/deps.py@@ -38,7 +38,7 @@ from app.api.v1.dev_auth import (DEMO_USER_ROLE,is_dev_mode,)-from app.core.security import decode_token, has_permission, hash_api_key+from app.core.security import decode_token, has_permission, hash_api_key, token_is_revokedfrom app.db.database import get_dbfrom app.models.tenant import ApiKey, User@@ -166,10 +166,21 @@ async def _resolve_api_key(raw_key: str, db: AsyncSession) -> CurrentUser:select(User).where(User.id == api_key.user_id, User.is_active == True) # noqa: E712)user = user_res.scalar_one_or_none()- if user is not None:- role = user.role- email = user.email- user_id = user.id+ if user is None:+ # The key names a principal who is deactivated or gone. Falling+ # through here left the key working under the generic+ # ``api_service`` role, so deprovisioning a user did not end the+ # programmatic access they had minted for themselves. A key+ # belongs to whoever owns it, and an owner who cannot sign in+ # cannot act through it either.+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Invalid or revoked API key",+ headers={"WWW-Authenticate": "Bearer"},+ )+ role = user.role+ email = user.email+ user_id = user.idreturn CurrentUser(user_id=user_id,@@ -231,6 +242,18 @@ async def get_current_user(if user is None:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")+ # A token minted before the principal's sessions were revoked stays+ # refused even after the principal is re-activated. Without this, the+ # `is_active` check above ends a session only for as long as the flag is+ # down, and re-enabling a deprovisioned account resurrects every token+ # still inside its expiry window.+ if token_is_revoked(payload.get("iat"), user.sessions_revoked_at):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Session revoked",+ headers={"WWW-Authenticate": "Bearer"},+ )+return CurrentUser(user_id=user.id,tenant_id=user.tenant_id,diff --git a/services/api/app/api/v1/endpoints/auth.py b/services/api/app/api/v1/endpoints/auth.pyindex 7867ab4fa..ba2905607 100644--- a/services/api/app/api/v1/endpoints/auth.py+++ b/services/api/app/api/v1/endpoints/auth.py@@ -16,6 +16,7 @@ from app.core.security import (create_access_token,create_refresh_token,decode_token,+ token_is_revoked,verify_password,)from app.models.tenant import User@@ -104,6 +105,12 @@ async def refresh_token(request: RefreshRequest, db: DBSession) -> TokenResponseif user is None:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")+ # A refresh token outlives an access token by days, so without this a+ # deprovisioned principal who is later re-activated could mint a fresh+ # session from a token issued before the revocation.+ if token_is_revoked(payload.get("iat"), user.sessions_revoked_at):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Session revoked")+token_data = {"sub": str(user.id),"tenant_id": str(user.tenant_id),diff --git a/services/api/app/api/v1/endpoints/scim.py b/services/api/app/api/v1/endpoints/scim.pynew file mode 100644index 000000000..d38249a48--- /dev/null+++ b/services/api/app/api/v1/endpoints/scim.py@@ -0,0 +1,936 @@+"""SCIM 2.0 provisioning endpoints (RFC 7643, RFC 7644).++Mounted outside ``/api/v1``. Identity providers are configured with a base+URL and append ``/Users`` and ``/Groups`` to it, so the path has to be the+one an administrator can paste, and the discovery documents have to describe+the same place.++Three properties hold across every handler here+------------------------------------------------+* **The tenant comes from the credential.** ``ScimAuth`` resolves a bearer+ token to a row, and that row carries the tenant. No handler reads a tenant+ from a path, a query or a body, and there is no SCIM attribute that could+ carry one.+* **Every write is audited.** Each mutating handler emits an ``scim:*``+ action through the existing hash-chained audit log, with the token name as+ the actor. The actor of a SCIM change is a machine, and an audit trail that+ cannot say which machine is not one.+* **Responses are SCIM-shaped.** Errors carry the RFC 7644 error schema and+ the ``application/scim+json`` content type, because a provider that+ receives a FastAPI validation error surfaces "unexpected response" to an+ administrator with nothing actionable in it.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Annotated, Any++from fastapi import APIRouter, Depends, Query, Request, Response, Security, status+from fastapi.responses import JSONResponse+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer+from sqlalchemy import delete, func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.db.database import get_db+from app.models.scim import ScimGroup, ScimGroupMember, ScimUser+from app.models.tenant import User+from app.services.audit import emit_audit+from app.services.scim import filters as scim_filters+from app.services.scim import patch as scim_patch+from app.services.scim import provisioning, resources, roles, tokens++router = APIRouter(prefix=resources.SCIM_BASE, tags=["scim"])++_bearer = HTTPBearer(auto_error=False)+++class ScimResponse(JSONResponse):+ """A response labelled ``application/scim+json``.++ Some provisioning clients reject ``application/json`` on a SCIM path.+ """++ media_type = resources.SCIM_CONTENT_TYPE+++def _error(status_code: int, detail: str, *, scim_type: str | None = None) -> ScimResponse:+ return ScimResponse(status_code=status_code, content=resources.error_response(status_code, detail, scim_type=scim_type))+++class ScimAuthFailed(Exception):+ """Raised by the dependency so the handler chain returns a SCIM error."""+++async def scim_principal(+ credentials: Annotated[HTTPAuthorizationCredentials | None, Security(_bearer)],+ db: Annotated[AsyncSession, Depends(get_db)],+) -> tokens.ScimPrincipal:+ """Resolve the bearer credential to a principal, or refuse.++ The 401 body is deliberately undifferentiated. The reason is recorded+ server-side; telling an unauthenticated caller whether a secret was+ wrong, revoked or expired tells it which secrets exist.+ """+ if credentials is None:+ raise ScimAuthFailed("no bearer credential presented")+ try:+ return await tokens.verify_token(db, credentials.credentials)+ except tokens.ScimAuthError as exc:+ raise ScimAuthFailed(exc.reason) from exc+++ScimAuth = Annotated[tokens.ScimPrincipal, Depends(scim_principal)]+ScimDB = Annotated[AsyncSession, Depends(get_db)]+++async def _audit(+ db: AsyncSession,+ principal: tokens.ScimPrincipal,+ request: Request,+ *,+ action: str,+ resource: str,+ resource_id: str | None,+ changes: dict[str, Any] | None = None,+) -> None:+ """Record one SCIM operation.++ ``actor_id`` is null because the actor is not a person. The credential's+ name and id go into ``changes`` so the trail can answer which+ integration made the change, which is the question an incident review+ asks first.++ The key is ``provisioned_by`` rather than anything containing "token",+ and the count below is ``programmatic_access_revoked`` rather than+ anything containing "api_key". ``audit_redaction`` masks values under+ secret-shaped keys, correctly, and neither of these values is a secret:+ naming them that way would replace the only two facts this record exists+ to carry with ``[REDACTED]`` while the row still looked complete.+ """+ payload = dict(changes or {})+ payload["provisioned_by"] = {"integration_id": str(principal.token_id), "integration": principal.token_name}+ if principal.org_id is not None:+ payload["org_id"] = str(principal.org_id)+ await emit_audit(+ db=db,+ tenant_id=principal.tenant_id,+ actor_id=None,+ actor_email=f"scim:{principal.token_name}",+ action=action,+ resource=resource,+ resource_id=resource_id,+ changes=payload,+ request=request,+ )+++# ── Discovery ─────────────────────────────────────────────────────────────+#+# Authenticated like everything else. RFC 7644 permits these to be+# anonymous, and both supported providers send the credential anyway. An+# anonymous discovery endpoint would publish which SCIM features a+# deployment has enabled to anyone who asks.++[email protected]("/ServiceProviderConfig")+async def get_service_provider_config(principal: ScimAuth) -> ScimResponse:+ del principal+ return ScimResponse(content=resources.service_provider_config())++[email protected]("/ResourceTypes")+async def list_resource_types(principal: ScimAuth) -> ScimResponse:+ del principal+ types = resources.resource_types()+ return ScimResponse(content=resources.list_response(types, total=len(types), start_index=1, count=len(types)))++[email protected]("/ResourceTypes/{resource_type_id}")+async def get_resource_type(resource_type_id: str, principal: ScimAuth) -> ScimResponse:+ del principal+ for entry in resources.resource_types():+ if entry["id"].casefold() == resource_type_id.casefold():+ return ScimResponse(content=entry)+ return _error(status.HTTP_404_NOT_FOUND, f"no resource type {resource_type_id!r}")++[email protected]("/Schemas")+async def list_schemas(principal: ScimAuth) -> ScimResponse:+ del principal+ docs = resources.schemas()+ return ScimResponse(content=resources.list_response(docs, total=len(docs), start_index=1, count=len(docs)))++[email protected]("/Schemas/{schema_id:path}")+async def get_schema(schema_id: str, principal: ScimAuth) -> ScimResponse:+ del principal+ for doc in resources.schemas():+ if doc["id"].casefold() == schema_id.casefold():+ return ScimResponse(content=doc)+ return _error(status.HTTP_404_NOT_FOUND, f"no schema {schema_id!r}")+++# ── Shared helpers ────────────────────────────────────────────────────────+++async def _load_scim_user(db: AsyncSession, tenant_id: uuid.UUID, user_id: uuid.UUID) -> tuple[User, ScimUser | None] | None:+ result = await db.execute(select(User).where(User.id == user_id, User.tenant_id == tenant_id))+ user = result.scalar_one_or_none()+ if user is None:+ return None+ meta = await db.execute(select(ScimUser).where(ScimUser.user_id == user.id, ScimUser.tenant_id == tenant_id))+ return user, meta.scalar_one_or_none()+++async def _user_groups(db: AsyncSession, tenant_id: uuid.UUID, user_id: uuid.UUID) -> list[tuple[uuid.UUID, str]]:+ rows = await db.execute(+ select(ScimGroup.id, ScimGroup.display_name)+ .join(ScimGroupMember, ScimGroupMember.group_id == ScimGroup.id)+ .where(+ ScimGroupMember.user_id == user_id,+ ScimGroupMember.tenant_id == tenant_id,+ ScimGroup.tenant_id == tenant_id,+ )+ .order_by(ScimGroup.display_name)+ )+ return [(row[0], row[1]) for row in rows.all()]+++async def _render_user(db: AsyncSession, user: User, meta: ScimUser | None) -> dict[str, Any]:+ return resources.user_resource(+ user_id=user.id,+ user_name=user.email,+ active=user.is_active,+ external_id=meta.external_id if meta else None,+ given_name=meta.given_name if meta else None,+ family_name=meta.family_name if meta else None,+ created_at=user.created_at,+ updated_at=meta.updated_at if meta else user.created_at,+ groups=await _user_groups(db, user.tenant_id, user.id),+ )+++async def _group_members(db: AsyncSession, tenant_id: uuid.UUID, group_id: uuid.UUID) -> list[tuple[uuid.UUID, str]]:+ rows = await db.execute(+ select(User.id, User.email)+ .join(ScimGroupMember, ScimGroupMember.user_id == User.id)+ .where(+ ScimGroupMember.group_id == group_id,+ ScimGroupMember.tenant_id == tenant_id,+ User.tenant_id == tenant_id,+ )+ .order_by(User.email)+ )+ return [(row[0], row[1]) for row in rows.all()]+++async def _render_group(db: AsyncSession, group: ScimGroup) -> dict[str, Any]:+ return resources.group_resource(+ group_id=group.id,+ display_name=group.display_name,+ external_id=group.external_id,+ mapped_role=group.mapped_role,+ created_at=group.created_at,+ updated_at=group.updated_at,+ members=await _group_members(db, group.tenant_id, group.id),+ )+++def _paging(start_index: int, count: int) -> tuple[int, int]:+ """Clamp SCIM's one-based paging to something a query can use."""+ start = max(start_index, 1)+ size = min(max(count, 1), resources.MAX_PAGE_SIZE)+ return start, size+++def _string_attr(value: Any) -> str | None:+ """Read an attribute a provider may send as a string or omit."""+ if value is None:+ return None+ if isinstance(value, str):+ stripped = value.strip()+ return stripped or None+ return None+++def _extract_names(body: dict[str, Any]) -> tuple[str | None, str | None]:+ name = body.get("name")+ if not isinstance(name, dict):+ return None, None+ given = family = None+ for key, value in name.items():+ if not isinstance(key, str):+ continue+ folded = key.casefold()+ if folded == "givenname":+ given = _string_attr(value)+ elif folded == "familyname":+ family = _string_attr(value)+ return given, family+++def _extract_username(body: dict[str, Any]) -> str | None:+ """Read ``userName``, falling back to a primary work email.++ One provider omits ``userName`` when the directory's username attribute+ is unset and sends only ``emails``. Without the fallback that create+ fails with a validation error the administrator reads as "SCIM is+ broken".+ """+ for key, value in body.items():+ if isinstance(key, str) and key.casefold() == "username":+ found = _string_attr(value)+ if found:+ return found+ emails = body.get("emails")+ if isinstance(emails, list):+ primary = None+ first = None+ for entry in emails:+ if not isinstance(entry, dict):+ continue+ value = _string_attr(entry.get("value"))+ if value is None:+ continue+ first = first or value+ if entry.get("primary") is True:+ primary = primary or value+ return primary or first+ return None+++def _extract_active(body: dict[str, Any], *, default: bool) -> bool:+ for key, value in body.items():+ if isinstance(key, str) and key.casefold() == "active":+ if value is None:+ return default+ return scim_patch.coerce_bool(value, attribute="active")+ return default+++# ── Users ─────────────────────────────────────────────────────────────────++[email protected]("/Users")+async def list_users(+ principal: ScimAuth,+ db: ScimDB,+ filter_: Annotated[str | None, Query(alias="filter")] = None,+ start_index: Annotated[int, Query(alias="startIndex", ge=1)] = 1,+ count: Annotated[int, Query(alias="count", ge=0)] = resources.DEFAULT_PAGE_SIZE,+) -> ScimResponse:+ """List or look up principals.++ A provider calls this with a filter before every create, so the+ filter path is the hot one and an unsupported filter must be an error+ rather than a full listing.+ """+ try:+ parsed = scim_filters.parse_equality(filter_, scim_filters.USER_FILTER_ATTRS)+ except scim_filters.ScimFilterError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ stmt = select(User).where(User.tenant_id == principal.tenant_id)+ if parsed is not None:+ if parsed.attribute == "username":+ stmt = stmt.where(func.lower(User.email) == parsed.value.strip().casefold())+ elif parsed.attribute == "external_id":+ stmt = stmt.join(ScimUser, ScimUser.user_id == User.id).where(+ ScimUser.external_id == parsed.value, ScimUser.tenant_id == principal.tenant_id+ )+ elif parsed.attribute == "id":+ try:+ stmt = stmt.where(User.id == uuid.UUID(parsed.value))+ except ValueError:+ return ScimResponse(content=resources.list_response([], total=0, start_index=start_index, count=0))++ total = await db.scalar(select(func.count()).select_from(stmt.subquery())) or 0+ start, size = _paging(start_index, count)+ rows = await db.execute(stmt.order_by(User.created_at, User.id).offset(start - 1).limit(size))+ users = list(rows.scalars().all())++ rendered = []+ for user in users:+ meta = await db.execute(select(ScimUser).where(ScimUser.user_id == user.id, ScimUser.tenant_id == principal.tenant_id))+ rendered.append(await _render_user(db, user, meta.scalar_one_or_none()))++ return ScimResponse(content=resources.list_response(rendered, total=int(total), start_index=start, count=size))++[email protected]("/Users/{user_id}")+async def get_user(user_id: str, principal: ScimAuth, db: ScimDB) -> ScimResponse:+ try:+ parsed_id = uuid.UUID(user_id)+ except ValueError:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ found = await _load_scim_user(db, principal.tenant_id, parsed_id)+ if found is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ user, meta = found+ return ScimResponse(content=await _render_user(db, user, meta))++[email protected]("/Users", status_code=status.HTTP_201_CREATED)+async def create_user(body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Create a principal, or return the existing one.++ A repeated create for a ``userName`` that already exists is answered+ 409, which is what RFC 7644 specifies and what a provider uses to+ reconcile. Creating a second principal for the same address instead+ would give one person two accounts with two sets of permissions.+ """+ if not isinstance(body, dict):+ return _error(status.HTTP_400_BAD_REQUEST, "request body must be a JSON object")++ user_name = _extract_username(body)+ if not user_name:+ return _error(status.HTTP_400_BAD_REQUEST, "userName is required", scim_type="invalidValue")++ try:+ active = _extract_active(body, default=True)+ except scim_patch.ScimPatchError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ external_id = _string_attr(body.get("externalId"))+ given, family = _extract_names(body)++ existing = await provisioning.find_user_by_username(db, principal.tenant_id, user_name)+ if existing is not None:+ return _error(status.HTTP_409_CONFLICT, f"userName {user_name!r} already exists", scim_type="uniqueness")++ # No password is set. A provisioned principal signs in through the+ # identity provider; an unusable hash means the password route cannot be+ # used to reach this account at all. `bcrypt` never produces a digest+ # that verifies against this value.+ user = User(+ tenant_id=principal.tenant_id,+ email=user_name,+ username=user_name,+ hashed_password="!scim-provisioned-no-password",+ role=provisioning.default_role(),+ is_active=active,+ is_verified=True,+ )+ db.add(user)+ await db.flush()++ meta = ScimUser(+ user_id=user.id,+ tenant_id=principal.tenant_id,+ external_id=external_id,+ given_name=given,+ family_name=family,+ token_id=principal.token_id,+ )+ db.add(meta)+ await db.flush()++ await _audit(+ db,+ principal,+ request,+ action="scim:user:create",+ resource="user",+ resource_id=str(user.id),+ changes={"user_name": user_name, "external_id": external_id, "active": active, "role": user.role},+ )+ await db.commit()++ return ScimResponse(status_code=status.HTTP_201_CREATED, content=await _render_user(db, user, meta))++[email protected]("/Users/{user_id}")+async def replace_user(user_id: str, body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Replace a principal's attributes.++ One provider sends PUT for ordinary profile updates and for+ deactivation, so this path has to handle ``active: false`` with the same+ consequences the PATCH path gives it.+ """+ try:+ parsed_id = uuid.UUID(user_id)+ except ValueError:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ found = await _load_scim_user(db, principal.tenant_id, parsed_id)+ if found is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ user, meta = found++ if not isinstance(body, dict):+ return _error(status.HTTP_400_BAD_REQUEST, "request body must be a JSON object")++ try:+ active = _extract_active(body, default=user.is_active)+ except scim_patch.ScimPatchError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ changes: dict[str, Any] = {}+ user_name = _extract_username(body)+ if user_name and user_name.casefold() != user.email.casefold():+ clash = await provisioning.find_user_by_username(db, principal.tenant_id, user_name)+ if clash is not None and clash.id != user.id:+ return _error(status.HTTP_409_CONFLICT, f"userName {user_name!r} already exists", scim_type="uniqueness")+ changes["user_name"] = {"from": user.email, "to": user_name}+ user.email = user_name+ user.username = user_name++ if meta is None:+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)+ db.add(meta)+ given, family = _extract_names(body)+ meta.given_name = given+ meta.family_name = family+ external_id = _string_attr(body.get("externalId"))+ if external_id is not None:+ meta.external_id = external_id+ meta.updated_at = datetime.now(UTC)++ changes.update(await _apply_active(db, user, active))++ await _audit(db, principal, request, action="scim:user:replace", resource="user", resource_id=str(user.id), changes=changes)+ await db.commit()+ return ScimResponse(content=await _render_user(db, user, meta))+++async def _apply_active(db: AsyncSession, user: User, active: bool) -> dict[str, Any]:+ """Apply an ``active`` value, doing the real work when it goes false.++ Returns what changed, so the audit record describes the effect rather+ than the request.+ """+ if active == user.is_active:+ return {}+ if not active:+ result = await provisioning.deactivate_user(db, user)+ return {+ "active": {"from": True, "to": False},+ "programmatic_access_revoked": result.api_keys_revoked,+ "sessions_revoked_at": result.sessions_revoked_at.isoformat(),+ }+ await provisioning.reactivate_user(db, user)+ return {"active": {"from": False, "to": True}}++[email protected]("/Users/{user_id}")+async def patch_user(user_id: str, body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Apply a PATCH, which is how both providers deactivate a principal.++ The body shapes differ between providers in five ways, all resolved by+ ``app.services.scim.patch``.+ """+ try:+ parsed_id = uuid.UUID(user_id)+ except ValueError:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ found = await _load_scim_user(db, principal.tenant_id, parsed_id)+ if found is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ user, meta = found++ try:+ operations = scim_patch.parse_patch(body)+ except scim_patch.ScimPatchError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ changes: dict[str, Any] = {}+ for op in operations:+ attribute = op.attribute or ""+ if attribute == "active":+ try:+ active = scim_patch.coerce_bool(op.value, attribute="active")+ except scim_patch.ScimPatchError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)+ changes.update(await _apply_active(db, user, active))+ elif attribute == "username":+ new_name = _string_attr(op.value)+ if new_name and new_name.casefold() != user.email.casefold():+ clash = await provisioning.find_user_by_username(db, principal.tenant_id, new_name)+ if clash is not None and clash.id != user.id:+ return _error(status.HTTP_409_CONFLICT, f"userName {new_name!r} already exists", scim_type="uniqueness")+ changes["user_name"] = {"from": user.email, "to": new_name}+ user.email = new_name+ user.username = new_name+ elif attribute in {"name.givenname", "givenname"}:+ if meta is None:+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)+ db.add(meta)+ meta.given_name = _string_attr(op.value)+ changes["given_name"] = meta.given_name+ elif attribute in {"name.familyname", "familyname"}:+ if meta is None:+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)+ db.add(meta)+ meta.family_name = _string_attr(op.value)+ changes["family_name"] = meta.family_name+ elif attribute == "externalid":+ if meta is None:+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)+ db.add(meta)+ meta.external_id = _string_attr(op.value)+ changes["external_id"] = meta.external_id+ elif attribute == "name":+ # A pathless replace sends the whole complex attribute.+ if isinstance(op.value, dict):+ if meta is None:+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)+ db.add(meta)+ given, family = _extract_names({"name": op.value})+ meta.given_name, meta.family_name = given, family+ changes["name"] = {"given": given, "family": family}+ else:+ # An attribute this platform does not store. Recorded rather than+ # rejected: a provider sends its whole mapped attribute set, and+ # 400-ing on `title` would fail the deactivation in the same body.+ changes.setdefault("ignored_attributes", []).append(attribute)++ if meta is not None:+ meta.updated_at = datetime.now(UTC)++ await _audit(db, principal, request, action="scim:user:patch", resource="user", resource_id=str(user.id), changes=changes)+ await db.commit()+ return ScimResponse(content=await _render_user(db, user, meta))++[email protected]("/Users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_user(user_id: str, principal: ScimAuth, db: ScimDB, request: Request) -> Response:+ """Deprovision a principal.++ Deactivates rather than deletes. A deleted row takes its audit+ attribution, case ownership and approval history with it, and this+ platform's own records reference the principal. Access ends completely+ either way, which is what DELETE means here.+ """+ try:+ parsed_id = uuid.UUID(user_id)+ except ValueError:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ found = await _load_scim_user(db, principal.tenant_id, parsed_id)+ if found is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no user {user_id!r}")+ user, _meta = found++ result = await provisioning.deactivate_user(db, user)+ await db.execute(delete(ScimGroupMember).where(ScimGroupMember.user_id == user.id, ScimGroupMember.tenant_id == principal.tenant_id))++ await _audit(+ db,+ principal,+ request,+ action="scim:user:delete",+ resource="user",+ resource_id=str(user.id),+ changes={+ "already_inactive": result.already_inactive,+ "programmatic_access_revoked": result.api_keys_revoked,+ "sessions_revoked_at": result.sessions_revoked_at.isoformat(),+ },+ )+ await db.commit()+ return Response(status_code=status.HTTP_204_NO_CONTENT)+++# ── Groups ────────────────────────────────────────────────────────────────++[email protected]("/Groups")+async def list_groups(+ principal: ScimAuth,+ db: ScimDB,+ filter_: Annotated[str | None, Query(alias="filter")] = None,+ start_index: Annotated[int, Query(alias="startIndex", ge=1)] = 1,+ count: Annotated[int, Query(alias="count", ge=0)] = resources.DEFAULT_PAGE_SIZE,+) -> ScimResponse:+ try:+ parsed = scim_filters.parse_equality(filter_, scim_filters.GROUP_FILTER_ATTRS)+ except scim_filters.ScimFilterError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ stmt = select(ScimGroup).where(ScimGroup.tenant_id == principal.tenant_id)+ if parsed is not None:+ if parsed.attribute == "display_name":+ stmt = stmt.where(ScimGroup.display_name == parsed.value)+ elif parsed.attribute == "external_id":+ stmt = stmt.where(ScimGroup.external_id == parsed.value)+ elif parsed.attribute == "id":+ try:+ stmt = stmt.where(ScimGroup.id == uuid.UUID(parsed.value))+ except ValueError:+ return ScimResponse(content=resources.list_response([], total=0, start_index=start_index, count=0))++ total = await db.scalar(select(func.count()).select_from(stmt.subquery())) or 0+ start, size = _paging(start_index, count)+ rows = await db.execute(stmt.order_by(ScimGroup.created_at, ScimGroup.id).offset(start - 1).limit(size))+ rendered = [await _render_group(db, group) for group in rows.scalars().all()]+ return ScimResponse(content=resources.list_response(rendered, total=int(total), start_index=start, count=size))++[email protected]("/Groups/{group_id}")+async def get_group(group_id: str, principal: ScimAuth, db: ScimDB) -> ScimResponse:+ group = await _load_group(db, principal.tenant_id, group_id)+ if group is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no group {group_id!r}")+ return ScimResponse(content=await _render_group(db, group))+++async def _load_group(db: AsyncSession, tenant_id: uuid.UUID, group_id: str) -> ScimGroup | None:+ try:+ parsed_id = uuid.UUID(group_id)+ except ValueError:+ return None+ result = await db.execute(select(ScimGroup).where(ScimGroup.id == parsed_id, ScimGroup.tenant_id == tenant_id))+ return result.scalar_one_or_none()++[email protected]("/Groups", status_code=status.HTTP_201_CREATED)+async def create_group(body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Create a directory group and resolve what it confers.++ The resolved role is recorded at create time and returned in the+ response, so an administrator can see immediately whether the group they+ pushed grants anything.+ """+ if not isinstance(body, dict):+ return _error(status.HTTP_400_BAD_REQUEST, "request body must be a JSON object")++ display_name = None+ for key, value in body.items():+ if isinstance(key, str) and key.casefold() == "displayname":+ display_name = _string_attr(value)+ if not display_name:+ return _error(status.HTTP_400_BAD_REQUEST, "displayName is required", scim_type="invalidValue")++ existing = await db.execute(select(ScimGroup).where(ScimGroup.tenant_id == principal.tenant_id, ScimGroup.display_name == display_name))+ if existing.scalar_one_or_none() is not None:+ return _error(status.HTTP_409_CONFLICT, f"displayName {display_name!r} already exists", scim_type="uniqueness")++ group = ScimGroup(+ tenant_id=principal.tenant_id,+ display_name=display_name,+ external_id=_string_attr(body.get("externalId")),+ mapped_role=roles.resolve_role(display_name),+ token_id=principal.token_id,+ )+ db.add(group)+ await db.flush()++ added = await _add_members(db, principal.tenant_id, group, _member_ids_from_body(body))++ await _audit(+ db,+ principal,+ request,+ action="scim:group:create",+ resource="scim_group",+ resource_id=str(group.id),+ changes={"display_name": display_name, "mapped_role": group.mapped_role, "members_added": added},+ )+ await db.commit()+ return ScimResponse(status_code=status.HTTP_201_CREATED, content=await _render_group(db, group))+++def _member_ids_from_body(body: dict[str, Any]) -> list[str]:+ members = body.get("members")+ if not isinstance(members, list):+ return []+ found: list[str] = []+ for entry in members:+ if isinstance(entry, str) and entry:+ found.append(entry)+ elif isinstance(entry, dict):+ for key, value in entry.items():+ if isinstance(key, str) and key.casefold() == "value" and isinstance(value, str) and value:+ found.append(value)+ return found+++async def _add_members(db: AsyncSession, tenant_id: uuid.UUID, group: ScimGroup, raw_ids: list[str]) -> int:+ """Add members, ignoring ids that are not principals of this tenant.++ A member id from outside the tenant is dropped rather than errored. It+ is a stale reference in the provider's own state, and failing the whole+ sync over one would stop every other change in the same push.+ """+ added = 0+ for raw in raw_ids:+ try:+ member_id = uuid.UUID(raw)+ except ValueError:+ continue+ exists = await db.execute(select(User.id).where(User.id == member_id, User.tenant_id == tenant_id))+ if exists.scalar_one_or_none() is None:+ continue+ already = await db.execute(+ select(ScimGroupMember).where(+ ScimGroupMember.group_id == group.id,+ ScimGroupMember.user_id == member_id,+ ScimGroupMember.tenant_id == tenant_id,+ )+ )+ if already.scalar_one_or_none() is not None:+ continue+ db.add(ScimGroupMember(group_id=group.id, user_id=member_id, tenant_id=tenant_id))+ added += 1++ if added:+ await db.flush()+ await provisioning.recompute_roles_for_group(db, group)+ return added+++async def _remove_members(db: AsyncSession, group: ScimGroup, raw_ids: list[str]) -> int:+ removed = 0+ affected: list[uuid.UUID] = []+ for raw in raw_ids:+ try:+ member_id = uuid.UUID(raw)+ except ValueError:+ continue+ result = await db.execute(+ delete(ScimGroupMember).where(+ ScimGroupMember.group_id == group.id,+ ScimGroupMember.user_id == member_id,+ ScimGroupMember.tenant_id == group.tenant_id,+ )+ )+ if result.rowcount:+ removed += int(result.rowcount)+ affected.append(member_id)++ # Recomputed after the deletes land, so a principal who has just lost the+ # group that granted their authority drops to the default rather than+ # keeping it. This is the step that makes removal mean something.+ for member_id in affected:+ user = await db.get(User, member_id)+ if user is not None:+ await provisioning.recompute_role(db, user)+ return removed++[email protected]("/Groups/{group_id}")+async def replace_group(group_id: str, body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Replace a group, including its entire membership.++ PUT on a group is a *set* operation: members absent from the body are+ removed. One provider uses it to reconcile a group wholesale.+ """+ group = await _load_group(db, principal.tenant_id, group_id)+ if group is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no group {group_id!r}")+ if not isinstance(body, dict):+ return _error(status.HTTP_400_BAD_REQUEST, "request body must be a JSON object")++ changes: dict[str, Any] = {}+ for key, value in body.items():+ if isinstance(key, str) and key.casefold() == "displayname":+ new_name = _string_attr(value)+ if new_name and new_name != group.display_name:+ changes["display_name"] = {"from": group.display_name, "to": new_name}+ group.display_name = new_name+ group.mapped_role = roles.resolve_role(new_name)+ changes["mapped_role"] = group.mapped_role++ external_id = _string_attr(body.get("externalId"))+ if external_id is not None:+ group.external_id = external_id++ desired = set(_member_ids_from_body(body))+ current = {str(member_id) for member_id, _ in await _group_members(db, group.tenant_id, group.id)}+ changes["members_added"] = await _add_members(db, principal.tenant_id, group, sorted(desired - current))+ changes["members_removed"] = await _remove_members(db, group, sorted(current - desired))+ group.updated_at = datetime.now(UTC)++ if "mapped_role" in changes:+ await provisioning.recompute_roles_for_group(db, group)++ await _audit(db, principal, request, action="scim:group:replace", resource="scim_group", resource_id=str(group.id), changes=changes)+ await db.commit()+ return ScimResponse(content=await _render_group(db, group))++[email protected]("/Groups/{group_id}")+async def patch_group(group_id: str, body: dict[str, Any], principal: ScimAuth, db: ScimDB, request: Request) -> ScimResponse:+ """Apply a group PATCH, which is how membership changes arrive.++ Both providers express member removal two ways, and one of those puts+ the member id in the path filter rather than the value. Both shapes are+ normalised before they reach this handler.+ """+ group = await _load_group(db, principal.tenant_id, group_id)+ if group is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no group {group_id!r}")++ try:+ operations = scim_patch.parse_patch(body)+ except scim_patch.ScimPatchError as exc:+ return _error(status.HTTP_400_BAD_REQUEST, exc.detail, scim_type=exc.scim_type)++ changes: dict[str, Any] = {"members_added": 0, "members_removed": 0}+ for op in operations:+ attribute = op.attribute or ""+ if attribute == "members":+ ids = scim_patch.member_ids(op)+ if op.op == "remove":+ if not ids and op.member_id is None and op.value is None:+ # `remove` on `members` with nothing named empties the+ # group. RFC 7644 allows it and a provider sends it when+ # the last member leaves.+ current = [str(member_id) for member_id, _ in await _group_members(db, group.tenant_id, group.id)]+ changes["members_removed"] += await _remove_members(db, group, current)+ else:+ changes["members_removed"] += await _remove_members(db, group, ids)+ elif op.op == "replace":+ current = [str(member_id) for member_id, _ in await _group_members(db, group.tenant_id, group.id)]+ changes["members_removed"] += await _remove_members(db, group, sorted(set(current) - set(ids)))+ changes["members_added"] += await _add_members(db, principal.tenant_id, group, sorted(set(ids) - set(current)))+ else:+ changes["members_added"] += await _add_members(db, principal.tenant_id, group, ids)+ elif attribute == "displayname":+ new_name = _string_attr(op.value)+ if new_name and new_name != group.display_name:+ changes["display_name"] = {"from": group.display_name, "to": new_name}+ group.display_name = new_name+ group.mapped_role = roles.resolve_role(new_name)+ changes["mapped_role"] = group.mapped_role+ await provisioning.recompute_roles_for_group(db, group)+ elif attribute == "externalid":+ group.external_id = _string_attr(op.value)+ else:+ changes.setdefault("ignored_attributes", []).append(attribute)++ group.updated_at = datetime.now(UTC)+ await _audit(db, principal, request, action="scim:group:patch", resource="scim_group", resource_id=str(group.id), changes=changes)+ await db.commit()+ return ScimResponse(content=await _render_group(db, group))++[email protected]("/Groups/{group_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_group(group_id: str, principal: ScimAuth, db: ScimDB, request: Request) -> Response:+ """Delete a group and recompute what its members are left holding."""+ group = await _load_group(db, principal.tenant_id, group_id)+ if group is None:+ return _error(status.HTTP_404_NOT_FOUND, f"no group {group_id!r}")++ members = [member_id for member_id, _ in await _group_members(db, group.tenant_id, group.id)]+ await db.execute(delete(ScimGroupMember).where(ScimGroupMember.group_id == group.id, ScimGroupMember.tenant_id == group.tenant_id))+ await db.delete(group)+ await db.flush()++ # Losing the group that granted a role has to take the role with it.+ for member_id in members:+ user = await db.get(User, member_id)+ if user is not None:+ await provisioning.recompute_role(db, user)++ await _audit(+ db,+ principal,+ request,+ action="scim:group:delete",+ resource="scim_group",+ resource_id=group_id,+ changes={"members_detached": len(members)},+ )+ await db.commit()+ return Response(status_code=status.HTTP_204_NO_CONTENT)diff --git a/services/api/app/api/v1/endpoints/scim_tokens.py b/services/api/app/api/v1/endpoints/scim_tokens.pynew file mode 100644index 000000000..8a0db62b6--- /dev/null+++ b/services/api/app/api/v1/endpoints/scim_tokens.py@@ -0,0 +1,201 @@+"""Administering the credentials the SCIM surface accepts.++Separate from ``scim.py`` on purpose. That module is the machine-facing+surface, authenticated by the token it is about; this one is the+human-facing surface, authenticated by a console session, and the two must+not share a credential. A SCIM token that could mint SCIM tokens would be a+credential that escalates itself.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Annotated, Any++from fastapi import APIRouter, HTTPException, Request, status+from pydantic import BaseModel, Field+from sqlalchemy import select++from app.api.v1.deps import AuthUser, DBSession, require_permission+from app.models.organization import OrganizationTenant+from app.models.scim import ScimToken+from app.services.audit import emit_audit+from app.services.scim import tokens as scim_tokens++router = APIRouter(prefix="/scim-tokens", tags=["scim"])+++class CreateScimTokenRequest(BaseModel):+ name: str = Field(..., min_length=1, max_length=200, description="Which identity provider this credential is for")+ expires_in_days: int | None = Field(None, ge=1, le=3650, description="Optional lifetime; omit for no expiry")+++class RotateScimTokenRequest(BaseModel):+ grace_hours: int = Field(+ 24,+ ge=0,+ le=168,+ description=("How long the superseded credential keeps working. Zero revokes it at once, for rotation after a disclosure."),+ )+++class ScimTokenOut(BaseModel):+ id: uuid.UUID+ name: str+ prefix: str+ org_id: uuid.UUID | None+ created_at: datetime+ last_used_at: datetime | None+ expires_at: datetime | None+ revoked_at: datetime | None+ rotated_from_id: uuid.UUID | None+ active: bool+++class CreatedScimTokenOut(ScimTokenOut):+ token: str = Field(..., description="The raw credential. Shown once and not recoverable.")+++def _to_out(row: ScimToken) -> ScimTokenOut:+ return ScimTokenOut(+ id=row.id,+ name=row.name,+ prefix=row.token_prefix,+ org_id=row.org_id,+ created_at=row.created_at,+ last_used_at=row.last_used_at,+ expires_at=row.expires_at,+ revoked_at=row.revoked_at,+ rotated_from_id=row.rotated_from_id,+ active=row.is_usable(),+ )+++async def _owning_org(db: Any, tenant_id: uuid.UUID) -> uuid.UUID | None:+ """The organisation whose portfolio holds this tenant, if any.++ Read here rather than accepted from the caller: ``organization_tenants``+ already carries a uniqueness constraint making one tenant's managing+ organisation single-valued, so there is nothing for a request field to+ usefully say and something for it to get wrong.+ """+ result = await db.execute(select(OrganizationTenant.org_id).where(OrganizationTenant.tenant_id == tenant_id))+ return result.scalar_one_or_none()++[email protected]("", response_model=list[ScimTokenOut])+async def list_scim_tokens(db: DBSession, current_user: AuthUser) -> list[ScimTokenOut]:+ """List this tenant's SCIM credentials. Secrets are never returned."""+ result = await db.execute(select(ScimToken).where(ScimToken.tenant_id == current_user.tenant_id).order_by(ScimToken.created_at.desc()))+ return [_to_out(row) for row in result.scalars().all()]++[email protected]("", response_model=CreatedScimTokenOut, status_code=status.HTTP_201_CREATED)+async def create_scim_token(+ body: CreateScimTokenRequest,+ db: DBSession,+ request: Request,+ current_user: Annotated[Any, require_permission("settings:write")],+) -> CreatedScimTokenOut:+ """Mint a SCIM credential for this tenant."""+ expires_at = None+ if body.expires_in_days is not None:+ expires_at = datetime.now(UTC) + timedelta(days=body.expires_in_days)++ token, raw = await scim_tokens.mint_token(+ db,+ tenant_id=current_user.tenant_id,+ org_id=await _owning_org(db, current_user.tenant_id),+ name=body.name,+ created_by=current_user.user_id,+ expires_at=expires_at,+ )+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ action="scim:token:create",+ resource="scim_token",+ resource_id=str(token.id),+ changes={"name": body.name, "prefix": token.token_prefix, "expires_at": expires_at.isoformat() if expires_at else None},+ request=request,+ )+ await db.commit()+ await db.refresh(token)+ return CreatedScimTokenOut(**_to_out(token).model_dump(), token=raw)++[email protected]("/{token_id}/rotate", response_model=CreatedScimTokenOut, status_code=status.HTTP_201_CREATED)+async def rotate_scim_token(+ token_id: uuid.UUID,+ body: RotateScimTokenRequest,+ db: DBSession,+ request: Request,+ current_user: Annotated[Any, require_permission("settings:write")],+) -> CreatedScimTokenOut:+ """Replace a credential, leaving the old one working for a grace window."""+ result = await db.execute(select(ScimToken).where(ScimToken.id == token_id, ScimToken.tenant_id == current_user.tenant_id))+ token = result.scalar_one_or_none()+ if token is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="SCIM token not found")+ if token.revoked_at is not None:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This token is revoked; create a new one instead")++ replacement, raw = await scim_tokens.rotate_token(+ db, token=token, created_by=current_user.user_id, grace=timedelta(hours=body.grace_hours)+ )+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ action="scim:token:rotate",+ resource="scim_token",+ resource_id=str(replacement.id),+ changes={+ "superseded": str(token.id),+ "grace_hours": body.grace_hours,+ "superseded_expires_at": token.expires_at.isoformat() if token.expires_at else None,+ },+ request=request,+ )+ await db.commit()+ await db.refresh(replacement)+ return CreatedScimTokenOut(**_to_out(replacement).model_dump(), token=raw)++[email protected]("/{token_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)+async def revoke_scim_token(+ token_id: uuid.UUID,+ db: DBSession,+ request: Request,+ current_user: Annotated[Any, require_permission("settings:write")],+) -> None:+ """Revoke a credential immediately.++ The row stays, because ``aisoc_scim_users.token_id`` references it and+ the audit trail answers "which integration provisioned this principal"+ through it.+ """+ result = await db.execute(select(ScimToken).where(ScimToken.id == token_id, ScimToken.tenant_id == current_user.tenant_id))+ token = result.scalar_one_or_none()+ if token is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="SCIM token not found")++ if token.revoked_at is None:+ token.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,+ action="scim:token:revoke",+ resource="scim_token",+ resource_id=str(token.id),+ changes={"prefix": token.token_prefix},+ request=request,+ )+ await db.commit()diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex a781666f7..48062bbfc 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -76,6 +76,7 @@ from app.api.v1.endpoints import (sandbox,saved_hunts,saved_views,+ scim_tokens,shifts,sla,stix_taxii,@@ -208,6 +209,9 @@ api_router.include_router(live_actions.router)# list pages. Per-user-per-tenant CRUD; tenant scoping via RLS, user# scoping in the API layer (every query filters on user_id).api_router.include_router(saved_views.router)+# Administering SCIM credentials, which is a console action. The SCIM+# surface those credentials authenticate is mounted at /scim/v2 in main.py.+api_router.include_router(scim_tokens.router)# Wave 3 — operational maturityapi_router.include_router(assets.router)diff --git a/services/api/app/core/security.py b/services/api/app/core/security.pyindex d26ba33b0..c2a3dca60 100644--- a/services/api/app/core/security.py+++ b/services/api/app/core/security.py@@ -170,21 +170,46 @@ def get_password_hash(password: str) -> str:def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:to_encode = data.copy()+ issued_at = datetime.now(UTC)if expires_delta:- expire = datetime.now(UTC) + expires_delta+ expire = issued_at + expires_deltaelse:- expire = datetime.now(UTC) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)- to_encode.update({"exp": expire, "type": "access"})+ expire = issued_at + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)+ to_encode.update({"exp": expire, "iat": issued_at, "type": "access"})return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)def create_refresh_token(data: dict[str, Any]) -> str:to_encode = data.copy()- expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)- to_encode.update({"exp": expire, "type": "refresh"})+ issued_at = datetime.now(UTC)+ expire = issued_at + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)+ to_encode.update({"exp": expire, "iat": issued_at, "type": "refresh"})return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)+def token_is_revoked(issued_at: Any, sessions_revoked_at: datetime | None) -> bool:+ """Whether a token predates the principal's last session revocation.++ ``iat`` is the only thing distinguishing a token minted before a+ deprovisioning from one minted after it. A token with no ``iat`` at all+ predates this claim being added and is treated as revoked whenever a+ revocation exists, which fails closed: the alternative would let a token+ from before the upgrade outlive the revocation that was supposed to end it.+ """+ if sessions_revoked_at is None:+ return False+ if issued_at is None:+ return True+ try:+ minted = datetime.fromtimestamp(float(issued_at), tz=UTC)+ except (TypeError, ValueError, OSError, OverflowError):+ return True+ cutoff = sessions_revoked_at if sessions_revoked_at.tzinfo else sessions_revoked_at.replace(tzinfo=UTC)+ # `<=` rather than `<`: `iat` has one-second resolution, so a token+ # minted in the same second as the revocation must not survive it.+ return minted <= cutoff++def decode_token(token: str) -> dict[str, Any]:return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])diff --git a/services/api/app/main.py b/services/api/app/main.pyindex c4ffe7ebf..8e14e4f50 100644--- a/services/api/app/main.py+++ b/services/api/app/main.py@@ -10,10 +10,13 @@ import structlogfrom fastapi import FastAPI, HTTPException, Request, Response, Security, statusfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddleware+from fastapi.responses import JSONResponsefrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latestfrom app._health import install_health_routes+from app.api.v1.endpoints.scim import ScimAuthFailed+from app.api.v1.endpoints.scim import router as scim_routerfrom app.api.v1.router import api_routerfrom app.auth.oidc import router as oidc_routerfrom app.auth.saml import router as saml_router@@ -31,6 +34,8 @@ from app.middleware.audit_middleware import AuditMiddlewarefrom app.middleware.demo_mode import DemoModeMiddlewarefrom app.models import Basefrom app.services.plugin_manager import get_plugin_manager+from app.services.scim.resources import SCIM_CONTENT_TYPE+from app.services.scim.resources import error_response as scim_error_responsefrom app.workers.hunt_scheduler import run_forever as run_hunt_schedulerfrom app.workers.oauth_refresh import run_forever as run_oauth_refreshfrom app.workers.retention_purge import run_forever as run_retention_purge@@ -598,8 +603,30 @@ def create_application() -> FastAPI:app.include_router(api_router)app.include_router(saml_router)app.include_router(oidc_router)+ # SCIM is mounted at /scim/v2 rather than under /api/v1. An identity+ # provider is configured with a base URL and appends /Users and /Groups+ # to it, and the discovery documents this service publishes name that+ # same base, so the path has to be the one an administrator can paste.+ app.include_router(scim_router)app.include_router(graphql_router, prefix="/graphql", tags=["graphql"])+ # A SCIM client that presents a bad credential must receive a SCIM error+ # document, not FastAPI's default. A provider shows an administrator+ # whatever it got back, and `{"detail": "..."}` gives them nothing to act+ # on while looking like the service is broken rather than the secret wrong.+ @app.exception_handler(ScimAuthFailed)+ async def _scim_auth_failed(request: Request, exc: ScimAuthFailed) -> JSONResponse:+ # The reason is logged, never returned: telling an unauthenticated+ # caller whether a secret was wrong, revoked or expired tells it+ # which secrets exist.+ logger.warning("scim: refused a request — %s", str(exc).replace("\r", "").replace("\n", " ")[:200])+ return JSONResponse(+ status_code=status.HTTP_401_UNAUTHORIZED,+ content=scim_error_response(status.HTTP_401_UNAUTHORIZED, "Invalid SCIM credential"),+ media_type=SCIM_CONTENT_TYPE,+ headers={"WWW-Authenticate": "Bearer"},+ )+return appdiff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.pyindex 9ebf5af5d..79813543b 100644--- a/services/api/app/models/__init__.py+++ b/services/api/app/models/__init__.py@@ -47,6 +47,7 @@ from app.models.responder import ()from app.models.saved_hunt import SavedHuntfrom app.models.saved_view import SavedView+from app.models.scim import ScimGroup, ScimGroupMember, ScimToken, ScimUserfrom app.models.tenant import ApiKey, Tenant, Userfrom app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC@@ -84,6 +85,10 @@ __all__ = ["MSSPTenantNote","OAuthAppCredential","Organization",+ "ScimGroup",+ "ScimGroupMember",+ "ScimToken",+ "ScimUser","OrganizationMember","OrganizationMemberTenant","OrganizationTenant",diff --git a/services/api/app/models/scim.py b/services/api/app/models/scim.pynew file mode 100644index 000000000..89e69f2b3--- /dev/null+++ b/services/api/app/models/scim.py@@ -0,0 +1,106 @@+"""SCIM 2.0 provisioning ORM models (migration 071).++Kept deliberately thin. The interesting decisions are recorded in+``services/api/migrations/071_scim_provisioning.sql`` next to the constraints+that enforce them; repeating them here would give a reader two places to+disagree with each other.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import DateTime, ForeignKey, Text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++class ScimToken(Base):+ """A per-organisation SCIM bearer credential.++ The raw secret exists only in the mint response. This row holds a+ SHA-256 digest for lookup and a short prefix for display.+ """++ __tablename__ = "aisoc_scim_tokens"++ 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)+ org_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("organizations.id", ondelete="CASCADE"), nullable=True, index=True)+ name: Mapped[str] = mapped_column(Text, nullable=False)+ token_prefix: Mapped[str] = mapped_column(Text, nullable=False)+ token_hash: Mapped[str] = mapped_column(Text, nullable=False, unique=True)+ created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ rotated_from_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("aisoc_scim_tokens.id", ondelete="SET NULL"), nullable=True)++ def is_usable(self, *, now: datetime | None = None) -> bool:+ """Whether this credential may authenticate a request right now.++ Revocation wins over expiry and both win over existence, so a caller+ never has to remember the order.+ """+ moment = now or datetime.now(UTC)+ if self.revoked_at is not None:+ return False+ return not (self.expires_at is not None and self.expires_at <= moment)+++class ScimUser(Base):+ """SCIM metadata for a provisioned principal, beside ``users``."""++ __tablename__ = "aisoc_scim_users"++ user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)+ external_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ given_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ family_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ token_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("aisoc_scim_tokens.id", ondelete="SET NULL"), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)+ )+++class ScimGroup(Base):+ """A directory group pushed by the identity provider.++ ``mapped_role`` is NULL for a group whose name does not resolve to a role+ this platform enforces. Such a group records membership and confers+ nothing, so an unrecognised directory group is powerless rather than+ unconstrained.+ """++ __tablename__ = "aisoc_scim_groups"++ 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)+ display_name: Mapped[str] = mapped_column(Text, nullable=False)+ external_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ mapped_role: Mapped[str | None] = mapped_column(Text, nullable=True)+ token_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("aisoc_scim_tokens.id", ondelete="SET NULL"), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)+ )+++class ScimGroupMember(Base):+ """Membership of one principal in one pushed group."""++ __tablename__ = "aisoc_scim_group_members"++ group_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("aisoc_scim_groups.id", ondelete="CASCADE"), primary_key=True)+ user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)+ added_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))+++__all__ = ["ScimGroup", "ScimGroupMember", "ScimToken", "ScimUser"]diff --git a/services/api/app/models/tenant.py b/services/api/app/models/tenant.pyindex 1cb118588..7ed459f79 100644--- a/services/api/app/models/tenant.py+++ b/services/api/app/models/tenant.py@@ -48,6 +48,12 @@ class User(Base):is_active: Mapped[bool] = mapped_column(Boolean, default=True)is_verified: Mapped[bool] = mapped_column(Boolean, default=False)last_login: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ # Access and refresh tokens issued at or before this instant are refused+ # (migration 071). Deactivating already stops a session, because the+ # request path re-reads `is_active`; this is what makes the revocation+ # survive a later re-activation, when tokens minted before it are still+ # inside their expiry window.+ sessions_revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)preferences: Mapped[dict] = mapped_column(JSONB, default=dict)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))updated_at: Mapped[datetime] = mapped_column(diff --git a/services/api/app/services/scim/__init__.py b/services/api/app/services/scim/__init__.pynew file mode 100644index 000000000..8f28dc3e9--- /dev/null+++ b/services/api/app/services/scim/__init__.py@@ -0,0 +1,50 @@+"""SCIM 2.0 provisioning (RFC 7643, RFC 7644).++Split by concern on purpose:++``patch``+ Normalises the PATCH bodies identity providers send, which differ from+ each other in five documented ways.+``filters``+ Parses the one filter shape provisioning sends, and refuses the rest+ rather than widening a result set.+``resources``+ SCIM representation and the discovery documents.+``roles``+ Maps directory groups onto the roles this platform enforces.+``tokens``+ Mints, verifies and rotates the bearer credential.+``provisioning``+ Applies operations to ``users`` and ``api_keys``, including the+ deprovisioning path that has to actually end access.+"""++from app.services.scim.filters import EqualityFilter, ScimFilterError, parse_equality+from app.services.scim.patch import ScimPatchError, ScimPatchOp, coerce_bool, member_ids, parse_patch+from app.services.scim.provisioning import DeactivationResult, deactivate_user, reactivate_user, recompute_role+from app.services.scim.roles import DEFAULT_PROVISIONED_ROLE, effective_role, resolve_role, validate_vocabulary+from app.services.scim.tokens import ScimAuthError, ScimPrincipal, mint_token, rotate_token, verify_token++__all__ = [+ "DEFAULT_PROVISIONED_ROLE",+ "DeactivationResult",+ "EqualityFilter",+ "ScimAuthError",+ "ScimFilterError",+ "ScimPatchError",+ "ScimPatchOp",+ "ScimPrincipal",+ "coerce_bool",+ "deactivate_user",+ "effective_role",+ "member_ids",+ "mint_token",+ "parse_equality",+ "parse_patch",+ "reactivate_user",+ "recompute_role",+ "resolve_role",+ "rotate_token",+ "validate_vocabulary",+ "verify_token",+]diff --git a/services/api/app/services/scim/filters.py b/services/api/app/services/scim/filters.pynew file mode 100644index 000000000..af63d3d8d--- /dev/null+++ b/services/api/app/services/scim/filters.py@@ -0,0 +1,99 @@+"""The narrow slice of SCIM filter syntax provisioning actually sends.++RFC 7644 section 3.4.2.2 defines a filter grammar with logical operators,+grouping, and a dozen comparators. Identity provider *provisioning* uses one+shape of it: an equality test on a single attribute, sent before a create to+find out whether the resource already exists.++Implementing the whole grammar would mean writing a parser whose untested+branches are reachable from an unauthenticated-adjacent surface. Implementing+a substring match instead of a grammar would mean ``userName eq "[email protected]"``+quietly matching ``userName eq "[email protected]"``. So this parses exactly the+supported shape and *refuses* everything else, which an identity provider+handles: an unsupported filter is a documented SCIM error, and a provider+that receives it falls back to listing.++The failure this avoids is the one where an unparsed filter is dropped and+the endpoint returns every user in the tenant. A provider reading that+concludes the user it was about to create already exists, or worse, picks the+first result and updates the wrong principal.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Final++#: ``attribute eq "value"``, tolerating either quote style and extra spaces.+#: Anchored at both ends, so a filter with a trailing ``and ...`` does not+#: match a prefix of itself and lose the second condition.+_EQ = re.compile(+ r"""^\s*(?P<attr>[A-Za-z][A-Za-z0-9_.:]*)\s+eq\s+["'](?P<value>[^"']*)["']\s*$""",+ re.IGNORECASE,+)++#: Attributes a caller may filter on, mapped to the canonical name handlers+#: switch on. Keyed case-folded because SCIM attribute names are+#: case-insensitive and providers exercise that.+USER_FILTER_ATTRS: Final[dict[str, str]] = {+ "username": "username",+ "externalid": "external_id",+ "emails.value": "username",+ 'emails[type eq "work"].value': "username",+ "id": "id",+}++GROUP_FILTER_ATTRS: Final[dict[str, str]] = {+ "displayname": "display_name",+ "externalid": "external_id",+ "id": "id",+}+++class ScimFilterError(ValueError):+ """A filter outside the supported shape."""++ def __init__(self, detail: str) -> None:+ super().__init__(detail)+ self.detail = detail+ self.scim_type = "invalidFilter"+++@dataclass(frozen=True)+class EqualityFilter:+ """``attribute eq "value"``, with the attribute already canonicalised."""++ attribute: str+ value: str+++def parse_equality(raw: str | None, allowed: dict[str, str]) -> EqualityFilter | None:+ """Parse a filter, or return ``None`` when none was supplied.++ Raises :class:`ScimFilterError` for a filter that is present and+ unsupported. Returning ``None`` for those would silently widen the+ result set to every row in the tenant.+ """+ if raw is None:+ return None+ stripped = raw.strip()+ if not stripped:+ return None++ match = _EQ.match(stripped)+ if match is None:+ raise ScimFilterError(f"unsupported filter {raw!r}; this service implements a single 'attribute eq \"value\"' comparison")++ attribute = match.group("attr").casefold()+ # A schema-qualified attribute name: everything before the last colon is+ # the URN. Split from the right because the URN itself contains colons.+ if attribute.startswith("urn:"):+ _, _, tail = attribute.rpartition(":")+ attribute = tail or attribute++ canonical = allowed.get(attribute)+ if canonical is None:+ raise ScimFilterError(f"filtering on {match.group('attr')!r} is not supported; supported: {sorted(allowed)}")++ return EqualityFilter(attribute=canonical, value=match.group("value"))diff --git a/services/api/app/services/scim/patch.py b/services/api/app/services/scim/patch.pynew file mode 100644index 000000000..5c7373da6--- /dev/null+++ b/services/api/app/services/scim/patch.py@@ -0,0 +1,281 @@+"""Normalising a SCIM PATCH request, which is where providers disagree.++RFC 7644 section 3.5.2 describes PATCH in terms that two conforming clients+read differently, and the two clients this platform has to serve read them+differently in five separate places. A handler written against one provider's+payloads fails against the other's in ways that look like a logic bug rather+than a parsing one, because the request is accepted, the operation is applied+to nothing, and the provider is told 204.++The five disagreements, each of which this module resolves+----------------------------------------------------------++1. ``op`` casing. RFC 7644 spells the values lowercase. One provider sends+ ``"replace"``; the other sends ``"Replace"``. Compared literally, half the+ operations fall through whatever ``if`` the handler wrote.++2. A missing ``path``. ``path`` is optional, and when it is absent ``value``+ is an object whose keys are the attributes to change:+ ``{"op": "replace", "value": {"active": false}}``. A handler that reads+ ``op["path"]`` raises ``KeyError`` on one provider and works on the other.++3. ``value`` typed as a string. A deactivation arrives as boolean ``false``+ from one provider and as the *string* ``"False"`` from the other. Python+ evaluates ``bool("False")`` as ``True``, so the naive read does not merely+ fail, it deactivates nothing while reporting success, which is the worst+ available outcome for the one operation that has to work.++4. Member removal expressed two ways. Either a filter in the path,+ ``members[value eq "abc"]`` with no ``value``, or ``path: "members"`` with+ a list of member objects to remove. Both providers emit both shapes+ depending on version and on whether the group is being emptied.++5. Attribute-name casing generally. ``userName``, ``username`` and+ ``UserName`` all appear across providers and versions; SCIM declares+ attribute names case-insensitive and clients take that at their word.++What this module deliberately does not do+------------------------------------------+It does not apply anything. It turns a request body into a list of+:class:`ScimPatchOp` with a resolved attribute, an optional member filter and+a coerced value, and the caller decides what those mean for its resource.+Parsing and applying were one function in the first draft, and the tests for+it could not distinguish "we misread the payload" from "we misapplied it".+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any++#: The PATCH request envelope every provider sends.+PATCH_OP_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:PatchOp"++#: Operations RFC 7644 defines. Compared case-folded, never literally.+VALID_OPS = frozenset({"add", "remove", "replace"})++#: ``members[value eq "abc"]`` and its single-quoted and unspaced variants.+_MEMBER_FILTER = re.compile(+ r"""^members\[\s*value\s+eq\s+["'](?P<id>[^"']+)["']\s*\]$""",+ re.IGNORECASE,+)++#: Strings a provider may send where the attribute is a boolean. Anything+#: outside this set raises rather than defaulting, because the failure this+#: exists to prevent is a deactivation silently read as an activation.+_TRUE_STRINGS = frozenset({"true", "t", "1", "yes"})+_FALSE_STRINGS = frozenset({"false", "f", "0", "no"})+++class ScimPatchError(ValueError):+ """A PATCH body that cannot be honoured.++ Carries the SCIM ``scimType`` the caller should return, so the error+ response is a SCIM error rather than a generic 400.+ """++ def __init__(self, detail: str, *, scim_type: str = "invalidSyntax") -> None:+ super().__init__(detail)+ self.detail = detail+ self.scim_type = scim_type+++@dataclass(frozen=True)+class ScimPatchOp:+ """One normalised operation.++ ``attribute`` is lowercased, and is the last segment of a sub-attribute+ path: ``name.givenName`` resolves to ``attribute="name.givenname"`` so a+ caller can match on the whole path. ``member_id`` is set only for the+ filtered member-removal shape, where the id lives in the path rather+ than in the value.+ """++ op: str+ attribute: str | None+ value: Any+ member_id: str | None = None+++def coerce_bool(raw: Any, *, attribute: str) -> bool:+ """Read a SCIM boolean that may have arrived as a string.++ Refuses anything it does not recognise instead of falling back. A+ fallback here would mean a payload the provider considered a+ deactivation being applied as something else, and the caller would have+ no way to tell that happened.+ """+ if isinstance(raw, bool):+ return raw+ if isinstance(raw, str):+ folded = raw.strip().casefold()+ if folded in _TRUE_STRINGS:+ return True+ if folded in _FALSE_STRINGS:+ return False+ raise ScimPatchError(+ f"attribute {attribute!r} expects a boolean; received {raw!r}",+ scim_type="invalidValue",+ )+++def _normalise_path(path: Any) -> tuple[str | None, str | None]:+ """Return ``(attribute, member_id)`` for one ``path`` value."""+ if path is None:+ return None, None+ if not isinstance(path, str):+ raise ScimPatchError(f"PATCH path must be a string; received {path!r}")++ stripped = path.strip()+ if not stripped:+ return None, None++ filtered = _MEMBER_FILTER.match(stripped)+ if filtered is not None:+ return "members", filtered.group("id")++ # A path may be schema-qualified:+ # `urn:ietf:params:scim:schemas:core:2.0:User:active`. Everything up to+ # the last colon is the schema URN, and the URN itself contains colons,+ # so this splits from the right rather than parsing the URN.+ if stripped.lower().startswith("urn:"):+ _, _, tail = stripped.rpartition(":")+ stripped = tail or stripped++ if "[" in stripped:+ # A filter this module does not implement. Refusing is correct:+ # applying the unfiltered attribute would act on more than the+ # provider asked for, and on `members` that means removing every+ # member when one was named.+ raise ScimPatchError(+ f"unsupported PATCH path filter {path!r}",+ scim_type="invalidPath",+ )++ return stripped.casefold(), None+++def _expand_valueless_op(op: str, value: Any) -> list[ScimPatchOp]:+ """Turn a pathless operation into one operation per attribute.++ ``{"op": "replace", "value": {"active": false, "userName": "a@b"}}``+ becomes two operations, so the caller sees the same shape it would have+ seen from a provider that sends an explicit path for each.+ """+ if not isinstance(value, dict):+ raise ScimPatchError(+ f"a {op!r} operation with no path must carry an object value; received {type(value).__name__}",+ )+ expanded: list[ScimPatchOp] = []+ for attribute, attribute_value in value.items():+ if not isinstance(attribute, str):+ raise ScimPatchError("PATCH attribute names must be strings")+ expanded.append(ScimPatchOp(op=op, attribute=attribute.casefold(), value=attribute_value))+ return expanded+++def parse_patch(body: Any) -> list[ScimPatchOp]:+ """Normalise a SCIM PATCH body into operations this codebase can apply.++ Raises :class:`ScimPatchError` for anything malformed. It never returns+ an empty list for a well-formed request with operations in it, because+ "parsed nothing" and "there was nothing to do" would otherwise be the+ same answer.+ """+ if not isinstance(body, dict):+ raise ScimPatchError("PATCH body must be a JSON object")++ schemas = body.get("schemas")+ if isinstance(schemas, list) and schemas:+ # Compared case-insensitively: the URN is spelled with different+ # casing by different providers and RFC 7643 treats it as a URI.+ if not any(isinstance(s, str) and s.casefold() == PATCH_OP_SCHEMA.casefold() for s in schemas):+ raise ScimPatchError(+ f"PATCH body must declare the {PATCH_OP_SCHEMA} schema",+ scim_type="invalidSyntax",+ )++ # `Operations` is the RFC spelling and the one both providers send, but+ # the attribute is case-insensitive like every other SCIM attribute.+ operations = None+ for key, candidate in body.items():+ if isinstance(key, str) and key.casefold() == "operations":+ operations = candidate+ break++ if not isinstance(operations, list) or not operations:+ raise ScimPatchError("PATCH body must carry a non-empty Operations array")++ parsed: list[ScimPatchOp] = []+ for entry in operations:+ if not isinstance(entry, dict):+ raise ScimPatchError("each PATCH operation must be an object")++ raw_op = None+ raw_path: Any = None+ has_value = False+ raw_value: Any = None+ for key, candidate in entry.items():+ if not isinstance(key, str):+ continue+ folded = key.casefold()+ if folded == "op":+ raw_op = candidate+ elif folded == "path":+ raw_path = candidate+ elif folded == "value":+ has_value = True+ raw_value = candidate++ if not isinstance(raw_op, str):+ raise ScimPatchError("each PATCH operation must carry an 'op'")+ op = raw_op.strip().casefold()+ if op not in VALID_OPS:+ raise ScimPatchError(+ f"unsupported PATCH op {raw_op!r}; expected one of {sorted(VALID_OPS)}",+ scim_type="invalidSyntax",+ )++ attribute, member_id = _normalise_path(raw_path)++ if attribute is None:+ if op == "remove":+ # RFC 7644: "remove" requires a target. Without one the+ # request is asking to delete the resource through a PATCH,+ # which DELETE already expresses.+ raise ScimPatchError("a 'remove' operation requires a path", scim_type="noTarget")+ if not has_value:+ raise ScimPatchError(f"a pathless {op!r} operation requires a value")+ parsed.extend(_expand_valueless_op(op, raw_value))+ continue++ parsed.append(ScimPatchOp(op=op, attribute=attribute, value=raw_value if has_value else None, member_id=member_id))++ return parsed+++def member_ids(op: ScimPatchOp) -> list[str]:+ """Every member id one ``members`` operation names.++ Covers the filtered path form, a list of member objects, a single member+ object and a bare string, because all four reach this platform from one+ provider or the other.+ """+ if op.member_id is not None:+ return [op.member_id]++ def _one(candidate: Any) -> str | None:+ if isinstance(candidate, str):+ return candidate or None+ if isinstance(candidate, dict):+ for key, value in candidate.items():+ if isinstance(key, str) and key.casefold() == "value" and isinstance(value, str) and value:+ return value+ return None++ raw = op.value+ if raw is None:+ return []+ candidates = raw if isinstance(raw, list) else [raw]+ return [found for found in (_one(entry) for entry in candidates) if found is not None]diff --git a/services/api/app/services/scim/provisioning.py b/services/api/app/services/scim/provisioning.pynew file mode 100644index 000000000..397f14cde--- /dev/null+++ b/services/api/app/services/scim/provisioning.py@@ -0,0 +1,149 @@+"""Applying SCIM operations to the principals this platform already has.++Everything here writes to tables that existed before SCIM did: ``users``,+``api_keys`` and the RBAC role a request is actually checked against. SCIM+owns no parallel copy of a principal, because two stores of "who may sign in"+drift, and the one an attacker finds is whichever the request path reads.++Deprovisioning, which is the operation that has to be real+-----------------------------------------------------------+:func:`deactivate_user` does three things, and the second and third are the+ones that make it more than a flag:++1. ``users.is_active = False``. The request path re-reads this column on+ every authenticated call, so an in-flight session stops at the next+ request rather than at the next token expiry.+2. ``users.sessions_revoked_at = now``. Without it, re-activating the+ principal resurrects every access token minted before the deactivation+ that is still inside its expiry window. Tokens carry ``iat``; a token+ issued at or before this instant is refused whatever the flag says.+3. Every ``api_keys`` row the principal owns is deactivated. An API key is a+ credential that outlives sessions entirely and is not reached by either+ of the first two steps, so a deprovisioned user who had minted one would+ otherwise keep full programmatic access indefinitely.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass+from datetime import UTC, datetime++from sqlalchemy import func, select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.scim import ScimGroup, ScimGroupMember, ScimUser+from app.models.tenant import ApiKey, User+from app.services.scim.roles import DEFAULT_PROVISIONED_ROLE, effective_role+++@dataclass(frozen=True)+class DeactivationResult:+ """What ending one principal's access actually ended.++ Counts rather than a boolean, so an audit record and a test can both+ assert on the work done instead of on the call having been made.+ """++ already_inactive: bool+ api_keys_revoked: int+ sessions_revoked_at: datetime+++async def deactivate_user(db: AsyncSession, user: User, *, now: datetime | None = None) -> DeactivationResult:+ """End a principal's access: sessions, future tokens and API keys."""+ moment = now or datetime.now(UTC)+ already_inactive = not user.is_active++ user.is_active = False+ user.sessions_revoked_at = moment++ revoked = await db.execute(+ update(ApiKey)+ .where(ApiKey.user_id == user.id, ApiKey.tenant_id == user.tenant_id, ApiKey.is_active.is_(True))+ .values(is_active=False)+ )++ return DeactivationResult(+ already_inactive=already_inactive,+ api_keys_revoked=int(revoked.rowcount or 0),+ sessions_revoked_at=moment,+ )+++async def reactivate_user(db: AsyncSession, user: User) -> None:+ """Restore sign-in for a principal an identity provider re-enabled.++ Deliberately does not restore API keys. They were revoked individually+ and a key a person cannot see was revoked is a key they will not rotate;+ re-minting is an explicit act with a fresh secret.++ ``sessions_revoked_at`` is left where it is, so tokens from before the+ deactivation stay dead.+ """+ user.is_active = True+++async def recompute_role(db: AsyncSession, user: User) -> str:+ """Set ``users.role`` from the principal's mapped group memberships.++ This is the column ``CurrentUser.require_permission`` reads, so writing+ it is what makes a group membership mean anything. A principal in no+ mapped group lands on the least-privilege default rather than keeping+ the authority a group used to confer.+ """+ result = await db.execute(+ select(ScimGroup.mapped_role)+ .join(ScimGroupMember, ScimGroupMember.group_id == ScimGroup.id)+ .where(+ ScimGroupMember.user_id == user.id,+ ScimGroupMember.tenant_id == user.tenant_id,+ ScimGroup.tenant_id == user.tenant_id,+ )+ )+ resolved = effective_role([row[0] for row in result.all()])+ user.role = resolved+ return resolved+++async def recompute_roles_for_group(db: AsyncSession, group: ScimGroup) -> dict[uuid.UUID, str]:+ """Recompute every current member's role after a group changed.++ Used when a group's own mapping changes, where the members are unchanged+ but what their membership confers is not.+ """+ members = await db.execute(+ select(User)+ .join(ScimGroupMember, ScimGroupMember.user_id == User.id)+ .where(+ ScimGroupMember.group_id == group.id,+ ScimGroupMember.tenant_id == group.tenant_id,+ User.tenant_id == group.tenant_id,+ )+ )+ return {user.id: await recompute_role(db, user) for user in members.scalars().all()}+++async def find_user_by_username(db: AsyncSession, tenant_id: uuid.UUID, username: str) -> User | None:+ """Locate a principal by SCIM ``userName``, which this platform maps to email.++ Compared case-insensitively. Identity providers do not guarantee the+ casing of an address is stable between syncs, and a second principal+ created because one sync sent ``[email protected]`` and the next sent ``[email protected]``+ is a duplicate account with its own permissions.+ """+ result = await db.execute(select(User).where(User.tenant_id == tenant_id, func.lower(User.email) == username.strip().casefold()))+ return result.scalar_one_or_none()+++async def find_user_by_external_id(db: AsyncSession, tenant_id: uuid.UUID, external_id: str) -> User | None:+ """Locate a principal by the identity provider's own identifier."""+ result = await db.execute(+ select(User).join(ScimUser, ScimUser.user_id == User.id).where(ScimUser.tenant_id == tenant_id, ScimUser.external_id == external_id)+ )+ return result.scalar_one_or_none()+++def default_role() -> str:+ """The role a principal holds before any group confers one."""+ return DEFAULT_PROVISIONED_ROLEdiff --git a/services/api/app/services/scim/resources.py b/services/api/app/services/scim/resources.pynew file mode 100644index 000000000..d792e8118--- /dev/null+++ b/services/api/app/services/scim/resources.py@@ -0,0 +1,299 @@+"""SCIM resource representation and the discovery documents (RFC 7643).++``ServiceProviderConfig``, ``ResourceTypes`` and ``Schemas`` are not+decoration. An identity provider reads them during setup to decide which+operations to attempt, and one that advertises a capability it does not+implement gets configured to use it. Everything declared here is+cross-checked against the implemented routes by+``scripts/check_scim_contract.py``, so this file cannot claim PATCH support+the router does not offer.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from typing import Any, Final++USER_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:User"+GROUP_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:Group"+LIST_RESPONSE_SCHEMA: Final[str] = "urn:ietf:params:scim:api:messages:2.0:ListResponse"+ERROR_SCHEMA: Final[str] = "urn:ietf:params:scim:api:messages:2.0:Error"+SERVICE_PROVIDER_CONFIG_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"+RESOURCE_TYPE_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:ResourceType"+SCHEMA_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:Schema"++#: The base path the router is mounted at. Referenced by the discovery+#: documents, which must give an identity provider a location it can fetch.+SCIM_BASE: Final[str] = "/scim/v2"++#: The SCIM content type. Providers send it and expect it back; some reject a+#: response labelled ``application/json``.+SCIM_CONTENT_TYPE: Final[str] = "application/scim+json"+++def _stamp(value: datetime | None) -> str | None:+ if value is None:+ return None+ return value.astimezone(UTC).isoformat().replace("+00:00", "Z")+++def user_resource(+ *,+ user_id: uuid.UUID,+ user_name: str,+ active: bool,+ external_id: str | None,+ given_name: str | None,+ family_name: str | None,+ created_at: datetime | None,+ updated_at: datetime | None,+ groups: list[tuple[uuid.UUID, str]] | None = None,+) -> dict[str, Any]:+ """One SCIM User.++ ``id`` is this platform's user UUID, so a provider's stored link survives+ a rename of every other attribute.+ """+ name: dict[str, Any] = {}+ if given_name:+ name["givenName"] = given_name+ if family_name:+ name["familyName"] = family_name+ if name:+ formatted = " ".join(part for part in (given_name, family_name) if part)+ if formatted:+ name["formatted"] = formatted++ resource: dict[str, Any] = {+ "schemas": [USER_SCHEMA],+ "id": str(user_id),+ "userName": user_name,+ "active": active,+ "emails": [{"value": user_name, "primary": True, "type": "work"}],+ "meta": {+ "resourceType": "User",+ "created": _stamp(created_at),+ "lastModified": _stamp(updated_at or created_at),+ "location": f"{SCIM_BASE}/Users/{user_id}",+ },+ }+ if external_id:+ resource["externalId"] = external_id+ if name:+ resource["name"] = name+ if groups:+ resource["groups"] = [+ {"value": str(group_id), "display": display, "$ref": f"{SCIM_BASE}/Groups/{group_id}"} for group_id, display in groups+ ]+ return resource+++def group_resource(+ *,+ group_id: uuid.UUID,+ display_name: str,+ external_id: str | None,+ mapped_role: str | None,+ created_at: datetime | None,+ updated_at: datetime | None,+ members: list[tuple[uuid.UUID, str]] | None = None,+) -> dict[str, Any]:+ """One SCIM Group.++ ``mapped_role`` is surfaced under this platform's own extension URN+ rather than smuggled into a core attribute. An administrator debugging+ "why did this group not grant anything" can read the answer out of the+ same response their identity provider sees, and a ``null`` there is the+ honest representation of a group that confers nothing.+ """+ resource: dict[str, Any] = {+ "schemas": [GROUP_SCHEMA, AISOC_GROUP_EXTENSION],+ "id": str(group_id),+ "displayName": display_name,+ "members": [+ {"value": str(member_id), "display": display, "$ref": f"{SCIM_BASE}/Users/{member_id}"}+ for member_id, display in (members or [])+ ],+ AISOC_GROUP_EXTENSION: {"mappedRole": mapped_role},+ "meta": {+ "resourceType": "Group",+ "created": _stamp(created_at),+ "lastModified": _stamp(updated_at or created_at),+ "location": f"{SCIM_BASE}/Groups/{group_id}",+ },+ }+ if external_id:+ resource["externalId"] = external_id+ return resource+++#: This platform's Group extension. Namespaced under our own URN so it can+#: never collide with a core attribute a future RFC revision adds.+AISOC_GROUP_EXTENSION: Final[str] = "urn:aisoc:params:scim:schemas:extension:2.0:Group"+++def list_response(resources: list[dict[str, Any]], *, total: int, start_index: int, count: int) -> dict[str, Any]:+ """A SCIM ListResponse.++ ``totalResults`` is the size of the whole match, not of this page.+ Providers page on it, and returning the page size instead makes a sync+ stop after the first page while reporting success.+ """+ return {+ "schemas": [LIST_RESPONSE_SCHEMA],+ "totalResults": total,+ "itemsPerPage": len(resources),+ "startIndex": start_index,+ "Resources": resources,+ }+++def error_response(status: int, detail: str, *, scim_type: str | None = None) -> dict[str, Any]:+ """A SCIM Error. ``status`` is a string per RFC 7644 section 3.12."""+ body: dict[str, Any] = {"schemas": [ERROR_SCHEMA], "status": str(status), "detail": detail}+ if scim_type:+ body["scimType"] = scim_type+ return body+++def service_provider_config() -> dict[str, Any]:+ """What this implementation actually supports.++ Every ``supported: false`` below is a deliberate answer rather than an+ omission. Advertising bulk or sort would have an identity provider+ configure itself to use them.+ """+ return {+ "schemas": [SERVICE_PROVIDER_CONFIG_SCHEMA],+ "documentationUri": "https://beenuar.github.io/AiSOC/docs/operations/scim",+ "patch": {"supported": True},+ # Bulk is not implemented. Neither provider requires it, and a+ # half-implemented bulk endpoint applies some operations and reports+ # on all of them.+ "bulk": {"supported": False, "maxOperations": 0, "maxPayloadSize": 0},+ "filter": {"supported": True, "maxResults": MAX_PAGE_SIZE},+ "changePassword": {"supported": False},+ # Sorting is not implemented; results are ordered by creation time so+ # paging is stable, which is the property paging actually needs.+ "sort": {"supported": False},+ "etag": {"supported": False},+ "authenticationSchemes": [+ {+ "type": "oauthbearertoken",+ "name": "OAuth Bearer Token",+ "description": "A per-organisation bearer token, hashed at rest and rotatable with an overlap window.",+ "specUri": "https://www.rfc-editor.org/rfc/rfc6750",+ "primary": True,+ }+ ],+ "meta": {"resourceType": "ServiceProviderConfig", "location": f"{SCIM_BASE}/ServiceProviderConfig"},+ }+++#: Largest page a caller may request. A provider that asks for more gets this+#: many with an honest ``itemsPerPage``, rather than an error it would+#: surface to an administrator as a failed sync.+MAX_PAGE_SIZE: Final[int] = 200++#: Default page size when a provider does not ask for one.+DEFAULT_PAGE_SIZE: Final[int] = 100+++def resource_types() -> list[dict[str, Any]]:+ return [+ {+ "schemas": [RESOURCE_TYPE_SCHEMA],+ "id": "User",+ "name": "User",+ "endpoint": "/Users",+ "description": "A principal that can sign in to this tenant.",+ "schema": USER_SCHEMA,+ "schemaExtensions": [],+ "meta": {"resourceType": "ResourceType", "location": f"{SCIM_BASE}/ResourceTypes/User"},+ },+ {+ "schemas": [RESOURCE_TYPE_SCHEMA],+ "id": "Group",+ "name": "Group",+ "endpoint": "/Groups",+ "description": "A directory group. Confers the platform role it maps to, or nothing.",+ "schema": GROUP_SCHEMA,+ "schemaExtensions": [{"schema": AISOC_GROUP_EXTENSION, "required": False}],+ "meta": {"resourceType": "ResourceType", "location": f"{SCIM_BASE}/ResourceTypes/Group"},+ },+ ]+++def _attribute(+ name: str,+ attr_type: str = "string",+ *,+ required: bool = False,+ multi: bool = False,+ mutability: str = "readWrite",+ case_exact: bool = False,+) -> dict[str, Any]:+ return {+ "name": name,+ "type": attr_type,+ "multiValued": multi,+ "required": required,+ "caseExact": case_exact,+ "mutability": mutability,+ "returned": "default",+ "uniqueness": "none",+ }+++def schemas() -> list[dict[str, Any]]:+ """The attribute definitions for the two resource types served here."""+ return [+ {+ "schemas": [SCHEMA_SCHEMA],+ "id": USER_SCHEMA,+ "name": "User",+ "description": "SCIM core User, as implemented by this platform.",+ "attributes": [+ _attribute("userName", required=True),+ _attribute("externalId"),+ _attribute("active", "boolean"),+ {+ **_attribute("name", "complex"),+ "subAttributes": [_attribute("givenName"), _attribute("familyName"), _attribute("formatted")],+ },+ {+ **_attribute("emails", "complex", multi=True),+ "subAttributes": [_attribute("value"), _attribute("primary", "boolean"), _attribute("type")],+ },+ {+ **_attribute("groups", "complex", multi=True, mutability="readOnly"),+ "subAttributes": [_attribute("value"), _attribute("display")],+ },+ ],+ "meta": {"resourceType": "Schema", "location": f"{SCIM_BASE}/Schemas/{USER_SCHEMA}"},+ },+ {+ "schemas": [SCHEMA_SCHEMA],+ "id": GROUP_SCHEMA,+ "name": "Group",+ "description": "SCIM core Group, as implemented by this platform.",+ "attributes": [+ _attribute("displayName", required=True),+ _attribute("externalId"),+ {+ **_attribute("members", "complex", multi=True),+ "subAttributes": [_attribute("value"), _attribute("display")],+ },+ ],+ "meta": {"resourceType": "Schema", "location": f"{SCIM_BASE}/Schemas/{GROUP_SCHEMA}"},+ },+ {+ "schemas": [SCHEMA_SCHEMA],+ "id": AISOC_GROUP_EXTENSION,+ "name": "AiSOCGroupExtension",+ "description": "The platform role a group confers, or null when it confers nothing.",+ "attributes": [_attribute("mappedRole", mutability="readOnly")],+ "meta": {"resourceType": "Schema", "location": f"{SCIM_BASE}/Schemas/{AISOC_GROUP_EXTENSION}"},+ },+ ]diff --git a/services/api/app/services/scim/roles.py b/services/api/app/services/scim/roles.pynew file mode 100644index 000000000..095eab91b--- /dev/null+++ b/services/api/app/services/scim/roles.py@@ -0,0 +1,199 @@+"""Mapping directory groups onto the roles this platform actually enforces.++Where the enforced vocabulary lives+------------------------------------+``services/api/app/core/security.py`` declares ``ROLE_PERMISSIONS``, and+``CurrentUser.require_permission`` reads it through ``has_permission(role, …)``+on every guarded request. That map is the role vocabulary. A role outside it+is a string in a column: it grants nothing, and worse, it *reads* in a console+as though it grants something.++So a pushed group resolves to one of those keys or to nothing at all.+``check_scim_contract.py`` compares this module against that map in both+directions, so a role renamed there cannot leave a mapping here pointing at a+role that no longer exists.++Why an unrecognised group confers nothing+------------------------------------------+An identity provider pushes whatever the administrator selected, named+however that directory names things. The tempting default is to create a role+per pushed group, which manufactures roles nobody granted permissions to. The+default here is the opposite: a group whose name does not resolve is recorded,+audited and powerless. Unrecognised means no privilege rather than unknown+privilege.++Why precedence is explicit+---------------------------+A principal is routinely in several groups, and ``users.role`` is a single+column. Picking "the most recently added" would make a user's authority+depend on the order an identity provider happened to sync, which changes+between runs. :data:`ROLE_PRECEDENCE` is a total order, so the same set of+groups always produces the same role.+"""++from __future__ import annotations++import re+from typing import Final++from app.core.security import ROLE_PERMISSIONS++#: The role a provisioned principal holds before any group confers one.+#: Least privilege: a user created by an IdP push but placed in no mapped+#: group can sign in and read, and can do nothing else.+DEFAULT_PROVISIONED_ROLE: Final[str] = "viewer"++#: Total order, least authority first. A principal's role is the last entry+#: in this list that any of their mapped groups confers.+#:+#: ``admin`` and ``platform_admin`` are both in ``ROLE_PERMISSIONS`` with+#: ``["*"]`` and are deliberately **not** reachable from a directory group:+#: see :data:`UNREACHABLE_BY_GROUP`.+ROLE_PRECEDENCE: Final[tuple[str, ...]] = (+ "viewer",+ "soc_analyst",+ "threat_hunter",+ "soc_lead",+ "tenant_admin",+)++#: Roles no directory group may confer, with the reason.+#:+#: ``platform_admin`` and ``admin`` hold ``*`` across every tenant. Letting a+#: group name grant that would mean anyone who can create a group in the+#: customer's directory, which is a different and usually larger set of people+#: than the platform's administrators, could mint a platform administrator by+#: choosing a group name. ``api_service`` is the identity an API key resolves+#: to and is not a human role at all.+UNREACHABLE_BY_GROUP: Final[dict[str, str]] = {+ "platform_admin": "holds '*' across every tenant; a directory group name must not be able to mint one",+ "admin": "holds '*' across every tenant; a directory group name must not be able to mint one",+ "api_service": "the identity an API key resolves to, not a role a person can hold",+}++#: Group-name fragments that resolve to a role, most specific first.+#:+#: Matched against the group's display name reduced to lowercase words, so+#: ``AiSOC-SOC-Analysts``, ``aisoc soc analyst`` and ``SOC_Analysts`` all+#: reach the same role. Order matters: ``soc lead`` must be tested before+#: ``soc analyst`` would match a name containing both.+GROUP_NAME_RULES: Final[tuple[tuple[tuple[str, ...], str], ...]] = (+ (("tenant", "admin"), "tenant_admin"),+ (("soc", "lead"), "soc_lead"),+ (("soc", "manager"), "soc_lead"),+ (("incident", "commander"), "soc_lead"),+ (("threat", "hunter"), "threat_hunter"),+ (("threat", "hunting"), "threat_hunter"),+ (("hunter",), "threat_hunter"),+ (("soc", "analyst"), "soc_analyst"),+ (("triage",), "soc_analyst"),+ (("analyst",), "soc_analyst"),+ (("viewer",), "viewer"),+ (("read", "only"), "viewer"),+ (("auditor",), "viewer"),+)++_WORD = re.compile(r"[a-z0-9]+")+++def assignable_roles() -> tuple[str, ...]:+ """Roles a directory group may confer, least authority first."""+ return ROLE_PRECEDENCE+++def normalise_group_name(display_name: str) -> list[str]:+ """Reduce a group display name to lowercase word tokens."""+ return _WORD.findall(display_name.casefold())+++def _match_tokens(display_name: str) -> set[str]:+ """Tokens a rule may match against, including depluralised forms.++ Directory groups are named for the people in them, so they are almost+ always plural: ``AiSOC-SOC-Analysts``, ``Threat Hunters``,+ ``Tenant Admins``. Matching on the exact token would resolve+ ``soc analyst`` and leave the plural spelling every real directory uses+ conferring nothing, which fails in the safe direction but fails on+ nearly every real group.++ Both forms are kept rather than replaced, so a name that is genuinely+ singular still matches.+ """+ tokens = set()+ for word in normalise_group_name(display_name):+ tokens.add(word)+ if len(word) > 3 and word.endswith("es"):+ tokens.add(word[:-2])+ if len(word) > 2 and word.endswith("s"):+ tokens.add(word[:-1])+ return tokens+++def resolve_role(display_name: str) -> str | None:+ """The role a group name confers, or ``None`` when it confers nothing.++ Returning ``None`` is a normal outcome, not a failure. It means the+ group is recorded and membership is tracked while no privilege changes+ hands.+ """+ present = _match_tokens(display_name)+ if not present:+ return None+ for fragments, role in GROUP_NAME_RULES:+ if all(fragment in present for fragment in fragments):+ return role+ return None+++def effective_role(mapped_roles: list[str | None]) -> str:+ """The single role a principal holds, given every group they are in.++ Unmapped groups contribute nothing. A principal in no mapped group falls+ back to :data:`DEFAULT_PROVISIONED_ROLE` rather than keeping whatever+ role they had, because otherwise removing somebody from the one group+ that granted their authority would leave that authority in place, which+ is the failure a deprovisioning test is written to catch.+ """+ rank = {role: index for index, role in enumerate(ROLE_PRECEDENCE)}+ best = DEFAULT_PROVISIONED_ROLE+ best_rank = rank.get(DEFAULT_PROVISIONED_ROLE, 0)+ for role in mapped_roles:+ if role is None:+ continue+ candidate = rank.get(role)+ if candidate is not None and candidate > best_rank:+ best, best_rank = role, candidate+ return best+++def validate_vocabulary() -> list[str]:+ """Disagreements between this module and the enforced role map.++ Returned rather than raised so both the gate and a test can report every+ problem at once instead of the first one.+ """+ problems: list[str] = []+ enforced = set(ROLE_PERMISSIONS)++ for role in ROLE_PRECEDENCE:+ if role not in enforced:+ problems.append(f"ROLE_PRECEDENCE names {role!r}, which ROLE_PERMISSIONS does not define")+ if role in UNREACHABLE_BY_GROUP:+ problems.append(f"{role!r} is both assignable and listed as unreachable by group")++ for _fragments, role in GROUP_NAME_RULES:+ if role not in ROLE_PRECEDENCE:+ problems.append(f"GROUP_NAME_RULES maps to {role!r}, which is not in ROLE_PRECEDENCE")++ for role in UNREACHABLE_BY_GROUP:+ if role not in enforced:+ problems.append(f"UNREACHABLE_BY_GROUP names {role!r}, which ROLE_PERMISSIONS no longer defines")++ uncovered = enforced - set(ROLE_PRECEDENCE) - set(UNREACHABLE_BY_GROUP)+ for role in sorted(uncovered):+ problems.append(f"ROLE_PERMISSIONS defines {role!r} and this module neither makes it assignable nor records why it is not")++ if DEFAULT_PROVISIONED_ROLE not in ROLE_PRECEDENCE:+ problems.append(f"DEFAULT_PROVISIONED_ROLE {DEFAULT_PROVISIONED_ROLE!r} is not in ROLE_PRECEDENCE")++ return problemsdiff --git a/services/api/app/services/scim/tokens.py b/services/api/app/services/scim/tokens.pynew file mode 100644index 000000000..bb093f784--- /dev/null+++ b/services/api/app/services/scim/tokens.py@@ -0,0 +1,184 @@+"""Minting, verifying and rotating SCIM bearer credentials.++A SCIM token is the only credential in this tree that is long-lived,+unattended and held by a third party's software. Everything here follows from+that: the raw secret exists once, lookup is by digest, rotation overlaps+rather than cuts over, and verification answers with a reason the caller can+audit instead of a bare boolean.+"""++from __future__ import annotations++import hashlib+import secrets+import uuid+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Final++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.scim import ScimToken++#: Distinguishes a SCIM credential from an ``aisoc_`` API key at a glance, in+#: a log line and in the dependency that resolves it. The two are verified by+#: different code against different tables, and a support conversation that+#: starts by naming the wrong one costs an hour.+TOKEN_PREFIX: Final[str] = "aisoc_scim_"++#: 192 bits from ``secrets``. A digest is the right store for this and a+#: password KDF would not be: there is no low-entropy guess to slow down, and+#: a KDF on the request path would put a deliberate delay in front of every+#: call an identity provider makes on its sync schedule.+_TOKEN_BYTES: Final[int] = 24++#: How long a rotated-out credential keeps working by default. Long enough+#: for an administrator to paste the replacement into the identity provider,+#: short enough that a leaked secret is not indefinite.+DEFAULT_ROTATION_GRACE: Final[timedelta] = timedelta(hours=24)+++def hash_token(raw: str) -> str:+ """SHA-256 hex digest of a raw SCIM token."""+ return hashlib.sha256(raw.encode()).hexdigest()+++def generate_token() -> tuple[str, str, str]:+ """Return ``(raw, prefix, digest)`` for a fresh credential."""+ raw = f"{TOKEN_PREFIX}{secrets.token_hex(_TOKEN_BYTES)}"+ return raw, raw[: len(TOKEN_PREFIX) + 6], hash_token(raw)+++@dataclass(frozen=True)+class ScimPrincipal:+ """The authenticated identity behind a SCIM request.++ ``tenant_id`` comes from the token row. There is no request field that+ can influence it, which is the whole reason this type exists rather than+ the handlers reading a header.+ """++ token_id: uuid.UUID+ tenant_id: uuid.UUID+ org_id: uuid.UUID | None+ token_name: str+++class ScimAuthError(Exception):+ """A SCIM credential that will not authenticate, with a recordable reason.++ The reason is for the audit log and the server's own logs. What goes back+ to the caller is an undifferentiated 401: telling an unauthenticated+ client whether a secret was wrong, revoked or merely expired is telling it+ which secrets exist.+ """++ def __init__(self, reason: str) -> None:+ super().__init__(reason)+ self.reason = reason+++async def verify_token(db: AsyncSession, raw: str, *, now: datetime | None = None) -> ScimPrincipal:+ """Resolve a raw bearer token to its principal, or raise.++ Records ``last_used_at`` on success. That column is what makes an+ abandoned integration visible: a token nobody has used for months is a+ standing credential with no owner, and there is no other signal for it.+ """+ moment = now or datetime.now(UTC)++ if not raw or not raw.startswith(TOKEN_PREFIX):+ raise ScimAuthError("token does not carry the SCIM prefix")++ result = await db.execute(select(ScimToken).where(ScimToken.token_hash == hash_token(raw)))+ token = result.scalar_one_or_none()+ if token is None:+ raise ScimAuthError("no SCIM token matches that digest")++ if token.revoked_at is not None:+ raise ScimAuthError(f"token {token.token_prefix} was revoked at {token.revoked_at.isoformat()}")+ if token.expires_at is not None and token.expires_at <= moment:+ raise ScimAuthError(f"token {token.token_prefix} expired at {token.expires_at.isoformat()}")++ token.last_used_at = moment++ return ScimPrincipal(+ token_id=token.id,+ tenant_id=token.tenant_id,+ org_id=token.org_id,+ token_name=token.name,+ )+++async def mint_token(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ org_id: uuid.UUID | None,+ name: str,+ created_by: uuid.UUID | None,+ expires_at: datetime | None = None,+ rotated_from_id: uuid.UUID | None = None,+) -> tuple[ScimToken, str]:+ """Create a credential and return it with its raw secret.++ The raw secret is returned, never stored, and is the only time it exists+ outside the identity provider's configuration.+ """+ raw, prefix, digest = generate_token()+ token = ScimToken(+ tenant_id=tenant_id,+ org_id=org_id,+ name=name,+ token_prefix=prefix,+ token_hash=digest,+ created_by=created_by,+ expires_at=expires_at,+ rotated_from_id=rotated_from_id,+ )+ db.add(token)+ await db.flush()+ return token, raw+++async def rotate_token(+ db: AsyncSession,+ *,+ token: ScimToken,+ created_by: uuid.UUID | None,+ grace: timedelta | None = None,+ now: datetime | None = None,+) -> tuple[ScimToken, str]:+ """Mint a replacement and put the old credential on a clock.++ Both secrets authenticate until the grace window closes. A rotation that+ invalidated the old secret immediately would take the integration down+ for as long as it takes a person to copy the new one across, which is the+ reason rotation gets deferred and secrets get old.++ A grace of zero is honoured, for the case rotation is a response to a+ disclosure rather than hygiene.+ """+ moment = now or datetime.now(UTC)+ window = DEFAULT_ROTATION_GRACE if grace is None else grace++ replacement, raw = await mint_token(+ db,+ tenant_id=token.tenant_id,+ org_id=token.org_id,+ name=token.name,+ created_by=created_by,+ expires_at=token.expires_at,+ rotated_from_id=token.id,+ )++ if window <= timedelta(0):+ token.revoked_at = moment+ else:+ # Never extend: a token already expiring sooner than the grace window+ # keeps its earlier deadline.+ deadline = moment + window+ token.expires_at = deadline if token.expires_at is None else min(token.expires_at, deadline)++ return replacement, rawdiff --git a/services/api/migrations/071_scim_provisioning.sql b/services/api/migrations/071_scim_provisioning.sqlnew file mode 100644index 000000000..91a3e742e--- /dev/null+++ b/services/api/migrations/071_scim_provisioning.sql@@ -0,0 +1,242 @@+-- 071: SCIM 2.0 provisioning (RFC 7643 / RFC 7644).+--+-- Gap-closure Phase 13.1.+--+-- What this table set is, and why it is shaped defensively+-- --------------------------------------------------------+-- SCIM is a write surface into the identity system, operated by a third+-- party, reached with a long-lived bearer token that lives in somebody+-- else's configuration screen. Every other write path in this tree is+-- driven by a human holding a session; this one is driven by a machine+-- holding a secret, unattended, on a schedule. So the boundary is the+-- token, and the columns below exist to make that boundary auditable and+-- revocable rather than merely present.+--+-- Why the tenant is on the token+-- -------------------------------+-- `aisoc_scim_tokens.tenant_id` is NOT NULL, and it is the only place the+-- tenant of a SCIM request comes from. A SCIM client never names a tenant:+-- there is no field for it in RFC 7643, and adding one would make the+-- boundary a request parameter. One token addresses exactly one tenant.+--+-- `org_id` is nullable on purpose. A single-tenant deployment has no+-- operator organisation and must still be able to run SCIM; an MSSP sets it+-- so the white-label and usage-metering surfaces (13.2, 13.3) can join a+-- provisioning event to the organisation that caused it.+--+-- Why the secret is a hash and a prefix+-- --------------------------------------+-- The same convention `api_keys` already uses: a SHA-256 digest for lookup+-- and a short prefix for display. A token is 192 bits from `secrets`, so a+-- plain digest is right here and a password KDF would not be: there is no+-- low-entropy guess to slow down, and a KDF on the request path would put a+-- deliberate delay in front of every SCIM call an IdP makes.+--+-- Why rotation is two rows rather than an UPDATE+-- ----------------------------------------------+-- Rotating in place means the old secret stops working the instant the new+-- one is minted, and the administrator pasting it into the IdP is offline+-- for however long that takes. `rotated_from_id` plus an `expires_at` on the+-- superseded row gives an overlap window: both secrets work, the old one+-- expires by itself, and the audit log shows which token served which call.+-- An UPDATE would also destroy the evidence of what the previous secret was+-- used for, which is the thing an incident review asks about first.+--+-- Why deactivation is a timestamp on the user, not a row here+-- -----------------------------------------------------------+-- See `users.sessions_revoked_at` at the foot of this file. Deprovisioning+-- has to end access, and flipping `users.is_active` already does that for+-- sessions because the request path re-reads it. What it does not do is+-- survive re-activation: an access token minted before the deactivation is+-- still inside its expiry window and starts working again. The timestamp+-- closes that, and it lives on `users` because it is a property of the+-- principal rather than of the provisioning channel.++CREATE TABLE IF NOT EXISTS aisoc_scim_tokens (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- The operator organisation this token belongs to, when there is one.+ -- Nullable: a single-tenant deployment runs SCIM with no organisation.+ org_id UUID REFERENCES organizations(id) ON DELETE CASCADE,++ -- Administrator-facing label, so a tenant with two IdPs can tell which+ -- token is which without comparing prefixes.+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 200),++ -- First 12 characters of the raw secret, for display only.+ token_prefix TEXT NOT NULL,+ -- SHA-256 hex digest of the raw secret. Indexed because it is the+ -- lookup key on every SCIM request.+ token_hash TEXT NOT NULL UNIQUE,++ created_by UUID REFERENCES users(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ last_used_at TIMESTAMPTZ,+ -- Set on the superseded token when a rotation opens an overlap window,+ -- and settable at mint time for a token that should not outlive a pilot.+ expires_at TIMESTAMPTZ,+ revoked_at TIMESTAMPTZ,+ rotated_from_id UUID REFERENCES aisoc_scim_tokens(id) ON DELETE SET NULL+);++COMMENT ON TABLE aisoc_scim_tokens IS+ 'Per-organisation SCIM bearer tokens. The tenant of a SCIM request comes '+ 'from this row and from nowhere else: RFC 7643 has no tenant field and '+ 'adding one would make the boundary a request parameter.';+COMMENT ON COLUMN aisoc_scim_tokens.token_hash IS+ 'SHA-256 of the raw secret. The raw value is returned once at mint time '+ 'and is not recoverable from this table.';+COMMENT ON COLUMN aisoc_scim_tokens.rotated_from_id IS+ 'The token this one replaced. Both work until the old row expires, so an '+ 'administrator can paste the new secret into the IdP without an outage.';++CREATE INDEX IF NOT EXISTS idx_scim_tokens_tenant ON aisoc_scim_tokens (tenant_id);+CREATE INDEX IF NOT EXISTS idx_scim_tokens_org ON aisoc_scim_tokens (org_id);+++-- SCIM metadata for a provisioned principal.+--+-- A side table rather than columns on `users`, because `users` is read on+-- every authenticated request in the platform and SCIM has no business+-- widening that row. The join only happens on the SCIM surface itself.+CREATE TABLE IF NOT EXISTS aisoc_scim_users (+ user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- The IdP's own identifier. Okta and Entra both send it and both expect+ -- it echoed back; it is how a rename is distinguished from a new user.+ external_id TEXT,++ given_name TEXT,+ family_name TEXT,+ -- Which token provisioned this principal, for the audit trail.+ token_id UUID REFERENCES aisoc_scim_tokens(id) ON DELETE SET NULL,++ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- An external id identifies one principal within one tenant. Two tenants+ -- provisioned from two IdPs may legitimately collide on it.+ UNIQUE (tenant_id, external_id)+);++COMMENT ON TABLE aisoc_scim_users IS+ 'SCIM metadata for a provisioned principal, kept beside users rather than '+ 'in it so the row read on every authenticated request stays narrow.';++CREATE INDEX IF NOT EXISTS idx_scim_users_tenant ON aisoc_scim_users (tenant_id);+++-- A group pushed by the identity provider.+--+-- Why `mapped_role` is nullable, and why that is the safe default+-- ---------------------------------------------------------------+-- An IdP pushes whatever groups the administrator selected, named however+-- that directory names things. Creating a platform role per pushed group+-- would manufacture roles that grant nothing and read, in the console, as+-- though they grant something. Instead a group either resolves to one of+-- the roles this platform actually enforces, or it resolves to NULL and is+-- membership-only: recorded, audited, and granting no privilege at all.+-- Unrecognised therefore means powerless rather than unconstrained.+CREATE TABLE IF NOT EXISTS aisoc_scim_groups (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ display_name TEXT NOT NULL CHECK (length(display_name) BETWEEN 1 AND 300),+ external_id TEXT,++ -- One of the roles services/api/app/core/security.py ROLE_PERMISSIONS+ -- enforces, or NULL for a group that confers nothing. Not a foreign key:+ -- the role vocabulary is code, not a table, and check_scim_contract.py+ -- is what keeps this column and that map in agreement.+ mapped_role TEXT,++ token_id UUID REFERENCES aisoc_scim_tokens(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ UNIQUE (tenant_id, display_name),+ UNIQUE (tenant_id, external_id)+);++COMMENT ON COLUMN aisoc_scim_groups.mapped_role IS+ 'The enforced platform role this group confers, or NULL for a group that '+ 'confers nothing. NULL is the default for an unrecognised group name, so '+ 'an unmapped directory group grants no privilege rather than an unknown one.';++CREATE INDEX IF NOT EXISTS idx_scim_groups_tenant ON aisoc_scim_groups (tenant_id);+++CREATE TABLE IF NOT EXISTS aisoc_scim_group_members (+ group_id UUID NOT NULL REFERENCES aisoc_scim_groups(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ -- Denormalised so this table carries the same row-level-security shape+ -- as every other tenant-scoped table, rather than depending on a join to+ -- be filtered.+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ PRIMARY KEY (group_id, user_id)+);++CREATE INDEX IF NOT EXISTS idx_scim_group_members_tenant ON aisoc_scim_group_members (tenant_id);+CREATE INDEX IF NOT EXISTS idx_scim_group_members_user ON aisoc_scim_group_members (user_id);+++-- Session revocation, so deprovisioning ends access instead of marking it.+--+-- `get_current_user` re-reads `users.is_active` on every request, so+-- deactivating already stops a session in its tracks. It does not survive+-- re-activation: an access token minted before the deactivation is still+-- inside its expiry window and resumes working the moment the row flips+-- back. Tokens now carry `iat`, and a token issued at or before this+-- timestamp is refused however active the principal currently is.+ALTER TABLE users ADD COLUMN IF NOT EXISTS sessions_revoked_at TIMESTAMPTZ;++COMMENT ON COLUMN users.sessions_revoked_at IS+ 'Access and refresh tokens issued at or before this instant are refused. '+ 'Set by SCIM deprovisioning and by an administrator ending sessions, so '+ 'revocation survives a later re-activation of the same principal.';+++-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets+-- the cross-tenant workers (retention purge, tenant deletion) reach these+-- tables; dropping it makes those silently see nothing. FORCE so the table+-- owner, which is the role that runs migrations, does not walk past it.+ALTER TABLE aisoc_scim_tokens ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_scim_tokens FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_scim_tokens_tenant ON aisoc_scim_tokens;+CREATE POLICY aisoc_scim_tokens_tenant ON aisoc_scim_tokens+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_scim_users ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_scim_users FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_scim_users_tenant ON aisoc_scim_users;+CREATE POLICY aisoc_scim_users_tenant ON aisoc_scim_users+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_scim_groups ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_scim_groups FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_scim_groups_tenant ON aisoc_scim_groups;+CREATE POLICY aisoc_scim_groups_tenant ON aisoc_scim_groups+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_scim_group_members ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_scim_group_members FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_scim_group_members_tenant ON aisoc_scim_group_members;+CREATE POLICY aisoc_scim_group_members_tenant ON aisoc_scim_group_members+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- 061 set ALTER DEFAULT PRIVILEGES so new tables pick these up, but only for+-- tables created by the role that ran it. Granting explicitly means a chain+-- replayed by a different owner still leaves the runtime role able to work.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_scim_tokens TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_scim_users TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_scim_groups TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_scim_group_members TO aisoc_app;+ END IF;+END+$$;diff --git a/services/api/tests/test_scim_mounted.py b/services/api/tests/test_scim_mounted.pynew file mode 100644index 000000000..fcf1a443d--- /dev/null+++ b/services/api/tests/test_scim_mounted.py@@ -0,0 +1,63 @@+"""The SCIM surface has to be reachable on the real application.++Five things in this program shipped with a passing test suite and no caller+on the path that needed them, so a module-level test of a router proves very+little. This builds the application the service actually serves and asks it+what it exposes.++``include_router`` does not populate ``app.routes`` usefully on the pinned+FastAPI, and a route inventory read from there can silently measure nothing+and report success. So this reads ``app.openapi()``, which is generated from+what was mounted, and it asserts the inventory is non-empty before asserting+anything about its contents.+"""++from __future__ import annotations++from app.main import create_application+from app.services.scim.resources import SCIM_BASE++#: Every path an identity provider reaches during a sync. A provider is+#: configured with the base URL only and appends these itself, so a missing+#: one surfaces to an administrator as a failed sync rather than as a 404+#: they can attribute.+REQUIRED_PATHS: dict[str, set[str]] = {+ f"{SCIM_BASE}/ServiceProviderConfig": {"get"},+ f"{SCIM_BASE}/ResourceTypes": {"get"},+ f"{SCIM_BASE}/Schemas": {"get"},+ f"{SCIM_BASE}/Users": {"get", "post"},+ f"{SCIM_BASE}/Users/{{user_id}}": {"get", "put", "patch", "delete"},+ f"{SCIM_BASE}/Groups": {"get", "post"},+ f"{SCIM_BASE}/Groups/{{group_id}}": {"get", "put", "patch", "delete"},+}+++def test_the_scim_surface_is_mounted_on_the_real_application() -> None:+ paths = create_application().openapi()["paths"]++ # Before asserting what is there, assert that anything is. An empty+ # inventory makes every membership check below vacuously unrunnable and+ # a naive version of this test would pass over it.+ assert paths, "the OpenAPI document exposes no paths at all; this test would otherwise measure nothing"+ scim_paths = {path for path in paths if path.startswith(SCIM_BASE)}+ assert scim_paths, f"no path under {SCIM_BASE} is mounted; the SCIM router is defined and never included"++ for path, methods in REQUIRED_PATHS.items():+ assert path in paths, f"{path} is not mounted"+ assert methods <= set(paths[path]), f"{path} is missing {sorted(methods - set(paths[path]))}"+++def test_the_console_facing_token_routes_are_mounted() -> None:+ """The credential the SCIM surface accepts has to be mintable.++ A SCIM surface with no way to issue a token for it is unreachable in+ practice however correct the handlers are.+ """+ paths = create_application().openapi()["paths"]+ assert paths, "the OpenAPI document exposes no paths at all"++ assert "/api/v1/scim-tokens" in paths+ assert {"get", "post"} <= set(paths["/api/v1/scim-tokens"])+ assert "/api/v1/scim-tokens/{token_id}/rotate" in paths+ assert "post" in paths["/api/v1/scim-tokens/{token_id}/rotate"]+ assert "delete" in paths["/api/v1/scim-tokens/{token_id}"]diff --git a/services/api/tests/test_scim_provisioning.py b/services/api/tests/test_scim_provisioning.pynew file mode 100644index 000000000..3444a604c--- /dev/null+++ b/services/api/tests/test_scim_provisioning.py@@ -0,0 +1,849 @@+"""SCIM 2.0 against the request shapes two identity providers actually send.++Gap-closure Phase 13.1 gate.++Why the payloads below are written out in full+-----------------------------------------------+A hand-written SCIM test agrees with the handler it was written beside. Both+providers this platform supports deviate from the obvious reading of RFC 7644,+in opposite directions, and a test that paraphrases their payloads reproduces+whatever the author assumed rather than what the provider sends. So the bodies+here are transcribed in the shape the providers emit, including the parts that+look like mistakes:++* deactivation with no ``path`` and an object value (Okta), versus an explicit+ ``path`` and the *string* ``"False"`` (Entra)+* ``op`` lowercase (Okta) versus capitalised (Entra)+* member removal through a path filter with no value (Okta), versus+ ``path: "members"`` with the id in a value array (Entra)+* ``userName`` omitted entirely in favour of ``emails`` (Entra, when the+ directory's username attribute is unset)++They are synthetic reproductions of documented request shapes, not captures+from a customer tenant.++The two sequences at the bottom are the acceptance criterion: create, update,+group membership, deactivate, run end to end in each provider's dialect.++Everything here runs on one event loop through ``httpx.ASGITransport``. The+threaded test client would put the request on a different loop from the+fixtures, and the shared in-memory SQLite connection cannot be reached from+two.+"""++from __future__ import annotations++import json+import uuid+from datetime import UTC, datetime, timedelta++import jwt+import pytest+import pytest_asyncio+from app.api.v1.endpoints.scim import ScimAuthFailed+from app.api.v1.endpoints.scim import router as scim_router+from app.core.security import create_access_token, token_is_revoked+from app.db.database import Base, get_db+from app.models.audit import AuditLog+from app.models.scim import ScimGroup, ScimGroupMember, ScimToken, ScimUser+from app.models.tenant import ApiKey, User+from app.services.scim import provisioning, resources, roles, tokens+from fastapi import FastAPI, status+from fastapi.responses import JSONResponse+from httpx import ASGITransport, AsyncClient+from sqlalchemy import select+from sqlalchemy.dialects.postgresql import INET, JSONB+from sqlalchemy.dialects.postgresql import UUID as PgUUID+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy.ext.compiler import compiles++TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-0000000000a1")+OTHER_TENANT = uuid.UUID("bbbbbbbb-0000-0000-0000-0000000000b1")++BASE = resources.SCIM_BASE+++@compiles(JSONB, "sqlite")+def _jsonb_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++@compiles(PgUUID, "sqlite")+def _uuid_sqlite(_type_, _compiler_, **_kw_):+ return "CHAR(36)"+++@compiles(INET, "sqlite")+def _inet_sqlite(_type_, _compiler_, **_kw_):+ return "TEXT"+++# ---------------------------------------------------------------------------+# Vendor-shaped request bodies (synthetic reproductions)+# ---------------------------------------------------------------------------++PATCH_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:PatchOp"++#: Okta: no `path`, value is an object, `op` lowercase.+OKTA_DEACTIVATE = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "value": {"active": False}}]}++#: Entra: explicit `path`, `op` capitalised, and the value is the *string*+#: "False". `bool("False")` is True, so a naive read deactivates nothing+#: while returning 200.+ENTRA_DEACTIVATE = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Replace", "path": "active", "value": "False"}]}++#: Entra also sends a real boolean in some versions. Both must work.+ENTRA_DEACTIVATE_BOOL = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Replace", "path": "active", "value": False}]}++#: Okta group member add.+OKTA_ADD_MEMBER = {+ "schemas": [PATCH_SCHEMA],+ "Operations": [{"op": "add", "path": "members", "value": [{"value": "__USER__", "display": "[email protected]"}]}],+}++#: Okta group member removal: the id lives in a path filter, and there is no+#: `value` at all.+OKTA_REMOVE_MEMBER = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "remove", "path": 'members[value eq "__USER__"]'}]}++#: Entra group member add: capitalised op, member objects in `value`.+ENTRA_ADD_MEMBER = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Add", "path": "members", "value": [{"value": "__USER__"}]}]}++#: Entra group member removal: `path` names the attribute and `value` names+#: the member. The opposite arrangement from Okta's removal above.+ENTRA_REMOVE_MEMBER = {+ "schemas": [PATCH_SCHEMA],+ "Operations": [{"op": "Remove", "path": "members", "value": [{"value": "__USER__"}]}],+}++#: Okta user create. `userName` present, name sub-attributes present.+OKTA_CREATE_USER = {+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName": "[email protected]",+ "name": {"givenName": "Ada", "familyName": "Lovelace"},+ "emails": [{"primary": True, "value": "[email protected]", "type": "work"}],+ "displayName": "Ada Lovelace",+ "active": True,+ "externalId": "00u1okta0000000001",+ "groups": [],+}++#: Entra user create. No `userName`; the address is only in `emails`, and the+#: enterprise-user extension arrives alongside the core schema.+ENTRA_CREATE_USER = {+ "schemas": [+ "urn:ietf:params:scim:schemas:core:2.0:User",+ "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",+ ],+ "externalId": "8a7b6c5d-entra-0000-0000-000000000001",+ "emails": [{"primary": True, "type": "work", "value": "[email protected]"}],+ "name": {"givenName": "Grace", "familyName": "Hopper"},+ "displayName": "Grace Hopper",+ "active": True,+ "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {"department": "Security"},+}+++def _with_user(template: dict, user_id: str) -> dict:+ """Substitute a real user id into a recorded payload."""+ return json.loads(json.dumps(template).replace("__USER__", user_id))+++# ---------------------------------------------------------------------------+# Harness+# ---------------------------------------------------------------------------++_TABLES = [+ User.__table__,+ ApiKey.__table__,+ AuditLog.__table__,+ ScimToken.__table__,+ ScimUser.__table__,+ ScimGroup.__table__,+ ScimGroupMember.__table__,+]+++@pytest_asyncio.fixture+async def session_factory():+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as conn:+ # Only the tables these paths touch. A whole-metadata create_all+ # drags in models using Postgres ARRAY, which SQLite cannot render.+ await conn.run_sync(Base.metadata.create_all, tables=_TABLES)+ yield async_sessionmaker(engine, expire_on_commit=False)+ await engine.dispose()+++@pytest_asyncio.fixture+async def secrets(session_factory):+ """A tenant with one SCIM credential, and a second tenant beside it."""+ async with session_factory() as db:+ _token, raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="okta-primary", created_by=None)+ _other, other_raw = await tokens.mint_token(db, tenant_id=OTHER_TENANT, org_id=None, name="other", created_by=None)+ await db.commit()+ return {"raw": raw, "other_raw": other_raw}+++def _build_app(session_factory) -> FastAPI:+ app = FastAPI()+ app.include_router(scim_router)++ @app.exception_handler(ScimAuthFailed)+ async def _refused(_request, _exc):+ return JSONResponse(+ status_code=status.HTTP_401_UNAUTHORIZED,+ content=resources.error_response(401, "Invalid SCIM credential"),+ media_type=resources.SCIM_CONTENT_TYPE,+ )++ async def _override_db():+ # Mirrors app.db.database.get_db, including the trailing commit.+ # Without it the harness would diverge from production for any write+ # a dependency makes and a handler does not commit, which is exactly+ # how `last_used_at` on a read-only SCIM call would be lost.+ async with session_factory() as db:+ try:+ yield db+ await db.commit()+ except Exception:+ await db.rollback()+ raise++ app.dependency_overrides[get_db] = _override_db+ return app+++@pytest_asyncio.fixture+async def client(session_factory, secrets):+ app = _build_app(session_factory)+ async with AsyncClient(+ transport=ASGITransport(app=app),+ base_url="http://scim.test",+ headers={"Authorization": f"Bearer {secrets['raw']}"},+ ) as http:+ yield http+++@pytest_asyncio.fixture+async def anonymous(session_factory):+ app = _build_app(session_factory)+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://scim.test") as http:+ yield http+++async def _seed_user(session_factory, *, email: str, tenant: uuid.UUID = TENANT, with_key: bool = False) -> uuid.UUID:+ user_id = uuid.uuid4()+ async with session_factory() as db:+ db.add(+ User(+ id=user_id,+ tenant_id=tenant,+ email=email,+ username=email,+ hashed_password="!x",+ role="soc_analyst",+ is_active=True,+ )+ )+ if with_key:+ db.add(+ ApiKey(+ tenant_id=tenant,+ user_id=user_id,+ name="minted before leaving",+ key_prefix="aisoc_zzz123",+ hashed_key=uuid.uuid4().hex,+ scopes=["*"],+ is_active=True,+ )+ )+ await db.commit()+ return user_id+++# ---------------------------------------------------------------------------+# The credential+# ---------------------------------------------------------------------------+++class TestTokens:+ async def test_raw_secret_is_not_recoverable_from_the_row(self, secrets, session_factory):+ """What is stored is a digest; the prefix is not the secret."""+ raw = secrets["raw"]+ assert raw.startswith(tokens.TOKEN_PREFIX)+ async with session_factory() as db:+ row = (await db.execute(select(ScimToken).where(ScimToken.name == "okta-primary"))).scalar_one()+ assert row.token_hash == tokens.hash_token(raw)+ assert raw not in row.token_hash+ assert row.token_prefix != raw+ assert len(row.token_prefix) < len(raw)++ @pytest.mark.parametrize("header", ["Bearer not-a-scim-token", "Bearer aisoc_scim_deadbeef", "Bearer "])+ async def test_a_bad_credential_gets_a_scim_error_with_no_detail(self, anonymous, header):+ response = await anonymous.get(f"{BASE}/Users", headers={"Authorization": header})+ assert response.status_code == 401+ body = response.json()+ assert body["schemas"] == [resources.ERROR_SCHEMA]+ # The reason is logged, not returned. A caller must not learn whether+ # a secret was wrong, revoked or merely expired.+ assert "revoked" not in body["detail"].casefold()+ assert "expired" not in body["detail"].casefold()++ async def test_no_credential_at_all_is_refused(self, anonymous):+ assert (await anonymous.get(f"{BASE}/Users")).status_code == 401++ async def test_revoked_and_expired_tokens_are_refused(self, session_factory):+ async with session_factory() as db:+ live, live_raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="live", created_by=None)+ revoked, revoked_raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="revoked", created_by=None)+ expired, expired_raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="expired", created_by=None)+ revoked.revoked_at = datetime.now(UTC)+ expired.expires_at = datetime.now(UTC) - timedelta(seconds=1)+ await db.commit()++ assert (await tokens.verify_token(db, live_raw)).tenant_id == TENANT+ assert live.is_usable()+ for raw in (revoked_raw, expired_raw):+ with pytest.raises(tokens.ScimAuthError):+ await tokens.verify_token(db, raw)++ async def test_rotation_leaves_an_overlap_window_then_closes_it(self, session_factory):+ """Both secrets work during the grace window; the old one then expires.++ A rotation that cut over instantly would take the integration down+ for as long as it takes a person to paste the new secret across,+ which is why rotation gets deferred and secrets get old.+ """+ async with session_factory() as db:+ old, old_raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="rotating", created_by=None)+ await db.commit()+ new, new_raw = await tokens.rotate_token(db, token=old, created_by=None, grace=timedelta(hours=1))+ await db.commit()++ assert new.rotated_from_id == old.id+ assert (await tokens.verify_token(db, old_raw)).tenant_id == TENANT+ assert (await tokens.verify_token(db, new_raw)).tenant_id == TENANT++ later = datetime.now(UTC) + timedelta(hours=2)+ with pytest.raises(tokens.ScimAuthError):+ await tokens.verify_token(db, old_raw, now=later)+ assert (await tokens.verify_token(db, new_raw, now=later)).tenant_id == TENANT++ async def test_zero_grace_revokes_the_old_secret_at_once(self, session_factory):+ """Rotation after a disclosure must not leave the leaked secret live."""+ async with session_factory() as db:+ old, old_raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="leaked", created_by=None)+ await db.commit()+ await tokens.rotate_token(db, token=old, created_by=None, grace=timedelta(0))+ await db.commit()+ with pytest.raises(tokens.ScimAuthError):+ await tokens.verify_token(db, old_raw)++ async def test_rotation_never_extends_an_earlier_deadline(self, session_factory):+ async with session_factory() as db:+ soon = datetime.now(UTC) + timedelta(minutes=5)+ old, _raw = await tokens.mint_token(db, tenant_id=TENANT, org_id=None, name="short-lived", created_by=None, expires_at=soon)+ await db.commit()+ await tokens.rotate_token(db, token=old, created_by=None, grace=timedelta(hours=48))+ await db.commit()+ assert old.expires_at == soon++ async def test_last_used_is_recorded_so_an_abandoned_integration_is_visible(self, client, session_factory):+ await client.get(f"{BASE}/ServiceProviderConfig")+ async with session_factory() as db:+ row = (await db.execute(select(ScimToken).where(ScimToken.name == "okta-primary"))).scalar_one()+ assert row.last_used_at is not None++ async def test_a_token_addresses_exactly_one_tenant(self, client, secrets):+ """Cross-tenant reach is impossible because there is no field for it."""+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ assert created.status_code == 201+ user_id = created.json()["id"]+ seen = await client.get(f"{BASE}/Users/{user_id}", headers={"Authorization": f"Bearer {secrets['other_raw']}"})+ assert seen.status_code == 404+++# ---------------------------------------------------------------------------+# Discovery+# ---------------------------------------------------------------------------+++class TestDiscovery:+ async def test_service_provider_config_describes_what_is_implemented(self, client):+ body = (await client.get(f"{BASE}/ServiceProviderConfig")).json()+ assert body["patch"]["supported"] is True+ assert body["filter"]["supported"] is True+ # Declared false rather than omitted: advertising either would have a+ # provider configure itself to use an endpoint that is not there.+ assert body["bulk"]["supported"] is False+ assert body["sort"]["supported"] is False++ async def test_resource_types_and_schemas_are_fetchable_individually(self, client):+ listed = (await client.get(f"{BASE}/ResourceTypes")).json()+ assert {entry["id"] for entry in listed["Resources"]} == {"User", "Group"}+ assert (await client.get(f"{BASE}/ResourceTypes/User")).status_code == 200++ schemas = (await client.get(f"{BASE}/Schemas")).json()+ ids = {entry["id"] for entry in schemas["Resources"]}+ assert {resources.USER_SCHEMA, resources.GROUP_SCHEMA} <= ids+ assert (await client.get(f"{BASE}/Schemas/{resources.USER_SCHEMA}")).status_code == 200++ async def test_discovery_requires_a_credential(self, anonymous):+ """RFC 7644 permits anonymous discovery; this deployment does not.++ The documents say which SCIM features are enabled here, which is not+ something to publish to anyone who asks.+ """+ assert (await anonymous.get(f"{BASE}/ServiceProviderConfig")).status_code == 401+ assert (await anonymous.get(f"{BASE}/Schemas")).status_code == 401++ async def test_responses_carry_the_scim_content_type(self, client):+ response = await client.get(f"{BASE}/ServiceProviderConfig")+ assert response.headers["content-type"].startswith(resources.SCIM_CONTENT_TYPE)+++# ---------------------------------------------------------------------------+# Filtering+# ---------------------------------------------------------------------------+++class TestFiltering:+ async def test_equality_filter_finds_the_user_a_provider_is_about_to_create(self, client):+ await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ found = (await client.get(f"{BASE}/Users", params={"filter": 'userName eq "[email protected]"'})).json()+ assert found["totalResults"] == 1+ assert found["Resources"][0]["userName"] == "[email protected]"++ async def test_a_filter_that_matches_nothing_returns_an_empty_list_not_everything(self, client):+ await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ found = (await client.get(f"{BASE}/Users", params={"filter": 'userName eq "[email protected]"'})).json()+ assert found["totalResults"] == 0+ assert found["Resources"] == []++ async def test_an_unsupported_filter_is_refused_rather_than_dropped(self, client):+ """Dropping it would return every principal in the tenant.++ A provider reading that concludes the user it was about to create+ already exists, or picks the first result and updates the wrong one.+ """+ await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ response = await client.get(f"{BASE}/Users", params={"filter": 'userName eq "[email protected]" and active eq "true"'})+ assert response.status_code == 400+ assert response.json()["scimType"] == "invalidFilter"++ async def test_username_matching_ignores_case(self, client):+ """Providers do not guarantee address casing is stable between syncs."""+ await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ found = (await client.get(f"{BASE}/Users", params={"filter": 'userName eq "[email protected]"'})).json()+ assert found["totalResults"] == 1++ async def test_external_id_filter_finds_a_renamed_principal(self, client):+ """The id a provider stores has to survive a change of address."""+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = created.json()["id"]+ await client.patch(+ f"{BASE}/Users/{user_id}",+ json={"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "value": {"userName": "[email protected]"}}]},+ )+ found = (await client.get(f"{BASE}/Users", params={"filter": 'externalId eq "00u1okta0000000001"'})).json()+ assert found["totalResults"] == 1+ assert found["Resources"][0]["userName"] == "[email protected]"++ async def test_total_results_counts_the_match_not_the_page(self, client):+ """Providers page on totalResults.++ Returning the page size instead stops a sync after the first page+ while reporting success.+ """+ for index in range(5):+ await client.post(+ f"{BASE}/Users",+ json={**OKTA_CREATE_USER, "userName": f"u{index}@example.com", "externalId": f"ext-{index}"},+ )+ page = (await client.get(f"{BASE}/Users", params={"count": 2})).json()+ assert page["totalResults"] == 5+ assert page["itemsPerPage"] == 2+++# ---------------------------------------------------------------------------+# Deprovisioning: the operation that has to be real+# ---------------------------------------------------------------------------+++class TestDeprovisioning:+ async def test_deactivation_revokes_sessions_and_api_keys(self, session_factory):+ """Three things end, and two of them are not the flag."""+ user_id = await _seed_user(session_factory, email="[email protected]", with_key=True)+ async with session_factory() as db:+ user = await db.get(User, user_id)+ result = await provisioning.deactivate_user(db, user)+ await db.commit()++ assert user.is_active is False+ assert result.api_keys_revoked == 1+ assert result.sessions_revoked_at is not None++ key = (await db.execute(select(ApiKey).where(ApiKey.user_id == user_id))).scalar_one()+ assert key.is_active is False++ def test_a_token_minted_before_deprovisioning_stays_dead_after_reactivation(self):+ """The flag alone is reversible; the timestamp is not.++ Re-enabling a principal must not resurrect tokens minted before they+ were deprovisioned, which are still inside their expiry window.+ """+ revoked_at = datetime.now(UTC)+ before = (revoked_at - timedelta(minutes=5)).timestamp()+ after = (revoked_at + timedelta(minutes=5)).timestamp()++ assert token_is_revoked(before, revoked_at) is True+ assert token_is_revoked(after, revoked_at) is False+ # No revocation recorded: nothing is refused.+ assert token_is_revoked(before, None) is False+ # A token with no `iat` predates the claim being added. Fails closed.+ assert token_is_revoked(None, revoked_at) is True++ def test_minted_tokens_carry_iat_so_the_check_has_something_to_read(self):+ """A revocation check against a claim nothing sets would never fire."""+ claims = jwt.decode(create_access_token({"sub": str(uuid.uuid4())}), options={"verify_signature": False})+ assert "iat" in claims++ async def test_reactivation_does_not_restore_revoked_api_keys(self, session_factory):+ """A key the owner cannot see was revoked is a key they will not rotate."""+ user_id = await _seed_user(session_factory, email="[email protected]", with_key=True)+ async with session_factory() as db:+ user = await db.get(User, user_id)+ await provisioning.deactivate_user(db, user)+ await provisioning.reactivate_user(db, user)+ await db.commit()++ assert user.is_active is True+ assert user.sessions_revoked_at is not None+ key = (await db.execute(select(ApiKey).where(ApiKey.user_id == user_id))).scalar_one()+ assert key.is_active is False++ async def test_delete_deprovisions_rather_than_erasing(self, client, session_factory):+ """A deleted row takes its audit attribution and case history with it.++ Access ends completely either way, which is what DELETE means here.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])+ deleted = await client.delete(f"{BASE}/Users/{user_id}")+ assert deleted.status_code == 204++ async with session_factory() as db:+ user = await db.get(User, user_id)+ assert user is not None, "the principal was erased; audit attribution would be lost"+ assert user.is_active is False+ assert user.sessions_revoked_at is not None++ async def test_deprovisioning_through_scim_revokes_the_principals_api_keys(self, client, session_factory):+ """The end-to-end version, driven through the SCIM surface itself."""+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])++ async with session_factory() as db:+ db.add(+ ApiKey(+ tenant_id=TENANT,+ user_id=user_id,+ name="minted before leaving",+ key_prefix="aisoc_zzz123",+ hashed_key=uuid.uuid4().hex,+ scopes=["*"],+ is_active=True,+ )+ )+ await db.commit()++ deleted = await client.delete(f"{BASE}/Users/{user_id}")+ assert deleted.status_code == 204++ async with session_factory() as db:+ key = (await db.execute(select(ApiKey).where(ApiKey.user_id == user_id))).scalar_one()+ user = await db.get(User, user_id)+ assert key.is_active is False+ assert user.is_active is False+ assert user.sessions_revoked_at is not None+++# ---------------------------------------------------------------------------+# Group to role mapping+# ---------------------------------------------------------------------------+++class TestRoleMapping:+ def test_the_mapping_only_names_roles_this_platform_enforces(self):+ assert roles.validate_vocabulary() == []++ @pytest.mark.parametrize(+ ("group_name", "expected"),+ [+ ("AiSOC-SOC-Analysts", "soc_analyst"),+ ("soc analyst", "soc_analyst"),+ ("SOC_Analysts", "soc_analyst"),+ ("AiSOC Threat Hunters", "threat_hunter"),+ ("AiSOC-SOC-Leads", "soc_lead"),+ ("Tenant Admins", "tenant_admin"),+ ("Security Viewers", "viewer"),+ ("Triage Team", "soc_analyst"),+ # Unrecognised: confers nothing rather than something unknown.+ ("Marketing", None),+ ("", None),+ ],+ )+ def test_group_names_resolve_to_the_role_they_name_or_to_nothing(self, group_name, expected):+ assert roles.resolve_role(group_name) == expected++ @pytest.mark.parametrize("privileged", ["Platform Admins", "admins", "AiSOC platform_admin", "api service"])+ def test_no_group_name_can_mint_a_wildcard_role(self, privileged):+ """A directory group name must not be able to grant '*' everywhere.++ Whoever can create a group in the customer's directory is usually a+ larger set of people than the platform's administrators.+ """+ assert roles.resolve_role(privileged) not in roles.UNREACHABLE_BY_GROUP++ def test_precedence_is_total_so_sync_order_cannot_change_authority(self):+ assert roles.effective_role(["soc_analyst", "tenant_admin"]) == "tenant_admin"+ assert roles.effective_role(["tenant_admin", "soc_analyst"]) == "tenant_admin"+ assert roles.effective_role([None, None]) == roles.DEFAULT_PROVISIONED_ROLE+ assert roles.effective_role([]) == roles.DEFAULT_PROVISIONED_ROLE++ async def test_membership_grants_the_role_and_removal_takes_it_back(self, client, session_factory):+ """This is the step that makes a group mean anything.++ ``users.role`` is the column the permission check reads, so a group+ that did not write it would be recorded and inert.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])++ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == roles.DEFAULT_PROVISIONED_ROLE++ group = await client.post(f"{BASE}/Groups", json={"displayName": "AiSOC-SOC-Leads"})+ group_id = group.json()["id"]+ await client.patch(f"{BASE}/Groups/{group_id}", json=_with_user(OKTA_ADD_MEMBER, str(user_id)))++ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == "soc_lead"++ await client.patch(f"{BASE}/Groups/{group_id}", json=_with_user(OKTA_REMOVE_MEMBER, str(user_id)))++ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == roles.DEFAULT_PROVISIONED_ROLE++ async def test_an_unmapped_group_confers_nothing(self, client, session_factory):+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])+ group = await client.post(f"{BASE}/Groups", json={"displayName": "Marketing"})+ assert group.json()[resources.AISOC_GROUP_EXTENSION]["mappedRole"] is None++ await client.patch(f"{BASE}/Groups/{group.json()['id']}", json=_with_user(OKTA_ADD_MEMBER, str(user_id)))+ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == roles.DEFAULT_PROVISIONED_ROLE++ async def test_deleting_the_group_takes_the_role_with_it(self, client, session_factory):+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])+ group = await client.post(f"{BASE}/Groups", json={"displayName": "Tenant Admins"})+ group_id = group.json()["id"]+ await client.patch(f"{BASE}/Groups/{group_id}", json=_with_user(OKTA_ADD_MEMBER, str(user_id)))++ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == "tenant_admin"++ deleted = await client.delete(f"{BASE}/Groups/{group_id}")+ assert deleted.status_code == 204+ async with session_factory() as db:+ assert (await db.get(User, user_id)).role == roles.DEFAULT_PROVISIONED_ROLE+++# ---------------------------------------------------------------------------+# End-to-end provider sequences: the acceptance criterion+# ---------------------------------------------------------------------------+++async def _sequence(client, *, create_body, deactivate_body, add_member, remove_member, group_name, expected_email):+ """create, update, group membership, deactivate, in one provider's dialect."""+ created = await client.post(f"{BASE}/Users", json=create_body)+ assert created.status_code == 201, created.text+ user = created.json()+ assert user["userName"] == expected_email+ assert user["active"] is True+ user_id = user["id"]++ # A repeated create is a conflict, never a duplicate principal.+ duplicate = await client.post(f"{BASE}/Users", json=create_body)+ assert duplicate.status_code == 409++ # Update: a rename through PUT, which one provider uses for profile+ # changes when attribute sync is enabled.+ renamed = await client.put(f"{BASE}/Users/{user_id}", json={**create_body, "name": {"givenName": "Renamed", "familyName": "Principal"}})+ assert renamed.status_code == 200, renamed.text+ assert renamed.json()["name"]["givenName"] == "Renamed"++ # Group membership: create, add, confirm the role it confers, then remove+ # and confirm the role goes with it.+ group = await client.post(f"{BASE}/Groups", json={"displayName": group_name, "members": []})+ assert group.status_code == 201, group.text+ group_id = group.json()["id"]+ assert group.json()[resources.AISOC_GROUP_EXTENSION]["mappedRole"] == "soc_lead"++ added = await client.patch(f"{BASE}/Groups/{group_id}", json=_with_user(add_member, user_id))+ assert added.status_code == 200, added.text+ assert [m["value"] for m in added.json()["members"]] == [user_id]++ seen = (await client.get(f"{BASE}/Users/{user_id}")).json()+ assert [g["value"] for g in seen.get("groups", [])] == [group_id]++ removed = await client.patch(f"{BASE}/Groups/{group_id}", json=_with_user(remove_member, user_id))+ assert removed.status_code == 200, removed.text+ assert removed.json()["members"] == []++ # Deactivate, in this provider's dialect.+ deactivated = await client.patch(f"{BASE}/Users/{user_id}", json=deactivate_body)+ assert deactivated.status_code == 200, deactivated.text+ assert deactivated.json()["active"] is False, "the deactivation did not take effect"++ # Visible on a subsequent read, not only in the response body.+ assert (await client.get(f"{BASE}/Users/{user_id}")).json()["active"] is False+ return user_id+++class TestProviderSequences:+ async def test_okta_shaped_sequence(self, client):+ await _sequence(+ client,+ create_body=OKTA_CREATE_USER,+ deactivate_body=OKTA_DEACTIVATE,+ add_member=OKTA_ADD_MEMBER,+ remove_member=OKTA_REMOVE_MEMBER,+ group_name="AiSOC-SOC-Leads",+ expected_email="[email protected]",+ )++ async def test_entra_shaped_sequence(self, client):+ await _sequence(+ client,+ create_body=ENTRA_CREATE_USER,+ deactivate_body=ENTRA_DEACTIVATE,+ add_member=ENTRA_ADD_MEMBER,+ remove_member=ENTRA_REMOVE_MEMBER,+ group_name="AiSOC SOC Lead",+ expected_email="[email protected]",+ )++ async def test_the_string_false_really_deactivates(self, client):+ """The single most consequential difference between the two dialects.++ ``bool("False")`` is True. Read naively, this payload deactivates+ nothing and returns 200, so the provider records the deprovisioning+ as successful and the principal keeps their access.+ """+ created = await client.post(f"{BASE}/Users", json=ENTRA_CREATE_USER)+ user_id = created.json()["id"]+ response = await client.patch(f"{BASE}/Users/{user_id}", json=ENTRA_DEACTIVATE)+ assert response.json()["active"] is False++ async def test_both_boolean_spellings_work(self, client):+ created = await client.post(f"{BASE}/Users", json=ENTRA_CREATE_USER)+ user_id = created.json()["id"]+ patched = await client.patch(f"{BASE}/Users/{user_id}", json=ENTRA_DEACTIVATE_BOOL)+ assert patched.json()["active"] is False++ async def test_a_value_that_is_neither_true_nor_false_is_refused(self, client):+ """Refused rather than defaulted.++ A default here would apply something the provider did not ask for,+ and neither side could tell that happened.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = created.json()["id"]+ response = await client.patch(+ f"{BASE}/Users/{user_id}",+ json={"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "path": "active", "value": "perhaps"}]},+ )+ assert response.status_code == 400+ assert response.json()["scimType"] == "invalidValue"++ async def test_an_unknown_attribute_does_not_fail_the_operation_beside_it(self, client):+ """A provider sends its whole mapped attribute set in one body.++ Rejecting ``title`` would fail the deactivation that arrived with it.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = created.json()["id"]+ response = await client.patch(+ f"{BASE}/Users/{user_id}",+ json={+ "schemas": [PATCH_SCHEMA],+ "Operations": [+ {"op": "replace", "path": "title", "value": "Principal Engineer"},+ {"op": "replace", "path": "active", "value": "False"},+ ],+ },+ )+ assert response.status_code == 200+ assert response.json()["active"] is False+++# ---------------------------------------------------------------------------+# Auditing+# ---------------------------------------------------------------------------+++class TestAuditing:+ async def test_every_write_lands_in_the_audit_log_naming_the_token(self, client, session_factory):+ """The actor of a SCIM change is a machine.++ An audit trail that cannot say which machine is not an audit trail.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = created.json()["id"]+ await client.patch(f"{BASE}/Users/{user_id}", json=OKTA_DEACTIVATE)+ group = await client.post(f"{BASE}/Groups", json={"displayName": "AiSOC-SOC-Leads"})+ await client.delete(f"{BASE}/Groups/{group.json()['id']}")++ async with session_factory() as db:+ rows = (await db.execute(select(AuditLog))).scalars().all()++ actions = {row.action for row in rows}+ assert {"scim:user:create", "scim:user:patch", "scim:group:create", "scim:group:delete"} <= actions+ for row in rows:+ assert row.actor_email.startswith("scim:")+ assert row.changes is not None+ assert "provisioned_by" in row.changes+ assert row.changes["provisioned_by"]["integration"] == "okta-primary"++ async def test_the_deprovisioning_record_says_what_it_ended(self, client, session_factory):+ """Counts, not a boolean.++ An audit row saying "deactivated" cannot answer whether the API keys+ went with it, which is the question a review asks.+ """+ created = await client.post(f"{BASE}/Users", json=OKTA_CREATE_USER)+ user_id = uuid.UUID(created.json()["id"])+ async with session_factory() as db:+ db.add(+ ApiKey(+ tenant_id=TENANT,+ user_id=user_id,+ name="k",+ key_prefix="aisoc_k1",+ hashed_key=uuid.uuid4().hex,+ scopes=[],+ is_active=True,+ )+ )+ await db.commit()++ await client.delete(f"{BASE}/Users/{user_id}")++ async with session_factory() as db:+ rows = (await db.execute(select(AuditLog).where(AuditLog.action == "scim:user:delete"))).scalars().all()+ assert len(rows) == 1+ assert rows[0].changes["programmatic_access_revoked"] == 1+ assert rows[0].changes["sessions_revoked_at"]