about summary refs log tree commit diff
path: root/tests/tokens.rs
blob: b1b2b41e61abb0cd07f6e3480f53886db47d5a57 (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
200
//! Token administration (`/tokens`, `/tokens/who`) answers only a caller
//! on this machine, and mints a token whose secret is shown exactly once
//! (src/routes/tokens.rs, src/tokens.rs).
//!
//! The peer address is the `ConnectInfo` a real server provides
//! (src/main.rs); these in-process requests supply one the same way
//! tests/get_test_token.rs does. The registry is a throwaway SQLite file
//! under the temp dir, wired in through `GN4_API_TOKENS_DB` before the
//! first `Config::load()` in this process.

use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Method, Request, StatusCode};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use std::net::SocketAddr;
use std::sync::OnceLock;
use tower::ServiceExt;

fn registry_path() -> &'static str {
    static PATH: OnceLock<String> = OnceLock::new();
    PATH.get_or_init(|| {
        let path = std::env::temp_dir().join(format!("gn4-tokens-it-{}.sqlite", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let path = path.to_string_lossy().into_owned();
        // SAFETY: set before any request in this test binary has loaded the
        // configuration, and to one value for the whole process, so no other
        // thread can observe a different one. `set_var` is unsafe on edition
        // 2024 because a concurrent reader could see a torn value; the
        // OnceLock makes this the only write.
        unsafe { std::env::set_var("GN4_API_TOKENS_DB", &path) };
        path
    })
}

/// A request against the app, from `peer`, optionally with a JSON body.
async fn call(
    method: Method,
    uri: &str,
    peer: Option<SocketAddr>,
    body: Option<Value>,
) -> axum::response::Response {
    let mut builder = Request::builder().method(method).uri(uri);
    if body.is_some() {
        builder = builder.header("content-type", "application/json");
    }
    let mut request = builder
        .body(match body {
            Some(body) => Body::from(body.to_string()),
            None => Body::empty(),
        })
        .unwrap();
    if let Some(peer) = peer {
        request.extensions_mut().insert(ConnectInfo(peer));
    }
    genenetwork4::app().oneshot(request).await.unwrap()
}

async fn error_of(response: axum::response::Response) -> Value {
    let body = response.into_body().collect().await.unwrap().to_bytes();
    serde_json::from_slice(&body).unwrap()
}

async fn json_of(response: axum::response::Response) -> Value {
    let body = response.into_body().collect().await.unwrap().to_bytes();
    serde_json::from_slice(&body).unwrap()
}

#[tokio::test]
async fn token_administration_refuses_every_caller_that_is_not_local() {
    registry_path();
    let remote: SocketAddr = "10.0.0.5:4000".parse().unwrap();
    let local: SocketAddr = "127.0.0.1:4000".parse().unwrap();

    // Every route, from another machine, and from a local caller that says it
    // came through a proxy: minting a credential must never be reachable.
    for (method, uri, body) in [
        (Method::GET, "/tokens", None),
        (
            Method::POST,
            "/tokens",
            Some(json!({"id": "x-1", "subject": "x"})),
        ),
        (Method::DELETE, "/tokens/x-1", None),
        (Method::GET, "/tokens/who", None),
    ] {
        let response = call(method.clone(), uri, Some(remote), body.clone()).await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} remote");
        let error = error_of(response).await;
        assert_eq!(error["code"], "not_local", "{method} {uri}");
        assert!(error["detail"].as_str().unwrap_or_default().contains("this machine"));

        // Fail closed with no peer at all.
        let response = call(method.clone(), uri, None, body.clone()).await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} no peer");

        // A local peer whose request claims to be proxied: a reverse proxy on
        // this host would make every remote client look local.
        let request = Request::builder()
            .method(method.clone())
            .uri(uri)
            .header("x-forwarded-for", "203.0.113.9")
            .body(Body::empty())
            .unwrap();
        let mut request = request;
        request.extensions_mut().insert(ConnectInfo(local));
        let response = genenetwork4::app().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {uri} proxied");
    }
}

#[tokio::test]
async fn a_token_minted_locally_authenticates_and_is_then_revoked() {
    registry_path();
    let local: SocketAddr = "127.0.0.1:4000".parse().unwrap();

    let response = call(
        Method::POST,
        "/tokens",
        Some(local),
        Some(json!({
            "id": "it-1",
            "subject": "zachs",
            "scope": "public",
            "ttl_days": 7,
            "note": "integration test"
        })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let reply = json_of(response).await;
    let token = reply["data"]["token"].as_str().expect("the secret, once").to_string();
    assert!(token.starts_with("gn4ai_"), "{token}");
    assert_eq!(token.len(), 64, "{token}");
    assert_eq!(reply["data"]["id"], "it-1");
    assert_eq!(reply["data"]["status"], "active");

    // The listing never repeats the secret or its hash.
    let response = call(Method::GET, "/tokens", Some(local), None).await;
    let listing = json_of(response).await;
    let listing_text = listing.to_string();
    assert!(!listing_text.contains(&token), "the listing leaked the token");
    assert!(!listing_text.contains("sha256"));
    assert_eq!(listing["data"][0]["id"], "it-1");

    // A second mint with the same id is a conflict, not a server error.
    let response = call(
        Method::POST,
        "/tokens",
        Some(local),
        Some(json!({"id": "it-1", "subject": "zachs"})),
    )
    .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);

    // The token works as a credential: /tokens/who describes it (it is the
    // only route that needs no model access to prove the extractor branch).
    let response = call_with_bearer(Method::GET, "/tokens/who", local, &token).await;
    assert_eq!(response.status(), StatusCode::OK);
    let who = json_of(response).await;
    assert_eq!(who["data"]["scheme"], "opaque");
    assert_eq!(who["data"]["subject"], "zachs");
    assert_eq!(who["data"]["id"], "it-1");
    assert!(who["data"]["created_at"].as_i64().is_some());

    // Revoking takes effect on the next request, with no restart.
    let response = call(Method::DELETE, "/tokens/it-1", Some(local), None).await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(json_of(response).await["data"]["status"], "revoked");

    let response = call_with_bearer(Method::GET, "/tokens/who", local, &token).await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // A typo is refused as unmintable, before any registry lookup, and
    // says so the same way as an unknown-but-well-formed token: the answer
    // must not distinguish "not ours" from "no such token" to a caller.
    let mut typo = token.clone().into_bytes();
    typo[10] = if typo[10] == b'a' { b'b' } else { b'a' };
    let typo = String::from_utf8(typo).unwrap();
    for candidate in [typo, "gn4ai_".to_string() + &"z".repeat(60), "not-a-token".to_string()] {
        let response = call_with_bearer(Method::GET, "/tokens/who", local, &candidate).await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{candidate}");
    }
}

async fn call_with_bearer(
    method: Method,
    uri: &str,
    peer: SocketAddr,
    token: &str,
) -> axum::response::Response {
    let mut request = Request::builder()
        .method(method)
        .uri(uri)
        .header("authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap();
    request.extensions_mut().insert(ConnectInfo(peer));
    genenetwork4::app().oneshot(request).await.unwrap()
}