chore: rustfmt the workspace and make clippy -D warnings pass
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -94,7 +94,9 @@ fn sign(alg: &str, kid: &str, signer: usize, claims: &Value) -> String {
|
||||
let header = json!({"alg": alg, "typ": "JWT", "kid": kid});
|
||||
let signing_input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string()));
|
||||
let signature = match alg {
|
||||
"RS256" => b64(SigningKey::<Sha256>::new(keys()[signer].clone()).sign(signing_input.as_bytes()).to_bytes()),
|
||||
"RS256" => b64(SigningKey::<Sha256>::new(keys()[signer].clone())
|
||||
.sign(signing_input.as_bytes())
|
||||
.to_bytes()),
|
||||
"HS256" => {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(CLIENT_SECRET.as_bytes()).unwrap();
|
||||
mac.update(signing_input.as_bytes());
|
||||
@@ -112,10 +114,14 @@ impl Respond for TokenEndpoint {
|
||||
return ResponseTemplate::new(scenario.token_status);
|
||||
}
|
||||
let form: std::collections::HashMap<String, String> =
|
||||
openidconnect::url::form_urlencoded::parse(&request.body).into_owned().collect();
|
||||
openidconnect::url::form_urlencoded::parse(&request.body)
|
||||
.into_owned()
|
||||
.collect();
|
||||
// Real PKCE check: S256(code_verifier) must equal the challenge sent at /authorize.
|
||||
let verifier = form.get("code_verifier").cloned().unwrap_or_default();
|
||||
if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge || form.get("code").map(String::as_str) != Some("good-code") {
|
||||
if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge
|
||||
|| form.get("code").map(String::as_str) != Some("good-code")
|
||||
{
|
||||
return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"}));
|
||||
}
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
@@ -155,12 +161,17 @@ impl Idp {
|
||||
async fn start() -> Self {
|
||||
// Generate the RSA keys up front: inside a mock handler, a slow debug-build
|
||||
// keygen would eat the hub's HTTP timeout.
|
||||
tokio::task::spawn_blocking(|| { keys(); }).await.unwrap();
|
||||
tokio::task::spawn_blocking(|| {
|
||||
keys();
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let server = MockServer::start().await;
|
||||
let scenario = Arc::new(Mutex::new(Scenario::default()));
|
||||
let jwks = Arc::new(Mutex::new(vec![("k1", 0usize)]));
|
||||
let issuer = server.uri();
|
||||
Mock::given(method("GET")).and(path("/.well-known/openid-configuration"))
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/openid-configuration"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"issuer": issuer,
|
||||
"authorization_endpoint": format!("{issuer}/authorize"),
|
||||
@@ -170,22 +181,39 @@ impl Idp {
|
||||
"subject_types_supported": ["public"],
|
||||
"id_token_signing_alg_values_supported": ["RS256"],
|
||||
})))
|
||||
.mount(&server).await;
|
||||
.mount(&server)
|
||||
.await;
|
||||
let served = jwks.clone();
|
||||
Mock::given(method("GET")).and(path("/jwks"))
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/jwks"))
|
||||
.respond_with(move |_: &MockRequest| {
|
||||
let keys_json: Vec<Value> = served.lock().unwrap().iter().map(|(kid, index)| {
|
||||
let public = keys()[*index].to_public_key();
|
||||
json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid,
|
||||
let keys_json: Vec<Value> = served
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(kid, index)| {
|
||||
let public = keys()[*index].to_public_key();
|
||||
json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid,
|
||||
"n": b64(public.n().to_bytes_be()), "e": b64(public.e().to_bytes_be())})
|
||||
}).collect();
|
||||
})
|
||||
.collect();
|
||||
ResponseTemplate::new(200).set_body_json(json!({"keys": keys_json}))
|
||||
})
|
||||
.mount(&server).await;
|
||||
Mock::given(method("POST")).and(path("/token"))
|
||||
.respond_with(TokenEndpoint { scenario: scenario.clone(), issuer })
|
||||
.mount(&server).await;
|
||||
Self { server, scenario, jwks }
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(TokenEndpoint {
|
||||
scenario: scenario.clone(),
|
||||
issuer,
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
Self {
|
||||
server,
|
||||
scenario,
|
||||
jwks,
|
||||
}
|
||||
}
|
||||
|
||||
fn issuer(&self) -> String {
|
||||
@@ -193,7 +221,13 @@ impl Idp {
|
||||
}
|
||||
|
||||
async fn hits(&self, route: &str) -> usize {
|
||||
self.server.received_requests().await.unwrap().iter().filter(|r| r.url.path() == route).count()
|
||||
self.server
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == route)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,12 +248,24 @@ fn config(idp: &Idp) -> OidcConfig {
|
||||
async fn harness_with(min_refresh: Duration) -> Harness {
|
||||
let idp = Idp::start().await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
|
||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
|
||||
.await
|
||||
.unwrap();
|
||||
let config = config(&idp);
|
||||
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint());
|
||||
state.oidc = Some(Arc::new(OidcProvider::new(config).unwrap().with_min_refresh(min_refresh)));
|
||||
state.sessions =
|
||||
SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint());
|
||||
state.oidc = Some(Arc::new(
|
||||
OidcProvider::new(config)
|
||||
.unwrap()
|
||||
.with_min_refresh(min_refresh),
|
||||
));
|
||||
let app = crate::api::router(state.clone());
|
||||
Harness { app, state, idp, _dir: dir }
|
||||
Harness {
|
||||
app,
|
||||
state,
|
||||
idp,
|
||||
_dir: dir,
|
||||
}
|
||||
}
|
||||
|
||||
async fn harness() -> Harness {
|
||||
@@ -227,7 +273,9 @@ async fn harness() -> Harness {
|
||||
}
|
||||
|
||||
fn get(uri: &str, cookies: &[String]) -> Request<Body> {
|
||||
let mut request = Request::builder().uri(uri).extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
|
||||
let mut request = Request::builder()
|
||||
.uri(uri)
|
||||
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
|
||||
if !cookies.is_empty() {
|
||||
request = request.header(header::COOKIE, cookies.join("; "));
|
||||
}
|
||||
@@ -235,7 +283,12 @@ fn get(uri: &str, cookies: &[String]) -> Request<Body> {
|
||||
}
|
||||
|
||||
fn set_cookies(response: &Response<Body>) -> Vec<String> {
|
||||
response.headers().get_all(header::SET_COOKIE).iter().map(|v| v.to_str().unwrap().to_string()).collect()
|
||||
response
|
||||
.headers()
|
||||
.get_all(header::SET_COOKIE)
|
||||
.iter()
|
||||
.map(|v| v.to_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn cookie_pair(set_cookie: &str) -> String {
|
||||
@@ -243,7 +296,10 @@ fn cookie_pair(set_cookie: &str) -> String {
|
||||
}
|
||||
|
||||
fn location(response: &Response<Body>) -> String {
|
||||
response.headers()[header::LOCATION].to_str().unwrap().to_string()
|
||||
response.headers()[header::LOCATION]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
struct Started {
|
||||
@@ -260,10 +316,17 @@ impl Harness {
|
||||
/// nonce and PKCE challenge the hub generated.
|
||||
async fn start(&self) -> Started {
|
||||
let response = self.call(get("/api/v1/auth/oidc/login", &[])).await;
|
||||
assert!(response.status().is_redirection(), "login redirects, got {}", response.status());
|
||||
assert!(
|
||||
response.status().is_redirection(),
|
||||
"login redirects, got {}",
|
||||
response.status()
|
||||
);
|
||||
let target = openidconnect::url::Url::parse(&location(&response)).unwrap();
|
||||
assert!(target.as_str().starts_with(&format!("{}/authorize", self.idp.issuer())));
|
||||
let q: std::collections::HashMap<String, String> = target.query_pairs().into_owned().collect();
|
||||
assert!(target
|
||||
.as_str()
|
||||
.starts_with(&format!("{}/authorize", self.idp.issuer())));
|
||||
let q: std::collections::HashMap<String, String> =
|
||||
target.query_pairs().into_owned().collect();
|
||||
assert_eq!(q["response_type"], "code");
|
||||
assert_eq!(q["client_id"], CLIENT_ID);
|
||||
assert_eq!(q["redirect_uri"], REDIRECT);
|
||||
@@ -281,17 +344,26 @@ impl Harness {
|
||||
scenario.nonce = q["nonce"].clone();
|
||||
scenario.challenge = q["code_challenge"].clone();
|
||||
}
|
||||
Started { state: q["state"].clone(), correlation: cookie_pair(&cookies[0]) }
|
||||
Started {
|
||||
state: q["state"].clone(),
|
||||
correlation: cookie_pair(&cookies[0]),
|
||||
}
|
||||
}
|
||||
|
||||
async fn callback(&self, started: &Started, query: &str) -> Response<Body> {
|
||||
self.call(get(&format!("/api/v1/auth/oidc/callback?{query}"), &[started.correlation.clone()])).await
|
||||
self.call(get(
|
||||
&format!("/api/v1/auth/oidc/callback?{query}"),
|
||||
std::slice::from_ref(&started.correlation),
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Full successful-or-not login with the current scenario.
|
||||
async fn login(&self) -> (Response<Body>, Started) {
|
||||
let started = self.start().await;
|
||||
let response = self.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
let response = self
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
(response, started)
|
||||
}
|
||||
|
||||
@@ -307,13 +379,19 @@ impl Harness {
|
||||
}
|
||||
|
||||
fn query<T: rusqlite::types::FromSql>(&self, sql: &str) -> T {
|
||||
rusqlite::Connection::open(self.state.data_dir.join("tessera.db")).unwrap().query_row(sql, [], |r| r.get(0)).unwrap()
|
||||
rusqlite::Connection::open(self.state.data_dir.join("tessera.db"))
|
||||
.unwrap()
|
||||
.query_row(sql, [], |r| r.get(0))
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn session_cookie(response: &Response<Body>) -> String {
|
||||
let cookies = set_cookies(response);
|
||||
let session = cookies.iter().find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0")).expect("session cookie");
|
||||
let session = cookies
|
||||
.iter()
|
||||
.find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0"))
|
||||
.expect("session cookie");
|
||||
for flag in ["HttpOnly", "Secure", "SameSite=Strict"] {
|
||||
assert!(session.contains(flag));
|
||||
}
|
||||
@@ -331,14 +409,25 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() {
|
||||
assert_eq!(response.status(), StatusCode::SEE_OTHER);
|
||||
assert_eq!(location(&response), "/", "fixed redirect target");
|
||||
let cookies = set_cookies(&response);
|
||||
assert_eq!(cookies.len(), 2, "session cookie plus cleared correlation cookie: {cookies:?}");
|
||||
assert!(cookies.iter().any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0")));
|
||||
assert_eq!(
|
||||
cookies.len(),
|
||||
2,
|
||||
"session cookie plus cleared correlation cookie: {cookies:?}"
|
||||
);
|
||||
assert!(cookies
|
||||
.iter()
|
||||
.any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0")));
|
||||
let session = session_cookie(&response);
|
||||
let headers_text = format!("{:?}", response.headers());
|
||||
assert!(!headers_text.contains("synthetic-access-token") && !headers_text.contains("eyJ"));
|
||||
assert!(to_bytes(response.into_body(), 4096).await.unwrap().is_empty());
|
||||
assert!(to_bytes(response.into_body(), 4096)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
|
||||
let me = h.call(get("/api/v1/me", &[session.clone()])).await;
|
||||
let me = h
|
||||
.call(get("/api/v1/me", std::slice::from_ref(&session)))
|
||||
.await;
|
||||
assert_eq!(me.status(), StatusCode::OK);
|
||||
let me = json_body(me).await;
|
||||
assert_eq!(me["kind"], "user");
|
||||
@@ -346,18 +435,29 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() {
|
||||
assert!(me["id"].as_str().unwrap().starts_with("oidc:"));
|
||||
assert_eq!(me["display_name"], "Ada Admin");
|
||||
assert_eq!(me["capabilities"][0], "admin");
|
||||
assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
h.call(get("/api/v1/orbits", std::slice::from_ref(&session)))
|
||||
.await
|
||||
.status(),
|
||||
StatusCode::OK
|
||||
);
|
||||
|
||||
// Identity is (issuer, subject); the transaction was consumed; the audit actor is the stable user id.
|
||||
let issuer: String = h.query("SELECT issuer FROM users");
|
||||
assert_eq!(issuer, h.idp.issuer());
|
||||
assert_eq!(h.count("oidc_login"), 0);
|
||||
let actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'");
|
||||
let actor: String = h.query(
|
||||
"SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'",
|
||||
);
|
||||
assert_eq!(actor, me["id"]);
|
||||
// PKCE verified by the IdP and the code is not reusable by replaying the callback.
|
||||
let replay = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
let replay = h
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
assert_eq!(location(&replay), "/?auth_error=invalid_state");
|
||||
assert!(set_cookies(&replay).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")));
|
||||
assert!(set_cookies(&replay)
|
||||
.iter()
|
||||
.all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")));
|
||||
assert_eq!(h.count("sessions"), 1);
|
||||
}
|
||||
|
||||
@@ -365,29 +465,57 @@ async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() {
|
||||
async fn a_signed_in_user_without_a_grant_gets_identity_but_no_api_access() {
|
||||
let h = harness().await;
|
||||
// Display name "operator" must not be mistaken for the emergency account.
|
||||
h.mutate(|s| { s.sub = Some("plain-user".into()); s.name = Some("operator".into()); });
|
||||
h.mutate(|s| {
|
||||
s.sub = Some("plain-user".into());
|
||||
s.name = Some("operator".into());
|
||||
});
|
||||
let (response, _) = h.login().await;
|
||||
assert_eq!(location(&response), "/");
|
||||
let session = session_cookie(&response);
|
||||
|
||||
let me = json_body(h.call(get("/api/v1/me", &[session.clone()])).await).await;
|
||||
let me = json_body(
|
||||
h.call(get("/api/v1/me", std::slice::from_ref(&session)))
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(me["capabilities"].as_array().unwrap().len(), 0);
|
||||
assert!(me["id"].as_str().unwrap().starts_with("oidc:"), "{me}");
|
||||
let status = json_body(h.call(get("/api/v1/operator/session", &[session.clone()])).await).await;
|
||||
let status = json_body(
|
||||
h.call(get(
|
||||
"/api/v1/operator/session",
|
||||
std::slice::from_ref(&session),
|
||||
))
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status["authorized"], false);
|
||||
assert_eq!(status["actor"], "operator");
|
||||
assert!(status["csrf"].is_string(), "can still sign out");
|
||||
assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(
|
||||
h.call(get("/api/v1/orbits", std::slice::from_ref(&session)))
|
||||
.await
|
||||
.status(),
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
let denied_actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id DESC LIMIT 1");
|
||||
assert!(denied_actor.starts_with("oidc:"), "audited as the OIDC user, not emergency:operator: {denied_actor}");
|
||||
assert!(
|
||||
denied_actor.starts_with("oidc:"),
|
||||
"audited as the OIDC user, not emergency:operator: {denied_actor}"
|
||||
);
|
||||
|
||||
let logout = Request::builder().method("DELETE").uri("/api/v1/operator/session")
|
||||
let logout = Request::builder()
|
||||
.method("DELETE")
|
||||
.uri("/api/v1/operator/session")
|
||||
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()))
|
||||
.header(header::COOKIE, session.clone())
|
||||
.header("x-tessera-csrf", status["csrf"].as_str().unwrap())
|
||||
.body(Body::empty()).unwrap();
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert_eq!(h.call(logout).await.status(), StatusCode::NO_CONTENT);
|
||||
assert_eq!(h.call(get("/api/v1/me", &[session])).await.status(), StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(
|
||||
h.call(get("/api/v1/me", &[session])).await.status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -401,11 +529,22 @@ async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing(
|
||||
(Some(json!([["tessera-admins"]])), false),
|
||||
(None, false),
|
||||
] {
|
||||
h.mutate(|s| { s.sub = Some("group-user".into()); s.groups = groups.clone(); });
|
||||
h.mutate(|s| {
|
||||
s.sub = Some("group-user".into());
|
||||
s.groups = groups.clone();
|
||||
});
|
||||
let (response, _) = h.login().await;
|
||||
let session = session_cookie(&response);
|
||||
let expected = if expect_admin { StatusCode::OK } else { StatusCode::FORBIDDEN };
|
||||
assert_eq!(h.call(get("/api/v1/orbits", &[session])).await.status(), expected, "{groups:?}");
|
||||
let expected = if expect_admin {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::FORBIDDEN
|
||||
};
|
||||
assert_eq!(
|
||||
h.call(get("/api/v1/orbits", &[session])).await.status(),
|
||||
expected,
|
||||
"{groups:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,27 +552,56 @@ async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing(
|
||||
async fn the_same_email_under_a_different_subject_is_a_different_user() {
|
||||
let h = harness().await;
|
||||
for sub in ["sub-a", "sub-b", "sub-a"] {
|
||||
h.mutate(|s| { s.sub = Some(sub.into()); s.email = Some("same@example.com".into()); });
|
||||
h.mutate(|s| {
|
||||
s.sub = Some(sub.into());
|
||||
s.email = Some("same@example.com".into());
|
||||
});
|
||||
let (response, _) = h.login().await;
|
||||
assert_eq!(location(&response), "/");
|
||||
}
|
||||
assert_eq!(h.count("users"), 2, "two subjects, no linking by email; the repeat logs in as the first");
|
||||
assert_eq!(
|
||||
h.count("users"),
|
||||
2,
|
||||
"two subjects, no linking by email; the repeat logs in as the first"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_tokens_never_create_a_session_or_a_user() {
|
||||
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
|
||||
let h = harness().await;
|
||||
let cases: Vec<(&str, Box<dyn Fn(&mut Scenario)>)> = vec![
|
||||
("wrong nonce", Box::new(|s| s.nonce = "not-the-nonce".into())),
|
||||
("wrong issuer", Box::new(|s| s.iss = Some("https://evil.example".into()))),
|
||||
("wrong audience", Box::new(|s| s.aud = json!("someone-else"))),
|
||||
("extra audience without azp", Box::new(|s| s.aud = json!([CLIENT_ID, "other"]))),
|
||||
("azp is another client", Box::new(|s| { s.aud = json!([CLIENT_ID, "other"]); s.azp = Some("other".into()); })),
|
||||
type Case = (&'static str, Box<dyn Fn(&mut Scenario)>);
|
||||
let cases: Vec<Case> = vec![
|
||||
(
|
||||
"wrong nonce",
|
||||
Box::new(|s| s.nonce = "not-the-nonce".into()),
|
||||
),
|
||||
(
|
||||
"wrong issuer",
|
||||
Box::new(|s| s.iss = Some("https://evil.example".into())),
|
||||
),
|
||||
(
|
||||
"wrong audience",
|
||||
Box::new(|s| s.aud = json!("someone-else")),
|
||||
),
|
||||
(
|
||||
"extra audience without azp",
|
||||
Box::new(|s| s.aud = json!([CLIENT_ID, "other"])),
|
||||
),
|
||||
(
|
||||
"azp is another client",
|
||||
Box::new(|s| {
|
||||
s.aud = json!([CLIENT_ID, "other"]);
|
||||
s.azp = Some("other".into());
|
||||
}),
|
||||
),
|
||||
("expired", Box::new(|s| s.exp_in = -3600)),
|
||||
("signed by an attacker key", Box::new(|s| s.signer = 2)),
|
||||
("alg none", Box::new(|s| s.alg = "none")),
|
||||
("HS256 with the client secret", Box::new(|s| s.alg = "HS256")),
|
||||
(
|
||||
"HS256 with the client secret",
|
||||
Box::new(|s| s.alg = "HS256"),
|
||||
),
|
||||
("no subject", Box::new(|s| s.sub = None)),
|
||||
("empty subject", Box::new(|s| s.sub = Some(String::new()))),
|
||||
];
|
||||
@@ -441,10 +609,17 @@ async fn invalid_tokens_never_create_a_session_or_a_user() {
|
||||
h.mutate(|s| *s = Scenario::default());
|
||||
let started = h.start().await;
|
||||
h.mutate(|s| change(s));
|
||||
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
let response = h
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
let target = location(&response);
|
||||
assert!(target == "/?auth_error=failed", "{name}: {target}");
|
||||
assert!(set_cookies(&response).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")), "{name}");
|
||||
assert!(
|
||||
set_cookies(&response)
|
||||
.iter()
|
||||
.all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(h.count("sessions"), 0, "{name}");
|
||||
assert_eq!(h.count("users"), 0, "{name}");
|
||||
}
|
||||
@@ -455,28 +630,74 @@ async fn login_transactions_cannot_be_replayed_borrowed_or_forged() {
|
||||
let h = harness().await;
|
||||
// Another browser (no / wrong correlation cookie) holding the right state.
|
||||
let started = h.start().await;
|
||||
let no_cookie = h.call(get(&format!("/api/v1/auth/oidc/callback?code=good-code&state={}", started.state), &[])).await;
|
||||
let no_cookie = h
|
||||
.call(get(
|
||||
&format!(
|
||||
"/api/v1/auth/oidc/callback?code=good-code&state={}",
|
||||
started.state
|
||||
),
|
||||
&[],
|
||||
))
|
||||
.await;
|
||||
assert_eq!(location(&no_cookie), "/?auth_error=invalid_state");
|
||||
let again = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
assert_eq!(location(&again), "/?auth_error=invalid_state", "a failed attempt burns the transaction");
|
||||
let again = h
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
assert_eq!(
|
||||
location(&again),
|
||||
"/?auth_error=invalid_state",
|
||||
"a failed attempt burns the transaction"
|
||||
);
|
||||
|
||||
let started = h.start().await;
|
||||
let wrong = Started { state: started.state.clone(), correlation: "__Host-tessera-oidc=forged".into() };
|
||||
assert_eq!(location(&h.callback(&wrong, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state");
|
||||
let wrong = Started {
|
||||
state: started.state.clone(),
|
||||
correlation: "__Host-tessera-oidc=forged".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
location(
|
||||
&h.callback(&wrong, &format!("code=good-code&state={}", started.state))
|
||||
.await
|
||||
),
|
||||
"/?auth_error=invalid_state"
|
||||
);
|
||||
|
||||
// Unknown, missing and mismatched state.
|
||||
let started = h.start().await;
|
||||
assert_eq!(location(&h.callback(&started, "code=good-code&state=made-up").await), "/?auth_error=invalid_state");
|
||||
assert_eq!(location(&h.callback(&started, "code=good-code").await), "/?auth_error=invalid_state");
|
||||
assert_eq!(
|
||||
location(&h.callback(&started, "code=good-code&state=made-up").await),
|
||||
"/?auth_error=invalid_state"
|
||||
);
|
||||
assert_eq!(
|
||||
location(&h.callback(&started, "code=good-code").await),
|
||||
"/?auth_error=invalid_state"
|
||||
);
|
||||
|
||||
// Expired transaction.
|
||||
let started = h.start().await;
|
||||
rusqlite::Connection::open(h.state.data_dir.join("tessera.db")).unwrap().execute("UPDATE oidc_login SET expires_at = 1", []).unwrap();
|
||||
assert_eq!(location(&h.callback(&started, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state");
|
||||
rusqlite::Connection::open(h.state.data_dir.join("tessera.db"))
|
||||
.unwrap()
|
||||
.execute("UPDATE oidc_login SET expires_at = 1", [])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
location(
|
||||
&h.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await
|
||||
),
|
||||
"/?auth_error=invalid_state"
|
||||
);
|
||||
|
||||
// The IdP reporting an error: shown as a fixed code, nothing echoed, transaction consumed.
|
||||
let started = h.start().await;
|
||||
let denied = h.callback(&started, &format!("error=access_denied&error_description=secret-detail&state={}", started.state)).await;
|
||||
let denied = h
|
||||
.callback(
|
||||
&started,
|
||||
&format!(
|
||||
"error=access_denied&error_description=secret-detail&state={}",
|
||||
started.state
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(location(&denied), "/?auth_error=denied");
|
||||
assert!(!format!("{:?}", denied.headers()).contains("secret-detail"));
|
||||
assert_eq!(h.count("oidc_login"), 0);
|
||||
@@ -484,7 +705,13 @@ async fn login_transactions_cannot_be_replayed_borrowed_or_forged() {
|
||||
|
||||
// A wrong code is rejected by the IdP.
|
||||
let started = h.start().await;
|
||||
assert_eq!(location(&h.callback(&started, &format!("code=bad-code&state={}", started.state)).await), "/?auth_error=failed");
|
||||
assert_eq!(
|
||||
location(
|
||||
&h.callback(&started, &format!("code=bad-code&state={}", started.state))
|
||||
.await
|
||||
),
|
||||
"/?auth_error=failed"
|
||||
);
|
||||
assert_eq!(h.count("sessions"), 0);
|
||||
let failed: i64 = h.query("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'");
|
||||
assert!(failed >= 6);
|
||||
@@ -499,10 +726,17 @@ async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() {
|
||||
|
||||
// The IdP rotates: new key and kid, old key withdrawn. The cached key set is stale.
|
||||
*h.idp.jwks.lock().unwrap() = vec![("k2", 1)];
|
||||
h.mutate(|s| { s.signer = 1; s.kid = "k2"; });
|
||||
h.mutate(|s| {
|
||||
s.signer = 1;
|
||||
s.kid = "k2";
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
let (after, _) = h.login().await;
|
||||
assert_eq!(location(&after), "/", "refreshed once and verified with the new key");
|
||||
assert_eq!(
|
||||
location(&after),
|
||||
"/",
|
||||
"refreshed once and verified with the new key"
|
||||
);
|
||||
assert_eq!(h.idp.hits("/jwks").await, 2);
|
||||
|
||||
// With the default 60s gap, a flood of bad signatures cannot hammer the IdP.
|
||||
@@ -511,7 +745,9 @@ async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() {
|
||||
limited.mutate(|s| *s = Scenario::default());
|
||||
let started = limited.start().await;
|
||||
limited.mutate(|s| s.signer = 2);
|
||||
let r = limited.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
let r = limited
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
assert_eq!(location(&r), "/?auth_error=failed");
|
||||
}
|
||||
assert!(limited.idp.hits("/.well-known/openid-configuration").await <= 2);
|
||||
@@ -532,21 +768,37 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
|
||||
assert_eq!(location(&ok), "/");
|
||||
h.mutate(|s| s.token_status = 500);
|
||||
let started = h.start().await; // metadata is cached, so /login still works
|
||||
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
let response = h
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
assert!(response.status().is_redirection());
|
||||
assert!(location(&response).starts_with("/?auth_error="));
|
||||
h.idp.server.reset().await;
|
||||
let started = h.start().await;
|
||||
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
|
||||
assert!(location(&response).starts_with("/?auth_error="), "{}", location(&response));
|
||||
let response = h
|
||||
.callback(&started, &format!("code=good-code&state={}", started.state))
|
||||
.await;
|
||||
assert!(
|
||||
location(&response).starts_with("/?auth_error="),
|
||||
"{}",
|
||||
location(&response)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
|
||||
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
|
||||
.await
|
||||
.unwrap();
|
||||
let app = crate::api::router(state);
|
||||
for uri in ["/api/v1/auth/oidc/login", "/api/v1/auth/oidc/callback?code=x&state=y"] {
|
||||
assert_eq!(app.clone().oneshot(get(uri, &[])).await.unwrap().status(), StatusCode::NOT_FOUND);
|
||||
for uri in [
|
||||
"/api/v1/auth/oidc/login",
|
||||
"/api/v1/auth/oidc/callback?code=x&state=y",
|
||||
] {
|
||||
assert_eq!(
|
||||
app.clone().oneshot(get(uri, &[])).await.unwrap().status(),
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user