Scoped API Keys
LatticeDX uses Personal Access Tokens (PATs) formatted as ldx_pat_* to grant programmatic access to external integrations, CI/CD pipelines, IIoT gateways, and off-box agents. Each key is bound to a verified user, organization, and role inside latticeApiKeys (protected by FORCE ROW LEVEL SECURITY) and checked against explicit permission scopes before any resource handler executes.
Token Format and Storage Schema
Tokens are generated using node:crypto randomBytes in a fixed structure:
ldx_pat_<8hex>_<32hex>| Token Part | Storage Behavior |
|---|---|
Lookup prefix (keyPrefix) | ldx_pat_ followed by 4 random hex-encoded bytes (8 characters), stored in plaintext for operator identification and auditing. |
Secret (token) | 16 random bytes (32 hex characters) returned once in the dxosApiKeys:issue response and never persisted. |
Hash storage (keyHash) | The server stores a SHA-256 digest of the full token string under the unique index uidx_lattice_api_keys_hash. |
| Parameter | Type | Default | Description |
|---|---|---|---|
organizationIdrequired | string | — | Tenant organization identifier bound to the key. |
namerequired | string | — | Human-readable label (1..120 characters). |
keyPrefixrequired | string | — | Public lookup prefix formatted as ldx_pat_<8hex>. |
keyHashrequired | string | — | SHA-256 digest of the raw token (unique index uidx_lattice_api_keys_hash). |
userId / employeeIdrequired | bigInt | — | Owning user ID and employee membership record. |
roleNamerequired | string | — | NocoBase role clamped onto every request using this key. |
scopesJsonrequired | jsonb | — | Array of granted permission scopes. |
expiresAt / lastUsedAt / revokedAt | date | — | Expiration timestamp, 60s-throttled last-used timestamp, and revocation timestamp. |
active | boolean | true | Active flag; set to false immediately on revocation. |
Middleware Verification Pipeline
The createPaasApiKeyAuthMiddleware handler (registered before: 'auth') accepts credentials via either header:
X-Lattice-API-Key: ldx_pat_<8hex>_<32hex>Authorization: Bearer ldx_pat_<8hex>_<32hex>(when no host session user is already resolved)
Verification runs inside withSystemRlsBypass:
- Validates format against
PAT_TOKEN_RE, computesSHA-256, and compareskeyHashusing constant-timetimingSafeEqualHex. - Asserts
active === true,revokedAt == null, and unexpiredexpiresAt. - Confirms the owning
usersaccount,rolesUsersrole binding, andlatticeEmployeesmembership inorganizationIdare all active. - Calls
clampHeaderRole(ctx, roleName)to overwrite any incomingx-roleheader variant, preventing header-based privilege elevation. - Throttles
lastUsedAtupdates to at most once per60seconds (LAST_USED_THROTTLE_MS = 60_000) to avoid database write amplification on hot API paths.
Direct REST queries against /api/latticeApiKeys:* are blocked (403 PAAS_PRIVATE_COLLECTION_FORBIDDEN) for all non-root roles.
7 Permission Scopes (ALLOWED_PAT_SCOPES)
Every issued key requires between 1 and 20 scopes chosen from the 7 valid values:
| Scope | Read Access | Unlocked Mutating Actions |
|---|---|---|
read | All GET, HEAD, OPTIONS endpoints and approved safe POST queries | Blocks all state-mutating operations (403 API_KEY_SCOPE_INSUFFICIENT) |
write | Includes all read access | Unlocks all create, update, delete, and key management (dxosApiKeys) actions across permitted roles |
wms | Role-permitted reads | Mutating actions on dxosWms (receiveStock, issueStock, epodCapture) |
dmn | Role-permitted reads | dxosDmn:saveTable and dxosDmn:saveDelegation |
iot | Role-permitted reads | dxosBroker, dxosAutomations, and IoT actions on dxosBlocks (telemetryIngest, twinSetDesired, twinAckCommand, alarmIngest, alarmAck, alarmClear, provisionDevice, revokeDevice, deviceStatusIngest) |
ai | Role-permitted reads | dxosAi, dxosMcp, /api/dxos-mcp, /api/dxos-mcp/it-ot, dxosN8n, dxosAutomations, and dxosApprovals:decide |
ledger | Role-permitted reads | Document signing and key rotation via dxosLedger:signDocument and dxosLedger:rotateKey |
Alongside GET, HEAD, and OPTIONS, keys holding only the read scope may invoke read-only POST actions (*:list, *:get, *:count) and deterministic verification/query endpoints: dxosLedger:verify, dxosLedger:verifySignature, latticePara:hybridSearch, dxosDmn:evaluate, dxosStudio:solutionBundleDiff, charts:queryData, dxosDataGov:computeMkt, and latticeIntegrations:{record,context,proposals,proposalReceipt}. Requests to /api/dxos-mcp* with a read-only key are rejected.
Key Lifecycle Endpoints (dxosApiKeys)
Issuing a Key
/api/dxosApiKeys:issue| Parameter | Type | Default | Description |
|---|---|---|---|
namerequired | string | — | Human-readable key label, 1..120 characters. |
scopesrequired | string[] | — | Non-empty array of scopes from {read, write, wms, dmn, iot, ai, ledger}. |
expiresInDays | integer | null | Validity window in days (1..365). Omit for non-expiring keys. |
roleName | string | — | Role bound to the key. Non-admin users may only select non-elevated roles they currently hold. |
userId | integer | — | Target user ID. Only administrators or root may issue keys for other users. |
organizationId | string | — | Target organization identifier (only root may specify another organization). |
Privilege escalation protections in resolveIssueTarget:
- Non-administrators (
allowConfigure !== trueand lackingpm/pm.*snippets) cannot issue keys for other users (API_KEY_FORBIDDEN) or bind elevated roles (API_KEY_ROLE_ESCALATION). - Organization admins (
ldx_admin) cannot issuerootkeys or keys belonging to another organization (NATIVE_ORGANIZATION_MISMATCH).
Listing and Revoking Keys
/api/dxosApiKeys:list?limit=50/api/dxosApiKeys:revokeZero-Downtime Key Rotation
To rotate credentials used by active workers or edge gateways without dropping traffic:
- Issue a replacement key via
POST /api/dxosApiKeys:issuewith the sameroleName,scopes, andexpiresInDays. - Deploy the new secret to client configurations and confirm a successful
GEThealth or list call. - Revoke the previous key via
POST /api/dxosApiKeys:revoke; subsequent requests using the old token fail immediately with401 API_KEY_REVOKED.
# 1. Issue a scoped key for WMS sync
curl -sS -X POST "https://app.example.com/api/dxosApiKeys:issue" \
-H "Authorization: Bearer <ADMIN_JWT>" \
-H "Content-Type: application/json" \
-d '{
"name": "wms-scanner-sync",
"scopes": ["read", "wms"],
"roleName": "ldx_operator",
"expiresInDays": 90
}'
# 2. Revoke the superseded key after rollout
curl -sS -X POST "https://app.example.com/api/dxosApiKeys:revoke" \
-H "Authorization: Bearer <ADMIN_JWT>" \
-H "Content-Type: application/json" \
-d '{"id": 14}'Rate Limits and Error Codes
Traffic authenticated with ldx_pat_* is subject to APISIX limit-count buckets (240 req/60s on /api/*, 120 req/60s on /api/dxos-mcp*, 300 req/60s on telemetry ingestion) and the NocoBase ACL rules attached to the key's roleName.
| Error Code | HTTP | Cause |
|---|---|---|
API_KEY_INVALID | 401 | Fails PAT_TOKEN_RE, fails keyHash match, or has invalid user/org binding |
API_KEY_REVOKED | 401 | Key is inactive (active !== true) or revokedAt is set |
API_KEY_EXPIRED | 401 | Current timestamp is past expiresAt |
API_KEY_USER_INACTIVE / API_KEY_ROLE_REVOKED / API_KEY_MEMBERSHIP_INACTIVE | 401 | Owner account disabled, role removed from rolesUsers, or employee deactivated in latticeEmployees |
API_KEY_SCOPE_INSUFFICIENT | 403 | Key lacks write or the domain scope (wms, dmn, iot, ai, ledger) required by the action |
API_KEY_ROLE_ESCALATION | 403 | Caller attempted to bind a role with higher privileges than held |
