Skip to main content

Crate orbit_auth

Crate orbit_auth 

Source
Expand description

§orbit-auth

Fleet-aware authentication with encrypted tokens, shared session state and local Principal caching. Available through orbitive::auth with the auth feature (also included in full), or as a direct dependency.

§Fleet-aware authentication

A user’s requests may reach different workers. In an SHM-backed fleet, every worker checks the same session, revocation and refresh state while keeping its own decoded Principal cache. A session created on one worker is recognized by the others when they validate its credentials; logout applies to subsequent checks across the fleet. Concurrent refresh attempts are coordinated atomically. Authentication needs no sticky-session routing or background state polling.

§Optional: cross-application sign-in and events

Fleet members on one host can serve different applications—a web portal, an API and a realtime service—while accepting credentials linked to one shared session. Users can carry their sign-in between applications, and one logout revokes all linked tokens. The application handles credential delivery across domains.

Downstream can combine this with orbit-events to notify other members and their connected clients. For example, publish application-defined events after the auth operation succeeds:

Sign in → create session + issue token → emit TokenCreated { session_ref }
Logout  → revoke session              → emit SessionInvalidated { session_ref }

Subscribers can prompt associated clients to obtain credentials or close a revoked connection. A session reference is enough; no token or user payload needs to be broadcast. Events notify, credentials authenticate: receiving an event does not sign a client in. Shared-state checks still enforce logout if an event is missed.

§Usage

Choose the shared-state protection explicitly:

use std::{num::NonZeroUsize, sync::Arc};
use orbit_auth::{Authority, Blake3State, FleetAuth, Keyring, SecretKey};

// Demo keys. Provision the same token and state keys to participating workers.
let authority = Authority::new("prod", "login",
    Keyring::new(1, [(1, SecretKey::generate()?)])?)?;
let fleet = Arc::new(orbit_core::Fleet::join("example", 1).unwrap());
let auth = FleetAuth::new(
    fleet, &authority, SecretKey::generate()?,
    NonZeroUsize::new(1024).unwrap(), Blake3State,
)?;

Create a session with create_session, issue its token with Authority::issue_session, then use validate_cached with &auth as both cache and validation hook. See the complete example.

§State protection

PolicySHM record protection
Blake3StateKeyed BLAKE3 authentication; metadata remains readable
EncryptedStateXChaCha20-Poly1305 encryption and authentication
UnprotectedStateNo cryptographic protection; trusts every writer

There is no default. Peers opening the same table must select the same policy. Tokens are always encrypted and authenticated, independently of this choice.

§Shared state and local cache

Backing follows the supplied Fleet: join uses memory; join_shm_as uses same-host SHM. Memory handles share state through the same Arc<Fleet>; SHM peers share a fleet name, UID, protection policy and state key.

SHM holds hashed identifiers, expiry, refresh generation and revocation/replay status. Tokens and decoded Principals stay out of SHM. Each worker validates a token on a local cache miss. Cache hits still check expiry and live session state; unchanged protected records reuse local verification without repeating crypto.

  • revoke_session rejects linked tokens on subsequent checks, including cache hits.
  • refresh consumes one refresh generation atomically. Existing access tokens remain valid until their own expiry or session revocation.
  • extend_session moves a live session’s horizon forward on activity the application trusts, with no credential and no generation change. Tokens issued before keep their own expiry; the returned handle issues ones that reach the new horizon. session reads a live session’s handle by id for its subject.
  • Validator::validate_lapsed authenticates a credential past its own expiry and still asks the hook, so a carrier whose session outlived it can be replaced; it admits nothing on the lapsed credential itself.
  • replay_guard admits a token’s jti once. Full tables reject new state rather than evict live records.

§Integration and limits

Adapters extract credentials from cookies, Bearer headers, WebSocket auth frames or internal handshakes. They own TLS, cookie/CSRF/CORS policy and connection expiry. Shared trust can span domains; cookies cannot span different registrable domains.

  • Tokens use a versioned oa1. envelope with XChaCha20-Poly1305 and HKDF-SHA256. Validate the expected audience, purpose and capabilities. All key holders can issue tokens.
  • Use FleetAuth as the hook for session-bound tokens; AllowReusable skips session checks.
  • Supply time and lifetimes explicitly. Cache TTL never extends token expiry. Keep the state key stable across token-key rotation.
  • SHM requires 0600. Protected modes reject forged records but cannot prevent restoring an older valid record, deleting state or denying service.
  • SHM survives restart. Clearing it loses sessions and replay history; retire outstanding one-use credentials before clearing. The table defaults to 1024 entries, configurable at build time with ORBIT_AUTH_STATE_CAPACITY.

Performance measurements

For a validator stored in a service, use authority.validator(policy).into_owned(). The resulting OwnedValidator keeps the prepared policy and derived keys without borrowing the authority. Borrowed Validator usage remains unchanged.

Structs§

AllowReusable
Explicitly permits token reuse until expiry; provides no revocation or replay protection.
Audience
Exact logical recipient; independent of DNS and transport.
Authority
Shared symmetric trust realm, independent of hostnames and protocols. Every key holder can mint tokens; provision keys only to equally trusted services.
Blake3State
Visible control metadata authenticated with full keyed BLAKE3 tags.
CacheKey
Opaque, keyed token fingerprint scoped to the keyring and validation context.
CachedPrincipal
Successful authenticated snapshot, never a raw token. Constructed only by the validator.
Capability
Exact application-defined permission; no implicit wildcards or hierarchy.
Claims
Issuer-authorized claims. All times are absolute Unix seconds; no implicit TTL or leeway.
EncryptedState
Control metadata encrypted and authenticated with XChaCha20-Poly1305. Verified plaintext remains in the worker’s private local session cache.
FleetAuth
Local decoded Principals plus fleet-native live sessions and replay state. Backing follows the supplied Fleet. SHM survives handle drop and restart; memory state lives as long as a handle retains it. No background driver.
Keyring
Immutable rotation snapshot: issue with the active key, validate with any retained key. Replace the authority to rotate; removing or replacing a key invalidates cache namespaces.
MemoryCache
Bounded process-local decoded-principal LRU. A hit only clones an Arc.
Principal
Authenticated identity snapshot. This value is not a transferable credential.
ReplayGuard
SecretKey
High-entropy 256-bit key material, zeroized on drop. Never use a password here.
Session
Issuer-side handle, never serialized into SHM. Live validation checks state even when a caller retained a handle predating refresh or revocation.
SessionId
Random session identity. It is not a bearer credential.
Token
Opaque bearer credential. Debug output is redacted and storage is zeroized on drop.
TokenId
Random 128-bit token identifier. Replay stores must also scope by realm and issuer.
UnprotectedState
No cryptographic protection of shared control records. Every SHM writer can forge session/replay state. Warm checks trust the commit revision alone; writers must publish a new revision for every mutation. Token AEAD, expiry and live-state checks remain. Choose explicitly only when all writers are trusted.
Validation
Expected recipient and use come from trusted routing configuration, never the token.
Validator
Prepared validator with mandatory audience/purpose and optional exact capabilities.

Enums§

Error
Authentication failures contain no credentials or decrypted claim data.
Purpose
Cryptographically separated credential uses, independent of extraction method.

Constants§

AUTH_STATE_CAPACITY
AUTH_STATE_KIND
Current session/replay state. Principal values live only in process memory.
MAX_CAPABILITIES
MAX_LABEL_LEN
Maximum UTF-8 byte length of each realm, issuer, subject, audience or capability.
MAX_TOKEN_LEN
Protocol allocation bound. Transport adapters may impose smaller limits (e.g. cookies).

Traits§

PrincipalCache
Trusted optimization only; misses and failures must return None.
StateProtection
One protection policy for a physical auth table. Implementations are sealed: the selected type defines a fixed wire contract, not a negotiable algorithm.
ValidationHook
Called after static validation on EVERY authentication, including cache hits.

Type Aliases§

KeyId
OwnedValidator
A prepared validator independent of the issuing Authority’s lifetime. Retains policy-scoped derived secrets, not the authority’s root keyring.
Result