//! Verifying bearer tokens issued by gn-auth, and checking gn-auth //! resource authorization for data that isn't public. See //! docs/gn-auth.md for the mechanism this implements. //! //! Two independent things happen here, and most endpoints only need //! the first: //! //! - **Token verification** ([`AuthToken`], an extractor): checks a //! bearer token's RS256 signature and standard time claims against //! gn-auth's JWKS (`GET /auth/public-jwks`), cached and refreshed //! periodically rather than fetched per request. Add `AuthToken` as //! a handler parameter to require a valid token; handlers that //! don't need one simply omit it -- this is what makes auth //! opt-in per route rather than a blanket gate. //! - **Resource authorization** ([`authorise`]): for data that isn't //! public (see [`is_publicly_readable`], matching GeneNetwork2's own //! `public > 0 AND confidentiality < 1` convention), asks gn-auth //! whether this token's holder has a given privilege on a specific //! resource (`POST /auth/resource/authorisation`), caching the //! per-(user, resource) answer briefly so repeated requests for the //! same resource don't each cost a round trip to gn-auth. use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::http::StatusCode; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; use crate::config::Config; use crate::error::ApiError; use crate::response::RequestInfo; /// The gn-auth privilege that means "can view this resource" -- the /// one every gated route in this API checks so far (see /// src/routes/datasets.rs, src/routes/traits.rs). pub const VIEW_RESOURCE_PRIVILEGE: &str = "group:resource:view-resource"; fn unauthorized(detail: impl Into) -> ApiError { ApiError::new( StatusCode::UNAUTHORIZED, "invalid_token", "Invalid or missing token", detail.into(), "authentication", ) } /// A verified caller: the token was signed by gn-auth and its /// standard time claims (exp/nbf, when present -- gn-auth itself /// treats them as optional, not every token carries them) checked. /// Does not by itself mean the caller is authorized for anything; see /// [`authorise`] for that. #[derive(Debug, Clone)] pub struct AuthToken { /// The token subject (gn-auth user id). pub sub: String, /// Space-separated OAuth2 scopes, e.g. "profile group resource". pub scope: String, /// The raw bearer token, forwarded as-is to gn-auth's own /// authorization endpoints on the caller's behalf. pub raw: String, } #[derive(Deserialize)] struct Claims { sub: String, #[serde(default)] scope: String, } impl FromRequestParts for AuthToken { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { let request = RequestInfo::from_parts(parts); let unauthorized = |detail: &str| unauthorized(detail).with_request_id(request.clone()); let header = parts .headers .get(axum::http::header::AUTHORIZATION) .and_then(|value| value.to_str().ok()) .ok_or_else(|| unauthorized("Missing Authorization header."))?; let token = header .strip_prefix("Bearer ") .ok_or_else(|| unauthorized("Authorization header must be a Bearer token."))?; let config = Config::load(); let claims = verify(token, &config.auth_server_url).map_err(|e| unauthorized(&e.to_string()))?; Ok(AuthToken { sub: claims.sub, scope: claims.scope, raw: token.to_string(), }) } } /// Verify `token`'s signature and standard time claims against /// `auth_server_url`'s JWKS. fn verify(token: &str, auth_server_url: &str) -> Result { let keys = jwks(auth_server_url)?; if keys.is_empty() { return Err("gn-auth has no signing keys published yet.".to_string()); } let mut validation = Validation::new(Algorithm::RS256); // gn-auth's own resource-server validator treats `exp` as // non-essential (not every token carries one), so don't demand it // either -- only validate it (below) when a token does have one. validation.required_spec_claims.clear(); validation.validate_exp = true; validation.validate_nbf = true; validation.set_issuer(&[auth_server_url]); let mut last_error = "No signing key matched this token.".to_string(); for key in &keys { match decode::(token, key, &validation) { Ok(data) => return Ok(data.claims), Err(e) => last_error = e.to_string(), } } Err(last_error) } /// Above this, a cached JWKS/authorization answer is refetched rather /// than reused. const JWKS_TTL: Duration = Duration::from_secs(3600); const AUTHORISATION_TTL: Duration = Duration::from_secs(60); #[derive(Deserialize)] struct JwksDocument { jwks: Vec, } #[derive(Deserialize)] struct Jwk { n: String, e: String, } /// The shared, periodically-refreshed JWKS cache, keyed by /// auth_server_url (in practice there is only ever one configured, /// but tests exercise more than one gn-auth instance). type JwksCache = Mutex)>>; fn jwks(auth_server_url: &str) -> Result, String> { static CACHE: OnceLock = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); let mut guard = cache.lock().unwrap(); if let Some((fetched_at, keys)) = guard.get(auth_server_url) { if fetched_at.elapsed() < JWKS_TTL { return Ok(keys.clone()); } } let keys = fetch_jwks(auth_server_url)?; guard.insert(auth_server_url.to_string(), (Instant::now(), keys.clone())); Ok(keys) } fn fetch_jwks(auth_server_url: &str) -> Result, String> { let url = format!("{}/auth/public-jwks", auth_server_url.trim_end_matches('/')); let doc: JwksDocument = ureq::get(&url) .call() .map_err(|e| format!("fetching {url}: {e}"))? .body_mut() .read_json() .map_err(|e| format!("parsing JWKS from {url}: {e}"))?; doc.jwks .iter() .map(|jwk| { DecodingKey::from_rsa_components(&jwk.n, &jwk.e) .map_err(|e| format!("invalid JWK: {e}")) }) .collect() } /// A dataset older than this is treated as publicly readable /// regardless of its `public`/`confidentiality` flags. const PUBLIC_AFTER_YEARS: i64 = 5; /// Matches GeneNetwork2's own threshold for whether a dataset is /// readable without authorization (e.g. `ProbeSetFreeze.public > 0 AND /// ProbeSetFreeze.confidentiality < 1`, used throughout /// `wqflask/api/router.py`). `InbredSet`/group rows carry a `public` /// column too, but GeneNetwork2 never actually filters on it -- it's /// informational only there -- so this only applies to dataset-level /// (`*Freeze`) rows, which carry both columns. /// /// Additionally, a dataset older than `PUBLIC_AFTER_YEARS` is treated /// as public regardless of those flags -- confidentiality embargoes /// are not meant to last forever. `create_time` is the dataset's /// `CreateTime` column, as `YYYY-MM-DD ...`; if it can't be parsed, /// this falls back to the flags alone. pub fn is_publicly_readable(public: u8, confidentiality: u8, create_time: &str) -> bool { (public > 0 && confidentiality < 1) || is_older_than_public_after_years(create_time) } fn is_older_than_public_after_years(create_time: &str) -> bool { let Some((year, month, day)) = parse_date_prefix(create_time) else { return false; }; let created_days = days_from_civil(year, month, day); let now_days = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) { Ok(since_epoch) => (since_epoch.as_secs() / 86400) as i64, Err(_) => return false, }; now_days - created_days >= PUBLIC_AFTER_YEARS * 365 } /// Parse the `YYYY-MM-DD` prefix of a `CreateTime` value such as /// `"2015-03-04 00:00:00"`. fn parse_date_prefix(s: &str) -> Option<(i64, i64, i64)> { let mut parts = s.get(0..10)?.split('-'); let year: i64 = parts.next()?.parse().ok()?; let month: i64 = parts.next()?.parse().ok()?; let day: i64 = parts.next()?.parse().ok()?; Some((year, month, day)) } /// Days since the Unix epoch (1970-01-01) for a date in the proleptic /// Gregorian calendar. Howard Hinnant's `days_from_civil` /// (https://howardhinnant.github.io/date_algorithms.html) -- used here /// instead of a date/time crate since this is the only place a date /// needs parsing. fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { let y = if m <= 2 { y - 1 } else { y }; let era = if y >= 0 { y } else { y - 399 } / 400; let yoe = y - era * 400; let mp = (m + 9) % 12; let doy = (153 * mp + 2) / 5 + d - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146097 + doe - 719468 } /// Proof that this request's data was cleared to go out: either it /// was already [`is_publicly_readable`], or gn-auth's resource- /// authorization round trip (`authorise_trait`/`authorise_dataset`, /// via [`check`]) said so. The field is private, so only this module /// can construct one -- a handler elsewhere can bind or match it /// (e.g. by having its `Found` variant carry `Authorized` alongside /// the data) but never fabricate one, which is what makes it an /// actual guarantee rather than a type-shaped comment. See /// `gnauth_macros::gnauth`, which checks at compile time that any /// handler tagged `#[gnauth(secured)]` actually mentions this type. #[derive(Debug, Clone, Copy)] pub struct Authorized(()); /// Check whether `token`'s holder may view data gated by /// `dataset_name`'s own public/confidentiality/create_time -- either /// because it's [`is_publicly_readable`], or because gn-auth's /// resource-authorization round trip says so (per-trait when /// `trait_name` is `Some`, dataset-wide when `None`, e.g. for a /// listing). Returns the [`Authorized`] capability on success, so /// callers can't construct a "found and visible" result without one. /// /// This is the one place [`is_publicly_readable`] and /// `authorise_trait`/`authorise_dataset` are combined; every gated /// handler (src/routes/traits.rs, src/routes/datasets.rs, /// src/routes/groups.rs) calls this instead of writing that branch /// out itself. pub fn check( auth_server_url: &str, token: &AuthToken, dataset_name: &str, trait_name: Option<&str>, public: u8, confidentiality: u8, create_time: &str, ) -> Result, String> { if is_publicly_readable(public, confidentiality, create_time) { return Ok(Some(Authorized(()))); } let authorised = match trait_name { Some(trait_name) => { authorise_trait(auth_server_url, token, dataset_name, trait_name, VIEW_RESOURCE_PRIVILEGE)? } None => authorise_dataset(auth_server_url, token, dataset_name, VIEW_RESOURCE_PRIVILEGE)?, }; Ok(authorised.then_some(Authorized(()))) } /// Boolean form of [`check`], for callers that filter a list of /// resources rather than reject a single request with 403 (e.g. /// publication_traits, which drops traits the caller may not view /// instead of failing the whole request). pub fn is_authorised( auth_server_url: &str, token: &AuthToken, dataset_name: &str, trait_name: Option<&str>, public: u8, confidentiality: u8, create_time: &str, ) -> Result { Ok(check(auth_server_url, token, dataset_name, trait_name, public, confidentiality, create_time)?.is_some()) } #[derive(Serialize)] struct AuthorisationRequest<'a> { #[serde(rename = "resource-ids")] resource_ids: [&'a str; 1], } #[derive(Deserialize)] struct ResourceAuthorisation { #[serde(default)] roles: Vec, } #[derive(Deserialize)] struct Role { privileges: Vec, } #[derive(Deserialize)] struct Privilege { privilege_id: String, } /// Ask gn-auth whether `token`'s holder has `privilege` on /// `resource_id` (`POST /auth/resource/authorisation`; see /// docs/gn-auth.md). Cached per (sub, resource_id) for /// `AUTHORISATION_TTL`, so repeated requests for the same resource by /// the same user don't each cost a round trip to gn-auth -- the /// fine-grained caching discussed before building this. /// /// Only call this for data that is *not* [`is_publicly_readable`]; /// public data needs a valid token (use [`AuthToken`] alone) but no /// per-resource check. pub fn authorise( auth_server_url: &str, token: &AuthToken, resource_id: &str, privilege: &str, ) -> Result { let privileges = resource_privileges(auth_server_url, token, resource_id)?; Ok(privileges.iter().any(|p| p == privilege)) } /// Privileges are cached per (subject, resource), refreshed after /// PRIV_TTL; the map type is shared by the resource- and trait-level /// privilege lookups. type PrivilegesCache = Mutex)>>; fn resource_privileges( auth_server_url: &str, token: &AuthToken, resource_id: &str, ) -> Result, String> { static CACHE: OnceLock = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); let key = (token.sub.clone(), resource_id.to_string()); { let guard = cache.lock().unwrap(); if let Some((fetched_at, privileges)) = guard.get(&key) { if fetched_at.elapsed() < AUTHORISATION_TTL { return Ok(privileges.clone()); } } } let privileges = fetch_resource_privileges(auth_server_url, token, resource_id)?; cache .lock() .unwrap() .insert(key, (Instant::now(), privileges.clone())); Ok(privileges) } fn fetch_resource_privileges( auth_server_url: &str, token: &AuthToken, resource_id: &str, ) -> Result, String> { let url = format!( "{}/auth/resource/authorisation", auth_server_url.trim_end_matches('/') ); let body = AuthorisationRequest { resource_ids: [resource_id], }; // Not .send_json(): it sets "Content-Type: application/json; // charset=utf-8", but gn-auth's request_json() (gn_auth/auth/ // requests.py) compares Content-Type for exact equality with // "application/json" and silently falls back to query/form // params (empty here) on anything else, turning this into a 400 // instead of the JSON body ever being read. let json = serde_json::to_vec(&body).map_err(|e| format!("encoding request body: {e}"))?; let mut response: HashMap = ureq::post(&url) .header("Authorization", &format!("Bearer {}", token.raw)) .content_type("application/json") .send(json.as_slice()) .map_err(|e| format!("calling {url}: {e}"))? .body_mut() .read_json() .map_err(|e| format!("parsing authorisation response from {url}: {e}"))?; Ok(response .remove(resource_id) .map(|r| { r.roles .into_iter() .flat_map(|role| role.privileges.into_iter().map(|p| p.privilege_id)) .collect() }) .unwrap_or_default()) } #[derive(Serialize)] struct DataAuthorisationRequest<'a> { traits: [&'a str; 1], } #[derive(Deserialize)] struct DataAuthorisationResponse { #[serde(default)] authorisation: Vec, } #[derive(Deserialize)] struct TraitAuthorisation { #[serde(default)] privileges: Vec, } /// Ask gn-auth whether `token`'s holder has `privilege` on the trait /// `dataset_name::trait_name` (`POST /auth/data/authorisation`; see /// docs/gn-auth.md). This is the dataset/trait-keyed equivalent of /// [`authorise`], for data addressed by a `(dataset, probeset)` pair /// rather than a gn-auth resource id directly -- gn-auth resolves the /// resource itself from the trait's dataset name. Cached per (sub, /// dataset::trait) for `AUTHORISATION_TTL`, same as [`authorise`]. /// /// Only call this for data that is *not* [`is_publicly_readable`]; /// public data needs a valid token (use [`AuthToken`] alone) but no /// per-resource check. pub fn authorise_trait( auth_server_url: &str, token: &AuthToken, dataset_name: &str, trait_name: &str, privilege: &str, ) -> Result { let privileges = trait_privileges(auth_server_url, token, dataset_name, trait_name)?; Ok(privileges.iter().any(|p| p == privilege)) } /// Ask gn-auth whether `token`'s holder has `privilege` on /// `dataset_name` as a whole -- for listing every trait in a dataset, /// where there's no single trait to name. gn-auth resolves a trait's /// resource purely from its dataset name (see docs/gn-auth.md); the /// trait half of a `"Dataset::Trait"` string never affects which /// resource, and so which privileges, come back -- this just omits it. pub fn authorise_dataset( auth_server_url: &str, token: &AuthToken, dataset_name: &str, privilege: &str, ) -> Result { authorise_trait(auth_server_url, token, dataset_name, "", privilege) } fn trait_privileges( auth_server_url: &str, token: &AuthToken, dataset_name: &str, trait_name: &str, ) -> Result, String> { static CACHE: OnceLock = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); let key = (token.sub.clone(), format!("{dataset_name}::{trait_name}")); { let guard = cache.lock().unwrap(); if let Some((fetched_at, privileges)) = guard.get(&key) { if fetched_at.elapsed() < AUTHORISATION_TTL { return Ok(privileges.clone()); } } } let privileges = fetch_trait_privileges(auth_server_url, token, dataset_name, trait_name)?; cache .lock() .unwrap() .insert(key, (Instant::now(), privileges.clone())); Ok(privileges) } fn fetch_trait_privileges( auth_server_url: &str, token: &AuthToken, dataset_name: &str, trait_name: &str, ) -> Result, String> { let url = format!( "{}/auth/data/authorisation", auth_server_url.trim_end_matches('/') ); let trait_fullname = format!("{dataset_name}::{trait_name}"); let body = DataAuthorisationRequest { traits: [&trait_fullname], }; // See fetch_resource_privileges for why this isn't .send_json(). let json = serde_json::to_vec(&body).map_err(|e| format!("encoding request body: {e}"))?; let sent = ureq::post(&url) .header("Authorization", &format!("Bearer {}", token.raw)) .content_type("application/json") .send(json.as_slice()); let mut response = match sent { Ok(response) => response, // gn-auth answers a trait with no linked resource (i.e. one // nobody has ever restricted) with a 404, not an empty // privilege list -- treat it the same as "no privileges" here // rather than as a request failure. Err(ureq::Error::StatusCode(404)) => return Ok(Vec::new()), Err(e) => return Err(format!("calling {url}: {e}")), }; let doc: DataAuthorisationResponse = response .body_mut() .read_json() .map_err(|e| format!("parsing authorisation response from {url}: {e}"))?; Ok(doc .authorisation .into_iter() .flat_map(|t| t.privileges) .collect()) } #[cfg(test)] mod tests { use super::*; #[test] fn is_publicly_readable_matches_genenetwork2_threshold() { let recent = "2024-01-01 00:00:00"; assert!(is_publicly_readable(1, 0, recent)); assert!(is_publicly_readable(2, 0, recent)); assert!(!is_publicly_readable(0, 0, recent)); assert!(!is_publicly_readable(1, 1, recent)); } #[test] fn is_publicly_readable_also_true_past_the_embargo_age() { assert!(is_publicly_readable(0, 1, "2000-01-01 00:00:00")); assert!(!is_publicly_readable(0, 1, "2024-01-01 00:00:00")); // Unparseable create_time: fall back to the flags alone. assert!(!is_publicly_readable(0, 1, "not-a-date")); } #[test] fn days_from_civil_matches_known_dates() { assert_eq!(days_from_civil(1970, 1, 1), 0); assert_eq!(days_from_civil(2000, 3, 1), 11017); assert_eq!(days_from_civil(1969, 12, 31), -1); } }