//! Token administration (`/tokens`, `/tokens/who`) answers only a caller //! on this machine, and mints a token whose secret is shown exactly once //! (src/routes/tokens.rs, src/tokens.rs). //! //! The peer address is the `ConnectInfo` a real server provides //! (src/main.rs); these in-process requests supply one the same way //! tests/get_test_token.rs does. The registry is a throwaway SQLite file //! under the temp dir, wired in through `GN4_API_TOKENS_DB` before the //! first `Config::load()` in this process. use axum::body::Body; use axum::extract::ConnectInfo; use axum::http::{Method, Request, StatusCode}; use http_body_util::BodyExt; use serde_json::{Value, json}; use std::net::SocketAddr; use std::sync::OnceLock; use tower::ServiceExt; fn registry_path() -> &'static str { static PATH: OnceLock = OnceLock::new(); PATH.get_or_init(|| { let path = std::env::temp_dir().join(format!("gn4-tokens-it-{}.sqlite", std::process::id())); let _ = std::fs::remove_file(&path); let path = path.to_string_lossy().into_owned(); // SAFETY: set before any request in this test binary has loaded the // configuration, and to one value for the whole process, so no other // thread can observe a different one. `set_var` is unsafe on edition // 2024 because a concurrent reader could see a torn value; the // OnceLock makes this the only write. unsafe { std::env::set_var("GN4_API_TOKENS_DB", &path) }; path }) } /// A request against the app, from `peer`, optionally with a JSON body. async fn call( method: Method, uri: &str, peer: Option, body: Option, ) -> axum::response::Response { let mut builder = Request::builder().method(method).uri(uri); if body.is_some() { builder = builder.header("content-type", "application/json"); } let mut request = builder .body(match body { Some(body) => Body::from(body.to_string()), None => Body::empty(), }) .unwrap(); if let Some(peer) = peer { request.extensions_mut().insert(ConnectInfo(peer)); } genenetwork4::app().oneshot(request).await.unwrap() } async fn error_of(response: axum::response::Response) -> Value { let body = response.into_body().collect().await.unwrap().to_bytes(); serde_json::from_slice(&body).unwrap() } async fn json_of(response: axum::response::Response) -> Value { let body = response.into_body().collect().await.unwrap().to_bytes(); serde_json::from_slice(&body).unwrap() } #[tokio::test] async fn token_administration_refuses_every_caller_that_is_not_local() { registry_path(); let remote: SocketAddr = "10.0.0.5:4000".parse().unwrap(); let local: SocketAddr = "127.0.0.1:4000".parse().unwrap(); // Every route, from another machine, and from a local caller that says it // came through a proxy: minting a credential must never be reachable. for (method, uri, body) in [ (Method::GET, "/tokens", None), ( Method::POST, "/tokens", Some(json!({"id": "x-1", "subject": "x"})), ), (Method::DELETE, "/tokens/x-1", None), (Method::GET, "/tokens/who", None), ] { let response = call(method.clone(), uri, Some(remote), body.clone()).await; assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} remote"); let error = error_of(response).await; assert_eq!(error["code"], "not_local", "{method} {uri}"); assert!(error["detail"].as_str().unwrap_or_default().contains("this machine")); // Fail closed with no peer at all. let response = call(method.clone(), uri, None, body.clone()).await; assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} no peer"); // A local peer whose request claims to be proxied: a reverse proxy on // this host would make every remote client look local. let request = Request::builder() .method(method.clone()) .uri(uri) .header("x-forwarded-for", "203.0.113.9") .body(Body::empty()) .unwrap(); let mut request = request; request.extensions_mut().insert(ConnectInfo(local)); let response = genenetwork4::app().oneshot(request).await.unwrap(); assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} proxied"); } } #[tokio::test] async fn a_token_minted_locally_authenticates_and_is_then_revoked() { registry_path(); let local: SocketAddr = "127.0.0.1:4000".parse().unwrap(); let response = call( Method::POST, "/tokens", Some(local), Some(json!({ "id": "it-1", "subject": "zachs", "scope": "public", "ttl_days": 7, "note": "integration test" })), ) .await; assert_eq!(response.status(), StatusCode::OK); let reply = json_of(response).await; let token = reply["data"]["token"].as_str().expect("the secret, once").to_string(); assert!(token.starts_with("gn4ai_"), "{token}"); assert_eq!(token.len(), 64, "{token}"); assert_eq!(reply["data"]["id"], "it-1"); assert_eq!(reply["data"]["status"], "active"); // The listing never repeats the secret or its hash. let response = call(Method::GET, "/tokens", Some(local), None).await; let listing = json_of(response).await; let listing_text = listing.to_string(); assert!(!listing_text.contains(&token), "the listing leaked the token"); assert!(!listing_text.contains("sha256")); assert_eq!(listing["data"][0]["id"], "it-1"); // A second mint with the same id is a conflict, not a server error. let response = call( Method::POST, "/tokens", Some(local), Some(json!({"id": "it-1", "subject": "zachs"})), ) .await; assert_eq!(response.status(), StatusCode::CONFLICT); // The token works as a credential: /tokens/who describes it (it is the // only route that needs no model access to prove the extractor branch). let response = call_with_bearer(Method::GET, "/tokens/who", local, &token).await; assert_eq!(response.status(), StatusCode::OK); let who = json_of(response).await; assert_eq!(who["data"]["scheme"], "opaque"); assert_eq!(who["data"]["subject"], "zachs"); assert_eq!(who["data"]["id"], "it-1"); assert!(who["data"]["created_at"].as_i64().is_some()); // Revoking takes effect on the next request, with no restart. let response = call(Method::DELETE, "/tokens/it-1", Some(local), None).await; assert_eq!(response.status(), StatusCode::OK); assert_eq!(json_of(response).await["data"]["status"], "revoked"); let response = call_with_bearer(Method::GET, "/tokens/who", local, &token).await; assert_eq!(response.status(), StatusCode::UNAUTHORIZED); // A typo is refused as unmintable, before any registry lookup, and // says so the same way as an unknown-but-well-formed token: the answer // must not distinguish "not ours" from "no such token" to a caller. let mut typo = token.clone().into_bytes(); typo[10] = if typo[10] == b'a' { b'b' } else { b'a' }; let typo = String::from_utf8(typo).unwrap(); for candidate in [typo, "gn4ai_".to_string() + &"z".repeat(60), "not-a-token".to_string()] { let response = call_with_bearer(Method::GET, "/tokens/who", local, &candidate).await; assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{candidate}"); } } async fn call_with_bearer( method: Method, uri: &str, peer: SocketAddr, token: &str, ) -> axum::response::Response { let mut request = Request::builder() .method(method) .uri(uri) .header("authorization", format!("Bearer {token}")) .body(Body::empty()) .unwrap(); request.extensions_mut().insert(ConnectInfo(peer)); genenetwork4::app().oneshot(request).await.unwrap() }