sbol-db-server 0.1.8

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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! SynBioHub v1 wire-compatibility adapter.
//!
//! This module is the quarantine layer for classic SynBioHub's HTTP quirks:
//! the `X-authorization` token header, the Accept-negotiated login response,
//! the form-encoded request bodies. Every route here talks only to the
//! [`AppServices`](sbol_db_app::AppServices) facade through `state.app`; none
//! reach into a concrete backend. Containing the quirks here lets the idiomatic
//! V2 surface evolve without inheriting them.

mod admin;
mod attachments;
mod auth;
mod download;
mod edit;
mod jobs;
mod mutate;
mod permission;
mod plugins;
mod queries;
mod render;
mod routes;
mod search;
mod sequence;
mod setup;
mod share;
mod submit;
mod support;

use axum::extract::{Request, State};
use axum::middleware::Next;
use axum::response::Response;
use axum::routing::{get, post};
use axum::Router;
use sbol_db_core::User;

use crate::{metrics, AppState};

/// The account a request authenticates as, resolved from the `X-authorization`
/// token by [`attach_current_user`] and read by the V1 routes through an
/// `Extension<CurrentUser>`. Anonymous (`None`) when no valid token is present.
#[derive(Clone, Debug, Default)]
pub struct CurrentUser(pub Option<User>);

/// The V1 SynBioHub-compatible auth routes, with the `X-authorization`
/// middleware applied so every route observes a resolved [`CurrentUser`]. The
/// Basic-auth `/sparql-auth*` path is unrelated and stays in [`crate::auth`]
/// for Virtuoso-protocol clients.
pub fn router(state: AppState) -> Router<AppState> {
    let public = Router::new()
        .route("/login", post(auth::login))
        .route("/logout", post(auth::logout))
        .route("/register", post(auth::register))
        .route(
            "/profile",
            get(auth::get_profile).post(auth::update_profile),
        )
        .route("/resetPassword", post(auth::reset_password))
        .route("/setNewPassword", post(auth::set_new_password))
        // First-launch setup: provision the first administrator + branding. The
        // UI shows its setup wizard when /admin/theme reports firstLaunch.
        .route("/setup", get(setup::get_setup).post(setup::post_setup))
        // The public Web of Registries update callback. Not admin-gated; it is
        // authenticated by the shared update secret, matching classic.
        .route(
            "/updateWebOfRegistries",
            post(admin::update_web_of_registries),
        )
        // Plugin proxying and the temp-file / async-stream handoffs. Public
        // (authenticated, not admin-gated), matching classic's
        // `requirePublicLogin` mount.
        .route("/callPlugin", post(plugins::call_plugin))
        .route("/expose/:id", get(plugins::serve_expose))
        .route(
            "/stream/:id",
            get(plugins::serve_stream).delete(plugins::clear_stream),
        )
        // Admin resources classic serves to anonymous callers so the UI can
        // render: theme/plugins/registries GET are public; the theme POST
        // self-authorizes (ConfigService rejects a non-admin with 403).
        .route("/admin/theme", get(admin::get_theme).post(admin::set_theme))
        .route("/admin/plugins", get(admin::plugins))
        .route("/admin/registries", get(admin::registries))
        // Jobs: the cancel/restart actions (the caller's `/jobs` list is served
        // by the native server router).
        .route("/actions/job/cancel", post(jobs::cancel_job))
        .route("/actions/job/restart", post(jobs::restart_job))
        .route("/corruptLog", get(jobs::corrupt_log))
        // UI-support data APIs (autocomplete, DataTables feed, result stream,
        // sequence-search entry point).
        .route("/autocomplete/:query", get(support::autocomplete))
        .route("/api/datatables", get(support::datatables))
        .route(
            "/api/stream/:id",
            get(support::stream).delete(support::stream),
        )
        .route(
            "/sbsearch",
            get(support::sbsearch_get).post(support::sbsearch_post),
        )
        // Share links: mint a share hash for an object, and the hash-scoped
        // read surface that serves the (possibly private) object without login.
        .route(
            "/user/:userId/:collectionId/:displayId/:version/shareLink",
            get(share::share_link),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share",
            get(share::share_bare),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/full",
            get(share::share_full),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/sbol",
            get(share::share_sbol),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/sbolnr",
            get(share::share_sbolnr),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/gb",
            get(share::share_genbank),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/fasta",
            get(share::share_fasta),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/gff",
            get(share::share_gff),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/omex",
            get(share::share_omex),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/summary",
            get(share::share_summary),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/metadata",
            get(share::share_metadata),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/subCollections",
            get(share::share_sub_collections),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/uses",
            get(share::share_uses),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/usesCount",
            get(share::share_uses_count),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/twins",
            get(share::share_twins),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/:hash/share/twinsCount",
            get(share::share_twins_count),
        )
        // Remote federation client. The remoteLogin/Search/Submit routes are
        // classic's deprecated no-HTML aliases for login/search/submit;
        // copyFromRemote imports an object from the registry that owns it.
        .route("/remoteLogin", post(auth::login))
        .route("/remoteSearch", get(routes::search_root))
        .route("/remoteSearch/*query", get(routes::search))
        .route("/remoteSubmit", post(submit::submit))
        .route("/remoteSubmit/", post(submit::submit))
        .route(
            "/public/:collectionId/:displayId/:version/copyFromRemote",
            get(support::public_copy_from_remote).post(support::public_copy_from_remote),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/copyFromRemote",
            get(support::user_copy_from_remote).post(support::user_copy_from_remote),
        )
        // Classic's /browse is the root-collections listing the UI browses; it
        // returns each collection with the route `url` and `public` flag that
        // /rootCollections omits.
        .route("/browse", get(routes::browse))
        .route("/submit", post(submit::submit))
        // Classic registers `/submit/` (trailing slash); Express matches both,
        // so accept both to stay a drop-in for clients built against either.
        .route("/submit/", post(submit::submit))
        // Bare object resolution (classic's `views.topLevel`): a GET on the
        // object URI, its `/full` alias, and the version-less persistent identity
        // all return the object's recursive SBOL closure for a non-HTML client. A
        // version-less URI resolves to the latest version.
        .route(
            "/public/:collectionId/:displayId/:version",
            get(download::public_object),
        )
        .route(
            "/public/:collectionId/:displayId/:version/full",
            get(download::public_object_full),
        )
        .route(
            "/public/:collectionId/:displayId",
            get(download::public_object_pi),
        )
        .route(
            "/public/:collectionId/:displayId/sbol",
            get(download::public_sbol_pi),
        )
        .route(
            "/public/:collectionId/:displayId/sbolnr",
            get(download::public_sbolnr_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version",
            get(download::user_object),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/full",
            get(download::user_object_full),
        )
        .route(
            "/user/:userId/:collectionId/:displayId",
            get(download::user_object_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/sbol",
            get(download::user_sbol_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/sbolnr",
            get(download::user_sbolnr_pi),
        )
        // Destructive object verbs. Classic triggers these with GET on the
        // object path (a browser-form quirk); the facade holds the real verbs
        // and gates every one on caller ownership.
        .route(
            "/user/:userId/:collectionId/:displayId/:version/makePublic",
            post(mutate::user_make_public),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/remove",
            get(mutate::user_remove).post(mutate::user_remove),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/replace",
            get(mutate::user_replace).post(mutate::user_replace),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/removeCollection",
            get(mutate::user_remove_collection).post(mutate::user_remove_collection),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/icon",
            post(mutate::user_icon),
        )
        .route(
            "/public/:collectionId/:displayId/:version/remove",
            get(mutate::public_remove).post(mutate::public_remove),
        )
        .route(
            "/public/:collectionId/:displayId/:version/replace",
            get(mutate::public_replace).post(mutate::public_replace),
        )
        .route(
            "/public/:collectionId/:displayId/:version/removeCollection",
            get(mutate::public_remove_collection).post(mutate::public_remove_collection),
        )
        .route(
            "/public/:collectionId/:displayId/:version/icon",
            post(mutate::public_icon),
        )
        // Field-edit surface. The mutable text fields and citations take the
        // target uri in the body; the generic edit/add/remove of a field and the
        // membership verbs take it in the path. Every one is owner-gated and
        // refreshes dcterms:modified.
        .route(
            "/updateMutableDescription",
            post(edit::update_mutable_description),
        )
        .route("/updateMutableNotes", post(edit::update_mutable_notes))
        .route("/updateMutableSource", post(edit::update_mutable_source))
        .route("/updateCitations", post(edit::update_citations))
        .route(
            "/user/:userId/:collectionId/:displayId/:version/edit/:field",
            post(edit::user_edit_field),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/add/:field",
            post(edit::user_add_field),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/remove/:field",
            post(edit::user_remove_field),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/addToCollection",
            post(edit::user_add_to_collection),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/removeMembership",
            post(edit::user_remove_membership),
        )
        .route(
            "/public/:collectionId/:displayId/:version/edit/:field",
            post(edit::public_edit_field),
        )
        .route(
            "/public/:collectionId/:displayId/:version/add/:field",
            post(edit::public_add_field),
        )
        .route(
            "/public/:collectionId/:displayId/:version/remove/:field",
            post(edit::public_remove_field),
        )
        .route(
            "/public/:collectionId/:displayId/:version/addToCollection",
            post(edit::public_add_to_collection),
        )
        .route(
            "/public/:collectionId/:displayId/:version/removeMembership",
            post(edit::public_remove_membership),
        )
        // Object-sharing (permission) surface: grant and revoke another user's
        // view access. Owner-gated through the facade.
        .route(
            "/user/:userId/:collectionId/:displayId/:version/addOwner",
            post(permission::user_add_owner),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/removeOwner/:username",
            get(permission::user_remove_owner).post(permission::user_remove_owner),
        )
        .route(
            "/public/:collectionId/:displayId/:version/addOwner",
            post(permission::public_add_owner),
        )
        .route(
            "/public/:collectionId/:displayId/:version/removeOwner/:username",
            get(permission::public_remove_owner).post(permission::public_remove_owner),
        )
        // Read/query surface. Free-text relevance runs over the ranked index;
        // facets, counts, members, uses, twins, and metadata are SPARQL over
        // the shared engine, all under the caller's authorized graph scope.
        .route("/search", get(routes::search_root))
        // The UI issues the term-less search as `/search/?offset=&limit=`; the
        // trailing slash matches neither `/search` nor the catch-all, so route
        // it to the same term-less handler classic serves.
        .route("/search/", get(routes::search_root))
        .route("/search/*query", get(routes::search))
        .route("/searchCount", get(routes::search_count_root))
        .route("/searchCount/", get(routes::search_count_root))
        .route("/searchCount/*query", get(routes::search_count))
        .route("/:type/count", get(routes::type_count))
        .route("/rootCollections", get(routes::root_collections))
        .route("/manage", get(routes::manage))
        .route("/shared", get(routes::shared))
        .route(
            "/public/:collectionId/:displayId/:version/uses",
            get(routes::public_uses),
        )
        .route(
            "/public/:collectionId/:displayId/:version/usesCount",
            get(routes::public_uses_count),
        )
        .route(
            "/public/:collectionId/:displayId/:version/similar",
            get(sequence::public_similar),
        )
        .route(
            "/public/:collectionId/:displayId/:version/similarCount",
            get(sequence::public_similar_count),
        )
        .route(
            "/public/:collectionId/:displayId/:version/twins",
            get(routes::public_twins),
        )
        .route(
            "/public/:collectionId/:displayId/:version/twinsCount",
            get(routes::public_twins_count),
        )
        .route(
            "/public/:collectionId/:displayId/:version/subCollections",
            get(routes::public_sub_collections),
        )
        .route(
            "/public/:collectionId/:displayId/:version/metadata",
            get(routes::public_metadata),
        )
        // Version-less relations: the UI fetches these off the persistent
        // identity (no version), which resolves to the latest version.
        .route(
            "/public/:collectionId/:displayId/uses",
            get(routes::public_uses_pi),
        )
        .route(
            "/public/:collectionId/:displayId/usesCount",
            get(routes::public_uses_count_pi),
        )
        .route(
            "/public/:collectionId/:displayId/similar",
            get(sequence::public_similar_pi),
        )
        .route(
            "/public/:collectionId/:displayId/similarCount",
            get(sequence::public_similar_count_pi),
        )
        .route(
            "/public/:collectionId/:displayId/twins",
            get(routes::public_twins_pi),
        )
        .route(
            "/public/:collectionId/:displayId/twinsCount",
            get(routes::public_twins_count_pi),
        )
        .route(
            "/public/:collectionId/:displayId/subCollections",
            get(routes::public_sub_collections_pi),
        )
        .route(
            "/public/:collectionId/:displayId/metadata",
            get(routes::public_metadata_pi),
        )
        // Download surface: the object's closure rendered in each exchange
        // format, ACL-scoped through the shared downloader and P3 serializers.
        .route(
            "/public/:collectionId/:displayId/:version/sbol",
            get(download::public_sbol),
        )
        .route(
            "/public/:collectionId/:displayId/:version/sbolnr",
            get(download::public_sbolnr),
        )
        .route(
            "/public/:collectionId/:displayId/:version/gb",
            get(download::public_genbank),
        )
        .route(
            "/public/:collectionId/:displayId/:version/fasta",
            get(download::public_fasta),
        )
        .route(
            "/public/:collectionId/:displayId/:version/gff",
            get(download::public_gff),
        )
        .route(
            "/public/:collectionId/:displayId/:version/omex",
            get(download::public_omex),
        )
        .route(
            "/public/:collectionId/:displayId/:version/summary",
            get(download::public_summary),
        )
        // Attachment surface: store an uploaded file or an external URL as a
        // first-class attachment, and stream a stored blob back. The attach
        // verbs are owner-gated; the download read is ACL-scoped.
        .route(
            "/public/:collectionId/:displayId/:version/attach",
            post(attachments::public_attach),
        )
        .route(
            "/public/:collectionId/:displayId/:version/attachUrl",
            post(attachments::public_attach_url),
        )
        .route(
            "/public/:collectionId/:displayId/:version/download",
            get(attachments::public_download),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/uses",
            get(routes::user_uses),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/usesCount",
            get(routes::user_uses_count),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/similar",
            get(sequence::user_similar),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/similarCount",
            get(sequence::user_similar_count),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/twins",
            get(routes::user_twins),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/twinsCount",
            get(routes::user_twins_count),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/subCollections",
            get(routes::user_sub_collections),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/metadata",
            get(routes::user_metadata),
        )
        // Version-less relations (resolve to the latest version).
        .route(
            "/user/:userId/:collectionId/:displayId/uses",
            get(routes::user_uses_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/usesCount",
            get(routes::user_uses_count_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/similar",
            get(sequence::user_similar_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/similarCount",
            get(sequence::user_similar_count_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/twins",
            get(routes::user_twins_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/twinsCount",
            get(routes::user_twins_count_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/subCollections",
            get(routes::user_sub_collections_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/metadata",
            get(routes::user_metadata_pi),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/sbol",
            get(download::user_sbol),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/sbolnr",
            get(download::user_sbolnr),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/gb",
            get(download::user_genbank),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/fasta",
            get(download::user_fasta),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/gff",
            get(download::user_gff),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/omex",
            get(download::user_omex),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/summary",
            get(download::user_summary),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/attach",
            post(attachments::user_attach),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/attachUrl",
            post(attachments::user_attach_url),
        )
        .route(
            "/user/:userId/:collectionId/:displayId/:version/download",
            get(attachments::user_download),
        )
        .route_layer(axum::middleware::from_fn_with_state(
            state.clone(),
            attach_current_user,
        ));
    // The admin surface carries its own identity + admin gate, so it is merged
    // in after the public routes rather than sharing their route layer.
    public
        .merge(admin::router(state))
        .route_layer(axum::middleware::from_fn(metrics::track_synbiohub_v1_usage))
}

/// Resolve the `X-authorization` token to the caller's account and attach it to
/// the request as a [`CurrentUser`] extension. A missing or unrecognized token
/// yields an anonymous `CurrentUser(None)` rather than a rejection; each route
/// decides whether it requires authentication.
pub async fn attach_current_user(
    State(state): State<AppState>,
    mut req: Request,
    next: Next,
) -> Response {
    let token = req
        .headers()
        .get("x-authorization")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);
    let user = match token {
        Some(token) if !token.is_empty() => resolve_user(&state, &token).await,
        _ => None,
    };
    req.extensions_mut().insert(CurrentUser(user));
    next.run(req).await
}

/// Resolve a plaintext token to the account it authenticates, tolerating a
/// stale or bogus token (which resolves to `None`).
async fn resolve_user(state: &AppState, token: &str) -> Option<User> {
    let user_id = state.app.auth.resolve_token(token).await.ok().flatten()?;
    state.app.users.get_by_id(user_id).await.ok().flatten()
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use axum::body::{to_bytes, Body};
    use axum::extract::Extension;
    use axum::http::{Request, StatusCode};
    use axum::routing::get;
    use axum::Router;
    use sbol_db_app::{AppServices, Registration};
    use sbol_db_backend::Backend;
    use sbol_db_sparql::{SparqlEngine, SparqlUpdateEngine};
    use tempfile::TempDir;
    use tower::ServiceExt;

    use super::*;
    use crate::{Metrics, SchemaCache, ServerConfig};

    /// A probe handler reporting the resolved identity: the authenticated
    /// username, or `anonymous` when the middleware attached no account.
    async fn whoami(Extension(CurrentUser(user)): Extension<CurrentUser>) -> String {
        user.map(|u| u.username)
            .unwrap_or_else(|| "anonymous".to_owned())
    }

    /// Build a real [`AppState`] over a fresh SQLite backend, register one
    /// account, and mint it a token. Returns the state, the account's plaintext
    /// token, its username, and the `TempDir` owning the database file.
    async fn state_with_user() -> (AppState, String, String, TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("mw.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 sparql = Arc::new(SparqlEngine::new(backend.triple_source.clone()));
        let sparql_update = Arc::new(SparqlUpdateEngine::new(
            backend.triple_source.clone(),
            backend.triple_writer.clone(),
        ));
        let app = Arc::new(AppServices::from_backend(&backend));
        let user = app
            .auth
            .register(Registration {
                username: "alice".to_owned(),
                name: "Alice".to_owned(),
                email: "alice@example.org".to_owned(),
                affiliation: None,
                password: "s3cret".to_owned(),
                is_admin: false,
                is_curator: false,
                is_member: true,
            })
            .await
            .expect("register");
        let token = app.auth.issue_token(user.id).await.expect("issue token");

        let state = AppState {
            service: backend.store.clone(),
            sparql,
            sparql_update,
            app,
            metrics: Metrics::install(None, env!("CARGO_PKG_VERSION")),
            jobs: backend.jobs.clone(),
            lab: backend.lab.clone(),
            config: ServerConfig::default(),
            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()),
        };
        (state, token, user.username, dir)
    }

    /// A router that runs `attach_current_user` ahead of the `whoami` probe.
    fn probe(state: AppState) -> Router {
        Router::new()
            .route("/whoami", get(whoami))
            .route_layer(axum::middleware::from_fn_with_state(
                state.clone(),
                attach_current_user,
            ))
            .with_state(state)
    }

    async fn whoami_with(app: &Router, header: Option<&str>) -> (StatusCode, String) {
        let mut builder = Request::builder().method("GET").uri("/whoami");
        if let Some(token) = header {
            builder = builder.header("x-authorization", token);
        }
        let res = app
            .clone()
            .oneshot(builder.body(Body::empty()).unwrap())
            .await
            .expect("whoami request");
        let status = res.status();
        let bytes = to_bytes(res.into_body(), 64 * 1024).await.expect("body");
        (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
    }

    #[tokio::test]
    async fn valid_token_resolves_current_user() {
        let (state, token, username, _dir) = state_with_user().await;
        let app = probe(state);
        let (status, body) = whoami_with(&app, Some(&token)).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, username, "the token should resolve to its account");
    }

    #[tokio::test]
    async fn missing_or_bad_token_is_anonymous() {
        let (state, _token, _username, _dir) = state_with_user().await;
        let app = probe(state);

        // No header: anonymous, not an error.
        let (status, body) = whoami_with(&app, None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, "anonymous");

        // An unrecognized token also resolves to anonymous.
        let (status, body) = whoami_with(&app, Some("not-a-real-token")).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, "anonymous");
    }

    /// Build the full V1 router and drive a read route and an auth-gated route,
    /// which also exercises route registration (a conflict would panic here).
    async fn v1_router() -> (Router, TempDir) {
        let (state, _token, _username, dir) = state_with_user().await;
        (router(state.clone()).with_state(state), dir)
    }

    async fn send_get(app: &Router, uri: &str, token: Option<&str>) -> (StatusCode, String) {
        let mut builder = Request::builder().method("GET").uri(uri);
        if let Some(token) = token {
            builder = builder.header("x-authorization", token);
        }
        let res = app
            .clone()
            .oneshot(builder.body(Body::empty()).unwrap())
            .await
            .expect("request");
        let status = res.status();
        let bytes = to_bytes(res.into_body(), 256 * 1024).await.expect("body");
        (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
    }

    #[tokio::test]
    async fn read_routes_register_and_respond() {
        let (app, _dir) = v1_router().await;

        // Classic serves the count as a bare integer in a text/plain body; an
        // empty store counts zero.
        let (status, body) = send_get(&app, "/ComponentDefinition/count", None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body.trim(), "0", "count response: {body}");

        // The ranked free-text path returns classic's JSON array; empty here.
        let (status, body) = send_get(&app, "/search/plasmid", None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body.trim(), "[]", "search response: {body}");

        // The UI's term-less search carries a trailing slash and paging in the
        // query string; classic accepts it, so the trailing-slash forms resolve
        // to the same term-less handlers rather than 404.
        let (status, body) = send_get(&app, "/search/?offset=0&limit=50", None).await;
        assert_eq!(status, StatusCode::OK, "GET /search/ must resolve");
        assert_eq!(body.trim(), "[]", "term-less search response: {body}");
        let (status, body) = send_get(&app, "/searchCount/", None).await;
        assert_eq!(status, StatusCode::OK, "GET /searchCount/ must resolve");
        assert_eq!(body.trim(), "0", "term-less count response: {body}");

        // The UI's sequence-search form submits an empty `globalsequence=`
        // before a sequence is entered; classic answers with no matches rather
        // than treating the key as an RDF predicate (which would 400).
        let (status, body) = send_get(&app, "/search/globalsequence=&", None).await;
        assert_eq!(status, StatusCode::OK, "empty sequence search must resolve");
        assert_eq!(body.trim(), "[]", "empty sequence search response: {body}");
        let (status, body) = send_get(&app, "/searchCount/globalsequence=&", None).await;
        assert_eq!(status, StatusCode::OK, "empty sequence count must resolve");
        assert_eq!(body.trim(), "0", "empty sequence count response: {body}");

        // Root collections is SPARQL over the accelerator.
        let (status, _body) = send_get(&app, "/rootCollections", None).await;
        assert_eq!(status, StatusCode::OK);

        // /browse is the root-collections listing in classic's richer shape.
        let (status, body) = send_get(&app, "/browse", None).await;
        assert_eq!(status, StatusCode::OK, "/browse must resolve");
        assert_eq!(body.trim(), "[]", "empty /browse: {body}");

        // A version-less relation on a nonexistent object resolves to 404, not a
        // 500 -- the persistent identity has no visible version.
        let (status, _body) = send_get(&app, "/public/nope/nope/usesCount", None).await;
        assert_eq!(
            status,
            StatusCode::NOT_FOUND,
            "missing version-less object is 404"
        );
    }

    #[tokio::test]
    async fn manage_and_shared_require_identity() {
        let (app, _dir) = v1_router().await;
        let (status, _body) = send_get(&app, "/manage", None).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        let (status, _body) = send_get(&app, "/shared", None).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }
}