Skip to main content

vcon_server/
api.rs

1//! The HTTP API, served over TLS only.
2
3use std::collections::BTreeSet;
4use std::path::Path;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use axum::Router;
9use axum::body::{Body, Bytes};
10use axum::extract::{MatchedPath, Path as UriPath, Request, State};
11use axum::http::header::{
12    AUTHORIZATION, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, ETAG, IF_MATCH, LOCATION,
13    WWW_AUTHENTICATE,
14};
15use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode, Uri};
16use axum::middleware::Next;
17use axum::response::{IntoResponse, Response};
18use axum::routing::{get, patch, post, put};
19use http_body_util::LengthLimitError;
20use rustls::ServerConfig;
21use rustls::pki_types::pem::PemObject;
22use rustls::pki_types::{CertificateDer, PrivateKeyDer};
23use serde::de::{Deserialize, DeserializeOwned, Deserializer, Error as _};
24
25use crate::access::{self, AuthError, Caller, Plane, Scope, Scopes};
26use crate::audit::{Action, Actor, AuditQuery, Entry};
27use crate::ids::{KeyId, TenantId, VersionId};
28use crate::query::BadQuery;
29use crate::retention::Retention;
30use crate::reveal::Part;
31use crate::store::{Caller as StoreCaller, Created, ListQuery, Store, StoreError};
32use crate::tenants::{KeyInfo, KeyLife, Removal, TenantError, TenantInfo, Tenants};
33use time::format_description::well_known::Rfc3339;
34use uuid::Uuid;
35use vcon::read::{Inspection, Rejection};
36
37mod csp_report;
38mod listen;
39mod report_gate;
40mod session_routes;
41mod tenant_plane;
42pub use listen::{
43    Accept, AfterFailure, ConnectionLimits, after_failure, serve, serve_observed, serve_within,
44};
45pub use report_gate::{Gate as ReportGate, ReportLimits};
46
47/// The limits from configuration that the API applies to every request.
48#[derive(Debug, Clone, Copy)]
49pub struct Limits {
50    /// The most bytes a request body may hold, as received.
51    pub body: usize,
52    /// The most bytes gzip inflation may produce while a body is inspected.
53    pub inflated: u64,
54    /// How long a request body may take to arrive.
55    pub body_timeout: Duration,
56}
57
58/// What the API serves from.
59pub struct App {
60    pub tenants: Arc<Tenants>,
61    pub limits: Limits,
62    /// The must_support extensions this server supports.
63    pub supported: BTreeSet<String>,
64    /// The retention period of a tenant that sets none.
65    pub retention_default: Retention,
66    /// The MCP server's limits.
67    pub mcp: crate::mcp::Limits,
68    /// Which keys the listener this serves on admits.
69    pub plane: Plane,
70    /// How many reports of a content-security-policy violation the
71    /// listener takes in a minute (`limits.csp_reports`).
72    pub reports: ReportGate,
73    /// The listener's public origin (`public_origin` or
74    /// `operator.public_origin`), which a request by session must come
75    /// from. With None the listener serves no session.
76    pub origin: Option<crate::session::Origin>,
77}
78
79/// The routes, served from `app`.
80pub fn router(app: Arc<App>) -> Router {
81    Router::new()
82        .route("/vcons", post(create).get(list))
83        .route("/vcons/{uuid}", get(read).put(replace).delete(delete))
84        .route("/health", get(health))
85        .route("/key", get(key_info))
86        .route("/audit", get(audit_read))
87        .route("/admin/audit", get(admin_audit_read))
88        .route("/openapi.json", get(openapi))
89        .route("/legal/vcons/{uuid}", get(legal_read))
90        .route("/legal/vcons/{uuid}/versions", get(legal_versions))
91        .route("/legal/vcons/{uuid}/versions/{version}", get(legal_version))
92        .route("/legal/vcons/{uuid}/restore", post(legal_restore))
93        .route("/legal/vcons/{uuid}/hold", put(hold_on).delete(hold_off))
94        .route("/admin/tenants", post(tenant_create).get(tenant_list))
95        .route(
96            "/admin/tenants/{id}",
97            patch(tenant_retention).delete(tenant_remove),
98        )
99        .route("/admin/tenants/{id}/metadata", put(tenant_metadata))
100        .route("/admin/tenants/{id}/keys", post(key_create).get(key_list))
101        .route("/admin/keys/{id}", axum::routing::delete(key_revoke))
102        .route(
103            "/tenant/settings",
104            get(tenant_plane::settings_read).put(tenant_plane::settings_set),
105        )
106        .route(
107            "/tenant/keys",
108            get(tenant_plane::key_list).post(tenant_plane::key_create),
109        )
110        .route(
111            "/tenant/keys/{id}",
112            axum::routing::delete(tenant_plane::key_revoke),
113        )
114        .route("/tenant/memberships", get(tenant_plane::member_list))
115        .route("/session", get(session_routes::session_read))
116        .route("/session/logout", post(session_routes::session_end))
117        .merge(crate::console::router_with(post(csp_report::receive)))
118        .with_state(app.clone())
119        .merge(crate::mcp::router(app))
120        .layer(axum::middleware::from_fn(log_request))
121}
122
123/// Logs each request once it is answered: a request id, the method, the
124/// route template, never the path, which holds ids, the status and how
125/// long it took. Bodies, tokens, uuids and tenant ids are in the audit
126/// only.
127async fn log_request(matched: Option<MatchedPath>, request: Request, next: Next) -> Response {
128    let started = Instant::now();
129    let method = request.method().clone();
130    let route = matched
131        .as_ref()
132        .map_or("unmatched", MatchedPath::as_str)
133        .to_owned();
134    let answer = next.run(request).await;
135    // In the unit tests every answer must be one the description lists, so
136    // a route or status added without its description fails the test
137    // that produced it. A method a path does not take (405) and a path no
138    // route matches are the router's, not a route's.
139    #[cfg(test)]
140    if route != "unmatched" && answer.status() != StatusCode::METHOD_NOT_ALLOWED {
141        let status = answer.status().as_u16();
142        assert!(
143            description::lists(method.as_str(), &route, status),
144            "openapi.json does not list {status} for {method} {route}"
145        );
146    }
147    let mut id = [0; 8];
148    // AWS-LC's RAND_bytes aborts the process when it cannot get enough
149    // randomness, so `fill` never returns its error.
150    aws_lc_rs::rand::fill(&mut id).expect("AWS-LC aborts instead of failing");
151    tracing::info!(
152        request_id = %u64::from_be_bytes(id),
153        %method,
154        %route,
155        status = answer.status().as_u16(),
156        duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
157        "request"
158    );
159    answer
160}
161
162/// The OpenAPI description of every route, as `GET /openapi.json` serves
163/// it and the website publishes it.
164pub const OPENAPI: &str = include_str!("../openapi.json");
165
166/// `GET /openapi.json`: the description, to any valid key, recorded as
167/// openapi in the key's tenant log or the admin log.
168async fn openapi(State(app): State<Arc<App>>, headers: HeaderMap) -> Response {
169    let caller = match authenticated(&app, &headers).await {
170        Ok(caller) => caller,
171        Err(refused) => return refused.into_response(),
172    };
173    let tenants = app.tenants.clone();
174    let recorded = blocking(move || {
175        let entry = |status| Entry {
176            actor: Actor::Key(caller.key),
177            action: Action::Openapi,
178            target: None,
179            version: None,
180            status,
181        };
182        let logged = |done: bool, answer| {
183            if done {
184                answer
185            } else {
186                Err(Problem::AuditFailed)
187            }
188        };
189        match caller.tenant.map(|t| tenants.store(t)) {
190            Some(Ok(store)) => logged(store.log(&entry(200)).is_ok(), Ok(())),
191            // A tenant being removed, or whose log cannot be opened, answers
192            // 503 here too, recorded in the admin log.
193            Some(Err(_)) => logged(
194                tenants.record_alone(&entry(503)).is_ok(),
195                Err(Problem::Unavailable),
196            ),
197            None => logged(tenants.record_alone(&entry(200)).is_ok(), Ok(())),
198        }
199    })
200    .await;
201    match recorded {
202        Ok(()) => (
203            StatusCode::OK,
204            [(CONTENT_TYPE, "application/json")],
205            OPENAPI,
206        )
207            .into_response(),
208        Err(refused) => refused.into_response(),
209    }
210}
211
212/// `POST /vcons`: stores a new vCon, or answers 200 when the same bytes
213/// are already current.
214async fn create(State(app): State<Arc<App>>, headers: HeaderMap, body: Body) -> Response {
215    let admitted = match admit(&app, &headers, body, Scope::Write, Action::Create).await {
216        Ok(admitted) => admitted,
217        Err(refused) => return refused.into_response(),
218    };
219    let found = match inspect(&app, &admitted, &headers, Action::Create).await {
220        Ok(found) => found,
221        Err(refused) => return refused.into_response(),
222    };
223    let (store, body, key) = (
224        admitted.store.clone(),
225        admitted.body.clone(),
226        admitted.caller.key,
227    );
228    // Store records its own outcomes.
229    match blocking(move || store.create(&StoreCaller { key }, &found, &body)).await {
230        Ok(Created::New(version)) => (
231            StatusCode::CREATED,
232            [
233                (LOCATION, format!("/vcons/{}", found.uuid)),
234                (ETAG, entity_tag(version)),
235            ],
236        )
237            .into_response(),
238        Ok(Created::Same(version)) => {
239            (StatusCode::OK, [(ETAG, entity_tag(version))]).into_response()
240        }
241        Err(error) => failed(error).into_response(),
242    }
243}
244
245/// What Format makes of `body`, sent as `content_type`, within the
246/// configured inflation limit and supported extensions; the HTTP routes
247/// and the MCP tools read every vCon through this. Records nothing.
248pub(crate) async fn read_vcon(
249    app: &Arc<App>,
250    body: Bytes,
251    content_type: Option<String>,
252) -> Result<Inspection, Problem> {
253    let worker = app.clone();
254    blocking(move || {
255        let limits = vcon::read::Limits::new(worker.limits.inflated);
256        vcon::read::inspect(&body, content_type.as_deref(), &limits, &worker.supported)
257            .map_err(|r| rejected(&r))
258    })
259    .await
260}
261
262/// Reads an admitted body as a vCon: its media type must be one a vCon is
263/// sent as (415), and Format must take it (422, or 413 when it inflates
264/// too far). A refusal here is recorded here, since Store never sees it.
265async fn inspect(
266    app: &Arc<App>,
267    admitted: &Admitted,
268    headers: &HeaderMap,
269    action: Action,
270) -> Result<Inspection, Problem> {
271    let content_type = headers
272        .get(CONTENT_TYPE)
273        .map(|v| v.to_str().unwrap_or("\u{0}").to_owned());
274    let found = if content_type.as_deref().is_none_or(is_vcon_media_type) {
275        read_vcon(app, admitted.body.clone(), content_type).await
276    } else {
277        Err(Problem::UnsupportedMediaType)
278    };
279    match found {
280        Ok(found) => Ok(found),
281        Err(refused) => {
282            let entry = refusal(admitted.caller.key, action, refused);
283            Err(app.refuse(Some(admitted.tenant), entry, refused).await)
284        }
285    }
286}
287
288/// `GET /vcons`: a page of the tenant's live vCons, newest stored first,
289/// as JSON, with the cursor of the next page.
290async fn list(State(app): State<Arc<App>>, uri: Uri, headers: HeaderMap, body: Body) -> Response {
291    let admitted = match admit(&app, &headers, body, Scope::Read, Action::List).await {
292        Ok(admitted) => admitted,
293        Err(refused) => return refused.into_response(),
294    };
295    let Ok(query) = ListQuery::from_query(uri.query()) else {
296        let refused = Problem::BadQuery;
297        let entry = refusal(admitted.caller.key, Action::List, refused);
298        return app
299            .refuse(Some(admitted.tenant), entry, refused)
300            .await
301            .into_response();
302    };
303    let (store, key) = (admitted.store.clone(), admitted.caller.key);
304    // Store records its own outcomes.
305    match blocking(move || store.list(&StoreCaller { key }, &query)).await {
306        Ok(listing) => json_answer(StatusCode::OK, &listing.to_json()),
307        Err(error) => failed(error).into_response(),
308    }
309}
310
311/// The media type of an audit page: JSON lines, one record a line.
312const JSON_LINES: &str = "application/jsonl";
313
314/// `GET /audit`: a page of the key's tenant's log, the lines `audit export`
315/// writes for the same records.
316async fn audit_read(
317    State(app): State<Arc<App>>,
318    uri: Uri,
319    headers: HeaderMap,
320    body: Body,
321) -> Response {
322    let admitted = match admit(&app, &headers, body, Scope::Audit, Action::AuditRead).await {
323        Ok(admitted) => admitted,
324        Err(refused) => return refused.into_response(),
325    };
326    let Ok(query) = AuditQuery::from_query(uri.query()) else {
327        let refused = Problem::BadQuery;
328        let entry = refusal(admitted.caller.key, Action::AuditRead, refused);
329        return app
330            .refuse(Some(admitted.tenant), entry, refused)
331            .await
332            .into_response();
333    };
334    let (store, key) = (admitted.store.clone(), admitted.caller.key);
335    // Store records its own outcomes.
336    match blocking(move || store.audit_page(&StoreCaller { key }, &query)).await {
337        Ok(lines) => (StatusCode::OK, [(CONTENT_TYPE, JSON_LINES)], lines).into_response(),
338        Err(error) => failed(error).into_response(),
339    }
340}
341
342/// `GET /admin/audit`: a page of the admin log, the lines
343/// `audit export --admin` writes for the same records.
344async fn admin_audit_read(
345    State(app): State<Arc<App>>,
346    uri: Uri,
347    headers: HeaderMap,
348    body: Body,
349) -> Response {
350    let action = Action::AuditRead;
351    let read = async {
352        let (key, _) = admin_admit(&app, &headers, body, action).await?;
353        let Ok(query) = AuditQuery::from_query(uri.query()) else {
354            let refused = Problem::BadQuery;
355            return Err(app
356                .refuse(None, refusal(key, action, refused), refused)
357                .await);
358        };
359        let tenants = app.tenants.clone();
360        // Tenants records its own outcomes.
361        blocking(move || tenants.audit_page(Actor::Key(key), &query))
362            .await
363            .map_err(Problem::Tenant)
364    };
365    match read.await {
366        Ok(lines) => (StatusCode::OK, [(CONTENT_TYPE, JSON_LINES)], lines).into_response(),
367        Err(refused) => refused.into_response(),
368    }
369}
370
371/// What a read's query makes of it: the part it reveals, if it carries
372/// the marker, and the action it is recorded under. A marker the route
373/// does not take leaves the request the plain read it is refused as.
374fn marked(
375    uri: &Uri,
376    read: Action,
377    reveal: fn(Part) -> Action,
378) -> (Result<Option<Part>, BadQuery>, Action) {
379    let marker = Part::from_query(uri.query());
380    let action = match marker {
381        Ok(Some(part)) => reveal(part),
382        Ok(None) | Err(BadQuery) => read,
383    };
384    (marker, action)
385}
386
387/// `GET /vcons/{uuid}`: the current version, as stored. With
388/// `?reveal=<part>` the answer is the same and the read is recorded as a
389/// reveal of that part.
390async fn read(
391    State(app): State<Arc<App>>,
392    UriPath(uuid): UriPath<String>,
393    uri: Uri,
394    headers: HeaderMap,
395    body: Body,
396) -> Response {
397    let (marker, action) = marked(&uri, Action::Read, Action::Reveal);
398    let admitted = match admit(&app, &headers, body, Scope::Read, action).await {
399        Ok(admitted) => admitted,
400        Err(refused) => return refused.into_response(),
401    };
402    let refuse = async |refused| {
403        let entry = refusal(admitted.caller.key, action, refused);
404        app.refuse(Some(admitted.tenant), entry, refused)
405            .await
406            .into_response()
407    };
408    let Some(uuid) = vcon::parse_uuid(&uuid) else {
409        return refuse(Problem::BadPathUuid).await;
410    };
411    let Ok(part) = marker else {
412        return refuse(Problem::BadQuery).await;
413    };
414    let (store, key) = (admitted.store.clone(), admitted.caller.key);
415    let read = move || match part {
416        Some(part) => store.reveal(&StoreCaller { key }, uuid, part),
417        None => store.get(&StoreCaller { key }, uuid),
418    };
419    match blocking(read).await {
420        Ok(stored) => {
421            let content_type = if stored.gzip {
422                "application/vcon+gzip"
423            } else {
424                "application/vcon"
425            };
426            (
427                StatusCode::OK,
428                [
429                    (CONTENT_TYPE, content_type.to_owned()),
430                    (ETAG, entity_tag(stored.version)),
431                ],
432                stored.body,
433            )
434                .into_response()
435        }
436        // Store records its own outcomes.
437        Err(error) => failed(error).into_response(),
438    }
439}
440
441/// `PUT /vcons/{uuid}`: replaces the current version named by `If-Match`.
442async fn replace(
443    State(app): State<Arc<App>>,
444    UriPath(uuid): UriPath<String>,
445    headers: HeaderMap,
446    body: Body,
447) -> Response {
448    let admitted = match admit(&app, &headers, body, Scope::Write, Action::Replace).await {
449        Ok(admitted) => admitted,
450        Err(refused) => return refused.into_response(),
451    };
452    let (shared, key, tenant) = (&app, admitted.caller.key, admitted.tenant);
453    let refuse = |refused| async move {
454        let entry = refusal(key, Action::Replace, refused);
455        shared
456            .refuse(Some(tenant), entry, refused)
457            .await
458            .into_response()
459    };
460    let Some(uuid) = vcon::parse_uuid(&uuid) else {
461        return refuse(Problem::BadPathUuid).await;
462    };
463    let current = match if_match(&headers) {
464        None => return refuse(Problem::PreconditionRequired).await,
465        Some(None) => return refuse(Problem::Store(StoreError::PreconditionFailed)).await,
466        Some(Some(current)) => current,
467    };
468    let found = match inspect(&app, &admitted, &headers, Action::Replace).await {
469        Ok(found) => found,
470        Err(refused) => return refused.into_response(),
471    };
472    if found.uuid != uuid {
473        return refuse(Problem::PathUuidMismatch).await;
474    }
475    let (store, body, key) = (
476        admitted.store.clone(),
477        admitted.body.clone(),
478        admitted.caller.key,
479    );
480    // Store records its own outcomes.
481    match blocking(move || store.replace(&StoreCaller { key }, current, &found, &body)).await {
482        Ok(version) => (StatusCode::OK, [(ETAG, entity_tag(version))]).into_response(),
483        Err(error) => failed(error).into_response(),
484    }
485}
486
487/// The version an `If-Match` header names: None without the header, and
488/// Some(None) when it is anything but one strong tag holding a version id,
489/// such as `*`, a weak tag or a list, since that names no version this
490/// server could replace.
491fn if_match(headers: &HeaderMap) -> Option<Option<VersionId>> {
492    let value = headers.get(IF_MATCH)?;
493    Some(
494        value
495            .to_str()
496            .ok()
497            .and_then(|tag| tag.trim().strip_prefix('"')?.strip_suffix('"'))
498            .and_then(VersionId::parse),
499    )
500}
501
502/// `DELETE /vcons/{uuid}`: hides the vCon; also 204 when it is already
503/// deleted or purged.
504async fn delete(
505    State(app): State<Arc<App>>,
506    UriPath(uuid): UriPath<String>,
507    headers: HeaderMap,
508    body: Body,
509) -> Response {
510    let admitted = match admit(&app, &headers, body, Scope::Delete, Action::Delete).await {
511        Ok(admitted) => admitted,
512        Err(refused) => return refused.into_response(),
513    };
514    let Some(uuid) = vcon::parse_uuid(&uuid) else {
515        let refused = Problem::BadPathUuid;
516        let entry = refusal(admitted.caller.key, Action::Delete, refused);
517        return app
518            .refuse(Some(admitted.tenant), entry, refused)
519            .await
520            .into_response();
521    };
522    // The tenant's own period, else the server's, read now so a change
523    // counts from the next delete. Unread, nothing is deleted.
524    let (tenants, tenant) = (app.tenants.clone(), admitted.tenant);
525    let retention = match blocking(move || tenants.retention(tenant)).await {
526        Ok(own) => own.unwrap_or(app.retention_default),
527        Err(_) => {
528            let refused = Problem::Unavailable;
529            let entry = refusal(admitted.caller.key, Action::Delete, refused);
530            return app
531                .refuse(Some(tenant), entry, refused)
532                .await
533                .into_response();
534        }
535    };
536    let (store, key) = (admitted.store.clone(), admitted.caller.key);
537    // Store records its own outcomes.
538    match blocking(move || store.delete(&StoreCaller { key }, uuid, retention)).await {
539        Ok(()) => StatusCode::NO_CONTENT.into_response(),
540        Err(error) => failed(error).into_response(),
541    }
542}
543
544/// Whether a legal read is of a live or a deleted uuid.
545const VCON_STATE: HeaderName = HeaderName::from_static("vcon-state");
546
547/// The legal routes' shared start: a key with the legal scope, then the
548/// path's uuid, each refusal recorded as `action`.
549async fn legal_admit(
550    app: &Arc<App>,
551    headers: &HeaderMap,
552    body: Body,
553    action: Action,
554    uuid: &str,
555) -> Result<(Admitted, Uuid), Problem> {
556    let admitted = admit(app, headers, body, Scope::Legal, action).await?;
557    let Some(uuid) = vcon::parse_uuid(uuid) else {
558        let refused = Problem::BadPathUuid;
559        let entry = refusal(admitted.caller.key, action, refused);
560        return Err(app.refuse(Some(admitted.tenant), entry, refused).await);
561    };
562    Ok((admitted, uuid))
563}
564
565/// `GET /legal/vcons/{uuid}`: the current version, or the latest kept one
566/// of a deleted uuid, as stored, with `Vcon-State`. With `?reveal=<part>`
567/// the answer is the same and the read is recorded as a legal reveal of
568/// that part.
569async fn legal_read(
570    State(app): State<Arc<App>>,
571    UriPath(uuid): UriPath<String>,
572    uri: Uri,
573    headers: HeaderMap,
574    body: Body,
575) -> Response {
576    let (marker, action) = marked(&uri, Action::LegalRead, Action::LegalReveal);
577    match legal_admit(&app, &headers, body, action, &uuid).await {
578        Ok((admitted, uuid)) => legal_body(&app, &admitted, uuid, None, marker).await,
579        Err(refused) => refused.into_response(),
580    }
581}
582
583/// `GET /legal/vcons/{uuid}/versions/{version}`: that kept version, as
584/// stored. With `?reveal=<part>` the answer is the same and the read is
585/// recorded as a legal reveal of that part.
586async fn legal_version(
587    State(app): State<Arc<App>>,
588    UriPath((uuid, version)): UriPath<(String, String)>,
589    uri: Uri,
590    headers: HeaderMap,
591    body: Body,
592) -> Response {
593    let (marker, action) = marked(&uri, Action::LegalRead, Action::LegalReveal);
594    let (admitted, uuid) = match legal_admit(&app, &headers, body, action, &uuid).await {
595        Ok(admitted) => admitted,
596        Err(refused) => return refused.into_response(),
597    };
598    let Some(version) = VersionId::parse(&version) else {
599        let refused = Problem::BadPathVersion;
600        let entry = refusal(admitted.caller.key, action, refused);
601        return app
602            .refuse(Some(admitted.tenant), entry, refused)
603            .await
604            .into_response();
605    };
606    legal_body(&app, &admitted, uuid, Some(version), marker).await
607}
608
609/// A legal read's answer: the body as stored, its tag and the uuid's
610/// state. A marker the route does not take is refused here, after the
611/// path, and recorded as the legal read it is.
612async fn legal_body(
613    app: &Arc<App>,
614    admitted: &Admitted,
615    uuid: Uuid,
616    version: Option<VersionId>,
617    marker: Result<Option<Part>, BadQuery>,
618) -> Response {
619    let (store, key) = (admitted.store.clone(), admitted.caller.key);
620    let Ok(part) = marker else {
621        let refused = Problem::BadQuery;
622        let entry = refusal(key, Action::LegalRead, refused);
623        return app
624            .refuse(Some(admitted.tenant), entry, refused)
625            .await
626            .into_response();
627    };
628    let read = move || match part {
629        Some(part) => store.legal_reveal(&StoreCaller { key }, uuid, version, part),
630        None => store.legal_get(&StoreCaller { key }, uuid, version),
631    };
632    // Store records its own outcomes.
633    match blocking(read).await {
634        Ok(read) => {
635            let content_type = if read.stored.gzip {
636                "application/vcon+gzip"
637            } else {
638                "application/vcon"
639            };
640            let state = if read.deleted { "deleted" } else { "live" };
641            (
642                StatusCode::OK,
643                [
644                    (CONTENT_TYPE, content_type.to_owned()),
645                    (ETAG, entity_tag(read.stored.version)),
646                    (VCON_STATE, state.to_owned()),
647                ],
648                read.stored.body,
649            )
650                .into_response()
651        }
652        Err(error) => failed(error).into_response(),
653    }
654}
655
656/// `GET /legal/vcons/{uuid}/versions`: every kept version, oldest first,
657/// as JSON: its id, when it was stored and hidden (RFC 3339, UTC), and
658/// whether it is current.
659async fn legal_versions(
660    State(app): State<Arc<App>>,
661    UriPath(uuid): UriPath<String>,
662    headers: HeaderMap,
663    body: Body,
664) -> Response {
665    let (admitted, uuid) =
666        match legal_admit(&app, &headers, body, Action::LegalVersions, &uuid).await {
667            Ok(admitted) => admitted,
668            Err(refused) => return refused.into_response(),
669        };
670    let (store, key) = (admitted.store.clone(), admitted.caller.key);
671    match blocking(move || store.legal_versions(&StoreCaller { key }, uuid)).await {
672        Ok(versions) => match versions_json(&versions) {
673            Some(listed) => (
674                StatusCode::OK,
675                [(CONTENT_TYPE, "application/json")],
676                serde_json::Value::Array(listed).to_string(),
677            )
678                .into_response(),
679            None => failed(StoreError::Damaged).into_response(),
680        },
681        Err(error) => failed(error).into_response(),
682    }
683}
684
685/// Kept versions as the legal routes and tools render them: each one's id,
686/// when it was stored and hidden (RFC 3339, UTC; null while current), and
687/// whether it is current. None when a time cannot be written.
688pub(crate) fn versions_json(
689    versions: &[crate::store::VersionInfo],
690) -> Option<Vec<serde_json::Value>> {
691    let time = |at: time::OffsetDateTime| at.format(&Rfc3339).ok();
692    versions
693        .iter()
694        .map(|v| {
695            let hidden_at = match v.hidden_at {
696                Some(at) => Some(time(at)?),
697                None => None,
698            };
699            Some(serde_json::json!({
700                "version": v.version.to_string(),
701                "stored_at": time(v.stored_at)?,
702                "hidden_at": hidden_at,
703                "current": v.current,
704            }))
705        })
706        .collect()
707}
708
709/// `POST /legal/vcons/{uuid}/restore`: makes a deleted vCon live again and
710/// answers 200 with the restored version's tag.
711async fn legal_restore(
712    State(app): State<Arc<App>>,
713    UriPath(uuid): UriPath<String>,
714    headers: HeaderMap,
715    body: Body,
716) -> Response {
717    let (admitted, uuid) = match legal_admit(&app, &headers, body, Action::Restore, &uuid).await {
718        Ok(admitted) => admitted,
719        Err(refused) => return refused.into_response(),
720    };
721    let (store, key) = (admitted.store.clone(), admitted.caller.key);
722    match blocking(move || store.restore(&StoreCaller { key }, uuid)).await {
723        Ok(version) => (StatusCode::OK, [(ETAG, entity_tag(version))]).into_response(),
724        Err(error) => failed(error).into_response(),
725    }
726}
727
728/// `PUT /legal/vcons/{uuid}/hold`: puts the uuid under a legal hold.
729async fn hold_on(
730    State(app): State<Arc<App>>,
731    UriPath(uuid): UriPath<String>,
732    headers: HeaderMap,
733    body: Body,
734) -> Response {
735    hold(app, uuid, headers, body, true).await
736}
737
738/// `DELETE /legal/vcons/{uuid}/hold`: releases the uuid's legal hold.
739async fn hold_off(
740    State(app): State<Arc<App>>,
741    UriPath(uuid): UriPath<String>,
742    headers: HeaderMap,
743    body: Body,
744) -> Response {
745    hold(app, uuid, headers, body, false).await
746}
747
748async fn hold(app: Arc<App>, uuid: String, headers: HeaderMap, body: Body, on: bool) -> Response {
749    // A release is its own action, so the log tells it from a hold.
750    let action = if on { Action::Hold } else { Action::Release };
751    let (admitted, uuid) = match legal_admit(&app, &headers, body, action, &uuid).await {
752        Ok(admitted) => admitted,
753        Err(refused) => return refused.into_response(),
754    };
755    let (store, key) = (admitted.store.clone(), admitted.caller.key);
756    match blocking(move || store.set_hold(&StoreCaller { key }, uuid, on)).await {
757        Ok(()) => StatusCode::NO_CONTENT.into_response(),
758        Err(error) => failed(error).into_response(),
759    }
760}
761
762/// The admin routes' shared start: an operator key holding the admin
763/// scope, then the body within the limits, each refusal recorded as
764/// `action`.
765async fn admin_admit(
766    app: &Arc<App>,
767    headers: &HeaderMap,
768    body: Body,
769    action: Action,
770) -> Result<(KeyId, Bytes), Problem> {
771    let caller = authenticated(app, headers).await?;
772    let entry = |refused| refusal(caller.key, action, refused);
773    if access::require(&caller, Scope::Admin).is_err() {
774        let refused = Problem::Forbidden;
775        return Err(app.refuse(caller.tenant, entry(refused), refused).await);
776    }
777    match read_body(body, headers, &app.limits).await {
778        Ok(body) => Ok((caller.key, body)),
779        Err(refused) => Err(app.refuse(None, entry(refused), refused).await),
780    }
781}
782
783/// An admin body as JSON, or the refusal recorded as `action`.
784async fn admin_body<T: DeserializeOwned>(
785    app: &Arc<App>,
786    key: KeyId,
787    action: Action,
788    body: &Bytes,
789) -> Result<T, Problem> {
790    match serde_json::from_slice(body) {
791        Ok(read) => Ok(read),
792        Err(_) => {
793            let refused = Problem::InvalidBody;
794            Err(app
795                .refuse(None, refusal(key, action, refused), refused)
796                .await)
797        }
798    }
799}
800
801/// A retention period in a body: a string `Retention` reads, or null for
802/// the server default.
803fn period<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Retention>, D::Error> {
804    Option::<String>::deserialize(d)?
805        .map(|text| Retention::parse(&text).ok_or_else(|| D::Error::custom("a bad period")))
806        .transpose()
807}
808
809/// The body of `POST /admin/tenants`.
810#[derive(serde::Deserialize)]
811#[serde(deny_unknown_fields)]
812struct NewTenant {
813    name: String,
814    #[serde(default, deserialize_with = "period")]
815    retention: Option<Retention>,
816}
817
818/// The body of `PATCH /admin/tenants/{id}`. The period must be there,
819/// null included, so an empty body changes nothing by mistake.
820#[derive(serde::Deserialize)]
821#[serde(deny_unknown_fields)]
822struct NewRetention {
823    #[serde(deserialize_with = "period")]
824    retention: Option<Retention>,
825}
826
827/// The body of `PUT /admin/tenants/{id}/metadata`.
828#[derive(serde::Deserialize)]
829#[serde(deny_unknown_fields)]
830struct NewMetadata {
831    #[serde(deserialize_with = "level")]
832    metadata: crate::export::Metadata,
833}
834
835/// A metadata level in a body: `none`, `counts` or `full`.
836fn level<'de, D: Deserializer<'de>>(d: D) -> Result<crate::export::Metadata, D::Error> {
837    let text = String::deserialize(d)?;
838    crate::export::Metadata::parse(&text).ok_or_else(|| D::Error::custom("a bad level"))
839}
840
841/// A JSON answer.
842fn json_answer(status: StatusCode, body: &serde_json::Value) -> Response {
843    (
844        status,
845        [(CONTENT_TYPE, "application/json")],
846        body.to_string(),
847    )
848        .into_response()
849}
850
851/// `POST /admin/tenants`: makes a tenant and answers 201 with its id.
852async fn tenant_create(State(app): State<Arc<App>>, headers: HeaderMap, body: Body) -> Response {
853    let action = Action::TenantCreate;
854    let made = async {
855        let (key, body) = admin_admit(&app, &headers, body, action).await?;
856        let new: NewTenant = admin_body(&app, key, action, &body).await?;
857        let tenants = app.tenants.clone();
858        // Tenants records its own outcomes.
859        blocking(move || tenants.create(Actor::Key(key), &new.name, new.retention))
860            .await
861            .map_err(Problem::Tenant)
862    };
863    match made.await {
864        Ok(id) => json_answer(
865            StatusCode::CREATED,
866            &serde_json::json!({ "id": id.to_string() }),
867        ),
868        Err(refused) => refused.into_response(),
869    }
870}
871
872/// `GET /admin/tenants`: every tenant by name, with its id and its own
873/// retention period, null for the server default.
874async fn tenant_list(State(app): State<Arc<App>>, headers: HeaderMap, body: Body) -> Response {
875    let listed = async {
876        let (key, _) = admin_admit(&app, &headers, body, Action::TenantList).await?;
877        let tenants = app.tenants.clone();
878        blocking(move || tenants.list(Actor::Key(key)))
879            .await
880            .map_err(Problem::Tenant)
881    };
882    match listed.await {
883        Ok(listed) => {
884            let listed: Vec<serde_json::Value> = listed.iter().map(TenantInfo::to_json).collect();
885            json_answer(StatusCode::OK, &serde_json::Value::Array(listed))
886        }
887        Err(refused) => refused.into_response(),
888    }
889}
890
891/// `PATCH /admin/tenants/{id}`: sets the tenant's retention period, or
892/// with null returns it to the server default, and answers 200 with it.
893async fn tenant_retention(
894    State(app): State<Arc<App>>,
895    UriPath(id): UriPath<String>,
896    headers: HeaderMap,
897    body: Body,
898) -> Response {
899    let action = Action::TenantRetention;
900    let changed = async {
901        let (key, body) = admin_admit(&app, &headers, body, action).await?;
902        let Some(id) = TenantId::parse(&id) else {
903            let refused = Problem::Tenant(TenantError::NotFound);
904            return Err(app
905                .refuse(None, refusal(key, action, refused), refused)
906                .await);
907        };
908        let new: NewRetention = admin_body(&app, key, action, &body).await?;
909        let tenants = app.tenants.clone();
910        blocking(move || tenants.set_retention(Actor::Key(key), id, new.retention))
911            .await
912            .map_err(Problem::Tenant)?;
913        Ok((id, new.retention))
914    };
915    match changed.await {
916        Ok((id, retention)) => json_answer(
917            StatusCode::OK,
918            &serde_json::json!({
919                "id": id.to_string(),
920                "retention": retention.map(|r| r.to_string()),
921            }),
922        ),
923        Err(refused) => refused.into_response(),
924    }
925}
926
927/// `PUT /admin/tenants/{id}/metadata`: sets which clear columns the
928/// tenant's Parquet files carry, and answers 200 with it.
929async fn tenant_metadata(
930    State(app): State<Arc<App>>,
931    UriPath(id): UriPath<String>,
932    headers: HeaderMap,
933    body: Body,
934) -> Response {
935    let action = Action::TenantMetadata;
936    let changed = async {
937        let (key, body) = admin_admit(&app, &headers, body, action).await?;
938        let Some(id) = TenantId::parse(&id) else {
939            let refused = Problem::Tenant(TenantError::NotFound);
940            return Err(app
941                .refuse(None, refusal(key, action, refused), refused)
942                .await);
943        };
944        let new: NewMetadata = admin_body(&app, key, action, &body).await?;
945        let tenants = app.tenants.clone();
946        blocking(move || tenants.set_metadata(Actor::Key(key), id, new.metadata))
947            .await
948            .map_err(Problem::Tenant)?;
949        Ok((id, new.metadata))
950    };
951    match changed.await {
952        Ok((id, level)) => json_answer(
953            StatusCode::OK,
954            &serde_json::json!({ "id": id.to_string(), "metadata": level.as_str() }),
955        ),
956        Err(refused) => refused.into_response(),
957    }
958}
959
960/// `DELETE /admin/tenants/{id}`: removes a tenant that keeps no version,
961/// or with `?force=true` one that does, unless a uuid of it is under a
962/// legal hold; answers 204.
963async fn tenant_remove(
964    State(app): State<Arc<App>>,
965    UriPath(id): UriPath<String>,
966    uri: Uri,
967    headers: HeaderMap,
968    body: Body,
969) -> Response {
970    let action = Action::TenantRemove;
971    let removed = async {
972        let (key, _) = admin_admit(&app, &headers, body, action).await?;
973        let refuse = |refused| app.refuse(None, refusal(key, action, refused), refused);
974        let Some(id) = TenantId::parse(&id) else {
975            return Err(refuse(Problem::Tenant(TenantError::NotFound)).await);
976        };
977        let Some(removal) = removal(uri.query()) else {
978            return Err(refuse(Problem::BadQuery).await);
979        };
980        let tenants = app.tenants.clone();
981        // Tenants records its own outcomes.
982        blocking(move || tenants.remove(Actor::Key(key), id, removal))
983            .await
984            .map_err(Problem::Tenant)
985    };
986    match removed.await {
987        Ok(()) => StatusCode::NO_CONTENT.into_response(),
988        Err(refused) => refused.into_response(),
989    }
990}
991
992/// How far a removal asked over HTTP may go: with no query or
993/// `force=false` only an empty tenant, with `force=true` its vCons too.
994/// No query overrides a legal hold; that is the command line's alone.
995fn removal(query: Option<&str>) -> Option<Removal> {
996    match query {
997        None | Some("force=false") => Some(Removal::Empty),
998        Some("force=true") => Some(Removal::Force),
999        Some(_) => None,
1000    }
1001}
1002
1003/// The body of `POST /admin/tenants/{id}/keys` and of `POST
1004/// /tenant/keys`.
1005#[derive(serde::Deserialize)]
1006#[serde(deny_unknown_fields)]
1007struct NewKeyBody {
1008    scopes: Vec<String>,
1009    label: String,
1010    /// The days the key lives, from 1 to 365; 90 when absent.
1011    #[serde(default)]
1012    expires_in_days: Option<i64>,
1013    /// True for a key with no expiry.
1014    #[serde(default)]
1015    no_expiry: Option<bool>,
1016}
1017
1018impl NewKeyBody {
1019    /// The scopes and the life the body asks for; the refusal when a
1020    /// scope has no name. A life no key can have is refused where the key
1021    /// is made, after its scopes.
1022    fn asked(&self) -> Result<(Scopes, KeyLife), TenantError> {
1023        let scopes = Scopes::named(&self.scopes).ok_or(TenantError::BadScopes)?;
1024        Ok((scopes, KeyLife::asked(self.expires_in_days, self.no_expiry)))
1025    }
1026}
1027
1028/// `POST /admin/tenants/{id}/keys`: makes a key for the tenant and
1029/// answers 201 with its id, its token and its expiry. The token is shown
1030/// this once; only its hash is kept. The key expires in `expires_in_days`
1031/// days (1 to 365; 90 when absent), or never with `no_expiry` where the
1032/// configuration allows it; any other expiry is 422 `bad-expiry`.
1033async fn key_create(
1034    State(app): State<Arc<App>>,
1035    UriPath(id): UriPath<String>,
1036    headers: HeaderMap,
1037    body: Body,
1038) -> Response {
1039    let action = Action::KeyCreate;
1040    let made = async {
1041        let (key, body) = admin_admit(&app, &headers, body, action).await?;
1042        let refuse = |refused| app.refuse(None, refusal(key, action, refused), refused);
1043        let Some(id) = TenantId::parse(&id) else {
1044            return Err(refuse(Problem::Tenant(TenantError::NotFound)).await);
1045        };
1046        let new: NewKeyBody = admin_body(&app, key, action, &body).await?;
1047        let (scopes, life) = match new.asked() {
1048            Ok(asked) => asked,
1049            Err(refused) => return Err(refuse(Problem::Tenant(refused)).await),
1050        };
1051        let tenants = app.tenants.clone();
1052        // Tenants records its own outcomes.
1053        blocking(move || {
1054            tenants.create_key_for(Actor::Key(key), Some(id), scopes, &new.label, life)
1055        })
1056        .await
1057        .map_err(Problem::Tenant)
1058    };
1059    match made.await {
1060        Ok(made) => new_key_answer(&made),
1061        Err(refused) => refused.into_response(),
1062    }
1063}
1064
1065/// The answer that shows a new key: 201 with its id, its token and its
1066/// expiry, never stored by a cache.
1067fn new_key_answer(made: &crate::tenants::NewKey) -> Response {
1068    let Some(body) = made.to_json() else {
1069        return Problem::Tenant(TenantError::Io).into_response();
1070    };
1071    let mut answer = json_answer(StatusCode::CREATED, &body);
1072    answer
1073        .headers_mut()
1074        .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
1075    answer
1076}
1077
1078/// `GET /admin/tenants/{id}/keys`: the tenant's keys, oldest first, with
1079/// their ids, scopes, labels and times (RFC 3339, UTC), never a token.
1080async fn key_list(
1081    State(app): State<Arc<App>>,
1082    UriPath(id): UriPath<String>,
1083    headers: HeaderMap,
1084    body: Body,
1085) -> Response {
1086    let action = Action::KeyList;
1087    let listed = async {
1088        let (key, _) = admin_admit(&app, &headers, body, action).await?;
1089        let Some(id) = TenantId::parse(&id) else {
1090            let refused = Problem::Tenant(TenantError::NotFound);
1091            return Err(app
1092                .refuse(None, refusal(key, action, refused), refused)
1093                .await);
1094        };
1095        let tenants = app.tenants.clone();
1096        blocking(move || tenants.list_keys(Actor::Key(key), Some(id)))
1097            .await
1098            .map_err(Problem::Tenant)
1099    };
1100    let keys = match listed.await {
1101        Ok(keys) => keys,
1102        Err(refused) => return refused.into_response(),
1103    };
1104    let listed: Option<Vec<serde_json::Value>> = keys.iter().map(KeyInfo::to_json).collect();
1105    match listed {
1106        Some(listed) => json_answer(StatusCode::OK, &serde_json::Value::Array(listed)),
1107        None => Problem::Tenant(TenantError::Io).into_response(),
1108    }
1109}
1110
1111/// `DELETE /admin/keys/{id}`: revokes the key, so its next request is
1112/// refused; 204 again for a key already revoked.
1113async fn key_revoke(
1114    State(app): State<Arc<App>>,
1115    UriPath(id): UriPath<String>,
1116    headers: HeaderMap,
1117    body: Body,
1118) -> Response {
1119    let action = Action::KeyRevoke;
1120    let revoked = async {
1121        let (key, _) = admin_admit(&app, &headers, body, action).await?;
1122        let Some(id) = KeyId::parse(&id) else {
1123            let refused = Problem::UnknownKey;
1124            return Err(app
1125                .refuse(None, refusal(key, action, refused), refused)
1126                .await);
1127        };
1128        let tenants = app.tenants.clone();
1129        // Tenants records its own outcomes.
1130        blocking(move || tenants.revoke_key(Actor::Key(key), id))
1131            .await
1132            .map_err(|error| match error {
1133                TenantError::NotFound => Problem::UnknownKey,
1134                error => Problem::Tenant(error),
1135            })
1136    };
1137    match revoked.await {
1138        Ok(()) => StatusCode::NO_CONTENT.into_response(),
1139        Err(refused) => refused.into_response(),
1140    }
1141}
1142
1143/// `GET /health`: any valid key may ask; 200 when server.sqlite answers,
1144/// and 503 for a key whose tenant is being removed.
1145///
1146/// Health requests are counted, one record per key, status and minute, in
1147/// the key's tenant log, or the admin log for an operator key or a tenant
1148/// whose log cannot be opened; a health request that cannot be counted is
1149/// not healthy.
1150async fn health(State(app): State<Arc<App>>, headers: HeaderMap) -> Response {
1151    let caller = match authenticated(&app, &headers).await {
1152        Ok(caller) => caller,
1153        Err(refused) => return refused.into_response(),
1154    };
1155    let tenants = app.tenants.clone();
1156    let (healthy, counted) = blocking(move || {
1157        // A tenant being removed answers 503 here too, as on every route.
1158        let store = caller.tenant.map(|t| tenants.store(t));
1159        let closing = matches!(store, Some(Err(TenantError::Closing)));
1160        let healthy = !closing && tenants.check().is_ok();
1161        let entry = Entry {
1162            actor: Actor::Key(caller.key),
1163            action: Action::Health,
1164            target: None,
1165            version: None,
1166            status: if healthy { 200 } else { 503 },
1167        };
1168        let counted = match store {
1169            Some(Ok(store)) => store.count(&entry).is_ok(),
1170            _ => tenants.count_admin(&entry).is_ok(),
1171        };
1172        (healthy, counted)
1173    })
1174    .await;
1175    match (healthy, counted) {
1176        (_, false) => Problem::AuditFailed.into_response(),
1177        (false, true) => Problem::Unavailable.into_response(),
1178        (true, true) => (
1179            StatusCode::OK,
1180            [(CONTENT_TYPE, "application/json")],
1181            r#"{"status":"ok"}"#,
1182        )
1183            .into_response(),
1184    }
1185}
1186
1187/// `GET /key`: any valid key reads what it may do: its own id, its tenant
1188/// (null for an operator key) and its scopes, so a client can tell which
1189/// requests it may make.
1190///
1191/// The read is recorded before the answer, in the key's tenant log, or the
1192/// admin log for an operator key. A key whose tenant is being removed, or
1193/// whose tenant's log cannot be opened, is refused with 503, recorded in
1194/// the admin log.
1195async fn key_info(State(app): State<Arc<App>>, headers: HeaderMap) -> Response {
1196    let caller = match authenticated(&app, &headers).await {
1197        Ok(caller) => caller,
1198        Err(refused) => return refused.into_response(),
1199    };
1200    let entry = |status| Entry {
1201        actor: Actor::Key(caller.key),
1202        action: Action::KeyInfo,
1203        target: Some(caller.key.to_string()),
1204        version: None,
1205        status,
1206    };
1207    let store = match caller.tenant {
1208        Some(t) => {
1209            let tenants = app.tenants.clone();
1210            match blocking(move || tenants.store(t)).await {
1211                Ok(store) => Some(store),
1212                Err(_) => {
1213                    let refused = Problem::Unavailable;
1214                    let entry = entry(refused.status().as_u16());
1215                    return app.refuse(None, entry, refused).await.into_response();
1216                }
1217            }
1218        }
1219        None => None,
1220    };
1221    let tenants = app.tenants.clone();
1222    let record = entry(200);
1223    let recorded = blocking(move || match store {
1224        Some(store) => store.log(&record).is_ok(),
1225        None => tenants.record_alone(&record).is_ok(),
1226    })
1227    .await;
1228    if !recorded {
1229        return Problem::AuditFailed.into_response();
1230    }
1231    let body = serde_json::json!({
1232        "id": caller.key.to_string(),
1233        "tenant": caller.tenant.map(|t| t.to_string()),
1234        "scopes": caller.scopes.names(),
1235    });
1236    let mut answer = json_answer(StatusCode::OK, &body);
1237    answer
1238        .headers_mut()
1239        .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
1240    answer
1241}
1242
1243/// The audit record of a request refused before Store saw it.
1244fn refusal(key: KeyId, action: Action, refused: Problem) -> Entry {
1245    Entry {
1246        actor: Actor::Key(key),
1247        action,
1248        target: None,
1249        version: None,
1250        status: refused.status().as_u16(),
1251    }
1252}
1253
1254/// A version id as a strong entity tag.
1255fn entity_tag(version: VersionId) -> String {
1256    format!("\"{version}\"")
1257}
1258
1259/// Whether a request's media type is one a vCon may be sent as:
1260/// `application/vcon`, `application/vcon+gzip` or `application/json`, in
1261/// any case and with any parameters.
1262fn is_vcon_media_type(content_type: &str) -> bool {
1263    let essence = content_type.split(';').next().unwrap_or("").trim();
1264    [
1265        "application/vcon",
1266        "application/vcon+gzip",
1267        "application/json",
1268    ]
1269    .iter()
1270    .any(|taken| essence.eq_ignore_ascii_case(taken))
1271}
1272
1273/// A request the pipeline let through, with its body read.
1274struct Admitted {
1275    caller: Caller,
1276    tenant: TenantId,
1277    store: Arc<Store>,
1278    body: Bytes,
1279}
1280
1281/// The steps every vCon request takes before its route's own work, in
1282/// order: authenticate, check the scope, open the caller's tenant, read
1283/// the body within the limits. A refusal at any step is recorded here,
1284/// since Store never sees the request.
1285async fn admit(
1286    app: &Arc<App>,
1287    headers: &HeaderMap,
1288    body: Body,
1289    scope: Scope,
1290    action: Action,
1291) -> Result<Admitted, Problem> {
1292    let caller = authenticated(app, headers).await?;
1293    let entry = |refused| refusal(caller.key, action, refused);
1294    let Ok(tenant) = access::tenant_for(&caller, scope) else {
1295        let refused = Problem::Forbidden;
1296        return Err(app.refuse(caller.tenant, entry(refused), refused).await);
1297    };
1298    let tenants = app.tenants.clone();
1299    let Ok(store) = blocking(move || tenants.store(tenant)).await else {
1300        let refused = Problem::Unavailable;
1301        return Err(app.refuse(None, entry(refused), refused).await);
1302    };
1303    match read_body(body, headers, &app.limits).await {
1304        Ok(body) => Ok(Admitted {
1305            caller,
1306            tenant,
1307            store,
1308            body,
1309        }),
1310        Err(refused) => Err(app.refuse(Some(tenant), entry(refused), refused).await),
1311    }
1312}
1313
1314/// The caller a request's bearer key names: 401 for a missing or bad
1315/// key, 503 when the key table cannot be read, and 403 `wrong-listener`
1316/// for a valid key of the kind this listener does not serve
1317/// ([`Plane::admits`]), counted in the audit.
1318///
1319/// A request that carries a key and the session cookie is refused with
1320/// 400 `key-and-session` before the key is read, and counted in the audit
1321/// as a failed authentication with no actor: a script uses a key and a
1322/// browser a session, and a request with both is neither.
1323pub(crate) async fn authenticated(app: &Arc<App>, headers: &HeaderMap) -> Result<Caller, Problem> {
1324    let authorization = headers
1325        .get(AUTHORIZATION)
1326        .map(|v| v.to_str().unwrap_or_default().to_owned());
1327    let (tenants, plane) = (app.tenants.clone(), app.plane);
1328    if authorization.is_some() && crate::session::cookie(headers) != crate::session::Cookie::Absent
1329    {
1330        blocking(move || tenants.count_session(Action::AuthFailed, 400, None)).await;
1331        return Err(Problem::KeyAndSession);
1332    }
1333    blocking(move || {
1334        let caller =
1335            access::authenticate(&tenants, authorization.as_deref()).map_err(|e| match e {
1336                AuthError::Io => Problem::Unavailable,
1337                AuthError::Expired => Problem::KeyExpired,
1338                _ => Problem::Unauthorized,
1339            })?;
1340        if plane.admits(&caller) {
1341            Ok(caller)
1342        } else {
1343            tenants.count_wrong_listener(caller.key, caller.tenant);
1344            Err(Problem::WrongListener)
1345        }
1346    })
1347    .await
1348}
1349
1350impl App {
1351    /// Records a refusal in the tenant's log, or the admin log when there
1352    /// is no tenant or its log cannot be opened, and answers it; a refusal
1353    /// that cannot be recorded answers that the audit failed.
1354    pub(crate) async fn refuse(
1355        &self,
1356        tenant: Option<TenantId>,
1357        entry: Entry,
1358        refused: Problem,
1359    ) -> Problem {
1360        let tenants = self.tenants.clone();
1361        let recorded = blocking(move || match tenant.and_then(|t| tenants.store(t).ok()) {
1362            Some(store) => store.log(&entry).is_ok(),
1363            None => tenants.record_alone(&entry).is_ok(),
1364        })
1365        .await;
1366        if recorded {
1367            refused
1368        } else {
1369            Problem::AuditFailed
1370        }
1371    }
1372}
1373
1374/// Reads a body within the size limit and the time limit. A declared
1375/// length over the limit is refused before anything is read, and a body
1376/// that passes it is refused as soon as it does.
1377pub(crate) async fn read_body(
1378    body: Body,
1379    headers: &HeaderMap,
1380    limits: &Limits,
1381) -> Result<Bytes, Problem> {
1382    let declared = headers
1383        .get(CONTENT_LENGTH)
1384        .and_then(|v| v.to_str().ok())
1385        .and_then(|v| v.parse::<u64>().ok());
1386    if declared.is_some_and(|length| length > limits.body as u64) {
1387        return Err(Problem::TooLarge);
1388    }
1389    match tokio::time::timeout(limits.body_timeout, axum::body::to_bytes(body, limits.body)).await {
1390        Err(_) => Err(Problem::Timeout),
1391        Ok(Ok(body)) => Ok(body),
1392        Ok(Err(e)) if std::error::Error::source(&e).is_some_and(|s| s.is::<LengthLimitError>()) => {
1393            Err(Problem::TooLarge)
1394        }
1395        Ok(Err(_)) => Err(Problem::BadBody),
1396    }
1397}
1398
1399/// Runs blocking work, SQLite and files, off the async workers.
1400pub(crate) async fn blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
1401    tokio::task::spawn_blocking(work)
1402        .await
1403        .expect("blocking work does not panic")
1404}
1405
1406/// An error answer: an RFC 9457 problem document with one type per error.
1407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1408pub(crate) enum Problem {
1409    Unauthorized,
1410    Forbidden,
1411    /// The key is valid, and this listener serves the other kind of key.
1412    WrongListener,
1413    TooLarge,
1414    Timeout,
1415    BadBody,
1416    Unavailable,
1417    AuditFailed,
1418    UnsupportedMediaType,
1419    /// The key's secret is right and the key is past its expiry.
1420    KeyExpired,
1421    /// The request carries both a key and the session cookie.
1422    KeyAndSession,
1423    /// A route of a session was asked with no cookie, or with one that
1424    /// names no live session.
1425    NoSession,
1426    /// A request by session does not come from the listener's public
1427    /// origin, or the listener has none.
1428    BadOrigin,
1429    /// A request by session has no CSRF token, or not the session's.
1430    BadCsrf,
1431    /// A uuid in the path is not in RFC 9562 text form.
1432    BadPathUuid,
1433    /// A version in the path is not a version id.
1434    BadPathVersion,
1435    /// A replacement came without `If-Match`.
1436    PreconditionRequired,
1437    /// The body's uuid is not the one in the path.
1438    PathUuidMismatch,
1439    /// Format refused the body.
1440    Invalid(Invalid),
1441    /// An admin body is not one the route takes.
1442    InvalidBody,
1443    /// The query is not one the route takes.
1444    BadQuery,
1445    /// No key has the id.
1446    UnknownKey,
1447    /// Store refused or failed the request.
1448    Store(StoreError),
1449    /// Tenants refused or failed the request.
1450    Tenant(TenantError),
1451    /// An MCP key made more tool calls than its allowance for this second.
1452    RateLimited,
1453    /// As many MCP tool calls are running as the server allows.
1454    AtCapacity,
1455    /// No MCP tool has the name called.
1456    UnknownTool,
1457    /// An MCP tool call's arguments do not fit the tool.
1458    InvalidArguments,
1459}
1460
1461/// Why Format refused a body, one problem type each.
1462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1463pub(crate) enum Invalid {
1464    BadGzip,
1465    NotJson,
1466    DuplicateMember,
1467    AmbiguousForm,
1468    NoForm,
1469    MissingUuid,
1470    BadUuid,
1471    MissingCreatedAt,
1472    BadPayload,
1473    UuidMismatch,
1474    BadCritical,
1475    UnsupportedExtension,
1476    TooDeep,
1477    /// A refusal from the vcon crate that this server does not name.
1478    Other,
1479}
1480
1481/// The problem for Format's refusal. Inflating past the limit is a body
1482/// too large; the others are unprocessable. No problem repeats the body,
1483/// so unsupported extensions are not named.
1484fn rejected(rejection: &Rejection) -> Problem {
1485    Problem::Invalid(match rejection {
1486        Rejection::TooLarge => return Problem::TooLarge,
1487        Rejection::BadGzip => Invalid::BadGzip,
1488        Rejection::NotJson => Invalid::NotJson,
1489        Rejection::DuplicateKey => Invalid::DuplicateMember,
1490        Rejection::AmbiguousForm => Invalid::AmbiguousForm,
1491        Rejection::NoForm => Invalid::NoForm,
1492        Rejection::MissingUuid => Invalid::MissingUuid,
1493        Rejection::BadUuid => Invalid::BadUuid,
1494        Rejection::MissingCreatedAt => Invalid::MissingCreatedAt,
1495        Rejection::BadPayload => Invalid::BadPayload,
1496        Rejection::UuidMismatch => Invalid::UuidMismatch,
1497        Rejection::BadCritical => Invalid::BadCritical,
1498        Rejection::UnsupportedCritical(_) => Invalid::UnsupportedExtension,
1499        Rejection::TooDeep => Invalid::TooDeep,
1500        // A refusal a later vcon release adds, before this server names it.
1501        // Every refusal there is today is named above, so no test reaches
1502        // this arm; the problem it answers with is tested on its own.
1503        _ => Invalid::Other,
1504    })
1505}
1506
1507/// The problem for Store's refusal or failure.
1508fn failed(error: StoreError) -> Problem {
1509    Problem::Store(error)
1510}
1511
1512impl Problem {
1513    pub(crate) fn status(self) -> StatusCode {
1514        match self {
1515            Problem::Unauthorized => StatusCode::UNAUTHORIZED,
1516            Problem::Forbidden | Problem::WrongListener => StatusCode::FORBIDDEN,
1517            Problem::UnknownKey => StatusCode::NOT_FOUND,
1518            Problem::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
1519            Problem::Timeout => StatusCode::REQUEST_TIMEOUT,
1520            Problem::NoSession | Problem::KeyExpired => StatusCode::UNAUTHORIZED,
1521            Problem::BadOrigin | Problem::BadCsrf => StatusCode::FORBIDDEN,
1522            Problem::BadBody
1523            | Problem::BadPathUuid
1524            | Problem::BadPathVersion
1525            | Problem::BadQuery
1526            | Problem::KeyAndSession => StatusCode::BAD_REQUEST,
1527            Problem::PreconditionRequired => StatusCode::PRECONDITION_REQUIRED,
1528            Problem::PathUuidMismatch => StatusCode::UNPROCESSABLE_ENTITY,
1529            Problem::Unavailable | Problem::AuditFailed | Problem::AtCapacity => {
1530                StatusCode::SERVICE_UNAVAILABLE
1531            }
1532            Problem::RateLimited => StatusCode::TOO_MANY_REQUESTS,
1533            Problem::UnknownTool => StatusCode::NOT_FOUND,
1534            Problem::InvalidArguments => StatusCode::UNPROCESSABLE_ENTITY,
1535            Problem::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
1536            Problem::Invalid(_) | Problem::InvalidBody => StatusCode::UNPROCESSABLE_ENTITY,
1537            Problem::Store(error) => match error {
1538                StoreError::Conflict | StoreError::NotDeleted | StoreError::Immutable => {
1539                    StatusCode::CONFLICT
1540                }
1541                StoreError::Gone => StatusCode::GONE,
1542                StoreError::NotFound => StatusCode::NOT_FOUND,
1543                StoreError::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
1544                StoreError::LimitReached | StoreError::AuditFailed => {
1545                    StatusCode::SERVICE_UNAVAILABLE
1546                }
1547                StoreError::Damaged | StoreError::Io => StatusCode::INTERNAL_SERVER_ERROR,
1548            },
1549            Problem::Tenant(error) => match error {
1550                TenantError::NotFound => StatusCode::NOT_FOUND,
1551                TenantError::NameTaken | TenantError::HoldsVcons | TenantError::UnderHold => {
1552                    StatusCode::CONFLICT
1553                }
1554                TenantError::BadName
1555                | TenantError::BadScopes
1556                | TenantError::BadExpiry
1557                | TenantError::BadSetting(_) => StatusCode::UNPROCESSABLE_ENTITY,
1558                TenantError::CliOnly => StatusCode::FORBIDDEN,
1559                TenantError::LimitReached | TenantError::AuditFailed | TenantError::Closing => {
1560                    StatusCode::SERVICE_UNAVAILABLE
1561                }
1562                TenantError::WrongKey | TenantError::Io => StatusCode::INTERNAL_SERVER_ERROR,
1563            },
1564        }
1565    }
1566
1567    /// The last part of its type URI, and its title.
1568    pub(crate) fn name(self) -> (&'static str, &'static str) {
1569        match self {
1570            Problem::Unauthorized => ("unauthorized", "A valid bearer key is needed"),
1571            Problem::Forbidden => ("forbidden", "The key does not allow this"),
1572            Problem::WrongListener => (
1573                "wrong-listener",
1574                "This listener does not serve this kind of key",
1575            ),
1576            Problem::KeyAndSession => (
1577                "key-and-session",
1578                "The request carries both a key and a session cookie",
1579            ),
1580            Problem::NoSession => ("no-session", "A live session is needed"),
1581            Problem::KeyExpired => ("key-expired", "The key has expired"),
1582            Problem::BadOrigin => (
1583                "bad-origin",
1584                "The request does not come from this listener's own pages",
1585            ),
1586            Problem::BadCsrf => ("bad-csrf", "The session's CSRF token is missing or wrong"),
1587            Problem::TooLarge => ("too-large", "The body is over the size limit"),
1588            Problem::Timeout => ("timeout", "The body did not arrive in time"),
1589            Problem::BadBody => ("bad-body", "The body could not be read"),
1590            Problem::BadPathUuid => (
1591                "bad-path-uuid",
1592                "The path's uuid is not in RFC 9562 text form",
1593            ),
1594            Problem::BadPathVersion => {
1595                ("bad-path-version", "The path's version is not a version id")
1596            }
1597            Problem::PreconditionRequired => (
1598                "precondition-required",
1599                "If-Match must name the current version",
1600            ),
1601            Problem::PathUuidMismatch => (
1602                "path-uuid-mismatch",
1603                "The body's uuid is not the one in the path",
1604            ),
1605            Problem::Unavailable => ("unavailable", "The service cannot answer now"),
1606            Problem::AuditFailed => ("audit-failed", "The audit record could not be written"),
1607            Problem::UnsupportedMediaType => {
1608                ("unsupported-media-type", "This media type is not taken")
1609            }
1610            Problem::Invalid(invalid) => match invalid {
1611                Invalid::BadGzip => ("bad-gzip", "The body is marked gzip but is not"),
1612                Invalid::NotJson => ("not-json", "The body is not one JSON object"),
1613                Invalid::DuplicateMember => ("duplicate-member", "An object repeats a member"),
1614                Invalid::AmbiguousForm => {
1615                    ("ambiguous-form", "The body is both signed and encrypted")
1616                }
1617                Invalid::NoForm => ("no-form", "The body is in no vCon form"),
1618                Invalid::MissingUuid => ("missing-uuid", "The vCon has no uuid"),
1619                Invalid::BadUuid => ("bad-uuid", "The uuid is not in RFC 9562 text form"),
1620                Invalid::MissingCreatedAt => ("missing-created-at", "The vCon has no created_at"),
1621                Invalid::BadPayload => ("bad-payload", "The signed payload cannot be read"),
1622                Invalid::UuidMismatch => ("uuid-mismatch", "A signature names another uuid"),
1623                Invalid::BadCritical => (
1624                    "bad-critical",
1625                    "critical or must_support is not a list of names",
1626                ),
1627                Invalid::UnsupportedExtension => (
1628                    "unsupported-extension",
1629                    "An extension the vCon needs is not supported",
1630                ),
1631                Invalid::TooDeep => ("too-deep", "The body nests too deeply"),
1632                Invalid::Other => ("not-a-vcon", "The body is not a vCon this server can read"),
1633            },
1634            Problem::Store(error) => match error {
1635                StoreError::Conflict => ("conflict", "Another vCon holds the uuid"),
1636                StoreError::Gone => ("gone", "The vCon was deleted or purged"),
1637                StoreError::NotFound => ("not-found", "No vCon has the uuid"),
1638                StoreError::NotDeleted => ("not-deleted", "The vCon is not deleted"),
1639                StoreError::PreconditionFailed => (
1640                    "precondition-failed",
1641                    "If-Match does not name the current version",
1642                ),
1643                StoreError::Immutable => {
1644                    ("immutable", "A signed or encrypted vCon is not replaced")
1645                }
1646                StoreError::LimitReached => ("limit-reached", "The tenant key must be rotated"),
1647                StoreError::Damaged => ("damaged", "A stored version is damaged"),
1648                StoreError::AuditFailed => {
1649                    ("audit-failed", "The audit record could not be written")
1650                }
1651                StoreError::Io => ("internal", "The server failed"),
1652            },
1653            Problem::BadQuery => ("bad-query", "The query is not one this route takes"),
1654            Problem::RateLimited => ("rate-limited", "Too many tool calls from this key"),
1655            Problem::AtCapacity => ("at-capacity", "Too many tool calls are running"),
1656            Problem::UnknownTool => ("unknown-tool", "No tool has the name"),
1657            Problem::InvalidArguments => ("invalid-arguments", "The arguments do not fit the tool"),
1658            Problem::UnknownKey => ("unknown-key", "No key has the id"),
1659            Problem::InvalidBody | Problem::Tenant(TenantError::BadName) => {
1660                ("invalid-body", "The body is not one this route takes")
1661            }
1662            Problem::Tenant(error) => match error {
1663                TenantError::NotFound => ("unknown-tenant", "No tenant has the id"),
1664                TenantError::NameTaken => ("name-taken", "Another tenant has the name"),
1665                TenantError::HoldsVcons => (
1666                    "holds-vcons",
1667                    "The tenant holds vCons; removing them needs force",
1668                ),
1669                TenantError::UnderHold => {
1670                    ("under-hold", "A vCon of the tenant is under a legal hold")
1671                }
1672                TenantError::BadScopes => ("bad-scopes", "A tenant key cannot hold these scopes"),
1673                TenantError::BadExpiry => ("bad-expiry", "A key cannot have this expiry"),
1674                TenantError::BadSetting(_) => (
1675                    "bad-setting",
1676                    "A setting's name or value is not one a tenant may set",
1677                ),
1678                TenantError::CliOnly => ("forbidden", "The key does not allow this"),
1679                TenantError::LimitReached => ("master-key-limit", "The master key must be rotated"),
1680                TenantError::AuditFailed => {
1681                    ("audit-failed", "The audit record could not be written")
1682                }
1683                TenantError::Closing => ("unavailable", "The service cannot answer now"),
1684                TenantError::BadName | TenantError::WrongKey | TenantError::Io => {
1685                    ("internal", "The server failed")
1686                }
1687            },
1688        }
1689    }
1690}
1691
1692impl Problem {
1693    /// The problem document (RFC 9457): its type, title and status. The
1694    /// HTTP API answers it, and an MCP refusal carries it as its data.
1695    pub(crate) fn document(self) -> serde_json::Value {
1696        let (name, title) = self.name();
1697        serde_json::json!({
1698            "type": format!("https://vcon-server.com/problems/{name}"),
1699            "title": title,
1700            "status": self.status().as_u16(),
1701        })
1702    }
1703}
1704
1705impl IntoResponse for Problem {
1706    fn into_response(self) -> Response {
1707        let (status, body) = (self.status(), self.document());
1708        let mut answer = (
1709            status,
1710            [(CONTENT_TYPE, "application/problem+json")],
1711            body.to_string(),
1712        )
1713            .into_response();
1714        // A 401 names what the route takes: a key, or a session.
1715        let challenge = match self {
1716            Problem::Unauthorized | Problem::KeyExpired => Some("Bearer"),
1717            Problem::NoSession => Some("Session"),
1718            _ => None,
1719        };
1720        if let Some(challenge) = challenge {
1721            answer
1722                .headers_mut()
1723                .insert(WWW_AUTHENTICATE, HeaderValue::from_static(challenge));
1724        }
1725        answer
1726    }
1727}
1728
1729/// Why the TLS configuration could not be made.
1730#[derive(Debug)]
1731pub enum TlsError {
1732    /// The certificate file could not be read, or holds no certificate.
1733    Certificate,
1734    /// The key file could not be read, or holds no key.
1735    Key,
1736    /// The key file breaks the secret-file rule or cannot be opened; the
1737    /// text names the configuration key, the file and the fix.
1738    KeyFile(String),
1739    /// rustls refused the pair, for instance a key that is not the
1740    /// certificate's.
1741    Refused(rustls::Error),
1742}
1743
1744/// The server's TLS configuration from a PEM certificate chain and a PEM
1745/// private key, the files `tls.cert` and `tls.key` name.
1746pub fn tls_config(certificate: &Path, key: &Path) -> Result<Arc<ServerConfig>, TlsError> {
1747    tls_config_named(certificate, key, "tls.key")
1748}
1749
1750/// [`tls_config`], for a key file that the configuration key `named`
1751/// names, so a refusal of the file says which key to look at.
1752pub fn tls_config_named(
1753    certificate: &Path,
1754    key: &Path,
1755    named: &str,
1756) -> Result<Arc<ServerConfig>, TlsError> {
1757    let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(certificate)
1758        .map_err(|_| TlsError::Certificate)?
1759        .collect::<Result<_, _>>()
1760        .map_err(|_| TlsError::Certificate)?;
1761    if chain.is_empty() {
1762        return Err(TlsError::Certificate);
1763    }
1764    let bytes = crate::secret_file::read(key, named).map_err(TlsError::KeyFile)?;
1765    let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|_| TlsError::Key)?;
1766    let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
1767    let mut config = ServerConfig::builder_with_provider(provider)
1768        .with_safe_default_protocol_versions()
1769        .map_err(TlsError::Refused)?
1770        .with_no_client_auth()
1771        .with_single_cert(chain, key)
1772        .map_err(TlsError::Refused)?;
1773    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
1774    Ok(Arc::new(config))
1775}
1776
1777#[cfg(test)]
1778mod tests {
1779    use std::net::SocketAddr;
1780    use std::path::PathBuf;
1781
1782    use axum::routing::get;
1783    use tokio::net::TcpListener;
1784
1785    use super::*;
1786
1787    /// A self-signed certificate for localhost and its key, as PEM files.
1788    struct Certificate {
1789        _dir: tempfile::TempDir,
1790        cert: PathBuf,
1791        key: PathBuf,
1792        pem: String,
1793    }
1794
1795    fn certificate() -> Certificate {
1796        let dir = tempfile::tempdir().expect("temp dir");
1797        let made = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()])
1798            .expect("a certificate");
1799        let pem = made.cert.pem();
1800        let (cert, key) = (dir.path().join("cert.pem"), dir.path().join("key.pem"));
1801        std::fs::write(&cert, &pem).expect("write");
1802        std::fs::write(&key, made.signing_key.serialize_pem()).expect("write");
1803        std::fs::set_permissions(
1804            &key,
1805            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
1806        )
1807        .expect("chmod 0600");
1808        Certificate {
1809            _dir: dir,
1810            cert,
1811            key,
1812            pem,
1813        }
1814    }
1815
1816    fn client(c: &Certificate, addr: SocketAddr) -> reqwest::Client {
1817        reqwest::Client::builder()
1818            .tls_certs_only([reqwest::Certificate::from_pem(c.pem.as_bytes()).expect("pem")])
1819            .resolve("localhost", addr)
1820            .no_proxy()
1821            .build()
1822            .expect("a client")
1823    }
1824
1825    #[tokio::test]
1826    async fn the_listener_speaks_tls_only() {
1827        let c = certificate();
1828        let tls = tls_config(&c.cert, &c.key).expect("loads");
1829        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
1830        let addr = listener.local_addr().expect("addr");
1831        let app = Router::new().route("/ping", get(|| async { "pong" }));
1832        let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1833        let server = tokio::spawn(serve(listener, tls, app, async {
1834            stopped.await.ok();
1835        }));
1836        let plain = reqwest::Client::builder()
1837            .no_proxy()
1838            .build()
1839            .expect("a client")
1840            .get(format!("http://{addr}/ping"))
1841            .send()
1842            .await;
1843        assert!(plain.is_err(), "plain HTTP is not served: {plain:?}");
1844        let answer = client(&c, addr)
1845            .get(format!("https://localhost:{}/ping", addr.port()))
1846            .send()
1847            .await
1848            .expect("TLS is served, after a plain-HTTP attempt too");
1849        assert_eq!(answer.status(), 200);
1850        assert_eq!(answer.version(), reqwest::Version::HTTP_2, "h2 by ALPN");
1851        assert_eq!(answer.text().await.expect("body"), "pong");
1852        stop.send(()).expect("stop");
1853        server.await.expect("joins").expect("serves");
1854    }
1855
1856    #[test]
1857    fn a_missing_or_unusable_certificate_or_key_is_refused() {
1858        let c = certificate();
1859        let other = certificate();
1860        let dir = tempfile::tempdir().expect("temp dir");
1861        let (missing, empty) = (dir.path().join("missing"), dir.path().join("empty"));
1862        std::fs::write(&empty, "").expect("write");
1863        std::fs::set_permissions(
1864            &empty,
1865            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
1866        )
1867        .expect("chmod 0600");
1868        assert!(matches!(
1869            tls_config(&missing, &c.key),
1870            Err(TlsError::Certificate)
1871        ));
1872        assert!(matches!(
1873            tls_config(&empty, &c.key),
1874            Err(TlsError::Certificate)
1875        ));
1876        assert!(
1877            matches!(tls_config(&c.cert, &missing), Err(TlsError::KeyFile(t)) if t.starts_with(&format!("tls.key {}: No such file", missing.display()))),
1878            "a missing key file is named with the key and the path"
1879        );
1880        assert!(matches!(tls_config(&c.cert, &empty), Err(TlsError::Key)));
1881        assert!(matches!(
1882            tls_config(&c.cert, &other.key),
1883            Err(TlsError::Refused(_))
1884        ));
1885        assert!(tls_config(&c.cert, &c.key).is_ok());
1886    }
1887
1888    pub(crate) mod pipeline {
1889        use std::net::SocketAddr;
1890
1891        use serde_json::Value;
1892        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1893
1894        use super::*;
1895        use crate::access::{Scope, Scopes};
1896        use crate::audit::Actor;
1897        use crate::clock::Clock;
1898        use crate::envelope::Key;
1899        use crate::fs::OsFs;
1900        use crate::ids::TenantId;
1901
1902        pub(crate) const LIMIT: usize = 64 * 1024;
1903
1904        /// The time every test server starts at.
1905        pub(crate) const START: time::OffsetDateTime =
1906            time::macros::datetime!(2026-10-23 12:00 UTC);
1907
1908        /// The test servers' clock. It starts at START, and each reading
1909        /// moves it on by a microsecond, so times read one after another are
1910        /// in order and differ, as on a real clock, but no answer depends on
1911        /// when a test runs. A test may set it.
1912        pub(crate) struct TestClock(std::sync::Mutex<time::OffsetDateTime>);
1913
1914        impl TestClock {
1915            pub(crate) fn set(&self, now: time::OffsetDateTime) {
1916                *self.0.lock().expect("clock") = now;
1917            }
1918        }
1919
1920        impl Clock for TestClock {
1921            fn now(&self) -> time::OffsetDateTime {
1922                let mut next = self.0.lock().expect("clock");
1923                let now = *next;
1924                *next += time::Duration::MICROSECOND;
1925                now
1926            }
1927        }
1928
1929        /// A server with one tenant, on a free port. Its registry and stores
1930        /// read the time from `clock`.
1931        pub(crate) struct Server {
1932            _dir: tempfile::TempDir,
1933            certificate: Certificate,
1934            addr: SocketAddr,
1935            pub(crate) clock: Arc<TestClock>,
1936            pub(crate) tenants: Arc<Tenants>,
1937            pub(crate) app: Arc<App>,
1938            pub(crate) tenant: TenantId,
1939            stop: Option<tokio::sync::oneshot::Sender<()>>,
1940        }
1941
1942        impl Drop for Server {
1943            fn drop(&mut self) {
1944                if let Some(stop) = self.stop.take() {
1945                    let _ = stop.send(());
1946                }
1947            }
1948        }
1949
1950        pub(crate) async fn server() -> Server {
1951            server_with(&[]).await
1952        }
1953
1954        /// A server that supports the must_support extensions named.
1955        pub(crate) async fn server_with(supported: &[&str]) -> Server {
1956            server_from(supported, Retention::Years(7)).await
1957        }
1958
1959        /// A server whose tenants that set no retention period keep
1960        /// vCons for `default`.
1961        pub(crate) async fn server_keeping(default: Retention) -> Server {
1962            server_from(&[], default).await
1963        }
1964
1965        /// A server whose listener is of `plane`.
1966        pub(crate) async fn server_on(plane: Plane) -> Server {
1967            server_of(&[], Retention::Years(7), plane).await
1968        }
1969
1970        async fn server_from(supported: &[&str], retention_default: Retention) -> Server {
1971            server_of(supported, retention_default, Plane::Both).await
1972        }
1973
1974        async fn server_of(
1975            supported: &[&str],
1976            retention_default: Retention,
1977            plane: Plane,
1978        ) -> Server {
1979            server_built(supported, retention_default, plane, ReportLimits::DEFAULT).await
1980        }
1981
1982        /// A server that takes the reports `reports` allows.
1983        pub(crate) async fn server_limiting(reports: ReportLimits) -> Server {
1984            server_built(&[], Retention::Years(7), Plane::Both, reports).await
1985        }
1986
1987        /// A server whose listener has no public origin, so it serves no
1988        /// session.
1989        pub(crate) async fn server_without_origin() -> Server {
1990            let reports = ReportLimits::DEFAULT;
1991            server_made(&[], Retention::Years(7), Plane::Both, reports, false).await
1992        }
1993
1994        async fn server_built(
1995            supported: &[&str],
1996            retention_default: Retention,
1997            plane: Plane,
1998            reports: ReportLimits,
1999        ) -> Server {
2000            server_made(supported, retention_default, plane, reports, true).await
2001        }
2002
2003        /// The server every other maker here makes. With `origin`, its
2004        /// public origin is the address its clients reach it at.
2005        async fn server_made(
2006            supported: &[&str],
2007            retention_default: Retention,
2008            plane: Plane,
2009            reports: ReportLimits,
2010            origin: bool,
2011        ) -> Server {
2012            let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
2013            let addr = listener.local_addr().expect("addr");
2014            let origin = origin.then(|| {
2015                crate::session::Origin::parse(&format!("https://localhost:{}", addr.port()))
2016                    .expect("an origin")
2017            });
2018            let dir = tempfile::tempdir().expect("temp dir");
2019            let clock = Arc::new(TestClock(std::sync::Mutex::new(START)));
2020            let tenants = Arc::new(
2021                Tenants::open(
2022                    dir.path(),
2023                    Key::generate().expect("master key"),
2024                    Arc::new(OsFs),
2025                    clock.clone(),
2026                )
2027                .expect("opens"),
2028            );
2029            let tenant = tenants.create(Actor::Cli, "acme", None).expect("a tenant");
2030            let app = Arc::new(App {
2031                tenants: tenants.clone(),
2032                limits: Limits {
2033                    body: LIMIT,
2034                    inflated: 1 << 20,
2035                    body_timeout: Duration::from_millis(300),
2036                },
2037                supported: supported.iter().map(|s| (*s).to_owned()).collect(),
2038                retention_default,
2039                mcp: crate::mcp::Limits::DEFAULT,
2040                plane,
2041                reports: ReportGate::new(reports),
2042                origin,
2043            });
2044            let certificate = certificate();
2045            let tls = tls_config(&certificate.cert, &certificate.key).expect("tls");
2046            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
2047            tokio::spawn(serve(listener, tls, router(app.clone()), async {
2048                stopped.await.ok();
2049            }));
2050            Server {
2051                _dir: dir,
2052                certificate,
2053                addr,
2054                clock,
2055                tenants,
2056                app,
2057                tenant,
2058                stop: Some(stop),
2059            }
2060        }
2061
2062        impl Server {
2063            pub(crate) fn dir(&self) -> &std::path::Path {
2064                self._dir.path()
2065            }
2066
2067            pub(crate) fn url(&self, path: &str) -> String {
2068                format!("https://localhost:{}{path}", self.addr.port())
2069            }
2070
2071            pub(crate) fn client(&self) -> reqwest::Client {
2072                client(&self.certificate, self.addr)
2073            }
2074
2075            /// A client that shows a redirect instead of following it.
2076            pub(crate) fn client_not_following(&self) -> reqwest::Client {
2077                let pem = self.certificate.pem.as_bytes();
2078                reqwest::Client::builder()
2079                    .tls_certs_only([reqwest::Certificate::from_pem(pem).expect("pem")])
2080                    .resolve("localhost", self.addr)
2081                    .no_proxy()
2082                    .redirect(reqwest::redirect::Policy::none())
2083                    .build()
2084                    .expect("a client")
2085            }
2086
2087            pub(crate) fn key(&self, scopes: &[Scope]) -> String {
2088                self.tenants
2089                    .create_key(Actor::Cli, Some(self.tenant), Scopes::of(scopes), "test")
2090                    .expect("a key")
2091                    .token
2092            }
2093
2094            pub(crate) fn tenant_log(&self, action: &str) -> Vec<Value> {
2095                let store = self.tenants.store(self.tenant).expect("its store");
2096                store
2097                    .records()
2098                    .into_iter()
2099                    .filter(|r| r["action"] == action)
2100                    .collect()
2101            }
2102
2103            /// Sends a POST /vcons over HTTP/1.1 with a chunked body: the
2104            /// chunks given, and then, unless `finish`, nothing more while
2105            /// the connection stays open. Returns the status line.
2106            async fn chunked(&self, token: &str, chunks: &[usize], finish: bool) -> String {
2107                let mut body = String::new();
2108                for &size in chunks {
2109                    body.push_str(&format!("{size:x}\r\n{}\r\n", "x".repeat(size)));
2110                }
2111                if finish {
2112                    body.push_str("0\r\n\r\n");
2113                }
2114                self.raw(token, "transfer-encoding: chunked", body.as_bytes())
2115                    .await
2116            }
2117
2118            /// Sends a POST /vcons over HTTP/1.1 with one header of the
2119            /// caller's and the bytes given, keeping the connection open.
2120            /// Returns the status line.
2121            async fn raw(&self, token: &str, header: &str, body: &[u8]) -> String {
2122                let head = format!(
2123                    "POST /vcons HTTP/1.1\r\nhost: localhost\r\nauthorization: Bearer {token}\r\n\
2124                     content-type: application/vcon\r\n{header}\r\n\r\n"
2125                );
2126                self.raw_request(&head, body).await
2127            }
2128
2129            /// Sends a request head as written, then the bytes given, over
2130            /// HTTP/1.1, keeping the connection open. Returns the status
2131            /// line.
2132            pub(crate) async fn raw_request(&self, head: &str, body: &[u8]) -> String {
2133                let mut roots = rustls::RootCertStore::empty();
2134                for cert in CertificateDer::pem_slice_iter(self.certificate.pem.as_bytes()) {
2135                    roots.add(cert.expect("pem")).expect("a root");
2136                }
2137                let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
2138                let mut config = rustls::ClientConfig::builder_with_provider(provider)
2139                    .with_safe_default_protocol_versions()
2140                    .expect("versions")
2141                    .with_root_certificates(roots)
2142                    .with_no_client_auth();
2143                config.alpn_protocols = vec![b"http/1.1".to_vec()];
2144                let tcp = tokio::net::TcpStream::connect(self.addr)
2145                    .await
2146                    .expect("connect");
2147                let mut tls = tokio_rustls::TlsConnector::from(Arc::new(config))
2148                    .connect("localhost".try_into().expect("name"), tcp)
2149                    .await
2150                    .expect("handshake");
2151                tls.write_all(head.as_bytes()).await.expect("head");
2152                // The server may answer and stop reading before all is sent.
2153                let _ = tls.write_all(body).await;
2154                let mut answer = vec![0; 4096];
2155                let read = tokio::time::timeout(Duration::from_secs(10), tls.read(&mut answer))
2156                    .await
2157                    .expect("an answer while the body is still open")
2158                    .expect("read");
2159                let answer = String::from_utf8_lossy(&answer[..read]).into_owned();
2160                answer.lines().next().unwrap_or_default().to_owned()
2161            }
2162        }
2163
2164        async fn post(s: &Server, token: Option<&str>, body: Vec<u8>) -> reqwest::Response {
2165            let mut request = s
2166                .client()
2167                .post(s.url("/vcons"))
2168                .header("content-type", "application/vcon")
2169                .body(body);
2170            if let Some(token) = token {
2171                request = request.bearer_auth(token);
2172            }
2173            request.send().await.expect("an answer")
2174        }
2175
2176        /// Checks the answer is a problem document for its status, and
2177        /// returns its type's last part.
2178        pub(crate) async fn problem(answer: reqwest::Response) -> String {
2179            assert_eq!(
2180                answer.headers()["content-type"],
2181                "application/problem+json",
2182                "{answer:?}"
2183            );
2184            let status = answer.status().as_u16();
2185            let body: Value =
2186                serde_json::from_str(&answer.text().await.expect("text")).expect("JSON");
2187            assert_eq!(body["status"], status);
2188            assert!(body["title"].as_str().is_some_and(|t| !t.is_empty()));
2189            body["type"]
2190                .as_str()
2191                .and_then(|t| t.strip_prefix("https://vcon-server.com/problems/"))
2192                .expect("a type under the server's domain")
2193                .to_owned()
2194        }
2195
2196        #[tokio::test]
2197        async fn a_request_without_a_valid_key_is_unauthorized() {
2198            let s = server().await;
2199            for token in [None, Some("vcs_nonsense")] {
2200                let answer = post(&s, token, b"{}".to_vec()).await;
2201                assert_eq!(answer.status(), 401, "{token:?}");
2202                assert_eq!(answer.headers()["www-authenticate"], "Bearer");
2203                assert_eq!(problem(answer).await, "unauthorized");
2204            }
2205        }
2206
2207        #[tokio::test]
2208        async fn a_key_table_that_cannot_be_read_makes_the_service_unavailable() {
2209            let s = server().await;
2210            let writer = s.key(&[Scope::Write]);
2211            s.tenants
2212                .conn_for_test()
2213                .execute_batch("ALTER TABLE api_key RENAME TO gone")
2214                .expect("lose the table");
2215            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2216            assert_eq!(answer.status(), 503);
2217            assert_eq!(problem(answer).await, "unavailable");
2218        }
2219
2220        #[tokio::test]
2221        async fn a_refusal_that_cannot_be_recorded_answers_that_the_audit_failed() {
2222            let s = server().await;
2223            let reader = s.key(&[Scope::Read]);
2224            s.tenants.store(s.tenant).expect("its store").break_audit();
2225            let answer = post(&s, Some(&reader), b"{}".to_vec()).await;
2226            assert_eq!(answer.status(), 503);
2227            assert_eq!(problem(answer).await, "audit-failed");
2228
2229            let operator = s
2230                .tenants
2231                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
2232                .expect("made")
2233                .token;
2234            s.tenants.break_audit();
2235            let answer = post(&s, Some(&operator), b"{}".to_vec()).await;
2236            assert_eq!(answer.status(), 503);
2237            assert_eq!(problem(answer).await, "audit-failed");
2238        }
2239
2240        #[tokio::test]
2241        async fn a_key_without_the_scope_is_forbidden_and_recorded() {
2242            let s = server().await;
2243            let reader = s.key(&[Scope::Read]);
2244            let answer = post(&s, Some(&reader), b"{}".to_vec()).await;
2245            assert_eq!(answer.status(), 403);
2246            assert_eq!(problem(answer).await, "forbidden");
2247            let refused = s.tenant_log("create");
2248            assert_eq!(refused.len(), 1);
2249            assert_eq!(refused[0]["status"], 403);
2250
2251            let operator = s
2252                .tenants
2253                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
2254                .expect("made")
2255                .token;
2256            let answer = post(&s, Some(&operator), b"{}".to_vec()).await;
2257            assert_eq!(answer.status(), 403);
2258            let admin: Vec<Value> = s
2259                .tenants
2260                .admin_records()
2261                .into_iter()
2262                .filter(|r| r["action"] == "create")
2263                .collect();
2264            assert_eq!(admin.len(), 1, "an operator's refusal is in the admin log");
2265            assert_eq!(admin[0]["status"], 403);
2266        }
2267
2268        #[tokio::test]
2269        async fn a_closing_tenant_is_unavailable() {
2270            let s = server().await;
2271            let writer = s.key(&[Scope::Write]);
2272            s.tenants.close(s.tenant);
2273            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2274            assert_eq!(answer.status(), 503);
2275            assert_eq!(problem(answer).await, "unavailable");
2276        }
2277
2278        #[tokio::test]
2279        async fn a_declared_length_over_the_limit_is_refused_at_once() {
2280            let s = server().await;
2281            let writer = s.key(&[Scope::Write]);
2282            let answer = post(&s, Some(&writer), vec![b'x'; LIMIT + 1]).await;
2283            assert_eq!(answer.status(), 413);
2284            assert_eq!(problem(answer).await, "too-large");
2285            assert_eq!(s.tenant_log("create")[0]["status"], 413);
2286            let declared = format!("content-length: {}", LIMIT + 1);
2287            assert_eq!(
2288                s.raw(&writer, &declared, b"").await,
2289                "HTTP/1.1 413 Payload Too Large",
2290                "refused on the declared length, with no byte of the body sent"
2291            );
2292        }
2293
2294        #[tokio::test]
2295        async fn a_body_over_the_limit_is_refused_before_it_is_read_in_full() {
2296            let s = server().await;
2297            let writer = s.key(&[Scope::Write]);
2298            let status = s.chunked(&writer, &[LIMIT / 2, LIMIT / 2 + 1], false).await;
2299            assert_eq!(status, "HTTP/1.1 413 Payload Too Large");
2300        }
2301
2302        #[tokio::test]
2303        async fn a_body_that_stops_arriving_times_out() {
2304            let s = server().await;
2305            let writer = s.key(&[Scope::Write]);
2306            let status = s.chunked(&writer, &[10], false).await;
2307            assert_eq!(status, "HTTP/1.1 408 Request Timeout");
2308            assert_eq!(s.tenant_log("create")[0]["status"], 408);
2309        }
2310
2311        #[tokio::test]
2312        /// The body reaches Format whole: a body of x's at the limit is
2313        /// refused as not JSON, not as too large.
2314        async fn a_request_within_the_limits_goes_on_to_its_route() {
2315            let s = server().await;
2316            let writer = s.key(&[Scope::Write]);
2317            let status = s.chunked(&writer, &[LIMIT / 2, LIMIT / 2], true).await;
2318            assert_eq!(status, "HTTP/1.1 422 Unprocessable Entity");
2319            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2320            assert_eq!(answer.status(), 422);
2321            assert_eq!(problem(answer).await, "no-form");
2322        }
2323    }
2324
2325    #[test]
2326    fn a_removal_query_is_none_or_force_true_or_false_and_nothing_else() {
2327        assert_eq!(removal(None), Some(Removal::Empty));
2328        assert_eq!(removal(Some("force=false")), Some(Removal::Empty));
2329        assert_eq!(removal(Some("force=true")), Some(Removal::Force));
2330        for query in [
2331            "",
2332            "force",
2333            "force=",
2334            "force=1",
2335            "Force=true",
2336            "force=true&",
2337        ] {
2338            assert_eq!(removal(Some(query)), None, "{query:?}");
2339        }
2340    }
2341
2342    /// A refusal the vcon crate adds in a later release, which this
2343    /// server does not name yet, still has a problem: not-a-vcon. No test
2344    /// can send one, since every refusal there is today is named above; this
2345    /// holds the problem the catch-all arm answers with.
2346    #[test]
2347    fn a_refusal_this_server_does_not_name_is_not_a_vcon() {
2348        let problem = Problem::Invalid(Invalid::Other);
2349        assert_eq!(
2350            (problem.status().as_u16(), problem.name().0),
2351            (422, "not-a-vcon")
2352        );
2353    }
2354
2355    #[tokio::test]
2356    async fn every_refusal_from_format_has_its_own_problem() {
2357        let cases = [
2358            (Rejection::TooLarge, 413, "too-large"),
2359            (Rejection::TooDeep, 422, "too-deep"),
2360            (Rejection::BadGzip, 422, "bad-gzip"),
2361            (Rejection::NotJson, 422, "not-json"),
2362            (Rejection::DuplicateKey, 422, "duplicate-member"),
2363            (Rejection::AmbiguousForm, 422, "ambiguous-form"),
2364            (Rejection::NoForm, 422, "no-form"),
2365            (Rejection::MissingUuid, 422, "missing-uuid"),
2366            (Rejection::BadUuid, 422, "bad-uuid"),
2367            (Rejection::MissingCreatedAt, 422, "missing-created-at"),
2368            (Rejection::BadPayload, 422, "bad-payload"),
2369            (Rejection::UuidMismatch, 422, "uuid-mismatch"),
2370            (Rejection::BadCritical, 422, "bad-critical"),
2371            (
2372                Rejection::UnsupportedCritical(vec!["secret-name".to_owned()]),
2373                422,
2374                "unsupported-extension",
2375            ),
2376        ];
2377        for (rejection, status, name) in &cases {
2378            let problem = rejected(rejection);
2379            assert_eq!(
2380                (problem.status().as_u16(), problem.name().0),
2381                (*status, *name),
2382                "{rejection:?}"
2383            );
2384            let body = axum::body::to_bytes(problem.into_response().into_body(), usize::MAX)
2385                .await
2386                .expect("the body");
2387            let answer = String::from_utf8(body.to_vec()).expect("UTF-8");
2388            assert!(answer.contains(&format!("\"status\":{status}")), "{answer}");
2389            assert!(
2390                !answer.contains("secret-name"),
2391                "the name is not repeated: {answer}"
2392            );
2393        }
2394    }
2395
2396    #[test]
2397    fn every_store_outcome_has_its_problem() {
2398        let cases = [
2399            (StoreError::Conflict, 409, "conflict"),
2400            (StoreError::Gone, 410, "gone"),
2401            (StoreError::NotFound, 404, "not-found"),
2402            (StoreError::NotDeleted, 409, "not-deleted"),
2403            (StoreError::PreconditionFailed, 412, "precondition-failed"),
2404            (StoreError::Immutable, 409, "immutable"),
2405            (StoreError::LimitReached, 503, "limit-reached"),
2406            (StoreError::Damaged, 500, "damaged"),
2407            (StoreError::AuditFailed, 503, "audit-failed"),
2408            (StoreError::Io, 500, "internal"),
2409        ];
2410        for (error, status, name) in cases {
2411            let problem = failed(error);
2412            assert_eq!(
2413                (problem.status().as_u16(), problem.name().0),
2414                (status, name),
2415                "{error:?}"
2416            );
2417        }
2418    }
2419
2420    #[test]
2421    fn every_tenants_outcome_has_its_problem() {
2422        let cases = [
2423            (TenantError::NotFound, 404, "unknown-tenant"),
2424            (TenantError::NameTaken, 409, "name-taken"),
2425            (TenantError::BadName, 422, "invalid-body"),
2426            (TenantError::HoldsVcons, 409, "holds-vcons"),
2427            (TenantError::UnderHold, 409, "under-hold"),
2428            (TenantError::LimitReached, 503, "master-key-limit"),
2429            (TenantError::AuditFailed, 503, "audit-failed"),
2430            (TenantError::Closing, 503, "unavailable"),
2431            (TenantError::CliOnly, 403, "forbidden"),
2432            (TenantError::BadScopes, 422, "bad-scopes"),
2433            (TenantError::BadExpiry, 422, "bad-expiry"),
2434            (
2435                TenantError::BadSetting(crate::settings::SettingError::UnknownName),
2436                422,
2437                "bad-setting",
2438            ),
2439            (TenantError::WrongKey, 500, "internal"),
2440            (TenantError::Io, 500, "internal"),
2441        ];
2442        for (error, status, name) in cases {
2443            let problem = Problem::Tenant(error);
2444            assert_eq!(
2445                (problem.status().as_u16(), problem.name().0),
2446                (status, name),
2447                "{error:?}"
2448            );
2449        }
2450    }
2451
2452    mod vcons {
2453        use std::io::Write;
2454
2455        use super::pipeline::{Server, problem, server};
2456        use crate::access::Scope;
2457        use crate::store::Caller as StoreCaller;
2458        use crate::store::testing::vcon;
2459
2460        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
2461
2462        fn uuid(n: u8) -> String {
2463            format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02x}")
2464        }
2465
2466        async fn post(
2467            s: &Server,
2468            token: &str,
2469            content_type: Option<&str>,
2470            body: Vec<u8>,
2471        ) -> reqwest::Response {
2472            let mut request = s
2473                .client()
2474                .post(s.url("/vcons"))
2475                .bearer_auth(token)
2476                .body(body);
2477            if let Some(content_type) = content_type {
2478                request = request.header("content-type", content_type);
2479            }
2480            request.send().await.expect("an answer")
2481        }
2482
2483        fn gzip(body: &[u8]) -> Vec<u8> {
2484            let mut encoder =
2485                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2486            encoder.write_all(body).expect("gzip");
2487            encoder.finish().expect("gzip")
2488        }
2489
2490        fn store_caller() -> StoreCaller {
2491            StoreCaller {
2492                key: crate::ids::KeyId([9; 8]),
2493            }
2494        }
2495
2496        #[tokio::test]
2497        async fn a_new_vcon_is_created_with_its_location_and_tag() {
2498            let s = server().await;
2499            let writer = s.key(&[Scope::Write]);
2500            let (found, body) = vcon(UUID, "first");
2501            let answer = post(&s, &writer, Some("application/vcon"), body.clone()).await;
2502            assert_eq!(answer.status(), 201);
2503            assert_eq!(answer.headers()["location"], format!("/vcons/{UUID}"));
2504            let tag = answer.headers()["etag"].to_str().expect("ascii").to_owned();
2505            let stored = s
2506                .tenants
2507                .store(s.tenant)
2508                .expect("its store")
2509                .get(&store_caller(), found.uuid)
2510                .expect("stored");
2511            assert_eq!(tag, format!("\"{}\"", stored.version), "a strong tag");
2512            assert_eq!(stored.body, body);
2513
2514            let again = post(&s, &writer, Some("application/vcon"), body).await;
2515            assert_eq!(again.status(), 200, "the same bytes are already current");
2516            assert_eq!(again.headers()["etag"], tag.as_str());
2517        }
2518
2519        #[tokio::test]
2520        async fn another_vcon_with_the_uuid_conflicts() {
2521            let s = server().await;
2522            let writer = s.key(&[Scope::Write]);
2523            let (_, first) = vcon(UUID, "first");
2524            let (_, other) = vcon(UUID, "other");
2525            assert_eq!(post(&s, &writer, None, first).await.status(), 201);
2526            let answer = post(&s, &writer, None, other).await;
2527            assert_eq!(answer.status(), 409);
2528            assert_eq!(problem(answer).await, "conflict");
2529            let statuses: Vec<_> = s
2530                .tenant_log("create")
2531                .into_iter()
2532                .map(|r| r["status"].clone())
2533                .collect();
2534            assert_eq!(statuses, [201, 409], "Store records its own, once");
2535        }
2536
2537        #[tokio::test]
2538        async fn a_vcon_needing_an_unsupported_extension_is_unprocessable() {
2539            let s = super::pipeline::server_with(&["known"]).await;
2540            let writer = s.key(&[Scope::Write]);
2541            let needing = |n: u8, extension: &str| {
2542                format!(
2543                    r#"{{"uuid": "{}", "created_at": "2026-10-23T12:00:00Z", "must_support": ["{extension}"], "parties": []}}"#,
2544                    uuid(n)
2545                )
2546                .into_bytes()
2547            };
2548            assert_eq!(
2549                post(&s, &writer, None, needing(1, "known")).await.status(),
2550                201
2551            );
2552            let answer = post(&s, &writer, None, needing(2, "unknown")).await;
2553            assert_eq!(answer.status(), 422);
2554            assert_eq!(problem(answer).await, "unsupported-extension");
2555        }
2556
2557        #[tokio::test]
2558        async fn a_media_type_that_is_not_text_is_unsupported() {
2559            let s = server().await;
2560            let writer = s.key(&[Scope::Write]);
2561            let (_, body) = vcon(UUID, "first");
2562            let answer = s
2563                .client()
2564                .post(s.url("/vcons"))
2565                .bearer_auth(&writer)
2566                .header(
2567                    "content-type",
2568                    reqwest::header::HeaderValue::from_bytes(b"application/vcon\xff")
2569                        .expect("a header value"),
2570                )
2571                .body(body)
2572                .send()
2573                .await
2574                .expect("an answer");
2575            assert_eq!(answer.status(), 415);
2576        }
2577
2578        #[tokio::test]
2579        async fn a_deleted_vcon_is_gone() {
2580            let s = server().await;
2581            let writer = s.key(&[Scope::Write]);
2582            let (found, body) = vcon(UUID, "first");
2583            assert_eq!(post(&s, &writer, None, body.clone()).await.status(), 201);
2584            s.tenants
2585                .store(s.tenant)
2586                .expect("its store")
2587                .delete(
2588                    &store_caller(),
2589                    found.uuid,
2590                    crate::retention::Retention::Years(7),
2591                )
2592                .expect("deleted");
2593            let answer = post(&s, &writer, None, body).await;
2594            assert_eq!(answer.status(), 410);
2595            assert_eq!(problem(answer).await, "gone");
2596        }
2597
2598        #[tokio::test]
2599        async fn the_vcon_media_types_json_and_none_are_taken() {
2600            let s = server().await;
2601            let writer = s.key(&[Scope::Write]);
2602            let cases: [(Option<&str>, bool); 6] = [
2603                (None, false),
2604                (Some("application/vcon"), false),
2605                (Some("application/vcon+gzip"), true),
2606                (Some("application/json"), false),
2607                (Some("Application/VCON; charset=utf-8"), false),
2608                (Some("APPLICATION/VCON+GZIP ; q=1"), true),
2609            ];
2610            for (n, (content_type, gzipped)) in cases.into_iter().enumerate() {
2611                let (_, body) = vcon(&uuid(n as u8), "typed");
2612                let body = if gzipped { gzip(&body) } else { body };
2613                let answer = post(&s, &writer, content_type, body).await;
2614                assert_eq!(answer.status(), 201, "{content_type:?}");
2615            }
2616        }
2617
2618        #[tokio::test]
2619        async fn another_media_type_is_unsupported_and_recorded() {
2620            let s = server().await;
2621            let writer = s.key(&[Scope::Write]);
2622            let (_, body) = vcon(UUID, "first");
2623            for content_type in ["text/plain", "application/vcon-json", "application/xml"] {
2624                let answer = post(&s, &writer, Some(content_type), body.clone()).await;
2625                assert_eq!(answer.status(), 415, "{content_type}");
2626                assert_eq!(problem(answer).await, "unsupported-media-type");
2627            }
2628            let refused: Vec<_> = s
2629                .tenant_log("create")
2630                .iter()
2631                .map(|r| r["status"].clone())
2632                .collect();
2633            assert_eq!(refused, [415, 415, 415], "one record per refusal");
2634        }
2635
2636        #[tokio::test]
2637        async fn a_body_format_refuses_is_unprocessable_and_recorded() {
2638            let s = server().await;
2639            let writer = s.key(&[Scope::Write]);
2640            let answer = post(&s, &writer, None, b"not json".to_vec()).await;
2641            assert_eq!(answer.status(), 422);
2642            assert_eq!(problem(answer).await, "not-json");
2643            let (_, body) = vcon(UUID, "first");
2644            let answer = post(&s, &writer, Some("application/vcon+gzip"), body).await;
2645            assert_eq!(answer.status(), 422);
2646            assert_eq!(problem(answer).await, "bad-gzip");
2647            let refused = s.tenant_log("create");
2648            assert_eq!(refused.len(), 2);
2649            assert_eq!(refused[0]["status"], 422);
2650        }
2651
2652        #[tokio::test]
2653        async fn a_body_that_inflates_past_its_limit_is_too_large() {
2654            let s = server().await;
2655            let writer = s.key(&[Scope::Write]);
2656            let bomb = gzip(&vec![b' '; 2 << 20]);
2657            assert!(bomb.len() < 64 * 1024, "small on the wire");
2658            let answer = post(&s, &writer, Some("application/vcon+gzip"), bomb).await;
2659            assert_eq!(answer.status(), 413);
2660            assert_eq!(problem(answer).await, "too-large");
2661        }
2662
2663        #[tokio::test]
2664        async fn a_body_nested_too_deeply_is_unprocessable_and_recorded() {
2665            use base64::Engine;
2666            use base64::engine::general_purpose::URL_SAFE_NO_PAD;
2667            let s = server().await;
2668            let writer = s.key(&[Scope::Write]);
2669            let (_, mut signed) = vcon(UUID, "first");
2670            for _ in 0..=vcon::read::MAX_SIGNED_LAYERS {
2671                signed = serde_json::json!({
2672                    "payload": URL_SAFE_NO_PAD.encode(gzip(&signed)),
2673                    "signatures": [{}],
2674                })
2675                .to_string()
2676                .into_bytes();
2677            }
2678            let open = "[".repeat(vcon::read::MAX_JSON_DEPTH);
2679            let close = "]".repeat(vcon::read::MAX_JSON_DEPTH);
2680            let json = format!(r#"{{"uuid":"{UUID}","created_at":"x","a":{open}{close}}}"#);
2681            for body in [signed, json.into_bytes()] {
2682                let answer = post(&s, &writer, None, body).await;
2683                assert_eq!(answer.status(), 422);
2684                assert_eq!(problem(answer).await, "too-deep");
2685            }
2686            let refused = s.tenant_log("create");
2687            assert_eq!(refused.len(), 2);
2688            assert!(refused.iter().all(|r| r["status"] == 422));
2689        }
2690
2691        #[tokio::test]
2692        async fn a_create_whose_record_fails_is_unavailable() {
2693            let s = server().await;
2694            let writer = s.key(&[Scope::Write]);
2695            s.tenants.store(s.tenant).expect("its store").break_audit();
2696            let (_, body) = vcon(UUID, "first");
2697            let answer = post(&s, &writer, None, body).await;
2698            assert_eq!(answer.status(), 503);
2699            assert_eq!(problem(answer).await, "audit-failed");
2700        }
2701    }
2702
2703    mod legal {
2704        use reqwest::Method;
2705        use serde_json::Value;
2706
2707        use super::pipeline::{Server, problem, server};
2708        use crate::access::{Scope, Scopes};
2709        use crate::audit::Actor;
2710        use crate::ids::VersionId;
2711        use crate::retention::Retention;
2712
2713        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
2714        const NEVER: &str = "0199e5c6-0d7a-7c11-8000-000000000001";
2715
2716        fn key(s: &Server, scopes: &[Scope]) -> String {
2717            s.tenants
2718                .create_key(Actor::Cli, Some(s.tenant), Scopes::of(scopes), "test")
2719                .expect("a key")
2720                .token
2721        }
2722
2723        fn a4() -> Vec<u8> {
2724            std::fs::read(format!(
2725                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
2726                env!("CARGO_MANIFEST_DIR")
2727            ))
2728            .expect("A.4")
2729        }
2730
2731        async fn call(s: &Server, method: Method, path: &str, token: &str) -> reqwest::Response {
2732            s.client()
2733                .request(method, s.url(path))
2734                .bearer_auth(token)
2735                .send()
2736                .await
2737                .expect("an answer")
2738        }
2739
2740        /// Stores A.4 and returns its entity tag.
2741        async fn stored(s: &Server) -> String {
2742            let writer = key(s, &[Scope::Write]);
2743            let answer = s
2744                .client()
2745                .post(s.url("/vcons"))
2746                .bearer_auth(&writer)
2747                .header("content-type", "application/vcon")
2748                .body(a4())
2749                .send()
2750                .await
2751                .expect("an answer");
2752            assert_eq!(answer.status(), 201);
2753            answer.headers()["etag"].to_str().expect("tag").to_owned()
2754        }
2755
2756        async fn deleted(s: &Server) {
2757            let deleter = key(s, &[Scope::Delete]);
2758            let path = format!("/vcons/{UUID}");
2759            assert_eq!(call(s, Method::DELETE, &path, &deleter).await.status(), 204);
2760        }
2761
2762        /// Every legal route for `uuid`, with `version` for the one that
2763        /// names a version.
2764        fn routes(uuid: &str, version: &str) -> Vec<(Method, String)> {
2765            vec![
2766                (Method::GET, format!("/legal/vcons/{uuid}")),
2767                (Method::GET, format!("/legal/vcons/{uuid}/versions")),
2768                (
2769                    Method::GET,
2770                    format!("/legal/vcons/{uuid}/versions/{version}"),
2771                ),
2772                (Method::POST, format!("/legal/vcons/{uuid}/restore")),
2773                (Method::PUT, format!("/legal/vcons/{uuid}/hold")),
2774                (Method::DELETE, format!("/legal/vcons/{uuid}/hold")),
2775            ]
2776        }
2777
2778        fn bare(tag: &str) -> String {
2779            tag.trim_matches('"').to_owned()
2780        }
2781
2782        #[tokio::test]
2783        async fn every_legal_route_needs_the_legal_scope() {
2784            let s = server().await;
2785            let tag = stored(&s).await;
2786            let others = key(&s, &[Scope::Write, Scope::Read, Scope::Delete]);
2787            for (method, path) in routes(UUID, &bare(&tag)) {
2788                let answer = call(&s, method.clone(), &path, &others).await;
2789                assert_eq!(answer.status(), 403, "{method} {path}");
2790            }
2791        }
2792
2793        #[tokio::test]
2794        async fn a_deleted_vcon_reads_back_byte_for_byte_with_a_legal_key() {
2795            let s = server().await;
2796            let tag = stored(&s).await;
2797            let legal = key(&s, &[Scope::Legal]);
2798            let path = format!("/legal/vcons/{UUID}");
2799
2800            let live = call(&s, Method::GET, &path, &legal).await;
2801            assert_eq!(live.status(), 200);
2802            assert_eq!(live.headers()["vcon-state"], "live");
2803
2804            deleted(&s).await;
2805            let answer = call(&s, Method::GET, &path, &legal).await;
2806            assert_eq!(answer.status(), 200);
2807            assert_eq!(answer.headers()["vcon-state"], "deleted");
2808            assert_eq!(answer.headers()["etag"], tag.as_str());
2809            assert_eq!(answer.headers()["content-type"], "application/vcon");
2810            assert_eq!(
2811                answer.bytes().await.expect("body").as_ref(),
2812                a4().as_slice()
2813            );
2814            assert_eq!(
2815                s.tenant_log("legal_read").last().expect("recorded")["status"],
2816                200
2817            );
2818        }
2819
2820        #[tokio::test]
2821        async fn the_version_list_and_a_named_version() {
2822            let s = server().await;
2823            let tag = stored(&s).await;
2824            let legal = key(&s, &[Scope::Legal]);
2825            let live = call(
2826                &s,
2827                Method::GET,
2828                &format!("/legal/vcons/{UUID}/versions"),
2829                &legal,
2830            )
2831            .await;
2832            let live: Value =
2833                serde_json::from_slice(&live.bytes().await.expect("body")).expect("json");
2834            assert_eq!(live[0]["current"], true, "live, so current");
2835            assert!(live[0]["hidden_at"].is_null(), "not hidden while live");
2836            deleted(&s).await;
2837
2838            let list = call(
2839                &s,
2840                Method::GET,
2841                &format!("/legal/vcons/{UUID}/versions"),
2842                &legal,
2843            )
2844            .await;
2845            assert_eq!(list.status(), 200);
2846            assert_eq!(list.headers()["content-type"], "application/json");
2847            let list: Value =
2848                serde_json::from_slice(&list.bytes().await.expect("body")).expect("json");
2849            let versions = list.as_array().expect("a list");
2850            assert_eq!(versions.len(), 1);
2851            assert_eq!(versions[0]["version"], bare(&tag));
2852            assert_eq!(versions[0]["current"], false);
2853            assert!(
2854                versions[0]["stored_at"]
2855                    .as_str()
2856                    .expect("a time")
2857                    .ends_with('Z')
2858            );
2859            assert!(versions[0]["hidden_at"].is_string(), "hidden by the delete");
2860
2861            let one = format!("/legal/vcons/{UUID}/versions/{}", bare(&tag));
2862            let answer = call(&s, Method::GET, &one, &legal).await;
2863            assert_eq!(answer.status(), 200);
2864            assert_eq!(answer.headers()["etag"], tag.as_str());
2865            assert_eq!(
2866                answer.bytes().await.expect("body").as_ref(),
2867                a4().as_slice()
2868            );
2869
2870            let unknown = format!("/legal/vcons/{UUID}/versions/{}", VersionId::generate());
2871            let answer = call(&s, Method::GET, &unknown, &legal).await;
2872            assert_eq!(answer.status(), 404);
2873            assert_eq!(problem(answer).await, "not-found");
2874
2875            let bad = format!("/legal/vcons/{UUID}/versions/not-a-version");
2876            let answer = call(&s, Method::GET, &bad, &legal).await;
2877            assert_eq!(answer.status(), 400);
2878            assert_eq!(problem(answer).await, "bad-path-version");
2879            assert_eq!(
2880                s.tenant_log("legal_read").last().expect("recorded")["status"],
2881                400
2882            );
2883        }
2884
2885        #[tokio::test]
2886        async fn restore_answers_its_tag_then_409_once_live() {
2887            let s = server().await;
2888            let tag = stored(&s).await;
2889            deleted(&s).await;
2890            let token = key(&s, &[Scope::Legal, Scope::Read]);
2891            let path = format!("/legal/vcons/{UUID}/restore");
2892
2893            let answer = call(&s, Method::POST, &path, &token).await;
2894            assert_eq!(answer.status(), 200);
2895            assert_eq!(answer.headers()["etag"], tag.as_str());
2896            let read = call(&s, Method::GET, &format!("/vcons/{UUID}"), &token).await;
2897            assert_eq!(read.status(), 200, "live again");
2898
2899            let again = call(&s, Method::POST, &path, &token).await;
2900            assert_eq!(again.status(), 409);
2901            assert_eq!(problem(again).await, "not-deleted");
2902        }
2903
2904        #[tokio::test]
2905        async fn a_hold_is_set_and_released_with_204() {
2906            let s = server().await;
2907            stored(&s).await;
2908            let legal = key(&s, &[Scope::Legal]);
2909            let path = format!("/legal/vcons/{UUID}/hold");
2910            for method in [Method::PUT, Method::DELETE] {
2911                let answer = call(&s, method, &path, &legal).await;
2912                assert_eq!(answer.status(), 204);
2913                assert!(answer.bytes().await.expect("body").is_empty());
2914            }
2915            assert_eq!(s.tenant_log("hold").len(), 1, "the hold");
2916            assert_eq!(s.tenant_log("release").len(), 1, "the release, as itself");
2917        }
2918
2919        #[tokio::test]
2920        async fn a_held_vcon_survives_a_zero_period_delete_until_released() {
2921            let s = server().await;
2922            stored(&s).await;
2923            let legal = key(&s, &[Scope::Legal]);
2924            let hold = format!("/legal/vcons/{UUID}/hold");
2925            let read = format!("/legal/vcons/{UUID}");
2926            assert_eq!(call(&s, Method::PUT, &hold, &legal).await.status(), 204);
2927            s.tenants
2928                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
2929                .expect("set");
2930            deleted(&s).await;
2931            assert_eq!(
2932                call(&s, Method::GET, &read, &legal).await.status(),
2933                200,
2934                "held"
2935            );
2936
2937            assert_eq!(call(&s, Method::DELETE, &hold, &legal).await.status(), 204);
2938            s.tenants
2939                .store(s.tenant)
2940                .expect("its store")
2941                .purge_due(Retention::Days(0))
2942                .expect("swept");
2943            assert_eq!(
2944                call(&s, Method::GET, &read, &legal).await.status(),
2945                410,
2946                "released"
2947            );
2948        }
2949
2950        #[tokio::test]
2951        async fn a_gzipped_vcon_reads_back_gzipped() {
2952            use std::io::Write;
2953            let s = server().await;
2954            let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2955            gz.write_all(&a4()).expect("gzip");
2956            let gzipped = gz.finish().expect("gzip");
2957            let writer = key(&s, &[Scope::Write]);
2958            let answer = s
2959                .client()
2960                .post(s.url("/vcons"))
2961                .bearer_auth(&writer)
2962                .header("content-type", "application/vcon+gzip")
2963                .body(gzipped.clone())
2964                .send()
2965                .await
2966                .expect("an answer");
2967            assert_eq!(answer.status(), 201);
2968            deleted(&s).await;
2969            let legal = key(&s, &[Scope::Legal]);
2970            let answer = call(&s, Method::GET, &format!("/legal/vcons/{UUID}"), &legal).await;
2971            assert_eq!(answer.status(), 200);
2972            assert_eq!(answer.headers()["content-type"], "application/vcon+gzip");
2973            assert_eq!(
2974                answer.bytes().await.expect("body").as_ref(),
2975                gzipped.as_slice()
2976            );
2977        }
2978
2979        #[tokio::test]
2980        async fn a_purged_uuid_is_410_on_every_legal_route() {
2981            let s = server().await;
2982            let tag = stored(&s).await;
2983            s.tenants
2984                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
2985                .expect("set");
2986            deleted(&s).await;
2987            let legal = key(&s, &[Scope::Legal]);
2988            for (method, path) in routes(UUID, &bare(&tag)) {
2989                let answer = call(&s, method.clone(), &path, &legal).await;
2990                assert_eq!(answer.status(), 410, "{method} {path}");
2991                assert_eq!(problem(answer).await, "gone");
2992            }
2993        }
2994
2995        #[tokio::test]
2996        async fn a_uuid_never_stored_is_404_and_a_bad_one_400_on_every_legal_route() {
2997            let s = server().await;
2998            let legal = key(&s, &[Scope::Legal]);
2999            let version = VersionId::generate().to_string();
3000            for (method, path) in routes(NEVER, &version) {
3001                let answer = call(&s, method.clone(), &path, &legal).await;
3002                assert_eq!(answer.status(), 404, "{method} {path}");
3003                assert_eq!(problem(answer).await, "not-found");
3004            }
3005            for (method, path) in routes("not-a-uuid", &version) {
3006                let answer = call(&s, method.clone(), &path, &legal).await;
3007                assert_eq!(answer.status(), 400, "{method} {path}");
3008                assert_eq!(problem(answer).await, "bad-path-uuid");
3009            }
3010            for action in ["legal_read", "legal_versions", "restore", "hold", "release"] {
3011                let last = s.tenant_log(action).last().expect("recorded").clone();
3012                assert_eq!(last["status"], 400, "{action}'s refusal is recorded");
3013            }
3014        }
3015
3016        #[tokio::test]
3017        async fn damage_is_500_on_every_legal_route() {
3018            let s = server().await;
3019            let tag = stored(&s).await;
3020            deleted(&s).await;
3021            let legal = key(&s, &[Scope::Legal]);
3022            let store = s.tenants.store(s.tenant).expect("its store");
3023            store
3024                .conn_for_test()
3025                .execute_batch(
3026                    "UPDATE version SET wrapped_key = x'00', stored_at = 'x';
3027                     CREATE TEMP TRIGGER broken BEFORE UPDATE ON vcon
3028                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
3029                )
3030                .expect("damaged");
3031            for (method, path) in routes(UUID, &bare(&tag)) {
3032                let answer = call(&s, method.clone(), &path, &legal).await;
3033                assert_eq!(answer.status(), 500, "{method} {path}");
3034            }
3035        }
3036
3037        #[tokio::test]
3038        async fn an_answer_that_cannot_be_recorded_is_503_on_every_legal_route() {
3039            let s = server().await;
3040            let tag = stored(&s).await;
3041            let legal = key(&s, &[Scope::Legal]);
3042            s.tenants.store(s.tenant).expect("its store").break_audit();
3043            for (method, path) in routes(UUID, &bare(&tag)) {
3044                let answer = call(&s, method.clone(), &path, &legal).await;
3045                assert_eq!(answer.status(), 503, "{method} {path}");
3046                assert_eq!(problem(answer).await, "audit-failed");
3047            }
3048        }
3049    }
3050
3051    mod admin {
3052        use reqwest::Method;
3053        use serde_json::{Value, json};
3054
3055        use super::pipeline::{Server, problem, server};
3056        use crate::access::{Scope, Scopes};
3057        use crate::audit::Actor;
3058        use time::format_description::well_known::Rfc3339;
3059
3060        use crate::access;
3061        use crate::export::Metadata;
3062        use crate::ids::{KeyId, TenantId};
3063        use crate::retention::Retention;
3064
3065        fn operator(s: &Server) -> String {
3066            s.tenants
3067                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
3068                .expect("an operator key")
3069                .token
3070        }
3071
3072        async fn call(
3073            s: &Server,
3074            method: Method,
3075            path: &str,
3076            token: Option<&str>,
3077            body: Option<&str>,
3078        ) -> reqwest::Response {
3079            let mut request = s.client().request(method, s.url(path));
3080            if let Some(token) = token {
3081                request = request.bearer_auth(token);
3082            }
3083            if let Some(body) = body {
3084                request = request
3085                    .header("content-type", "application/json")
3086                    .body(body.to_owned());
3087            }
3088            request.send().await.expect("an answer")
3089        }
3090
3091        async fn json(answer: reqwest::Response) -> Value {
3092            assert_eq!(answer.headers()["content-type"], "application/json");
3093            serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON")
3094        }
3095
3096        /// The admin log's records of `action` written for requests, not
3097        /// for the tests' own setup from the command line.
3098        fn admin_log(s: &Server, action: &str) -> Vec<Value> {
3099            s.tenants
3100                .admin_records()
3101                .into_iter()
3102                .filter(|r| r["action"] == action && r["actor"] != "cli")
3103                .collect()
3104        }
3105
3106        fn key_id(token: &str) -> KeyId {
3107            access::parse(token).expect("a token")
3108        }
3109
3110        /// Each admin route, with a body it takes, and its audit action.
3111        fn routes(
3112            id: TenantId,
3113            key: KeyId,
3114        ) -> Vec<(Method, String, Option<&'static str>, &'static str)> {
3115            vec![
3116                (
3117                    Method::POST,
3118                    "/admin/tenants".to_owned(),
3119                    Some(r#"{"name":"beta"}"#),
3120                    "tenant_create",
3121                ),
3122                (
3123                    Method::GET,
3124                    "/admin/tenants".to_owned(),
3125                    None,
3126                    "tenant_list",
3127                ),
3128                (
3129                    Method::PATCH,
3130                    format!("/admin/tenants/{id}"),
3131                    Some(r#"{"retention":"5y"}"#),
3132                    "tenant_retention",
3133                ),
3134                (
3135                    Method::PUT,
3136                    format!("/admin/tenants/{id}/metadata"),
3137                    Some(r#"{"metadata":"counts"}"#),
3138                    "tenant_metadata",
3139                ),
3140                (
3141                    Method::DELETE,
3142                    format!("/admin/tenants/{id}"),
3143                    None,
3144                    "tenant_remove",
3145                ),
3146                (
3147                    Method::POST,
3148                    format!("/admin/tenants/{id}/keys"),
3149                    Some(r#"{"scopes":["read"],"label":"ingest"}"#),
3150                    "key_create",
3151                ),
3152                (
3153                    Method::GET,
3154                    format!("/admin/tenants/{id}/keys"),
3155                    None,
3156                    "key_list",
3157                ),
3158                (
3159                    Method::DELETE,
3160                    format!("/admin/keys/{key}"),
3161                    None,
3162                    "key_revoke",
3163                ),
3164            ]
3165        }
3166
3167        #[tokio::test]
3168        async fn a_tenant_key_is_forbidden_and_no_key_unauthorized_on_every_admin_route() {
3169            let s = server().await;
3170            let every = [Scope::Write, Scope::Read, Scope::Delete, Scope::Legal];
3171            let tenant_key = s.key(&every);
3172            for (method, path, body, action) in routes(s.tenant, key_id(&tenant_key)) {
3173                let answer = call(&s, method.clone(), &path, Some(&tenant_key), body).await;
3174                assert_eq!(answer.status(), 403, "{method} {path}");
3175                assert_eq!(problem(answer).await, "forbidden");
3176                let refused: Vec<Value> = s
3177                    .tenant_log(action)
3178                    .into_iter()
3179                    .filter(|r| r["actor"] != "cli")
3180                    .collect();
3181                assert_eq!(refused.len(), 1, "{action} refusal in the tenant's log");
3182                assert_eq!(refused[0]["status"], 403);
3183
3184                let answer = call(&s, method.clone(), &path, None, body).await;
3185                assert_eq!(answer.status(), 401, "{method} {path}");
3186            }
3187            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3188            assert_eq!(s.tenants.retention(s.tenant), Ok(None), "nothing changed");
3189            let keys = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3190            let keys = keys.expect("listed");
3191            assert_eq!(keys.len(), 1, "no key made");
3192            assert_eq!(keys[0].revoked_at, None, "nor revoked");
3193        }
3194
3195        #[tokio::test]
3196        async fn a_tenant_is_created_with_201_and_its_id_and_listed() {
3197            let s = server().await;
3198            let op = operator(&s);
3199            let body = r#"{"name":"beta","retention":"5y"}"#;
3200            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3201            assert_eq!(answer.status(), 201);
3202            let made = json(answer).await;
3203            let id = TenantId::parse(made["id"].as_str().expect("an id")).expect("a tenant id");
3204            assert_eq!(made, json!({ "id": id.to_string() }));
3205            assert_eq!(s.tenants.retention(id), Ok(Some(Retention::Years(5))));
3206            let created = admin_log(&s, "tenant_create");
3207            assert_eq!(created.last().expect("recorded")["status"], 201);
3208
3209            let body = r#"{"name":"gamma"}"#;
3210            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3211            assert_eq!(answer.status(), 201);
3212
3213            let answer = call(&s, Method::GET, "/admin/tenants", Some(&op), None).await;
3214            assert_eq!(answer.status(), 200);
3215            let listed = json(answer).await;
3216            let gamma = s
3217                .tenants
3218                .list(Actor::Cli)
3219                .expect("listed")
3220                .into_iter()
3221                .find(|t| t.name == "gamma")
3222                .expect("gamma")
3223                .id;
3224            assert_eq!(
3225                listed,
3226                json!([
3227                    { "id": s.tenant.to_string(), "name": "acme", "retention": null, "metadata": "none" },
3228                    { "id": id.to_string(), "name": "beta", "retention": "5y", "metadata": "none" },
3229                    { "id": gamma.to_string(), "name": "gamma", "retention": null, "metadata": "none" },
3230                ])
3231            );
3232            assert_eq!(admin_log(&s, "tenant_list")[0]["status"], 200);
3233        }
3234
3235        #[tokio::test]
3236        async fn a_taken_name_is_409() {
3237            let s = server().await;
3238            let op = operator(&s);
3239            let body = r#"{"name":"acme"}"#;
3240            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3241            assert_eq!(answer.status(), 409);
3242            assert_eq!(problem(answer).await, "name-taken");
3243            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3244        }
3245
3246        #[tokio::test]
3247        async fn a_create_body_it_does_not_take_is_422_and_recorded_once() {
3248            let s = server().await;
3249            let op = operator(&s);
3250            let bodies = [
3251                "",
3252                "not json",
3253                "[]",
3254                "{}",
3255                r#"{"name":7}"#,
3256                r#"{"name":null}"#,
3257                r#"{"name":"beta","colour":"red"}"#,
3258                r#"{"name":"beta","name":"gamma"}"#,
3259                r#"{"name":"beta","retention":"7x"}"#,
3260                r#"{"name":"beta","retention":7}"#,
3261                r#"{"name":" beta"}"#,
3262                r#"{"name":""}"#,
3263            ];
3264            for body in bodies {
3265                let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3266                assert_eq!(answer.status(), 422, "{body}");
3267                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3268            }
3269            let refused = admin_log(&s, "tenant_create");
3270            assert_eq!(refused.len(), bodies.len(), "one per refusal");
3271            assert!(refused.iter().all(|r| r["status"] == 422));
3272            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3273        }
3274
3275        #[tokio::test]
3276        async fn a_create_past_the_master_keys_wrap_limit_is_503() {
3277            let s = server().await;
3278            let op = operator(&s);
3279            s.tenants
3280                .conn_for_test()
3281                .execute("UPDATE master_key_use SET wraps = ?1", [1_i64 << 32])
3282                .expect("at the limit");
3283            let body = r#"{"name":"beta"}"#;
3284            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3285            assert_eq!(answer.status(), 503);
3286            assert_eq!(problem(answer).await, "master-key-limit");
3287        }
3288
3289        #[tokio::test]
3290        async fn a_retention_change_answers_200_with_the_period() {
3291            let s = server().await;
3292            let op = operator(&s);
3293            let path = format!("/admin/tenants/{}", s.tenant);
3294            let id = s.tenant.to_string();
3295            for (body, period, kept) in [
3296                (
3297                    r#"{"retention":"30d"}"#,
3298                    json!("30d"),
3299                    Some(Retention::Days(30)),
3300                ),
3301                (r#"{"retention":null}"#, Value::Null, None),
3302            ] {
3303                let answer = call(&s, Method::PATCH, &path, Some(&op), Some(body)).await;
3304                assert_eq!(answer.status(), 200, "{body}");
3305                assert_eq!(json(answer).await, json!({ "id": id, "retention": period }));
3306                assert_eq!(s.tenants.retention(s.tenant), Ok(kept), "{body}");
3307            }
3308            let changed = admin_log(&s, "tenant_retention");
3309            assert_eq!(changed.len(), 2);
3310            assert!(changed.iter().all(|r| r["status"] == 200));
3311            assert_eq!(s.tenant_log("retention").len(), 2, "the tenant's log too");
3312        }
3313
3314        #[tokio::test]
3315        async fn a_retention_change_for_no_tenant_is_404_and_recorded() {
3316            let s = server().await;
3317            let op = operator(&s);
3318            let body = Some(r#"{"retention":"5y"}"#);
3319            let unknown = TenantId([7; 16]).to_string();
3320            for id in [
3321                unknown.as_str(),
3322                "acme",
3323                "0123",
3324                &s.tenant.to_string().to_uppercase(),
3325            ] {
3326                let path = format!("/admin/tenants/{id}");
3327                let answer = call(&s, Method::PATCH, &path, Some(&op), body).await;
3328                assert_eq!(answer.status(), 404, "{id}");
3329                assert_eq!(problem(answer).await, "unknown-tenant", "{id}");
3330            }
3331            let refused = admin_log(&s, "tenant_retention");
3332            assert_eq!(refused.len(), 4);
3333            assert!(refused.iter().all(|r| r["status"] == 404));
3334            assert_eq!(s.tenants.retention(s.tenant), Ok(None));
3335        }
3336
3337        #[tokio::test]
3338        async fn a_retention_body_it_does_not_take_is_422_and_recorded() {
3339            let s = server().await;
3340            let op = operator(&s);
3341            let path = format!("/admin/tenants/{}", s.tenant);
3342            let bodies = [
3343                "",
3344                "{}",
3345                r#"{"retention":"7"}"#,
3346                r#"{"retention":"07y"}"#,
3347                r#"{"retention":5}"#,
3348                r#"{"retention":"5y","name":"beta"}"#,
3349            ];
3350            for body in bodies {
3351                let answer = call(&s, Method::PATCH, &path, Some(&op), Some(body)).await;
3352                assert_eq!(answer.status(), 422, "{body}");
3353                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3354            }
3355            let refused = admin_log(&s, "tenant_retention");
3356            assert_eq!(refused.len(), bodies.len());
3357            assert!(refused.iter().all(|r| r["status"] == 422));
3358            assert_eq!(s.tenants.retention(s.tenant), Ok(None));
3359        }
3360
3361        #[tokio::test]
3362        async fn a_metadata_change_answers_200_with_the_level() {
3363            let s = server().await;
3364            let op = operator(&s);
3365            let path = format!("/admin/tenants/{}/metadata", s.tenant);
3366            let id = s.tenant.to_string();
3367            for (level, kept) in [
3368                ("full", Metadata::Full),
3369                ("counts", Metadata::Counts),
3370                ("none", Metadata::None),
3371            ] {
3372                let body = format!(r#"{{"metadata":"{level}"}}"#);
3373                let answer = call(&s, Method::PUT, &path, Some(&op), Some(&body)).await;
3374                assert_eq!(answer.status(), 200, "{body}");
3375                assert_eq!(
3376                    json(answer).await,
3377                    json!({ "id": id, "metadata": level }),
3378                    "the answer names the tenant and its new level"
3379                );
3380                assert_eq!(s.tenants.metadata(s.tenant), Ok(kept), "{body}");
3381            }
3382            let changed = admin_log(&s, "tenant_metadata");
3383            assert_eq!(changed.len(), 3, "one admin record per change");
3384            assert!(
3385                changed.iter().all(|r| r["status"] == 200),
3386                "each change succeeded"
3387            );
3388            assert_eq!(s.tenant_log("metadata").len(), 3, "the tenant's log too");
3389        }
3390
3391        #[tokio::test]
3392        async fn a_metadata_change_it_cannot_take_is_refused_and_recorded() {
3393            let s = server().await;
3394            let op = operator(&s);
3395            let path = format!("/admin/tenants/{}/metadata", s.tenant);
3396            let bodies = [
3397                "",
3398                "{}",
3399                r#"{"metadata":null}"#,
3400                r#"{"metadata":"most"}"#,
3401                r#"{"metadata":"Full"}"#,
3402                r#"{"metadata":"full","retention":"5y"}"#,
3403            ];
3404            for body in bodies {
3405                let answer = call(&s, Method::PUT, &path, Some(&op), Some(body)).await;
3406                assert_eq!(answer.status(), 422, "{body}");
3407                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3408            }
3409            let unknown = format!("/admin/tenants/{}/metadata", TenantId([7; 16]));
3410            let body = Some(r#"{"metadata":"full"}"#);
3411            let answer = call(&s, Method::PUT, &unknown, Some(&op), body).await;
3412            assert_eq!(
3413                answer.status(),
3414                404,
3415                "a tenant id no tenant has is not found"
3416            );
3417            assert_eq!(problem(answer).await, "unknown-tenant", "its problem type");
3418            let refused = admin_log(&s, "tenant_metadata");
3419            assert_eq!(refused.len(), bodies.len() + 1, "every refusal is recorded");
3420            assert_eq!(
3421                s.tenants.metadata(s.tenant),
3422                Ok(Metadata::None),
3423                "unchanged"
3424            );
3425            s.tenants.close(s.tenant);
3426            let answer = call(&s, Method::PUT, &path, Some(&op), body).await;
3427            assert_eq!(
3428                answer.status(),
3429                503,
3430                "a closing tenant cannot change its level"
3431            );
3432            assert_eq!(problem(answer).await, "unavailable", "its problem type");
3433        }
3434
3435        #[tokio::test]
3436        async fn a_retention_change_for_a_closing_tenant_is_503() {
3437            let s = server().await;
3438            let op = operator(&s);
3439            s.tenants.close(s.tenant);
3440            let path = format!("/admin/tenants/{}", s.tenant);
3441            let body = Some(r#"{"retention":"5y"}"#);
3442            let answer = call(&s, Method::PATCH, &path, Some(&op), body).await;
3443            assert_eq!(answer.status(), 503);
3444            assert_eq!(problem(answer).await, "unavailable");
3445        }
3446
3447        #[tokio::test]
3448        async fn damage_is_500_on_every_admin_route() {
3449            let s = server().await;
3450            let op = operator(&s);
3451            let kept = key_id(&s.key(&[Scope::Read]));
3452            s.tenants
3453                .conn_for_test()
3454                .execute_batch(
3455                    "UPDATE tenant SET retention = 'x';
3456                     UPDATE api_key SET created_at = 'x' WHERE tenant IS NOT NULL;
3457                     CREATE TEMP TRIGGER no_key BEFORE INSERT ON api_key
3458                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3459                     CREATE TEMP TRIGGER no_revoke BEFORE UPDATE ON api_key
3460                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3461                     CREATE TEMP TRIGGER broken BEFORE INSERT ON tenant
3462                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3463                     CREATE TEMP TRIGGER broken_too BEFORE UPDATE ON tenant
3464                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3465                     CREATE TEMP TRIGGER broken_three BEFORE DELETE ON tenant
3466                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
3467                )
3468                .expect("damaged");
3469            for (method, path, body, _) in routes(s.tenant, kept) {
3470                let answer = call(&s, method.clone(), &path, Some(&op), body).await;
3471                assert_eq!(answer.status(), 500, "{method} {path}");
3472                assert_eq!(problem(answer).await, "internal");
3473            }
3474        }
3475
3476        #[tokio::test]
3477        async fn an_answer_that_cannot_be_recorded_is_503_on_every_admin_route() {
3478            let s = server().await;
3479            let op = operator(&s);
3480            let kept = key_id(&s.key(&[Scope::Read]));
3481            s.tenants.break_audit();
3482            for (method, path, body, _) in routes(s.tenant, kept) {
3483                let answer = call(&s, method.clone(), &path, Some(&op), body).await;
3484                assert_eq!(answer.status(), 503, "{method} {path}");
3485                assert_eq!(problem(answer).await, "audit-failed");
3486            }
3487            for body in ["{}", r#"{"retention":"5y"}"#] {
3488                let path = if body == "{}" {
3489                    "/admin/tenants".to_owned()
3490                } else {
3491                    format!("/admin/tenants/{}", TenantId([7; 16]))
3492                };
3493                let method = if body == "{}" {
3494                    Method::POST
3495                } else {
3496                    Method::PATCH
3497                };
3498                let answer = call(&s, method, &path, Some(&op), Some(body)).await;
3499                assert_eq!(problem(answer).await, "audit-failed", "a refusal too");
3500            }
3501            assert_eq!(
3502                s.tenants.list(Actor::Cli).err(),
3503                Some(crate::tenants::TenantError::AuditFailed)
3504            );
3505        }
3506
3507        /// Stores A.4 in the server's tenant with a key of its own.
3508        async fn stored(s: &Server) {
3509            let body = std::fs::read(format!(
3510                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
3511                env!("CARGO_MANIFEST_DIR")
3512            ))
3513            .expect("A.4");
3514            let answer = s
3515                .client()
3516                .post(s.url("/vcons"))
3517                .bearer_auth(s.key(&[Scope::Write]))
3518                .header("content-type", "application/vcon")
3519                .body(body)
3520                .send()
3521                .await
3522                .expect("an answer");
3523            assert_eq!(answer.status(), 201);
3524        }
3525
3526        fn listed(s: &Server) -> Vec<TenantId> {
3527            let tenants = s.tenants.list(Actor::Cli).expect("listed");
3528            tenants.into_iter().map(|t| t.id).collect()
3529        }
3530
3531        #[tokio::test]
3532        async fn an_empty_tenant_is_removed_with_204_then_unknown() {
3533            let s = server().await;
3534            let op = operator(&s);
3535            let beta = s.tenants.create(Actor::Cli, "beta", None).expect("made");
3536            let path = format!("/admin/tenants/{beta}");
3537            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3538            assert_eq!(answer.status(), 204);
3539            assert_eq!(listed(&s), vec![s.tenant]);
3540            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3541            assert_eq!(answer.status(), 404);
3542            assert_eq!(problem(answer).await, "unknown-tenant");
3543            let removed = admin_log(&s, "tenant_remove");
3544            let statuses: Vec<&Value> = removed.iter().map(|r| &r["status"]).collect();
3545            assert_eq!(statuses, [204, 404]);
3546        }
3547
3548        #[tokio::test]
3549        async fn a_tenant_holding_vcons_is_409_without_force_and_removed_with_it() {
3550            let s = server().await;
3551            let op = operator(&s);
3552            stored(&s).await;
3553            let reader = s.key(&[Scope::Read]);
3554            let path = format!("/admin/tenants/{}", s.tenant);
3555            for query in ["", "?force=false"] {
3556                let path = format!("{path}{query}");
3557                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3558                assert_eq!(answer.status(), 409, "{query}");
3559                assert_eq!(problem(answer).await, "holds-vcons", "{query}");
3560            }
3561            assert_eq!(listed(&s), vec![s.tenant], "still there");
3562
3563            let forced = format!("{path}?force=true");
3564            let answer = call(&s, Method::DELETE, &forced, Some(&op), None).await;
3565            assert_eq!(answer.status(), 204);
3566            assert_eq!(listed(&s), Vec::<TenantId>::new());
3567            let health = s
3568                .client()
3569                .get(s.url("/health"))
3570                .bearer_auth(&reader)
3571                .send()
3572                .await
3573                .expect("an answer");
3574            assert_eq!(health.status(), 401, "its keys went with it");
3575        }
3576
3577        #[tokio::test]
3578        async fn a_legal_hold_is_409_even_with_force() {
3579            let s = server().await;
3580            let op = operator(&s);
3581            stored(&s).await;
3582            let legal = s.key(&[Scope::Legal]);
3583            let hold = s
3584                .client()
3585                .put(s.url("/legal/vcons/01a07da8-c2bb-83e5-b9a2-279e0d16bc46/hold"))
3586                .bearer_auth(&legal)
3587                .send()
3588                .await
3589                .expect("an answer");
3590            assert_eq!(hold.status(), 204);
3591            let path = format!("/admin/tenants/{}?force=true", s.tenant);
3592            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3593            assert_eq!(answer.status(), 409);
3594            assert_eq!(problem(answer).await, "under-hold");
3595            assert_eq!(listed(&s), vec![s.tenant], "still there");
3596            let removed = admin_log(&s, "tenant_remove");
3597            assert_eq!(removed.len(), 1);
3598            assert_eq!(removed[0]["status"], 409);
3599            let read = s
3600                .client()
3601                .get(s.url("/legal/vcons/01a07da8-c2bb-83e5-b9a2-279e0d16bc46"))
3602                .bearer_auth(&legal)
3603                .send()
3604                .await
3605                .expect("an answer");
3606            assert_eq!(read.status(), 200, "the tenant is served again");
3607        }
3608
3609        #[tokio::test]
3610        async fn a_query_it_does_not_take_is_400_and_recorded() {
3611            let s = server().await;
3612            let op = operator(&s);
3613            let queries = [
3614                "force=yes",
3615                "force=TRUE",
3616                "force",
3617                "force=",
3618                "force=true&force=true",
3619                "force=true&other=1",
3620                "other=1",
3621            ];
3622            for query in queries {
3623                let path = format!("/admin/tenants/{}?{query}", s.tenant);
3624                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3625                assert_eq!(answer.status(), 400, "{query}");
3626                assert_eq!(problem(answer).await, "bad-query", "{query}");
3627            }
3628            let refused = admin_log(&s, "tenant_remove");
3629            assert_eq!(refused.len(), queries.len());
3630            assert!(refused.iter().all(|r| r["status"] == 400));
3631            assert_eq!(listed(&s), vec![s.tenant]);
3632        }
3633
3634        #[tokio::test]
3635        async fn a_removal_of_no_tenant_is_404_and_recorded() {
3636            let s = server().await;
3637            let op = operator(&s);
3638            let unknown = TenantId([7; 16]).to_string();
3639            for id in [unknown.as_str(), "acme"] {
3640                let path = format!("/admin/tenants/{id}?force=true");
3641                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3642                assert_eq!(answer.status(), 404, "{id}");
3643                assert_eq!(problem(answer).await, "unknown-tenant", "{id}");
3644            }
3645            let refused = admin_log(&s, "tenant_remove");
3646            assert_eq!(refused.len(), 2);
3647            assert!(refused.iter().all(|r| r["status"] == 404));
3648        }
3649
3650        #[tokio::test]
3651        async fn a_removal_of_a_closing_tenant_is_503() {
3652            let s = server().await;
3653            let op = operator(&s);
3654            s.tenants.close(s.tenant);
3655            let path = format!("/admin/tenants/{}", s.tenant);
3656            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3657            assert_eq!(answer.status(), 503);
3658            assert_eq!(problem(answer).await, "unavailable");
3659        }
3660
3661        async fn health(s: &Server, token: &str) -> u16 {
3662            let answer = s.client().get(s.url("/health")).bearer_auth(token).send();
3663            answer.await.expect("an answer").status().as_u16()
3664        }
3665
3666        /// Issues a key over HTTP and returns its id and token.
3667        async fn issued(s: &Server, op: &str, body: &str) -> (String, String) {
3668            let path = format!("/admin/tenants/{}/keys", s.tenant);
3669            let answer = call(s, Method::POST, &path, Some(op), Some(body)).await;
3670            assert_eq!(answer.status(), 201, "{body}");
3671            assert_eq!(answer.headers()["cache-control"], "no-store");
3672            let made = json(answer).await;
3673            let id = made["id"].as_str().expect("an id").to_owned();
3674            let token = made["token"].as_str().expect("a token").to_owned();
3675            assert!(made["expires_at"].is_string(), "the expiry of the new key");
3676            assert_eq!(
3677                made.as_object().expect("an object").len(),
3678                3,
3679                "id, token and expires_at, nothing else"
3680            );
3681            assert_eq!(key_id(&token).to_string(), id, "the token names its key");
3682            (id, token)
3683        }
3684
3685        async fn key_list(s: &Server, op: &str) -> (String, Value) {
3686            let path = format!("/admin/tenants/{}/keys", s.tenant);
3687            let answer = call(s, Method::GET, &path, Some(op), None).await;
3688            assert_eq!(answer.status(), 200);
3689            assert_eq!(answer.headers()["content-type"], "application/json");
3690            let text = answer.text().await.expect("text");
3691            let listed = serde_json::from_str(&text).expect("JSON");
3692            (text, listed)
3693        }
3694
3695        #[tokio::test]
3696        async fn a_key_is_issued_with_201_and_its_token_shown_once() {
3697            let s = server().await;
3698            let op = operator(&s);
3699            let body = r#"{"scopes":["read","write"],"label":"ingest"}"#;
3700            let (id, token) = issued(&s, &op, body).await;
3701            assert_eq!(health(&s, &token).await, 200, "the token works");
3702            let (again, other) = issued(&s, &op, body).await;
3703            assert_ne!((&again, &other), (&id, &token), "each key is new");
3704
3705            let (text, listed) = key_list(&s, &op).await;
3706            for token in [&token, &other] {
3707                // vcs_<key id>_<secret>: the secret is base64url, whose
3708                // alphabet includes `_`, so it is all after the second `_`.
3709                let secret = token.splitn(3, '_').nth(2).expect("a secret");
3710                assert_eq!(secret.len(), 43, "the whole 32-byte secret");
3711                assert!(!text.contains(secret), "no token is listed");
3712            }
3713            let first = &listed[0];
3714            assert_eq!(first["id"], id.as_str());
3715            assert_eq!(
3716                first["scopes"],
3717                json!(["write", "read"]),
3718                "in the fixed order"
3719            );
3720            assert_eq!(first["label"], "ingest");
3721            assert_eq!(first["revoked_at"], Value::Null);
3722            let stored = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3723            let stored = stored.expect("listed")[0].created_at;
3724            let stored = stored.format(&Rfc3339).expect("RFC 3339");
3725            assert_eq!(first["created_at"], stored.as_str());
3726            let fields: Vec<&String> = first.as_object().expect("an object").keys().collect();
3727            assert_eq!(
3728                fields,
3729                [
3730                    "created_at",
3731                    "expires_at",
3732                    "id",
3733                    "label",
3734                    "last_used_at",
3735                    "revoked_at",
3736                    "scopes",
3737                    "tenant"
3738                ]
3739            );
3740            assert_eq!(first["tenant"], s.tenant.to_string().as_str());
3741
3742            let made = admin_log(&s, "key_create");
3743            assert_eq!(made.len(), 2);
3744            assert_eq!(made[0]["status"], 201);
3745            assert_eq!(made[0]["target"], id.as_str());
3746            let copied = s.tenant_log("key_create");
3747            assert_eq!(copied.len(), 2, "the tenant's log shows it");
3748            assert_eq!(copied[0]["target"], id.as_str());
3749            assert_eq!(admin_log(&s, "key_list")[0]["status"], 200);
3750        }
3751
3752        #[tokio::test]
3753        async fn a_revoked_key_answers_401_and_the_tenants_log_shows_it() {
3754            let s = server().await;
3755            let op = operator(&s);
3756            let (id, token) = issued(&s, &op, r#"{"scopes":["read"],"label":"a"}"#).await;
3757            let (_, kept) = issued(&s, &op, r#"{"scopes":["read"],"label":"b"}"#).await;
3758            let path = format!("/admin/keys/{id}");
3759            for _ in 0..2 {
3760                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3761                assert_eq!(answer.status(), 204, "again too");
3762            }
3763            assert_eq!(health(&s, &token).await, 401);
3764            assert_eq!(health(&s, &kept).await, 200, "only that key");
3765            let (_, listed) = key_list(&s, &op).await;
3766            assert!(listed[0]["revoked_at"].is_string(), "{listed}");
3767            assert_eq!(listed[1]["revoked_at"], Value::Null);
3768            let revoked = s.tenant_log("key_revoke");
3769            assert_eq!(revoked.len(), 2);
3770            assert!(
3771                revoked
3772                    .iter()
3773                    .all(|r| r["status"] == 204 && r["target"] == id.as_str())
3774            );
3775            assert_eq!(admin_log(&s, "key_revoke").len(), 2);
3776        }
3777
3778        #[tokio::test]
3779        async fn scopes_a_tenant_key_cannot_hold_are_422_and_recorded() {
3780            let s = server().await;
3781            let op = operator(&s);
3782            let path = format!("/admin/tenants/{}/keys", s.tenant);
3783            let scopes = [
3784                "[]",
3785                r#"["admin"]"#,
3786                r#"["read","admin"]"#,
3787                r#"["superuser"]"#,
3788                r#"["read","superuser"]"#,
3789                r#"["Read"]"#,
3790                r#"["read","read"]"#,
3791            ];
3792            for scopes in scopes {
3793                let body = format!(r#"{{"scopes":{scopes},"label":"x"}}"#);
3794                let answer = call(&s, Method::POST, &path, Some(&op), Some(&body)).await;
3795                assert_eq!(answer.status(), 422, "{scopes}");
3796                assert_eq!(problem(answer).await, "bad-scopes", "{scopes}");
3797            }
3798            let refused = admin_log(&s, "key_create");
3799            assert_eq!(refused.len(), scopes.len(), "each recorded once");
3800            assert!(refused.iter().all(|r| r["status"] == 422));
3801            let keys = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3802            assert_eq!(keys.expect("listed").len(), 0, "no key made");
3803        }
3804
3805        #[tokio::test]
3806        async fn a_key_body_it_does_not_take_is_422_and_recorded() {
3807            let s = server().await;
3808            let op = operator(&s);
3809            let path = format!("/admin/tenants/{}/keys", s.tenant);
3810            let bodies = [
3811                "",
3812                "{}",
3813                r#"{"scopes":["read"]}"#,
3814                r#"{"label":"x"}"#,
3815                r#"{"scopes":"read","label":"x"}"#,
3816                r#"{"scopes":["read"],"label":7}"#,
3817                r#"{"scopes":["read"],"label":"x","tenant":"y"}"#,
3818            ];
3819            for body in bodies {
3820                let answer = call(&s, Method::POST, &path, Some(&op), Some(body)).await;
3821                assert_eq!(answer.status(), 422, "{body}");
3822                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3823            }
3824            let refused = admin_log(&s, "key_create");
3825            assert_eq!(refused.len(), bodies.len());
3826            assert!(refused.iter().all(|r| r["status"] == 422));
3827        }
3828
3829        #[tokio::test]
3830        async fn key_routes_for_no_tenant_or_no_key_are_404_and_recorded() {
3831            let s = server().await;
3832            let op = operator(&s);
3833            let body = Some(r#"{"scopes":["read"],"label":"x"}"#);
3834            let unknown = TenantId([7; 16]).to_string();
3835            for id in [unknown.as_str(), "acme"] {
3836                let path = format!("/admin/tenants/{id}/keys");
3837                let answer = call(&s, Method::POST, &path, Some(&op), body).await;
3838                assert_eq!(answer.status(), 404, "POST {id}");
3839                assert_eq!(problem(answer).await, "unknown-tenant");
3840                let answer = call(&s, Method::GET, &path, Some(&op), None).await;
3841                assert_eq!(answer.status(), 404, "GET {id}");
3842                assert_eq!(problem(answer).await, "unknown-tenant");
3843            }
3844            let unknown_key = KeyId([7; 8]).to_string();
3845            for id in [unknown_key.as_str(), "acme", &unknown_key.to_uppercase()] {
3846                let path = format!("/admin/keys/{id}");
3847                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3848                assert_eq!(answer.status(), 404, "DELETE {id}");
3849                assert_eq!(problem(answer).await, "unknown-key");
3850            }
3851            for (action, count) in [("key_create", 2), ("key_list", 2), ("key_revoke", 3)] {
3852                let refused = admin_log(&s, action);
3853                assert_eq!(refused.len(), count, "{action}");
3854                assert!(refused.iter().all(|r| r["status"] == 404), "{action}");
3855            }
3856        }
3857
3858        #[tokio::test]
3859        async fn requests_during_a_removal_get_503_then_401() {
3860            let s = server().await;
3861            let op = operator(&s);
3862            stored(&s).await;
3863            let uuid = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
3864            let writer = s.key(&[Scope::Write]);
3865            let reader = s.key(&[Scope::Read]);
3866            let legal = s.key(&[Scope::Legal]);
3867            let a4 = std::fs::read(format!(
3868                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
3869                env!("CARGO_MANIFEST_DIR")
3870            ))
3871            .expect("A.4");
3872            let requests = || {
3873                let client = s.client();
3874                [
3875                    client
3876                        .post(s.url("/vcons"))
3877                        .bearer_auth(&writer)
3878                        .header("content-type", "application/vcon")
3879                        .body(a4.clone()),
3880                    client
3881                        .get(s.url(&format!("/vcons/{uuid}")))
3882                        .bearer_auth(&reader),
3883                    client
3884                        .get(s.url(&format!("/legal/vcons/{uuid}")))
3885                        .bearer_auth(&legal),
3886                    client.get(s.url("/health")).bearer_auth(&reader),
3887                ]
3888            };
3889
3890            // A request still holding the tenant keeps the removal draining.
3891            let in_flight = s.tenants.store(s.tenant).expect("its store");
3892            let removal = {
3893                let request = s
3894                    .client()
3895                    .delete(s.url(&format!("/admin/tenants/{}?force=true", s.tenant)))
3896                    .bearer_auth(&op);
3897                tokio::spawn(async move { request.send().await.expect("an answer").status() })
3898            };
3899            let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
3900            while s.tenants.store(s.tenant).is_ok() {
3901                assert!(
3902                    tokio::time::Instant::now() < deadline,
3903                    "the removal never began"
3904                );
3905                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
3906            }
3907            for request in requests() {
3908                let answer = request.send().await.expect("an answer");
3909                let url = answer.url().path().to_owned();
3910                assert_eq!(answer.status(), 503, "{url} while removing");
3911                assert_eq!(problem(answer).await, "unavailable", "{url}");
3912            }
3913            assert!(!removal.is_finished(), "still draining");
3914
3915            drop(in_flight);
3916            assert_eq!(removal.await.expect("joined"), 204);
3917            for request in requests() {
3918                let answer = request.send().await.expect("an answer");
3919                let url = answer.url().path().to_owned();
3920                assert_eq!(answer.status(), 401, "{url} once removed");
3921            }
3922        }
3923
3924        #[tokio::test]
3925        async fn a_key_for_a_closing_tenant_is_503() {
3926            let s = server().await;
3927            let op = operator(&s);
3928            s.tenants.close(s.tenant);
3929            let path = format!("/admin/tenants/{}/keys", s.tenant);
3930            let body = Some(r#"{"scopes":["read"],"label":"x"}"#);
3931            let answer = call(&s, Method::POST, &path, Some(&op), body).await;
3932            assert_eq!(answer.status(), 503);
3933            assert_eq!(problem(answer).await, "unavailable");
3934        }
3935
3936        #[tokio::test]
3937        async fn a_body_over_the_limit_is_413() {
3938            let s = server().await;
3939            let op = operator(&s);
3940            let body = format!(r#"{{"name":"{}"}}"#, "x".repeat(super::pipeline::LIMIT));
3941            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(&body)).await;
3942            assert_eq!(answer.status(), 413);
3943            assert_eq!(problem(answer).await, "too-large");
3944        }
3945    }
3946
3947    mod by_uuid {
3948        use super::pipeline::{START, Server, problem, server, server_keeping};
3949        use crate::access::{Scope, Scopes};
3950        use crate::audit::Actor;
3951        use crate::ids::TenantId;
3952        use crate::retention::Retention;
3953
3954        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
3955
3956        fn fixture(name: &str) -> Vec<u8> {
3957            let path = format!(
3958                "{}/../vcon/tests/fixtures/ietf/{name}",
3959                env!("CARGO_MANIFEST_DIR")
3960            );
3961            std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
3962        }
3963
3964        fn gzip(body: &[u8]) -> Vec<u8> {
3965            use std::io::Write;
3966            let mut encoder =
3967                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
3968            encoder.write_all(body).expect("gzip");
3969            encoder.finish().expect("gzip")
3970        }
3971
3972        /// A key of this tenant's with these scopes.
3973        fn key_in(s: &Server, tenant: TenantId, scopes: &[Scope]) -> String {
3974            s.tenants
3975                .create_key(Actor::Cli, Some(tenant), Scopes::of(scopes), "test")
3976                .expect("a key")
3977                .token
3978        }
3979
3980        async fn get(s: &Server, token: &str, uuid: &str) -> reqwest::Response {
3981            s.client()
3982                .get(s.url(&format!("/vcons/{uuid}")))
3983                .bearer_auth(token)
3984                .send()
3985                .await
3986                .expect("an answer")
3987        }
3988
3989        async fn post(s: &Server, token: &str, content_type: &str, body: Vec<u8>) -> String {
3990            let answer = s
3991                .client()
3992                .post(s.url("/vcons"))
3993                .bearer_auth(token)
3994                .header("content-type", content_type)
3995                .body(body)
3996                .send()
3997                .await
3998                .expect("an answer");
3999            assert_eq!(answer.status(), 201);
4000            answer.headers()["etag"].to_str().expect("ascii").to_owned()
4001        }
4002
4003        /// A.4, A.6 and A.7 share one uuid, so each runs in its own tenant.
4004        #[tokio::test]
4005        async fn the_core_examples_come_back_byte_for_byte_plain_and_gzipped() {
4006            let s = server().await;
4007            let files = [
4008                "ab_call_ext_rec.vcon",
4009                "ab_call_ext_rec_signed.vcon",
4010                "ab_call_ext_rec_encrypted.vcon",
4011            ];
4012            for (n, file) in files.into_iter().enumerate() {
4013                for gzipped in [false, true] {
4014                    let tenant = s
4015                        .tenants
4016                        .create(Actor::Cli, &format!("t{n}{gzipped}"), None)
4017                        .expect("a tenant");
4018                    let token = key_in(&s, tenant, &[Scope::Write, Scope::Read]);
4019                    let plain = fixture(file);
4020                    let (sent, content_type) = if gzipped {
4021                        (gzip(&plain), "application/vcon+gzip")
4022                    } else {
4023                        (plain, "application/vcon")
4024                    };
4025                    let tag = post(&s, &token, content_type, sent.clone()).await;
4026                    let answer = get(&s, &token, UUID).await;
4027                    assert_eq!(answer.status(), 200, "{file} {gzipped}");
4028                    assert_eq!(answer.headers()["content-type"], content_type);
4029                    assert_eq!(answer.headers()["etag"], tag.as_str());
4030                    assert!(answer.headers().get("content-encoding").is_none());
4031                    let got = answer.bytes().await.expect("body");
4032                    assert_eq!(got.as_ref(), sent.as_slice(), "{file} {gzipped}");
4033                }
4034            }
4035        }
4036
4037        #[tokio::test]
4038        async fn a_uuid_is_found_in_either_case() {
4039            let s = server().await;
4040            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4041            post(
4042                &s,
4043                &token,
4044                "application/vcon",
4045                fixture("ab_call_ext_rec.vcon"),
4046            )
4047            .await;
4048            let answer = get(&s, &token, &UUID.to_uppercase()).await;
4049            assert_eq!(answer.status(), 200);
4050        }
4051
4052        #[tokio::test]
4053        async fn a_uuid_never_stored_is_not_found_and_a_deleted_one_is_gone() {
4054            let s = server().await;
4055            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4056            let answer = get(&s, &token, UUID).await;
4057            assert_eq!(answer.status(), 404);
4058            assert_eq!(problem(answer).await, "not-found");
4059            post(
4060                &s,
4061                &token,
4062                "application/vcon",
4063                fixture("ab_call_ext_rec.vcon"),
4064            )
4065            .await;
4066            s.tenants
4067                .store(s.tenant)
4068                .expect("its store")
4069                .delete(
4070                    &crate::store::Caller {
4071                        key: crate::ids::KeyId([9; 8]),
4072                    },
4073                    UUID.parse().expect("uuid"),
4074                    crate::retention::Retention::Years(7),
4075                )
4076                .expect("deleted");
4077            let answer = get(&s, &token, UUID).await;
4078            assert_eq!(answer.status(), 410);
4079            assert_eq!(problem(answer).await, "gone");
4080        }
4081
4082        #[tokio::test]
4083        async fn a_path_uuid_not_in_text_form_is_a_bad_request_and_recorded() {
4084            let s = server().await;
4085            let token = key_in(&s, s.tenant, &[Scope::Read]);
4086            let simple = UUID.replace('-', "");
4087            for bad in [
4088                "not-a-uuid".to_owned(),
4089                simple.clone(),
4090                format!("%7B{UUID}%7D"),
4091                format!("urn:uuid:{UUID}"),
4092                format!("{UUID}0"),
4093            ] {
4094                let answer = get(&s, &token, &bad).await;
4095                assert_eq!(answer.status(), 400, "{bad}");
4096                assert_eq!(problem(answer).await, "bad-path-uuid");
4097            }
4098            let refused = s.tenant_log("read");
4099            assert_eq!(refused.len(), 5);
4100            assert_eq!(refused[0]["status"], 400);
4101        }
4102
4103        #[tokio::test]
4104        async fn a_key_without_read_is_forbidden() {
4105            let s = server().await;
4106            let token = key_in(&s, s.tenant, &[Scope::Write]);
4107            let answer = get(&s, &token, UUID).await;
4108            assert_eq!(answer.status(), 403);
4109        }
4110
4111        #[tokio::test]
4112        async fn a_read_whose_record_fails_sends_nothing() {
4113            let s = server().await;
4114            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4115            post(
4116                &s,
4117                &token,
4118                "application/vcon",
4119                fixture("ab_call_ext_rec.vcon"),
4120            )
4121            .await;
4122            s.tenants.store(s.tenant).expect("its store").break_audit();
4123            let answer = get(&s, &token, UUID).await;
4124            assert_eq!(answer.status(), 503);
4125            assert_eq!(problem(answer).await, "audit-failed");
4126        }
4127
4128        #[tokio::test]
4129        async fn a_version_whose_file_is_missing_is_damaged() {
4130            let s = server().await;
4131            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4132            let tag = post(
4133                &s,
4134                &token,
4135                "application/vcon",
4136                fixture("ab_call_ext_rec.vcon"),
4137            )
4138            .await;
4139            let object = s
4140                .dir()
4141                .join("tenants")
4142                .join(s.tenant.to_string())
4143                .join("objects")
4144                .join(tag.trim_matches('"'));
4145            std::fs::remove_file(&object).expect("remove the object file");
4146            let answer = get(&s, &token, UUID).await;
4147            assert_eq!(answer.status(), 500);
4148            assert_eq!(problem(answer).await, "damaged");
4149        }
4150
4151        async fn put(
4152            s: &Server,
4153            token: &str,
4154            uuid: &str,
4155            if_match: Option<&str>,
4156            body: Vec<u8>,
4157        ) -> reqwest::Response {
4158            let mut request = s
4159                .client()
4160                .put(s.url(&format!("/vcons/{uuid}")))
4161                .bearer_auth(token)
4162                .header("content-type", "application/vcon")
4163                .body(body);
4164            if let Some(tag) = if_match {
4165                request = request.header("if-match", tag);
4166            }
4167            request.send().await.expect("an answer")
4168        }
4169
4170        /// A writer and reader in the fixture's tenant, with A.4 stored.
4171        async fn stored_a4(s: &Server) -> (String, String) {
4172            let token = key_in(s, s.tenant, &[Scope::Write, Scope::Read]);
4173            let tag = post(
4174                s,
4175                &token,
4176                "application/vcon",
4177                fixture("ab_call_ext_rec.vcon"),
4178            )
4179            .await;
4180            (token, tag)
4181        }
4182
4183        /// An unsigned vCon may be replaced by its signed form, and a signed
4184        /// one is replaced by nothing.
4185        #[tokio::test]
4186        async fn a4_then_a6_by_put_and_a7_after_a6_conflicts() {
4187            let s = server().await;
4188            let (token, a4) = stored_a4(&s).await;
4189            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4190            let answer = put(&s, &token, UUID, Some(&a4), a6.clone()).await;
4191            assert_eq!(answer.status(), 200);
4192            let new_tag = answer.headers()["etag"].to_str().expect("ascii").to_owned();
4193            assert_ne!(new_tag, a4);
4194            let read = get(&s, &token, UUID).await;
4195            assert_eq!(read.headers()["etag"], new_tag.as_str());
4196            assert_eq!(read.bytes().await.expect("body").as_ref(), a6.as_slice());
4197
4198            let a7 = fixture("ab_call_ext_rec_encrypted.vcon");
4199            let answer = put(&s, &token, UUID, Some(&new_tag), a7).await;
4200            assert_eq!(answer.status(), 409);
4201            assert_eq!(problem(answer).await, "immutable");
4202        }
4203
4204        #[tokio::test]
4205        async fn a_put_without_if_match_is_refused_and_recorded() {
4206            let s = server().await;
4207            let (token, _) = stored_a4(&s).await;
4208            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4209            let answer = put(&s, &token, UUID, None, a6).await;
4210            assert_eq!(answer.status(), 428);
4211            assert_eq!(problem(answer).await, "precondition-required");
4212            assert_eq!(s.tenant_log("replace")[0]["status"], 428);
4213        }
4214
4215        #[tokio::test]
4216        async fn an_if_match_that_does_not_name_the_current_version_fails() {
4217            let s = server().await;
4218            let (token, a4) = stored_a4(&s).await;
4219            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4220            let weak = format!("W/{a4}");
4221            let listed = format!("{a4}, \"00000000000000000000000000000000\"");
4222            let stale = format!("\"{}\"", crate::ids::VersionId([7; 16]));
4223            for tag in [
4224                "*",
4225                weak.as_str(),
4226                listed.as_str(),
4227                "garbage",
4228                stale.as_str(),
4229            ] {
4230                let answer = put(&s, &token, UUID, Some(tag), a6.clone()).await;
4231                assert_eq!(answer.status(), 412, "{tag}");
4232                assert_eq!(problem(answer).await, "precondition-failed");
4233            }
4234            let current = get(&s, &token, UUID).await;
4235            assert_eq!(current.headers()["etag"], a4.as_str(), "nothing replaced");
4236        }
4237
4238        #[tokio::test]
4239        async fn a_body_naming_another_uuid_is_unprocessable() {
4240            let s = server().await;
4241            let (token, a4) = stored_a4(&s).await;
4242            let (_, other) =
4243                crate::store::testing::vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "x");
4244            let answer = put(&s, &token, UUID, Some(&a4), other).await;
4245            assert_eq!(answer.status(), 422);
4246            assert_eq!(problem(answer).await, "path-uuid-mismatch");
4247            assert_eq!(s.tenant_log("replace")[0]["status"], 422);
4248        }
4249
4250        #[tokio::test]
4251        async fn a_put_to_a_uuid_never_stored_or_deleted_or_badly_written() {
4252            let s = server().await;
4253            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4254            let tag = format!("\"{}\"", crate::ids::VersionId([7; 16]));
4255            let a4 = fixture("ab_call_ext_rec.vcon");
4256            let answer = put(&s, &token, UUID, Some(&tag), a4.clone()).await;
4257            assert_eq!(answer.status(), 404);
4258            assert_eq!(problem(answer).await, "not-found");
4259
4260            let answer = put(&s, &token, "not-a-uuid", Some(&tag), a4.clone()).await;
4261            assert_eq!(answer.status(), 400);
4262            assert_eq!(problem(answer).await, "bad-path-uuid");
4263
4264            let a4_tag = post(&s, &token, "application/vcon", a4.clone()).await;
4265            s.tenants
4266                .store(s.tenant)
4267                .expect("its store")
4268                .delete(
4269                    &crate::store::Caller {
4270                        key: crate::ids::KeyId([9; 8]),
4271                    },
4272                    UUID.parse().expect("uuid"),
4273                    crate::retention::Retention::Years(7),
4274                )
4275                .expect("deleted");
4276            let answer = put(&s, &token, UUID, Some(&a4_tag), a4).await;
4277            assert_eq!(answer.status(), 410);
4278            assert_eq!(problem(answer).await, "gone");
4279        }
4280
4281        #[tokio::test]
4282        async fn a_put_needs_write_and_a_vcon_media_type() {
4283            let s = server().await;
4284            let (_, a4) = stored_a4(&s).await;
4285            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4286            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4287            let answer = put(&s, &reader, UUID, Some(&a4), a6.clone()).await;
4288            assert_eq!(answer.status(), 403);
4289            let writer = key_in(&s, s.tenant, &[Scope::Write]);
4290            let answer = s
4291                .client()
4292                .put(s.url(&format!("/vcons/{UUID}")))
4293                .bearer_auth(&writer)
4294                .header("content-type", "text/plain")
4295                .header("if-match", &a4)
4296                .body(a6)
4297                .send()
4298                .await
4299                .expect("an answer");
4300            assert_eq!(answer.status(), 415);
4301        }
4302
4303        async fn delete(s: &Server, token: &str, uuid: &str) -> reqwest::Response {
4304            s.client()
4305                .delete(s.url(&format!("/vcons/{uuid}")))
4306                .bearer_auth(token)
4307                .send()
4308                .await
4309                .expect("an answer")
4310        }
4311
4312        #[tokio::test]
4313        async fn a_delete_answers_204_again_and_again() {
4314            let s = server().await;
4315            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read, Scope::Delete]);
4316            post(
4317                &s,
4318                &token,
4319                "application/vcon",
4320                fixture("ab_call_ext_rec.vcon"),
4321            )
4322            .await;
4323            for _ in 0..2 {
4324                let answer = delete(&s, &token, UUID).await;
4325                assert_eq!(answer.status(), 204);
4326                assert!(answer.bytes().await.expect("body").is_empty());
4327            }
4328            assert_eq!(get(&s, &token, UUID).await.status(), 410);
4329            let deletes = s.tenant_log("delete");
4330            assert_eq!(deletes.len(), 2, "Store records each");
4331        }
4332
4333        #[tokio::test]
4334        async fn a_delete_of_a_uuid_never_stored_or_badly_written() {
4335            let s = server().await;
4336            let token = key_in(&s, s.tenant, &[Scope::Delete]);
4337            let answer = delete(&s, &token, UUID).await;
4338            assert_eq!(answer.status(), 404);
4339            assert_eq!(problem(answer).await, "not-found");
4340            let answer = delete(&s, &token, "not-a-uuid").await;
4341            assert_eq!(answer.status(), 400);
4342            assert_eq!(problem(answer).await, "bad-path-uuid");
4343            assert_eq!(
4344                s.tenant_log("delete").last().expect("recorded")["status"],
4345                400
4346            );
4347        }
4348
4349        #[tokio::test]
4350        async fn a_delete_needs_the_delete_scope_and_its_record() {
4351            let s = server().await;
4352            let (writer, _) = stored_a4(&s).await;
4353            let answer = delete(&s, &writer, UUID).await;
4354            assert_eq!(answer.status(), 403);
4355            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4356            s.tenants.store(s.tenant).expect("its store").break_audit();
4357            let answer = delete(&s, &deleter, UUID).await;
4358            assert_eq!(answer.status(), 503);
4359            assert_eq!(problem(answer).await, "audit-failed");
4360        }
4361
4362        /// The purge records of `s`'s tenant whose actor is `token`'s key.
4363        fn purged_by(s: &Server, token: &str) -> usize {
4364            s.tenant_log("purge")
4365                .iter()
4366                .filter(|r| r["actor"] == token[4..20])
4367                .count()
4368        }
4369
4370        #[tokio::test]
4371        async fn a_delete_erases_at_once_under_the_tenants_zero_period() {
4372            let s = server().await;
4373            s.tenants
4374                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
4375                .expect("set");
4376            let (_, _) = stored_a4(&s).await;
4377            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4378            assert_eq!(delete(&s, &deleter, UUID).await.status(), 204);
4379            assert_eq!(purged_by(&s, &deleter), 1);
4380        }
4381
4382        #[tokio::test]
4383        async fn a_delete_uses_the_server_default_when_the_tenant_sets_none() {
4384            let s = server_keeping(Retention::Days(0)).await;
4385            let (_, _) = stored_a4(&s).await;
4386            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4387            assert_eq!(delete(&s, &deleter, UUID).await.status(), 204);
4388            assert_eq!(purged_by(&s, &deleter), 1);
4389        }
4390
4391        #[tokio::test]
4392        async fn a_delete_keeps_a_young_vcon_for_legal_reads() {
4393            let s = server().await;
4394            let (_, _) = stored_a4(&s).await;
4395            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4396            assert_eq!(delete(&s, &deleter, UUID).await.status(), 204);
4397            assert_eq!(purged_by(&s, &deleter), 0);
4398        }
4399
4400        #[tokio::test]
4401        async fn a_delete_whose_period_cannot_be_read_deletes_nothing() {
4402            let s = server().await;
4403            let (_, _) = stored_a4(&s).await;
4404            s.tenants
4405                .conn_for_test()
4406                .execute(
4407                    "UPDATE tenant SET retention = '7w' WHERE id = ?1",
4408                    [s.tenant.0],
4409                )
4410                .expect("damaged");
4411            let token = key_in(&s, s.tenant, &[Scope::Delete, Scope::Read]);
4412            let answer = delete(&s, &token, UUID).await;
4413            assert_eq!(answer.status(), 503);
4414            assert_eq!(problem(answer).await, "unavailable");
4415            assert_eq!(get(&s, &token, UUID).await.status(), 200);
4416            assert_eq!(
4417                s.tenant_log("delete").last().expect("recorded")["status"],
4418                503
4419            );
4420        }
4421
4422        async fn health(s: &Server, token: Option<&str>) -> reqwest::Response {
4423            let mut request = s.client().get(s.url("/health"));
4424            if let Some(token) = token {
4425                request = request.bearer_auth(token);
4426            }
4427            request.send().await.expect("an answer")
4428        }
4429
4430        #[tokio::test]
4431        async fn health_needs_a_key_of_any_scope_and_is_counted() {
4432            let s = server().await;
4433            assert_eq!(health(&s, None).await.status(), 401);
4434            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4435            for _ in 0..2 {
4436                let answer = health(&s, Some(&reader)).await;
4437                assert_eq!(answer.status(), 200);
4438                assert_eq!(answer.headers()["content-type"], "application/json");
4439            }
4440            let counted = s.tenant_log("health");
4441            assert_eq!(counted.len(), 1, "one record a minute");
4442            assert_eq!(counted[0]["count"], 2);
4443            assert_eq!(counted[0]["status"], 200);
4444            // The last second of the minute still counts in it; the next
4445            // minute starts a record of its own.
4446            s.clock.set(START + time::Duration::seconds(59));
4447            health(&s, Some(&reader)).await;
4448            s.clock.set(START + time::Duration::minutes(1));
4449            health(&s, Some(&reader)).await;
4450            let counted = s.tenant_log("health");
4451            assert_eq!(
4452                counted
4453                    .iter()
4454                    .map(|r| (
4455                        r["at"].as_str().expect("at"),
4456                        r["count"].as_u64().expect("count")
4457                    ))
4458                    .collect::<Vec<_>>(),
4459                [("2026-10-23T12:00:00Z", 3), ("2026-10-23T12:01:00Z", 1)],
4460                "a record counts the requests of its minute only"
4461            );
4462
4463            let operator = s
4464                .tenants
4465                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4466                .expect("made")
4467                .token;
4468            assert_eq!(health(&s, Some(&operator)).await.status(), 200);
4469            let admin: Vec<_> = s
4470                .tenants
4471                .admin_records()
4472                .into_iter()
4473                .filter(|r| r["action"] == "health")
4474                .collect();
4475            assert_eq!(admin.len(), 1);
4476            assert_eq!(admin[0]["actor"], operator[4..20]);
4477        }
4478
4479        #[tokio::test]
4480        async fn health_is_unavailable_when_the_catalog_does_not_answer() {
4481            let s = server().await;
4482            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4483            s.tenants
4484                .conn_for_test()
4485                .execute_batch("ALTER TABLE tenant RENAME TO gone")
4486                .expect("lose the table");
4487            let answer = health(&s, Some(&reader)).await;
4488            assert_eq!(answer.status(), 503);
4489            assert_eq!(problem(answer).await, "unavailable");
4490        }
4491
4492        #[tokio::test]
4493        async fn health_whose_count_fails_is_unavailable() {
4494            let s = server().await;
4495            let operator = s
4496                .tenants
4497                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4498                .expect("made")
4499                .token;
4500            s.tenants.break_audit();
4501            let answer = health(&s, Some(&operator)).await;
4502            assert_eq!(answer.status(), 503);
4503            assert_eq!(problem(answer).await, "audit-failed");
4504        }
4505    }
4506
4507    /// `GET /openapi.json`: the description, to any valid key.
4508    mod openapi_route {
4509        use super::pipeline::{Server, problem, server};
4510        use crate::access::{Scope, Scopes};
4511        use crate::audit::Actor;
4512
4513        async fn get(s: &Server, token: Option<&str>) -> reqwest::Response {
4514            let mut request = s.client().get(s.url("/openapi.json"));
4515            if let Some(token) = token {
4516                request = request.bearer_auth(token);
4517            }
4518            request.send().await.expect("an answer")
4519        }
4520
4521        fn admin_openapi_records(s: &Server) -> usize {
4522            let mut out = Vec::new();
4523            s.tenants.export_admin(None, &mut out).expect("export");
4524            String::from_utf8(out)
4525                .expect("UTF-8")
4526                .lines()
4527                .filter(|l| l.contains("\"action\":\"openapi\""))
4528                .count()
4529        }
4530
4531        #[tokio::test]
4532        async fn any_valid_key_gets_the_description_as_compiled_and_it_is_recorded() {
4533            let s = server().await;
4534            let operator = s
4535                .tenants
4536                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4537                .expect("an operator key")
4538                .token;
4539            for token in [s.key(&[Scope::Read]), s.key(&[Scope::Write]), operator] {
4540                let answer = get(&s, Some(&token)).await;
4541                assert_eq!(answer.status(), 200);
4542                assert_eq!(answer.headers()["content-type"], "application/json");
4543                assert_eq!(answer.text().await.expect("text"), super::super::OPENAPI);
4544            }
4545            let recorded = s.tenant_log("openapi");
4546            assert_eq!(recorded.len(), 2, "the two tenant keys");
4547            assert!(recorded.iter().all(|r| r["status"] == 200));
4548            assert_eq!(admin_openapi_records(&s), 1, "the operator key");
4549        }
4550
4551        #[tokio::test]
4552        async fn no_key_is_401_and_a_read_that_cannot_be_recorded_503() {
4553            let s = server().await;
4554            let answer = get(&s, None).await;
4555            assert_eq!(answer.status(), 401);
4556            assert_eq!(problem(answer).await, "unauthorized");
4557            let reader = s.key(&[Scope::Read]);
4558            s.tenants.store(s.tenant).expect("its store").break_audit();
4559            let answer = get(&s, Some(&reader)).await;
4560            assert_eq!(answer.status(), 503);
4561            assert_eq!(problem(answer).await, "audit-failed");
4562        }
4563
4564        #[tokio::test]
4565        async fn a_key_of_a_closing_tenant_is_503() {
4566            let s = server().await;
4567            let reader = s.key(&[Scope::Read]);
4568            s.tenants.close(s.tenant);
4569            let answer = get(&s, Some(&reader)).await;
4570            assert_eq!(answer.status(), 503);
4571            assert_eq!(problem(answer).await, "unavailable");
4572        }
4573    }
4574
4575    /// `GET /audit` and `GET /admin/audit`: a log a page at a time, as the
4576    /// command line exports it.
4577    mod audit_routes {
4578        use super::pipeline::{Server, problem, server};
4579        use crate::access::{Scope, Scopes};
4580        use crate::audit::Actor;
4581        use crate::store::testing::vcon;
4582
4583        fn operator(s: &Server) -> String {
4584            s.tenants
4585                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4586                .expect("an operator key")
4587                .token
4588        }
4589
4590        async fn get(s: &Server, path: &str, token: Option<&str>) -> reqwest::Response {
4591            let mut request = s.client().get(s.url(path));
4592            if let Some(token) = token {
4593                request = request.bearer_auth(token);
4594            }
4595            request.send().await.expect("an answer")
4596        }
4597
4598        async fn body(answer: reqwest::Response) -> Vec<u8> {
4599            assert_eq!(answer.status(), 200);
4600            assert_eq!(answer.headers()["content-type"], "application/jsonl");
4601            answer.bytes().await.expect("body").to_vec()
4602        }
4603
4604        /// The tenant's log as `audit export --tenant` writes it.
4605        fn tenant_export(s: &Server, since: Option<i64>) -> Vec<u8> {
4606            let mut out = Vec::new();
4607            s.tenants
4608                .store(s.tenant)
4609                .expect("its store")
4610                .export(since, &mut out)
4611                .expect("export");
4612            out
4613        }
4614
4615        fn admin_export(s: &Server) -> Vec<u8> {
4616            let mut out = Vec::new();
4617            s.tenants.export_admin(None, &mut out).expect("export");
4618            out
4619        }
4620
4621        async fn three_stored(s: &Server) {
4622            let writer = s.key(&[Scope::Write]);
4623            for n in 1..=3 {
4624                let answer = s
4625                    .client()
4626                    .post(s.url("/vcons"))
4627                    .bearer_auth(&writer)
4628                    .header("content-type", "application/vcon")
4629                    .body(vcon(&format!("01a07da8-c2bb-83e5-b9a2-{n:012x}"), "x").1)
4630                    .send()
4631                    .await
4632                    .expect("an answer");
4633                assert_eq!(answer.status(), 201);
4634            }
4635        }
4636
4637        #[tokio::test]
4638        async fn the_tenant_log_is_its_export_byte_for_byte_a_page_at_a_time() {
4639            let s = server().await;
4640            three_stored(&s).await;
4641            let auditor = s.key(&[Scope::Audit]);
4642            let before = tenant_export(&s, None);
4643            assert_eq!(body(get(&s, "/audit", Some(&auditor)).await).await, before);
4644            let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
4645            assert_eq!(
4646                body(get(&s, "/audit?after=1&limit=2", Some(&auditor)).await).await,
4647                lines[1..3].concat()
4648            );
4649            // The reads are recorded, each after its own page.
4650            let reads = s.tenant_log("audit_read");
4651            assert_eq!(reads.len(), 2);
4652            assert!(reads.iter().all(|r| r["status"] == 200));
4653            // The page is the log as it stood before the read, which then
4654            // records itself after it.
4655            let after = 3;
4656            let expected = tenant_export(&s, Some(after));
4657            assert!(
4658                !expected.is_empty(),
4659                "three stores and two reads leave records past seq 3"
4660            );
4661            let page = body(get(&s, &format!("/audit?after={after}"), Some(&auditor)).await).await;
4662            assert_eq!(
4663                page, expected,
4664                "the page is every record after seq 3, whole"
4665            );
4666        }
4667
4668        #[tokio::test]
4669        async fn the_admin_log_is_its_export_byte_for_byte() {
4670            let s = server().await;
4671            let op = operator(&s);
4672            let before = admin_export(&s);
4673            assert!(!before.is_empty(), "the tenant's creation, at least");
4674            assert_eq!(body(get(&s, "/admin/audit", Some(&op)).await).await, before);
4675            let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
4676            assert_eq!(
4677                body(get(&s, "/admin/audit?limit=1", Some(&op)).await).await,
4678                lines[0]
4679            );
4680            let mut recorded = Vec::new();
4681            s.tenants.export_admin(None, &mut recorded).expect("export");
4682            let reads = String::from_utf8(recorded)
4683                .expect("UTF-8")
4684                .lines()
4685                .filter(|l| l.contains("\"action\":\"audit_read\""))
4686                .count();
4687            assert_eq!(reads, 2);
4688        }
4689
4690        #[tokio::test]
4691        async fn the_tenant_log_needs_a_tenant_key_with_audit() {
4692            let s = server().await;
4693            assert_eq!(get(&s, "/audit", None).await.status(), 401);
4694            for scopes in [
4695                &[Scope::Read][..],
4696                &[Scope::Legal],
4697                &[Scope::Write, Scope::Delete],
4698            ] {
4699                let answer = get(&s, "/audit", Some(&s.key(scopes))).await;
4700                assert_eq!(answer.status(), 403, "{scopes:?}");
4701                assert_eq!(problem(answer).await, "forbidden");
4702            }
4703            let answer = get(&s, "/audit", Some(&operator(&s))).await;
4704            assert_eq!(answer.status(), 403, "an operator key");
4705            let refused = s.tenant_log("audit_read");
4706            assert_eq!(refused.len(), 3, "the tenant keys' refusals");
4707            assert!(refused.iter().all(|r| r["status"] == 403));
4708        }
4709
4710        #[tokio::test]
4711        async fn the_admin_log_needs_an_operator_key() {
4712            let s = server().await;
4713            assert_eq!(get(&s, "/admin/audit", None).await.status(), 401);
4714            let every = s.key(&[
4715                Scope::Write,
4716                Scope::Read,
4717                Scope::Delete,
4718                Scope::Legal,
4719                Scope::Audit,
4720            ]);
4721            let answer = get(&s, "/admin/audit", Some(&every)).await;
4722            assert_eq!(answer.status(), 403);
4723            assert_eq!(problem(answer).await, "forbidden");
4724            assert_eq!(s.tenant_log("audit_read").len(), 1, "recorded");
4725        }
4726
4727        #[tokio::test]
4728        async fn a_query_the_routes_do_not_take_is_a_bad_query_and_recorded() {
4729            let s = server().await;
4730            let auditor = s.key(&[Scope::Audit]);
4731            let op = operator(&s);
4732            let bad = [
4733                "?since=3",
4734                "?after=-1",
4735                "?limit=0",
4736                "?limit=10001",
4737                "?after=1&after=2",
4738            ];
4739            for query in bad {
4740                for (path, token) in [("/audit", &auditor), ("/admin/audit", &op)] {
4741                    let answer = get(&s, &format!("{path}{query}"), Some(token)).await;
4742                    assert_eq!(answer.status(), 400, "{path}{query}");
4743                    assert_eq!(problem(answer).await, "bad-query");
4744                }
4745            }
4746            let refused = s.tenant_log("audit_read");
4747            assert_eq!(refused.len(), bad.len());
4748            assert!(refused.iter().all(|r| r["status"] == 400));
4749            let mut admin = Vec::new();
4750            s.tenants.export_admin(None, &mut admin).expect("export");
4751            let admin_refused = String::from_utf8(admin)
4752                .expect("UTF-8")
4753                .lines()
4754                .filter(|l| l.contains("\"action\":\"audit_read\"") && l.contains("\"status\":400"))
4755                .count();
4756            assert_eq!(admin_refused, bad.len());
4757        }
4758
4759        #[tokio::test]
4760        async fn a_read_that_cannot_be_recorded_is_503() {
4761            let s = server().await;
4762            let auditor = s.key(&[Scope::Audit]);
4763            let op = operator(&s);
4764            s.tenants.store(s.tenant).expect("its store").break_audit();
4765            let answer = get(&s, "/audit", Some(&auditor)).await;
4766            assert_eq!(answer.status(), 503);
4767            assert_eq!(problem(answer).await, "audit-failed");
4768            s.tenants.break_audit();
4769            let answer = get(&s, "/admin/audit", Some(&op)).await;
4770            assert_eq!(answer.status(), 503);
4771            assert_eq!(problem(answer).await, "audit-failed");
4772        }
4773    }
4774
4775    /// `GET /vcons`: a tenant's live vCons, a page at a time.
4776    mod list {
4777        use serde_json::Value;
4778
4779        use super::pipeline::{START, Server, problem, server};
4780        use crate::access::{Scope, Scopes};
4781        use crate::audit::Actor;
4782        use crate::ids::TenantId;
4783        use crate::store::testing::vcon;
4784
4785        fn uuid(n: u32) -> String {
4786            format!("01a07da8-c2bb-83e5-b9a2-{n:012x}")
4787        }
4788
4789        fn key_of(s: &Server, tenant: TenantId, scopes: &[Scope]) -> String {
4790            s.tenants
4791                .create_key(Actor::Cli, Some(tenant), Scopes::of(scopes), "test")
4792                .expect("a key")
4793                .token
4794        }
4795
4796        /// Stores vCon `n` with `writer` and returns its tag, unquoted.
4797        async fn stored(s: &Server, writer: &str, n: u32) -> String {
4798            let answer = s
4799                .client()
4800                .post(s.url("/vcons"))
4801                .bearer_auth(writer)
4802                .header("content-type", "application/vcon")
4803                .body(vcon(&uuid(n), "listed").1)
4804                .send()
4805                .await
4806                .expect("an answer");
4807            assert_eq!(answer.status(), 201);
4808            answer.headers()["etag"]
4809                .to_str()
4810                .expect("text")
4811                .trim_matches('"')
4812                .to_owned()
4813        }
4814
4815        async fn list(s: &Server, token: Option<&str>, query: &str) -> reqwest::Response {
4816            let mut request = s.client().get(s.url(&format!("/vcons{query}")));
4817            if let Some(token) = token {
4818                request = request.bearer_auth(token);
4819            }
4820            request.send().await.expect("an answer")
4821        }
4822
4823        async fn page(s: &Server, reader: &str, query: &str) -> Value {
4824            let answer = list(s, Some(reader), query).await;
4825            assert_eq!(answer.status(), 200, "{query}");
4826            assert_eq!(answer.headers()["content-type"], "application/json");
4827            serde_json::from_str(&answer.text().await.expect("text")).expect("JSON")
4828        }
4829
4830        fn uuids(page: &Value) -> Vec<String> {
4831            page["vcons"]
4832                .as_array()
4833                .expect("a list")
4834                .iter()
4835                .map(|v| v["uuid"].as_str().expect("a uuid").to_owned())
4836                .collect()
4837        }
4838
4839        /// Every vCon the reader's pages list, following `next`.
4840        async fn every_page(s: &Server, reader: &str, limit: u32) -> Vec<String> {
4841            let mut seen = Vec::new();
4842            let mut query = format!("?limit={limit}");
4843            for _ in 0..100 {
4844                let page = page(s, reader, &query).await;
4845                seen.extend(uuids(&page));
4846                match page["next"].as_str() {
4847                    Some(cursor) => query = format!("?limit={limit}&cursor={cursor}"),
4848                    None => return seen,
4849                }
4850            }
4851            panic!("the cursors end")
4852        }
4853
4854        #[tokio::test]
4855        async fn the_list_is_newest_first_with_each_tag_and_time() {
4856            let s = server().await;
4857            let writer = s.key(&[Scope::Write]);
4858            let mut tags = Vec::new();
4859            for n in 1..=3 {
4860                tags.push(stored(&s, &writer, n).await);
4861            }
4862            let reader = s.key(&[Scope::Read]);
4863            let page = page(&s, &reader, "").await;
4864            assert_eq!(uuids(&page), [3, 2, 1].map(uuid));
4865            assert_eq!(page["next"], Value::Null);
4866            for (listed, tag) in page["vcons"]
4867                .as_array()
4868                .expect("a list")
4869                .iter()
4870                .zip(tags.iter().rev())
4871            {
4872                assert_eq!(listed["version"], tag.as_str());
4873                assert_eq!(listed["stored_at"], listed["updated_at"]);
4874                let at = listed["stored_at"].as_str().expect("a time");
4875                assert!(at.ends_with('Z'), "{at}");
4876            }
4877            let recorded = s.tenant_log("list");
4878            assert_eq!(recorded.len(), 1);
4879            assert_eq!(recorded[0]["status"], 200);
4880        }
4881
4882        #[tokio::test]
4883        async fn paging_returns_each_vcon_once_and_a_deleted_one_never() {
4884            let s = server().await;
4885            let writer = s.key(&[Scope::Write]);
4886            for n in 1..=7 {
4887                stored(&s, &writer, n).await;
4888            }
4889            let deleted = s
4890                .client()
4891                .delete(s.url(&format!("/vcons/{}", uuid(4))))
4892                .bearer_auth(s.key(&[Scope::Delete]))
4893                .send()
4894                .await
4895                .expect("an answer");
4896            assert_eq!(deleted.status(), 204);
4897            let reader = s.key(&[Scope::Read]);
4898            for limit in [1, 2, 3, 6, 7, 100] {
4899                assert_eq!(
4900                    every_page(&s, &reader, limit).await,
4901                    [7, 6, 5, 3, 2, 1].map(uuid),
4902                    "limit {limit}"
4903                );
4904            }
4905        }
4906
4907        #[tokio::test]
4908        async fn a_tenant_lists_its_own_vcons_never_another_tenants() {
4909            let s = server().await;
4910            let beta = s.tenants.create(Actor::Cli, "beta", None).expect("made");
4911            let acme_writer = s.key(&[Scope::Write]);
4912            let beta_writer = key_of(&s, beta, &[Scope::Write]);
4913            // Stored a second apart, acme's first: 1, 3, 5, then beta's
4914            // 2, 3, 4. vCon 3 is held by both tenants, each its own.
4915            let mut at = START;
4916            for (writer, n) in [(&acme_writer, 1), (&acme_writer, 3), (&acme_writer, 5)]
4917                .into_iter()
4918                .chain([(&beta_writer, 2), (&beta_writer, 3), (&beta_writer, 4)])
4919            {
4920                at += time::Duration::SECOND;
4921                s.clock.set(at);
4922                stored(&s, writer, n).await;
4923            }
4924            let acme = s.key(&[Scope::Read]);
4925            let beta_reader = key_of(&s, beta, &[Scope::Read]);
4926            assert_eq!(every_page(&s, &acme, 1).await, [5, 3, 1].map(uuid));
4927            assert_eq!(every_page(&s, &beta_reader, 1).await, [4, 3, 2].map(uuid));
4928            // A cursor from the other tenant's list only sets a place.
4929            let beta_page = page(&s, &beta_reader, "?limit=1").await;
4930            let cursor = beta_page["next"].as_str().expect("a cursor");
4931            // Beta's first, vCon 4, was stored after all of acme's, so the
4932            // place is before every acme vCon.
4933            let mixed = page(&s, &acme, &format!("?cursor={cursor}")).await;
4934            assert_eq!(
4935                uuids(&mixed),
4936                [5, 3, 1].map(uuid),
4937                "a foreign cursor sets a place in this tenant's list, and lists all of it after"
4938            );
4939        }
4940
4941        #[tokio::test]
4942        async fn since_and_until_bound_the_first_store_time() {
4943            let s = server().await;
4944            let writer = s.key(&[Scope::Write]);
4945            stored(&s, &writer, 1).await;
4946            let reader = s.key(&[Scope::Read]);
4947            let first = page(&s, &reader, "").await;
4948            let at = first["vcons"][0]["stored_at"]
4949                .as_str()
4950                .expect("a time")
4951                .to_owned();
4952            let at = at.replace(':', "%3A");
4953            assert_eq!(
4954                uuids(&page(&s, &reader, &format!("?since={at}")).await),
4955                vec![uuid(1)]
4956            );
4957            assert_eq!(
4958                uuids(&page(&s, &reader, &format!("?until={at}")).await),
4959                Vec::<String>::new()
4960            );
4961        }
4962
4963        #[tokio::test]
4964        async fn a_query_the_route_does_not_take_is_a_bad_query_and_recorded() {
4965            let s = server().await;
4966            let reader = s.key(&[Scope::Read]);
4967            let bad = [
4968                "?offset=2",
4969                "?limit=0",
4970                "?limit=1001",
4971                "?limit=ten",
4972                "?limit=1&limit=2",
4973                "?cursor=nope",
4974                "?since=yesterday",
4975                "?until=2026-10-25",
4976            ];
4977            for query in bad {
4978                let answer = list(&s, Some(&reader), query).await;
4979                assert_eq!(answer.status(), 400, "{query}");
4980                assert_eq!(problem(answer).await, "bad-query", "{query}");
4981            }
4982            let recorded = s.tenant_log("list");
4983            assert_eq!(recorded.len(), bad.len());
4984            assert!(recorded.iter().all(|r| r["status"] == 400));
4985        }
4986
4987        #[tokio::test]
4988        async fn the_list_needs_a_tenant_key_with_read() {
4989            let s = server().await;
4990            let answer = list(&s, None, "").await;
4991            assert_eq!(answer.status(), 401);
4992            for scopes in [&[Scope::Write][..], &[Scope::Delete], &[Scope::Legal]] {
4993                let answer = list(&s, Some(&s.key(scopes)), "").await;
4994                assert_eq!(answer.status(), 403, "{scopes:?}");
4995                assert_eq!(problem(answer).await, "forbidden");
4996            }
4997            let operator = s
4998                .tenants
4999                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
5000                .expect("an operator key")
5001                .token;
5002            let answer = list(&s, Some(&operator), "").await;
5003            assert_eq!(answer.status(), 403);
5004            let recorded = s.tenant_log("list");
5005            assert_eq!(recorded.len(), 3, "the tenant keys' refusals");
5006            assert!(recorded.iter().all(|r| r["status"] == 403));
5007        }
5008
5009        #[tokio::test]
5010        async fn damage_is_500_and_a_list_that_cannot_be_recorded_503() {
5011            let s = server().await;
5012            let writer = s.key(&[Scope::Write]);
5013            stored(&s, &writer, 1).await;
5014            let reader = s.key(&[Scope::Read]);
5015            let store = s.tenants.store(s.tenant).expect("its store");
5016            store
5017                .conn_for_test()
5018                .execute("DELETE FROM version", [])
5019                .expect("damaged");
5020            let answer = list(&s, Some(&reader), "").await;
5021            assert_eq!(answer.status(), 500);
5022            assert_eq!(problem(answer).await, "damaged");
5023            store.break_audit();
5024            let answer = list(&s, Some(&reader), "").await;
5025            assert_eq!(answer.status(), 503);
5026            assert_eq!(problem(answer).await, "audit-failed");
5027        }
5028    }
5029
5030    /// `GET /key`: a key learns its own id, tenant and scopes, and the
5031    /// request is recorded before the answer goes out.
5032    mod key_info {
5033        use serde_json::Value;
5034
5035        use super::pipeline::{Server, problem, server};
5036        use crate::access::{self, Scope, Scopes};
5037        use crate::audit::Actor;
5038
5039        async fn key(s: &Server, token: Option<&str>) -> reqwest::Response {
5040            let mut request = s.client().get(s.url("/key"));
5041            if let Some(token) = token {
5042                request = request.bearer_auth(token);
5043            }
5044            request.send().await.expect("an answer")
5045        }
5046
5047        /// What the key may do, and nothing else: its id, tenant and scopes.
5048        fn own(token: &str, tenant: Option<String>, scopes: &[&str]) -> Value {
5049            let id = access::parse(token).expect("a token").to_string();
5050            serde_json::json!({ "id": id, "tenant": tenant, "scopes": scopes })
5051        }
5052
5053        #[tokio::test]
5054        async fn a_tenant_key_reads_its_own_record_and_the_read_is_recorded() {
5055            let s = server().await;
5056            let token = s.key(&[Scope::Read, Scope::Delete]);
5057            let answer = key(&s, Some(&token)).await;
5058            assert_eq!(answer.status(), 200);
5059            assert_eq!(answer.headers()["content-type"], "application/json");
5060            assert_eq!(answer.headers()["cache-control"], "no-store");
5061            let body: Value =
5062                serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON");
5063            let tenant = Some(s.tenant.to_string());
5064            assert_eq!(body, own(&token, tenant, &["read", "delete"]));
5065            let records = s.tenant_log("key_info");
5066            assert_eq!(records.len(), 1, "one record per request");
5067            assert_eq!(records[0]["status"], 200);
5068            assert_eq!(records[0]["actor"], token[4..20]);
5069            assert_eq!(records[0]["target"], token[4..20], "the key read");
5070        }
5071
5072        #[tokio::test]
5073        async fn an_operator_key_reads_its_record_in_the_admin_log() {
5074            let s = server().await;
5075            let token = s
5076                .tenants
5077                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
5078                .expect("made")
5079                .token;
5080            let answer = key(&s, Some(&token)).await;
5081            assert_eq!(answer.status(), 200);
5082            let body: Value =
5083                serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON");
5084            assert_eq!(body, own(&token, None, &["admin"]));
5085            let records: Vec<_> = s
5086                .tenants
5087                .admin_records()
5088                .into_iter()
5089                .filter(|r| r["action"] == "key_info")
5090                .collect();
5091            assert_eq!(records.len(), 1);
5092            assert_eq!(records[0]["status"], 200);
5093            assert_eq!(records[0]["target"], token[4..20]);
5094            assert!(s.tenant_log("key_info").is_empty(), "no tenant's log");
5095        }
5096
5097        #[tokio::test]
5098        async fn no_key_or_a_bad_one_is_401() {
5099            let s = server().await;
5100            for token in [None, Some("vcs_nonsense")] {
5101                let answer = key(&s, token).await;
5102                assert_eq!(answer.status(), 401, "{token:?}");
5103                assert_eq!(problem(answer).await, "unauthorized");
5104            }
5105        }
5106
5107        #[tokio::test]
5108        async fn a_read_that_cannot_be_recorded_shows_nothing() {
5109            let s = server().await;
5110            let token = s.key(&[Scope::Read]);
5111            s.tenants.store(s.tenant).expect("its store").break_audit();
5112            let answer = key(&s, Some(&token)).await;
5113            assert_eq!(answer.status(), 503);
5114            assert_eq!(problem(answer).await, "audit-failed");
5115        }
5116
5117        #[tokio::test]
5118        async fn a_key_whose_tenant_is_closing_is_503() {
5119            let s = server().await;
5120            let token = s.key(&[Scope::Read]);
5121            s.tenants.close(s.tenant);
5122            let answer = key(&s, Some(&token)).await;
5123            assert_eq!(answer.status(), 503);
5124            assert_eq!(problem(answer).await, "unavailable");
5125            let refused: Vec<_> = s
5126                .tenants
5127                .admin_records()
5128                .into_iter()
5129                .filter(|r| r["action"] == "key_info")
5130                .collect();
5131            assert_eq!(refused.len(), 1, "the refusal is recorded");
5132            assert_eq!(refused[0]["status"], 503);
5133        }
5134    }
5135
5136    /// The console's files are served through the API's own router, with
5137    /// its headers, and the API itself never asks a browser to keep or
5138    /// share anything.
5139    mod console {
5140        use super::pipeline::server;
5141        use crate::access::Scope;
5142
5143        #[tokio::test]
5144        async fn the_router_serves_the_console_without_a_key() {
5145            let s = server().await;
5146            for (file, _, media_type) in crate::console::FILES {
5147                let path = &crate::console::path_of(file);
5148                let answer = s.client().get(s.url(path)).send().await.expect("an answer");
5149                assert_eq!(answer.status(), 200, "{path}");
5150                assert_eq!(answer.headers()["content-type"], media_type, "{path}");
5151                // The player's page has a policy of its own, which
5152                // api::player_routes holds; every other header is shared.
5153                let shared = usize::from(path == crate::console::PLAYER_PATH);
5154                for (name, value) in &crate::console::HEADERS[shared..] {
5155                    assert_eq!(answer.headers()[*name], *value, "{path} {name}");
5156                }
5157                let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5158                    .join("console")
5159                    .join(file);
5160                let source = std::fs::read(source).expect("the source file");
5161                assert_eq!(answer.bytes().await.expect("body"), source, "{path}");
5162            }
5163        }
5164
5165        /// Every answer under /console carries the headers, a refusal too.
5166        #[tokio::test]
5167        async fn every_other_console_answer_carries_the_headers() {
5168            let s = server().await;
5169            let client = s.client_not_following();
5170            let answers = [
5171                (client.get(s.url("/console/other.js")), 404),
5172                (client.get(s.url("/console/a/b")), 404),
5173                (client.post(s.url("/console/")), 405),
5174                (client.get(s.url("/console")), 308),
5175            ];
5176            for (request, status) in answers {
5177                let answer = request.send().await.expect("an answer");
5178                assert_eq!(answer.status(), status, "{answer:?}");
5179                for (name, value) in crate::console::HEADERS {
5180                    assert_eq!(answer.headers()[name], value, "{status} {name}");
5181                }
5182                if status == 308 {
5183                    assert_eq!(answer.headers()["location"], "/console/");
5184                }
5185            }
5186            let elsewhere = client
5187                .get(s.url("/consoles"))
5188                .send()
5189                .await
5190                .expect("an answer");
5191            assert_eq!(elsewhere.status(), 404);
5192            assert!(
5193                !elsewhere.headers().contains_key("content-security-policy"),
5194                "only console answers carry its headers"
5195            );
5196        }
5197
5198        #[tokio::test]
5199        async fn no_answer_sets_a_cookie_or_allows_another_origin() {
5200            let s = server().await;
5201            let token = s.key(&[Scope::Read]);
5202            for path in ["/console/", "/health", "/key", "/vcons/nonsense"] {
5203                let answer = s
5204                    .client()
5205                    .get(s.url(path))
5206                    .bearer_auth(&token)
5207                    .header("origin", "https://elsewhere.example.com")
5208                    .send()
5209                    .await
5210                    .expect("an answer");
5211                let headers = answer.headers();
5212                assert!(!headers.contains_key("set-cookie"), "{path}");
5213                assert!(
5214                    !headers.contains_key("access-control-allow-origin"),
5215                    "{path}"
5216                );
5217            }
5218        }
5219    }
5220}
5221
5222/// The website documents every problem type at the URL the type names, so
5223/// a client following a `type` finds what it means. These tests hold the
5224/// pages to the code.
5225#[cfg(test)]
5226mod reveal_routes;
5227
5228#[cfg(test)]
5229mod player_routes;
5230
5231#[cfg(test)]
5232mod plane_routes;
5233
5234#[cfg(test)]
5235mod policy_tests;
5236
5237#[cfg(test)]
5238mod tenant_routes;
5239
5240#[cfg(test)]
5241mod session_tests;
5242
5243#[cfg(test)]
5244mod key_life_tests;
5245
5246#[cfg(test)]
5247mod site_pages {
5248    use std::collections::BTreeSet;
5249    use std::path::PathBuf;
5250
5251    use super::*;
5252
5253    /// One of every problem the API can answer. Each list sits behind an
5254    /// exhaustive match, so a new kind of problem fails to compile here
5255    /// until it is listed, and then fails the test until it has its page.
5256    pub(super) fn every_problem() -> Vec<Problem> {
5257        let mut all = vec![
5258            Problem::Unauthorized,
5259            Problem::Forbidden,
5260            Problem::WrongListener,
5261            Problem::TooLarge,
5262            Problem::Timeout,
5263            Problem::BadBody,
5264            Problem::Unavailable,
5265            Problem::AuditFailed,
5266            Problem::UnsupportedMediaType,
5267            Problem::KeyExpired,
5268            Problem::KeyAndSession,
5269            Problem::NoSession,
5270            Problem::BadOrigin,
5271            Problem::BadCsrf,
5272            Problem::BadPathUuid,
5273            Problem::BadPathVersion,
5274            Problem::PreconditionRequired,
5275            Problem::PathUuidMismatch,
5276            Problem::InvalidBody,
5277            Problem::BadQuery,
5278            Problem::UnknownKey,
5279            Problem::RateLimited,
5280            Problem::AtCapacity,
5281            Problem::UnknownTool,
5282            Problem::InvalidArguments,
5283        ];
5284        for problem in &all {
5285            match problem {
5286                Problem::Unauthorized
5287                | Problem::Forbidden
5288                | Problem::WrongListener
5289                | Problem::TooLarge
5290                | Problem::Timeout
5291                | Problem::BadBody
5292                | Problem::Unavailable
5293                | Problem::AuditFailed
5294                | Problem::UnsupportedMediaType
5295                | Problem::KeyExpired
5296                | Problem::KeyAndSession
5297                | Problem::NoSession
5298                | Problem::BadOrigin
5299                | Problem::BadCsrf
5300                | Problem::BadPathUuid
5301                | Problem::BadPathVersion
5302                | Problem::PreconditionRequired
5303                | Problem::PathUuidMismatch
5304                | Problem::InvalidBody
5305                | Problem::BadQuery
5306                | Problem::UnknownKey
5307                | Problem::RateLimited
5308                | Problem::AtCapacity
5309                | Problem::UnknownTool
5310                | Problem::InvalidArguments
5311                | Problem::Invalid(_)
5312                | Problem::Store(_)
5313                | Problem::Tenant(_) => {}
5314            }
5315        }
5316        let invalid = [
5317            Invalid::BadGzip,
5318            Invalid::NotJson,
5319            Invalid::DuplicateMember,
5320            Invalid::AmbiguousForm,
5321            Invalid::NoForm,
5322            Invalid::MissingUuid,
5323            Invalid::BadUuid,
5324            Invalid::MissingCreatedAt,
5325            Invalid::BadPayload,
5326            Invalid::UuidMismatch,
5327            Invalid::BadCritical,
5328            Invalid::UnsupportedExtension,
5329            Invalid::TooDeep,
5330            Invalid::Other,
5331        ];
5332        for kind in invalid {
5333            match kind {
5334                Invalid::BadGzip
5335                | Invalid::NotJson
5336                | Invalid::DuplicateMember
5337                | Invalid::AmbiguousForm
5338                | Invalid::NoForm
5339                | Invalid::MissingUuid
5340                | Invalid::BadUuid
5341                | Invalid::MissingCreatedAt
5342                | Invalid::BadPayload
5343                | Invalid::UuidMismatch
5344                | Invalid::BadCritical
5345                | Invalid::UnsupportedExtension
5346                | Invalid::TooDeep
5347                | Invalid::Other => all.push(Problem::Invalid(kind)),
5348            }
5349        }
5350        let store = [
5351            StoreError::Conflict,
5352            StoreError::Gone,
5353            StoreError::NotFound,
5354            StoreError::NotDeleted,
5355            StoreError::PreconditionFailed,
5356            StoreError::Immutable,
5357            StoreError::LimitReached,
5358            StoreError::Damaged,
5359            StoreError::AuditFailed,
5360            StoreError::Io,
5361        ];
5362        for error in store {
5363            match error {
5364                StoreError::Conflict
5365                | StoreError::Gone
5366                | StoreError::NotFound
5367                | StoreError::NotDeleted
5368                | StoreError::PreconditionFailed
5369                | StoreError::Immutable
5370                | StoreError::LimitReached
5371                | StoreError::Damaged
5372                | StoreError::AuditFailed
5373                | StoreError::Io => all.push(Problem::Store(error)),
5374            }
5375        }
5376        let tenant = [
5377            TenantError::NotFound,
5378            TenantError::NameTaken,
5379            TenantError::BadName,
5380            TenantError::HoldsVcons,
5381            TenantError::UnderHold,
5382            TenantError::LimitReached,
5383            TenantError::AuditFailed,
5384            TenantError::Closing,
5385            TenantError::CliOnly,
5386            TenantError::BadScopes,
5387            TenantError::BadExpiry,
5388            TenantError::BadSetting(crate::settings::SettingError::UnknownName),
5389            TenantError::WrongKey,
5390            TenantError::Io,
5391        ];
5392        for error in tenant {
5393            match error {
5394                TenantError::NotFound
5395                | TenantError::NameTaken
5396                | TenantError::BadName
5397                | TenantError::HoldsVcons
5398                | TenantError::UnderHold
5399                | TenantError::LimitReached
5400                | TenantError::AuditFailed
5401                | TenantError::Closing
5402                | TenantError::CliOnly
5403                | TenantError::BadScopes
5404                | TenantError::BadExpiry
5405                | TenantError::BadSetting(_)
5406                | TenantError::WrongKey
5407                | TenantError::Io => all.push(Problem::Tenant(error)),
5408            }
5409        }
5410        all
5411    }
5412
5413    fn pages() -> PathBuf {
5414        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../website/content/problems")
5415    }
5416
5417    #[test]
5418    fn every_problem_type_has_its_page_with_its_status_and_title() {
5419        for problem in every_problem() {
5420            let (name, title) = problem.name();
5421            let page = pages().join(format!("{name}.md"));
5422            let text = std::fs::read_to_string(&page)
5423                .unwrap_or_else(|e| panic!("{problem:?}: {}: {e}", page.display()));
5424            let status = problem.status().as_u16();
5425            for line in [
5426                format!("title = \"{name}\""),
5427                format!("status = {status}"),
5428                format!("problem_title = \"{title}\""),
5429            ] {
5430                assert!(
5431                    text.lines().any(|l| l == line),
5432                    "{}: no line `{line}`",
5433                    page.display()
5434                );
5435            }
5436        }
5437    }
5438
5439    /// No page outlives its problem type.
5440    #[test]
5441    fn every_problem_page_is_a_problem_type() {
5442        let names: BTreeSet<String> = every_problem()
5443            .into_iter()
5444            .map(|p| p.name().0.to_owned())
5445            .collect();
5446        let pages: BTreeSet<String> = std::fs::read_dir(pages())
5447            .expect("the problem pages")
5448            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
5449            .filter(|f| f != "_index.md")
5450            .map(|f| f.strip_suffix(".md").unwrap_or(&f).to_owned())
5451            .collect();
5452        assert_eq!(pages, names);
5453    }
5454
5455    /// The `application/vcon` media types `text` names, each with the
5456    /// `+suffix` that follows it, if any.
5457    fn vcon_media_types(text: &str) -> Vec<&str> {
5458        const NAME: &str = "application/vcon";
5459        let mut found = Vec::new();
5460        let mut rest = text;
5461        while let Some(at) = rest.find(NAME) {
5462            let from = &rest[at..];
5463            let end = from[NAME.len()..]
5464                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '+' || c == '-'))
5465                .map_or(from.len(), |n| NAME.len() + n);
5466            found.push(&from[..end]);
5467            rest = &from[end..];
5468        }
5469        found
5470    }
5471
5472    #[test]
5473    fn the_media_type_reader_takes_each_name_with_its_suffix() {
5474        assert_eq!(
5475            vcon_media_types(
5476                "Send `application/vcon`, or \"application/vcon+gzip\"; not application/vcon+json."
5477            ),
5478            [
5479                "application/vcon",
5480                "application/vcon+gzip",
5481                "application/vcon+json"
5482            ],
5483            "each name ends where its suffix does"
5484        );
5485        assert!(
5486            vcon_media_types("application/json and text/plain").is_empty(),
5487            "other media types are not read"
5488        );
5489    }
5490
5491    /// Every Markdown file under `dir`.
5492    fn markdown_under(dir: &std::path::Path, found: &mut Vec<PathBuf>) {
5493        for entry in std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) {
5494            let path = entry.expect("entry").path();
5495            if path.is_dir() {
5496                markdown_under(&path, found);
5497            } else if path.extension().is_some_and(|ext| ext == "md") {
5498                found.push(path);
5499            }
5500        }
5501    }
5502
5503    /// A reader copies a media type from an example into a request. One the
5504    /// API does not take would be refused with `unsupported-media-type`.
5505    /// Found on 0.4.2: the `vcon` crate's README and the library page passed
5506    /// `application/vcon+json`, which the vCon draft does not register.
5507    #[test]
5508    fn every_vcon_media_type_the_pages_name_is_one_the_api_takes() {
5509        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
5510        let mut files = vec![
5511            root.join("README.md"),
5512            root.join("crates/vcon/README.md"),
5513            root.join("crates/vcon-server/README.md"),
5514            root.join("website/static/llms.txt"),
5515        ];
5516        markdown_under(&root.join("website/content"), &mut files);
5517        assert!(
5518            files.iter().any(|f| f.ends_with("docs/library.md")),
5519            "the walk reached the docs pages"
5520        );
5521        let mut named = 0;
5522        let mut refused = Vec::new();
5523        for file in &files {
5524            let text =
5525                std::fs::read_to_string(file).unwrap_or_else(|e| panic!("{}: {e}", file.display()));
5526            for media_type in vcon_media_types(&text) {
5527                named += 1;
5528                if !is_vcon_media_type(media_type) {
5529                    refused.push(format!("{}: {media_type}", file.display()));
5530                }
5531            }
5532        }
5533        assert!(
5534            named > 10,
5535            "the reader found the pages' media types: {named}"
5536        );
5537        assert!(
5538            refused.is_empty(),
5539            "the pages name media types the API refuses: {refused:#?}"
5540        );
5541    }
5542}
5543
5544/// Reading the description, for the tests that hold it to the code.
5545#[cfg(test)]
5546mod description {
5547    use std::sync::OnceLock;
5548
5549    use serde_json::Value;
5550
5551    fn parsed() -> &'static Value {
5552        static PARSED: OnceLock<Value> = OnceLock::new();
5553        PARSED.get_or_init(|| serde_json::from_str(super::OPENAPI).expect("openapi.json is JSON"))
5554    }
5555
5556    /// Whether the description lists `status` for `method` on `route`, a
5557    /// route template as the router writes it. The router's `{*name}`, the
5558    /// rest of a path, is OpenAPI's `{name}`.
5559    pub(super) fn lists(method: &str, route: &str, status: u16) -> bool {
5560        let path = route.replace("{*", "{");
5561        parsed()["paths"][path.as_str()][method.to_ascii_lowercase()]["responses"]
5562            .get(status.to_string())
5563            .is_some()
5564    }
5565
5566    /// Whether the operation needs a key: it does unless it says
5567    /// `security: []`, or names a way that is not the bearer key, as the
5568    /// session routes do.
5569    pub(super) fn keyed(method: &str, path: &str) -> bool {
5570        parsed()["paths"][path][method.to_ascii_lowercase()]["security"]
5571            .as_array()
5572            .is_none_or(|ways| ways.iter().any(|way| way.get("bearer").is_some()))
5573    }
5574
5575    /// Every path and its methods, as the description names them.
5576    pub(super) fn operations() -> Vec<(String, String)> {
5577        let mut all = Vec::new();
5578        for (path, item) in parsed()["paths"].as_object().expect("paths") {
5579            for method in item.as_object().expect("a path item").keys() {
5580                if ["get", "put", "post", "delete", "patch"].contains(&method.as_str()) {
5581                    all.push((method.to_ascii_uppercase(), path.clone()));
5582                }
5583            }
5584        }
5585        all
5586    }
5587
5588    pub(super) fn document() -> &'static Value {
5589        parsed()
5590    }
5591}
5592
5593/// The description against the code: the published copy, the version, the
5594/// problem types and every route and method. Statuses are checked on every
5595/// answer the unit tests produce, in `log_request`.
5596#[cfg(test)]
5597mod openapi_description {
5598    use std::collections::BTreeSet;
5599
5600    use reqwest::Method;
5601
5602    use super::description::{document, keyed, lists, operations};
5603    use super::site_pages::every_problem;
5604    use super::tests::pipeline::server;
5605    use super::*;
5606
5607    #[test]
5608    fn the_website_publishes_the_compiled_description() {
5609        let published = std::fs::read_to_string(format!(
5610            "{}/../../website/static/openapi.json",
5611            env!("CARGO_MANIFEST_DIR")
5612        ))
5613        .expect("the website's copy");
5614        assert!(published == OPENAPI, "website/static/openapi.json differs");
5615    }
5616
5617    #[test]
5618    fn it_is_openapi_3_1_for_this_version() {
5619        let doc = document();
5620        assert!(
5621            doc["openapi"]
5622                .as_str()
5623                .is_some_and(|v| v.starts_with("3.1.")),
5624            "{}",
5625            doc["openapi"]
5626        );
5627        assert_eq!(doc["info"]["version"], env!("CARGO_PKG_VERSION"));
5628        assert!(doc["info"]["title"].as_str().is_some_and(|t| !t.is_empty()));
5629    }
5630
5631    #[test]
5632    fn its_problem_types_are_the_ones_the_api_answers() {
5633        let described: BTreeSet<String> =
5634            document()["components"]["schemas"]["Problem"]["properties"]["type"]["enum"]
5635                .as_array()
5636                .expect("the Problem type list")
5637                .iter()
5638                .map(|t| t.as_str().expect("a URL").to_owned())
5639                .collect();
5640        let answered: BTreeSet<String> = every_problem()
5641            .into_iter()
5642            .map(|p| format!("https://vcon-server.com/problems/{}", p.name().0))
5643            .collect();
5644        assert_eq!(described, answered);
5645    }
5646
5647    /// A path template with sample values, so it reaches its route.
5648    fn concrete(path: &str) -> String {
5649        path.replace("{uuid}", "01a07da8-c2bb-83e5-b9a2-279e0d16bc46")
5650            .replace("{version}", "00112233445566778899aabbccddeeff")
5651            .replace("{id}", "00112233445566778899aabbccddeeff")
5652            .replace("{other}", "no-such-file")
5653    }
5654
5655    /// Every operation the description names is routed (one that needs a
5656    /// key asks for it; one that needs none answers a status it lists), and
5657    /// every other method on its paths is not (405).
5658    #[tokio::test]
5659    async fn every_described_route_is_routed_and_no_other_method() {
5660        let s = server().await;
5661        let described: BTreeSet<(String, String)> = operations().into_iter().collect();
5662        assert!(!described.is_empty());
5663        let paths: BTreeSet<&String> = described.iter().map(|(_, p)| p).collect();
5664        for path in paths {
5665            for method in ["GET", "POST", "PUT", "PATCH", "DELETE"] {
5666                // Not following redirects, so each answer is the route's own.
5667                let answer = s
5668                    .client_not_following()
5669                    .request(
5670                        Method::from_bytes(method.as_bytes()).expect("a method"),
5671                        s.url(&concrete(path)),
5672                    )
5673                    .send()
5674                    .await
5675                    .expect("an answer");
5676                let status = answer.status().as_u16();
5677                if !described.contains(&(method.to_owned(), path.clone())) {
5678                    assert_eq!(status, 405, "{method} {path}");
5679                } else if keyed(method, path) {
5680                    assert_eq!(status, 401, "{method} {path}");
5681                } else {
5682                    assert!(lists(method, path, status), "{method} {path}: {status}");
5683                }
5684            }
5685        }
5686    }
5687}