Skip to content

Commit a40652a

Browse files
PiquelChipsclaude
andcommitted
refactor(sdk): session backends instead of stores, without back-channel logout
Applications now implement SessionBackend: load, insert, a compare-and-swap replace, and a remove that reports whether the record existed, over opaque records. The SDK keeps the record format and its validation, expiry, pending logins and the refresh lease, which it stores inside the session record. Backends see only the SHA-256 of each session key. MemoryBackend is for development and tests; check_backend (the test-util feature) checks an application's backend against the contract. PostgresSessions and the postgres feature are gone, and with them sqlx and the SDK's runtime-checked SQL: applications write their own backend with their own migrations and checked queries. Back-channel logout is removed until auth sends logout tokens (#65); the previous implementation is kept on the sdk/backchannel-logout branch. The axum integration is documented with an example on every extractor, layer and route builder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 748a9d4 commit a40652a

19 files changed

Lines changed: 889 additions & 1154 deletions

File tree

‎Cargo.lock‎

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/auth-service/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ webauthn-rs.workspace = true
3131
webauthn-rs-proto.workspace = true
3232

3333
[dev-dependencies]
34-
piquel-auth = { workspace = true, features = ["axum", "postgres"] }
34+
piquel-auth = { workspace = true, features = ["axum", "test-util"] }
3535
rcgen.workspace = true
3636
tokio-rustls.workspace = true
3737
piquel-repository = { workspace = true, features = ["test-support"] }

‎apps/auth-service/src/oidc/tests.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,7 +1211,7 @@ impl LoginApp {
12111211
async fn start() -> Self {
12121212
use piquel_auth::{
12131213
ClientConfig, ClientId, Credentials,
1214-
axum::{LoginRoutes, MemorySessions, SignedIn},
1214+
axum::{LoginRoutes, MemoryBackend, SignedIn},
12151215
};
12161216
let tcp = tokio::net::TcpListener::bind("127.0.0.1:0")
12171217
.await
@@ -1237,7 +1237,7 @@ impl LoginApp {
12371237
credentials: Credentials::Secret(CLIENT_SECRET.into()),
12381238
redirect_uri: flow.client.redirect_uris[0].parse().expect("callback"),
12391239
});
1240-
let auth = LoginRoutes::new(client, MemorySessions::default())
1240+
let auth = LoginRoutes::new(client, MemoryBackend::default())
12411241
.scopes("profile offline_access".parse().expect("scopes"))
12421242
.after_logout(flow.client.post_logout_uris[0].parse().expect("logout URI"));
12431243
let app = Router::new()

‎crates/auth-protocol/src/claims.rs‎

Lines changed: 0 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
use crate::{AuthenticationMethod, ClientId, SessionId, TokenId, oauth::Scopes};
66
use chrono::{DateTime, Utc};
77
use serde::{Deserialize, Serialize};
8-
use std::collections::BTreeMap;
98

109
piquel_common::open_str_enum! {
1110
/// `amr` values (RFC 8176): how the user authenticated. This is the wire view,
@@ -237,76 +236,3 @@ pub struct UserInfo {
237236
#[serde(flatten)]
238237
pub profile: ProfileClaims,
239238
}
240-
241-
/// The `events` member a logout token must carry (OIDC Back-Channel Logout 1.0 §2.4).
242-
pub const BACKCHANNEL_LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout";
243-
244-
/// An event's payload: a JSON object, empty for back-channel logout. Members are
245-
/// ignored, but anything other than an object is refused.
246-
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
247-
pub struct Event {}
248-
249-
impl<'de> Deserialize<'de> for Event {
250-
/// Requires an object.
251-
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
252-
BTreeMap::<String, serde::de::IgnoredAny>::deserialize(deserializer).map(|_| Self {})
253-
}
254-
}
255-
256-
/// A claim whose presence alone matters, whatever its value, such as a logout
257-
/// token's forbidden `nonce`. Present even as `null`; serialized as `null`.
258-
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
259-
pub struct Present;
260-
261-
impl Present {
262-
/// Reads a claim as present whenever it appears.
263-
fn some<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Self>, D::Error> {
264-
serde::de::IgnoredAny::deserialize(deserializer).map(|_| Some(Self))
265-
}
266-
}
267-
268-
impl Serialize for Present {
269-
/// Writes `null`.
270-
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
271-
serializer.serialize_unit()
272-
}
273-
}
274-
275-
/// Claims of a back-channel logout token (OIDC Back-Channel Logout 1.0 §2.4), signed
276-
/// with `typ: logout+jwt`. It ends one session (`sid`) or every session of a user at
277-
/// one client (`sub` alone).
278-
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
279-
pub struct LogoutTokenClaims {
280-
/// Issuer, exactly as in discovery.
281-
pub iss: String,
282-
/// The client being told.
283-
pub aud: Audience,
284-
/// Issue time.
285-
#[serde(with = "chrono::serde::ts_seconds")]
286-
pub iat: DateTime<Utc>,
287-
/// Expiry time.
288-
#[serde(with = "chrono::serde::ts_seconds")]
289-
pub exp: DateTime<Utc>,
290-
/// Unique token ID, for replay detection.
291-
pub jti: String,
292-
/// The user whose sessions end.
293-
#[serde(default, skip_serializing_if = "Option::is_none")]
294-
pub sub: Option<String>,
295-
/// The session that ends.
296-
#[serde(default, skip_serializing_if = "Option::is_none")]
297-
pub sid: Option<SessionId>,
298-
/// Must contain [`BACKCHANNEL_LOGOUT_EVENT`].
299-
#[expect(
300-
clippy::zero_sized_map_values,
301-
reason = "The wire format is a JSON object of event URIs to empty objects."
302-
)]
303-
pub events: BTreeMap<String, Event>,
304-
/// Must be absent, even as `null`, so an ID token can never pass as a logout
305-
/// token.
306-
#[serde(
307-
default,
308-
deserialize_with = "Present::some",
309-
skip_serializing_if = "Option::is_none"
310-
)]
311-
pub nonce: Option<Present>,
312-
}

‎crates/auth-protocol/src/jwt.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ piquel_common::str_enum! {
99
Access = "at+jwt",
1010
/// ID token, also accepted back as an `id_token_hint`.
1111
Id = "JWT",
12-
/// Back-channel logout token (OIDC Back-Channel Logout 1.0 §2.4).
13-
Logout = "logout+jwt",
1412
}
1513
}
1614
piquel_common::str_enum! {

‎crates/auth-sdk/Cargo.toml‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ repository.workspace = true
99
[features]
1010
# Extractors, layers and login routes for axum.
1111
axum = ["dep:axum", "dep:tower", "dep:tracing"]
12-
# A PostgreSQL session store for the axum login routes.
13-
postgres = ["axum", "dep:sqlx"]
12+
# `axum::check_backend`, to test an application's session backend.
13+
test-util = ["axum"]
1414

1515
[dependencies]
1616
piquel-auth-protocol.workspace = true
@@ -25,7 +25,6 @@ secrecy.workspace = true
2525
serde.workspace = true
2626
serde_json.workspace = true
2727
sha2.workspace = true
28-
sqlx = { workspace = true, optional = true }
2928
thiserror.workspace = true
3029
tokio.workspace = true
3130
tower = { workspace = true, optional = true }
@@ -34,7 +33,6 @@ url.workspace = true
3433

3534
[dev-dependencies]
3635
axum.workspace = true
37-
piquel-crypto.workspace = true
3836
trybuild.workspace = true
3937

4038
[[example]]

‎crates/auth-sdk/examples/notes.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
use axum::{Json, Router, extract::State, http::StatusCode, routing::get};
1313
use piquel_auth::{
1414
ClientConfig, ClientId, Credentials, Issuer, Resource,
15-
axum::{BearerLayer, LoginRoutes, MemorySessions, Scoped, SignedIn},
15+
axum::{BearerLayer, LoginRoutes, MemoryBackend, Scoped, SignedIn},
1616
};
1717
use std::{
1818
env,
@@ -73,7 +73,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
7373
credentials: Credentials::Secret(env::var("NOTES_CLIENT_SECRET")?.into()),
7474
redirect_uri: env::var("NOTES_REDIRECT_URI")?.parse()?,
7575
};
76-
let auth = LoginRoutes::new(issuer.client(config), MemorySessions::default())
76+
// Sessions in memory, lost on restart: a real deployment implements
77+
// `SessionBackend` over its own database.
78+
let auth = LoginRoutes::new(issuer.client(config), MemoryBackend::default())
7779
.scopes("profile".parse()?);
7880

7981
let app = Router::new()

‎crates/auth-sdk/src/axum/bearer.rs‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,38 @@ struct Bearer<X> {
3131
/// without a token passes through, so public routes can share the router; only the
3232
/// extractors reject. Tokens are read from `Authorization: Bearer` only, never from
3333
/// the query string.
34+
///
35+
/// ```no_run
36+
/// # async fn run(issuer: piquel_auth::Issuer) -> Result<(), Box<dyn std::error::Error>> {
37+
/// use axum::{Router, routing::get};
38+
/// use piquel_auth::{
39+
/// Resource,
40+
/// axum::{Authenticated, BearerLayer},
41+
/// };
42+
///
43+
/// /// Application claims some tokens carry.
44+
/// #[derive(Clone, serde::Deserialize)]
45+
/// struct Tenant {
46+
/// tenant: String,
47+
/// }
48+
///
49+
/// async fn status() -> &'static str {
50+
/// "public: no token needed"
51+
/// }
52+
///
53+
/// async fn whoami(Authenticated(token): Authenticated<Tenant>) -> String {
54+
/// format!("{:?} in {}", token.subject, token.extra.tenant)
55+
/// }
56+
///
57+
/// let validator = issuer
58+
/// .resource(Resource::new("notes-api")?)
59+
/// .with_claims::<Tenant>();
60+
/// let app: Router = Router::new()
61+
/// .route("/status", get(status))
62+
/// .route("/me", get(whoami))
63+
/// .layer(BearerLayer::new(validator));
64+
/// # Ok(()) }
65+
/// ```
3466
pub struct BearerLayer<X = ()>(ResourceValidator<X>);
3567

3668
impl<X> Clone for BearerLayer<X> {
@@ -151,6 +183,25 @@ enum Reason {
151183
/// [`Resource`](crate::Resource) names it, and an empty body. When signing keys
152184
/// cannot be fetched it answers 503 without a challenge: that failure is the
153185
/// server's, not the client's.
186+
///
187+
/// Take the extractor as a `Result` to see a rejection before answering with it:
188+
///
189+
/// ```no_run
190+
/// use axum::response::{IntoResponse, Response};
191+
/// use piquel_auth::axum::{AuthRejection, Authenticated};
192+
///
193+
/// async fn audited(token: Result<Authenticated, AuthRejection>) -> Response {
194+
/// match token {
195+
/// Ok(Authenticated(token)) => format!("{:?}", token.subject).into_response(),
196+
/// Err(rejection) => {
197+
/// if let Some(error) = rejection.token_error() {
198+
/// eprintln!("refused a token: {error}");
199+
/// }
200+
/// rejection.into_response()
201+
/// }
202+
/// }
203+
/// }
204+
/// ```
154205
#[derive(Debug)]
155206
pub struct AuthRejection {
156207
/// Why the request was rejected.

0 commit comments

Comments
 (0)