diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-13 06:06:37 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-13 06:06:37 +0000 |
| commit | 2551418eede25d0ffaebef67f9950f13e3551567 (patch) | |
| tree | 1d173432582191401f69622925d7337d5ebe81c8 | |
| parent | 2456d66fc2c14345ab0730ef0a4ae07458af8ec6 (diff) | |
| download | genenetwork4-2551418eede25d0ffaebef67f9950f13e3551567.tar.gz | |
auth: add gnauth compile-time tags (secured/token_only/disabled)
Adds a gnauth-macros proc-macro crate and a private-field Authorized capability type in src/auth.rs, so #[gnauth(secured)] is a real, compile-time-checked guarantee that a handler performs the gn-auth resource-authorisation round trip before sharing trait/probeset values, rather than just a comment. #[gnauth(token_only)] marks handlers that require a token but skip the round trip, and #[gnauth(disabled)] marks the two handlers that need no token at all. Also fixes groups.rs: group_trait_values, group_trait_info and group_traits previously performed no gn-auth round trip at all for published-trait data; they now resolve the group's PublishFreeze row and call the same auth::check used elsewhere, denying by default when no such row exists. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
| -rw-r--r-- | Cargo.lock | 10 | ||||
| -rw-r--r-- | Cargo.toml | 1 | ||||
| -rw-r--r-- | README.md | 28 | ||||
| -rw-r--r-- | docs/gn-auth.md | 55 | ||||
| -rw-r--r-- | gnauth-macros/Cargo.toml | 12 | ||||
| -rw-r--r-- | gnauth-macros/src/lib.rs | 118 | ||||
| -rw-r--r-- | src/auth.rs | 63 | ||||
| -rw-r--r-- | src/lib.rs | 6 | ||||
| -rw-r--r-- | src/routes/accessions.rs | 3 | ||||
| -rw-r--r-- | src/routes/correlation.rs | 3 | ||||
| -rw-r--r-- | src/routes/datasets.rs | 117 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 4 | ||||
| -rw-r--r-- | src/routes/groups.rs | 474 | ||||
| -rw-r--r-- | src/routes/mapping_methods.rs | 3 | ||||
| -rw-r--r-- | src/routes/publications.rs | 3 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 4 | ||||
| -rw-r--r-- | src/routes/search.rs | 3 | ||||
| -rw-r--r-- | src/routes/species.rs | 5 | ||||
| -rw-r--r-- | src/routes/traits.rs | 139 |
19 files changed, 744 insertions, 307 deletions
diff --git a/Cargo.lock b/Cargo.lock index c886665..e5ccd59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1037,6 +1037,7 @@ version = "0.1.0" dependencies = [ "axum", "duckdb", + "gnauth-macros", "http-body-util", "jsonwebtoken", "lmdb", @@ -1117,6 +1118,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] +name = "gnauth-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] name = "half" version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/Cargo.toml b/Cargo.toml index 3bd3c30..72df08f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2024" [dependencies] axum = "0.8.9" duckdb = "1.10506.0" +gnauth-macros = { path = "gnauth-macros" } jsonwebtoken = "9.3.1" lmdb = "0.8.0" mysql = { version = "26.0.1", default-features = false, features = ["minimal-rust", "derive"] } diff --git a/README.md b/README.md index 0dbe4da..a8d04d6 100644 --- a/README.md +++ b/README.md @@ -316,13 +316,16 @@ Details, including example responses, below. - `GET /groups/{group}/traits` - returns every published (phenotype) trait belonging to a group, the listing equivalent of `/groups/{group}/traits/{trait_id}` (same fields, same join, no - `trait_id` filter and no `PublishFreeze.public`/`confidentiality` - check, matching that endpoint). 404 if no group matches. A large - group (e.g. BXD, with 15000+ phenotype traits) can take several - seconds and tens of megabytes to return in full; there's no - pagination or limit yet, matching GeneNetwork2's own - `wqflask.api.router.fetch_traits`, which defaults to unbounded too. - Needs `SQL_URI`, same as `/species` above. + `trait_id` filter). 404 if no group matches. If the group has any + published traits, its `PublishFreeze` row is checked the same way as + `/traits/{dataset}` (see docs/gn-auth.md): 403 if it isn't public + and the caller isn't authorized for it; an empty list (most groups + have no phenotype dataset at all) skips the check, since there's + nothing in it to protect. A large group (e.g. BXD, with 15000+ + phenotype traits) can take several seconds and tens of megabytes to + return in full; there's no pagination or limit yet, matching + GeneNetwork2's own `wqflask.api.router.fetch_traits`, which defaults + to unbounded too. Needs `SQL_URI`, same as `/species` above. The optional `abbreviation` parameter keeps only the traits with that short name, e.g. `/groups/BXD/traits?abbreviation=5HT_MB_M` finds @@ -365,7 +368,9 @@ Details, including example responses, below. section, which identifies exactly this join as worth surfacing). `trait_id` is `PublishXRef.Id`, scoped by group for the same reason as `/groups/{group}/traits/{trait_id}/values`. 404 if no group - matches, or if the group has no such trait. + matches, or if the group has no such trait; 403 if the trait's + `PublishFreeze` isn't public and the caller isn't authorized for it + (see docs/gn-auth.md). ```json { @@ -414,8 +419,11 @@ Details, including example responses, below. `PublishXRef.Id`; it alone doesn't identify a trait uniquely across groups (only the pair of group and `PublishXRef.Id` does), hence the group in the path. 404 if no group matches, or if the group has no - such trait. Only Publish (phenotype) traits are supported so far, not - ProbeSet (expression) or Geno (genotype) traits. + such trait; 403 if the trait's `PublishFreeze` isn't public and the + caller isn't authorized for it (see docs/gn-auth.md -- this is a + `#[gnauth(secured)]` endpoint, since it shares actual trait values). + Only Publish (phenotype) traits are supported so far, not ProbeSet + (expression) or Geno (genotype) traits. ```json { diff --git a/docs/gn-auth.md b/docs/gn-auth.md index 8e39773..2802784 100644 --- a/docs/gn-auth.md +++ b/docs/gn-auth.md @@ -252,6 +252,16 @@ failure. dataset at once (e.g. before listing every probeset in it) -- gn-auth resolves a trait's resource purely from its dataset name, so the trait half of the `"Dataset::Trait"` string never affects the answer. +- `check(auth_server_url, token, dataset_name, trait_name, public, + confidentiality, create_time)`: combines `is_publicly_readable` and + `authorise_trait`/`authorise_dataset` (always with + `"group:resource:view-resource"`, the only privilege any route here + checks) into the one branch every gated handler below actually + wants, returning `Option<Authorized>` -- the capability a handler + can require to construct a "found and visible" result, rather than + writing the branch out by hand. `is_authorised` is its boolean form, + for a caller that filters a list instead of rejecting one request + (`publication_traits`). - `tests/auth.rs` runs all of this against a real gn-auth instance (set `GN4_TEST_AUTH_TOKEN`/`GN4_TEST_RESOURCE_ID`; skips otherwise). @@ -278,11 +288,42 @@ probeset in the list): and `tests/dataset_probesets.rs` for all of these cases exercised against a real gn-auth instance. -`GET /groups/{group}/traits` and its singular siblings (Publish/ -phenotype data) require a token like every endpoint now (see "Every -endpoint requires a token" below) but don't check any further -resource-level authorization -- that remains a separate, not yet made -decision, same as every endpoint outside this family and `/traits`. +`GET /groups/{group}/traits` and its singular siblings (`/traits/ +{trait_id}` and its `/values` sibling) are gated the same way as +`/traits/{dataset}/...` below: resolve the group's own `PublishFreeze` +row (by the group's name -- `PublishXRef`/`PublishFreeze` aren't tied +by a foreign key, so this is a name lookup, not a join) and run the +same `is_publicly_readable`/`authorise_trait`/`authorise_dataset` +check against it. If a group has published traits but no matching +`PublishFreeze` row to check, that's treated as a deny rather than as +ungated/public data. `/traits` (the listing) skips the round trip only +when the group has zero published traits -- there's nothing to +protect in an empty list, so no reason to spend a gn-auth call (or +risk denying) on it. + +All three endpoints, and the two above them +(`/datasets/{dataset}/probesets/{probeset}/values` and `/traits/ +{dataset}/{trait}/values`), carry `#[gnauth(secured)]` +(`gnauth-macros`): a compile-time tag, checked by that attribute +macro, for handlers that can share actual trait/probeset *values*. +It's a textual check only -- it can't see across function calls -- so +it verifies the handler takes `AuthToken` and mentions +`auth::Authorized`, the capability type only `auth::check` can +produce (its field is private, so it can't be fabricated outside +`src/auth.rs`). Metadata-only endpoints (`/traits/{dataset}`, +`/datasets/{dataset}/probesets`, `/groups/{group}/traits` and their +singular siblings) are gated the same way but don't carry the tag -- +they don't share values, just whether a trait/dataset is visible at +all. + +`gnauth-macros` also has the opposite tag, `#[gnauth(disabled)]`, for +the handful of endpoints that intentionally take no `AuthToken` at +all -- `hello_world` and `version` (`src/lib.rs`) carry it, marking +"no token needed" as a deliberate decision rather than an oversight. +It checks the converse of `secured`: the signature must *not* take +`AuthToken`. (`routes::dev::get_test_token` also takes no token, but +isn't tagged -- it's a conditionally-registered test utility, a +different category from a normal public endpoint.) ### Wired into routes: `/traits/{dataset}/...`, spanning both categories @@ -306,7 +347,9 @@ No non-public `PublishFreeze` exists in the database this was tested against, so the deny path for the Publish branch specifically wasn't exercised against real data -- only against the already-proven ProbeSet branch and gn-auth's own "unlinked dataset" 404-to-deny -behavior, which this new branch calls unchanged. +behavior, which this new branch calls unchanged. The same caveat +applies to `/groups/{group}/traits...` above, which resolves to the +same `PublishFreeze` check. ### Every endpoint requires a token diff --git a/gnauth-macros/Cargo.toml b/gnauth-macros/Cargo.toml new file mode 100644 index 0000000..f3cbce9 --- /dev/null +++ b/gnauth-macros/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "gnauth-macros" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full"] } diff --git a/gnauth-macros/src/lib.rs b/gnauth-macros/src/lib.rs new file mode 100644 index 0000000..67d4852 --- /dev/null +++ b/gnauth-macros/src/lib.rs @@ -0,0 +1,118 @@ +//! `#[gnauth(secured)]`/`#[gnauth(token_only)]`/`#[gnauth(disabled)]`: +//! compile-time tags spanning this API's whole auth spectrum. +//! +//! - `disabled`: handlers that intentionally require no token at all +//! (e.g. a health check or the version endpoint). Marks the +//! decision as deliberate, not an oversight. +//! - `token_only`: handlers that require a valid bearer token but +//! never make the gn-auth resource-authorization round trip -- +//! everything gated purely by "is this caller who they say they +//! are," not "is this specific resource visible to them." +//! - `secured`: handlers that must make the gn-auth resource- +//! authorization round trip -- not just hold a valid bearer token -- +//! before returning data. Use it only on endpoints that can share +//! actual trait/probeset *values*; metadata- or listing-only +//! endpoints that happen to gate the same way (e.g. `traits`, +//! `dataset_probesets`, `group_traits`) are deliberately left +//! untagged by either `secured` or `token_only` -- they're a fourth, +//! unlabeled case (token + round trip, but no values), since neither +//! tag's check would describe them honestly. +//! +//! A proc-macro attribute only ever sees tokens, never types, so none +//! of these can verify the real guarantee by itself -- each is a +//! *textual* sanity check on top of the real mechanism, so an endpoint +//! can't silently drift out of sync with its tag: +//! - `secured` requires the signature to take `AuthToken` and the body +//! to mention `Authorized`, the capability type only `auth::check` +//! can produce (its field is private, so it can't be fabricated +//! outside `src/auth.rs` -- see that module). +//! - `token_only` requires the signature to take `AuthToken`, and the +//! body to *not* mention `Authorized` -- if it started doing the +//! round trip, the tag is now wrong and should become `secured` (or +//! be removed, if the endpoint stays metadata-only). +//! - `disabled` requires the signature to *not* take `AuthToken`. +//! +//! All three are markers, not wrappers: the function is re-emitted +//! unchanged, so they cost nothing at runtime. + +use proc_macro::TokenStream; +use quote::{quote, ToTokens}; +use syn::{parse_macro_input, ItemFn}; + +#[proc_macro_attribute] +pub fn gnauth(attr: TokenStream, item: TokenStream) -> TokenStream { + let attr_str = attr.to_string(); + let input = parse_macro_input!(item as ItemFn); + let sig_text = input.sig.to_token_stream().to_string(); + + match attr_str.as_str() { + "secured" => { + if !sig_text.contains("AuthToken") { + return syn::Error::new_spanned( + &input.sig, + "#[gnauth(secured)] requires an `AuthToken` parameter: \ + this handler must require a valid bearer token", + ) + .to_compile_error() + .into(); + } + let body_text = input.block.to_token_stream().to_string(); + if !body_text.contains("Authorized") { + return syn::Error::new_spanned( + &input.sig, + "#[gnauth(secured)] requires the handler to use `auth::Authorized` \ + (produced only by auth::check, i.e. the gn-auth resource-authorization \ + round trip): this handler is tagged as sharing secured data but never \ + mentions it", + ) + .to_compile_error() + .into(); + } + } + "token_only" => { + if !sig_text.contains("AuthToken") { + return syn::Error::new_spanned( + &input.sig, + "#[gnauth(token_only)] requires an `AuthToken` parameter: \ + this handler must require a valid bearer token", + ) + .to_compile_error() + .into(); + } + let body_text = input.block.to_token_stream().to_string(); + if body_text.contains("Authorized") { + return syn::Error::new_spanned( + &input.sig, + "#[gnauth(token_only)] asserts this handler never makes the gn-auth \ + resource-authorization round trip, but its body mentions \ + `auth::Authorized`: retag it `#[gnauth(secured)]` if it now shares \ + values, or remove the tag if it's metadata-only", + ) + .to_compile_error() + .into(); + } + } + "disabled" => { + if sig_text.contains("AuthToken") { + return syn::Error::new_spanned( + &input.sig, + "#[gnauth(disabled)] asserts this handler takes no `AuthToken`: \ + remove the tag (or the parameter) since it now does", + ) + .to_compile_error() + .into(); + } + } + _ => { + return syn::Error::new( + proc_macro2::Span::call_site(), + "expected `#[gnauth(secured)]`, `#[gnauth(token_only)]` or \ + `#[gnauth(disabled)]`", + ) + .to_compile_error() + .into(); + } + } + + quote! { #input }.into() +} diff --git a/src/auth.rs b/src/auth.rs index eb13186..d1a86c6 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -234,6 +234,69 @@ fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { 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")] diff --git a/src/lib.rs b/src/lib.rs index 75746d9..f011219 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ use axum::Json; use axum::Router; +use gnauth_macros::gnauth; use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer}; use utoipa::OpenApi; use utoipa_axum::router::OpenApiRouter; @@ -108,11 +109,13 @@ pub fn app() -> Router { // whose response is not wrapped in the envelope, like /openapi.json. // Both opt out of ApiDoc's default security requirement with an empty // security() -- neither takes an AuthToken, so documenting them as -// needing one would be wrong, not just inconsistent. +// needing one would be wrong, not just inconsistent. #[gnauth(disabled)] +// below makes that a compile-time assertion, not just this comment. #[utoipa::path(get, path = "/", summary = "Greeting; confirms the server is up", responses( (status = 200, description = "Greeting", body = String), (status = 500, description = "Internal error", body = ApiError) ), security())] +#[gnauth(disabled)] async fn hello_world() -> &'static str { "Hello, world!" } @@ -131,6 +134,7 @@ struct VersionInfo { (status = 200, description = "Build information", body = Envelope<VersionInfo>), (status = 500, description = "Internal error", body = ApiError) ), security())] +#[gnauth(disabled)] async fn version(ctx: Ctx) -> Json<Envelope<VersionInfo>> { Json(ctx.envelope(VersionInfo { name: "GeneNetwork4", diff --git a/src/routes/accessions.rs b/src/routes/accessions.rs index f4ce3b1..c55bfd7 100644 --- a/src/routes/accessions.rs +++ b/src/routes/accessions.rs @@ -4,6 +4,8 @@ use axum::Json; use axum::extract::Path; use axum::http::StatusCode; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -27,6 +29,7 @@ fn parse_accession(text: &str) -> Option<u32> { (status = 404, description = "No dataset has this accession", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn accession( ctx: Ctx, Path(accession): Path<String>, diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index b774577..e703fd0 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -8,6 +8,8 @@ use axum::Json; use serde::{Deserialize, Serialize}; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::error::{ApiError, Unauthorized}; use crate::response::{Ctx, Envelope}; @@ -43,6 +45,7 @@ Currently returns canned data wrapped in the descriptive envelope \ Unauthorized, (status = 500, description = "Internal error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn correlation( ctx: Ctx, _token: AuthToken, diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs index cdcca99..b011099 100644 --- a/src/routes/datasets.rs +++ b/src/routes/datasets.rs @@ -5,7 +5,9 @@ use axum::Json; use axum::extract::{Path}; use axum::http::StatusCode; -use crate::auth::{self, AuthToken, VIEW_RESOURCE_PRIVILEGE}; +use gnauth_macros::gnauth; + +use crate::auth::{self, AuthToken, Authorized}; use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -19,6 +21,7 @@ use crate::response::{Ctx, Envelope, path_segment}; (status = 404, description = "No matching dataset", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn dataset_by_name( ctx: Ctx, Path(dataset): Path<String>, @@ -73,7 +76,7 @@ pub async fn dataset_by_name( enum DatasetProbesetsLookup { DatasetNotFound, Forbidden, - Found(Vec<db::ProbeSetInfo>), + Found(Authorized, Vec<db::ProbeSetInfo>), } fn get_dataset_probesets_result( @@ -85,17 +88,23 @@ fn get_dataset_probesets_result( None => return Ok(DatasetProbesetsLookup::DatasetNotFound), Some(dataset) => dataset, }; - if !auth::is_publicly_readable(dataset.public, dataset.confidentiality, &dataset.create_time) { - let authorised = - auth::authorise_dataset(auth_server_url, token, &dataset.name, VIEW_RESOURCE_PRIVILEGE) - .map_err(DatasetAuthError::Auth)?; - if !authorised { - return Ok(DatasetProbesetsLookup::Forbidden); - } - } - Ok(DatasetProbesetsLookup::Found(db::get_dataset_probesets( - dataset.id, - )?)) + let Some(auth) = auth::check( + auth_server_url, + token, + &dataset.name, + None, + dataset.public, + dataset.confidentiality, + &dataset.create_time, + ) + .map_err(DatasetAuthError::Auth)? + else { + return Ok(DatasetProbesetsLookup::Forbidden); + }; + Ok(DatasetProbesetsLookup::Found( + auth, + db::get_dataset_probesets(dataset.id)?, + )) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets", summary = "List the expression (ProbeSet) traits belonging to a dataset", params( @@ -149,7 +158,7 @@ pub async fn dataset_probesets( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetsLookup::Found(probesets) => Ok(Json( + DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json( ctx.envelope(probesets) .with_note(db::LOD_NOTE) .with_next( @@ -187,7 +196,7 @@ enum DatasetProbesetLookup<T> { DatasetNotFound, ProbesetNotFound, Forbidden, - Found(T), + Found(Authorized, T), } /// Either a database error, or a failure to reach/parse gn-auth's @@ -217,20 +226,20 @@ fn get_dataset_probeset_info_result( None => return Ok(DatasetProbesetLookup::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(DatasetProbesetLookup::Forbidden); - } - } - Ok(DatasetProbesetLookup::Found(info)) + let Some(auth) = auth::check( + auth_server_url, + token, + &dataset.name, + Some(&info.name), + dataset.public, + dataset.confidentiality, + &dataset.create_time, + ) + .map_err(DatasetAuthError::Auth)? + else { + return Ok(DatasetProbesetLookup::Forbidden); + }; + Ok(DatasetProbesetLookup::Found(auth, info)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}", summary = "Get one expression trait's ProbeSetXRef/ProbeSet metadata", params( @@ -286,7 +295,7 @@ pub async fn dataset_probeset_info( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetLookup::Found(info) => { + DatasetProbesetLookup::Found(_authorized, info) => { let dataset = path_segment(¬_found_dataset); let probeset = path_segment(¬_found_probeset); Ok(Json( @@ -343,20 +352,20 @@ fn get_dataset_probeset_values_result( if values.is_empty() { return Ok(DatasetProbesetLookup::ProbesetNotFound); } - if !auth::is_publicly_readable(dataset.public, dataset.confidentiality, &dataset.create_time) { - let authorised = auth::authorise_trait( - auth_server_url, - token, - &dataset.name, - probeset, - VIEW_RESOURCE_PRIVILEGE, - ) - .map_err(DatasetAuthError::Auth)?; - if !authorised { - return Ok(DatasetProbesetLookup::Forbidden); - } - } - Ok(DatasetProbesetLookup::Found(values)) + let Some(auth) = auth::check( + auth_server_url, + token, + &dataset.name, + Some(probeset), + dataset.public, + dataset.confidentiality, + &dataset.create_time, + ) + .map_err(DatasetAuthError::Auth)? + else { + return Ok(DatasetProbesetLookup::Forbidden); + }; + Ok(DatasetProbesetLookup::Found(auth, values)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}/values", summary = "Get one expression trait's value in each strain in the dataset", params( @@ -370,6 +379,7 @@ fn get_dataset_probeset_values_result( (status = 500, description = "Database error", body = ApiError), (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) ))] +#[gnauth(secured)] pub async fn dataset_probeset_values( ctx: Ctx, Path((dataset, probeset)): Path<(String, String)>, @@ -412,14 +422,17 @@ pub async fn dataset_probeset_values( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetLookup::Found(values) => Ok(Json(ctx.envelope(values).with_next( - &format!( - "/datasets/{}/probesets/{}", - path_segment(¬_found_dataset), - path_segment(¬_found_probeset) - ), - "The probeset's metadata", - ))), + DatasetProbesetLookup::Found(authorized, values) => { + let _: Authorized = authorized; + Ok(Json(ctx.envelope(values).with_next( + &format!( + "/datasets/{}/probesets/{}", + path_segment(¬_found_dataset), + path_segment(¬_found_probeset) + ), + "The probeset's metadata", + ))) + } DatasetProbesetLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 5ed3336..0b6b748 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -14,6 +14,8 @@ use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Deserialize; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::config::Config; use crate::error::{ApiError, Unauthorized}; @@ -71,6 +73,7 @@ trait values, and returns the resulting rows of GEMMA's own \ (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9), or id not alnum/-/_ (max 64 chars)", body = ApiError), (status = 502, description = "gemma-wrapper or GEMMA failed", body = ApiError) ))] +#[gnauth(token_only)] pub async fn compute_gemma( ctx: Ctx, _token: AuthToken, @@ -154,6 +157,7 @@ R/qtl.", (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError), (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError) ))] +#[gnauth(token_only)] pub async fn gemma_status( ctx: Ctx, _token: AuthToken, diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 70d46f3..1c87cdd 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -6,7 +6,10 @@ use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Deserialize; -use crate::auth::AuthToken; +use gnauth_macros::gnauth; + +use crate::auth::{self, AuthToken, Authorized}; +use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; use crate::response::{Ctx, Envelope, path_segment}; @@ -36,6 +39,7 @@ fn contains_ci(field: &Option<String>, needle: &str) -> bool { Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn groups( ctx: Ctx, _token: AuthToken, @@ -97,6 +101,7 @@ pub async fn groups( (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn group_by_name( ctx: Ctx, Path(group): Path<String>, @@ -172,6 +177,7 @@ pub struct GroupStrainsParams { (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn group_strains( ctx: Ctx, Path(group): Path<String>, @@ -234,28 +240,79 @@ pub async fn group_strains( /// What looking up a trait within a group found, shared by /// group_trait_values and group_trait_info so each can tell a missing -/// group from a missing trait and return the right 404. +/// group from a missing trait and return the right 404. `Forbidden` +/// mirrors src/routes/traits.rs and src/routes/datasets.rs: the same +/// published (phenotype) data is reachable there via +/// /traits/{dataset}/... with a gn-auth check, so it needs one here +/// too (this was a known gap -- see docs/gn-auth.md). enum GroupTraitLookup<T> { GroupNotFound, TraitNotFound, - Found(T), + Forbidden, + Found(Authorized, T), +} + +/// Either a database error, or a failure to reach/parse gn-auth's +/// answer while checking authorization for a non-public group. +enum GroupAuthError { + Db(mysql::Error), + Auth(String), +} + +impl From<mysql::Error> for GroupAuthError { + fn from(e: mysql::Error) -> Self { + GroupAuthError::Db(e) + } +} + +/// Resolve `group`'s PublishFreeze row and run the same +/// public/confidentiality/create_time-gated gn-auth check +/// src/routes/traits.rs applies when the same data is reached via +/// /traits/{dataset}/... When a group has published traits +/// (PublishXRef rows) with no PublishFreeze row to check -- not +/// expected, but PublishXRef/PublishFreeze aren't tied by a foreign +/// key -- this denies rather than treating ungated data as public. +fn check_group_trait_authorized( + group: &db::GroupDetail, + trait_name: Option<&str>, + auth_server_url: &str, + token: &AuthToken, +) -> Result<Option<Authorized>, GroupAuthError> { + let Some(pf) = db::get_publish_freeze_by_name(&group.name)? else { + return Ok(None); + }; + auth::check( + auth_server_url, + token, + &pf.name, + trait_name, + pf.public, + pf.confidentiality, + &pf.create_time, + ) + .map_err(GroupAuthError::Auth) } fn get_group_trait_values_result( group: &str, trait_id: u32, -) -> Result<GroupTraitLookup<Vec<db::TraitValue>>, mysql::Error> { - match db::get_group_by_name(group)? { - None => Ok(GroupTraitLookup::GroupNotFound), - Some(group) => { - let values = db::get_group_trait_values(group.id, trait_id)?; - if values.is_empty() { - Ok(GroupTraitLookup::TraitNotFound) - } else { - Ok(GroupTraitLookup::Found(values)) - } - } + auth_server_url: &str, + token: &AuthToken, +) -> Result<GroupTraitLookup<Vec<db::TraitValue>>, GroupAuthError> { + let Some(group) = db::get_group_by_name(group)? else { + return Ok(GroupTraitLookup::GroupNotFound); + }; + let values = db::get_group_trait_values(group.id, trait_id)?; + if values.is_empty() { + return Ok(GroupTraitLookup::TraitNotFound); } + let trait_id_string = trait_id.to_string(); + let Some(auth) = + check_group_trait_authorized(&group, Some(&trait_id_string), auth_server_url, token)? + else { + return Ok(GroupTraitLookup::Forbidden); + }; + Ok(GroupTraitLookup::Found(auth, values)) } #[utoipa::path(get, path = "/groups/{group}/traits/{trait_id}/values", summary = "Get one published trait's value in each of a group's strains", params( @@ -264,77 +321,111 @@ fn get_group_trait_values_result( ), responses( (status = 200, description = "The group's per-strain values for the trait", body = Envelope<Vec<db::TraitValue>>), Unauthorized, + (status = 403, description = "The trait's dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group, or no matching trait in that group", 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) ))] +#[gnauth(secured)] pub async fn group_trait_values( ctx: Ctx, Path((group, trait_id)): Path<(String, u32)>, - _token: AuthToken, + token: AuthToken, ) -> Result<Json<Envelope<Vec<db::TraitValue>>>, ApiError> { let rid = ctx.request_info(); let not_found_group = group.clone(); - tokio::task::spawn_blocking(move || get_group_trait_values_result(&group, trait_id)) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "group_trait_values", - ) - .with_request_id(rid.clone()) - })? - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "group_trait_values", - ) - .with_request_id(rid.clone()) - }) - .and_then(|lookup| match lookup { - GroupTraitLookup::Found(values) => { - let group = path_segment(¬_found_group); - Ok(Json(ctx.envelope(values).with_next( - &format!("/groups/{group}/traits/{trait_id}"), - "The trait's metadata", - ))) - } - GroupTraitLookup::GroupNotFound => Err(ApiError::new( - StatusCode::NOT_FOUND, - "group_not_found", - "Group not found", - format!("No group matching '{not_found_group}'."), - "group_trait_values", - ) - .with_request_id(rid.clone()) - .with_next("/groups")), - GroupTraitLookup::TraitNotFound => Err(ApiError::new( - StatusCode::NOT_FOUND, - "trait_not_found", - "Trait not found", - format!("No trait {trait_id} in group '{not_found_group}'."), - "group_trait_values", - ) - .with_request_id(rid)), - }) + let auth_server_url = Config::load().auth_server_url.clone(); + tokio::task::spawn_blocking(move || { + get_group_trait_values_result(&group, trait_id, &auth_server_url, &token) + }) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "group_trait_values", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| match e { + GroupAuthError::Db(e) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "group_trait_values", + ) + .with_request_id(rid.clone()), + GroupAuthError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "group_trait_values", + ) + .with_request_id(rid.clone()), + }) + .and_then(|lookup| match lookup { + GroupTraitLookup::Found(authorized, values) => { + let _: Authorized = authorized; + let group = path_segment(¬_found_group); + Ok(Json(ctx.envelope(values).with_next( + &format!("/groups/{group}/traits/{trait_id}"), + "The trait's metadata", + ))) + } + GroupTraitLookup::Forbidden => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!( + "Trait {trait_id} in group '{not_found_group}' is not public, \ + and you are not authorized to view it." + ), + "group_trait_values", + ) + .with_request_id(rid.clone())), + GroupTraitLookup::GroupNotFound => Err(ApiError::new( + StatusCode::NOT_FOUND, + "group_not_found", + "Group not found", + format!("No group matching '{not_found_group}'."), + "group_trait_values", + ) + .with_request_id(rid.clone()) + .with_next("/groups")), + GroupTraitLookup::TraitNotFound => Err(ApiError::new( + StatusCode::NOT_FOUND, + "trait_not_found", + "Trait not found", + format!("No trait {trait_id} in group '{not_found_group}'."), + "group_trait_values", + ) + .with_request_id(rid)), + }) } fn get_group_trait_info_result( group: &str, trait_id: u32, -) -> Result<GroupTraitLookup<db::TraitInfo>, mysql::Error> { - match db::get_group_by_name(group)? { - None => Ok(GroupTraitLookup::GroupNotFound), - Some(group) => match db::get_group_trait_info(group.id, trait_id)? { - None => Ok(GroupTraitLookup::TraitNotFound), - Some(info) => Ok(GroupTraitLookup::Found(info)), - }, - } + auth_server_url: &str, + token: &AuthToken, +) -> Result<GroupTraitLookup<db::TraitInfo>, GroupAuthError> { + let Some(group) = db::get_group_by_name(group)? else { + return Ok(GroupTraitLookup::GroupNotFound); + }; + let Some(info) = db::get_group_trait_info(group.id, trait_id)? else { + return Ok(GroupTraitLookup::TraitNotFound); + }; + let trait_id_string = trait_id.to_string(); + let Some(auth) = + check_group_trait_authorized(&group, Some(&trait_id_string), auth_server_url, token)? + else { + return Ok(GroupTraitLookup::Forbidden); + }; + Ok(GroupTraitLookup::Found(auth, info)) } #[utoipa::path(get, path = "/groups/{group}/traits/{trait_id}", summary = "Get one published trait's PublishXRef/Phenotype/Publication metadata", params( @@ -343,76 +434,100 @@ fn get_group_trait_info_result( ), responses( (status = 200, description = "The trait's PublishXRef/Phenotype/Publication metadata", body = Envelope<db::TraitInfo>), Unauthorized, + (status = 403, description = "The trait's dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group, or no matching trait in that group", 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) ))] pub async fn group_trait_info( ctx: Ctx, Path((group, trait_id)): Path<(String, u32)>, - _token: AuthToken, + token: AuthToken, ) -> Result<Json<Envelope<db::TraitInfo>>, ApiError> { let rid = ctx.request_info(); let not_found_group = group.clone(); - tokio::task::spawn_blocking(move || get_group_trait_info_result(&group, trait_id)) - .await - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Internal error", - e.to_string(), - "group_trait_info", - ) - .with_request_id(rid.clone()) - })? - .map_err(|e| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "database_error", - "Database error", - e.to_string(), - "group_trait_info", - ) - .with_request_id(rid.clone()) - }) - .and_then(|lookup| match lookup { - GroupTraitLookup::Found(info) => { - let group = path_segment(¬_found_group); - let pubmed_id = info.pubmed_id; - let mut envelope = ctx - .envelope(info) - .with_note(db::LOD_NOTE) - .with_next( - &format!("/groups/{group}/traits/{trait_id}/values"), - "The trait's value in each strain", - ) - .with_next(&format!("/groups/{group}"), "The group this trait belongs to"); - if let Some(pubmed_id) = pubmed_id { - envelope = envelope.with_next( - &format!("/publications/{pubmed_id}/traits"), - "Every trait reported by this trait's publication", - ); - } - Ok(Json(envelope)) + let auth_server_url = Config::load().auth_server_url.clone(); + tokio::task::spawn_blocking(move || { + get_group_trait_info_result(&group, trait_id, &auth_server_url, &token) + }) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "group_trait_info", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| match e { + GroupAuthError::Db(e) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "database_error", + "Database error", + e.to_string(), + "group_trait_info", + ) + .with_request_id(rid.clone()), + GroupAuthError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "group_trait_info", + ) + .with_request_id(rid.clone()), + }) + .and_then(|lookup| match lookup { + GroupTraitLookup::Found(_authorized, info) => { + let group = path_segment(¬_found_group); + let pubmed_id = info.pubmed_id; + let mut envelope = ctx + .envelope(info) + .with_note(db::LOD_NOTE) + .with_next( + &format!("/groups/{group}/traits/{trait_id}/values"), + "The trait's value in each strain", + ) + .with_next(&format!("/groups/{group}"), "The group this trait belongs to"); + if let Some(pubmed_id) = pubmed_id { + envelope = envelope.with_next( + &format!("/publications/{pubmed_id}/traits"), + "Every trait reported by this trait's publication", + ); } - GroupTraitLookup::GroupNotFound => Err(ApiError::new( - StatusCode::NOT_FOUND, - "group_not_found", - "Group not found", - format!("No group matching '{not_found_group}'."), - "group_trait_info", - ) - .with_request_id(rid.clone()) - .with_next("/groups")), - GroupTraitLookup::TraitNotFound => Err(ApiError::new( - StatusCode::NOT_FOUND, - "trait_not_found", - "Trait not found", - format!("No trait {trait_id} in group '{not_found_group}'."), - "group_trait_info", - ) - .with_request_id(rid)), - }) + Ok(Json(envelope)) + } + GroupTraitLookup::Forbidden => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!( + "Trait {trait_id} in group '{not_found_group}' is not public, \ + and you are not authorized to view it." + ), + "group_trait_info", + ) + .with_request_id(rid.clone())), + GroupTraitLookup::GroupNotFound => Err(ApiError::new( + StatusCode::NOT_FOUND, + "group_not_found", + "Group not found", + format!("No group matching '{not_found_group}'."), + "group_trait_info", + ) + .with_request_id(rid.clone()) + .with_next("/groups")), + GroupTraitLookup::TraitNotFound => Err(ApiError::new( + StatusCode::NOT_FOUND, + "trait_not_found", + "Trait not found", + format!("No trait {trait_id} in group '{not_found_group}'."), + "group_trait_info", + ) + .with_request_id(rid)), + }) } /// Query parameters for `GET /groups/{group}/traits`. @@ -423,31 +538,59 @@ pub struct GroupTraitsParams { pub abbreviation: Option<String>, } +enum GroupTraitsLookup { + GroupNotFound, + Forbidden, + Found(Vec<db::TraitInfo>), +} + +fn get_group_traits_result( + group: &str, + abbreviation: Option<&str>, + auth_server_url: &str, + token: &AuthToken, +) -> Result<GroupTraitsLookup, GroupAuthError> { + let Some(group) = db::get_group_by_name(group)? else { + return Ok(GroupTraitsLookup::GroupNotFound); + }; + let traits = match abbreviation { + Some(abbreviation) => db::get_group_traits_by_abbreviation(group.id, abbreviation)?, + None => db::get_group_traits(group.id)?, + }; + // Most groups have no published (phenotype) dataset at all -- + // nothing here to protect, so don't spend a gn-auth round trip + // (or deny) on an empty list. + if traits.is_empty() { + return Ok(GroupTraitsLookup::Found(traits)); + } + let Some(_auth) = check_group_trait_authorized(&group, None, auth_server_url, token)? else { + return Ok(GroupTraitsLookup::Forbidden); + }; + Ok(GroupTraitsLookup::Found(traits)) +} + #[utoipa::path(get, path = "/groups/{group}/traits", summary = "List the published (phenotype) traits belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), GroupTraitsParams ), responses( (status = 200, description = "The published traits belonging to the group", body = Envelope<Vec<db::TraitInfo>>), Unauthorized, + (status = 403, description = "The group's published data isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group", 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) ))] pub async fn group_traits( ctx: Ctx, Path(group): Path<String>, - _token: AuthToken, + token: AuthToken, Query(params): Query<GroupTraitsParams>, ) -> Result<Json<Envelope<Vec<db::TraitInfo>>>, ApiError> { let rid = ctx.request_info(); let not_found_name = group.clone(); + let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { - db::get_group_by_name(&group).and_then(|group| match (group, params.abbreviation) { - (Some(group), Some(abbreviation)) => { - db::get_group_traits_by_abbreviation(group.id, &abbreviation).map(Some) - } - (Some(group), None) => db::get_group_traits(group.id).map(Some), - (None, _) => Ok(None), - }) + get_group_traits_result(&group, params.abbreviation.as_deref(), &auth_server_url, &token) }) .await .map_err(|e| { @@ -460,26 +603,45 @@ pub async fn group_traits( ) .with_request_id(rid.clone()) })? - .map_err(|e| { - ApiError::new( + .map_err(|e| match e { + GroupAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "group_traits", ) - .with_request_id(rid.clone()) - })? - .map(|traits| { - let group = path_segment(¬_found_name); - Json( - ctx.envelope(traits) - .with_note(db::LOD_NOTE) - .with_next(&format!("/groups/{group}"), "The group these traits belong to"), + .with_request_id(rid.clone()), + GroupAuthError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "group_traits", ) + .with_request_id(rid.clone()), }) - .ok_or_else(|| { - ApiError::new( + .and_then(|lookup| match lookup { + GroupTraitsLookup::Found(traits) => { + let group = path_segment(¬_found_name); + Ok(Json( + ctx.envelope(traits) + .with_note(db::LOD_NOTE) + .with_next(&format!("/groups/{group}"), "The group these traits belong to"), + )) + } + GroupTraitsLookup::Forbidden => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!( + "Group '{not_found_name}' published data is not public, \ + and you are not authorized to view it." + ), + "group_traits", + ) + .with_request_id(rid.clone())), + GroupTraitsLookup::GroupNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "group_not_found", "Group not found", @@ -487,7 +649,7 @@ pub async fn group_traits( "group_traits", ) .with_request_id(rid) - .with_next("/groups") + .with_next("/groups")), }) } @@ -499,6 +661,7 @@ pub async fn group_traits( (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn group_case_attributes( ctx: Ctx, Path(group): Path<String>, @@ -560,6 +723,7 @@ pub async fn group_case_attributes( (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn group_datasets( ctx: Ctx, Path(group): Path<String>, diff --git a/src/routes/mapping_methods.rs b/src/routes/mapping_methods.rs index 9805fe8..224d90f 100644 --- a/src/routes/mapping_methods.rs +++ b/src/routes/mapping_methods.rs @@ -3,6 +3,8 @@ use axum::Json; use axum::http::StatusCode; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -13,6 +15,7 @@ use crate::response::{Ctx, Envelope}; Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn mapping_methods( ctx: Ctx, _token: AuthToken, diff --git a/src/routes/publications.rs b/src/routes/publications.rs index 2431964..850f934 100644 --- a/src/routes/publications.rs +++ b/src/routes/publications.rs @@ -5,12 +5,11 @@ use axum::extract::{Path}; use axum::http::StatusCode; use std::collections::HashMap; -use crate::auth::AuthToken; +use crate::auth::{AuthToken, is_authorised}; use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; use crate::response::{Ctx, Envelope, path_segment}; -use crate::routes::traits::is_authorised; enum PublicationTraits { NotFound, diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 0cc7d23..4535d30 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -11,6 +11,8 @@ use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Deserialize; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::config::Config; use crate::error::{ApiError, Unauthorized}; @@ -77,6 +79,7 @@ concurrently -- same shape as /compute/gemma.", (status = 422, description = "id not alnum/-/_ (max 64 chars)", body = ApiError), (status = 502, description = "Rscript or rqtl_wrapper.R failed", body = ApiError) ))] +#[gnauth(token_only)] pub async fn compute_rqtl( ctx: Ctx, _token: AuthToken, @@ -151,6 +154,7 @@ the run_id passed as ?id= on POST /compute/rqtl.", (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError), (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError) ))] +#[gnauth(token_only)] pub async fn rqtl_status( ctx: Ctx, _token: AuthToken, diff --git a/src/routes/search.rs b/src/routes/search.rs index b28a4f3..3fdfc36 100644 --- a/src/routes/search.rs +++ b/src/routes/search.rs @@ -19,6 +19,8 @@ use axum::http::StatusCode; use serde::Deserialize; use std::collections::HashMap; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -165,6 +167,7 @@ queries carry the backend's parser diagnostic as a 422.", (status = 422, description = "Query unparsable by the search backend; carries gn3's diagnostic", body = ApiError), (status = 502, description = "Search backend unreachable or misbehaving", body = ApiError) ))] +#[gnauth(token_only)] pub async fn search( ctx: Ctx, _token: AuthToken, diff --git a/src/routes/species.rs b/src/routes/species.rs index af3bd5d..94f8736 100644 --- a/src/routes/species.rs +++ b/src/routes/species.rs @@ -4,6 +4,8 @@ use axum::Json; use axum::extract::{Path}; use axum::http::StatusCode; +use gnauth_macros::gnauth; + use crate::auth::AuthToken; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -14,6 +16,7 @@ use crate::response::{Ctx, Envelope, path_segment}; Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn species( ctx: Ctx, _token: AuthToken, @@ -59,6 +62,7 @@ pub async fn species( (status = 404, description = "No matching species", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn species_by_name( ctx: Ctx, Path(species): Path<String>, @@ -120,6 +124,7 @@ pub async fn species_by_name( (status = 404, description = "No matching species", body = ApiError), (status = 500, description = "Database error", body = ApiError) ))] +#[gnauth(token_only)] pub async fn species_datasets( ctx: Ctx, Path(species): Path<String>, diff --git a/src/routes/traits.rs b/src/routes/traits.rs index 7f6cbfe..0b7e77c 100644 --- a/src/routes/traits.rs +++ b/src/routes/traits.rs @@ -17,7 +17,9 @@ use axum::http::StatusCode; use axum::Json; use serde::Serialize; -use crate::auth::{self, AuthToken, VIEW_RESOURCE_PRIVILEGE}; +use gnauth_macros::gnauth; + +use crate::auth::{self, AuthToken, Authorized}; use crate::config::Config; use crate::db; use crate::error::{ApiError, Unauthorized}; @@ -51,46 +53,10 @@ impl From<mysql::Error> for TraitAuthError { } } -/// True if `token`'s holder may view `trait_name` (or, when -/// `trait_name` is `None`, the dataset as a whole, e.g. for a listing) -/// given the dataset's own public/confidentiality/create_time -- -/// either because it's publicly readable, or because gn-auth says so. -/// Shared by all three handlers below so the ProbeSet and Publish -/// branches of each only differ in which db:: functions they call, not -/// in how they're gated. -pub(crate) 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> { - if auth::is_publicly_readable(public, confidentiality, create_time) { - return Ok(true); - } - match trait_name { - Some(trait_name) => auth::authorise_trait( - auth_server_url, - token, - dataset_name, - trait_name, - VIEW_RESOURCE_PRIVILEGE, - ), - None => auth::authorise_dataset( - auth_server_url, - token, - dataset_name, - VIEW_RESOURCE_PRIVILEGE, - ), - } -} - enum TraitsLookup { DatasetNotFound, Forbidden, - Found(Vec<TraitInfoResponse>), + Found(Authorized, Vec<TraitInfoResponse>), } fn get_traits_result( @@ -104,7 +70,7 @@ fn get_traits_result( }; match dataset { db::TraitDataset::ProbeSet(ds) => { - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &ds.name, @@ -113,11 +79,12 @@ fn get_traits_result( ds.confidentiality, &ds.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitsLookup::Forbidden); - } + }; Ok(TraitsLookup::Found( + auth, db::get_dataset_probesets(ds.id)? .into_iter() .map(TraitInfoResponse::Probeset) @@ -125,7 +92,7 @@ fn get_traits_result( )) } db::TraitDataset::Publish(pf) => { - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &pf.name, @@ -134,11 +101,12 @@ fn get_traits_result( pf.confidentiality, &pf.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitsLookup::Forbidden); - } + }; Ok(TraitsLookup::Found( + auth, db::get_group_traits(pf.inbred_set_id)? .into_iter() .map(TraitInfoResponse::Publish) @@ -197,7 +165,9 @@ pub async fn traits( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - TraitsLookup::Found(traits) => Ok(Json(ctx.envelope(traits).with_note(db::LOD_NOTE))), + TraitsLookup::Found(_authorized, traits) => { + Ok(Json(ctx.envelope(traits).with_note(db::LOD_NOTE))) + } TraitsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", @@ -223,7 +193,7 @@ enum TraitInfoLookup { DatasetNotFound, TraitNotFound, Forbidden, - Found(Box<TraitInfoResponse>), + Found(Authorized, Box<TraitInfoResponse>), } fn get_trait_info_result( @@ -242,7 +212,7 @@ fn get_trait_info_result( None => return Ok(TraitInfoLookup::TraitNotFound), Some(info) => info, }; - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &ds.name, @@ -251,13 +221,14 @@ fn get_trait_info_result( ds.confidentiality, &ds.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitInfoLookup::Forbidden); - } - Ok(TraitInfoLookup::Found(Box::new( - TraitInfoResponse::Probeset(info), - ))) + }; + Ok(TraitInfoLookup::Found( + auth, + Box::new(TraitInfoResponse::Probeset(info)), + )) } db::TraitDataset::Publish(pf) => { let Ok(trait_id) = trait_name.parse::<u32>() else { @@ -267,7 +238,7 @@ fn get_trait_info_result( None => return Ok(TraitInfoLookup::TraitNotFound), Some(info) => info, }; - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &pf.name, @@ -276,13 +247,14 @@ fn get_trait_info_result( pf.confidentiality, &pf.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitInfoLookup::Forbidden); - } - Ok(TraitInfoLookup::Found(Box::new( - TraitInfoResponse::Publish(info), - ))) + }; + Ok(TraitInfoLookup::Found( + auth, + Box::new(TraitInfoResponse::Publish(info)), + )) } } } @@ -340,7 +312,7 @@ pub async fn trait_info( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - TraitInfoLookup::Found(info) => { + TraitInfoLookup::Found(_authorized, info) => { let base = format!( "/traits/{}/{}", path_segment(¬_found_dataset), @@ -396,7 +368,7 @@ enum TraitValuesLookup { DatasetNotFound, TraitNotFound, Forbidden, - Found(Vec<db::TraitValue>), + Found(Authorized, Vec<db::TraitValue>), } fn get_trait_values_result( @@ -415,7 +387,7 @@ fn get_trait_values_result( if values.is_empty() { return Ok(TraitValuesLookup::TraitNotFound); } - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &ds.name, @@ -424,11 +396,12 @@ fn get_trait_values_result( ds.confidentiality, &ds.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitValuesLookup::Forbidden); - } + }; Ok(TraitValuesLookup::Found( + auth, values .into_iter() .map(|v| db::TraitValue { @@ -446,7 +419,7 @@ fn get_trait_values_result( if values.is_empty() { return Ok(TraitValuesLookup::TraitNotFound); } - let authorised = is_authorised( + let Some(auth) = auth::check( auth_server_url, token, &pf.name, @@ -455,11 +428,11 @@ fn get_trait_values_result( pf.confidentiality, &pf.create_time, ) - .map_err(TraitAuthError::Auth)?; - if !authorised { + .map_err(TraitAuthError::Auth)? + else { return Ok(TraitValuesLookup::Forbidden); - } - Ok(TraitValuesLookup::Found(values)) + }; + Ok(TraitValuesLookup::Found(auth, values)) } } } @@ -475,6 +448,7 @@ fn get_trait_values_result( (status = 500, description = "Database error", body = ApiError), (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) ))] +#[gnauth(secured)] pub async fn trait_values( ctx: Ctx, Path((dataset, trait_name)): Path<(String, String)>, @@ -517,14 +491,17 @@ pub async fn trait_values( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - TraitValuesLookup::Found(values) => Ok(Json(ctx.envelope(values).with_next( - &format!( - "/traits/{}/{}", - path_segment(¬_found_dataset), - path_segment(¬_found_trait) - ), - "The trait's metadata", - ))), + TraitValuesLookup::Found(authorized, values) => { + let _: Authorized = authorized; + Ok(Json(ctx.envelope(values).with_next( + &format!( + "/traits/{}/{}", + path_segment(¬_found_dataset), + path_segment(¬_found_trait) + ), + "The trait's metadata", + ))) + } TraitValuesLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", |
