about summary refs log tree commit diff
path: root/tests/auth.rs
blob: 1541a6f476e38b4d6d459e3f93614681eb1296ef (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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
//! Exercises src/auth.rs against a real gn-auth instance. Needs one
//! running and reachable at AUTH_SERVER_URL (see docs/gn-auth.md);
//! skips with a message rather than failing when it isn't, same
//! pattern as the MariaDB-backed tests.
//!
//! The fixtures below (token, resource id) are produced by hand
//! against a from-scratch gn-auth instance as described in
//! RELEASE_NOTES.md -- set these environment variables to point at
//! your own instance and data before running:
//!   GN4_TEST_AUTH_TOKEN   - a valid bearer token (e.g. from the
//!                           password grant against /auth/token)
//!   GN4_TEST_RESOURCE_ID  - a resource-id that token's user owns
//!                           (e.g. from POST /auth/resource/populations/create)

use genenetwork4::auth::{self, AuthToken};

mod common;
use genenetwork4::config::Config;
use tower::ServiceExt;

fn auth_server_reachable(auth_server_url: &str) -> bool {
    ureq::get(format!(
        "{}/auth/public-jwks",
        auth_server_url.trim_end_matches('/')
    ))
    .call()
    .is_ok()
}

fn test_fixtures() -> Option<(String, String, String)> {
    let auth_server_url = Config::load().auth_server_url;
    let token = std::env::var("GN4_TEST_AUTH_TOKEN").ok()?;
    let resource_id = std::env::var("GN4_TEST_RESOURCE_ID").ok()?;
    Some((auth_server_url, token, resource_id))
}

#[test]
fn is_publicly_readable_skips_authorisation_entirely() {
    // No gn-auth call at all for public data -- this doesn't even need
    // a reachable server, which is the point: a public dataset costs
    // nothing beyond token verification.
    let recent = "2024-01-01 00:00:00";
    assert!(auth::is_publicly_readable(2, 0, recent));
    assert!(!auth::is_publicly_readable(0, 0, recent));
}

#[tokio::test]
async fn valid_token_is_accepted_and_resolves_sub() {
    let Some((auth_server_url, token, _)) = test_fixtures() else {
        eprintln!(
            "skipping valid_token_is_accepted_and_resolves_sub: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)"
        );
        return;
    };
    if !auth_server_reachable(&auth_server_url) {
        eprintln!(
            "skipping valid_token_is_accepted_and_resolves_sub: no gn-auth at {auth_server_url}"
        );
        return;
    }

    use axum::extract::FromRequestParts;
    use axum::http::Request;

    let request = Request::builder()
        .header("Authorization", format!("Bearer {token}"))
        .body(())
        .unwrap();
    let (mut parts, ()) = request.into_parts();
    let auth_token = AuthToken::from_request_parts(&mut parts, &())
        .await
        .unwrap();

    assert!(!auth_token.sub.is_empty());
    assert_eq!(auth_token.raw, token);
}

/// The proxy logs `$upstream_http_x_gn4_user`; this is where that header
/// comes from. It has to name the caller on authenticated responses and
/// stay off the ones with no identity to name -- the difference between "a
/// log that says who is working" and one that says only which address.
#[tokio::test]
async fn an_authenticated_response_names_its_caller() {
    if !common::auth_server_available() {
        eprintln!("skipping an_authenticated_response_names_its_caller: no gn-auth reachable");
        return;
    }
    let Some(token) = common::auth_token().await else {
        eprintln!("skipping an_authenticated_response_names_its_caller: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
        return;
    };
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;

    let response = genenetwork4::app()
        .oneshot(
            Request::builder()
                .uri("/species")
                .header("Authorization", format!("Bearer {token}"))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let named = response
        .headers()
        .get(genenetwork4::auth::USER_HEADER)
        .expect("an authenticated response names its caller")
        .to_str()
        .unwrap()
        .to_string();
    // ... and it is the token's own subject, not a label.
    use axum::extract::FromRequestParts;
    let request = Request::builder()
        .header("Authorization", format!("Bearer {token}"))
        .body(())
        .unwrap();
    let (mut parts, ()) = request.into_parts();
    let auth_token = genenetwork4::auth::AuthToken::from_request_parts(&mut parts, &())
        .await
        .unwrap();
    assert_eq!(named, auth_token.sub);

    // A response with no identity (no token) carries no name.
    let response = genenetwork4::app()
        .oneshot(Request::builder().uri("/version").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert!(
        response.headers().get(genenetwork4::auth::USER_HEADER).is_none(),
        "no token, no name"
    );
    let _ = response.into_body().collect().await;
}

#[tokio::test]
async fn malformed_token_is_rejected() {
    let Some((auth_server_url, _, _)) = test_fixtures() else {
        eprintln!(
            "skipping malformed_token_is_rejected: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)"
        );
        return;
    };
    if !auth_server_reachable(&auth_server_url) {
        eprintln!("skipping malformed_token_is_rejected: no gn-auth at {auth_server_url}");
        return;
    }

    use axum::extract::FromRequestParts;
    use axum::http::Request;

    let request = Request::builder()
        .header("Authorization", "Bearer not-a-real-token")
        .body(())
        .unwrap();
    let (mut parts, ()) = request.into_parts();
    let result = AuthToken::from_request_parts(&mut parts, &()).await;

    assert!(result.is_err());
    assert_eq!(result.err().unwrap().code, "invalid_token");
}

#[test]
fn owner_is_authorised_and_stranger_is_not() {
    let Some((auth_server_url, token, resource_id)) = test_fixtures() else {
        eprintln!(
            "skipping owner_is_authorised_and_stranger_is_not: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)"
        );
        return;
    };
    if !auth_server_reachable(&auth_server_url) {
        eprintln!(
            "skipping owner_is_authorised_and_stranger_is_not: no gn-auth at {auth_server_url}"
        );
        return;
    }

    let owner = AuthToken {
        scheme: auth::Scheme::Jwt,
        id: None,
        sub: "owner".to_string(),
        scope: "profile resource".to_string(),
        raw: token,
    };
    let authorised = auth::authorise(
        &auth_server_url,
        &owner,
        &resource_id,
        "group:resource:view-resource",
    )
    .unwrap();
    assert!(
        authorised,
        "the resource's own creator should hold view-resource"
    );

    // A syntactically-valid but unrelated token has no roles on this
    // resource at all -- gn-auth's own default, not something this
    // client invents.
    let stranger = AuthToken {
        scheme: auth::Scheme::Jwt,
        id: None,
        sub: "stranger".to_string(),
        scope: "profile resource".to_string(),
        raw: "not-a-real-token".to_string(),
    };
    let result = auth::authorise(
        &auth_server_url,
        &stranger,
        &resource_id,
        "group:resource:view-resource",
    );
    // An invalid bearer token makes gn-auth treat the call as
    // anonymous (see docs/gn-auth.md); anonymous gets no roles on a
    // non-public resource, so this comes back Ok(false), not an error.
    assert_eq!(result, Ok(false));
}

#[test]
fn authorisation_result_is_cached() {
    let Some((auth_server_url, token, resource_id)) = test_fixtures() else {
        eprintln!(
            "skipping authorisation_result_is_cached: set GN4_TEST_AUTH_TOKEN and GN4_TEST_RESOURCE_ID (see docs/gn-auth.md)"
        );
        return;
    };
    if !auth_server_reachable(&auth_server_url) {
        eprintln!("skipping authorisation_result_is_cached: no gn-auth at {auth_server_url}");
        return;
    }

    let owner = AuthToken {
        scheme: auth::Scheme::Jwt,
        id: None,
        sub: "cache-test-owner".to_string(),
        scope: "profile resource".to_string(),
        raw: token,
    };

    let start = std::time::Instant::now();
    auth::authorise(
        &auth_server_url,
        &owner,
        &resource_id,
        "group:resource:view-resource",
    )
    .unwrap();
    let first_call = start.elapsed();

    let start = std::time::Instant::now();
    auth::authorise(
        &auth_server_url,
        &owner,
        &resource_id,
        "group:resource:view-resource",
    )
    .unwrap();
    let second_call = start.elapsed();

    // The second call hits the in-process cache and shouldn't touch
    // the network at all; it should be at least an order of magnitude
    // faster than the first, uncached call.
    assert!(
        second_call < first_call / 2,
        "expected the cached call ({second_call:?}) to be much faster than the first ({first_call:?})"
    );
}