Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

test(scim): patch, group membership and deprovisioning against live Postgres, and the console the doc promised (#1198)

Beenu Arora54f6875f27ed
diff --git a/.github/workflows/scim-live.yml b/.github/workflows/scim-live.yml
index e0d863e5b..299dbb463 100644
--- a/.github/workflows/scim-live.yml
+++ b/.github/workflows/scim-live.yml
@@ -64,7 +64,16 @@ jobs:
SCIM_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc
DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc
PGPASSWORD: aisoc_ci_only
- ENVIRONMENT: development
+ # `test`, not `development`. `development` is in
+ # `AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request resolves
+ # to a demo **admin** — inside the one suite whose purpose is
+ # proving the tenant comes from the credential.
+ # `config.py` records that `"test"` was deliberately excluded from
+ # that set for exactly this reason.
+ ENVIRONMENT: test
+ # A skip here is a green report over nothing. The suite refuses to
+ # collect when this is set and the DSN is not.
+ ISOLATION_REQUIRE_LIVE: "1"
# Nothing to export to, and the retry backoff adds a minute of noise
# to every run.
OTEL_SDK_DISABLED: "true"
@@ -106,13 +115,42 @@ jobs:
psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \
"GRANT USAGE ON SCHEMA public TO aisoc_app;"
- - name: SCIM provisions, lists and isolates
+ - name: SCIM provisions, patches, groups, deprovisions and isolates
working-directory: services/api
env:
ISOLATION_SCIM_DSN: ${{ env.SCIM_DSN }}
DATABASE_URL: ${{ env.SCIM_DSN }}
+ # `-p no:randomly` is not needed and `--runxfail` would hide a
+ # skip, so the guard against a vacuous pass is the module's own
+ # `ISOLATION_REQUIRE_LIVE` check plus the step below, which reads
+ # the counts out of the report rather than trusting the exit code.
run: python -m pytest ../../tests/isolation/test_scim_live.py -v --tb=short
+ # A suite that skipped every case exits 0.
+ #
+ # The module-level guard catches a missing DSN; this catches the
+ # other route to the same outcome — a fixture, a marker or a
+ # collection error leaving nothing to run while the job stays green.
+ - name: Every live case ran, none skipped
+ working-directory: services/api
+ env:
+ ISOLATION_SCIM_DSN: ${{ env.SCIM_DSN }}
+ DATABASE_URL: ${{ env.SCIM_DSN }}
+ run: |
+ set -euo pipefail
+ python -m pytest ../../tests/isolation/test_scim_live.py -q \
+ --junitxml=/tmp/scim-live.xml >/dev/null
+ python - <<'PY'
+ import sys, xml.etree.ElementTree as ET
+ suite = ET.parse("/tmp/scim-live.xml").getroot().find("testsuite")
+ ran, skipped = int(suite.get("tests", 0)), int(suite.get("skipped", 0))
+ print(f"collected {ran}, skipped {skipped}")
+ if ran - skipped < 20:
+ sys.exit(f"FAIL: only {ran - skipped} live case(s) executed; this job is supposed to run the whole suite")
+ if skipped:
+ sys.exit(f"FAIL: {skipped} case(s) skipped in a job that exists to run live")
+ PY
+
# Moved here from `isolation.yml`, which is path-filtered. A static
# gate behind a filter does not satisfy the unconditional property,
# and these two are the contract checks for this capability.
@@ -158,3 +196,72 @@ jobs:
cp /tmp/scim.bak app/api/v1/endpoints/scim.py
echo "OK: removing the tenant predicate makes the suite fail, as it must."
python -m pytest ../../tests/isolation/test_scim_live.py -q
+
+ # The negative control for the three operations added in fix-pass 4.5.
+ #
+ # The tenant-predicate control above covers the *read* path only, and
+ # would stay red for its own reason if PATCH, groups or deprovisioning
+ # silently stopped writing. This one makes `_apply_active` a no-op:
+ # the handler still answers 200 with a correct-looking resource and
+ # the row never changes, which is the exact shape a response-only
+ # assertion cannot see.
+ #
+ # Expected: the deactivation and deprovisioning cases fail.
+ - name: The gate fails when deactivation stops writing the row
+ working-directory: services/api
+ env:
+ ISOLATION_SCIM_DSN: ${{ env.SCIM_DSN }}
+ DATABASE_URL: ${{ env.SCIM_DSN }}
+ run: |
+ cp app/api/v1/endpoints/scim.py /tmp/scim.bak
+ python - <<'PY'
+ import pathlib, sys
+ p = pathlib.Path("app/api/v1/endpoints/scim.py")
+ s = p.read_text()
+ needle = " if active == user.is_active:\n return {}\n"
+ if needle not in s:
+ print("negative control could not find the body of _apply_active; it has been "
+ "reshaped and this control is no longer proving anything")
+ sys.exit(1)
+ p.write_text(s.replace(needle, " return {} # injected no-op\n", 1))
+ PY
+ if python -m pytest ../../tests/isolation/test_scim_live.py -q >/dev/null 2>&1; then
+ cp /tmp/scim.bak app/api/v1/endpoints/scim.py
+ echo "FAIL: the suite passed with deactivation writing nothing."
+ exit 1
+ fi
+ cp /tmp/scim.bak app/api/v1/endpoints/scim.py
+ echo "OK: a no-op deactivation makes the suite fail, as it must."
+ python -m pytest ../../tests/isolation/test_scim_live.py -q
+
+ # And the same for group membership, whose writes are a different
+ # handler and a different table.
+ - name: The gate fails when group membership stops being written
+ working-directory: services/api
+ env:
+ ISOLATION_SCIM_DSN: ${{ env.SCIM_DSN }}
+ DATABASE_URL: ${{ env.SCIM_DSN }}
+ run: |
+ cp app/api/v1/endpoints/scim.py /tmp/scim.bak
+ python - <<'PY'
+ import pathlib, sys
+ p = pathlib.Path("app/api/v1/endpoints/scim.py")
+ s = p.read_text()
+ needle = (
+ "async def _add_members(db: AsyncSession, tenant_id: uuid.UUID, "
+ "group: ScimGroup, raw_ids: list[str]) -> int:\n"
+ )
+ if needle not in s:
+ print("negative control could not find _add_members; it has been reshaped "
+ "and this control is no longer proving anything")
+ sys.exit(1)
+ p.write_text(s.replace(needle, needle + " return 0 # injected no-op\n", 1))
+ PY
+ if python -m pytest ../../tests/isolation/test_scim_live.py -q >/dev/null 2>&1; then
+ cp /tmp/scim.bak app/api/v1/endpoints/scim.py
+ echo "FAIL: the suite passed with group membership never being written."
+ exit 1
+ fi
+ cp /tmp/scim.bak app/api/v1/endpoints/scim.py
+ echo "OK: a no-op membership write makes the suite fail, as it must."
+ python -m pytest ../../tests/isolation/test_scim_live.py -q
diff --git a/apps/docs/docs/operations/scim.md b/apps/docs/docs/operations/scim.md
index 0f3da5268..04372925a 100644
--- a/apps/docs/docs/operations/scim.md
+++ b/apps/docs/docs/operations/scim.md
@@ -44,7 +44,14 @@ exists.
## Creating a credential
SCIM authenticates with a bearer token scoped to one tenant. Mint one from
-the console, or through the API:
+the console, or through the API.
+
+In the console, open **Settings → SCIM provisioning**, name the credential
+after the identity provider it is for, and optionally give it a lifetime in
+days. The table lists every credential for the tenant with its prefix, its
+state and when it was last used.
+
+Through the API:
```bash
curl -X POST https://<your-aisoc-host>/api/v1/scim-tokens \
@@ -53,13 +60,16 @@ curl -X POST https://<your-aisoc-host>/api/v1/scim-tokens \
-d '{"name": "corporate-directory", "expires_in_days": 365}'
```
-The response carries the raw secret once. It is stored as a SHA-256 digest,
+Either way the raw secret is shown 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
+Use **Rotate** on the credential's row in the console, choosing the grace
+window first, or:
+
```bash
curl -X POST https://<your-aisoc-host>/api/v1/scim-tokens/<id>/rotate \
-H "Authorization: Bearer $AISOC_SESSION_TOKEN" \
@@ -71,9 +81,10 @@ 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.
+If you are rotating because a secret was disclosed, send `{"grace_hours": 0}`
+— **Immediately (after a disclosure)** in the console. That revokes the old
+secret at once 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
@@ -168,7 +179,11 @@ single-provider implementation gets wrong:
attribute is unset
Both providers' full sequences (create, update, group membership, deactivate)
-run in CI.
+run in CI, twice over: once offline against an in-memory database, and once
+against a real Postgres through the application a deployment runs. The second
+is what covers the parts the first cannot — `UUID` and `TIMESTAMPTZ` columns,
+the composite key behind group membership, and the cascading foreign keys that
+let `DELETE` end access while the row survives.
## Troubleshooting
diff --git a/apps/web/src/components/settings/ScimTokensPanel.test.tsx b/apps/web/src/components/settings/ScimTokensPanel.test.tsx
new file mode 100644
index 000000000..f0bb2f5cc
--- /dev/null
+++ b/apps/web/src/components/settings/ScimTokensPanel.test.tsx
@@ -0,0 +1,133 @@
+/**
+ * The console surface `apps/docs/docs/operations/scim.md` promised.
+ *
+ * The doc said "mint one from the console, or through the API". Only the
+ * second half existed: `/api/v1/scim-tokens` had shipped with the SCIM
+ * surface and nothing under `apps/web/src` referenced it, so an
+ * administrator following the doc looked for a panel that was not there.
+ *
+ * What these cases are for
+ * -------------------------
+ * The API client is mocked rather than the component's own hooks, so the
+ * wiring between the two is inside the test. The three properties worth
+ * pinning are the ones where a mistake is expensive rather than visible:
+ *
+ * - the raw secret appears exactly once, because the backend returns it
+ * exactly once and a panel that discarded it would leave the credential
+ * unrecoverable;
+ * - a load failure renders an error and no rows, because a fabricated row
+ * invites someone to trust or revoke a credential that does not exist;
+ * - a failed revoke leaves the row showing as active, because the reverse
+ * tells an administrator a live provisioning key is dead.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+const mockList = vi.hoisted(() => vi.fn());
+const mockCreate = vi.hoisted(() => vi.fn());
+const mockRotate = vi.hoisted(() => vi.fn());
+const mockRevoke = vi.hoisted(() => vi.fn());
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ scimTokensApi: {
+ list: mockList,
+ create: mockCreate,
+ rotate: mockRotate,
+ revoke: mockRevoke,
+ },
+}));
+
+const mockToastError = vi.hoisted(() => vi.fn());
+vi.mock('react-hot-toast', () => ({
+ __esModule: true,
+ default: { success: vi.fn(), error: mockToastError },
+}));
+
+import { ScimTokensPanel } from './ScimTokensPanel';
+
+const TOKEN = {
+ id: 'cd1d6cf0-0000-0000-0000-000000000001',
+ name: 'corporate-directory',
+ prefix: 'aisoc_scim_AbCd',
+ org_id: null,
+ created_at: '2026-03-10T09:00:00Z',
+ last_used_at: null,
+ expires_at: null,
+ revoked_at: null,
+ rotated_from_id: null,
+ active: true,
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockList.mockResolvedValue([TOKEN]);
+});
+
+describe('ScimTokensPanel', () => {
+ it('lists the tenant’s credentials from the real endpoint', async () => {
+ render(<ScimTokensPanel />);
+
+ await waitFor(() => expect(mockList).toHaveBeenCalled());
+ expect(await screen.findByText('corporate-directory')).toBeInTheDocument();
+ expect(screen.getByText('aisoc_scim_AbCd')).toBeInTheDocument();
+ });
+
+ it('shows the raw secret once, with the reason it cannot be shown again', async () => {
+ mockCreate.mockResolvedValue({ ...TOKEN, token: 'aisoc_scim_the_only_time_this_exists' });
+ const user = userEvent.setup();
+ render(<ScimTokensPanel />);
+ await waitFor(() => expect(mockList).toHaveBeenCalled());
+
+ await user.type(screen.getByLabelText('Credential name'), 'okta');
+ await user.click(screen.getByRole('button', { name: /create credential/i }));
+
+ expect(await screen.findByText('aisoc_scim_the_only_time_this_exists')).toBeInTheDocument();
+ expect(screen.getByText(/cannot be shown again/i)).toBeInTheDocument();
+ expect(mockCreate).toHaveBeenCalledWith({ name: 'okta', expires_in_days: null });
+ });
+
+ it('rotates with the grace window the operator chose', async () => {
+ mockRotate.mockResolvedValue({ ...TOKEN, token: 'aisoc_scim_replacement' });
+ const user = userEvent.setup();
+ render(<ScimTokensPanel />);
+ await screen.findByText('corporate-directory');
+
+ await user.selectOptions(screen.getByLabelText('Rotation grace window'), '0');
+ await user.click(screen.getByRole('button', { name: /rotate/i }));
+
+ // Zero is the disclosure case: the old secret dies immediately and the
+ // next sync fails until the replacement is in place. Sending the
+ // default instead would leave a disclosed credential live for a day.
+ await waitFor(() => expect(mockRotate).toHaveBeenCalledWith(TOKEN.id, 0));
+ });
+
+ it('renders an error and no rows when the list cannot be loaded', async () => {
+ mockList.mockRejectedValue(new Error('upstream is down'));
+ render(<ScimTokensPanel />);
+
+ expect(await screen.findByText(/could not load scim credentials/i)).toBeInTheDocument();
+ expect(screen.queryByText('corporate-directory')).not.toBeInTheDocument();
+ });
+
+ it('leaves the row showing as active when a revoke fails', async () => {
+ mockRevoke.mockRejectedValue(new Error('nope'));
+ const user = userEvent.setup();
+ render(<ScimTokensPanel />);
+ await screen.findByText('corporate-directory');
+
+ await user.click(screen.getByRole('button', { name: /revoke/i }));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalled());
+ expect(screen.getByText('Active')).toBeInTheDocument();
+ expect(screen.getByText('corporate-directory')).toBeInTheDocument();
+ });
+
+ it('says a credential has never been used rather than dashing the cell', async () => {
+ // `last_used_at` is how an abandoned integration is found. A dash reads
+ // as "no data", and the fact here is "nobody has ever synced with this".
+ render(<ScimTokensPanel />);
+ expect(await screen.findByText('Never')).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/settings/ScimTokensPanel.tsx b/apps/web/src/components/settings/ScimTokensPanel.tsx
new file mode 100644
index 000000000..3fac45b64
--- /dev/null
+++ b/apps/web/src/components/settings/ScimTokensPanel.tsx
@@ -0,0 +1,306 @@
+'use client';
+
+/**
+ * SCIM credentials, minted from the console.
+ *
+ * `apps/docs/docs/operations/scim.md` told administrators to "mint one from
+ * the console, or through the API". The CRUD backend at
+ * `/api/v1/scim-tokens` shipped with the SCIM surface; the console had no
+ * binding to it at all, so the sentence described a surface that did not
+ * exist and the only working route was the curl command beneath it.
+ *
+ * Three properties this panel has to get right, because a provisioning
+ * credential is a standing key into the tenant's identity:
+ *
+ * - the raw secret is returned exactly once and is never recoverable, so
+ * it is shown once, here, with the fact stated rather than implied;
+ * - rotation is a *create*, not an edit: both secrets work for the grace
+ * window so a sync never fails in between, and the superseded one
+ * expires by itself;
+ * - a load failure renders an error, never a plausible list. A fabricated
+ * row invites an administrator to trust or revoke a credential that does
+ * not exist, and `last_used_at` is the field they would read to decide.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { format, formatDistanceToNow } from 'date-fns';
+import toast from 'react-hot-toast';
+
+import { scimTokensApi, type ScimTokenRecord } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+
+/** Offered rotation windows, in hours. */
+const GRACE_CHOICES = [
+ { hours: 24, label: '24 hours' },
+ { hours: 72, label: '72 hours' },
+ { hours: 0, label: 'Immediately (after a disclosure)' },
+];
+
+function inputClass() {
+ return 'w-full rounded-lg border border-gray-700 bg-gray-950 px-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:border-blue-500 focus:outline-none';
+}
+
+function describeError(err: unknown, fallback: string): string {
+ return err instanceof Error ? err.message : fallback;
+}
+
+export function ScimTokensPanel() {
+ const [tokens, setTokens] = useState<ScimTokenRecord[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [draftName, setDraftName] = useState('');
+ const [draftExpiry, setDraftExpiry] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [revealed, setRevealed] = useState<{ token: string; name: string } | null>(null);
+ const [graceHours, setGraceHours] = useState(24);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ setTokens(await scimTokensApi.list());
+ setLoadError(null);
+ } catch (err) {
+ setTokens([]);
+ setLoadError(describeError(err, 'Could not load SCIM credentials.'));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const create = async () => {
+ const name = draftName.trim();
+ if (!name) {
+ toast.error('Name the identity provider this credential is for');
+ return;
+ }
+ const days = draftExpiry.trim() ? Number(draftExpiry) : null;
+ if (days !== null && (!Number.isInteger(days) || days < 1 || days > 3650)) {
+ toast.error('Expiry must be a whole number of days between 1 and 3650');
+ return;
+ }
+ setBusy(true);
+ try {
+ const created = await scimTokensApi.create({ name, expires_in_days: days });
+ setRevealed({ token: created.token, name: created.name });
+ setDraftName('');
+ setDraftExpiry('');
+ await load();
+ toast.success('SCIM credential created');
+ } catch (err) {
+ toast.error(describeError(err, 'Could not create the credential'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const rotate = async (token: ScimTokenRecord) => {
+ setBusy(true);
+ try {
+ const created = await scimTokensApi.rotate(token.id, graceHours);
+ setRevealed({ token: created.token, name: created.name });
+ await load();
+ toast.success(
+ graceHours === 0
+ ? 'Rotated. The previous secret is revoked now, so the next sync fails until this one is in place.'
+ : `Rotated. Both secrets work for ${graceHours} hours.`,
+ );
+ } catch (err) {
+ toast.error(describeError(err, 'Could not rotate the credential'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const revoke = async (token: ScimTokenRecord) => {
+ setBusy(true);
+ try {
+ await scimTokensApi.revoke(token.id);
+ await load();
+ toast.success('Credential revoked. Provisioning with it stops at the next sync.');
+ } catch (err) {
+ // Never drop the row locally on failure: showing a credential as
+ // revoked while it still provisions is the dangerous direction.
+ toast.error(describeError(err, 'Could not revoke the credential'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const copy = (value: string) => {
+ if (typeof navigator !== 'undefined' && navigator.clipboard) {
+ navigator.clipboard.writeText(value).catch(() => undefined);
+ toast.success('Copied to clipboard');
+ }
+ };
+
+ return (
+ <div data-testid="scim-tokens-panel">
+ <div className="border-b border-gray-800 px-6 py-4">
+ <h2 className="text-base font-semibold text-gray-100">SCIM provisioning</h2>
+ <p className="mt-1 text-sm text-gray-500">
+ Bearer credentials your identity provider uses to create, update and
+ deprovision principals. Each one is scoped to this tenant.
+ </p>
+ </div>
+
+ <div className="space-y-5 px-6 py-5">
+ <div className="flex flex-col gap-3 rounded-lg border border-gray-800 bg-gray-950/40 p-4 sm:flex-row sm:items-end">
+ <label className="flex-1 text-sm">
+ <span className="mb-1 block text-gray-400">Name</span>
+ <input
+ className={inputClass()}
+ value={draftName}
+ onChange={(e) => setDraftName(e.target.value)}
+ placeholder="e.g. corporate-directory"
+ aria-label="Credential name"
+ />
+ </label>
+ <label className="text-sm sm:w-48">
+ <span className="mb-1 block text-gray-400">Expires in (days)</span>
+ <input
+ className={inputClass()}
+ value={draftExpiry}
+ onChange={(e) => setDraftExpiry(e.target.value)}
+ placeholder="Leave blank for no expiry"
+ inputMode="numeric"
+ aria-label="Expires in days"
+ />
+ </label>
+ <button
+ type="button"
+ onClick={() => void create()}
+ disabled={busy}
+ className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500 disabled:opacity-50"
+ >
+ {busy ? 'Working…' : 'Create credential'}
+ </button>
+ </div>
+
+ {revealed ? (
+ <div className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-4">
+ <p className="text-sm font-medium text-amber-200">
+ Copy this now. It is stored as a digest and cannot be shown again
+ — if it is lost, rotate.
+ </p>
+ <p className="mt-1 text-xs text-amber-300/80">{revealed.name}</p>
+ <div className="mt-3 flex items-center gap-2">
+ <code className="block flex-1 truncate rounded bg-gray-950 px-3 py-2 font-mono text-sm text-amber-100 ring-1 ring-amber-500/30">
+ {revealed.token}
+ </code>
+ <button
+ type="button"
+ onClick={() => copy(revealed.token)}
+ className="rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-sm text-gray-200 hover:bg-gray-800"
+ >
+ Copy
+ </button>
+ <button
+ type="button"
+ onClick={() => setRevealed(null)}
+ className="rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-sm text-gray-200 hover:bg-gray-800"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ ) : null}
+
+ <label className="flex items-center gap-2 text-xs text-gray-500">
+ Rotation grace window
+ <select
+ className="rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200"
+ value={graceHours}
+ onChange={(e) => setGraceHours(Number(e.target.value))}
+ aria-label="Rotation grace window"
+ >
+ {GRACE_CHOICES.map((choice) => (
+ <option key={choice.hours} value={choice.hours}>
+ {choice.label}
+ </option>
+ ))}
+ </select>
+ </label>
+
+ {loadError ? (
+ <EmptyState title="Could not load SCIM credentials" description={loadError} />
+ ) : loading ? (
+ <EmptyState title="Loading SCIM credentials…" description="" />
+ ) : tokens.length === 0 ? (
+ <EmptyState
+ title="No SCIM credentials yet"
+ description="Create one above, then paste it into your identity provider alongside this deployment's /scim/v2 base URL."
+ />
+ ) : (
+ <div className="overflow-hidden rounded-lg border border-gray-800">
+ <table className="w-full text-sm">
+ <thead className="bg-gray-900/60 text-xs uppercase tracking-wide text-gray-500">
+ <tr>
+ <th className="px-4 py-2 text-left">Name</th>
+ <th className="px-4 py-2 text-left">Prefix</th>
+ <th className="px-4 py-2 text-left">State</th>
+ <th className="px-4 py-2 text-left">Created</th>
+ <th className="px-4 py-2 text-left">Last used</th>
+ <th className="px-4 py-2 text-right">Actions</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-800 bg-gray-950/40">
+ {tokens.map((token) => (
+ <tr key={token.id}>
+ <td className="px-4 py-3 font-medium text-gray-100">{token.name}</td>
+ <td className="px-4 py-3 font-mono text-xs text-gray-400">{token.prefix}</td>
+ <td className="px-4 py-3 text-xs">
+ <span
+ className={
+ token.active
+ ? 'rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-300 ring-1 ring-emerald-500/30'
+ : 'rounded bg-gray-800 px-1.5 py-0.5 text-gray-400 ring-1 ring-gray-700'
+ }
+ >
+ {token.active ? 'Active' : token.revoked_at ? 'Revoked' : 'Expired'}
+ </span>
+ </td>
+ <td className="px-4 py-3 text-xs text-gray-400" suppressHydrationWarning>
+ {format(new Date(token.created_at), 'PPP')}
+ </td>
+ <td className="px-4 py-3 text-xs text-gray-400" suppressHydrationWarning>
+ {/* A credential nobody has used for months is a standing
+ key with no owner, which is why this column exists.
+ "Never" is a fact; an em dash would hide it. */}
+ {token.last_used_at
+ ? formatDistanceToNow(new Date(token.last_used_at), { addSuffix: true })
+ : 'Never'}
+ </td>
+ <td className="px-4 py-3 text-right">
+ <div className="flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={() => void rotate(token)}
+ disabled={busy || !token.active}
+ className="rounded border border-gray-700 bg-gray-900 px-2 py-1 text-xs text-gray-200 hover:bg-gray-800 disabled:opacity-40"
+ >
+ Rotate
+ </button>
+ <button
+ type="button"
+ onClick={() => void revoke(token)}
+ disabled={busy || !token.active}
+ className="rounded border border-red-900/60 bg-red-950/40 px-2 py-1 text-xs text-red-300 hover:bg-red-950/70 disabled:opacity-40"
+ >
+ Revoke
+ </button>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index 92078163a..d5f290a66 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -48,6 +48,7 @@ import { EmptyState } from '@/components/ui/EmptyState';
import { AutonomyPolicyPanel } from '@/components/settings/AutonomyPolicy';
import { AssignRoleModal } from '@/components/settings/AssignRoleModal';
import { RetroHuntSettingsPanel } from './RetroHuntSettings';
+import { ScimTokensPanel } from './ScimTokensPanel';
import { useTheme, type ThemePreference } from '@/components/theme/ThemeProvider';
import { canUseDemoData } from '@/lib/demoFallback';
import { rbacApi, authApi } from '@/lib/api';
@@ -60,6 +61,7 @@ type TabId =
| 'integrations'
| 'autonomy'
| 'api-keys'
+ | 'scim'
| 'notifications'
| 'appearance'
| 'deployment'
@@ -315,6 +317,12 @@ const TABS: { id: TabId; label: string; description: string }[] = [
label: 'API keys',
description: 'Programmatic access for pipelines and integrations.',
},
+ {
+ id: 'scim',
+ label: 'SCIM provisioning',
+ description:
+ 'Bearer credentials your identity provider uses to create and deprovision principals.',
+ },
{
id: 'notifications',
label: 'Notifications',
@@ -412,6 +420,7 @@ export function SettingsView() {
</div>
)}
{tab === 'api-keys' && <ApiKeysPanel />}
+ {tab === 'scim' && <ScimTokensPanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'appearance' && <AppearancePanel />}
{tab === 'deployment' && <DeploymentAIPanel />}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 468b251e4..ebccf9b5e 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -6840,6 +6840,59 @@ export const apiKeysApi = {
request<void>(`/api/v1/api-keys/${id}`, { method: 'DELETE' }),
};
+// ─── SCIM credentials ────────────────────────────────────────────────────────
+//
+// `apps/docs/docs/operations/scim.md` told administrators to "mint one from
+// the console". The CRUD backend at `/api/v1/scim-tokens` had existed since
+// the SCIM surface shipped and the console had no binding to it at all — not
+// a panel, not a client function, not a string containing "scim" anywhere
+// under `apps/web/src` — so the only way to obtain a credential was the curl
+// command two paragraphs further down.
+
+export interface ScimTokenRecord {
+ id: string;
+ name: string;
+ /** Display prefix. The secret itself is stored as a digest and never returned. */
+ prefix: string;
+ org_id: string | null;
+ created_at: string;
+ last_used_at: string | null;
+ expires_at: string | null;
+ revoked_at: string | null;
+ rotated_from_id: string | null;
+ active: boolean;
+}
+
+/** Create and rotate both return the raw secret, exactly once. */
+export interface CreatedScimToken extends ScimTokenRecord {
+ token: string;
+}
+
+export const scimTokensApi = {
+ list: () => request<ScimTokenRecord[]>('/api/v1/scim-tokens'),
+
+ create: (data: { name: string; expires_in_days?: number | null }) =>
+ request<CreatedScimToken>('/api/v1/scim-tokens', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ }),
+
+ /**
+ * Both secrets work for `grace_hours`, so the replacement can be pasted
+ * into the identity provider without a failed sync in between. Zero
+ * revokes the old one at once, which is the right trade after a
+ * disclosure and the wrong one otherwise.
+ */
+ rotate: (id: string, grace_hours: number) =>
+ request<CreatedScimToken>(`/api/v1/scim-tokens/${id}/rotate`, {
+ method: 'POST',
+ body: JSON.stringify({ grace_hours }),
+ }),
+
+ revoke: (id: string) =>
+ request<void>(`/api/v1/scim-tokens/${id}`, { method: 'DELETE' }),
+};
+
// ─── Replay evaluation (gap-closure Phase 1.4) ───────────────────────────────
//
// Wraps `services/api/app/api/v1/endpoints/evaluations.py`: measure triage
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index ab8bb0004..b2b2279b5 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -216,11 +216,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A skill cannot be activated without a completed backtest of the exact version, graded over alerts that skill matches | `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. `TestActivationReadsTheBacktest` seeds the two replay runs and refuses activation when either is missing, still going or failed, and when the graded window holds no alert the skill's match block selects; `test_the_delta_is_computed_over_the_matched_alerts_and_not_the_window` pins the matched subset at 4 of a 20-alert window and fails when the comparison widens to the window. `TestMatchBlockSelection` covers each of the four match conditions) + `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) | core | 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. **Widened by fix-pass 3.8:** the version check alone was satisfied by two ids naming two crashed runs, or a window holding nothing the skill applies to, so activation now opens both runs. The subset is the skill's declared match scope read from each decision's recorded evidence, which is **not** a record of which alerts triage actually applied the skill to: a replay decision does not carry the skill that steered it, so the scope can be wider than the set production steered and never narrower |
| 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) | core | 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) | core | 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) | core | 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) | core | 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}`) | core | 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 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) + `scim-live.yml` (the live suite runs at `ENVIRONMENT=test`, **not** `development`, which is in `AUTH_BYPASS_ENVIRONMENTS` — an uncredentialed request there resolves to a demo *admin*, inside the one suite whose purpose is proving the tenant comes from the credential; tenant B is asserted unable to read, PATCH or list the group of tenant A) | core | 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) + `scim-live.yml` (`check_scim_contract.py` cross-checks the doc's "mint one from the console" sentence against the console in **both** directions, proven able to fail by deleting the render site and by rewording the doc; the sentence was true of no release before this one) + `ci.yml` web job (`ScimTokensPanel.test.tsx` - the raw secret is shown exactly once with the reason it cannot be shown again, the chosen grace window reaches the API, a load failure renders an error and no rows, and a failed revoke leaves the row showing as active) | core | 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}`) + `scim-live.yml` (`TestDeprovisioningEndsAccess` repeats all four against **real Postgres through the real application**, reading `users.is_active`, the `TIMESTAMPTZ` stamp and the `api_keys` rows out of the database rather than off the response, with a negative control that makes `_apply_active` a no-op — the handler then still answers 200 with a correct-looking resource, which is the shape a response-only assertion cannot see) | core | 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) | core | 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) | core | 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" |
+| 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) + `scim-live.yml` (`TestPatchInBothProvidersDialects` and `TestGroupMembershipInBothProvidersDialects` run Okta's and Entra's PATCH and membership shapes against real Postgres, asserting on `users.is_active` and on `aisoc_scim_group_members` rather than on the response; the vendor payloads are pinned against the offline suite's copies so the two cannot drift; the job refuses to collect when `ISOLATION_REQUIRE_LIVE` is set without a DSN, and a following step reads the JUnit counts and fails on any skip, because a suite that skipped every case exits 0) | core | 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" |
| No principal can confer a role, scope or organisation membership beyond the authority it was itself admitted on, and the wildcard roles are unreachable from any request | `apps/docs/docs/operations/security.md` (Role grants are scoped to the granter); GHSA-pm3f-h6gc-rvgp; GHSA-4gx4-x7gm-4xq8 | `isolation.yml` (`check_role_grant_scope.py` asks of every handler binding a request model that declares `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` whether it reaches `app.core.role_grants`, checks each waiver still covers a live handler, and derives the refused set from `ROLE_PERMISSIONS` so a role declared with the wildcard later is un-grantable the moment it is declared; and asks of every call to `authorize_role_grant`, `authorize_role_change` or `authorize_permission_grant` whether it passes `granter_permissions=`, since reaching the chokepoint while handing it the caller's *static* role measures the grant against an authority the caller was not admitted on; seven injected drifts prove it fails, and run against the pre-fix tree it names all nine handlers and all six under-authorised call sites) + `ci.yml` api job (`test_role_grant_scope.py` calls the shipped handlers and asserts both directions per call site — the escalating request is refused and nothing is written, a legitimate grant still lands; 16 of its 28 tests fail against the vulnerable tree, every one of them for the grant succeeding rather than for a missing symbol) + `ci.yml` api job (`test_role_grant_effective_permissions.py` drives the same handlers with a principal whose database permissions are narrower than its static role; 7 of its 10 tests fail against the pre-fix tree, each for the escalation landing, and the other 3 hold the positive direction so a tenant with no RBAC rows keeps conferring what its role confers) | core | GATED | Scoped to grants a *request* makes. `scripts/bootstrap_admin.py` still mints a wildcard role out of band with database credentials, which is deliberate: it is the only path left, and it is not reachable over HTTP |
| An uploaded brand asset cannot execute, and is never fetched from a third party | `plans/aisoc_gap_closure_plan.plan.md` (13.2); `apps/docs/docs/operations/white-label.md` (SVG uploads are sanitised) | `ci.yml` api job (`test_svg_sanitizer.py`, 29 cases written as attacks rather than round trips: `<script>`, a namespace-qualified `<svg:script>` that a bare-name comparison misses, event handlers, `<foreignObject>` in well-formed XML, `<animate attributeName="href">`, `<set>`, an external `<use xlink:href>`, a remote `<image>`, `@import`, a `fill="url(https://…)"` paint server, `javascript:` in an `<a>`, a billion-laughs DTD, an XXE entity and a bare DOCTYPE. A benign logo is asserted to survive **intact**, because a sanitiser that removes everything is safe and useless) + `isolation.yml` (`check_whitelabel_metering.py` refuses any script-capable element or `on*` attribute entering the allowlist, and refuses a remote scheme in the logo reference; proven able to fail by injecting each) | core | GATED | Allowlist rather than denylist: a denylist of `<script>` passes while `<foreignObject>` renders arbitrary HTML. DTD and entity declarations are refused on a byte scan before parsing, which removes the expansion class rather than bounding it |
| A white-labelled organisation's console and PDF report carry its branding | `plans/aisoc_gap_closure_plan.plan.md` (13.2, Done when); `apps/docs/docs/operations/white-label.md` | `ci.yml` api job (`test_branding.py` renders the digest HTML that becomes the PDF and asserts the product name, the palette and the logo are present **and** that the platform wordmark is gone, since a report showing both is co-branded by accident; a separate case asserts the rendered report contains **no** external URL at all) + `web` job (`SidebarBranding.test.tsx` renders the real console shell against a branded API response and reads the wordmark out of the DOM, mocking the API client rather than the hook so the wiring is inside the test) | core | GATED | The PDF is this HTML through WeasyPrint, so asserting on the HTML asserts on the PDF without requiring the native stack in CI. Email approvals and ChatOps read the same resolved `sender_name` and are **not** covered end to end; the doc says so rather than implying they are |
diff --git a/scripts/check_scim_contract.py b/scripts/check_scim_contract.py
index 6060b1758..7e76c9c24 100644
--- a/scripts/check_scim_contract.py
+++ b/scripts/check_scim_contract.py
@@ -38,6 +38,16 @@ Beyond the documents, two more disagreements would each be silent:
``main.py``, and ``test_scim_provisioning.py`` proves reachability by
sending real requests.
+*the console the doc promises*
+ ``apps/docs/docs/operations/scim.md`` told administrators to "mint one
+ from the console". ``/api/v1/scim-tokens`` had shipped with the SCIM
+ surface and nothing under ``apps/web/src`` referenced it — not a panel,
+ not a client function, not the string ``scim`` — so the sentence
+ described a surface that did not exist and the only working route was
+ the curl command beneath it. Checked in both directions: a doc claiming
+ a console that is gone fails, and so does a console surface the doc
+ never mentions, because an unmentioned panel is one nobody finds.
+
Run: python3 scripts/check_scim_contract.py [--self-test]
"""
@@ -65,6 +75,24 @@ SECURITY = REPO_ROOT / "services/api/app/core/security.py"
#: became one.
ROLE_GRANTS = REPO_ROOT / "services/api/app/core/role_grants.py"
MAIN = REPO_ROOT / "services/api/app/main.py"
+#: The console surface and the doc that promises it. Both sides are named
+#: so the check runs in the direction that drifts: the doc is edited far
+#: more often than the panel, and a panel deleted in a refactor is exactly
+#: as damaging as a doc sentence that was never true.
+CONSOLE_PANEL = REPO_ROOT / "apps/web/src/components/settings/ScimTokensPanel.tsx"
+CONSOLE_SETTINGS = REPO_ROOT / "apps/web/src/components/settings/SettingsView.tsx"
+CONSOLE_CLIENT = REPO_ROOT / "apps/web/src/lib/api.ts"
+SCIM_DOC = REPO_ROOT / "apps/docs/docs/operations/scim.md"
+
+#: The sentence the console has to make true. Matched literally: a reworded
+#: claim should re-run this decision rather than inherit it.
+CONSOLE_CLAIM = "Mint one from\nthe console"
+
+#: The endpoint prefix a console panel must call for the claim to hold. A
+#: panel that renders a form and posts nowhere is the shape this repository
+#: already shipped once, minting an `aisoc_live_…` string in the browser
+#: that authenticated nothing.
+CONSOLE_ENDPOINT = "/api/v1/scim-tokens"
#: Operations RFC 7644 defines that this deployment intends to serve, mapped
#: to the ``ServiceProviderConfig`` key that advertises them. A key absent
@@ -344,7 +372,7 @@ def _group_rule_roles(tree: ast.Module) -> set[str]:
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}
+ counts = {"routes": 0, "capabilities": 0, "roles": 0, "mutating_handlers": 0, "console_bindings": 0}
router_path = root / ROUTER.relative_to(REPO_ROOT)
resources_path = root / RESOURCES.relative_to(REPO_ROOT)
@@ -442,9 +470,65 @@ def audit(root: Path) -> tuple[list[str], dict[str, int]]:
"nor records why a directory group may not confer it"
)
+ problems.extend(_console_problems(root, counts))
+
return problems, counts
+def _console_problems(root: Path, counts: dict[str, int]) -> list[str]:
+ """The doc's "mint one from the console" claim, against the console.
+
+ Both directions. The doc promising a panel that is gone sends an
+ administrator looking for a surface that is not there; a panel the doc
+ never mentions is one nobody finds, and the curl command stays the only
+ documented route.
+ """
+ problems: list[str] = []
+ doc_path = root / SCIM_DOC.relative_to(REPO_ROOT)
+ if not doc_path.is_file():
+ return [f"{SCIM_DOC.name} is absent, so the console claim cannot be checked either way"]
+
+ doc = doc_path.read_text(encoding="utf-8")
+ claims_console = CONSOLE_CLAIM in doc
+
+ # A binding is the endpoint named in the client *and* a panel that calls
+ # the client *and* the panel reachable from the settings surface. Any one
+ # of the three alone is the "exists unwired" shape: a client function
+ # nothing imports, or a component no route renders.
+ bindings: list[str] = []
+ client_path = root / CONSOLE_CLIENT.relative_to(REPO_ROOT)
+ if client_path.is_file() and CONSOLE_ENDPOINT in client_path.read_text(encoding="utf-8"):
+ bindings.append("client")
+
+ panel_path = root / CONSOLE_PANEL.relative_to(REPO_ROOT)
+ if panel_path.is_file() and "scimTokensApi" in panel_path.read_text(encoding="utf-8"):
+ bindings.append("panel")
+
+ # The *rendering*, not the import. An imported component nothing renders
+ # is the "exists unwired" shape, and it reads in a diff exactly like a
+ # working one.
+ settings_path = root / CONSOLE_SETTINGS.relative_to(REPO_ROOT)
+ if settings_path.is_file() and "<ScimTokensPanel" in settings_path.read_text(encoding="utf-8"):
+ bindings.append("settings")
+
+ counts["console_bindings"] = len(bindings)
+ wired = len(bindings) == 3
+
+ if claims_console and not wired:
+ missing = sorted({"client", "panel", "settings"} - set(bindings))
+ problems.append(
+ f"{SCIM_DOC.name} tells administrators to mint a SCIM credential from the console, and the console is "
+ f"missing its {', '.join(missing)}. Either restore the surface or reword the doc; the curl command below "
+ "it is then the only documented route."
+ )
+ if wired and not claims_console:
+ problems.append(
+ f"the console can mint SCIM credentials and {SCIM_DOC.name} no longer says so. A panel nobody is told "
+ "about is one nobody finds."
+ )
+ return problems
+
+
def _self_test_cases() -> list[tuple[str, bool]]:
"""Prove the gate detects each drift it exists to catch.
@@ -488,13 +572,39 @@ def _self_test_cases() -> list[tuple[str, bool]]:
'@router.patch("/Users/{user_id}")',
'@router.post("/Users/{user_id}/patched")',
),
+ (
+ # The defect this direction was added for: the doc said the
+ # console could mint a credential for four releases while
+ # nothing under apps/web/src mentioned SCIM at all.
+ "a doc promising a console panel that is not wired is reported",
+ CONSOLE_SETTINGS,
+ "<ScimTokensPanel />",
+ "null /* panel imported, never rendered */",
+ ),
+ (
+ "a console panel the doc does not mention is reported",
+ SCIM_DOC,
+ CONSOLE_CLAIM,
+ "Mint one\nthrough the API",
+ ),
]
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, ROLE_GRANTS, MAIN}:
+ for source in {
+ ROUTER,
+ RESOURCES,
+ ROLES,
+ SECURITY,
+ ROLE_GRANTS,
+ MAIN,
+ CONSOLE_PANEL,
+ CONSOLE_SETTINGS,
+ CONSOLE_CLIENT,
+ SCIM_DOC,
+ }:
destination = tree / source.relative_to(REPO_ROOT)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
@@ -520,7 +630,8 @@ def main() -> int:
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)"
+ f"{counts['mutating_handlers']} mutating handler(s), {counts['roles']} enforced role(s) and "
+ f"{counts['console_bindings']}/3 console credential binding(s)"
)
# "found nothing" and "scanned nothing" must not print the same word.
diff --git a/scripts/check_test_discovery.py b/scripts/check_test_discovery.py
index 1e7ab742e..f91e26648 100644
--- a/scripts/check_test_discovery.py
+++ b/scripts/check_test_discovery.py
@@ -136,6 +136,9 @@ _PIP_INSTALL = re.compile(r"\b(?:pip3?|python3?(?:\.\d+)?\s+-m\s+pip)\s+install\
#: test *name*, which this gate does not model — it is a filter a developer
#: types, not a standing property of a workflow, and no workflow here uses it.
#: ``-m`` is different and is captured below.
+#: A shell redirection: `>f`, `>>f`, `2>f`, `<f`, or the bare operator.
+_REDIRECT = re.compile(r"^(?:[0-9]*>>?|<|&>)")
+
_OPTS_WITH_VALUE = frozenset({"-k", "-p", "-n", "--rootdir", "--cov", "--cov-config", "--cov-report", "--junitxml", "--tb", "-W"})
@@ -296,6 +299,16 @@ def _split_args(args: list[str]) -> tuple[list[str], list[str], str]:
index += 1
elif token.startswith("-"):
pass
+ elif _REDIRECT.match(token):
+ # A redirection, not a path. `shlex` does not know shell syntax,
+ # so `-q \<newline>--junitxml=… >/dev/null` tokenised the target
+ # as a positional argument and the gate reported the step as
+ # naming `services/api/>/dev/null`, a path that is not in the
+ # tree — a real invocation failing a gate that had mis-read it.
+ # `>file` is one token, `> file` is two, so a bare operator also
+ # consumes the token after it.
+ if token in {">", ">>", "<", "2>", "2>>", "&>"} and index + 1 < len(args):
+ index += 1
else:
paths.append(token)
index += 1
diff --git a/tests/isolation/test_scim_live.py b/tests/isolation/test_scim_live.py
index 609d3ac88..738ae6452 100644
--- a/tests/isolation/test_scim_live.py
+++ b/tests/isolation/test_scim_live.py
@@ -27,17 +27,42 @@ This suite uses `app.main:create_application` and real Postgres, so the
types, the constraints, the middleware and the auth are the ones a
deployment runs.
+What it covers, and why the three additions matter
+---------------------------------------------------
+Create, list and discovery were here from the start. PATCH, group
+membership and deactivation were not, and those are the three operations
+whose correctness depends on the things SQLite cannot reproduce:
+
+* **PATCH** is how both providers deactivate, and the two send the value
+ in incompatible shapes — Okta an object with no `path` and a lowercase
+ `op`, Entra an explicit `path` and the *string* `"False"`, for which
+ `bool("False")` is `True`. The effect is a write to `users.is_active`
+ and a `TIMESTAMPTZ` stamp, neither of which a shimmed column proves.
+* **Group membership** writes `aisoc_scim_group_members`, a composite
+ primary key over two `UUID` columns with cascading foreign keys. The
+ offline harness compiles both types away, and the two providers remove
+ a member in opposite arrangements (Okta through a path filter with no
+ value, Entra with `path: "members"` and the id in a value array).
+* **Deactivation** is the one that has to be true: it revokes API keys by
+ count, stamps `sessions_revoked_at`, and `DELETE` must deactivate
+ rather than erase. The whole point is a row that survives with access
+ withdrawn, which only a real foreign-key graph can demonstrate.
+
The negative control
--------------------
`test_an_unauthenticated_request_is_refused` and
`test_another_tenants_token_cannot_read_these_users` are what stop the
positive assertions passing for the wrong reason: a surface that returned
everything to everyone would satisfy "the user I created is listed".
+`TestGroupsAreTenantScoped` does the same for the group surface, which has
+its own list handler and would not be covered by the user one.
"""
from __future__ import annotations
+import ast
import os
+import pathlib
import uuid
import pytest
@@ -66,7 +91,51 @@ pytestmark = [
),
]
+# A skip in a job that exists to run live is a green report over nothing.
+#
+# The skip above is right for the offline collection job and wrong for
+# `scim-live.yml`, and pytest cannot tell them apart — so the live job sets
+# this flag and the suite refuses to collect rather than skipping. Raising
+# at import is deliberate: a collection error is red, where a skipped
+# module is not.
+#
+# `wet-eval.yml` reported success on eight consecutive weekly runs with
+# every real step skipped. This is the same shape, one directory down.
+if os.environ.get("ISOLATION_REQUIRE_LIVE", "").strip() and not os.environ.get("ISOLATION_SCIM_DSN", "").strip():
+ raise RuntimeError(
+ "ISOLATION_REQUIRE_LIVE is set and ISOLATION_SCIM_DSN is not. This job is supposed to "
+ "exercise SCIM against a real Postgres, and skipping would report success having run nothing."
+ )
+
SCIM_CONTENT_TYPE = "application/scim+json"
+PATCH_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:PatchOp"
+USER_SCHEMA = "urn:ietf:params:scim:schemas:core:2.0:User"
+GROUP_SCHEMA = "urn:ietf:params:scim:schemas:core:2.0:Group"
+
+# The two providers' request shapes, transcribed rather than paraphrased.
+#
+# Copied from `services/api/tests/test_scim_provisioning.py` rather than
+# imported: that module installs `@compiles(..., "sqlite")` shims and builds
+# its own app at import time, and importing it here would apply both to a
+# suite whose entire purpose is to avoid them.
+# `TestTheVendorPayloadsHaveNotDrifted` reads the offline module's source
+# and fails if the two copies stop agreeing.
+OKTA_DEACTIVATE = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "value": {"active": False}}]}
+ENTRA_DEACTIVATE = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Replace", "path": "active", "value": "False"}]}
+ENTRA_DEACTIVATE_BOOL = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Replace", "path": "active", "value": False}]}
+OKTA_ADD_MEMBER = {
+ "schemas": [PATCH_SCHEMA],
+ "Operations": [{"op": "add", "path": "members", "value": [{"value": "__USER__", "display": "[email protected]"}]}],
+}
+OKTA_REMOVE_MEMBER = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "remove", "path": 'members[value eq "__USER__"]'}]}
+ENTRA_ADD_MEMBER = {"schemas": [PATCH_SCHEMA], "Operations": [{"op": "Add", "path": "members", "value": [{"value": "__USER__"}]}]}
+ENTRA_REMOVE_MEMBER = {
+ "schemas": [PATCH_SCHEMA],
+ "Operations": [{"op": "Remove", "path": "members", "value": [{"value": "__USER__"}]}],
+}
+
+#: Where the offline copies live, for the drift pin.
+OFFLINE_SUITE = pathlib.Path(__file__).resolve().parents[2] / "services" / "api" / "tests" / "test_scim_provisioning.py"
def _dsn() -> str:
@@ -76,6 +145,13 @@ def _dsn() -> str:
return value
+def _with_user(payload: dict, user_id: str) -> dict:
+ """Substitute the member placeholder, including inside a path filter."""
+ import json
+
+ return json.loads(json.dumps(payload).replace("__USER__", user_id))
+
+
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def app_client():
"""The real application, against real Postgres.
@@ -85,11 +161,17 @@ async def app_client():
graph are part of what a SCIM client talks to, and a harness that
skips them is testing a different surface.
"""
- pytest.importorskip("httpx")
+ import httpx
+
os.environ["DATABASE_URL"] = _dsn()
- os.environ.setdefault("ENVIRONMENT", "development")
+ # Not `development`, which is in `AUTH_BYPASS_ENVIRONMENTS`: an
+ # uncredentialed request there resolves to a demo **admin**, inside the
+ # one suite whose purpose is proving the tenant comes from the
+ # credential. `test_an_unauthenticated_request_is_refused` would then be
+ # asserting against a bypass rather than against SCIM's own auth.
+ # `"test"` was removed from that bypass set for exactly this reason.
+ os.environ["ENVIRONMENT"] = "test"
- import httpx
from app.main import create_application
application = create_application()
@@ -107,7 +189,10 @@ async def db():
and the teardown of one fails with "Event loop is closed" while
telling you nothing about the code under test.
"""
- pytest.importorskip("asyncpg")
+ # Imported, not `importorskip`ed: a missing driver in the job that is
+ # supposed to be live is a broken job, and turning it into a skip makes
+ # that report green.
+ import asyncpg # noqa: F401
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
engine = create_async_engine(_dsn(), future=True)
@@ -262,6 +347,385 @@ class TestTenantIsolation:
assert email not in theirs.text, "tenant B's SCIM token listed a user provisioned by tenant A"
+async def _provision(app_client, token: str, email: str | None = None) -> tuple[str, str]: # noqa: ANN001
+ """Create a user over SCIM and return `(id, email)`."""
+ address = email or f"ci-{uuid.uuid4().hex[:8]}@example.com"
+ created = await app_client.post(
+ "/scim/v2/Users",
+ headers=_auth(token),
+ json={"schemas": [USER_SCHEMA], "userName": address, "active": True},
+ )
+ assert created.status_code == 201, f"{created.status_code}: {created.text[:300]}"
+ return created.json()["id"], address
+
+
+async def _group(app_client, token: str, name: str | None = None) -> str:
+ """Create a group over SCIM and return its id."""
+ created = await app_client.post(
+ "/scim/v2/Groups",
+ headers=_auth(token),
+ json={"schemas": [GROUP_SCHEMA], "displayName": name or f"AiSOC-SOC-Analysts-{uuid.uuid4().hex[:6]}"},
+ )
+ assert created.status_code == 201, f"{created.status_code}: {created.text[:300]}"
+ return created.json()["id"]
+
+
+async def _members(db, group_id: str) -> set[str]: # noqa: ANN001
+ """Membership read straight out of Postgres, not off the response.
+
+ The response is the handler describing itself. The table is what the
+ next sync and every authorisation decision read.
+ """
+ import sqlalchemy
+
+ rows = await db.execute(
+ sqlalchemy.text("SELECT user_id FROM aisoc_scim_group_members WHERE group_id = CAST(:g AS uuid)"),
+ {"g": group_id},
+ )
+ await db.commit()
+ return {str(row[0]) for row in rows}
+
+
+class TestPatchInBothProvidersDialects:
+ """PATCH is how Okta and Entra deactivate, and they disagree about how.
+
+ Both bodies are asserted against `users.is_active` in Postgres rather
+ than against the response, because a handler that returns a correct
+ resource and writes nothing is the shape a 200 hides.
+ """
+
+ @pytest.mark.parametrize(
+ ("label", "body"),
+ [
+ # No `path`, value is an object, `op` lowercase.
+ ("okta", OKTA_DEACTIVATE),
+ # Explicit `path`, `op` capitalised, value is the *string*
+ # "False" — for which `bool("False")` is True, so a naive read
+ # deactivates nothing and returns 200.
+ ("entra-string", ENTRA_DEACTIVATE),
+ # Entra also sends a real boolean in some versions.
+ ("entra-bool", ENTRA_DEACTIVATE_BOOL),
+ ],
+ )
+ async def test_a_deactivating_patch_turns_the_row_inactive(self, app_client, db, tenants, label, body) -> None: # noqa: ANN001
+ import sqlalchemy
+
+ user_id, email = await _provision(app_client, tenants["token_a"])
+
+ before = await db.execute(sqlalchemy.text("SELECT is_active FROM users WHERE email = :e"), {"e": email})
+ await db.commit()
+ assert before.scalar_one() is True, f"{label}: the user was not active to begin with"
+
+ patched = await app_client.patch(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_a"]), json=body)
+ assert patched.status_code == 200, f"{label}: {patched.status_code}: {patched.text[:300]}"
+
+ after = await db.execute(sqlalchemy.text("SELECT is_active FROM users WHERE email = :e"), {"e": email})
+ await db.commit()
+ assert after.scalar_one() is False, f"{label}: SCIM answered 200 and left the account active"
+
+ async def test_a_patch_can_rename_a_principal(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """A directory rename is the other PATCH a provider sends routinely,
+ and it writes the column every other surface joins on."""
+ import sqlalchemy
+
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ renamed = f"ci-{uuid.uuid4().hex[:8]}@example.com"
+
+ response = await app_client.patch(
+ f"/scim/v2/Users/{user_id}",
+ headers=_auth(tenants["token_a"]),
+ json={"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "path": "userName", "value": renamed}]},
+ )
+ assert response.status_code == 200, f"{response.status_code}: {response.text[:300]}"
+
+ rows = await db.execute(sqlalchemy.text("SELECT email FROM users WHERE id = CAST(:i AS uuid)"), {"i": user_id})
+ await db.commit()
+ assert rows.scalar_one() == renamed
+
+ async def test_another_tenants_token_cannot_patch_this_user(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """The isolation claim on the write side.
+
+ Reading is covered below; a surface that scoped its list and not
+ its PATCH would let one customer deactivate another's staff.
+ """
+ import sqlalchemy
+
+ user_id, email = await _provision(app_client, tenants["token_a"])
+
+ response = await app_client.patch(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_b"]), json=OKTA_DEACTIVATE)
+ assert response.status_code == 404, f"tenant B reached tenant A's user with {response.status_code}"
+
+ rows = await db.execute(sqlalchemy.text("SELECT is_active FROM users WHERE email = :e"), {"e": email})
+ await db.commit()
+ assert rows.scalar_one() is True, "tenant B's PATCH deactivated tenant A's user"
+
+
+class TestGroupMembershipInBothProvidersDialects:
+ """`aisoc_scim_group_members` is a composite key over two `UUID`
+ columns with cascading foreign keys — the shape the offline harness
+ compiles away. Every assertion reads the table.
+ """
+
+ @pytest.mark.parametrize(("label", "body"), [("okta", OKTA_ADD_MEMBER), ("entra", ENTRA_ADD_MEMBER)])
+ async def test_adding_a_member_writes_the_row(self, app_client, db, tenants, label, body) -> None: # noqa: ANN001
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ group_id = await _group(app_client, tenants["token_a"])
+
+ assert await _members(db, group_id) == set(), f"{label}: the group was not empty to begin with"
+
+ response = await app_client.patch(
+ f"/scim/v2/Groups/{group_id}",
+ headers=_auth(tenants["token_a"]),
+ json=_with_user(body, user_id),
+ )
+ assert response.status_code == 200, f"{label}: {response.status_code}: {response.text[:300]}"
+ assert await _members(db, group_id) == {user_id}, f"{label}: the membership row was not written"
+
+ @pytest.mark.parametrize(
+ ("label", "removal"),
+ [
+ # Okta puts the id in a path filter and sends no `value` at all.
+ ("okta", OKTA_REMOVE_MEMBER),
+ # Entra names the attribute in `path` and the member in `value`
+ # — the opposite arrangement.
+ ("entra", ENTRA_REMOVE_MEMBER),
+ ],
+ )
+ async def test_removing_a_member_deletes_the_row(self, app_client, db, tenants, label, removal) -> None: # noqa: ANN001
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ group_id = await _group(app_client, tenants["token_a"])
+
+ added = await app_client.patch(
+ f"/scim/v2/Groups/{group_id}",
+ headers=_auth(tenants["token_a"]),
+ json=_with_user(OKTA_ADD_MEMBER, user_id),
+ )
+ assert added.status_code == 200
+ assert await _members(db, group_id) == {user_id}, f"{label}: nothing to remove, so the removal proves nothing"
+
+ response = await app_client.patch(
+ f"/scim/v2/Groups/{group_id}",
+ headers=_auth(tenants["token_a"]),
+ json=_with_user(removal, user_id),
+ )
+ assert response.status_code == 200, f"{label}: {response.status_code}: {response.text[:300]}"
+ assert await _members(db, group_id) == set(), f"{label}: the membership row survived the removal"
+
+ async def test_a_group_name_resolves_to_the_role_it_advertises(self, app_client, tenants) -> None: # noqa: ANN001
+ """The resolved role is returned on the resource so an administrator
+ can confirm what a group grants by reading the same response their
+ provider sees. A `null` there means it grants nothing."""
+ group_id = await _group(app_client, tenants["token_a"], name="AiSOC-SOC-Analysts")
+ response = await app_client.get(f"/scim/v2/Groups/{group_id}", headers=_auth(tenants["token_a"]))
+
+ assert response.status_code == 200
+ extension = response.json().get("urn:aisoc:params:scim:schemas:extension:2.0:Group", {})
+ assert extension.get("mappedRole") == "soc_analyst", response.text[:300]
+
+ async def test_a_group_name_matching_nothing_grants_nothing(self, app_client, tenants) -> None: # noqa: ANN001
+ """The control for the case above.
+
+ Without it, a resolver that returned a role for every name would
+ pass — and the set of people who can create a directory group is
+ larger than the set of AiSOC administrators.
+ """
+ group_id = await _group(app_client, tenants["token_a"], name=f"Bowling-Club-{uuid.uuid4().hex[:6]}")
+ response = await app_client.get(f"/scim/v2/Groups/{group_id}", headers=_auth(tenants["token_a"]))
+
+ assert response.status_code == 200
+ extension = response.json().get("urn:aisoc:params:scim:schemas:extension:2.0:Group", {})
+ assert extension.get("mappedRole") is None, response.text[:300]
+
+
+class TestGroupsAreTenantScoped:
+ async def test_another_tenants_token_cannot_read_this_group(self, app_client, tenants) -> None: # noqa: ANN001
+ """The group surface has its own list handler.
+
+ The user-listing control above says nothing about it, and a group
+ carries the membership that decides what a principal may do.
+ """
+ name = f"AiSOC-SOC-Leads-{uuid.uuid4().hex[:8]}"
+ await _group(app_client, tenants["token_a"], name=name)
+
+ theirs = await app_client.get("/scim/v2/Groups", headers=_auth(tenants["token_b"]))
+ assert theirs.status_code == 200
+ assert name not in theirs.text, "tenant B's SCIM token listed a group provisioned by tenant A"
+
+
+class TestDeprovisioningEndsAccess:
+ """Deactivation has to do three things, and the doc says all three.
+
+ The row surviving with access withdrawn is the whole design, so this
+ needs a real foreign-key graph rather than a shimmed one.
+ """
+
+ async def test_a_deactivation_revokes_the_principals_api_keys(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """An API key outlives a session and is reached by neither the
+ `is_active` flag nor the session-revocation stamp."""
+ import sqlalchemy
+
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ await db.execute(
+ sqlalchemy.text(
+ "INSERT INTO api_keys (id, tenant_id, user_id, name, key_prefix, hashed_key, is_active) "
+ "VALUES (gen_random_uuid(), CAST(:t AS uuid), CAST(:u AS uuid), 'ci', 'aisoc_ci', :h, TRUE)"
+ ),
+ {"t": tenants["a"], "u": user_id, "h": uuid.uuid4().hex},
+ )
+ await db.commit()
+
+ active_before = await db.execute(
+ sqlalchemy.text("SELECT count(*) FROM api_keys WHERE user_id = CAST(:u AS uuid) AND is_active"),
+ {"u": user_id},
+ )
+ await db.commit()
+ assert active_before.scalar_one() == 1, "no active key to revoke, so this proves nothing"
+
+ patched = await app_client.patch(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_a"]), json=OKTA_DEACTIVATE)
+ assert patched.status_code == 200, patched.text[:300]
+
+ active_after = await db.execute(
+ sqlalchemy.text("SELECT count(*) FROM api_keys WHERE user_id = CAST(:u AS uuid) AND is_active"),
+ {"u": user_id},
+ )
+ await db.commit()
+ assert active_after.scalar_one() == 0, "the principal was deactivated and their API key still authenticates"
+
+ async def test_a_deactivation_stamps_the_session_revocation_time(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """A `TIMESTAMPTZ` write, which is where the offline harness is
+ weakest: a shimmed column accepts a value without storing a
+ comparable one, and every token issued before this instant is
+ refused by comparing against it."""
+ import sqlalchemy
+
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ patched = await app_client.patch(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_a"]), json=ENTRA_DEACTIVATE)
+ assert patched.status_code == 200, patched.text[:300]
+
+ rows = await db.execute(
+ sqlalchemy.text("SELECT sessions_revoked_at FROM users WHERE id = CAST(:u AS uuid)"),
+ {"u": user_id},
+ )
+ await db.commit()
+ stamped = rows.scalar_one()
+ assert stamped is not None, "deactivation left no session-revocation stamp, so an open token keeps working"
+ assert stamped.tzinfo is not None, "the stamp came back naive; a comparison against an aware `now()` would raise"
+
+ async def test_delete_deactivates_rather_than_erasing_the_row(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """RFC 7644 permits it, and erasing would take the principal's
+ audit attribution, case ownership and approval history with it.
+ Access ends either way."""
+ import sqlalchemy
+
+ user_id, email = await _provision(app_client, tenants["token_a"])
+
+ response = await app_client.delete(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_a"]))
+ assert response.status_code == 204, f"{response.status_code}: {response.text[:300]}"
+
+ rows = await db.execute(sqlalchemy.text("SELECT is_active FROM users WHERE email = :e"), {"e": email})
+ await db.commit()
+ surviving = rows.all()
+ assert len(surviving) == 1, "DELETE erased the row, taking its audit attribution with it"
+ assert surviving[0][0] is False
+
+ async def test_reactivating_does_not_restore_the_revoked_api_keys(self, app_client, db, tenants) -> None: # noqa: ANN001
+ """A key whose owner cannot see it was revoked is a key nobody will
+ rotate."""
+ import sqlalchemy
+
+ user_id, _ = await _provision(app_client, tenants["token_a"])
+ await db.execute(
+ sqlalchemy.text(
+ "INSERT INTO api_keys (id, tenant_id, user_id, name, key_prefix, hashed_key, is_active) "
+ "VALUES (gen_random_uuid(), CAST(:t AS uuid), CAST(:u AS uuid), 'ci', 'aisoc_ci', :h, TRUE)"
+ ),
+ {"t": tenants["a"], "u": user_id, "h": uuid.uuid4().hex},
+ )
+ await db.commit()
+
+ await app_client.patch(f"/scim/v2/Users/{user_id}", headers=_auth(tenants["token_a"]), json=OKTA_DEACTIVATE)
+ reactivated = await app_client.patch(
+ f"/scim/v2/Users/{user_id}",
+ headers=_auth(tenants["token_a"]),
+ json={"schemas": [PATCH_SCHEMA], "Operations": [{"op": "replace", "path": "active", "value": True}]},
+ )
+ assert reactivated.status_code == 200, reactivated.text[:300]
+
+ rows = await db.execute(
+ sqlalchemy.text(
+ "SELECT u.is_active, (SELECT count(*) FROM api_keys k WHERE k.user_id = u.id AND k.is_active) "
+ "FROM users u WHERE u.id = CAST(:u AS uuid)"
+ ),
+ {"u": user_id},
+ )
+ await db.commit()
+ is_active, live_keys = rows.one()
+ assert is_active is True, "re-activation did not restore sign-in"
+ assert live_keys == 0, "re-activation resurrected an API key the deprovisioning revoked"
+
+
+class TestTheVendorPayloadsHaveNotDrifted:
+ """The offline suite holds the same payloads, and two copies disagreeing
+ is how a live test ends up certifying a shape no provider sends.
+
+ Read from source rather than imported: that module installs
+ `@compiles(..., "sqlite")` type shims and builds its own application at
+ import time, both of which this suite exists to avoid.
+ """
+
+ SHARED = (
+ "OKTA_DEACTIVATE",
+ "ENTRA_DEACTIVATE",
+ "ENTRA_DEACTIVATE_BOOL",
+ "OKTA_ADD_MEMBER",
+ "OKTA_REMOVE_MEMBER",
+ "ENTRA_ADD_MEMBER",
+ "ENTRA_REMOVE_MEMBER",
+ )
+
+ async def test_every_shared_payload_matches_the_offline_copy(self) -> None:
+ assert OFFLINE_SUITE.exists(), f"{OFFLINE_SUITE} has moved; this pin is reading nothing"
+ tree = ast.parse(OFFLINE_SUITE.read_text(encoding="utf-8"))
+
+ # The offline payloads reference module-level names — every one of
+ # them opens `{"schemas": [PATCH_SCHEMA], …}` — so `literal_eval`
+ # alone raises on the first `ast.Name`. Those names are resolved
+ # first, which is also what makes the comparison meaningful: a
+ # changed `PATCH_SCHEMA` has to show up as a changed payload.
+ constants = {
+ target.id: node.value.value
+ for node in tree.body
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
+ for target in node.targets
+ if isinstance(target, ast.Name)
+ }
+
+ def evaluate(node: ast.expr) -> object:
+ if isinstance(node, ast.Name):
+ assert node.id in constants, f"the offline suite builds a payload from {node.id!r}, which this pin cannot resolve"
+ return constants[node.id]
+ if isinstance(node, ast.Dict):
+ return {evaluate(k): evaluate(v) for k, v in zip(node.keys, node.values, strict=True) if k is not None}
+ if isinstance(node, ast.List | ast.Tuple):
+ return [evaluate(element) for element in node.elts]
+ return ast.literal_eval(node)
+
+ offline = {
+ target.id: evaluate(node.value)
+ for node in tree.body
+ if isinstance(node, ast.Assign)
+ for target in node.targets
+ if isinstance(target, ast.Name) and target.id in self.SHARED
+ }
+
+ missing = set(self.SHARED) - set(offline)
+ assert not missing, f"the offline suite no longer defines {sorted(missing)}"
+
+ here = globals()
+ differing = {name: (offline[name], here[name]) for name in self.SHARED if offline[name] != here[name]}
+ assert not differing, f"the live and offline vendor payloads have drifted: {sorted(differing)}"
+
+
class TestTheDiscoveryEndpoints:
async def test_service_provider_config_is_served(self, app_client, tenants) -> None: # noqa: ANN001
"""An IdP reads this first. If it 404s, nothing else is reached."""