From 715517a5deba77ce989476b90b301cf99c4d4060 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:09:40 +0200 Subject: [PATCH 1/4] feat(auth): define private service rpc contract --- .../migrations/0006_service_identities.sql | 3 +++ docs/architecture/service-rpc.md | 6 +++++ proto/piquel/auth/v1/auth.proto | 23 +++++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 crates/database/migrations/0006_service_identities.sql create mode 100644 docs/architecture/service-rpc.md create mode 100644 proto/piquel/auth/v1/auth.proto diff --git a/crates/database/migrations/0006_service_identities.sql b/crates/database/migrations/0006_service_identities.sql new file mode 100644 index 000000000..a3f94246a --- /dev/null +++ b/crates/database/migrations/0006_service_identities.sql @@ -0,0 +1,3 @@ +CREATE TABLE service_identities (id TEXT PRIMARY KEY, display_name TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now()); +CREATE TABLE service_identity_keys (id UUID PRIMARY KEY, service_id TEXT NOT NULL REFERENCES service_identities(id) ON DELETE CASCADE, kid TEXT NOT NULL, algorithm TEXT NOT NULL, public_key BYTEA NOT NULL, not_before TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, revoked_at TIMESTAMPTZ, UNIQUE (service_id, kid)); +CREATE TABLE service_rpc_permissions (service_id TEXT NOT NULL REFERENCES service_identities(id) ON DELETE CASCADE, method TEXT NOT NULL, PRIMARY KEY (service_id, method)); diff --git a/docs/architecture/service-rpc.md b/docs/architecture/service-rpc.md new file mode 100644 index 000000000..45a6954c0 --- /dev/null +++ b/docs/architecture/service-rpc.md @@ -0,0 +1,6 @@ +# Private service RPC + +`piquel.auth.v1.AuthService` is private gRPC only. Production callers authenticate +with a distinct, short-lived service token for `piquel-internal-api`; browser +code never receives service credentials. Ordinary product requests continue to +validate Piquel user access JWTs locally and never call `ValidateAccessToken`. diff --git a/proto/piquel/auth/v1/auth.proto b/proto/piquel/auth/v1/auth.proto new file mode 100644 index 000000000..ecc11ab29 --- /dev/null +++ b/proto/piquel/auth/v1/auth.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package piquel.auth.v1; + +service AuthService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); + rpc BatchGetUsers(BatchGetUsersRequest) returns (BatchGetUsersResponse); + rpc GetSessionStatus(GetSessionStatusRequest) returns (GetSessionStatusResponse); + rpc RevokeSession(RevokeSessionRequest) returns (RevokeSessionResponse); + rpc RevokeAllUserSessions(RevokeAllUserSessionsRequest) returns (RevokeAllUserSessionsResponse); + rpc GetServiceConfiguration(GetServiceConfigurationRequest) returns (GetServiceConfigurationResponse); +} +message GetUserRequest { string user_id = 1; reserved 2; reserved "include_private_fields"; } +message GetUserResponse { string user_id = 1; string display_name = 2; string account_status = 3; } +message BatchGetUsersRequest { repeated string user_ids = 1; } +message BatchGetUsersResponse { repeated GetUserResponse users = 1; } +message GetSessionStatusRequest { string session_id = 1; } +message GetSessionStatusResponse { bool active = 1; string user_id = 2; } +message RevokeSessionRequest { string session_id = 1; } +message RevokeSessionResponse { bool revoked = 1; } +message RevokeAllUserSessionsRequest { string user_id = 1; } +message RevokeAllUserSessionsResponse { uint32 revoked_count = 1; } +message GetServiceConfigurationRequest {} +message GetServiceConfigurationResponse { string issuer = 1; string jwks_uri = 2; } From eb49d613f13a1d83c90999880e1a1fc879d63be6 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:53:25 +0200 Subject: [PATCH 2/4] fix(auth): implement mTLS service RPC and token exchange --- Cargo.toml | 5 + apps/auth-service/Cargo.toml | 2 + apps/auth-service/src/lib.rs | 13 +- apps/auth-service/src/main.rs | 48 ++- apps/auth-service/src/oidc.rs | 25 +- apps/auth-service/src/service_rpc.rs | 284 ++++++++++++++++++ crates/auth-client/Cargo.toml | 18 ++ crates/auth-client/src/lib.rs | 131 ++++++++ crates/auth-sdk/Cargo.toml | 1 + crates/auth-sdk/src/lib.rs | 1 + .../migrations/0006_service_identities.sql | 4 +- crates/database/src/models.rs | 8 + crates/database/src/repositories.rs | 52 +++- crates/service-auth/Cargo.toml | 27 ++ crates/service-auth/build.rs | 16 + crates/service-auth/src/lib.rs | 45 +++ proto/piquel/auth/v1/auth.proto | 5 + 17 files changed, 669 insertions(+), 16 deletions(-) create mode 100644 apps/auth-service/src/service_rpc.rs create mode 100644 crates/auth-client/Cargo.toml create mode 100644 crates/auth-client/src/lib.rs create mode 100644 crates/service-auth/Cargo.toml create mode 100644 crates/service-auth/build.rs create mode 100644 crates/service-auth/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 98097f5c4..8ba0ad867 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,8 @@ members = [ "crates/auth-protocol", "crates/auth-middleware", "crates/auth-sdk", + "crates/auth-client", + "crates/service-auth", "crates/configuration", "crates/database", "crates/telemetry", @@ -37,6 +39,7 @@ http-body-util = "0.1" jsonwebtoken = "9.3" openssl = { version = "0.10", features = ["vendored"] } p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } +prost = "0.13" rand = "0.8" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1.0", features = ["derive"] } @@ -44,6 +47,8 @@ serde_json = "1.0" sha2 = "0.10" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" +tonic = { version = "0.12", features = ["tls"] } +tonic-build = "0.12" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time", "sync"] } tower = { version = "0.5", features = ["util"] } tower-http = { version = "0.6", features = ["trace"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 09638fdff..12e682557 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -19,6 +19,7 @@ p256.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } piquel-configuration = { path = "../../crates/configuration" } piquel-repository = { path = "../../crates/database" } +piquel-service-auth = { path = "../../crates/service-auth" } piquel-telemetry = { path = "../../crates/telemetry" } serde.workspace = true serde_json.workspace = true @@ -27,6 +28,7 @@ rand.workspace = true reqwest.workspace = true thiserror.workspace = true tokio.workspace = true +tonic.workspace = true tracing.workspace = true unicode-normalization.workspace = true url.workspace = true diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 56d0bb07f..0dd5599fe 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -20,12 +20,14 @@ mod federation; pub use federation::{FederationApplication, ProviderConfiguration}; #[allow(dead_code)] mod oidc; -pub use oidc::{Es256KeyProvider, OidcApplication}; +pub use oidc::{Es256KeyProvider, KeyProvider, OidcApplication}; #[allow(dead_code)] mod passkey; pub use passkey::PasskeyApplication; +mod service_rpc; #[allow(dead_code)] mod session; +pub use service_rpc::ServiceRpcApplication; /// Typed auth-service configuration. #[derive(Clone, Debug)] @@ -50,6 +52,12 @@ pub struct AuthConfig { pub github: ProviderConfiguration, /// Google OIDC client configuration. pub google: ProviderConfiguration, + /// Server certificate for the mTLS private RPC listener. + pub rpc_tls_certificate: SecretReference, + /// Server private key for the mTLS private RPC listener. + pub rpc_tls_private_key: SecretReference, + /// Client CA used to require private-RPC client certificates. + pub rpc_client_ca: SecretReference, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -97,6 +105,9 @@ impl AuthConfig { client_id: required("AUTH_GOOGLE_CLIENT_ID")?, client_secret: SecretReference::parse(&required("AUTH_GOOGLE_CLIENT_SECRET")?)?, }, + rpc_tls_certificate: SecretReference::parse(&required("AUTH_RPC_TLS_CERTIFICATE")?)?, + rpc_tls_private_key: SecretReference::parse(&required("AUTH_RPC_TLS_PRIVATE_KEY")?)?, + rpc_client_ca: SecretReference::parse(&required("AUTH_RPC_CLIENT_CA")?)?, }) } } diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index d533388fa..463e0e5c8 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -2,12 +2,13 @@ use auth_service::{ AuthConfig, Es256KeyProvider, FederationApplication, OidcApplication, PasskeyApplication, - ProductionReadiness, router, + ProductionReadiness, ServiceRpcApplication, router, }; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; #[tokio::main] +#[allow(clippy::too_many_lines)] async fn main() -> anyhow::Result<()> { piquel_telemetry::init("auth_service=info"); let config = AuthConfig::from_environment()?; @@ -37,14 +38,14 @@ async fn main() -> anyhow::Result<()> { database.clone(), config.public_base_url.as_url(), key_secret.expose_secret(), - keys, + keys.clone(), ) } else { OidcApplication::new( database.clone(), config.public_base_url.as_url(), key_secret.expose_secret(), - keys, + keys.clone(), ) } .map_err(|()| anyhow::anyhow!("invalid OIDC configuration"))?; @@ -63,9 +64,22 @@ async fn main() -> anyhow::Result<()> { config.google, ) }?; + let rpc = ServiceRpcApplication::new( + database.clone(), + config + .public_base_url + .as_url() + .as_str() + .trim_end_matches('/') + .to_owned(), + keys, + ); + let rpc_certificate = config.rpc_tls_certificate.resolve()?; + let rpc_private_key = config.rpc_tls_private_key.resolve()?; + let rpc_client_ca = config.rpc_client_ca.resolve()?; let listener = tokio::net::TcpListener::bind(listener_address).await?; tracing::info!(%listener_address, "auth service listening"); - axum::serve( + let public = axum::serve( listener, router( Arc::new(ProductionReadiness::new(database, config.key_provider)), @@ -73,9 +87,29 @@ async fn main() -> anyhow::Result<()> { Some(oidc), Some(federation), ), - ) - .with_graceful_shutdown(shutdown_signal()) - .await?; + ); + let tls = tonic::transport::ServerTlsConfig::new() + .identity(tonic::transport::Identity::from_pem( + rpc_certificate.expose_secret(), + rpc_private_key.expose_secret(), + )) + .client_ca_root(tonic::transport::Certificate::from_pem( + rpc_client_ca.expose_secret(), + )); + let private = tonic::transport::Server::builder() + .tls_config(tls)? + .add_service( + rpc.clone() + .token_server() + .max_decoding_message_size(16 * 1024), + ) + .add_service(rpc.auth_server().max_decoding_message_size(1024 * 1024)) + .serve(config.internal_listener); + tokio::select! { + result = public => result?, + result = private => result?, + () = shutdown_signal() => {}, + } Ok(()) } diff --git a/apps/auth-service/src/oidc.rs b/apps/auth-service/src/oidc.rs index 5334dd022..275b4e6d1 100644 --- a/apps/auth-service/src/oidc.rs +++ b/apps/auth-service/src/oidc.rs @@ -37,9 +37,22 @@ const ACCESS_TOKEN_SECONDS: i64 = 300; /// Supplies a stable active ES256 key and its public JWK. pub trait KeyProvider: Send + Sync { + /// Signs a JSON claim set with the active asymmetric key. + /// + /// # Errors + /// + /// Returns an error when claims cannot be serialized or signed. + #[allow(clippy::result_unit_err)] fn sign(&self, token_type: &str, claims: &Value) -> Result; + /// Publishes the provider's public verification keys. fn jwks(&self) -> Value; - fn verify_access(&self, token: &str, issuer: &str) -> Result; + /// Verifies a locally issued token with an exact type and issuer. + /// + /// # Errors + /// + /// Returns an error for malformed, expired, mismatched, or invalidly signed tokens. + #[allow(clippy::result_unit_err)] + fn verify(&self, token: &str, token_type: &str, issuer: &str) -> Result; } /// Local PEM-backed key provider. Production callers resolve the PEM through a secret reference. @@ -98,7 +111,7 @@ impl KeyProvider for Es256KeyProvider { }]}) } - fn verify_access(&self, token: &str, issuer: &str) -> Result { + fn verify(&self, token: &str, token_type: &str, issuer: &str) -> Result { if token.len() > 8192 { return Err(()); } @@ -114,7 +127,7 @@ impl KeyProvider for Es256KeyProvider { .map_err(|_| ())?; if header.get("alg") != Some(&json!("ES256")) || header.get("kid") != Some(&json!(self.kid)) - || header.get("typ") != Some(&json!("at+jwt")) + || header.get("typ") != Some(&json!(token_type)) { return Err(()); } @@ -775,7 +788,7 @@ async fn userinfo( .ok_or_else(ApiError::unauthorized)?; let claims = app .keys - .verify_access(token, &app.issuer) + .verify(token, "at+jwt", &app.issuer) .map_err(|()| ApiError::unauthorized())?; let scopes: BTreeSet<_> = claims .get("scope") @@ -999,13 +1012,13 @@ mod tests { &json!({"iss":"https://issuer","exp":now+60,"iat":now}), ) .expect("sign"); - assert!(keys.verify_access(&id, "https://issuer").is_err()); + assert!(keys.verify(&id, "at+jwt", "https://issuer").is_err()); let access = keys .sign( "at+jwt", &json!({"iss":"https://issuer","exp":now+60,"iat":now}), ) .expect("sign"); - assert!(keys.verify_access(&access, "https://issuer").is_ok()); + assert!(keys.verify(&access, "at+jwt", "https://issuer").is_ok()); } } diff --git a/apps/auth-service/src/service_rpc.rs b/apps/auth-service/src/service_rpc.rs new file mode 100644 index 000000000..5fdeb444d --- /dev/null +++ b/apps/auth-service/src/service_rpc.rs @@ -0,0 +1,284 @@ +//! mTLS-protected service-token issuance and permissioned private RPC. + +use crate::KeyProvider; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{TimeZone, Utc}; +use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier}; +use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_repository::Database; +use piquel_service_auth::v1::{ + self, auth_service_server::AuthService, service_token_service_server::ServiceTokenService, +}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{str::FromStr, sync::Arc}; +use tonic::{Request, Response, Status}; + +/// Private RPC implementation shared by the token and authority services. +#[derive(Clone)] +pub struct ServiceRpcApplication { + database: Database, + issuer: String, + keys: Arc, +} +impl ServiceRpcApplication { + /// Constructs the private RPC service. + #[must_use] + pub fn new(database: Database, issuer: String, keys: Arc) -> Self { + Self { + database, + issuer, + keys, + } + } + /// Builds the permissioned authority server. + #[must_use] + pub fn auth_server(self) -> v1::auth_service_server::AuthServiceServer { + v1::auth_service_server::AuthServiceServer::new(self) + } + /// Builds the replay-protected service-token server. + #[must_use] + pub fn token_server(self) -> v1::service_token_service_server::ServiceTokenServiceServer { + v1::service_token_service_server::ServiceTokenServiceServer::new(self) + } +} + +#[derive(Deserialize)] +struct AssertionHeader { + alg: String, + typ: String, + kid: String, +} +#[derive(Deserialize)] +struct AssertionClaims { + iss: String, + sub: String, + aud: String, + jti: String, + iat: i64, + exp: i64, +} +impl ServiceRpcApplication { + async fn verify_assertion(&self, token: &str) -> Result<(String, Vec), Status> { + if token.len() > 8192 { + return Err(Status::unauthenticated("invalid service credential")); + } + let mut parts = token.split('.'); + let hp = parts.next().ok_or_else(auth_error)?; + let cp = parts.next().ok_or_else(auth_error)?; + let sp = parts.next().ok_or_else(auth_error)?; + if parts.next().is_some() { + return Err(auth_error()); + } + let header: AssertionHeader = decode_part(hp)?; + let claims: AssertionClaims = decode_part(cp)?; + let now = Utc::now().timestamp(); + if header.alg != "ES256" + || header.typ != "client-assertion+jwt" + || claims.iss != claims.sub + || claims.aud != "piquel-service-token" + || claims.exp <= now + || claims.exp > claims.iat + 60 + || claims.iat > now + 30 + { + return Err(auth_error()); + } + let identity = self + .database + .service_identities() + .find_active_key(&claims.iss, &header.kid) + .await + .map_err(internal)? + .ok_or_else(auth_error)?; + let key = VerifyingKey::from_sec1_bytes(&identity.public_key).map_err(|_| auth_error())?; + let signature = + Signature::from_slice(&URL_SAFE_NO_PAD.decode(sp).map_err(|_| auth_error())?) + .map_err(|_| auth_error())?; + key.verify(format!("{hp}.{cp}").as_bytes(), &signature) + .map_err(|_| auth_error())?; + let jti = TokenId::from_str(&claims.jti).map_err(|_| auth_error())?; + let expires = Utc + .timestamp_opt(claims.exp, 0) + .single() + .ok_or_else(auth_error)?; + self.database + .service_identities() + .record_assertion(jti, &identity.id, expires) + .await + .map_err(|_| auth_error())?; + Ok((identity.id, identity.permissions)) + } + #[allow(clippy::result_large_err)] + fn authorize(&self, request: &Request, method: &str) -> Result { + let token = request + .metadata() + .get("authorization") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")) + .ok_or_else(auth_error)?; + let claims = self + .keys + .verify(token, "service+jwt", &self.issuer) + .map_err(|()| auth_error())?; + if claims.get("aud") != Some(&json!("piquel-internal-api")) + || !claims + .get("permissions") + .and_then(Value::as_array) + .is_some_and(|values| values.iter().any(|value| value == method)) + { + return Err(Status::permission_denied("service is not permitted")); + } + Ok(claims) + } +} +#[allow(clippy::result_large_err)] +fn decode_part Deserialize<'de>>(part: &str) -> Result { + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(part).map_err(|_| auth_error())?) + .map_err(|_| auth_error()) +} +fn auth_error() -> Status { + Status::unauthenticated("invalid service credential") +} +fn internal(_: piquel_repository::DatabaseError) -> Status { + Status::internal("service operation failed") +} + +#[tonic::async_trait] +impl ServiceTokenService for ServiceRpcApplication { + async fn issue_service_token( + &self, + request: Request, + ) -> Result, Status> { + let (service_id, permissions) = self + .verify_assertion(&request.into_inner().client_assertion) + .await?; + let now = Utc::now().timestamp(); + let token=self.keys.sign("service+jwt",&json!({"iss":self.issuer,"sub":service_id,"aud":"piquel-internal-api","jti":TokenId::new(),"permissions":permissions,"iat":now,"exp":now+300})).map_err(|()|Status::internal("token issuance failed"))?; + Ok(Response::new(v1::IssueServiceTokenResponse { + access_token: token, + expires_in: 300, + token_type: "Bearer".into(), + })) + } +} + +#[tonic::async_trait] +impl AuthService for ServiceRpcApplication { + async fn get_user( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "GetUser")?; + let id = UserId::from_str(&request.get_ref().user_id) + .map_err(|_| Status::invalid_argument("invalid user id"))?; + let user = self + .database + .users() + .find_by_id(id) + .await + .map_err(internal)? + .ok_or_else(|| Status::not_found("user not found"))?; + Ok(Response::new(user_response(user))) + } + async fn batch_get_users( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "BatchGetUsers")?; + if request.get_ref().user_ids.len() > 100 { + return Err(Status::invalid_argument("batch too large")); + } + let mut users = Vec::new(); + for id in &request.get_ref().user_ids { + let id = + UserId::from_str(id).map_err(|_| Status::invalid_argument("invalid user id"))?; + if let Some(user) = self + .database + .users() + .find_by_id(id) + .await + .map_err(internal)? + { + users.push(user_response(user)); + } + } + Ok(Response::new(v1::BatchGetUsersResponse { users })) + } + async fn get_session_status( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "GetSessionStatus")?; + let id = SessionId::from_str(&request.get_ref().session_id) + .map_err(|_| Status::invalid_argument("invalid session id"))?; + let session = self + .database + .sessions() + .find_by_id(id) + .await + .map_err(internal)?; + let (active, user_id) = session.map_or((false, String::new()), |session| { + ( + session.revoked_at.is_none() && session.expires_at > Utc::now(), + session.user_id.to_string(), + ) + }); + Ok(Response::new(v1::GetSessionStatusResponse { + active, + user_id, + })) + } + async fn revoke_session( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "RevokeSession")?; + let id = SessionId::from_str(&request.get_ref().session_id) + .map_err(|_| Status::invalid_argument("invalid session id"))?; + let revoked = self + .database + .sessions() + .revoke(id) + .await + .map_err(internal)?; + Ok(Response::new(v1::RevokeSessionResponse { revoked })) + } + async fn revoke_all_user_sessions( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "RevokeAllUserSessions")?; + let id = UserId::from_str(&request.get_ref().user_id) + .map_err(|_| Status::invalid_argument("invalid user id"))?; + let count = self + .database + .sessions() + .revoke_all_for_user(id) + .await + .map_err(internal)?; + Ok(Response::new(v1::RevokeAllUserSessionsResponse { + revoked_count: u32::try_from(count).unwrap_or(u32::MAX), + })) + } + async fn get_service_configuration( + &self, + request: Request, + ) -> Result, Status> { + self.authorize(&request, "GetServiceConfiguration")?; + Ok(Response::new(v1::GetServiceConfigurationResponse { + issuer: self.issuer.clone(), + jwks_uri: format!("{}/.well-known/jwks.json", self.issuer), + })) + } +} +fn user_response(user: piquel_repository::StoredUser) -> v1::GetUserResponse { + v1::GetUserResponse { + user_id: user.id.to_string(), + display_name: user.display_name, + account_status: match user.status { + piquel_auth_protocol::AccountStatus::Active => "active", + piquel_auth_protocol::AccountStatus::Disabled => "disabled", + } + .into(), + } +} diff --git a/crates/auth-client/Cargo.toml b/crates/auth-client/Cargo.toml new file mode 100644 index 000000000..d6fc3e667 --- /dev/null +++ b/crates/auth-client/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "piquel-auth-client" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +chrono.workspace = true +p256.workspace = true +piquel-service-auth = { path = "../service-auth" } +thiserror.workspace = true +tokio.workspace = true +tonic.workspace = true + +[lints] +workspace = true diff --git a/crates/auth-client/src/lib.rs b/crates/auth-client/src/lib.rs new file mode 100644 index 000000000..8aa0b9aee --- /dev/null +++ b/crates/auth-client/src/lib.rs @@ -0,0 +1,131 @@ +//! Concurrency-safe private RPC client with short-lived service-token caching. +#![allow(missing_docs)] +#![allow(clippy::missing_errors_doc, clippy::too_many_arguments)] + +use chrono::Utc; +use p256::ecdsa::SigningKey; +use piquel_service_auth::{ + create_client_assertion, + v1::{ + self, auth_service_client::AuthServiceClient, + service_token_service_client::ServiceTokenServiceClient, + }, +}; +use std::{sync::Arc, time::Duration}; +use thiserror::Error; +use tokio::sync::Mutex; +use tonic::{ + Request, + metadata::MetadataValue, + transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}, +}; + +#[derive(Debug, Error)] +#[error("private authentication RPC failed")] +pub struct ClientError; +struct CachedToken { + value: String, + renew_at: i64, +} +#[derive(Clone)] +pub struct ServiceAuthClient { + auth: AuthServiceClient, + tokens: ServiceTokenServiceClient, + service_id: String, + kid: String, + audience: String, + key: Arc, + cache: Arc>>, +} +impl ServiceAuthClient { + pub async fn connect( + uri: String, + domain: String, + ca: Vec, + identity_certificate: Vec, + identity_key: Vec, + service_id: String, + kid: String, + key: SigningKey, + ) -> Result { + let tls = ClientTlsConfig::new() + .domain_name(domain) + .ca_certificate(Certificate::from_pem(ca)) + .identity(Identity::from_pem(identity_certificate, identity_key)); + let channel = Endpoint::from_shared(uri) + .map_err(|_| ClientError)? + .tls_config(tls) + .map_err(|_| ClientError)? + .connect_timeout(Duration::from_secs(3)) + .timeout(Duration::from_secs(5)) + .connect() + .await + .map_err(|_| ClientError)?; + Ok(Self { + auth: AuthServiceClient::new(channel.clone()), + tokens: ServiceTokenServiceClient::new(channel), + service_id, + kid, + audience: "piquel-service-token".into(), + key: Arc::new(key), + cache: Arc::new(Mutex::new(None)), + }) + } + async fn token(&mut self) -> Result { + let mut cache = self.cache.lock().await; + let now = Utc::now().timestamp(); + if let Some(token) = cache.as_ref().filter(|token| token.renew_at > now) { + return Ok(token.value.clone()); + } + let assertion = create_client_assertion( + &self.service_id, + &self.kid, + &self.audience, + self.key.as_ref(), + ) + .map_err(|_| ClientError)?; + let response = self + .tokens + .issue_service_token(v1::IssueServiceTokenRequest { + client_assertion: assertion, + }) + .await + .map_err(|_| ClientError)? + .into_inner(); + *cache = Some(CachedToken { + value: response.access_token.clone(), + renew_at: now + i64::from(response.expires_in) - 30, + }); + Ok(response.access_token) + } + async fn authorized(&mut self, message: T) -> Result, ClientError> { + let token = self.token().await?; + let mut request = Request::new(message); + request.set_timeout(Duration::from_secs(3)); + request.metadata_mut().insert( + "authorization", + MetadataValue::try_from(format!("Bearer {token}")).map_err(|_| ClientError)?, + ); + Ok(request) + } + pub async fn get_user(&mut self, user_id: String) -> Result { + let request = self.authorized(v1::GetUserRequest { user_id }).await?; + self.auth + .get_user(request) + .await + .map(tonic::Response::into_inner) + .map_err(|_| ClientError) + } + pub async fn revoke_session(&mut self, session_id: String) -> Result { + let request = self + .authorized(v1::RevokeSessionRequest { session_id }) + .await?; + Ok(self + .auth + .revoke_session(request) + .await + .map_err(|_| ClientError)? + .into_inner() + .revoked) + } +} diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml index bd2feaaa4..cc70d922d 100644 --- a/crates/auth-sdk/Cargo.toml +++ b/crates/auth-sdk/Cargo.toml @@ -11,6 +11,7 @@ base64.workspace = true chrono.workspace = true p256.workspace = true piquel-auth-middleware = { path = "../auth-middleware" } +piquel-auth-client = { path = "../auth-client" } piquel-auth-protocol = { path = "../auth-protocol" } rand.workspace = true reqwest.workspace = true diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index 1801561d3..7ef07831a 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -1,6 +1,7 @@ //! Downstream facade for local token validation and server-side OIDC flows. #![allow(missing_docs)] +pub use piquel_auth_client::{ClientError as ServiceClientError, ServiceAuthClient}; pub use piquel_auth_middleware::{ AuthMiddleware, AuthenticatedUser, AuthenticationError, ConfigurationError, JwksFetcher, }; diff --git a/crates/database/migrations/0006_service_identities.sql b/crates/database/migrations/0006_service_identities.sql index a3f94246a..811a82759 100644 --- a/crates/database/migrations/0006_service_identities.sql +++ b/crates/database/migrations/0006_service_identities.sql @@ -1,3 +1,5 @@ CREATE TABLE service_identities (id TEXT PRIMARY KEY, display_name TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now()); -CREATE TABLE service_identity_keys (id UUID PRIMARY KEY, service_id TEXT NOT NULL REFERENCES service_identities(id) ON DELETE CASCADE, kid TEXT NOT NULL, algorithm TEXT NOT NULL, public_key BYTEA NOT NULL, not_before TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, revoked_at TIMESTAMPTZ, UNIQUE (service_id, kid)); +CREATE TABLE service_identity_keys (id UUID PRIMARY KEY, service_id TEXT NOT NULL REFERENCES service_identities(id) ON DELETE CASCADE, kid TEXT NOT NULL, algorithm TEXT NOT NULL CHECK(algorithm='ES256'), public_key BYTEA NOT NULL, not_before TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, revoked_at TIMESTAMPTZ, UNIQUE (service_id, kid)); CREATE TABLE service_rpc_permissions (service_id TEXT NOT NULL REFERENCES service_identities(id) ON DELETE CASCADE, method TEXT NOT NULL, PRIMARY KEY (service_id, method)); +CREATE TABLE service_assertion_replays (jti UUID PRIMARY KEY, service_id TEXT NOT NULL REFERENCES service_identities(id), expires_at TIMESTAMPTZ NOT NULL); +CREATE INDEX service_assertion_replays_expiry_idx ON service_assertion_replays(expires_at); diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index 73e31443b..c781ec509 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -264,3 +264,11 @@ pub struct StoredExternalIdentity { pub subject: String, pub linked_email: String, } + +#[derive(Clone, Debug)] +pub struct StoredServiceIdentity { + pub id: String, + pub kid: String, + pub public_key: Vec, + pub permissions: Vec, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 8b8db22b0..76889b740 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -7,7 +7,7 @@ use crate::{ InsertFederationTransaction, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, RotatedRefreshToken, StoredAuthorizationRequest, StoredEmail, StoredExternalIdentity, StoredOidcClient, - StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, + StoredPasskey, StoredServiceIdentity, StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; @@ -695,6 +695,56 @@ fn stored_external_identity( .map_err(|_| DatabaseError::InvalidStoredData)?, }) } + +impl ServiceIdentityRepository<'_> { + pub async fn find_active_key( + &mut self, + service_id: &str, + kid: &str, + ) -> Result, DatabaseError> { + let row=fetch_optional!(self,sqlx::query("SELECT s.id,k.kid,k.public_key,COALESCE(jsonb_agg(p.method) FILTER(WHERE p.method IS NOT NULL),'[]'::jsonb) permissions FROM service_identities s JOIN service_identity_keys k ON k.service_id=s.id LEFT JOIN service_rpc_permissions p ON p.service_id=s.id WHERE s.id=$1 AND k.kid=$2 AND s.enabled AND k.algorithm='ES256' AND k.revoked_at IS NULL AND k.not_before<=now() AND k.expires_at>now() GROUP BY s.id,k.kid,k.public_key").bind(service_id).bind(kid))?; + row.map(|row| { + Ok(StoredServiceIdentity { + id: row + .try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + kid: row + .try_get("kid") + .map_err(|_| DatabaseError::InvalidStoredData)?, + public_key: row + .try_get("public_key") + .map_err(|_| DatabaseError::InvalidStoredData)?, + permissions: serde_json::from_value( + row.try_get("permissions") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + }) + .transpose() + } + pub async fn record_assertion( + &mut self, + jti: TokenId, + service_id: &str, + expires_at: chrono::DateTime, + ) -> Result<(), DatabaseError> { + execute!( + self, + sqlx::query("DELETE FROM service_assertion_replays WHERE expires_at<=now()") + )?; + execute!( + self, + sqlx::query( + "INSERT INTO service_assertion_replays(jti,service_id,expires_at) VALUES($1,$2,$3)" + ) + .bind(jti.as_uuid()) + .bind(service_id) + .bind(expires_at) + )?; + Ok(()) + } +} fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row .try_get("authentication_methods") diff --git a/crates/service-auth/Cargo.toml b/crates/service-auth/Cargo.toml new file mode 100644 index 000000000..f22569f66 --- /dev/null +++ b/crates/service-auth/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "piquel-service-auth" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +build = "build.rs" + +[dependencies] +base64.workspace = true +chrono.workspace = true +p256.workspace = true +piquel-auth-protocol = { path = "../auth-protocol" } +prost.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tonic.workspace = true + +[build-dependencies] +prost-build = "0.13" +protoc-bin-vendored = "3" +tonic-build.workspace = true + +[lints] +workspace = true diff --git a/crates/service-auth/build.rs b/crates/service-auth/build.rs new file mode 100644 index 000000000..84450c71c --- /dev/null +++ b/crates/service-auth/build.rs @@ -0,0 +1,16 @@ +#![allow(missing_docs)] +fn main() { + let protoc = protoc_bin_vendored::protoc_bin_path().expect("vendored protoc"); + let mut prost = prost_build::Config::new(); + prost.protoc_executable(protoc); + tonic_build::configure() + .build_server(true) + .build_client(true) + .compile_protos_with_config( + prost, + &["../../proto/piquel/auth/v1/auth.proto"], + &["../../proto"], + ) + .expect("compile versioned auth protocol"); + println!("cargo:rerun-if-changed=../../proto/piquel/auth/v1/auth.proto"); +} diff --git a/crates/service-auth/src/lib.rs b/crates/service-auth/src/lib.rs new file mode 100644 index 000000000..6fc639360 --- /dev/null +++ b/crates/service-auth/src/lib.rs @@ -0,0 +1,45 @@ +//! Generated private RPC contract and client-assertion creation. +#![allow(missing_docs)] + +pub mod v1 { + #![allow(clippy::all, clippy::pedantic)] + tonic::include_proto!("piquel.auth.v1"); +} + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::Utc; +use p256::ecdsa::{Signature, SigningKey, signature::Signer}; +use piquel_auth_protocol::TokenId; +use serde_json::json; +use thiserror::Error; + +#[derive(Debug, Error)] +#[error("service assertion creation failed")] +pub struct AssertionError; +/// Creates a one-minute ES256 assertion for the private token service. +/// +/// # Errors +/// +/// Returns an error when identifiers are empty or serialization fails. +pub fn create_client_assertion( + service_id: &str, + kid: &str, + audience: &str, + key: &SigningKey, +) -> Result { + if service_id.is_empty() || kid.is_empty() { + return Err(AssertionError); + } + let now = Utc::now().timestamp(); + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg":"ES256","typ":"client-assertion+jwt","kid":kid})) + .map_err(|_| AssertionError)?, + ); + let payload=URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"iss":service_id,"sub":service_id,"aud":audience,"jti":TokenId::new(),"iat":now,"exp":now+60})).map_err(|_|AssertionError)?); + let input = format!("{header}.{payload}"); + let signature: Signature = key.sign(input.as_bytes()); + Ok(format!( + "{input}.{}", + URL_SAFE_NO_PAD.encode(signature.to_bytes()) + )) +} diff --git a/proto/piquel/auth/v1/auth.proto b/proto/piquel/auth/v1/auth.proto index ecc11ab29..b4922afb8 100644 --- a/proto/piquel/auth/v1/auth.proto +++ b/proto/piquel/auth/v1/auth.proto @@ -9,6 +9,11 @@ service AuthService { rpc RevokeAllUserSessions(RevokeAllUserSessionsRequest) returns (RevokeAllUserSessionsResponse); rpc GetServiceConfiguration(GetServiceConfigurationRequest) returns (GetServiceConfigurationResponse); } +service ServiceTokenService { + rpc IssueServiceToken(IssueServiceTokenRequest) returns (IssueServiceTokenResponse); +} +message IssueServiceTokenRequest { string client_assertion = 1; } +message IssueServiceTokenResponse { string access_token = 1; uint32 expires_in = 2; string token_type = 3; } message GetUserRequest { string user_id = 1; reserved 2; reserved "include_private_fields"; } message GetUserResponse { string user_id = 1; string display_name = 2; string account_status = 3; } message BatchGetUsersRequest { repeated string user_ids = 1; } From a82a6cedc045d1f1181131e0ab1e93715e3cd3e2 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:57:29 +0200 Subject: [PATCH 3/4] fix(auth): bind private RPC identity to mTLS certificates --- Cargo.lock | 486 ++++++++++++++++++++++++++- apps/auth-service/src/main.rs | 6 +- apps/auth-service/src/service_rpc.rs | 102 +++++- 3 files changed, 570 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f374320cc..d1dfd02a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -125,7 +125,7 @@ version = "0.1.0" dependencies = [ "anyhow", "async-trait", - "axum", + "axum 0.8.9", "base64 0.22.1", "chrono", "hmac", @@ -135,6 +135,7 @@ dependencies = [ "piquel-auth-protocol", "piquel-configuration", "piquel-repository", + "piquel-service-auth", "piquel-telemetry", "rand 0.8.7", "reqwest", @@ -143,7 +144,8 @@ dependencies = [ "sha2", "thiserror 2.0.18", "tokio", - "tower", + "tonic", + "tower 0.5.3", "tracing", "unicode-normalization", "url", @@ -157,13 +159,40 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core 0.4.5", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "itoa", + "matchit 0.7.3", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "sync_wrapper", + "tower 0.5.3", + "tower-layer", + "tower-service", +] + [[package]] name = "axum" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "axum-core", + "axum-core 0.5.6", "bytes", "form_urlencoded", "futures-util", @@ -173,7 +202,7 @@ dependencies = [ "hyper", "hyper-util", "itoa", - "matchit", + "matchit 0.8.4", "memchr", "mime", "percent-encoding", @@ -184,12 +213,32 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tower", + "tower 0.5.3", "tower-layer", "tower-service", "tracing", ] +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", +] + [[package]] name = "axum-core" version = "0.5.6" @@ -420,9 +469,9 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.1.7" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", "typenum", @@ -575,6 +624,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + [[package]] name = "ff" version = "0.13.1" @@ -591,6 +646,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flume" version = "0.11.1" @@ -602,6 +663,12 @@ dependencies = [ "spin", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" @@ -733,9 +800,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.7" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" dependencies = [ "typenum", "version_check", @@ -792,6 +859,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -803,6 +889,12 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.15.5" @@ -923,6 +1015,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -950,6 +1043,19 @@ dependencies = [ "webpki-roots 1.0.8", ] +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.20" @@ -967,7 +1073,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio", "tower-service", "tracing", @@ -1100,6 +1206,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -1116,6 +1232,15 @@ version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1191,6 +1316,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -1227,6 +1358,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + [[package]] name = "matchit" version = "0.8.4" @@ -1272,6 +1409,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + [[package]] name = "nom" version = "7.1.3" @@ -1497,12 +1640,54 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap 2.14.0", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piquel-auth-client" +version = "0.1.0" +dependencies = [ + "chrono", + "p256", + "piquel-service-auth", + "thiserror 2.0.18", + "tokio", + "tonic", +] + [[package]] name = "piquel-auth-middleware" version = "0.1.0" @@ -1536,6 +1721,7 @@ dependencies = [ "base64 0.22.1", "chrono", "p256", + "piquel-auth-client", "piquel-auth-middleware", "piquel-auth-protocol", "rand 0.8.7", @@ -1572,6 +1758,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "piquel-service-auth" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "chrono", + "p256", + "piquel-auth-protocol", + "prost", + "prost-build", + "protoc-bin-vendored", + "serde", + "serde_json", + "thiserror 2.0.18", + "tonic", + "tonic-build", +] + [[package]] name = "piquel-telemetry" version = "0.1.0" @@ -1637,6 +1841,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + [[package]] name = "primeorder" version = "0.13.6" @@ -1655,6 +1869,122 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prost" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "once_cell", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "prost-types" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16" +dependencies = [ + "prost", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" + [[package]] name = "quinn" version = "0.11.11" @@ -1668,7 +1998,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2", + "socket2 0.6.5", "thiserror 2.0.18", "tokio", "tracing", @@ -1706,7 +2036,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.5", "tracing", "windows-sys 0.61.2", ] @@ -1835,6 +2165,18 @@ dependencies = [ "bitflags 2.13.0", ] +[[package]] +name = "regex" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.15" @@ -1880,7 +2222,7 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls", - "tower", + "tower 0.5.3", "tower-http", "tower-service", "url", @@ -1949,12 +2291,26 @@ dependencies = [ "nom", ] +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138" dependencies = [ + "log", "once_cell", "ring", "rustls-pki-types", @@ -1963,6 +2319,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "rustls-pki-types" version = "1.15.0" @@ -2186,6 +2551,16 @@ dependencies = [ "serde", ] +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.5" @@ -2247,7 +2622,7 @@ dependencies = [ "futures-util", "hashbrown 0.15.5", "hashlink", - "indexmap", + "indexmap 2.14.0", "log", "memchr", "once_cell", @@ -2467,6 +2842,19 @@ dependencies = [ "syn", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -2582,7 +2970,7 @@ dependencies = [ "mio", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] @@ -2633,6 +3021,72 @@ dependencies = [ "tokio", ] +[[package]] +name = "tonic" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52" +dependencies = [ + "async-stream", + "async-trait", + "axum 0.7.9", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "prost", + "rustls-pemfile", + "socket2 0.5.10", + "tokio", + "tokio-rustls", + "tokio-stream", + "tower 0.4.13", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9557ce109ea773b399c9b9e5dca39294110b74f1f342cb347a80d1fce8c26a11" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "indexmap 1.9.3", + "pin-project", + "pin-project-lite", + "rand 0.8.7", + "slab", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "tower" version = "0.5.3" @@ -2661,7 +3115,7 @@ dependencies = [ "http", "http-body", "pin-project-lite", - "tower", + "tower 0.5.3", "tower-layer", "tower-service", "url", diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 463e0e5c8..a56edcd5b 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -5,7 +5,7 @@ use auth_service::{ ProductionReadiness, ServiceRpcApplication, router, }; use piquel_repository::Database; -use std::{net::SocketAddr, sync::Arc}; +use std::{net::SocketAddr, sync::Arc, time::Duration}; #[tokio::main] #[allow(clippy::too_many_lines)] @@ -98,6 +98,10 @@ async fn main() -> anyhow::Result<()> { )); let private = tonic::transport::Server::builder() .tls_config(tls)? + .timeout(Duration::from_secs(10)) + .concurrency_limit_per_connection(64) + .http2_keepalive_interval(Some(Duration::from_secs(30))) + .http2_keepalive_timeout(Some(Duration::from_secs(5))) .add_service( rpc.clone() .token_server() diff --git a/apps/auth-service/src/service_rpc.rs b/apps/auth-service/src/service_rpc.rs index 5fdeb444d..e549778bf 100644 --- a/apps/auth-service/src/service_rpc.rs +++ b/apps/auth-service/src/service_rpc.rs @@ -59,7 +59,11 @@ struct AssertionClaims { exp: i64, } impl ServiceRpcApplication { - async fn verify_assertion(&self, token: &str) -> Result<(String, Vec), Status> { + async fn verify_assertion( + &self, + token: &str, + peer_service_id: &str, + ) -> Result<(String, Vec), Status> { if token.len() > 8192 { return Err(Status::unauthenticated("invalid service credential")); } @@ -76,6 +80,7 @@ impl ServiceRpcApplication { if header.alg != "ES256" || header.typ != "client-assertion+jwt" || claims.iss != claims.sub + || claims.sub != peer_service_id || claims.aud != "piquel-service-token" || claims.exp <= now || claims.exp > claims.iat + 60 @@ -110,6 +115,7 @@ impl ServiceRpcApplication { } #[allow(clippy::result_large_err)] fn authorize(&self, request: &Request, method: &str) -> Result { + let peer_service_id = service_identity_from_peer(request)?; let token = request .metadata() .get("authorization") @@ -121,6 +127,7 @@ impl ServiceRpcApplication { .verify(token, "service+jwt", &self.issuer) .map_err(|()| auth_error())?; if claims.get("aud") != Some(&json!("piquel-internal-api")) + || claims.get("sub").and_then(Value::as_str) != Some(peer_service_id.as_str()) || !claims .get("permissions") .and_then(Value::as_array) @@ -131,6 +138,33 @@ impl ServiceRpcApplication { Ok(claims) } } + +#[allow(clippy::result_large_err)] +fn service_identity_from_peer(request: &Request) -> Result { + let certificates = request.peer_certs().ok_or_else(auth_error)?; + let leaf = certificates.first().ok_or_else(auth_error)?; + service_identity_from_certificate(leaf.as_ref()).ok_or_else(auth_error) +} + +fn service_identity_from_certificate(der: &[u8]) -> Option { + const PREFIX: &str = "spiffe://piquel.fr/service/"; + let certificate = openssl::x509::X509::from_der(der).ok()?; + let identities: Vec<_> = certificate + .subject_alt_names()? + .iter() + .filter_map(|name| name.uri()) + .filter_map(|uri| uri.strip_prefix(PREFIX)) + .filter(|service_id| { + !service_id.is_empty() + && service_id.len() <= 64 + && service_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }) + .map(str::to_owned) + .collect(); + (identities.len() == 1).then(|| identities[0].clone()) +} #[allow(clippy::result_large_err)] fn decode_part Deserialize<'de>>(part: &str) -> Result { serde_json::from_slice(&URL_SAFE_NO_PAD.decode(part).map_err(|_| auth_error())?) @@ -149,8 +183,9 @@ impl ServiceTokenService for ServiceRpcApplication { &self, request: Request, ) -> Result, Status> { + let peer_service_id = service_identity_from_peer(&request)?; let (service_id, permissions) = self - .verify_assertion(&request.into_inner().client_assertion) + .verify_assertion(&request.into_inner().client_assertion, &peer_service_id) .await?; let now = Utc::now().timestamp(); let token=self.keys.sign("service+jwt",&json!({"iss":self.issuer,"sub":service_id,"aud":"piquel-internal-api","jti":TokenId::new(),"permissions":permissions,"iat":now,"exp":now+300})).map_err(|()|Status::internal("token issuance failed"))?; @@ -214,14 +249,11 @@ impl AuthService for ServiceRpcApplication { let session = self .database .sessions() - .find_by_id(id) + .find_active_by_id(id) .await .map_err(internal)?; let (active, user_id) = session.map_or((false, String::new()), |session| { - ( - session.revoked_at.is_none() && session.expires_at > Utc::now(), - session.user_id.to_string(), - ) + (true, session.user_id.to_string()) }); Ok(Response::new(v1::GetSessionStatusResponse { active, @@ -282,3 +314,59 @@ fn user_response(user: piquel_repository::StoredUser) -> v1::GetUserResponse { .into(), } } + +#[cfg(test)] +mod tests { + use super::*; + use openssl::{ + asn1::Asn1Time, + hash::MessageDigest, + pkey::PKey, + rsa::Rsa, + x509::{X509, X509NameBuilder, extension::SubjectAlternativeName}, + }; + + fn certificate(uri: &str) -> Vec { + let key = PKey::from_rsa(Rsa::generate(2048).expect("RSA key")).expect("private key"); + let mut name = X509NameBuilder::new().expect("name"); + name.append_entry_by_text("CN", "service test") + .expect("common name"); + let name = name.build(); + let mut builder = X509::builder().expect("certificate"); + builder.set_version(2).expect("version"); + builder.set_subject_name(&name).expect("subject"); + builder.set_issuer_name(&name).expect("issuer"); + builder.set_pubkey(&key).expect("public key"); + builder + .set_not_before(&Asn1Time::days_from_now(0).expect("not before")) + .expect("not before"); + builder + .set_not_after(&Asn1Time::days_from_now(1).expect("not after")) + .expect("not after"); + let extension = SubjectAlternativeName::new() + .uri(uri) + .build(&builder.x509v3_context(None, None)) + .expect("SAN"); + builder.append_extension(extension).expect("extension"); + builder + .sign(&key, MessageDigest::sha256()) + .expect("signature"); + builder.build().to_der().expect("DER") + } + + #[test] + fn service_identity_is_an_exact_spiffe_uri_san() { + assert_eq!( + service_identity_from_certificate(&certificate( + "spiffe://piquel.fr/service/catalog-api" + )), + Some("catalog-api".into()) + ); + assert!( + service_identity_from_certificate(&certificate( + "spiffe://attacker.example/service/catalog-api" + )) + .is_none() + ); + } +} From 8938754233cecc9730dff419851604fbafea8232 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:32:58 +0200 Subject: [PATCH 4/4] fix(auth): prove private RPC trust boundaries --- Cargo.lock | 2 + Cargo.toml | 1 + apps/auth-service/Cargo.toml | 2 + apps/auth-service/src/service_rpc.rs | 28 +- apps/auth-service/tests/rpc_flow.rs | 375 +++++++++++++++++++++++++++ crates/auth-client/src/lib.rs | 27 +- crates/database/src/models.rs | 11 + crates/database/src/repositories.rs | 59 ++++- 8 files changed, 493 insertions(+), 12 deletions(-) create mode 100644 apps/auth-service/tests/rpc_flow.rs diff --git a/Cargo.lock b/Cargo.lock index d1dfd02a4..da2bb63b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -132,6 +132,7 @@ dependencies = [ "jsonwebtoken", "openssl", "p256", + "piquel-auth-client", "piquel-auth-protocol", "piquel-configuration", "piquel-repository", @@ -144,6 +145,7 @@ dependencies = [ "sha2", "thiserror 2.0.18", "tokio", + "tokio-stream", "tonic", "tower 0.5.3", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 8ba0ad867..a0dc9a4e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ thiserror = "2.0" tonic = { version = "0.12", features = ["tls"] } tonic-build = "0.12" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time", "sync"] } +tokio-stream = { version = "0.1", features = ["net"] } tower = { version = "0.5", features = ["util"] } tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 12e682557..5d98e0f88 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -35,6 +35,8 @@ url.workspace = true webauthn-rs.workspace = true [dev-dependencies] +piquel-auth-client = { path = "../../crates/auth-client" } +tokio-stream.workspace = true tower.workspace = true webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] } diff --git a/apps/auth-service/src/service_rpc.rs b/apps/auth-service/src/service_rpc.rs index e549778bf..a447134ec 100644 --- a/apps/auth-service/src/service_rpc.rs +++ b/apps/auth-service/src/service_rpc.rs @@ -5,7 +5,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::{TimeZone, Utc}; use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier}; use piquel_auth_protocol::{SessionId, TokenId, UserId}; -use piquel_repository::Database; +use piquel_repository::{AppendAuditEvent, Database}; use piquel_service_auth::v1::{ self, auth_service_server::AuthService, service_token_service_server::ServiceTokenService, }; @@ -22,6 +22,20 @@ pub struct ServiceRpcApplication { keys: Arc, } impl ServiceRpcApplication { + async fn audit_token_issue(&self, outcome: &str) -> Result<(), Status> { + self.database + .audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: None, + action: "service_token.issue".into(), + outcome: outcome.into(), + request_metadata: json!({}), + }) + .await + .map_err(internal) + } + /// Constructs the private RPC service. #[must_use] pub fn new(database: Database, issuer: String, keys: Arc) -> Self { @@ -184,11 +198,19 @@ impl ServiceTokenService for ServiceRpcApplication { request: Request, ) -> Result, Status> { let peer_service_id = service_identity_from_peer(&request)?; - let (service_id, permissions) = self + let verified = self .verify_assertion(&request.into_inner().client_assertion, &peer_service_id) - .await?; + .await; + let (service_id, permissions) = match verified { + Ok(verified) => verified, + Err(error) => { + let _ = self.audit_token_issue("failure").await; + return Err(error); + } + }; let now = Utc::now().timestamp(); let token=self.keys.sign("service+jwt",&json!({"iss":self.issuer,"sub":service_id,"aud":"piquel-internal-api","jti":TokenId::new(),"permissions":permissions,"iat":now,"exp":now+300})).map_err(|()|Status::internal("token issuance failed"))?; + self.audit_token_issue("success").await?; Ok(Response::new(v1::IssueServiceTokenResponse { access_token: token, expires_in: 300, diff --git a/apps/auth-service/tests/rpc_flow.rs b/apps/auth-service/tests/rpc_flow.rs new file mode 100644 index 000000000..0fd419587 --- /dev/null +++ b/apps/auth-service/tests/rpc_flow.rs @@ -0,0 +1,375 @@ +#![allow(missing_docs)] + +use auth_service::{Es256KeyProvider, ServiceRpcApplication}; +use chrono::{Duration as ChronoDuration, Utc}; +use openssl::{ + asn1::{Asn1Integer, Asn1Time}, + bn::BigNum, + hash::MessageDigest, + pkey::{PKey, Private}, + rsa::Rsa, + x509::{ + X509, X509NameBuilder, + extension::{BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName}, + }, +}; +use p256::ecdsa::SigningKey; +use piquel_auth_client::ServiceAuthClient; +use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_repository::{BootstrapServiceIdentity, Database, DatabaseConfig, InsertUser}; +use piquel_service_auth::{ + create_client_assertion, + v1::{IssueServiceTokenRequest, service_token_service_client::ServiceTokenServiceClient}, +}; +use rand::rngs::OsRng; +use std::{env, sync::Arc, time::Duration}; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::{ + Code, + transport::{Certificate, ClientTlsConfig, Endpoint, Identity, Server, ServerTlsConfig}, +}; + +async fn database() -> Database { + let url = env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new_development(url, 8, Duration::from_secs(5)) + .expect("test database configuration"), + ) + .await + .expect("connect test database") +} + +fn name(common_name: &str) -> openssl::x509::X509Name { + let mut name = X509NameBuilder::new().expect("name builder"); + name.append_entry_by_text("CN", common_name) + .expect("common name"); + name.build() +} + +fn certificate( + serial: u32, + common_name: &str, + key: &PKey, + issuer: Option<(&X509, &PKey)>, + dns_name: Option<&str>, + uri: Option<&str>, +) -> X509 { + let mut builder = X509::builder().expect("certificate builder"); + builder.set_version(2).expect("certificate version"); + let serial = + Asn1Integer::from_bn(&BigNum::from_u32(serial).expect("serial bignum")).expect("serial"); + builder + .set_serial_number(&serial) + .expect("certificate serial"); + let subject = name(common_name); + builder.set_subject_name(&subject).expect("subject"); + builder + .set_issuer_name(issuer.map_or(&subject, |(certificate, _)| certificate.subject_name())) + .expect("issuer"); + builder.set_pubkey(key).expect("public key"); + builder + .set_not_before(Asn1Time::days_from_now(0).expect("not before").as_ref()) + .expect("not before"); + builder + .set_not_after(Asn1Time::days_from_now(1).expect("not after").as_ref()) + .expect("not after"); + if issuer.is_none() { + builder + .append_extension(BasicConstraints::new().critical().ca().build().expect("CA")) + .expect("CA extension"); + builder + .append_extension( + KeyUsage::new() + .key_cert_sign() + .crl_sign() + .build() + .expect("CA usage"), + ) + .expect("CA usage extension"); + } else { + builder + .append_extension(BasicConstraints::new().critical().build().expect("leaf")) + .expect("leaf extension"); + builder + .append_extension( + KeyUsage::new() + .digital_signature() + .key_encipherment() + .build() + .expect("leaf usage"), + ) + .expect("leaf usage extension"); + let mut usage = ExtendedKeyUsage::new(); + if dns_name.is_some() { + usage.server_auth(); + } + if uri.is_some() { + usage.client_auth(); + } + builder + .append_extension(usage.build().expect("extended usage")) + .expect("extended usage extension"); + let alternative_name = { + let mut names = SubjectAlternativeName::new(); + if let Some(dns_name) = dns_name { + names.dns(dns_name); + } + if let Some(uri) = uri { + names.uri(uri); + } + names + .build(&builder.x509v3_context(issuer.map(|value| value.0.as_ref()), None)) + .expect("alternative name") + }; + builder + .append_extension(alternative_name) + .expect("alternative name extension"); + } + builder + .sign(issuer.map_or(key, |(_, key)| key), MessageDigest::sha256()) + .expect("certificate signature"); + builder.build() +} + +struct TlsMaterial { + ca: Vec, + server_certificate: Vec, + server_key: Vec, + client_certificate: Vec, + client_key: Vec, + wrong_certificate: Vec, + wrong_key: Vec, +} + +fn tls_material(service_id: &str) -> TlsMaterial { + let ca_key = PKey::from_rsa(Rsa::generate(2048).expect("CA key")).expect("CA PKey"); + let ca = certificate(1, "Piquel test CA", &ca_key, None, None, None); + let server_key = PKey::from_rsa(Rsa::generate(2048).expect("server key")).expect("server PKey"); + let server = certificate( + 2, + "localhost", + &server_key, + Some((&ca, &ca_key)), + Some("localhost"), + None, + ); + let client_key = PKey::from_rsa(Rsa::generate(2048).expect("client key")).expect("client PKey"); + let client = certificate( + 3, + service_id, + &client_key, + Some((&ca, &ca_key)), + None, + Some(&format!("spiffe://piquel.fr/service/{service_id}")), + ); + let wrong_client_key = + PKey::from_rsa(Rsa::generate(2048).expect("wrong client key")).expect("wrong client PKey"); + let wrong_client = certificate( + 4, + "different-service", + &wrong_client_key, + Some((&ca, &ca_key)), + None, + Some("spiffe://piquel.fr/service/different-service"), + ); + TlsMaterial { + ca: ca.to_pem().expect("CA PEM"), + server_certificate: server.to_pem().expect("server PEM"), + server_key: server_key + .private_key_to_pem_pkcs8() + .expect("server key PEM"), + client_certificate: client.to_pem().expect("client PEM"), + client_key: client_key + .private_key_to_pem_pkcs8() + .expect("client key PEM"), + wrong_certificate: wrong_client.to_pem().expect("wrong client PEM"), + wrong_key: wrong_client_key + .private_key_to_pem_pkcs8() + .expect("wrong client key PEM"), + } +} + +async fn channel( + uri: String, + ca: Vec, + certificate: Vec, + key: Vec, +) -> tonic::transport::Channel { + Endpoint::from_shared(uri) + .expect("endpoint") + .tls_config( + ClientTlsConfig::new() + .domain_name("localhost") + .ca_certificate(Certificate::from_pem(ca)) + .identity(Identity::from_pem(certificate, key)), + ) + .expect("client TLS") + .connect() + .await + .expect("mTLS connection") +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL after migrations"] +#[allow(clippy::too_many_lines)] +async fn private_rpc_enforces_mtls_replay_and_permissions() { + let database = database().await; + let service_id = format!("rpc-test-{}", TokenId::new()); + let kid = "assertion-key"; + let assertion_key = SigningKey::random(&mut OsRng); + database + .service_identities() + .bootstrap(&BootstrapServiceIdentity { + id: service_id.clone(), + display_name: "RPC integration test".into(), + enabled: true, + kid: kid.into(), + public_key: assertion_key + .verifying_key() + .to_encoded_point(false) + .as_bytes() + .to_vec(), + not_before: Utc::now() - ChronoDuration::minutes(1), + expires_at: Utc::now() + ChronoDuration::hours(1), + permissions: vec!["GetUser".into()], + }) + .await + .expect("service identity"); + let user_id = UserId::new(); + database + .users() + .insert(&InsertUser { + id: user_id, + username: format!("rpc_{}", &user_id.to_string()[..8]), + display_name: "RPC User".into(), + }) + .await + .expect("RPC user"); + + let TlsMaterial { + ca, + server_certificate, + server_key, + client_certificate, + client_key, + wrong_certificate, + wrong_key, + } = tls_material(&service_id); + let authority_keys = Arc::new(Es256KeyProvider::generate_for_development("rpc-authority")); + let rpc = ServiceRpcApplication::new(database, "https://auth.piquel.fr".into(), authority_keys); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("RPC listener"); + let address = listener.local_addr().expect("RPC address"); + let incoming = TcpListenerStream::new(listener); + let tls = ServerTlsConfig::new() + .identity(tonic::transport::Identity::from_pem( + server_certificate.clone(), + server_key, + )) + .client_ca_root(Certificate::from_pem(ca.clone())); + let (shutdown, stopped) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + Server::builder() + .tls_config(tls) + .expect("server TLS") + .add_service(rpc.clone().token_server()) + .add_service(rpc.auth_server()) + .serve_with_incoming_shutdown(incoming, async { + let _ = stopped.await; + }) + .await + .expect("RPC server"); + }); + let uri = format!("https://{address}"); + + let raw_channel = channel( + uri.clone(), + ca.clone(), + client_certificate.clone(), + client_key.clone(), + ) + .await; + let mut tokens = ServiceTokenServiceClient::new(raw_channel); + let assertion = + create_client_assertion(&service_id, kid, "piquel-service-token", &assertion_key) + .expect("assertion"); + tokens + .issue_service_token(IssueServiceTokenRequest { + client_assertion: assertion.clone(), + }) + .await + .expect("first assertion use"); + let replay = tokens + .issue_service_token(IssueServiceTokenRequest { + client_assertion: assertion, + }) + .await + .expect_err("assertion replay must fail"); + assert_eq!(replay.code(), Code::Unauthenticated); + + let mut client = ServiceAuthClient::connect( + uri.clone(), + "localhost".into(), + ca.clone(), + client_certificate, + client_key, + service_id.clone(), + kid.into(), + assertion_key.clone(), + ) + .await + .expect("service auth client"); + let user = client + .get_user(user_id.to_string()) + .await + .expect("permitted GetUser"); + assert_eq!(user.user_id, user_id.to_string()); + assert_eq!(user.display_name, "RPC User"); + assert!( + client + .revoke_session(SessionId::new().to_string()) + .await + .is_err() + ); + + let mut wrong_identity = ServiceAuthClient::connect( + uri.clone(), + "localhost".into(), + ca.clone(), + wrong_certificate, + wrong_key, + service_id.clone(), + kid.into(), + assertion_key.clone(), + ) + .await + .expect("trusted but mismatched client certificate"); + assert!(wrong_identity.get_user(user_id.to_string()).await.is_err()); + let without_identity = Endpoint::from_shared(uri) + .expect("endpoint") + .tls_config( + ClientTlsConfig::new() + .domain_name("localhost") + .ca_certificate(Certificate::from_pem(ca)), + ) + .expect("TLS config") + .connect() + .await + .expect("channel creation is lazy"); + let assertion = + create_client_assertion(&service_id, kid, "piquel-service-token", &assertion_key) + .expect("assertion without TLS identity"); + assert!( + ServiceTokenServiceClient::new(without_identity) + .issue_service_token(IssueServiceTokenRequest { + client_assertion: assertion, + }) + .await + .is_err() + ); + + let _ = shutdown.send(()); + server.await.expect("server task"); +} diff --git a/crates/auth-client/src/lib.rs b/crates/auth-client/src/lib.rs index 8aa0b9aee..a7b7e932a 100644 --- a/crates/auth-client/src/lib.rs +++ b/crates/auth-client/src/lib.rs @@ -108,13 +108,28 @@ impl ServiceAuthClient { ); Ok(request) } + async fn invalidate_token(&self) { + *self.cache.lock().await = None; + } pub async fn get_user(&mut self, user_id: String) -> Result { - let request = self.authorized(v1::GetUserRequest { user_id }).await?; - self.auth - .get_user(request) - .await - .map(tonic::Response::into_inner) - .map_err(|_| ClientError) + let request = self + .authorized(v1::GetUserRequest { + user_id: user_id.clone(), + }) + .await?; + match self.auth.get_user(request).await { + Ok(response) => Ok(response.into_inner()), + Err(status) if status.code() == tonic::Code::Unauthenticated => { + self.invalidate_token().await; + let retry = self.authorized(v1::GetUserRequest { user_id }).await?; + self.auth + .get_user(retry) + .await + .map(tonic::Response::into_inner) + .map_err(|_| ClientError) + } + Err(_) => Err(ClientError), + } } pub async fn revoke_session(&mut self, session_id: String) -> Result { let request = self diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index c781ec509..403c63727 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -265,6 +265,17 @@ pub struct StoredExternalIdentity { pub linked_email: String, } +#[derive(Clone, Debug)] +pub struct BootstrapServiceIdentity { + pub id: String, + pub display_name: String, + pub enabled: bool, + pub kid: String, + pub public_key: Vec, + pub not_before: DateTime, + pub expires_at: DateTime, + pub permissions: Vec, +} #[derive(Clone, Debug)] pub struct StoredServiceIdentity { pub id: String, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 76889b740..60a8987f5 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,9 +1,9 @@ //! Domain repository handles backed by a private pool or transaction connection. use crate::{ - AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, ConsumedAuthorizationCode, - ConsumedCeremony, ConsumedFederationTransaction, DatabaseError, InsertAuthorizationCode, - InsertAuthorizationRequest, InsertCeremony, InsertExternalIdentity, + AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, BootstrapServiceIdentity, + ConsumedAuthorizationCode, ConsumedCeremony, ConsumedFederationTransaction, DatabaseError, + InsertAuthorizationCode, InsertAuthorizationRequest, InsertCeremony, InsertExternalIdentity, InsertFederationTransaction, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, RotatedRefreshToken, StoredAuthorizationRequest, StoredEmail, StoredExternalIdentity, StoredOidcClient, @@ -697,6 +697,19 @@ fn stored_external_identity( } impl ServiceIdentityRepository<'_> { + /// Atomically provisions an administratively reviewed service key and permission set. + pub async fn bootstrap( + &mut self, + input: &BootstrapServiceIdentity, + ) -> Result<(), DatabaseError> { + validate_service_identity(input)?; + fetch_one!(self, sqlx::query("WITH service AS (INSERT INTO service_identities(id,display_name,enabled) VALUES($1,$2,$3) ON CONFLICT(id) DO UPDATE SET display_name=EXCLUDED.display_name,enabled=EXCLUDED.enabled RETURNING id), key AS (INSERT INTO service_identity_keys(id,service_id,kid,algorithm,public_key,not_before,expires_at) SELECT $4,$1,$5,'ES256',$6,$7,$8 FROM service ON CONFLICT(service_id,kid) DO UPDATE SET public_key=EXCLUDED.public_key,not_before=EXCLUDED.not_before,expires_at=EXCLUDED.expires_at,revoked_at=NULL RETURNING service_id), desired(method) AS (SELECT unnest($9::text[])), removed AS (DELETE FROM service_rpc_permissions p WHERE p.service_id=$1 AND NOT EXISTS(SELECT 1 FROM desired d WHERE d.method=p.method) RETURNING method), inserted AS (INSERT INTO service_rpc_permissions(service_id,method) SELECT $1,d.method FROM desired d,key ON CONFLICT DO NOTHING RETURNING method) SELECT id FROM service") + .bind(&input.id).bind(&input.display_name).bind(input.enabled) + .bind(TokenId::new().as_uuid()).bind(&input.kid).bind(&input.public_key) + .bind(input.not_before).bind(input.expires_at).bind(&input.permissions))?; + Ok(()) + } + pub async fn find_active_key( &mut self, service_id: &str, @@ -745,6 +758,46 @@ impl ServiceIdentityRepository<'_> { Ok(()) } } + +fn validate_service_identity(input: &BootstrapServiceIdentity) -> Result<(), DatabaseError> { + const METHODS: &[&str] = &[ + "GetUser", + "BatchGetUsers", + "GetSessionStatus", + "RevokeSession", + "RevokeAllUserSessions", + "GetServiceConfiguration", + ]; + let identifier = |value: &str| { + (1..=64).contains(&value.len()) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }; + let valid = identifier(&input.id) + && identifier(&input.kid) + && !input.display_name.trim().is_empty() + && input.display_name.chars().count() <= 80 + && matches!(input.public_key.len(), 33 | 65) + && input.not_before < input.expires_at + && !input.permissions.is_empty() + && input.permissions.len() <= METHODS.len() + && input + .permissions + .iter() + .collect::>() + .len() + == input.permissions.len() + && input + .permissions + .iter() + .all(|method| METHODS.contains(&method.as_str())); + if valid { + Ok(()) + } else { + Err(DatabaseError::Conflict) + } +} fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row .try_get("authentication_methods")