sbol-db-server 0.1.7

HTTP server for sbol-db.
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Portal bootstrap and browser-session contract tests.
//!
//! These exercise the real combined router over SQLite so the SynBioHub v2
//! contracts, v1 compatibility endpoints, cookie transport, and shared
//! application facade are proven together rather than as isolated handler units.

use std::sync::Arc;

use axum::body::{to_bytes, Body};
use axum::http::header::{CACHE_CONTROL, SET_COOKIE, VARY};
use axum::http::{Request, Response, StatusCode};
use axum::Router;
use sbol_db_app::{AppServices, Registration};
use sbol_db_backend::Backend;
use sbol_db_core::User;
use sbol_db_server::{router, AppState, Metrics, SchemaCache, ServerConfig};
use sbol_db_sparql::{SparqlEngine, SparqlUpdateEngine};
use serde_json::{json, Value};
use sha3::{Digest, Sha3_256};
use tempfile::TempDir;
use tower::ServiceExt;

const BODY_LIMIT: usize = 1024 * 1024;

async fn app_with(config: ServerConfig) -> (Router, Arc<AppServices>, TempDir) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("v2-session.db");
    let url = format!("sqlite://{}", path.display());
    let backend = Backend::open(&url).await.expect("open sqlite backend");
    backend
        .migrator
        .as_ref()
        .expect("sqlite backend has a migrator")
        .run_migrations()
        .await
        .expect("run migrations");

    let services = Arc::new(AppServices::from_backend(&backend));
    let state = AppState {
        service: backend.store.clone(),
        sparql: Arc::new(SparqlEngine::new(backend.triple_source.clone())),
        sparql_update: Arc::new(SparqlUpdateEngine::new(
            backend.triple_source.clone(),
            backend.triple_writer.clone(),
        )),
        app: services.clone(),
        metrics: Metrics::install(None, env!("CARGO_PKG_VERSION")),
        jobs: backend.jobs.clone(),
        lab: backend.lab.clone(),
        config: config.clone(),
        backend_kind: backend.kind,
        sql_console: backend.sql_console.clone(),
        db_stats: backend.db_stats.clone(),
        lsm_stats: backend.lsm_stats.clone(),
        schema_cache: Arc::new(SchemaCache::new()),
    };
    (router(state, config), services, dir)
}

async fn register(services: &AppServices, username: &str, email: &str, is_admin: bool) -> User {
    services
        .auth
        .register(Registration {
            username: username.to_owned(),
            name: format!("{username} name"),
            email: email.to_owned(),
            affiliation: Some("Example Lab".to_owned()),
            password: "s3cret".to_owned(),
            is_admin,
            is_curator: is_admin,
            is_member: true,
        })
        .await
        .expect("register user")
}

#[tokio::test]
async fn first_launch_setup_requires_the_configured_one_time_token() {
    let token = "phase-two-setup-token-with-more-than-32-characters";
    let config = ServerConfig {
        setup_token_hash: Some(Sha3_256::digest(token.as_bytes()).into()),
        allow_public_signup: false,
        ..ServerConfig::default()
    };
    let (app, services, _directory) = app_with(config).await;
    let setup = json!({
        "instanceName": "Production Registry",
        "userName": "admin",
        "userFullName": "Administrator",
        "userEmail": "admin@example.org",
        "userPassword": "correct horse battery staple",
        "userPasswordConfirm": "correct horse battery staple"
    })
    .to_string();

    let missing = send(
        &app,
        "POST",
        "/setup",
        &[("content-type", "application/json")],
        setup.clone(),
    )
    .await;
    assert_eq!(missing.status(), StatusCode::UNAUTHORIZED);
    assert!(!services.auth.any_admin().await.expect("admin lookup"));

    let accepted = send(
        &app,
        "POST",
        "/setup",
        &[
            ("content-type", "application/json"),
            ("x-sbol-db-setup-token", token),
        ],
        setup,
    )
    .await;
    assert_eq!(accepted.status(), StatusCode::OK);
    assert!(services.auth.any_admin().await.expect("admin lookup"));

    let theme = services
        .config
        .get("theme")
        .await
        .expect("theme lookup")
        .expect("theme stored");
    assert_eq!(theme["allowPublicSignup"], false);
}

#[tokio::test]
async fn concurrent_first_launch_requests_create_exactly_one_admin() {
    let (app, services, _directory) = app_with(ServerConfig::default()).await;
    let first = json!({
        "userName": "first-admin",
        "userEmail": "first@example.org",
        "userPassword": "first password",
        "userPasswordConfirm": "first password"
    })
    .to_string();
    let second = json!({
        "userName": "second-admin",
        "userEmail": "second@example.org",
        "userPassword": "second password",
        "userPasswordConfirm": "second password"
    })
    .to_string();

    let first_request = send(
        &app,
        "POST",
        "/setup",
        &[("content-type", "application/json")],
        first,
    );
    let second_request = send(
        &app,
        "POST",
        "/setup",
        &[("content-type", "application/json")],
        second,
    );
    let (first_response, second_response) = tokio::join!(first_request, second_request);
    let mut statuses = [first_response.status(), second_response.status()];
    statuses.sort_unstable();
    assert_eq!(statuses, [StatusCode::OK, StatusCode::FORBIDDEN]);

    let users = services.users.list_users().await.expect("list users");
    assert_eq!(users.len(), 1);
    assert!(users[0].is_admin);
}

async fn send(
    app: &Router,
    method: &str,
    uri: &str,
    headers: &[(&str, &str)],
    body: impl Into<Body>,
) -> Response<Body> {
    let mut builder = Request::builder().method(method).uri(uri);
    for (name, value) in headers {
        builder = builder.header(*name, *value);
    }
    app.clone()
        .oneshot(builder.body(body.into()).expect("request"))
        .await
        .expect("response")
}

async fn json_body(response: Response<Body>) -> Value {
    let bytes = to_bytes(response.into_body(), BODY_LIMIT)
        .await
        .expect("response body");
    serde_json::from_slice(&bytes).expect("JSON response")
}

fn cookie_pair(response: &Response<Body>) -> String {
    response
        .headers()
        .get(SET_COOKIE)
        .expect("Set-Cookie")
        .to_str()
        .expect("cookie text")
        .split(';')
        .next()
        .expect("cookie pair")
        .to_owned()
}

#[tokio::test]
async fn instance_contract_is_safe_and_matches_enforced_registration_policy() {
    let (app, services, _dir) = app_with(ServerConfig::default()).await;

    let response = send(&app, "GET", "/api/v2/instance", &[], Body::empty()).await;
    assert_eq!(response.status(), StatusCode::OK);
    let initial = json_body(response).await;
    assert_eq!(initial["name"], "SBOL DB");
    assert_eq!(initial["setup_required"], true);
    assert_eq!(initial["policies"]["allow_public_signup"], true);
    assert_eq!(initial["capabilities"]["browser_sessions"], true);

    register(&services, "admin", "admin@example.org", true).await;
    services
        .config
        .set(
            "theme",
            &json!({
                "instanceName": "Cell Atlas",
                "instanceUrl": "https://parts.example.org",
                "uriPrefix": "https://parts.example.org/",
                "frontPageText": "A **curated** registry",
                "themeParameters": [
                    {"name": "Base Color", "variable": "baseColor", "value": "#D25627"}
                ],
                "allowPublicSignup": false,
                "requireLogin": true,
                "firstLaunch": true,
                "sendgridApiKey": "must-never-be-public"
            }),
        )
        .await
        .expect("store theme");

    let response = send(&app, "GET", "/api/v2/instance", &[], Body::empty()).await;
    let instance = json_body(response).await;
    assert_eq!(instance["name"], "Cell Atlas");
    // Classic clients may retain their stored theme, but it is deliberately
    // absent from the native SBOL DB bootstrap and cannot recolor the app.
    assert!(instance.get("accent_color").is_none());
    assert_eq!(instance["setup_required"], false);
    assert_eq!(instance["policies"]["allow_public_signup"], false);
    assert_eq!(instance["policies"]["require_login"], true);
    let encoded = instance.to_string();
    assert!(!encoded.contains("sendgrid"));
    assert!(!encoded.contains("must-never-be-public"));

    // Derived setup state also wins on the compatibility representation.
    let theme = json_body(send(&app, "GET", "/admin/theme", &[], Body::empty()).await).await;
    assert_eq!(theme["firstLaunch"], false);

    // The same stored policy drives actual registration, not just UI display.
    let form = "name=Visitor&username=visitor&email=visitor%40example.org&password=s3cret";
    let response = send(
        &app,
        "POST",
        "/register",
        &[
            ("content-type", "application/x-www-form-urlencoded"),
            ("accept", "application/json"),
        ],
        Body::from(form),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn browser_session_login_resolution_and_logout_share_one_revoked_token() {
    let config = ServerConfig {
        session_cookie_secure: true,
        ..ServerConfig::default()
    };
    let (app, services, _dir) = app_with(config).await;
    let alice = register(&services, "alice", "alice@example.org", false).await;
    let login = json!({"identifier": "alice@example.org", "password": "s3cret"}).to_string();
    let response = send(
        &app,
        "POST",
        "/api/v2/session",
        &[
            ("content-type", "application/json"),
            ("host", "parts.example.org"),
            ("origin", "https://parts.example.org"),
        ],
        Body::from(login),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
    let set_cookie = response.headers()[SET_COOKIE].to_str().unwrap();
    assert!(set_cookie.contains("HttpOnly"));
    assert!(set_cookie.contains("SameSite=Lax"));
    assert!(set_cookie.contains("Secure"));
    let cookie = cookie_pair(&response);
    let logged_in = json_body(response).await;
    assert_eq!(logged_in["authenticated"], true);
    assert_eq!(logged_in["user"]["id"], alice.id.to_string());
    assert_eq!(logged_in["user"]["username"], "alice");
    assert!(logged_in.get("token").is_none());
    let encoded = logged_in.to_string();
    assert!(!encoded.contains("password"));
    assert!(!encoded.contains("reset_password"));

    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("cookie", &cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers()[VARY]
        .to_str()
        .unwrap()
        .contains("Authorization"));
    assert_eq!(json_body(response).await["user"]["username"], "alice");

    let response = send(
        &app,
        "DELETE",
        "/api/v2/session",
        &[
            ("cookie", &cookie),
            ("host", "parts.example.org"),
            ("origin", "https://parts.example.org"),
        ],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    assert!(response.headers()[SET_COOKIE]
        .to_str()
        .unwrap()
        .contains("Max-Age=0"));

    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("cookie", &cookie)],
        Body::empty(),
    )
    .await;
    let logged_out = json_body(response).await;
    assert_eq!(logged_out["authenticated"], false);
    assert!(logged_out["user"].is_null());
}

#[tokio::test]
async fn credential_precedence_and_origin_guards_are_explicit() {
    let (app, services, _dir) = app_with(ServerConfig::default()).await;
    let alice = register(&services, "alice", "alice@example.org", false).await;
    let bob = register(&services, "bob", "bob@example.org", false).await;
    let admin = register(&services, "admin", "admin@example.org", true).await;
    let alice_token = services.auth.issue_token(alice.id).await.unwrap();
    let bob_token = services.auth.issue_token(bob.id).await.unwrap();
    let admin_token = services.auth.issue_token(admin.id).await.unwrap();
    let alice_cookie = format!("sbol-db-token={alice_token}");

    // An explicit bearer credential wins over ambient cookie authority.
    let bearer = format!("Bearer {bob_token}");
    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("authorization", &bearer), ("cookie", &alice_cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(json_body(response).await["user"]["username"], "bob");

    // A malformed explicit Authorization header does not fall through.
    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[
            ("authorization", "Basic not-bearer"),
            ("cookie", &alice_cookie),
        ],
        Body::empty(),
    )
    .await;
    assert_eq!(json_body(response).await["authenticated"], false);

    // Cookie-backed unsafe requests are same-origin only, and rejection does
    // not revoke the session.
    let response = send(
        &app,
        "DELETE",
        "/api/v2/session",
        &[
            ("cookie", &alice_cookie),
            ("host", "parts.example.org"),
            ("origin", "https://evil.example"),
        ],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    assert_eq!(json_body(response).await["error"]["code"], "forbidden");
    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("cookie", &alice_cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(json_body(response).await["user"]["username"], "alice");

    let response = send(
        &app,
        "POST",
        "/api/v2/session",
        &[
            ("content-type", "application/json"),
            ("host", "parts.example.org"),
            ("origin", "https://evil.example"),
        ],
        Body::from(json!({"identifier": "alice", "password": "s3cret"}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FORBIDDEN);

    let response = send(
        &app,
        "POST",
        "/api/v2/session",
        &[("content-type", "application/json")],
        Body::from(json!({"identifier": "alice", "password": "wrong"}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(response.headers().get(SET_COOKIE).is_none());
    assert_eq!(json_body(response).await["error"]["code"], "unauthorized");

    // The relocated workbench is protected at its JSON boundary, not just by
    // a client-side route guard.
    let response = send(&app, "GET", "/lab/api/info", &[], Body::empty()).await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    let alice_bearer = format!("Bearer {alice_token}");
    let response = send(
        &app,
        "GET",
        "/lab/api/info",
        &[("authorization", &alice_bearer)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    let admin_bearer = format!("Bearer {admin_token}");
    let response = send(
        &app,
        "GET",
        "/lab/api/info",
        &[("authorization", &admin_bearer)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn require_login_policy_is_enforced_by_v2_resources() {
    let (app, services, _dir) = app_with(ServerConfig::default()).await;
    let admin = register(&services, "admin", "admin@example.org", true).await;
    services
        .config
        .set("theme", &json!({"requireLogin": true}))
        .await
        .expect("store require-login policy");

    for path in ["/api/v2", "/api/v2/instance", "/api/v2/session"] {
        let response = send(&app, "GET", path, &[], Body::empty()).await;
        assert_eq!(response.status(), StatusCode::OK, "bootstrap path {path}");
    }

    let response = send(&app, "GET", "/api/v2/search", &[], Body::empty()).await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(response).await["error"]["code"], "unauthorized");

    let token = services.auth.issue_token(admin.id).await.unwrap();
    let bearer = format!("Bearer {token}");
    let response = send(
        &app,
        "GET",
        "/api/v2/search",
        &[("authorization", &bearer)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn compatibility_browser_login_cookie_is_understood_and_revoked_by_v2() {
    let (app, services, _dir) = app_with(ServerConfig::default()).await;
    register(&services, "alice", "alice@example.org", false).await;
    let response = send(
        &app,
        "POST",
        "/login",
        &[
            ("content-type", "application/x-www-form-urlencoded"),
            ("accept", "text/html"),
        ],
        Body::from("email=alice%40example.org&password=s3cret"),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FOUND);
    let cookie = cookie_pair(&response);

    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("cookie", &cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(json_body(response).await["user"]["username"], "alice");

    // V1 logout accepts the browser cookie for revocation even though V1 data
    // handlers retain their X-authorization compatibility contract.
    let response = send(
        &app,
        "POST",
        "/logout",
        &[("accept", "text/html"), ("cookie", &cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::FOUND);
    assert!(response.headers()[SET_COOKIE]
        .to_str()
        .unwrap()
        .contains("Max-Age=0"));

    let response = send(
        &app,
        "GET",
        "/api/v2/session",
        &[("cookie", &cookie)],
        Body::empty(),
    )
    .await;
    assert_eq!(json_body(response).await["authenticated"], false);
}

#[tokio::test]
async fn account_profile_and_password_commands_are_self_scoped_and_secret_free() {
    let (app, services, _dir) = app_with(ServerConfig::default()).await;
    let alice = register(&services, "alice", "alice@example.org", false).await;
    let token = services.auth.issue_token(alice.id).await.unwrap();
    let bearer = format!("Bearer {token}");

    for (method, path) in [
        ("GET", "/api/v2/account"),
        ("PATCH", "/api/v2/account"),
        ("POST", "/api/v2/account/password"),
        ("GET", "/api/v2/account/shared"),
    ] {
        let response = send(
            &app,
            method,
            path,
            &[("content-type", "application/json")],
            Body::from("{}"),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN, "{method} {path}");
    }

    let response = send(
        &app,
        "GET",
        "/api/v2/account",
        &[("authorization", &bearer)],
        Body::empty(),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
    let profile = json_body(response).await;
    assert_eq!(profile["username"], "alice");
    assert_eq!(profile["name"], "alice name");
    let encoded = profile.to_string();
    assert!(!encoded.contains("password"));
    assert!(!encoded.contains("token"));

    let response = send(
        &app,
        "PATCH",
        "/api/v2/account",
        &[
            ("authorization", &bearer),
            ("content-type", "application/json"),
        ],
        Body::from(json!({"name": "Alice Researcher", "affiliation": "CU Boulder"}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let profile = json_body(response).await;
    assert_eq!(profile["name"], "Alice Researcher");
    assert_eq!(profile["affiliation"], "CU Boulder");
    assert_eq!(profile["is_admin"], false);

    let response = send(
        &app,
        "PATCH",
        "/api/v2/account",
        &[
            ("authorization", &bearer),
            ("content-type", "application/json"),
        ],
        Body::from(json!({"is_admin": true}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let response = send(
        &app,
        "POST",
        "/api/v2/account/password",
        &[
            ("authorization", &bearer),
            ("content-type", "application/json"),
        ],
        Body::from(json!({"current_password": "wrong", "new_password": "new-secret"}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let response = send(
        &app,
        "POST",
        "/api/v2/account/password",
        &[
            ("authorization", &bearer),
            ("content-type", "application/json"),
        ],
        Body::from(json!({"current_password": "s3cret", "new_password": "new-secret"}).to_string()),
    )
    .await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    assert!(services
        .auth
        .authenticate("alice", "s3cret", &ServerConfig::default().password_salt)
        .await
        .is_err());
    assert!(services
        .auth
        .authenticate(
            "alice",
            "new-secret",
            &ServerConfig::default().password_salt
        )
        .await
        .is_ok());
}