about summary refs log tree commit diff
path: root/src/auth.rs
blob: d1a86c66ef6dda3d257886db6fd6799315b6b09a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Verifying bearer tokens issued by gn-auth, and checking gn-auth
//! resource authorization for data that isn't public. See
//! docs/gn-auth.md for the mechanism this implements.
//!
//! Two independent things happen here, and most endpoints only need
//! the first:
//!
//! - **Token verification** ([`AuthToken`], an extractor): checks a
//!   bearer token's RS256 signature and standard time claims against
//!   gn-auth's JWKS (`GET /auth/public-jwks`), cached and refreshed
//!   periodically rather than fetched per request. Add `AuthToken` as
//!   a handler parameter to require a valid token; handlers that
//!   don't need one simply omit it -- this is what makes auth
//!   opt-in per route rather than a blanket gate.
//! - **Resource authorization** ([`authorise`]): for data that isn't
//!   public (see [`is_publicly_readable`], matching GeneNetwork2's own
//!   `public > 0 AND confidentiality < 1` convention), asks gn-auth
//!   whether this token's holder has a given privilege on a specific
//!   resource (`POST /auth/resource/authorisation`), caching the
//!   per-(user, resource) answer briefly so repeated requests for the
//!   same resource don't each cost a round trip to gn-auth.

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::StatusCode;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::config::Config;
use crate::error::ApiError;
use crate::response::RequestInfo;

/// The gn-auth privilege that means "can view this resource" -- the
/// one every gated route in this API checks so far (see
/// src/routes/datasets.rs, src/routes/traits.rs).
pub const VIEW_RESOURCE_PRIVILEGE: &str = "group:resource:view-resource";

fn unauthorized(detail: impl Into<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 request = RequestInfo::from_parts(parts);
        let unauthorized = |detail: &str| unauthorized(detail).with_request_id(request.clone());
        let header = parts
            .headers
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok())
            .ok_or_else(|| unauthorized("Missing Authorization header."))?;
        let token = header
            .strip_prefix("Bearer ")
            .ok_or_else(|| unauthorized("Authorization header must be a Bearer token."))?;

        let config = Config::load();
        let claims =
            verify(token, &config.auth_server_url).map_err(|e| unauthorized(&e.to_string()))?;
        Ok(AuthToken {
            sub: claims.sub,
            scope: claims.scope,
            raw: token.to_string(),
        })
    }
}

/// Verify `token`'s signature and standard time claims against
/// `auth_server_url`'s JWKS.
fn verify(token: &str, auth_server_url: &str) -> Result<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).
type JwksCache = Mutex<HashMap<String, (Instant, Vec<DecodingKey>)>>;

fn jwks(auth_server_url: &str) -> Result<Vec<DecodingKey>, String> {
    static CACHE: OnceLock<JwksCache> = 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
}

/// Proof that this request's data was cleared to go out: either it
/// was already [`is_publicly_readable`], or gn-auth's resource-
/// authorization round trip (`authorise_trait`/`authorise_dataset`,
/// via [`check`]) said so. The field is private, so only this module
/// can construct one -- a handler elsewhere can bind or match it
/// (e.g. by having its `Found` variant carry `Authorized` alongside
/// the data) but never fabricate one, which is what makes it an
/// actual guarantee rather than a type-shaped comment. See
/// `gnauth_macros::gnauth`, which checks at compile time that any
/// handler tagged `#[gnauth(secured)]` actually mentions this type.
#[derive(Debug, Clone, Copy)]
pub struct Authorized(());

/// Check whether `token`'s holder may view data gated by
/// `dataset_name`'s own public/confidentiality/create_time -- either
/// because it's [`is_publicly_readable`], or because gn-auth's
/// resource-authorization round trip says so (per-trait when
/// `trait_name` is `Some`, dataset-wide when `None`, e.g. for a
/// listing). Returns the [`Authorized`] capability on success, so
/// callers can't construct a "found and visible" result without one.
///
/// This is the one place [`is_publicly_readable`] and
/// `authorise_trait`/`authorise_dataset` are combined; every gated
/// handler (src/routes/traits.rs, src/routes/datasets.rs,
/// src/routes/groups.rs) calls this instead of writing that branch
/// out itself.
pub fn check(
    auth_server_url: &str,
    token: &AuthToken,
    dataset_name: &str,
    trait_name: Option<&str>,
    public: u8,
    confidentiality: u8,
    create_time: &str,
) -> Result<Option<Authorized>, String> {
    if is_publicly_readable(public, confidentiality, create_time) {
        return Ok(Some(Authorized(())));
    }
    let authorised = match trait_name {
        Some(trait_name) => {
            authorise_trait(auth_server_url, token, dataset_name, trait_name, VIEW_RESOURCE_PRIVILEGE)?
        }
        None => authorise_dataset(auth_server_url, token, dataset_name, VIEW_RESOURCE_PRIVILEGE)?,
    };
    Ok(authorised.then_some(Authorized(())))
}

/// Boolean form of [`check`], for callers that filter a list of
/// resources rather than reject a single request with 403 (e.g.
/// publication_traits, which drops traits the caller may not view
/// instead of failing the whole request).
pub fn is_authorised(
    auth_server_url: &str,
    token: &AuthToken,
    dataset_name: &str,
    trait_name: Option<&str>,
    public: u8,
    confidentiality: u8,
    create_time: &str,
) -> Result<bool, String> {
    Ok(check(auth_server_url, token, dataset_name, trait_name, public, confidentiality, create_time)?.is_some())
}

#[derive(Serialize)]
struct AuthorisationRequest<'a> {
    #[serde(rename = "resource-ids")]
    resource_ids: [&'a str; 1],
}

#[derive(Deserialize)]
struct ResourceAuthorisation {
    #[serde(default)]
    roles: Vec<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))
}

/// Privileges are cached per (subject, resource), refreshed after
/// PRIV_TTL; the map type is shared by the resource- and trait-level
/// privilege lookups.
type PrivilegesCache = Mutex<HashMap<(String, String), (Instant, Vec<String>)>>;

fn resource_privileges(
    auth_server_url: &str,
    token: &AuthToken,
    resource_id: &str,
) -> Result<Vec<String>, String> {
    static CACHE: OnceLock<PrivilegesCache> = 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))
}

/// Ask gn-auth whether `token`'s holder has `privilege` on
/// `dataset_name` as a whole -- for listing every trait in a dataset,
/// where there's no single trait to name. gn-auth resolves a trait's
/// resource purely from its dataset name (see docs/gn-auth.md); the
/// trait half of a `"Dataset::Trait"` string never affects which
/// resource, and so which privileges, come back -- this just omits it.
pub fn authorise_dataset(
    auth_server_url: &str,
    token: &AuthToken,
    dataset_name: &str,
    privilege: &str,
) -> Result<bool, String> {
    authorise_trait(auth_server_url, token, dataset_name, "", privilege)
}

fn trait_privileges(
    auth_server_url: &str,
    token: &AuthToken,
    dataset_name: &str,
    trait_name: &str,
) -> Result<Vec<String>, String> {
    static CACHE: OnceLock<PrivilegesCache> = 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);
    }
}