Skip to content
Open
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
4 changes: 2 additions & 2 deletions crates/auth-sdk/src/axum/tests/backchannel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ struct Down;
/// 500 when it fails, so auth retries; an invalid token never reaches it.
#[tokio::test]
async fn backchannel_logout_hands_tokens_to_the_handler() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let issuer = endpoint.issuer(&clock());
let response = post_logout(
&login_app(&issuer),
Expand Down Expand Up @@ -126,7 +126,7 @@ async fn backchannel_logout_hands_tokens_to_the_handler() {
/// 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 endpoint = TokenEndpoint::start().await;
let handled = Arc::new(Mutex::new(0));
let app = login_app_with(&endpoint.issuer(&clock()), |routes| {
let handled = handled.clone();
Expand Down
18 changes: 9 additions & 9 deletions crates/auth-sdk/src/axum/tests/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ fn return_to_vectors() {
/// not redeem it: the login routes take confidential clients only.
#[tokio::test]
async fn login_routes_refuse_public_clients() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let public = endpoint.issuer(&clock()).client(ClientConfig {
client_id: CLIENT.parse().expect("client ID"),
credentials: Credentials::None,
Expand All @@ -39,7 +39,7 @@ async fn login_routes_refuse_public_clients() {
/// redirect to auth would fail its CORS check.
#[tokio::test]
async fn signed_in_redirects_only_navigations() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
let response = get_with(&app, "/app/notes?page=2", &[]).await;
assert_eq!(
Expand All @@ -61,7 +61,7 @@ async fn signed_in_redirects_only_navigations() {
/// the 401 instead of a redirect.
#[tokio::test]
async fn step_ups_in_nested_routers_keep_their_prefix() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let issuer = endpoint.issuer(&clock());
let key = CookieKey::generate().expect("cookie key");
let auth = LoginRoutes::new(client(&issuer), key).expect("a confidential client");
Expand Down Expand Up @@ -101,7 +101,7 @@ async fn step_ups_in_nested_routers_keep_their_prefix() {
/// start at once, a browser holds at most three cookies, one per slot.
#[tokio::test]
async fn logins_in_several_tabs_complete() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
// Start logins until every slot is used: random `state`s land in all three
// within 200 but for a chance of about 1 in 10^35.
Expand Down Expand Up @@ -154,7 +154,7 @@ async fn logins_in_several_tabs_complete() {
/// it returns home instead, and to the root when the home path is too long as well.
#[tokio::test]
async fn pending_cookies_fit_their_slots() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let issuer = endpoint.issuer(&clock());
// Quotes double in JSON, so 2048 of them would seal to some 6 KB.
let quotes = format!("%2F{}", "%22".repeat(2047));
Expand Down Expand Up @@ -218,7 +218,7 @@ async fn send_from(
/// Logout is accepted only from the app's own pages.
#[tokio::test]
async fn logout_refuses_other_origins() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
let session = sign_in(&app, USER).await;
for (fetch_site, origin, own) in ORIGINS {
Expand All @@ -242,7 +242,7 @@ async fn logout_refuses_other_origins() {
/// [`CrossOrigin`] skip the check.
#[tokio::test]
async fn signed_in_refuses_unsafe_requests_from_other_origins() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
let cookie = sign_in(&app, USER).await;
let signed_in =
Expand Down Expand Up @@ -286,7 +286,7 @@ const OTHER: &str = "01936f3e-8c00-7000-8000-000000000009";
/// accounts.
#[tokio::test]
async fn step_ups_stay_on_the_signed_in_account() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
let session = sign_in(&app, USER).await;
let step_up = "%2F&step_up=true";
Expand Down Expand Up @@ -350,7 +350,7 @@ async fn step_ups_stay_on_the_signed_in_account() {
/// names; another user's grant is revoked as it is refused.
#[tokio::test]
async fn hinted_logins_complete_only_for_the_hinted_user() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let client = client(&endpoint.issuer(&clock()));
let claims = serde_json::from_value(id_claims(USER)).expect("ID token claims");
let hint = crate::IdToken::unchecked(claims, "id-0");
Expand Down
20 changes: 8 additions & 12 deletions crates/auth-sdk/src/axum/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,9 @@ use ::axum::{
use chrono::Utc;
use serde_json::json;
use sourceorigin_common::protocol::jwt::TokenType;
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
time::Duration,
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
};
use tower::ServiceExt;
use url::Url;
Expand Down Expand Up @@ -122,19 +119,18 @@ struct TokenEndpoint {
revocations_fail: Arc<AtomicBool>,
/// Tokens whose revocation fails, while others' succeeds.
refused: Arc<Mutex<Vec<String>>>,
/// Whether revocations hang for an hour before answering, as a stuck auth would.
/// Whether revocations never answer, as a stuck auth would.
revocations_hang: Arc<AtomicBool>,
}

/// The form a token or revocation request posts.
type Form = std::collections::HashMap<String, String>;

impl TokenEndpoint {
/// Serves endpoints whose `n`th refresh answers, after `delay`, `access-n` and no
/// refresh token, as auth answers a confidential client.
async fn start(delay: Duration) -> Self {
/// Serves endpoints whose `n`th refresh answers `access-n` and no refresh
/// token, as auth answers a confidential client.
async fn start() -> Self {
Self::refreshing(move |call| async move {
tokio::time::sleep(delay).await;
::axum::Json(Self::tokens(&format!("access-{call}"))).into_response()
})
.await
Expand Down Expand Up @@ -199,7 +195,7 @@ impl TokenEndpoint {
let revoke = move |::axum::Form(form): ::axum::Form<Form>| async move {
received.fetch_add(1, Ordering::SeqCst);
if hanging.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_secs(3600)).await;
std::future::pending::<()>().await;
}
let token = &form["token"];
if failing.load(Ordering::SeqCst) || refusing.lock().expect("refused").contains(token) {
Expand Down
32 changes: 23 additions & 9 deletions crates/auth-sdk/src/axum/tests/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use chrono::TimeDelta;
/// the shape they write, or none.
#[tokio::test]
async fn session_cookie_vectors() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
for case in Case::all("sessions") {
let client = endpoint.issuer(&case.clock()).client(ClientConfig {
client_id: case.text("client_id").parse().expect("client ID"),
Expand Down Expand Up @@ -96,7 +96,21 @@ async fn home(app: &Router, session: &str) -> (StatusCode, String, Option<String
/// session twice refreshes once.
#[tokio::test]
async fn concurrent_refreshes_all_succeed() {
let endpoint = TokenEndpoint::start(Duration::from_millis(100)).await;
// Auth answers a refresh only once two are in flight, so the first two overlap:
// a lease between them would leave the first unanswered.
let arrived = tokio::sync::watch::Sender::new(0_usize);
let endpoint = TokenEndpoint::refreshing(move |call| {
let arrived = arrived.clone();
async move {
let mut both = arrived.subscribe();
arrived.send_modify(|count| *count += 1);
both.wait_for(|&count| count >= 2)
.await
.expect("the endpoint holds a sender");
::axum::Json(TokenEndpoint::tokens(&format!("access-{call}"))).into_response()
}
})
.await;
let clock = clock();
let app = login_app(&endpoint.issuer(&clock));
let session = sign_in(&app, USER).await;
Expand Down Expand Up @@ -164,7 +178,7 @@ async fn refresh_failures_end_the_session_only_when_auth_refuses() {
/// response clears it.
#[tokio::test]
async fn ended_sessions_are_cleared() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let clock = clock();
let app = login_app(&endpoint.issuer(&clock));
let session = sign_in(&app, USER).await;
Expand All @@ -186,7 +200,7 @@ async fn ended_sessions_are_cleared() {
/// cookie stays, for the user to try again.
#[tokio::test]
async fn logout_revokes_the_refresh_token() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let app = login_app(&endpoint.issuer(&clock()));
let session = sign_in(&app, USER).await;
let logout = || async {
Expand Down Expand Up @@ -232,7 +246,7 @@ async fn logout_revokes_the_refresh_token() {
/// sign in again.
#[tokio::test]
async fn sign_ins_revoke_the_session_they_replace() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let clock = clock();
let app = login_app(&endpoint.issuer(&clock));
let first = sign_in(&app, USER).await;
Expand Down Expand Up @@ -329,7 +343,7 @@ fn worst_case_tokens(access_bytes: usize) -> Tokens {
/// would drop.
#[tokio::test]
async fn sessions_fit_in_a_cookie() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
let routes = LoginRoutes::new(
client(&endpoint.issuer(&clock())),
CookieKey::generate().expect("cookie key"),
Expand Down Expand Up @@ -368,14 +382,14 @@ fn sessions_without_a_refresh_token_end_with_their_access_token() {
/// replacing the session answers 502 too, so neither hangs.
#[tokio::test]
async fn revocations_give_up_after_their_deadline() {
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
let endpoint = TokenEndpoint::start().await;
// An injected client without a timeout of its own.
let http = Http::plain(reqwest::Client::builder());
let app = login_app(&endpoint.issuer_with(&clock(), http));
let session = sign_in(&app, USER).await;
endpoint.revocations_hang.store(true, Ordering::SeqCst);
// Waiting out the hour the revocation hangs takes no time, but the deadline
// must end it first.
// The revocation never answers: the SDK's deadline ends it, which paused
// time reaches at once.
tokio::time::pause();
let logout = Request::post("/auth/logout")
.header(header::COOKIE, &session)
Expand Down
8 changes: 5 additions & 3 deletions crates/auth-sdk/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -800,9 +800,11 @@ async fn cancelled_fetches_leave_keys_unavailable() {
Arc::new(ManualClock::at(1_767_225_600)),
);
let token = vector_token("access-valid");
let cancelled =
tokio::time::timeout(std::time::Duration::from_millis(100), verify(&keys, &token)).await;
assert!(cancelled.is_err(), "the fetch never completes");
// Cancelled once the server accepts its connection.
tokio::select! {
verified = verify(&keys, &token) => panic!("the fetch never completes: {verified:?}"),
accepted = silent.accept() => drop(accepted.expect("the fetch connects")),
}
assert!(matches!(
verify(&keys, &token).await,
Err(TokenError::Keys(KeyError::Unavailable))
Expand Down