From 6a5f9ef61d19b2a1a3204df223e2ffb21691a988 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 4 Oct 2026 09:20:33 +0000 Subject: Add token verification and gn-auth resource authorization. * Cargo.toml (jsonwebtoken, ureq): New dependencies, RS256 JWT verification and gn-auth's HTTP API respectively. ureq pulls in ring for RSA verification, needing a C compiler at build time -- already provided by cargo-build-system's standard inputs, nothing added to guix.scm for it. Promote serde_json from dev-dependencies to dependencies; src/auth.rs needs it outside tests now. (mysql-common-derive, simple_asn1, time): Pin to the newest versions still compatible with the Guix-packaged rustc 1.85.1 (same trap as before: ureq's dependency chain pulls darling 0.23/time 0.3.46+, both needing rustc 1.88). * rust-package.scm: Regenerate with `guix import crate -f Cargo.lock genenetwork4`. * guix.scm (genenetwork4-git)[native-inputs]: Update crate list to match. * src/auth.rs (AuthToken): New extractor. Verifies a bearer token's RS256 signature and standard time claims (exp/nbf, checked only when present -- gn-auth's own validator treats them as optional too) against gn-auth's JWKS, cached and refreshed periodically (OnceLock>>, same shape as db::pool()) rather than fetched per request. (is_publicly_readable): New function. Matches GeneNetwork2's own threshold (public > 0 AND confidentiality < 1, used throughout wqflask/api/router.py) for whether a dataset needs an authorization check at all; InbredSet/group rows carry a public column too, but GN2 never filters on it, so groups/species endpoints need no gating. (authorise): New function. Wraps gn-auth's POST /auth/resource/authorisation, caching the per-(user, resource) answer briefly (AUTHORISATION_TTL) so repeated requests for the same resource by the same user don't each cost a round trip. Not yet called from any route -- see RELEASE_NOTES.md. * src/config.rs (Config)[auth_server_url]: New field, AUTH_SERVER_URL config key, matching GeneNetwork3's own key of the same name. * src/error.rs (ApiError): Derive Debug; needed by tests/auth.rs's .unwrap() on a Result<_, ApiError>, and every error type should implement it regardless. * src/lib.rs: Register the new auth module. * tests/auth.rs: New file. Runs AuthToken verification and authorise() (including its cache) against a real gn-auth instance; set GN4_TEST_AUTH_TOKEN/GN4_TEST_RESOURCE_ID (see docs/gn-auth.md), skips otherwise. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d --- src/auth.rs | 298 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 20 +++- src/error.rs | 2 +- src/lib.rs | 1 + 4 files changed, 318 insertions(+), 3 deletions(-) create mode 100644 src/auth.rs (limited to 'src') diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..ccbefe4 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,298 @@ +//! 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::StatusCode; +use axum::http::request::Parts; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; +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; + +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 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). +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() +} + +/// 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. +pub fn is_publicly_readable(public: u8, confidentiality: u8) -> bool { + public > 0 && confidentiality < 1 +} + +#[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)) +} + +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()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_publicly_readable_matches_genenetwork2_threshold() { + assert!(is_publicly_readable(1, 0)); + assert!(is_publicly_readable(2, 0)); + assert!(!is_publicly_readable(0, 0)); + assert!(!is_publicly_readable(1, 1)); + } +} diff --git a/src/config.rs b/src/config.rs index 75adaf2..c403083 100644 --- a/src/config.rs +++ b/src/config.rs @@ -19,6 +19,10 @@ pub struct Config { pub sql_uri: String, /// TCP port to bind. pub port: u16, + /// Base URL of the gn-auth server, e.g. "http://127.0.0.1:8081/". + /// Same AUTH_SERVER_URL config key GeneNetwork3 uses. See + /// docs/gn-auth.md. + pub auth_server_url: String, } impl Config { @@ -32,6 +36,10 @@ impl Config { "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl".to_string(), ); values.insert("GENENETWORK4_PORT".to_string(), "3000".to_string()); + values.insert( + "AUTH_SERVER_URL".to_string(), + "http://127.0.0.1:8081/".to_string(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -43,7 +51,7 @@ impl Config { } // Layer 4: environment wins over everything. - for key in ["SQL_URI", "GENENETWORK4_PORT"] { + for key in ["SQL_URI", "GENENETWORK4_PORT", "AUTH_SERVER_URL"] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); } @@ -54,6 +62,7 @@ impl Config { port: values["GENENETWORK4_PORT"] .parse() .expect("GENENETWORK4_PORT must be a number"), + auth_server_url: values["AUTH_SERVER_URL"].clone(), } } } @@ -87,7 +96,13 @@ mod tests { /// knobs this test asserts on. #[test] fn defaults_apply_with_no_files_or_env() { - for key in ["SQL_URI", "GN4_CONF", "GN4_SECRETS", "GENENETWORK4_PORT"] { + for key in [ + "SQL_URI", + "GN4_CONF", + "GN4_SECRETS", + "GENENETWORK4_PORT", + "AUTH_SERVER_URL", + ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); return; @@ -96,6 +111,7 @@ mod tests { let config = Config::load(); assert!(config.sql_uri.contains("db_webqtl")); assert_eq!(config.port, 3000); + assert_eq!(config.auth_server_url, "http://127.0.0.1:8081/"); } #[test] diff --git a/src/error.rs b/src/error.rs index 49e1574..f96f44b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -14,7 +14,7 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; -#[derive(Serialize, utoipa::ToSchema)] +#[derive(Debug, Serialize, utoipa::ToSchema)] pub struct ApiError { pub r#type: String, pub title: String, diff --git a/src/lib.rs b/src/lib.rs index 6b1d3a6..8377643 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ use utoipa::OpenApi; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +pub mod auth; pub mod config; mod db; mod error; -- cgit 1.4.1 From 859a86bf39df6eafa6988215cb84556fc9623ea0 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 4 Oct 2026 11:37:55 +0000 Subject: Gate GET /datasets/{dataset}/probesets/{probeset} on gn-auth Require a valid gn-auth bearer token on this endpoint unconditionally. For a dataset that isn't publicly readable, check the group:resource:view-resource privilege via a new auth::authorise_trait, the "Dataset::Trait"-keyed equivalent of authorise (POST /auth/data/authorisation instead of /auth/resource/authorisation) -- gn-auth resolves the resource itself from the dataset name, so no separate resource-id lookup is needed here. A trait never linked to a gn-auth resource (gn-auth answers 404) is treated as "no privileges", not a request failure. Denied requests get a 403; a failure to reach/parse gn-auth's answer gets a 502, distinct from both that and this service's own 500s. is_publicly_readable now also takes the dataset's CreateTime and treats anything older than 5 years as public regardless of its public/confidentiality flags -- a confidentiality embargo isn't meant to last forever. No admin/sysadmin bypass is implemented. Register a "bearer_token" OpenAPI security scheme (src/lib.rs) so the new security(...) annotation on this endpoint's #[utoipa::path] has something to point at. tests/dataset_probeset_info.rs and its Python mirror gain cases for the missing-token (401) and denied-but-existing (403) outcomes, run against a real gn-auth instance set up as described in docs/gn-auth.md; the 403 case uses UTHSC_BXD_Cochlea_0225, a real non-public, non-embargoed dataset never linked into gn-auth. tests/common gains get_with_token and auth_server_available/auth_token helpers for this. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d --- RELEASE_NOTES.md | 17 ++- docs/gn-auth.md | 53 ++++++++- src/auth.rs | 182 +++++++++++++++++++++++++++++- src/lib.rs | 24 +++- src/routes/datasets.rs | 106 ++++++++++++++--- test/python/test_dataset_probeset_info.py | 88 +++++++++++---- tests/auth.rs | 5 +- tests/common/mod.rs | 49 ++++++-- tests/dataset_probeset_info.rs | 111 ++++++++++++++++-- 9 files changed, 566 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 2861f16..ca1eef7 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -26,12 +26,23 @@ gn-auth. Not all endpoints will require a token -- see - `jsonwebtoken` (RS256 verification) and `ureq` (gn-auth's HTTP API) as new dependencies; `AUTH_SERVER_URL` as a new `Config` key, matching GeneNetwork3's own config key of the same name. +- `is_publicly_readable` also treats a dataset older than 5 years as + public, regardless of its `public`/`confidentiality` flags. +- `auth::authorise_trait`, wrapping `POST /auth/data/authorisation` + (the `"Dataset::Trait"`-keyed equivalent of `authorise`), for data + addressed by a `(dataset, probeset)` pair rather than a resource id. +- `GET /datasets/{dataset}/probesets/{probeset}` now requires a valid + token unconditionally, and -- for a dataset that isn't publicly + readable -- checks `group:resource:view-resource` via + `authorise_trait`, returning 403 (not 404) when denied and 502 if + gn-auth itself couldn't be reached. See docs/gn-auth.md. ### Not yet done -- Deciding which existing endpoints should require a token at all, and - which gn-auth privilege each should check -- `src/auth.rs` is built - and tested end-to-end, but not yet wired into any route. +- Deciding which other endpoints should require a token, and which + gn-auth privilege each should check -- only + `dataset_probeset_info` is wired so far; its sibling + `dataset_probeset_values` is not. ### Found and fixed upstream, in gn-auth diff --git a/docs/gn-auth.md b/docs/gn-auth.md index 27bcd88..c33dc54 100644 --- a/docs/gn-auth.md +++ b/docs/gn-auth.md @@ -201,6 +201,27 @@ by this test, still require a valid token (don't skip verification entirely), but skip the resource-authorization call to gn-auth -- one less network round trip for what is, in practice, most of the data. +A dataset older than 5 years is treated as public too, regardless of +its `public`/`confidentiality` flags -- a confidentiality embargo isn't +meant to last forever. This isn't a GN2 convention, just a rule applied +here, based on `CreateTime`. + +### Resolving a probeset/trait to a gn-auth resource + +A group/`InbredSet` resource's id is resolved via +`GET /auth/resource/populations/resource-id//` +(above). A probeset/trait doesn't have an equivalent "resolve this id +to a resource id" endpoint -- instead, call +`POST /auth/data/authorisation` directly with a `"Dataset::Trait"` +string (e.g. `{"traits": ["HC_M2_0606_P::1442370_at"]}`); gn-auth +resolves the resource itself, internally, via a join on +`linked_mrna_data.dataset_name` (`gn_auth/auth/authorisation/data/ +mrna.py`'s `resources_by_datasets_and_traits`). If the trait's dataset +was never linked to a gn-auth resource at all (the common case for +data nobody has ever restricted), gn-auth answers with a 404, which +genenetwork4 treats the same as "no privileges" -- not a request +failure. + ### Implemented, in `src/auth.rs` - `AuthToken`, an Axum extractor (`impl FromRequestParts`): verifies a @@ -209,20 +230,42 @@ less network round trip for what is, in practice, most of the data. confirmed against its own validator) against a cached, periodically refreshed JWKS. Add it as a handler parameter to require a valid token; omit it for endpoints that don't need one. -- `is_publicly_readable(public, confidentiality)`: the GN2 threshold - above, as a plain function a handler calls on its own fetched row. +- `is_publicly_readable(public, confidentiality, create_time)`: the GN2 + threshold above, plus the 5-year embargo-age rule, as a plain + function a handler calls on its own fetched row. - `authorise(auth_server_url, token, resource_id, privilege)`: the two gn-auth calls (resource-id resolution is the caller's job -- `GET /auth/resource/populations/resource-id/...` -- `authorise` itself only wraps `POST /auth/resource/authorisation`), with the per-(user, resource) answer cached briefly so repeated requests for the same resource by the same user don't each cost a round trip. +- `authorise_trait(auth_server_url, token, dataset_name, trait_name, + privilege)`: the trait-keyed equivalent of `authorise`, wrapping + `POST /auth/data/authorisation` -- for data addressed by a + `(dataset, probeset)` pair rather than a resource id directly. Same + caching as `authorise`. - `tests/auth.rs` runs all of this against a real gn-auth instance (set `GN4_TEST_AUTH_TOKEN`/`GN4_TEST_RESOURCE_ID`; skips otherwise). -Wiring this into specific existing endpoints (which ones should -require a token at all, and which privilege string each should check) -is a separate decision, not yet made here. +### Wired into a route: `GET /datasets/{dataset}/probesets/{probeset}` + +This is the first (and so far only) endpoint gated this way: + +- An `AuthToken` is required unconditionally -- every caller needs a + valid token, even for public data. +- If the dataset is publicly readable (`is_publicly_readable`), the + probeset's metadata is returned with no further gn-auth call. +- Otherwise, `authorise_trait(..., "group:resource:view-resource")` is + called; a `false` result (including the "never linked, so no + privileges" 404 case above) is a 403, not a 404 -- the dataset and + probeset both exist, the caller just isn't allowed to see them. +- A failure to reach/parse gn-auth's answer is a 502, distinct from a + 403 (denied) or a 500 (this service's own database error) -- see + `tests/dataset_probeset_info.rs` for all of these cases exercised + against a real gn-auth instance. + +Which other endpoints should require a token, and which privilege each +should check, remains a separate decision, not yet made here. ### Found wrong in gn-auth while building this diff --git a/src/auth.rs b/src/auth.rs index ccbefe4..d9cc8c4 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -166,6 +166,10 @@ fn fetch_jwks(auth_server_url: &str) -> Result, String> { .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 @@ -173,8 +177,51 @@ fn fetch_jwks(auth_server_url: &str) -> Result, String> { /// 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. -pub fn is_publicly_readable(public: u8, confidentiality: u8) -> bool { - public > 0 && confidentiality < 1 +/// +/// 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 } #[derive(Serialize)] @@ -284,15 +331,138 @@ fn fetch_resource_privileges( .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)) +} + +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() { - assert!(is_publicly_readable(1, 0)); - assert!(is_publicly_readable(2, 0)); - assert!(!is_publicly_readable(0, 0)); - assert!(!is_publicly_readable(1, 1)); + 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); } } diff --git a/src/lib.rs b/src/lib.rs index 8377643..4013797 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,9 +21,31 @@ use error::ApiError; title = "GeneNetwork4 API", description = "GeneNetwork4 REST API", license(name = "AGPL-3.0-or-later") -))] +), modifiers(&SecurityAddon))] struct ApiDoc; +/// Registers the "bearer_token" scheme used by endpoints that require a +/// gn-auth token (see `security(...)` on their `#[utoipa::path]`, e.g. +/// `routes::datasets::dataset_probeset_info`). +struct SecurityAddon; + +impl utoipa::Modify for SecurityAddon { + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { + use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme}; + if let Some(components) = openapi.components.as_mut() { + components.add_security_scheme( + "bearer_token", + SecurityScheme::Http( + HttpBuilder::new() + .scheme(HttpAuthScheme::Bearer) + .bearer_format("JWT") + .build(), + ), + ); + } + } +} + /// Build the application router. Public so integration tests (tests/) and /// the binary (src/main.rs) can both use it without binding a real socket. pub fn app() -> Router { diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs index f1b5671..dd6adc5 100644 --- a/src/routes/datasets.rs +++ b/src/routes/datasets.rs @@ -6,10 +6,15 @@ use axum::extract::{Extension, Path}; use axum::http::StatusCode; use tower_http::request_id::RequestId; +use crate::auth::{self, AuthToken}; +use crate::config::Config; use crate::db; use crate::error::ApiError; use crate::request_id_string; +/// The gn-auth privilege required to view a non-public probeset. +const VIEW_RESOURCE_PRIVILEGE: &str = "group:resource:view-resource"; + #[utoipa::path(get, path = "/datasets/{dataset}", summary = "Get one expression dataset's full record by name or numeric id", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( @@ -66,17 +71,59 @@ enum DatasetProbesetLookup { Found(T), } +/// What looking up and authorizing a probeset trait found. Unlike +/// [`DatasetProbesetLookup`], this also covers the "dataset isn't +/// public and the caller isn't authorized for it" outcome, since +/// `dataset_probeset_info` (unlike `dataset_probeset_values`) gates on +/// gn-auth. +enum DatasetProbesetInfoLookup { + DatasetNotFound, + ProbesetNotFound, + Forbidden, + Found(db::ProbeSetInfo), +} + +/// Either a database error, or a failure to reach/parse gn-auth's +/// answer while checking authorization for a non-public dataset. +enum DatasetAuthError { + Db(mysql::Error), + Auth(String), +} + +impl From for DatasetAuthError { + fn from(e: mysql::Error) -> Self { + DatasetAuthError::Db(e) + } +} + fn get_dataset_probeset_info_result( dataset: &str, probeset: &str, -) -> Result, mysql::Error> { - match db::get_dataset_by_name(dataset)? { - None => Ok(DatasetProbesetLookup::DatasetNotFound), - Some(dataset) => match db::get_dataset_probeset_info(dataset.id, probeset)? { - None => Ok(DatasetProbesetLookup::ProbesetNotFound), - Some(info) => Ok(DatasetProbesetLookup::Found(info)), - }, + auth_server_url: &str, + token: &AuthToken, +) -> Result { + let dataset = match db::get_dataset_by_name(dataset)? { + None => return Ok(DatasetProbesetInfoLookup::DatasetNotFound), + Some(dataset) => dataset, + }; + let info = match db::get_dataset_probeset_info(dataset.id, probeset)? { + None => return Ok(DatasetProbesetInfoLookup::ProbesetNotFound), + Some(info) => info, + }; + if !auth::is_publicly_readable(dataset.public, dataset.confidentiality, &dataset.create_time) { + let authorised = auth::authorise_trait( + auth_server_url, + token, + &dataset.name, + &info.name, + VIEW_RESOURCE_PRIVILEGE, + ) + .map_err(DatasetAuthError::Auth)?; + if !authorised { + return Ok(DatasetProbesetInfoLookup::Forbidden); + } } + Ok(DatasetProbesetInfoLookup::Found(info)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}", summary = "Get one expression trait's ProbeSetXRef/ProbeSet metadata", params( @@ -84,18 +131,24 @@ fn get_dataset_probeset_info_result( ("probeset" = String, Path, description = "ProbeSet.Name within the dataset") ), responses( (status = 200, description = "The probeset's ProbeSetXRef/ProbeSet metadata", body = db::ProbeSetInfo), + (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset, or no matching probeset in that dataset", body = ApiError), - (status = 500, description = "Database error", body = ApiError) -))] + (status = 500, description = "Database error", body = ApiError), + (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) +), security(("bearer_token" = [])))] pub async fn dataset_probeset_info( Extension(request_id): Extension, Path((dataset, probeset)): Path<(String, String)>, + token: AuthToken, ) -> Result, ApiError> { let rid = request_id_string(&request_id); let not_found_dataset = dataset.clone(); let not_found_probeset = probeset.clone(); - tokio::task::spawn_blocking(move || get_dataset_probeset_info_result(&dataset, &probeset)) - .await + let auth_server_url = Config::load().auth_server_url.clone(); + tokio::task::spawn_blocking(move || { + get_dataset_probeset_info_result(&dataset, &probeset, &auth_server_url, &token) + }) + .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, @@ -106,19 +159,38 @@ pub async fn dataset_probeset_info( ) .with_request_id(rid.clone()) })? - .map_err(|e| { - ApiError::new( + .map_err(|e| match e { + DatasetAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "dataset_probeset_info", ) - .with_request_id(rid.clone()) + .with_request_id(rid.clone()), + DatasetAuthError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "dataset_probeset_info", + ) + .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetLookup::Found(info) => Ok(Json(info)), - DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new( + DatasetProbesetInfoLookup::Found(info) => Ok(Json(info)), + DatasetProbesetInfoLookup::Forbidden => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!( + "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \ + and you are not authorized to view it." + ), + "dataset_probeset_info", + ) + .with_request_id(rid.clone())), + DatasetProbesetInfoLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", @@ -126,7 +198,7 @@ pub async fn dataset_probeset_info( "dataset_probeset_info", ) .with_request_id(rid.clone())), - DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new( + DatasetProbesetInfoLookup::ProbesetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "probeset_not_found", "Probeset not found", diff --git a/test/python/test_dataset_probeset_info.py b/test/python/test_dataset_probeset_info.py index cfb219c..569e9f0 100644 --- a/test/python/test_dataset_probeset_info.py +++ b/test/python/test_dataset_probeset_info.py @@ -1,15 +1,22 @@ """Mirrors tests/dataset_probeset_info.rs. Needs a live MariaDB (SQL_URI); skips with a message rather than failing when none is -reachable, same as test_group_by_name.py. +reachable, same as test_group_by_name.py. Also needs a live gn-auth +(AUTH_SERVER_URL) and GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md), since +this endpoint now requires a bearer token; skips when either is +missing. """ import http.client import json +import os import socket import unittest +from urllib.parse import urlparse from server_test_case import HOST, PORT, ServerTestCase +AUTH_SERVER_URL = os.environ.get("AUTH_SERVER_URL", "http://127.0.0.1:8081/") + def database_reachable(): try: @@ -19,18 +26,45 @@ def database_reachable(): return False +def auth_server_reachable(): + url = urlparse(AUTH_SERVER_URL) + conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=2) + try: + conn.request("GET", url.path.rstrip("/") + "/auth/public-jwks") + return conn.getresponse().status == 200 + except OSError: + return False + finally: + conn.close() + + +def auth_token(): + return os.environ.get("GN4_TEST_AUTH_TOKEN") + + class DatasetProbesetInfoTest(ServerTestCase): - def test_dataset_probeset_info_returns_gene_annotation(self): + def require_fixtures(self): if not database_reachable(): self.skipTest("no database on 127.0.0.1:3306") + if not auth_token(): + self.skipTest("set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)") + if not auth_server_reachable(): + self.skipTest(f"no gn-auth reachable at {AUTH_SERVER_URL}") + def get(self, path, with_token=True): conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) try: - conn.request("GET", "/datasets/Br_U_0803_M/probesets/100001_at") + headers = {"Authorization": f"Bearer {auth_token()}"} if with_token else {} + conn.request("GET", path, headers=headers) response = conn.getresponse() - body = response.read() + return response, response.read() finally: conn.close() + + def test_dataset_probeset_info_returns_gene_annotation(self): + self.require_fixtures() + + response, body = self.get("/datasets/Br_U_0803_M/probesets/100001_at") self.assertEqual(response.status, 200) info = json.loads(body) @@ -38,17 +72,19 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(info["symbol"], "Cd3g") self.assertIsInstance(info["mean"], float) - def test_dataset_probeset_info_unknown_dataset_returns_404(self): + def test_dataset_probeset_info_without_a_token_returns_401(self): if not database_reachable(): self.skipTest("no database on 127.0.0.1:3306") - conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) - try: - conn.request("GET", "/datasets/not-a-real-dataset/probesets/100001_at") - response = conn.getresponse() - body = response.read() - finally: - conn.close() + response, _body = self.get( + "/datasets/Br_U_0803_M/probesets/100001_at", with_token=False + ) + self.assertEqual(response.status, 401) + + def test_dataset_probeset_info_unknown_dataset_returns_404(self): + self.require_fixtures() + + response, body = self.get("/datasets/not-a-real-dataset/probesets/100001_at") self.assertEqual(response.status, 404) error = json.loads(body) @@ -57,16 +93,9 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(error["operation_id"], "dataset_probeset_info") def test_dataset_probeset_info_unknown_probeset_in_dataset_returns_404(self): - if not database_reachable(): - self.skipTest("no database on 127.0.0.1:3306") + self.require_fixtures() - conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) - try: - conn.request("GET", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset") - response = conn.getresponse() - body = response.read() - finally: - conn.close() + response, body = self.get("/datasets/Br_U_0803_M/probesets/not-a-real-probeset") self.assertEqual(response.status, 404) error = json.loads(body) @@ -74,6 +103,23 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(error["code"], "probeset_not_found") self.assertEqual(error["operation_id"], "dataset_probeset_info") + def test_dataset_probeset_info_non_public_unlinked_dataset_returns_403(self): + """UTHSC_BXD_Cochlea_0225 (public=1, confidentiality=1, created + 2025-02-13) is neither publicly readable by the flags nor old + enough for the embargo-age rule, and has never been linked to a + gn-auth resource -- so even the token's owner has no privilege + on it. + """ + self.require_fixtures() + + response, body = self.get( + "/datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180" + ) + self.assertEqual(response.status, 403) + + error = json.loads(body) + self.assertEqual(error["code"], "forbidden") + if __name__ == "__main__": unittest.main() diff --git a/tests/auth.rs b/tests/auth.rs index 324c984..85b5cc2 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -33,8 +33,9 @@ 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. - assert!(auth::is_publicly_readable(2, 0)); - assert!(!auth::is_publicly_readable(0, 0)); + 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] diff --git a/tests/common/mod.rs b/tests/common/mod.rs index ad0a50b..84273a5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -19,18 +19,38 @@ pub fn db_available() -> bool { mysql::Conn::new(opts).is_ok() } +/// True only when gn-auth is actually reachable at the configured +/// AUTH_SERVER_URL. Tests that need a live gn-auth skip (rather than +/// fail) when this is false, same reasoning as `db_available`. +pub fn auth_server_available() -> bool { + let config = genenetwork4::config::Config::load(); + ureq::get(format!( + "{}/auth/public-jwks", + config.auth_server_url.trim_end_matches('/') + )) + .call() + .is_ok() +} + +/// A bearer token to use against a live gn-auth instance in tests that +/// need one, e.g. for an endpoint requiring `AuthToken`. Set +/// GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md); tests using this skip +/// rather than fail when it isn't set. +pub fn auth_token() -> Option { + std::env::var("GN4_TEST_AUTH_TOKEN").ok() +} + /// Above this, a request's timing is reported as a warning (see `get`). const SLOW_THRESHOLD: Duration = Duration::from_secs(1); -/// GETs `uri` against genenetwork4::app() and warns on stderr if the -/// response -- which for every endpoint using this helper means its SQL -/// query -- takes longer than SLOW_THRESHOLD. Warnings only show with -/// `cargo test -- --nocapture` (or on a failing test), since cargo -/// captures stdout/stderr for passing tests otherwise. -pub async fn get(label: &str, uri: &str) -> Response { +async fn request(label: &str, uri: &str, bearer_token: Option<&str>) -> Response { let start = Instant::now(); + let mut builder = Request::builder().uri(uri); + if let Some(token) = bearer_token { + builder = builder.header("Authorization", format!("Bearer {token}")); + } let response = genenetwork4::app() - .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .oneshot(builder.body(Body::empty()).unwrap()) .await .unwrap(); let elapsed = start.elapsed(); @@ -39,3 +59,18 @@ pub async fn get(label: &str, uri: &str) -> Response { } response } + +/// GETs `uri` against genenetwork4::app() and warns on stderr if the +/// response -- which for every endpoint using this helper means its SQL +/// query -- takes longer than SLOW_THRESHOLD. Warnings only show with +/// `cargo test -- --nocapture` (or on a failing test), since cargo +/// captures stdout/stderr for passing tests otherwise. +pub async fn get(label: &str, uri: &str) -> Response { + request(label, uri, None).await +} + +/// Like `get`, but with an `Authorization: Bearer ` header, for +/// endpoints that require `AuthToken`. +pub async fn get_with_token(label: &str, uri: &str, token: &str) -> Response { + request(label, uri, Some(token)).await +} diff --git a/tests/dataset_probeset_info.rs b/tests/dataset_probeset_info.rs index eb0224b..b529cec 100644 --- a/tests/dataset_probeset_info.rs +++ b/tests/dataset_probeset_info.rs @@ -4,10 +4,14 @@ use serde_json::Value; mod common; -/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather -/// than fails when none is reachable, same as group_by_name.rs. -/// Probeset 100001_at (gene symbol Cd3g) in dataset Br_U_0803_M is a -/// real row in the database. +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs) and a live +/// gn-auth (AUTH_SERVER_URL) plus GN4_TEST_AUTH_TOKEN (see +/// docs/gn-auth.md); skips rather than fails when either is missing, +/// same as group_by_name.rs. Probeset 100001_at (gene symbol Cd3g) in +/// dataset Br_U_0803_M is a real row in the database; the dataset's +/// CreateTime is 2003-08-01, so it's publicly readable regardless of +/// its public/confidentiality flags (see src/auth.rs) -- a valid token +/// is still required, but no gn-auth authorization call happens. #[tokio::test] async fn dataset_probeset_info_returns_gene_annotation() { if !common::db_available() { @@ -16,10 +20,21 @@ async fn dataset_probeset_info_returns_gene_annotation() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_returns_gene_annotation: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!("skipping dataset_probeset_info_returns_gene_annotation: no gn-auth reachable"); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/Br_U_0803_M/probesets/100001_at", "/datasets/Br_U_0803_M/probesets/100001_at", + &token, ) .await; @@ -33,6 +48,24 @@ async fn dataset_probeset_info_returns_gene_annotation() { assert!(info["mean"].as_f64().is_some()); } +#[tokio::test] +async fn dataset_probeset_info_without_a_token_returns_401() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_without_a_token_returns_401: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/100001_at (no token)", + "/datasets/Br_U_0803_M/probesets/100001_at", + ) + .await; + + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + #[tokio::test] async fn dataset_probeset_info_unknown_dataset_returns_404() { if !common::db_available() { @@ -41,10 +74,21 @@ async fn dataset_probeset_info_unknown_dataset_returns_404() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_unknown_dataset_returns_404: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!("skipping dataset_probeset_info_unknown_dataset_returns_404: no gn-auth reachable"); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/not-a-real-dataset/probesets/100001_at", "/datasets/not-a-real-dataset/probesets/100001_at", + &token, ) .await; @@ -65,10 +109,23 @@ async fn dataset_probeset_info_unknown_probeset_in_dataset_returns_404() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_unknown_probeset_in_dataset_returns_404: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!( + "skipping dataset_probeset_info_unknown_probeset_in_dataset_returns_404: no gn-auth reachable" + ); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/Br_U_0803_M/probesets/not-a-real-probeset", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset", + &token, ) .await; @@ -80,3 +137,43 @@ async fn dataset_probeset_info_unknown_probeset_in_dataset_returns_404() { assert_eq!(error["code"], "probeset_not_found"); assert_eq!(error["operation_id"], "dataset_probeset_info"); } + +/// UTHSC_BXD_Cochlea_0225 (public=1, confidentiality=1, created +/// 2025-02-13) is neither publicly readable by the flags +/// (confidentiality >= 1) nor old enough for the embargo-age rule, and +/// has never been linked to a gn-auth resource -- so even the token's +/// owner has no privilege on it, and the request must be denied rather +/// than silently allowed. +#[tokio::test] +async fn dataset_probeset_info_non_public_unlinked_dataset_returns_403() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: no usable database (check SQL_URI credentials)" + ); + return; + } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: no gn-auth reachable" + ); + return; + } + + let response = common::get_with_token( + "GET /datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180", + "/datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180", + &token, + ) + .await; + + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(error["code"], "forbidden"); +} -- cgit 1.4.1