Security

Authorization

ulex's authorization model: the full scope list with what each grants, tenant isolation, organization membership roles, the auth policy, per-application restrictions, how impersonation is gated and audited, and how to choose the narrowest scope that works.

ulex has four authorization layers, checked in this order. Knowing which one rejected a request is most of the debugging.

text
1. Authentication   is there a valid credential?
2. Scope            does it carry the scope this operation requires?
3. Tenant isolation is the resource in THIS tenant?
4. Application policy   is the user's membership, status, and MFA level sufficient?

#1. Scopes

#User-facing (OIDC)

ScopeGrantsIn the token
openidsub, the OIDC handshakeyes
profilename, nickname, locale, pictureyes
emailemail, email_verifiedyes
offline_accessa refresh tokenyes

#Control plane

ScopeGrants
read:organizationsGET /organizations*, /domains, /members
write:organizationsPOST/PATCH/PUT/DELETE on the same
read:usersGET /users*
write:usersPOST/PATCH/DELETE /users*, suspend, unsuspend
read:groupsGET /groups*
write:groupsgroup and membership writes
read:connectionsGET /connections*, /saml/metadata, /saml/login
write:connectionsconnection CRUD, /activate, /verify
read:directoriesGET /directories*, sync runs
write:directoriesdirectory CRUD, /sync
read:applicationsGET /applications*, /secret, /metadata
write:applicationsapplication CRUD, /rotate-secret
read:webhooksGET /webhooks*, /deliveries
write:webhookswebhook CRUD, /enable, /disable, /test
read:audit_logsGET /audit-events*, including export
read:deploymentsGET /deployments*, /environments*, /logs
write:deploymentsPOST /deployments, /cancel, /rollback

#Protocol and MCP

ScopeGrants
scim:provisioninbound /scim/v2 writes, and reading SCIM bearer tokens
saml:consumePOST /connections/{id}/saml/acs and /saml/slo
mcp:toolsevery read-only MCP tool
mcp:admindestructive MCP tools: ulex_reset_tenant, ulex_delete_*, ulex_rotate_*
sso:impersonateimpersonation_only connections
ulex:admineverything, including key rotation, signing-key rotation, and impersonation

#Admin-only

ulex:admin, mcp:admin and sso:impersonate are rejected at mint time for a non-admin key, not at call time. You cannot create a key that carries a scope you are not entitled to.

#Choosing

WorkloadScopes
An agent bootstrapping an appmcp:tools, read:organizations, write:organizations, read:users, write:users, read:groups, write:groups, read:applications, write:applications, read:connections, write:connections, read:audit_logs
A CI test suitethe same, minus mcp:admin
A read-only dashboardmcp:tools, read:organizations, read:users
A web service reading its own directoryread:organizations, read:users via client credentials
A customer's IdP (SCIM)scim:provision via a SCIM bearer token
Key rotation in CIulex:admin, ip_allowlist set, 30-day expiry
Warning

ulex:admin also grants ulex_revoke_api_key, ulex_reset_tenant, and impersonation. A key with it can log in as any user in your tenant. Always treat it as a high-privilege credential.

#Reading the rejection

json
{
  "error": {
    "type": "permission_error",
    "code": "insufficient_scope",
    "message": "This credential requires the write:organizations scope.",
    "request_id": "req_01M3PSW9R0175NAW62NYR403R8",
    "retryable": false,
    "hint": "Request scope: write:organizations.",
    "docs_url": "https://docs.ulexid.com/security/authorization#scopes"
  }
}

hint names the exact scope. insufficient_scope is retryable: false — a broader credential is required, not a retry.

#2. Tenant isolation

Every persisted record carries tenant_id, and every repository read filters on it in the query, not in application code.

Behaviour
A resource in another tenant404 not_found, not 403
A resource in another tenant, deliberately403 cross_tenant — only for explicitly cross-tenant operations
Cross-tenant access without ulex:adminimpossible. There is no API surface that does it
Cross-tenant access with ulex:adminaudited as category: authorization with your request_id

Returning 404 for another tenant's resource is deliberate. A 403 confirms the id exists, which is a tenant-enumeration oracle.

Tenants and API keys are strictly bound to their originating store: a local in-memory key cannot reach https://ulexid.com, and an API key for one tenant cannot access another — there is no header that bypasses it.

#3. Organization membership

A user is tenant-global. Their authority is per organization.

roleCan do
ownereverything an admin can, plus delete the organization, transfer ownership, and change billing-relevant fields. The last owner cannot be removed
adminmanage users, groups, connections, and settings. Cannot delete the organization
memberuse the application. Read-only on identity resources
guestuse the application, scoped to specific groups via membership.group_ids

organization_membership.group_ids restricts a guest to the resources those groups grant. It is enforced at the API layer, not in your application.

#Join policy and SSO

FieldDefaultStateEnforced effect
allow_profiles_outside_organizationfalseEnforceda new user may join or JIT provision only if their email domain matches a verified domain on the organization
sso_onlyfalseEnforceddirect password sign-in is refused; only organization.connection_id or default_connection_id may authenticate. For users in multiple orgs, the most-restrictive rule applies across all memberships

ulex_bootstrap sets sso_only: true for enterprise SSO strategies, ensuring bootstrapped organizations require single sign-on through their configured enterprise connection. Direct password or social logins are refused with 403 access_denied.

#4. The auth policy

GET /api/v1/auth-policy and PUT /api/v1/auth-policy, or ulex_get_auth_policy / ulex_update_auth_policy.

There is one policy per tenant. GET never 404s: configured: false means nobody has called PUT yet, and the values returned are ulex's defaults. Each block also reports a set flag, so you can tell a value an operator chose from one they inherited:

json
{
  "configured": true,
  "policy": {
    "id": "pol_01M3PSW6DEQ00R000000R00000",
    "object": "auth_policy",
    "environment": "prod",
    "password": {
      "min_length": 14,
      "require_uppercase": true,
      "require_lowercase": true,
      "require_number": true,
      "require_symbol": true,
      "check_breached_passwords": true,
      "max_age_days": 365,
      "forbid_reuse_count": 5
    },
    "session": {
      "lifetime_seconds": 43200,
      "idle_timeout_seconds": 3600,
      "reauthenticate_after_seconds": 3600,
      "bind_to_ip": false,
      "bind_to_user_agent": true,
      "cross_app_sso": false
    },
    "mfa": {
      "mode": "adaptive",
      "methods": ["webauthn", "totp"],
      "remember_device_days": 30
    },
    "blocked_ip_ranges": ["203.0.113.0/24"],
    "set": { "password": true, "session": true, "mfa": false, "blocked_ip_ranges": true }
  }
}

set.mfa is false there: mfa.mode reads optional because that is the schema default, not because anyone decided on it. A value alone cannot tell you that, and an audit asking "did this tenant choose this" cannot answer it from the number.

PUT takes any subset of the blocks and merges onto the stored policy, so a call naming only session leaves password alone. id, tenant_id, environment and the timestamps are refused.

#What is enforced

Every field in auth_policy is enforced (password, session, mfa, and blocked_ip_ranges):

FieldDefaultWhere
password.min_length12the three places a human chooses a password: admin reset, portal signup, portal change
password.require_uppercase / _lowercase / _number / _symboltruesame
password.forbid_reuse_count5checks stored password history across resets and password changes
password.max_age_days365rejects stale password sign-ins with password_expired until rotated
password.check_breached_passwordstruetenant setting controls screening; ULEX_SCREEN_PASSWORDS is the default only when no tenant policy exists. A hit is a warning recorded as user.password_screened
mfa.mode: requiredoptionalchallenges enrolled users and enforces inline TOTP enrollment for factorless users
mfa.mode: adaptiveoptionalrisk engine evaluates new device cookie (ulex_device), IP changes, failed attempt velocity, and mfa.trigger_on_* flags
mfa.methods & remember_device_days["totp","webauthn"], 30restricts permitted enrollment/challenge factor types; remember_device_days issues signed ulex_device trust cookies
session.lifetime_seconds86,400written as session.expires_at
session.idle_timeout_seconds604,800written as session.idle_expires_at, clamped to lifetime_seconds
session.reauthenticate_after_seconds86,400written as session.reauthenticate_at; drives OIDC step-up
session.bind_to_user_agenttrueevery request that reads a session; a mismatch revokes it
session.bind_to_ipfalsesame, against a pseudonym of the address
session.cross_app_ssotrue/oauth2/authorize, on reuse from another application
blocked_ip_ranges[]every authenticated request, before any credential is read

A password that fails composition or history is refused with 400 password_policy_not_met or password_reused, and the composition message names every unmet rule at once. A password that appears in a breach corpus is warned about and stored: a corpus can be stale, and a refusal has to be right.

bind_to_ip defaults off because mobile networks change address mid-session. bind_to_user_agent defaults on because a cookie presented from a different browser is a stolen cookie far more often than it is a user with two browsers.

blocked_ip_ranges covers the whole API, not just the sign-in form: a blocklist consulted at the password page alone would leave the token endpoint, refresh rotation and every REST route reachable from the blocked network. Refusals are recorded as auth_policy.ip_blocked with the address pseudonymised, because a blocklist that refuses silently reads as a network fault to whoever is affected.

#RBAC roles and permissions

In addition to per-organization membership roles (owner, admin, member, guest), tenants can define custom RBAC roles (/api/v1/roles) with slugs and permission strings, assigned to organization memberships (PUT /api/v1/organizations/{id}/members/{userId}/roles) or groups (PATCH /api/v1/groups/{id}). Active matching-organization role slugs and permissions are emitted in deduplicated roles and permissions claims on access tokens, ID tokens, and /oauth2/userinfo, and enforced by @ulex/node (requiredRoles / requiredPermissions).

#allowed_countries was removed

It was a configurable field enforced nowhere, like the rest of this policy when it was written — and unlike blocked_ip_ranges it cannot be implemented honestly here. The only data source for a country is CloudFront-Viewer-Country, and ulex's CloudFront distribution configures no origin request policy that overwrites a viewer-supplied one. An allowlist built on that is worse than an absent one: it looks enforced, an auditor ticks the box, and one request header defeats it.

blocked_ip_ranges survives because its source is requestContext.http.sourceIp, which API Gateway populates from the connection and a client cannot set.

Restoring allowed_countries requires an origin request policy that sets the header explicitly, plus a test asserting the distribution has one. Add the field back at that point, not before.

An empty blocklist means nothing is blocked. There is no deny-by-default that surprises you on day one, and a request with no address at all — every local CLI and MCP invocation — is never refused.

#5. Per-application restrictions

Beyond scopes, an application constrains what its token can do:

FieldDefaultRestricts
grant_typesauthorization_code, refresh_tokenwhich grants the token endpoint will honour (including jwt-bearer, token-exchange, device_code)
response_types["code"]implicit is rejected in prod
response_modeform_post
require_pkcetruecannot be disabled
pkce_methods["S256"]plain must be added explicitly and is refused in prod
token_endpoint_auth_methodclient_secret_basicsupports client_secret_basic, client_secret_post, secretless private_key_jwt (via registered jwks / SSRF-checked jwks_uri + jti replay protection), mTLS (tls_client_auth with DN/SAN matching and self_signed_tls_client_auth via JWKS), and none
dpop_bound_access_tokensfalsewhen true, /oauth2/token and /oauth2/userinfo require valid RFC 9449 DPoP proofs bound via cnf.jkt, ath, and single-use jti
tls_client_certificate_bound_access_tokensfalsewhen true, binds access tokens to the mTLS peer certificate via cnf["x5t#S256"] (RFC 8705) checked at /oauth2/userinfo
subject_typenullnull defaults to public for first_party and pairwise for third_party; explicit public or pairwise overrides per OIDC Core §8.1
sector_identifier_urinullSSRF-checked HTTPS URL grouping pairwise-subject applications; required when explicit pairwise spans multiple redirect_uris hosts
require_pushed_authorization_requestsfalsewhen true, /oauth2/authorize refuses raw requests without a POST /oauth2/par request_uri
cross_app_sso_enabledtrueenforced: false means no session from another application may mint a code for this one
cross_app_sso_redirect_urls[]enforced: restricts which cross-app SSO handoff redirect URLs an application accepts
max_age on authorizationper requestenforced: the client's max_age is compared against session.auth_time
acr_valuesnullenforced: sets required assurance level / step-up floor (aal2 triggers MFA step-up when missing)
grant_access_to_organizationtrueenforced: false omits org_id/org_slug claims from issued tokens
organization_usageallowenforced: deny refuses an organization param; require prompts or demands organization membership selection (account_selection_required on prompt=none)
sign_in_with_email_enabledtrueenforced: false disables email/password & email-OTP sign-in on hosted UI and login endpoints
sign_up_enabledtrueenforced: false blocks self-registration on the hosted login flow for that application
brandingulex defaultsenforced: renders custom colors and sanitized logo_url/favicon_url in the hosted login UI
default_locale"en"enforced: localizes hosted UI strings with ui_locales support
saml_allow_idp_initiatedfalseenforced: GET /saml/idp/init/{appId} strictly returns 403 unless opted in

#6. Impersonation

impersonation_only connections and POST /simulator/authenticate let a tool log in as a user with no credential.

GateValue
Scopesso:impersonate or ulex:admin
Tenant modeallow_mocks: true (off by default on https://ulexid.com, forbidden when hipaa_enabled: true; true by default in local in-memory mode)
Auditimpersonation.started and impersonation.ended, always
Actoractor_type: "agent", never user
Token markeramr: ["urn:ulex:amr:impersonated"], acr: "urn:ulex:acr:simulated"
json
{
  "id": "aud_01M3PSW3WGDDFJFJHZ4QJNNFZD",
  "action": "impersonation.started",
  "category": "authorization",
  "actor_type": "agent",
  "actor_id": "key_01M3PSVJA0YP2WDPM2RDR15MGH",
  "target": { "type": "user", "id": "usr_01M3PSV9GRT8GQGEG686AR1W9S", "display_name": "Dana Okafor" },
  "metadata": { "connection_id": "con_01M3PSVAG0QFJG99R0M5DXSR5A", "reason": "e2e test" },
  "outcome": "success",
  "timestamp": 1790693112
}

Your application must reject these tokens in production. If acr === "urn:ulex:acr:simulated" satisfies an authorization check, any test tenant with allow_mocks: true could mint an accepted login. A token minted by ulex_mint_access_token carries urn:ulex:amr:simulated for the same reason.

ts
export function isSimulated(claims: AccessTokenClaims): boolean {
  return (
    claims.acr === "urn:ulex:acr:simulated" ||
    (claims.amr ?? []).some((m) => m.startsWith("urn:ulex:amr:sim"))
  );
}
if (isSimulated(claims)) throw new Error("simulated token rejected");

#7. Auditing denials

Every denial is an audit event with outcome: "denied".

bash
curl -sS -G "$BASE/audit-events" -H "$AUTH" \
  --data-urlencode 'outcome=denied' \
  --data-urlencode 'since=2026-09-29T00:00:00.000Z' \
  --data-urlencode 'limit=200' | jq -r '.data[] | "\(.actor_type) \(.action) \(.error_code) \(.target.id // "-") \(.ip_hash)"'
text
api_key mcp.tool_denied insufficient_scope ulex_delete_application sha256:9c2e4a6b…
api_key mcp.tool_denied insufficient_scope ulex_reset_tenant      sha256:9c2e4a6b…
user    authentication.succeeded  null         usr_01M3PSV9GRT8…   sha256:1a3c5e7f…

A sustained mcp.tool_denied from one actor is usually a mis-scoped key in a loop. A single authentication.succeeded for a user whose organization is pinned to one connection is worth a look; sso_only restricts authentication to the organization's enterprise connections.

#Reference