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
16 changes: 10 additions & 6 deletions crates/auth-sdk/src/axum/login/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::{BoxFuture, CookieKey, seal::SealError, session::StoredLogin};
use crate::{Client, ClientId, Credentials, LogoutToken, Scopes, StepUpRequirement};
use axum::{
Router,
extract::OriginalUri,
extract::{DefaultBodyLimit, OriginalUri},
http::{Extensions, HeaderMap, HeaderValue, Method, StatusCode, Uri, header, request::Parts},
response::{IntoResponse, Response},
routing::{get, post},
Expand All @@ -29,8 +29,8 @@ use sourceorigin_common::{
ErrorChain,
protocol::{
constants::{
COOKIE_PREFIX, DEFAULT_SESSION_LIFETIME, MAX_COOKIE_BYTES, MAX_RETURN_TO_BYTES,
PENDING_LOGIN_SLOTS,
COOKIE_PREFIX, DEFAULT_SESSION_LIFETIME, MAX_COOKIE_BYTES, MAX_LOGOUT_REQUEST_BYTES,
MAX_RETURN_TO_BYTES, PENDING_LOGIN_SLOTS,
},
same_origin::BrowserRequest,
},
Expand Down Expand Up @@ -324,8 +324,8 @@ impl LoginRoutes {
/// The handler must be idempotent and return only once its record is durable:
/// auth retries a delivery until it is answered 200, so a token can arrive twice,
/// and an error answers 500 for auth to retry. The route answers 200 once the
/// handler succeeds; 400 with `{"error":"invalid_request"}` for an invalid token;
/// and 503 when auth's keys cannot be fetched.
/// handler succeeds; 400 with `{"error":"invalid_request"}` for an invalid token
/// or a request over 64 KiB; and 503 when auth's keys cannot be fetched.
///
/// ```no_run
/// # fn run(auth: sourceorigin_auth::axum::LoginRoutes) {
Expand Down Expand Up @@ -365,7 +365,11 @@ impl LoginRoutes {
.route("/callback", get(Login::callback))
.route("/logout", post(Login::logout));
if self.0.on_logout.is_some() {
router = router.route("/backchannel-logout", post(Login::backchannel_logout));
router = router.route(
"/backchannel-logout",
post(Login::backchannel_logout)
.layer(DefaultBodyLimit::max(MAX_LOGOUT_REQUEST_BYTES)),
);
}
router.with_state(Arc::new(self.0.clone()))
}
Expand Down
31 changes: 31 additions & 0 deletions crates/auth-sdk/src/axum/tests/backchannel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,34 @@ async fn backchannel_logout_hands_tokens_to_the_handler() {
}
assert_eq!(received.lock().expect("received").len(), 3, "never handled");
}

/// The route reads at most 64 KiB, like the TypeScript SDK: a larger form is
/// refused as invalid without reaching the handler, even around a valid token.
#[tokio::test]
async fn backchannel_logout_refuses_large_requests() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let handled = Arc::new(Mutex::new(0));
let app = login_app_with(&endpoint.issuer(&clock()), |routes| {
let handled = handled.clone();
routes.on_backchannel_logout(move |_: crate::LogoutToken| {
*handled.lock().expect("handled") += 1;
async { Ok::<_, Down>(()) }
})
});
let token = logout(Some(USER), None);
let response = post_logout(
&app,
format!("logout_token={token}&pad={}", "x".repeat(1 << 20)),
)
.await;
assert_eq!(
status(&response),
(StatusCode::BAD_REQUEST, Some("no-store"))
);
assert_eq!(text(response).await, r#"{"error":"invalid_request"}"#);
assert_eq!(*handled.lock().expect("handled"), 0, "never handled");

let response = post_logout(&app, format!("logout_token={token}&pad=x")).await;
assert_eq!(status(&response), (StatusCode::OK, Some("no-store")));
assert_eq!(*handled.lock().expect("handled"), 1);
}
3 changes: 3 additions & 0 deletions crates/common/src/protocol/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ super::sdk_constants! {
pub const MAX_LOGOUT_LIFETIME: TimeDelta = TimeDelta::minutes(10);
/// Longest compact token read, in bytes: decoding is bounded before it starts.
pub const MAX_TOKEN_BYTES: usize = 16 * 1024;
/// Most bytes read of a back-channel logout request, whose one logout token is at
/// most `MAX_TOKEN_BYTES`. A larger body is refused as an invalid request.
pub const MAX_LOGOUT_REQUEST_BYTES: usize = 4 * MAX_TOKEN_BYTES;
/// Shortest RSA modulus a key may have, in bits (RFC 7518 §3.3).
pub const MIN_MODULUS_BITS: usize = 2048;
/// Longest RSA modulus a key may have, in bits, as aws-lc verifies.
Expand Down
7 changes: 4 additions & 3 deletions docs/dev/architecture/sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,10 +418,11 @@ names where every replica sees it, so the app refuses those sessions itself: tho
with the token's `sid` (auth's session ID), or without one, every session of its
`sub` (the user) signed in before the token's `iat`. A record can go a session
lifetime after its token. Auth delivers again until it gets a 200, so a handler
must be idempotent and return only once its record is durable. The route answers
must be idempotent and return only once its record is durable. The route reads
at most 64 KiB of the request, since a logout token is at most 16 KiB. It answers
200 once the handler succeeds, 400 with `{"error":"invalid_request"}` for an invalid
token, 503 when signing keys cannot be fetched and 500 when the handler fails, so
auth retries. Every answer has `Cache-Control: no-store`.
token or a larger request, 503 when signing keys cannot be fetched and 500 when the
handler fails, so auth retries. Every answer has `Cache-Control: no-store`.

## Step-up

Expand Down
5 changes: 2 additions & 3 deletions packages/auth/src/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
DEFAULT_SESSION_LIFETIME,
type IdTokenClaims,
MAX_COOKIE_BYTES,
MAX_LOGOUT_REQUEST_BYTES,
MAX_PENDING_COOKIE_BYTES,
MAX_RETURN_TO_BYTES,
PENDING_LOGIN_LIFETIME,
Expand All @@ -36,8 +37,6 @@ import type { CookieKey } from './seal.ts';
import { type PendingAuthorization, StoredLogin, pendingAuthorization } from './session.ts';
import { AuthenticatedToken, type LogoutToken } from './token.ts';

/** Longest back-channel logout request read: a logout token is at most 16 KiB. */
const MAX_LOGOUT_REQUEST = 64 * 1024;
/** Methods that must not change anything, so any origin may send them with the session cookie. */
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);

Expand Down Expand Up @@ -794,7 +793,7 @@ export class Login {
const invalid = () => Response.json({ error: 'invalid_request' }, { status: 400 });
const type = request.headers.get('content-type') ?? '';
if (!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(type)) return invalid();
const body = await Http.readBody(request.body, MAX_LOGOUT_REQUEST);
const body = await Http.readBody(request.body, MAX_LOGOUT_REQUEST_BYTES);
if (body === undefined) return invalid();
const form = new URLSearchParams(new TextDecoder().decode(body));
const [token, ...others] = form.getAll('logout_token');
Expand Down
6 changes: 6 additions & 0 deletions packages/auth/src/protocol.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.