about summary refs log tree commit diff
path: root/tests/get_test_token.rs
blob: 56886aeb1e4a67babc3ba75581c87315e013cfe4 (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
//! POST /get-test-token is not tied to a mode or a bind address: it is
//! registered and documented by default (GENENETWORK4_TEST_TOKEN switches
//! it off; see tests/get_test_token_off.rs), and answers a request only
//! when it comes from this machine -- a TCP peer in 127.0.x.x (or ::1), with no
//! proxy header (src/routes/dev.rs). The request's peer address is the
//! `ConnectInfo` a real server provides (src/main.rs); `common::post_from`
//! supplies one for these in-process requests.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use serde_json::Value;
use tower::ServiceExt;

mod common;

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()
}

#[tokio::test]
async fn get_test_token_refuses_callers_that_are_not_local() {
    // Other machines, IPv4 and IPv6.
    for remote in [
        "10.0.0.5:4000",
        "192.168.1.20:4000",
        "128.0.0.1:4000",
        "[2001:db8::7]:4000",
    ] {
        let response = common::post_from(
            "POST /get-test-token (remote peer)",
            "/get-test-token",
            remote.parse().unwrap(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{remote}");
        let error = error_of(response).await;
        assert_eq!(error["code"], "forbidden");
        assert_eq!(error["operation_id"], "get_test_token");
        assert!(error["request_id"].is_string() && error["took_ms"].is_u64());
    }

    // No known peer address at all: refused, not allowed (fail closed).
    let no_peer = genenetwork4::app()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/get-test-token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(no_peer.status(), StatusCode::FORBIDDEN, "no peer address");

    // A local peer that says it was forwarded by a proxy: a reverse proxy
    // on this host would make every remote client look local.
    for header in ["x-forwarded-for", "forwarded", "x-real-ip"] {
        let response = genenetwork4::app()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/get-test-token")
                    .header(header, "203.0.113.9")
                    .extension(axum::extract::ConnectInfo(std::net::SocketAddr::from((
                        [127, 0, 0, 1],
                        4000,
                    ))))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{header}");
    }
}

#[tokio::test]
async fn get_test_token_answers_callers_on_this_machine() {
    // Anywhere in 127.0.0.0/8, and ::1, is local: never refused with a 403
    // (the answer is the token, or a 502 when no gn-auth is reachable).
    for local in ["127.0.0.1:4000", "127.8.9.10:4000", "[::1]:4000"] {
        let response = common::post_from(
            "POST /get-test-token (local peer)",
            "/get-test-token",
            local.parse().unwrap(),
        )
        .await;
        assert_ne!(response.status(), StatusCode::FORBIDDEN, "{local}");
    }

    if !common::auth_server_available() {
        eprintln!(
            "skipping the token checks of get_test_token_answers_callers_on_this_machine: no gn-auth reachable"
        );
        return;
    }
    let response = common::post("POST /get-test-token", "/get-test-token").await;
    assert_eq!(response.status(), StatusCode::OK);
    let body = response.into_body().collect().await.unwrap().to_bytes();
    let token: Value = common::data(&body);
    assert!(!token["access_token"].as_str().unwrap().is_empty());
    assert_eq!(token["token_type"], "Bearer");

    // The issued token is genuinely usable against a gated endpoint, not
    // just a well-formed response.
    if !common::db_available() {
        eprintln!("skipping the gated-endpoint check: no usable database (check SQL_URI)");
        return;
    }
    let access_token = token["access_token"].as_str().unwrap();
    let response = common::get_with_token(
        "GET /traits/BXD/10001 (with test token)",
        "/traits/BXD/10001",
        access_token,
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
}

/// The endpoint is part of the API's documentation in the default
/// configuration: no mode or bind address is needed to register it.
#[tokio::test]
async fn get_test_token_is_documented_by_default() {
    let response = common::get("GET /openapi.json", "/openapi.json").await;
    let body = response.into_body().collect().await.unwrap().to_bytes();
    let spec: Value = serde_json::from_slice(&body).unwrap();
    let operation = &spec["paths"]["/get-test-token"]["post"];
    assert!(operation.is_object(), "{}", spec["paths"]);
    assert!(operation["responses"]["403"].is_object());
}