about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-10-04 09:20:33 +0000
committerPjotr <wrk@bosa.lan>2026-10-04 09:20:33 +0000
commit6a5f9ef61d19b2a1a3204df223e2ffb21691a988 (patch)
treebad1d720158075b73425a04d77762bf509e6ab7a /src
parent7ff37201f5bfe97c07305dd0f07c5c18c63d9edf (diff)
downloadgenenetwork4-6a5f9ef61d19b2a1a3204df223e2ffb21691a988.tar.gz
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<Mutex<HashMap<...>>>, 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'src')
-rw-r--r--src/auth.rs298
-rw-r--r--src/config.rs20
-rw-r--r--src/error.rs2
-rw-r--r--src/lib.rs1
4 files changed, 318 insertions, 3 deletions
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<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()
+}
+
+/// 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<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())
+}
+
+#[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;