Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ client and scope; explicitly trusted clients bypass consent.
bound to the initiating browser. Auth cookies are host-only, Secure and HttpOnly.
Mutations require an exact allowed origin and CSRF header; OIDC back-channel
endpoints instead validate their protocol credentials.
- Request throttling and expiring-state cleanup use PostgreSQL. Throttling uses separate login, token and account budgets per client IP.
- Request throttling and expiring-state cleanup use PostgreSQL. Throttling uses separate login, token, userinfo and account budgets per client IP, and covers every API route except health probes and discovery.
By default it uses the direct peer IP; only peers in `AUTH_TRUSTED_PROXIES`
may supply a single overwritten `X-Forwarded-For`. Configure this when terminating TLS
at a reverse proxy so users do not share the proxy’s budget. Untrusted headers
Expand Down
36 changes: 23 additions & 13 deletions apps/auth-service/src/security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,8 +356,10 @@ enum Endpoint {
OAuthBackChannel,
/// Bearer-authenticated `UserInfo`.
UserInfo,
/// Public discovery and signing keys.
/// Public discovery and signing keys, served from memory.
Discovery,
/// Liveness and readiness probes polled by the orchestrator.
Health,
/// Authorization requests, including cross-site form navigation.
Authorize,
/// RP-initiated logout, validated by its own hint and same-origin checks.
Expand All @@ -377,6 +379,7 @@ impl Endpoint {
oidc::TOKEN | oidc::REVOKE => Self::OAuthBackChannel,
oidc::USERINFO => Self::UserInfo,
oidc::DISCOVERY | oidc::JWKS => Self::Discovery,
service::LIVE | service::READY => Self::Health,
oidc::AUTHORIZE => Self::Authorize,
oidc::LOGOUT => Self::Logout,
service::CONFIG | passkey::SESSION | passkey::SESSION_LOGOUT => Self::Account,
Expand All @@ -390,31 +393,38 @@ impl Endpoint {
const fn is_protocol(self) -> bool {
match self {
Self::OAuthBackChannel | Self::UserInfo | Self::Authorize | Self::Logout => true,
Self::Discovery | Self::Account | Self::Login | Self::Other => false,
Self::Discovery | Self::Health | Self::Account | Self::Login | Self::Other => false,
}
}

/// Selects a request budget. Safe reads only count on login flows and the token endpoint.
fn rate_category(self, mutation: bool) -> Option<RateCategory> {
/// Selects the budget of a matched route, reads included: they verify token
/// signatures or hold a connection from the small database pool. Only routes that
/// do neither are free. Discovery is served from memory and cacheable, and a
/// throttled health probe would take the service out of rotation; readiness costs
/// one `SELECT 1`, no more than the budget's own upsert would.
const fn rate_category(self) -> Option<RateCategory> {
match self {
Self::OAuthBackChannel => Some(RateCategory::Token),
Self::Login | Self::Authorize => Some(RateCategory::Login),
Self::Account => mutation.then_some(RateCategory::Account),
Self::UserInfo | Self::Discovery | Self::Logout | Self::Other => {
mutation.then_some(RateCategory::Login)
}
Self::UserInfo => Some(RateCategory::UserInfo),
Self::Account => Some(RateCategory::Account),
Self::Login | Self::Authorize | Self::Logout | Self::Other => Some(RateCategory::Login),
Self::Discovery | Self::Health => None,
}
}
}

piquel_common::str_enum! {
/// Independent request budgets persisted under stable category names.
/// Independent request budgets persisted under stable category names, so one kind of
/// traffic from a client cannot exhaust another: a relying party's `UserInfo` calls
/// never block its code exchanges, and settings reads never block a sign-in.
enum RateCategory {
/// OAuth credential exchanges and revocation.
Token = "token",
/// Settings mutations.
/// Bearer-token claim lookups by relying parties.
UserInfo = "userinfo",
/// Settings and browser-session reads and mutations.
Account = "account",
/// Login navigation and other mutations.
/// Sign-in, authorization, logout and the other auth-origin routes.
Login = "login",
}
}
Expand Down Expand Up @@ -627,7 +637,7 @@ impl HttpSecurity {
Self::check_browser(endpoint, request.headers(), allowed, mutation)?;
// Unknown paths have no `MatchedPath`: they never consume a budget or need peer metadata.
if request.extensions().get::<MatchedPath>().is_some()
&& let Some(category) = endpoint.rate_category(mutation)
&& let Some(category) = endpoint.rate_category()
{
let bucket =
Digest::sha256(format!("{category}:{}", self.client_ip(&request)?).as_bytes());
Expand Down
93 changes: 65 additions & 28 deletions apps/auth-service/src/security/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Focused persistence and security contract tests.

use super::*;
use crate::routes::federation;
use axum::{Router, body::Body, http::Request as HttpRequest, middleware, routing::any};
use piquel_crypto::Secret;
use piquel_repository::DatabaseConfig;
Expand Down Expand Up @@ -50,6 +51,7 @@ impl SecurityFixture {
"/oauth/revoke",
"/oidc/userinfo",
"/oidc/logout",
"/session",
] {
router = router.route(path, any(|| async { StatusCode::ACCEPTED }));
}
Expand Down Expand Up @@ -418,6 +420,33 @@ async fn rate_budgets_are_separate_and_unknown_paths_do_not_consume_them() {
StatusCode::ACCEPTED
);
}
/// Reads spend their budget and then get a retry delay, without draining other budgets.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL"]
async fn reads_exhaust_their_own_budget() {
let fixture = SecurityFixture::new().await;
for _ in 0..REQUESTS_PER_MINUTE {
assert_eq!(
fixture
.request(Method::GET, "/oidc/userinfo", None, false)
.await
.status(),
StatusCode::ACCEPTED
);
}
let response = fixture
.request(Method::GET, "/oidc/userinfo", None, false)
.await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(response.headers()[header::RETRY_AFTER], RETRY_AFTER_SECONDS);
assert_eq!(
fixture
.request(Method::GET, "/session", None, false)
.await
.status(),
StatusCode::ACCEPTED
);
}
/// A trusted proxy shares each budget by forwarded client IP rather than ingress IP.
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL"]
Expand Down Expand Up @@ -463,37 +492,45 @@ async fn trusted_proxy_clients_have_independent_budgets() {
}
}

/// Browser mutation proof and independent request categories follow each endpoint's policy.
/// Every route that verifies a token or queries the database has a budget, reads
/// included; only in-memory discovery and health probes are free.
#[test]
fn endpoint_policy_requires_browser_proof_and_selects_independent_budgets() {
for (endpoint, protocol, read_budget, mutation_budget) in [
(
Endpoint::OAuthBackChannel,
true,
Some(RateCategory::Token),
RateCategory::Token,
),
(Endpoint::UserInfo, true, None, RateCategory::Login),
(Endpoint::Discovery, false, None, RateCategory::Login),
(
Endpoint::Authorize,
true,
Some(RateCategory::Login),
RateCategory::Login,
),
(Endpoint::Logout, true, None, RateCategory::Login),
(Endpoint::Account, false, None, RateCategory::Account),
(
Endpoint::Login,
false,
Some(RateCategory::Login),
RateCategory::Login,
),
(Endpoint::Other, false, None, RateCategory::Login),
fn routes_doing_real_work_have_budgets() {
for (path, budget) in [
(service::LIVE, None),
(service::READY, None),
(oidc::DISCOVERY, None),
(oidc::JWKS, None),
(oidc::TOKEN, Some(RateCategory::Token)),
(oidc::USERINFO, Some(RateCategory::UserInfo)),
(oidc::LOGOUT, Some(RateCategory::Login)),
(oidc::AUTHORIZE, Some(RateCategory::Login)),
(oidc::AUTHORIZE_RESUME, Some(RateCategory::Login)),
("/oauth/authorize/transaction/1", Some(RateCategory::Login)),
(passkey::SESSION, Some(RateCategory::Account)),
(passkey::LIST, Some(RateCategory::Account)),
(federation::IDENTITIES, Some(RateCategory::Account)),
(federation::PENDING, Some(RateCategory::Login)),
] {
assert_eq!(Endpoint::classify(path).rate_category(), budget, "{path}");
}
}

/// Browser origin and mutation proof are required everywhere except protocol endpoints.
#[test]
fn endpoint_policy_requires_browser_proof_outside_protocol_endpoints() {
for (endpoint, protocol) in [
(Endpoint::OAuthBackChannel, true),
(Endpoint::UserInfo, true),
(Endpoint::Discovery, false),
(Endpoint::Health, false),
(Endpoint::Authorize, true),
(Endpoint::Logout, true),
(Endpoint::Account, false),
(Endpoint::Login, false),
(Endpoint::Other, false),
] {
assert_eq!(endpoint.is_protocol(), protocol);
assert_eq!(endpoint.rate_category(false), read_budget);
assert_eq!(endpoint.rate_category(true), Some(mutation_budget));
let anonymous = HeaderMap::new();
let mut browser = HeaderMap::new();
browser.insert(
Expand Down
Loading