Document the accepted MVP and retire superseded development plans
Rust development slice / linux (push) Failing after 14s
Rust development slice / linux (push) Failing after 14s
This commit is contained in:
@@ -1,172 +0,0 @@
|
||||
# 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.
|
||||
+3
-162
@@ -1,164 +1,5 @@
|
||||
# RMM OIDC authentication adapter (standalone package)
|
||||
# Authentisierung im MVP
|
||||
|
||||
Optional encrypted SQLx/PostgreSQL login-state storage and its migration/permissions
|
||||
contract: **[POSTGRES.md](POSTGRES.md)** (`postgres-state` feature).
|
||||
Die öffentliche WebUI verwendet ein lokales Konto mit Passwort und TOTP. Der MCP-Server prüft kundengebundene Bearer-Tokens. Die Einrichtung dieser beiden Zugänge steht in der [Betriebsanleitung](../../docs/public-access.md).
|
||||
|
||||
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.
|
||||
Dieses Rust-Paket wird vom Server als lokale Abhängigkeit eingebunden und enthält den separat konfigurierbaren OIDC-Adapter. Im öffentlichen MVP ist dieser Adapter deaktiviert. [Server-Abhängigkeiten](../server/Cargo.toml) · [Authentisierung im Server](../server/src/auth.rs)
|
||||
|
||||
Reference in New Issue
Block a user