diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-04 15:00:58 +0200 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-04 15:00:58 +0200 |
| commit | dfbf105652140d52e50a96853f0a7ab91fec0776 (patch) | |
| tree | e31e62d0d891dce85be8a09d5094d9d8f06cf7e0 | |
| parent | abb1fe51b1e8cf4079c462b3657e21376d389b99 (diff) | |
| parent | 859a86bf39df6eafa6988215cb84556fc9623ea0 (diff) | |
| download | genenetwork4-dfbf105652140d52e50a96853f0a7ab91fec0776.tar.gz | |
Merge branch 'gn-auth'
| -rw-r--r-- | Cargo.lock | 297 | ||||
| -rw-r--r-- | Cargo.toml | 4 | ||||
| -rw-r--r-- | RELEASE_NOTES.md | 63 | ||||
| -rw-r--r-- | docs/gn-auth.md | 102 | ||||
| -rw-r--r-- | guix.scm | 31 | ||||
| -rw-r--r-- | rust-package.scm | 122 | ||||
| -rw-r--r-- | src/auth.rs | 468 | ||||
| -rw-r--r-- | src/config.rs | 20 | ||||
| -rw-r--r-- | src/error.rs | 2 | ||||
| -rw-r--r-- | src/lib.rs | 25 | ||||
| -rw-r--r-- | src/routes/datasets.rs | 106 | ||||
| -rw-r--r-- | test/python/test_dataset_probeset_info.py | 88 | ||||
| -rw-r--r-- | tests/auth.rs | 163 | ||||
| -rw-r--r-- | tests/common/mod.rs | 49 | ||||
| -rw-r--r-- | tests/dataset_probeset_info.rs | 111 |
15 files changed, 1575 insertions, 76 deletions
diff --git a/Cargo.lock b/Cargo.lock index 0e40688..e02c094 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -88,6 +88,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -136,12 +142,51 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fc4bff745c9b4c7fb1e97b25d13153da2bc7796260141df62378998d070207f" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] name = "cpufeatures" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -220,6 +265,15 @@ dependencies = [ ] [[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] name = "derive_utils" version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -252,12 +306,27 @@ dependencies = [ ] [[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] name = "flate2" version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -265,6 +334,7 @@ checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -321,12 +391,14 @@ version = "0.1.0" dependencies = [ "axum", "http-body-util", + "jsonwebtoken", "mysql", "serde", "serde_json", "tokio", "tower", "tower-http", + "ureq", "utoipa", "utoipa-axum", ] @@ -343,6 +415,19 @@ dependencies = [ [[package]] name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" @@ -603,6 +688,21 @@ dependencies = [ ] [[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] name = "libc" version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -615,6 +715,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] name = "log" version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -656,9 +762,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -712,7 +818,7 @@ version = "0.35.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbb9f371618ce723f095c61fbcdc36e8936956d2b62832f9c7648689b338e052" dependencies = [ - "base64", + "base64 0.22.1", "bitflags", "btoi", "byteorder", @@ -753,6 +859,12 @@ dependencies = [ ] [[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] name = "num-integer" version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -788,7 +900,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -814,6 +926,12 @@ dependencies = [ ] [[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] name = "proc-macro-crate" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -904,6 +1022,55 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1010,12 +1177,30 @@ dependencies = [ ] [[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] +name = "simple_asn1" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1060,6 +1245,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] name = "syn" version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1128,6 +1319,37 @@ dependencies = [ ] [[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] name = "tinystr" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1276,6 +1498,44 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] name = "url" version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1288,6 +1548,12 @@ dependencies = [ ] [[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] name = "utf8_iter" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1408,6 +1674,15 @@ dependencies = [ ] [[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1429,7 +1704,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1592,6 +1867,12 @@ dependencies = [ ] [[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] name = "zerotrie" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1625,6 +1906,12 @@ dependencies = [ ] [[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/Cargo.toml b/Cargo.toml index 7744bbb..0ddfa34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,14 +5,16 @@ edition = "2024" [dependencies] axum = "0.8.9" +jsonwebtoken = "9.3.1" mysql = { version = "26.0.1", default-features = false, features = ["minimal-rust", "derive"] } serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] } tower-http = { version = "0.7.1", features = ["request-id", "util"] } +ureq = { version = "3.2.1", features = ["json"] } utoipa = { version = "5.5.0", features = ["axum_extras"] } utoipa-axum = "0.2.0" [dev-dependencies] http-body-util = "0.1.5" -serde_json = "1.0.151" tower = { version = "0.5.3", features = ["util"] } diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..ca1eef7 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,63 @@ +# Release Notes + +## Unreleased (`gn-auth` branch) + +Work towards securing endpoints with per-user tokens issued by +gn-auth. Not all endpoints will require a token -- see +`docs/gn-auth.md`. + +### Added + +- `docs/gn-auth.md`: how gn-auth works from a client's perspective -- + tokens are RS256 JWTs verified locally via `GET /auth/public-jwks` + (no per-request call to gn-auth needed), and resource-scoped + authorization (e.g. "can this user do X on InbredSet Y") via + `GET /auth/resource/populations/resource-id/...` followed by + `POST /auth/resource/authorisation`, mirroring + `genenetwork3/gn3/api/case_attributes.py`. +- `src/auth.rs`: `AuthToken`, an Axum extractor that verifies a bearer + token's RS256 signature and standard time claims against a cached, + periodically-refreshed JWKS; `is_publicly_readable(public, + confidentiality)`, matching GeneNetwork2's own threshold for whether + a dataset needs authorization at all; and `authorise(...)`, wrapping + gn-auth's resource-authorization check with a short-lived + per-(user, resource) cache. `tests/auth.rs` runs the whole flow + (including the cache) against a real gn-auth instance. +- `jsonwebtoken` (RS256 verification) and `ureq` (gn-auth's HTTP API) + as new dependencies; `AUTH_SERVER_URL` as a new `Config` key, + matching GeneNetwork3's own config key of the same name. +- `is_publicly_readable` also treats a dataset older than 5 years as + public, regardless of its `public`/`confidentiality` flags. +- `auth::authorise_trait`, wrapping `POST /auth/data/authorisation` + (the `"Dataset::Trait"`-keyed equivalent of `authorise`), for data + addressed by a `(dataset, probeset)` pair rather than a resource id. +- `GET /datasets/{dataset}/probesets/{probeset}` now requires a valid + token unconditionally, and -- for a dataset that isn't publicly + readable -- checks `group:resource:view-resource` via + `authorise_trait`, returning 403 (not 404) when denied and 502 if + gn-auth itself couldn't be reached. See docs/gn-auth.md. + +### Not yet done + +- Deciding which other endpoints should require a token, and which + gn-auth privilege each should check -- only + `dataset_probeset_info` is wired so far; its sibling + `dataset_probeset_values` is not. + +### Found and fixed upstream, in gn-auth + +While standing up a from-scratch gn-auth instance to test against (no +prior JWKs/users/sysadmins), four bugs surfaced that blocked this +integration; see gn-auth's own `RELEASE_NOTES.md` for details: + +- A freshly-started gn-auth could reject every token for up to 6 hours + (stale/empty JWKS cache). +- gn-auth's own `flask init-dev-clients` dev client could not + authenticate at all (unhashed client secret). +- `POST /auth/resource/authorisation` -- the endpoint this integration + depends on -- crashed with a 500 on every fresh deployment. +- The same endpoint also crashed (instead of degrading to the + anonymous view, as it does for a missing token) on an invalid bearer + token. + +All four are fixed on gn-auth's `fix-fresh-deployment-bugs` branch. diff --git a/docs/gn-auth.md b/docs/gn-auth.md index 42ff910..c33dc54 100644 --- a/docs/gn-auth.md +++ b/docs/gn-auth.md @@ -185,14 +185,96 @@ has many more (`/auth/role/...`, `/auth/user/...`, genenetwork4 doesn't need to talk to gn-auth for every request -- only for the two things above: verifying a presented token's signature (cache the JWKS, refresh periodically, don't refetch per-request), and --- for endpoints that should be scoped to a specific group/species -- -asking gn-auth what that token's holder is allowed to do on that -resource. Endpoints with no sensitive data behind them don't need to -call gn-auth at all. - -This document describes the mechanism; implementing it in Rust -- -likely a custom Axum extractor that verifies the JWT (e.g. via the -`jsonwebtoken` or `josekit` crate for RS256) and yields the resolved -user to handlers that opt in, so endpoints that don't need auth aren't -forced to go through it -- is still to be done. +-- for data that isn't public -- asking gn-auth what that token's +holder is allowed to do on a specific resource. Endpoints with no +sensitive data behind them don't need to call gn-auth at all. + +Whether data "is public" is answered by GeneNetwork's own schema, not +by asking gn-auth: GeneNetwork2 treats a dataset (`ProbeSetFreeze`, +`PublishFreeze`, `GenoFreeze`) as public exactly when +`public > 0 AND confidentiality < 1` (`wqflask/api/router.py`, used +consistently throughout GN2/GN3). `InbredSet`/group rows carry a +`public` column too, but GN2 never actually filters on it anywhere -- +it's informational only there -- so groups/species endpoints need no +gating at all, matching GN2's own behavior. For data that *is* public +by this test, still require a valid token (don't skip verification +entirely), but skip the resource-authorization call to gn-auth -- one +less network round trip for what is, in practice, most of the data. + +A dataset older than 5 years is treated as public too, regardless of +its `public`/`confidentiality` flags -- a confidentiality embargo isn't +meant to last forever. This isn't a GN2 convention, just a rule applied +here, based on `CreateTime`. + +### Resolving a probeset/trait to a gn-auth resource + +A group/`InbredSet` resource's id is resolved via +`GET /auth/resource/populations/resource-id/<speciesid>/<inbredsetid>` +(above). A probeset/trait doesn't have an equivalent "resolve this id +to a resource id" endpoint -- instead, call +`POST /auth/data/authorisation` directly with a `"Dataset::Trait"` +string (e.g. `{"traits": ["HC_M2_0606_P::1442370_at"]}`); gn-auth +resolves the resource itself, internally, via a join on +`linked_mrna_data.dataset_name` (`gn_auth/auth/authorisation/data/ +mrna.py`'s `resources_by_datasets_and_traits`). If the trait's dataset +was never linked to a gn-auth resource at all (the common case for +data nobody has ever restricted), gn-auth answers with a 404, which +genenetwork4 treats the same as "no privileges" -- not a request +failure. + +### Implemented, in `src/auth.rs` + +- `AuthToken`, an Axum extractor (`impl FromRequestParts`): verifies a + bearer token's RS256 signature and standard time claims (`exp`/`nbf`, + checked when present -- gn-auth itself treats them as optional, + confirmed against its own validator) against a cached, periodically + refreshed JWKS. Add it as a handler parameter to require a valid + token; omit it for endpoints that don't need one. +- `is_publicly_readable(public, confidentiality, create_time)`: the GN2 + threshold above, plus the 5-year embargo-age rule, as a plain + function a handler calls on its own fetched row. +- `authorise(auth_server_url, token, resource_id, privilege)`: the two + gn-auth calls (resource-id resolution is the caller's job -- + `GET /auth/resource/populations/resource-id/...` -- `authorise` + itself only wraps `POST /auth/resource/authorisation`), with the + per-(user, resource) answer cached briefly so repeated requests for + the same resource by the same user don't each cost a round trip. +- `authorise_trait(auth_server_url, token, dataset_name, trait_name, + privilege)`: the trait-keyed equivalent of `authorise`, wrapping + `POST /auth/data/authorisation` -- for data addressed by a + `(dataset, probeset)` pair rather than a resource id directly. Same + caching as `authorise`. +- `tests/auth.rs` runs all of this against a real gn-auth instance + (set `GN4_TEST_AUTH_TOKEN`/`GN4_TEST_RESOURCE_ID`; skips otherwise). + +### Wired into a route: `GET /datasets/{dataset}/probesets/{probeset}` + +This is the first (and so far only) endpoint gated this way: + +- An `AuthToken` is required unconditionally -- every caller needs a + valid token, even for public data. +- If the dataset is publicly readable (`is_publicly_readable`), the + probeset's metadata is returned with no further gn-auth call. +- Otherwise, `authorise_trait(..., "group:resource:view-resource")` is + called; a `false` result (including the "never linked, so no + privileges" 404 case above) is a 403, not a 404 -- the dataset and + probeset both exist, the caller just isn't allowed to see them. +- A failure to reach/parse gn-auth's answer is a 502, distinct from a + 403 (denied) or a 500 (this service's own database error) -- see + `tests/dataset_probeset_info.rs` for all of these cases exercised + against a real gn-auth instance. + +Which other endpoints should require a token, and which privilege each +should check, remains a separate decision, not yet made here. + +### Found wrong in gn-auth while building this + +Four bugs in gn-auth itself blocked this integration before they were +fixed (see gn-auth's own `RELEASE_NOTES.md` and its +`fix-fresh-deployment-bugs` branch): a JWKS cache that could stay empty +for hours after a fresh deployment's first token was issued, a dev +client whose secret was never hashed so it could never authenticate, +`public_resources()` crashing on every fresh deployment, and +`POST /auth/resource/authorisation` crashing (instead of degrading to +the anonymous view) on an invalid rather than missing bearer token. diff --git a/guix.scm b/guix.scm index 57c7e3f..6ee2b78 100644 --- a/guix.scm +++ b/guix.scm @@ -59,6 +59,7 @@ rust-axum-0.8.9 rust-axum-core-0.5.6 rust-base64-0.22.1 + rust-base64-0.23.1 rust-bitflags-2.13.2 rust-block-buffer-0.10.4 rust-btoi-0.4.3 @@ -66,7 +67,10 @@ rust-bumpalo-3.20.3 rust-byteorder-1.5.0 rust-bytes-1.12.1 + rust-cc-1.6.0 rust-cfg-if-1.0.5 + rust-cookie-0.18.2 + rust-cookie-store-0.22.0 rust-cpufeatures-0.2.17 rust-crc32fast-1.5.2 rust-crossbeam-queue-0.3.14 @@ -75,10 +79,13 @@ rust-darling-0.20.11 rust-darling-core-0.20.11 rust-darling-macro-0.20.11 + rust-deranged-0.5.8 rust-derive-utils-0.16.0 rust-digest-0.10.7 rust-displaydoc-0.2.7 + rust-document-features-0.2.12 rust-equivalent-1.0.2 + rust-find-msvc-tools-0.1.14 rust-flate2-1.1.10 rust-fnv-1.0.7 rust-form-urlencoded-1.2.2 @@ -87,6 +94,7 @@ rust-futures-task-0.3.34 rust-futures-util-0.3.34 rust-generic-array-0.14.7 + rust-getrandom-0.2.17 rust-getrandom-0.3.4 rust-getrandom-0.4.3 rust-hashbrown-0.17.1 @@ -112,20 +120,23 @@ rust-io-enum-1.3.0 rust-itoa-1.0.18 rust-js-sys-0.3.106 + rust-jsonwebtoken-9.3.1 rust-libc-0.2.190 rust-litemap-0.8.3 + rust-litrs-1.0.0 rust-log-0.4.34 rust-lru-0.12.5 rust-matchit-0.8.4 rust-memchr-2.8.3 rust-mime-0.3.17 rust-miniz-oxide-0.9.1 - rust-mio-1.2.3 + rust-mio-1.2.4 rust-mysql-26.0.1 rust-mysql-common-0.35.5 rust-mysql-common-derive-0.32.1 rust-named-pipe-0.4.1 rust-num-bigint-0.4.8 + rust-num-conv-0.1.0 rust-num-integer-0.1.47 rust-num-traits-0.2.19 rust-once-cell-1.21.4 @@ -134,6 +145,7 @@ rust-percent-encoding-2.3.2 rust-pin-project-lite-0.2.17 rust-potential-utf-0.1.6 + rust-powerfmt-0.2.0 rust-proc-macro-crate-3.5.0 rust-proc-macro-error-attr2-2.0.0 rust-proc-macro-error2-2.0.1 @@ -144,6 +156,10 @@ rust-regex-1.13.1 rust-regex-automata-0.4.18 rust-regex-syntax-0.8.11 + rust-ring-0.17.14 + rust-rustls-0.23.45 + rust-rustls-pki-types-1.15.1 + rust-rustls-webpki-0.103.15 rust-rustversion-1.0.23 rust-ryu-1.0.23 rust-saturating-0.1.0 @@ -155,13 +171,16 @@ rust-serde-urlencoded-0.7.1 rust-sha1-0.10.7 rust-sha2-0.10.9 + rust-shlex-2.0.1 rust-simd-adler32-0.3.10 + rust-simple-asn1-0.6.3 rust-slab-0.4.12 rust-smallvec-1.16.2 rust-socket2-0.5.10 rust-socket2-0.6.5 rust-stable-deref-trait-1.2.1 rust-strsim-0.11.1 + rust-subtle-2.6.1 rust-syn-2.0.119 rust-syn-3.0.6 rust-sync-wrapper-1.0.2 @@ -169,6 +188,9 @@ rust-termcolor-1.4.1 rust-thiserror-2.0.21 rust-thiserror-impl-2.0.21 + rust-time-0.3.45 + rust-time-core-0.1.7 + rust-time-macros-0.2.25 rust-tinystr-0.8.4 rust-tokio-1.53.2 rust-tokio-macros-2.7.2 @@ -184,8 +206,12 @@ rust-twox-hash-2.1.4 rust-typenum-1.20.1 rust-unicode-ident-1.0.26 + rust-untrusted-0.9.0 + rust-ureq-3.4.2 + rust-ureq-proto-0.6.4 rust-url-2.5.8 rust-utf8-iter-1.0.4 + rust-utf8-zero-0.8.1 rust-utoipa-5.5.0 rust-utoipa-axum-0.2.0 rust-utoipa-gen-5.5.0 @@ -197,6 +223,7 @@ rust-wasm-bindgen-macro-0.2.129 rust-wasm-bindgen-macro-support-0.2.129 rust-wasm-bindgen-shared-0.2.129 + rust-webpki-roots-1.0.9 rust-winapi-0.3.9 rust-winapi-i686-pc-windows-gnu-0.4.0 rust-winapi-util-0.1.11 @@ -220,9 +247,11 @@ rust-yoke-derive-0.8.4 rust-zerofrom-0.1.8 rust-zerofrom-derive-0.1.8 + rust-zeroize-1.9.0 rust-zerotrie-0.2.5 rust-zerovec-0.11.8 rust-zerovec-derive-0.11.6 + rust-zlib-rs-0.6.8 rust-zmij-1.0.23)) (home-page "https://github.com/genenetwork/genenetwork4") (synopsis "GeneNetwork API server") diff --git a/rust-package.scm b/rust-package.scm index e1c4ed4..9e1b6e3 100644 --- a/rust-package.scm +++ b/rust-package.scm @@ -36,6 +36,10 @@ (crate-source "base64" "0.22.1" "1imqzgh7bxcikp5vx3shqvw9j09g9ly0xr0jma0q66i52r7jbcvj")) +(define-public rust-base64-0.23.1 + (crate-source "base64" "0.23.1" + "19cdw4vh3d8qndbxjmbf6ddvmpicyddg704b4fjxjlchz7ncs1xc")) + (define-public rust-bitflags-2.13.2 (crate-source "bitflags" "2.13.2" "01hbgjwvid66850fzi76mvn5f2bqycx6sf165ng1kfjqq9bl1v9x")) @@ -64,10 +68,22 @@ (crate-source "bytes" "1.12.1" "017z19dpg4f942h051m7bpnzcgng042hhcpd7bmg7bjjqd42lrgw")) +(define-public rust-cc-1.6.0 + (crate-source "cc" "1.6.0" + "0c3n82hdi355xa6z9x4zgnpjwsh1szkkcs0zl8q8nl5ggk874j7p")) + (define-public rust-cfg-if-1.0.5 (crate-source "cfg-if" "1.0.5" "0026j56901nzjraap3da0a8njw42j66zcxnn6s2s9aa5bcblhxjf")) +(define-public rust-cookie-0.18.2 + (crate-source "cookie" "0.18.2" + "11rg5wdxnqy4hfa771zyd1hiw59mb7pg1llnlkg3q73908v3wdqs")) + +(define-public rust-cookie-store-0.22.0 + (crate-source "cookie_store" "0.22.0" + "0zr0f389i29pcbgl2096jrvvr8ix2l9mvclp3vxwgd698pvvzi1z")) + (define-public rust-cpufeatures-0.2.17 (crate-source "cpufeatures" "0.2.17" "10023dnnaghhdl70xcds12fsx2b966sxbxjq5sxs49mvxqw5ivar")) @@ -100,6 +116,10 @@ (crate-source "darling_macro" "0.20.11" "1bbfbc2px6sj1pqqq97bgqn6c8xdnb2fmz66f7f40nrqrcybjd7w")) +(define-public rust-deranged-0.5.8 + (crate-source "deranged" "0.5.8" + "0711df3w16vx80k55ivkwzwswziinj4dz05xci3rvmn15g615n3w")) + (define-public rust-derive-utils-0.16.0 (crate-source "derive_utils" "0.16.0" "08sg4dwc3qpd5zvcaylqj2h0kcjbv559711yhx7ph35j7p9sa1fw")) @@ -112,10 +132,18 @@ (crate-source "displaydoc" "0.2.7" "1a42mwpgpwcqq2qqgkcc630wvsc2p2dkmgacjnclginwfz9js8y6")) +(define-public rust-document-features-0.2.12 + (crate-source "document-features" "0.2.12" + "0qcgpialq3zgvjmsvar9n6v10rfbv6mk6ajl46dd4pj5hn3aif6l")) + (define-public rust-equivalent-1.0.2 (crate-source "equivalent" "1.0.2" "03swzqznragy8n0x31lqc78g2af054jwivp7lkrbrc0khz74lyl7")) +(define-public rust-find-msvc-tools-0.1.14 + (crate-source "find-msvc-tools" "0.1.14" + "112ljldlv150fpl8xr2jl5czg51k3kdfn6cy5fqdsvkl14sgpp5f")) + (define-public rust-flate2-1.1.10 (crate-source "flate2" "1.1.10" "1jvd2cl8j5hyf8imi62y1x7gwzz1hajirni0801yxhds1qp4wqvf")) @@ -148,6 +176,10 @@ (crate-source "generic-array" "0.14.7" "16lyyrzrljfq424c3n8kfwkqihlimmsg5nhshbbp48np3yjrqr45")) +(define-public rust-getrandom-0.2.17 + (crate-source "getrandom" "0.2.17" + "1l2ac6jfj9xhpjjgmcx6s1x89bbnw9x6j9258yy6xjkzpq0bqapz")) + (define-public rust-getrandom-0.3.4 (crate-source "getrandom" "0.3.4" "1zbpvpicry9lrbjmkd4msgj3ihff1q92i334chk7pzf46xffz7c9")) @@ -249,6 +281,10 @@ (crate-source "js-sys" "0.3.106" "1icwmpjw54lb7vg5926k5y4y5jbiih0zxhwgjwnzn475v90xk0vq")) +(define-public rust-jsonwebtoken-9.3.1 + (crate-source "jsonwebtoken" "9.3.1" + "1plx2qf8mpg96bpsa1aalfsf4jvgwcnl6i37x7masysk91xcr1ss")) + (define-public rust-libc-0.2.190 (crate-source "libc" "0.2.190" "0y5yap4bfp7rfsldcbk9pb5alcgygca5xn1n2pmh181zdpf3spff")) @@ -257,6 +293,10 @@ (crate-source "litemap" "0.8.3" "1bpgpj87560hmckh3875fbahpmfxbk4g8pzns84h3ykf3nfx3na7")) +(define-public rust-litrs-1.0.0 + (crate-source "litrs" "1.0.0" + "14p0kzzkavnngvybl88nvfwv031cc2qx4vaxpfwsiifm8grdglqi")) + (define-public rust-log-0.4.34 (crate-source "log" "0.4.34" "1ihkzn0m33ab79fcl4mkb04n5iwqzbxzyw7l7hazqkffaqzbvy7r")) @@ -281,9 +321,9 @@ (crate-source "miniz_oxide" "0.9.1" "0k2bgjzk2sbsynpsv4wizwxbqp6vs7g08y5anbkrh3l6a15bqgxn")) -(define-public rust-mio-1.2.3 - (crate-source "mio" "1.2.3" - "1n5ryp7j5fga38z7php5yy9k7ia24rp6cl9gm27zwar6khz4862b")) +(define-public rust-mio-1.2.4 + (crate-source "mio" "1.2.4" + "1vl6px9zy0pwhlwnw3cknsqyzkg8bcpiwiq4cgicf2fwgywfv20p")) (define-public rust-mysql-26.0.1 (crate-source "mysql" "26.0.1" @@ -305,6 +345,10 @@ (crate-source "num-bigint" "0.4.8" "0ry3xjal8f5xhdinani268ci13h14mf7j4w0y1gflfzhw3knk7n8")) +(define-public rust-num-conv-0.1.0 + (crate-source "num-conv" "0.1.0" + "1ndiyg82q73783jq18isi71a7mjh56wxrk52rlvyx0mi5z9ibmai")) + (define-public rust-num-integer-0.1.47 (crate-source "num-integer" "0.1.47" "02z1p3azy6p10n99skrab4a6hhfd4amf2i9gm8sxqd1p9dfxkqkw")) @@ -337,6 +381,10 @@ (crate-source "potential_utf" "0.1.6" "0qbndl2fpphq7mph41m11vaixs05xrh1s451wxlgap4fdnybjgnq")) +(define-public rust-powerfmt-0.2.0 + (crate-source "powerfmt" "0.2.0" + "14ckj2xdpkhv3h6l5sdmb9f1d57z8hbfpdldjc2vl5givq2y77j3")) + (define-public rust-proc-macro-crate-3.5.0 (crate-source "proc-macro-crate" "3.5.0" "0kv1g1d1zjwxlgcaba2qlshzyy32j03xic8rskqlcr5mnblsfyz6")) @@ -377,6 +425,22 @@ (crate-source "regex-syntax" "0.8.11" "1m25h5q2wp976fb9gc3dsc9l99svcvd5cri8lncb51c46ydgzxnn")) +(define-public rust-ring-0.17.14 + (crate-source "ring" "0.17.14" + "1dw32gv19ccq4hsx3ribhpdzri1vnrlcfqb2vj41xn4l49n9ws54")) + +(define-public rust-rustls-0.23.45 + (crate-source "rustls" "0.23.45" + "0d6n90q52x5cjyxb6bwcnf9hwg6yb31cwr63rk8n5yfjqwqxfh8d")) + +(define-public rust-rustls-pki-types-1.15.1 + (crate-source "rustls-pki-types" "1.15.1" + "15hakk4pcvr5278cazgw9qf2r7gdg09rg5pivbyd3dbyih12aj9g")) + +(define-public rust-rustls-webpki-0.103.15 + (crate-source "rustls-webpki" "0.103.15" + "1hhanq3lz384v4nccacnjfwsyy99n3yc6m6iw8kljz8yicfwzhzk")) + (define-public rust-rustversion-1.0.23 (crate-source "rustversion" "1.0.23" "07z2a843fs80fawwflj9jwn49k9b0bd0dhhbvy0ar69vaxd72m6g")) @@ -421,10 +485,18 @@ (crate-source "sha2" "0.10.9" "10xjj843v31ghsksd9sl9y12qfc48157j1xpb8v1ml39jy0psl57")) +(define-public rust-shlex-2.0.1 + (crate-source "shlex" "2.0.1" + "1fjsll1cd7d2bcpdij9kd6w62rpbc7qqzvydvs021vsmr1cxvypq")) + (define-public rust-simd-adler32-0.3.10 (crate-source "simd-adler32" "0.3.10" "1sny4y2qa5mwyxx5x59ln2p02vsdh92004njlslnx98imjc9489s")) +(define-public rust-simple-asn1-0.6.3 + (crate-source "simple_asn1" "0.6.3" + "1fz8842yya5qrbdsgcij1ysw0zlrcdwqcrs6p2cqr73ja0gn6zr9")) + (define-public rust-slab-0.4.12 (crate-source "slab" "0.4.12" "1xcwik6s6zbd3lf51kkrcicdq2j4c1fw0yjdai2apy9467i0sy8c")) @@ -449,6 +521,10 @@ (crate-source "strsim" "0.11.1" "0kzvqlw8hxqb7y598w1s0hxlnmi84sg5vsipp3yg5na5d1rvba3x")) +(define-public rust-subtle-2.6.1 + (crate-source "subtle" "2.6.1" + "14ijxaymghbl1p0wql9cib5zlwiina7kall6w7g89csprkgbvhhk")) + (define-public rust-syn-2.0.119 (crate-source "syn" "2.0.119" "15vjy620l91a3q4n4f4gzhnflmdr6pnm38v2m6cpk86i8av32a47")) @@ -477,6 +553,18 @@ (crate-source "thiserror-impl" "2.0.21" "0945n8agp7kg6n6b35yyjb4g5xv2q22vrw15h6jj1nw76a99flgy")) +(define-public rust-time-0.3.45 + (crate-source "time" "0.3.45" + "1gdag88agck220k6fxbgb7gsnr2r14n33sxzm5db9zfp6gy45r7r")) + +(define-public rust-time-core-0.1.7 + (crate-source "time-core" "0.1.7" + "1jilglvr6m6h2iidnvdp3zfahck9wa7kw64rslk79v1izncfwdlb")) + +(define-public rust-time-macros-0.2.25 + (crate-source "time-macros" "0.2.25" + "1pg3zrqyvjcy1nh470mdw7qxwwq6zmwq3f1dlp11mxlv4k8m5rbi")) + (define-public rust-tinystr-0.8.4 (crate-source "tinystr" "0.8.4" "0hzncw8rgk4syla79qscfml46jm7ll1zdp7kdacc42cj8n8prqmi")) @@ -537,10 +625,26 @@ (crate-source "unicode-ident" "1.0.26" "0m3915ipi4zz7isncf5k1dz47ys0nq9j7l4l2n2rm03zaxwg8ifj")) +(define-public rust-untrusted-0.9.0 + (crate-source "untrusted" "0.9.0" + "1ha7ib98vkc538x0z60gfn0fc5whqdd85mb87dvisdcaifi6vjwf")) + +(define-public rust-ureq-3.4.2 + (crate-source "ureq" "3.4.2" + "1z6pmhf27s54f3sn2ja1rnqsrnbnjq2lr5xzpl5nwwmpx45w4yls")) + +(define-public rust-ureq-proto-0.6.4 + (crate-source "ureq-proto" "0.6.4" + "1gl32l71mdak562scwp66vpsjr894bbbvdk1ix2rwmnarird2vzq")) + (define-public rust-url-2.5.8 (crate-source "url" "2.5.8" "1v8f7nx3hpr1qh76if0a04sj08k86amsq4h8cvpw6wvk76jahrzz")) +(define-public rust-utf8-zero-0.8.1 + (crate-source "utf8-zero" "0.8.1" + "0vjsmwd1k2wwlsn1phi7mrcjxn4bv8fzk24caxyaw2slr51s1h5q")) + (define-public rust-utf8-iter-1.0.4 (crate-source "utf8_iter" "1.0.4" "1gmna9flnj8dbyd8ba17zigrp9c4c3zclngf5lnb5yvz1ri41hdn")) @@ -589,6 +693,10 @@ (crate-source "wasm-bindgen-shared" "0.2.129" "1ilmp5d3sl8lrq9djhcs90gk66yvk8mgwk4sfrvpvkd75b2wkw13")) +(define-public rust-webpki-roots-1.0.9 + (crate-source "webpki-roots" "1.0.9" + "0apja04243wz3vi26pqjg4sq8cqaac66prj490sgb1crlc4rvkbx")) + (define-public rust-winapi-0.3.9 (crate-source "winapi" "0.3.9" "06gl025x418lchw1wxj64ycr7gha83m44cjr5sarhynd9xkrm0sw")) @@ -683,6 +791,10 @@ (crate-source "zerofrom-derive" "0.1.8" "0jhdy4p9c6ja3dynsdck14g2iilq8ai5ch6nsi455x67ys1lcnzp")) +(define-public rust-zeroize-1.9.0 + (crate-source "zeroize" "1.9.0" + "0kpnij2v1ig6g2mhc0bnci0lrdfdhiq40afbc0fahajqc9jiag71")) + (define-public rust-zerotrie-0.2.5 (crate-source "zerotrie" "0.2.5" "0gss16krjzk22m57dz5hkdjg99ibj6pa41qr68na7w1jpp1nk8jf")) @@ -695,6 +807,10 @@ (crate-source "zerovec-derive" "0.11.6" "1ni5j8v99x3fcf3l8kp64b7aq4vf8y22jshfq74xs9mxkp1nzprl")) +(define-public rust-zlib-rs-0.6.8 + (crate-source "zlib-rs" "0.6.8" + "04j158293bx73kv5pj1i89ai411q7fxc9zwk3wkpqgb9gj7fas5j")) + (define-public rust-zmij-1.0.23 (crate-source "zmij" "1.0.23" "06zwri21nnrl34rwinmvbciap8yk1mrl8qfg9pff7lgspc56sri9")) diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..d9cc8c4 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,468 @@ +//! Verifying bearer tokens issued by gn-auth, and checking gn-auth +//! resource authorization for data that isn't public. See +//! docs/gn-auth.md for the mechanism this implements. +//! +//! Two independent things happen here, and most endpoints only need +//! the first: +//! +//! - **Token verification** ([`AuthToken`], an extractor): checks a +//! bearer token's RS256 signature and standard time claims against +//! gn-auth's JWKS (`GET /auth/public-jwks`), cached and refreshed +//! periodically rather than fetched per request. Add `AuthToken` as +//! a handler parameter to require a valid token; handlers that +//! don't need one simply omit it -- this is what makes auth +//! opt-in per route rather than a blanket gate. +//! - **Resource authorization** ([`authorise`]): for data that isn't +//! public (see [`is_publicly_readable`], matching GeneNetwork2's own +//! `public > 0 AND confidentiality < 1` convention), asks gn-auth +//! whether this token's holder has a given privilege on a specific +//! resource (`POST /auth/resource/authorisation`), caching the +//! per-(user, resource) answer briefly so repeated requests for the +//! same resource don't each cost a round trip to gn-auth. + +use axum::extract::FromRequestParts; +use axum::http::StatusCode; +use axum::http::request::Parts; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use crate::config::Config; +use crate::error::ApiError; + +fn unauthorized(detail: impl Into<String>) -> ApiError { + ApiError::new( + StatusCode::UNAUTHORIZED, + "invalid_token", + "Invalid or missing token", + detail.into(), + "authentication", + ) +} + +/// A verified caller: the token was signed by gn-auth and its +/// standard time claims (exp/nbf, when present -- gn-auth itself +/// treats them as optional, not every token carries them) checked. +/// Does not by itself mean the caller is authorized for anything; see +/// [`authorise`] for that. +#[derive(Debug, Clone)] +pub struct AuthToken { + /// The token subject (gn-auth user id). + pub sub: String, + /// Space-separated OAuth2 scopes, e.g. "profile group resource". + pub scope: String, + /// The raw bearer token, forwarded as-is to gn-auth's own + /// authorization endpoints on the caller's behalf. + pub raw: String, +} + +#[derive(Deserialize)] +struct Claims { + sub: String, + #[serde(default)] + scope: String, +} + +impl<S: Send + Sync> FromRequestParts<S> for AuthToken { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { + let header = parts + .headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .ok_or_else(|| unauthorized("Missing Authorization header."))?; + let token = header + .strip_prefix("Bearer ") + .ok_or_else(|| unauthorized("Authorization header must be a Bearer token."))?; + + let config = Config::load(); + let claims = + verify(token, &config.auth_server_url).map_err(|e| unauthorized(e.to_string()))?; + Ok(AuthToken { + sub: claims.sub, + scope: claims.scope, + raw: token.to_string(), + }) + } +} + +/// Verify `token`'s signature and standard time claims against +/// `auth_server_url`'s JWKS. +fn verify(token: &str, auth_server_url: &str) -> Result<Claims, String> { + let keys = jwks(auth_server_url)?; + if keys.is_empty() { + return Err("gn-auth has no signing keys published yet.".to_string()); + } + + let mut validation = Validation::new(Algorithm::RS256); + // gn-auth's own resource-server validator treats `exp` as + // non-essential (not every token carries one), so don't demand it + // either -- only validate it (below) when a token does have one. + validation.required_spec_claims.clear(); + validation.validate_exp = true; + validation.validate_nbf = true; + validation.set_issuer(&[auth_server_url]); + + let mut last_error = "No signing key matched this token.".to_string(); + for key in &keys { + match decode::<Claims>(token, key, &validation) { + Ok(data) => return Ok(data.claims), + Err(e) => last_error = e.to_string(), + } + } + Err(last_error) +} + +/// Above this, a cached JWKS/authorization answer is refetched rather +/// than reused. +const JWKS_TTL: Duration = Duration::from_secs(3600); +const AUTHORISATION_TTL: Duration = Duration::from_secs(60); + +#[derive(Deserialize)] +struct JwksDocument { + jwks: Vec<Jwk>, +} + +#[derive(Deserialize)] +struct Jwk { + n: String, + e: String, +} + +/// The shared, periodically-refreshed JWKS cache, keyed by +/// auth_server_url (in practice there is only ever one configured, +/// but tests exercise more than one gn-auth instance). +fn jwks(auth_server_url: &str) -> Result<Vec<DecodingKey>, String> { + static CACHE: OnceLock<Mutex<HashMap<String, (Instant, Vec<DecodingKey>)>>> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let mut guard = cache.lock().unwrap(); + if let Some((fetched_at, keys)) = guard.get(auth_server_url) { + if fetched_at.elapsed() < JWKS_TTL { + return Ok(keys.clone()); + } + } + let keys = fetch_jwks(auth_server_url)?; + guard.insert(auth_server_url.to_string(), (Instant::now(), keys.clone())); + Ok(keys) +} + +fn fetch_jwks(auth_server_url: &str) -> Result<Vec<DecodingKey>, String> { + let url = format!("{}/auth/public-jwks", auth_server_url.trim_end_matches('/')); + let doc: JwksDocument = ureq::get(&url) + .call() + .map_err(|e| format!("fetching {url}: {e}"))? + .body_mut() + .read_json() + .map_err(|e| format!("parsing JWKS from {url}: {e}"))?; + doc.jwks + .iter() + .map(|jwk| { + DecodingKey::from_rsa_components(&jwk.n, &jwk.e) + .map_err(|e| format!("invalid JWK: {e}")) + }) + .collect() +} + +/// A dataset older than this is treated as publicly readable +/// regardless of its `public`/`confidentiality` flags. +const PUBLIC_AFTER_YEARS: i64 = 5; + +/// Matches GeneNetwork2's own threshold for whether a dataset is +/// readable without authorization (e.g. `ProbeSetFreeze.public > 0 AND +/// ProbeSetFreeze.confidentiality < 1`, used throughout +/// `wqflask/api/router.py`). `InbredSet`/group rows carry a `public` +/// column too, but GeneNetwork2 never actually filters on it -- it's +/// informational only there -- so this only applies to dataset-level +/// (`*Freeze`) rows, which carry both columns. +/// +/// Additionally, a dataset older than `PUBLIC_AFTER_YEARS` is treated +/// as public regardless of those flags -- confidentiality embargoes +/// are not meant to last forever. `create_time` is the dataset's +/// `CreateTime` column, as `YYYY-MM-DD ...`; if it can't be parsed, +/// this falls back to the flags alone. +pub fn is_publicly_readable(public: u8, confidentiality: u8, create_time: &str) -> bool { + (public > 0 && confidentiality < 1) || is_older_than_public_after_years(create_time) +} + +fn is_older_than_public_after_years(create_time: &str) -> bool { + let Some((year, month, day)) = parse_date_prefix(create_time) else { + return false; + }; + let created_days = days_from_civil(year, month, day); + let now_days = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) { + Ok(since_epoch) => (since_epoch.as_secs() / 86400) as i64, + Err(_) => return false, + }; + now_days - created_days >= PUBLIC_AFTER_YEARS * 365 +} + +/// Parse the `YYYY-MM-DD` prefix of a `CreateTime` value such as +/// `"2015-03-04 00:00:00"`. +fn parse_date_prefix(s: &str) -> Option<(i64, i64, i64)> { + let mut parts = s.get(0..10)?.split('-'); + let year: i64 = parts.next()?.parse().ok()?; + let month: i64 = parts.next()?.parse().ok()?; + let day: i64 = parts.next()?.parse().ok()?; + Some((year, month, day)) +} + +/// Days since the Unix epoch (1970-01-01) for a date in the proleptic +/// Gregorian calendar. Howard Hinnant's `days_from_civil` +/// (https://howardhinnant.github.io/date_algorithms.html) -- used here +/// instead of a date/time crate since this is the only place a date +/// needs parsing. +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146097 + doe - 719468 +} + +#[derive(Serialize)] +struct AuthorisationRequest<'a> { + #[serde(rename = "resource-ids")] + resource_ids: [&'a str; 1], +} + +#[derive(Deserialize)] +struct ResourceAuthorisation { + #[serde(default)] + roles: Vec<Role>, +} + +#[derive(Deserialize)] +struct Role { + privileges: Vec<Privilege>, +} + +#[derive(Deserialize)] +struct Privilege { + privilege_id: String, +} + +/// Ask gn-auth whether `token`'s holder has `privilege` on +/// `resource_id` (`POST /auth/resource/authorisation`; see +/// docs/gn-auth.md). Cached per (sub, resource_id) for +/// `AUTHORISATION_TTL`, so repeated requests for the same resource by +/// the same user don't each cost a round trip to gn-auth -- the +/// fine-grained caching discussed before building this. +/// +/// Only call this for data that is *not* [`is_publicly_readable`]; +/// public data needs a valid token (use [`AuthToken`] alone) but no +/// per-resource check. +pub fn authorise( + auth_server_url: &str, + token: &AuthToken, + resource_id: &str, + privilege: &str, +) -> Result<bool, String> { + let privileges = resource_privileges(auth_server_url, token, resource_id)?; + Ok(privileges.iter().any(|p| p == privilege)) +} + +fn resource_privileges( + auth_server_url: &str, + token: &AuthToken, + resource_id: &str, +) -> Result<Vec<String>, String> { + static CACHE: OnceLock<Mutex<HashMap<(String, String), (Instant, Vec<String>)>>> = + OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let key = (token.sub.clone(), resource_id.to_string()); + + { + let guard = cache.lock().unwrap(); + if let Some((fetched_at, privileges)) = guard.get(&key) { + if fetched_at.elapsed() < AUTHORISATION_TTL { + return Ok(privileges.clone()); + } + } + } + + let privileges = fetch_resource_privileges(auth_server_url, token, resource_id)?; + cache + .lock() + .unwrap() + .insert(key, (Instant::now(), privileges.clone())); + Ok(privileges) +} + +fn fetch_resource_privileges( + auth_server_url: &str, + token: &AuthToken, + resource_id: &str, +) -> Result<Vec<String>, String> { + let url = format!( + "{}/auth/resource/authorisation", + auth_server_url.trim_end_matches('/') + ); + let body = AuthorisationRequest { + resource_ids: [resource_id], + }; + // Not .send_json(): it sets "Content-Type: application/json; + // charset=utf-8", but gn-auth's request_json() (gn_auth/auth/ + // requests.py) compares Content-Type for exact equality with + // "application/json" and silently falls back to query/form + // params (empty here) on anything else, turning this into a 400 + // instead of the JSON body ever being read. + let json = serde_json::to_vec(&body).map_err(|e| format!("encoding request body: {e}"))?; + let mut response: HashMap<String, ResourceAuthorisation> = ureq::post(&url) + .header("Authorization", &format!("Bearer {}", token.raw)) + .content_type("application/json") + .send(json.as_slice()) + .map_err(|e| format!("calling {url}: {e}"))? + .body_mut() + .read_json() + .map_err(|e| format!("parsing authorisation response from {url}: {e}"))?; + Ok(response + .remove(resource_id) + .map(|r| { + r.roles + .into_iter() + .flat_map(|role| role.privileges.into_iter().map(|p| p.privilege_id)) + .collect() + }) + .unwrap_or_default()) +} + +#[derive(Serialize)] +struct DataAuthorisationRequest<'a> { + traits: [&'a str; 1], +} + +#[derive(Deserialize)] +struct DataAuthorisationResponse { + #[serde(default)] + authorisation: Vec<TraitAuthorisation>, +} + +#[derive(Deserialize)] +struct TraitAuthorisation { + #[serde(default)] + privileges: Vec<String>, +} + +/// Ask gn-auth whether `token`'s holder has `privilege` on the trait +/// `dataset_name::trait_name` (`POST /auth/data/authorisation`; see +/// docs/gn-auth.md). This is the dataset/trait-keyed equivalent of +/// [`authorise`], for data addressed by a `(dataset, probeset)` pair +/// rather than a gn-auth resource id directly -- gn-auth resolves the +/// resource itself from the trait's dataset name. Cached per (sub, +/// dataset::trait) for `AUTHORISATION_TTL`, same as [`authorise`]. +/// +/// Only call this for data that is *not* [`is_publicly_readable`]; +/// public data needs a valid token (use [`AuthToken`] alone) but no +/// per-resource check. +pub fn authorise_trait( + auth_server_url: &str, + token: &AuthToken, + dataset_name: &str, + trait_name: &str, + privilege: &str, +) -> Result<bool, String> { + let privileges = trait_privileges(auth_server_url, token, dataset_name, trait_name)?; + Ok(privileges.iter().any(|p| p == privilege)) +} + +fn trait_privileges( + auth_server_url: &str, + token: &AuthToken, + dataset_name: &str, + trait_name: &str, +) -> Result<Vec<String>, String> { + static CACHE: OnceLock<Mutex<HashMap<(String, String), (Instant, Vec<String>)>>> = + OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let key = (token.sub.clone(), format!("{dataset_name}::{trait_name}")); + + { + let guard = cache.lock().unwrap(); + if let Some((fetched_at, privileges)) = guard.get(&key) { + if fetched_at.elapsed() < AUTHORISATION_TTL { + return Ok(privileges.clone()); + } + } + } + + let privileges = fetch_trait_privileges(auth_server_url, token, dataset_name, trait_name)?; + cache + .lock() + .unwrap() + .insert(key, (Instant::now(), privileges.clone())); + Ok(privileges) +} + +fn fetch_trait_privileges( + auth_server_url: &str, + token: &AuthToken, + dataset_name: &str, + trait_name: &str, +) -> Result<Vec<String>, String> { + let url = format!( + "{}/auth/data/authorisation", + auth_server_url.trim_end_matches('/') + ); + let trait_fullname = format!("{dataset_name}::{trait_name}"); + let body = DataAuthorisationRequest { + traits: [&trait_fullname], + }; + // See fetch_resource_privileges for why this isn't .send_json(). + let json = serde_json::to_vec(&body).map_err(|e| format!("encoding request body: {e}"))?; + let sent = ureq::post(&url) + .header("Authorization", &format!("Bearer {}", token.raw)) + .content_type("application/json") + .send(json.as_slice()); + let mut response = match sent { + Ok(response) => response, + // gn-auth answers a trait with no linked resource (i.e. one + // nobody has ever restricted) with a 404, not an empty + // privilege list -- treat it the same as "no privileges" here + // rather than as a request failure. + Err(ureq::Error::StatusCode(404)) => return Ok(Vec::new()), + Err(e) => return Err(format!("calling {url}: {e}")), + }; + let doc: DataAuthorisationResponse = response + .body_mut() + .read_json() + .map_err(|e| format!("parsing authorisation response from {url}: {e}"))?; + Ok(doc + .authorisation + .into_iter() + .flat_map(|t| t.privileges) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_publicly_readable_matches_genenetwork2_threshold() { + let recent = "2024-01-01 00:00:00"; + assert!(is_publicly_readable(1, 0, recent)); + assert!(is_publicly_readable(2, 0, recent)); + assert!(!is_publicly_readable(0, 0, recent)); + assert!(!is_publicly_readable(1, 1, recent)); + } + + #[test] + fn is_publicly_readable_also_true_past_the_embargo_age() { + assert!(is_publicly_readable(0, 1, "2000-01-01 00:00:00")); + assert!(!is_publicly_readable(0, 1, "2024-01-01 00:00:00")); + // Unparseable create_time: fall back to the flags alone. + assert!(!is_publicly_readable(0, 1, "not-a-date")); + } + + #[test] + fn days_from_civil_matches_known_dates() { + assert_eq!(days_from_civil(1970, 1, 1), 0); + assert_eq!(days_from_civil(2000, 3, 1), 11017); + assert_eq!(days_from_civil(1969, 12, 31), -1); + } +} diff --git a/src/config.rs b/src/config.rs index 75adaf2..c403083 100644 --- a/src/config.rs +++ b/src/config.rs @@ -19,6 +19,10 @@ pub struct Config { pub sql_uri: String, /// TCP port to bind. pub port: u16, + /// Base URL of the gn-auth server, e.g. "http://127.0.0.1:8081/". + /// Same AUTH_SERVER_URL config key GeneNetwork3 uses. See + /// docs/gn-auth.md. + pub auth_server_url: String, } impl Config { @@ -32,6 +36,10 @@ impl Config { "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl".to_string(), ); values.insert("GENENETWORK4_PORT".to_string(), "3000".to_string()); + values.insert( + "AUTH_SERVER_URL".to_string(), + "http://127.0.0.1:8081/".to_string(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -43,7 +51,7 @@ impl Config { } // Layer 4: environment wins over everything. - for key in ["SQL_URI", "GENENETWORK4_PORT"] { + for key in ["SQL_URI", "GENENETWORK4_PORT", "AUTH_SERVER_URL"] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); } @@ -54,6 +62,7 @@ impl Config { port: values["GENENETWORK4_PORT"] .parse() .expect("GENENETWORK4_PORT must be a number"), + auth_server_url: values["AUTH_SERVER_URL"].clone(), } } } @@ -87,7 +96,13 @@ mod tests { /// knobs this test asserts on. #[test] fn defaults_apply_with_no_files_or_env() { - for key in ["SQL_URI", "GN4_CONF", "GN4_SECRETS", "GENENETWORK4_PORT"] { + for key in [ + "SQL_URI", + "GN4_CONF", + "GN4_SECRETS", + "GENENETWORK4_PORT", + "AUTH_SERVER_URL", + ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); return; @@ -96,6 +111,7 @@ mod tests { let config = Config::load(); assert!(config.sql_uri.contains("db_webqtl")); assert_eq!(config.port, 3000); + assert_eq!(config.auth_server_url, "http://127.0.0.1:8081/"); } #[test] diff --git a/src/error.rs b/src/error.rs index 49e1574..f96f44b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -14,7 +14,7 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; -#[derive(Serialize, utoipa::ToSchema)] +#[derive(Debug, Serialize, utoipa::ToSchema)] pub struct ApiError { pub r#type: String, pub title: String, diff --git a/src/lib.rs b/src/lib.rs index 6b1d3a6..4013797 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ use utoipa::OpenApi; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +pub mod auth; pub mod config; mod db; mod error; @@ -20,9 +21,31 @@ use error::ApiError; title = "GeneNetwork4 API", description = "GeneNetwork4 REST API", license(name = "AGPL-3.0-or-later") -))] +), modifiers(&SecurityAddon))] struct ApiDoc; +/// Registers the "bearer_token" scheme used by endpoints that require a +/// gn-auth token (see `security(...)` on their `#[utoipa::path]`, e.g. +/// `routes::datasets::dataset_probeset_info`). +struct SecurityAddon; + +impl utoipa::Modify for SecurityAddon { + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { + use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme}; + if let Some(components) = openapi.components.as_mut() { + components.add_security_scheme( + "bearer_token", + SecurityScheme::Http( + HttpBuilder::new() + .scheme(HttpAuthScheme::Bearer) + .bearer_format("JWT") + .build(), + ), + ); + } + } +} + /// Build the application router. Public so integration tests (tests/) and /// the binary (src/main.rs) can both use it without binding a real socket. pub fn app() -> Router { diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs index f1b5671..dd6adc5 100644 --- a/src/routes/datasets.rs +++ b/src/routes/datasets.rs @@ -6,10 +6,15 @@ use axum::extract::{Extension, Path}; use axum::http::StatusCode; use tower_http::request_id::RequestId; +use crate::auth::{self, AuthToken}; +use crate::config::Config; use crate::db; use crate::error::ApiError; use crate::request_id_string; +/// The gn-auth privilege required to view a non-public probeset. +const VIEW_RESOURCE_PRIVILEGE: &str = "group:resource:view-resource"; + #[utoipa::path(get, path = "/datasets/{dataset}", summary = "Get one expression dataset's full record by name or numeric id", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( @@ -66,17 +71,59 @@ enum DatasetProbesetLookup<T> { Found(T), } +/// What looking up and authorizing a probeset trait found. Unlike +/// [`DatasetProbesetLookup`], this also covers the "dataset isn't +/// public and the caller isn't authorized for it" outcome, since +/// `dataset_probeset_info` (unlike `dataset_probeset_values`) gates on +/// gn-auth. +enum DatasetProbesetInfoLookup { + DatasetNotFound, + ProbesetNotFound, + Forbidden, + Found(db::ProbeSetInfo), +} + +/// Either a database error, or a failure to reach/parse gn-auth's +/// answer while checking authorization for a non-public dataset. +enum DatasetAuthError { + Db(mysql::Error), + Auth(String), +} + +impl From<mysql::Error> for DatasetAuthError { + fn from(e: mysql::Error) -> Self { + DatasetAuthError::Db(e) + } +} + fn get_dataset_probeset_info_result( dataset: &str, probeset: &str, -) -> Result<DatasetProbesetLookup<db::ProbeSetInfo>, mysql::Error> { - match db::get_dataset_by_name(dataset)? { - None => Ok(DatasetProbesetLookup::DatasetNotFound), - Some(dataset) => match db::get_dataset_probeset_info(dataset.id, probeset)? { - None => Ok(DatasetProbesetLookup::ProbesetNotFound), - Some(info) => Ok(DatasetProbesetLookup::Found(info)), - }, + auth_server_url: &str, + token: &AuthToken, +) -> Result<DatasetProbesetInfoLookup, DatasetAuthError> { + let dataset = match db::get_dataset_by_name(dataset)? { + None => return Ok(DatasetProbesetInfoLookup::DatasetNotFound), + Some(dataset) => dataset, + }; + let info = match db::get_dataset_probeset_info(dataset.id, probeset)? { + None => return Ok(DatasetProbesetInfoLookup::ProbesetNotFound), + Some(info) => info, + }; + if !auth::is_publicly_readable(dataset.public, dataset.confidentiality, &dataset.create_time) { + let authorised = auth::authorise_trait( + auth_server_url, + token, + &dataset.name, + &info.name, + VIEW_RESOURCE_PRIVILEGE, + ) + .map_err(DatasetAuthError::Auth)?; + if !authorised { + return Ok(DatasetProbesetInfoLookup::Forbidden); + } } + Ok(DatasetProbesetInfoLookup::Found(info)) } #[utoipa::path(get, path = "/datasets/{dataset}/probesets/{probeset}", summary = "Get one expression trait's ProbeSetXRef/ProbeSet metadata", params( @@ -84,18 +131,24 @@ fn get_dataset_probeset_info_result( ("probeset" = String, Path, description = "ProbeSet.Name within the dataset") ), responses( (status = 200, description = "The probeset's ProbeSetXRef/ProbeSet metadata", body = db::ProbeSetInfo), + (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset, or no matching probeset in that dataset", body = ApiError), - (status = 500, description = "Database error", body = ApiError) -))] + (status = 500, description = "Database error", body = ApiError), + (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError) +), security(("bearer_token" = [])))] pub async fn dataset_probeset_info( Extension(request_id): Extension<RequestId>, Path((dataset, probeset)): Path<(String, String)>, + token: AuthToken, ) -> Result<Json<db::ProbeSetInfo>, ApiError> { let rid = request_id_string(&request_id); let not_found_dataset = dataset.clone(); let not_found_probeset = probeset.clone(); - tokio::task::spawn_blocking(move || get_dataset_probeset_info_result(&dataset, &probeset)) - .await + let auth_server_url = Config::load().auth_server_url.clone(); + tokio::task::spawn_blocking(move || { + get_dataset_probeset_info_result(&dataset, &probeset, &auth_server_url, &token) + }) + .await .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, @@ -106,19 +159,38 @@ pub async fn dataset_probeset_info( ) .with_request_id(rid.clone()) })? - .map_err(|e| { - ApiError::new( + .map_err(|e| match e { + DatasetAuthError::Db(e) => ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "database_error", "Database error", e.to_string(), "dataset_probeset_info", ) - .with_request_id(rid.clone()) + .with_request_id(rid.clone()), + DatasetAuthError::Auth(e) => ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + e, + "dataset_probeset_info", + ) + .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetLookup::Found(info) => Ok(Json(info)), - DatasetProbesetLookup::DatasetNotFound => Err(ApiError::new( + DatasetProbesetInfoLookup::Found(info) => Ok(Json(info)), + DatasetProbesetInfoLookup::Forbidden => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!( + "'{not_found_probeset}' in dataset '{not_found_dataset}' is not public, \ + and you are not authorized to view it." + ), + "dataset_probeset_info", + ) + .with_request_id(rid.clone())), + DatasetProbesetInfoLookup::DatasetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "dataset_not_found", "Dataset not found", @@ -126,7 +198,7 @@ pub async fn dataset_probeset_info( "dataset_probeset_info", ) .with_request_id(rid.clone())), - DatasetProbesetLookup::ProbesetNotFound => Err(ApiError::new( + DatasetProbesetInfoLookup::ProbesetNotFound => Err(ApiError::new( StatusCode::NOT_FOUND, "probeset_not_found", "Probeset not found", diff --git a/test/python/test_dataset_probeset_info.py b/test/python/test_dataset_probeset_info.py index cfb219c..569e9f0 100644 --- a/test/python/test_dataset_probeset_info.py +++ b/test/python/test_dataset_probeset_info.py @@ -1,15 +1,22 @@ """Mirrors tests/dataset_probeset_info.rs. Needs a live MariaDB (SQL_URI); skips with a message rather than failing when none is -reachable, same as test_group_by_name.py. +reachable, same as test_group_by_name.py. Also needs a live gn-auth +(AUTH_SERVER_URL) and GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md), since +this endpoint now requires a bearer token; skips when either is +missing. """ import http.client import json +import os import socket import unittest +from urllib.parse import urlparse from server_test_case import HOST, PORT, ServerTestCase +AUTH_SERVER_URL = os.environ.get("AUTH_SERVER_URL", "http://127.0.0.1:8081/") + def database_reachable(): try: @@ -19,18 +26,45 @@ def database_reachable(): return False +def auth_server_reachable(): + url = urlparse(AUTH_SERVER_URL) + conn = http.client.HTTPConnection(url.hostname, url.port or 80, timeout=2) + try: + conn.request("GET", url.path.rstrip("/") + "/auth/public-jwks") + return conn.getresponse().status == 200 + except OSError: + return False + finally: + conn.close() + + +def auth_token(): + return os.environ.get("GN4_TEST_AUTH_TOKEN") + + class DatasetProbesetInfoTest(ServerTestCase): - def test_dataset_probeset_info_returns_gene_annotation(self): + def require_fixtures(self): if not database_reachable(): self.skipTest("no database on 127.0.0.1:3306") + if not auth_token(): + self.skipTest("set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)") + if not auth_server_reachable(): + self.skipTest(f"no gn-auth reachable at {AUTH_SERVER_URL}") + def get(self, path, with_token=True): conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) try: - conn.request("GET", "/datasets/Br_U_0803_M/probesets/100001_at") + headers = {"Authorization": f"Bearer {auth_token()}"} if with_token else {} + conn.request("GET", path, headers=headers) response = conn.getresponse() - body = response.read() + return response, response.read() finally: conn.close() + + def test_dataset_probeset_info_returns_gene_annotation(self): + self.require_fixtures() + + response, body = self.get("/datasets/Br_U_0803_M/probesets/100001_at") self.assertEqual(response.status, 200) info = json.loads(body) @@ -38,17 +72,19 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(info["symbol"], "Cd3g") self.assertIsInstance(info["mean"], float) - def test_dataset_probeset_info_unknown_dataset_returns_404(self): + def test_dataset_probeset_info_without_a_token_returns_401(self): if not database_reachable(): self.skipTest("no database on 127.0.0.1:3306") - conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) - try: - conn.request("GET", "/datasets/not-a-real-dataset/probesets/100001_at") - response = conn.getresponse() - body = response.read() - finally: - conn.close() + response, _body = self.get( + "/datasets/Br_U_0803_M/probesets/100001_at", with_token=False + ) + self.assertEqual(response.status, 401) + + def test_dataset_probeset_info_unknown_dataset_returns_404(self): + self.require_fixtures() + + response, body = self.get("/datasets/not-a-real-dataset/probesets/100001_at") self.assertEqual(response.status, 404) error = json.loads(body) @@ -57,16 +93,9 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(error["operation_id"], "dataset_probeset_info") def test_dataset_probeset_info_unknown_probeset_in_dataset_returns_404(self): - if not database_reachable(): - self.skipTest("no database on 127.0.0.1:3306") + self.require_fixtures() - conn = http.client.HTTPConnection(HOST, int(PORT), timeout=10) - try: - conn.request("GET", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset") - response = conn.getresponse() - body = response.read() - finally: - conn.close() + response, body = self.get("/datasets/Br_U_0803_M/probesets/not-a-real-probeset") self.assertEqual(response.status, 404) error = json.loads(body) @@ -74,6 +103,23 @@ class DatasetProbesetInfoTest(ServerTestCase): self.assertEqual(error["code"], "probeset_not_found") self.assertEqual(error["operation_id"], "dataset_probeset_info") + def test_dataset_probeset_info_non_public_unlinked_dataset_returns_403(self): + """UTHSC_BXD_Cochlea_0225 (public=1, confidentiality=1, created + 2025-02-13) is neither publicly readable by the flags nor old + enough for the embargo-age rule, and has never been linked to a + gn-auth resource -- so even the token's owner has no privilege + on it. + """ + self.require_fixtures() + + response, body = self.get( + "/datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180" + ) + self.assertEqual(response.status, 403) + + error = json.loads(body) + self.assertEqual(error["code"], "forbidden") + if __name__ == "__main__": unittest.main() diff --git a/tests/auth.rs b/tests/auth.rs new file mode 100644 index 0000000..85b5cc2 --- /dev/null +++ b/tests/auth.rs @@ -0,0 +1,163 @@ +//! Exercises src/auth.rs against a real gn-auth instance. Needs one +//! running and reachable at AUTH_SERVER_URL (see docs/gn-auth.md); +//! skips with a message rather than failing when it isn't, same +//! pattern as the MariaDB-backed tests. +//! +//! The fixtures below (token, resource id) are produced by hand +//! against a from-scratch gn-auth instance as described in +//! RELEASE_NOTES.md -- set these environment variables to point at +//! your own instance and data before running: +//! GN4_TEST_AUTH_TOKEN - a valid bearer token (e.g. from the +//! password grant against /auth/token) +//! GN4_TEST_RESOURCE_ID - a resource-id that token's user owns +//! (e.g. from POST /auth/resource/populations/create) + +use genenetwork4::auth::{self, AuthToken}; +use genenetwork4::config::Config; + +fn auth_server_reachable(auth_server_url: &str) -> bool { + ureq::get(format!("{}/auth/public-jwks", auth_server_url.trim_end_matches('/'))) + .call() + .is_ok() +} + +fn test_fixtures() -> Option<(String, String, String)> { + let auth_server_url = Config::load().auth_server_url; + let token = std::env::var("GN4_TEST_AUTH_TOKEN").ok()?; + let resource_id = std::env::var("GN4_TEST_RESOURCE_ID").ok()?; + Some((auth_server_url, token, resource_id)) +} + +#[test] +fn is_publicly_readable_skips_authorisation_entirely() { + // No gn-auth call at all for public data -- this doesn't even need + // a reachable server, which is the point: a public dataset costs + // nothing beyond token verification. + let recent = "2024-01-01 00:00:00"; + assert!(auth::is_publicly_readable(2, 0, recent)); + assert!(!auth::is_publicly_readable(0, 0, recent)); +} + +#[tokio::test] +async fn valid_token_is_accepted_and_resolves_sub() { + let Some((auth_server_url, token, _)) = test_fixtures() else { + eprintln!( + "skipping valid_token_is_accepted_and_resolves_sub: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !auth_server_reachable(&auth_server_url) { + eprintln!("skipping valid_token_is_accepted_and_resolves_sub: no gn-auth at {auth_server_url}"); + return; + } + + use axum::extract::FromRequestParts; + use axum::http::Request; + + let request = Request::builder() + .header("Authorization", format!("Bearer {token}")) + .body(()) + .unwrap(); + let (mut parts, ()) = request.into_parts(); + let auth_token = AuthToken::from_request_parts(&mut parts, &()).await.unwrap(); + + assert!(!auth_token.sub.is_empty()); + assert_eq!(auth_token.raw, token); +} + +#[tokio::test] +async fn malformed_token_is_rejected() { + let Some((auth_server_url, _, _)) = test_fixtures() else { + eprintln!("skipping malformed_token_is_rejected: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)"); + return; + }; + if !auth_server_reachable(&auth_server_url) { + eprintln!("skipping malformed_token_is_rejected: no gn-auth at {auth_server_url}"); + return; + } + + use axum::extract::FromRequestParts; + use axum::http::Request; + + let request = Request::builder() + .header("Authorization", "Bearer not-a-real-token") + .body(()) + .unwrap(); + let (mut parts, ()) = request.into_parts(); + let result = AuthToken::from_request_parts(&mut parts, &()).await; + + assert!(result.is_err()); + assert_eq!(result.err().unwrap().code, "invalid_token"); +} + +#[test] +fn owner_is_authorised_and_stranger_is_not() { + let Some((auth_server_url, token, resource_id)) = test_fixtures() else { + eprintln!( + "skipping owner_is_authorised_and_stranger_is_not: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)" + ); + return; + }; + if !auth_server_reachable(&auth_server_url) { + eprintln!("skipping owner_is_authorised_and_stranger_is_not: no gn-auth at {auth_server_url}"); + return; + } + + let owner = AuthToken { + sub: "owner".to_string(), + scope: "profile resource".to_string(), + raw: token, + }; + let authorised = + auth::authorise(&auth_server_url, &owner, &resource_id, "group:resource:view-resource") + .unwrap(); + assert!(authorised, "the resource's own creator should hold view-resource"); + + // A syntactically-valid but unrelated token has no roles on this + // resource at all -- gn-auth's own default, not something this + // client invents. + let stranger = AuthToken { + sub: "stranger".to_string(), + scope: "profile resource".to_string(), + raw: "not-a-real-token".to_string(), + }; + let result = auth::authorise(&auth_server_url, &stranger, &resource_id, "group:resource:view-resource"); + // An invalid bearer token makes gn-auth treat the call as + // anonymous (see docs/gn-auth.md); anonymous gets no roles on a + // non-public resource, so this comes back Ok(false), not an error. + assert_eq!(result, Ok(false)); +} + +#[test] +fn authorisation_result_is_cached() { + let Some((auth_server_url, token, resource_id)) = test_fixtures() else { + eprintln!("skipping authorisation_result_is_cached: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)"); + return; + }; + if !auth_server_reachable(&auth_server_url) { + eprintln!("skipping authorisation_result_is_cached: no gn-auth at {auth_server_url}"); + return; + } + + let owner = AuthToken { + sub: "cache-test-owner".to_string(), + scope: "profile resource".to_string(), + raw: token, + }; + + let start = std::time::Instant::now(); + auth::authorise(&auth_server_url, &owner, &resource_id, "group:resource:view-resource").unwrap(); + let first_call = start.elapsed(); + + let start = std::time::Instant::now(); + auth::authorise(&auth_server_url, &owner, &resource_id, "group:resource:view-resource").unwrap(); + let second_call = start.elapsed(); + + // The second call hits the in-process cache and shouldn't touch + // the network at all; it should be at least an order of magnitude + // faster than the first, uncached call. + assert!( + second_call < first_call / 2, + "expected the cached call ({second_call:?}) to be much faster than the first ({first_call:?})" + ); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index ad0a50b..84273a5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -19,18 +19,38 @@ pub fn db_available() -> bool { mysql::Conn::new(opts).is_ok() } +/// True only when gn-auth is actually reachable at the configured +/// AUTH_SERVER_URL. Tests that need a live gn-auth skip (rather than +/// fail) when this is false, same reasoning as `db_available`. +pub fn auth_server_available() -> bool { + let config = genenetwork4::config::Config::load(); + ureq::get(format!( + "{}/auth/public-jwks", + config.auth_server_url.trim_end_matches('/') + )) + .call() + .is_ok() +} + +/// A bearer token to use against a live gn-auth instance in tests that +/// need one, e.g. for an endpoint requiring `AuthToken`. Set +/// GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md); tests using this skip +/// rather than fail when it isn't set. +pub fn auth_token() -> Option<String> { + std::env::var("GN4_TEST_AUTH_TOKEN").ok() +} + /// Above this, a request's timing is reported as a warning (see `get`). const SLOW_THRESHOLD: Duration = Duration::from_secs(1); -/// GETs `uri` against genenetwork4::app() and warns on stderr if the -/// response -- which for every endpoint using this helper means its SQL -/// query -- takes longer than SLOW_THRESHOLD. Warnings only show with -/// `cargo test -- --nocapture` (or on a failing test), since cargo -/// captures stdout/stderr for passing tests otherwise. -pub async fn get(label: &str, uri: &str) -> Response { +async fn request(label: &str, uri: &str, bearer_token: Option<&str>) -> Response { let start = Instant::now(); + let mut builder = Request::builder().uri(uri); + if let Some(token) = bearer_token { + builder = builder.header("Authorization", format!("Bearer {token}")); + } let response = genenetwork4::app() - .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .oneshot(builder.body(Body::empty()).unwrap()) .await .unwrap(); let elapsed = start.elapsed(); @@ -39,3 +59,18 @@ pub async fn get(label: &str, uri: &str) -> Response { } response } + +/// GETs `uri` against genenetwork4::app() and warns on stderr if the +/// response -- which for every endpoint using this helper means its SQL +/// query -- takes longer than SLOW_THRESHOLD. Warnings only show with +/// `cargo test -- --nocapture` (or on a failing test), since cargo +/// captures stdout/stderr for passing tests otherwise. +pub async fn get(label: &str, uri: &str) -> Response { + request(label, uri, None).await +} + +/// Like `get`, but with an `Authorization: Bearer <token>` header, for +/// endpoints that require `AuthToken`. +pub async fn get_with_token(label: &str, uri: &str, token: &str) -> Response { + request(label, uri, Some(token)).await +} diff --git a/tests/dataset_probeset_info.rs b/tests/dataset_probeset_info.rs index eb0224b..b529cec 100644 --- a/tests/dataset_probeset_info.rs +++ b/tests/dataset_probeset_info.rs @@ -4,10 +4,14 @@ use serde_json::Value; mod common; -/// Needs a live MariaDB connection (SQL_URI, see src/db.rs); skips rather -/// than fails when none is reachable, same as group_by_name.rs. -/// Probeset 100001_at (gene symbol Cd3g) in dataset Br_U_0803_M is a -/// real row in the database. +/// Needs a live MariaDB connection (SQL_URI, see src/db.rs) and a live +/// gn-auth (AUTH_SERVER_URL) plus GN4_TEST_AUTH_TOKEN (see +/// docs/gn-auth.md); skips rather than fails when either is missing, +/// same as group_by_name.rs. Probeset 100001_at (gene symbol Cd3g) in +/// dataset Br_U_0803_M is a real row in the database; the dataset's +/// CreateTime is 2003-08-01, so it's publicly readable regardless of +/// its public/confidentiality flags (see src/auth.rs) -- a valid token +/// is still required, but no gn-auth authorization call happens. #[tokio::test] async fn dataset_probeset_info_returns_gene_annotation() { if !common::db_available() { @@ -16,10 +20,21 @@ async fn dataset_probeset_info_returns_gene_annotation() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_returns_gene_annotation: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!("skipping dataset_probeset_info_returns_gene_annotation: no gn-auth reachable"); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/Br_U_0803_M/probesets/100001_at", "/datasets/Br_U_0803_M/probesets/100001_at", + &token, ) .await; @@ -34,6 +49,24 @@ async fn dataset_probeset_info_returns_gene_annotation() { } #[tokio::test] +async fn dataset_probeset_info_without_a_token_returns_401() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_without_a_token_returns_401: no usable database (check SQL_URI credentials)" + ); + return; + } + + let response = common::get( + "GET /datasets/Br_U_0803_M/probesets/100001_at (no token)", + "/datasets/Br_U_0803_M/probesets/100001_at", + ) + .await; + + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] async fn dataset_probeset_info_unknown_dataset_returns_404() { if !common::db_available() { eprintln!( @@ -41,10 +74,21 @@ async fn dataset_probeset_info_unknown_dataset_returns_404() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_unknown_dataset_returns_404: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!("skipping dataset_probeset_info_unknown_dataset_returns_404: no gn-auth reachable"); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/not-a-real-dataset/probesets/100001_at", "/datasets/not-a-real-dataset/probesets/100001_at", + &token, ) .await; @@ -65,10 +109,23 @@ async fn dataset_probeset_info_unknown_probeset_in_dataset_returns_404() { ); return; } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_unknown_probeset_in_dataset_returns_404: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!( + "skipping dataset_probeset_info_unknown_probeset_in_dataset_returns_404: no gn-auth reachable" + ); + return; + } - let response = common::get( + let response = common::get_with_token( "GET /datasets/Br_U_0803_M/probesets/not-a-real-probeset", "/datasets/Br_U_0803_M/probesets/not-a-real-probeset", + &token, ) .await; @@ -80,3 +137,43 @@ async fn dataset_probeset_info_unknown_probeset_in_dataset_returns_404() { assert_eq!(error["code"], "probeset_not_found"); assert_eq!(error["operation_id"], "dataset_probeset_info"); } + +/// UTHSC_BXD_Cochlea_0225 (public=1, confidentiality=1, created +/// 2025-02-13) is neither publicly readable by the flags +/// (confidentiality >= 1) nor old enough for the embargo-age rule, and +/// has never been linked to a gn-auth resource -- so even the token's +/// owner has no privilege on it, and the request must be denied rather +/// than silently allowed. +#[tokio::test] +async fn dataset_probeset_info_non_public_unlinked_dataset_returns_403() { + if !common::db_available() { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: no usable database (check SQL_URI credentials)" + ); + return; + } + let Some(token) = common::auth_token() else { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)" + ); + return; + }; + if !common::auth_server_available() { + eprintln!( + "skipping dataset_probeset_info_non_public_unlinked_dataset_returns_403: no gn-auth reachable" + ); + return; + } + + let response = common::get_with_token( + "GET /datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180", + "/datasets/UTHSC_BXD_Cochlea_0225/probesets/ENSMUSG00000028180", + &token, + ) + .await; + + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let error: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(error["code"], "forbidden"); +} |
