vyuh 0.2.6

Vyuh web framework for Axum and SQLx with handler-first APIs
Documentation
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use vyuh::{
    SiteConf,
    auth::{
        ApiKey, ApiKeyConf, ApiKeyPrincipal, ApiKeyVerifier, AuthAudiencePolicy, AuthConf,
        AuthError, AuthUser, BitRole, JWTClaim, TokenKind, permit,
    },
    bundles, routes,
    routes::{Json, StatusCode},
    testing::TestClient,
};

fn test_conf() -> SiteConf {
    SiteConf {
        secret_key: "auth-test-secret-minimum-32-chars".to_string(),
        log_init: false,
        logging: vyuh::logging::LoggingConf {
            env_prefix: None,
            rules: vec![],
        },
        ..SiteConf::default()
    }
}

#[derive(BitRole)]
enum TestRole {
    Manager,
    Viewer,
}

#[derive(Debug, Serialize, JsonSchema)]
struct WhoAmI {
    key: String,
    roles: u64,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema, PartialEq)]
struct KeyInfo {
    key_id: String,
    subject: Option<String>,
    roles: u64,
}

struct StaticApiKeyVerifier;

impl ApiKeyVerifier for StaticApiKeyVerifier {
    async fn verify(&self, presented: &str) -> Result<ApiKeyPrincipal, AuthError> {
        if presented == "valid-key" {
            Ok(ApiKeyPrincipal::new("key-1")
                .subject("service-1")
                .roles(TestRole::Viewer.to_role_type()))
        } else {
            Err(AuthError::InvalidApiKey)
        }
    }
}

#[bundles::route(path = "/public")]
async fn public() -> Json<&'static str> {
    Json("ok")
}

#[bundles::route(path = "/me")]
async fn me(user: AuthUser) -> Json<WhoAmI> {
    Json(WhoAmI {
        key: user.key.to_string(),
        roles: user.roles,
    })
}

#[bundles::route(path = "/api-key")]
async fn api_key_route(key: ApiKey) -> Json<KeyInfo> {
    Json(KeyInfo {
        key_id: key.key_id.to_string(),
        subject: key.subject.as_ref().map(ToString::to_string),
        roles: key.roles,
    })
}

#[bundles::route(path = "/secure")]
async fn secure(_permit: permit!(TestRole, Manager)) -> Json<WhoAmI> {
    Json(WhoAmI {
        key: "manager".to_string(),
        roles: TestRole::Manager.to_role_type(),
    })
}

#[tokio::test]
async fn auth_accepts_bearer_authorization_header() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            me,
        },
    )
    .await
    .unwrap();
    let token = site
        .auth()
        .create_token_pair(
            AuthUser::new("user-1", TestRole::Viewer.to_role_type()),
            &[],
        )
        .unwrap()
        .access_token;
    let client = TestClient::new(site.clone());

    client
        .get("/me")
        .header("authorization", &format!("Bearer {token}"))
        .send()
        .await
        .assert_status(StatusCode::OK);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn public_route_does_not_require_auth() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            public,
        },
    )
    .await
    .unwrap();
    let client = TestClient::new(site.clone());

    client
        .get("/public")
        .send()
        .await
        .assert_status(StatusCode::OK);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn auth_accepts_legacy_jwt_authorization_header() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            me,
        },
    )
    .await
    .unwrap();
    let token = site
        .auth()
        .create_token_pair(
            AuthUser::new("user-1", TestRole::Viewer.to_role_type()),
            &[],
        )
        .unwrap()
        .access_token;
    let client = TestClient::new(site.clone());

    client
        .get("/me")
        .header("authorization", &format!("JWT {token}"))
        .send()
        .await
        .assert_status(StatusCode::OK);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn auth_missing_token_returns_unauthorized() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            me,
        },
    )
    .await
    .unwrap();
    let client = TestClient::new(site.clone());

    client
        .get("/me")
        .send()
        .await
        .assert_status(StatusCode::UNAUTHORIZED);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn auth_permit_rejects_missing_role() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            secure,
        },
    )
    .await
    .unwrap();
    let token = site
        .auth()
        .create_token_pair(
            AuthUser::new("user-1", TestRole::Viewer.to_role_type()),
            &[],
        )
        .unwrap()
        .access_token;
    let client = TestClient::new(site.clone());

    client
        .get("/secure")
        .header("authorization", &format!("Bearer {token}"))
        .send()
        .await
        .assert_status(StatusCode::FORBIDDEN);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn auth_user_rejects_refresh_token() {
    let site = vyuh::Site::build(
        test_conf(),
        bundles::bundle! {
            me,
        },
    )
    .await
    .unwrap();
    let token = site
        .auth()
        .create_token_pair(
            AuthUser::new("user-1", TestRole::Viewer.to_role_type()),
            &[],
        )
        .unwrap()
        .refresh_token;
    let client = TestClient::new(site.clone());

    client
        .get("/me")
        .header("authorization", &format!("Bearer {token}"))
        .send()
        .await
        .assert_status(StatusCode::UNAUTHORIZED);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn refresh_rejects_access_token() {
    let site = vyuh::Site::build(test_conf(), bundles::Bundle::new())
        .await
        .unwrap();
    let token = site
        .auth()
        .create_token_pair(
            AuthUser::new("user-1", TestRole::Viewer.to_role_type()),
            &[],
        )
        .unwrap()
        .access_token;
    let req = routes::Request::builder()
        .header("authorization", format!("Bearer {token}"))
        .body(routes::Body::empty())
        .unwrap();
    let (parts, _) = req.into_parts();

    let err = site.auth().refresh(&parts, &[]).unwrap_err();
    assert!(matches!(err, AuthError::WrongTokenKind));

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn audience_required_rejects_route_without_audience() {
    let conf = test_conf().auth(AuthConf::default().audience(AuthAudiencePolicy::Required));
    let site = vyuh::Site::build(
        conf,
        bundles::bundle! {
            me,
        },
    )
    .await
    .unwrap();
    let token = site
        .auth()
        .create_token_pair(AuthUser::new("user-1", 0), &["web"])
        .unwrap()
        .access_token;
    let client = TestClient::new(site.clone());

    client
        .get("/me")
        .header("authorization", &format!("Bearer {token}"))
        .send()
        .await
        .assert_status(StatusCode::FORBIDDEN);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn issuer_must_match_when_configured() {
    let conf = test_conf().auth(AuthConf::default().issuer("expected"));
    let site = vyuh::Site::build(conf, bundles::Bundle::new())
        .await
        .unwrap();
    let claims = JWTClaim::new(
        &AuthUser::new("user-1", 0),
        "",
        Some("wrong".to_string()),
        vec![],
        3600,
        TokenKind::Access,
    );
    let token = site.auth().encode(&claims).unwrap();

    let err = site.auth().decode(&token).unwrap_err();
    assert!(matches!(
        err,
        AuthError::InvalidToken | AuthError::InternalError(_)
    ));

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn leeway_allows_recently_expired_tokens() {
    let conf = test_conf().auth(AuthConf::default().leeway_seconds(30));
    let site = vyuh::Site::build(conf, bundles::Bundle::new())
        .await
        .unwrap();
    let claims = JWTClaim::new(
        &AuthUser::new("user-1", 0),
        "",
        None,
        vec![],
        -10,
        TokenKind::Access,
    );
    let token = site.auth().encode(&claims).unwrap();

    site.auth().decode(&token).unwrap();

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn configured_minimum_secret_length_is_validated() {
    let err = vyuh::Site::build(
        SiteConf::default()
            .secret_key("short")
            .log_init(false)
            .auth(AuthConf::default().min_secret_len(32)),
        bundles::Bundle::new(),
    )
    .await
    .unwrap_err();

    assert!(err.to_string().contains("secret_key"));
}

#[tokio::test]
async fn default_cookies_are_disabled() {
    let site = vyuh::Site::build(test_conf(), bundles::Bundle::new())
        .await
        .unwrap();
    let mut response = routes::Response::new(routes::Body::empty());
    site.auth()
        .login_user(AuthUser::new("user-1", 0), &[], &mut response)
        .unwrap();

    assert!(
        response
            .headers()
            .get_all("set-cookie")
            .iter()
            .next()
            .is_none()
    );

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn opt_in_cookies_are_written() {
    let conf = test_conf().auth(AuthConf::cookie_pair("access_token", "refresh_token"));
    let site = vyuh::Site::build(conf, bundles::Bundle::new())
        .await
        .unwrap();
    let mut response = routes::Response::new(routes::Body::empty());
    site.auth()
        .login_user(AuthUser::new("user-1", 0), &[], &mut response)
        .unwrap();

    assert_eq!(response.headers().get_all("set-cookie").iter().count(), 2);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn api_key_extracts_from_configured_header() {
    let conf = test_conf()
        .auth(AuthConf::default().api_keys(ApiKeyConf::default().verifier(StaticApiKeyVerifier)));
    let site = vyuh::Site::build(
        conf,
        bundles::bundle! {
            api_key_route,
        },
    )
    .await
    .unwrap();
    let client = TestClient::new(site.clone());

    client
        .get("/api-key")
        .header("x-api-key", "valid-key")
        .send()
        .await
        .assert_json(
            StatusCode::OK,
            &KeyInfo {
                key_id: "key-1".to_string(),
                subject: Some("service-1".to_string()),
                roles: TestRole::Viewer.to_role_type(),
            },
        )
        .await;

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn api_key_authorization_scheme_works_when_configured() {
    let conf = test_conf()
        .auth(AuthConf::default().api_keys(ApiKeyConf::default().verifier(StaticApiKeyVerifier)));
    let site = vyuh::Site::build(
        conf,
        bundles::bundle! {
            api_key_route,
        },
    )
    .await
    .unwrap();
    let client = TestClient::new(site.clone());

    client
        .get("/api-key")
        .header("authorization", "ApiKey valid-key")
        .send()
        .await
        .assert_status(StatusCode::OK);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn api_key_query_param_is_explicit_opt_in() {
    let disabled_conf = test_conf()
        .auth(AuthConf::default().api_keys(ApiKeyConf::default().verifier(StaticApiKeyVerifier)));
    let disabled_site = vyuh::Site::build(
        disabled_conf,
        bundles::bundle! {
            api_key_route,
        },
    )
    .await
    .unwrap();
    let disabled_client = TestClient::new(disabled_site.clone());

    disabled_client
        .get("/api-key?api_key=valid-key")
        .send()
        .await
        .assert_status(StatusCode::UNAUTHORIZED);
    disabled_site.shutdown_and_wait().await;

    let enabled_conf = test_conf().auth(
        AuthConf::default().api_keys(
            ApiKeyConf::default()
                .allow_query_param(true)
                .verifier(StaticApiKeyVerifier),
        ),
    );
    let enabled_site = vyuh::Site::build(
        enabled_conf,
        bundles::bundle! {
            api_key_route,
        },
    )
    .await
    .unwrap();
    let enabled_client = TestClient::new(enabled_site.clone());

    enabled_client
        .get("/api-key?api_key=valid-key")
        .send()
        .await
        .assert_status(StatusCode::OK);

    enabled_site.shutdown_and_wait().await;
}

#[tokio::test]
async fn api_key_missing_verifier_returns_server_error() {
    let conf = test_conf().auth(AuthConf::default().api_keys(ApiKeyConf::default().enabled(true)));
    let site = vyuh::Site::build(
        conf,
        bundles::bundle! {
            api_key_route,
        },
    )
    .await
    .unwrap();
    let client = TestClient::new(site.clone());

    client
        .get("/api-key")
        .header("x-api-key", "valid-key")
        .send()
        .await
        .assert_status(StatusCode::INTERNAL_SERVER_ERROR);

    site.shutdown_and_wait().await;
}

#[tokio::test]
async fn api_key_openapi_security_scheme_is_generated() {
    let conf = test_conf()
        .auth(AuthConf::default().api_keys(ApiKeyConf::default().verifier(StaticApiKeyVerifier)));
    let bundle = bundles::bundle! {
        api_key_route,
    }
    .with_openapi(
        bundles::OpenApiConf::default()
            .title("Auth API")
            .spec("/openapi.json"),
    );
    let site = vyuh::Site::build(conf, bundle).await.unwrap();
    let client = TestClient::new(site.clone());

    let spec: serde_json::Value = client
        .get("/openapi.json")
        .send()
        .await
        .assert_ok()
        .json()
        .await;
    assert_eq!(
        spec["components"]["securitySchemes"]["apiKeyAuth"]["type"],
        "apiKey"
    );
    assert_eq!(
        spec["components"]["securitySchemes"]["apiKeyAuth"]["name"],
        "X-API-Key"
    );

    site.shutdown_and_wait().await;
}