atlasauth
The official Rust backend verification crate for Atlas.
It is the Rust peer of the TypeScript @atlasauth/backend, Go (atlas-go), and
Ruby SDKs — the same verification semantics, the same claim names, the same
@no-email.invalid handling.
This is a server-side crate. API-key verification uses your instance secret key (
sk_...), which must never ship to a browser or mobile app. For client-side sign-in flows use the JS, Swift, Kotlin, or Flutter SDKs.
It does the two things a Rust service needs:
- Verify a session token locally against the instance JWKS — fast, offline, and correct within the short token lifetime, with no outbound call per request.
- Verify an end-user API key (
ak_...) against Atlas, with separate positive and negative caches so a busy API — or a caller hammering a bad key — never hammers Atlas.
Install
On crates.io:
# Cargo.toml
[]
= "0.32"
Requires Rust 1.95+ (the optional webhook-dedupe-sqlx feature needs sqlx's newer minimum). The default reqwest-transport feature pulls in reqwest
(rustls) for the built-in HTTP transport; disable it to supply your own.
Token verification
Backend services verify a session JWT locally against the instance JWKS. The
JWKS is cached in-process and refetched on an unknown kid at most once a minute
— the rate limit is a security property, not politeness: it stops a caller
sending random kids from turning your process into a traffic amplifier aimed at
the JWKS endpoint.
use ;
# async
# let session_jwt = "";
Verification is RS256 only: a token whose header says alg: none, HS256,
or anything else is rejected before any key is touched. It also checks exp /
nbf (5 s clock-skew tolerance), the issuer, and — as an OP token-confusion
guard — rejects any token carrying a token_use other than session or an
unexpected aud.
From a request
An Authorization: Bearer … header wins over a __session cookie (a
deliberately-set header should not be overridden by a stale cookie):
# use AtlasBackend;
# async
Authorized parties and audience
# use AtlasBackend;
#
Audience checking is optional and backwards-compatible. An Atlas session token
carries its instance id as aud by default, so leave it unset and the token
still verifies (the OP token-confusion guard is the token_use:"session"
marker, not the presence of aud). Set one or more expected audiences — via
.audience(x) one at a time or .audiences([...]) — and the token's aud must
contain at least one of them (OR), which is how a single verifier can serve
tokens for several instances or resource servers.
While your instance moves to a new sign-in host (a custom domain or a path mount
going active), .previous_issuers(["https://your-instance-fapi.atlasauth.net"])
also accepts tokens whose iss is the old host. iss must equal the issuer or
one of these; nothing else. The discovery document lists them in
atlas_previous_issuers with an accepted_until; remove them after that.
Offline / CI
Pass a static key set instead of a URL — no network call is ever made:
# use ;
#
Signing algorithms
Instances can sign session tokens with RS256, ES256, ES384, PS256 or EdDSA. Every verifier in the crate (session
tokens, the relying party's ID tokens, logout tokens, transaction tokens) accepts exactly those five. The key's
type must fit the algorithm in the token header (an RSA key verifies RS256 or PS256, a P-256 key ES256, a P-384 key
ES384, an Ed25519 key EdDSA); a key whose own alg differs is skipped, and none and HS* never verify.
Relying party (rp, rp-axum, rp-actix features)
Sign users in through Atlas's hosted page and keep your own session. RelyingParty builds the authorize redirect
(PKCE S256, state and nonce in one sealed, short-lived cookie), finishes the callback (code exchange, ID-token
verification against the issuer's JWKS), asks the same user to authenticate again for a step-up
(require_recent_auth), keeps the Atlas session alive (touch_if_due) and signs out (sign_out). The
rp-axum and rp-actix features add ready-made routes: implement RpHooks::on_signed_in to create your session.
let rp = new?;
let started = rp.start.await?; // 302 to started.location, set started.set_cookies
let done = rp.callback.await?; // done.user.sub, done.user.sid, done.redirect
Local mirrors, Web Bot Auth, webhook dedupe (backend / web-bot-auth features)
mirror::KeyMirror: end-user API keys verified against a local table (sha256 hash, scopes, expiry, IP allowlist) with Atlas as the minting and revocation backstop;mirror::SidRevocationListrejects tokens of revoked sessions;mirror::ResourceRoleMirroranswerscan(subject, permission, resource)with the server's inheritance rules. Each takes a small store trait (in-memory included) and async()on a timer.mirror::SidListRevocation { status_list: Some(Arc::new(StatusListSource::new(jwks_url, jwks_source, Some(issuer)))), .. }uses the signed session status list (one small signed answer, verified against the instance JWKS) and falls back to the paged feed when it is unavailable, was cut short, or does not verify.web_bot_auth: verify and sign RFC 9421 Web Bot Auth requests with a cached key directory and allow / block lists.webhook_dedupe::WebhookDeduper: verify a webhook and drop a retried delivery by its signedatlas-id. Featurewebhook-dedupe-sqlxaddssqlx_store::SqlxWebhookStore(PostgreSQL, SQLite, MySQL; use it from a multi-thread tokio runtime).client::MachineSession(featuremachine): enrol once, keep the identity in a store, mint audience-scoped machine tokens and cache them..dpop_key(DpopKey::generate())binds the tokens to a DPoP key (cnf.jkt); sign each call to your API withsession.dpop_proof(&token.token, "GET", url, None)and sendAuthorization: DPoP <token>.verify_transaction_token,Claims::authenticated_within,Claims::used_multi_factor,mfa_org_satisfied.
Observability and resilience
- Feature
tracing: every management-client request runs inside anatlas.requestspan withhttp.method,http.route(ids collapsed to{id}),http.status_code,atlas.retriesandatlas.duration_ms. Bridge to OpenTelemetry withtracing-opentelemetry. Without the feature there is no dependency and no code. - Feature
tracing-metrics(impliestracing):atlas_requests_total{method,route,status},atlas_request_duration_seconds{method,route}andatlas_request_retries_total{method,route}through themetricsfacade; install the recorder you like (Prometheus, an OpenTelemetry bridge). Route labels are templates, never ids. BackendClientBuilder::resilience(ResilienceConfig):Retry-Afteron 429 and 503 is honoured (up to a cap), retries back off with jitter, and withstatus_awarea 5xx reads the public status endpoint first (fail fast during a declared major outage, slower backoff while degraded).doctor::run: checks key shapes, clock skew against the API, JWKS reachability, service status, URL schemes and that the secret key is accepted; the report never contains a key.
Identity & email helpers
Resolving "what is this user's real email?" has one subtlety: when an OAuth
provider shares no email, Atlas seeds a …@no-email.invalid placeholder. The
helpers treat it as no real email:
# use User;
#
atlasauth::real_email(s) is the standalone twin: Some(s) for a real address,
None for the placeholder or an empty string. The verified session's email
claim has the same filter: claims.real_email().
API-key verification
End-user API keys (ak_...) are verified online against Atlas, because a
key's validity (revoked? expired? subject deleted?) lives server-side. To keep a
busy API from calling out per request, results are cached — with a longer
positive TTL and a short negative TTL, so a bad key is answered locally
without hammering Atlas, yet a freshly-minted key starts working within seconds.
use ApiKeyVerifier;
# async
# let presented_secret = "";
Every negative — unknown, malformed, revoked, expired, or a since-deleted
subject — resolves to the same valid == false, so a caller learns nothing about
which keys exist. A valid == false verdict is not an error; an
ApiKeyError means the endpoint could not be reached or the response did not
parse (e.g. a bad sk_ key → HTTP 401).
The secret key is sent as Authorization: Bearer sk_... and is never placed in a
URL.
Back-channel logout
When a user signs out, Atlas can POST a logout_token (OpenID Connect
Back-Channel Logout) to your app's back-channel logout URI. Verify it with the
same AtlasBackend you use for tokens — built with the issuer of the provider
that registered your client (https://atlasauth.net for Sign in with Atlas
apps, your instance issuer for your instance's own OAuth clients):
use ;
# async
# let logout_token = "";
The check follows the spec: RS256 only, the expected issuer, your client id in
aud, iat present (and not in the future), exp honoured when present, a
jti, the back-channel logout event, a sid and/or sub, no nonce, and a
typ of logout+jwt when present. Any failure is a VerifyError — answer 400.
A framework-agnostic handler:
use ;
/// POST /backchannel-logout (Content-Type: application/x-www-form-urlencoded)
/// Returns (status, headers) — map it onto your framework's response type.
async
# async
# async
LogoutTokenReplayCache remembers each accepted jti in memory so a replayed
token is refused. It covers one process; with several instances, record the
jti in your shared store instead (for example a Redis SET <jti> 1 NX EX 300).
Management API (backend feature)
= { = "0.32", = ["backend"] }
BackendClient covers the whole Backend API with your secret key, and the
Platform API with a platform key:
use ;
# async
Typed surfaces include users, organizations (memberships, invitations, domains,
policy, settings, branding, design), sessions, API keys, machines, billing,
entitlement overrides, notifications, audit events, tickets, user erasure, the
instance preflight, cookie consent, email/SMS delivery providers, social sign-in
providers, webhook endpoints, and the sign-in page design. Everything else —
roles and permissions, OAuth clients, SSO/LDAP/SCIM, FGA and the
OpenFGA-compatible API, connectors, data subject requests, templates,
localizations, log streams, network ACLs, RADIUS, rate limits, risk-based MFA,
bot signals, jobs, and the test-mode helpers — has a typed method per route,
whose request and response structs live in atlasauth::backend::types:
- Build a request with
Type::new()and thewith_*setters (orType::default()and assign fields). Unset optional fields are left out of the request;clear_*sendsnullwhere the API lets you clear a value. - Every struct has an
extramap. On a response it keeps any field the server added after this crate was released; on a request,with_extra(key, value)sends a field this crate does not know yet. - Enumerations are plain
Strings (each field's docs list the known values), so a new value from the server never fails to decode. - A few operations whose request or response is open-ended JSON keep
serde_json::Valueon that side.BackendClient::request_valuecalls any route with raw JSON.
Strict request bodies
By default the API ignores a body field it does not accept and names it in an
Atlas-Unknown-Fields response header. Turn on strict mode to get a
422 UNKNOWN_FIELD instead, and/or log what was ignored:
use ;
# async
Error codes worth branching on are in atlasauth::backend::codes
(UNKNOWN_FIELD, WRONG_KEY_SURFACE, INVALID_KEY, PLAN_IN_USE,
EMAIL_DELIVERY_NOT_CONFIGURED, EMAIL_PROVIDER_REQUIRED, EMAIL_PROVIDER_IN_USE, …):
err.has_code(codes::UNKNOWN_FIELD).
API key spend caps
Give an end-user API key caps per unit and period ("request", "second",
"minute", "day", "month" or "total"), then meter what each call costs. A debit that would
exceed a cap records nothing and comes back with allowed: false; it is not an
error:
use ;
# async
ApiKeyVerifier::verify also returns the key's name, scopes,
constraints, limits and current usage.
Session keep-alive
If your app loads the Atlas frontend SDK only on some pages, time spent on the other pages can count as inactivity. Touch the session from your backend to slide its inactivity window:
# async
A touch never extends past the session's absolute expiry and never revives an
ended session (409 SESSION_REVOKED, SESSION_IDLE_EXPIRED or
SESSION_EXPIRED). It writes at most once a minute, so calling it on every
request is safe.
Cookie settings link
With cookie consent on, the hosted pages can show a "Cookie settings" link in
their footer that reopens your consent tool. Pick a preset (cookiemunch,
cookiebot, onetrust, or custom with your own attributes):
use ;
# async
Removing the email provider
Removing the email provider is refused with 409 EMAIL_PROVIDER_IN_USE while
features that need email (email code or link sign-in, sign-up email
verification, password reset) are on and nothing else would send email. The
error's meta.features names them. To remove it anyway:
use ;
# async
Logout without a confirmation page
For a first-party OAuth client, skip_logout_confirmation makes RP-initiated
logout with the client's client_id and an exactly registered
post_logout_redirect_uri end the session and redirect straight back, without
the "Sign out?" page:
types::OAuthClientsUpdateBody::new().with_skip_logout_confirmation(true).
On a third-party client the API answers 422 VALIDATION_FAILED.
Sign-in page design and image uploads
The design is fully typed (AtlasDesign: preset, palettes, typography, shape,
card, layout, buttons, inputs, backgrounds, logo). Images are uploaded as raw
bytes; the content type is detected from the bytes when you pass None:
use ;
# async
Domain moves, logout fan-out and managed email
# async
logout_notify_endpoints() registers services that get the same logout_token as your OIDC apps,
messaging_providers().create_managed_email(..) sets your domain up on your own Resend or Brevo account
(with_transport + with_config(..with_api_key(..)), or with_provider_id), and with a platform
key platform().atlas_id_apps().find_users(..) answers a privacy request for one app and
platform().atlas_id_publisher() claims the publisher name shown on consent screens.
OAuth client secret rotation and development email
# async
Webhook::verify accepts an atlas-signature header that carries several signatures separated by spaces
(v1,<sig> v1,<sig>). While an endpoint secret rotates, Atlas may sign each delivery with the old and the new
secret; the delivery verifies when any one signature matches.
Webhook rotation overlaps and the trusted reverse proxy
A webhook rotation stops the old secret at once by default. Pass an overlap (at most 7 days) to keep it signing
each delivery next to the new one while you deploy; choose one only once every receiver accepts several
signatures. If a reverse proxy serves the Frontend API from your own origin, give it a proxy secret: it sends the
secret in X-Atlas-Proxy-Secret and the browser's IP in X-Atlas-Client-IP, and Atlas uses that IP for rate
limits, lockout, risk signals and audit logs.
# async
Platform rotations take an overlap too: platform().apps().rotate_instance_secret_with(.., &RotatePlatformSecretBody::new().with_overlap_seconds(0), ..) (default 72 hours),
platform().atlas_id_apps().rotate_secret_with(..) (default 24 hours) and rotate_webhook_secret_with(..)
(default 0).
Application webhooks
Send your app's own events to endpoints your customers' organizations register. Atlas signs them with
Standard Webhooks headers (webhook-id, webhook-timestamp in seconds, webhook-signature), retries
them and keeps the delivery log. Organization members manage their endpoints from the Frontend API with
the org:webhooks:manage permission (PERMISSION_ORG_WEBHOOKS_MANAGE).
# async
Browser tickets, test sign-in URLs, hosted pages
sessions().create_browser_ticket(user_id, redirect_url, expires_in_seconds) returns a one-time ticket
(and a ready url when you pass a redirect_url) that signs a browser in as the user, for support
handoffs and end-to-end tests. It replaces sign_in_tokens().create(), deprecated with a sunset of
2027-04-01. On a development instance the same client may redeem a ticket again within 10 seconds (a
dev-server double render); production tickets are strictly single-use. sessions().create_with(..)
takes the full POST /v1/sessions body. On development instances testing().create_sign_in_url(user_id, redirect_url, None) gives the URL in one call.
instance().get_sign_in_with_atlas() / update_sign_in_with_atlas(enabled, connection_id) control the
"Continue with Atlas" button, get_hosted_pages() / update_hosted_pages(..) send the hosted sign-in,
sign-up and account pages to your own URLs, and privacy().connect_integration(..) sets up the consent
manager, privacy orchestrator, completion webhook and executor key in one idempotent call
(get_integration() reads it back). PATCH /v1/instance and PATCH /v1/instance/referrals responses
carry warnings (for example an unknown_field that was dropped). /v1/instance/secret_keys is the same
route as /v1/secret_keys (secret_keys()).
Organizations, trusted-JWT connections, path mounts
organizations().create(..) takes external_id, public_metadata, private_metadata, owner_email
(the response then carries owner_invitation) and role_mappings; leave created_by empty for an
organization with no members yet. organizations().list_with(&metadata_query(..).set("external_id", "acme-1"))
filters, find_by_domain("ada@acme.example.com", false) finds the owner of a domain or email address,
get_policy(id) reads the policy, and get(id) carries the sso block (connections, scim_base_url).
Organization domains verify by DNS TXT, a well_known file or an emailed code:
domains(org_id).send_verification_email(domain_id, None) then verify_with(domain_id, "email", Some(code)).
jwt_connections() (list, get, create, update, delete) signs people in with a JWT your system
signs: send them to the connection's login_url?token=…&redirect_url=…. domains().create_path_mount(host, None, None) serves the Frontend API under /__atlas on a host you already run. Webhook endpoints take your
own secret on create and on rotate_secret_with(.., &RotateWebhookSecretBody::new().with_secret(..));
platform().apps().reveal_initial_secret(app_id, false) shows a new app's secret once more within 10 minutes.
Policy acceptance
Terms of service, a privacy policy or any policy your users accept at sign-up (and again at sign-in when a new version takes effect):
let tos = atlas.policies.create.await?;
atlas.policies.create_version.await?; // a draft, or publish at once
atlas.policies.publish_version.await?; // effective_at in epoch ms
let standing = atlas.users.get_policies.await?;
let csv = atlas.policies.export_acceptances_csv.await?;
instance().set_policy_source(..) connects an external system that serves your policy text (the signing secret is
write-only); instance().update_policy_settings(..) turns on the pol session claim, which Claims::pol() and
Claims::has_accepted_policy(key, version) read.
To serve the feed yourself (feature backend), verify_policy_feed_request(&PolicyFeedRequest { .. }) checks Atlas's
signed GET {endpoint_url}/policies request, and sign_policy_source_event(&PolicySourceEvent::Published { key, version }, secret)
produces the signed body and headers to POST to the source's webhook_url.
Referral attribution
With referral attribution on, Atlas reports every interactive sign-up to your referral platform before
user.created is sent. User gains referral (who referred them, or None), referral_code and referral_link.
use ;
let body = new
.with_enabled
.with_provider // the Atlas referral protocol; or a built-in vendor adapter
.with_endpoint_url
.with_signing_secret
.with_security
.clear_link_template; // sent as null
atlas.instance.update_referrals.await?;
let test = atlas.instance.test_referrals.await?; // ok, http_status, latency_ms, error
let failed = atlas.instance.list_referral_calls.await?;
atlas.instance.retry_referral_call.await?;
atlas.users.update.await?;
atlas.users.flag_referral.await?;
Enabling without what the provider needs is 422 REFERRALS_NOT_CONFIGURED; a code another user holds is
409 REFERRAL_CODE_TAKEN. A late answer from the platform arrives as the user.referral_attributed webhook
(EventType::UserReferralAttributed, data UserReferralAttributedEvent).
Two-way sync: a provider with the inbound capability sends referral changes made after sign-up back to Atlas.
The settings report inbound (url to give the platform, secret_set, endpoint_id, and last_event with
at, type, outcome). Store the platform's event secret with with_inbound_secret (write-only, 16-512
characters) and its subscription id with with_inbound_endpoint_id; clear_inbound_secret /
clear_inbound_endpoint_id send null.
Browser capture: browser_sources lists the referral programs whose script or cookie the browser reads
(clear_browser_sources goes back to the provider's default, reported by browser_sources_default), and
consent_provider picks the consent manager that decides (auto, one manager, or app).
Migrate from Better Auth
Import the sealed bundle the Better Auth exporter wrote (npx atlas-better-auth-export --public-key <kid:key>;
the key is better_auth_imports().get_public_key() → compact):
use ;
# async
No forced logout. Turn the session bridge on (better_auth_bridge().update(...) with enabled, ends_at,
cookie_prefix and an optional live_fallback), then put the bridge in front of your routes. A returning user's
Better Auth cookie is exchanged once, server to server with your secret key (forwarding the user's IP and user
agent), for Atlas session cookies:
use Arc;
use ;
use ;
#
Without Axum, call bridge.decide(cookie_header, client_ip, user_agent).await and render the BridgeDecision
(should_redirect(), cookies[i].to_set_cookie(), continuation_url(..)), or use
exchange_better_auth_session directly. Better Auth cookies are cleared only when the refusal is final, so a
closed bridge, a 429 or an outage retries on a later request.
Better Auth JWTs your API clients still hold can be accepted until a cutover date:
use Arc;
use ;
#
Verified claims carry sub (the Atlas id), external_id (the Better Auth id) and extra["legacy"]. EdDSA,
ES256, RS256 and PS256 are accepted; ES512 is not supported by this crate (its signature backend has no
P-521), so ES512 tokens are refused — let them expire, or verify them elsewhere during the window.
Platform API: Sign in with Atlas apps
Build the client with a platform key (psk_…) and use platform():
use ;
# async
Test and review accounts (0.26): platform().atlas_id_apps().provisioned_accounts() creates accounts
confined to one app (list, create, get, remove, rotate_password). It needs the scope
platform:atlas_id_apps:provision, or atlas_id_apps:<app id>:provision for a single app. The password is
returned once as password, or as sealed_password when the client has a secret_recipient; Debug never
prints it. platform().domains() (list, claim, check, remove) manages the verified domains that
test_mode and provisioned_verified_domains_only (on UpdateAtlasIdAppBody) rely on. New error codes:
TEST_ACCOUNT_RESTRICTED, PROVISIONED_ACCOUNT_LIMIT_REACHED, DOMAIN_NOT_VERIFIED.
platform().apps() provisions and manages the apps your platform owns, and
platform().upload_design_asset(...) uploads images for app designs.
Integrator platform (0.23)
Secret keys, whoami, partner links, the privacy executor client, identity
integrations, webhook health / replay / signature v2, status, notices, audit
exports and the operator device login live next to the rest of the Management
API (backend feature; client for the CLI login helpers).
use ;
use HttpMethod;
# async
- Credentials:
secret_keys()(create / list / get / update / rotate with overlap / revoke),keys(),partner_links()(+.outbound()),atlas_id_grants(),platform().whoami()/list_keys/create_key/audit_logs/ audit streams.is_secret_key,is_platform_key,is_webhook_secret,parse_key_prefix… accept theatlas_<env>_<kind>_…and legacy (sk_/pk_/psk_/whsec_) formats. - Webhooks:
webhook_endpoints().get/upsert_by_url/test_now/redeliver_window/replay/deliveries_with, the health fields onWebhookEndpoint, destinations (EventBridge, Pub/Sub, Cloudflare Queues),delivery()(health, egress IPs, alert contacts).Webhook::verify_urlverifies the URL-boundv2signature;canonical_webhook_event/webhook_event_spellingsmap the deprecated event names. - Privacy executor:
privacy()(lookup, requests, orchestrator),verify_privacy_callfor the signed calls andprivacy_request.*events (with thetraceparentAtlas sent). - Identity integrations:
instance().set_integration/integration_deliveries,sessions().get_integration_token,integrations().card/revoke_sessions, public instance metadata. - Instance:
unknown_fields_report,openapi_diff,integration_health,embed,preflight_with,status(),notices(),security_advisories(),sub_processors(),audit_exports(),entitlements(). - Lists:
users().list_query(&Query)(updated_after,order_by), cursorstarting_afteron org memberships, revoked keys and the delivery logs. - Errors:
AtlasApiError::is_insufficient_scope()(accepts the oldSCOPE_MISSING),required_scope(),is_step_up_required(),is_route_not_found()+did_you_mean(), and the new codes incodes::. - Back-channel logout:
AtlasBackend::handle_backchannel_logoutverifies the token, runs your callback and returns the200/400/503 + Retry-Afteranswer (BackchannelLogoutResponse).
CLI login (client feature)
use Arc;
use *;
use ;
# async
Root actions need a multi-factor sign-in within five minutes (otherwise
STEP_UP_REQUIRED, see OperatorError::is_step_up_required).
partner_link_token runs client_credentials for a partner service and
revoke_leaked_keys reports leaked credentials. With the backend feature,
backend_client_from_access_token builds a BackendClient from the token.
Sealed secrets (sealed-box feature)
use ;
use BackendClient;
# async
Built on the crypto_box crate (libsodium crypto_box_seal).
Custom transport (no reqwest)
Disable the default feature to compile with no HTTP dependency and supply your
own transport by implementing JwksSource (for session verification) and/or
HttpPost (for API-key verification):
= { = "0.32", = false }
use ;
use Arc;
#
For the management client, implement HttpTransport. Its send_full method
(which has a default) carries binary upload bodies and returns response
headers; override it if you need image uploads or Atlas-Unknown-Fields
reporting through your own transport.
Development
License
MIT.
actix-web and Rocket
Two more framework integrations, off by default, both over the same AtlasBackend verifier (local RS256 against the cached JWKS, issuer, expiry, azp allowlist). A missing or invalid credential is a 401; a verifier that was never registered fails closed with a 500.
= { = "0.32", = ["actix"] } # or "rocket"
// actix-web: register the verifier as app data, take AtlasClaims in the handler
use ;
use ;
async
// Rocket: manage an Arc<AtlasBackend>, use AtlasClaims as a request guard
use Arc;
use ;
The token is Authorization: Bearer <jwt>, else the __session cookie. Option<AtlasClaims> serves anonymous and signed-in callers without rejecting.