Files
rust-discovery/crates/oidc-auth/README.md
BuTzZ 6c3203d725
Rust development slice / linux (push) Failing after 1m10s
feat: snapshot Linux-first RMM MVP and pause handover
2026-11-12 22:06:25 +01:00

10 KiB

RMM OIDC authentication adapter (standalone package)

Optional encrypted SQLx/PostgreSQL login-state storage and its migration/permissions contract: POSTGRES.md (postgres-state feature).

This crate is not wired into the server and does not change the root workspace. It authenticates against a configured HTTPS OIDC provider using real RSA signatures, discovery, JWKS and authorization-code exchange. It never grants tenant membership, roles, approval authority or an RMM session by itself. External IdP configuration is currently not_configured; no external-provider or VM acceptance is claimed.

Explicit supported provider profile

  • RS256 only, RSA signing JWKS with unique kid, alg=RS256, use=sig. Mixed-algorithm JWKS are deliberately rejected by this initial strict profile.
  • Configured issuer is the only authority. Discovery's issuer must match exactly; authorization, token and JWKS endpoints must be HTTPS, same origin (including port) as that issuer, with no userinfo, fragment or query. Providers using a separate CDN/origin for JWKS are not supported, rather than automatically trusted.
  • Normal rustls trust roots, optional explicitly provisioned CA roots; no HTTP, insecure certificate mode, HTTP redirects or environment proxy. Administrators must restrict configured issuers/network egress; user input cannot choose issuers.
  • Browser: authorization code, openid, PKCE S256, random nonce/state/browser binding, fixed registered HTTPS callback, client_secret_post. The IdP must advertise these features. PKCE rejection surfaces as CodeExchange; response bodies are not logged.
  • MCP: RFC 9068 JWT access token with typ=at+jwt, dedicated resource audience, approved client_id, required jti, issuer/signature/expiry/nbf/iat checks, required scopes. Opaque/introspected tokens and other JWT access-token profiles are unsupported. Browser ID tokens are never accepted as bearer credentials.
  • JWT validity uses zero clock leeway; synchronize clocks. Browser multiple audiences require matching azp; any supplied browser azp must match the browser client ID.
  • JWKS cache TTL 300 seconds; unknown-kid refresh throttled to once per second, serialized across callers. A newly rotated key may require retry after one second. Invalid JWKS/failed refresh clears the old key cache and fails closed. Revocation of a cached key is bounded by the TTL, not instantaneous. Issuer operator must rotate to a new kid (same-kid replacement is visible on the next TTL refresh).
  • HTTP connect timeout 3 seconds, total request timeout 10 seconds, response 128 KiB, JWT 32 KiB, code 4 KiB, maximum 64 signing keys. No refresh-token persistence.

Public integration API

let auth = OidcAuth::discover(
    Config {
        issuer: Url::parse("https://idp.example/realms/rmm")?,
        browser_client_id: "rmm-browser".into(),
        client_secret_ref: "secret-store:rmm/oidc-client".into(),
        redirect_uri: Url::parse("https://rmm.example/auth/oidc/callback")?,
        mcp_audience: "https://rmm.example/mcp".into(),
        mcp_client_ids: BTreeSet::from(["approved-mcp-client".into()]),
    },
    Profile::Production,
    persistent_state_store,
    secret_resolver,
    vec![], // normal roots; provision a private CA explicitly if necessary
).await?;
let start: LoginStart = auth.login_start().await?;
// Set start.binding_set_cookie and redirect to start.authorization_url.
let identity: Identity = auth.callback(Callback {
    code: parsed_query_code,
    state: parsed_query_state,
    browser_binding: parsed_host_binding_cookie,
}).await?;
let bearer: BearerIdentity = auth
    .verify_mcp_bearer(raw_bearer, &["inventory:read"]).await?;

SecretResolver::resolve(reference) returns secrecy::SecretString; resolve from an authorized secret store, never from a token claim. The adapter exposes only coarse typed Errors, not reqwest errors (which may contain URLs), codes or token bodies. Do not log callback URLs, authorization URLs, cookies, state records, secrets or JWTs. Sensitive flow types intentionally do not implement Debug.

Required server/cookie adapter work (not implemented here)

  1. Register login start and GET callback routes. Rate-limit both; do not allow caller-supplied issuer, audience, scopes, redirect URI or post-login return URL. Reject duplicate query/cookie parameters and provider error callbacks. Return Cache-Control: no-store and Referrer-Policy: no-referrer on all auth routes; avoid request/query logging and third-party resources there.
  2. Set LoginStart.binding_set_cookie verbatim: __Host-rmm_oidc_binding, Secure, HttpOnly, Path=/, SameSite=Lax, Max-Age=300, no Domain. Strict would omit this cookie on the cross-site provider callback. Start replaces an outstanding binding; multi-tab login is intentionally fail-closed, not a bypass.
  3. Pass only parsed code/state and binding cookie value to callback. The store must atomically consume state before token exchange. On terminal callback success or failure, clear binding with CLEAR_BINDING_COOKIE; failures require fresh login.
  4. Resolve Identity { issuer, subject } to a persistent principal and current scoped memberships. Email and untrusted group/role claims are not identity keys or memberships (this crate does not expose them). No implicit all-tenant role.
  5. On browser success only, rotate/create a new opaque RMM session, bound to that principal, with bounded expiry and the existing Secure/HttpOnly/host-only SameSite=Strict final session cookie. Keep CSRF token + exact Origin checks for writes, authorization checks and explicit UI plan approval. An ID token is not an RMM session cookie or permission to approve a plan.
  6. Bearer always wins over browser cookies. Use verify_mcp_bearer only for MCP/API bearer paths; combine returned scopes with persistent memberships on every request. Never construct an interactive browser session or approval context from a bearer token, even if a principal has an approver membership. Preserve pending_approval and all immutable plan/attempt bindings.
  7. Logout must invalidate the server-side RMM session, clear the final cookie, require its normal CSRF/Origin checks and prevent reuse. IdP logout is intentionally not implemented or falsely advertised; local logout does not end an IdP session.
  8. Disable dev identities/simulated principals in production independently of this crate. Existing dev identity auth is not replaced until the backend is integrated.

Persistent state store port

Alternative adapters must implement async StateStore::{insert, consume} plus is_persistent() == true using shared durable storage. Do not merely return true for a memory-backed adapter. State lookup keys and browser bindings supplied to the store are SHA-256 base64url hashes; records contain nonce, verifier and absolute Unix expiry. Protect record contents at rest and restrict database access. insert must enforce unique keys, bounded capacity and expiry cleanup. consume must perform one atomic conditional delete/return based on (state_hash, binding_hash, expires_at > now); no read-then- delete race, no restoration after exchange/nonce failure. A SQL transaction or DELETE ... WHERE ... RETURNING is suitable. Store failures must fail closed.

dev::InMemoryStateStore::new(dev::DevTestOnly) exists only under the explicit dev-memory-store feature or unit tests. Profile::Production rejects it. This is not a production SQL adapter. The optional PostgreSQL adapter below supplies durable encrypted storage; applying its migration and server wiring remain integration work.

Targeted local verification

cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check
cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings
cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features

Tests run a native loopback HTTPS OIDC provider with an ephemeral private CA, real 2048-bit RSA signing keys/JWKS, actual one-use authorization codes, real form-encoded token exchange and server-enforced PKCE. The CA is added only to the test clients, never to the host truststore. No checked-in private key, external IdP, VM modification, host-service installation, Docker/server restart or reboot is needed. The provider is a test double, not a claim of external-provider interoperability or VM acceptance. Test assertions/counters contain no secret output. Run results are reported separately by the implementation dispatch, not presumed by these commands.

Actual local verification (2026-11-12)

Executed on the development Linux host, not the Linux test VM:

  • cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check: passed.
  • cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings: passed.
  • cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked: 13 passed, 0 failed; 0 documentation tests. Covers real code exchange, browser binding/replay/expiry/concurrency, PKCE failure, nonce/authorized party, issuer/audience/expiry/nbf/iat/required claims/scopes, algorithm/signature/ID-token confusion, JWKS caching/rotation, actual TLS trust/hostname rejection, discovery origin restrictions, HTTP redirect rejection and response/token size limits.
  • cargo metadata --manifest-path crates/oidc-auth/Cargo.toml --no-deps --format-version 1: independent workspace at crates/oidc-auth, exactly one member and own lockfile.

Initial build checks found missing URL serde and JWT PEM feature flags; both were fixed. Clippy found an unnecessary test format!, also fixed. The final commands above passed after those corrections. Pinned lockfile resolves jsonwebtoken 10.4.0, reqwest 0.12.28 and rustls 0.23.46 on the repository's Rust 1.99.1 toolchain.

Not executed in that initial verification: external real-IdP interoperability, production SQL state adapter, server routes/cookies/sessions/membership integration, VM execution or browser UI login against the running RMM server. Timeout values are configured; a deliberately stalling provider timeout test has not been run. No production acceptance claimed.