//! 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. //! //! 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::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; use crate::response::{Ctx, Envelope}; /// 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 TestToken { pub access_token: String, pub token_type: String, pub scope: String, } #[derive(Deserialize)] struct TokenResponse { access_token: String, token_type: String, scope: String, } /// 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. pub(crate) 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. pub(crate) 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), (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 // endpoint that must NOT need a token already (that would be circular). ), security())] pub async fn get_test_token( ctx: Ctx, peer: Option>>, headers: HeaderMap, ) -> Result>, 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 .map_err(|e| { ApiError::new( StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Internal error", e.to_string(), "get_test_token", ) .with_request_id(rid.clone()) })? .map(|token| Json(ctx.envelope(token))) .map_err(|e| { ApiError::new( StatusCode::BAD_GATEWAY, "auth_server_error", "Could not obtain a token from gn-auth", e, "get_test_token", ) .with_request_id(rid) }) } fn fetch_test_token(config: &Config) -> Result { 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(TestToken { access_token: response.access_token, token_type: response.token_type, 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::().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}"); } } }