diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-08 14:57:35 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-08 14:57:35 +0000 |
| commit | 69aac61b0c5b2d8a4f909de6a6d6af8d6ee293a3 (patch) | |
| tree | 8c3734e6a3ca0baca7872d6e87cbe3167fb128b6 /src | |
| parent | 679136801effc34ff4b50e54abfc40592ee1d64d (diff) | |
| download | genenetwork4-69aac61b0c5b2d8a4f909de6a6d6af8d6ee293a3.tar.gz | |
* src/routes/dev.rs: POST /get-test-token answers local callers only, not tied to dev mode.
The endpoint no longer depends on GENENETWORK4_DEV_MODE or on the bind
address. It decides per request whether to answer.
* src/routes/dev.rs (get_test_token): answers a caller only when the TCP
peer (axum ConnectInfo) is in 127.0.x.x (or ::1, or an IPv4-mapped
127.x) and the request carries no X-Forwarded-For, Forwarded or
X-Real-IP header (a reverse proxy on the same host would otherwise make
every client look local). Anything else, including an unknown peer, is a
403. Local is never established from a header.
* src/main.rs: serve with into_make_service_with_connect_info, which
provides the peer address.
* src/config.rs: remove dev_mode, GENENETWORK4_DEV_MODE and
dev_token_enabled(). Add GENENETWORK4_TEST_TOKEN (on by default); when it
is not a clearly affirmative value (true/1/yes/on) the route is not
registered: a 404, absent from /openapi.json. It fails closed, so a
typo ("flase") turns the endpoint off.
* src/lib.rs: register the route unless that switch is off.
* tests: tests/get_test_token.rs rewritten (remote, unknown and proxied
peers refused; 127.x and ::1 answered; always documented by default);
tests/get_test_token_off.rs for the switch (own process: it sets an
environment variable); common::post_from supplies a peer address to the
in-process requests. Python: test_get_test_token.py rewritten, TOKEN_ENV
is now empty (no setting needed).
* README.md, docs/gn-auth.md, docs/SKILL.md, RELEASE_NOTES.md: document
the check, the switch, and "Behind nginx or in a container" (a bridge
container sees the gateway as the peer; a host-network container behind
nginx sees 127.0.0.1, so block the path in nginx, set X-Forwarded-For,
or switch the endpoint off).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 99 | ||||
| -rw-r--r-- | src/lib.rs | 9 | ||||
| -rw-r--r-- | src/main.rs | 9 | ||||
| -rw-r--r-- | src/routes/dev.rs | 110 |
4 files changed, 137 insertions, 90 deletions
diff --git a/src/config.rs b/src/config.rs index f8dbb50..10f5755 100644 --- a/src/config.rs +++ b/src/config.rs @@ -44,14 +44,13 @@ pub struct Config { 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 /get-test-token (see - /// src/routes/dev.rs). + /// accept local connections. 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, + /// Whether POST /get-test-token is registered at all + /// (GENENETWORK4_TEST_TOKEN; on by default). When off the route is + /// absent: a 404, and not in /openapi.json either. See + /// `parse_switch` and src/routes/dev.rs. + pub test_token_enabled: bool, /// gn-auth OAuth2 client id/secret and dev user credentials used by /// POST /get-test-token's password-grant call. Default to gn-auth's own /// well-known development fixtures (`flask init-dev-clients`, @@ -64,21 +63,6 @@ pub struct Config { } impl Config { - /// Whether POST /get-test-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 { /// Load configuration from all layers, highest priority last. pub fn load() -> Config { let mut values = HashMap::<String, String>::new(); @@ -94,7 +78,7 @@ impl Config { "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("GENENETWORK4_TEST_TOKEN".to_string(), "true".to_string()); values.insert( "GN_AUTH_DEV_CLIENT_ID".to_string(), "0bbfca82-d73f-4bd4-a140-5ae7abb4a64d".to_string(), @@ -134,7 +118,7 @@ impl Config { "GENENETWORK4_PORT", "AUTH_SERVER_URL", "GENENETWORK4_BIND", - "GENENETWORK4_DEV_MODE", + "GENENETWORK4_TEST_TOKEN", "GN_AUTH_DEV_CLIENT_ID", "GN_AUTH_DEV_CLIENT_SECRET", "GN_AUTH_DEV_USERNAME", @@ -164,7 +148,7 @@ impl Config { .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", + test_token_enabled: parse_switch(&values["GENENETWORK4_TEST_TOKEN"]), 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(), @@ -173,6 +157,18 @@ impl Config { } } +/// Reads an on/off setting, failing closed: only a clearly affirmative +/// value ("true", "1", "yes", "on", any case) is on; "false", "0", "no", +/// "off", the empty string and anything unrecognised (a typo like +/// "flase") are off. For a switch guarding a credential-issuing endpoint, +/// a typo must not leave it running. +fn parse_switch(value: &str) -> bool { + matches!( + value.trim().to_ascii_lowercase().as_str(), + "true" | "1" | "yes" | "on" + ) +} + /// The proxy appends "search/" to this base; without a trailing slash /// the result would be ".../apisearch/". Operators may set either form. fn normalize_base_url(mut url: String) -> String { @@ -218,7 +214,7 @@ mod tests { "GENENETWORK4_PORT", "AUTH_SERVER_URL", "GENENETWORK4_BIND", - "GENENETWORK4_DEV_MODE", + "GENENETWORK4_TEST_TOKEN", "GN_AUTH_DEV_CLIENT_ID", "GN_AUTH_DEV_CLIENT_SECRET", "GN_AUTH_DEV_USERNAME", @@ -238,7 +234,7 @@ mod tests { 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!(config.test_token_enabled, "on by default"); assert_eq!(config.dev_token_username, "test@development.user"); // Search-engine wiring defaults: forwarding stays the default // engine and no index path is configured out of the box. @@ -247,48 +243,13 @@ mod tests { } #[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(), - gn3_url: String::new(), - gn3_timeout_secs: 30, - xapian_db_path: String::new(), - search_engine: "forward".to_string(), - 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" - ); + fn a_switch_is_on_only_for_a_clearly_affirmative_value() { + for on in ["true", "TRUE", "True", "1", "yes", "ON", " on "] { + assert!(parse_switch(on), "{on:?}"); + } + for off in ["false", "False", "0", "no", "off", "", "flase", "maybe", "2", "tru"] { + assert!(!parse_switch(off), "{off:?}"); + } } #[test] diff --git a/src/lib.rs b/src/lib.rs index 63c25a1..42b2da7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -76,11 +76,10 @@ pub fn app() -> Router { .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) .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() { + // Registered -- and so reachable and listed in /openapi.json -- unless + // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides + // per request whether the caller is local. See src/routes/dev.rs. + if config::Config::load().test_token_enabled { api_router = api_router.routes(routes!(routes::dev::get_test_token)); } let (router, api) = api_router.split_for_parts(); diff --git a/src/main.rs b/src/main.rs index 7e99847..21a0e55 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,5 +7,12 @@ async fn main() { .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(); + // The connect info (the peer's address) is what POST /get-test-token + // checks to answer only local callers (src/routes/dev.rs). + axum::serve( + listener, + genenetwork4::app().into_make_service_with_connect_info::<std::net::SocketAddr>(), + ) + .await + .unwrap(); } diff --git a/src/routes/dev.rs b/src/routes/dev.rs index 91f69f7..7b1aa49 100644 --- a/src/routes/dev.rs +++ b/src/routes/dev.rs @@ -1,21 +1,30 @@ -//! 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. +//! Convenience endpoint for local use: 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. It's also the one endpoint in this API that must -//! NOT itself require a token -- that would be circular. +//! It is not tied to a mode or to the bind address: it is registered +//! and documented in /openapi.json (unless `GENENETWORK4_TEST_TOKEN` is +//! set to something other than a clearly affirmative value, which leaves +//! the route out entirely: a 404 and absent from the spec), and decides +//! per request whether to answer. It answers only a caller on this +//! machine: the TCP peer address is 127.0.x.x (or ::1) and the request +//! carries no proxy header (X-Forwarded-For, Forwarded, X-Real-IP -- a +//! reverse proxy on the same host would otherwise make every remote +//! client look local). +//! Everything else is a 403, including a request with no known peer. +//! The peer address comes from the connection (axum's `ConnectInfo`, +//! provided in src/main.rs), never from a header the client controls. +//! Any caller who gets an answer gets a token for gn-auth's own +//! published, publicly-known dev credentials. It's also the one +//! endpoint in this API that must NOT itself require a token -- that +//! would be circular. use axum::Json; -use axum::http::StatusCode; +use axum::extract::{ConnectInfo, Extension}; +use axum::http::{HeaderMap, StatusCode}; use serde::{Deserialize, Serialize}; +use std::net::{IpAddr, SocketAddr}; use crate::config::Config; use crate::error::ApiError; @@ -38,8 +47,29 @@ struct TokenResponse { scope: String, } -#[utoipa::path(post, path = "/get-test-token", summary = "Development only: obtain a real gn-auth token for gn-auth's own dev user", responses( +/// Whether the connection's peer is this machine: an address in +/// 127.0.0.0/8 (127.0.x.x), the IPv6 loopback `::1`, or an IPv4-mapped +/// 127.x. +fn is_local(peer: &SocketAddr) -> bool { + match peer.ip() { + IpAddr::V4(ip) => ip.is_loopback(), + IpAddr::V6(ip) => ip.is_loopback() || ip.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()), + } +} + +/// Whether the request says it was forwarded by a proxy. A client can set +/// these headers to anything, so they are never trusted to *establish* +/// that a caller is local -- only used to refuse a request that claims to +/// have come through a proxy. +fn via_proxy(headers: &HeaderMap) -> bool { + ["x-forwarded-for", "forwarded", "x-real-ip"] + .into_iter() + .any(|name| headers.contains_key(name)) +} + +#[utoipa::path(post, path = "/get-test-token", summary = "Development only: obtain a real gn-auth token for gn-auth's own dev user", description = "Only answers a caller on this machine (127.0.x.x or ::1, directly, not through a proxy); anything else is a 403.", responses( (status = 200, description = "A bearer token for gn-auth's well-known development user", body = Envelope<TestToken>), + (status = 403, description = "The request did not come from localhost", body = ApiError), (status = 500, description = "Internal error", body = ApiError), (status = 502, description = "Could not obtain a token from gn-auth", body = ApiError) // Opts out of ApiDoc's default security requirement: this is the one @@ -47,8 +77,24 @@ struct TokenResponse { ), security())] pub async fn get_test_token( ctx: Ctx, + peer: Option<Extension<ConnectInfo<SocketAddr>>>, + headers: HeaderMap, ) -> Result<Json<Envelope<TestToken>>, ApiError> { let rid = ctx.request_info(); + // Fail closed: a request with no known peer address is refused too. + let local = peer.as_ref().is_some_and(|Extension(ConnectInfo(addr))| is_local(addr)); + if !local || via_proxy(&headers) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + "This endpoint only answers callers on this machine (127.0.x.x or ::1), \ + directly and not through a proxy." + .to_string(), + "get_test_token", + ) + .with_request_id(rid)); + } let config = Config::load(); tokio::task::spawn_blocking(move || fetch_test_token(&config)) .await @@ -99,3 +145,37 @@ fn fetch_test_token(config: &Config) -> Result<TestToken, String> { scope: response.scope, }) } + +#[cfg(test)] +mod tests { + use super::{is_local, via_proxy}; + use axum::http::HeaderMap; + use std::net::SocketAddr; + + fn local(addr: &str) -> bool { + is_local(&addr.parse::<SocketAddr>().unwrap()) + } + + #[test] + fn only_loopback_peers_are_local() { + for yes in ["127.0.0.1:1", "127.0.1.2:80", "127.255.255.254:9", "[::1]:3000", "[::ffff:127.0.0.1]:5"] { + assert!(local(yes), "{yes}"); + } + for no in ["10.0.0.5:1", "192.168.1.20:80", "128.0.0.1:1", "0.0.0.0:1", "[::2]:1", "[::ffff:10.0.0.1]:1", "[fe80::1]:1"] { + assert!(!local(no), "{no}"); + } + } + + #[test] + fn proxy_headers_are_refused() { + assert!(!via_proxy(&HeaderMap::new())); + for name in ["x-forwarded-for", "Forwarded", "X-Real-IP"] { + let mut headers = HeaderMap::new(); + headers.insert( + axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(), + "203.0.113.9".parse().unwrap(), + ); + assert!(via_proxy(&headers), "{name}"); + } + } +} |
