about summary refs log tree commit diff
path: root/src/routes/dev.rs
blob: ef87986b5d07905d90acf38bae32084f0e1c5916 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! 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<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
// endpoint that must NOT need a token already (that would be circular).
), 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
        .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<TestToken, 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(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::<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}");
        }
    }
}