axiam-sdk (Rust)
Official Rust client SDK for AXIAM — Access eXtended Identity and Authorization Management.
Platform documentation: https://ilpanich.github.io/axiam/ — getting started, the authorization model, the OAuth2/OIDC surface, and the operations guides. This README covers the SDK; the site covers the server it talks to.
Package identity
- Crate:
axiam-sdk - Repository: github.com/ilpanich/axiam-rust-sdk
- Registry: crates.io/crates/axiam-sdk
- API docs: docs.rs/axiam-sdk — built automatically by docs.rs on each release
- License: Apache-2.0
- MSRV: Rust 1.89 (
rust-version = "1.89"inCargo.toml, enforced in CI) — see Supported Rust versions
Supported Rust versions
| Toolchain | Why this one | |
|---|---|---|
| Floor | 1.89 | rust-version in Cargo.toml. Exposed as supported_versions::MIN_RUST_VERSION. Edition 2024 sets the hard lower bound at 1.85. |
| Newest | stable |
Tracked, not pinned. Exposed as supported_versions::NEWEST_TESTED. |
The crate is built against the floor, and against current stable. The gating
matrix in sdk-ci-rust.yml runs the full suite on both (D-10). Style gates —
cargo fmt, clippy -D warnings — run on stable only, deliberately: clippy's lint
set grows with every release, so running it under the pinned MSRV compiler would turn
each new lint into a spurious MSRV-job failure. The MSRV job's job is to prove the
crate still compiles on 1.89.
Rust enforces the floor better than most ecosystems do, and there is genuinely
nothing to preflight there: rust-version is a hard constraint Cargo checks during
resolution, so a consumer on an older toolchain gets a message naming this crate and
the version it needs, rather than a compile error deep in someone else's source.
The upper end has no enforcement anywhere, because there is no "maximum Rust" to
declare. Code that compiles on the MSRV keeps compiling on newer toolchains almost
always — and "almost" is where new deny-by-default lints and tightened inference
live. Only a build on a current toolchain settles it, which is what the stable leg
is for.
The upper leg tracks stable rather than a pinned version on purpose. Pinning would
freeze the newest end at whatever was current the day it was written and quietly stop
testing anything after that, while still looking like a two-legged matrix.
tests/version_policy.rs asserts it stays stable, along with everything else here
— and additionally that the MSRV is high enough for the declared edition, since those
two are set independently in the same file and lowering one without the other
produces a manifest promising a toolchain the edition cannot compile on.
See examples/version_compatibility.rs.
Stability
axiam-sdk 1.0.0 was the first stable release; this is 1.1.2. Its public API and the wire contract
it speaks (CONTRACT.md, the REST, gRPC and AMQP surfaces) follow semantic versioning from 1.0.0: a
breaking change waits for 2.0.0, and security fixes ship in 1.1.x.
What a minor release may do. A contract record may add a member or widen a type with a
minor bump: a struct gains a public field, an enum a variant, a request member loses its narrower
type (1.1.0's request user_id went from Option<Uuid> to Option<String>). In Rust that can
break a struct literal that names every field, or code that depended on the narrower type, so
each such change is named under "Source-breaking changes" in the change log.
A removal — of a method, a field, a variant or a type — waits for 2.0.0.
Contract conformance
This SDK conforms to contract 1.66: CONTRACT.md §1–§13 and §12.7, §14, §15, §17, §19, §20,
§21, §22, §23, §24, §25, §26, §27, §28, §28.12, §29, §30, §31, §32, §33, §36 and §37, with §32.7 and
§33.2 signed (including §6.1 mTLS, the §10.1 minimum
local-verification set — including rule 9, sender-constrained tokens — and §13 webhook
signature verification). §12 is implemented in full at its 1.38 shape: all thirteen operations,
including the four public "Sign in with X" entry points, on the same host object
([AxiamClient]) as the nine that preceded them.
The MUST-level §16 (retry policy) and §18 (deterministic shutdown) are implemented and so
are not named — a MUST is not something an SDK opts into.
§27 is implemented in full, both halves: the 202-operation imperative surface and
the §27.6 declarative manifest with its §27.7 manifest! form. The contract asks an SDK
that ships only one half to say which; this one ships both. (The manifest has no kind for
the four namespaces contract 1.54–1.57 added, by the contract's design; network from contract
1.62 is a manifest namespace here — see below.)
Manifest pruning: not offered in any namespace (§27.10). plan never emits a Delete, so
§27.6.2 item 6 and §27.9's "with pruning on" assertion have nothing to bind here.
§12.7, §14, §15, §17, §19, §20, §22, §24, §25, §26, §27, §28.12, §29, §30, §31, §32, §32.7,
§33, §36 and §37 are named rather than folded into the range because they landed after this SDK already
claimed §1–§13: widening the range silently would turn a statement that was true when written
into a different claim without anyone editing it. The §21.3.1 amendment of contract 1.58 (the
seventh mtls_endpoint_aliases member, backchannel_authentication_endpoint) is decoded and
honoured on an mTLS CIBA call, and vector A is pinned as the vendored CONTRACT.md prints it.
"§33.2 signed" means all three algorithms — PS256, ES256 and EdDSA (contract 1.59, §34.2 P12.7).
Contract 1.66 (§34.10) adds no operation and changes no API here. A federated sign-in is bound
to the client that started it (§12.1 rule 12b): send the start and the completion of one sign-in
through the same AxiamClient — its §4 cookie jar carries the axiam_fed_bind cookie, and a
completion without it is a terminal 401. The optional reauthenticate start input (rule 12c) is
not exposed.
Contract 1.65 (§34.9, the platform's 1.2.0) adds native sign-in with a provider ID token (§37:
login_with_provider_id_token and native_nonce, see below) and the idp_hint input of
oidc_begin and oidc_par (§12.1, §26.2 rule 8); it regenerates the §27 layer (default_idp,
refresh_reuse_response, native_login; still 202 operations). A replayed refresh token now
ends the session server-side by default (§9): this SDK's single-flight oidc_refresh is what
keeps one process from causing it, and the same refresh token must never be refreshed from two
places. Server floor: federation-config admin calls (federation.create_config, get_config,
list_configs, update_config) of this 1.2-line SDK need an AXIAM server 1.2.0 or later:
FederationConfigResponse.native_login is required from 1.2.0, and a response from an older
server fails to decode.
Contract 1.64 (§34.8, released as 1.1.2) adds no operation. This SDK ports its one rule: the
device_login loop waits out a 429 rate_limit_exceeded on a poll (§14.2 rule 9) — Retry-After
as a minimum, capped at the expires_in deadline, counted as one interval, the interval not
raised — while a single device_poll still raises the OAuthProtocolError. The amended rules
(CONTRACT.md as of axiam 21beda0 and after) are carried too: the poll's status decides — a 5xx
is not terminal whatever its body (500 {"error":"server_error"} is the §2 NetworkError, retried
under §16 inside the poll), any 429 is the wait, and only the 400 slow_down raises the
interval. A refusal at plan names the member and the value (§27.6.2 item 4: this SDK keeps the
value).
Contract 1.63 (§34.7, released as 1.1.1) changes no operation. This SDK sends no axiam_* cookie
and no X-CSRF-Token to any /oauth2/* endpoint (§6.1 rule 11, §12.1 rule 3), refuses a reserved
tenants. / gdpr. audit action in AuditEventMessage::sign (and in check_action, §8), and
refuses at plan an open-enum profile value it cannot send (§27.6.2 item 4). It generates no DPoP
proofs, so §21.7.4's key-lifetime rule has nothing to bind here.
Contract 1.62 (§34.6, released as 1.1.0 together with 1.61 — the never-tagged 1.0.1 is folded in) adds one management namespace and tightens a few rules. This SDK carries all of it:
client.network()(§36, item l): the twelve operations —list_segments,create_segment,get_segment,replace_segment,delete_segment,list_profiles,create_profile,get_profile,replace_profile,delete_profile,get_policy,replace_policy— generated from the registry like the rest of §27. Every write names theversionit read and is issued once; a409carries areason_code, read withAxiamError::reason_code(). The decision routePOST /api/v1/network/decideis FreeRADIUS's, not an SDK's, and has no method.networkin a manifest (§27.6.2, items n, u, v, w): see "Declarative management" below.- The device grant authenticates its client (§14.1 rule 2, items m, t): a client configured
with a secret sends it as
client_secretin the form body atdevice_authorizeand at everydevice_poll, never asAuthorization: Basic; an mTLS client presents its certificate; a public client sends nothing. The poll sendsclient_id;401 invalid_clientis terminal. This SDK generates no DPoP proof and noprivate_key_jwtassertion. - A change-taking SSF form (§32.2, item e):
SsfStreamInput::from_stream_with(&stream, SsfStreamChanges { .. })sendsevents_requestedandexpected_updated_atas read and cutsevents_requestedto a loweredevents_allowed;update_streamdocuments the three meanings ofevents_requested(item h). - The request
user_idis a plain string (§27.11 rule 5, item i) — source-breaking: it isOption<String>onCreateCertificateRequestandSignCertificateCsrRequest, so a malformed value reaches the server and its400is what you see. The responseCertificate.user_idstaysOption<Uuid>. - Already held (items f, g): an assigned "none" never sends
null(Option<String>members are omitted whenNone), andexpected_updated_atis the response's own string, byte for byte. - Not SDK work for this SDK (items a – d, k, o – s): the CIBA list's rate limits, the CA
revocation row,
slow_down,CibaPendingList, the threat-model entries, the counts and the CRL number are server or contract text.
Contract 1.61 (§34.5) is additive and clarifying — no route, no operation, one optional member on each of three models — and this SDK carries it on its REST transport (it has no gRPC or AMQP message that holds these models):
Certificate.user_id(§27.11 rule 5):Option<Uuid>onCertificateandGeneratedCertificate; a UUID decodes,nulland an absent member both readNone("no account named"), never synthesised frommetadata. OnCreateCertificateRequestandSignCertificateCsrRequestaSomeis sent exactly as given andNoneleaves the key out (nevernull); the SDK does not judge it, the server answers400.SsfStreamInput.expected_updated_at(§32.2, §32.3 rule 4):Option<String>, sent exactly as the stream'supdated_atwas read and absent whenNone.SsfStreamInput::from(&SsfStream)sets it to the read'supdated_atand always carriesevents_requestedas read (Some(vec![])stays[]; omitting it would reset a receiver's narrowing to every allowed event), so an update built from a read is a409(is_conflict(), never retried) if the stream was written since — the receiver's pause or narrowing included. If you lowerevents_allowed, cutevents_requestedto it.CibaPendingList.total_pending,truncated(§33.3 rule 16): not modelled — the type belongs to the console'sGET /api/v1/ciba/requestsroute, which no registry operation returns and no SDK drives.
Contract 1.59 and 1.60 add no section an SDK claims (1.60's §35, certificate revocation
lists, is informative and has no SDK surface): §34 records the cross-SDK review of the
1.53 – 1.58 ports, its clarifications P1 – P12 and the answers of §34.4. This SDK follows them — SsfReceiver::poll records no
jti it does not return (P1), a replayed refusal is acknowledged (P2), a custom
ReplayStore answers Result<bool, _> and a store that cannot answer gives no verdict (P4, as rewritten in 1.60), ciba_await ends on a decisive answer or any failure after a
200 and survives a 5xx whatever its body (P8, P9), a §16 retry inside ciba_await never
waits past its deadline (P10), the SSF key cache expires within ten minutes and a failed key
fetch counts toward its once-a-minute limit (P6), and an RFC 7592 update sends no list its
read lacked (P12.4). The contract 1.60 additions are carried too: expected_updated_at on
ScimTargetInput (§31.3 rule 4), window_minutes on notification rules, the federation
configuration's allow_sha1_signatures and idp_metadata_signing_cert_pem and its
update_config null rule (§27.15), a refresh's scope read as the token's (§12.1), and the
four revocation and introspection discovery members (§21.5).
Contract 1.53 – 1.58 — what this SDK ships
| Section | Here |
|---|---|
| §28.12 RFC 7592 client configuration | read_client_registration, update_client_registration, delete_client_registration on AxiamClient; ClientRegistration |
| §29 SAML service providers | client.saml() — eleven generated operations, call-site notes, ParseSamlSpMetadata::from_url / from_xml |
| §30 directory | client.directory() — six generated operations; bind_secret Sensitive; explicit null on update |
| §31 outbound SCIM targets | client.scim_targets() — six generated operations; credential Sensitive |
| §32 SSF streams | client.ssf() — five generated operations; authorization_header Sensitive |
| §32.7 SSF receiver helper | axiam_sdk::ssf::SsfReceiver::{verify_set, poll} |
| §33 CIBA | ciba_initiate, ciba_poll, ciba_await, ciba_handle_ping on AxiamClient |
| §33.2 signed request | CibaRequestSigner (PS256, ES256, EdDSA; the caller's key and algorithm) |
Contract 1.51 — what this SDK ships, and what it declines
| Contract 1.51 item | Status here |
|---|---|
§1.1.1 validate_token / introspect_token (gRPC) |
Shipped: grpc::TokenGrpcClient. Every response field, cnf optional, status() / verify_possession() for §10.3 rules 1–4 |
| §5.2 rule 1 acting tenant (SHOULD) | Shipped: with_acting_tenant(Uuid) / acting_tenant(Uuid) / clear_acting_tenant(). REST-only; gRPC acts on the token's tenant |
§6.1 rules 6–10 authenticate_device() |
Shipped. Rule 7 is enforced client-side at runtime (AxiamError::Auth, zero wire calls), not in the type system — see below |
| §10.1 rule 9 in the documented guard | Shipped, as a fix: JwksVerifier::verify / AxiamUser refuse a bound token without evidence, and accept it with PeerCertificate or verify_with_proofs |
§27.6.1 resources[].metadata |
Shipped, whole-object equality |
§27.6.1 two-shape role binding, inherit |
Shipped on groups, users and service accounts |
§27.6.1 service_accounts, §27.5 rule 5 |
Shipped; the one-time client_secret is on Outcome::CreatedServiceAccount |
§27.13 Server type, subject_alt_names, inherit |
Shipped via the regenerated surface; CertificateType decodes openly |
§27.6 webhooks in the manifest |
Declined: the contract names it without specifying it, and no consumer has asked for it |
Why §6.1 rule 7 is a runtime check here. The contract says "where the type system
can express that, it does". Rust's could, but only by making AxiamClient a typestate.
AxiamClient<WithCertificate> would change the type of every client in every caller,
and would force every builder method to be forwarded for the sake of one operation. The
SDK uses the rule's other branch instead: the call fails with AxiamError::Auth before
any request, and a test pins that no request is made.
The manifest, in §27.10's terms. This SDK is in the full tier: resources (nested),
scopes, permissions, roles, role grants, groups, users, service accounts, resource
metadata, and group/user/service-account role bindings in both shapes. webhooks is not
implemented. The §27.7 #[derive(AxiamSpec)] form has never shipped here; manifest!
is the declarative form.
Retry policy (§16)
Read-only authorization checks — check_access, check_access_as, can, batch_check
— retry transient failures under the contract's normative table: 3 attempts (1 initial
- 2 retries), 200 ms base, 5 s cap, full jitter (uniform over
[0, backoff]), andRetry-Afterhonored as a floor.
Only failures that could plausibly succeed on a second attempt are retried — transport
errors, 408, 429, 5xx. A 401 or 403 is an answer, not a transport failure, and
is surfaced after exactly one attempt.
Nothing that changes server state is ever retried. login, verify_mfa, refresh,
logout, oidc_exchange, device_authorize, device_login, token_exchange and
oidc_revoke all make exactly one attempt, for two independent reasons: a transient
failure after the server committed is indistinguishable at the client from one before
it, and their credentials are single-use, so a retry replays a spent credential into a
hard invalid_grant.
// Turn it off if you own your own retry layer — you know your deadline, this SDK doesn't.
let client = builder
.base_url?
.tenant_slug
.retry_enabled
.build?;
There is deliberately no knob for the attempt cap, base delay or delay cap: §16.1 forbids raising them, and eleven SDKs agreeing on one table is the point of the section.
Deterministic shutdown (§18)
AxiamClient::close() releases the client's local resources. It is idempotent, and any
call afterwards fails with an AxiamError::Network naming the cause rather than silently
reconnecting.
close() does not log out. It never reaches the network. The server-side session
deliberately outlives the client object — that is what lets a process restart and resume —
so a close() that logged out would silently end every user's session on each deploy.
Call logout() first if ending the session is what you want.
client.close.await; // local teardown only
assert!;
Telemetry hooks (§19)
Wire metrics without this crate depending on any metrics library:
use TelemetryEvent;
let client = builder
.base_url?
.tenant_slug
.telemetry_hook
.build?;
Three properties worth knowing:
- A hook that panics cannot fail the operation that fired it. Telemetry is not permitted to fail an authorization check.
- No event payload can carry a token.
TelemetryEventhas a closed field set with no escape hatch — this surface exists to be shipped to a metrics backend, which is the last place a bearer token should land. - Path templates, not URLs.
/api/v1/authz/check, never a path with ids substituted in, so a metric label cannot become a cardinality bomb.
One RequestStart/RequestEnd pair is emitted per attempt, not per logical call, so
you can count real wire calls. The Retry event exists because a retried-then-succeeded
operation is otherwise invisible — a slow success with no signal that the server is
failing.
Decision memo (§17) — opt-in, off by default
An optional TTL-bounded cache for check_access results. Disabled by default, because
§11.2 rule 6's ban on caching authorization decisions is still the default behaviour.
let client = builder
.base_url?
.tenant_slug
.decision_memo_ttl // 0 = off, which is the default
.build?;
What you are accepting. The staleness bound is the TTL, in both directions: a grant revoked on the server can still read as allowed for up to the TTL, and a grant just added can still read as denied for up to the TTL.
Reads-your-own-writes is not guaranteed. An admin UI that grants a role and immediately re-checks is the case that breaks, and it breaks silently. If that is your workload, leave this off.
The TTL is clamped to 5 s rather than rejected, so asking for an hour gets you 5 s. Allows
and denies are memoized identically — asymmetric caching would leak which outcome occurred
through latency. Failures are never memoized: caching a transport error as a deny would
turn a blip into a TTL-long outage. The memo is cleared on login, verify_mfa,
refresh and logout, since entries are keyed by subject rather than by session. And the
§11 route guard's fail-closed path never consults it, so an outage cannot be papered over
with a stale allow.
§10.1 minimum local-verification set
JwksVerifier::verify is the documented guard entry point and applies every §10.1
rule on every inbound token: EdDSA alg pinned before the JWKS is consulted, a REQUIRED
numeric exp, nbf honoured when present, tenant_id asserted against the configured
tenant, iss/aud checked when configured, all under a named 60-second
CLOCK_SKEW_LEEWAY_SECS. The §10 AxiamUser extractor and the §11 require_auth /
require_access / require_role macros (which inject that extractor) all route through
it — there is no second verification path.
Because the /oauth2/jwks trust anchor is organization-wide, a verifier used as a
route guard MUST be told which tenant it is guarding:
let verifier = new?
.expect_tenant_id // §10.1 rule 4 — required, fails closed without it
.expect_audience; // §10.1 rule 6 — optional, recommended
JwksVerifier::verify_signature_only_unchecked is the §10.1 raw signature-only
primitive, for integrators implementing their own policy. It checks the signature and
nothing else — never use it to guard a route.
Rule 9, sender-constrained tokens (fixed in contract 1.51). verify(token) applies
rule 9 with no evidence at all, so it refuses any token carrying cnf. That includes
every §6.1 device token, which is bound to its certificate. Until 1.51 it accepted those
as bearer tokens. To accept bound tokens, give the verifier the evidence your transport
holds:
// The certificate the TLS layer verified for this connection — never a header.
let claims = verifier
.verify_with_proofs
.await?;
AxiamUser does this by itself when the server records the peer certificate as
middleware::PeerCertificate in HttpServer::on_connect. A deployment where the
application never sees a client certificate refuses bound tokens, as detail 3 requires.
§10.4 the session-revocation feed (contract 1.44, opt-in)
§10.2 records the gap this narrows: local verification proves a token was issued and has not expired, never that the session behind it still exists. A logout or a role removal does not reach a token already in a caller's hands until it expires — up to fifteen minutes. The documented answer has been "route the decision through gRPC introspection instead", which is correct and costs a round trip per request.
A deployment can publish GET /oauth2/revocations: the hashed ids of sessions revoked
within the last access-token lifetime. Attach a poller and the guard rejects a revoked
session within one poll interval instead, for one cacheable fetch per interval:
use RevocationFeed;
let verifier = new?
.expect_tenant_id
.with_revocation_feed;
It is not a control, and every property follows from that. It is off unless you
attach one. It is never consulted over the network on the request path — verify reads
a cached set and, at most, starts a refresh whose result the next caller sees. And it
never fails closed: an unreachable feed, a non-200, a body that does not parse, or
an alg this build does not know all behave exactly as no feed at all — not as an empty
list, which would assert that nothing has been revoked and is a guard silently honouring
no revocations while appearing to honour them. Every §10.1 rule runs first and still
decides; the feed can only ever turn an accept into a reject.
A token with no sid — a client-credentials token, an RPT, a token exchange — is never
matched against it. There is no session behind one, and hashing jti instead would match
nothing while looking like it worked.
The poll interval defaults to 30 seconds and is clamped to a 15-second floor
(RevocationFeed::with_poll_interval); the cached set is bounded, and a document larger
than the bound is treated as unusable rather than truncated — a truncated set is a guard
that admits some revoked sessions and reports none.
See CONTRACT.md for the full cross-language behavioral contract. It is shared
verbatim across all seven AXIAM SDKs; the copy in this repository is the authority for this
crate's behaviour.
Features
axiam-sdk's functionality is split into Cargo features so a consumer only pulls in the
dependencies for the transports/integrations it actually uses:
| Feature | Default | Enables |
|---|---|---|
rest |
on | AxiamClient REST transport: login/verify_mfa/refresh/logout, the §6.1 mTLS device login authenticate_device, the §5.2 acting tenant (with_acting_tenant / acting_tenant / clear_acting_tenant), check_access/can/batch_check, cookie-jar session management, local JWKS/EdDSA verification, the CONTRACT.md §12 OIDC/SSO relying-party helpers (oidc_discover, oidc_begin, oidc_exchange, oidc_refresh, login_client_credentials, introspect, revoke, sso_start, sso_complete, sso_providers, sso_start_oauth2, sso_complete_oauth2, sso_complete_handoff), the §12.7 logout helpers (logout_url, verify_logout_token), the §14 device grant (device_authorize, device_poll, device_login) and the §15 token_exchange |
grpc |
on | AuthzGrpcClient gRPC transport: check_access/batch_check; UserInfoGrpcClient gRPC get_user_info (OIDC identity read, CONTRACT §1.1); TokenGrpcClient gRPC validate_token/introspect_token (CONTRACT §1.1.1, reading cnf per §10.3) — all over a shared lazily-connected tonic::Channel, with the shared single-flight refresh guard driven on UNAUTHENTICATED |
amqp |
on | consume(amqp_url, queue, signing_key, handler) closure-handler AMQP consumer with mandatory pre-handler HMAC-SHA256 verification (CONTRACT.md §8), and reactor_serve(config, handler) — the CONTRACT.md §22 reactor runtime (hook events, signed in both directions) |
observability |
off | Enables tracing instrumentation crate-wide beyond the mandatory AMQP security-event logging (which is always emitted regardless of this flag) |
| — | — | webhook::verify_webhook (CONTRACT.md §13) has no feature of its own: it is compiled whenever rest or amqp is on, since both already vendor its hmac/sha2/hex/subtle inputs. With the default feature set it is always available |
actix |
off | The AxiamUser Actix-Web FromRequest extractor (CONTRACT.md §10 route guard). Implies rest (shares the same JwksVerifier) |
macros |
off | The #[require_access] / #[require_auth] / #[require_role] declarative authorization attribute macros (CONTRACT.md §11), plus the programmatic middleware::RequireAccess guard. Implies actix |
opaque |
on | CONTRACT.md §23 OPAQUE (RFC 9807): login_opaque, opaque_enrollment, opaque_available. Its own feature because it is the only thing in this crate that pulls an elliptic-curve stack and an Argon2/scrypt implementation — a build that will never call login_opaque should not carry them. Implies rest: OPAQUE is a login path, not a transport |
reactor-macros |
off | The #[reactor_handler("...")] attribute macro (CONTRACT.md §22.14), which binds an async fn to one hook event and validates the name against the §22.5 registry at compile time. Implies amqp, and deliberately not macros: a reactor is an AMQP daemon with no HTTP surface, so it should not pull actix-web in to get an attribute macro |
To build a REST-only client (no gRPC, no AMQP), disable the default feature set and opt back
into just rest:
[]
= { = "1.1.2", = false, = ["rest"] }
Usage
[]
= "1.1.2"
Each capability below has a complete, runnable example under examples/ — they
are illustrative/compilable (reading connection details from environment variables) and do not
require a live AXIAM server to cargo build --examples --all-features.
Login + MFA (rest)
Construct a client with a non-optional tenant identifier (CONTRACT.md §5 — there is no default tenant) plus the organization identifier login/refresh require (CONTRACT.md §5.1 — a tenant slug is only unique within an organization), then complete the two-phase login/MFA flow:
use AxiamClient;
# async
REST authorization checks (rest)
# use AxiamClient;
# async
See examples/rest_check_access.rs.
Acting on another tenant (rest, CONTRACT.md §5.2 rule 1)
An organization-level principal (one whose record lives in the organization's
reserved tenant) acts on another tenant of the organization by sending
X-Axiam-Tenant. Build a handle for that tenant; the original keeps acting on its own:
let client = builder
.base_url?
.tenant_slug
.org_slug
.build?;
client.login.await?;
let prod = client.acting_tenant?; // refused client-side unless organization_level
prod.groups.list.await?; // sends X-Axiam-Tenant: <prod_tenant_id>
client.groups.list.await?; // sends none
The header is sent only when set. It changes neither X-Tenant-ID nor a {tenant_id} path
segment, and it does not reach gRPC, whose calls act on the token's tenant.
mTLS device login (rest, CONTRACT.md §6.1 rules 6–10)
A device holding a certificate that is bound to a service account logs in with the certificate alone:
let device = builder
.base_url?
.tenant_id
.with_client_cert?
.build?;
let token = device.authenticate_device.await?; // POST /api/v1/auth/device, no body
device.can.await?;
The token is a service-account token bound to the certificate. It works only over
connections that present that certificate, which this client does on REST and gRPC alike.
It has no refresh: call authenticate_device() again before expires_in runs out. See
examples/device_mtls_login.rs. Not to be confused with
the RFC 8628 device grant in examples/device_login.rs.
gRPC authorization checks (grpc)
use ;
#
See examples/grpc_check_access.rs for the full
AuthzGrpcClient wiring, including the single-flight refresh guard (§9).
OIDC / SSO relying-party helpers (rest)
CONTRACT.md §12 adds thirteen operations for "Login with AXIAM" (authorization-code + PKCE
against AXIAM's own OIDC provider), service-account client_credentials login, token
introspection/revocation, the upstream-IdP federation pair, and — as of contract 1.38 — the
four public "Sign in with X" entry points. All are methods directly on [AxiamClient]
(§12.2's host rule: this SDK has no packaging constraint that would justify a second host),
configured with an OIDC client_id/client_secret on the same builder used for everything
else:
use AxiamClient;
use OidcBeginParams;
# async
The thirteen operations (CONTRACT.md §12.2 Rust naming):
| Operation | What it does |
|---|---|
oidc_discover |
GET /.well-known/openid-configuration, cached per origin (≥5 min TTL) with single-flight de-duplication |
oidc_begin |
Pure, local PKCE (S256-only) + state/nonce generation and authorization-URL construction — no network I/O |
oidc_exchange |
grant_type=authorization_code — exchanges a code for an [oidc::OidcTokenSet], validating any id_token against the full §12.4 checklist before returning it |
oidc_refresh |
grant_type=refresh_token, under a §9-conformant single-flight guard dedicated to the OAuth2 token namespace (§9 rule 5): a burst of N concurrent callers makes exactly one wire call and every caller receives that call's outcome (§9 rule 2). Distinct from and never merged with the §1 refresh() cookie-session path |
login_client_credentials |
grant_type=client_credentials — service-account machine-to-machine login |
introspect |
POST /oauth2/introspect (RFC 7662) — requires a confidential client |
revoke |
POST /oauth2/revoke (RFC 7009) — idempotent; requires a confidential client |
sso_start |
POST /api/v1/auth/federation/oidc/start — step 1 of upstream-IdP SSO |
sso_complete |
POST /api/v1/auth/federation/oidc/callback — step 2; the session arrives via Set-Cookie through the same §4 cookie jar every other REST call uses, and the same post-login sync login() runs seeds the token manager and resolves tenant_id/org_id, so refresh()/logout() work straight afterwards |
sso_providers |
GET /api/v1/auth/federation/providers — which "Sign in with X" buttons to render. The identifiers travel as query parameters, not a body. An empty list is a success, for an unknown organization, a known one with nothing configured, and a request naming no workspace at all alike (§12.1 note 9): the endpoint is shaped so it cannot enumerate organization slugs, and an SDK that told the three apart would rebuild that oracle |
sso_start_oauth2 |
POST /api/v1/auth/federation/oauth2/start — step 1 through a plain-OAuth2 upstream (GitHub, Facebook, generic_oauth2). PKCE is mandatory here and is generated and held server-side (§12.1 note 11), so this SDK computes no verifier and sends no challenge |
sso_complete_oauth2 |
POST /api/v1/auth/federation/oauth2/callback — step 2 of the OAuth2 variant; same Set-Cookie session and same post-login sync as sso_complete |
sso_complete_handoff |
POST /api/v1/auth/federation/handoff — redeems the single-use axiam_handoff code the SAML and Apple flows deliver on the SPA's callback URL. Valid 60 s, redeemable once; a 401 is terminal and is never retried (§12.1 note 12) — unknown, expired and already-redeemed all answer the same 401, deliberately |
Which start operation to call is decided by protocol, not by provider_kind (§12.1 note
10): OidcConnect → sso_start, OAuth2 → sso_start_oauth2, Saml → the SAML login
endpoint, which is not a §12 vocabulary operation. The server refuses a mismatch with 400.
[oidc::FederationProvider] is modelled faithfully, button_icon (a data: URL, None for
most providers), has_bundled_mark and inherited included. Inheritance from the organization
is resolved server-side (§12.1 note 13): pass back the workspace and the config id
sso_providers handed you and compute nothing locally.
A 400 from a start call is a configuration refusal (§12.1 rule 12a). On the SAML and Apple
flows the identity provider never validates the SPA redirect_uri, so the server confines it to
its own issuer origin plus AXIAM__AUTH__SSO_SPA_ORIGINS. That refusal surfaces as
AxiamError::Network — §2's 400 row, the taxonomy's configuration/programming-error member,
as distinct from the AxiamError::Auth a 401 gets — and is not retried. Never build a
redirect_uri out of anything the identity provider supplied.
The caller owns the login state (§12.3 rule 1). oidc_begin returns state, nonce and
code_verifier; this SDK stores none of them. Persist all three yourself (your own HTTP session,
a database row, …) between the login redirect and the callback, or use
[axiam_sdk::oidc::MemoryOidcStateStore] — a ready single-process, single-use, 10-minute-TTL
reference implementation of [axiam_sdk::oidc::OidcStateStore] — and pass nonce +
code_verifier back into oidc_exchange when the code arrives. See
examples/oidc_login.rs for the full two-step flow.
The five §12.5 secret fields — access_token, refresh_token, id_token, client_secret,
code_verifier — are all Sensitive<String>; state and nonce are not
secrets and are plain Strings. ID-token validation is EdDSA-only (rejecting alg: none and
every other algorithm outright) and all-or-nothing: on any failure the whole token set —
including the access and refresh tokens from the same response — is discarded and an AuthError
carrying one of invalid_alg/unknown_kid/invalid_signature/invalid_issuer/
invalid_audience/token_expired/nonce_mismatch is raised.
AMQP consumer (amqp)
use ;
use Sensitive;
# async
# async
See examples/amqp_consumer.rs. Every delivery's HMAC-SHA256
signature (CONTRACT.md §8) is verified before the handler runs; failures are nacked without
requeue.
A broker confirm is not evidence that AXIAM saw a message (CONTRACT.md §8, minimal
profile). A publisher confirm — including the one reactor_serve waits for on a reply — means
only that the broker accepted the message; it never means AXIAM decided a request or recorded
an event. A server running in the minimal profile (AXIAM__AMQP__ENABLED=false) reads no AMQP
queue at all: it consumes neither axiam.authz.request nor axiam.audit.events, whatever a
broker holds. Against one, use REST or gRPC (GET /health reports profile: minimal and lists
amqp_authz and amqp_audit_ingestion under unavailable).
Transport security (§8b)
consume, consume_with_tls and reactor_serve all require amqps:// and check it
before opening a socket. HMAC signing (§8) gives authenticity and replay protection
across broker hops; TLS gives confidentiality. Both are required and neither
substitutes for the other — a signed AuthzRequest still names its subject, resource
and action in cleartext on an unencrypted wire.
AmqpTlsConfig field |
Meaning |
|---|---|
ca_cert_pem |
PEM bundle for a privately issued broker certificate. Omit for a publicly issued one (platform roots verify it). |
client_cert_pem + client_key_pem |
Mutual TLS toward the broker. All-or-nothing: half an identity is refused before dialling. |
There is deliberately no verification-skip option, under any name (§8b rule 4).
Note there is no loopback exception here. The http://localhost carve-out that
§6 grants the REST and gRPC base URLs does not extend to the broker URL: §8b rules 1
and 5 are unconditional, and the AXIAM server itself is TLS-only with no plaintext
listener for such an exception to reach.
Reactors — AMQP extension actors (amqp, CONTRACT.md §22)
A reactor is an external process that subscribes to named hook events on the AMQP bus and answers back — allow, deny, or a field-allow-listed mutation — inside a timeout the server declared. It is AXIAM's answer to Zitadel Actions and Keycloak SPIs, and the difference is the whole design: those load third-party code into the authorization server, and this keeps it outside, reachable only through a signed reply schema the server validates before it believes a word of it.
use Sensitive;
use ;
# async
Binding handlers per event (§22.14)
The match above is the shape every multi-event reactor grows, and its _ => arm —
ReactorDecision::allow() — answers on behalf of code that never ran. That is the defect
§22.10 rule 2 forbids the runtime from committing, relocated into your file where the
rule does not reach it: an operator who set fail_closed on the registration has it
defeated there.
ReactorRouter is §22.14's declarative form, in the spirit of the §11 declarative
authorization helpers:
use ;
# use ReactorConfig;
# async
With the reactor-macros feature, #[reactor_handler] moves the event name next to the
function it belongs to — and checks it at compile time:
use reactor_handler;
async
let handler = new..build?;
#[reactor_handler("token.pre_isue")] does not compile. The function itself is emitted
unchanged, so it stays directly callable and directly unit-testable; the macro adds only a
marker type in the type namespace carrying the validated event name.
- A misspelled event is refused when you bind it — the router accepts only §22.5 registry names, which is also how it refuses the three hot-path operations §22.7 excludes: they are in no registry row. The diagnostic names the registry, never the exclusions.
- An unbound event abstains — no reply, and the registration's
failure_policydecides (§22.8), exactly as it decides a timeout. Never a synthesizedallow. - A duplicate binding is an error rather than a silent overwrite, and
router.events()feedsdefault_failure_policy_forso you can see what an unreachable reactor costs before you go live.
It is pure sugar: build() produces exactly the handler reactor_serve already takes. It
opens nothing, verifies nothing, signs nothing, does not filter a patch, and a handler's
own panic reaches the runtime unchanged so nothing is published.
See examples/reactor/ for a complete three-hook reactor with
graceful shutdown and a telemetry hook.
The five hookable events, and their allow-lists
| Event | Mutable | Complete allow-list | Default failure policy |
|---|---|---|---|
token.pre_issue |
yes | the ext. namespace only |
fail_open |
login.post_auth |
no | — (veto, or require_mfa) |
fail_closed |
user.pre_create |
yes | username, email, metadata. |
fail_closed |
user.pre_update |
yes | username, email, metadata. |
fail_closed |
grant.pre_assign |
no | — (veto only) | fail_closed |
An entry ending in . is a namespace prefix and needs at least one character after the
dot: ext. admits ext.department and ext.a.b.c, and refuses ext. itself, ext,
extra, external_id and evil.ext.department. So a reactor can never reach sub,
aud, exp, scope or any other standard claim — a correctly signed reply setting
sub is refused exactly as a forged one is.
Registrations that name no failure_policy get the strictest default among their
events, in either array order — default_failure_policy_for([...]) computes it, and
"take the first event's default" is specifically what §22.8 forbids, because it lets the
order of a JSON array decide whether an unreachable fraud check passes.
authz.check is not hookable, and this SDK does not pretend otherwise
authz.check, authz.check_batch and token.introspect are absent from EVENT_REGISTRY,
from the events constants and from every example here (§22.7, a normative MUST NOT). A
reactor round-trip is milliseconds; the check path's budget is microseconds. An application
that needs external input on an authorization decision writes a deny grant, which the
engine evaluates in the hot path at hot-path cost — and there is deliberately no
client-side interceptor in this SDK offering itself as the reactor equivalent.
What the runtime guarantees
- Both directions are signed. The server signs the event with the tenant's HKDF-derived
AMQP subkey; the reactor signs its reply with the same key. An unsigned or stale reply is
not a weak reply — the server discards it as though the reactor had never answered. Every
event is verified (
key_version ≥ 2, MAC, ±300 s freshness, nonce seen-set) before your handler is called. - One canonicalization quirk, and it is the whole difference. A reactor body signs
hmac_signatureasnull, where §8's own two message types omit it. Getting this wrong produces a MAC that never verifies and no other symptom. It is pinned by server-generated vectors rather than by memory — seetestdata/reactor_v2_reference_vectors.jsonandtests/reactor_vectors_test.rs. - It declares no topology. No
queue_declare, noexchange_declare, noqueue_bind— the server owns all three, and the transport seam this runtime is written against does not even offer them. A reactor that can bind is a reactor that can bind itself to*.token.pre_issueand read another tenant's issuance events. - It fails closed on its own errors. A handler that panics, a body that will not decode,
a window that has already closed: each publishes nothing, so the registration's
failure_policydecides. Synthesizing anallowwould override the operator'sfail_closedsetting from inside the library.ReactorDecision::abstain()is the explicit form of the same thing. - It does not filter your patch. One forbidden key rejects the whole patch server-side;
pruning it here would leave you believing a field was set when it was dropped. Check
yourself with
ReactorEventSpec::patch_field_allowedif you want to know before you send. - It honours
timeout_ms. The handler runs inside the window the server declared, and a reply whose window has closed is abandoned rather than published late. - Shutdown drains (§18).
ReactorShutdown::trigger()stops the runtime taking new deliveries; the event in flight finishes — handler, signature, publish — first.
Registering a reactor (§22.9)
Registration is a REST admin call, not part of this runtime:
The response's id is what reactor_id(..) takes, and the server declares the queue.
timeout_ms defaults to 500 and is refused outside 1…5000; the chain's wall-clock
ceiling is 5000 ms and the per-tenant in-flight cap is 64. This SDK exposes those as
constants (DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_IN_FLIGHT) but ships no
typed client for the CRUD endpoints — call them through AxiamClient's HTTP surface, and
let the server validate; §22.9 explicitly warns against re-deriving PUT merge semantics or
the failure_policy re-derivation client-side.
Logging
The payload, patch, reason and decision are tenant business data — readable by
design, since a handler that cannot inspect the event cannot decide anything, but this
runtime never logs them at info level and yours should not either (§22.12). The signing key
is Sensitive<Vec<u8>>, is never logged at any level, and never appears in a reconnect
diagnostic. nonce, correlation_id and hmac_signature are not secrets and may be logged
for correlation.
Actix-Web route guard (actix)
use AxiamUser;
async
See examples/actix_route_guard.rs.
A certificate-bound token (every §6.1 device token) is accepted only when the server has
recorded the connection's verified client certificate as middleware::PeerCertificate in
HttpServer::on_connect and the token names it. With no certificate it is refused
(CONTRACT.md §10.1 rule 9).
Declarative authorization helpers (macros)
The macros feature adds the CONTRACT.md §11 declarative authorization
helpers — attribute macros that place a per-endpoint AXIAM permission check
directly on an Actix-Web handler, layered on top of the §10 AxiamUser
extractor. They run strictly after authentication and issue the check for
the request's authenticated user (subject_id = user.user_id), so the
app's own (usually service-account) AxiamClient session is never mistaken for
the end user.
Register a web::Data<AxiamClient> (used to issue the check) and a
web::Data<JwksVerifier> (used by the extractor) as app data, then annotate
handlers:
use ;
use AxiamUser;
// Require a `read` check on the `{id}` path resource. The handler may still
// take its own `AxiamUser` to use the identity in the body.
async
// Require an authenticated identity (no resource check).
async
// Local, no-round-trip role check (not a substitute for require_access).
async
#[require_access] also accepts resource_id = "<uuid>" (a static singleton
resource), resolver = path::to::fn (a
fn(&HttpRequest) -> Result<Uuid, AuthzGuardError> for body/header/composite
lookups), and an optional scope = "…" passed through verbatim. Errors map to
the standardized { "error", "message" } JSON body: 401 authentication_failed
(unauthenticated), 403 authorization_denied (denied), 400 invalid_request
(unresolvable resource id), and 503 authz_unavailable (transport failure —
fail closed, never allow on error). No decision is cached.
For handlers that don't fit the attribute shape, the same logic is available
programmatically via middleware::RequireAccess:
use RequireAccess;
new
.scope
.check
.await?;
See examples/actix_route_guard.rs.
Device authorization grant (rest)
CONTRACT.md §14 (RFC 8628) — signing in a device that cannot show a browser: a TV, a CLI, a headless commissioning tool.
let tokens = client
.device_login
.await?;
device_authorize and device_poll are also public, for an application that wants to
drive its own loop (to render a countdown, say). The polling rules are where
implementations go wrong, so they are worth stating:
slow_downraises the interval permanently. An SDK that backs off for one round and returns to the original interval will be told to slow down again, forever.access_deniedandexpired_tokenstay distinct. A human said no, versus nobody answered — the only information the device can act on.- Polling stops at
expires_in, even if the server has not yet saidexpired_token. - A
5xxmid-poll is not terminal. A server restart must not lose a grant the user has already approved.
The client authenticates (§14.1 rule 2, contract 1.62). A client built with
.oidc_client_secret(..) sends it as client_secret in the form body at device_authorize
and at every poll — never as Authorization: Basic, whether the client is registered
client_secret_post or client_secret_basic — and a client built with .with_client_cert(..)
presents its certificate and uses the mtls_endpoint_aliases entries. A public client (the
usual device) sends client_id and nothing else, and is not refused. The poll names its client
on every request. A failed client authentication is 401 invalid_client: an OAuthProtocolError,
terminal, never retried and never through the refresh guard. This SDK produces no DPoP proof and
no private_key_jwt assertion, so a client registered for either cannot be driven by it.
device_code is Sensitive; user_code deliberately is not — it exists to be read
aloud, and wrapping it would defeat the one thing it is for.
Per §14.3 rule 4, device_login returns the token set rather than adopting it, which
matches this SDK's login_client_credentials posture. See
examples/device_login.rs.
Token exchange (rest)
CONTRACT.md §15 (RFC 8693) — a service holding a user's token exchanging it for a narrower one before calling the next service.
let exchanged = client
.token_exchange
.await?;
Most of what this method does is refuse to be helpful, and each refusal is deliberate:
- No default
actor_token. Omitting it asks for impersonation; the SDK will not quietly substitute the client's own session token and turn that into a delegation. - The actor token is the exchanging client's own (§15.2 rule 9). Pass an
actor_tokenthe same client was issued — usually its ownclient_credentialstoken, fromlogin_client_credentials— and the issued token'sact.subis that client'sclient_id. An actor token issued to another client, a console sign-in or a service account is answered400 invalid_request(actor_token was not issued to the exchanging client), which the SDK surfaces unchanged and neither retries nor rewrites into an impersonation. - No auto-narrowing after
invalid_scope. The server refuses rather than silently narrowing precisely so the caller finds out here. - No refresh token, ever —
ExchangedTokenhas no such field, so there is nothing to synthesise. Re-run the exchange. - No adoption. The issued token is handed onward in one call; adopting it would
silently re-privilege every later call this client makes. A MUST NOT, where
login_client_credentialsadoption is a MAY.
See examples/token_exchange.rs.
External-IdP subject tokens (CONTRACT.md §15.7)
The same method exchanges a token minted by a trusted external IdP — a partner's Entra, Okta or Keycloak — for an AXIAM token scoped to what the resolved AXIAM user may actually do. There is no separate operation:
let exchanged = client
.token_exchange
.await?;
subject_token_typeis yours to state, and is required (§15.1). The SDK never decodes the subject token to pick it, and never overrides what you named. There is deliberately noOption: a field that can hold "no answer" forces the SDK to have one ready, and any answer it picks is the guess §15.7 forbids.TokenExchangeParams::newtakes it alongside the subject token.- No actor token. Delegation across a trust boundary is unsupported in v1;
sending one is
invalid_request, which the SDK will not work around by dropping it and re-sending. - One refusal is distinguishable.
invalid_grantwhose description isthe subject token's issuer is not configured for token exchangemeans fix the AXIAM trust configuration. Every otherinvalid_grantmeans fix your token, and is deliberately generic. - Forward the result as-is. It carries an
ext_exchangeclaim naming the partner issuer; never strip it, and never read it as an authorization input. It also cannot be exchanged again — exchanges do not compose.
The operator guide is docs/api/federated-token-exchange.md.
Logout — RP-initiated and back-channel (rest)
CONTRACT.md §12.7. logout_url builds the redirect (pure local computation);
verify_logout_token validates a token the OP pushed to your back-channel endpoint.
let url = client.logout_url?;
// …and at your registered backchannel_logout_uri:
let verified = client.verify_logout_token.await?;
if let Some = verified.sid
The verifier is where the security weight sits — the input arrives unsolicited and
instructs you to terminate a session. It checks the signature, iss, aud, that
events carries the back-channel-logout key (the only thing separating a logout token
from an ID token), that nonce is absent (its presence is how an ID token gets
replayed as one), that something is named, and freshness.
It returns sid/sub/jti rather than a bare boolean: you have to know which session
to end. Dedup on jti yourself — delivery is at-least-once, so a valid token
legitimately arrives twice; the SDK has no durable store and an in-memory guard would
silently drop a real second logout after a restart.
See examples/logout.rs.
UMA 2.0 — Protection API and ticket grant (rest, actix)
The resource-server side of User-Managed Access: register what you guard, ask the authorization server what a caller would need, and redeem the resulting ticket.
The two runnable halves are examples/uma_resource_server.rs
and examples/uma_client.rs — run the first, then the second
against it.
Guarding a route so a denial is actionable (needs actix):
# use AxiamClient;
# use ;
# use Uuid;
# async #
Without with_uma_challenge this is an ordinary §11 check and a denial is a bare 403. With
it, the guard mints a permission ticket for the action it just refused and returns
WWW-Authenticate: UMA realm=…, as_uri=…, ticket=… alongside the 403 — so a UMA-aware
client knows where to obtain authority instead of only being told no. The body is unchanged,
so a client that does not speak UMA sees exactly the 403 it saw before.
It is opt-in, and that is a design decision rather than an oversight. Emitting a challenge means minting a credential: a wire call to the Protection API and a live ticket, produced on a path the caller did not explicitly request. A guard that did that on every denial by default would turn each unauthorized request into a Protection API call — a denial-of-service amplifier pointed at your own authorization server.
Failure is not escalation. If minting fails — expired PAT, Protection API down, a scope the resource never declared — the denial still surfaces as a plain 403 with no challenge. A caller who was going to be refused is refused either way; letting an outage turn a deny into a 500 would give it a second consequence, and letting it turn into an allow would be a security bug.
Consuming the challenge, client side:
# use Sensitive;
# use AxiamClient;
use uma_parse_challenge;
# async #
The rest of the surface — uma_register_resource, the other four rreg operations,
uma_request_ticket, uma_exchange_ticket — plus the rules they enforce (a ticket is never
retried, the RPT is never adopted, an update replaces the scope list rather than merging it)
is documented on the uma module.
MCP resource-server helpers (actix, CONTRACT.md §28)
The resource-server half of the Model Context Protocol authorization handshake: publish the
RFC 9728 document that tells an MCP client which authorization server guards this resource,
and put the RFC 6750 WWW-Authenticate challenge on the 401 that starts its discovery.
AXIAM is the authorization server and implements none of this. Your MCP server is the
resource server, and this is its side. Nothing here talks to AXIAM, performs any network I/O,
or touches the SDK client's own session — all three operations are pure local computation,
like oidc_begin and uma_parse_challenge. The client half — parsing a challenge, fetching
a document, deciding whether to trust the authorization server it names — is deliberately not
in the SDK: a helper that read a 401 and acted on it would send a credential to whatever host
the 401 asked it to.
It is opt-in and off by default. With resource_metadata_url unset, every guard behaves
byte-for-byte as it did before §28 existed: no header on any response, no status changed, no
body changed.
The whole integration:
use ;
use ;
use JwksVerifier;
# async
A request with no credential now gets what it needs to go and get one:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
Content-Type: application/json
{"error":"authentication_failed","message":"..."}
and the document it points at answers without a credential:
The path is derived from the resource, not chosen. RFC 9728 §3.1 inserts
/.well-known/oauth-protected-resource between the authority and the path, so
https://mcp.example.com/mcp publishes at /.well-known/oauth-protected-resource/mcp and
https://mcp.example.com at the bare well-known path. A trailing slash is carried through
rather than trimmed — it is part of the identifier the client compares, and two resources
that differ only by it are two resources. Exactly one route is registered; a deployment
fronting several resources calls serve_protected_resource_metadata once per resource.
Actix needs no exemption to implement, unlike Express or Fastify. §28.3 rule 2 requires
an SDK to exempt the metadata document's path wherever the §10 guard is applied globally —
a requirement written for a middleware that wraps every route. AxiamUser is a FromRequest
extractor a handler opts into by declaring it as a parameter, never a blanket App::wrap,
so the route serve_protected_resource_metadata returns is unauthenticated by construction: it
composes no AxiamUser extractor, and there is no global guard for it to be exempted from.
Announcing yourself obliges you to check
expect_audience is mandatory before with_resource_metadata_url, and the latter refuses
otherwise, naming both. A resource server that publishes "tokens for me carry this aud" and
then does not check aud has published a claim it does not honour — and a token minted for a
different MCP server opens it. That is the confusion RFC 8707 exists to prevent, so it is
impossible to configure rather than merely discouraged:
# use JwksVerifier;
#
With both set, a token carrying aud: "axiam:user" — a perfectly valid AXIAM token that
simply was not minted for this resource — is a 401, exactly like a token minted for
https://other.example.com/mcp.
The 403 that asks for a scope
One class of 403 carries a challenge, and only one: a RequireAccess check that named a
scope whose decision came back allowed: false with reason_code: "no_grant".
# use AxiamClient;
# use ;
# use JwksVerifier;
# use Uuid;
# async #
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="mcp:tools", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
Content-Type: application/json
{"error":"authorization_denied","message":"..."}
insufficient_scope is in the header and authorization_denied is in the body, and they are
not two spellings of one thing: the body is the §11 error taxonomy, unchanged, and the header
is the RFC 6750 hint. The scope named is the one the route asked for, verbatim — never
synthesised, never derived from action/resource, never substituted from the document's
scopes_supported, because where a deployment's AXIAM resource-scope names and its OAuth
scope names differ, that mapping is the operator's decision and the SDK cannot see it.
Every other 403 carries no header at all: a RequireAccess check with no scope, a
require_role_check failure, a §3 CSRF refusal, and — the one that matters — a decision whose
reason_code is denied_by_rule. no_grant means ask for more, which is what a challenge
invites a client to do; denied_by_rule means an administrator has already decided, and
challenging on it would send an MCP client all the way around the authorization loop to arrive
at the identical 403. An absent or unrecognised reason_code is not eligible either.
Where a check also carries a UmaChallenger via with_uma_challenge (§20.3), a successful
UMA mint wins: it is per-check opt-in and carries a live ticket for the exact authority just
refused, where this one is the generic hint. Only when §20.3 was not configured, or its mint
failed, does this challenge take over — exactly one WWW-Authenticate value is ever emitted.
The challenge says only what RFC 6750 can say
Expired, not yet valid, wrong tenant, wrong audience, bad signature, an unsatisfiable cnf, a
sid in the §10.4 revocation feed — all of them are invalid_token, indistinguishably. The
SDK's own guard never emits an error_description, and adds nothing to the response that tells
them apart. It is a 401 to an unauthenticated stranger: every distinction it draws is an oracle.
bearer_challenge exists for the challenge you build yourself, for your own 400, and it takes
error_description for that reason alone. It refuses rather than escapes: RFC 6750
restricts every parameter to a character set that cannot contain " or \, so a value needing
an escape is a value that does not belong in a challenge.
use ;
let url = "https://mcp.example.com/.well-known/oauth-protected-resource/mcp";
let challenge = bearer_challenge
.unwrap;
// Bearer error="invalid_request", error_description="The access token is malformed",
// scope="mcp:read mcp:tools", resource_metadata="https://mcp.example.com/.well-known/…/mcp"
assert!;
Validation refuses; it never repairs
Every §28.2 rule is checked by protected_resource_metadata itself, and a violation returns
AxiamError::Network carrying a ValidationError source (§2's taxonomy, unchanged — §28 adds
no new error type). Nothing is normalised, trimmed, lowercased or re-encoded to make it pass:
that would publish a document describing a resource server that does not exist. The rules, in
one list:
| Member | Rule |
|---|---|
resource |
absolute URI with a scheme and an authority, no query and no fragment; a trailing slash is significant |
| any URL | https, except on 127.0.0.1, [::1] or localhost — there is no flag, env var or debug build that widens this |
authorization_servers |
at least one entry, each an issuer verbatim (no ?tenant_id=), no query, no fragment, no duplicates |
scopes_supported |
RFC 6749 NQCHAR tokens, order preserved, no duplicates; an empty list omits the member |
bearer_methods_supported |
exactly ["header"] — this SDK's guard reads a bearer credential from the Authorization header alone |
resource_documentation |
an absolute URL, query and fragment permitted; omitted when absent, never null |
Nothing in the document may come from a request. resource and authorization_servers are
configuration, and this SDK offers no option to build either from the Host header, the
Forwarded/X-Forwarded-* family or the request URL. A document assembled from the request is
a document an attacker can point at an authorization server of their choosing — the whole
handshake redirected with one header.
No gRPC or AMQP guard to extend
§28.5 rule 8 lets an SDK "whose guard also covers gRPC" attach the same challenge as
www-authenticate metadata on an UNAUTHENTICATED status, and forbids inventing an AMQP
equivalent outright. This SDK's grpc module is an outbound client speaking to AXIAM's own
check_access/user_info RPCs, and its amqp module is a Reactor consumer subscribing to
AXIAM's hook events — neither is a resource-server guard protecting a service this SDK's
consumer builds, the way AxiamUser protects one on the REST/Actix surface. There is
therefore no transport-appropriate equivalent to extend on either transport in this SDK today;
see CHANGELOG.md for this recorded as a structural fact about the crate's surface rather than
an omission from this port.
Webhook signature verification (rest or amqp)
AXIAM signs every webhook delivery with a Stripe-style signed timestamp:
X-Axiam-Signature: t=<unix_seconds>,v1=<hex>, where
v1 = HMAC-SHA256(secret, "<t>.<raw_body>"). verify_webhook recomputes the
MAC, compares it in constant time, and applies a two-sided 300-second freshness
window (CONTRACT.md §13).
use ;
use Sensitive;
use ;
async
⚠ Pass the raw body bytes.
verify_webhooktakes&[u8]deliberately. Parsing the body into JSON and re-serializing it changes key order and whitespace, so the recomputed MAC covers different bytes than the server signed and every genuine delivery is rejected. Capture the untouched body (web::Bytes,axum::body::Bytes,hyper::body::to_bytes, …), verify, then parse.
Deliveries are at-least-once. A retry replays a valid signature inside the freshness window, so a successful verification does not mean a new event.
X-Axiam-Deliveryis the dedup key — keep a short-lived seen-set.
The tolerance (default 300 s) and a now injection seam for tests are both on
WebhookVerifyOptions.
WebAuthn and passkeys (§24)
A passkey ceremony is two exchanges stacked: one with an authenticator, which needs a platform API, and one with AXIAM, which is four ordinary JSON round trips. The native build has no authenticator, so it ships the second half.
That is not a consolation prize. A Rust service completing a ceremony that ran on
an Android or iOS handset is the relying party exactly as a browser is — and
§24.6b rule 2 forbids the alternative outright: an SDK must not emulate an
authenticator in software, because a "credential" held in process memory is not a
second factor. axiam-sdk-wasm is the one build that does reach an
authenticator, through web-sys.
The three-step shape
let challenge = client.webauthn_discoverable_start.await?;
// The JSON form every platform authenticator API takes (§24.6a) — the exact
// string Android's CreatePublicKeyCredentialRequest and a browser's
// parseCreationOptionsFromJSON() both want.
let response_json = your_device_channel?;
let session = client
.webauthn_discoverable_finish
.await?;
The client is authenticated when that returns — §24.3 rule 1 is not a "MAY
adopt". webauthn_register_start/_finish and
webauthn_authenticate_start/_finish follow the same shape, for enrolling a
credential and for a passkey used as a second factor after login() set
mfa_required.
The challenge is a serde_json::Value, not a modelled struct — precisely so
there is nothing to normalize through. webauthn_response_from_json takes the
platform's own string; making a caller model one as a Rust struct this SDK
immediately re-serializes is three chances to corrupt a signed buffer in service
of nothing.
What the SDK will not do
It never adjusts an option. The server generates the challenge and chooses
residentKey, userVerification, the attestation conveyance, the exclusion list
and the timeout; this SDK carries all of it through unchanged and posts the
answer back unchanged. Not because those fields are hard — because they are not,
and relaxing userVerification to "preferred" because a test authenticator
kept prompting weakens a ceremony the server believes it configured. The server
cannot catch it: an assertion produced under weaker options is a valid assertion.
It never parses state_token. It is opaque, it is Sensitive, and it goes
straight back to the matching *_finish.
Classifying a device's failure
Every platform reports a ceremony failure as one opaque type whose only machine-readable part is a name — so a handset can relay just that name, and a Rust service can turn it into the same five outcomes a browser would see:
let failure = classify;
if failure == AlreadyRegistered
show;
Cancelled covers both an explicit refusal and a silent timeout. The
WebAuthn spec deliberately refuses to distinguish them, because telling a website
which one happened leaks whether an authenticator was present — so the copy does
not accuse anyone of cancelling, and the distinction must not be recovered by
timing the call.
Two error rows that are not the generic mapping
- A
403onwebauthn_register_finishis the tenant's attestation policy refusing this authenticator — an AAGUID that is not allow-listed, a missing FIDO certification, a revoked status — not a permission problem with the user. The policy message survives intoAxiamError::Authz, because it is the only way the person holding the key learns a different one would work. - A
503onwebauthn_register_startmeans attestation is required and the FIDO metadata service has no usable snapshot. A server configuration state, not a transient failure, and deliberately not retried.
Worked example: examples/webauthn_relying_party.rs.
Account lifecycle and MFA enrolment (§25)
§1 locks the middle of an account's life — login, verify_mfa, refresh,
logout all assume an account that already exists, is verified, and already has
its second factor. These nine operations are how it gets there.
let enrolment = client.mfa_enroll.await?;
render_qr;
let enabled = client.mfa_confirm.await?;
secret_base32 and totp_uri are both Sensitive, and the URI is the one that
matters: it is otpauth://…?secret=…, so it contains the secret it sits beside.
Wrapping only the secret would have wrapped nothing — the URI is the field that
actually reaches a log, because it is the field you hand to a QR renderer.
login() has a third outcome
LoginResult gains mfa_setup_required and setup_token. The server has always
been able to answer 403 mfa_setup_required for an account in a tenant that
requires MFA; it used to reach you as AxiamError::Authz, saying you lacked
permission to log in when what the server said was recoverable.
let result = client.login.await?;
if result.mfa_setup_required
Additive here rather than a new type, because LoginResult has always been one
struct with flags rather than a discriminated enum — so nothing that reads
mfa_required today has to change. A genuine authorization refusal is still
AxiamError::Authz: the branch is matched on the body's discriminant, not the
403 alone.
A passkey or security key instead of TOTP (contract 1.45)
webauthn_setup_register_start / webauthn_setup_register_finish are the
WebAuthn twin of mfa_setup_enroll / mfa_setup_confirm — a tenant that
requires MFA no longer limits a new user's first factor to TOTP:
let result = client.login.await?;
if result.mfa_setup_required
Both take no session at all — the setup token is the only credential,
exactly as it is for the TOTP pair, and neither call attaches this client's own
session credential even when one happens to be configured (CONTRACT.md §24.1).
webauthn_setup_register_finish adopts credentials exactly as
mfa_setup_confirm does (§25.2 rule 2): the client is authenticated
afterwards, the same way, whichever factor the user chose.
Organization-level principals (§5.2)
A completed login also reports whether the account is an organization-level principal — one whose record lives in its organization's reserved tenant, so its global grants apply in every tenant of that organization:
if result.organization_level
Check it before offering a tenant switch. An ordinary tenant principal is a principal of
exactly one tenant, and changing the header for one of those produces a 403 — so a UI
that offers the switch to everyone has turned a distinction the server made into a failure
the user discovers. false on a server older than contract 1.31, which is the safe
reading of absent: no cross-tenant action offered.
Signing one in (§5.2.1)
The reserved tenant has a fixed slug, organization, the same in every deployment — so
signing in as an organization-level principal needs no new surface, only the ordinary
builder:
let client = builder
.base_url?
.tenant_slug
.org_slug
.build?;
client.login.await?;
Prefer that form. The server also reads a login body naming no tenant as "the
organization's own scope", but §5 rule 2 still requires a tenant on the X-Tenant-ID
header of every request after the login, so the client needs one either way.
What §5.2.1 forbids is the third possibility: an empty-string slug. Nothing can carry one,
so tenant_slug: "" resolves nothing — and on /auth/opaque/login/start it fails on the
workspace before the tenant's OPAQUE mode is read, so the 404 that means "OPAQUE is
not offered here" never arrives and this crate has no fallback to take. Sign-in then fails
even against a tenant with OPAQUE disabled, reported as invalid credentials, which sends
a user off to reset a password that works.
build() refuses a blank tenant_slug or org_slug so that never reaches the wire —
"" is exactly as much of a tenant as none at all. It is checked at build() rather than
in tenant_slug(), which returns Self and has nowhere to put an error.
Email verification and password reset
client.verify_email.await?;
client.resend_verification.await?; // anonymous caller
client.resend_own_verification.await?; // signed-in caller
client.request_password_reset.await?;
There are two resends, and picking the wrong one is silent. Use the second one whenever you have a session.
resend_verification takes an address from an unauthenticated caller, so it answers
identically whatever happens — unknown address, already verified, over the daily limit —
and returns Ok(()) in all of them. That constancy is the point: anything else is an
oracle for which addresses have accounts.
resend_own_verification is for a caller signed in to the account it is asking about. It
takes no address at all (the server reads it off your own record, and a parameter here
would let a session mail an arbitrary one) and it says what happened:
match client.resend_own_verification.await
A profile page that called the first one reports success while doing nothing, which is
the bug this pair exists to separate. This SDK does not fall back from the second to the
first on either failure — that would turn both back into a green Ok(()) with an extra
round-trip. And Ok(()) means enqueued: delivery is asynchronous and can still fail at
the provider.
request_password_reset returns Ok(()) whether or not the address exists,
and this SDK exposes no way to tell them apart. Any signal distinguishing them —
including one inferred from timing — turns the endpoint into the account
enumeration oracle its uniform response exists to prevent.
Setting the new password takes one extra call on any tenant that might have OPAQUE enabled, because the client has to build a registration record and cannot know the parameters before it has a token to ask with:
let context = client.password_reset_context.await?;
client.confirm_password_reset.await?;
The context discloses no identity, and a 404 covers unknown, expired and
already-consumed without distinguishing them.
Worked example: examples/account_lifecycle.rs.
Pushed authorization requests (§26)
PAR (RFC 9126) moves the authorization request off the browser: the client POSTs
scope, redirect_uri, state and the PKCE challenge straight to AXIAM over an
authenticated back channel and puts an opaque request_uri in the redirect, so
what travels through the user agent is a random string that cannot be edited into
meaning something else.
Required for a FAPI 2.0 client — profile: "fapi2" refuses a registration that
does not set require_par.
let configuration = client.oidc_discover.await?;
let request = client.oidc_begin?;
let pushed = client.oidc_par.await?;
redirect;
oidc_begin still does the computing — there is no second generator for state,
nonce and PKCE — and pushed.code_verifier is the one it produced, so there is
exactly one value to keep.
Three things that are easy to get wrong:
- The endpoint answers
201, not200. RFC 9126 §2.2 specifies Created, and a success predicate written== 200treats every successful push as a failure. - The authorization URL carries exactly
client_idandrequest_uri. The server refuses a request mixing arequest_uriwith inline authorization parameters rather than merging them, and re-adding them "for compatibility" restores the parameter-confusion attack the refusal prevents. request_uriis single-use and short-lived. There is nothing to retry with it; the safe recovery is a fresh push.oidc_paris correspondingly never retried on a5xxor a transport failure — it is a POST that creates state.
Worked example: examples/par_login.rs.
Choosing the provider: idp_hint (contract 1.65)
OidcBeginParams::with_idp_hint("google") adds the single query parameter axiam_idp_hint
(a provider UUID, slug or branded kind name) so the browser goes straight to that provider.
It is checked for emptiness and 256 bytes only (a local ValidationError, no URL built),
never trimmed, case-folded or looked up. Under oidc_par the hint travels in the pushed body
and never in the redirect, which stays client_id and request_uri.
Native sign-in with a provider ID token (§37)
A mobile or desktop app that used Google, Apple or Facebook's native SDK presents the provider's ID token to AXIAM and gets the client's ordinary token set back. This is not token exchange.
use ;
// 1. A fresh pair per attempt. Give the provider's SDK `pair.hashed` as ITS nonce.
let pair = native_nonce?;
let provider_id_token: String = /* the provider SDK's result */ todo!;
// 2. Present the token with the RAW nonce. `provider` is a UUID or the operator's slug,
// not a kind name. Pass "openid" yourself if you want an ID token back.
let tokens = client
.login_with_provider_id_token
.await?;
It is never retried (the provider token is single-use deployment-wide, and invalid_grant is
one generic answer to every refusal): after any failure obtain a fresh provider token and a fresh
nonce. Neither the provider token nor the raw nonce is logged or kept, so hold the raw nonce only
for the attempt. A public client (client_id only) is the normal caller. The returned tokens are
returned, not adopted as the client's credential. Local refusals (empty provider, id_token or
nonce) are ValidationErrors with no request sent.
OPAQUE (§23)
login_opaque proves the password without sending it. What crosses the wire is
a blinded group element and a MAC, neither of which is useful to anyone who
does not already hold the account's record and the tenant's OPRF seed.
use AxiamClient;
let client = builder
.base_url?
.org_slug
.tenant_slug
.build?;
// Same LoginResult as login(), including the MFA-challenge case.
let result = client.login_opaque.await?;
if result.mfa_required
Fall back to login() when the tenant does not offer OPAQUE — that case is a
NetworkError naming OPAQUE, deliberately not an AuthError, so it cannot
be mistaken for a bad password:
let result = match client.login_opaque.await ;
Do not fall back on any other error — and you no longer need to for the
one case where a fallback is correct. login/start reports the tenant's
opaque_mode, and CONTRACT.md §23.4 rule 7 makes login_opaque act on it when
the exchange fails:
optional— the mid-migration state. Every account has no OPAQUE record until its password is next set, so a failed exchange is the ordinary case rather than a wrong password.login_opaqueretries overlogin()itself with the same credentials and returns that call's outcome, so most of a tenant can still sign in.required, an unrecognised mode, or a server too old to report one — the failure is final and comes back as anAuthError. No plaintext password goes on the wire;requiredanswers403 opaque_requiredfor every principal anyway.
In both cases no KE3 is ever sent once the envelope fails. mode is not
downgrade protection — a hostile server that wanted the plaintext could just
answer 404 and take the fallback above. What closes that is required,
server-side.
Enrolment
The server cannot build a record — it never sees the plaintext — so one has to be sent with any request that sets a password:
let enrollment = client.opaque_enrollment.await?;
// send `enrollment` as the request's `opaque` field
One argument, where the SRP verifier this replaces took four. There is no
identity, no group and no KDF: the server names the ciphersuite and the costs
in its register/start response, and the record binds to a credential
identifier the server chooses. It is async because that response has to be
fetched — OPAQUE's envelope is sealed under the server's oblivious PRF, so
there is no offline computation that produces a valid record.
Three things worth knowing
Nothing about the account's name matters. The SRP version of this section
opened with a warning that the identity is always the username, because x was
derived over username ":" password and enrolling against an email produced a
verifier no login could satisfy. That whole class of mistake is gone, and so is
its consequence: a later rename no longer invalidates a credential.
login_opaque blocks. It runs the tenant's key-stretching function:
Argon2id at 19 MiB by default, tens to hundreds of milliseconds. That cost is
the point — it is what makes a stolen record expensive to attack even by
someone holding the OPRF seed — but on an async runtime, treat the call as
blocking work.
What it does and does not protect. A TLS-terminating proxy, an accidentally verbose request log, or a heap dump on the server can no longer capture a plaintext password, because the server never has one. A stolen record database is additionally not offline-crackable without the tenant's OPRF seed, which is the property SRP could not offer. It does not protect against a compromised AXIAM server.
This SDK does not implement OPAQUE. CONTRACT.md §23.1 forbids it, and this
crate obeys: the protocol comes from axiam-opaque, the same implementation
the AXIAM server links and the other ten SDKs bind through a C ABI or
WebAssembly. That is why the opaque feature no longer pulls num-bigint, and
why the ~870 lines of group arithmetic the SRP implementation needed are gone.
Management API (§27)
Everything above assumes a populated tenant. login signs a user in, check_access asks
about a resource, verify_webhook checks a delivery signature — and none of them can
create the user, declare the resource or register the webhook. client.management is the
part that can: 202 operations across 29 namespaces, generated from
management-registry.json, which is the whole server API minus what other contract
sections own and minus organization creation and deletion (§27.0 keeps those out of reach
of a client library on purpose).
use PageRequest;
let page = client.users.list.await?;
let every = client.users.list_all.await?;
let found = client.users.list.await?;
let role = client.roles.get.await?;
client.roles.assign_to_user.await?;
Operations hang off namespace handles rather than the client. Twenty namespaces have a
list and fourteen a get, so flattening them would need a disambiguating prefix invented
once per operation — and would bury the eight §1 methods most callers want under five times
as many they do not. Acquiring a handle performs no I/O.
Every management call goes through the same request path as §1's, so it inherits CSRF
forwarding (§3), the cookie jar (§4), the X-Tenant-ID header (§5), the TLS policy (§6),
single-flight refresh (§9), the retry policy (§16) and telemetry (§19). None of it is
reimplemented, and none of it can be forgotten per-operation.
Five things that bite
Reads retry; writes never do. Not even the idempotent-looking ones.
certificates().generate() twice mints two certificates; service_accounts() .rotate_secret() twice invalidates the secret the first call returned and you already
stored.
Seventeen PUTs patch, four replace. A sparse update sends only the fields you set —
an unset field is absent from the wire body, not null, so it is left unchanged.
But settings().set_org(), email_config().set_org(), webauthn_policy().set() and
ca_certificates().set_mtls_trust_anchor() replace: what you omit is not preserved.
Their request types have required fields, so a half-filled one does not compile — which is
the point, since sending a subset of SetOrgSettings resets the other eighteen.
Seven calls return a secret exactly once. Creating a service account or an OAuth2
client, minting a SCIM token, generating a certificate, a CA, a signing CA or a PGP key.
The field is Sensitive<String> — redacted in every debug rendering, readable with
.expose(). No later get returns it again, and the get projection has no field where
it was, so nothing tells you it is missing.
404 means "absent, or not yours." The server answers 404 for a resource in another
tenant deliberately: a distinguishable "exists but not yours" lets a caller enumerate
another tenant's ids. Both arrive as AxiamError::Authz { kind: AuthzKind::NotFound, .. }.
match client.users.get.await
NotFoundError, ConflictError and ValidationError are §2 sub-types. Rust has no
subtyping, so they are a discriminant on the variant (404/409) and a typed error source
(400/422) — matches!(e, AxiamError::Authz { .. }) keeps compiling and keeps being true.
{org_id} and {tenant_id} default from the client, and are overridable per handle
with .in_org(id) / .for_tenant(id). A client built with a slug fails locally, with no
request, on any route that needs the UUID — the SDK will not resolve a slug behind your
back.
search is on the page request, and the server does the filtering. All twenty
paginated operations take it:
let page = client.users.list.await?;
let all = client.users.list_all.await?;
It is matched case-insensitively against the identifying fields of whatever is being listed — a name or username, plus the record id, so a UUID out of a log line pastes in as-is. Three consequences worth knowing:
totalcounts matches, not rows, because the filter is applied beforeoffset/limit. That is what makes a pager built on it show a page count belonging to the result set it is paging. Filtering a page client-side instead gives you neither.list_allcarries the term across the whole walk, so it returns the matches and not the matches followed by the unfiltered tail.- A blank term is no term.
.search("")and.search(" ")send nosearchparameter at all, so a box that fires on every keystroke does not ask a different question once it has been cleared. The server also caps the term's length; this SDK does not copy that cap, because a client-side truncation the server would not have made is a silently different query.
PageRequest is Clone and no longer Copy — an owned term cannot be copied
bit-for-bit — so a value reused across several calls needs an explicit .clone().
Three model fields arrived with contract 1.31 (§27.11). Tenant::kind says whether a
tenant is ordinary or its organization's own scope, and is None on a row written before
that scope existed. MtlsTrustAnchorResponse::trusted_anchors is None when nothing was
reloaded — which is not zero: "the listener trusts no CAs" and "there was no listener to
ask" are different states, and only one is a problem. Certificate::bound_service_account_id
is resolved by certificates().list() and is None on get; the SDK does not issue a
second request to fill it in.
Generated enums are open. A value this SDK's copy of the spec does not list decodes to
Unknown(String) carrying it verbatim, rather than failing the response it arrived in. A
closed enum would turn the next kind or status the server adds into a parse error on
the whole list — taking down every record on the page over one field of one of them.
Declarative manifests (§27.6, §27.7)
Calling 202 operations one at a time is rarely what an application wants. What it does at start-up, in a migration, or in a test fixture is assert a shape:
use ;
let desired = manifest! ;
let plan = client.manifest.plan.await?; // reads only — no writes
for action in plan.changes
let report = client.manifest.apply.await?;
plan() issues GETs and nothing else, so it is safe to point at production. It matches
each spec by its natural key — a user's username, a role's name, a scope's name
within its resource — and returns the ordered actions that would reconcile the tenant.
- Nothing outside a manifest's own entities is ever deleted. A manifest is usually a
subset of a tenant's truth, and a prune would turn "make sure these three roles exist"
into "delete the other forty". There is no prune option, deliberately. The one exception is
a role binding's own
Update: there is no update endpoint, so it is performed as unassign, then assign, and between the two calls the subject does not hold the role. - A field the manifest does not state is never a difference, so
applyis safe against a tenant that also holds hand-made state. - Applying twice converges: the second plan is all
NoChange. That is what makes re-running after a failure safe. - There is no transaction across 158 independent HTTP endpoints, and
ApplyReportdoes not pretend there is. If step 12 of 30 fails, steps 1–11 have happened and the report says which, execution stops rather than continuing blindly. The one exception is a bindingUpdate's own assign half: if it fails,applyre-assigns the previous binding and reports both outcomes (Outcome::BindingUpdateFailed { restore }) — restoring one binding is not a transaction over the other 157 endpoints, which still have no rollback.
Broken manifests are refused before the first request: dangling keys, duplicate keys, a
cycle in the resource parent graph, a user that would have to be created with no
initial_password, a role bound twice to one subject (the server keys assignments on
subject and role and answers 409 to a second), and a global role bound with
inherit: false (the server answers 400; §27.6.1 lets an SDK say so first) all fail while
nothing has been changed. One check cannot run this early: a service account's name is not
unique on the server, so an ambiguous one — more than one existing account sharing a
manifest entry's name — is caught only once plan()'s own GETs have run, and fails there.
The network namespace (§27.6.2, contract 1.62)
Segments, their reply profiles and the tenant's Session-Timeout cap are a manifest
namespace, planned last — policy, then segments, then profiles:
use ;
let desired = new
.with_network_policy
.with_network_segment
.with_network_segment
.with_network_profile;
let report = client.manifest.apply.await?;
- Natural keys. A segment is keyed by site + kind + name, where the kind is the wire
spelling
accessorquarantine; a profile by its segment; the policy is a singleton. One key named twice, a profile for a segment the manifest does not declare, and a segment that lists one Filter-Id twice are refused before any request. - Judged on the read. Every stated member is compared with the value the server returns —
for a profile, the effective one.
filter_idscompare as a set (a reorder alone isNoChange; a write sends them in the order you state). A statedsession_timeout_secsabove the tenant's cap differs from the read, soplanshows anUpdateandapplysends it; the server refuses it with403,applyreports that as given and stops, and nothing is lowered or retried for you. State a higherNetworkPolicySpecin the same manifest to raise the cap first. A read-modify-write of a clamped profile cannot restore the stored value (§36.3 rule 6): raise the cap, leave the profile alone. - Writes are version-conditional and never retried. The replace bodies are built from the
read with its
version; a profile'ssegment_versionis the response of the segment write the sameapplyjust made. A409is that action's failure —Outcome::Conflict { message, reason_code }, orreport.reason_code()— and you runapplyagain, which re-reads. - No pruning. As for every namespace, this SDK offers none:
plannever emits aDelete. Useclient.network().delete_segment(id, version)anddelete_profilefor that. - The
manifest!macro andManifestBuilderdo not declarenetworkstatements; use the constructors above.
Resource-scoped bindings, service accounts, and metadata
The example above only assigns a role tenant-wide. The full grammar of the manifest!
macro's assign statement, contract 1.51's RoleBinding type:
assign role editor, to group staff; // RoleBinding::Role — tenant-wide
assign role editor, to group staff, at documents; // RoleBinding::at — reaches descendants
assign role editor, to group staff, at documents, here only; // RoleBinding::at_only — inherit: false
The same three forms work for to user and to service_account. A plain (non-assign)
statement — group_role(g, "key"), user_role(u, "key") — still compiles and produces
RoleBinding::Role; a manifest built by hand does the same by pushing RoleBindings onto a
spec's roles: Vec<RoleBinding> (RoleBinding::at/at_only take a role key and a resource
key). inherit: false on a role the manifest declares global is refused client-side
(§27.6.1) — a global role reaches everywhere and ignores the resource.
Service accounts are a manifest entity too, with their own bindings:
service_account device_writer = "device-writer", "Writes telemetry for this fleet";
assign role editor, to service_account device_writer, at documents;
ServiceAccountSpec mirrors UserSpec: key, name (the natural key — see the ambiguity
refusal above), an optional description (the only field an Update reconciles), and
roles: Vec<RoleBinding>. A Create step's Outcome is Outcome::CreatedServiceAccount,
carrying the server's one-time client_secret (never returned by a later read, §27.5 rules 3
and 5); ApplyReport::created_service_accounts() iterates every one an apply created,
including ones created before a later step failed.
ResourceSpec takes arbitrary metadata:
resource documents = "documents", "collection", under workspace, metadata json!;
or, built by hand, ResourceSpec::new(key, name, kind).with_metadata(json!({...})). Drift on
it compares by JSON value equality, independent of key order — a stated {} is a value like
any other, distinct from an unstated field.
A binding Update's own re-assignment can itself fail (its unassign already succeeded).
apply re-assigns the previous binding and reports both outcomes as data, not only a
message: Outcome::BindingUpdateFailed { error, restore: Result<(), String> } — restore: Ok
means the subject holds the role exactly as before, restore: Err(reason) means it holds
none and says why. plan() reports the binding change itself as Change::Update, not only
apply().
Examples
examples/management_basics.rs— the imperative surface and the rules above, one at a time.examples/management_manifest.rs— the declarative form end to end.examples/device_mtls_provisioning.rs— provisioning an IoT device and its mTLS identity: anchor the CA, create the service account, generate the certificate, bind it, then authenticate with it. This is the flow §27 exists for; before it, every step but the last had to happen out of band.
Regenerating
src/management/models.rs and src/management/ops/ are generated and committed. After
re-vendoring management-registry.json or openapi.json:
RFC 7592 client configuration (§28.12)
A client that registered itself through POST /oauth2/register received a
registration_client_uri and a registration_access_token, once. With them it manages its
own registration — and only at this client's configured AXIAM: a URI at any other origin is
refused before a request is sent.
use Sensitive;
let token = new;
let mut registration = client.read_client_registration.await?;
registration.client_name = Some;
// A full replacement: start from the read. The token ROTATES — persist the new one first.
let updated = client
.update_client_registration
.await?;
let rotated = updated.registration_access_token.expect;
store;
Neither write is retried: an update whose answer was lost has already rotated the token.
The token never travels anywhere but Authorization: Bearer, these requests carry no SDK
session, and a 401 from them never triggers the §9 refresh.
Directory, SAML, SSF and SCIM targets (§29 – §32)
Four management namespaces, generated like the rest of §27, with the contract's call-site rules in each method's documentation.
use Sensitive;
use models;
// §30 — moving the connection (url, start_tls, bind_dn, trust_anchors_pem) needs the
// secret again; the SDK keeps no copy.
client.directory.update.await?;
// §29 — a metadata import is a draft; nothing is stored until you create it.
let draft = client.saml
.parse_sp_metadata
.await?;
let sp = client.saml.create_service_provider.await?;
// §31 / §32 — replace updates: read, convert, change, write. The write-only secret is
// left absent, which keeps the stored one. The SCIM conversion also carries the
// `updated_at` it read as `expected_updated_at`, so the write is refused `409` if another
// administrator changed the target in between (§31.3 rule 4): reload and retry.
let target = client.scim_targets.get.await?;
let mut body = from;
body.enabled = Some;
client.scim_targets.update.await?;
// §27.15 note 8 — federation.update_config is sparse: `None` leaves a member as stored,
// and on its ten nullable members `Some(None)` sends `null`, which clears it.
client.federation.update_config.await?;
A stream is edited with the change-taking form, which does what the plain converter leaves
to you (§32.2, contract 1.62): it sends events_requested and expected_updated_at as read
and cuts events_requested to a lowered events_allowed.
use SsfStreamChanges;
let stream = client.ssf.get_stream.await?;
let body = from_stream_with;
client.ssf.update_stream.await?; // 409 if the stream was written since
events_requested has three meanings on an update: left None it resets the stream to every
event of events_allowed; an empty list is the receiver's "none"; a list is stored as given and
refused 400 outside events_allowed. The plain SsfStreamInput::from(&stream) also sends it
as read, but cannot know you will lower the ceiling, so the cut is yours there.
SamlIdpCredential has no key member and never will; delete on a SCIM target deprovisions
nothing downstream; retiring the active SAML credential with no successor stops SAML sign-on
for the whole tenant. Every write in these namespaces is issued exactly once.
SSF receiver (§32.7)
For the relying party that receives AXIAM's CAEP and RISC events:
use Arc;
use SetFailureReason;
use ;
let mut config = new;
config.access_token_provider = Some;
let receiver = new?;
// Push: verify, then answer 202 — or 400 {"err": reason.push_error_code()} for a
// refusal. An error with no `set_failure_reason` (the JWKS fetch failed) is no
// verdict on the SET: answer 5xx, so the transmitter retries.
let event = receiver.verify_set.await?;
// Poll: acknowledge what you processed on the next call; refuse the rest by setErrs —
// except a `replayed` one, which you accepted on an earlier poll: acknowledge it.
let result = receiver.poll.await?;
let set_errs = result.refused.iter
.filter
.map
.collect;
The verification order, the reason codes (AxiamError::set_failure_reason) and the
seven-day replay window are the contract's. A replay window below seven days is refused
at configuration.
poll is all or nothing (contract 1.59, §34.2 P1): it checks every SET of a batch before
it records any jti, so a key fetch that fails part-way returns that error with nothing
recorded, and the transmitter offers the whole batch again. It never keeps a jti it does
not return.
The replay store is pluggable (SsfReceiverConfig::replay_store). The default
MemoryReplayStore is one process's memory, bounded in time — each jti is kept for the
replay window — and unbounded in count: nothing caps how many it holds meanwhile.
A store has three answers — seen, not seen, cannot answer — and
ReplayStore::check_and_record returns Result<bool, ReplayStoreError> to give all three
(contract 1.60, §34.2 P4). A store that cannot answer (backend unreachable, a timeout) returns
Err, which is no verdict: the SET is neither refused nor accepted and stays unjudged.
verify_set raises an AxiamError::Network chaining your error, with no reason code; poll
records nothing for the SET, returns it in neither events nor refused, lists its jti in
SsfPollResult::unjudged (with the rest of the batch, which the failed store is not asked
about) and expects you not to acknowledge it, so the transmitter offers it again. Never answer
Ok(false) for a jti you could not check: that reads as replayed, which you acknowledge,
and an event nobody processed is lost. (Before 1.0.0 the method answered a bare bool and
documented "return false when you cannot answer"; that route is withdrawn.) An AxiamError
your store returns passes through unchanged; any other error is wrapped. A poll that returns
with SETs unjudged emits the §19 TelemetryEvent::SsfUnjudged event (their count, and
replay_store), so an outage is visible to a telemetry hook even though no error was raised.
The signing keys are cached for five minutes (the contract's ceiling is ten). An unknown
kid costs one refetch, at most once a minute; a key fetch that fails — the first fill,
the refresh of an expired cache, or that refetch — counts toward the same minute, so a JWKS
outage is not one fetch per SET: a SET inside that minute makes no fetch and gets an
AxiamError::Network with no reason code (no verdict; answer it 5xx), and poll raises it
having recorded nothing (§34.2 P6).
CIBA (§33)
Ask AXIAM to authenticate a user on another device, then collect the tokens.
use ;
let mut request = new;
request.binding_message = Some;
let initiated = client.ciba_initiate.await?; // never retried
match client.ciba_await.await
Ping mode: initiate with CibaDelivery::Ping { client_notification_token }, and in the
handler of your notification endpoint call client.ciba_handle_ping(headers, body, &token)? — no I/O — answer 204, then client.ciba_poll(...) once. A successful
ciba_initiate proves nothing about the user: AXIAM answers an unknown or locked user
exactly like a real one, and only expired_token says nobody answered. A client
registered with a request-signing algorithm sends request.signer = Some(CibaRequestSigner::from_pem(alg, &key, kid)?).
Browser builds (axiam-sdk-wasm)
This crate compiles to wasm32-unknown-unknown and is published to npm as
axiam-sdk-wasm — the same implementation, in a
browser, rather than a second one written in JavaScript.
The browser build is REST + OPAQUE only: gRPC and AMQP need sockets, and mTLS and
custom CA roots belong to the browser rather than to page script (both return a
typed error rather than being silently ignored). See that package's README for
the full list and for the CORS requirement that comes with HttpOnly cookies.
It is also the one build of this SDK that can run a WebAuthn ceremony
(§24.6b): navigator.credentials is reachable there through web-sys, where the
native build has no authenticator at all and ships the relying-party layer plus
the §24.6a JSON bridge instead.
Security notes
Sensitive<T>(§7): all token-carrying values redact their raw contents fromDebugandDisplay. The raw value is reachable only via the documentedexpose()accessor, which exists because CONTRACT.md §12'sOidcTokenSet(unlike the §1 cookie-only session) hands tokens directly to the caller in the OAuth2 response body — a relying party must be able to read them back out to use them (e.g. as a downstreamAuthorizationheader). Never pass its return value to a log/Debug/serialization sink.- TLS (§6): strict TLS verification against the system trust store is always on. The only
escape hatch is
with_custom_ca(pem)for development environments with self-signed certificates — there is no API surface that disables or skips certificate verification.
mTLS / client certificates (§6.1)
AXIAM can authenticate IoT devices and service accounts by mutual TLS: the client presents
an X.509 identity certificate (signed by the tenant's organization CA) that the server binds to
a service account. Configure it with with_client_cert(cert_pem, key_pem) — a PEM certificate
chain plus a PEM private key (PKCS#8 or PKCS#1). The identity is applied to both the REST
transport and any gRPC channel built from the same client. Presenting a client certificate never
relaxes server verification — strict TLS stays on. The private key is retained behind
Sensitive<T> and is never exposed via any getter, Debug, or log output.
use AxiamClient;
use build_channel;
#
RFC 8705 §5 mtls_endpoint_aliases (contract 1.40, CONTRACT.md §21.3 rule 2)
A TLS listener decides whether to ask for a client certificate during the handshake, before it
has seen a byte of HTTP, so "request one on /oauth2/token but not on /oauth2/authorize" is
not something a single listener can do. A deployment that wants both runs two — and
mtls_endpoint_aliases in the discovery document is how the second one is named.
Once the client above is built with with_client_cert, every request it makes presents that
certificate, so the §12 helpers prefer the alias over the top-level entry of the same name
wherever the document publishes one:
| Operation | Endpoint aliased |
|---|---|
oidc_exchange, oidc_refresh, login_client_credentials, device_poll, token_exchange, uma_exchange_ticket |
token_endpoint |
introspect |
introspection_endpoint |
revoke |
revocation_endpoint |
device_authorize |
device_authorization_endpoint |
oidc_par |
pushed_authorization_request_endpoint |
Three things this deliberately does not do:
- An absent
mtls_endpoint_aliasesis not an error. It means "this deployment terminates mutual TLS on the issuer's own host", so the conventional endpoints keep being used. A deployment runningclient_auth = optionalon one listener serves both populations there and correctly publishes nothing. The same holds one level in: every field ofMtlsEndpointAliasesisOption, and an endpoint the object does not name falls back rather than failing the document. - No alias is ever synthesised. Only the six endpoints RFC 8705 §5 lists can be aliased —
never
authorization_endpoint,end_session_endpointorjwks_uri. The first two are front-channel and the third is public key material; sending a browser to an mTLS host raises a native certificate-chooser dialog most users cannot answer. issuerdoes not move. It is an identifier, not an endpoint. §12.4 rule 3 still requires a token'sissto equal the document'sissuerby exact string comparison, including for a token minted at an alias endpoint — the expected issuer is never derived from the host that was called.
A client built without with_client_cert keeps using the top-level endpoints even when the
document publishes aliases: the alias exists for the handshake, and there is no handshake to
make.
A malformed alias is refused, never fallen back from (contract 1.43)
mtls_endpoint_aliases is read only by a client that actually presents a
certificate, and an alias that cannot carry one fails the call rather than
quietly reverting to the top-level endpoint. Falling back looks like the safe
answer and is the dangerous one: the caller asked to authenticate with a
certificate, the operator published something unusable, and sending the
certificate to the front-channel host authenticates nothing while appearing to
work.
Two defects, each a refusal on its own:
- Not an absolute URL. A relative alias resolves against nothing the client holds, and the base that might seem obvious — the issuer's host — is precisely the host the alias exists to name a different one from.
- A scheme weaker than the endpoint it replaces. An alias substitutes for
exactly one top-level endpoint, so that is what it is compared against. An
httpalias for anhttpstoken_endpointis a downgrade; anhttpalias for anhttpendpoint is a development deployment, not a misconfiguration.
A client built without with_client_cert never reads the member at all —
not even to validate it — so a deployment whose aliases are malformed cannot
break the clients that never use them.
An alias's query component is preserved rather than appended to: the
tenant_id the caller authenticated against displaces the published one, and
every other parameter survives exactly as the server wrote it.
The discovery document now carries the tenant (contract 1.42)
Since AXIAM's first OpenID Foundation conformance run, a discovery document that describes one
tenant publishes ?tenant_id=<uuid> inside the endpoint URLs it advertises — every endpoint
that authenticates a client, plus authorization_endpoint and end_session_endpoint. A document
that names no tenant (and a deployment with no default tenant configured) still advertises them
bare, exactly as before.
Nothing in this SDK's API changes. The /oauth2/* helpers now replace rather than append the
tenant_id they resolve, so a scoped document produces one parameter instead of two, and any
other query parameter the endpoint carries is preserved — RFC 6749 §3.1/§3.2 require a client
adding parameters of its own to retain the endpoint's existing query component. oidc_par's
redirect target now always carries the tenant the push was made under, which it previously
discarded entirely: the authorization endpoint reads tenant_id for a request with no
authenticated principal — every browser on a PAR redirect, since logging in is what the
redirect is for — and answers 401 without it. It is sent unconditionally rather than copied
from the advertised endpoint, because oidc_discover names no tenant, so a multi-tenant
deployment with no default tenant serves a document carrying none.
userinfo_endpoint and jwks_uri are never scoped — one resolves the tenant from its bearer
token, the other is deployment-wide.
The ID token no longer carries tenant_id, org_id or email (contract 1.42)
OIDC Core §5.4: the ID token carries standard OIDC claims only, and the email scope is answered
at UserInfo rather than in the token. This SDK never typed those three — IdTokenClaims models
the claims §12.4 validates and keeps everything else in extra — so no type changed and no code
here needed fixing. But if your application read them out of extra, they will now be absent.
Resolve them from the access-token claims returned by login, which still carry tenant_id
and org_id, or from UserInfo, which carries both as always-present members. An OP other
than AXIAM that still sends them is unaffected: they keep arriving in extra, as any
unrecognised claim does.
RFC 9449 §10 dpop_jkt at PAR (contract 1.42)
OidcParParams::dpop_jkt pins the pushed request to a DPoP key, so the authorization code it
yields cannot be redeemed by anyone else. It is caller-supplied: this SDK verifies proofs but
does not generate them (§21.9), so compute the thumbprint from your public JWK with
axiam_sdk::token::jwk_thumbprint_s256 — the same function the resource-server half uses for
§21.7.2 check 10, so the two cannot disagree about what a thumbprint is.
Release-profile tuning (for consumers)
Cargo applies only the top-level workspace's [profile.*] tables. The
[profile.release] block in this repository's Cargo.toml therefore governs
this repository's own cargo build --release / cargo bench — it is not
inherited by anything that depends on axiam-sdk, and a [profile.*] table in
any dependency is silently ignored.
If you want whole-program optimization across the SDK, put it in your own top-level manifest:
# your-app/Cargo.toml
[]
= 3
= "fat" # cross-crate inlining into axiam-sdk and its deps
= 1 # slower to build, best generated code
= "abort" # optional; only if your app has no unwinding requirement
Two caveats worth knowing before reaching for these:
lto = "fat"+codegen-units = 1mainly buy link-time optimization. The SDK's own per-call cost is dominated by network round-trips and by Ed25519/HMAC primitives insidejsonwebtoken/ringthat are already compiled with full optimization, so the runtime gain on SDK code paths is small while the build gets substantially slower.- Measure before adopting.
cargo bench --bench jwks_verify --features restin this repository measures the SDK's hottest CPU path (per-request access-token verification behind the §10/§11 route guard) against a local mock JWKS endpoint, alongside a "floor" row (jsonwebtoken::decodewith a pre-built key) that shows how much of the cost the SDK can influence at all.
Build-time notes
A cold cargo build --all-features compiles ~276 crates. The great majority of
that time is not SDK code:
aws-lc-sys— a C build pulled in byrustls's defaultaws-lc-rscrypto provider, via bothreqwest(rustlsfeature) andlapin(default features). On a cold build its build script alone was measured between 65 s and 119 s depending on machine load — comfortably the single largest item. Note thattonicis configured for theringprovider, so a full-feature build currently compiles two rustls crypto backends.- The SDK depends on
actix-webwithdefault-features = falseprecisely to keep the next tier off the graph (brotli/zstd/flate2 compression,h20.3, theregex-based router). Your application's ownactix-webdependency decides which of those it wants; Cargo unifies features across the graph.
Enabling only the transports you use (default-features = false, features = ["rest"]) is the most effective single lever a consumer has.
Development
Building with the grpc feature requires protoc on PATH (apt install protobuf-compiler,
brew install protobuf): build.rs compiles proto/ into the gitignored src/gen/
via tonic-prost-build. buf.gen.yaml drives the equivalent buf generate
pipeline into the same output directory; either path yields the same axiam.v1 module, so buf
is optional for local work. Consumers installing from crates.io need neither — the stubs are
pre-generated into the published tarball.
testdata/v2_reference_vectors.json is generated by the AXIAM server's AMQP sign path and
vendored here verbatim. It pins this SDK's HMAC implementation byte-for-byte to the server's
(CONTRACT.md §8); re-vendor it from the server repository whenever §8 changes.