diff --git a/pkgs/idp-provider/README.md b/pkgs/idp-provider/README.md index d0a458c484..65ab2aae19 100644 --- a/pkgs/idp-provider/README.md +++ b/pkgs/idp-provider/README.md @@ -46,6 +46,48 @@ SSO never rebinds an id key (#2060). UPDATE/DELETE are blocked by triggers, and a failed audit write fails the attempt closed). +## Integrating an app (the consumer pattern) + +How an application consumes this provider (#13416). The +reference implementation is the crate's `verify` module plus +`examples/role-gated-app.rs`; the aggregator integration +(#13798) is the first production consumer. + +1. **Register the app.** Add a row to the provider config's + `clients` (a `client_id` and its exact redirect URIs). There + are no client secrets: public clients with PKCE (S256) only. +2. **Configure from discovery.** Point the app at the issuer and + read the endpoints and `jwks_uri` from + `/.well-known/openid-configuration`. Never hardcode a key or + an endpoint. +3. **Sign in with code + PKCE.** The ID token proves who signed + in; the access token is what the app checks on API calls. + Tokens live 300 s and there are no refresh tokens — when one + expires, run the flow again. +4. **Verify every request.** RS256 against the JWKS, selecting + the key by the token's `kid` — so a provider key rollover + (Slice 5) needs no app change — then check `iss`, `exp`, and + `token_use=access`. `verify::TokenVerifier` does exactly + this; verification is offline once the JWKS is fetched (a + long-lived app re-fetches it on a schedule). +5. **Enforce roles on the server.** Roles are read only from + the verified token — never from request bodies, headers, or + client-side state. The reference gate: reads accept any valid + token; writes require `owner` or `orchestrator` + (`verify::require_any_role`). A valid token without a write + role gets **403**; an invalid or expired one gets **401**. + +The reference consumer serves `/read` and `/write` under that +gate and is configured by environment alone (`APP_ISSUER`, +`APP_BIND`); `tests/consumer.rs` proves the gate against tokens +from the provider's real loop, including the read-only denial. + +Cloudflare Access and this provider compose rather than +compete: Access decides who can *reach* an app, the IdP token +decides what the app lets them *do*. For the PM stack, the +#9608 break-glass owner token remains the path when the IdP +itself is down. + ## Configuration (environment) | Variable | Default | Meaning | diff --git a/pkgs/idp-provider/examples/role-gated-app.rs b/pkgs/idp-provider/examples/role-gated-app.rs new file mode 100644 index 0000000000..5fdcf6e8ed --- /dev/null +++ b/pkgs/idp-provider/examples/role-gated-app.rs @@ -0,0 +1,40 @@ +//! Reference consumer for the minimal IdP (#13416): the +//! smallest complete application that takes the provider's +//! tokens seriously. +//! +//! - `GET /read` — any valid access token. +//! - `POST /write` — a valid access token carrying a write role +//! (`owner` or `orchestrator`); enforcement is server-side, on +//! every request, against the verified token. +//! +//! Configuration is environment-only, per the integration +//! pattern in the crate README: +//! +//! - `APP_ISSUER` — the IdP issuer URL (default +//! `http://127.0.0.1:8911`). Discovery + JWKS are fetched from +//! it at startup; verification after that is offline. +//! - `APP_BIND` — listen address (default `127.0.0.1:8913`). +//! +//! Run it next to a live provider and drive it with any token +//! the provider mints (the test-rp example completes a loop and +//! userinfo shows the claims; curl works too). + +use idp_provider::verify::{reference_app, TokenVerifier}; +use std::sync::Arc; + +#[tokio::main] +async fn main() { + let issuer = + std::env::var("APP_ISSUER").unwrap_or_else(|_| "http://127.0.0.1:8911".to_string()); + let bind = std::env::var("APP_BIND").unwrap_or_else(|_| "127.0.0.1:8913".to_string()); + let verifier = TokenVerifier::from_issuer(&issuer) + .await + .unwrap_or_else(|e| panic!("cannot build verifier from {issuer}: {e}")); + let listener = tokio::net::TcpListener::bind(&bind) + .await + .unwrap_or_else(|e| panic!("cannot bind {bind}: {e}")); + println!("role-gated-app listening on {bind}, issuer {issuer}"); + axum::serve(listener, reference_app(Arc::new(verifier))) + .await + .expect("server error"); +} diff --git a/pkgs/idp-provider/src/lib.rs b/pkgs/idp-provider/src/lib.rs index 75026c2ae5..2324a41f98 100644 --- a/pkgs/idp-provider/src/lib.rs +++ b/pkgs/idp-provider/src/lib.rs @@ -33,6 +33,7 @@ pub mod identities; pub mod registry; pub mod signing; pub mod upstream; +pub mod verify; use audit::AuditLog; use axum::{routing::get, Json, Router}; @@ -42,7 +43,7 @@ use flow::FlowState; use identities::IdentityStore; use pkcs1::DecodeRsaPublicKey; use rsa::{traits::PublicKeyParts, RsaPublicKey}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::path::PathBuf; use std::sync::Arc; @@ -164,7 +165,7 @@ pub fn cert_thumbprint_sha256(der_bytes: &[u8]) -> String { b64url(&Sha256::digest(der_bytes)) } -#[derive(Clone, Debug, Serialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct Jwk { pub kty: String, #[serde(rename = "use")] @@ -177,7 +178,7 @@ pub struct Jwk { pub e: String, } -#[derive(Clone, Debug, Serialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct Jwks { pub keys: Vec, } diff --git a/pkgs/idp-provider/src/verify.rs b/pkgs/idp-provider/src/verify.rs new file mode 100644 index 0000000000..c4637a74f6 --- /dev/null +++ b/pkgs/idp-provider/src/verify.rs @@ -0,0 +1,227 @@ +//! Relying-party side of the provider: verify access tokens +//! against a JWKS and gate on roles (#13416). +//! +//! This is the consumer half of the per-app integration pattern +//! documented in the crate README. A consuming application: +//! +//! 1. builds a [`TokenVerifier`] from the issuer (discovery → +//! JWKS), or from a JWKS it already holds; +//! 2. calls [`TokenVerifier::verify_access_token`] on every +//! request's bearer token — the verifier selects the JWKS key +//! by the token's `kid`, so a provider key rollover (Slice 5) +//! needs no consumer change and no flag day; +//! 3. gates writes server-side with [`require_any_role`], reading +//! roles only from the verified token — never from request +//! bodies, headers, or client-side state. +//! +//! [`reference_app`] is the smallest complete consumer: a router +//! with a read endpoint any valid token may use and a write +//! endpoint gated on the `owner`/`orchestrator` roles. The +//! `role-gated-app` example serves it; other apps copy the shape. + +use axum::extract::State; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine as _}; +use rsa::pkcs1v15::{Signature, VerifyingKey}; +use rsa::signature::Verifier; +use rsa::{BigUint, RsaPublicKey}; +use serde_json::{json, Value}; +use sha2::Sha256; +use std::sync::Arc; + +use crate::registry::now_unix; +use crate::Jwks; + +/// A verified access token: the claims an app may act on. +#[derive(Debug, Clone)] +pub struct VerifiedToken { + pub sub: String, + pub roles: Vec, + pub claims: Value, +} + +/// Verifies this provider's access tokens against a JWKS. +pub struct TokenVerifier { + issuer: String, + jwks: Jwks, +} + +fn b64_decode(s: &str) -> Result, String> { + B64URL + .decode(s) + .map_err(|e| format!("base64url decode failed: {e}")) +} + +impl TokenVerifier { + pub fn new(issuer: impl Into, jwks: Jwks) -> Self { + TokenVerifier { + issuer: issuer.into(), + jwks, + } + } + + /// Build a verifier from an issuer base URL: fetch the + /// discovery document, then the JWKS it names. (A long-lived + /// consumer re-fetches on a schedule so a provider key + /// rollover is picked up without a restart; verification + /// itself is per-token and offline.) + pub async fn from_issuer(issuer: &str) -> Result { + let issuer = issuer.trim_end_matches('/'); + let client = reqwest::Client::new(); + let discovery: Value = client + .get(format!("{issuer}/.well-known/openid-configuration")) + .send() + .await + .map_err(|e| format!("discovery fetch failed: {e}"))? + .error_for_status() + .map_err(|e| format!("discovery fetch failed: {e}"))? + .json() + .await + .map_err(|e| format!("discovery parse failed: {e}"))?; + let jwks_uri = discovery["jwks_uri"] + .as_str() + .ok_or("discovery document has no jwks_uri")?; + let jwks: Jwks = client + .get(jwks_uri) + .send() + .await + .map_err(|e| format!("jwks fetch failed: {e}"))? + .error_for_status() + .map_err(|e| format!("jwks fetch failed: {e}"))? + .json() + .await + .map_err(|e| format!("jwks parse failed: {e}"))?; + Ok(TokenVerifier::new(issuer.to_string(), jwks)) + } + + /// Verify an access token: RS256 signature against the JWKS + /// key named by the token's `kid`, then issuer, `token_use`, + /// and expiry. Any failure is an error string the caller maps + /// to 401 — the checks are ordered so a forged token fails at + /// the signature, before any claim is read. + pub fn verify_access_token(&self, token: &str) -> Result { + let parts: Vec<&str> = token.split('.').collect(); + if parts.len() != 3 { + return Err("token is not a compact JWS".to_string()); + } + let header: Value = serde_json::from_slice(&b64_decode(parts[0])?) + .map_err(|e| format!("jwt header parse failed: {e}"))?; + if header["alg"] != "RS256" { + return Err("unexpected jwt alg".to_string()); + } + let kid = header["kid"].as_str().ok_or("jwt header has no kid")?; + let jwk = self + .jwks + .keys + .iter() + .find(|k| k.kid == kid) + .ok_or("unexpected jwt kid")?; + let pubkey = RsaPublicKey::new( + BigUint::from_bytes_be(&b64_decode(&jwk.n)?), + BigUint::from_bytes_be(&b64_decode(&jwk.e)?), + ) + .map_err(|e| format!("jwks key is not a valid RSA public key: {e}"))?; + let signature = Signature::try_from(b64_decode(parts[2])?.as_slice()) + .map_err(|_| "bad signature encoding".to_string())?; + VerifyingKey::::new(pubkey) + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .map_err(|_| "jwt signature verification failed".to_string())?; + let claims: Value = serde_json::from_slice(&b64_decode(parts[1])?) + .map_err(|e| format!("jwt claims parse failed: {e}"))?; + if claims["iss"].as_str() != Some(self.issuer.as_str()) { + return Err("unexpected jwt issuer".to_string()); + } + if claims["token_use"].as_str() != Some("access") { + return Err("not an access token".to_string()); + } + let exp = claims["exp"].as_i64().ok_or("jwt has no exp")?; + if exp <= now_unix() { + return Err("jwt expired".to_string()); + } + let sub = claims["sub"].as_str().ok_or("jwt has no sub")?.to_string(); + let roles = claims["roles"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|r| r.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + Ok(VerifiedToken { sub, roles, claims }) + } +} + +/// The write gate: the verified token must carry at least one of +/// `roles`. This is the whole of role enforcement — it runs on +/// the server, on every write, against the verified token. +pub fn require_any_role(token: &VerifiedToken, roles: &[&str]) -> Result<(), String> { + if token.roles.iter().any(|r| roles.contains(&r.as_str())) { + Ok(()) + } else { + Err(format!("requires one of the roles: {}", roles.join(", "))) + } +} + +/// Roles allowed to write in the reference consumer. +pub const WRITE_ROLES: [&str; 2] = ["owner", "orchestrator"]; + +fn bearer(headers: &HeaderMap) -> Result<&str, Response> { + headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .ok_or_else(|| { + ( + StatusCode::UNAUTHORIZED, + Json(json!({"error": "missing bearer token"})), + ) + .into_response() + }) +} + +async fn read_handler(State(verifier): State>, headers: HeaderMap) -> Response { + let token = match bearer(&headers) { + Ok(t) => t, + Err(r) => return r, + }; + match verifier.verify_access_token(token) { + Ok(v) => ( + StatusCode::OK, + Json(json!({"sub": v.sub, "roles": v.roles})), + ) + .into_response(), + Err(e) => (StatusCode::UNAUTHORIZED, Json(json!({"error": e}))).into_response(), + } +} + +async fn write_handler(State(verifier): State>, headers: HeaderMap) -> Response { + let token = match bearer(&headers) { + Ok(t) => t, + Err(r) => return r, + }; + let verified = match verifier.verify_access_token(token) { + Ok(v) => v, + Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({"error": e}))).into_response(), + }; + match require_any_role(&verified, &WRITE_ROLES) { + Ok(()) => ( + StatusCode::OK, + Json(json!({"written": true, "sub": verified.sub})), + ) + .into_response(), + Err(e) => (StatusCode::FORBIDDEN, Json(json!({"error": e}))).into_response(), + } +} + +/// The reference consumer application: `/healthz`, `/read` (any +/// valid access token), `/write` (valid token + a write role). +pub fn reference_app(verifier: Arc) -> Router { + Router::new() + .route("/healthz", get(|| async { Json(json!({"status": "ok"})) })) + .route("/read", get(read_handler)) + .route("/write", post(write_handler)) + .with_state(verifier) +} diff --git a/pkgs/idp-provider/tests/consumer.rs b/pkgs/idp-provider/tests/consumer.rs new file mode 100644 index 0000000000..5b8eeb696b --- /dev/null +++ b/pkgs/idp-provider/tests/consumer.rs @@ -0,0 +1,279 @@ +//! Consumer tests (#13416): the reference consumer verifies the +//! provider's access tokens against the JWKS and enforces roles +//! on writes, server-side. +//! +//! The owner token comes through the provider's real +//! authorize/token loop; the read-only and expired tokens are +//! minted directly with the provider's signer (the live +//! provider's single account holds every role, so a low-role +//! token can only be produced at this level — the denial it +//! proves is a property of the consumer's gate, not of any one +//! account). + +use axum::body::Body; +use axum::http::{header, Request, StatusCode}; +use idp_provider::audit::AuditLog; +use idp_provider::flow::FlowState; +use idp_provider::identities::IdentityStore; +use idp_provider::registry::{now_unix, url_encode, Account, Client, Identity, ProviderConfig}; +use idp_provider::signing::TokenSigner; +use idp_provider::verify::{reference_app, TokenVerifier}; +use idp_provider::{b64url, build_app_with_flow, Config, Jwk, Jwks}; +use rand_core::OsRng; +use rsa::traits::PublicKeyParts; +use rsa::{RsaPrivateKey, RsaPublicKey}; +use sha2::{Digest, Sha256}; +use std::path::PathBuf; +use std::sync::Arc; +use tower::ServiceExt; + +const ISSUER: &str = "http://127.0.0.1:8911"; +const CLIENT_ID: &str = "test-rp"; +const REDIRECT_URI: &str = "http://127.0.0.1:8912/callback"; +const OWNER_CREDENTIAL: &str = "test-owner-credential"; +const KID: &str = "test-kid"; + +struct Harness { + provider: axum::Router, + consumer: axum::Router, + signer: TokenSigner, +} + +fn jwks_for(pubkey: &RsaPublicKey) -> Jwks { + Jwks { + keys: vec![Jwk { + kty: "RSA".to_string(), + use_: "sig".to_string(), + alg: "RS256".to_string(), + kid: KID.to_string(), + x5t_s256: KID.to_string(), + n: b64url(&pubkey.n().to_bytes_be()), + e: b64url(&pubkey.e().to_bytes_be()), + }], + } +} + +fn harness() -> Harness { + let mut rng = OsRng; + let key = RsaPrivateKey::new(&mut rng, 2048).expect("generate throwaway key"); + let pubkey = RsaPublicKey::from(&key); + let credential_hash = { + let salt = b"0123456789abcdef"; + let hash = idp_provider::registry::pbkdf2_sha256(OWNER_CREDENTIAL.as_bytes(), salt, 1000); + format!("pbkdf2-sha256$1000${}${}", b64url(salt), b64url(&hash)) + }; + let registry = ProviderConfig { + account: Account { + account_id: "drew".to_string(), + display_name: "Drew".to_string(), + roles: ["owner", "orchestrator", "agent", "read-only"] + .iter() + .map(|s| s.to_string()) + .collect(), + identities: vec![Identity { + provider: "devtoday-local".to_string(), + subject: "drew".to_string(), + }], + local_credential_hash: credential_hash, + }, + allowlist: vec!["devtoday-local:drew".to_string()], + clients: vec![Client { + client_id: CLIENT_ID.to_string(), + name: "Test RP".to_string(), + redirect_uris: vec![REDIRECT_URI.to_string()], + }], + doors: vec![], + audit_db_path: None, + identity_db_path: None, + }; + let audit = Arc::new(AuditLog::open(None).expect("audit")); + let identities = Arc::new(IdentityStore::open(None).expect("identity store")); + let signer = TokenSigner::new(key.clone(), KID.to_string()); + let flow = Arc::new(FlowState::new( + registry, + TokenSigner::new(key, KID.to_string()), + audit, + identities, + vec![], + ISSUER.to_string(), + )); + let config = Config { + issuer: ISSUER.to_string(), + bind: "127.0.0.1:0".to_string(), + oidc_cert_path: PathBuf::new(), + provider_config_path: None, + signing_key_path: None, + audit_db_path: None, + identity_db_path: None, + oidc_cert_paths: vec![], + signing_key_paths: vec![], + oidc_active_kid: None, + }; + let provider = build_app_with_flow(config, jwks_for(&pubkey), Some(flow)); + let verifier = Arc::new(TokenVerifier::new(ISSUER, jwks_for(&pubkey))); + let consumer = reference_app(verifier); + Harness { + provider, + consumer, + signer, + } +} + +fn form_body(pairs: &[(&str, &str)]) -> String { + pairs + .iter() + .map(|(k, v)| format!("{}={}", url_encode(k), url_encode(v))) + .collect::>() + .join("&") +} + +/// Run the provider's real loop and return (id_token, access_token). +async fn owner_tokens(provider: &axum::Router) -> (String, String) { + let verifier = "consumer-test-verifier-0123456789-abcdefghij"; + let challenge = b64url(&Sha256::digest(verifier.as_bytes())); + let resp = provider + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/authorize") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(form_body(&[ + ("response_type", "code"), + ("client_id", CLIENT_ID), + ("redirect_uri", REDIRECT_URI), + ("scope", "openid"), + ("state", "consumer-test"), + ("nonce", "consumer-test"), + ("code_challenge", &challenge), + ("code_challenge_method", "S256"), + ("login_id", "drew"), + ("credential", OWNER_CREDENTIAL), + ]))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::FOUND, "authorize redirects"); + let location = resp + .headers() + .get(header::LOCATION) + .unwrap() + .to_str() + .unwrap() + .to_string(); + let code = location + .split("code=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .to_string(); + let resp = provider + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/token") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(form_body(&[ + ("grant_type", "authorization_code"), + ("code", &code), + ("redirect_uri", REDIRECT_URI), + ("client_id", CLIENT_ID), + ("code_verifier", verifier), + ]))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK, "token issued"); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let tokens: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + ( + tokens["id_token"].as_str().unwrap().to_string(), + tokens["access_token"].as_str().unwrap().to_string(), + ) +} + +fn mint(signer: &TokenSigner, roles: &[&str], exp_offset: i64, token_use: &str) -> String { + let now = now_unix(); + signer + .sign_jwt(&serde_json::json!({ + "iss": ISSUER, + "sub": "drew", + "aud": CLIENT_ID, + "iat": now, + "exp": now + exp_offset, + "scope": "openid", + "roles": roles, + "preferred_username": "devtoday-local:drew", + "token_use": token_use, + })) + .expect("mint token") +} + +async fn call( + app: &axum::Router, + method: &str, + uri: &str, + token: Option<&str>, +) -> (StatusCode, serde_json::Value) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(t) = token { + builder = builder.header(header::AUTHORIZATION, format!("Bearer {t}")); + } + let resp = app + .clone() + .oneshot(builder.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null); + (status, body) +} + +#[tokio::test] +async fn consumer_verifies_tokens_and_gates_writes_on_roles() { + let h = harness(); + let (id_token, access_token) = owner_tokens(&h.provider).await; + + // Owner token (all roles, through the real loop): read + write. + let (status, body) = call(&h.consumer, "GET", "/read", Some(&access_token)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["sub"], "drew"); + let (status, body) = call(&h.consumer, "POST", "/write", Some(&access_token)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["written"], true); + + // Read-only token: read passes, the write gate refuses. + let readonly = mint(&h.signer, &["read-only"], 300, "access"); + let (status, _) = call(&h.consumer, "GET", "/read", Some(&readonly)).await; + assert_eq!(status, StatusCode::OK); + let (status, body) = call(&h.consumer, "POST", "/write", Some(&readonly)).await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "write gate refuses read-only" + ); + assert!(body["error"].as_str().unwrap().contains("roles")); + + // An ID token is not an access token. + let (status, _) = call(&h.consumer, "GET", "/read", Some(&id_token)).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + // Expired token, garbage token, missing token: all 401. + let expired = mint(&h.signer, &["owner"], -60, "access"); + let (status, _) = call(&h.consumer, "POST", "/write", Some(&expired)).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _) = call(&h.consumer, "GET", "/read", Some("not.a.token")).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _) = call(&h.consumer, "GET", "/read", None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); +}