Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rullst Connect 🦀

Important

This page describes Rullst v13 (13.0.0). The v12 line (rullst-connect@12) reached end of life on 16 October 2026; see the release record. Use a path dependency only for checkout-local review.

Since 12.1.2 (and in v13), built-in authorization-code URLs explicitly request response_type=code. The OAuth protocol and Google request contract require this field. Offline parsed-query tests cover all eleven providers. Google and GitHub sign-in are used by the maintainer’s production applications; no automated test runs against a live account, and the other providers have not been used with real accounts. Temporary workarounds for earlier 12.x releases should add the field only when absent.

Vision preserved: message brokers, additional queue transports, remote storage, and media work are retained with explicit status and recommendations in the capability ledger.

Crates.io Downloads Documentation Build License

Rullst Connect is an async OAuth2/OIDC client layer with a shared Provider interface and normalized ConnectUser output. Provider-specific protocols, scopes, claims, and application account-linking rules still require explicit review.

🛡️ Security Engineering

Rullst Connect uses layered tests and repository security checks. CI badges report the state of those checks for the referenced commit; they are not an absolute security guarantee.

Security AuditStatusDescription
OpenSSF ScorecardOpenSSF ScorecardCurrent public supply-chain practice score; not a security certification
CodecovFramework library coverageBlocking 90% target for the measured framework-library scope; the complete repository aggregate now also has its own 90% gate
OpenSSF Best PracticesOpenSSF Best PracticesCurrent project badge from the official programme
Release ProvenanceReleaseProvenance attestations for release artifacts; no SLSA level is claimed here
On-demand fuzzingFuzzingManual time-bounded targets; no continuous OSS-Fuzz claim
Property testsProptestScheduled/manual bounded invariant evidence
Miri research matrixMiriManual bounded evidence; the selected pure-Rust client scope is strict, while network/provider execution remains outside Miri
Kani research harnessesKaniManual bounded formal evidence, not proof of the complete protocol surface
CodeQL SASTCodeQLAdvanced semantic code analysis
Supply ChainSupply ChainCargo Deny (vulnerable, unmaintained or banned crates, licenses) and Cargo Audit (RustSec advisories)
Benchmark CIBenchmarkBenchmarks after pushes to main and weekly; a regression past 120% posts an alert comment but does not fail the run
Cargo SemVerSemver ChecksStrict SemVer API breakage checks
Cargo MacheteMacheteDetecting unused and bloated dependencies
Spellcheck CISpellcheckAutomated typo detection across docs and code
Mutation TestingMutantsMutation testing for test suite robustness
Secret ScanningTrufflehogAutomated CI prevention of leaked credentials
Unsafe PolicyUnsafeAudits unsafe usage within the workflow’s declared scope
Panic PolicyPanicsGraceful error handling across the framework

✨ Features

  • 🚀 Async HTTP: Built on Tokio-compatible request paths and reqwest.
  • 🧩 Standardized: All providers return a unified ConnectUser struct.
  • 🛡️ Type-Safe: Robust error handling using thiserror (ConnectError).
  • 🔌 Framework adapters: Core provider APIs are framework-independent; optional extractor features cover the integrations declared in the crate.
  • 🔐 Login challenge store (v13, 13.0.0-alpha.3): begin_login and finish_login keep state + PKCE + OIDC nonce in a ChallengeStore (memory, or the application’s SQLite, PostgreSQL or MySQL pool) behind an opaque id in a short HttpOnly, SameSite=Lax cookie, and consume each challenge exactly once. cargo rullst make:oauth google|github|microsoft|apple generates it for Rullst accounts.
  • 🔐 Managed callback transaction: The optional Axum/tower-sessions path generates, stores, expires, validates, and consumes state + PKCE + OIDC nonce.
  • 🔏 Encrypted token snapshots: Versioned AES-256-GCM envelopes bind a refresh generation to one trusted provider/account pair and an explicit key rotation ID before application-owned persistence.
  • 🔐 OIDC Security: Strict discovery validation plus isolated JWKS caches with TTL, single-flight refresh on unknown kid (at most once per 30 seconds per JWKS URL, after rejecting malformed kid values without I/O), and bounded stale-if-error behavior. OidcProvider verifies an ID token without kid only against a single-key JWK Set whose key fits the token’s asymmetric alg (OIDC Core 10.1); other sets fail closed.
  • 🚪 Typed remote revocation: Access and refresh tokens are distinct API operations. Google, GitHub, Discord, Apple, Auth0 and Cognito have bounded protocol adapters; unsupported providers fail explicitly and offline credentials remain network-free.
  • 🏢 Explicit Corporate Proxy: First-class HTTP(S) proxy clients, including bounded Basic proxy authentication without credentials in the endpoint URL.
  • 📺 Device Flow: RFC 8628 device authorization for headless CLI and Smart TV auth through Provider::request_device_code/poll_device_token; the GitHub adapter implements it and other providers return an explicit error.
  • 🛠️ Testing: With the mock feature (rullst/oauth-mock through the facade), empty or mock_* credentials select a deterministic offline transport; without it, try_new rejects them. mock_idp supplies a loopback-only signed OIDC fixture with one-shot codes, PKCE, nonce, EdDSA ID tokens and JWKS.

📚 Important Documents:

  • CHANGELOG.md: See what’s new.
  • ISSUES: Any issue? Please report.
  • AUDIT.md: Repository audit record; current workflow evidence remains authoritative.

📦 Supported Providers

Official support for 11 core providers:

  1. Google
  2. GitHub (OAuth 2.0, not OpenID Connect: ConnectUser::id is the numeric account id of GET /user, which never changes, never the login name. From 13.0.0-alpha.3 email is the address GET /user/emails marks primary and email_verified is its verified flag; the default user:email scope grants the call. When it fails or lists no primary address, email is the public profile address and email_verified is None)
  3. Microsoft / Azure AD, two adapters:
    • MicrosoftOidcProvider (v13, from 13.0.0-alpha.3) signs in with OpenID Connect for an explicit MicrosoftTenant: Common (any Entra ID organization and personal accounts), Organizations, Consumers or one directory ID (MicrosoftTenant::parse reads common, organizations, consumers or a GUID). It verifies the RS256 ID token against https://login.microsoftonline.com/<tenant>/discovery/v2.0/keys, requires the issuer https://login.microsoftonline.com/<tid>/v2.0 of the token’s own tid and refuses a tid the tenant choice does not admit. ConnectUser::id is <tid>:<oid>, Microsoft’s stable key for a user (sub is pairwise per application). email is the optional email claim, which Microsoft does not verify; email_verified is Some(true) only when the token also carries the optional claim xms_edov: true (request email and xms_edov in the app registration’s Token configuration), otherwise None. It has no get_user_from_token: the identity comes only from the code exchange.
    • MicrosoftProvider reads Microsoft Graph /me through the multi-tenant common authority, so any Entra tenant and personal Microsoft accounts can sign in, and returns no tenant ID; email is Graph mail or, failing that, userPrincipalName, which tenant administrators control and which may not be a mailbox, so email_verified is None. Never link accounts or grant tenant access on it.
  4. Apple (Sign in with Apple; AppleProvider::verify_signing_key checks at startup that the .p8 key can sign the ES256 client secret, and AppleProvider::name_from_user_field reads the unsigned first-login name from the callback’s user field, from 13.0.0-alpha.3)
  5. Auth0
  6. AWS Cognito
  7. Facebook
  8. X (Twitter) (Strict PKCE requirement; confidential clients authenticate to the token endpoint with HTTP Basic, client_secret_basic)
  9. Discord
  10. LinkedIn
  11. OIDC (OpenID Connect Custom Provider) (sends the client secret in the token request body unless discovery lists client_secret_basic without client_secret_post, in which case it uses HTTP Basic)

Tokens supplied by native or mobile clients

Provider::get_user_from_token is not an authentication primitive for a token that a client (for example a native or mobile app) sends to your backend. Except for Apple, it sends the bearer token to the provider’s userinfo or profile endpoint, which proves only that the token is valid for some client of the provider, not that it was issued to your client_id. Another app that obtained a user’s token for its own client ID could replay it and be signed in as that user.

Sign users in with your own authorization-code exchange (get_user with state, PKCE and, for OIDC, nonce), or with an ID token whose signature, issuer, audience (your client_id), expiry and nonce are verified for your client. Use get_user_from_token only for tokens your server obtained itself. Apple’s adapter treats its argument as an ID token and checks signature, issuer, audience and expiry but no nonce, so a captured Apple ID token for your client can be replayed until it expires.

v13 (since 13.0.0-alpha.1) adds that audience-bound entry point for Google and OidcProvider: verify_id_token(id_token, expected_nonce) verifies the signature through the provider’s rotating JWKS and requires the exact issuer, aud equal to your client_id (and, when present, an azp equal to it or, for Google, to a configured native presenter), valid exp/iat and the nonce your server issued for that sign-in attempt. It never calls userinfo. The returned ConnectUser carries the verified ID token in access_token; there is no provider access or refresh token in this flow.

OidcProvider treats profile claims as optional (OIDC Core 5.1) in ID tokens and userinfo alike: without name, ConnectUser::name falls back to given_name and family_name, then preferred_username, then nickname, and is empty when none is present. The email address and subject are never used as a display name.

#![allow(unused)]
fn main() {
use rullst_connect::prelude::{ConnectError, ConnectUser, GoogleProvider};

async fn sign_in_native_google_user(
    google: &GoogleProvider,
    id_token: &str,
    nonce_issued_for_this_attempt: &str,
) -> Result<ConnectUser, ConnectError> {
    google
        .verify_id_token(id_token, nonce_issued_for_this_attempt)
        .await
}
}

Generate the nonce on your server, give it to the client for the provider sign-in request, and consume it once, just like an OAuth state.

Android Credential Manager and iOS Google Sign-In request the ID token for your server (web) client ID, so aud is that ID and azp is the Android or iOS client ID. Configure the server client ID on GoogleProvider and list the native client IDs with try_with_authorized_presenters(["ANDROID_CLIENT_ID", "IOS_CLIENT_ID"]) (at most 16). aud must still equal the server client ID; any other azp is rejected, and the authorization-code flow keeps requiring azp to equal the server client ID.

Remote token revocation is deliberately narrower than login support. Use Provider::revoke_token for an access token and Provider::revoke_refresh_token for a refresh token; Auth0/Cognito accept only the latter through these adapters, while GitHub accepts only the former. A successful provider response does not clear application cookies, sessions, cached identity, or durable token records—the host must commit that local logout lifecycle. Provider revocation endpoints are intentionally idempotent in several ecosystems, so HTTP success is protocol acceptance, not proof that the token was valid immediately before the call.

🛠️ Installation

Inside a source checkout, a path dependency intentionally follows that tree. For a reproducible application, install the exact registry version instead.

v13 command (the v12 line reached end of life on 16 October 2026):

cargo add rullst-connect
cargo add secrecy

With no feature, the crate has the providers and begin_login; AuthCallback and finish_login need one of the axum, actix, leptos or rullst features (--features axum, for example).

A Rullst application can use the facade instead: the rullst feature oauth re-exports this crate as rullst::connect with its Axum integration (rullst-connect/rullst), so rullst::connect::extractors::AuthCallback works as a handler argument without a direct dependency. The login challenge store is rullst::connect::challenge; oauth-sqlite, oauth-postgres and oauth-mysql add its SQL store for that database. The managed tower-sessions transaction below (axum-session) still needs a direct dependency.

For the recommended Axum session transaction, enable axum-session and add a tower-sessions store:

rullst-connect = { version = "13.0.0", features = ["axum-session"] }
tower-sessions = "0.15"

The extractors read the Session that your SessionManagerLayer puts in the request, so your tower-sessions must be the 0.15 line that Connect uses; it stays on that line for all of 13.x (a public dependency).

Or manually add it to your Cargo.toml:

[dependencies]
rullst-connect = "13.0.0"
secrecy = "0.10"
tokio = { version = "1.52", features = ["full"] }

🚀 Quick Start

1. Initialize the Provider

Choose your provider and pass your credentials and callback URL:

use rullst_connect::prelude::*;

fn main() -> Result<(), ConnectError> {
let github = GithubProvider::try_new(
    "YOUR_CLIENT_ID",
    "YOUR_CLIENT_SECRET".to_string().into(),
    "http://localhost:3000/auth/github/callback",
)?;
let _ = github;
Ok(())
}

Credential modes and offline development

Every provider exposes credential_mode() -> CredentialMode. An empty credential or a value beginning with mock_ selects CredentialMode::Mock, a deterministic transport that never accesses the network and signs in a fixed mock user. That mode needs the Cargo feature mock (or oauth-mock on the rullst facade). Without it, try_new, Connect::driver and OidcProvider::discover return ConnectError::InvalidConfiguration for the field credentials when they receive such a value, so a missing production secret fails when the provider is built instead of at the login callback. Enable the feature only in development and test builds, because it turns mock credentials into a working sign-in. In a facade application, run cargo run --features dev-oauth with:

[features]
dev-oauth = ["rullst/oauth-mock"]

With a direct rullst-connect dependency, name rullst-connect/mock instead, or enable it for tests only:

[dev-dependencies]
rullst-connect = { version = "13.0.0", features = ["mock"] }

In mock mode the authorization URL is the configured redirect_url with the fixed code=mock_authorization_code, the state and any PKCE challenge, as a real provider redirects after consent. The browser flow, including the managed axum-session transaction, therefore runs locally without a login page; Apple’s mock also uses a query string instead of a form post. Mock profiles use the reserved example.invalid email domain. For a real protocol exchange with discovery, one-shot codes and signed ID tokens, use the fixture below.

Signed local OIDC fixture

Enable axum and mount mock_idp::mock_router_with_config only on an exact loopback listener. MockIdpConfig::try_new also rejects non-loopback issuer and callback URLs. The resulting fixture exercises discovery, an exact registered client/callback, expiring one-shot authorization codes, optional nonce, S256 PKCE, EdDSA ID-token validation through JWKS and bearer-protected userinfo.

Its signing seed and credentials are deterministic public test material. It is not a production identity provider, interactive login/consent UI, refresh-token service, federation implementation or OIDC conformance suite. Follow the local OIDC testing tutorial for a complete loopback setup.

Explicit corporate proxy

Live providers can receive a first-class proxy-aware transport without relying on ambient HTTP_PROXY state:

#![allow(unused)]
fn main() {
use rullst_connect::client::ReqwestClient;
use rullst_connect::prelude::{ConnectError, GithubProvider};
use std::sync::Arc;

fn github_through_corporate_proxy(
    proxy_password: impl Into<String>,
) -> Result<GithubProvider, ConnectError> {
    let proxy = ReqwestClient::try_with_proxy_basic_auth(
        "https://proxy.corp.example:8443",
        "proxy-user",
        proxy_password,
    )?;
    let github = GithubProvider::try_new(
        "YOUR_CLIENT_ID",
        "YOUR_CLIENT_SECRET".to_string().into(),
        "http://localhost:3000/auth/github/callback",
    )?;
    Ok(github.with_http_client(Arc::new(proxy)))
}
}

With the retry feature, a provider’s with_retry replaces its transport with a new direct client, so call it before with_http_client, or not at all: the proxy constructors already apply the bounded retry policy.

OidcProvider::discover fetches its metadata before with_http_client can apply, so pass the proxy client to OidcProvider::discover_with_client instead (added in v13); discovery, JWKS and token calls then share it.

Proxy URLs are limited to an HTTP(S) scheme and authority, with no embedded credentials, path, query, or fragment. Authenticated non-loopback proxies must use HTTPS. The configured client uses only that explicit proxy; PAC/WPAD, SOCKS, proxy mTLS identity and deployment certification remain outside this bounded transport.

2. Start a Server-Bound Authorization

A Rullst application signs users in with its own encrypted session cookie and has no tower-sessions store. For it, rullst_connect::challenge keeps each attempt in a ChallengeStore (v13, 13.0.0-alpha.3): begin_login stores the state, PKCE verifier, nonce and an optional same-site return page and returns the redirect plus an opaque id for a ChallengeCookie; finish_login consumes the challenge once, compares the state in constant time and exchanges the code with the stored verifier and nonce:

#![allow(unused)]
fn main() {
use rullst_connect::challenge::{LoginOptions, LoginRedirect, MemoryChallengeStore, begin_login};
use rullst_connect::challenge::LoginError;
use rullst_connect::providers::GoogleProvider;

async fn start_google(
    store: &MemoryChallengeStore,
    google: &GoogleProvider,
) -> Result<LoginRedirect, LoginError> {
    // Redirect to `url()` and set `set_cookie(&ChallengeCookie::new("/auth/google", secure)?)`.
    begin_login(store, google, LoginOptions::oidc("google")).await
}
}

SqlChallengeStore::open(pool, max_entries) stores them in the application’s SQLite, PostgreSQL or MySQL database instead (features sqlite, postgres, mysql), consuming each row with one atomic statement or transaction. cargo rullst make:oauth google|github|microsoft|apple generates the handlers, account linking and sign-in for a Rullst application: the accounts of cargo rullst auth or the SaaS starter, or an application’s own sign-in through its authentication contract. A provider that POSTs the callback from its own site, such as Sign in with Apple, needs ChallengeCookie::for_cross_site_post (SameSite=None; Secure): browsers attach no SameSite=Lax cookie to that POST. See Tutorial 42.

The axum-session path generates state and PKCE, stores their private counterparts in tower-sessions for ten minutes, and returns only the redirect URL:

#![allow(unused)]
fn main() {
use axum::response::Redirect;
use rullst_connect::prelude::{ConnectError, GithubProvider};
use rullst_connect::extractors::begin_oauth_session;
use tower_sessions::Session;

async fn start_github_authorization(
    session: &Session,
    github: &GithubProvider,
) -> Result<Redirect, ConnectError> {
    let authorization = begin_oauth_session(session, github).await?;
    Ok(Redirect::temporary(authorization.url()))
}
}

Use begin_oidc_session instead for Google or a custom OIDC provider. It adds and stores an OIDC nonce as well.

Sign in with Apple is different: AppleProvider always requests response_mode=form_post, so Apple returns code, state and id_token in a cross-site POST body. AuthSession reads only the query string, and a SameSite=Lax or Strict session cookie is not sent on that POST, so the managed begin_oidc_session + AuthSession flow cannot complete an Apple login. In v13, use the store-backed login above with ChallengeCookie::for_cross_site_post, or AuthSessionForm below. The manual state/PKCE/nonce flow with a dedicated SameSite=None; Secure; HttpOnly challenge cookie, described in Sign in with Apple: form POST callback, also works and is the only option on 12.x.

v13 (since 13.0.0-alpha.1) adds AuthSessionForm, which consumes the begin_oidc_session challenge from the form POST body (at most 16 KiB). The session cookie that holds that challenge must still be SameSite=None; Secure, so give the Apple routes their own session layer.

3. Consume the Callback and Get the User

AuthSession consumes the challenge before checking its expiry and state. It then supplies the exact PKCE verifier and optional OIDC nonce to the provider:

#![allow(unused)]
fn main() {
use rullst_connect::extractors::AuthSession;
use rullst_connect::prelude::{
    ConnectError, GithubProvider, Provider as _, UniversalProfile,
};

async fn finish_github_callback(
    auth_session: AuthSession,
    github: &GithubProvider,
) -> Result<UniversalProfile, ConnectError> {
    let params = auth_session.exchange_params()?;
    let user = github.get_user(params).await?;
    Ok(user.universal_profile())
}
}

Only one managed challenge is active per browser session. Starting another login deliberately invalidates the earlier tab. The application must configure a durable production session store, Secure/HttpOnly/SameSite cookies, TLS, registered redirect URLs, account-linking policy, and post-login session rotation. See Server-Bound OAuth/OIDC Sessions.

Deprecated oauth_state fallback. When the session holds no challenge from begin_oauth_session or begin_oidc_session, AuthSession and AuthSessionForm still accept a state that the application stored itself under the oauth_state session key, as applications did before 12.0. It is consumed once and compared in constant time, but it has no expiry, PKCE verifier or OIDC nonce. Since 13.0.0-rc.1 each callback that uses it logs a tracing warning (without the state); the fallback is kept through 13.x. Start the login with begin_oauth_session or begin_oidc_session instead, or use begin_login and finish_login above.

🛡️ Manual State Handling

Non-Axum hosts may use the framework-neutral primitives directly. The host must atomically take the expected value from a short-lived server-side store before comparison; a reusable cookie value is not equivalent.

The following fragment is host pseudocode because the durable one-time store and callback extractor are deliberately application-provided:

use rullst_connect::pkce::generate_oauth_state;

let state = generate_oauth_state();
store_one_time_state(&state).await?; // application-provided durable operation
let url = github.redirect_url_with_state(&state);

let expected = take_one_time_state().await?; // atomically removes it
callback.verify_state(&expected)?;

🔄 Refreshing Tokens

If the provider returned expires_in plus a refresh token, bind the result to a statically dispatched, process-local coordinator when the callback receives it:

#![allow(unused)]
fn main() {
use rullst_connect::{AutoRefreshingSession, ConnectError, ConnectUser};
use rullst_connect::prelude::ExposeSecret as _;

async fn send_token_to_the_authorized_api(_: &str) -> Result<(), ConnectError> {
    Ok(())
}

async fn call_provider_api(
    github: &rullst_connect::providers::GithubProvider,
    user: &ConnectUser,
    token_received_at: u64,
) -> Result<(), ConnectError> {
    let session = AutoRefreshingSession::from_user_at(
        github,
        user,
        token_received_at,
    )?;
    let lease = session.access_token().await?;
    send_token_to_the_authorized_api(lease.access_token().expose_secret()).await?;
    Ok(())
}
}

The default checks 60 seconds before expiration. Refresh calls cannot overlap; callers waiting behind a successful refresh reuse its state. A response replaces the access token only after the lifetime and original provider user ID validate. If a response for the original user is otherwise rejected (for example it omits expires_in), its rotated refresh token is still kept and the generation advances, because the provider has already consumed the prior one; the call fails and the next call refreshes with the rotation. The same applies when the grant succeeds but the follow-up profile lookup or ID-token validation fails: provider adapters then return ConnectError::RefreshIncomplete (added in v13), whose IssuedTokens carry the new tokens to direct Provider::refresh_token callers, and the session keeps the rotation and returns the underlying error. Persist the snapshot after such a failure too.

Do not cancel access_token() while it refreshes. The provider call runs inside the caller’s future, so dropping that future (a client disconnect, a tower timeout layer or tokio::select!) after the provider accepted the grant discards its response: a provider that rotates or consumes refresh tokens has then spent the credential this session still holds, and the next refresh fails with invalid_grant (Auth0 rotation may also revoke the token family). Drive refreshes from a task that is not cancelled with the request, or treat such an invalid_grant as a reauthentication signal.

Use access_token_at in deterministic workers/tests. Seal state_snapshot() with EncryptedTokenSnapshot before writing it to a dedicated application store:

#![allow(unused)]
fn main() {
use rullst_connect::{
    EncryptedTokenSnapshot, RefreshableTokenState, TokenSnapshotBinding,
    TokenSnapshotError, TokenSnapshotKey,
};

fn seal_for_storage(
    state: &RefreshableTokenState,
    key_bytes: [u8; 32],
    local_account_id: &str,
) -> Result<EncryptedTokenSnapshot, TokenSnapshotError> {
    let binding = TokenSnapshotBinding::try_new("github", local_account_id)?;
    let key = TokenSnapshotKey::try_new("oauth-primary-2026", key_bytes)?;
    EncryptedTokenSnapshot::seal(state, &key, &binding)
}
}

Persist only snapshot.as_str(). On restart, validate it with try_from_envelope, select the secret-manager key named by key_id(), and call open with the same trusted binding. Keys must be 32 bytes from a secret manager or CSPRNG; human passwords require an application-selected KDF. The envelope authenticates confidentiality, ownership binding and generation but does not provide a database transaction by itself.

Durable shared-local SQLite state

Enable rullst-connect/sqlite (or umbrella rullst/oauth-sqlite) to store the encrypted generations in one local SQLite file:

#![allow(unused)]
fn main() {
use rullst_connect::{
    RefreshableTokenState, SqliteTokenSnapshotStore, TokenSnapshotBinding,
    TokenSnapshotKey, TokenStoreError,
};

async fn persist_initial_generation(
    state: &RefreshableTokenState,
    key: &TokenSnapshotKey,
    account_id: &str,
) -> Result<(), TokenStoreError> {
    let store = SqliteTokenSnapshotStore::connect(
        "sqlite:///var/lib/my-app/oauth-tokens.sqlite",
        50_000,
    )
    .await?;
    let binding = TokenSnapshotBinding::try_new("github", account_id)?;
    store.insert_initial(&binding, state, key).await?;
    store.close().await;
    Ok(())
}
}

After refreshing from generation n, call compare_and_swap(&binding, n, &replacement, &key). BEGIN IMMEDIATE serializes local writers and only generation n + 1 can replace the observed row. The fixed schema persists its configured 1–1,000,000 row ceiling and restart/key metadata; malformed rows, configuration drift, quota exhaustion and stale replacement/deletion fail with typed redacted errors. The account locator is a SHA-256 pseudonymous digest, not an anonymity guarantee; the provider/account binding is also authenticated inside the ciphertext.

This local CAS does not serialize the earlier call to a remote OAuth provider. Applications must still authorize the account, lease that remote operation, reconcile a provider rotation lost to CAS, configure retry/backoff and local logout, keep keys in a secret manager, protect/backup the directory and provide multi-host replication when needed. A provider that does not support refresh continues to return a typed error.

🔒 Manual PKCE Support

Provider adapters expose PKCE (Proof Key for Code Exchange) where supported by the provider protocol. Some providers such as X (Twitter) v2 require it; applications must preserve and validate the verifier/state for the complete authorization transaction. The generic provider boundary accepts both values explicitly:

#![allow(unused)]
fn main() {
use rullst_connect::{
    ConnectError, ConnectUser,
    pkce::{generate_oauth_state, generate_pkce},
    provider::{ExchangeParams, Provider},
};

async fn exchange_with_pkce<P: Provider>(
    provider: &P,
    authorization_code: &str,
) -> Result<ConnectUser, ConnectError> {
    let state = generate_oauth_state();
    let (code_verifier, code_challenge) = generate_pkce();

    // Persist state + verifier in a short-lived server-side record before redirecting.
    let authorization_url =
        provider.redirect_url_with_pkce_and_state(&code_challenge, &state);
    let _ = authorization_url;

    // After atomically consuming and validating that state in the callback:
    provider
        .get_user(ExchangeParams::new(authorization_code).with_code_verifier(&code_verifier))
        .await
}
}

🧑‍💻 Full Example with Axum

A complete Axum server is in rullst-connect/examples/axum_server.rs. From the repository root, without provider credentials (the mock feature makes the mock_* fallback credentials sign in offline):

cargo run -p rullst-connect --example axum_server --features axum,mock

📦 Releasing a New Version

Connect is released only through the repository-wide, topologically ordered release workflow. Do not publish this crate independently from a working tree. Follow the release guide and require all candidate-SHA gates before creating a release tag.

🤝 Contributing

Feel free to open Issues and submit Pull Requests! Want to add a new provider? It’s easy! Just implement the Provider trait.

📄 License

This project is licensed under the MIT License.