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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/30958-scim-connection-credential-door.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/plugin-auth': patch
---

feat(plugin-auth): a platform administrator can mint and revoke SCIM connection credentials

Clause-②: yes (widening)
Metadata-protocol: none
Skills-docs: updated here — `content/docs/permissions/authentication.mdx` ("SCIM Connection Credentials" under Admin User Management); `skills/**` teaches no SCIM setup

An identity provider (Okta, Entra ID) provisions users through `/api/v1/auth/scim/v2/*` with a bearer credential that this platform issues, but nothing could issue one: the mint existed with no caller, and the credential object refuses create on the data API, so no identity provider could connect. Two routes now do it, for the platform administrator only (the shared ADR-0068 gate: anyone else is refused `403 PERMISSION_DENIED`, `401 UNAUTHENTICATED` when signed out):

- `POST /api/v1/auth/admin/scim/mint-credential` with `{ connectionId, label?, expiresAt?, provisioningDomainId?, organizationId? }` answers `{ credentialId, connectionId, token, expiresAt }`. `connectionId` is at most 246 characters, so the connection's audit actor `svc:scim:<connectionId>` fits `sys_audit_log.actor`. The `token` is shown once, in that response only (`Cache-Control: no-store`); only its keyed one-way digest is stored, and it is not readable through the data API, the audit log or the logs. Refused `503 SERVICE_UNAVAILABLE` while SCIM is off. The credential row is owned by `organizationId` when given (it must exist), otherwise by the Default Organization.
- `POST /api/v1/auth/admin/scim/revoke-credential` with `{ credentialId }` switches the credential off, so the identity provider's next SCIM request with it answers `401`. `404 RESOURCE_NOT_FOUND` for an unknown credential, `409 RESOURCE_CONFLICT` for one already revoked. Served whether or not SCIM is on.

Rotation is a second mint for the same `connectionId`, moving the identity provider to the new bearer, then revoking the old one. Each mint and each revoke writes one `sys_audit_log` row naming the administrator and the connection, never the credential. Nothing that existed changes: no route, response or stored row moves, and the credential object stays read-only on the data API.
37 changes: 37 additions & 0 deletions content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1166,6 +1166,43 @@ rows that resolve to a temporary password (all of them under `temporary`, only
the unreachable ones under `auto`) — reveals the generated passwords once with a
download, splitting files above 500 rows into batches automatically.

#### SCIM Connection Credentials

With SCIM enabled (`OS_SCIM_ENABLED=true`, or `plugins.scim`), an identity
provider such as Okta or Entra ID provisions users through
`/api/v1/auth/scim/v2/*` with a bearer credential the platform issues. Only a
platform administrator mints or revokes one, through the same gate as the
routes above; anyone else is refused `403 PERMISSION_DENIED` (`401` when
signed out).

```bash
curl -X POST http://localhost:3000/api/v1/auth/admin/scim/mint-credential \
-H 'Content-Type: application/json' -H "Authorization: Bearer $ADMIN_SESSION" \
-d '{ "connectionId": "okta-prod", "label": "rotation 2026-Q4" }'
# → { success, data: { credentialId, connectionId, token, expiresAt } }
```

- `connectionId` (required) names the connection every provisioned resource
is scoped to: at most 246 characters, so the connection's audit actor
`svc:scim:<connectionId>` fits the audit log's 255. Optional: `label`, `expiresAt` (a future ISO date-time),
`provisioningDomainId`, and `organizationId` (the organization that owns the
credential row; the Default Organization when omitted).
- The `token` is shown **once**, in this response only (`Cache-Control:
no-store`). Only a keyed one-way digest of it is stored; it is not readable
through the data API, the audit log or the logs afterwards. Paste it into the
identity provider's SCIM settings as the bearer token.
- While SCIM is off the mint is refused `503 SERVICE_UNAVAILABLE`: a credential
nothing can verify is not issued.

`POST /api/v1/auth/admin/scim/revoke-credential` with `{ "credentialId": "…" }`
switches that credential off: the identity provider's next SCIM request with it
is refused `401`. An unknown credential answers `404 RESOURCE_NOT_FOUND`, one
already revoked `409 RESOURCE_CONFLICT`. Revocation works whether or not SCIM is
on. To **rotate**, mint a second credential for the same `connectionId`, move
the identity provider to it, then revoke the old one; both authenticate until
you do. Each mint and each revoke writes one `sys_audit_log` row naming the
administrator and the connection, never the credential.

---

## Client Integration
Expand Down
40 changes: 20 additions & 20 deletions content/docs/permissions/tenant-audit-census.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way.

The same holds twice over for the context. An options argument spelled as a
literal can be read; one spelled `options`, `{ ...opts }`, or handed through a
forwarding shim cannot, and **55 of the 261 sites are spelled that way**. A
forwarding shim cannot, and **55 of the 263 sites are spelled that way**. A
context resolved from an inline literal or a local `const` can be tested for
`isSystem`; one arriving from a helper call cannot.

Expand Down Expand Up @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page:

| carried figure | where it survives | this census |
| :--- | :--- | ---: |
| 175 write call sites | quoted in the merged changeset | **261** |
| 175 write call sites | quoted in the merged changeset | **263** |
| 24 carrying no tenant context | quoted in the merged changeset | **2** provable and tenancy-enabled; **29** more whose options argument is unreadable |
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **184 of 261** decidable, **77** undecidable |
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 144 decidably elevated, 0 decidably not, 109 undecidable |
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **186 of 263** decidable, **77** undecidable |
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 146 decidably elevated, 0 decidably not, 109 undecidable |
| 141 and 132, two independent re-derivations | the card that filed this work | — |

**The differences are not reconciled, and deliberately so.** The old census's
Expand All @@ -211,17 +211,17 @@ at any commit.

Two structural facts do plausibly widen this reading against any hand or regex
one, and both are counted in the generated tables below: the 62 sites reached
through an erased (`any`) receiver, and the 68 that name their object through a
through an erased (`any`) receiver, and the 69 that name their object through a
`const` rather than inline. An instrument that read either the way a person does
would report a smaller number and would not say so.

The fourth row is the one worth flagging to anyone citing it. **The 135 / 77%
figure has no surviving corroboration anywhere in the tree.** This census reads
144 of 261 (55%) as decidably elevated, with 109 more whose elevation is a
146 of 263 (56%) as decidably elevated, with 109 more whose elevation is a
run-time fact — so the claim is neither confirmed nor refuted, and the honest
answer is that a static reading cannot settle it.

⇒ **Cite `2 / 261`, and say what it is**: the sites whose options argument was
⇒ **Cite `2 / 263`, and say what it is**: the sites whose options argument was
READ and holds no tenant context, against a decidably tenancy-enabled object.
That is the control's provable yield surface. ⛔ Do not cite it as "the sites
without tenant context" — **29 further sites** have an options argument this
Expand All @@ -233,29 +233,29 @@ cannot read, and they are neither in nor out.

| what | count |
| :--- | ---: |
| write call sites on the application surface | **261** |
| …whose object name is statically decidable | 184 |
| write call sites on the application surface | **263** |
| …whose object name is statically decidable | 186 |
| …whose object name is chosen at run time | 77 |
| …against an object with tenancy ENABLED | 178 |
| …against an object with tenancy ENABLED | 180 |
| …against an object that declares tenancy off | 6 |
| threading a tenant context | 198 |
| threading a tenant context | 200 |
| PROVABLY carrying none (options read, no context key) | **8** |
| …of those, against a decidably tenancy-enabled object | **2** |
| options argument UNREADABLE — may or may not carry one | 55 |
| …of those, against a decidably tenancy-enabled object | 29 |
| threading a decidably ELEVATED (`isSystem`) context | 144 |
| threading a decidably ELEVATED (`isSystem`) context | 146 |
| threading a context that is decidably NOT elevated | 0 |
| threading a context whose elevation is a run-time fact | 109 |

| how the instrument reached the site | count |
| :--- | ---: |
| receiver carried a readable engine type | 199 |
| receiver carried a readable engine type | 201 |
| receiver erased, placed by the object NAME | 52 |
| receiver erased, placed by an `object: string` PARAMETER | 5 |
| receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 |

| object name spelled inline | 116 |
| object name spelled through a `const` | 68 |
| object name spelled inline | 117 |
| object name spelled through a `const` | 69 |
| object name is an `object: string` parameter | 7 |
| object name is some other run-time expression | 70 |

Expand Down Expand Up @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true;
their values are not compared. The reasoning, and the measurement behind it,
are in `scripts/check-tenant-audit-census.mjs`.

Measured on 2026-11-05 at `e40e04854`.
Measured on 2026-11-06 at `ac688f409`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 871 |
| engine-shaped types recognised | 105 |
| declared objects in the registry | 127 |
| same-named calls subtracted as non-engine | 229 |
| tracked non-test sources scanned | 1037 |
| engine-shaped types recognised | 111 |
| declared objects in the registry | 130 |
| same-named calls subtracted as non-engine | 230 |

{/* END GENERATED: tenant-audit-census */}
22 changes: 12 additions & 10 deletions docs/audits/2026-08-tenant-audit-write-call-sites.counts.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution.

| Measure | Value |
|---|---:|
| Write call sites | 261 |
| Object name statically decidable | 184 |
| Write call sites | 263 |
| Object name statically decidable | 186 |
| Object name chosen at run time | 77 |
| Against a tenancy-enabled object | 178 |
| Against a tenancy-enabled object | 180 |
| Against an object declaring tenancy off | 6 |
| Threading a tenant context | 198 |
| Threading a tenant context | 200 |
| Provably carrying none | 8 |
| …and decidably tenancy-enabled | 2 |
| Options argument unreadable | 55 |
| …and decidably tenancy-enabled | 29 |
| Threading a decidably elevated context | 144 |
| Threading a decidably elevated context | 146 |
| Threading a decidably non-elevated context | 0 |
| Threading a context of undecidable elevation | 109 |

Expand Down Expand Up @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true;
their values are not compared. The reasoning, and the measurement behind it,
are in `scripts/check-tenant-audit-census.mjs`.

Measured on 2026-11-05 at `e40e04854`.
Measured on 2026-11-06 at `ac688f409`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 871 |
| engine-shaped types recognised | 105 |
| declared objects in the registry | 127 |
| same-named calls subtracted as non-engine | 229 |
| tracked non-test sources scanned | 1037 |
| engine-shaped types recognised | 111 |
| declared objects in the registry | 130 |
| same-named calls subtracted as non-engine | 230 |

## Every site

Expand Down Expand Up @@ -166,7 +166,9 @@ Measured on 2026-11-05 at `e40e04854`.
| `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team_member` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/reconcile-membership.ts` | `insert` | `sys_member` | enabled | context, elevation undecidable | 1 |
| `packages/plugins/plugin-auth/src/scim-connection-admin.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `insert` | `sys_scim_connection_credential` | enabled | PROVABLY NONE | 1 |
| `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `update` | `sys_scim_connection_credential` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/session-tombstone.ts` | `update` | `objectName` | undecidable | options unreadable | 1 |
| `packages/plugins/plugin-auth/src/sso-client-secret.ts` | `update` | `sys_sso_provider` | disabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 |
Expand Down
27 changes: 27 additions & 0 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ import { createAuthInstance, type AuthInstanceHost } from './auth-manager-auth-i
import { buildPluginList, type PluginListHost } from './auth-manager-plugin-list.js';
import { resolveTurnstileKeys } from './turnstile-sign-up.js';
import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js';
import type { MintScimConnectionCredentialInput, MintedScimConnectionCredential } from './scim-connection-service.js';

/**
* Detect WebContainer (StackBlitz) environment.
Expand Down Expand Up @@ -6194,6 +6195,32 @@ export class AuthManager {
return this.config.trustProxy === true;
}

/**
* [#30958] Is the SCIM 2.0 service provider mounted on this deployment? The
* same decision `buildPluginList` mounts `@better-auth/scim` on
* ({@link resolveScimEnabled}), so the credential door's "SCIM is off"
* refusal can never disagree with the `/scim/v2` routes actually served.
*/
public isScimWired(): boolean {
return resolveScimEnabled(this.config.plugins);
}

/**
* [#30958] Mint a SCIM connection bearer with this deployment's auth secret,
* the key the mounted SCIM plugin's verifier digests with
* (`buildPluginList`), so the bearer is one that plugin accepts. The secret
* never leaves the manager. The only caller is the platform-admin
* `/admin/scim/mint-credential` mount (`scim-connection-admin.ts`), which
* hands the engine to write through.
*/
public async mintScimConnectionCredential(
engine: IDataEngine,
input: MintScimConnectionCredentialInput,
): Promise<MintedScimConnectionCredential> {
const { mintScimConnectionCredential } = await import('./scim-connection-service.js');
return mintScimConnectionCredential(engine as never, this.resolveAuthSecret(), input);
}

/**
* Returns the data engine wired into this auth manager. Used by route
* handlers (e.g. bootstrap-status) that need to query identity tables
Expand Down
45 changes: 45 additions & 0 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3874,6 +3874,51 @@ export class AuthPlugin implements Plugin {
}
});

// ────────────────────────────────────────────────────────────────────
// [#30958] ADR-0134 — admin: mint and revoke the bearer credentials SCIM
// connections authenticate with. The SCIM plugin verifies against
// `sys_scim_connection_credential` rows, which the data API never creates
// or updates (engine-owned, list only), so these two mounts are the
// credential lifecycle's only door. Same family as `set-user-manager`: the
// shared platform-admin gate runs first, ahead of any body read, and the
// store writes are credited to the admin. The minted bearer is answered
// once, `no-store`, and kept nowhere; see `scim-connection-admin.ts`.
{
const scimCredentialDeps = (actor: PlatformAdminActor): import('./scim-connection-admin.js').ScimCredentialAdminDeps => ({
getDataEngine: () => this.authManager!.getDataEngine(),
isScimEnabled: () => this.authManager!.isScimWired(),
mint: (engine, input) => this.authManager!.mintScimConnectionCredential(engine, input),
attributed: (fn) => runAttributedToUser(actor, fn),
logger: { warn: (m) => ctx.logger.warn(m), error: (m) => ctx.logger.error(m) },
});
rawApp.post(`${basePath}/admin/scim/mint-credential`, async (c: any) => {
try {
const actor = await gateAdmin(c);
if (actor instanceof Response) return actor;
const { runMintScimCredential } = await import('./scim-connection-admin.js');
const { status, body, headers } = await runMintScimCredential(scimCredentialDeps(actor), actor, c.req.raw);
return c.json(body, status as any, headers);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
ctx.logger.error('[AuthPlugin] admin/scim/mint-credential failed', err);
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
}
});
rawApp.post(`${basePath}/admin/scim/revoke-credential`, async (c: any) => {
try {
const actor = await gateAdmin(c);
if (actor instanceof Response) return actor;
const { runRevokeScimCredential } = await import('./scim-connection-admin.js');
const { status, body } = await runRevokeScimCredential(scimCredentialDeps(actor), actor, c.req.raw);
return c.json(body, status as any);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
ctx.logger.error('[AuthPlugin] admin/scim/revoke-credential failed', err);
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
}
});
}

// ────────────────────────────────────────────────────────────────────
// #2766 V1 — admin direct user management. `sys_user` CRUD is suppressed
// (managedBy better-auth), and until now the only add-a-teammate path was
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ describe('auth route ledger hygiene', () => {
// below holds it to the same proof — better-auth serves no roster.
'POST /api/v1/auth/admin/list-platform-admins',
'POST /api/v1/auth/admin/oauth2/toggle-disabled',
// [#30958] On this pin's own terms: `auth-plugin.ts` mounts both itself
// (`rawApp.post` on the `${basePath}/admin/scim/mint-credential` and
// `${basePath}/admin/scim/revoke-credential` templates, ahead of the
// catch-all), and the `live.has(route)` loop below holds them to the
// same proof — stable `@better-auth/scim` serves no credential endpoint.
'POST /api/v1/auth/admin/scim/mint-credential',
'POST /api/v1/auth/admin/scim/revoke-credential',
// [#16678] The thirteenth, added on this pin's own terms exactly as the
// set-initial-password row below was: `auth-plugin.ts` mounts it itself
// (a `rawApp.post` on the `${basePath}/admin/set-user-manager`
Expand Down
Loading
Loading