feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target/
|
||||
Generated
+2748
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "rmm-oidc-auth"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
dev-memory-store = []
|
||||
postgres-state = ["dep:sqlx", "dep:aes-gcm"]
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1"
|
||||
aes-gcm = { version = "0.10", optional = true }
|
||||
base64 = "0.22"
|
||||
jsonwebtoken = { version = "10", default-features = false, features = ["rust_crypto", "use_pem"] }
|
||||
rand = "0.9"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] }
|
||||
secrecy = "0.10"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
subtle = "2"
|
||||
sqlx = { version = "0.8", optional = true, default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["sync", "time"] }
|
||||
url = { version = "2", features = ["serde"] }
|
||||
zeroize = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
openssl = "0.10"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
serde_urlencoded = "0.7"
|
||||
@@ -0,0 +1,172 @@
|
||||
# PostgreSQL pre-auth state adapter
|
||||
|
||||
Enable package feature **`postgres-state`**. Dependencies: SQLx 0.8 (PostgreSQL and
|
||||
Tokio/rustls only; no macros/automatic migrations), RustCrypto `aes-gcm` 0.10.
|
||||
The default build still has no SQL dependency. No root-workspace changes are needed.
|
||||
|
||||
## Migration and least privilege
|
||||
|
||||
Export: `rmm_oidc_auth::postgres::MIGRATION_SQL`, exactly the package-owned file
|
||||
`sql/001_oidc_login_states.sql`. Transfer this SQL into a future **normal server
|
||||
migration** under the migration/owner identity; the adapter never runs it. It is
|
||||
deliberately not idempotent and creates a dedicated schema/table:
|
||||
|
||||
`rmm_oidc_auth.login_states(state_hash bytea PRIMARY KEY, binding_hash bytea,
|
||||
expires_at bigint, created_at bigint, encryption_key_ref text,
|
||||
encryption_nonce bytea, ciphertext bytea)` plus expiry index and integrity checks.
|
||||
|
||||
This is **global PREAUTH state**, not tenant data: no tenant IDs, principal IDs,
|
||||
memberships or user attributes. Use a separate global-auth-service pool/role, not a
|
||||
tenant transaction with previous RLS context. Grant only:
|
||||
|
||||
```sql
|
||||
GRANT USAGE ON SCHEMA rmm_oidc_auth TO your_auth_service_runtime_role;
|
||||
GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO your_auth_service_runtime_role;
|
||||
```
|
||||
|
||||
Replace the example role identifier through the normal deployment configuration,
|
||||
not a request parameter. Runtime must be **non-owner, NOSUPERUSER, NOBYPASSRLS**,
|
||||
without schema CREATE, UPDATE, TRUNCATE, tenant-table or migration permissions.
|
||||
No RLS bypass is needed: the global table intentionally has no tenant RLS policy.
|
||||
Membership and approval checks remain in the tenant-bound application layer.
|
||||
Use verified PostgreSQL TLS for remote databases and restricted local transport
|
||||
where appropriate. Never print DB URLs/passwords or enable parameter logging.
|
||||
|
||||
## Configuration and public API
|
||||
|
||||
```rust,ignore
|
||||
use rmm_oidc_auth::postgres::PostgresStateStore;
|
||||
|
||||
// Pool supplied by the backend with the dedicated restricted global-auth role.
|
||||
// Configure bounded acquisition timeout (e.g. 5 seconds) and pool size there.
|
||||
let state_store = PostgresStateStore::new(
|
||||
global_auth_pool,
|
||||
secret_resolver.as_ref(),
|
||||
"secret-store:rmm/oidc-state-key/version-1".into(),
|
||||
10_000, // global outstanding-state capacity, including expired rows
|
||||
).await?;
|
||||
// Pass Arc::new(state_store) as the unchanged StateStore port to
|
||||
// OidcAuth::discover(..., Profile::Production, ..., ...).
|
||||
```
|
||||
|
||||
`PostgresStateStore::new(PgPool, &dyn SecretResolver, key_ref: String,
|
||||
capacity: u32) -> Result<Self>` resolves exactly the configured reference, once.
|
||||
The secret is **32 cryptographically random bytes encoded as unpadded base64url**.
|
||||
Do not derive it from a password, the OIDC client secret, or a token claim. The
|
||||
reference must identify an **immutable version**, not a mutable `latest` alias.
|
||||
Store the key outside PostgreSQL and backups of login-state ciphertext. Ref strings
|
||||
are metadata, not secret values. Never log the resolved key.
|
||||
|
||||
The library does not automatically read environment configuration. A backend may
|
||||
map e.g. `RMM_OIDC_STATE_BACKEND=postgres`, `RMM_OIDC_STATE_KEY_REF` and a private DB
|
||||
connection reference to this constructor; these are integration examples, not
|
||||
implemented server flags. Missing/invalid configuration must fail startup closed.
|
||||
`is_persistent()` is true for this adapter; `Profile::Production` continues rejecting
|
||||
the memory adapter independently. No production in-memory fallback is provided.
|
||||
|
||||
## Confidentiality, atomicity and lifetime
|
||||
|
||||
- The existing flow generates 256-bit opaque state/binding values and passes only
|
||||
canonical SHA-256 base64url hashes to `StateStore`. PostgreSQL stores their decoded
|
||||
**32-byte digests**, not raw handles/cookies. Nonce and verifier are validated as
|
||||
canonical 32-byte random-value encodings before persistence.
|
||||
- The complete `PendingLogin` JSON is encrypted with **AES-256-GCM**, a fresh random
|
||||
96-bit encryption nonce and authenticated associated data binding a fixed format
|
||||
domain/version, state hash, browser-binding hash, expiry and configured key ref.
|
||||
Plaintext serialization/decryption buffers and resolved key bytes are zeroized.
|
||||
The store, pending records and key material have no Debug/log implementation.
|
||||
Hashes, expiry, version reference and ciphertext length remain DB-visible.
|
||||
A privileged DBA can delete/deny service, but cannot forge a valid encrypted login
|
||||
without the external key. Protect the auth-service process and secret resolver.
|
||||
- Insertion refuses expired states, TTL above **300 seconds**, duplicates and
|
||||
capacity outside 1..=100,000. Database checks independently bound expiry relative
|
||||
to creation (600 seconds for clock skew); DB clock also rejects expired insertions.
|
||||
- A transaction-scoped, database-local advisory lock serializes admission checks
|
||||
across adapter instances. A fresh READ COMMITTED snapshot prevents capacity races,
|
||||
even on pools with a different default isolation level. All instances sharing a
|
||||
table must use the **same capacity policy**. No upsert/overwrite path exists.
|
||||
- Consumption is one parameterized **`DELETE ... WHERE state_hash=$1 AND
|
||||
binding_hash=$2 AND encryption_key_ref=$3 AND expires_at > GREATEST($4, DB_now)
|
||||
RETURNING ...`**. Exactly one concurrent callback receives a record. Wrong binding,
|
||||
wrong key version, missing/replayed or expired state does not delete a valid row.
|
||||
Thus a guessed-handle/wrong-cookie request cannot burn someone else's state.
|
||||
- Delete is committed **before** authenticated decryption/parsing. Corruption,
|
||||
nonce/code-exchange failure or later callback failure never restores state. A
|
||||
connection failure during commit has uncertain delivery and fails closed: restart
|
||||
login, never replay a potentially consumed flow.
|
||||
- `cleanup_expired(batch: u32) -> Result<u64>` deletes only expired rows, at most
|
||||
`batch` (1..=**1,000**), using the expiry index and one atomic CTE/DELETE.
|
||||
It intentionally does not use SELECT FOR UPDATE, which would require granting
|
||||
UPDATE privilege to this read/insert/delete-only role. Concurrent cleanup calls
|
||||
may select the same expired batch; only one deletes it, another may return zero.
|
||||
Call periodically from the global auth service; no background scheduler is spawned.
|
||||
Each adapter transaction uses a 5-second statement timeout and 2-second lock
|
||||
timeout; pool/network timeouts are the backend's connection policy. Expired rows
|
||||
count against capacity until cleaned, deliberately failing closed under overload.
|
||||
Rate-limit login start/callback independently; database capacity is not a rate limit.
|
||||
- Key rotation for this first adapter is **drain then switch**: pause new logins,
|
||||
allow outstanding flows to complete/expire, clean expired rows, switch all instances
|
||||
to a new versioned external key, resume. Do not silently mutate a referenced key or
|
||||
mix key versions during rolling deployment. Rotate well before 2^32 encryptions per
|
||||
key. Old/incompatible ciphertext cannot be accepted by a differently configured key.
|
||||
|
||||
All queries use fixed schema/table names and bound data. No runtime table/schema
|
||||
name interpolation, DDL, role changes, tenant RLS changes or session approvals occur.
|
||||
|
||||
## Explicit real PostgreSQL test
|
||||
|
||||
```sh
|
||||
python3 crates/oidc-auth/tests/run_postgres.py
|
||||
```
|
||||
|
||||
The runner refuses an existing container named **`rust-discovery-oidc-test`**. It
|
||||
creates only that disposable PostgreSQL 17.6 container, publishes an automatically
|
||||
allocated port **only on 127.0.0.1**, generates a private ephemeral password in memory,
|
||||
and removes its own container/anonymous volumes afterwards. Existing PostgreSQL and
|
||||
RMM containers are never inspected for credentials, restarted, migrated or reset.
|
||||
No credential file, stdout secret, host service package or VM change is needed.
|
||||
|
||||
The Rust integration test is explicitly ignored in ordinary test runs. The runner
|
||||
opts in with `RMM_OIDC_TEST_ALLOW_OWNER_DDL=isolated` and a private
|
||||
`RMM_OIDC_TEST_DATABASE_URL` passed only through process environment; only the
|
||||
disposable owner test identity applies fixture DDL and creates a separate restricted
|
||||
runtime role. Do not point these variables at a real server database.
|
||||
|
||||
Checks: runtime nonownership/no superuser/no BYPASSRLS/no schema CREATE and actual
|
||||
DDL rejection; encrypted persistence; wrong-cookie non-burning; caller/DB expiry;
|
||||
duplicate/replay rejection; exactly one winner among 16 callbacks; authenticated
|
||||
ciphertext-tamper rejection and consumption; concurrent capacity 2/8; bounded TTL
|
||||
cleanup; invalid hashes/TTL rejection. This is a local native PostgreSQL test, not
|
||||
server/VM or external-IdP acceptance. Actual run results are recorded separately.
|
||||
|
||||
## Actual local verification — 2026-11-12
|
||||
|
||||
Executed on the development Linux host, not the Linux test VM:
|
||||
|
||||
- `cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features --locked -- -D warnings`: passed.
|
||||
- `cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked`:
|
||||
**13 unit tests passed**, 0 failed; the explicit-owner PostgreSQL test is ignored
|
||||
in this general run; 0 documentation tests.
|
||||
- `python3 crates/oidc-auth/tests/run_postgres.py`: **1 actual PostgreSQL integration
|
||||
test passed**, 0 failed, 0 ignored. PostgreSQL 17.6; restricted non-owner role with
|
||||
real DDL/UPDATE rejection; **1/16** concurrent consume winners; **2/8** concurrent
|
||||
capacity admissions. Also checked ciphertext, binding non-burning, DB/caller expiry,
|
||||
duplicates/replay, tamper consumption, cleanup limits, key-version mismatch,
|
||||
invalid key/hash and overlong TTL rejection. Own disposable container removed.
|
||||
- `cargo check --manifest-path crates/oidc-auth/Cargo.toml --lib --no-default-features --locked`: passed.
|
||||
- `cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check`: passed.
|
||||
- `cargo package --manifest-path crates/oidc-auth/Cargo.toml --allow-dirty --features postgres-state --locked`:
|
||||
packaged **11 files** and verified the extracted package build successfully.
|
||||
Non-failing warning: package metadata has no description/documentation/homepage/repository.
|
||||
|
||||
The first Clippy run rejected a deprecated generic-array nonce constructor; replaced
|
||||
with array conversion, no lint suppression. The first real database run reached
|
||||
cleanup but failed there: SELECT FOR UPDATE required UPDATE permission. Cleanup
|
||||
was changed to a bounded atomic CTE/DELETE, retaining the restricted role rather
|
||||
than expanding its privileges. Both subsequent real PostgreSQL runs passed, including
|
||||
the final expanded test. No server DB migration/reset, runtime server restart,
|
||||
membership change, host package installation, VM effect or production acceptance.
|
||||
|
||||
The migration has been applied only to the disposable test database. Applying it
|
||||
through normal server migrations, provisioning the global auth role/key reference,
|
||||
and wiring backend configuration/routes remain explicit integration work.
|
||||
@@ -0,0 +1,164 @@
|
||||
# RMM OIDC authentication adapter (standalone package)
|
||||
|
||||
Optional encrypted SQLx/PostgreSQL login-state storage and its migration/permissions
|
||||
contract: **[POSTGRES.md](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
|
||||
|
||||
```rust,ignore
|
||||
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 `Error`s, 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
|
||||
|
||||
```sh
|
||||
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.
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Run ONLY through the normal owner/migration identity, never the runtime adapter.
|
||||
-- Global PREAUTH data: no tenant identifiers, memberships or tenant RLS bypass.
|
||||
CREATE SCHEMA rmm_oidc_auth;
|
||||
REVOKE ALL ON SCHEMA rmm_oidc_auth FROM PUBLIC;
|
||||
|
||||
CREATE TABLE rmm_oidc_auth.login_states (
|
||||
state_hash bytea PRIMARY KEY CHECK (octet_length(state_hash) = 32),
|
||||
binding_hash bytea NOT NULL CHECK (octet_length(binding_hash) = 32),
|
||||
expires_at bigint NOT NULL CHECK (expires_at > 0),
|
||||
created_at bigint NOT NULL DEFAULT floor(extract(epoch FROM clock_timestamp()))::bigint,
|
||||
encryption_key_ref text NOT NULL CHECK (length(encryption_key_ref) BETWEEN 1 AND 256),
|
||||
encryption_nonce bytea NOT NULL CHECK (octet_length(encryption_nonce) = 12),
|
||||
ciphertext bytea NOT NULL CHECK (octet_length(ciphertext) BETWEEN 16 AND 4096),
|
||||
CHECK (expires_at > created_at AND expires_at <= created_at + 600)
|
||||
);
|
||||
CREATE INDEX login_states_expiry ON rmm_oidc_auth.login_states (expires_at, state_hash);
|
||||
REVOKE ALL ON rmm_oidc_auth.login_states FROM PUBLIC;
|
||||
|
||||
-- Deployment must explicitly grant its dedicated global auth-service runtime role:
|
||||
-- GRANT USAGE ON SCHEMA rmm_oidc_auth TO <auth_service_runtime_role>;
|
||||
-- GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO <auth_service_runtime_role>;
|
||||
-- Do NOT grant schema CREATE, table ownership, UPDATE, TRUNCATE, superuser,
|
||||
-- BYPASSRLS, tenant-table privileges or general migration privileges to that role.
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Fixed RS256 OIDC browser and RFC 9068 MCP resource-server profiles.
|
||||
//! Authentication only: persistent tenant memberships and interactive sessions belong to the server.
|
||||
use async_trait::async_trait;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use subtle::ConstantTimeEq;
|
||||
use tokio::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
#[cfg(feature = "postgres-state")]
|
||||
pub mod postgres;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
#[error("not_configured or invalid OIDC configuration")]
|
||||
Configuration,
|
||||
#[error("OIDC transport, TLS or bounded response failed")]
|
||||
Transport,
|
||||
#[error("untrusted or unsupported discovery metadata")]
|
||||
Discovery,
|
||||
#[error("invalid JWT")]
|
||||
InvalidToken,
|
||||
#[error("invalid issuer")]
|
||||
InvalidIssuer,
|
||||
#[error("invalid audience or authorized party")]
|
||||
InvalidAudience,
|
||||
#[error("expired token")]
|
||||
Expired,
|
||||
#[error("token not yet valid")]
|
||||
NotYetValid,
|
||||
#[error("unknown signing key")]
|
||||
UnknownKid,
|
||||
#[error("invalid nonce")]
|
||||
Nonce,
|
||||
#[error("invalid, expired, unbound or replayed login state")]
|
||||
State,
|
||||
#[error("authorization code exchange rejected (including PKCE failure)")]
|
||||
CodeExchange,
|
||||
#[error("missing required resource scope")]
|
||||
MissingScope,
|
||||
#[error("state store unavailable or capacity exceeded")]
|
||||
Store,
|
||||
#[error("client secret unavailable")]
|
||||
Secret,
|
||||
}
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
pub issuer: Url,
|
||||
pub browser_client_id: String,
|
||||
pub client_secret_ref: String,
|
||||
pub redirect_uri: Url,
|
||||
/// Dedicated resource audience; MUST differ from the browser client ID.
|
||||
pub mcp_audience: String,
|
||||
/// Explicit authorized OAuth client IDs for the RFC 9068 profile.
|
||||
pub mcp_client_ids: BTreeSet<String>,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Production,
|
||||
DevTest,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait SecretResolver: Send + Sync {
|
||||
async fn resolve(&self, reference: &str) -> Result<SecretString>;
|
||||
}
|
||||
|
||||
/// Store encrypted at rest. No Debug: verifier and nonce are sensitive.
|
||||
#[derive(Serialize, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
|
||||
pub struct PendingLogin {
|
||||
pub binding_hash: String,
|
||||
pub nonce: String,
|
||||
pub pkce_verifier: String,
|
||||
pub expires_at: u64,
|
||||
}
|
||||
#[async_trait]
|
||||
pub trait StateStore: Send + Sync {
|
||||
/// Production adapters must implement durable, shared, atomic storage.
|
||||
fn is_persistent(&self) -> bool;
|
||||
async fn insert(&self, state_hash: String, login: PendingLogin) -> Result<()>;
|
||||
/// Atomically DELETE ... RETURNING only when binding matches and expiry > now.
|
||||
/// Concurrent callbacks must return at most one record. Never restore on failure.
|
||||
async fn consume(&self, state_hash: &str, binding_hash: &str, now: u64)
|
||||
-> Result<PendingLogin>;
|
||||
}
|
||||
|
||||
/// Sensitive URL and cookie: intentionally not Debug/Serialize.
|
||||
pub struct LoginStart {
|
||||
pub authorization_url: Url,
|
||||
/// Set verbatim; Secure, HttpOnly, host-only Lax cookie permits the cross-site GET callback.
|
||||
pub binding_set_cookie: String,
|
||||
}
|
||||
pub struct Callback<'a> {
|
||||
pub code: &'a str,
|
||||
pub state: &'a str,
|
||||
/// Value of __Host-rmm_oidc_binding, NOT the entire Cookie header.
|
||||
pub browser_binding: &'a str,
|
||||
}
|
||||
pub const CLEAR_BINDING_COOKIE: &str =
|
||||
"__Host-rmm_oidc_binding=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Identity {
|
||||
pub issuer: String,
|
||||
pub subject: String,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct BearerIdentity {
|
||||
pub identity: Identity,
|
||||
pub scopes: BTreeSet<String>,
|
||||
pub client_id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Discovery {
|
||||
issuer: String,
|
||||
authorization_endpoint: Url,
|
||||
token_endpoint: Url,
|
||||
jwks_uri: Url,
|
||||
response_types_supported: Vec<String>,
|
||||
id_token_signing_alg_values_supported: Vec<String>,
|
||||
code_challenge_methods_supported: Vec<String>,
|
||||
token_endpoint_auth_methods_supported: Vec<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Jwk {
|
||||
kid: String,
|
||||
kty: String,
|
||||
alg: String,
|
||||
#[serde(rename = "use")]
|
||||
usage: String,
|
||||
n: String,
|
||||
e: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Jwks {
|
||||
keys: Vec<Jwk>,
|
||||
}
|
||||
struct Cache {
|
||||
keys: Vec<Jwk>,
|
||||
fetched: Option<Instant>,
|
||||
}
|
||||
|
||||
pub struct OidcAuth {
|
||||
config: Config,
|
||||
http: reqwest::Client,
|
||||
discovery: Discovery,
|
||||
keys: Mutex<Cache>,
|
||||
store: Arc<dyn StateStore>,
|
||||
secrets: Arc<dyn SecretResolver>,
|
||||
}
|
||||
|
||||
fn https(url: &Url) -> bool {
|
||||
url.scheme() == "https"
|
||||
&& url.host_str().is_some()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.fragment().is_none()
|
||||
}
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
fn random() -> String {
|
||||
URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>())
|
||||
}
|
||||
fn hash(value: &str) -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(value.as_bytes()))
|
||||
}
|
||||
fn equal(a: &str, b: &str) -> bool {
|
||||
bool::from(a.as_bytes().ct_eq(b.as_bytes()))
|
||||
}
|
||||
async fn bounded<T: serde::de::DeserializeOwned>(mut response: reqwest::Response) -> Result<T> {
|
||||
if !response.status().is_success() || response.content_length().is_some_and(|n| n > 131072) {
|
||||
return Err(Error::Transport);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|_| Error::Transport)? {
|
||||
if body.len() + chunk.len() > 131072 {
|
||||
return Err(Error::Transport);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
serde_json::from_slice(&body).map_err(|_| Error::Transport)
|
||||
}
|
||||
|
||||
impl OidcAuth {
|
||||
/// Normal TLS roots; additional roots may be explicitly provisioned for a private IdP.
|
||||
/// No arbitrary HTTP client injection, redirects, environment proxies or insecure TLS switches.
|
||||
pub async fn discover(
|
||||
config: Config,
|
||||
profile: Profile,
|
||||
store: Arc<dyn StateStore>,
|
||||
secrets: Arc<dyn SecretResolver>,
|
||||
extra_roots: Vec<reqwest::Certificate>,
|
||||
) -> Result<Self> {
|
||||
if !https(&config.issuer)
|
||||
|| config.issuer.query().is_some()
|
||||
|| !https(&config.redirect_uri)
|
||||
|| config.redirect_uri.query().is_some()
|
||||
|| config.browser_client_id.is_empty()
|
||||
|| config.client_secret_ref.is_empty()
|
||||
|| config.mcp_audience.is_empty()
|
||||
|| config.mcp_audience == config.browser_client_id
|
||||
|| config.mcp_client_ids.is_empty()
|
||||
|| (profile == Profile::Production && !store.is_persistent())
|
||||
{
|
||||
return Err(Error::Configuration);
|
||||
}
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.https_only(true)
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.connect_timeout(Duration::from_secs(3))
|
||||
.timeout(Duration::from_secs(10));
|
||||
for root in extra_roots {
|
||||
builder = builder.add_root_certificate(root);
|
||||
}
|
||||
let http = builder.build().map_err(|_| Error::Transport)?;
|
||||
let discovery_url = format!(
|
||||
"{}/.well-known/openid-configuration",
|
||||
config.issuer.as_str().trim_end_matches('/')
|
||||
);
|
||||
let discovery: Discovery = bounded(
|
||||
http.get(discovery_url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| Error::Transport)?,
|
||||
)
|
||||
.await?;
|
||||
if discovery.issuer != config.issuer.as_str()
|
||||
|| [
|
||||
&discovery.authorization_endpoint,
|
||||
&discovery.token_endpoint,
|
||||
&discovery.jwks_uri,
|
||||
]
|
||||
.iter()
|
||||
.any(|u| !https(u) || u.origin() != config.issuer.origin() || u.query().is_some())
|
||||
|| !discovery
|
||||
.response_types_supported
|
||||
.iter()
|
||||
.any(|s| s == "code")
|
||||
|| !discovery
|
||||
.id_token_signing_alg_values_supported
|
||||
.iter()
|
||||
.any(|s| s == "RS256")
|
||||
|| !discovery
|
||||
.code_challenge_methods_supported
|
||||
.iter()
|
||||
.any(|s| s == "S256")
|
||||
|| !discovery
|
||||
.token_endpoint_auth_methods_supported
|
||||
.iter()
|
||||
.any(|s| s == "client_secret_post")
|
||||
{
|
||||
return Err(Error::Discovery);
|
||||
}
|
||||
Ok(Self {
|
||||
config,
|
||||
http,
|
||||
discovery,
|
||||
keys: Mutex::new(Cache {
|
||||
keys: vec![],
|
||||
fetched: None,
|
||||
}),
|
||||
store,
|
||||
secrets,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn login_start(&self) -> Result<LoginStart> {
|
||||
let state = random();
|
||||
let binding = random();
|
||||
let nonce = random();
|
||||
let verifier = random();
|
||||
let mut url = self.discovery.authorization_endpoint.clone();
|
||||
url.query_pairs_mut().extend_pairs([
|
||||
("response_type", "code"),
|
||||
("client_id", &self.config.browser_client_id),
|
||||
("redirect_uri", self.config.redirect_uri.as_str()),
|
||||
("scope", "openid"),
|
||||
("state", &state),
|
||||
("nonce", &nonce),
|
||||
("code_challenge", &hash(&verifier)),
|
||||
("code_challenge_method", "S256"),
|
||||
]);
|
||||
self.store
|
||||
.insert(
|
||||
hash(&state),
|
||||
PendingLogin {
|
||||
binding_hash: hash(&binding),
|
||||
nonce,
|
||||
pkce_verifier: verifier,
|
||||
expires_at: now() + 300,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(LoginStart {
|
||||
authorization_url: url,
|
||||
binding_set_cookie: format!(
|
||||
"__Host-rmm_oidc_binding={binding}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=300"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn callback(&self, input: Callback<'_>) -> Result<Identity> {
|
||||
if input.state.len() != 43
|
||||
|| input.browser_binding.len() != 43
|
||||
|| input.code.is_empty()
|
||||
|| input.code.len() > 4096
|
||||
{
|
||||
return Err(Error::State);
|
||||
}
|
||||
let login = self
|
||||
.store
|
||||
.consume(&hash(input.state), &hash(input.browser_binding), now())
|
||||
.await?;
|
||||
if login.expires_at <= now() || !equal(&login.binding_hash, &hash(input.browser_binding)) {
|
||||
return Err(Error::State);
|
||||
}
|
||||
let secret = self.secrets.resolve(&self.config.client_secret_ref).await?;
|
||||
#[derive(Deserialize)]
|
||||
struct Tokens {
|
||||
id_token: String,
|
||||
}
|
||||
let response = self
|
||||
.http
|
||||
.post(self.discovery.token_endpoint.clone())
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("code", input.code),
|
||||
("redirect_uri", self.config.redirect_uri.as_str()),
|
||||
("client_id", &self.config.browser_client_id),
|
||||
("client_secret", secret.expose_secret()),
|
||||
("code_verifier", &login.pkce_verifier),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| Error::Transport)?;
|
||||
if !response.status().is_success() {
|
||||
return Err(Error::CodeExchange);
|
||||
}
|
||||
let tokens: Tokens = bounded(response).await?;
|
||||
let claims = self
|
||||
.verify(&tokens.id_token, &self.config.browser_client_id, false)
|
||||
.await?;
|
||||
if !claims
|
||||
.nonce
|
||||
.as_deref()
|
||||
.is_some_and(|n| equal(n, &login.nonce))
|
||||
{
|
||||
return Err(Error::Nonce);
|
||||
}
|
||||
Ok(self.identity(claims))
|
||||
}
|
||||
|
||||
pub async fn verify_mcp_bearer(
|
||||
&self,
|
||||
token: &str,
|
||||
required_scopes: &[&str],
|
||||
) -> Result<BearerIdentity> {
|
||||
let claims = self.verify(token, &self.config.mcp_audience, true).await?;
|
||||
let client_id = claims
|
||||
.client_id
|
||||
.clone()
|
||||
.filter(|id| self.config.mcp_client_ids.contains(id))
|
||||
.ok_or(Error::InvalidAudience)?;
|
||||
let scopes: BTreeSet<String> = claims
|
||||
.scope
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.split_ascii_whitespace()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if required_scopes.iter().any(|s| !scopes.contains(*s)) {
|
||||
return Err(Error::MissingScope);
|
||||
}
|
||||
Ok(BearerIdentity {
|
||||
identity: self.identity(claims),
|
||||
scopes,
|
||||
client_id,
|
||||
})
|
||||
}
|
||||
fn identity(&self, claims: Claims) -> Identity {
|
||||
Identity {
|
||||
issuer: self.config.issuer.to_string(),
|
||||
subject: claims.sub,
|
||||
}
|
||||
}
|
||||
|
||||
async fn verify(&self, token: &str, audience: &str, access: bool) -> Result<Claims> {
|
||||
if token.len() > 32768 {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
let header = decode_header(token).map_err(|_| Error::InvalidToken)?;
|
||||
if header.alg != Algorithm::RS256 || (access && header.typ.as_deref() != Some("at+jwt")) {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
let kid = header
|
||||
.kid
|
||||
.filter(|s| !s.is_empty() && s.len() <= 256)
|
||||
.ok_or(Error::UnknownKid)?;
|
||||
// Header kid is only a selector within configured-issuer keys, never a URL/authority.
|
||||
let mut cache = self.keys.lock().await;
|
||||
let unknown = !cache.keys.iter().any(|k| k.kid == kid);
|
||||
let stale = cache
|
||||
.fetched
|
||||
.is_none_or(|t| t.elapsed() >= Duration::from_secs(300));
|
||||
if stale
|
||||
|| (unknown
|
||||
&& cache
|
||||
.fetched
|
||||
.is_some_and(|t| t.elapsed() >= Duration::from_secs(1)))
|
||||
{
|
||||
// Throttle even failed refreshes; one lock prevents concurrent refresh storms.
|
||||
cache.fetched = Some(Instant::now());
|
||||
cache.keys.clear();
|
||||
let jwks: Jwks = bounded(
|
||||
self.http
|
||||
.get(self.discovery.jwks_uri.clone())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| Error::Transport)?,
|
||||
)
|
||||
.await?;
|
||||
let mut ids = BTreeSet::new();
|
||||
if jwks.keys.is_empty()
|
||||
|| jwks.keys.len() > 64
|
||||
|| jwks.keys.iter().any(|k| {
|
||||
!ids.insert(&k.kid) || k.kty != "RSA" || k.alg != "RS256" || k.usage != "sig"
|
||||
})
|
||||
{
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
cache.keys = jwks.keys;
|
||||
}
|
||||
let jwk = cache
|
||||
.keys
|
||||
.iter()
|
||||
.find(|k| k.kid == kid)
|
||||
.ok_or(Error::UnknownKid)?;
|
||||
let key =
|
||||
DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(|_| Error::InvalidToken)?;
|
||||
drop(cache);
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_issuer(&[self.config.issuer.as_str()]);
|
||||
validation.set_audience(&[audience]);
|
||||
validation.set_required_spec_claims(&["exp", "iss", "aud", "sub", "iat"]);
|
||||
validation.leeway = 0;
|
||||
validation.validate_nbf = true;
|
||||
let claims = decode::<Claims>(token, &key, &validation)
|
||||
.map_err(|e| match e.kind() {
|
||||
jsonwebtoken::errors::ErrorKind::InvalidIssuer => Error::InvalidIssuer,
|
||||
jsonwebtoken::errors::ErrorKind::InvalidAudience => Error::InvalidAudience,
|
||||
jsonwebtoken::errors::ErrorKind::ExpiredSignature => Error::Expired,
|
||||
jsonwebtoken::errors::ErrorKind::ImmatureSignature => Error::NotYetValid,
|
||||
_ => Error::InvalidToken,
|
||||
})?
|
||||
.claims;
|
||||
if claims.sub.is_empty() || claims.sub.len() > 1024 || claims.iat > now() {
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
if access
|
||||
&& !claims
|
||||
.jti
|
||||
.as_deref()
|
||||
.is_some_and(|jti| !jti.is_empty() && jti.len() <= 1024)
|
||||
{
|
||||
return Err(Error::InvalidToken);
|
||||
}
|
||||
if !access
|
||||
&& ((claims.aud.len() > 1 && claims.azp.is_none())
|
||||
|| claims
|
||||
.azp
|
||||
.as_deref()
|
||||
.is_some_and(|a| a != self.config.browser_client_id))
|
||||
{
|
||||
return Err(Error::InvalidAudience);
|
||||
}
|
||||
Ok(claims)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
struct Claims {
|
||||
jti: Option<String>,
|
||||
sub: String,
|
||||
#[serde(deserialize_with = "audiences")]
|
||||
aud: Vec<String>,
|
||||
iat: u64,
|
||||
azp: Option<String>,
|
||||
nonce: Option<String>,
|
||||
scope: Option<String>,
|
||||
client_id: Option<String>,
|
||||
}
|
||||
fn audiences<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Aud {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
Ok(match Aud::deserialize(d)? {
|
||||
Aud::One(s) => vec![s],
|
||||
Aud::Many(v) => v,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "dev-memory-store"))]
|
||||
pub mod dev {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
/// Explicit dev/test-only volatile adapter. Rejected by the production constructor.
|
||||
pub struct InMemoryStateStore {
|
||||
records: Mutex<HashMap<String, PendingLogin>>,
|
||||
}
|
||||
impl InMemoryStateStore {
|
||||
pub fn new(_profile: DevTestOnly) -> Self {
|
||||
Self {
|
||||
records: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct DevTestOnly;
|
||||
#[async_trait]
|
||||
impl StateStore for InMemoryStateStore {
|
||||
fn is_persistent(&self) -> bool {
|
||||
false
|
||||
}
|
||||
async fn insert(&self, state: String, login: PendingLogin) -> Result<()> {
|
||||
let mut records = self.records.lock().await;
|
||||
records.retain(|_, v| v.expires_at > now());
|
||||
if records.len() >= 1024 || records.contains_key(&state) {
|
||||
return Err(Error::Store);
|
||||
}
|
||||
records.insert(state, login);
|
||||
Ok(())
|
||||
}
|
||||
async fn consume(&self, state: &str, binding: &str, time: u64) -> Result<PendingLogin> {
|
||||
let mut records = self.records.lock().await;
|
||||
if !records
|
||||
.get(state)
|
||||
.is_some_and(|v| v.expires_at > time && equal(&v.binding_hash, binding))
|
||||
{
|
||||
return Err(Error::State);
|
||||
}
|
||||
records.remove(state).ok_or(Error::State)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,226 @@
|
||||
//! Encrypted, global pre-auth state. No runtime DDL or tenant access.
|
||||
use crate::{Error, PendingLogin, Result, SecretResolver, StateStore, now};
|
||||
use aes_gcm::{
|
||||
Aes256Gcm, KeyInit, Nonce,
|
||||
aead::{Aead, Payload},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use secrecy::ExposeSecret;
|
||||
use sqlx::{PgPool, Row};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub const MIGRATION_SQL: &str = include_str!("../sql/001_oidc_login_states.sql");
|
||||
pub const MAX_LOGIN_TTL_SECONDS: u64 = 300;
|
||||
pub const MAX_CLEANUP_BATCH: u32 = 1000;
|
||||
// App-specific, database-local insertion admission lock; never an authorization bypass.
|
||||
const ADMISSION_LOCK: i64 = 0x524d4d4f49444301;
|
||||
|
||||
/// No Debug: neither pool configuration nor cryptographic material should enter logs.
|
||||
pub struct PostgresStateStore {
|
||||
pool: PgPool,
|
||||
cipher: Aes256Gcm,
|
||||
key_ref: String,
|
||||
capacity: i64,
|
||||
}
|
||||
|
||||
impl PostgresStateStore {
|
||||
/// `key_ref` must be an immutable/versioned secret reference. Its value is exactly
|
||||
/// 32 random bytes encoded as unpadded base64url. Resolve it from outside the DB.
|
||||
/// This constructor does NOT create tables, grant privileges or verify migrations.
|
||||
pub async fn new(
|
||||
pool: PgPool,
|
||||
resolver: &dyn SecretResolver,
|
||||
key_ref: String,
|
||||
capacity: u32,
|
||||
) -> Result<Self> {
|
||||
if key_ref.is_empty() || key_ref.len() > 256 || !(1..=100_000).contains(&capacity) {
|
||||
return Err(Error::Configuration);
|
||||
}
|
||||
let secret = resolver.resolve(&key_ref).await?;
|
||||
let bytes = Zeroizing::new(
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(secret.expose_secret())
|
||||
.map_err(|_| Error::Configuration)?,
|
||||
);
|
||||
let cipher = Aes256Gcm::new_from_slice(&bytes).map_err(|_| Error::Configuration)?;
|
||||
Ok(Self {
|
||||
pool,
|
||||
cipher,
|
||||
key_ref,
|
||||
capacity: i64::from(capacity),
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded, concurrent-safe TTL cleanup. Invoke periodically from the global auth
|
||||
/// service; expired rows also count toward admission capacity until removed.
|
||||
pub async fn cleanup_expired(&self, batch: u32) -> Result<u64> {
|
||||
if batch == 0 || batch > MAX_CLEANUP_BATCH {
|
||||
return Err(Error::Configuration);
|
||||
}
|
||||
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
||||
limits(&mut tx).await?;
|
||||
let result = sqlx::query(
|
||||
"WITH expired AS (SELECT state_hash FROM rmm_oidc_auth.login_states \
|
||||
WHERE expires_at <= floor(extract(epoch FROM clock_timestamp()))::bigint \
|
||||
ORDER BY expires_at, state_hash LIMIT $1) \
|
||||
DELETE FROM rmm_oidc_auth.login_states AS states USING expired \
|
||||
WHERE states.state_hash = expired.state_hash",
|
||||
)
|
||||
.bind(i64::from(batch))
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
tx.commit().await.map_err(|_| Error::Store)?;
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
|
||||
fn aad(&self, state: &[u8], binding: &[u8], expiry: i64) -> Vec<u8> {
|
||||
let mut aad = b"rmm-oidc-preauth-v1\0".to_vec();
|
||||
aad.extend_from_slice(state);
|
||||
aad.extend_from_slice(binding);
|
||||
aad.extend_from_slice(&expiry.to_be_bytes());
|
||||
aad.extend_from_slice(self.key_ref.as_bytes());
|
||||
aad
|
||||
}
|
||||
}
|
||||
|
||||
async fn limits(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
|
||||
// Admission must see a fresh snapshot after waiting for the advisory lock,
|
||||
// even if the caller's pool changes the connection's default isolation level.
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL READ COMMITTED")
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
sqlx::query("SET LOCAL statement_timeout = '5s'")
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
sqlx::query("SET LOCAL lock_timeout = '2s'")
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn digest(value: &str) -> Result<Vec<u8>> {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(value).map_err(|_| Error::State)?;
|
||||
if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
|
||||
return Err(Error::State);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StateStore for PostgresStateStore {
|
||||
fn is_persistent(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
async fn insert(&self, state_hash: String, login: PendingLogin) -> Result<()> {
|
||||
let state = digest(&state_hash)?;
|
||||
let binding = digest(&login.binding_hash)?;
|
||||
let time = now();
|
||||
if login.expires_at <= time
|
||||
|| login.expires_at > time.saturating_add(MAX_LOGIN_TTL_SECONDS)
|
||||
|| digest(&login.nonce).is_err()
|
||||
|| digest(&login.pkce_verifier).is_err()
|
||||
{
|
||||
return Err(Error::State);
|
||||
}
|
||||
let expiry = i64::try_from(login.expires_at).map_err(|_| Error::State)?;
|
||||
let plaintext = Zeroizing::new(serde_json::to_vec(&login).map_err(|_| Error::Store)?);
|
||||
let nonce = rand::random::<[u8; 12]>();
|
||||
let aad = self.aad(&state, &binding, expiry);
|
||||
let ciphertext = self
|
||||
.cipher
|
||||
.encrypt(
|
||||
&Nonce::from(nonce),
|
||||
Payload {
|
||||
msg: &plaintext,
|
||||
aad: &aad,
|
||||
},
|
||||
)
|
||||
.map_err(|_| Error::Store)?;
|
||||
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
||||
limits(&mut tx).await?;
|
||||
// All adapter instances share this lock; concurrent capacity checks cannot race.
|
||||
sqlx::query("SELECT pg_advisory_xact_lock($1)")
|
||||
.bind(ADMISSION_LOCK)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO rmm_oidc_auth.login_states \
|
||||
(state_hash, binding_hash, expires_at, encryption_key_ref, encryption_nonce, ciphertext) \
|
||||
SELECT $1, $2, $3, $4, $5, $6 \
|
||||
WHERE (SELECT count(*) FROM rmm_oidc_auth.login_states) < $7 \
|
||||
AND $3 > floor(extract(epoch FROM clock_timestamp()))::bigint"
|
||||
).bind(&state).bind(&binding).bind(expiry).bind(&self.key_ref).bind(nonce.as_slice()).bind(ciphertext).bind(self.capacity)
|
||||
.execute(&mut *tx).await.map_err(|_| Error::Store)?;
|
||||
if result.rows_affected() != 1 {
|
||||
return Err(Error::Store);
|
||||
}
|
||||
tx.commit().await.map_err(|_| Error::Store)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn consume(
|
||||
&self,
|
||||
state_hash: &str,
|
||||
binding_hash: &str,
|
||||
time: u64,
|
||||
) -> Result<PendingLogin> {
|
||||
let state = digest(state_hash)?;
|
||||
let binding = digest(binding_hash)?;
|
||||
let time = i64::try_from(time).map_err(|_| Error::State)?;
|
||||
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
||||
limits(&mut tx).await?;
|
||||
// The binding predicate is inside DELETE: a wrong-cookie attack cannot burn state.
|
||||
// Server time is authoritative even when a caller supplies an earlier time.
|
||||
let row = sqlx::query(
|
||||
"DELETE FROM rmm_oidc_auth.login_states \
|
||||
WHERE state_hash = $1 AND binding_hash = $2 AND encryption_key_ref = $3 \
|
||||
AND expires_at > GREATEST($4, floor(extract(epoch FROM clock_timestamp()))::bigint) \
|
||||
RETURNING expires_at, encryption_nonce, ciphertext",
|
||||
)
|
||||
.bind(&state)
|
||||
.bind(&binding)
|
||||
.bind(&self.key_ref)
|
||||
.bind(time)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| Error::Store)?;
|
||||
// Commit consumption BEFORE decrypt/parse: never restore after invalid data or callback failure.
|
||||
tx.commit().await.map_err(|_| Error::Store)?;
|
||||
let row = row.ok_or(Error::State)?;
|
||||
let expiry: i64 = row.try_get("expires_at").map_err(|_| Error::Store)?;
|
||||
let nonce: Vec<u8> = row.try_get("encryption_nonce").map_err(|_| Error::Store)?;
|
||||
let ciphertext: Vec<u8> = row.try_get("ciphertext").map_err(|_| Error::Store)?;
|
||||
if nonce.len() != 12 || ciphertext.len() > 4096 {
|
||||
return Err(Error::Store);
|
||||
}
|
||||
let nonce: [u8; 12] = nonce.try_into().map_err(|_| Error::Store)?;
|
||||
let aad = self.aad(&state, &binding, expiry);
|
||||
let plaintext = Zeroizing::new(
|
||||
self.cipher
|
||||
.decrypt(
|
||||
&Nonce::from(nonce),
|
||||
Payload {
|
||||
msg: &ciphertext,
|
||||
aad: &aad,
|
||||
},
|
||||
)
|
||||
.map_err(|_| Error::Store)?,
|
||||
);
|
||||
let login: PendingLogin = serde_json::from_slice(&plaintext).map_err(|_| Error::Store)?;
|
||||
if login.binding_hash != binding_hash
|
||||
|| i64::try_from(login.expires_at).ok() != Some(expiry)
|
||||
|| digest(&login.nonce).is_err()
|
||||
|| digest(&login.pkce_verifier).is_err()
|
||||
{
|
||||
return Err(Error::Store);
|
||||
}
|
||||
Ok(login)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
use super::*;
|
||||
use jsonwebtoken::{EncodingKey, Header, encode};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
bn::{BigNum, MsbOption},
|
||||
hash::MessageDigest,
|
||||
pkey::{PKey, Private},
|
||||
rsa::Rsa,
|
||||
x509::{
|
||||
X509, X509NameBuilder,
|
||||
extension::{BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName},
|
||||
},
|
||||
};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
};
|
||||
|
||||
struct Signing {
|
||||
kid: String,
|
||||
key: PKey<Private>,
|
||||
}
|
||||
impl Signing {
|
||||
fn new(kid: &str) -> Self {
|
||||
Self {
|
||||
kid: kid.into(),
|
||||
key: PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap(),
|
||||
}
|
||||
}
|
||||
fn jwk(&self) -> Value {
|
||||
let rsa = self.key.rsa().unwrap();
|
||||
json!({"kid":self.kid,"alg":"RS256","kty":"RSA","use":"sig", "n":URL_SAFE_NO_PAD.encode(rsa.n().to_vec()),"e":URL_SAFE_NO_PAD.encode(rsa.e().to_vec())})
|
||||
}
|
||||
fn token(&self, claims: &Value, access: bool) -> String {
|
||||
let mut header = Header::new(Algorithm::RS256);
|
||||
header.kid = Some(self.kid.clone());
|
||||
header.typ = Some(if access { "at+jwt" } else { "JWT" }.into());
|
||||
encode(
|
||||
&header,
|
||||
claims,
|
||||
&EncodingKey::from_rsa_pem(&self.key.private_key_to_pem_pkcs8().unwrap()).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
struct Code {
|
||||
challenge: String,
|
||||
nonce: String,
|
||||
redirect: String,
|
||||
}
|
||||
struct Mock {
|
||||
issuer: String,
|
||||
signing: Mutex<Signing>,
|
||||
codes: Mutex<HashMap<String, Code>>,
|
||||
jwks_calls: AtomicUsize,
|
||||
exchanges: AtomicUsize,
|
||||
mutate: Mutex<Option<(&'static str, Value)>>,
|
||||
discovery_override: Mutex<Option<Value>>,
|
||||
response_override: Mutex<Option<ResponseOverride>>,
|
||||
unexpected_calls: AtomicUsize,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct ResponseOverride {
|
||||
path: String,
|
||||
status: &'static str,
|
||||
location: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
struct Provider {
|
||||
state: Arc<Mock>,
|
||||
root: reqwest::Certificate,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Drop for Provider {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
fn certificates() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||
let ca_key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "Ephemeral OIDC test CA")
|
||||
.unwrap();
|
||||
let name = name.build();
|
||||
let mut ca = X509::builder().unwrap();
|
||||
ca.set_version(2).unwrap();
|
||||
let mut serial = BigNum::new().unwrap();
|
||||
serial.rand(128, MsbOption::MAYBE_ZERO, false).unwrap();
|
||||
let serial = serial.to_asn1_integer().unwrap();
|
||||
ca.set_serial_number(&serial).unwrap();
|
||||
ca.set_subject_name(&name).unwrap();
|
||||
ca.set_issuer_name(&name).unwrap();
|
||||
ca.set_pubkey(&ca_key).unwrap();
|
||||
ca.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
ca.set_not_after(&Asn1Time::days_from_now(1).unwrap())
|
||||
.unwrap();
|
||||
ca.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
||||
.unwrap();
|
||||
ca.append_extension(
|
||||
KeyUsage::new()
|
||||
.critical()
|
||||
.key_cert_sign()
|
||||
.crl_sign()
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
ca.sign(&ca_key, MessageDigest::sha256()).unwrap();
|
||||
let ca = ca.build();
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut leaf = X509::builder().unwrap();
|
||||
leaf.set_version(2).unwrap();
|
||||
leaf.set_serial_number(&serial).unwrap();
|
||||
leaf.set_subject_name(&name).unwrap();
|
||||
leaf.set_issuer_name(ca.subject_name()).unwrap();
|
||||
leaf.set_pubkey(&key).unwrap();
|
||||
leaf.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
leaf.set_not_after(&Asn1Time::days_from_now(1).unwrap())
|
||||
.unwrap();
|
||||
leaf.append_extension(BasicConstraints::new().critical().build().unwrap())
|
||||
.unwrap();
|
||||
leaf.append_extension(
|
||||
KeyUsage::new()
|
||||
.critical()
|
||||
.digital_signature()
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
leaf.append_extension(ExtendedKeyUsage::new().server_auth().build().unwrap())
|
||||
.unwrap();
|
||||
let san = SubjectAlternativeName::new()
|
||||
.dns("localhost")
|
||||
.build(&leaf.x509v3_context(Some(&ca), None))
|
||||
.unwrap();
|
||||
leaf.append_extension(san).unwrap();
|
||||
leaf.sign(&ca_key, MessageDigest::sha256()).unwrap();
|
||||
(
|
||||
ca.to_pem().unwrap(),
|
||||
leaf.build().to_der().unwrap(),
|
||||
key.private_key_to_pkcs8().unwrap(),
|
||||
)
|
||||
}
|
||||
impl Provider {
|
||||
async fn start() -> Self {
|
||||
let (ca, cert, key) = certificates();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let config = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(
|
||||
vec![CertificateDer::from(cert)],
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key)),
|
||||
)
|
||||
.unwrap();
|
||||
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
|
||||
let state = Arc::new(Mock {
|
||||
issuer: format!("https://localhost:{port}/"),
|
||||
signing: Mutex::new(Signing::new("first")),
|
||||
codes: Mutex::new(HashMap::new()),
|
||||
jwks_calls: AtomicUsize::new(0),
|
||||
exchanges: AtomicUsize::new(0),
|
||||
mutate: Mutex::new(None),
|
||||
discovery_override: Mutex::new(None),
|
||||
response_override: Mutex::new(None),
|
||||
unexpected_calls: AtomicUsize::new(0),
|
||||
});
|
||||
let server_state = state.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let acceptor = acceptor.clone();
|
||||
let state = server_state.clone();
|
||||
tokio::spawn(async move {
|
||||
let Ok(mut stream) = acceptor.accept(socket).await else {
|
||||
return;
|
||||
};
|
||||
let mut request = vec![];
|
||||
let mut chunk = [0u8; 4096];
|
||||
let (head_end, length) = loop {
|
||||
let n = stream.read(&mut chunk).await.unwrap_or(0);
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
request.extend_from_slice(&chunk[..n]);
|
||||
if request.len() > 32768 {
|
||||
return;
|
||||
}
|
||||
if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]);
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
line.to_ascii_lowercase()
|
||||
.strip_prefix("content-length:")
|
||||
.and_then(|s| s.trim().parse::<usize>().ok())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
break (end + 4, length);
|
||||
}
|
||||
};
|
||||
while request.len() < head_end + length {
|
||||
let n = stream.read(&mut chunk).await.unwrap_or(0);
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
request.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
let first = String::from_utf8_lossy(&request[..head_end]);
|
||||
let target = first.split_whitespace().nth(1).unwrap();
|
||||
let url =
|
||||
Url::parse(&format!("{}{}", state.issuer.trim_end_matches('/'), target))
|
||||
.unwrap();
|
||||
let (status, location, body) = state
|
||||
.respond(url, &request[head_end..head_end + length])
|
||||
.await;
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{}\r\n{body}",
|
||||
body.len(),
|
||||
location
|
||||
.map(|l| format!("Location: {l}\r\n"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
let _ = stream.shutdown().await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Self {
|
||||
state,
|
||||
root: reqwest::Certificate::from_pem(&ca).unwrap(),
|
||||
task,
|
||||
}
|
||||
}
|
||||
fn config(&self) -> Config {
|
||||
Config {
|
||||
issuer: Url::parse(&self.state.issuer).unwrap(),
|
||||
browser_client_id: "browser".into(),
|
||||
client_secret_ref: "test-only-secret-reference".into(),
|
||||
redirect_uri: Url::parse("https://rmm.example/callback").unwrap(),
|
||||
mcp_audience: "https://rmm.example/mcp".into(),
|
||||
mcp_client_ids: BTreeSet::from(["mcp-client".into()]),
|
||||
}
|
||||
}
|
||||
async fn auth(&self) -> OidcAuth {
|
||||
OidcAuth::discover(
|
||||
self.config(),
|
||||
Profile::DevTest,
|
||||
Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly)),
|
||||
Arc::new(Secrets),
|
||||
vec![self.root.clone()],
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
fn http(&self) -> reqwest::Client {
|
||||
reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.add_root_certificate(self.root.clone())
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
async fn authorize(&self, start: &LoginStart) -> (String, String, String) {
|
||||
let response = self
|
||||
.http()
|
||||
.get(start.authorization_url.clone())
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 302);
|
||||
let callback = Url::parse(response.headers()["location"].to_str().unwrap()).unwrap();
|
||||
let pairs: HashMap<_, _> = callback.query_pairs().into_owned().collect();
|
||||
let binding = start
|
||||
.binding_set_cookie
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
.split_once('=')
|
||||
.unwrap()
|
||||
.1
|
||||
.to_owned();
|
||||
(pairs["code"].clone(), pairs["state"].clone(), binding)
|
||||
}
|
||||
async fn access_token(&self, field: Option<(&str, Value)>) -> String {
|
||||
let mut claims = self.state.claims("https://rmm.example/mcp");
|
||||
claims["scope"] = json!("inventory:read operations:submit");
|
||||
claims["client_id"] = json!("mcp-client");
|
||||
if let Some((key, value)) = field {
|
||||
claims[key] = value;
|
||||
}
|
||||
self.state.signing.lock().await.token(&claims, true)
|
||||
}
|
||||
}
|
||||
impl Mock {
|
||||
fn claims(&self, aud: &str) -> Value {
|
||||
json!({"iss":self.issuer,"sub":"stable-subject","aud":aud,"iat":now(),"exp":now()+300,"nbf":now()-1,"jti":random()})
|
||||
}
|
||||
async fn respond(&self, url: Url, body: &[u8]) -> (&'static str, Option<String>, String) {
|
||||
if let Some(response) = self.response_override.lock().await.clone()
|
||||
&& response.path == url.path()
|
||||
{
|
||||
return (response.status, response.location, response.body);
|
||||
}
|
||||
let output = match url.path() {
|
||||
"/.well-known/openid-configuration" => {
|
||||
if let Some(value) = self.discovery_override.lock().await.clone() {
|
||||
value
|
||||
} else {
|
||||
json!({"issuer":self.issuer,"authorization_endpoint":format!("{}authorize",self.issuer),"token_endpoint":format!("{}token",self.issuer),"jwks_uri":format!("{}jwks",self.issuer),"response_types_supported":["code"],"id_token_signing_alg_values_supported":["RS256"],"code_challenge_methods_supported":["S256"],"token_endpoint_auth_methods_supported":["client_secret_post"]})
|
||||
}
|
||||
}
|
||||
"/jwks" => {
|
||||
self.jwks_calls.fetch_add(1, Ordering::SeqCst);
|
||||
json!({"keys":[self.signing.lock().await.jwk()]})
|
||||
}
|
||||
"/authorize" => {
|
||||
let q: HashMap<_, _> = url.query_pairs().into_owned().collect();
|
||||
if q.get("client_id").map(String::as_str) != Some("browser")
|
||||
|| q.get("code_challenge_method").map(String::as_str) != Some("S256")
|
||||
|| q.get("redirect_uri").map(String::as_str)
|
||||
!= Some("https://rmm.example/callback")
|
||||
{
|
||||
return ("400 Bad Request", None, "{}".into());
|
||||
}
|
||||
let code = random();
|
||||
self.codes.lock().await.insert(
|
||||
code.clone(),
|
||||
Code {
|
||||
challenge: q["code_challenge"].clone(),
|
||||
nonce: q["nonce"].clone(),
|
||||
redirect: q["redirect_uri"].clone(),
|
||||
},
|
||||
);
|
||||
let mut callback = Url::parse(&q["redirect_uri"]).unwrap();
|
||||
callback
|
||||
.query_pairs_mut()
|
||||
.extend_pairs([("code", code.as_str()), ("state", q["state"].as_str())]);
|
||||
return ("302 Found", Some(callback.to_string()), "{}".into());
|
||||
}
|
||||
"/token" => {
|
||||
self.exchanges.fetch_add(1, Ordering::SeqCst);
|
||||
let q: HashMap<String, String> = serde_urlencoded::from_bytes(body).unwrap();
|
||||
let Some(code) = self.codes.lock().await.remove(&q["code"]) else {
|
||||
return ("400 Bad Request", None, "{}".into());
|
||||
};
|
||||
if q.get("grant_type").map(String::as_str) != Some("authorization_code")
|
||||
|| q.get("client_id").map(String::as_str) != Some("browser")
|
||||
|| q.get("client_secret").map(String::as_str) != Some("ephemeral-test-secret")
|
||||
|| q.get("redirect_uri") != Some(&code.redirect)
|
||||
|| q.get("code_verifier")
|
||||
.is_none_or(|v| hash(v) != code.challenge)
|
||||
{
|
||||
return ("400 Bad Request", None, "{}".into());
|
||||
}
|
||||
let mut claims = self.claims("browser");
|
||||
claims["nonce"] = json!(code.nonce);
|
||||
if let Some((key, value)) = self.mutate.lock().await.clone() {
|
||||
claims[key] = value;
|
||||
}
|
||||
json!({"id_token":self.signing.lock().await.token(&claims, false),"token_type":"Bearer","access_token":"unused-by-rmm"})
|
||||
}
|
||||
_ => {
|
||||
self.unexpected_calls.fetch_add(1, Ordering::SeqCst);
|
||||
return ("404 Not Found", None, "{}".into());
|
||||
}
|
||||
};
|
||||
("200 OK", None, output.to_string())
|
||||
}
|
||||
}
|
||||
struct Secrets;
|
||||
#[async_trait]
|
||||
impl SecretResolver for Secrets {
|
||||
async fn resolve(&self, _: &str) -> Result<SecretString> {
|
||||
Ok(SecretString::from("ephemeral-test-secret"))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browser_code_exchange_pkce_nonce_binding_and_replay() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let start = auth.login_start().await.unwrap();
|
||||
assert!(start.binding_set_cookie.contains("SameSite=Lax"));
|
||||
let (code, state, binding) = provider.authorize(&start).await;
|
||||
assert_eq!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &random()
|
||||
})
|
||||
.await,
|
||||
Err(Error::State)
|
||||
);
|
||||
let identity = auth
|
||||
.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(identity.subject, "stable-subject");
|
||||
assert_eq!(identity.issuer, provider.state.issuer);
|
||||
assert_eq!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding
|
||||
})
|
||||
.await,
|
||||
Err(Error::State)
|
||||
);
|
||||
assert_eq!(provider.state.exchanges.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_nonce_and_multi_audience_authorized_party() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
for (field, value, expected) in [
|
||||
("nonce", json!("wrong"), Error::Nonce),
|
||||
("aud", json!(["browser", "other"]), Error::InvalidAudience),
|
||||
("azp", json!("other-client"), Error::InvalidAudience),
|
||||
] {
|
||||
*provider.state.mutate.lock().await = Some((field, value));
|
||||
let start = auth.login_start().await.unwrap();
|
||||
let (code, state, binding) = provider.authorize(&start).await;
|
||||
assert_eq!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding
|
||||
})
|
||||
.await,
|
||||
Err(expected)
|
||||
);
|
||||
}
|
||||
*provider.state.mutate.lock().await = Some(("azp", json!("browser")));
|
||||
let start = auth.login_start().await.unwrap();
|
||||
let (code, state, binding) = provider.authorize(&start).await;
|
||||
assert!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding
|
||||
})
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pkce_failure_and_one_use_provider_code() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let start = auth.login_start().await.unwrap();
|
||||
let (code, state, binding) = provider.authorize(&start).await;
|
||||
provider
|
||||
.state
|
||||
.codes
|
||||
.lock()
|
||||
.await
|
||||
.get_mut(&code)
|
||||
.unwrap()
|
||||
.challenge = "mismatched-challenge".into();
|
||||
assert_eq!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding
|
||||
})
|
||||
.await,
|
||||
Err(Error::CodeExchange)
|
||||
);
|
||||
assert!(!provider.state.codes.lock().await.contains_key(&code));
|
||||
let response = provider
|
||||
.http()
|
||||
.post(format!("{}token", provider.state.issuer))
|
||||
.form(&[("code", code)])
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bearer_issuer_audience_expiry_nbf_scope_and_client() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let token = provider.access_token(None).await;
|
||||
let principal = auth
|
||||
.verify_mcp_bearer(&token, &["inventory:read"])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(principal.identity.subject, "stable-subject");
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&token, &["approvals:write"]).await,
|
||||
Err(Error::MissingScope)
|
||||
));
|
||||
for (field, value, expected) in [
|
||||
(
|
||||
"iss",
|
||||
json!("https://attacker.example/"),
|
||||
Error::InvalidIssuer,
|
||||
),
|
||||
("aud", json!("browser"), Error::InvalidAudience),
|
||||
("exp", json!(now() - 60), Error::Expired),
|
||||
("nbf", json!(now() + 300), Error::NotYetValid),
|
||||
("client_id", json!("unknown-client"), Error::InvalidAudience),
|
||||
] {
|
||||
let token = provider.access_token(Some((field, value))).await;
|
||||
assert_eq!(
|
||||
auth.verify_mcp_bearer(&token, &[]).await.unwrap_err(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn signature_algorithm_and_id_token_confusion_rejected() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let signing = provider.state.signing.lock().await;
|
||||
let id = signing.token(&provider.state.claims("https://rmm.example/mcp"), false);
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&id, &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
let mut header = Header::new(Algorithm::HS256);
|
||||
header.kid = Some(signing.kid.clone());
|
||||
header.typ = Some("at+jwt".into());
|
||||
let hs = encode(
|
||||
&header,
|
||||
&provider.state.claims("https://rmm.example/mcp"),
|
||||
&EncodingKey::from_secret(b"not-an-rsa-key"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&hs, &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
drop(signing);
|
||||
let unsigned = format!(
|
||||
"{}.{}.",
|
||||
URL_SAFE_NO_PAD.encode(br#"{"alg":"none","typ":"at+jwt"}"#),
|
||||
URL_SAFE_NO_PAD.encode(b"{}")
|
||||
);
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&unsigned, &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
let forged =
|
||||
Signing::new("first").token(&provider.state.claims("https://rmm.example/mcp"), true);
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&forged, &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn jwks_cache_unknown_kid_and_real_rotation() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let first = provider.access_token(None).await;
|
||||
auth.verify_mcp_bearer(&first, &[]).await.unwrap();
|
||||
auth.verify_mcp_bearer(&first, &[]).await.unwrap();
|
||||
assert_eq!(provider.state.jwks_calls.load(Ordering::SeqCst), 1);
|
||||
*provider.state.signing.lock().await = Signing::new("rotated");
|
||||
let rotated = provider.access_token(None).await;
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&rotated, &[]).await,
|
||||
Err(Error::UnknownKid)
|
||||
));
|
||||
tokio::time::sleep(Duration::from_millis(1100)).await;
|
||||
auth.verify_mcp_bearer(&rotated, &[]).await.unwrap();
|
||||
assert_eq!(provider.state.jwks_calls.load(Ordering::SeqCst), 2);
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&first, &[]).await,
|
||||
Err(Error::UnknownKid)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tls_trust_and_hostname_are_actually_checked() {
|
||||
let provider = Provider::start().await;
|
||||
let store = || Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly));
|
||||
assert!(matches!(
|
||||
OidcAuth::discover(
|
||||
provider.config(),
|
||||
Profile::DevTest,
|
||||
store(),
|
||||
Arc::new(Secrets),
|
||||
vec![]
|
||||
)
|
||||
.await,
|
||||
Err(Error::Transport)
|
||||
));
|
||||
let mut config = provider.config();
|
||||
config.issuer.set_host(Some("127.0.0.1")).unwrap();
|
||||
assert!(matches!(
|
||||
OidcAuth::discover(
|
||||
config,
|
||||
Profile::DevTest,
|
||||
store(),
|
||||
Arc::new(Secrets),
|
||||
vec![provider.root.clone()]
|
||||
)
|
||||
.await,
|
||||
Err(Error::Transport)
|
||||
));
|
||||
provider.auth().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn insecure_configuration_and_volatile_production_store_rejected() {
|
||||
let provider = Provider::start().await;
|
||||
for variant in 0..4 {
|
||||
let mut config = provider.config();
|
||||
let mut profile = Profile::DevTest;
|
||||
match variant {
|
||||
0 => {
|
||||
config.issuer.set_scheme("http").unwrap();
|
||||
}
|
||||
1 => {
|
||||
config.mcp_audience = config.browser_client_id.clone();
|
||||
}
|
||||
2 => {
|
||||
profile = Profile::Production;
|
||||
}
|
||||
_ => {
|
||||
config.redirect_uri.set_fragment(Some("untrusted"));
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
OidcAuth::discover(
|
||||
config,
|
||||
profile,
|
||||
Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly)),
|
||||
Arc::new(Secrets),
|
||||
vec![provider.root.clone()]
|
||||
)
|
||||
.await,
|
||||
Err(Error::Configuration)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn untrusted_discovery_endpoints_and_issuer_rejected() {
|
||||
let provider = Provider::start().await;
|
||||
for (issuer, jwks) in [
|
||||
(
|
||||
provider.state.issuer.clone(),
|
||||
"https://attacker.example/jwks".to_owned(),
|
||||
),
|
||||
(
|
||||
"https://attacker.example/".to_owned(),
|
||||
format!("{}jwks", provider.state.issuer),
|
||||
),
|
||||
(
|
||||
provider.state.issuer.clone(),
|
||||
"http://localhost/jwks".to_owned(),
|
||||
),
|
||||
] {
|
||||
*provider.state.discovery_override.lock().await = Some(
|
||||
json!({"issuer":issuer,"authorization_endpoint":format!("{}authorize",provider.state.issuer),"token_endpoint":format!("{}token",provider.state.issuer),"jwks_uri":jwks,"response_types_supported":["code"],"id_token_signing_alg_values_supported":["RS256"],"code_challenge_methods_supported":["S256"],"token_endpoint_auth_methods_supported":["client_secret_post"]}),
|
||||
);
|
||||
assert!(matches!(
|
||||
OidcAuth::discover(
|
||||
provider.config(),
|
||||
Profile::DevTest,
|
||||
Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly)),
|
||||
Arc::new(Secrets),
|
||||
vec![provider.root.clone()]
|
||||
)
|
||||
.await,
|
||||
Err(Error::Discovery)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn state_expiry_and_concurrent_single_use() {
|
||||
let store = Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly));
|
||||
store
|
||||
.insert(
|
||||
"expired".into(),
|
||||
PendingLogin {
|
||||
binding_hash: "binding".into(),
|
||||
nonce: random(),
|
||||
pkce_verifier: random(),
|
||||
expires_at: now() - 1,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
store.consume("expired", "binding", now()).await,
|
||||
Err(Error::State)
|
||||
));
|
||||
store
|
||||
.insert(
|
||||
"once".into(),
|
||||
PendingLogin {
|
||||
binding_hash: "binding".into(),
|
||||
nonce: random(),
|
||||
pkce_verifier: random(),
|
||||
expires_at: now() + 30,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (a, b) = tokio::join!(
|
||||
store.consume("once", "binding", now()),
|
||||
store.consume("once", "binding", now())
|
||||
);
|
||||
assert_eq!(usize::from(a.is_ok()) + usize::from(b.is_ok()), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_jwks_and_exchange_never_follow_redirects() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let token = provider.access_token(None).await;
|
||||
for path in ["/jwks", "/token", "/.well-known/openid-configuration"] {
|
||||
*provider.state.response_override.lock().await = Some(ResponseOverride {
|
||||
path: path.into(),
|
||||
status: "302 Found",
|
||||
location: Some(format!("{}untrusted-trap", provider.state.issuer)),
|
||||
body: "{}".into(),
|
||||
});
|
||||
match path {
|
||||
"/jwks" => assert!(matches!(
|
||||
auth.verify_mcp_bearer(&token, &[]).await,
|
||||
Err(Error::Transport)
|
||||
)),
|
||||
"/token" => {
|
||||
let start = auth.login_start().await.unwrap();
|
||||
let (code, state, binding) = provider.authorize(&start).await;
|
||||
assert_eq!(
|
||||
auth.callback(Callback {
|
||||
code: &code,
|
||||
state: &state,
|
||||
browser_binding: &binding
|
||||
})
|
||||
.await,
|
||||
Err(Error::CodeExchange)
|
||||
);
|
||||
}
|
||||
_ => assert!(matches!(
|
||||
OidcAuth::discover(
|
||||
provider.config(),
|
||||
Profile::DevTest,
|
||||
Arc::new(dev::InMemoryStateStore::new(dev::DevTestOnly)),
|
||||
Arc::new(Secrets),
|
||||
vec![provider.root.clone()]
|
||||
)
|
||||
.await,
|
||||
Err(Error::Transport)
|
||||
)),
|
||||
}
|
||||
}
|
||||
assert_eq!(provider.state.unexpected_calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_responses_and_tokens_fail_closed() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
let token = provider.access_token(None).await;
|
||||
*provider.state.response_override.lock().await = Some(ResponseOverride {
|
||||
path: "/jwks".into(),
|
||||
status: "200 OK",
|
||||
location: None,
|
||||
body: "x".repeat(131073),
|
||||
});
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&token, &[]).await,
|
||||
Err(Error::Transport)
|
||||
));
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&"x".repeat(32769), &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn required_claims_and_future_iat_are_rejected() {
|
||||
let provider = Provider::start().await;
|
||||
let auth = provider.auth().await;
|
||||
for field in ["exp", "iss", "aud", "sub", "iat", "jti"] {
|
||||
let mut claims = provider.state.claims("https://rmm.example/mcp");
|
||||
claims.as_object_mut().unwrap().remove(field);
|
||||
let token = provider.state.signing.lock().await.token(&claims, true);
|
||||
assert!(
|
||||
auth.verify_mcp_bearer(&token, &[]).await.is_err(),
|
||||
"missing required claim must fail"
|
||||
);
|
||||
}
|
||||
let token = provider
|
||||
.access_token(Some(("iat", json!(now() + 300))))
|
||||
.await;
|
||||
assert!(matches!(
|
||||
auth.verify_mcp_bearer(&token, &[]).await,
|
||||
Err(Error::InvalidToken)
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
#![cfg(feature = "postgres-state")]
|
||||
use async_trait::async_trait;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use rmm_oidc_auth::{
|
||||
Error, PendingLogin, Result, SecretResolver, StateStore,
|
||||
postgres::{MIGRATION_SQL, PostgresStateStore},
|
||||
};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{
|
||||
ConnectOptions, Row,
|
||||
postgres::{PgConnectOptions, PgPoolOptions},
|
||||
};
|
||||
use std::{
|
||||
sync::Arc,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
fn must<T, E>(result: std::result::Result<T, E>, message: &str) -> T {
|
||||
result.unwrap_or_else(|_| panic!("{message}"))
|
||||
}
|
||||
fn time() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs()
|
||||
}
|
||||
fn random() -> String {
|
||||
URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>())
|
||||
}
|
||||
fn handle() -> String {
|
||||
URL_SAFE_NO_PAD.encode(Sha256::digest(random().as_bytes()))
|
||||
}
|
||||
fn pending(binding: &str) -> PendingLogin {
|
||||
PendingLogin {
|
||||
binding_hash: binding.into(),
|
||||
nonce: random(),
|
||||
pkce_verifier: random(),
|
||||
expires_at: time() + 300,
|
||||
}
|
||||
}
|
||||
struct Key(SecretString);
|
||||
#[async_trait]
|
||||
impl SecretResolver for Key {
|
||||
async fn resolve(&self, reference: &str) -> Result<SecretString> {
|
||||
if reference != "test-oidc-state-key-v1" && reference != "test-oidc-state-key-v2" {
|
||||
return Err(Error::Secret);
|
||||
}
|
||||
Ok(SecretString::from(self.0.expose_secret().to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit opt-in; the supplied owner identity must belong to a disposable database.
|
||||
/// The package runner creates a new dedicated container and never uses the server DB.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires isolated PostgreSQL owner test identity; use tests/run_postgres.py"]
|
||||
async fn real_postgres_encrypted_state_nonowner_atomicity_and_limits() {
|
||||
assert_eq!(
|
||||
std::env::var("RMM_OIDC_TEST_ALLOW_OWNER_DDL")
|
||||
.ok()
|
||||
.as_deref(),
|
||||
Some("isolated"),
|
||||
"owner DDL must be explicitly permitted for isolated tests"
|
||||
);
|
||||
let url = must(
|
||||
std::env::var("RMM_OIDC_TEST_DATABASE_URL"),
|
||||
"isolated PostgreSQL URL missing",
|
||||
);
|
||||
let options: PgConnectOptions = must(url.parse(), "invalid isolated PostgreSQL configuration");
|
||||
let options = options.disable_statement_logging();
|
||||
let owner = must(
|
||||
PgPoolOptions::new()
|
||||
.max_connections(2)
|
||||
.connect_with(options.clone())
|
||||
.await,
|
||||
"owner connection failed",
|
||||
);
|
||||
must(
|
||||
sqlx::raw_sql(MIGRATION_SQL).execute(&owner).await,
|
||||
"isolated migration fixture failed",
|
||||
);
|
||||
let role = format!("oidc_auth_test_{:016x}", rand::random::<u64>());
|
||||
let password = format!(
|
||||
"{:032x}{:032x}",
|
||||
rand::random::<u128>(),
|
||||
rand::random::<u128>()
|
||||
);
|
||||
// Both interpolated values are locally generated ASCII hex/identifier characters,
|
||||
// never caller/config input. Runtime adapter queries contain only bind parameters.
|
||||
must(sqlx::raw_sql(&format!(
|
||||
"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \
|
||||
GRANT USAGE ON SCHEMA rmm_oidc_auth TO {role}; \
|
||||
GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO {role};"
|
||||
)).execute(&owner).await, "isolated nonowner runtime role fixture failed");
|
||||
let runtime = must(
|
||||
PgPoolOptions::new()
|
||||
.max_connections(16)
|
||||
.acquire_timeout(std::time::Duration::from_secs(10))
|
||||
.connect_with(options.username(&role).password(&password))
|
||||
.await,
|
||||
"nonowner runtime connection failed",
|
||||
);
|
||||
let privileges = must(
|
||||
sqlx::query(
|
||||
"SELECT r.rolsuper, r.rolbypassrls, \
|
||||
has_schema_privilege(current_user, 'rmm_oidc_auth', 'CREATE') AS can_create, \
|
||||
c.relowner <> r.oid AS nonowner \
|
||||
FROM pg_roles r CROSS JOIN pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace \
|
||||
WHERE r.rolname=current_user AND n.nspname='rmm_oidc_auth' AND c.relname='login_states'",
|
||||
)
|
||||
.fetch_one(&runtime)
|
||||
.await,
|
||||
"runtime privilege check failed",
|
||||
);
|
||||
assert!(!privileges.get::<bool, _>("rolsuper"));
|
||||
assert!(!privileges.get::<bool, _>("rolbypassrls"));
|
||||
assert!(!privileges.get::<bool, _>("can_create"));
|
||||
assert!(privileges.get::<bool, _>("nonowner"));
|
||||
assert!(
|
||||
sqlx::query("CREATE TABLE rmm_oidc_auth.forbidden_runtime_ddl (id int)")
|
||||
.execute(&runtime)
|
||||
.await
|
||||
.is_err(),
|
||||
"runtime must not create tables"
|
||||
);
|
||||
let resolver = Key(SecretString::from(random()));
|
||||
let store = Arc::new(must(
|
||||
PostgresStateStore::new(
|
||||
runtime.clone(),
|
||||
&resolver,
|
||||
"test-oidc-state-key-v1".into(),
|
||||
100,
|
||||
)
|
||||
.await,
|
||||
"state adapter setup failed",
|
||||
));
|
||||
assert!(store.is_persistent());
|
||||
assert!(matches!(
|
||||
PostgresStateStore::new(
|
||||
runtime.clone(),
|
||||
&Key(SecretString::from("invalid-key")),
|
||||
"test-oidc-state-key-v1".into(),
|
||||
100
|
||||
)
|
||||
.await,
|
||||
Err(Error::Configuration)
|
||||
));
|
||||
assert!(
|
||||
sqlx::query("UPDATE rmm_oidc_auth.login_states SET expires_at=expires_at WHERE false")
|
||||
.execute(&runtime)
|
||||
.await
|
||||
.is_err(),
|
||||
"runtime must not update state"
|
||||
);
|
||||
|
||||
let state = handle();
|
||||
let binding = handle();
|
||||
let login = pending(&binding);
|
||||
let nonce = login.nonce.clone();
|
||||
let verifier = login.pkce_verifier.clone();
|
||||
must(
|
||||
store.insert(state.clone(), login).await,
|
||||
"nonowner insert failed",
|
||||
);
|
||||
let other_version = must(
|
||||
PostgresStateStore::new(
|
||||
runtime.clone(),
|
||||
&resolver,
|
||||
"test-oidc-state-key-v2".into(),
|
||||
100,
|
||||
)
|
||||
.await,
|
||||
"key-version test setup failed",
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
other_version.consume(&state, &binding, time()).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"a different configured key version must not consume this state"
|
||||
);
|
||||
let saved = must(
|
||||
sqlx::query("SELECT state_hash, binding_hash, ciphertext FROM rmm_oidc_auth.login_states")
|
||||
.fetch_one(&owner)
|
||||
.await,
|
||||
"encrypted fixture inspection failed",
|
||||
);
|
||||
assert_eq!(saved.get::<Vec<u8>, _>("state_hash").len(), 32);
|
||||
assert_eq!(saved.get::<Vec<u8>, _>("binding_hash").len(), 32);
|
||||
let ciphertext: Vec<u8> = saved.get("ciphertext");
|
||||
assert!(
|
||||
!ciphertext
|
||||
.windows(nonce.len())
|
||||
.any(|w| w == nonce.as_bytes())
|
||||
);
|
||||
assert!(
|
||||
!ciphertext
|
||||
.windows(verifier.len())
|
||||
.any(|w| w == verifier.as_bytes())
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&state, &handle(), time()).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"wrong binding must fail"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&state, &binding, time() + 600).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"caller expiry must fail without burning valid state"
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.insert(state.clone(), pending(&binding))
|
||||
.await
|
||||
.is_err(),
|
||||
"duplicate handle must not overwrite"
|
||||
);
|
||||
let mut tasks = vec![];
|
||||
for _ in 0..16 {
|
||||
let store = store.clone();
|
||||
let state = state.clone();
|
||||
let binding = binding.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
store.consume(&state, &binding, time()).await
|
||||
}));
|
||||
}
|
||||
let mut winners = 0;
|
||||
for task in tasks {
|
||||
match must(task.await, "concurrent callback task failed") {
|
||||
Ok(login) => {
|
||||
winners += 1;
|
||||
assert!(login.nonce == nonce);
|
||||
assert!(login.pkce_verifier == verifier);
|
||||
}
|
||||
Err(error) => assert_eq!(error, Error::State),
|
||||
}
|
||||
}
|
||||
assert_eq!(winners, 1, "exactly one callback may consume state");
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&state, &binding, time()).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"replay must fail"
|
||||
);
|
||||
|
||||
let expired = handle();
|
||||
must(
|
||||
store.insert(expired.clone(), pending(&binding)).await,
|
||||
"expiry fixture insert failed",
|
||||
);
|
||||
must(
|
||||
sqlx::query("UPDATE rmm_oidc_auth.login_states SET created_at=$1, expires_at=$2")
|
||||
.bind(i64::try_from(time() - 600).unwrap())
|
||||
.bind(i64::try_from(time() - 1).unwrap())
|
||||
.execute(&owner)
|
||||
.await,
|
||||
"owner expiry fixture failed",
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&expired, &binding, 0).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"database clock must prevent revival with an old caller clock"
|
||||
);
|
||||
assert_eq!(
|
||||
must(store.cleanup_expired(1).await, "expiry cleanup failed"),
|
||||
1
|
||||
);
|
||||
assert!(matches!(
|
||||
store.cleanup_expired(1001).await,
|
||||
Err(Error::Configuration)
|
||||
));
|
||||
|
||||
let tampered = handle();
|
||||
must(
|
||||
store.insert(tampered.clone(), pending(&binding)).await,
|
||||
"tamper fixture insert failed",
|
||||
);
|
||||
must(
|
||||
sqlx::query("UPDATE rmm_oidc_auth.login_states SET ciphertext=$1")
|
||||
.bind(vec![0u8; 32])
|
||||
.execute(&owner)
|
||||
.await,
|
||||
"owner tamper fixture failed",
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&tampered, &binding, time()).await,
|
||||
Err(Error::Store)
|
||||
),
|
||||
"tampering must fail authenticated decryption"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
store.consume(&tampered, &binding, time()).await,
|
||||
Err(Error::State)
|
||||
),
|
||||
"decrypt failure must not restore consumed state"
|
||||
);
|
||||
|
||||
let small = Arc::new(must(
|
||||
PostgresStateStore::new(
|
||||
runtime.clone(),
|
||||
&resolver,
|
||||
"test-oidc-state-key-v1".into(),
|
||||
2,
|
||||
)
|
||||
.await,
|
||||
"capacity adapter setup failed",
|
||||
));
|
||||
let mut tasks = vec![];
|
||||
for _ in 0..8 {
|
||||
let small = small.clone();
|
||||
let binding = binding.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
small.insert(handle(), pending(&binding)).await
|
||||
}));
|
||||
}
|
||||
let mut admitted = 0;
|
||||
for task in tasks {
|
||||
admitted += usize::from(must(task.await, "admission task failed").is_ok());
|
||||
}
|
||||
assert_eq!(
|
||||
admitted, 2,
|
||||
"capacity check must serialize concurrent inserts"
|
||||
);
|
||||
must(
|
||||
sqlx::query("UPDATE rmm_oidc_auth.login_states SET created_at=$1, expires_at=$2")
|
||||
.bind(i64::try_from(time() - 600).unwrap())
|
||||
.bind(i64::try_from(time() - 1).unwrap())
|
||||
.execute(&owner)
|
||||
.await,
|
||||
"cleanup fixtures failed",
|
||||
);
|
||||
assert_eq!(
|
||||
must(store.cleanup_expired(1).await, "bounded cleanup failed"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
must(store.cleanup_expired(1).await, "bounded cleanup failed"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
must(store.cleanup_expired(1).await, "bounded cleanup failed"),
|
||||
0
|
||||
);
|
||||
assert!(matches!(
|
||||
store
|
||||
.insert("not-a-hashed-state".into(), pending(&binding))
|
||||
.await,
|
||||
Err(Error::State)
|
||||
));
|
||||
let mut too_long = pending(&binding);
|
||||
too_long.expires_at = time() + 3600;
|
||||
assert!(matches!(
|
||||
store.insert(handle(), too_long).await,
|
||||
Err(Error::State)
|
||||
));
|
||||
|
||||
runtime.close().await;
|
||||
must(
|
||||
sqlx::raw_sql(&format!("DROP OWNED BY {role}; DROP ROLE {role};"))
|
||||
.execute(&owner)
|
||||
.await,
|
||||
"isolated role cleanup failed",
|
||||
);
|
||||
owner.close().await;
|
||||
println!(
|
||||
"PostgreSQL: nonowner role verified; concurrent consume winners=1/16; capacity admitted=2/8; encrypted storage, wrong binding, expiry, replay, tampering and bounded cleanup checked"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in disposable PostgreSQL test. No existing container/DB or host trust changes."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
NAME = "rust-discovery-oidc-test"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def quiet(args, **kwargs):
|
||||
return subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
if quiet(["docker", "container", "inspect", NAME]).returncode == 0:
|
||||
raise RuntimeError("dedicated test container name already exists; refusing to touch it")
|
||||
env = os.environ.copy()
|
||||
env["POSTGRES_PASSWORD"] = secrets.token_hex(32)
|
||||
created = False
|
||||
try:
|
||||
result = quiet([
|
||||
"docker", "run", "--detach", "--name", NAME,
|
||||
"--label", "rmm.oidc.disposable-test=true",
|
||||
"--publish", "127.0.0.1::5432",
|
||||
"--env", "POSTGRES_PASSWORD", "--env", "POSTGRES_DB=oidc_test",
|
||||
"postgres:17.6-bookworm",
|
||||
], env=env, timeout=30)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError("could not create isolated PostgreSQL test container")
|
||||
created = True
|
||||
ready = False
|
||||
for _ in range(80):
|
||||
if quiet(["docker", "exec", NAME, "pg_isready", "-q", "-h", "127.0.0.1", "-U", "postgres", "-d", "oidc_test"], timeout=5).returncode == 0:
|
||||
ready = True
|
||||
break
|
||||
time.sleep(0.25)
|
||||
if not ready:
|
||||
raise RuntimeError("isolated PostgreSQL did not become ready")
|
||||
port_result = subprocess.run(["docker", "port", NAME, "5432/tcp"], capture_output=True, text=True, timeout=5)
|
||||
mapping = port_result.stdout.strip()
|
||||
if port_result.returncode != 0 or not mapping.startswith("127.0.0.1:") or not mapping.split(":")[-1].isdigit():
|
||||
raise RuntimeError("test port is not a single IPv4 loopback binding")
|
||||
port = int(mapping.rsplit(":", 1)[1])
|
||||
env["RMM_OIDC_TEST_DATABASE_URL"] = f"postgres://postgres:{env['POSTGRES_PASSWORD']}@127.0.0.1:{port}/oidc_test"
|
||||
env["RMM_OIDC_TEST_ALLOW_OWNER_DDL"] = "isolated"
|
||||
# No URL/password arguments, env printing, inherited SQL logging or backtraces.
|
||||
env.pop("RUST_LOG", None)
|
||||
env.pop("RUST_BACKTRACE", None)
|
||||
cargo = shutil.which("cargo") or str(Path.home() / ".cargo/bin/cargo")
|
||||
result = subprocess.run([
|
||||
cargo, "test", "--manifest-path", str(ROOT / "Cargo.toml"), "--locked",
|
||||
"--features", "postgres-state", "--test", "postgres_state", "--",
|
||||
"--ignored", "--nocapture",
|
||||
], env=env, cwd=ROOT, timeout=180)
|
||||
return result.returncode
|
||||
finally:
|
||||
if created:
|
||||
if quiet(["docker", "rm", "--force", "--volumes", NAME], timeout=30).returncode != 0:
|
||||
raise RuntimeError("own disposable test container cleanup failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (RuntimeError, subprocess.SubprocessError):
|
||||
print("isolated PostgreSQL test failed (details/credentials suppressed)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user