about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-10-04 15:00:58 +0200
committerPjotr Prins <pjotr.public01@thebird.nl>2026-10-04 15:00:58 +0200
commitdfbf105652140d52e50a96853f0a7ab91fec0776 (patch)
treee31e62d0d891dce85be8a09d5094d9d8f06cf7e0 /src
parentabb1fe51b1e8cf4079c462b3657e21376d389b99 (diff)
parent859a86bf39df6eafa6988215cb84556fc9623ea0 (diff)
downloadgenenetwork4-dfbf105652140d52e50a96853f0a7ab91fec0776.tar.gz
Merge branch 'gn-auth'
Diffstat (limited to 'src')
-rw-r--r--src/auth.rs468
-rw-r--r--src/config.rs20
-rw-r--r--src/error.rs2
-rw-r--r--src/lib.rs25
-rw-r--r--src/routes/datasets.rs106
5 files changed, 600 insertions, 21 deletions
diff --git a/src/auth.rs b/src/auth.rs
new file mode 100644
index 0000000..d9cc8c4
--- /dev/null
+++ b/src/auth.rs
@@ -0,0 +1,468 @@
+//! 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<String>) -> 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<S: Send + Sync> FromRequestParts<S> for AuthToken {
+    type Rejection = ApiError;
+
+    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
+        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<Claims, String> {
+    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::<Claims>(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<Jwk>,
+}
+
+#[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<Vec<DecodingKey>, String> {
+    static CACHE: OnceLock<Mutex<HashMap<String, (Instant, Vec<DecodingKey>)>>> = 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<Vec<DecodingKey>, 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
+}
+
+#[derive(Serialize)]
+struct AuthorisationRequest<'a> {
+    #[serde(rename = "resource-ids")]
+    resource_ids: [&'a str; 1],
+}
+
+#[derive(Deserialize)]
+struct ResourceAuthorisation {
+    #[serde(default)]
+    roles: Vec<Role>,
+}
+
+#[derive(Deserialize)]
+struct Role {
+    privileges: Vec<Privilege>,
+}
+
+#[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<bool, String> {
+    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<Vec<String>, String> {
+    static CACHE: OnceLock<Mutex<HashMap<(String, String), (Instant, Vec<String>)>>> =
+        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<Vec<String>, 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<String, ResourceAuthorisation> = 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<TraitAuthorisation>,
+}
+
+#[derive(Deserialize)]
+struct TraitAuthorisation {
+    #[serde(default)]
+    privileges: Vec<String>,
+}
+
+/// 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<bool, String> {
+    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<Vec<String>, String> {
+    static CACHE: OnceLock<Mutex<HashMap<(String, String), (Instant, Vec<String>)>>> =
+        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<Vec<String>, 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);
+    }
+}
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..4013797 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;
@@ -20,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<T> {
     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<mysql::Error> for DatasetAuthError {
+    fn from(e: mysql::Error) -> Self {
+        DatasetAuthError::Db(e)
+    }
+}
+
 fn get_dataset_probeset_info_result(
     dataset: &str,
     probeset: &str,
-) -> Result<DatasetProbesetLookup<db::ProbeSetInfo>, 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<DatasetProbesetInfoLookup, DatasetAuthError> {
+    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<RequestId>,
     Path((dataset, probeset)): Path<(String, String)>,
+    token: AuthToken,
 ) -> Result<Json<db::ProbeSetInfo>, 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",