diff --git a/.changeset/custom-claims.md b/.changeset/custom-claims.md new file mode 100644 index 00000000..5865d573 --- /dev/null +++ b/.changeset/custom-claims.md @@ -0,0 +1,13 @@ +--- +'seamless-auth-api': minor +--- + +Add static custom claims (ADR 0005, #417). + +- Admin API under `/admin/custom-claims`: list every source with the reserved names, prefixes and budget, and read, replace or delete the set for an instance role, an organization role or an OpenID Provider client. Writes take step-up and are audited by claim name, never value. +- A set is refused when it uses a reserved name or prefix, a name outside `^[a-z][a-z0-9_]{0,63}$`, a value nested deeper than 3, or more than 1 KiB. The role or client must exist. +- First-party access tokens now carry the claims of the user's instance roles, then of their roles in the active organization (only while the membership exists), then the session's `pre_token` hook claims, a later source winning per name. Roles of one kind apply in name order. Recovery tokens carry none. +- OpenID Provider client sets are stored and served here, and applied by the provider in a later release. +- Permission claims and custom claims now share one 1 KiB token budget (`AUTHORIZATION_CLAIMS_BUDGET_BYTES`, replacing `PERMISSION_CLAIMS_BUDGET_BYTES`), so the server adapter's cookie holds the worst case. When both do not fit, permissions give way first and are replaced with `permissions_omitted: true`, as before. Only when the custom claims do not fit even beside that marker are they all dropped, and the mint writes `custom_claims_omitted`. Nothing is trimmed. This is a behavior change: a token with custom claims can now carry `permissions_omitted` at a smaller permission set than before. +- Retiring an instance role, deleting an organization role, or deleting an OpenID Provider application deletes its custom claims, so adding the name back does not restore them. +- New audit events `admin_custom_claims_updated`, `admin_custom_claims_deleted` and `custom_claims_omitted`. diff --git a/adapter-manifest.json b/adapter-manifest.json index 9fa6a459..6fcd1ae0 100644 --- a/adapter-manifest.json +++ b/adapter-manifest.json @@ -33,6 +33,22 @@ { "method": "GET", "path": "/admin/auth-events/export", "credential": "access" }, { "method": "GET", "path": "/admin/auth-events/integrity", "credential": "access" }, { "method": "GET", "path": "/admin/credential-count", "credential": "access" }, + { "method": "GET", "path": "/admin/custom-claims", "credential": "access" }, + { + "method": "DELETE", + "path": "/admin/custom-claims/{sourceKind}/{sourceName}", + "credential": "access" + }, + { + "method": "GET", + "path": "/admin/custom-claims/{sourceKind}/{sourceName}", + "credential": "access" + }, + { + "method": "PUT", + "path": "/admin/custom-claims/{sourceKind}/{sourceName}", + "credential": "access" + }, { "method": "GET", "path": "/admin/enrollment", "credential": "access" }, { "method": "POST", "path": "/admin/enrollment/invites", "credential": "access" }, { "method": "GET", "path": "/admin/login-hooks", "credential": "access" }, diff --git a/docs/adr/0004-permissions-and-organization-roles.md b/docs/adr/0004-permissions-and-organization-roles.md index 15c7ddca..3a3e5020 100644 --- a/docs/adr/0004-permissions-and-organization-roles.md +++ b/docs/adr/0004-permissions-and-organization-roles.md @@ -53,6 +53,8 @@ This differs from `requireRole`, deliberately. Roles keep their scoped matching. The organization roles and the two permission arrays get 1 KiB, serialized, together. A server adapter keeps the whole access token inside a signed cookie, so it is base64 encoded twice under the browser's 4 KiB cookie limit, and a test builds that cookie at the budget. Over the budget all three are replaced with `"permissions_omitted": true`. +The 1 KiB is now shared with custom claims (ADR 0005, E6), and permissions are the first to give way when both do not fit. + Nothing is trimmed, because a partial list looks complete and denies silently. A guard that sees the marker reads `GET /users/me/permissions` with the caller's token and fails closed if it cannot. A plain 403 would turn an organization growing past a limit into an outage. ### P5. Organization roles are a catalogue diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index f98c9b32..f5a7d9ce 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -83,7 +83,14 @@ Sources, lowest precedence first: an instance role, an organization role (while Reserved, refused when written and stripped (and audited) when a hook returns them: JWT registered claims, OpenID and OAuth protocol claims including `act` and `may_act`, Seamless's own claims, the OpenID standard identity claims (so no source can assert an email address the user never proved), and any name starting `seamless_` or `org_`. The list lives in `@seamless-auth/types/customClaim/reserved`, shared with the provider. -All custom claims together get 1 KiB serialized, on top of ADR 0004's permission budget. Unlike permissions they are never dropped: a static set over the budget is refused when written, and a hook over it has failed. +Each static set gets 1 KiB serialized, refused when written over it, and a hook over it has failed. In the token, custom claims share one 1 KiB budget with ADR 0004's permission claims (`permissions`, `org_roles`, `org_permissions`), serialized together, so the adapter cookie holds the worst case. Brandon chose this rule on 2026-11-07: + +1. If the permission claims and the merged custom claims fit together, the token carries both. +2. Otherwise permissions give way first, since a guard has a live fallback for them and custom claims have none: the three are replaced with `"permissions_omitted": true` and the custom claims stay, if the custom claims and the marker fit. +3. Only when they do not fit even beside the marker are all custom claims dropped, and the mint writes `custom_claims_omitted`. The token then carries just the marker. +4. Nothing is ever trimmed partially. Recovery tokens carry neither. + +Among roles of one kind, sets apply in role-name order, so the last name alphabetically wins a claim two of them set. It is deterministic and does not depend on the order roles were granted in, which an administrator cannot see. The console shows which role wins when two set the same claim. Brandon decided this on 2026-11-07. ### E7. SIEM streaming @@ -124,6 +131,11 @@ They must be read back to sign, so they cannot be hashed. They are AES-256-GCM e - When a mint finds the user has left the session's organization, the session's hook claims are cleared with the organization, since the hook decided them for it. - `client` in the call is always null for now: no first-party sign-in knows which OpenID Provider client it is for. The provider can fill it in seamless-auth-oidc-provider#47. - A test call sends a placeholder user and no request details, and is not recorded as an invocation. +- Custom claims (#417): + - Roles of one kind apply in role-name order (E6), rather than the order they are held in. Brandon confirmed this on 2026-11-07. + - Separate 1 KiB budgets for permissions and custom claims did not fit the server adapter's session cookie: 5670 bytes against 4096 at both, with only about 136 bytes of custom claims fitting beside a full permission set. Brandon chose the shared budget and the order in E6 on 2026-11-07. At the shared budget the worst-case cookie measures 3868 bytes. + - A set can only be written for a role or client that exists, and retiring the role or deleting the client deletes its set. + - `z.json()` in the shared claim schemas overflowed the OpenAPI generator. `@seamless-auth/types` 0.40.0 describes a claim value as a union bounded at the claim depth, so the route schemas use the shared ones directly. ## Consequences diff --git a/docs/api-contract.md b/docs/api-contract.md index 2f68f4f2..e3f72129 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -31,8 +31,9 @@ All tokens are returned in the JSON body (the API never sets cookies). Present t - **Access token** — a signed JWT (RS256). Claims include `sub` (user id), `sid` (session id), `iss`, `typ: "access"`, `roles` and `permissions`. In an active organization it also carries - `org_id`, `org_roles` and `org_permissions`, which apply to that organization only. When the - permission claims would not fit, `permissions_omitted: true` replaces `permissions`, `org_roles` + `org_id`, `org_roles` and `org_permissions`, which apply to that organization only, and any + custom claims (ADR 0005). The permission claims and custom claims share one 1 KiB budget. When + they would not fit together, `permissions_omitted: true` replaces `permissions`, `org_roles` and `org_permissions`, and absent then means "ask" rather than "none": read the live set from `GET /users/me/permissions`. See [Permissions](./admin-operations.md#permissions). Verify it against the JWKS at `GET /.well-known/jwks.json`. diff --git a/openapi.json b/openapi.json index 8a427a01..037dc9d9 100644 --- a/openapi.json +++ b/openapi.json @@ -7307,7 +7307,10 @@ "login_hook_claims_stripped", "login_hook_denied", "login_hook_failed", - "login_hook_success" + "login_hook_success", + "admin_custom_claims_deleted", + "admin_custom_claims_updated", + "custom_claims_omitted" ] }, { "type": "string" }, @@ -7460,7 +7463,10 @@ "login_hook_claims_stripped", "login_hook_denied", "login_hook_failed", - "login_hook_success" + "login_hook_success", + "admin_custom_claims_deleted", + "admin_custom_claims_updated", + "custom_claims_omitted" ] }, { "type": "string" } @@ -10699,6 +10705,1380 @@ } } }, + "/admin/custom-claims": { + "get": { + "summary": "List custom claim sources", + "description": "Also lists the reserved names and prefixes, and the per-token budget.", + "tags": ["Admin", "Custom claims"], + "security": [{ "bearerAuth": [] }], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "sources": [null], + "reservedNames": [null], + "reservedPrefixes": [null], + "budgetBytes": 0 + }, + "schema": { + "type": "object", + "properties": { + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceKind": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "sourceName": { "type": "string" }, + "claims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + } + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": ["sourceKind", "sourceName", "claims", "updatedAt"] + } + }, + "reservedNames": { "type": "array", "items": { "type": "string" } }, + "reservedPrefixes": { "type": "array", "items": { "type": "string" } }, + "budgetBytes": { "type": "integer", "minimum": 0, "exclusiveMinimum": true } + }, + "required": ["sources", "reservedNames", "reservedPrefixes", "budgetBytes"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/custom-claims/{sourceKind}/{sourceName}": { + "get": { + "summary": "Get a source's custom claims", + "tags": ["Admin", "Custom claims"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "required": true, + "name": "sourceKind", + "in": "path" + }, + { + "schema": { "type": "string", "minLength": 1, "maxLength": 200 }, + "required": true, + "name": "sourceName", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "source": { + "sourceKind": null, + "sourceName": "string", + "claims": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "source": { + "type": "object", + "properties": { + "sourceKind": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "sourceName": { "type": "string" }, + "claims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + } + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": ["sourceKind", "sourceName", "claims", "updatedAt"] + } + }, + "required": ["source"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "put": { + "summary": "Replace a source's custom claims", + "description": "Replaces the whole set. Reserved names, values nested deeper than 3 and a set over 1 KiB are refused. The role or client must exist.", + "tags": ["Admin", "Custom claims"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "required": true, + "name": "sourceKind", + "in": "path" + }, + { + "schema": { "type": "string", "minLength": 1, "maxLength": 200 }, + "required": true, + "name": "sourceName", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "claims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + }, + "required": ["claims"] + } + } + } + }, + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "source": { + "sourceKind": null, + "sourceName": "string", + "claims": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "source": { + "type": "object", + "properties": { + "sourceKind": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "sourceName": { "type": "string" }, + "claims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + } + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": ["sourceKind", "sourceName", "claims", "updatedAt"] + } + }, + "required": ["source"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "delete": { + "summary": "Delete a source's custom claims", + "tags": ["Admin", "Custom claims"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { + "type": "string", + "enum": ["instance_role", "organization_role", "oidc_client"] + }, + "required": true, + "name": "sourceKind", + "in": "path" + }, + { + "schema": { "type": "string", "minLength": 1, "maxLength": 200 }, + "required": true, + "name": "sourceName", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "message": "string", "token": "string", "delivery": null }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "token": { "type": "string" }, + "delivery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_sms"] }, + "to": { "type": "string" }, + "token": { "anyOf": [{ "type": "string" }, { "type": "number" }] }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["magic_link_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "magicLinkUrl": { "type": "string" } + }, + "required": ["kind", "to", "magicLinkUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["enrollment_invite_email"] }, + "to": { "type": "string" }, + "signInUrl": { "type": "string" } + }, + "required": ["kind", "to", "signInUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_email"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "subject": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "subject", "text"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_sms"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "text"] + } + ] + } + }, + "required": ["message"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, "/health/status": { "get": { "summary": "Health check endpoint", diff --git a/src/controllers/customClaims.ts b/src/controllers/customClaims.ts new file mode 100644 index 00000000..5261234e --- /dev/null +++ b/src/controllers/customClaims.ts @@ -0,0 +1,112 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + CUSTOM_CLAIMS_BUDGET_BYTES, + type CustomClaimSourceKind, + RESERVED_CLAIM_NAMES, + RESERVED_CLAIM_PREFIXES, +} from '@seamless-auth/types'; +import { Request, Response } from 'express'; + +import { AuthEventService } from '../services/authEventService.js'; +import { + CustomClaimError, + deleteCustomClaimSource, + getCustomClaimSource, + listCustomClaimSources, + serializeCustomClaimSource, + setCustomClaimSource, +} from '../services/customClaimService.js'; +import { AuthenticatedRequest } from '../types/types.js'; + +function actorUserId(req: Request) { + return (req as AuthenticatedRequest).user?.id ?? null; +} + +function source(req: Request) { + return { + sourceKind: req.params.sourceKind as CustomClaimSourceKind, + sourceName: req.params.sourceName as string, + }; +} + +function sendError(res: Response, error: unknown) { + if (error instanceof CustomClaimError) { + return res.status(error.status).json({ error: error.message }); + } + + throw error; +} + +export async function listCustomClaims(_req: Request, res: Response) { + const sources = await listCustomClaimSources(); + return res.json({ + sources: sources.map(serializeCustomClaimSource), + reservedNames: [...RESERVED_CLAIM_NAMES], + reservedPrefixes: [...RESERVED_CLAIM_PREFIXES], + budgetBytes: CUSTOM_CLAIMS_BUDGET_BYTES, + }); +} + +export async function getCustomClaims(req: Request, res: Response) { + const { sourceKind, sourceName } = source(req); + try { + return res.json({ + source: serializeCustomClaimSource(await getCustomClaimSource(sourceKind, sourceName)), + }); + } catch (error) { + return sendError(res, error); + } +} + +export async function setCustomClaims(req: Request, res: Response) { + const { sourceKind, sourceName } = source(req); + try { + const { source: saved, previous } = await setCustomClaimSource( + sourceKind, + sourceName, + req.body.claims, + ); + const names = Object.keys(saved.claims ?? {}); + + // Names only: a value can be anything an administrator typed, and the audit log is permanent. + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_custom_claims_updated', + req, + metadata: { + sourceKind, + sourceName, + claimNames: names, + added: names.filter((name) => !previous.includes(name)), + removed: previous.filter((name) => !names.includes(name)), + }, + }); + + return res.json({ source: serializeCustomClaimSource(saved) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function deleteCustomClaims(req: Request, res: Response) { + const { sourceKind, sourceName } = source(req); + try { + const removed = await deleteCustomClaimSource(sourceKind, sourceName); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_custom_claims_deleted', + req, + metadata: { sourceKind, sourceName, claimNames: Object.keys(removed.claims ?? {}) }, + }); + + return res.json({ message: 'Custom claims deleted' }); + } catch (error) { + return sendError(res, error); + } +} diff --git a/src/generated/api.ts b/src/generated/api.ts index 235b2994..6467be2c 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -6914,6 +6914,9 @@ export interface paths { | 'login_hook_denied' | 'login_hook_failed' | 'login_hook_success' + | 'admin_custom_claims_deleted' + | 'admin_custom_claims_updated' + | 'custom_claims_omitted' ) | string | ( @@ -7061,6 +7064,9 @@ export interface paths { | 'login_hook_denied' | 'login_hook_failed' | 'login_hook_success' + | 'admin_custom_claims_deleted' + | 'admin_custom_claims_updated' + | 'custom_claims_omitted' ) | string )[]; @@ -10245,6 +10251,928 @@ export interface paths { patch?: never; trace?: never; }; + '/admin/custom-claims': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List custom claim sources + * @description Also lists the reserved names and prefixes, and the per-token budget. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "sources": [ + * null + * ], + * "reservedNames": [ + * null + * ], + * "reservedPrefixes": [ + * null + * ], + * "budgetBytes": 0 + * } + */ + 'application/json': { + sources: { + /** @enum {string} */ + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + claims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; + /** Format: date-time */ + updatedAt: string | null; + }[]; + reservedNames: string[]; + reservedPrefixes: string[]; + budgetBytes: number; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/custom-claims/{sourceKind}/{sourceName}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a source's custom claims */ + get: { + parameters: { + query?: never; + header?: never; + path: { + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "source": { + * "sourceKind": null, + * "sourceName": "string", + * "claims": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + source: { + /** @enum {string} */ + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + claims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + /** + * Replace a source's custom claims + * @description Replaces the whole set. Reserved names, values nested deeper than 3 and a set over 1 KiB are refused. The role or client must exist. + */ + put: { + parameters: { + query?: never; + header?: never; + path: { + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + claims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; + }; + }; + }; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "source": { + * "sourceKind": null, + * "sourceName": "string", + * "claims": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + source: { + /** @enum {string} */ + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + claims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + post?: never; + /** Delete a source's custom claims */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + sourceKind: 'instance_role' | 'organization_role' | 'oidc_client'; + sourceName: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "token": "string", + * "delivery": null + * } + */ + 'application/json': { + message: string; + token?: string; + delivery?: + | { + /** @enum {string} */ + kind: 'otp_email'; + to: string; + token: string; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'otp_sms'; + to: string; + token: string | number; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'magic_link_email'; + to: string; + token?: string; + magicLinkUrl: string; + } + | { + /** @enum {string} */ + kind: 'enrollment_invite_email'; + to: string; + signInUrl: string; + } + | { + /** @enum {string} */ + kind: 'account_notice_email'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + subject: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + } + | { + /** @enum {string} */ + kind: 'account_notice_sms'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/health/status': { parameters: { query?: never; diff --git a/src/lib/authEventCategories.ts b/src/lib/authEventCategories.ts index db7b4277..5658f484 100644 --- a/src/lib/authEventCategories.ts +++ b/src/lib/authEventCategories.ts @@ -59,6 +59,7 @@ const EXACT_CATEGORIES: Readonly> = { break_glass_enrollment: 'webauthn', break_glass_sign_in: 'login', credentials_deleted: 'webauthn', + custom_claims_omitted: 'token', informational: 'system', internal_user_updated_by_owner: 'system', notification_sent: 'system', diff --git a/src/migrations/20261108130000-add-custom-claims.cjs b/src/migrations/20261108130000-add-custom-claims.cjs new file mode 100644 index 00000000..73c5508b --- /dev/null +++ b/src/migrations/20261108130000-add-custom-claims.cjs @@ -0,0 +1,35 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * Static custom claims (ADR 0005, E6): one set per source. Instance and organization role sets + * reach first-party access tokens; OpenID Provider client sets are stored here and applied by + * the provider. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE TABLE IF NOT EXISTS public.custom_claims ( + "sourceKind" character varying(32) NOT NULL, + "sourceName" character varying(200) NOT NULL, + claims jsonb NOT NULL DEFAULT '{}'::jsonb, + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT custom_claims_pkey PRIMARY KEY ("sourceKind", "sourceName"), + CONSTRAINT custom_claims_source_kind + CHECK ("sourceKind" IN ('instance_role', 'organization_role', 'oidc_client')) + ); + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(`DROP TABLE IF EXISTS public.custom_claims;`); + }, +}; diff --git a/src/models/customClaims.ts b/src/models/customClaims.ts new file mode 100644 index 00000000..c149974e --- /dev/null +++ b/src/models/customClaims.ts @@ -0,0 +1,48 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { CustomClaimSourceKind } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface CustomClaimAttributes { + sourceKind: CustomClaimSourceKind; + /** A role name, or an OpenID Provider client id. */ + sourceName: string; + claims: Record; + createdAt?: Date; + updatedAt?: Date; +} + +type CustomClaimCreationAttributes = Optional; + +export class CustomClaim + extends Model + implements CustomClaimAttributes +{ + declare sourceKind: CustomClaimSourceKind; + declare sourceName: string; + declare claims: Record; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeCustomClaimModel = (sequelize: Sequelize) => { + CustomClaim.init( + { + sourceKind: { type: DataTypes.STRING(32), primaryKey: true, allowNull: false }, + sourceName: { type: DataTypes.STRING(200), primaryKey: true, allowNull: false }, + claims: { type: DataTypes.JSONB, allowNull: false, defaultValue: {} }, + }, + { + sequelize, + tableName: 'custom_claims', + modelName: 'CustomClaim', + }, + ); + return CustomClaim; +}; + +export default initializeCustomClaimModel; diff --git a/src/routes/customClaims.routes.ts b/src/routes/customClaims.routes.ts new file mode 100644 index 00000000..002f6295 --- /dev/null +++ b/src/routes/customClaims.routes.ts @@ -0,0 +1,94 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + deleteCustomClaims, + getCustomClaims, + listCustomClaims, + setCustomClaims, +} from '../controllers/customClaims.js'; +import { createRouter } from '../lib/createRouter.js'; +import { requireAdmin } from '../middleware/requireAdmin.js'; +import { requireStepUp } from '../middleware/requireStepUp.js'; +import { + CustomClaimListResponseSchema, + CustomClaimSourceParamSchema, + CustomClaimSourceResponseSchema, + SetCustomClaimsRequestSchema, +} from '../schemas/customClaim.schemas.js'; +import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; +import { StepUpRequiredErrorSchema } from '../schemas/stepUp.responses.js'; + +/** + * Static custom claims (ADR 0005, E6). Instance and organization role sets reach first-party + * access tokens. OpenID Provider client sets are stored and served here and applied by the + * provider. + */ +const router = createRouter('/admin'); + +const tags = ['Admin', 'Custom claims']; +const read = { auth: 'access', tags, middleware: [requireAdmin('read')] }; +const write = { auth: 'access', tags, middleware: [requireAdmin('write'), requireStepUp()] }; + +router.get( + '/custom-claims', + { + ...read, + summary: 'List custom claim sources', + description: 'Also lists the reserved names and prefixes, and the per-token budget.', + schemas: { response: { 200: CustomClaimListResponseSchema } }, + }, + listCustomClaims, +); + +router.get( + '/custom-claims/:sourceKind/:sourceName', + { + ...read, + summary: "Get a source's custom claims", + schemas: { + params: CustomClaimSourceParamSchema, + response: { 200: CustomClaimSourceResponseSchema, 404: ErrorSchema }, + }, + }, + getCustomClaims, +); + +router.put( + '/custom-claims/:sourceKind/:sourceName', + { + ...write, + summary: "Replace a source's custom claims", + description: + 'Replaces the whole set. Reserved names, values nested deeper than 3 and a set over 1 KiB are refused. The role or client must exist.', + schemas: { + params: CustomClaimSourceParamSchema, + body: SetCustomClaimsRequestSchema, + response: { + 200: CustomClaimSourceResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + setCustomClaims, +); + +router.delete( + '/custom-claims/:sourceKind/:sourceName', + { + ...write, + summary: "Delete a source's custom claims", + schemas: { + params: CustomClaimSourceParamSchema, + response: { 200: MessageSchema, 403: StepUpRequiredErrorSchema, 404: ErrorSchema }, + }, + }, + deleteCustomClaims, +); + +export default router.router; diff --git a/src/schemas/authEvent.types.ts b/src/schemas/authEvent.types.ts index c04f5b72..a0485f49 100644 --- a/src/schemas/authEvent.types.ts +++ b/src/schemas/authEvent.types.ts @@ -151,6 +151,9 @@ export const AUTH_EVENT_TYPES = [ 'login_hook_denied', 'login_hook_failed', 'login_hook_success', + 'admin_custom_claims_deleted', + 'admin_custom_claims_updated', + 'custom_claims_omitted', ] as const; export const AuthEventTypeEnum = z.enum(AUTH_EVENT_TYPES); diff --git a/src/schemas/customClaim.schemas.ts b/src/schemas/customClaim.schemas.ts new file mode 100644 index 00000000..c0248532 --- /dev/null +++ b/src/schemas/customClaim.schemas.ts @@ -0,0 +1,12 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +export { + CustomClaimListResponseSchema, + CustomClaimSourceParamSchema, + CustomClaimSourceResponseSchema, + SetCustomClaimsRequestSchema, +} from '@seamless-auth/types'; diff --git a/src/services/accessTokenService.ts b/src/services/accessTokenService.ts index 321bbec4..1a7878c8 100644 --- a/src/services/accessTokenService.ts +++ b/src/services/accessTokenService.ts @@ -4,22 +4,26 @@ * See LICENSE file in the project root for full license information */ -import { isReservedClaimName } from '@seamless-auth/types'; import type { Transaction } from 'sequelize'; import { type AuthorizationClaims, signAccessToken } from '../lib/token.js'; import { OrganizationMembership } from '../models/organizationMemberships.js'; import { Session } from '../models/sessions.js'; +import { AuthEventService } from './authEventService.js'; +import { resolveCustomClaims } from './customClaimService.js'; import { findMembership } from './organizationService.js'; import { permissionsForRoles } from './permissionService.js'; /** - * How much of an access token the organization roles and permission arrays may take, - * serialized. A server adapter keeps the whole token inside a signed cookie, so it is base64 - * encoded twice under the browser's 4 KiB limit. `tests/unit/services/accessTokenService.spec.ts` - * builds that cookie at this budget and holds it under the limit. + * How much of an access token its authorization claims may take together, serialized: the + * permission claims (`permissions`, `org_roles`, `org_permissions`) and the custom claims + * (ADR 0004 P4, ADR 0005 E6). A server adapter keeps the whole token inside a signed cookie, so + * it is base64 encoded twice under the browser's 4 KiB limit. + * `tests/unit/services/accessTokenService.spec.ts` builds that cookie at this budget and holds + * it under the limit. Each custom claim set is separately held to `CUSTOM_CLAIMS_BUDGET_BYTES` + * when written. */ -export const PERMISSION_CLAIMS_BUDGET_BYTES = 1024; +export const AUTHORIZATION_CLAIMS_BUDGET_BYTES = 1024; type AuthorizationInput = { userId: string; @@ -84,35 +88,53 @@ export async function resolveAuthorization({ }; } +export type BudgetedClaims = { + authorization: AuthorizationClaims; + customClaims: Record; + /** Set when the custom claims had to go, with the size that did not fit. */ + customClaimsOmitted: { bytes: number } | null; +}; + +function serializedBytes(claims: Record) { + return Buffer.byteLength(JSON.stringify(claims)); +} + /** - * All or nothing. A partial list looks complete and denies silently, so a set that does not - * fit is replaced with a marker that sends a guard to `GET /users/me/permissions`. + * One budget for every authorization claim, each set kept whole or not at all, since a partial + * list looks complete and denies silently. Permissions give way first: a guard that sees + * `permissions_omitted` reads `GET /users/me/permissions`, and custom claims have no such + * fallback. Custom claims go only when they do not fit even beside the marker. */ -export function authorizationClaims({ - permissions, - organizationId, - organizationRoles, - organizationPermissions, -}: ResolvedAuthorization): AuthorizationClaims { - const claims = { +export function authorizationClaims( + { + permissions, + organizationId, + organizationRoles, + organizationPermissions, + }: ResolvedAuthorization, + customClaims: Record = {}, +): BudgetedClaims { + const permissionClaims = { permissions, ...(organizationId ? { org_roles: organizationRoles, org_permissions: organizationPermissions } : {}), }; - if (Buffer.byteLength(JSON.stringify(claims)) > PERMISSION_CLAIMS_BUDGET_BYTES) { - return { permissions_omitted: true }; + if ( + serializedBytes({ ...customClaims, ...permissionClaims }) <= AUTHORIZATION_CLAIMS_BUDGET_BYTES + ) { + return { authorization: permissionClaims, customClaims, customClaimsOmitted: null }; } - return claims; -} + const marker = { permissions_omitted: true } as const; + const withMarker = serializedBytes({ ...customClaims, ...marker }); -/** Reserved names are refused when written and stripped from hooks; this is the last line. */ -export function withoutReservedClaims(claims: Record | null | undefined) { - return Object.fromEntries( - Object.entries(claims ?? {}).filter(([name]) => !isReservedClaimName(name)), - ); + if (withMarker <= AUTHORIZATION_CLAIMS_BUDGET_BYTES) { + return { authorization: marker, customClaims, customClaimsOmitted: null }; + } + + return { authorization: marker, customClaims: {}, customClaimsOmitted: { bytes: withMarker } }; } /** @@ -160,15 +182,36 @@ export async function mintAccessToken({ ); } - const customClaims = - recovery || leftOrganization ? {} : withoutReservedClaims(session.hookClaims); + const budgeted = authorizationClaims( + authorization, + recovery + ? {} + : await resolveCustomClaims({ + roles: user.roles ?? [], + organizationRoles: authorization.organizationRoles, + hookClaims: leftOrganization ? null : session.hookClaims, + transaction, + }), + ); + + if (budgeted.customClaimsOmitted) { + await AuthEventService.logContext({ + userId: user.id, + sessionId: session.id, + type: 'custom_claims_omitted', + metadata: { + bytes: budgeted.customClaimsOmitted.bytes, + budgetBytes: AUTHORIZATION_CLAIMS_BUDGET_BYTES, + }, + }); + } const token = await signAccessToken( session.id, user.id, user.roles ?? [], authorization.organizationId, - { recovery, authorization: authorizationClaims(authorization), customClaims }, + { recovery, authorization: budgeted.authorization, customClaims: budgeted.customClaims }, ); return { diff --git a/src/services/customClaimService.ts b/src/services/customClaimService.ts new file mode 100644 index 00000000..89cf4d2e --- /dev/null +++ b/src/services/customClaimService.ts @@ -0,0 +1,158 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { type CustomClaimSourceKind, isReservedClaimName } from '@seamless-auth/types'; +import { Op, type Transaction } from 'sequelize'; + +import { getSystemConfig } from '../config/getSystemConfig.js'; +import { CustomClaim } from '../models/customClaims.js'; +import { OidcClient } from '../models/oidcClients.js'; +import { OrganizationRole } from '../models/organizationRoles.js'; + +export class CustomClaimError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = 'CustomClaimError'; + } +} + +export type ClaimSet = Record; + +export function serializeCustomClaimSource(source: CustomClaim) { + return { + sourceKind: source.sourceKind, + sourceName: source.sourceName, + claims: source.claims ?? {}, + updatedAt: source.updatedAt.toISOString(), + }; +} + +export async function listCustomClaimSources() { + return CustomClaim.findAll({ + order: [ + ['sourceKind', 'ASC'], + ['sourceName', 'ASC'], + ], + }); +} + +export async function getCustomClaimSource(sourceKind: CustomClaimSourceKind, sourceName: string) { + const source = await CustomClaim.findOne({ where: { sourceKind, sourceName } }); + if (!source) throw new CustomClaimError(404, 'Custom claims not found'); + return source; +} + +async function sourceExists(sourceKind: CustomClaimSourceKind, sourceName: string) { + switch (sourceKind) { + case 'instance_role': + return ((await getSystemConfig()).available_roles ?? []).includes(sourceName); + case 'organization_role': + return Boolean(await OrganizationRole.findByPk(sourceName)); + case 'oidc_client': + return Boolean(await OidcClient.findByPk(sourceName)); + } +} + +/** + * Replaces the source's whole set. The request schema has already refused reserved names, deep + * values and a set over the budget. The source must exist, so a typo is not stored as claims + * nothing will ever carry. + */ +export async function setCustomClaimSource( + sourceKind: CustomClaimSourceKind, + sourceName: string, + claims: ClaimSet, +) { + if (!(await sourceExists(sourceKind, sourceName))) { + throw new CustomClaimError(404, 'Source not found'); + } + + const existing = await CustomClaim.findOne({ where: { sourceKind, sourceName } }); + const previous = existing ? Object.keys(existing.claims ?? {}) : []; + + if (existing) { + // A new object, so Sequelize sees the JSONB change. + await existing.update({ claims: { ...claims } }); + return { source: existing, previous }; + } + + const source = await CustomClaim.create({ sourceKind, sourceName, claims }); + return { source, previous }; +} + +export async function deleteCustomClaimSource( + sourceKind: CustomClaimSourceKind, + sourceName: string, +) { + const source = await getCustomClaimSource(sourceKind, sourceName); + await source.destroy(); + return source; +} + +/** For a role or client leaving the instance, so adding the name back cannot restore old claims. */ +export async function deleteCustomClaimsFor( + sourceKind: CustomClaimSourceKind, + names: string[], + transaction?: Transaction, +) { + if (names.length === 0) return 0; + return CustomClaim.destroy({ + where: { sourceKind, sourceName: { [Op.in]: names } }, + transaction, + }); +} + +function setsFor(rows: CustomClaim[], kind: CustomClaimSourceKind, names: string[]) { + return [...new Set(names)] + .sort() + .map((name) => rows.find((row) => row.sourceKind === kind && row.sourceName === name)) + .filter((row): row is CustomClaim => row !== undefined) + .map((row) => row.claims ?? {}); +} + +/** + * Instance role sets, then organization role sets (only while the membership exists), then the + * session's hook claims. A later source wins per name, and roles of one kind apply in name order, + * so the result does not depend on the order roles were granted in. Reserved names are filtered + * again here, whatever was stored. The token budget is applied by `authorizationClaims`. + */ +export async function resolveCustomClaims({ + roles, + organizationRoles, + hookClaims, + transaction, +}: { + roles: string[]; + organizationRoles: string[]; + hookClaims: ClaimSet | null | undefined; + transaction?: Transaction; +}): Promise { + const wanted = [ + ...(roles.length ? [{ sourceKind: 'instance_role', sourceName: { [Op.in]: roles } }] : []), + ...(organizationRoles.length + ? [{ sourceKind: 'organization_role', sourceName: { [Op.in]: organizationRoles } }] + : []), + ]; + const rows = wanted.length + ? await CustomClaim.findAll({ where: { [Op.or]: wanted }, transaction }) + : []; + + const merged: ClaimSet = {}; + for (const set of [ + ...setsFor(rows, 'instance_role', roles), + ...setsFor(rows, 'organization_role', organizationRoles), + hookClaims ?? {}, + ]) { + for (const [name, value] of Object.entries(set)) { + if (!isReservedClaimName(name)) merged[name] = value; + } + } + + return merged; +} diff --git a/src/services/oidcApplicationService.ts b/src/services/oidcApplicationService.ts index 8641fe19..4c079f6c 100644 --- a/src/services/oidcApplicationService.ts +++ b/src/services/oidcApplicationService.ts @@ -25,6 +25,7 @@ import type { OidcApplicationUpdateRequest, } from '../schemas/oidcApplications.requests.js'; import type { OidcApplicationView } from '../schemas/oidcApplications.responses.js'; +import { deleteCustomClaimsFor } from './customClaimService.js'; import { createOidcClientSecretLookup, isNativeRedirectUri } from './oidcClientRegistry.js'; import { revokeSessionsExchangedBy } from './sessionRevocation.js'; @@ -309,9 +310,9 @@ export async function rotateOidcApplicationSecret(id: string) { } /** - * Deletes the application with its resource grants, its links in both directions, every - * provider record issued to it (grants, codes and tokens) and the sessions it exchanged for, - * so nothing it was given outlives it. + * Deletes the application with its resource grants, its custom claims, its links in both + * directions, every provider record issued to it (grants, codes and tokens) and the sessions it + * exchanged for, so nothing it was given outlives it. */ export async function deleteOidcApplication(id: string) { const client = await findOidcApplication(id); @@ -320,6 +321,7 @@ export async function deleteOidcApplication(id: string) { await revokeSessionsExchangedBy(id, 'oidc_client_deleted', transaction); await OidcPayload.destroy({ where: { payload: { clientId: id } }, transaction }); await OidcClientResource.destroy({ where: { clientId: id }, transaction }); + await deleteCustomClaimsFor('oidc_client', [id], transaction); await OidcClientLink.destroy({ where: { [Op.or]: [{ clientId: id }, { linkedClientId: id }] }, transaction, diff --git a/src/services/permissionService.ts b/src/services/permissionService.ts index 34dc02b9..9e7366fc 100644 --- a/src/services/permissionService.ts +++ b/src/services/permissionService.ts @@ -12,6 +12,7 @@ import { OrganizationMembership } from '../models/organizationMemberships.js'; import { OrganizationRole } from '../models/organizationRoles.js'; import { Permission } from '../models/permissions.js'; import { RolePermission } from '../models/rolePermissions.js'; +import { deleteCustomClaimsFor } from './customClaimService.js'; export class PermissionError extends Error { constructor( @@ -203,7 +204,7 @@ export async function setRolePermissions({ /** * For a role leaving the instance. Without this, adding the name back later would silently - * restore whatever it used to grant. Returns the roles that held any mapping, for the audit. + * restore whatever it used to grant, permissions and custom claims alike. Returns the roles that held any mapping, for the audit. */ export async function deleteRoleMappings( kind: RoleKind, @@ -212,6 +213,12 @@ export async function deleteRoleMappings( ) { if (names.length === 0) return []; + await deleteCustomClaimsFor( + kind === 'instance' ? 'instance_role' : 'organization_role', + names, + transaction, + ); + const where = { roleKind: kind, roleName: { [Op.in]: names } }; const mappings = await RolePermission.findAll({ where, transaction }); diff --git a/tests/integration/admin/adminStepUp.spec.ts b/tests/integration/admin/adminStepUp.spec.ts index dab8ca7e..2f8af71f 100644 --- a/tests/integration/admin/adminStepUp.spec.ts +++ b/tests/integration/admin/adminStepUp.spec.ts @@ -53,6 +53,8 @@ const GUARDED = [ 'DELETE /admin/login-hooks/{trigger}', 'POST /admin/login-hooks/{trigger}/secret', 'POST /admin/login-hooks/{trigger}/test', + 'PUT /admin/custom-claims/{sourceKind}/{sourceName}', + 'DELETE /admin/custom-claims/{sourceKind}/{sourceName}', 'POST /admin/users', 'POST /admin/users/import', 'DELETE /admin/users', diff --git a/tests/integration/admin/customClaims.spec.ts b/tests/integration/admin/customClaims.spec.ts new file mode 100644 index 00000000..bd6583c9 --- /dev/null +++ b/tests/integration/admin/customClaims.spec.ts @@ -0,0 +1,167 @@ +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/models/oidcClients.js', async (importOriginal) => { + const actual = await importOriginal(); + actual.OidcClient.findByPk = vi.fn() as never; + return actual; +}); + +import { createApp } from '../../../src/app'; +import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { CustomClaim } from '../../../src/models/customClaims.js'; +import { OidcClient } from '../../../src/models/oidcClients.js'; +import { Session } from '../../../src/models/sessions.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory'; +import { buildSystemConfig } from '../../factories/systemConfigFactory'; + +let app: Application; +const now = new Date('2026-11-07T12:00:00.000Z'); + +function buildSource(overrides: Record = {}) { + const record: any = { + sourceKind: 'instance_role', + sourceName: 'user', + claims: { plan: 'pro' }, + createdAt: now, + updatedAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + record.destroy = vi.fn(); + return record; +} + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); + vi.mocked(getSystemConfig).mockResolvedValue({ + ...buildSystemConfig(), + available_roles: ['user', 'admin'], + } as never); +}); + +describe('custom claims admin', () => { + it('lists sources with the reserved names and the budget', async () => { + vi.mocked(CustomClaim.findAll).mockResolvedValue([buildSource()] as never); + + const res = await request(app).get('/admin/custom-claims'); + + expect(res.status).toBe(200); + expect(res.body.sources).toEqual([ + { + sourceKind: 'instance_role', + sourceName: 'user', + claims: { plan: 'pro' }, + updatedAt: now.toISOString(), + }, + ]); + expect(res.body.reservedNames).toContain('sub'); + expect(res.body.reservedPrefixes).toEqual(['seamless_', 'org_']); + expect(res.body.budgetBytes).toBe(1024); + }); + + it('replaces an instance role set and audits the names, not the values', async () => { + vi.mocked(CustomClaim.create).mockImplementation(async (values: any) => buildSource(values)); + + const res = await request(app) + .put('/admin/custom-claims/instance_role/user') + .send({ claims: { plan: 'pro', limits: { seats: 5, regions: ['us', 'eu'] } } }); + + expect(res.status).toBe(200); + expect(res.body.source.claims).toEqual({ + plan: 'pro', + limits: { seats: 5, regions: ['us', 'eu'] }, + }); + const [event] = vi.mocked(AuthEventService.log).mock.calls[0]; + expect(event).toMatchObject({ + type: 'admin_custom_claims_updated', + metadata: { + sourceKind: 'instance_role', + sourceName: 'user', + claimNames: ['plan', 'limits'], + added: ['plan', 'limits'], + removed: [], + }, + }); + expect(JSON.stringify(event.metadata)).not.toContain('"pro"'); + }); + + it.each([ + ['a reserved name', { sub: 'x' }], + ['an OpenID identity claim', { email: 'ceo@example.com' }], + ['a reserved prefix', { org_plan: 'x' }], + ['a name outside the alphabet', { Plan: 'x' }], + ['a value nested deeper than 3', { deep: { a: { b: { c: { d: 1 } } } } }], + ['a set over 1 KiB', { big: 'x'.repeat(1100) }], + ])('refuses %s', async (_name, claims) => { + const res = await request(app).put('/admin/custom-claims/instance_role/user').send({ claims }); + + expect(res.status).toBe(400); + expect(CustomClaim.create).not.toHaveBeenCalled(); + }); + + it('refuses a role or client that does not exist', async () => { + vi.mocked(OidcClient.findByPk).mockResolvedValue(null); + + for (const path of [ + '/admin/custom-claims/instance_role/ghost', + '/admin/custom-claims/organization_role/ghost', + '/admin/custom-claims/oidc_client/ghost', + ]) { + const res = await request(app) + .put(path) + .send({ claims: { plan: 'pro' } }); + expect(res.status).toBe(404); + } + expect(CustomClaim.create).not.toHaveBeenCalled(); + }); + + it('stores an OpenID Provider client set for the provider to apply', async () => { + vi.mocked(OidcClient.findByPk).mockResolvedValue({ id: 'cli' } as never); + vi.mocked(CustomClaim.create).mockImplementation(async (values: any) => buildSource(values)); + + const res = await request(app) + .put('/admin/custom-claims/oidc_client/cli') + .send({ claims: { tenant: 'acme' } }); + + expect(res.status).toBe(200); + expect(res.body.source).toMatchObject({ sourceKind: 'oidc_client', sourceName: 'cli' }); + }); + + it('refuses an unknown source kind', async () => { + const res = await request(app) + .put('/admin/custom-claims/session/x') + .send({ claims: { plan: 'pro' } }); + expect(res.status).toBe(400); + }); + + it('reads and deletes a set, auditing the delete', async () => { + const record = buildSource(); + vi.mocked(CustomClaim.findOne).mockResolvedValue(record as never); + + expect((await request(app).get('/admin/custom-claims/instance_role/user')).status).toBe(200); + + const deleted = await request(app).delete('/admin/custom-claims/instance_role/user'); + + expect(deleted.status).toBe(200); + expect(record.destroy).toHaveBeenCalled(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_custom_claims_deleted', + metadata: { sourceKind: 'instance_role', sourceName: 'user', claimNames: ['plan'] }, + }), + ); + }); + + it('answers 404 for a source with no set', async () => { + expect((await request(app).get('/admin/custom-claims/instance_role/user')).status).toBe(404); + expect((await request(app).delete('/admin/custom-claims/instance_role/user')).status).toBe(404); + }); +}); diff --git a/tests/integration/admin/permissions.spec.ts b/tests/integration/admin/permissions.spec.ts index e459c019..0fe36dbf 100644 --- a/tests/integration/admin/permissions.spec.ts +++ b/tests/integration/admin/permissions.spec.ts @@ -10,6 +10,9 @@ import { OrganizationRole } from '../../../src/models/organizationRoles.js'; import { Permission } from '../../../src/models/permissions.js'; import { RolePermission } from '../../../src/models/rolePermissions.js'; import { Session } from '../../../src/models/sessions.js'; +import { CustomClaim } from '../../../src/models/customClaims.js'; +import { signAccessToken } from '../../../src/lib/token.js'; +import { mintAccessToken } from '../../../src/services/accessTokenService.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { buildFreshStepUpSession, buildSession } from '../../factories/sessionFactory'; @@ -441,6 +444,35 @@ describe('organization role catalogue', () => { }); describe('GET /users/me/permissions', () => { + it('returns the full set when the token gave its permissions way to custom claims', async () => { + const permissions = Array.from({ length: 50 }, (_, index) => `resource-${index}:read`).sort(); + const plan = 'x'.repeat(200); + // The permissions fit alone; only beside the custom claims do they go over. + expect(Buffer.byteLength(JSON.stringify({ permissions }))).toBeLessThan(1024); + (RolePermission.findAll as any).mockResolvedValue( + permissions.map((permissionName) => ({ permissionName })), + ); + vi.mocked(CustomClaim.findAll).mockResolvedValue([ + { sourceKind: 'instance_role', sourceName: 'user', claims: { plan } }, + ] as never); + + await mintAccessToken({ + session: { id: 'session-1' }, + user: { id: 'user-1', roles: ['user'] }, + }); + + const [, , , , options] = vi.mocked(signAccessToken).mock.calls[0]; + expect(options).toMatchObject({ + authorization: { permissions_omitted: true }, + customClaims: { plan }, + }); + + const res = await request(app).get('/users/me/permissions'); + + expect(res.status).toBe(200); + expect(res.body.permissions).toEqual(permissions); + }); + it('answers with what the caller holds now', async () => { (RolePermission.findAll as any).mockResolvedValue([{ permissionName: 'invoices:read' }]); diff --git a/tests/postgres/customClaims.spec.ts b/tests/postgres/customClaims.spec.ts new file mode 100644 index 00000000..cdc4da23 --- /dev/null +++ b/tests/postgres/customClaims.spec.ts @@ -0,0 +1,145 @@ +import { randomUUID } from 'crypto'; +import { decodeJwt } from 'jose'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { invalidateSystemConfigCache } from '../../src/config/getSystemConfig.js'; +import { AuthEvent } from '../../src/models/authEvents.js'; +import { CustomClaim } from '../../src/models/customClaims.js'; +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { OidcClient } from '../../src/models/oidcClients.js'; +import { mintAccessToken } from '../../src/services/accessTokenService.js'; +import { setCustomClaimSource } from '../../src/services/customClaimService.js'; +import { deleteOidcApplication } from '../../src/services/oidcApplicationService.js'; +import { + createOrganizationRole, + deleteRoleMappings, +} from '../../src/services/permissionService.js'; +import { buildSystemConfig } from '../factories/systemConfigFactory.js'; + +vi.hoisted(() => { + process.env.ISSUER = 'http://localhost:5312'; +}); + +type Models = Awaited>; +let models: Models; + +const role = 'claims-role'; + +async function setAvailableRoles(roles: string[]) { + for (const [key, value] of Object.entries(buildSystemConfig({ available_roles: roles }))) { + await getSequelize().query( + `INSERT INTO system_config (key, value, "createdAt", "updatedAt") + VALUES (:key, CAST(:value AS jsonb), now(), now()) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, + { replacements: { key, value: JSON.stringify(value) } }, + ); + } + invalidateSystemConfigCache(); +} + +beforeAll(async () => { + models = await initializeModels(); +}); + +beforeEach(async () => { + await getSequelize().query('DELETE FROM custom_claims;'); + await setAvailableRoles(['user', role]); +}); + +afterAll(async () => { + await getSequelize().query('DELETE FROM custom_claims;'); + await setAvailableRoles(['user']); + await getSequelize().close(); +}); + +async function member(orgRoles: string[]) { + const { Organization, OrganizationMembership, Session, User } = models; + const userId = randomUUID(); + const user = await User.create({ + id: userId, + email: `${userId}@example.com`, + phone: null, + roles: [role], + }); + const organization = await Organization.create({ + name: `Acme ${userId.slice(0, 8)}`, + slug: `acme-${userId.slice(0, 8)}`, + }); + const membership = await OrganizationMembership.create({ + organizationId: organization.id, + userId, + roles: orgRoles, + }); + const now = Date.now(); + const session = await Session.create({ + userId, + organizationId: organization.id, + mode: 'server', + refreshTokenLookup: randomUUID(), + expiresAt: new Date(now + 3_600_000), + idleExpiresAt: new Date(now + 3_600_000), + hookClaims: { seats: 10 }, + }); + return { user, organization, membership, session }; +} + +describe('custom claims on the deployed schema', () => { + it('merge instance, organization and hook claims into the token, until the member leaves', async () => { + const orgRole = `claims-org-${randomUUID().slice(0, 8)}`; + await createOrganizationRole({ name: orgRole, actorUserId: null }); + await setCustomClaimSource('instance_role', role, { plan: 'free', region: 'us' }); + await setCustomClaimSource('organization_role', orgRole, { plan: 'team', seats: 5 }); + const { user, membership, session } = await member([orgRole]); + + const before = decodeJwt((await mintAccessToken({ session, user })).token); + expect(before).toMatchObject({ plan: 'team', region: 'us', seats: 10 }); + + await membership.destroy(); + const after = decodeJwt((await mintAccessToken({ session, user })).token); + expect(after).toMatchObject({ plan: 'free', region: 'us' }); + expect(after).not.toHaveProperty('seats'); + }); + + it('omits them all, and records it, when the sources together exceed the budget', async () => { + await setCustomClaimSource('instance_role', role, { a: 'x'.repeat(1000) }); + const { user, session } = await member([]); + await session.update({ hookClaims: { b: 'y'.repeat(100) } }); + + const claims = decodeJwt((await mintAccessToken({ session, user })).token); + + expect(claims).not.toHaveProperty('a'); + expect(claims).not.toHaveProperty('b'); + const event = await AuthEvent.findOne({ + where: { type: 'custom_claims_omitted', session_id: session.id }, + }); + expect(event?.metadata).toMatchObject({ budgetBytes: 1024 }); + }); + + it('are deleted with a role or client leaving the instance, so the name cannot get them back', async () => { + const clientId = `claims-${randomUUID()}`; + await OidcClient.create({ + id: clientId, + name: clientId, + firstParty: true, + clientType: 'public', + tokenEndpointAuthMethod: 'none', + redirectUris: ['http://127.0.0.1/cb'], + }); + await setCustomClaimSource('instance_role', role, { plan: 'pro' }); + await setCustomClaimSource('oidc_client', clientId, { tenant: 'acme' }); + + await deleteRoleMappings('instance', [role]); + await deleteOidcApplication(clientId); + + expect(await CustomClaim.count()).toBe(0); + }); + + it('refuses a source kind the table does not know', async () => { + await expect( + getSequelize().query( + `INSERT INTO custom_claims ("sourceKind", "sourceName", claims, "createdAt", "updatedAt") + VALUES ('session', 'x', '{}', now(), now())`, + ), + ).rejects.toThrow(/custom_claims_source_kind/); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 6b72a589..d18e6788 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -212,6 +212,15 @@ vi.mock('../../src/models/webhookDeliveries.js', () => ({ }, })); +vi.mock('../../src/models/customClaims.js', () => ({ + CustomClaim: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findOne: vi.fn(async () => null), + destroy: vi.fn(async () => 0), + }, +})); + vi.mock('../../src/models/loginHooks.js', () => ({ LoginHook: { create: vi.fn(), diff --git a/tests/unit/models/models.spec.ts b/tests/unit/models/models.spec.ts index 17975d10..4beb14ca 100644 --- a/tests/unit/models/models.spec.ts +++ b/tests/unit/models/models.spec.ts @@ -16,6 +16,7 @@ vi.unmock('../../../src/models/organizationMemberships.js'); vi.unmock('../../../src/models/organizationRoles.js'); vi.unmock('../../../src/models/permissions.js'); vi.unmock('../../../src/models/rolePermissions.js'); +vi.unmock('../../../src/models/customClaims.js'); vi.unmock('../../../src/models/loginHookInvocations.js'); vi.unmock('../../../src/models/loginHooks.js'); vi.unmock('../../../src/models/webhookDeliveries.js'); diff --git a/tests/unit/services/accessTokenService.spec.ts b/tests/unit/services/accessTokenService.spec.ts index ed8c73d1..806b57fe 100644 --- a/tests/unit/services/accessTokenService.spec.ts +++ b/tests/unit/services/accessTokenService.spec.ts @@ -13,14 +13,16 @@ vi.mock('../../../src/utils/signingKeyStore.js', () => ({ })); import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { CustomClaim } from '../../../src/models/customClaims.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; import { signAccessToken } from '../../../src/lib/token.js'; import { OrganizationMembership } from '../../../src/models/organizationMemberships.js'; import { RolePermission } from '../../../src/models/rolePermissions.js'; import { Session } from '../../../src/models/sessions.js'; import { + AUTHORIZATION_CLAIMS_BUDGET_BYTES, authorizationClaims, mintAccessToken, - PERMISSION_CLAIMS_BUDGET_BYTES, resolveAuthorization, } from '../../../src/services/accessTokenService.js'; import { getSigningKey } from '../../../src/utils/signingKeyStore.js'; @@ -51,7 +53,9 @@ function fittingPermissions() { for (let index = 0; ; index += 1) { const next = [...permissions, `resource-${index}:action`]; - if (Buffer.byteLength(JSON.stringify({ permissions: next })) > PERMISSION_CLAIMS_BUDGET_BYTES) { + if ( + Buffer.byteLength(JSON.stringify({ permissions: next })) > AUTHORIZATION_CLAIMS_BUDGET_BYTES + ) { return permissions; } @@ -59,6 +63,15 @@ function fittingPermissions() { } } +/** One string claim padded so the set serializes to exactly `bytes`. */ +function claimsOf(bytes: number, name = 'pad') { + return { [name]: 'x'.repeat(bytes - JSON.stringify({ [name]: '' }).length) }; +} + +function bytesOf(claims: Record) { + return Buffer.byteLength(JSON.stringify(claims)); +} + const organizationId = '2c0d53c2-a541-452b-b71b-54c7f15e5877'; const noOrganization = { organizationId: null, organizationRoles: [], organizationPermissions: [] }; @@ -157,31 +170,39 @@ describe('resolveAuthorization', () => { describe('authorizationClaims', () => { const resolved = { roles: [], permissions: [], ...noOrganization }; + const marker = { permissions_omitted: true }; it('carries a set that fits, with no organization claims outside an organization', () => { expect(authorizationClaims({ ...resolved, permissions: ['a:read'] })).toEqual({ - permissions: ['a:read'], + authorization: { permissions: ['a:read'] }, + customClaims: {}, + customClaimsOmitted: null, }); }); it('carries the organization claims inside one, even when empty', () => { expect( - authorizationClaims({ ...resolved, organizationId, organizationRoles: ['member'] }), + authorizationClaims({ ...resolved, organizationId, organizationRoles: ['member'] }) + .authorization, ).toEqual({ permissions: [], org_roles: ['member'], org_permissions: [] }); }); - it('carries a set exactly at the budget', () => { + it('carries permissions exactly at the budget', () => { const permissions = fittingPermissions(); - expect(authorizationClaims({ ...resolved, permissions })).toEqual({ permissions }); + expect(authorizationClaims({ ...resolved, permissions }).authorization).toEqual({ + permissions, + }); }); // A partial list looks complete and denies silently, so nothing is trimmed. - it('replaces a set over the budget with the marker', () => { + it('replaces permissions over the budget with the marker', () => { const permissions = [...fittingPermissions(), 'one-more:action']; expect(authorizationClaims({ ...resolved, permissions })).toEqual({ - permissions_omitted: true, + authorization: marker, + customClaims: {}, + customClaimsOmitted: null, }); }); @@ -192,8 +213,66 @@ describe('authorizationClaims', () => { organizationId, organizationRoles: ['member'], organizationPermissions: fittingPermissions(), - }), - ).toEqual({ permissions_omitted: true }); + }).authorization, + ).toEqual(marker); + }); + + describe('shared with custom claims', () => { + const permissions = ['reports:read', 'projects:write']; + const permissionBytes = bytesOf({ permissions }); + // `{...custom, permissions}` joins the two objects with one comma, losing a brace each. + const customRoom = AUTHORIZATION_CLAIMS_BUDGET_BYTES - permissionBytes + 1; + + it('carries everything when permissions and custom claims together are exactly at the budget', () => { + const custom = claimsOf(customRoom); + expect(bytesOf({ ...custom, permissions })).toBe(AUTHORIZATION_CLAIMS_BUDGET_BYTES); + + expect(authorizationClaims({ ...resolved, permissions }, custom)).toEqual({ + authorization: { permissions }, + customClaims: custom, + customClaimsOmitted: null, + }); + }); + + it('omits the permissions first, keeping the custom claims, one byte over', () => { + const custom = claimsOf(customRoom + 1); + + expect(authorizationClaims({ ...resolved, permissions }, custom)).toEqual({ + authorization: marker, + customClaims: custom, + customClaimsOmitted: null, + }); + }); + + it('keeps custom claims that fit exactly beside the marker', () => { + const room = AUTHORIZATION_CLAIMS_BUDGET_BYTES - bytesOf(marker) + 1; + const custom = claimsOf(room); + expect(bytesOf({ ...custom, ...marker })).toBe(AUTHORIZATION_CLAIMS_BUDGET_BYTES); + + expect( + authorizationClaims({ ...resolved, permissions: fittingPermissions() }, custom), + ).toMatchObject({ authorization: marker, customClaims: custom, customClaimsOmitted: null }); + }); + + it('omits both when the custom claims do not fit even beside the marker', () => { + const room = AUTHORIZATION_CLAIMS_BUDGET_BYTES - bytesOf(marker) + 1; + const custom = claimsOf(room + 1); + + expect(authorizationClaims({ ...resolved, permissions }, custom)).toEqual({ + authorization: marker, + customClaims: {}, + customClaimsOmitted: { bytes: AUTHORIZATION_CLAIMS_BUDGET_BYTES + 1 }, + }); + }); + + it('omits only the custom claims when there are no permissions to give way', () => { + const custom = claimsOf(1100); + + expect(authorizationClaims(resolved, custom)).toMatchObject({ + authorization: marker, + customClaims: {}, + }); + }); }); }); @@ -326,41 +405,153 @@ describe('mintAccessToken', () => { expect(claims).not.toHaveProperty('plan'); }); - /** - * A server adapter signs the whole access token into a cookie alongside the user's details - * (`issueSessionCookies` in seamless-auth-server), and browsers drop a cookie over 4 KiB, - * which would sign the user out. This builds that cookie at the worst case the budget allows. - */ - it('keeps the adapter session cookie under the browser limit at the budget', async () => { - const longRoles = Array.from({ length: 5 }, (_, index) => `billing:invoices:role-${index}`); - const authorization = authorizationClaims({ - roles: longRoles, - permissions: fittingPermissions(), - ...noOrganization, - }); + it('carries instance role claims, then organization role claims, then hook claims', async () => { + memberOf(['admin']); + vi.mocked(CustomClaim.findAll).mockResolvedValue([ + { sourceKind: 'instance_role', sourceName: 'user', claims: { plan: 'free', region: 'us' } }, + { sourceKind: 'organization_role', sourceName: 'admin', claims: { plan: 'team', seats: 5 } }, + ] as never); - expect(authorization.permissions_omitted).toBeUndefined(); + const claims = decodeJwt( + ( + await mintAccessToken({ + session: { ...session, organizationId, hookClaims: { seats: 10 } }, + user, + }) + ).token, + ); - const token = await signAccessToken(session.id, user.id, longRoles, organizationId, { - authorization, - }); + expect(claims).toMatchObject({ plan: 'team', region: 'us', seats: 10 }); + }); - const cookie = await new SignJWT({ - sub: user.id, - sessionId: session.id, - token, - roles: longRoles, - email: `${'a'.repeat(64)}@${'b'.repeat(40)}.example.com`, - phone: '+15555550100', - organizationId, - }) - .setProtectedHeader({ alg: 'HS256' }) - .setIssuedAt() - .setExpirationTime('15m') - .sign(new TextEncoder().encode('cookie-secret-cookie-secret-cookie')); + it('applies organization role claims only while the membership exists', async () => { + (OrganizationMembership.findOne as any).mockResolvedValue(null); + vi.mocked(CustomClaim.findAll).mockResolvedValue([ + { sourceKind: 'organization_role', sourceName: 'admin', claims: { plan: 'team' } }, + ] as never); + + await mintAccessToken({ session: { ...session, organizationId }, user }); + + const where = vi.mocked(CustomClaim.findAll).mock.calls[0][0]!.where as any; + const sources = where[Object.getOwnPropertySymbols(where)[0]]; + expect(sources.map((source: any) => source.sourceKind)).toEqual(['instance_role']); + }); + + it('gives a recovery token no custom claims and reads none', async () => { + await mintAccessToken({ session: { ...session, recovery: true }, user }); + expect(CustomClaim.findAll).not.toHaveBeenCalled(); + }); + + it('omits the custom claims, and records why, when they do not fit even beside the marker', async () => { + vi.mocked(CustomClaim.findAll).mockResolvedValue([ + { sourceKind: 'instance_role', sourceName: 'user', claims: { a: 'x'.repeat(700) } }, + ] as never); + + const claims = decodeJwt( + ( + await mintAccessToken({ + session: { ...session, hookClaims: { b: 'y'.repeat(700) } }, + user, + }) + ).token, + ); + + expect(claims).not.toHaveProperty('a'); + expect(claims).not.toHaveProperty('b'); + expect(claims).not.toHaveProperty('permissions'); + expect(claims.permissions_omitted).toBe(true); + expect(claims.roles).toEqual(['user']); + expect(AuthEventService.logContext).toHaveBeenCalledWith( + expect.objectContaining({ + userId: user.id, + sessionId: session.id, + type: 'custom_claims_omitted', + metadata: { bytes: expect.any(Number), budgetBytes: 1024 }, + }), + ); + }); - const setCookie = `seamless-access=${cookie}; Max-Age=900; Path=/; HttpOnly; Secure; SameSite=Lax`; + it('omits the permissions and keeps the custom claims when only the custom claims fit', async () => { + mappings(...fittingPermissions()); + vi.mocked(CustomClaim.findAll).mockResolvedValue([ + { sourceKind: 'instance_role', sourceName: 'user', claims: { plan: 'pro' } }, + ] as never); - expect(Buffer.byteLength(setCookie)).toBeLessThanOrEqual(4096); + const claims = decodeJwt((await mintAccessToken({ session, user })).token); + + expect(claims.plan).toBe('pro'); + expect(claims.permissions_omitted).toBe(true); + expect(claims).not.toHaveProperty('permissions'); + expect(AuthEventService.logContext).not.toHaveBeenCalled(); }); + + /** + * A server adapter signs the whole access token into a cookie alongside the user's details + * (`issueSessionCookies` in seamless-auth-server), and browsers drop a cookie over 4 KiB, + * which would sign the user out. This builds that cookie at the worst case the shared budget + * allows, however the budget is split between permissions and custom claims. + */ + it.each([ + ['all permissions', () => ({ permissions: fittingPermissions(), custom: {} })], + [ + 'permissions and custom claims together', + () => { + const permissions = fittingPermissions().slice(0, 20); + return { + permissions, + custom: claimsOf(AUTHORIZATION_CLAIMS_BUDGET_BYTES - bytesOf({ permissions }) + 1), + }; + }, + ], + [ + 'custom claims beside the marker', + () => ({ + permissions: [...fittingPermissions(), 'one-more:action'], + custom: claimsOf( + AUTHORIZATION_CLAIMS_BUDGET_BYTES - bytesOf({ permissions_omitted: true }) + 1, + ), + }), + ], + ])( + 'keeps the adapter session cookie under the browser limit at the budget: %s', + async (_name, build) => { + const { permissions, custom } = build(); + const longRoles = Array.from({ length: 5 }, (_, index) => `billing:invoices:role-${index}`); + const budgeted = authorizationClaims( + { roles: longRoles, permissions, ...noOrganization }, + custom, + ); + + expect(budgeted.customClaimsOmitted).toBeNull(); + expect(bytesOf({ ...budgeted.customClaims, ...budgeted.authorization })).toBeLessThanOrEqual( + AUTHORIZATION_CLAIMS_BUDGET_BYTES, + ); + expect( + bytesOf({ ...budgeted.customClaims, ...budgeted.authorization }), + ).toBeGreaterThanOrEqual(AUTHORIZATION_CLAIMS_BUDGET_BYTES - 32); + + const token = await signAccessToken(session.id, user.id, longRoles, organizationId, { + authorization: budgeted.authorization, + customClaims: budgeted.customClaims, + }); + + const cookie = await new SignJWT({ + sub: user.id, + sessionId: session.id, + token, + roles: longRoles, + email: `${'a'.repeat(64)}@${'b'.repeat(40)}.example.com`, + phone: '+15555550100', + organizationId, + }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuedAt() + .setExpirationTime('15m') + .sign(new TextEncoder().encode('cookie-secret-cookie-secret-cookie')); + + const setCookie = `seamless-access=${cookie}; Max-Age=900; Path=/; HttpOnly; Secure; SameSite=Lax`; + + expect(Buffer.byteLength(setCookie)).toBeLessThanOrEqual(4096); + }, + ); }); diff --git a/tests/unit/services/customClaimService.spec.ts b/tests/unit/services/customClaimService.spec.ts new file mode 100644 index 00000000..b70211b5 --- /dev/null +++ b/tests/unit/services/customClaimService.spec.ts @@ -0,0 +1,235 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/models/oidcClients.js', () => ({ + OidcClient: { findByPk: vi.fn() }, +})); + +import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { CustomClaim } from '../../../src/models/customClaims.js'; +import { OidcClient } from '../../../src/models/oidcClients.js'; +import { OrganizationRole } from '../../../src/models/organizationRoles.js'; +import { + CustomClaimError, + deleteCustomClaimsFor, + deleteCustomClaimSource, + getCustomClaimSource, + listCustomClaimSources, + resolveCustomClaims, + serializeCustomClaimSource, + setCustomClaimSource, +} from '../../../src/services/customClaimService.js'; + +const at = new Date('2026-11-07T12:00:00.000Z'); + +function row(sourceKind: string, sourceName: string, claims: Record) { + const record: any = { sourceKind, sourceName, claims, createdAt: at, updatedAt: at }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + record.destroy = vi.fn(); + return record; +} + +function stored(...rows: ReturnType[]) { + vi.mocked(CustomClaim.findAll).mockResolvedValue(rows as never); +} + +beforeEach(() => { + vi.mocked(getSystemConfig).mockResolvedValue({ available_roles: ['user', 'billing'] } as never); +}); + +describe('resolveCustomClaims', () => { + it('reads nothing when there are no roles', async () => { + expect( + await resolveCustomClaims({ roles: [], organizationRoles: [], hookClaims: null }), + ).toEqual({}); + expect(CustomClaim.findAll).not.toHaveBeenCalled(); + }); + + it('applies instance roles, then organization roles, then the hook, later winning per name', async () => { + stored( + row('instance_role', 'user', { plan: 'free', region: 'us', tier: 1 }), + row('organization_role', 'admin', { plan: 'team', seats: 5 }), + ); + + const resolved = await resolveCustomClaims({ + roles: ['user'], + organizationRoles: ['admin'], + hookClaims: { plan: 'enterprise' }, + }); + + expect(resolved).toEqual({ plan: 'enterprise', region: 'us', tier: 1, seats: 5 }); + }); + + it('applies instance roles in name order, whatever order they were granted in', async () => { + stored( + row('instance_role', 'zeta', { plan: 'z' }), + row('instance_role', 'alpha', { plan: 'a' }), + ); + + const first = await resolveCustomClaims({ + roles: ['zeta', 'alpha'], + organizationRoles: [], + hookClaims: null, + }); + const second = await resolveCustomClaims({ + roles: ['alpha', 'zeta'], + organizationRoles: [], + hookClaims: null, + }); + + expect(first).toEqual({ plan: 'z' }); + expect(second).toEqual({ plan: 'z' }); + }); + + it('applies organization roles in name order, whatever order they were granted in', async () => { + stored( + row('organization_role', 'owner', { plan: 'owner' }), + row('organization_role', 'billing', { plan: 'billing' }), + ); + + for (const organizationRoles of [ + ['owner', 'billing'], + ['billing', 'owner'], + ]) { + expect(await resolveCustomClaims({ roles: [], organizationRoles, hookClaims: null })).toEqual( + { plan: 'owner' }, + ); + } + }); + + it('never lets an organization role set apply as an instance one', async () => { + stored(row('organization_role', 'admin', { plan: 'team' })); + + expect( + await resolveCustomClaims({ roles: ['admin'], organizationRoles: [], hookClaims: null }), + ).toEqual({}); + }); + + it('filters reserved names, whatever was stored', async () => { + stored(row('instance_role', 'user', { sub: 'x', org_id: 'y', email: 'z', plan: 'pro' })); + + expect( + await resolveCustomClaims({ + roles: ['user'], + organizationRoles: [], + hookClaims: { iss: 'h' }, + }), + ).toEqual({ plan: 'pro' }); + }); + + it('merges sources whole, leaving the budget to the mint', async () => { + stored(row('instance_role', 'user', { a: 'x'.repeat(600) })); + + expect( + await resolveCustomClaims({ + roles: ['user'], + organizationRoles: [], + hookClaims: { b: 'y'.repeat(600) }, + }), + ).toEqual({ a: 'x'.repeat(600), b: 'y'.repeat(600) }); + }); + + it('treats a stored set with no claims as empty', async () => { + stored(row('instance_role', 'user', null as never)); + expect( + await resolveCustomClaims({ roles: ['user'], organizationRoles: [], hookClaims: undefined }), + ).toEqual({}); + }); +}); + +describe('admin', () => { + it('serializes a source', () => { + expect(serializeCustomClaimSource(row('oidc_client', 'cli', { a: 1 }))).toEqual({ + sourceKind: 'oidc_client', + sourceName: 'cli', + claims: { a: 1 }, + updatedAt: at.toISOString(), + }); + expect(serializeCustomClaimSource(row('oidc_client', 'cli', null as never)).claims).toEqual({}); + }); + + it('lists in a stable order', async () => { + await listCustomClaimSources(); + expect(CustomClaim.findAll).toHaveBeenCalledWith({ + order: [ + ['sourceKind', 'ASC'], + ['sourceName', 'ASC'], + ], + }); + }); + + it('answers 404 for a source with no claims', async () => { + await expect(getCustomClaimSource('instance_role', 'user')).rejects.toMatchObject({ + status: 404, + }); + }); + + it.each([ + ['an instance role outside available_roles', 'instance_role', 'ghost'], + ['an organization role outside the catalogue', 'organization_role', 'ghost'], + ['an OpenID Provider client that does not exist', 'oidc_client', 'ghost'], + ] as const)('refuses %s', async (_name, kind, name) => { + vi.mocked(OrganizationRole.findByPk).mockResolvedValue(null); + vi.mocked(OidcClient.findByPk).mockResolvedValue(null); + + await expect(setCustomClaimSource(kind, name, { plan: 'pro' })).rejects.toBeInstanceOf( + CustomClaimError, + ); + expect(CustomClaim.create).not.toHaveBeenCalled(); + }); + + it('refuses an instance role when no roles are configured', async () => { + vi.mocked(getSystemConfig).mockResolvedValue({} as never); + await expect(setCustomClaimSource('instance_role', 'user', {})).rejects.toMatchObject({ + status: 404, + }); + }); + + it('creates a set for a source that exists', async () => { + vi.mocked(OidcClient.findByPk).mockResolvedValue({ id: 'cli' } as never); + vi.mocked(CustomClaim.create).mockImplementation(async (values: any) => values); + + const { source, previous } = await setCustomClaimSource('oidc_client', 'cli', { plan: 'pro' }); + + expect(source).toMatchObject({ sourceKind: 'oidc_client', claims: { plan: 'pro' } }); + expect(previous).toEqual([]); + }); + + it('replaces an existing set whole', async () => { + vi.mocked(OrganizationRole.findByPk).mockResolvedValue({ name: 'admin' } as never); + const existing = row('organization_role', 'admin', { old: 1, kept: 2 }); + vi.mocked(CustomClaim.findOne).mockResolvedValue(existing as never); + + const { previous } = await setCustomClaimSource('organization_role', 'admin', { kept: 3 }); + + expect(previous).toEqual(['old', 'kept']); + expect(existing.update).toHaveBeenCalledWith({ claims: { kept: 3 } }); + }); + + it('reports a replaced set that had no claims as empty', async () => { + const existing = row('instance_role', 'user', null as never); + vi.mocked(CustomClaim.findOne).mockResolvedValue(existing as never); + + expect((await setCustomClaimSource('instance_role', 'user', {})).previous).toEqual([]); + }); + + it('deletes a set', async () => { + const existing = row('instance_role', 'user', {}); + vi.mocked(CustomClaim.findOne).mockResolvedValue(existing as never); + + await deleteCustomClaimSource('instance_role', 'user'); + + expect(existing.destroy).toHaveBeenCalled(); + }); + + it('deletes the sets of sources leaving the instance, and nothing when none', async () => { + expect(await deleteCustomClaimsFor('instance_role', [])).toBe(0); + expect(CustomClaim.destroy).not.toHaveBeenCalled(); + + await deleteCustomClaimsFor('organization_role', ['legacy']); + expect(CustomClaim.destroy).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ sourceKind: 'organization_role' }), + }), + ); + }); +});