Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
488 changes: 472 additions & 16 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -44,14 +46,18 @@ 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"] }
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"] }
tokio-stream = { version = "0.1", features = ["net"] }
tower = { version = "0.5", features = ["util"] }
tower-http = { version = "0.6", features = ["trace"] }
tracing = "0.1"
Expand Down
4 changes: 4 additions & 0 deletions apps/auth-service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,23 @@ hmac.workspace = true
jsonwebtoken.workspace = true
openssl.workspace = true
p256.workspace = true
piquel-service-auth = { path = "../../crates/service-auth" }
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
reqwest.workspace = true
thiserror.workspace = true
tokio.workspace = true
tonic.workspace = true
tracing.workspace = true
unicode-normalization.workspace = true
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"] }

Expand Down
13 changes: 12 additions & 1 deletion apps/auth-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ mod federation;
pub use federation::{FederationApplication, ProviderConfiguration};
#[allow(dead_code)]
mod oidc;
pub use oidc::OidcApplication;
pub use oidc::{KeyProvider, OidcApplication};
#[allow(dead_code)]
mod passkey;
pub use passkey::PasskeyApplication;
mod service_rpc;
#[allow(dead_code)]
mod session;
pub use service_rpc::ServiceRpcApplication;
mod signing;
pub use signing::Es256KeyProvider;

Expand All @@ -52,6 +54,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.
Expand Down Expand Up @@ -99,6 +107,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")?)?,
})
}
}
Expand Down
54 changes: 46 additions & 8 deletions apps/auth-service/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
use std::{net::SocketAddr, sync::Arc, time::Duration};

#[tokio::main]
#[allow(clippy::too_many_lines)]
async fn main() -> anyhow::Result<()> {
piquel_telemetry::init("auth_service=info");
let config = AuthConfig::from_environment()?;
Expand Down Expand Up @@ -38,14 +39,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"))?;
Expand All @@ -64,19 +65,56 @@ 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)),
Some(passkeys),
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)?
.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()
.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(())
}

Expand Down
25 changes: 19 additions & 6 deletions apps/auth-service/src/oidc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,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<String, ()>;
/// Publishes the provider's public verification keys.
fn jwks(&self) -> Value;
fn verify_access(&self, token: &str, issuer: &str) -> Result<Value, ()>;
/// 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<Value, ()>;
}

impl KeyProvider for Es256KeyProvider {
Expand All @@ -45,8 +58,8 @@ impl KeyProvider for Es256KeyProvider {
self.public_jwks()
}

fn verify_access(&self, token: &str, issuer: &str) -> Result<Value, ()> {
let claims: Value = self.verify("at+jwt", token)?;
fn verify(&self, token: &str, token_type: &str, issuer: &str) -> Result<Value, ()> {
let claims: Value = Es256KeyProvider::verify(self, token_type, token)?;
let now = Utc::now().timestamp();
if claims.get("iss") != Some(&json!(issuer))
|| claims
Expand Down Expand Up @@ -692,7 +705,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")
Expand Down Expand Up @@ -916,13 +929,13 @@ mod tests {
&json!({"iss":"https://issuer","exp":now+60,"iat":now}),
)
.expect("sign");
assert!(keys.verify_access(&id, "https://issuer").is_err());
assert!(KeyProvider::verify(&keys, &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!(KeyProvider::verify(&keys, &access, "at+jwt", "https://issuer").is_ok());
}
}
Loading