173 lines
11 KiB
Markdown
173 lines
11 KiB
Markdown
# 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.
|