//! Exercises src/auth.rs against a real gn-auth instance. Needs one //! running and reachable at AUTH_SERVER_URL (see docs/gn-auth.md); //! skips with a message rather than failing when it isn't, same //! pattern as the MariaDB-backed tests. //! //! The fixtures below (token, resource id) are produced by hand //! against a from-scratch gn-auth instance as described in //! RELEASE_NOTES.md -- set these environment variables to point at //! your own instance and data before running: //! GN4_TEST_AUTH_TOKEN - a valid bearer token (e.g. from the //! password grant against /auth/token) //! GN4_TEST_RESOURCE_ID - a resource-id that token's user owns //! (e.g. from POST /auth/resource/populations/create) use genenetwork4::auth::{self, AuthToken}; mod common; use genenetwork4::config::Config; use tower::ServiceExt; fn auth_server_reachable(auth_server_url: &str) -> bool { ureq::get(format!( "{}/auth/public-jwks", auth_server_url.trim_end_matches('/') )) .call() .is_ok() } fn test_fixtures() -> Option<(String, String, String)> { let auth_server_url = Config::load().auth_server_url; let token = std::env::var("GN4_TEST_AUTH_TOKEN").ok()?; let resource_id = std::env::var("GN4_TEST_RESOURCE_ID").ok()?; Some((auth_server_url, token, resource_id)) } #[test] fn is_publicly_readable_skips_authorisation_entirely() { // No gn-auth call at all for public data -- this doesn't even need // a reachable server, which is the point: a public dataset costs // nothing beyond token verification. let recent = "2024-01-01 00:00:00"; assert!(auth::is_publicly_readable(2, 0, recent)); assert!(!auth::is_publicly_readable(0, 0, recent)); } #[tokio::test] async fn valid_token_is_accepted_and_resolves_sub() { let Some((auth_server_url, token, _)) = test_fixtures() else { eprintln!( "skipping valid_token_is_accepted_and_resolves_sub: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" ); return; }; if !auth_server_reachable(&auth_server_url) { eprintln!( "skipping valid_token_is_accepted_and_resolves_sub: no gn-auth at {auth_server_url}" ); return; } use axum::extract::FromRequestParts; use axum::http::Request; let request = Request::builder() .header("Authorization", format!("Bearer {token}")) .body(()) .unwrap(); let (mut parts, ()) = request.into_parts(); let auth_token = AuthToken::from_request_parts(&mut parts, &()) .await .unwrap(); assert!(!auth_token.sub.is_empty()); assert_eq!(auth_token.raw, token); } /// The proxy logs `$upstream_http_x_gn4_user`; this is where that header /// comes from. It has to name the caller on authenticated responses and /// stay off the ones with no identity to name -- the difference between "a /// log that says who is working" and one that says only which address. #[tokio::test] async fn an_authenticated_response_names_its_caller() { if !common::auth_server_available() { eprintln!("skipping an_authenticated_response_names_its_caller: no gn-auth reachable"); return; } let Some(token) = common::auth_token().await else { eprintln!("skipping an_authenticated_response_names_its_caller: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)"); return; }; use axum::body::Body; use axum::http::{Request, StatusCode}; use http_body_util::BodyExt; let response = genenetwork4::app() .oneshot( Request::builder() .uri("/species") .header("Authorization", format!("Bearer {token}")) .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); let named = response .headers() .get(genenetwork4::auth::USER_HEADER) .expect("an authenticated response names its caller") .to_str() .unwrap() .to_string(); // ... and it is the token's own subject, not a label. use axum::extract::FromRequestParts; let request = Request::builder() .header("Authorization", format!("Bearer {token}")) .body(()) .unwrap(); let (mut parts, ()) = request.into_parts(); let auth_token = genenetwork4::auth::AuthToken::from_request_parts(&mut parts, &()) .await .unwrap(); assert_eq!(named, auth_token.sub); // A response with no identity (no token) carries no name. let response = genenetwork4::app() .oneshot(Request::builder().uri("/version").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); assert!( response.headers().get(genenetwork4::auth::USER_HEADER).is_none(), "no token, no name" ); let _ = response.into_body().collect().await; } #[tokio::test] async fn malformed_token_is_rejected() { let Some((auth_server_url, _, _)) = test_fixtures() else { eprintln!( "skipping malformed_token_is_rejected: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" ); return; }; if !auth_server_reachable(&auth_server_url) { eprintln!("skipping malformed_token_is_rejected: no gn-auth at {auth_server_url}"); return; } use axum::extract::FromRequestParts; use axum::http::Request; let request = Request::builder() .header("Authorization", "Bearer not-a-real-token") .body(()) .unwrap(); let (mut parts, ()) = request.into_parts(); let result = AuthToken::from_request_parts(&mut parts, &()).await; assert!(result.is_err()); assert_eq!(result.err().unwrap().code, "invalid_token"); } #[test] fn owner_is_authorised_and_stranger_is_not() { let Some((auth_server_url, token, resource_id)) = test_fixtures() else { eprintln!( "skipping owner_is_authorised_and_stranger_is_not: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)" ); return; }; if !auth_server_reachable(&auth_server_url) { eprintln!( "skipping owner_is_authorised_and_stranger_is_not: no gn-auth at {auth_server_url}" ); return; } let owner = AuthToken { scheme: auth::Scheme::Jwt, id: None, sub: "owner".to_string(), scope: "profile resource".to_string(), raw: token, }; let authorised = auth::authorise( &auth_server_url, &owner, &resource_id, "group:resource:view-resource", ) .unwrap(); assert!( authorised, "the resource's own creator should hold view-resource" ); // A syntactically-valid but unrelated token has no roles on this // resource at all -- gn-auth's own default, not something this // client invents. let stranger = AuthToken { scheme: auth::Scheme::Jwt, id: None, sub: "stranger".to_string(), scope: "profile resource".to_string(), raw: "not-a-real-token".to_string(), }; let result = auth::authorise( &auth_server_url, &stranger, &resource_id, "group:resource:view-resource", ); // An invalid bearer token makes gn-auth treat the call as // anonymous (see docs/gn-auth.md); anonymous gets no roles on a // non-public resource, so this comes back Ok(false), not an error. assert_eq!(result, Ok(false)); } #[test] fn authorisation_result_is_cached() { let Some((auth_server_url, token, resource_id)) = test_fixtures() else { eprintln!( "skipping authorisation_result_is_cached: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)" ); return; }; if !auth_server_reachable(&auth_server_url) { eprintln!("skipping authorisation_result_is_cached: no gn-auth at {auth_server_url}"); return; } let owner = AuthToken { scheme: auth::Scheme::Jwt, id: None, sub: "cache-test-owner".to_string(), scope: "profile resource".to_string(), raw: token, }; let start = std::time::Instant::now(); auth::authorise( &auth_server_url, &owner, &resource_id, "group:resource:view-resource", ) .unwrap(); let first_call = start.elapsed(); let start = std::time::Instant::now(); auth::authorise( &auth_server_url, &owner, &resource_id, "group:resource:view-resource", ) .unwrap(); let second_call = start.elapsed(); // The second call hits the in-process cache and shouldn't touch // the network at all; it should be at least an order of magnitude // faster than the first, uncached call. assert!( second_call < first_call / 2, "expected the cached call ({second_call:?}) to be much faster than the first ({first_call:?})" ); }