diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-05 06:50:30 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-05 06:50:30 +0000 |
| commit | 693e7ee89f8618c1abbf8af5c0db23b071700803 (patch) | |
| tree | e5db71e3f7e8af7342be1004aac9d5dfd0e1db2a /src | |
| parent | adc173c1f3c78da487827122262573e753284260 (diff) | |
| download | genenetwork4-693e7ee89f8618c1abbf8af5c0db23b071700803.tar.gz | |
Add POST /dev/token, a dev-only gn-auth token issuer
Calls gn-auth's own password grant (POST /auth/token) for gn-auth's well-known development user and returns the result, so local testing no longer needs a manual curl/gn-auth round trip of its own. Only ever registered -- not just rejected at request time, genuinely absent from the router and from /openapi.json -- when two new Config fields are both set: dev_mode (GENENETWORK4_DEV_MODE) and a loopback bind (GENENETWORK4_BIND, also new). Both are config, not something genenetwork4 infers from its actual network exposure, by design: dev mode alone, or a loopback bind alone, each leave it disabled, and the check (Config::dev_token_enabled) is a plain function so the condition itself has direct unit test coverage rather than only being exercised indirectly through the route. src/main.rs now binds to config.bind instead of a hardcoded "0.0.0.0", via a proper SocketAddr rather than string formatting -- the latter would mishandle an IPv6 bind address like "::1" (needs brackets). GN_AUTH_DEV_CLIENT_ID/_CLIENT_SECRET/_USERNAME/_PASSWORD default to gn-auth's own published dev fixtures (flask init-dev-clients, gn_auth/wsgi.py), so this works unconfigured against an unmodified dev gn-auth instance -- confirmed live, including using the returned token against a real gated endpoint (/traits/BXD/10001), not just checking the token response's shape. tests/dev_token.rs covers all four combinations of the two settings in one sequential test function (mutating the same two env vars from more than one #[tokio::test] in a file would race, since they run concurrently by default) plus the /openapi.json visibility check. test/python/test_dev_token.py mirrors this using separate test classes instead, which is safe here since each spawns its own server subprocess with its own environment (ServerTestCase gains EXTRA_ENV for this). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 120 | ||||
| -rw-r--r-- | src/lib.rs | 13 | ||||
| -rw-r--r-- | src/main.rs | 9 | ||||
| -rw-r--r-- | src/routes/dev.rs | 100 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 |
5 files changed, 236 insertions, 7 deletions
diff --git a/src/config.rs b/src/config.rs index c403083..0f2df91 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,6 +23,40 @@ pub struct Config { /// Same AUTH_SERVER_URL config key GeneNetwork3 uses. See /// docs/gn-auth.md. pub auth_server_url: String, + /// Address to bind the TCP listener to (see src/main.rs). Defaults + /// to "0.0.0.0" (every interface); set to "127.0.0.1" to only + /// accept local connections -- required, together with `dev_mode`, + /// for `dev_token_enabled()` to allow POST /dev/token (see + /// src/routes/dev.rs). + pub bind: String, + /// Enables development-only endpoints when combined with a + /// loopback-only `bind` -- see `dev_token_enabled()`. Never turn + /// this on in a deployment reachable from anywhere but localhost. + pub dev_mode: bool, + /// gn-auth OAuth2 client id/secret and dev user credentials used by + /// POST /dev/token's password-grant call. Default to gn-auth's own + /// well-known development fixtures (`flask init-dev-clients`, + /// `gn_auth/wsgi.py`), so this works against an unmodified dev + /// gn-auth instance with no extra configuration. + pub dev_token_client_id: String, + pub dev_token_client_secret: String, + pub dev_token_username: String, + pub dev_token_password: String, +} + +impl Config { + /// Whether POST /dev/token (src/routes/dev.rs) should be + /// registered at all: `dev_mode` on, and `bind` resolves to a + /// loopback address (127.0.0.1, ::1, ...) -- both set in config, + /// per the feature's own requirement that it never be reachable + /// from outside localhost. + pub fn dev_token_enabled(&self) -> bool { + self.dev_mode + && self + .bind + .parse::<std::net::IpAddr>() + .is_ok_and(|ip| ip.is_loopback()) + } } impl Config { @@ -40,6 +74,24 @@ impl Config { "AUTH_SERVER_URL".to_string(), "http://127.0.0.1:8081/".to_string(), ); + values.insert("GENENETWORK4_BIND".to_string(), "0.0.0.0".to_string()); + values.insert("GENENETWORK4_DEV_MODE".to_string(), "false".to_string()); + values.insert( + "GN_AUTH_DEV_CLIENT_ID".to_string(), + "0bbfca82-d73f-4bd4-a140-5ae7abb4a64d".to_string(), + ); + values.insert( + "GN_AUTH_DEV_CLIENT_SECRET".to_string(), + "yadabadaboo".to_string(), + ); + values.insert( + "GN_AUTH_DEV_USERNAME".to_string(), + "test@development.user".to_string(), + ); + values.insert( + "GN_AUTH_DEV_PASSWORD".to_string(), + "testpasswd".to_string(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -51,7 +103,17 @@ impl Config { } // Layer 4: environment wins over everything. - for key in ["SQL_URI", "GENENETWORK4_PORT", "AUTH_SERVER_URL"] { + for key in [ + "SQL_URI", + "GENENETWORK4_PORT", + "AUTH_SERVER_URL", + "GENENETWORK4_BIND", + "GENENETWORK4_DEV_MODE", + "GN_AUTH_DEV_CLIENT_ID", + "GN_AUTH_DEV_CLIENT_SECRET", + "GN_AUTH_DEV_USERNAME", + "GN_AUTH_DEV_PASSWORD", + ] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); } @@ -63,6 +125,12 @@ impl Config { .parse() .expect("GENENETWORK4_PORT must be a number"), auth_server_url: values["AUTH_SERVER_URL"].clone(), + bind: values["GENENETWORK4_BIND"].clone(), + dev_mode: values["GENENETWORK4_DEV_MODE"] == "true", + dev_token_client_id: values["GN_AUTH_DEV_CLIENT_ID"].clone(), + dev_token_client_secret: values["GN_AUTH_DEV_CLIENT_SECRET"].clone(), + dev_token_username: values["GN_AUTH_DEV_USERNAME"].clone(), + dev_token_password: values["GN_AUTH_DEV_PASSWORD"].clone(), } } } @@ -102,6 +170,12 @@ mod tests { "GN4_SECRETS", "GENENETWORK4_PORT", "AUTH_SERVER_URL", + "GENENETWORK4_BIND", + "GENENETWORK4_DEV_MODE", + "GN_AUTH_DEV_CLIENT_ID", + "GN_AUTH_DEV_CLIENT_SECRET", + "GN_AUTH_DEV_USERNAME", + "GN_AUTH_DEV_PASSWORD", ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); @@ -112,6 +186,50 @@ mod tests { assert!(config.sql_uri.contains("db_webqtl")); assert_eq!(config.port, 3000); assert_eq!(config.auth_server_url, "http://127.0.0.1:8081/"); + assert_eq!(config.bind, "0.0.0.0"); + assert!(!config.dev_mode); + assert_eq!(config.dev_token_username, "test@development.user"); + } + + #[test] + fn dev_token_enabled_requires_both_dev_mode_and_loopback_bind() { + let dev_fields = || Config { + sql_uri: String::new(), + port: 0, + auth_server_url: String::new(), + bind: "127.0.0.1".to_string(), + dev_mode: true, + dev_token_client_id: String::new(), + dev_token_client_secret: String::new(), + dev_token_username: String::new(), + dev_token_password: String::new(), + }; + + assert!(dev_fields().dev_token_enabled()); + assert!( + !Config { + dev_mode: false, + ..dev_fields() + } + .dev_token_enabled(), + "dev_mode off should disable it even on loopback" + ); + assert!( + !Config { + bind: "0.0.0.0".to_string(), + ..dev_fields() + } + .dev_token_enabled(), + "a non-loopback bind should disable it even in dev_mode" + ); + assert!( + Config { + bind: "::1".to_string(), + ..dev_fields() + } + .dev_token_enabled(), + "IPv6 loopback should count too" + ); } #[test] diff --git a/src/lib.rs b/src/lib.rs index 47d808f..84a143a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,7 +49,7 @@ impl utoipa::Modify for SecurityAddon { /// 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 { - let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) + let mut api_router = OpenApiRouter::with_openapi(ApiDoc::openapi()) .routes(routes!(hello_world)) .routes(routes!(version)) .routes(routes!(routes::species::species)) @@ -69,8 +69,15 @@ pub fn app() -> Router { .routes(routes!(routes::traits::traits)) .routes(routes!(routes::traits::trait_info)) .routes(routes!(routes::traits::trait_values)) - .routes(routes!(routes::correlation::correlation)) - .split_for_parts(); + .routes(routes!(routes::correlation::correlation)); + // Only registered -- so only ever reachable, and only ever + // documented in /openapi.json -- when config says this is a + // dev-mode server bound to loopback only. See + // Config::dev_token_enabled and src/routes/dev.rs. + if config::Config::load().dev_token_enabled() { + api_router = api_router.routes(routes!(routes::dev::dev_token)); + } + let (router, api) = api_router.split_for_parts(); router .route("/openapi.json", axum::routing::get(|| async { Json(api) })) // Assigns each request an x-request-id (if the client didn't diff --git a/src/main.rs b/src/main.rs index 58a96e2..7e99847 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,11 @@ #[tokio::main] async fn main() { let config = genenetwork4::config::Config::load(); - let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", config.port)) - .await - .unwrap(); + let bind_ip: std::net::IpAddr = config + .bind + .parse() + .expect("GENENETWORK4_BIND must be an IP address"); + let addr = std::net::SocketAddr::new(bind_ip, config.port); + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); axum::serve(listener, genenetwork4::app()).await.unwrap(); } diff --git a/src/routes/dev.rs b/src/routes/dev.rs new file mode 100644 index 0000000..04e88e4 --- /dev/null +++ b/src/routes/dev.rs @@ -0,0 +1,100 @@ +//! Development-only convenience endpoint: hands out a real gn-auth +//! token (via gn-auth's own password grant, `POST /auth/token`) for +//! gn-auth's well-known development user, so local testing doesn't +//! need a manual curl/password-grant call of its own. +//! +//! Only ever registered (see `app()` in src/lib.rs) when +//! `Config::dev_token_enabled()` is true -- `GENENETWORK4_DEV_MODE` is +//! on *and* `GENENETWORK4_BIND` resolves to a loopback address. Both +//! are config, not runtime-detected, by design (see the discussion +//! that led to this file): this endpoint must never exist on a server +//! reachable from anywhere but localhost, since any caller who can +//! reach it gets a token for gn-auth's own published, publicly-known +//! dev credentials. + +use axum::Json; +use axum::extract::Extension; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use tower_http::request_id::RequestId; + +use crate::config::Config; +use crate::error::ApiError; +use crate::request_id_string; + +/// A token for gn-auth's development user, as returned by its password +/// grant -- just the fields a caller actually needs to use it (see +/// AuthToken in src/auth.rs), not gn-auth's full token response. +#[derive(Serialize, utoipa::ToSchema)] +pub struct DevToken { + pub access_token: String, + pub token_type: String, + pub scope: String, +} + +#[derive(Deserialize)] +struct TokenResponse { + access_token: String, + token_type: String, + scope: String, +} + +#[utoipa::path(post, path = "/dev/token", summary = "Development only: obtain a real gn-auth token for gn-auth's own dev user", responses( + (status = 200, description = "A bearer token for gn-auth's well-known development user", body = DevToken), + (status = 500, description = "Internal error", body = ApiError), + (status = 502, description = "Could not obtain a token from gn-auth", body = ApiError) +))] +pub async fn dev_token( + Extension(request_id): Extension<RequestId>, +) -> Result<Json<DevToken>, ApiError> { + let rid = request_id_string(&request_id); + let config = Config::load(); + tokio::task::spawn_blocking(move || fetch_dev_token(&config)) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "dev_token", + ) + .with_request_id(rid.clone()) + })? + .map(Json) + .map_err(|e| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not obtain a token from gn-auth", + e, + "dev_token", + ) + .with_request_id(rid) + }) +} + +fn fetch_dev_token(config: &Config) -> Result<DevToken, String> { + let url = format!( + "{}/auth/token", + config.auth_server_url.trim_end_matches('/') + ); + let response: TokenResponse = ureq::post(&url) + .send_form([ + ("grant_type", "password"), + ("client_id", config.dev_token_client_id.as_str()), + ("client_secret", config.dev_token_client_secret.as_str()), + ("username", config.dev_token_username.as_str()), + ("password", config.dev_token_password.as_str()), + ("scope", "profile group resource"), + ]) + .map_err(|e| format!("calling {url}: {e}"))? + .body_mut() + .read_json() + .map_err(|e| format!("parsing token response from {url}: {e}"))?; + Ok(DevToken { + access_token: response.access_token, + token_type: response.token_type, + scope: response.scope, + }) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 5c08a95..7a7a01a 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -5,6 +5,7 @@ pub mod correlation; pub mod datasets; +pub mod dev; pub mod groups; pub mod species; pub mod traits; |
