Users & tokens API
Users are identity records within a tenant. Each user has a role and can hold multiple auth tokens. Tokens are the credentials used to authenticate inference requests.
Base URL: https://<your-gateway-host>/admin/v1
Endpoints
Users
The {id} in every /users/{id} route is matched byte-exact. An id that differs from a real user id only in letter case, a trailing space or an invisible character (such as a zero-width space) answers 404, exactly like an unknown id.
| Method | Path | Description |
|---|---|---|
GET |
/users |
List tenant-less platform-level users (scope=platform, the default), every user of every live tenant (scope=all), or the users of deleted tenants (scope=deleted_tenants) — platform admin only |
POST |
/users/search |
Find users in your own tenant by exact email, sent in the JSON body (any member — powers project/group/agent member pickers; the GET ?email= form is deprecated) |
POST |
/users/roster/search |
Find colleagues in your own tenant by part of a name or email, sent in the JSON body (any member except a viewer or the demo identity — powers the workflow Approval step's approver box) |
GET |
/users/{id}/reactivation-status |
A member's reactivation e-mail opt-out and send history (USERS_MANAGE + REQUEST_LOGS_VIEW) — see Reactivation e-mails |
GET |
/users/{id}/erase/preview |
Show what erasing the user would do, without changing anything — see Previewing an erasure |
DELETE |
/users/{id}/erase |
Erase a user and hand over their shared agents — see Erasing a user |
GET / PUT |
/users/{id}/department |
Read or set the user's department — see Assigning a department |
GET |
/user-types |
List the available chat-persona roles |
GET |
/tenants/{id}/users |
List users for a tenant |
GET |
/users/{id} |
Get a single user (USERS_MANAGE) |
POST |
/tenants/{id}/users |
Create a user (sends an invitation email) |
POST |
/users/{id}/resend-invite |
Resend the invitation email |
PATCH |
/users/{id} |
Update a user. A role change applies on the user's next admin request, open sessions included (no re-login). An email change is guarded and signs the user out everywhere — sessions, API tokens, device sign-ins and pending one-time codes are revoked and the user's push-notification registrations removed (see Updating a user) |
DELETE |
/users/{id} |
Soft-delete a user (sets deleted_at; locks out the account; frees the address for a new invite). The user's agents that are shared with the organisation, a group or other users are handed to a successor and stay paused until the successor confirms them; the successor is notified after the commit. With no live successor, the user's agents are left exactly as they were (kept, still shared, schedules unchanged); only a SCIM deprovision also unpublishes them and disables their schedules |
POST |
/users/{id}/move |
Move a user to another tenant — a fresh account with the same address in the target tenant; the old account and its data stay with the old tenant (platform admin only, see Moving a user to another tenant) |
POST |
/users/{id}/restore |
Restore a soft-deleted user (admin path; no self-service). Agents handed over at deletion and not yet confirmed by the successor return to the restored user; restoring a live user is 200 already_active and changes nothing |
POST |
/users/{id}/disable |
Disable a user: block login and end every session/API token permanently on every device (re-enabling restores login but does not revive them) |
POST |
/users/{id}/enable |
Re-enable a disabled user (login restored; the sessions and API tokens that existed before the disable stay ended — the user signs in afresh) |
GET / DELETE |
/users/{id}/sso-links |
List the user's SSO identity links, or unlink one exact link (USERS_MANAGE) — see SSO links |
PUT |
/users/{id}/static-otp |
Set or clear a fixed OTP code for a user (platform admin only) |
GET |
/static-otp/legacy?kind=user\|partner |
List accounts whose fixed code is still a legacy (pre-12-character) code (see Legacy static codes) |
DELETE |
/users/{id}/budget |
Reset all token spend counters for a user (not the per-user budget below) |
PUT |
/users/{id}/budget-cap |
Set or remove a member's personal budget (an optional per-user spending cap) — see Per-user budgets |
GET |
/users/{id}/spend-limits |
The effective spend limits of a member, computed by the same resolver as /me (spend_limits per scope, effective_limit_scope; the user entry carries source: person, department or tenant) plus the member's department ({id, name} or null). Needs TENANT_SETTINGS_MANAGE or BUDGETS_MANAGE, like the user-budgets read; same tenant fence as the budget-cap PUT (read-only, so no rank check); 409 user_budget_not_on_trial on a trial workspace. Period spend (used_usd) and the user entry's status (derived from that spend) are included only for a caller with COGS_PER_USER_VIEW, like the user-budgets list. A limit that cannot be read is readable: false, never omitted as unlimited. For a caller with COGS_PER_USER_VIEW the response also carries department_spend_this_month: [{ department_id, name, cost_usd }], the member's chargeback this calendar month per department ([] when none) (a single member can have spend in several departments after moves; spend with no department has an empty department_id and empty name, a deleted department a non-empty department_id and empty name; the UI labels both in the user's language). This is the cost-allocation view, not the budget ledger the department cap counts. Omitted without the permission, and omitted when the cost read faults |
GET |
/tenants/{id}/user-budgets |
The workspace's per-user budgets for the current period (allocation summary + one entry per member) |
Tokens
Creating, editing and revoking a gateway token requires GATEWAY_TOKENS_MANAGE and access to the gateway; the user-token routes require USERS_MANAGE.
| Method | Path | Description |
|---|---|---|
GET |
/gateways/{id}/tokens |
List a gateway's tokens (requires GATEWAY_TOKENS_MANAGE; 403 otherwise; the gateway's own internal service credentials are excluded — see Internal service credentials — and so are grant-managed tokens: device sessions and MCP OAuth grants) |
POST |
/gateways/{id}/tokens |
Create a gateway-scoped token |
PATCH |
/gateways/{id}/tokens/{tid} |
Edit an existing token's rate_limit / budget_usd / expires_at (an internal service credential → 403; a device-session or MCP OAuth grant token → 404, as for an unknown id) |
DELETE |
/gateways/{id}/tokens/{tid} |
Revoke a token (an internal service credential → 403; a device-session or MCP OAuth grant token → 404, as for an unknown id; revoke those through their device session or MCP grant) |
GET |
/users/{id}/tokens |
List tokens belonging to a user (USERS_MANAGE; token hashes are never returned). Unlike the user's own GET /me/tokens, it includes the short-lived playground session tokens |
POST |
/users/{id}/tokens |
Create a user-scoped token (on a gateway of the user's own workspace only). Optional body field step_up_token (step-up); required only for a caller on password and second-factor sign-in, who gets 403 step_up_required without it; other callers need not send it and the field is ignored. The check comes after the permission, tenant, rank, gateway, label, scope and lifetime checks and right before the token is created. The signed-in admin's sign-in policy decides, not the target user's: a platform admin whose own policy is not password_mfa mints a token without a step-up while admin_mfa_enforced is off, even when the target user's organisation is on password_mfa |
Self-service (my tokens)
| Method | Path | Description |
|---|---|---|
GET |
/me/tokens |
List the caller's own tokens |
POST |
/me/tokens |
Create a token for the caller |
DELETE |
/me/tokens/{tid} |
Revoke one of the caller's own tokens |
Users
Listing users
Returns one tenant's members (all roles). Requires USERS_MANAGE and access to that tenant. Takes the
sort, dir and include_deleted parameters described under Query parameters.
Response: same row shape as listing all users below,
including assignable_roles:
[
{
"id": "usr_abc123",
"tenant_id": "ten_xyz",
"email": "alice@example.com",
"name": "Alice",
"role": "member",
"created_at": 1742551200,
"assignable_roles": []
}
]
Listing all users (platform-level)
GET /admin/v1/users — platform administrators only (USERS_GLOBAL_MANAGE, a platform permission
no tenant role can hold; any other signed-in caller gets 403, a caller without a session 401). The scope parameter selects the list:
scope |
Returns |
|---|---|
platform (default) |
Only tenant-less, platform-level users (tenant_id === null). |
all |
Every user of every live tenant plus the tenant-less users, in one response — the platform-wide member roster. Users of a soft-deleted tenant, and users whose tenant no longer exists, are not included. |
deleted_tenants |
The users whose tenant is no longer live — soft-deleted, or its row no longer exists. These accounts cannot sign in and still hold their email address; move or delete them. Tenant-less platform users are never included. Same parameters, single read and 422 roster_too_large ceiling as all. |
scope=all is answered from a single database read, so the list is a consistent snapshot: one request
returns the complete roster, however many tenants there are. It is not paginated; filter and page it on
the client. If the roster ever exceeds 50,000 users the request is refused with 422 roster_too_large
rather than answered with a truncated list; list one tenant at a time instead
(GET /admin/v1/tenants/{tenant_id}/users).
Query parameters
These apply to GET /admin/v1/users (both scopes) and GET /admin/v1/tenants/{tenant_id}/users.
| Parameter | Type | Default | Accepted values |
|---|---|---|---|
scope |
string | platform |
platform or all. Only on GET /admin/v1/users. |
sort |
string | email |
email, name, role, tenant, department (the name of the department that applies, see department_name below; no department sorts first in ascending order), last_login_at, created_at. Rows with equal sort values are ordered by email, then id (in the same direction as dir), so two reads return the same order. Text is compared case- and accent-insensitively (the database collation). |
dir |
string | asc |
asc or desc (lower case). |
include_deleted |
string | 0 |
1 or true also returns soft-deleted users; 0 or false (or omitting it) returns active users only. |
Each parameter may be given once. A value outside the accepted set is rejected with 400 and a
machine-readable code; it never falls back to the default:
code |
When |
|---|---|
invalid_scope |
scope is not platform or all (also: empty, repeated, or given without a value). |
invalid_sort |
sort is not one of the listed columns (also: repeated, or given without a value). |
invalid_dir |
dir is not asc or desc (also: upper case, repeated, or given without a value). |
invalid_include_deleted |
include_deleted is not 1, true, 0 or false (also: repeated, or given without a value). |
invalid_param |
scope sent to GET /admin/v1/tenants/{tenant_id}/users, or more than 100 query parameters. |
Other, unknown parameters are ignored, except the five paging and filter names below. Permission checks
run first: a caller without the required permission gets 403 whatever the parameters are.
Paging and filtering the tenant list
GET /admin/v1/tenants/{tenant_id}/users returns a bare array, exactly as before, unless limit or
offset is present. Then it returns the envelope { "items": [...], "total": N, "limit": L, "offset": O },
where total counts the rows matching the filters (not just this page).
| Parameter | Accepted values | Rejected with 400 |
|---|---|---|
limit |
Plain decimal integer, at least 1. Default 50 when only offset is sent. A value above 500 is capped at 500 (the envelope's limit shows the value used). |
invalid_limit: 0, a sign, a decimal point, an exponent, hex, whitespace, more than 9 digits, empty, repeated, or given without a value. |
offset |
Plain decimal integer, at least 0. A value above 100000000 is capped at 100000000. An offset past the end returns items: [] with the true total. |
invalid_offset: same rules as limit. |
q |
Search text, 1 to 200 characters after trimming. Matches name or email, case- and accent-insensitively; %, _ and ! match literally. |
invalid_q: empty or whitespace only, longer than 200 characters, not valid UTF-8, repeated, or given without a value. |
department |
A department id, or none for members without a department. It matches the department that applies to the user, the same value as effective_department_id (so a user without an assignment of their own matches the tenant's default department, and none lists exactly the users with no department in effect). An id of another tenant's department matches nobody. |
invalid_department: anything else, repeated, or given without a value. |
group |
A group id. An id of another tenant's group matches nobody. | invalid_group: anything else, repeated, or given without a value. |
Filters combine (AND). On GET /admin/v1/users all five names are rejected with 400 invalid_param
("… is not accepted on this list").
Response: array of user rows.
| Field | Type | Description |
|---|---|---|
id |
string | User UUID. |
tenant_id |
string | Tenant UUID. Absent (the key is left out) for a tenant-less platform user. |
email |
string | Email address. |
name |
string | Display name. Absent when the user has none. |
role |
string | One of admin, tenant_admin, ki_manager, finance, member, viewer, or demouser. Absent for a user with no role on record. |
tenant_slug |
string | Slug of the user's tenant. Absent for a tenant-less platform user. |
created_at |
integer | Creation time as a Unix timestamp (seconds). |
last_login_at |
integer | Last successful login as a Unix timestamp (seconds). Absent if never. |
deleted_at |
integer | Soft-delete time as a Unix timestamp (seconds). Absent if active. |
deleted_by_id |
string | UUID of the admin who deleted the user. Absent if active. Also absent when the deleting account was later erased or its tenant purged. |
disabled_at |
integer | Disable (suspension) time as a Unix timestamp (seconds). Absent if not disabled. Independent of deleted_at. |
department_id |
string | The user's own department assignment. Absent when the user has none (see Departments). |
effective_department_id |
string | List endpoints only. The department that applies to the user: their own assignment, otherwise the tenant's default department (unless an admin pinned "no department"). Absent when no department applies, or the assigned department no longer exists. |
department_name |
string | List endpoints only. The name of effective_department_id. Absent together with it. |
department_from_idp |
integer | List endpoints only. 1 when the identity provider set the user's department (the admin UI marks it "IdP"), 0 otherwise, including a tenant default. |
role_from_idp |
integer | List endpoints. 1 when the user's role comes from an identity-provider group mapping, 0 otherwise. |
can_manage |
boolean | Whether the caller passes the out-rank rule for this user (always true for the caller's own account) — see Acting on another user requires out-ranking them. Present on the list and get endpoints. |
processing_restricted |
integer | 1 when the user is under a GDPR Art. 18 processing hold, 0 otherwise (a missing or unrecognised stored value is enforced as a hold and reported as 1) (see Restricting processing). Returned, in this canonical form, by every endpoint that returns the user: list, get, PATCH, and the disable / enable responses; set via PATCH. |
assignable_roles |
string[] | What THIS ROW's own role tier may assign to others — server-derived from the same ASSIGNABLE_ROLES authority every actual role-assignment re-checks (never client-computed). Powers the admin UI's "Can assign" column. [] for a role with no assignable roles (ki_manager, finance, member, viewer, demouser) or an absent/unmapped role. Present on this endpoint, GET /tenants/{id}/users, and GET /users/{id} only — not on the PATCH/disable/enable responses. |
[
{
"id": "usr_abc123",
"tenant_id": "ten_xyz",
"email": "alice@example.com",
"name": "Alice",
"role": "member",
"tenant_slug": "myapp",
"created_at": 1742551200,
"last_login_at": 1742637600,
"processing_restricted": 0,
"assignable_roles": [],
"can_manage": true
}
]
Searching users by email
Looks up users in the caller's own tenant by exact email match (up to 5 results; letter case is ignored). Available to any authenticated admin user that belongs to a tenant. The address is sent in a JSON body — never in the URL, because the web server writes request lines into its error log.
curl -X POST "https://<your-gateway-host>/admin/v1/users/search" \
-H "Content-Type: application/json" \
-d '{"email": "alice@example.com"}'
| Body field | Type | Required | Description |
|---|---|---|---|
email |
string | Yes | Exact email address to match. Surrounding whitespace is trimmed; at most 1024 characters, valid UTF-8. |
Returns a JSON array ([] when nobody matches). Rejections: 400 { "error": "email parameter required", "code": "email_required" } if email is absent, empty or whitespace-only; 400 { "error": "…", "code": "invalid_email" } if it is not a string, not valid UTF-8 or longer than 1024 characters; 400 malformed_body for a body that is not a JSON object; 400 for a non-JSON Content-Type; 400 pii_in_query if ?email= is also in the query string; 400 { "error": "user has no tenant" } if the caller has no tenant. A database fault is 503 (retry) — never an empty result, so "no such user" and "lookup failed" stay distinguishable.
Deprecated: GET /admin/v1/users/search?email=… still answers the same way until 11 January 2027 and carries Deprecation / Sunset headers; a repeated ?email= is invalid_email. See Search and lookup values travel in the request body.
Response: array of matching users (max 5), each with id, email, and name.
Searching the roster
POST /admin/v1/users/roster/search finds users in the caller's own tenant whose name or email contains the text you send (letter case is ignored); an exact address match is listed first, so typing a colleague's full address always finds them. It powers the approver box of the workflow Approval step; the exact-email lookup above is unchanged.
curl -X POST "https://<your-gateway-host>/admin/v1/users/roster/search" \
-H "Content-Type: application/json" \
-d '{"query": "tanavde"}'
| Body field | Type | Required | Description |
|---|---|---|---|
query |
string | Yes | Part of a name or email. Surrounding whitespace is trimmed; at least 2 characters (an emoji counts as one) and at most 1024, valid UTF-8. %, _ and ! match literally. |
Who may call it: the same callers who may already browse the tenant roster by creating a project: any signed-in user of a tenant except a viewer and the shared demo identity (demouser). Everyone else gets 403 { "code": "roster_search_forbidden" } and should use the exact-email lookup. The 403 is answered before the body is read, so a malformed body from a viewer is still 403. Administrators impersonating a user may call it.
Result: a JSON array of up to 10 users, ordered by email, except that an exact address match comes first, each with id, email and name. Disabled and deleted users are never returned (a user who cannot sign in cannot act as an approver). Users of other tenants are never returned.
Rejections (400): query_required (absent, empty or whitespace-only), invalid_query (not a string, not valid UTF-8, or longer than 1024 characters), query_too_short (fewer than 2 characters after trimming), malformed_body (the body is not a JSON object), pii_in_query (?query= in the URL), a non-JSON Content-Type, and { "error": "user has no tenant" } for a caller without a tenant. Control characters are not rejected; they simply match nobody. A database fault is 503 (retry), never an empty result. There is no GET form.
Getting a user
Returns the single user record, including assignable_roles (see the field table above). The caller must have access to the user (require_user_access); otherwise the request is rejected. Returns 404 { "error": "user not found", "code": "user_not_found" } if no such user exists.
Creating a user
curl -X POST https://<your-gateway-host>/admin/v1/tenants/{tenant_id}/users \
-H "Content-Type: application/json" \
-d '{
"email": "alice@example.com",
"name": "Alice",
"role": "member"
}'
| Field | Type | Required | Description |
|---|---|---|---|
email |
string | Yes | Email address of the user. Must be globally unique. |
name |
string | No | Display name — a valid UTF-8 string of at most 255 characters (code points, not bytes), or null/absent for none. A non-string, a longer value or invalid UTF-8 is HTTP 400 with code invalid_name or name_too_long, and nothing is created. |
role |
string | No | One of tenant_admin, ki_manager, finance, member, viewer, or demouser. Defaults to member only when the key is absent: a present role that is not a string (null, false, 42, an object) is 400 { "error": "role must be a string", "code": "invalid_role" } and nothing is created, never the silent member. Only platform admin users can create other admin accounts. The finance role is a billing-scoped role assignable by admin and tenant_admin; see the Finance API. |
inviter_locale |
string | No | The inviting admin's interface language ("en" or "de"; a region tag such as "de-DE" is folded). Used only to seed the tenant's default e-mail language (default_locale) the first time a member of the same tenant invites — and only as a fallback when the inviter's own stored locale is unset (the stored value wins). Never overwrites an existing default; never seeds when the actor is a platform operator from outside the tenant, or when the invite itself is refused (403/409/404). Accepted: a string that names a supported language. Ignored (never a 400): absent, empty, an unsupported language, a non-string — nothing is written and the invitation goes out in the tenant's current default (English when none). The seed is audited (tenant.default_locale_seeded). |
Response: 201 { "id": "usr_abc123", "email": "alice@example.com", "invitation_mail": "queued" }. invitation_mail says what happened to the invitation e-mail: queued (it is being sent), suppressed (the tenant is suspended, nothing is sent), state_unknown (the tenant's suspension state could not be read, nothing is sent; see below) or not_queued (the server could not schedule the send, nothing is sent; logged, use the resend). queued means the mail was handed to the mail sender; a delivery failure after that is logged, not reported here
The invitation is stored under the organization's stored id, whatever letter case the URL uses. If the stored organization record carries no usable id, the answer is a 500 server error (not retryable: the record must be repaired) and nothing is created.
Errors: 400 { "error": "email required", "code": "email_required" } (email absent); 400 { "error": "email must be a string", "code": "invalid_email" } (email is JSON null, a number, a boolean or an object: present but malformed; nothing is created); 400 { "error": "email required", "code": "email_required" } for ""; 400 { "error": "invalid body", "code": "invalid_body" } (the body is JSON null, an array or a scalar; nothing is created or sent); 400 { "error": "email must be a valid address", "code": "invalid_email", "field": "email" } (a string that is not a valid address — local@domain.tld, a single @, a dotted domain, 3–254 bytes, printable ASCII only: a non-ASCII character (e.g. jörg@firma.de, a no-break space or byte-order mark), invalid UTF-8 or a control byte is refused because such an account could never sign in; the address is checked as sent, never trimmed, coerced or lower-cased, and nothing is created, no seat is used and no invitation is sent); 500 { "error": "internal error", "request_id": "…" } an unexpected server fault (the cause is logged under that request id, never returned); 403 role not assignable by the caller, or seat_limit_reached (the tenant is at its seat cap); 404 tenant not found (also when the tenant was deleted while the invitation was being created); 409 { "error": "email already in use", "code": "email_in_use" } (the address belongs to another active account — addresses are globally unique; see Address conflicts). A deadlock with a concurrent write (or another immediate serialization abort the database asks the client to restart — e.g. two invitations created at the same moment) is retried by the server: the whole create runs again from scratch, up to 4 attempts with a short backoff, and can never create a second account for the address. Only when the conflict persists through every attempt, or no database connection could be obtained, does the request answer 503 { "error": "temporarily unavailable; retry later" }: nothing was created and no invitation was sent, so retrying the same request is safe. Two concurrent invitations of the same address end as one 201 and one 409. A 503 is also returned when the tenant's seat cap cannot be resolved (fail closed). While a seat reduction is scheduled (see Billing), the cap is the scheduled count, and the 403 seat_limit_reached body also carries scheduled_seats, scheduled_effective_at (unix seconds) and a human-readable note; a scheduled increase never raises the cap, and a schedule never lowers an unlimited cap (a tenant without a seat limit stays unlimited).
Accepted address shape (create and email change): local@domain.tld — printable ASCII only, a single @ with non-empty sides, a dotted domain without a leading, trailing or doubled dot, no whitespace or control bytes, 3–254 bytes. The address is validated as sent — never trimmed or repaired — so a leading or trailing space, a no-break space, a BOM, a non-ASCII character such as jörg@firma.de, or invalid UTF-8 is refused. The stored address is the one-time-passcode sign-in identity, so an address nobody can receive mail at would be an account nobody can sign in to. A missing email (email required) and a wrong type (email must be a string) are different answers from a malformed address (invalid_email). The same 400 {"code":"invalid_email","field":"email"} applies to create and to an email change.
Address conflicts
When the invited address already belongs to another active account, the answer is 409 with
"code": "email_in_use". What else the body carries depends on the caller:
-
Platform administrators (
USERS_GLOBAL_MANAGE) also get aholderobject, so they can resolve the conflict — typically by moving that user into this tenant:{ "error": "email already in use", "code": "email_in_use", "holder": { "user_id": "…", "tenant_id": "…", "tenant_slug": "acme-trial", "tenant_deleted": true, "platform_user": false } }tenant_deletedistruewhen the holder's tenant was deleted (the user is stranded: they cannot sign in). A tenant-less platform account hasplatform_user: trueand notenant_id/tenant_slug; it cannot be moved into a tenant. -
Everyone else (a tenant administrator above all) gets only
errorandcode— never another customer's tenant name, id or user id. The admin console adds a hint to contact Myra support.
If the holder cannot be looked up, a platform administrator gets the same short answer (no holder).
For a suspended tenant (a platform admin acting for it) the user is still created and 201 is answered with invitation_mail: "suppressed", but no invitation e-mail is sent; use the resend after the tenant is resumed. When the tenant's suspension state cannot be read, the user is created too and the 201 carries invitation_mail: "state_unknown": no e-mail is sent and none is sent later, so use the resend once the state can be read again (until then the resend answers 503 tenant_state_unknown). The state is checked before the answer, so the body says whether a mail was handed to the sender. (tests: tests/unit/test_admin_api.lua "MAP-4136 invite") The invitation e-mail is sent in the tenant's default e-mail language (see above), else English; the resend uses the member's own locale when set, then the tenant default, then English.
Updating a user
Required permission: USERS_MANAGE (Manage tenant users; held by tenant_admin and admin by default, grantable through a custom role). Accepts any subset of email, name (the same rule as on invite: a valid UTF-8 string of at most 255 characters, else 400 with code invalid_name / name_too_long; null clears the name; omit the key to leave it unchanged), role, processing_restricted, reactivation_opted_out (see Reactivation e-mails), and conversation_retention_days (an integer 30–3650, or null/0 to clear the per-user override; any other value returns 400). Any other key is refused 400 unknown_field (see below). tenant_id does not move a user: a tenant_id equal to the user's current tenant (any letter case) is accepted and changes nothing; any other value — another tenant, null, a non-string, or any value on a tenant-less user — is 409 {"error": …, "code": "use_move_endpoint"} and nothing is changed (for a user of a live tenant, a non-platform-admin gets 403 first). To move a user use POST /users/{id}/move. A user of a deleted tenant (see Moving a user to another tenant) cannot be edited with PATCH: for a platform admin, a tenant_id that is not the deleted tenant's own id (another tenant, null, a non-string, "") returns the same 409 use_move_endpoint; every other request — tenant_id absent or equal to the deleted tenant's id (any letter case), a body that is not a JSON object, or an account that is itself deleted — returns 404 {"error":"not found"}, and malformed JSON returns 400. Nothing is changed in any of these cases. Anyone else (a tenant admin included) gets exactly the 404 (or the 403 of the permission check) that a non-existent user id gets, so the answer does not reveal that such a user exists. Every field is checked before anything is changed: a 400 or 403 (or a 503 from a failed read) means none of the request was applied. A non-platform-admin editing their own record cannot change their own role or tenant_id (both return 403; see Editing your own record).
Accepted fields and unknown keys. The body may contain only email, name, role, processing_restricted, reactivation_opted_out, conversation_retention_days and tenant_id (the last is refused 403/409 as described above). Any other key is refused 400 { "error": "unknown_field", "code": "unknown_field", "field": "<key>" } (the echoed field is capped at 64 bytes) and nothing is written — a misspelt processing_restriced can therefore never answer 200 while leaving an Art. 18 restriction unset. A body that is not a JSON object is 400.
curl -X PATCH https://<your-gateway-host>/admin/v1/users/{id} \
-H "Content-Type: application/json" \
-d '{"role": "viewer"}'
A tenant-scoped role needs a home tenant. tenant_admin, ki_manager and finance only mean something inside a tenant. A PATCH that changes the role of a user with no home tenant (a platform user, tenant_id null) to one of them is refused 409 {"error": "role '<role>' needs a user with a home tenant — this user has none", "code": "role_requires_tenant"} and nothing is changed (a name or email in the same request is not applied either). The check runs after the permission, own-role and out-rank checks. A tenant-less account cannot be given a tenant (POST /users/{id}/move refuses it with 409 platform_user): to make the person a tenant role holder, erase the account (DELETE /users/{id}/erase; a soft-deleted account still reserves its address) and invite the address into the organisation with that role. The check does not fire when the role is omitted or re-sent unchanged, so an account already in that state can still be renamed; to repair it, change its role to member or viewer, or erase it and invite the address into the organisation. Any role on a user who has a home tenant, and admin / member / viewer on a tenant-less user, are not affected.
Changing a user's email is an account-identity change and is guarded. Because email one-time-passcode sign-in resolves by the stored address, moving a user's email would otherwise redirect their next login code — an account-takeover vector. When (and only when) the request actually changes the email:
- A malformed address is rejected with
400({"error":"email must be a valid address","code":"invalid_email","field":"email"}, the same body as on create) — never coerced or truncated. The accepted shape is the one stated under Accepted address shape above (printable ASCII only, validated as sent, not trimmed), identical to create. Anull/omittedemail, or one equal to the stored value, is not an email change and is not validated (so a legacy stored address can be re-sent unchanged). - The change to a different user requires the caller to out-rank the target — the same role hierarchy that governs role assignment and the processing hold. A caller may change an email only on a user whose role they could also assign, so a delegate holding
USERS_MANAGEvia a custom role but whose base role ismembercannot rewrite atenant_admin's (or any peer's) email — the request returns403. Likewise atenant_admincannot change the email of anothertenant_admin(the tenant owners) or of a platform admin —403target_outranks_caller; only a platform admin can. Editing your own email is always allowed (self-service) — except while impersonating, where the viewed account is never treated as your own and the rank rule applies. Aname-only edit by that same delegate still succeeds (200) — the delegation feature is not affected. - A successful email change ends every credential of the target — the same rule as an email change by SCIM (SCIM). In the same transaction as the address change it stamps the per-user session-revocation floor (
sessions_valid_after), so an admin cookie issued before the change is rejected with401on its next/admin/request; revokes every/v1API token the user owns — personal tokens and the MCP connection tokens of the user's agents included, so an external integration must be reconnected — (a later call with one gets the typedtoken_revoked401; they are removed from the token cache right after the change, so none survives even briefly); revokes the user's device sign-ins (device-code token families and their refresh tokens) and denies a device code or MCP consent the user approved but that was not redeemed yet; removes the user's push-notification device registrations (the tokens registered throughPOST /me/device-token, so a device that was signed in no longer receives this account's notifications — the app registers again after its next sign-in); and deletes the pending sign-in one-time codes, magic links and password reset links of the old address (a code or link mailed before the change no longer works; matched as stored and in lower case) and of the new address (a code someone requested for the new address before the change cannot sign into this account afterwards). The user (and anyone riding a stale credential) must sign in afresh at the new address and mint new tokens. This also applies when you change your own address. A request that does not change the address (name / role only, or the stored address re-sent unchanged) revokes nothing. If any of these steps fails, nothing is changed (the request answers503or500as described under Storage failures below). - An address already in use by another account (a live account, or a soft-deleted one that still reserves the address) returns
409{"error":"email already in use"}, never a raw500. Reclaiming a departed user's address requires erasing the old record first.
Storage failures. The identity update (email, name, role and, on an email change, the credential revocation above) and its audit rows (user.rectified, plus user.email_changed for an email change and user.role_changed for a role change) are one transaction: an audit row that cannot be written rolls the change back, and the request is never answered 200 for a change that was not recorded. The update is conditional on the record still matching what the request read: a concurrent change to the same user answers 409 { "code": "user_changed_concurrently" } (nothing written; reload and re-apply) and a user removed meanwhile answers 404 { "code": "user_not_found" }. processing_restricted, reactivation_opted_out and conversation_retention_days are each written in their own short transaction after it, in that order, each together with its own audit row. Every one of these writes is retried by the server on a deadlock with a concurrent write (up to 4 attempts; a write re-runs from scratch, so nothing is applied twice). A conflict that persists through every attempt, or a write that could not obtain a database connection, answers 503 { "error": "temporarily unavailable; retry later" }: the write that failed changed nothing, but the writes of the same PATCH that ran before it (for example the identity update before a retention change) may already be applied. Re-sending the same PATCH is safe — every field is an absolute value, so the already-applied part is a no-op. Any other server fault answers 500 { "error": "internal error", "request_id": "…" } — the cause is logged under that request id and the database's error text is never returned.
Editing your own record
A non-platform-admin cannot change their own role or tenant_id. When the caller is not a platform admin and the target user is themselves ({id} == the caller's own id):
- A
rolechange is rejected with403({"error":"you cannot change your own role"}) — regardless of how many other administrators exist. A tenant admin cannot demote themselves out of the admin set (a self-inflicted lockout: amembercannot manage users and atenant_admincannot re-grant thetenant_adminrole), and no self-service role change on one's own account serves any other purpose. Absent vs malformed: an omittedrole(or one equal to the current value) is a no-op and is allowed; a non-stringroleis rejected with400— neither degrades into a permissive write. - A
tenant_idin the body is rejected with403({"error":"only platform admins may change a user's tenant"}) — moving a user to another tenant is a platform-level operation, never self-service (this applies to any non-platform-admin, self or not). - Other self-edits are unaffected: changing your own
nameoremail(self-service, subject to the email guard above) still returns200.
A platform admin editing any record (including their own) is exempt. A tenant admin editing a different user's role is unaffected (subject to the role-assignment hierarchy). The client is never the authorization boundary — the UI hides these fields on your own row, and the server enforces the rejection.
Demoting the last administrator is refused. A role change that would move the tenant's sole active administrator (admin or tenant_admin) out of the admin set is rejected with 409 {"error": …, "code": "last_admin_blocked"} — the same guard (and code) the delete and disable paths use. Because a non-platform-admin's own role change is already refused by the self-edit guard above, this 409 governs demoting another administrator (for example a platform admin demoting the only other tenant admin): a demotion keeps the user but strips the tenant's last admin, leaving nobody who can manage the organisation and no in-product way back. Promote another administrator first, then retry. A role change that keeps the user an administrator, or that targets a non-administrator, is unaffected.
The same rank check guards conversation_retention_days on a different user (RBAC-2): it arms irreversible automated deletion of that user's conversations, so a delegate may set it only on a user they out-rank (else 403); setting your own retention is self-service.
Changes to email, name or role are recorded in the audit log as a user.rectified event (GDPR Art. 16). The event stores only the names of the changed fields — never the old or new values — so that a later Art. 17 erasure cannot leak personal data through the retained audit trail. An email change additionally writes a user.email_changed event whose before/after holds only the email domain ({ "email_domain": "corp.example" } → { "email_domain": "other.example" }, lower-cased; "" when the stored address has no domain part; written for every address change, so a change of the local part or of letter case shows the same domain on both sides), never the address — the same disclosure as the SCIM scim.user_email_changed event — so an investigator can see that an account was moved to another domain. It is written in the same transaction as the change. The tenant audit view lists the event without its before/after.
Assigning a department
PUT /admin/v1/users/{id}/department with { "department_id": "<id>" | null } (the key is required; null removes the user from their department). Requires DEPARTMENTS_MANAGE. See Departments API. PATCH /users/{id} does not move a user between tenants; a move (POST /users/{id}/move) creates a new account in the target tenant without a department — the department stays with the old account in the old tenant.
Bulk department and group changes
POST /admin/v1/users/bulk applies one change to many users atomically: either every listed user
is changed or none is.
{ "op": "department",
"user_ids": ["0b6c1f6e-6a1e-4d0e-9a3c-2f1e8f3f7a10", "5d2e9c41-8b7a-4f63-a1d2-7c9e0b3a4f55"],
"department_id": "c3a9e7d2-1f4b-4c8e-9d6a-0e2b7f5a1c33" }
| Field | Meaning |
|---|---|
op |
department, group_add or group_remove. |
user_ids |
1 to 1000 distinct user ids. Each id is matched byte-exact against the stored user id: a spelling variant (another letter case, a trailing space, an invisible character) answers the same 404 as an unknown user, for every op. |
department_id |
op=department only; the key is required. A department id exactly as the API lists it (generated as a lower-case uuid); an id with invisible or non-uuid characters is rejected as malformed (invalid_department_id) before any lookup, while a well-formed different spelling (for example another letter case) is refused like an unknown one, or null to clear the department. |
group_id |
Required for group_add and group_remove. Matched byte-exact against the stored group id: a spelling variant of an existing id answers the same 404 as an unknown group. |
tenant_id |
Required for a platform admin; all users and the department or group must belong to it. |
Requires DEPARTMENTS_MANAGE for department, GROUPS_MANAGE for the group operations. Success is
{ "ok": true, "op": "...", "count": N }; the group operations also return changed, the number of memberships that
really changed (users already in the group on group_add, and non-members on group_remove, count in count but not in
changed). Only real changes are audited: one group.member_added / group.member_removed event per user whose
membership changed, none for an unchanged one. The department operation also returns impact, a list of
{ "user_id", "agents", "scheduled_tasks", "workflows" } (at most 200 entries) for the users whose items
become unavailable in the new department, and impact_complete (false when the list was cut off).
Every refusal applies nothing:
| Status | Code | When |
|---|---|---|
400 |
invalid_body |
The body is a JSON scalar, array or null (a JSON scalar, array or null body → 400 invalid_body); an absent body is treated as {}. |
400 |
invalid_op |
op is missing or not one of the three operations. |
400 |
invalid_user_ids |
user_ids is missing, not an array, empty, or an element is not a user id string (the message names the index). |
400 |
too_many_user_ids |
More than 1000 ids. |
400 |
duplicate_user_id |
The same id twice (compared case-insensitively). |
400 |
department_id_required / invalid_department_id |
op=department without the department_id key (absent or "") / with a value that is neither an id nor null. |
400 |
invalid_group_id |
A group operation without a valid group_id. |
400 |
invalid_param |
A field of the other operation is sent (group_id with department, department_id with a group operation). |
400 / 404 |
tenant_id_required, invalid_tenant_id / tenant_not_found |
Platform admin: tenant_id missing or "" (tenant_id_required), null, not a string or not a tenant id (invalid_tenant_id), or a well-formed id that is not a live tenant (tenant_not_found). |
401 |
unauthenticated |
No session. |
403 |
shared-gate code / target_outranks_caller / group_not_manageable |
The permission is missing (the shared-gate code); the caller may not act on one of the users (role rank, or their own department as a delegate: target_outranks_caller); or, for group operations, the caller may not manage the group (group_not_manageable). |
403 |
shared-gate code | The group operations apply the same gates as the single member routes: a group that carries gateway grants additionally needs DEPARTMENTS_MANAGE (a department delegate may only change members of their own department; a delegate acting on themselves or on a user who out-ranks them is refused department_self_management / department_target_outranks), and a group with a member limit additionally needs TENANT_SETTINGS_MANAGE. A refusal refuses the whole batch. |
404 |
Any id is unknown, belongs to another tenant or is soft-deleted (group_remove accepts soft-deleted members of the tenant), or the group does not exist in the tenant. A group_id you cannot see (unknown, another tenant's, malformed) on group_add / group_remove is the audited 404 (group and role ids): one access.denied event, no entity. |
|
422 |
department_not_found |
The department does not exist in the tenant, or the id is not the stored spelling of one (upper-case, padded). |
409 |
users_changed |
A user was deleted or moved between the check and the write, or (group_remove) a membership of one of the users in the group was added, removed or changed its source meanwhile; nothing was removed. Retry. |
409 |
last_owner |
group_remove would leave a project without an owner; projects lists them ({id, name}). Do not retry unchanged. |
409 |
idp_managed |
group_add into an identity-provider-managed group, or group_remove of a scim member from one (the same answer as the single member routes). |
409 |
membership_managed_by_idp |
group_remove: at least one of the users holds an identity-provider membership (scim, saml_claim, scim_attr, oidc_claim) in the group; user_ids lists them. Nothing was removed and nothing audited; remove those users in the IdP, or send only manually added members. |
503 |
Storage fault, or a lock held for longer than 5 seconds; nothing was applied and no audit row was written. Retry. | |
500 |
Sanitised internal error; the change was not applied or its outcome is unknown. |
Every membership change and its group.member_added / group.member_removed events (or, for department, the department change and its event) commit in one transaction with the users' check.
group_remove additionally applies the role-rank check per user, which the single
DELETE /groups/{id}/members/{user_id} route does not.
Restricting processing (GDPR Art. 18)
processing_restricted is a boolean. When true, the user is placed under a reversible legal hold: every inference request they make (raw /v1, /easy/playground, and any agent the user owns) is rejected with 403 processing_restricted and no model is ever called. The hold is independent of the viewer role and of soft/hard deletion. Send false to lift it.
curl -X PATCH https://<your-gateway-host>/admin/v1/users/{id} \
-H "Content-Type: application/json" \
-d '{"processing_restricted": true}'
Only a real JSON boolean is accepted — any other type (1, "true", 0) is rejected with 400, never silently dropped, so an admin sending 0/"false" to lift a hold can never receive a 200 with the hold still in place. A caller may only toggle the restriction on a user whose role they could also assign: a tenant_admin cannot restrict a platform admin or a peer tenant_admin (the request returns 403 { "code": "target_outranks_caller" }, nothing applied), mirroring the role-change hierarchy. A restricted registrant is also not exported to Salesforce (events and backfill skip them), but setting the hold sends Salesforce one restriction notice (processing_restricted: true; it carries only the e-mail key plus event, timestamp and flag, no name or other lead data) so Sales stops contacting them; lifting the hold exports them right away (see Salesforce lead sync). A toggle to the value the account already holds is a no-op (no write, no audit). A real change emits a user.processing_restricted / user.processing_unrestricted audit event (actor + timestamp, no values).
App-feedback inbox. The in-app feedback entries of a restricted author stay listed in GET /admin/v1/app-feedback, but their diagnostics and screenshots are withheld: client_context, url and the image fields are empty and the entry carries personal_data_withheld: "processing_restricted"; for an automatic app diagnostic (recognised by its content, not only its status) the probe description is null and the summary is the fixed label AIG_MIC_DIAG; a content edit of such an entry is refused with 409 personal_data_withheld; the image routes return the same marker instead of image data (see Feedback). Lifting the hold restores them. The hold never limits the restricted person's own access: their own data export and My feedback screenshots stay complete.
Feedback triage queue. Feedback a restricted user writes (in-app feedback, chat feedback, content reports) is still stored and visible to admins, but it is never copied into the model_error triage queue the headless triage agent reads, and a copy already in the queue is withheld from the agent (not leased, not shown by list/context, and excluded from the counts the triage agent sees and acts on in assess; assess reports the open held rows only as the numbers held_restricted and held rows already resolved needs_human (awaiting a person) as held_restricted_needs_human, so neither is silently dropped). While a restriction lasts, the author's rows are also left out of the assessment's historic statistics (by source, resolutions, tickets, latency, recurring) and come back when it is lifted. The ids and ticket references of rows that were already escalated before the restriction still appear in the escalation lists of assess (no author text; their context stays refused). A human close (needs_human resolution by an admin) still works. The hold is derived from the user's current state: lifting the restriction releases existing queue copies immediately (the hold is a live predicate), while submissions that were never mirrored are copied on the next reconcile; there is no stored pause state. An author with no user row is treated as restricted (fail closed); an anonymous submission (no user) is not.
Other triage sources. The same hold covers the rest of what the triage agent reads. For a restricted person the technical error stays in the queue and can still be claimed, listed, completed and escalated, but the personal parts are withheld and marked processing_restricted instead of being shown as empty: the conversation messages, the linked request log, the client error and the agent or workflow run, plus the row's user id, e-mail, client context, feedback text and rating. When the conversation is restricted (its owner or any person who wrote in it), the linked request log is withheld too, even if the request itself was made by an unrestricted account, because the request body carries the conversation's messages. The request-log command refuses a request made by (or invoked on behalf of) a restricted person, and cleanup-fixtures samples show a user id only for a known unrestricted account. A client error from an anonymous visitor keeps its message and stack trace, but its IP address, URL, user agent and client context are withheld. A missing user row, a missing run owner or any stored value other than 0 counts as restricted (fail closed).
A conversation is restricted when its owner or any member who wrote a message in it is restricted, because a shared conversation is also that member's personal data. This also applies to feedback on a shared conversation: it is held as soon as any message author is restricted, not only the owner.
Reactivation e-mails: opt-out and status
The administrative door to a member's reactivation-mail opt-out — the way to honour an objection received by phone or e-mail; the member's own door is the signed link in every mail.
curl -X PATCH https://<your-gateway-host>/admin/v1/users/{id} \
-H "Content-Type: application/json" \
-d '{"reactivation_opted_out": true}'
reactivation_opted_out is a boolean: true stamps reactivation_opted_out_at (an existing
stamp is kept), false clears it (opt-in). Same rules as processing_restricted: any other type
(1, "true") → 400, never coerced; the caller must out-rank the target (else 403 target_outranks_caller); a
toggle to the value already held is a no-op; a real change emits user.reactivation_opted_out /
user.reactivation_opted_in (actor, IP, timestamp). An administrative opt-in does not invalidate
the member's own link — a renewed objection wins.
GET /admin/v1/users/{id}/reactivation-status answers "why did this member (not) get mail X".
Required permissions: USERS_MANAGE and REQUEST_LOGS_VIEW (the answer is the member's
activity timeline, which a plain USERS_MANAGE delegate may not see), plus access to the user's
tenant; a member reading their own status is 403. A tenant admin naming a user of
another tenant gets 404, the same as for an unknown or
soft-deleted user (require_user_access fences the tenant first). Response fields: enabled_effective (0|1 — the tenant's resolved switch),
excluded_reason (disabled | processing_restricted | opted_out | no_email |
test_email, or absent), ever_active, last_activity_at, state (never_activated | lapsed
| dormant | active), anchor_at, next_step, next_due_at, due_now, blocked
(pending_in_flight | gap | not_yet_due), sequence_complete, and events[] — every send-log
row (sequence, step, anchor_at, sent_at, outcome, attempts, reactivated_at). A
database fault is 503.
Deleting a user
Deletes the user record and immediately disables all tokens associated with that user, and removes the user's push-notification device registrations. In-flight requests that have already passed the auth phase complete normally.
Projects the user owned are handed over. A project that would be left without an effective owner goes to a live tenant_admin of the project's own tenant (the oldest live tenant_admin of that tenant, otherwise the oldest live admin; disabled users are never picked), in the same transaction, and one project.owner_handed_over audit row is written per project. If the tenant has no live admin the project is kept without an owner, a warning is logged and a project_without_owner alert is sent after the commit; a platform admin can recover it. A lock wait answers 503 after one lock-wait timeout, with nothing written; a deadlock is retried, and one that persists answers 503; retry the request.
Self-serve trial reset: when the caller is a platform administrator, a delete (and an
/erase) also releases the one-free-trial-per-email lock for that user's address, so the person can register again from scratch — including a fresh trial via Sign up with Google/Microsoft. A delete by a tenant's owntenant_admin, or a user self-deleting, keeps the lock. Restoring the user re-applies it. Deleting a self-serve tenant with"users": "delete"(platform administrator) releases the lock for each deleted member the same way; deleting a tenant while keeping the users, or deleting a non-self-serve tenant's users in bulk, does not.
Your own account cannot be deleted here. A request whose {id} is the caller's own user answers 409 {"error": …, "code": "self_delete"} and nothing is changed. The same holds for erasing and previewing an erasure of your own account (self_erase). Another administrator deletes the account.
Last-administrator guard. Deleting an administrator (admin or tenant_admin) is
guarded server-side so a tenant cannot be left with nobody able to manage it. The check runs
regardless of the client:
| Situation | Result |
|---|---|
Not the last administrator (e.g. a member, or another admin remains) |
200, deleted normally. |
| Sole administrator while other members remain | 409 { "error": …, "code": "last_admin_blocked" }. Deleting would orphan those members. Not overridable — promote another administrator first. |
| Sole administrator who is the only member | 409 { "error": …, "code": "last_admin_confirm_required" }. The organisation would be left with zero administrators. Legitimate when winding an organisation down, so it is overridable by re-issuing the request with ?confirm_last_admin=1. |
| The administrators cannot be counted (a database read fault) | 503 { "error": "temporarily unavailable; retry later" } — nothing deleted; the guard is never skipped. Retry. |
The override flag is checked for exact equality with the string 1 — a bare ?confirm_last_admin,
a duplicated key, or any other value (e.g. 0) fails closed and the delete is still refused. A DB
fault reading the administrator counts also fails closed (503 { "error": "temporarily unavailable; retry later" }, nothing deleted). The delete itself
(token revocation + soft-delete, one transaction) is retried by the server on a deadlock with a
concurrent write (up to 4 attempts); a conflict that persists, or no database connection could be obtained, answers 503 (nothing changed,
retry), any other fault 500 { "error": "internal error", "request_id": "…" } (never the database's
error text). The admin console
turns the last_admin_confirm_required code into a warning naming the organisation and retries with
the flag on confirmation; last_admin_blocked is shown as a remediation message.
Users of a deleted tenant. A platform administrator can also delete — or erase (DELETE
/users/{id}/erase, GDPR Art. 17) — a user whose tenant was deleted (listed by
scope=deleted_tenants), including the old account a
move left behind; the last-administrator guard does not apply there
(the organisation no longer exists). Deleting frees the address for a new invite. Anyone else gets 404
for such a user.
Erasing a user and handing over their shared agents
DELETE /admin/v1/users/{id}/erase (GDPR Art. 17) hard-deletes the user's personal data. Shared agents are handed over, not deleted: an agent of the leaver that is shared with anyone (organisation-wide, with named users, or with a group) survives, its owner becomes a successor, and it is paused until the successor confirms it (see Confirming a hand-over). Private agents are always deleted. The leaver's account is anonymised and the retained audit trail carries no name.
The successor of each shared agent is chosen in this order: the explicit choice for that agent in successors > successor_default > the oldest active ki_manager of the tenant > the acting administrator (admin-driven erasure only; a self-erase has no acting administrator) > the oldest active tenant_admin or admin > none. With no candidate left the agent is deleted like a private one.
The optional request body is a JSON object with exactly these keys:
| Key | Type | Meaning |
|---|---|---|
successor_default |
user id (UUID) | Successor for every shared agent without its own entry. |
successors |
object, agent id (UUID) to user id (UUID); at most 500 entries | Successor for one agent. |
This applies to DELETE /users/{id}/erase only; a self-erase (DELETE /me/erase) takes no body other than the optional step_up_token (see Erasing the calling account). An absent body (or {}) uses the fallback order. Anything else is refused and nothing is erased: JSON null, an array or a scalar answers 400 invalid_body; an unknown key, a non-UUID id, or a wrong type answers 400 invalid_request. A well-formed body naming a bad choice answers 400 successor_agent_unknown (the agent is not one of the user's shared agents) or 400 invalid_successor (the successor is not an active user of the same tenant, or may not author agents). A disabled user is not an eligible successor, and neither is a user without a valid id or tenant (the same rule applies to the erase preview's candidates). Successor user ids are matched case-insensitively and always stored (agent owner, schedules, triggers, audit trail, erased.handed_over) in the user's own canonical spelling, never the spelling of the request. Agent ids used as keys in successors must be given in the API's canonical lower-case spelling; any other spelling is refused with 400 successor_agent_unknown. An explicit successor (a per-agent choice or successor_default) that is no longer eligible when the erasure transaction runs answers 409 successor_conflict and nothing is erased; a fallback candidate that is no longer eligible is skipped in favour of the next one. The response lists the hand-overs in erased.handed_over as [{ "agent_id", "successor_id" }] ([] when nothing was handed over). See Error codes for the full list.
Shared projects and chat bridge connections of the leaver are not agents and are not chosen by the order above. A project counts as shared, and is handed to the successor, when it has another member, a grant to a group of the same tenant (even an empty group), an organisation grant (even while organisation sharing is off), or belongs to a department of the same tenant. Only a project with none of these is deleted with the user. Ownership is granted, not just recorded: the successor receives an owner membership row on the project (rewriting the creator alone grants no access), and only when no other effective owner remains. An effective owner is a direct owner or a member of a group holding the owner role, in the project's own tenant; a co-owner who is disabled but not deleted still counts, so no second owner is added. A kept project that is already ownerless gets the successor as owner. This also applies to a kept project the leaver effectively owned without having created it (including one in the trash), and it holds even when the leaver's account was already deleted (soft-deleted) before the erasure. If no successor can be found for such a project, the project is kept (it is not the leaver's to delete) without an owner row, the erasure still completes, the project is not counted in chat_project_owner_granted, and a warning naming the project, its tenant and the leaver is logged; a platform admin can recover the project. When the successor comes from the member fallback, that member is promoted to owner. The number of projects granted is reported as chat_project_owner_granted in the erase counts. Each goes to a successor from the project's (or bridge's) own tenant: the acting admin, if they are a live user of that tenant; otherwise the oldest live tenant_admin, then the oldest live admin; otherwise (projects only) the oldest live member of that tenant, or a disabled member of that tenant if no live member exists. Disabled users are never picked as the acting admin or as an admin successor, and users of other tenants, including platform admins, are never picked. With no admin and no direct member, the project is then handed to a user who can reach it through its sharing instead: a member of a group it is granted to, otherwise a member of its department, otherwise (only while organisation sharing is on) a user of the organisation grant; live users before disabled ones, the oldest first, always from the project's own tenant, and never a demo user or the leaver. Only when none of those exists either (no live admin, no direct member and no such grantee in the project's tenant) the project is deleted with the user, even if it was shared only by a grant (with its knowledge and its members' project memories; members' conversations and agents are detached, and their code-interpreter sessions are closed after the commit) and the bridge connection is removed with its service token revoked. When SCIM deprovisions a user, the same admin pick is used (there is no acting admin).
A storage fault while the erase checks an explicit successor's permissions answers 503 and nothing is erased; retry the request. Erasing the sole administrator of an organisation that still has other members answers 409 with code: "last_admin_blocked" (promote another administrator first), and a user id that does not exist (or is not visible to you) answers 404 before any erasure starts; last_admin_blocked carries the unchanged error sentence.
Request-log rows are kept, personal fields are cleared. The erasure does not delete the leaver's request-log rows: they are billing evidence and are kept for their retention period. Instead every personal column in them is reset: the user and invoker ids, token label, client IP, user agent, referer, client request id, the prompt and response bodies (including the raw and scrubbed copies), the detector list, the block reason and the free-form meta (reset to {}). Billing columns (tenant, gateway, provider, model, tokens, cost, status, timestamps, trace id) stay unchanged. A row the leaver owned is marked personal_scrubbed = 1. A row the leaver only drove on behalf of another user (the leaver was the invoker) is cleared the same way, but it keeps its owner's user id and is not marked, because the owner is still a person. Where the optional ClickHouse analytics copy is enabled, the erasure does not reach it (nothing in it is deleted or anonymised): its text expires after 14 days and its other personal fields after 730 days — see ClickHouse analytics sink.
The successor is told. After the erasure commits, each successor receives one e-mail per erasure listing the agents handed over to them (name and a link to the Agents page; the leaver is never named), in the successor's language and branded with the tenant's product name (white-label). The mail is best-effort and sent after the response, so a mail failure never undoes or delays the erasure. The durable signal is handover_pending on GET /admin/auth/me, which the notification bell shows until the agent is confirmed.
Previewing an erasure
GET /admin/v1/users/{id}/erase/preview shows what erasing the user would do, without changing anything. The erase page (Erase permanently (GDPR) on a person's page) uses it to list the leaver's agents and propose a successor. It takes no parameters and no body. It needs the same permission and the same checks as the erase itself: USERS_MANAGE, access to the user, and the caller must out-rank the user (403 target_outranks_caller). A user from another tenant, an unknown id and a malformed id all answer 404, an account that cannot be erased 403, and a storage fault 503.
{
"user": { "id": "…", "name": "…", "email": "…" },
"shared_agents": [
{ "id": "…", "name": "…", "runs_30d": 12, "users_30d": 3, "default_successor_id": "…" }
],
"private_agents": [ { "id": "…", "name": "…" } ],
"default_successor": { "id": "…", "name": "…", "email": "…", "reason": "ki_manager" },
"candidates": [ { "id": "…", "name": "…", "email": "…", "is_you": false } ],
"candidates_truncated": false,
"shared_agents_truncated": false,
"private_agents_truncated": false
}
shared_agentsare the agents that would be handed over;private_agentswould be deleted.runs_30dandusers_30dcount runs and distinct users over the last 30 days, with clones counted on the agent they were cloned from - the same numbers the analytics by agent table shows.default_successor_idis the id ofdefault_successor, ornull.default_successoris the user the erase would pick with an empty body, withreasonki_manager(the oldest active KI manager),acting_admin(you, when you are an administrator of that tenant) ortenant_admin(the oldest active tenant administrator). It isnullwhen nobody qualifies; the shared agents would then be deleted like private ones. A user is only proposed if they could be chosen explicitly: active, in the same tenant, and allowed to author agents. In the rare case that a role-based fallback user lacks that permission, the preview skips them although a plain erase would still hand over to them; the preview errs on the conservative side.name(inuser,default_successorand eachcandidatesentry) is absent when that user has no name.candidatesare the active users of the tenant who may be named as successor (never the leaver), ordered by name, withis_youset for the caller. The default successor is always included.- Lists are capped at 500 agents and 100 candidates. The matching
*_truncatedflag istruewhen more exist. - Above 500 shared agents the list holds only the first 500 and the erase page's review groups (agents per successor) count only those listed agents;
shared_agents_truncatedtells you the rest exist. The erase itself hands over all of them. - A shared agent that is itself a clone reports its usage under the agent it was cloned from (its lineage root), so its own row can show
runs_30dandusers_30dof0while the root agent carries the numbers. users_30dcounts distinct users byte for byte, like the analytics by agent table: user ids that differ only by case or a trailing space count as separate users.
Moving a user to another tenant
POST /admin/v1/users/{id}/move — platform administrators only (USERS_GLOBAL_MANAGE; any other
caller 403; like every write on a user account, the caller must out-rank the user). Typical use: a user whose tenant was deleted (an expired trial) should join another
tenant with the same email address.
curl -X POST https://<your-gateway-host>/admin/v1/users/{id}/move \
-H "Content-Type: application/json" \
-d '{"tenant_id": "<target tenant id>", "role": "member"}'
What a move does. The user gets a new account with the same email address, name (or the
name sent with the move) and language in the target tenant, with the given role — they sign in with the same address and land there. The
old account is deleted: its conversations, projects, files, API keys, budgets and department stay
with the old tenant and are not visible from the new account; every session and API key of the old
account stops working (API keys answer TOKEN_REVOKED), and its push-notification device registrations are removed (the app registers again after signing in to the new account). An admin suspension (disabled) and a GDPR
Art. 18 processing restriction carry over to the new account. Both steps run in one transaction — a
move either happens completely or not at all. The response is
200 { "ok": true, "user_id": "<new id>", "tenant_id": "…", "role": "…" } — note the new user id.
The audit log records user.deleted (reason moved_to_another_tenant) in the old tenant and
user.moved_tenant (old and new user id, role — and name_overridden: true when a name replaced the
old one; the name itself is not written to the audit log) in the target tenant.
| Field | Accepted | Rejected (400, nothing changed) |
|---|---|---|
tenant_id |
the id of a live tenant (a UUID string; upper case is accepted) | absent or "" → tenant_id_required; null, a number, object, or a string that is not a UUID → invalid_tenant_id; a well-formed id of no live tenant → 404 tenant_not_found |
role |
tenant_admin, ki_manager, finance, member, viewer (exact spelling) |
absent or null → role_required (there is no default role); anything else — including the platform roles admin and demouser — → invalid_role |
name (optional) |
a string of at most 255 characters, valid UTF-8 (the invite's rule) — stored on the new account with leading and trailing ASCII whitespace removed. Absent, null, "" or only whitespace (including non-breaking and other Unicode spaces) keep the old account's name (a name is never replaced by nothing). The admin UI's Move user here (from a New User invite whose address belongs to another tenant) sends the name entered in the invite. |
a number, boolean, object or array or invalid UTF-8 → invalid_name; longer than 255 characters → name_too_long |
A body that is a JSON scalar, array or null is 400 invalid_body.
| Situation | Answer |
|---|---|
| The user is deleted | 409 user_deleted (invite the address instead) |
The user is a platform account — tenant-less, or a platform role (admin, demouser) attached to a tenant |
409 platform_user (a move would recreate it with a tenant role) |
| The user is the caller themselves | 409 self_move |
| A protected account | 403 |
| The target is the user's current tenant (any letter case) | 409 same_tenant |
| The target tenant does not exist or is deleted | 404 tenant_not_found |
| The user is the last administrator of a live organisation while other members remain | 409 last_admin_blocked — promote another administrator first (not overridable) |
| The user is the only administrator and the only member of a live organisation | 409 last_admin_confirm_required — moving them leaves the organisation empty; re-send with ?confirm_last_admin=1 (exactly 1; anything else is refused again). A user of a deleted tenant is not guarded. The rule is checked again inside the move's transaction, so two simultaneous moves of an organisation's two administrators cannot both succeed. |
| The target tenant has no free seat | 403 seat_limit_reached (the same seat limit as an invitation, including the lower count of a scheduled seat reduction, with scheduled_seats / scheduled_effective_at / note) |
| The user changed meanwhile (moved, deleted) | 409 user_changed — reload and retry |
| Another active account took the address meanwhile | 409 email_in_use |
| The seat limit cannot be read, or a database conflict persists | 503 — nothing changed, retry |
Not carried over: the new account has no SCIM externalId; if the target tenant provisions users
through SCIM, the identity provider's next sync may report a conflict for this address until it is
linked again.
Acting on another user requires out-ranking them
Creating a token on another user's account (POST /users/{id}/tokens, and POST /gateways/{id}/tokens with a user_id), editing or revoking a token that belongs to another user (PATCH / DELETE /gateways/{id}/tokens/{token_id} — for example lifting its budget cap or expiry), deleting (DELETE /users/{id}), erasing (DELETE /users/{id}/erase), restoring (POST /users/{id}/restore) and resetting the budget (DELETE /users/{id}/budget) of another user all require the caller to out-rank the target — the same role hierarchy that governs role assignment, disabling and email changes. A caller may act only on a user whose role they could also assign: a tenant_admin may act on ki_manager, finance, member and viewer users, but not on another tenant_admin or a platform admin (only a platform admin can); a delegate holding USERS_MANAGE via a custom role whose base role is member cannot do any of these to another user. A user with no role on record counts as a member. The same rule applies to changing another user's role (the caller must out-rank the user's current role, not only be allowed to grant the new one) and to impersonating a user (see Impersonation). A refused request answers 403 { "error": "…", "code": "target_outranks_caller" } and changes nothing. Acting on your own account (creating your own token, resetting your own budget) is self-service and not affected — except while impersonating, where the viewed account is never treated as your own. User records returned by GET /users and GET /users/{id} carry can_manage (boolean): whether the caller passes this rule for that user. The SPA also shows the email and retention fields of the edit dialog read-only for a user you cannot manage (the server refuses the change with target_outranks_caller regardless), and hides the New User button unless GET /admin/auth/me reports a non-empty assignable_roles (see Account).
Resetting user token budgets
Clears the accumulated spend for every token belonging to the user.
This resets token spend only. A member's personal budget counter is reset
together with the workspace spend (DELETE /tenants/{id}/budget, platform admins), never here.
Per-user budgets
An optional spending cap for one member, for the same period as the workspace budget
(see Per-user budgets for how it is enforced). The
workspace budget still applies on top. Each member has a mode: inherit (use the default that
applies to them, or share the workspace budget when there is none), none (explicitly no personal
limit) or amount (a personal budget).
Required permission: BUDGETS_MANAGE (Manage spending limits, held by admin, tenant_admin and finance; the workspace budget itself stays with TENANT_SETTINGS_MANAGE),
plus the usual user fence: the target must be in your workspace and, for another user, you must
out-rank them. A holder may set their own budget.
curl -X PUT https://<your-gateway-host>/admin/v1/users/{id}/budget-cap \
-H "Content-Type: application/json" \
-d '{"mode": "amount", "budget_usd": 50}'
Accepted body: a JSON object with mode and, for amount only, budget_usd:
| Body | Meaning |
|---|---|
{"mode": "amount", "budget_usd": 50} |
a personal budget: 0, or a number from 0.000001 to 1000000 (USD); 0 freezes the member (every request refused) |
{"mode": "none"} |
no personal limit, whatever a default says |
{"mode": "inherit"} |
follow the default that applies to the member |
{"budget_usd": 50} (legacy) |
the same as {"mode": "amount", "budget_usd": 50} |
{"budget_usd": null} (legacy) |
the same as {"mode": "inherit"} |
Behaviour change.
{"budget_usd": null}used to mean "no personal budget"; it now means Inherit. Until a workspace default exists that is the same thing, but a client that wants an explicit "unlimited" must send{"mode": "none"}.
When the mode is inherit the cap is resolved in order, and the first level that is not inherit
wins: the member, their department's member default, then the workspace's member default.
Rejected:
| Input | Answer |
|---|---|
neither mode nor budget_usd present (an empty object, a different key) |
400 — never read as "remove" |
mode present but not exactly "inherit", "none" or "amount" (wrong case, a number, null, "") |
400 — never read as a permissive mode |
mode "none" or "inherit" together with a budget_usd number |
400 (ambiguous; nothing is dropped silently) |
mode "amount" without budget_usd, or with null |
400 |
a string ("50"), a boolean, an object, a negative, above 1000000, a positive amount below 0.000001 (it would round to a silent freeze), an overflowing number (1e999) |
400 |
| a body that is not a JSON object, or malformed JSON | 400 |
no BUDGETS_MANAGE |
403 |
| a user in another workspace | 404 (the same as an unknown user) |
| a user you do not out-rank | 403 {"code": "user_budget_forbidden_rank"} |
| a free-trial workspace (each member already has their own trial credit) | 409 {"code": "user_budget_not_on_trial"} |
| a deleted user, or an account with no workspace | 409 (user_deleted / user_budget_no_workspace) |
| the user left the workspace while the request ran | 409 {"code": "user_budget_not_member"} |
| a database conflict that persists / any other fault | 503 (retry) / 500 |
A success answers 200 {"id": "...", "budget_mode": "amount", "budget_usd": 50} (budget_usd is
null unless the mode is amount). Every change is recorded in the audit log as
user.budget_cap_changed with the before and after mode and amount.
{
"trial": false,
"period": "2026-10",
"resets_at": 1793491200,
"tenant_spend_cap_usd": 100,
"allocated_usd": 120,
"unallocated_usd": -20,
"users": [
{ "id": "u-1", "disabled": false, "budget_mode": "amount", "budget_usd": 30, "spent_usd": 12.5 },
{ "id": "u-2", "disabled": false, "budget_mode": "inherit", "budget_usd": null, "spent_usd": 3.1 }
]
}
period— the per-user budget period: the calendar month ("2026-10"), or"allowance"for a self-serve workspace (the budget renews with the allowance);resets_at— when it next rolls (unix seconds; on a self-serve workspace it is the same instant asallowance_renewal_date),nullwhen no allowance renewal is scheduled.tenant_spend_cap_usd— the workspace's self-imposed monthly spend cap (spend_cap_usd, seePATCH /tenants/{id}),nullwhen no cap is set.allocated_usd— the sum of the active members' budgets (disabled members are not counted).unallocated_usd=tenant_spend_cap_usd− allocated, for information only: it may be negative (over-allocation is allowed — the workspace spend cap and the wallet still bound the total), and isnullwhen no workspace spend cap is set.users— one entry per member (always an array,[]when empty).spent_usd(this period) is present only when you also holdCOGS_PER_USER_VIEW.budget_invalid: truemarks a stored budget that cannot be read: that member's requests are refused until a new budget is saved.- A free-trial workspace answers
{"trial": true, "period": null, "users": [], ...}. - Required permission:
TENANT_SETTINGS_MANAGEorBUDGETS_MANAGE, and access to the workspace. Any read fault →503(never a partial list). All amounts are USD.
Resending the invitation email
Required permission: USERS_MANAGE (Manage tenant users; held by tenant_admin and admin by default, grantable through a custom role). The endpoint sends the same invitation template that was sent on user creation. The response is {"ok": true}.
An invitation cannot be re-sent to your own account: a request whose {id} is the caller's own user answers 409 {"error": …, "code": "self_resend_invite"} and no email is sent.
While the tenant is suspended (see Messages while suspended) the resend is refused 403 {"code": "tenant_suspended"}; if the tenant's state cannot be read it answers 503 {"error": "tenant state unknown", "code": "tenant_state_unknown"}. Nothing is sent in either case. (tests: tests/unit/test_admin_api.lua "MAP-4136")
Restoring a soft-deleted user
Required permission: USERS_MANAGE (Manage tenant users; held by tenant_admin and admin by default, grantable through a custom role). Restoring an already-active user returns {"ok": true, "already_active": true} (for a user the caller out-ranks; otherwise 403 target_outranks_caller, see above). There is no self-service restore — a deleted user cannot reactivate their own account.
Seat-capped. A restore re-activates a seat, so it obeys the same per-plan seat cap as an invite (plan_config.max_seats, resolved via the effective-seat-cap resolver). If the tenant is already at its cap, the restore is refused 403 seat_limit_reached and the user stays soft-deleted — free a seat (delete or hard-delete another active user, or raise the plan) and retry. Other outcomes: the address was reclaimed by a live account → 409; the user's tenant no longer exists → 404; the user was moved to another tenant while the restore was in flight → 409 {"error":"the user was moved to another tenant; reload and retry"}; a deadlock with a concurrent write is first retried by the server (up to 4 attempts, the restore re-runs from scratch); only a conflict that persists, no database connection, or a failure resolving the cap → 503 (nothing changed; retry). An unexpected server fault → 500 { "error": "internal error", "request_id": "…" }. While a seat reduction is scheduled the cap is the scheduled count and the refusal also carries scheduled_seats, scheduled_effective_at and note. Uncapped tenants (enterprise with no seats override) are never blocked, even while a seat reduction is still recorded as scheduled.
Disabling and re-enabling a user
Required permission: USERS_MANAGE (Manage tenant users; held by tenant_admin and admin by default, grantable through a custom role). The caller must be allowed to manage the target's role (same role hierarchy as updating a user) and must be able to reach the target (same tenant; a tenant_admin cannot act on a platform admin). Both endpoints take an empty body.
Disabling sets disabled_at (a unix-seconds timestamp). A disabled account is blocked, fail-closed, from every authentication and run path — admin session, inference token, email OTP / SSO / SAML / OIDC / Google login, the Mattermost bridge, scheduled and saved-agent runs, and workflow email delivery. Active admin sessions and inference tokens are rejected on their next request (session state is stateless, re-validated against the live account on every request), so access is revoked promptly. The revocation is also permanent and per-device: disabling stamps a per-user revocation floor (sessions_valid_after) that an older admin cookie can never pass, and revokes the user's /v1 API tokens (a subsequent call gets a typed token_revoked 401). It also removes the user's push-notification device registrations, so the user's devices stop receiving notifications. Re-enabling restores login but does not clear the floor or restore the tokens or registrations — the user signs in afresh (the app registers its push token again) and mints new tokens.
Rejected requests (fail-closed at the trust boundary, server-side):
- disabling your own account →
409(platformadmin); for atenant_adminthe out-rank rule (below) answers first →403target_outranks_caller. Either way you cannot disable yourself, and the SPA hides the control on your own row; - disabling the last active administrator (
adminortenant_admin) of a tenant while other users remain →409(promote another administrator first); - disabling/enabling a soft-deleted account →
409(restore it first); - a user of another tenant →
404, the same as an unknown id; a platform-admin target for a tenant admin →403; - a user whose role is at or above your own (for example a
tenant_admindisabling or enabling a peertenant_admin) →403 { "code": "target_outranks_caller" }, nothing changed. The user list marks such rowscan_manage: false.
Disabling an already-disabled account (or enabling an already-enabled one) is an idempotent no-op that returns 200. A disable (token revocation + flag + its user.disabled audit row, one transaction) and a re-enable (flag + user.enabled row) are retried by the server on a deadlock with a concurrent write (up to 4 attempts); a conflict that persists, no database connection could be obtained, or the last-administrator check could not read the tenant's administrators answers 503 (nothing changed, retry). Any other server fault answers 500 { "error": "internal error", "request_id": "…" } (the cause is logged, never returned). Re-enabling clears disabled_at but not the revocation floor: the sessions and API tokens that were open at the disable stay dead on every device, and the user re-authenticates. This mirrors soft-delete → restore, which behaves the same way.
# Disable (block login; ends every session + API token permanently on every device)
curl -X POST https://<your-gateway-host>/admin/v1/users/{id}/disable
# Re-enable (login restored)
curl -X POST https://<your-gateway-host>/admin/v1/users/{id}/enable
The user's disabled state is exposed as disabled_at on the user object returned by the list and get endpoints, and in the users CSV export Status column (active, disabled, or deleted).
Signing a user out everywhere
Required permission: USERS_MANAGE. Ends every admin (browser) session of the user on every device: the per-user revocation floor (sessions_valid_after) is stamped, and each session cookie issued up to now answers 401 on its next request. API tokens are not touched and keep working; the account is not disabled. Acting on your own account is allowed. Returns 200 { "ok": true }; the action is audited as user.sessions_revoked, written in the same transaction as the floor stamp, so a 200 always means both exist and a failed audit write leaves every session valid (503 when nothing was sent, retry).
Rejections: missing permission → 403; a user of another tenant → 404; a target at or above your role → 403 { "code": "target_outranks_caller" } (checked before the deleted check, so it reveals nothing about the target); a soft-deleted account → 409; a storage fault → 503/500 (sanitised), nothing signed out.
SSO links: listing and unlinking
An SSO sign-in (OIDC or SAML) links the identity provider's subject to the account on its first sign-in. If the identity provider later sends a different subject for the same person (the user was recreated at the identity provider, subject_claim was switched, the app was re-registered, or a SAML NameID was regenerated), the first sign-in with the new subject is refused (403, audit action link_conflict, see Authentication) for as long as the old link exists. These routes let an administrator remove the stale link; the next sign-in then links the new subject.
# List
curl https://<your-gateway-host>/admin/v1/users/{id}/sso-links
# Unlink one exact link
curl -X DELETE https://<your-gateway-host>/admin/v1/users/{id}/sso-links \
-H "Content-Type: application/json" \
-d '{"provider": "oidc", "issuer": "https://idp.example.com/realms/acme", "subject": "8f14e45f-ceea-467a"}'
Required permission: USERS_MANAGE, for both routes. The user must be in your tenant (a platform admin reaches every tenant): a user of another tenant answers 404, exactly like an unknown id.
List. GET returns 200 { "links": [ { "provider", "issuer", "subject", "email" } ] }, ordered by provider, issuer and subject; links is [] when the account has no link. provider is google, microsoft, oidc or saml; issuer is the identity provider's issuer (an empty string for Google); subject is the identifier the identity provider sends; email is the address the identity provider last sent for this link, or null. A database fault answers 503, never an empty list.
Unlink. DELETE takes a JSON object with exactly three keys, which name one link byte for byte (copy them from the list):
| Key | Accepted | Rejected |
|---|---|---|
provider |
a string of at most 32 characters | absent or null → 400 field_required; any other type, longer, or invalid UTF-8 → 400 invalid_field |
issuer |
a string of at most 255 characters; "" is the issuer of Google links |
absent or null → 400 field_required; any other type, longer, or invalid UTF-8 → 400 invalid_field |
subject |
a string of at most 255 characters (a character can be up to 4 bytes) | absent or null → 400 field_required; any other type, longer, or invalid UTF-8 → 400 invalid_field |
Every value a stored link can hold is accepted, including an empty string, spaces and control characters that links created before the current sign-in validation may carry, so any listed link can be unlinked.
The field of each 400 names the offending key; the keys are checked in the order provider, issuer, subject. Values are never trimmed or case-folded: Alice and alice are different subjects, and a value that matches no link of this user answers 404 { "code": "sso_link_not_found" } and nothing changes. Any other key is 400 unknown_field (plus field), an absent body is 400 field_required (field provider), a JSON array, scalar or null body is 400 invalid_body, and malformed JSON is 400 malformed_body; nothing is deleted on any 400. Only the named link of this user is removed: other links (another provider, another issuer, another subject) stay, and a link of another account is never touched, whatever the body says.
Returns 200 { "ok": true }. The unlink is audited as sso.link_removed (target = the user; before carries the removed provider, issuer and subject), written in the same transaction as the delete: a 200 always means both exist, and a failed audit write deletes nothing (503 when nothing was sent, retry). Acting on your own account is allowed (not while impersonating: then the target is ranked like any other account).
Rejections: missing permission → 403; a user of another tenant → 404; a target at or above your role → 403 { "code": "target_outranks_caller" } (checked before the deleted check); a soft-deleted account → 409 user_deleted; a storage fault → 503/500 (sanitised), nothing unlinked.
In the admin console the same list and the Unlink action (with a confirmation) are the SSO links card on the member's page (Organisation › People › Members › the member › Overview).
Legacy static codes
GET /admin/v1/static-otp/legacy?kind=user|partner lists the accounts that still carry a fixed code set before the 12-character minimum, so an administrator can replace them before the 30-day grace ends. kind=user needs the USERS_GLOBAL_MANAGE permission, kind=partner needs PARTNERS_MANAGE. A missing kind is 400 kind_required, any other value 400 invalid_kind; a storage fault is 503. The call is read-only and writes no audit row.
{ "kind": "user", "min_length": 12, "legacy_until": 1767225600,
"accounts": [ { "id": "…", "email": "…", "name": "…", "tenant_id": "…" } ] }
legacy_until is the epoch second at which the grace ends (null if no deadline is on record, which means every legacy code is already refused). accounts is capped at 500 and never contains a code or its hash. After the deadline a legacy code answers 403 { "error": "this fixed sign-in code has expired; an administrator must set a new code of at least 12 characters", "code": "static_code_expired", "docs": "/account/user-management/users/#static-sign-in-codes" } and the attempt is audited as auth.static_otp_expired.
Setting or clearing a static OTP
Required role: platform admin only. Sets a fixed OTP code that the user enters during sign-in instead of the email-delivered OTP. Useful for App Store reviewer accounts and similar fixed credentials. The code must be a JSON string of 12 to 32 ASCII digits (0-9, leading zeros allowed) after trimming surrounding whitespace; anything else (a JSON number such as 428193 unquoted, a boolean, an object or an array, fewer than 12 or more than 32 characters, letters, an inner space, a non-ASCII digit such as a fullwidth or Arabic-Indic one, a control character) is refused as 400 invalid_code and nothing changes (a code stored before this rule is a legacy code: it keeps signing in for 30 days after the migration first ran, then is refused with 403 static_code_expired until an administrator sets a new code; a wrong guess stays 401); the value is stored as a SHA-256 hash. To clear the static OTP and revert to email OTP, send {"code": null}; an absent body or {} also clears (200 {"ok": true}, audited user.static_otp_cleared, no code is generated or stored). The user must exist and not be deleted: an unknown id, a soft-deleted user, or a user whose tenant was deleted answers 404 { "error": "user not found", "code": "user_not_found" } and nothing is stored (it used to answer 200 with a code that could log nobody in). The body is a closed schema: its only accepted top-level key is code. Any other key (a misspelt Code, otp, pin, or a key sent beside a valid code) is refused 400 unknown_field with the offending key in field (capped at 64 bytes), and nothing is read, stored or audited, so a stored credential is never cleared by a typo; only an absent body, {} or {"code": null} clears (an absent code key inside a body that names other keys does not). Body validation, including this key check, runs before the user lookup: an unknown key on an id that does not exist answers 400, not 404. A bad code is 400 invalid_code (not a JSON string of 12 to 32 ASCII digits) or invalid_body (the body is not a JSON object). A set and a clear are each audited (user.static_otp_set / user.static_otp_cleared, target = the user); the audit row never contains the code or its hash. The {id} must be 1–36 printable ASCII characters without spaces; anything else (trailing spaces, over 36 bytes) answers 404 user_not_found before any lookup and nothing is stored. The id is matched byte-exact here too: an id that differs from a real user id only in letter case answers the same 404 user_not_found, nothing is stored and no audit row is written; the write and the audit row always carry the canonical id. The credential change and its audit row are one transaction (see below). The audit row records the administrator as the actor and the client IP as seen through the CDN (the X-Forwarded-For client address), not the edge address. A deadlock on the write is retried by the server (up to 4 attempts); a conflict that persists, or no database connection could be obtained, answers 503 (nothing changed — retry); any other server fault 500 { "error": "internal error", "request_id": "…" }.
# Set
curl -X PUT https://<your-gateway-host>/admin/v1/users/{id}/static-otp \
-H "Content-Type: application/json" \
-d '{"code": "123456"}'
# Clear
curl -X PUT https://<your-gateway-host>/admin/v1/users/{id}/static-otp \
-H "Content-Type: application/json" \
-d '{"code": null}'
The credential change and its user.static_otp_set / user.static_otp_cleared audit row (never the code or its hash) are one transaction: either both are stored or neither is. A lock held for longer than 5 seconds or a conflict answers 503 { "error": "temporarily unavailable; retry later" } with nothing written; retry. A refused audit row or an unknown outcome answers a sanitised 500; read the user back before retrying. A user deleted in the meantime answers 404 and writes no row.
Error codes on the user routes
Every refusal on the user routes above carries a stable top-level code next to the unchanged error text and status. Branch on code, never on the message. The full naming rule and the list for all org admin routes is in Typed codes on the org admin routes.
| Status | code |
When |
|---|---|---|
400 |
caller_has_no_tenant |
The roster was asked for by a caller whose account has no tenant. |
400 |
invalid_body |
The body is a JSON scalar, array or null (invite, user update, move, per-user budget, static OTP, and the erase body): nothing is written. An absent body on the user update and static OTP routes is an empty object, not this code; on the move route it answers tenant_id_required; on the per-user budget route (PUT /users/{id}/budget-cap) an absent body also answers this code. |
400 |
email_required / invalid_email |
Invite: email absent or "" (email_required) / null, a non-string or an invalid address (invalid_email). Update: a non-string or invalid address (invalid_email). |
400 |
role_required / invalid_role |
Invite: role present but not a string (invalid_role). Move: role absent or null (role_required) / present but not a string or not an assignable role (invalid_role). PATCH /users/{id} answers only invalid_role, for a non-string role and for role: null; an absent role leaves the role unchanged. |
400 |
invalid_processing_restricted, invalid_reactivation_opted_out, invalid_conversation_retention_days |
The field is present but not a boolean / not an accepted retention value. |
400 |
mode_required, invalid_mode, budget_usd_required, invalid_budget_usd |
Per-user budget body: neither mode nor budget_usd present (mode_required), or mode not exactly inherit, none or amount; amount without budget_usd; budget_usd malformed or sent with inherit / none. |
400 |
unknown_field (plus field) |
User static OTP body carries a top-level key other than code, or the SSO unlink body a key other than provider, issuer and subject; nothing is read, written or audited. |
400 |
field_required / invalid_field (plus field) |
SSO unlink body: provider, issuer or subject absent or null (field_required) / present but malformed (invalid_field). See SSO links. |
400 |
invalid_code |
User static OTP code is not a string of 12 to 32 ASCII digits. (The partner route uses invalid_code / code_too_long for 12-32 printable ASCII.) |
400 |
invalid_field (plus field) |
A token field (label, scopes, rate_limit, budget_usd, expires_at) is malformed; field names it. |
the refusal's 4xx |
invalid_request |
Defensive fallback (logged as a WARN) when an erase, disable, enable, static-OTP or per-user-budget refusal has no more specific code (the group-member budget route has the same fallback). |
400 |
disable_target_missing, enable_target_missing |
Defensive: a disable or enable with no resolvable target. Not reachable over HTTP today (the path id always resolves or answers 404). |
403 |
platform_admin_only |
A non-platform-admin tried to change a user's tenant. |
403 |
role_assignment_forbidden |
The assigned role is above what the caller may grant. |
403 |
account_not_erasable, account_not_deletable, account_not_movable |
A protected account. |
403 |
seat_limit_reached |
Invite, restore or move would exceed the seat limit (body also carries the seat fields). |
403 |
self_role_change |
A role change on your own account. |
404 |
user_not_found |
The user does not exist (resource-naming 404). |
404 |
sso_link_not_found |
SSO unlink: the user has no link with exactly this provider, issuer and subject; nothing changed. |
404 |
tenant_not_found |
The target tenant does not exist or is deleted. |
409 |
role_managed_by_idp |
PATCH /users/{id} changed the role of a user whose role is managed by an identity-provider group. |
409 |
role_requires_tenant |
PATCH /users/{id} changed the role of a user without a home tenant to tenant_admin, ki_manager or finance. |
409 |
same_tenant, self_move, platform_user |
Move: the user is already in that tenant / is your own account / is a platform account. |
409 |
user_changed |
The user was changed meanwhile; reload and retry. |
409 |
user_budget_not_member, user_budget_not_on_trial |
Per-user budget: the user left the workspace / a free-trial workspace has no per-user budgets. |
403 |
user_budget_forbidden_rank |
Per-user budget: the target is ranked at or above your own role. |
403 / 422 |
roster_search_forbidden / roster_too_large |
The roster search is not allowed for the caller / the roster is too large for one response. |
400 |
successor_agent_unknown, invalid_successor |
Erase hand-over names an agent that is not shared by the user / a successor that is not an active, agent-authoring user of the tenant. |
409 |
user_deleted |
The account is soft-deleted; restore it first. |
409 |
email_in_use |
Another active account holds the address. |
409 |
user_moved |
The user moved to another tenant while the request ran; reload and retry. |
409 |
self_disable, last_admin_blocked |
You cannot disable your own account / the last administrator cannot be disabled. |
409 |
self_delete, self_erase, self_resend_invite |
You cannot delete, erase or re-invite your own account through user management. |
Not coded by design: the plain 404 { "error": "not found" } for a user the caller may not see (the same answer as for an unknown id), and storage faults (503 / 500).
Tokens
Token fields
Refused characters (one rule on every token route). Token text — label, user_id, agent_id, gateway_id — is refused with HTTP 400 naming the field when it contains a control or invisible formatting character: control characters (C0 incl. tab/newline/CR, DEL, C1 U+0080–U+009F), the line/paragraph separators U+2028/U+2029, the interlinear annotation controls U+FFF9–U+FFFB, the braille blank U+2800, and every Unicode default-ignorable code point (zero-width and bidi controls, soft hyphen, byte-order mark, word joiner / invisible operators, Hangul fillers, Unicode tag characters …) except a variation selector (U+180B–U+180D, U+180F, U+FE00–U+FE0F, U+E0100–U+E01EF) that directly follows a base character of its own kind (a symbol or emoji, a CJK ideograph, a Mongolian letter), at most one per base; any other variation selector is refused, so emoji (❤️), CJK variants and Mongolian text stay accepted. A variation selector is a code point that is invisible by itself, so it is accepted only in its proper place: U+FE00–U+FE0F directly after a symbol, emoji, digit, #, *, ©, ® or CJK ideograph; U+E0100–U+E01EF directly after a CJK ideograph; U+180B–U+180D and U+180F directly after a Mongolian letter (U+1820–U+18AA) — never at the start, after a space or another invisible character, or after a second selector (❤️️ is refused). The rule removes free-standing, stacked and letter-attached selectors; it does not remove the channel entirely: after each valid base one selector remains possible (one of 256 values after a CJK ideograph, one of 16 after a digit, symbol or emoji, one of 4 after a Mongolian letter), whereas letters, punctuation and spaces carry none. Exact bases: U+FE00–U+FE0F after #, *, 0–9, U+00A9, U+00AE, U+203C, U+2049, U+2100–U+2BFF, U+3030, U+303D, U+3297, U+3299, U+1F000–U+1FAFF, or a CJK ideograph (U+3400–U+4DBF, U+4E00–U+9FFF, U+F900–U+FAFF, U+20000–U+3FFFF); U+E0100–U+E01EF after a CJK ideograph; U+180B–U+180D and U+180F after U+1820–U+18AA. Nothing is persisted on refusal. Ordinary text — umlauts, accents, CJK, simple emoji and plain spaces — is accepted. Emoji sequences joined with the zero-width joiner U+200D (for example 👩💻, 🏳️🌈 or family emoji) are refused, because U+200D is one of the zero-width characters above; write such a label without the joiner. The same rule covers the gateway, user, personal and agent MCP token routes, so a label cannot forge a token-list or audit row or disguise itself.
| Field | Type | Default | Description |
|---|---|---|---|
label |
string | — | Human-readable name shown in the admin UI and logs. Accepted: a valid UTF-8 string of at most 255 bytes, or null; the labels playground, device and mcp_oauth (any case, surrounding whitespace ignored) are reserved (the last two mark credentials minted by the device-code and MCP OAuth flows) and answer HTTP 400; a non-string, an oversize value, invalid UTF-8 bytes, or a control / invisible formatting character (see the refused set above) is rejected with HTTP 400. An operator budget alert for the token shows the label in its e-mail / Mattermost body, marked as user-set and reduced to ASCII letters, digits, space, ., _ and - (never in the alert's subject, log line or webhook) (see Soft-threshold alerts). The label is descriptive only and never changes authorization: every user-bound token passes the same live user checks (deleted or disabled user, processing restriction, viewer role) and the same tenant check, whatever its label. |
user_id |
string | null | null |
Associates the token with a user for audit trail and per-user budget tracking (By-User analytics). Accepted: a valid UTF-8 string id of at most 36 bytes naming a user in the gateway's own tenant, or null; a non-string (object, number, boolean), an oversize value, invalid UTF-8, or a refused character (see above) is rejected with HTTP 400 (user_id must be a string id). The id is scoped to the gateway's tenant, not merely well-formed — a well-formed id that is not a user of this gateway's tenant (whether it does not exist, or belongs to another tenant) is the same audited HTTP 404 { "error": "not found" } (recorded as one access.denied security event, like every other id the caller cannot see), and no token is created. The two answer byte-identically so the route is not a cross-tenant existence oracle (a caller cannot confirm a UUID is a real user in another tenant). A platform administrator can see users of every workspace, so naming a user outside the gateway's workspace is a policy refusal rather than a missing id: HTTP 403 gateway_outside_owner_tenant, and no token is created. Only the shape of user_id is a 400. The caller must also out-rank that user — a user whose role is at or above the caller's (another tenant admin, a platform admin) is refused with HTTP 403 { "code": "target_outranks_caller" }, and so is any user for a caller who can assign no roles (a member holding the permission through a custom role); binding a token to your own user id is always allowed. The FK is the last-line authority (a user hard-deleted mid-mint → the same audited 404 { "error": "not found" }). A transient fault while resolving the id (a DB blip in the tenant-scope lookup) fails closed with HTTP 503 { "error": "temporarily unavailable; retry later" } — no token is created, retry — kept distinct from the deterministic 404 so a caller can tell "unknown" from "try again". A user whose department does not allow this gateway gets no token (HTTP 403 department_gateway_not_allowed) — the same check applies to POST /users/{id}/tokens, POST /me/tokens, the chat/playground token, the OX connect token and device-code approval. An existing token of a user later moved into a department is refused on its next request by the inference gate. |
agent_id |
string | null | null |
mints a PER-AGENT token bound to one saved agent (create-only). Accepted: a valid UTF-8 string id of at most 36 bytes naming an agent that exists on this gateway — a non-string / oversize / invalid-UTF-8 value or one with a refused character (see above) is rejected HTTP 400 agent_id must be a string id, and an id that is not an agent of this gateway is HTTP 400 unknown agent_id for this gateway (the client is never the authz boundary). null/absent = a normal token. See Per-agent tokens below. |
scopes |
array | [] |
Capability scopes (opt-in least-privilege). Recognized capabilities: inference, tools, admin, admin_read (see Authentication → admin_read). A token that declares one or more recognized capabilities is enforced fail-closed — e.g. one whose scopes exclude inference is refused at the inference endpoint with HTTP 403. A token with an empty array or only legacy/unknown strings (e.g. ["read","write"]) is unrestricted. The scope playground is reserved (it marks the Playground's interactive token) and cannot be requested on any token route: it answers HTTP 400, whatever its case. Today inference is enforced at the request boundary; see Authentication → Token capability scopes. Accepted shape: absent, null, or a JSON array of at most 50 strings, each 1–64 characters from A-Z a-z 0-9 . _ : / -; absent / null / an empty array or empty object are all stored as []. Rejected with HTTP 400: a string, number, or boolean ("inference", 0, true); an object with keys ({"inference": true} — it would read as no scopes and mint an unrestricted token); an element that is not a string, is empty, contains whitespace or any other character outside the alphabet ("inference ", "'; DROP…", an emoji), or exceeds 64 characters; more than 50 elements. Previously a non-array scopes answered an opaque 500. |
expires_at |
integer | null | null |
Unix expiry timestamp (seconds since epoch). null means the token never expires — the recommended default for a service/scheduler token, which cannot then die silently. Must be a whole number in the future and within 100 years; a non-integer (e.g. an ISO-8601 string), past, or implausibly far-future value (e.g. a milliseconds timestamp) is rejected with HTTP 400. When an expiry is set, the owner is warned in-app and by email 7 days before it lapses (a no-owner service token warns the tenant's active admins; an admin-disabled account is skipped; a token on a gateway of a soft-deleted tenant is not warned at all, neither by e-mail nor in-app, until the tenant is restored) — see Agents → Proactive token pre-expiry warning. A scheduler-service token cannot be given an expiry on create: for the agent scheduler's per-gateway service token — a user-less token (user_id null) with no scopes whose label ends -scheduler-service — a finite expires_at on create is rejected with HTTP 400. Such a token gates a customer-facing feature (scheduled agents); a lapse would 401 every scheduled agent on the gateway, so it must never expire. On the edit route the token is now a protected internal service credential: any PATCH on it (including clearing its expiry) answers HTTP 403, and it is hidden from the token list entirely. |
rate_limit |
object | null | null |
Per-token sliding-window limit: {"requests": N, "window_sec": S}. Applied independently of the gateway-level rate limit — a request can be blocked by either. Accepted shape: absent or null (no per-token limit), or a JSON object whose only keys are requests (required, a whole number 1–1 000 000 000) and window_sec (optional, a whole number 1–31 536 000; when absent or null the default 60 is stored, so a token always reads back with both keys). Rejected with HTTP 400: a scalar or string; an array ([], ["x"]); an empty object or any object without requests (a limit with no count was previously stored and silently applied no limit); requests: null (what a form emits for a non-numeric input); any other key (e.g. window, rpm); a leaf below 1, above its cap, fractional, non-numeric, or non-finite (inf/nan) — a window_sec of 0 would divide by zero in the rate-limit hot path. The shape itself is the one shared with the gateway rate_limit: at request time a stored value the gateway cannot use (not an object, or an unusable present leaf) makes the token's requests fail with 500 configuration_error rather than run unlimited — extra keys in an older stored row are ignored, an empty stored column is treated as unset — and the token list then shows rate_limit: null plus rate_limit_malformed naming the reason, so such a token is not mistaken for an unlimited one. |
budget_usd |
number | null | null |
Per-token spend cap in USD. null means no cap. Enforced with every digit it is stored with, whether or not the token's row is served from the gateway's short-lived auth cache. Must be a JSON number that is finite and non-negative; a negative, non-finite (inf — e.g. JSON 1e999 — or nan), or non-numeric value is rejected with HTTP 400 — including a numeric string such as "5" (unlike expires_at, which also accepts a decimal-digit string, a budget is only ever a number). |
Amount input. Applies to
budget_usd(token and per-user budget). The console's amount fields read what you type exactly; this is the console's input rule, not an API rule: the API takes JSON numbers. The console accepts plain digits with at most one decimal separator (50,12.5,12,5). It refuses, with a message under the field as you type and nothing sent: an ambiguous amount (10,000,10.000), thousands grouping (1,234.50), more than six decimal places or 15 significant digits, anything that is not an amount (letters, currency symbols, exponents such as1e3, signs) and an amount out of range. See Entering an amount.
Token lifetime policy and self-minting
A tenant can bound how long a token lives and decide whether members may mint their own. Both are tenant settings, changed with PATCH /tenants/{id} (see Tenants and gateways).
| Setting | Default | Effect |
|---|---|---|
token_max_lifetime_days |
null (no cap) |
Maximum lifetime of a token minted or edited on a user-facing route. A whole number of days; null means no cap (tokens may be non-expiring), and PATCHing null clears an existing cap. The policy is enforced on mint and on PATCH of expires_at. |
self_mint_tokens |
1 (on) |
An integer switch, 0 or 1 (the strings "0"/"1" are accepted too); any other value, booleans included, answers HTTP 400. With 0, POST /me/tokens, POST /me/connect/ox and device-code approval (POST /admin/v1/device/approve) answer HTTP 403 self_mint_disabled; MCP OAuth consent is not blocked. Admin mint routes (POST /users/{id}/tokens, POST /gateways/{id}/tokens) are not affected. |
Under the policy a mint with no expires_at (or null), or one beyond now plus token_max_lifetime_days, answers HTTP 400 with code: "token_lifetime_exceeded" and max_lifetime_days in the body; nothing is persisted. A PATCH that moves expires_at past the limit (or clears it) is refused the same way. A PATCH that does not send expires_at (for example a rate_limit edit) is not affected, and the policy check on a PATCH runs after the 404/403 checks, so a caller refused there never sees the policy. The OX connect token expires at now plus the policy's days (no expiry when the tenant has no cap). The tenant policy is read fail-closed: a database fault answers HTTP 503 (retry); a missing or malformed tenant row answers HTTP 500; there is never a permissive default. A tenant with no stored cap (null) and self-minting on (1) behaves as before this feature.
In the admin UI the token create and edit forms (Profile → Tokens, Users, Gateway tokens, agent token) show these refusals next to the field they name instead of the generic "could not be created" message: a 400 invalid_field with field set to label, scopes, rate_limit, budget_usd or expires_at, and a 400 token_lifetime_exceeded (at the expiry field, with the maximum number of days). An expiry in the past is refused in the form before anything is sent. Such a refusal is a validation answer, not a client error, and is not reported. A refusal for a field the form has no input for is shown as the server's reason in the form's "could not be created" message (or the general message when the reason is not safe to show) and is reported.
Storage faults on a mint. Every token-mint route (POST /admin/v1/me/tokens, POST /admin/v1/users/{id}/tokens, POST /admin/v1/gateways/{gw}/tokens, the playground token, the connect token and the agent MCP token) answers 503 { "error": "temporarily unavailable; retry later" } with a Retry-After header when the token row insert hit a transient database fault and the storage layer proved that nothing was stored (no token exists; the plaintext was never returned). Mint again. A foreign-key refusal (the user, gateway or agent was deleted meanwhile) is never the 503: no retry can succeed, so it keeps its own answer. Any other storage fault answers the sanitised 500 { "error": "internal error", "request_id": "…" }.
Not retroactive. Tokens minted before a policy was set, non-expiring ones included, keep working until they expire or are revoked. Only a PATCH that touches expires_at must comply with the policy; other edits are allowed.
Exempt by construction. The agent scheduler's service token and the chat-bridge loopback token are created by internal code that never reads the policy, so they stay non-expiring. There is no label that exempts a token on the HTTP routes. The device-code and MCP OAuth credential families follow token_max_lifetime_days (absolute lifetime and access-token expiry are capped; see Device-code auth and MCP proxy OAuth); self_mint_tokens gates device approval only.
Audit. Every successful mint writes exactly one token.minted row to the audit log with the actor, gateway, route and token id, and never the token itself. Changing the settings writes tenant.token_max_lifetime_days_changed / tenant.self_mint_tokens_changed.
💡 Note: Tokens are hashed with SHA-256 before storage. The plaintext
tokenvalue is returned once in the creation response and cannot be retrieved later. If a token is lost, revoke it and create a new one. Beyond the configurable fields above, the list endpoint returnsid,user_id,token_hash(not the plaintext value), andcreated_at(Unix seconds) for each token.
Per-agent tokens
Passing agent_id on token create mints a per-agent token — a token cryptographically bound to one saved agent (auth_token.agent_id), so a scheduled agent's actions are attributable to a distinct verifiable principal instead of a shared human/service token. A per-agent token:
- may invoke ONLY its bound agent via
POST /v1/{tenant}/{gateway}/agents/{slug}/invoke. Invoking a different agent, or driving the agent-less scheduled-task endpoints (/agents/scheduled-task/{id}/...), is rejected404AGENT_NOT_FOUND(enumeration-safe, fail-closed); - may NOT drive raw inference. A raw inference call on a real provider —
POST /v1/{tenant}/{gateway}/{provider}/...where{provider}isanthropic/openai/compat/ a model provider (not theagentspseudo-provider) — is rejected403FORBIDDENat the request boundary, before any routing or model call. The token is confined to theagentspseudo-provider (its/invokeand, for the scheduler, its own/deliver-emailseam); within that plane the fences above decide (own agent → allowed, a different agent or the scheduled-task plane →404). Enforced server-side from the token→agent binding, independent of the token'sscopes(the client is never the authz boundary); - is attributed on every request as
request_log.token_agent_id(the bound principal — distinct fromagent_id, the invoked agent); - dies with its agent — the FK is
ON DELETE CASCADE, so hard-deleting the agent removes the token (no orphan credential).
Least-privilege confinement. A per-agent token is confined to its own agent's operational plane — it is not a full inference credential (unlike the shared service token it replaces): it cannot make a raw inference call on any real provider. The confinement derives from the token→agent binding, not from a capability scope: a per-agent token still lists inference in its scopes (scopes and agent-binding are orthogonal axes), but that inference scope is overridden by the binding — the token cannot make a raw inference call regardless of what its scopes display. The scheduler continues to drive its agent's deliver-email with the per-agent token (same-agent, recipient-pinned, PII-gated), so per-agent attribution is preserved on delivery. On an auth_required: false gateway (where an anonymous, token-less request may already infer) the confinement is not applied — a known-but-confined token is never held stricter than presenting no token at all.
Scheduler adoption. The agent scheduler prefers a per-agent token file (~/.config/myra-dev/agent-token-<agent_id>) when an operator provisions one — mint a per-agent token here, then drop it in that file (the same operator model as the per-gateway service token). Absent → the per-gateway service token is used unchanged (zero behaviour change). If a provisioned per-agent token is rejected (401 — token_expired for a lapsed one, token_revoked for one an administrator deleted; see Error codes), the scheduler falls back once to the gateway service token (with a warning) so a bad per-agent credential can't silently kill the agent. The agent Try-it tab and the create-modal Preview show a localized message for each of these codes instead of the raw server text.
Hint and last use. A per-agent token minted through POST /gateways/{gw}/tokens stores its 4-character hint (the last 4 characters of the token), so the agent's credentials list can name it ("Token ending …abcd"); other gateway tokens are minted without a hint, as before. When a token was last used (last_used_at, unix seconds, recorded at most once per token per 5 minutes) is exposed only by GET …/agents/{id}/credentials; the gateway token list and the MCP token list do not include it. Creating and revoking these tokens in the web app: The agent's identity and credentials.
Listing gateway tokens
Listing requires the GATEWAY_TOKENS_MANAGE permission, the same as creating, editing and revoking
gateway tokens. A caller without it gets 403, answered before the gateway is looked up (so it
does not reveal whether a gateway exists). The Gateways page hides the Auth Tokens card for such a role.
The response is always a JSON array (an empty gateway returns []). The gateway's own
internal service credentials are excluded from this list — see below.
Internal service credentials
Some auth_token rows are the gateway's OWN internal operational credentials, not
customer-manageable tokens. They are minted user-less (user_id null) under a reserved label
convention:
- the agent scheduler's per-gateway service token — label ends
-scheduler-service(empty scopes, no expiry, a spend cap); - the chat-bridge loopback invoke token — label starts
chat-bridge:(empty scopes, no expiry).
These credentials are hidden from GET /gateways/{id}/tokens, and PATCH or DELETE on one
answers 403 { "error": "this token is an internal service credential and cannot be … " }
before any change is made. Revoking one would 401 every scheduled agent / the
chat-bridge invoke path — a self-inflicted outage — so the tenant admin API refuses. A malformed
user_id, or empty/rotated scopes, does not weaken the protection (the check fails closed —
it matches on the user-less shape plus the reserved label and deliberately ignores scopes). A
DELETE that cannot read the row's identity because of a transient database fault answers
503 rather than deleting anyway. (Internal teardown paths — e.g. removing a chat-bridge
connection — revoke these tokens through the storage layer directly, not this HTTP route, so they
are unaffected.)
Creating a gateway token
curl -X POST https://<your-gateway-host>/admin/v1/gateways/{gateway_id}/tokens \
-H "Content-Type: application/json" \
-d '{
"label": "CI bot",
"scopes": ["inference"],
"expires_at": null,
"rate_limit": null,
"budget_usd": null
}'
expires_at follows the same rule as the other token routes: an optional whole unix-seconds timestamp in the future and within 100 years; a non-integer, past, or milliseconds-magnitude value is rejected with HTTP 400. Every other field is validated by the one shared token-body boundary — the same module the edit route, the user token route and the personal token route use, so no route can drift: label, user_id and agent_id per the Token fields table, scopes as an array of alphabet strings, rate_limit as an object with a required requests, and budget_usd as a finite non-negative number. Every malformed field answers HTTP 400 with an error that names the field, and nothing is persisted; a well-formed body is unchanged. A gateway that was deleted while the mint was in flight answers 404 { "error": "not found" } (the insert waits behind the delete's row lock and is refused once the gateway is gone — never a token on a deleted gateway, and never a misleading user message); the same mapping applies to the user token, personal token and playground token routes — one shared classifier decides from the constraint the database named. The user-side counterpart differs per route because each route knows what the user was on its wire: on this route user_id is a body field, so an unknown or other-workspace one, or one hard-deleted while the mint was in flight, is the audited 404 { "error": "not found" } (the gateway-deleted race above is audited the same way); on /users/{user_id}/tokens the user is the path resource, so a user hard-deleted while the mint was in flight is that route's 404 { "error": "user not found" }; on /me/tokens and /playground/token the user is the session itself, so the same race is the masked 500 (logged) — never a user_id message about a field the caller did not send. Should the insert still fail for a reason the validators cannot foresee, the response is the sanitised 500 {"error":"internal error","request_id":"…"} — the raw database message is logged server-side under the request_id, never returned.
Response:
{
"id": "tok_def456",
"token": "myra_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"gateway_id": "gw_xyz789"
}
Creating a gateway token with rate limit and budget
curl -X POST https://<your-gateway-host>/admin/v1/gateways/{gateway_id}/tokens \
-H "Content-Type: application/json" \
-d '{
"label": "production-client",
"user_id": "usr_abc123",
"scopes": ["inference"],
"expires_at": 1798761600,
"rate_limit": {"requests": 60, "window_sec": 60},
"budget_usd": 100.00
}'
A token lives in its owner's own workspace
A token that belongs to a user — a personal token (POST /me/tokens), a token created for another user (POST /users/{id}/tokens, or POST /gateways/{id}/tokens with a user_id), an OX Connect token and a device-code approval — can only be created on a gateway of that user's own workspace (tenant). This holds for platform administrators too: an administrator can see and manage every workspace's gateways, but cannot put a user's token (their own included) on another workspace's gateway. An account that belongs to no workspace has no gateway a token could use.
gateway_id in the body is checked in this order, and each answer refuses — nothing is created:
| Input | Answer |
|---|---|
absent or JSON null |
400 { "error": "gateway_id required", "code": "gateway_id_required" } |
not a string, "", longer than 36 bytes, invalid UTF-8, or containing a refused character (a number, boolean, object, array …) |
400 { "error": "gateway_id must be a gateway id", "code": "gateway_id_invalid" } — no lookup is made |
| a well-formed id of no gateway | 404 { "error": "not found" } |
| a gateway the caller cannot reach (a tenant-scoped caller naming another workspace's gateway, or any caller without a workspace who is not a platform administrator) | 404 { "error": "not found" } — the same answer as an unknown id (why) |
| a gateway outside the token owner's workspace (e.g. a platform administrator creating a token for a user of workspace A on a gateway of workspace B, or on any customer gateway for themselves), or an owner without a workspace | 403 { "error": "gateway_outside_owner_tenant", "code": "gateway_outside_owner_tenant", "message": "…" } |
| the owner's department does not allow the gateway | 403 department_gateway_not_allowed |
On POST /gateways/{id}/tokens, when the workspace has switched on require_token_owner, a request with neither a user_id nor an agent_id (absent or null) is 400 { "error": "token_owner_required" } and no token is created. The label does not exempt a request. If the setting cannot be read, the mint fails closed (503) rather than creating the token.
GET /gateways/{id}/tokens takes one optional filter, ?owner=none: it returns only the live tokens with no user and no agent. The parameter is validated after the permission and gateway-reach checks; any other value (empty, bare ?owner, all, NONE, a repeated parameter) is 400 { "error": "invalid_owner_filter" }. Without the parameter the list is unchanged. Known gap: a user-less token whose label imitates an internal service credential is hidden from this list (and from the normal one) like the real ones.
On POST /gateways/{id}/tokens the gateway is the path and a user_id the caller cannot see (unknown, or of another workspace) is the audited 404 { "error": "not found" } (the same as an unknown id — no cross-tenant existence oracle); a platform administrator naming a user outside the gateway's workspace gets 403 gateway_outside_owner_tenant. The stored and returned gateway_id is the gateway's own id (its canonical spelling), not the request's. Tokens created before this rule existed are not revoked by it; the inference gate already refuses a token whose owner belongs to another workspace than the gateway (or drops it to anonymous on a gateway that does not require auth).
Creating a user token
User tokens work identically to gateway tokens but are listed under the user and can be managed via the user endpoint. gateway_id is required — it specifies which gateway the token grants access to, and it must be a gateway of the target user's own workspace (see A token lives in its owner's own workspace).
curl -X POST https://<your-gateway-host>/admin/v1/users/{user_id}/tokens \
-H "Content-Type: application/json" \
-d '{
"gateway_id": "gw_xyz789",
"label": "personal dev token",
"scopes": ["inference"],
"budget_usd": 10.00
}'
Editing a token
The three operational controls of an existing gateway token — rate_limit, budget_usd (spend cap), and expires_at — can be changed in place, without revoking and re-minting the token (so the plaintext secret already deployed to a client keeps working). The token's identity fields (token_hash, scopes, user_id, label) are set at mint time and are not editable here.
curl -X PATCH https://<your-gateway-host>/admin/v1/gateways/{gateway_id}/tokens/{token_id} \
-H "Content-Type: application/json" \
-d '{
"budget_usd": 250.00,
"rate_limit": {"requests": 120, "window_sec": 60},
"expires_at": 1798761600
}'
Authorization: same as creating or revoking a token — the caller needs the GATEWAY_TOKENS_MANAGE permission (Manage gateway API tokens; held by tenant_admin and platform admin by default) and access to the gateway's tenant. A member / cross-tenant caller is rejected; the SPA hides the control from non-admins, but the backend is the authoritative boundary. A token that belongs to a user additionally requires the caller to out-rank that user (see Acting on another user requires out-ranking them): editing — or revoking — a peer tenant admin's or a platform admin's token is refused with 403 (target_outranks_caller), nothing changed. Your own tokens and gateway service tokens (no user) are not affected.
Owner rank guard (the same rule as minting a token for a user — see Acting on another user requires out-ranking them): when the token belongs to a user, the caller must reach and out-rank that user. A tenant_admin may edit or revoke the tokens of users whose role it could assign (ki_manager, finance, member, viewer); editing — for example lifting the budget cap or clearing the expiry of — or revoking the token of a peer tenant_admin, a platform admin, or a user of another tenant is refused 403 target_outranks_caller, even on a gateway of the caller's tenant; a platform admin may edit or revoke any. Your own tokens and a token without an owner (user_id empty) are not affected. If the owner cannot be looked up (a database fault) the request is refused 503 and nothing changes.
Partial semantics. Only the fields present in the body are changed; an omitted field is left untouched. A field sent as JSON null clears that control — "budget_usd": null removes the spend cap, "expires_at": null makes the token non-expiring, "rate_limit": null removes the per-token limit. At least one of rate_limit / budget_usd / expires_at must be present.
Accepted / rejected (validated at the trust boundary — fail closed, nothing persisted on rejection):
| Input | Result |
|---|---|
budget_usd a finite non-negative number, or null |
Accepted (sets / clears the cap) |
budget_usd negative, non-numeric, or non-finite (inf — e.g. JSON 1e999 — / nan) |
400 |
expires_at a whole future unix-seconds timestamp within 100 years, or null |
Accepted (same rule as create) |
expires_at a non-integer (e.g. ISO-8601), past, or milliseconds-magnitude value |
400 |
any PATCH on an internal service credential (user-less -scheduler-service / chat-bridge: token) |
403 { "code": "service_credential_protected" } — the credential is gateway-internal and un-editable; even expires_at: null is refused |
rate_limit a JSON object with a required whole-number requests (1–1 000 000 000) and an optional whole-number window_sec (1–31 536 000, default 60), or null |
Accepted — stored as {"requests": N, "window_sec": S} with the default filled in |
rate_limit a scalar / string, an array, an empty object or one without requests, requests: null, any key other than requests / window_sec, or a leaf below 1, above its cap, fractional, non-numeric, or non-finite |
400 |
any field other than rate_limit / budget_usd / expires_at |
400 { "error": "unknown_field", "code": "unknown_field", "field": "<key>" } |
| empty body (no updatable field) | 400 { "code": "no_fields" } |
a token_id that is not a token of this gateway |
404 { "error": "token not found", "code": "token_not_found" } |
a token owned by a user the caller does not out-rank (a platform admin, a peer tenant_admin, another tenant's user) |
403 { "code": "target_outranks_caller" } — nothing changed |
| the owner lookup fails (database fault) | 503 — nothing changed, retry |
Response: 200 { "ok": true }. The updated controls take effect immediately — the cached token authorization is invalidated on update, so a lowered spend cap or rate limit applies to the very next request rather than after a cache-expiry delay.
Reading the controls back. To confirm a change, re-list the gateway's tokens with GET /admin/v1/gateways/{gateway_id}/tokens. In that response each token's rate_limit is a JSON object { "requests": …, "window_sec": … } (or null when the token has no per-token limit) — the same object shape you send on create/edit; budget_usd and expires_at come back as numbers. A stored rate_limit that cannot be parsed or used reads back as null rather than erroring the listing, with a rate_limit_malformed string naming the reason (such a token refuses every request until it is corrected).
Revoking a token
Response: 200 { "ok": true }; 403 { "code": "target_outranks_caller" } for a token owned by a user the caller does not out-rank (the same rule as editing it, above); 404 { "error": "token not found" } for a token_id that is not (or no longer) a token of this gateway — a second DELETE of an already-revoked id is a 404, not a silent success. An internal service credential answers 403 and is never revoked; a transient database fault while checking that answers 503 (never a delete-anyway).
The token row is deleted and a revocation tombstone (its hash, its gateway, the time) is written in the same transaction, so any subsequent inference request using the revoked token on this gateway returns 401 token_revoked with the revocation date — never the generic "verify the {gateway} segment" hint. Only an explicit revocation leaves a tombstone: a token that disappears together with its agent, user or gateway answers the generic 401 unauthorized. On an auth_required: false gateway a revoked token is silently dropped and the request proceeds anonymously, consistent with the rule that a known-but-refused token is never held stricter than presenting no token at all.
How immediate. On the site that processed the revocation the cached authorization is dropped right after the commit, so the next request there is refused. A request that read the live row just before the commit, or the other production site (active-active, per-site cache), can still be served for at most one authorization-cache TTL (5 minutes) — see Token security model.
Self-service tokens (/me/tokens)
These endpoints let users create and manage tokens for themselves without needing an admin to act on their behalf. Listing (GET) and revoking (DELETE) own tokens are available to any authenticated user regardless of role. Creating a token (POST /me/tokens), however, requires an authoring role (member, ki_manager, tenant_admin, or admin); a viewer or demouser gets 403, because such a user is read-only and blocked from inference, so a minted token would be inert.
💡 Note: Creating a token via
/me/tokensdefaultsscopesto["inference"]when thescopesfield is absent ornull. An explicit[]is stored as[](unrestricted) — it is not silently narrowed. Every field of this body is validated by the same shared boundary as the gateway token route: a malformedscopes,label,rate_limit,budget_usdorexpires_atanswers HTTP 400 naming the field and mints nothing.
Listing own tokens
Response: array of token objects.
Creating own token
curl -X POST https://<your-gateway-host>/admin/v1/me/tokens \
-H "Cookie: aig_admin=<session>" \
-H "Content-Type: application/json" \
-d '{
"gateway_id": "gw_xyz789",
"label": "my laptop",
"expires_at": null,
"budget_usd": null,
"rate_limit": null
}'
| Field | Type | Required | Description |
|---|---|---|---|
gateway_id |
string | Yes | Gateway the token grants access to. Must be a gateway of your own workspace — platform administrators included; absent → 400 gateway_id_required, malformed → 400 gateway_id_invalid, another workspace's → 404 not found, the same as an unknown id (a platform administrator: 403 gateway_outside_owner_tenant) (see A token lives in its owner's own workspace). |
label |
string | No | Human-readable name — a valid UTF-8 string of at most 255 bytes without control or invisible formatting characters (see refused characters); anything else is HTTP 400. The label playground is reserved (HTTP 400). The label is descriptive only and never changes authorization: every user-bound token passes the same live user checks (deleted or disabled user, processing restriction, viewer role) and the same tenant check, whatever its label. |
scopes |
array | No | Capability scopes, same rule as the Token fields table (array of alphabet strings, ≤ 50). Absent or null → ["inference"]; a string / number / object-with-keys is HTTP 400. |
expires_at |
integer | null | No | Unix expiry timestamp (seconds since epoch). null = never. Must be a whole future value within 100 years; a non-integer (e.g. an ISO-8601 string), past, or milliseconds-magnitude value is rejected with HTTP 400. |
budget_usd |
number | null | No | Per-token spend cap in USD — a finite non-negative JSON number; a string (even "5"), object, or negative value is HTTP 400. |
rate_limit |
object | null | No | {"requests": N, "window_sec": S} — requests required, window_sec optional (default 60); a scalar, array, empty object, requests: null, or unknown key is HTTP 400. |
Response:
{
"id": "tok_abc123",
"token": "myra_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"gateway_id": "gw_xyz789"
}
Revoking own token
curl -X DELETE https://<your-gateway-host>/admin/v1/me/tokens/{token_id} \
-H "Cookie: aig_admin=<session>"
Response: 200 { "ok": true }. Returns 403 if the token does not belong to the caller — including an id the caller already revoked (it is no longer in the caller's list, so the ownership check refuses it before anything else); 404 { "error": "token not found" } is possible only if the token vanishes between that check and the delete. The revocation itself works exactly like the gateway route above: row deleted and tombstone written in one transaction, the token's next use on its gateway answers 401 token_revoked, and the cache guarantee is the same.
User types
Listing user types
Returns the registry of available chat-persona roles ("user types"). These are the options for a tenant's default_user_type setting; they are static metadata, not tenant-scoped data. Available to any authenticated admin user.
Response: array of persona entries. Returns 401 { "error": "unauthenticated" } if the caller is not authenticated.
| Field | Type | Description |
|---|---|---|
slug |
string | Persona identifier used as default_user_type (e.g. consumer, bundestag). |
label_key |
string | i18n key for the display label (e.g. userType.consumer). |
[
{ "slug": "consumer", "label_key": "userType.consumer" },
{ "slug": "bundestag", "label_key": "userType.bundestag" }
]