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::NoFileBackup | TenantError::Io => {
1563                    StatusCode::INTERNAL_SERVER_ERROR
1564                }
1565            },
1566        }
1567    }
1568
1569    /// The last part of its type URI, and its title.
1570    pub(crate) fn name(self) -> (&'static str, &'static str) {
1571        match self {
1572            Problem::Unauthorized => ("unauthorized", "A valid bearer key is needed"),
1573            Problem::Forbidden => ("forbidden", "The key does not allow this"),
1574            Problem::WrongListener => (
1575                "wrong-listener",
1576                "This listener does not serve this kind of key",
1577            ),
1578            Problem::KeyAndSession => (
1579                "key-and-session",
1580                "The request carries both a key and a session cookie",
1581            ),
1582            Problem::NoSession => ("no-session", "A live session is needed"),
1583            Problem::KeyExpired => ("key-expired", "The key has expired"),
1584            Problem::BadOrigin => (
1585                "bad-origin",
1586                "The request does not come from this listener's own pages",
1587            ),
1588            Problem::BadCsrf => ("bad-csrf", "The session's CSRF token is missing or wrong"),
1589            Problem::TooLarge => ("too-large", "The body is over the size limit"),
1590            Problem::Timeout => ("timeout", "The body did not arrive in time"),
1591            Problem::BadBody => ("bad-body", "The body could not be read"),
1592            Problem::BadPathUuid => (
1593                "bad-path-uuid",
1594                "The path's uuid is not in RFC 9562 text form",
1595            ),
1596            Problem::BadPathVersion => {
1597                ("bad-path-version", "The path's version is not a version id")
1598            }
1599            Problem::PreconditionRequired => (
1600                "precondition-required",
1601                "If-Match must name the current version",
1602            ),
1603            Problem::PathUuidMismatch => (
1604                "path-uuid-mismatch",
1605                "The body's uuid is not the one in the path",
1606            ),
1607            Problem::Unavailable => ("unavailable", "The service cannot answer now"),
1608            Problem::AuditFailed => ("audit-failed", "The audit record could not be written"),
1609            Problem::UnsupportedMediaType => {
1610                ("unsupported-media-type", "This media type is not taken")
1611            }
1612            Problem::Invalid(invalid) => match invalid {
1613                Invalid::BadGzip => ("bad-gzip", "The body is marked gzip but is not"),
1614                Invalid::NotJson => ("not-json", "The body is not one JSON object"),
1615                Invalid::DuplicateMember => ("duplicate-member", "An object repeats a member"),
1616                Invalid::AmbiguousForm => {
1617                    ("ambiguous-form", "The body is both signed and encrypted")
1618                }
1619                Invalid::NoForm => ("no-form", "The body is in no vCon form"),
1620                Invalid::MissingUuid => ("missing-uuid", "The vCon has no uuid"),
1621                Invalid::BadUuid => ("bad-uuid", "The uuid is not in RFC 9562 text form"),
1622                Invalid::MissingCreatedAt => ("missing-created-at", "The vCon has no created_at"),
1623                Invalid::BadPayload => ("bad-payload", "The signed payload cannot be read"),
1624                Invalid::UuidMismatch => ("uuid-mismatch", "A signature names another uuid"),
1625                Invalid::BadCritical => (
1626                    "bad-critical",
1627                    "critical or must_support is not a list of names",
1628                ),
1629                Invalid::UnsupportedExtension => (
1630                    "unsupported-extension",
1631                    "An extension the vCon needs is not supported",
1632                ),
1633                Invalid::TooDeep => ("too-deep", "The body nests too deeply"),
1634                Invalid::Other => ("not-a-vcon", "The body is not a vCon this server can read"),
1635            },
1636            Problem::Store(error) => match error {
1637                StoreError::Conflict => ("conflict", "Another vCon holds the uuid"),
1638                StoreError::Gone => ("gone", "The vCon was deleted or purged"),
1639                StoreError::NotFound => ("not-found", "No vCon has the uuid"),
1640                StoreError::NotDeleted => ("not-deleted", "The vCon is not deleted"),
1641                StoreError::PreconditionFailed => (
1642                    "precondition-failed",
1643                    "If-Match does not name the current version",
1644                ),
1645                StoreError::Immutable => {
1646                    ("immutable", "A signed or encrypted vCon is not replaced")
1647                }
1648                StoreError::LimitReached => ("limit-reached", "The tenant key must be rotated"),
1649                StoreError::Damaged => ("damaged", "A stored version is damaged"),
1650                StoreError::AuditFailed => {
1651                    ("audit-failed", "The audit record could not be written")
1652                }
1653                StoreError::Io => ("internal", "The server failed"),
1654            },
1655            Problem::BadQuery => ("bad-query", "The query is not one this route takes"),
1656            Problem::RateLimited => ("rate-limited", "Too many tool calls from this key"),
1657            Problem::AtCapacity => ("at-capacity", "Too many tool calls are running"),
1658            Problem::UnknownTool => ("unknown-tool", "No tool has the name"),
1659            Problem::InvalidArguments => ("invalid-arguments", "The arguments do not fit the tool"),
1660            Problem::UnknownKey => ("unknown-key", "No key has the id"),
1661            Problem::InvalidBody | Problem::Tenant(TenantError::BadName) => {
1662                ("invalid-body", "The body is not one this route takes")
1663            }
1664            Problem::Tenant(error) => match error {
1665                TenantError::NotFound => ("unknown-tenant", "No tenant has the id"),
1666                TenantError::NameTaken => ("name-taken", "Another tenant has the name"),
1667                TenantError::HoldsVcons => (
1668                    "holds-vcons",
1669                    "The tenant holds vCons; removing them needs force",
1670                ),
1671                TenantError::UnderHold => {
1672                    ("under-hold", "A vCon of the tenant is under a legal hold")
1673                }
1674                TenantError::BadScopes => ("bad-scopes", "A tenant key cannot hold these scopes"),
1675                TenantError::BadExpiry => ("bad-expiry", "A key cannot have this expiry"),
1676                TenantError::BadSetting(_) => (
1677                    "bad-setting",
1678                    "A setting's name or value is not one a tenant may set",
1679                ),
1680                TenantError::CliOnly => ("forbidden", "The key does not allow this"),
1681                TenantError::LimitReached => ("master-key-limit", "The master key must be rotated"),
1682                TenantError::AuditFailed => {
1683                    ("audit-failed", "The audit record could not be written")
1684                }
1685                TenantError::Closing => ("unavailable", "The service cannot answer now"),
1686                TenantError::BadName
1687                | TenantError::WrongKey
1688                | TenantError::NoFileBackup
1689                | TenantError::Io => ("internal", "The server failed"),
1690            },
1691        }
1692    }
1693}
1694
1695impl Problem {
1696    /// The problem document (RFC 9457): its type, title and status. The
1697    /// HTTP API answers it, and an MCP refusal carries it as its data.
1698    pub(crate) fn document(self) -> serde_json::Value {
1699        let (name, title) = self.name();
1700        serde_json::json!({
1701            "type": format!("https://vcon-server.com/problems/{name}"),
1702            "title": title,
1703            "status": self.status().as_u16(),
1704        })
1705    }
1706}
1707
1708impl IntoResponse for Problem {
1709    fn into_response(self) -> Response {
1710        let (status, body) = (self.status(), self.document());
1711        let mut answer = (
1712            status,
1713            [(CONTENT_TYPE, "application/problem+json")],
1714            body.to_string(),
1715        )
1716            .into_response();
1717        // A 401 names what the route takes: a key, or a session.
1718        let challenge = match self {
1719            Problem::Unauthorized | Problem::KeyExpired => Some("Bearer"),
1720            Problem::NoSession => Some("Session"),
1721            _ => None,
1722        };
1723        if let Some(challenge) = challenge {
1724            answer
1725                .headers_mut()
1726                .insert(WWW_AUTHENTICATE, HeaderValue::from_static(challenge));
1727        }
1728        answer
1729    }
1730}
1731
1732/// Why the TLS configuration could not be made.
1733#[derive(Debug)]
1734pub enum TlsError {
1735    /// The certificate file could not be read, or holds no certificate.
1736    Certificate,
1737    /// The key file could not be read, or holds no key.
1738    Key,
1739    /// The key file breaks the secret-file rule or cannot be opened; the
1740    /// text names the configuration key, the file and the fix.
1741    KeyFile(String),
1742    /// rustls refused the pair, for instance a key that is not the
1743    /// certificate's.
1744    Refused(rustls::Error),
1745}
1746
1747/// The server's TLS configuration from a PEM certificate chain and a PEM
1748/// private key, the files `tls.cert` and `tls.key` name.
1749pub fn tls_config(certificate: &Path, key: &Path) -> Result<Arc<ServerConfig>, TlsError> {
1750    tls_config_named(certificate, key, "tls.key")
1751}
1752
1753/// [`tls_config`], for a key file that the configuration key `named`
1754/// names, so a refusal of the file says which key to look at.
1755pub fn tls_config_named(
1756    certificate: &Path,
1757    key: &Path,
1758    named: &str,
1759) -> Result<Arc<ServerConfig>, TlsError> {
1760    let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(certificate)
1761        .map_err(|_| TlsError::Certificate)?
1762        .collect::<Result<_, _>>()
1763        .map_err(|_| TlsError::Certificate)?;
1764    if chain.is_empty() {
1765        return Err(TlsError::Certificate);
1766    }
1767    let bytes = crate::secret_file::read(key, named).map_err(TlsError::KeyFile)?;
1768    let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|_| TlsError::Key)?;
1769    let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
1770    let mut config = ServerConfig::builder_with_provider(provider)
1771        .with_safe_default_protocol_versions()
1772        .map_err(TlsError::Refused)?
1773        .with_no_client_auth()
1774        .with_single_cert(chain, key)
1775        .map_err(TlsError::Refused)?;
1776    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
1777    Ok(Arc::new(config))
1778}
1779
1780#[cfg(test)]
1781mod tests {
1782    use std::net::SocketAddr;
1783    use std::path::PathBuf;
1784
1785    use axum::routing::get;
1786    use tokio::net::TcpListener;
1787
1788    use super::*;
1789
1790    /// A self-signed certificate for localhost and its key, as PEM files.
1791    struct Certificate {
1792        _dir: tempfile::TempDir,
1793        cert: PathBuf,
1794        key: PathBuf,
1795        pem: String,
1796    }
1797
1798    fn certificate() -> Certificate {
1799        let dir = tempfile::tempdir().expect("temp dir");
1800        let made = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()])
1801            .expect("a certificate");
1802        let pem = made.cert.pem();
1803        let (cert, key) = (dir.path().join("cert.pem"), dir.path().join("key.pem"));
1804        std::fs::write(&cert, &pem).expect("write");
1805        std::fs::write(&key, made.signing_key.serialize_pem()).expect("write");
1806        std::fs::set_permissions(
1807            &key,
1808            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
1809        )
1810        .expect("chmod 0600");
1811        Certificate {
1812            _dir: dir,
1813            cert,
1814            key,
1815            pem,
1816        }
1817    }
1818
1819    fn client(c: &Certificate, addr: SocketAddr) -> reqwest::Client {
1820        reqwest::Client::builder()
1821            .tls_certs_only([reqwest::Certificate::from_pem(c.pem.as_bytes()).expect("pem")])
1822            .resolve("localhost", addr)
1823            .no_proxy()
1824            .build()
1825            .expect("a client")
1826    }
1827
1828    #[tokio::test]
1829    async fn the_listener_speaks_tls_only() {
1830        let c = certificate();
1831        let tls = tls_config(&c.cert, &c.key).expect("loads");
1832        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
1833        let addr = listener.local_addr().expect("addr");
1834        let app = Router::new().route("/ping", get(|| async { "pong" }));
1835        let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
1836        let server = tokio::spawn(serve(listener, tls, app, async {
1837            stopped.await.ok();
1838        }));
1839        let plain = reqwest::Client::builder()
1840            .no_proxy()
1841            .build()
1842            .expect("a client")
1843            .get(format!("http://{addr}/ping"))
1844            .send()
1845            .await;
1846        assert!(plain.is_err(), "plain HTTP is not served: {plain:?}");
1847        let answer = client(&c, addr)
1848            .get(format!("https://localhost:{}/ping", addr.port()))
1849            .send()
1850            .await
1851            .expect("TLS is served, after a plain-HTTP attempt too");
1852        assert_eq!(answer.status(), 200);
1853        assert_eq!(answer.version(), reqwest::Version::HTTP_2, "h2 by ALPN");
1854        assert_eq!(answer.text().await.expect("body"), "pong");
1855        stop.send(()).expect("stop");
1856        server.await.expect("joins").expect("serves");
1857    }
1858
1859    #[test]
1860    fn a_missing_or_unusable_certificate_or_key_is_refused() {
1861        let c = certificate();
1862        let other = certificate();
1863        let dir = tempfile::tempdir().expect("temp dir");
1864        let (missing, empty) = (dir.path().join("missing"), dir.path().join("empty"));
1865        std::fs::write(&empty, "").expect("write");
1866        std::fs::set_permissions(
1867            &empty,
1868            <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
1869        )
1870        .expect("chmod 0600");
1871        assert!(matches!(
1872            tls_config(&missing, &c.key),
1873            Err(TlsError::Certificate)
1874        ));
1875        assert!(matches!(
1876            tls_config(&empty, &c.key),
1877            Err(TlsError::Certificate)
1878        ));
1879        assert!(
1880            matches!(tls_config(&c.cert, &missing), Err(TlsError::KeyFile(t)) if t.starts_with(&format!("tls.key {}: No such file", missing.display()))),
1881            "a missing key file is named with the key and the path"
1882        );
1883        assert!(matches!(tls_config(&c.cert, &empty), Err(TlsError::Key)));
1884        assert!(matches!(
1885            tls_config(&c.cert, &other.key),
1886            Err(TlsError::Refused(_))
1887        ));
1888        assert!(tls_config(&c.cert, &c.key).is_ok());
1889    }
1890
1891    pub(crate) mod pipeline {
1892        use std::net::SocketAddr;
1893
1894        use serde_json::Value;
1895        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1896
1897        use super::*;
1898        use crate::access::{Scope, Scopes};
1899        use crate::audit::Actor;
1900        use crate::clock::Clock;
1901        use crate::envelope::Key;
1902        use crate::fs::OsFs;
1903        use crate::ids::TenantId;
1904
1905        pub(crate) const LIMIT: usize = 64 * 1024;
1906
1907        /// The time every test server starts at.
1908        pub(crate) const START: time::OffsetDateTime =
1909            time::macros::datetime!(2026-10-23 12:00 UTC);
1910
1911        /// The test servers' clock. It starts at START, and each reading
1912        /// moves it on by a microsecond, so times read one after another are
1913        /// in order and differ, as on a real clock, but no answer depends on
1914        /// when a test runs. A test may set it.
1915        pub(crate) struct TestClock(std::sync::Mutex<time::OffsetDateTime>);
1916
1917        impl TestClock {
1918            pub(crate) fn set(&self, now: time::OffsetDateTime) {
1919                *self.0.lock().expect("clock") = now;
1920            }
1921        }
1922
1923        impl Clock for TestClock {
1924            fn now(&self) -> time::OffsetDateTime {
1925                let mut next = self.0.lock().expect("clock");
1926                let now = *next;
1927                *next += time::Duration::MICROSECOND;
1928                now
1929            }
1930        }
1931
1932        /// A server with one tenant, on a free port. Its registry and stores
1933        /// read the time from `clock`.
1934        pub(crate) struct Server {
1935            _dir: tempfile::TempDir,
1936            certificate: Certificate,
1937            addr: SocketAddr,
1938            pub(crate) clock: Arc<TestClock>,
1939            pub(crate) tenants: Arc<Tenants>,
1940            pub(crate) app: Arc<App>,
1941            pub(crate) tenant: TenantId,
1942            stop: Option<tokio::sync::oneshot::Sender<()>>,
1943        }
1944
1945        impl Drop for Server {
1946            fn drop(&mut self) {
1947                if let Some(stop) = self.stop.take() {
1948                    let _ = stop.send(());
1949                }
1950            }
1951        }
1952
1953        pub(crate) async fn server() -> Server {
1954            server_with(&[]).await
1955        }
1956
1957        /// A server that supports the must_support extensions named.
1958        pub(crate) async fn server_with(supported: &[&str]) -> Server {
1959            server_from(supported, Retention::Years(7)).await
1960        }
1961
1962        /// A server whose tenants that set no retention period keep
1963        /// vCons for `default`.
1964        pub(crate) async fn server_keeping(default: Retention) -> Server {
1965            server_from(&[], default).await
1966        }
1967
1968        /// A server whose listener is of `plane`.
1969        pub(crate) async fn server_on(plane: Plane) -> Server {
1970            server_of(&[], Retention::Years(7), plane).await
1971        }
1972
1973        async fn server_from(supported: &[&str], retention_default: Retention) -> Server {
1974            server_of(supported, retention_default, Plane::Both).await
1975        }
1976
1977        async fn server_of(
1978            supported: &[&str],
1979            retention_default: Retention,
1980            plane: Plane,
1981        ) -> Server {
1982            server_built(supported, retention_default, plane, ReportLimits::DEFAULT).await
1983        }
1984
1985        /// A server that takes the reports `reports` allows.
1986        pub(crate) async fn server_limiting(reports: ReportLimits) -> Server {
1987            server_built(&[], Retention::Years(7), Plane::Both, reports).await
1988        }
1989
1990        /// A server whose listener has no public origin, so it serves no
1991        /// session.
1992        pub(crate) async fn server_without_origin() -> Server {
1993            let reports = ReportLimits::DEFAULT;
1994            server_made(&[], Retention::Years(7), Plane::Both, reports, false).await
1995        }
1996
1997        async fn server_built(
1998            supported: &[&str],
1999            retention_default: Retention,
2000            plane: Plane,
2001            reports: ReportLimits,
2002        ) -> Server {
2003            server_made(supported, retention_default, plane, reports, true).await
2004        }
2005
2006        /// The server every other maker here makes. With `origin`, its
2007        /// public origin is the address its clients reach it at.
2008        async fn server_made(
2009            supported: &[&str],
2010            retention_default: Retention,
2011            plane: Plane,
2012            reports: ReportLimits,
2013            origin: bool,
2014        ) -> Server {
2015            let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
2016            let addr = listener.local_addr().expect("addr");
2017            let origin = origin.then(|| {
2018                crate::session::Origin::parse(&format!("https://localhost:{}", addr.port()))
2019                    .expect("an origin")
2020            });
2021            let dir = tempfile::tempdir().expect("temp dir");
2022            let clock = Arc::new(TestClock(std::sync::Mutex::new(START)));
2023            let tenants = Arc::new(
2024                Tenants::open(
2025                    dir.path(),
2026                    Key::generate().expect("master key"),
2027                    Arc::new(OsFs),
2028                    clock.clone(),
2029                )
2030                .expect("opens"),
2031            );
2032            let tenant = tenants.create(Actor::Cli, "acme", None).expect("a tenant");
2033            let app = Arc::new(App {
2034                tenants: tenants.clone(),
2035                limits: Limits {
2036                    body: LIMIT,
2037                    inflated: 1 << 20,
2038                    body_timeout: Duration::from_millis(300),
2039                },
2040                supported: supported.iter().map(|s| (*s).to_owned()).collect(),
2041                retention_default,
2042                mcp: crate::mcp::Limits::DEFAULT,
2043                plane,
2044                reports: ReportGate::new(reports),
2045                origin,
2046            });
2047            let certificate = certificate();
2048            let tls = tls_config(&certificate.cert, &certificate.key).expect("tls");
2049            let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
2050            tokio::spawn(serve(listener, tls, router(app.clone()), async {
2051                stopped.await.ok();
2052            }));
2053            Server {
2054                _dir: dir,
2055                certificate,
2056                addr,
2057                clock,
2058                tenants,
2059                app,
2060                tenant,
2061                stop: Some(stop),
2062            }
2063        }
2064
2065        impl Server {
2066            pub(crate) fn dir(&self) -> &std::path::Path {
2067                self._dir.path()
2068            }
2069
2070            pub(crate) fn url(&self, path: &str) -> String {
2071                format!("https://localhost:{}{path}", self.addr.port())
2072            }
2073
2074            pub(crate) fn client(&self) -> reqwest::Client {
2075                client(&self.certificate, self.addr)
2076            }
2077
2078            /// A client that shows a redirect instead of following it.
2079            pub(crate) fn client_not_following(&self) -> reqwest::Client {
2080                let pem = self.certificate.pem.as_bytes();
2081                reqwest::Client::builder()
2082                    .tls_certs_only([reqwest::Certificate::from_pem(pem).expect("pem")])
2083                    .resolve("localhost", self.addr)
2084                    .no_proxy()
2085                    .redirect(reqwest::redirect::Policy::none())
2086                    .build()
2087                    .expect("a client")
2088            }
2089
2090            pub(crate) fn key(&self, scopes: &[Scope]) -> String {
2091                self.tenants
2092                    .create_key(Actor::Cli, Some(self.tenant), Scopes::of(scopes), "test")
2093                    .expect("a key")
2094                    .token
2095            }
2096
2097            pub(crate) fn tenant_log(&self, action: &str) -> Vec<Value> {
2098                let store = self.tenants.store(self.tenant).expect("its store");
2099                store
2100                    .records()
2101                    .into_iter()
2102                    .filter(|r| r["action"] == action)
2103                    .collect()
2104            }
2105
2106            /// Sends a POST /vcons over HTTP/1.1 with a chunked body: the
2107            /// chunks given, and then, unless `finish`, nothing more while
2108            /// the connection stays open. Returns the status line.
2109            async fn chunked(&self, token: &str, chunks: &[usize], finish: bool) -> String {
2110                let mut body = String::new();
2111                for &size in chunks {
2112                    body.push_str(&format!("{size:x}\r\n{}\r\n", "x".repeat(size)));
2113                }
2114                if finish {
2115                    body.push_str("0\r\n\r\n");
2116                }
2117                self.raw(token, "transfer-encoding: chunked", body.as_bytes())
2118                    .await
2119            }
2120
2121            /// Sends a POST /vcons over HTTP/1.1 with one header of the
2122            /// caller's and the bytes given, keeping the connection open.
2123            /// Returns the status line.
2124            async fn raw(&self, token: &str, header: &str, body: &[u8]) -> String {
2125                let head = format!(
2126                    "POST /vcons HTTP/1.1\r\nhost: localhost\r\nauthorization: Bearer {token}\r\n\
2127                     content-type: application/vcon\r\n{header}\r\n\r\n"
2128                );
2129                self.raw_request(&head, body).await
2130            }
2131
2132            /// Sends a request head as written, then the bytes given, over
2133            /// HTTP/1.1, keeping the connection open. Returns the status
2134            /// line.
2135            pub(crate) async fn raw_request(&self, head: &str, body: &[u8]) -> String {
2136                let mut roots = rustls::RootCertStore::empty();
2137                for cert in CertificateDer::pem_slice_iter(self.certificate.pem.as_bytes()) {
2138                    roots.add(cert.expect("pem")).expect("a root");
2139                }
2140                let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
2141                let mut config = rustls::ClientConfig::builder_with_provider(provider)
2142                    .with_safe_default_protocol_versions()
2143                    .expect("versions")
2144                    .with_root_certificates(roots)
2145                    .with_no_client_auth();
2146                config.alpn_protocols = vec![b"http/1.1".to_vec()];
2147                let tcp = tokio::net::TcpStream::connect(self.addr)
2148                    .await
2149                    .expect("connect");
2150                let mut tls = tokio_rustls::TlsConnector::from(Arc::new(config))
2151                    .connect("localhost".try_into().expect("name"), tcp)
2152                    .await
2153                    .expect("handshake");
2154                tls.write_all(head.as_bytes()).await.expect("head");
2155                // The server may answer and stop reading before all is sent.
2156                let _ = tls.write_all(body).await;
2157                let mut answer = vec![0; 4096];
2158                let read = tokio::time::timeout(Duration::from_secs(10), tls.read(&mut answer))
2159                    .await
2160                    .expect("an answer while the body is still open")
2161                    .expect("read");
2162                let answer = String::from_utf8_lossy(&answer[..read]).into_owned();
2163                answer.lines().next().unwrap_or_default().to_owned()
2164            }
2165        }
2166
2167        async fn post(s: &Server, token: Option<&str>, body: Vec<u8>) -> reqwest::Response {
2168            let mut request = s
2169                .client()
2170                .post(s.url("/vcons"))
2171                .header("content-type", "application/vcon")
2172                .body(body);
2173            if let Some(token) = token {
2174                request = request.bearer_auth(token);
2175            }
2176            request.send().await.expect("an answer")
2177        }
2178
2179        /// Checks the answer is a problem document for its status, and
2180        /// returns its type's last part.
2181        pub(crate) async fn problem(answer: reqwest::Response) -> String {
2182            assert_eq!(
2183                answer.headers()["content-type"],
2184                "application/problem+json",
2185                "{answer:?}"
2186            );
2187            let status = answer.status().as_u16();
2188            let body: Value =
2189                serde_json::from_str(&answer.text().await.expect("text")).expect("JSON");
2190            assert_eq!(body["status"], status);
2191            assert!(body["title"].as_str().is_some_and(|t| !t.is_empty()));
2192            body["type"]
2193                .as_str()
2194                .and_then(|t| t.strip_prefix("https://vcon-server.com/problems/"))
2195                .expect("a type under the server's domain")
2196                .to_owned()
2197        }
2198
2199        #[tokio::test]
2200        async fn a_request_without_a_valid_key_is_unauthorized() {
2201            let s = server().await;
2202            for token in [None, Some("vcs_nonsense")] {
2203                let answer = post(&s, token, b"{}".to_vec()).await;
2204                let sent = if token.is_some() {
2205                    "a bad key"
2206                } else {
2207                    "no key"
2208                };
2209                assert_eq!(answer.status(), 401, "{sent}");
2210                assert_eq!(answer.headers()["www-authenticate"], "Bearer");
2211                assert_eq!(problem(answer).await, "unauthorized");
2212            }
2213        }
2214
2215        #[tokio::test]
2216        async fn a_key_table_that_cannot_be_read_makes_the_service_unavailable() {
2217            let s = server().await;
2218            let writer = s.key(&[Scope::Write]);
2219            s.tenants
2220                .conn_for_test()
2221                .execute_batch("ALTER TABLE api_key RENAME TO gone")
2222                .expect("lose the table");
2223            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2224            assert_eq!(answer.status(), 503);
2225            assert_eq!(problem(answer).await, "unavailable");
2226        }
2227
2228        #[tokio::test]
2229        async fn a_refusal_that_cannot_be_recorded_answers_that_the_audit_failed() {
2230            let s = server().await;
2231            let reader = s.key(&[Scope::Read]);
2232            s.tenants.store(s.tenant).expect("its store").break_audit();
2233            let answer = post(&s, Some(&reader), b"{}".to_vec()).await;
2234            assert_eq!(answer.status(), 503);
2235            assert_eq!(problem(answer).await, "audit-failed");
2236
2237            let operator = s
2238                .tenants
2239                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
2240                .expect("made")
2241                .token;
2242            s.tenants.break_audit();
2243            let answer = post(&s, Some(&operator), b"{}".to_vec()).await;
2244            assert_eq!(answer.status(), 503);
2245            assert_eq!(problem(answer).await, "audit-failed");
2246        }
2247
2248        #[tokio::test]
2249        async fn a_key_without_the_scope_is_forbidden_and_recorded() {
2250            let s = server().await;
2251            let reader = s.key(&[Scope::Read]);
2252            let answer = post(&s, Some(&reader), b"{}".to_vec()).await;
2253            assert_eq!(answer.status(), 403);
2254            assert_eq!(problem(answer).await, "forbidden");
2255            let refused = s.tenant_log("create");
2256            assert_eq!(refused.len(), 1);
2257            assert_eq!(refused[0]["status"], 403);
2258
2259            let operator = s
2260                .tenants
2261                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
2262                .expect("made")
2263                .token;
2264            let answer = post(&s, Some(&operator), b"{}".to_vec()).await;
2265            assert_eq!(answer.status(), 403);
2266            let admin: Vec<Value> = s
2267                .tenants
2268                .admin_records()
2269                .into_iter()
2270                .filter(|r| r["action"] == "create")
2271                .collect();
2272            assert_eq!(admin.len(), 1, "an operator's refusal is in the admin log");
2273            assert_eq!(admin[0]["status"], 403);
2274        }
2275
2276        #[tokio::test]
2277        async fn a_closing_tenant_is_unavailable() {
2278            let s = server().await;
2279            let writer = s.key(&[Scope::Write]);
2280            s.tenants.close(s.tenant);
2281            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2282            assert_eq!(answer.status(), 503);
2283            assert_eq!(problem(answer).await, "unavailable");
2284        }
2285
2286        #[tokio::test]
2287        async fn a_declared_length_over_the_limit_is_refused_at_once() {
2288            let s = server().await;
2289            let writer = s.key(&[Scope::Write]);
2290            let answer = post(&s, Some(&writer), vec![b'x'; LIMIT + 1]).await;
2291            assert_eq!(answer.status(), 413);
2292            assert_eq!(problem(answer).await, "too-large");
2293            assert_eq!(s.tenant_log("create")[0]["status"], 413);
2294            let declared = format!("content-length: {}", LIMIT + 1);
2295            assert_eq!(
2296                s.raw(&writer, &declared, b"").await,
2297                "HTTP/1.1 413 Payload Too Large",
2298                "refused on the declared length, with no byte of the body sent"
2299            );
2300        }
2301
2302        #[tokio::test]
2303        async fn a_body_over_the_limit_is_refused_before_it_is_read_in_full() {
2304            let s = server().await;
2305            let writer = s.key(&[Scope::Write]);
2306            let status = s.chunked(&writer, &[LIMIT / 2, LIMIT / 2 + 1], false).await;
2307            assert_eq!(status, "HTTP/1.1 413 Payload Too Large");
2308        }
2309
2310        #[tokio::test]
2311        async fn a_body_that_stops_arriving_times_out() {
2312            let s = server().await;
2313            let writer = s.key(&[Scope::Write]);
2314            let status = s.chunked(&writer, &[10], false).await;
2315            assert_eq!(status, "HTTP/1.1 408 Request Timeout");
2316            assert_eq!(s.tenant_log("create")[0]["status"], 408);
2317        }
2318
2319        #[tokio::test]
2320        /// The body reaches Format whole: a body of x's at the limit is
2321        /// refused as not JSON, not as too large.
2322        async fn a_request_within_the_limits_goes_on_to_its_route() {
2323            let s = server().await;
2324            let writer = s.key(&[Scope::Write]);
2325            let status = s.chunked(&writer, &[LIMIT / 2, LIMIT / 2], true).await;
2326            assert_eq!(status, "HTTP/1.1 422 Unprocessable Entity");
2327            let answer = post(&s, Some(&writer), b"{}".to_vec()).await;
2328            assert_eq!(answer.status(), 422);
2329            assert_eq!(problem(answer).await, "no-form");
2330        }
2331    }
2332
2333    #[test]
2334    fn a_removal_query_is_none_or_force_true_or_false_and_nothing_else() {
2335        assert_eq!(removal(None), Some(Removal::Empty));
2336        assert_eq!(removal(Some("force=false")), Some(Removal::Empty));
2337        assert_eq!(removal(Some("force=true")), Some(Removal::Force));
2338        for query in [
2339            "",
2340            "force",
2341            "force=",
2342            "force=1",
2343            "Force=true",
2344            "force=true&",
2345        ] {
2346            assert_eq!(removal(Some(query)), None, "{query:?}");
2347        }
2348    }
2349
2350    /// A refusal the vcon crate adds in a later release, which this
2351    /// server does not name yet, still has a problem: not-a-vcon. No test
2352    /// can send one, since every refusal there is today is named above; this
2353    /// holds the problem the catch-all arm answers with.
2354    #[test]
2355    fn a_refusal_this_server_does_not_name_is_not_a_vcon() {
2356        let problem = Problem::Invalid(Invalid::Other);
2357        assert_eq!(
2358            (problem.status().as_u16(), problem.name().0),
2359            (422, "not-a-vcon")
2360        );
2361    }
2362
2363    #[tokio::test]
2364    async fn every_refusal_from_format_has_its_own_problem() {
2365        let cases = [
2366            (Rejection::TooLarge, 413, "too-large"),
2367            (Rejection::TooDeep, 422, "too-deep"),
2368            (Rejection::BadGzip, 422, "bad-gzip"),
2369            (Rejection::NotJson, 422, "not-json"),
2370            (Rejection::DuplicateKey, 422, "duplicate-member"),
2371            (Rejection::AmbiguousForm, 422, "ambiguous-form"),
2372            (Rejection::NoForm, 422, "no-form"),
2373            (Rejection::MissingUuid, 422, "missing-uuid"),
2374            (Rejection::BadUuid, 422, "bad-uuid"),
2375            (Rejection::MissingCreatedAt, 422, "missing-created-at"),
2376            (Rejection::BadPayload, 422, "bad-payload"),
2377            (Rejection::UuidMismatch, 422, "uuid-mismatch"),
2378            (Rejection::BadCritical, 422, "bad-critical"),
2379            (
2380                Rejection::UnsupportedCritical(vec!["secret-name".to_owned()]),
2381                422,
2382                "unsupported-extension",
2383            ),
2384        ];
2385        for (rejection, status, name) in &cases {
2386            let problem = rejected(rejection);
2387            assert_eq!(
2388                (problem.status().as_u16(), problem.name().0),
2389                (*status, *name),
2390                "{rejection:?}"
2391            );
2392            let body = axum::body::to_bytes(problem.into_response().into_body(), usize::MAX)
2393                .await
2394                .expect("the body");
2395            let answer = String::from_utf8(body.to_vec()).expect("UTF-8");
2396            assert!(answer.contains(&format!("\"status\":{status}")), "{answer}");
2397            assert!(
2398                !answer.contains("secret-name"),
2399                "the name is not repeated: {answer}"
2400            );
2401        }
2402    }
2403
2404    #[test]
2405    fn every_store_outcome_has_its_problem() {
2406        let cases = [
2407            (StoreError::Conflict, 409, "conflict"),
2408            (StoreError::Gone, 410, "gone"),
2409            (StoreError::NotFound, 404, "not-found"),
2410            (StoreError::NotDeleted, 409, "not-deleted"),
2411            (StoreError::PreconditionFailed, 412, "precondition-failed"),
2412            (StoreError::Immutable, 409, "immutable"),
2413            (StoreError::LimitReached, 503, "limit-reached"),
2414            (StoreError::Damaged, 500, "damaged"),
2415            (StoreError::AuditFailed, 503, "audit-failed"),
2416            (StoreError::Io, 500, "internal"),
2417        ];
2418        for (error, status, name) in cases {
2419            let problem = failed(error);
2420            assert_eq!(
2421                (problem.status().as_u16(), problem.name().0),
2422                (status, name),
2423                "{error:?}"
2424            );
2425        }
2426    }
2427
2428    #[test]
2429    fn every_tenants_outcome_has_its_problem() {
2430        let cases = [
2431            (TenantError::NotFound, 404, "unknown-tenant"),
2432            (TenantError::NameTaken, 409, "name-taken"),
2433            (TenantError::BadName, 422, "invalid-body"),
2434            (TenantError::HoldsVcons, 409, "holds-vcons"),
2435            (TenantError::UnderHold, 409, "under-hold"),
2436            (TenantError::LimitReached, 503, "master-key-limit"),
2437            (TenantError::AuditFailed, 503, "audit-failed"),
2438            (TenantError::Closing, 503, "unavailable"),
2439            (TenantError::CliOnly, 403, "forbidden"),
2440            (TenantError::BadScopes, 422, "bad-scopes"),
2441            (TenantError::BadExpiry, 422, "bad-expiry"),
2442            (
2443                TenantError::BadSetting(crate::settings::SettingError::UnknownName),
2444                422,
2445                "bad-setting",
2446            ),
2447            (TenantError::WrongKey, 500, "internal"),
2448            (TenantError::NoFileBackup, 500, "internal"),
2449            (TenantError::Io, 500, "internal"),
2450        ];
2451        for (error, status, name) in cases {
2452            let problem = Problem::Tenant(error);
2453            assert_eq!(
2454                (problem.status().as_u16(), problem.name().0),
2455                (status, name),
2456                "{error:?}"
2457            );
2458        }
2459    }
2460
2461    mod vcons {
2462        use std::io::Write;
2463
2464        use super::pipeline::{Server, problem, server};
2465        use crate::access::Scope;
2466        use crate::store::Caller as StoreCaller;
2467        use crate::store::testing::vcon;
2468
2469        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
2470
2471        fn uuid(n: u8) -> String {
2472            format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02x}")
2473        }
2474
2475        async fn post(
2476            s: &Server,
2477            token: &str,
2478            content_type: Option<&str>,
2479            body: Vec<u8>,
2480        ) -> reqwest::Response {
2481            let mut request = s
2482                .client()
2483                .post(s.url("/vcons"))
2484                .bearer_auth(token)
2485                .body(body);
2486            if let Some(content_type) = content_type {
2487                request = request.header("content-type", content_type);
2488            }
2489            request.send().await.expect("an answer")
2490        }
2491
2492        fn gzip(body: &[u8]) -> Vec<u8> {
2493            let mut encoder =
2494                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2495            encoder.write_all(body).expect("gzip");
2496            encoder.finish().expect("gzip")
2497        }
2498
2499        fn store_caller() -> StoreCaller {
2500            StoreCaller {
2501                key: crate::ids::KeyId([9; 8]),
2502            }
2503        }
2504
2505        #[tokio::test]
2506        async fn a_new_vcon_is_created_with_its_location_and_tag() {
2507            let s = server().await;
2508            let writer = s.key(&[Scope::Write]);
2509            let (found, body) = vcon(UUID, "first");
2510            let answer = post(&s, &writer, Some("application/vcon"), body.clone()).await;
2511            assert_eq!(answer.status(), 201);
2512            assert_eq!(answer.headers()["location"], format!("/vcons/{UUID}"));
2513            let tag = answer.headers()["etag"].to_str().expect("ascii").to_owned();
2514            let stored = s
2515                .tenants
2516                .store(s.tenant)
2517                .expect("its store")
2518                .get(&store_caller(), found.uuid)
2519                .expect("stored");
2520            assert_eq!(tag, format!("\"{}\"", stored.version), "a strong tag");
2521            assert_eq!(stored.body, body);
2522
2523            let again = post(&s, &writer, Some("application/vcon"), body).await;
2524            assert_eq!(again.status(), 200, "the same bytes are already current");
2525            assert_eq!(again.headers()["etag"], tag.as_str());
2526        }
2527
2528        #[tokio::test]
2529        async fn another_vcon_with_the_uuid_conflicts() {
2530            let s = server().await;
2531            let writer = s.key(&[Scope::Write]);
2532            let (_, first) = vcon(UUID, "first");
2533            let (_, other) = vcon(UUID, "other");
2534            assert_eq!(post(&s, &writer, None, first).await.status(), 201);
2535            let answer = post(&s, &writer, None, other).await;
2536            assert_eq!(answer.status(), 409);
2537            assert_eq!(problem(answer).await, "conflict");
2538            let statuses: Vec<_> = s
2539                .tenant_log("create")
2540                .into_iter()
2541                .map(|r| r["status"].clone())
2542                .collect();
2543            assert_eq!(statuses, [201, 409], "Store records its own, once");
2544        }
2545
2546        #[tokio::test]
2547        async fn a_vcon_needing_an_unsupported_extension_is_unprocessable() {
2548            let s = super::pipeline::server_with(&["known"]).await;
2549            let writer = s.key(&[Scope::Write]);
2550            let needing = |n: u8, extension: &str| {
2551                format!(
2552                    r#"{{"uuid": "{}", "created_at": "2026-10-23T12:00:00Z", "must_support": ["{extension}"], "parties": []}}"#,
2553                    uuid(n)
2554                )
2555                .into_bytes()
2556            };
2557            assert_eq!(
2558                post(&s, &writer, None, needing(1, "known")).await.status(),
2559                201
2560            );
2561            let answer = post(&s, &writer, None, needing(2, "unknown")).await;
2562            assert_eq!(answer.status(), 422);
2563            assert_eq!(problem(answer).await, "unsupported-extension");
2564        }
2565
2566        #[tokio::test]
2567        async fn a_media_type_that_is_not_text_is_unsupported() {
2568            let s = server().await;
2569            let writer = s.key(&[Scope::Write]);
2570            let (_, body) = vcon(UUID, "first");
2571            let answer = s
2572                .client()
2573                .post(s.url("/vcons"))
2574                .bearer_auth(&writer)
2575                .header(
2576                    "content-type",
2577                    reqwest::header::HeaderValue::from_bytes(b"application/vcon\xff")
2578                        .expect("a header value"),
2579                )
2580                .body(body)
2581                .send()
2582                .await
2583                .expect("an answer");
2584            assert_eq!(answer.status(), 415);
2585        }
2586
2587        #[tokio::test]
2588        async fn a_deleted_vcon_is_gone() {
2589            let s = server().await;
2590            let writer = s.key(&[Scope::Write]);
2591            let (found, body) = vcon(UUID, "first");
2592            assert_eq!(post(&s, &writer, None, body.clone()).await.status(), 201);
2593            s.tenants
2594                .store(s.tenant)
2595                .expect("its store")
2596                .delete(
2597                    &store_caller(),
2598                    found.uuid,
2599                    crate::retention::Retention::Years(7),
2600                )
2601                .expect("deleted");
2602            let answer = post(&s, &writer, None, body).await;
2603            assert_eq!(answer.status(), 410);
2604            assert_eq!(problem(answer).await, "gone");
2605        }
2606
2607        #[tokio::test]
2608        async fn the_vcon_media_types_json_and_none_are_taken() {
2609            let s = server().await;
2610            let writer = s.key(&[Scope::Write]);
2611            let cases: [(Option<&str>, bool); 6] = [
2612                (None, false),
2613                (Some("application/vcon"), false),
2614                (Some("application/vcon+gzip"), true),
2615                (Some("application/json"), false),
2616                (Some("Application/VCON; charset=utf-8"), false),
2617                (Some("APPLICATION/VCON+GZIP ; q=1"), true),
2618            ];
2619            for (n, (content_type, gzipped)) in cases.into_iter().enumerate() {
2620                let (_, body) = vcon(&uuid(n as u8), "typed");
2621                let body = if gzipped { gzip(&body) } else { body };
2622                let answer = post(&s, &writer, content_type, body).await;
2623                assert_eq!(answer.status(), 201, "{content_type:?}");
2624            }
2625        }
2626
2627        #[tokio::test]
2628        async fn another_media_type_is_unsupported_and_recorded() {
2629            let s = server().await;
2630            let writer = s.key(&[Scope::Write]);
2631            let (_, body) = vcon(UUID, "first");
2632            for content_type in ["text/plain", "application/vcon-json", "application/xml"] {
2633                let answer = post(&s, &writer, Some(content_type), body.clone()).await;
2634                assert_eq!(answer.status(), 415, "{content_type}");
2635                assert_eq!(problem(answer).await, "unsupported-media-type");
2636            }
2637            let refused: Vec<_> = s
2638                .tenant_log("create")
2639                .iter()
2640                .map(|r| r["status"].clone())
2641                .collect();
2642            assert_eq!(refused, [415, 415, 415], "one record per refusal");
2643        }
2644
2645        #[tokio::test]
2646        async fn a_body_format_refuses_is_unprocessable_and_recorded() {
2647            let s = server().await;
2648            let writer = s.key(&[Scope::Write]);
2649            let answer = post(&s, &writer, None, b"not json".to_vec()).await;
2650            assert_eq!(answer.status(), 422);
2651            assert_eq!(problem(answer).await, "not-json");
2652            let (_, body) = vcon(UUID, "first");
2653            let answer = post(&s, &writer, Some("application/vcon+gzip"), body).await;
2654            assert_eq!(answer.status(), 422);
2655            assert_eq!(problem(answer).await, "bad-gzip");
2656            let refused = s.tenant_log("create");
2657            assert_eq!(refused.len(), 2);
2658            assert_eq!(refused[0]["status"], 422);
2659        }
2660
2661        #[tokio::test]
2662        async fn a_body_that_inflates_past_its_limit_is_too_large() {
2663            let s = server().await;
2664            let writer = s.key(&[Scope::Write]);
2665            let bomb = gzip(&vec![b' '; 2 << 20]);
2666            assert!(bomb.len() < 64 * 1024, "small on the wire");
2667            let answer = post(&s, &writer, Some("application/vcon+gzip"), bomb).await;
2668            assert_eq!(answer.status(), 413);
2669            assert_eq!(problem(answer).await, "too-large");
2670        }
2671
2672        #[tokio::test]
2673        async fn a_body_nested_too_deeply_is_unprocessable_and_recorded() {
2674            use base64::Engine;
2675            use base64::engine::general_purpose::URL_SAFE_NO_PAD;
2676            let s = server().await;
2677            let writer = s.key(&[Scope::Write]);
2678            let (_, mut signed) = vcon(UUID, "first");
2679            for _ in 0..=vcon::read::MAX_SIGNED_LAYERS {
2680                signed = serde_json::json!({
2681                    "payload": URL_SAFE_NO_PAD.encode(gzip(&signed)),
2682                    "signatures": [{}],
2683                })
2684                .to_string()
2685                .into_bytes();
2686            }
2687            let open = "[".repeat(vcon::read::MAX_JSON_DEPTH);
2688            let close = "]".repeat(vcon::read::MAX_JSON_DEPTH);
2689            let json = format!(r#"{{"uuid":"{UUID}","created_at":"x","a":{open}{close}}}"#);
2690            for body in [signed, json.into_bytes()] {
2691                let answer = post(&s, &writer, None, body).await;
2692                assert_eq!(answer.status(), 422);
2693                assert_eq!(problem(answer).await, "too-deep");
2694            }
2695            let refused = s.tenant_log("create");
2696            assert_eq!(refused.len(), 2);
2697            assert!(refused.iter().all(|r| r["status"] == 422));
2698        }
2699
2700        #[tokio::test]
2701        async fn a_create_whose_record_fails_is_unavailable() {
2702            let s = server().await;
2703            let writer = s.key(&[Scope::Write]);
2704            s.tenants.store(s.tenant).expect("its store").break_audit();
2705            let (_, body) = vcon(UUID, "first");
2706            let answer = post(&s, &writer, None, body).await;
2707            assert_eq!(answer.status(), 503);
2708            assert_eq!(problem(answer).await, "audit-failed");
2709        }
2710    }
2711
2712    mod legal {
2713        use reqwest::Method;
2714        use serde_json::Value;
2715
2716        use super::pipeline::{Server, problem, server};
2717        use crate::access::{Scope, Scopes};
2718        use crate::audit::Actor;
2719        use crate::ids::VersionId;
2720        use crate::retention::Retention;
2721
2722        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
2723        const NEVER: &str = "0199e5c6-0d7a-7c11-8000-000000000001";
2724
2725        fn key(s: &Server, scopes: &[Scope]) -> String {
2726            s.tenants
2727                .create_key(Actor::Cli, Some(s.tenant), Scopes::of(scopes), "test")
2728                .expect("a key")
2729                .token
2730        }
2731
2732        fn a4() -> Vec<u8> {
2733            std::fs::read(format!(
2734                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
2735                env!("CARGO_MANIFEST_DIR")
2736            ))
2737            .expect("A.4")
2738        }
2739
2740        async fn call(s: &Server, method: Method, path: &str, token: &str) -> reqwest::Response {
2741            s.client()
2742                .request(method, s.url(path))
2743                .bearer_auth(token)
2744                .send()
2745                .await
2746                .expect("an answer")
2747        }
2748
2749        /// Stores A.4 and returns its entity tag.
2750        async fn stored(s: &Server) -> String {
2751            let writer = key(s, &[Scope::Write]);
2752            let answer = s
2753                .client()
2754                .post(s.url("/vcons"))
2755                .bearer_auth(&writer)
2756                .header("content-type", "application/vcon")
2757                .body(a4())
2758                .send()
2759                .await
2760                .expect("an answer");
2761            assert_eq!(answer.status(), 201);
2762            answer.headers()["etag"].to_str().expect("tag").to_owned()
2763        }
2764
2765        async fn deleted(s: &Server) {
2766            let deleter = key(s, &[Scope::Delete]);
2767            let path = format!("/vcons/{UUID}");
2768            assert_eq!(call(s, Method::DELETE, &path, &deleter).await.status(), 204);
2769        }
2770
2771        /// Every legal route for `uuid`, with `version` for the one that
2772        /// names a version.
2773        fn routes(uuid: &str, version: &str) -> Vec<(Method, String)> {
2774            vec![
2775                (Method::GET, format!("/legal/vcons/{uuid}")),
2776                (Method::GET, format!("/legal/vcons/{uuid}/versions")),
2777                (
2778                    Method::GET,
2779                    format!("/legal/vcons/{uuid}/versions/{version}"),
2780                ),
2781                (Method::POST, format!("/legal/vcons/{uuid}/restore")),
2782                (Method::PUT, format!("/legal/vcons/{uuid}/hold")),
2783                (Method::DELETE, format!("/legal/vcons/{uuid}/hold")),
2784            ]
2785        }
2786
2787        fn bare(tag: &str) -> String {
2788            tag.trim_matches('"').to_owned()
2789        }
2790
2791        #[tokio::test]
2792        async fn every_legal_route_needs_the_legal_scope() {
2793            let s = server().await;
2794            let tag = stored(&s).await;
2795            let others = key(&s, &[Scope::Write, Scope::Read, Scope::Delete]);
2796            for (method, path) in routes(UUID, &bare(&tag)) {
2797                let answer = call(&s, method.clone(), &path, &others).await;
2798                assert_eq!(answer.status(), 403, "{method} {path}");
2799            }
2800        }
2801
2802        #[tokio::test]
2803        async fn a_deleted_vcon_reads_back_byte_for_byte_with_a_legal_key() {
2804            let s = server().await;
2805            let tag = stored(&s).await;
2806            let legal = key(&s, &[Scope::Legal]);
2807            let path = format!("/legal/vcons/{UUID}");
2808
2809            let live = call(&s, Method::GET, &path, &legal).await;
2810            assert_eq!(live.status(), 200);
2811            assert_eq!(live.headers()["vcon-state"], "live");
2812
2813            deleted(&s).await;
2814            let answer = call(&s, Method::GET, &path, &legal).await;
2815            assert_eq!(answer.status(), 200);
2816            assert_eq!(answer.headers()["vcon-state"], "deleted");
2817            assert_eq!(answer.headers()["etag"], tag.as_str());
2818            assert_eq!(answer.headers()["content-type"], "application/vcon");
2819            assert_eq!(
2820                answer.bytes().await.expect("body").as_ref(),
2821                a4().as_slice()
2822            );
2823            assert_eq!(
2824                s.tenant_log("legal_read").last().expect("recorded")["status"],
2825                200
2826            );
2827        }
2828
2829        #[tokio::test]
2830        async fn the_version_list_and_a_named_version() {
2831            let s = server().await;
2832            let tag = stored(&s).await;
2833            let legal = key(&s, &[Scope::Legal]);
2834            let live = call(
2835                &s,
2836                Method::GET,
2837                &format!("/legal/vcons/{UUID}/versions"),
2838                &legal,
2839            )
2840            .await;
2841            let live: Value =
2842                serde_json::from_slice(&live.bytes().await.expect("body")).expect("json");
2843            assert_eq!(live[0]["current"], true, "live, so current");
2844            assert!(live[0]["hidden_at"].is_null(), "not hidden while live");
2845            deleted(&s).await;
2846
2847            let list = call(
2848                &s,
2849                Method::GET,
2850                &format!("/legal/vcons/{UUID}/versions"),
2851                &legal,
2852            )
2853            .await;
2854            assert_eq!(list.status(), 200);
2855            assert_eq!(list.headers()["content-type"], "application/json");
2856            let list: Value =
2857                serde_json::from_slice(&list.bytes().await.expect("body")).expect("json");
2858            let versions = list.as_array().expect("a list");
2859            assert_eq!(versions.len(), 1);
2860            assert_eq!(versions[0]["version"], bare(&tag));
2861            assert_eq!(versions[0]["current"], false);
2862            assert!(
2863                versions[0]["stored_at"]
2864                    .as_str()
2865                    .expect("a time")
2866                    .ends_with('Z')
2867            );
2868            assert!(versions[0]["hidden_at"].is_string(), "hidden by the delete");
2869
2870            let one = format!("/legal/vcons/{UUID}/versions/{}", bare(&tag));
2871            let answer = call(&s, Method::GET, &one, &legal).await;
2872            assert_eq!(answer.status(), 200);
2873            assert_eq!(answer.headers()["etag"], tag.as_str());
2874            assert_eq!(
2875                answer.bytes().await.expect("body").as_ref(),
2876                a4().as_slice()
2877            );
2878
2879            let unknown = format!("/legal/vcons/{UUID}/versions/{}", VersionId::generate());
2880            let answer = call(&s, Method::GET, &unknown, &legal).await;
2881            assert_eq!(answer.status(), 404);
2882            assert_eq!(problem(answer).await, "not-found");
2883
2884            let bad = format!("/legal/vcons/{UUID}/versions/not-a-version");
2885            let answer = call(&s, Method::GET, &bad, &legal).await;
2886            assert_eq!(answer.status(), 400);
2887            assert_eq!(problem(answer).await, "bad-path-version");
2888            assert_eq!(
2889                s.tenant_log("legal_read").last().expect("recorded")["status"],
2890                400
2891            );
2892        }
2893
2894        #[tokio::test]
2895        async fn restore_answers_its_tag_then_409_once_live() {
2896            let s = server().await;
2897            let tag = stored(&s).await;
2898            deleted(&s).await;
2899            let token = key(&s, &[Scope::Legal, Scope::Read]);
2900            let path = format!("/legal/vcons/{UUID}/restore");
2901
2902            let answer = call(&s, Method::POST, &path, &token).await;
2903            assert_eq!(answer.status(), 200);
2904            assert_eq!(answer.headers()["etag"], tag.as_str());
2905            let read = call(&s, Method::GET, &format!("/vcons/{UUID}"), &token).await;
2906            assert_eq!(read.status(), 200, "live again");
2907
2908            let again = call(&s, Method::POST, &path, &token).await;
2909            assert_eq!(again.status(), 409);
2910            assert_eq!(problem(again).await, "not-deleted");
2911        }
2912
2913        #[tokio::test]
2914        async fn a_hold_is_set_and_released_with_204() {
2915            let s = server().await;
2916            stored(&s).await;
2917            let legal = key(&s, &[Scope::Legal]);
2918            let path = format!("/legal/vcons/{UUID}/hold");
2919            for method in [Method::PUT, Method::DELETE] {
2920                let answer = call(&s, method, &path, &legal).await;
2921                assert_eq!(answer.status(), 204);
2922                assert!(answer.bytes().await.expect("body").is_empty());
2923            }
2924            assert_eq!(s.tenant_log("hold").len(), 1, "the hold");
2925            assert_eq!(s.tenant_log("release").len(), 1, "the release, as itself");
2926        }
2927
2928        #[tokio::test]
2929        async fn a_held_vcon_survives_a_zero_period_delete_until_released() {
2930            let s = server().await;
2931            stored(&s).await;
2932            let legal = key(&s, &[Scope::Legal]);
2933            let hold = format!("/legal/vcons/{UUID}/hold");
2934            let read = format!("/legal/vcons/{UUID}");
2935            assert_eq!(call(&s, Method::PUT, &hold, &legal).await.status(), 204);
2936            s.tenants
2937                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
2938                .expect("set");
2939            deleted(&s).await;
2940            assert_eq!(
2941                call(&s, Method::GET, &read, &legal).await.status(),
2942                200,
2943                "held"
2944            );
2945
2946            assert_eq!(call(&s, Method::DELETE, &hold, &legal).await.status(), 204);
2947            s.tenants
2948                .store(s.tenant)
2949                .expect("its store")
2950                .purge_due(Retention::Days(0))
2951                .expect("swept");
2952            assert_eq!(
2953                call(&s, Method::GET, &read, &legal).await.status(),
2954                410,
2955                "released"
2956            );
2957        }
2958
2959        #[tokio::test]
2960        async fn a_gzipped_vcon_reads_back_gzipped() {
2961            use std::io::Write;
2962            let s = server().await;
2963            let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2964            gz.write_all(&a4()).expect("gzip");
2965            let gzipped = gz.finish().expect("gzip");
2966            let writer = key(&s, &[Scope::Write]);
2967            let answer = s
2968                .client()
2969                .post(s.url("/vcons"))
2970                .bearer_auth(&writer)
2971                .header("content-type", "application/vcon+gzip")
2972                .body(gzipped.clone())
2973                .send()
2974                .await
2975                .expect("an answer");
2976            assert_eq!(answer.status(), 201);
2977            deleted(&s).await;
2978            let legal = key(&s, &[Scope::Legal]);
2979            let answer = call(&s, Method::GET, &format!("/legal/vcons/{UUID}"), &legal).await;
2980            assert_eq!(answer.status(), 200);
2981            assert_eq!(answer.headers()["content-type"], "application/vcon+gzip");
2982            assert_eq!(
2983                answer.bytes().await.expect("body").as_ref(),
2984                gzipped.as_slice()
2985            );
2986        }
2987
2988        #[tokio::test]
2989        async fn a_purged_uuid_is_410_on_every_legal_route() {
2990            let s = server().await;
2991            let tag = stored(&s).await;
2992            s.tenants
2993                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
2994                .expect("set");
2995            deleted(&s).await;
2996            let legal = key(&s, &[Scope::Legal]);
2997            for (method, path) in routes(UUID, &bare(&tag)) {
2998                let answer = call(&s, method.clone(), &path, &legal).await;
2999                assert_eq!(answer.status(), 410, "{method} {path}");
3000                assert_eq!(problem(answer).await, "gone");
3001            }
3002        }
3003
3004        #[tokio::test]
3005        async fn a_uuid_never_stored_is_404_and_a_bad_one_400_on_every_legal_route() {
3006            let s = server().await;
3007            let legal = key(&s, &[Scope::Legal]);
3008            let version = VersionId::generate().to_string();
3009            for (method, path) in routes(NEVER, &version) {
3010                let answer = call(&s, method.clone(), &path, &legal).await;
3011                assert_eq!(answer.status(), 404, "{method} {path}");
3012                assert_eq!(problem(answer).await, "not-found");
3013            }
3014            for (method, path) in routes("not-a-uuid", &version) {
3015                let answer = call(&s, method.clone(), &path, &legal).await;
3016                assert_eq!(answer.status(), 400, "{method} {path}");
3017                assert_eq!(problem(answer).await, "bad-path-uuid");
3018            }
3019            for action in ["legal_read", "legal_versions", "restore", "hold", "release"] {
3020                let last = s.tenant_log(action).last().expect("recorded").clone();
3021                assert_eq!(last["status"], 400, "{action}'s refusal is recorded");
3022            }
3023        }
3024
3025        #[tokio::test]
3026        async fn damage_is_500_on_every_legal_route() {
3027            let s = server().await;
3028            let tag = stored(&s).await;
3029            deleted(&s).await;
3030            let legal = key(&s, &[Scope::Legal]);
3031            let store = s.tenants.store(s.tenant).expect("its store");
3032            store
3033                .conn_for_test()
3034                .execute_batch(
3035                    "UPDATE version SET wrapped_key = x'00', stored_at = 'x';
3036                     CREATE TEMP TRIGGER broken BEFORE UPDATE ON vcon
3037                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
3038                )
3039                .expect("damaged");
3040            for (method, path) in routes(UUID, &bare(&tag)) {
3041                let answer = call(&s, method.clone(), &path, &legal).await;
3042                assert_eq!(answer.status(), 500, "{method} {path}");
3043            }
3044        }
3045
3046        #[tokio::test]
3047        async fn an_answer_that_cannot_be_recorded_is_503_on_every_legal_route() {
3048            let s = server().await;
3049            let tag = stored(&s).await;
3050            let legal = key(&s, &[Scope::Legal]);
3051            s.tenants.store(s.tenant).expect("its store").break_audit();
3052            for (method, path) in routes(UUID, &bare(&tag)) {
3053                let answer = call(&s, method.clone(), &path, &legal).await;
3054                assert_eq!(answer.status(), 503, "{method} {path}");
3055                assert_eq!(problem(answer).await, "audit-failed");
3056            }
3057        }
3058    }
3059
3060    mod admin {
3061        use reqwest::Method;
3062        use serde_json::{Value, json};
3063
3064        use super::pipeline::{Server, problem, server};
3065        use crate::access::{Scope, Scopes};
3066        use crate::audit::Actor;
3067        use time::format_description::well_known::Rfc3339;
3068
3069        use crate::access;
3070        use crate::export::Metadata;
3071        use crate::ids::{KeyId, TenantId};
3072        use crate::retention::Retention;
3073
3074        fn operator(s: &Server) -> String {
3075            s.tenants
3076                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
3077                .expect("an operator key")
3078                .token
3079        }
3080
3081        async fn call(
3082            s: &Server,
3083            method: Method,
3084            path: &str,
3085            token: Option<&str>,
3086            body: Option<&str>,
3087        ) -> reqwest::Response {
3088            let mut request = s.client().request(method, s.url(path));
3089            if let Some(token) = token {
3090                request = request.bearer_auth(token);
3091            }
3092            if let Some(body) = body {
3093                request = request
3094                    .header("content-type", "application/json")
3095                    .body(body.to_owned());
3096            }
3097            request.send().await.expect("an answer")
3098        }
3099
3100        async fn json(answer: reqwest::Response) -> Value {
3101            assert_eq!(answer.headers()["content-type"], "application/json");
3102            serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON")
3103        }
3104
3105        /// The admin log's records of `action` written for requests, not
3106        /// for the tests' own setup from the command line.
3107        fn admin_log(s: &Server, action: &str) -> Vec<Value> {
3108            s.tenants
3109                .admin_records()
3110                .into_iter()
3111                .filter(|r| r["action"] == action && r["actor"] != "cli")
3112                .collect()
3113        }
3114
3115        fn key_id(token: &str) -> KeyId {
3116            access::parse(token).expect("a token")
3117        }
3118
3119        /// Each admin route, with a body it takes, and its audit action.
3120        fn routes(
3121            id: TenantId,
3122            key: KeyId,
3123        ) -> Vec<(Method, String, Option<&'static str>, &'static str)> {
3124            vec![
3125                (
3126                    Method::POST,
3127                    "/admin/tenants".to_owned(),
3128                    Some(r#"{"name":"beta"}"#),
3129                    "tenant_create",
3130                ),
3131                (
3132                    Method::GET,
3133                    "/admin/tenants".to_owned(),
3134                    None,
3135                    "tenant_list",
3136                ),
3137                (
3138                    Method::PATCH,
3139                    format!("/admin/tenants/{id}"),
3140                    Some(r#"{"retention":"5y"}"#),
3141                    "tenant_retention",
3142                ),
3143                (
3144                    Method::PUT,
3145                    format!("/admin/tenants/{id}/metadata"),
3146                    Some(r#"{"metadata":"counts"}"#),
3147                    "tenant_metadata",
3148                ),
3149                (
3150                    Method::DELETE,
3151                    format!("/admin/tenants/{id}"),
3152                    None,
3153                    "tenant_remove",
3154                ),
3155                (
3156                    Method::POST,
3157                    format!("/admin/tenants/{id}/keys"),
3158                    Some(r#"{"scopes":["read"],"label":"ingest"}"#),
3159                    "key_create",
3160                ),
3161                (
3162                    Method::GET,
3163                    format!("/admin/tenants/{id}/keys"),
3164                    None,
3165                    "key_list",
3166                ),
3167                (
3168                    Method::DELETE,
3169                    format!("/admin/keys/{key}"),
3170                    None,
3171                    "key_revoke",
3172                ),
3173            ]
3174        }
3175
3176        #[tokio::test]
3177        async fn a_tenant_key_is_forbidden_and_no_key_unauthorized_on_every_admin_route() {
3178            let s = server().await;
3179            let every = [Scope::Write, Scope::Read, Scope::Delete, Scope::Legal];
3180            let tenant_key = s.key(&every);
3181            for (method, path, body, action) in routes(s.tenant, key_id(&tenant_key)) {
3182                let answer = call(&s, method.clone(), &path, Some(&tenant_key), body).await;
3183                assert_eq!(answer.status(), 403, "{method} {path}");
3184                assert_eq!(problem(answer).await, "forbidden");
3185                let refused: Vec<Value> = s
3186                    .tenant_log(action)
3187                    .into_iter()
3188                    .filter(|r| r["actor"] != "cli")
3189                    .collect();
3190                assert_eq!(refused.len(), 1, "{action} refusal in the tenant's log");
3191                assert_eq!(refused[0]["status"], 403);
3192
3193                let answer = call(&s, method.clone(), &path, None, body).await;
3194                assert_eq!(answer.status(), 401, "{method} {path}");
3195            }
3196            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3197            assert_eq!(s.tenants.retention(s.tenant), Ok(None), "nothing changed");
3198            let keys = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3199            let keys = keys.expect("listed");
3200            assert_eq!(keys.len(), 1, "no key made");
3201            assert_eq!(keys[0].revoked_at, None, "nor revoked");
3202        }
3203
3204        #[tokio::test]
3205        async fn a_tenant_is_created_with_201_and_its_id_and_listed() {
3206            let s = server().await;
3207            let op = operator(&s);
3208            let body = r#"{"name":"beta","retention":"5y"}"#;
3209            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3210            assert_eq!(answer.status(), 201);
3211            let made = json(answer).await;
3212            let id = TenantId::parse(made["id"].as_str().expect("an id")).expect("a tenant id");
3213            assert_eq!(made, json!({ "id": id.to_string() }));
3214            assert_eq!(s.tenants.retention(id), Ok(Some(Retention::Years(5))));
3215            let created = admin_log(&s, "tenant_create");
3216            assert_eq!(created.last().expect("recorded")["status"], 201);
3217
3218            let body = r#"{"name":"gamma"}"#;
3219            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3220            assert_eq!(answer.status(), 201);
3221
3222            let answer = call(&s, Method::GET, "/admin/tenants", Some(&op), None).await;
3223            assert_eq!(answer.status(), 200);
3224            let listed = json(answer).await;
3225            let gamma = s
3226                .tenants
3227                .list(Actor::Cli)
3228                .expect("listed")
3229                .into_iter()
3230                .find(|t| t.name == "gamma")
3231                .expect("gamma")
3232                .id;
3233            assert_eq!(
3234                listed,
3235                json!([
3236                    { "id": s.tenant.to_string(), "name": "acme", "retention": null, "metadata": "none" },
3237                    { "id": id.to_string(), "name": "beta", "retention": "5y", "metadata": "none" },
3238                    { "id": gamma.to_string(), "name": "gamma", "retention": null, "metadata": "none" },
3239                ])
3240            );
3241            assert_eq!(admin_log(&s, "tenant_list")[0]["status"], 200);
3242        }
3243
3244        #[tokio::test]
3245        async fn a_taken_name_is_409() {
3246            let s = server().await;
3247            let op = operator(&s);
3248            let body = r#"{"name":"acme"}"#;
3249            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3250            assert_eq!(answer.status(), 409);
3251            assert_eq!(problem(answer).await, "name-taken");
3252            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3253        }
3254
3255        #[tokio::test]
3256        async fn a_create_body_it_does_not_take_is_422_and_recorded_once() {
3257            let s = server().await;
3258            let op = operator(&s);
3259            let bodies = [
3260                "",
3261                "not json",
3262                "[]",
3263                "{}",
3264                r#"{"name":7}"#,
3265                r#"{"name":null}"#,
3266                r#"{"name":"beta","colour":"red"}"#,
3267                r#"{"name":"beta","name":"gamma"}"#,
3268                r#"{"name":"beta","retention":"7x"}"#,
3269                r#"{"name":"beta","retention":7}"#,
3270                r#"{"name":" beta"}"#,
3271                r#"{"name":""}"#,
3272            ];
3273            for body in bodies {
3274                let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3275                assert_eq!(answer.status(), 422, "{body}");
3276                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3277            }
3278            let refused = admin_log(&s, "tenant_create");
3279            assert_eq!(refused.len(), bodies.len(), "one per refusal");
3280            assert!(refused.iter().all(|r| r["status"] == 422));
3281            assert_eq!(s.tenants.list(Actor::Cli).expect("listed").len(), 1);
3282        }
3283
3284        #[tokio::test]
3285        async fn a_create_past_the_master_keys_wrap_limit_is_503() {
3286            let s = server().await;
3287            let op = operator(&s);
3288            s.tenants
3289                .conn_for_test()
3290                .execute("UPDATE master_key_use SET wraps = ?1", [1_i64 << 32])
3291                .expect("at the limit");
3292            let body = r#"{"name":"beta"}"#;
3293            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(body)).await;
3294            assert_eq!(answer.status(), 503);
3295            assert_eq!(problem(answer).await, "master-key-limit");
3296        }
3297
3298        #[tokio::test]
3299        async fn a_retention_change_answers_200_with_the_period() {
3300            let s = server().await;
3301            let op = operator(&s);
3302            let path = format!("/admin/tenants/{}", s.tenant);
3303            let id = s.tenant.to_string();
3304            for (body, period, kept) in [
3305                (
3306                    r#"{"retention":"30d"}"#,
3307                    json!("30d"),
3308                    Some(Retention::Days(30)),
3309                ),
3310                (r#"{"retention":null}"#, Value::Null, None),
3311            ] {
3312                let answer = call(&s, Method::PATCH, &path, Some(&op), Some(body)).await;
3313                assert_eq!(answer.status(), 200, "{body}");
3314                assert_eq!(json(answer).await, json!({ "id": id, "retention": period }));
3315                assert_eq!(s.tenants.retention(s.tenant), Ok(kept), "{body}");
3316            }
3317            let changed = admin_log(&s, "tenant_retention");
3318            assert_eq!(changed.len(), 2);
3319            assert!(changed.iter().all(|r| r["status"] == 200));
3320            assert_eq!(s.tenant_log("retention").len(), 2, "the tenant's log too");
3321        }
3322
3323        #[tokio::test]
3324        async fn a_retention_change_for_no_tenant_is_404_and_recorded() {
3325            let s = server().await;
3326            let op = operator(&s);
3327            let body = Some(r#"{"retention":"5y"}"#);
3328            let unknown = TenantId([7; 16]).to_string();
3329            for id in [
3330                unknown.as_str(),
3331                "acme",
3332                "0123",
3333                &s.tenant.to_string().to_uppercase(),
3334            ] {
3335                let path = format!("/admin/tenants/{id}");
3336                let answer = call(&s, Method::PATCH, &path, Some(&op), body).await;
3337                assert_eq!(answer.status(), 404, "{id}");
3338                assert_eq!(problem(answer).await, "unknown-tenant", "{id}");
3339            }
3340            let refused = admin_log(&s, "tenant_retention");
3341            assert_eq!(refused.len(), 4);
3342            assert!(refused.iter().all(|r| r["status"] == 404));
3343            assert_eq!(s.tenants.retention(s.tenant), Ok(None));
3344        }
3345
3346        #[tokio::test]
3347        async fn a_retention_body_it_does_not_take_is_422_and_recorded() {
3348            let s = server().await;
3349            let op = operator(&s);
3350            let path = format!("/admin/tenants/{}", s.tenant);
3351            let bodies = [
3352                "",
3353                "{}",
3354                r#"{"retention":"7"}"#,
3355                r#"{"retention":"07y"}"#,
3356                r#"{"retention":5}"#,
3357                r#"{"retention":"5y","name":"beta"}"#,
3358            ];
3359            for body in bodies {
3360                let answer = call(&s, Method::PATCH, &path, Some(&op), Some(body)).await;
3361                assert_eq!(answer.status(), 422, "{body}");
3362                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3363            }
3364            let refused = admin_log(&s, "tenant_retention");
3365            assert_eq!(refused.len(), bodies.len());
3366            assert!(refused.iter().all(|r| r["status"] == 422));
3367            assert_eq!(s.tenants.retention(s.tenant), Ok(None));
3368        }
3369
3370        #[tokio::test]
3371        async fn a_metadata_change_answers_200_with_the_level() {
3372            let s = server().await;
3373            let op = operator(&s);
3374            let path = format!("/admin/tenants/{}/metadata", s.tenant);
3375            let id = s.tenant.to_string();
3376            for (level, kept) in [
3377                ("full", Metadata::Full),
3378                ("counts", Metadata::Counts),
3379                ("none", Metadata::None),
3380            ] {
3381                let body = format!(r#"{{"metadata":"{level}"}}"#);
3382                let answer = call(&s, Method::PUT, &path, Some(&op), Some(&body)).await;
3383                assert_eq!(answer.status(), 200, "{body}");
3384                assert_eq!(
3385                    json(answer).await,
3386                    json!({ "id": id, "metadata": level }),
3387                    "the answer names the tenant and its new level"
3388                );
3389                assert_eq!(s.tenants.metadata(s.tenant), Ok(kept), "{body}");
3390            }
3391            let changed = admin_log(&s, "tenant_metadata");
3392            assert_eq!(changed.len(), 3, "one admin record per change");
3393            assert!(
3394                changed.iter().all(|r| r["status"] == 200),
3395                "each change succeeded"
3396            );
3397            assert_eq!(s.tenant_log("metadata").len(), 3, "the tenant's log too");
3398        }
3399
3400        #[tokio::test]
3401        async fn a_metadata_change_it_cannot_take_is_refused_and_recorded() {
3402            let s = server().await;
3403            let op = operator(&s);
3404            let path = format!("/admin/tenants/{}/metadata", s.tenant);
3405            let bodies = [
3406                "",
3407                "{}",
3408                r#"{"metadata":null}"#,
3409                r#"{"metadata":"most"}"#,
3410                r#"{"metadata":"Full"}"#,
3411                r#"{"metadata":"full","retention":"5y"}"#,
3412            ];
3413            for body in bodies {
3414                let answer = call(&s, Method::PUT, &path, Some(&op), Some(body)).await;
3415                assert_eq!(answer.status(), 422, "{body}");
3416                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3417            }
3418            let unknown = format!("/admin/tenants/{}/metadata", TenantId([7; 16]));
3419            let body = Some(r#"{"metadata":"full"}"#);
3420            let answer = call(&s, Method::PUT, &unknown, Some(&op), body).await;
3421            assert_eq!(
3422                answer.status(),
3423                404,
3424                "a tenant id no tenant has is not found"
3425            );
3426            assert_eq!(problem(answer).await, "unknown-tenant", "its problem type");
3427            let refused = admin_log(&s, "tenant_metadata");
3428            assert_eq!(refused.len(), bodies.len() + 1, "every refusal is recorded");
3429            assert_eq!(
3430                s.tenants.metadata(s.tenant),
3431                Ok(Metadata::None),
3432                "unchanged"
3433            );
3434            s.tenants.close(s.tenant);
3435            let answer = call(&s, Method::PUT, &path, Some(&op), body).await;
3436            assert_eq!(
3437                answer.status(),
3438                503,
3439                "a closing tenant cannot change its level"
3440            );
3441            assert_eq!(problem(answer).await, "unavailable", "its problem type");
3442        }
3443
3444        #[tokio::test]
3445        async fn a_retention_change_for_a_closing_tenant_is_503() {
3446            let s = server().await;
3447            let op = operator(&s);
3448            s.tenants.close(s.tenant);
3449            let path = format!("/admin/tenants/{}", s.tenant);
3450            let body = Some(r#"{"retention":"5y"}"#);
3451            let answer = call(&s, Method::PATCH, &path, Some(&op), body).await;
3452            assert_eq!(answer.status(), 503);
3453            assert_eq!(problem(answer).await, "unavailable");
3454        }
3455
3456        #[tokio::test]
3457        async fn damage_is_500_on_every_admin_route() {
3458            let s = server().await;
3459            let op = operator(&s);
3460            let kept = key_id(&s.key(&[Scope::Read]));
3461            s.tenants
3462                .conn_for_test()
3463                .execute_batch(
3464                    "UPDATE tenant SET retention = 'x';
3465                     UPDATE api_key SET created_at = 'x' WHERE tenant IS NOT NULL;
3466                     CREATE TEMP TRIGGER no_key BEFORE INSERT ON api_key
3467                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3468                     CREATE TEMP TRIGGER no_revoke BEFORE UPDATE ON api_key
3469                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3470                     CREATE TEMP TRIGGER broken BEFORE INSERT ON tenant
3471                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3472                     CREATE TEMP TRIGGER broken_too BEFORE UPDATE ON tenant
3473                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;
3474                     CREATE TEMP TRIGGER broken_three BEFORE DELETE ON tenant
3475                     BEGIN SELECT RAISE(ABORT, 'the disk has failed'); END;",
3476                )
3477                .expect("damaged");
3478            for (method, path, body, _) in routes(s.tenant, kept) {
3479                let answer = call(&s, method.clone(), &path, Some(&op), body).await;
3480                assert_eq!(answer.status(), 500, "{method} {path}");
3481                assert_eq!(problem(answer).await, "internal");
3482            }
3483        }
3484
3485        #[tokio::test]
3486        async fn an_answer_that_cannot_be_recorded_is_503_on_every_admin_route() {
3487            let s = server().await;
3488            let op = operator(&s);
3489            let kept = key_id(&s.key(&[Scope::Read]));
3490            s.tenants.break_audit();
3491            for (method, path, body, _) in routes(s.tenant, kept) {
3492                let answer = call(&s, method.clone(), &path, Some(&op), body).await;
3493                assert_eq!(answer.status(), 503, "{method} {path}");
3494                assert_eq!(problem(answer).await, "audit-failed");
3495            }
3496            for body in ["{}", r#"{"retention":"5y"}"#] {
3497                let path = if body == "{}" {
3498                    "/admin/tenants".to_owned()
3499                } else {
3500                    format!("/admin/tenants/{}", TenantId([7; 16]))
3501                };
3502                let method = if body == "{}" {
3503                    Method::POST
3504                } else {
3505                    Method::PATCH
3506                };
3507                let answer = call(&s, method, &path, Some(&op), Some(body)).await;
3508                assert_eq!(problem(answer).await, "audit-failed", "a refusal too");
3509            }
3510            assert_eq!(
3511                s.tenants.list(Actor::Cli).err(),
3512                Some(crate::tenants::TenantError::AuditFailed)
3513            );
3514        }
3515
3516        /// Stores A.4 in the server's tenant with a key of its own.
3517        async fn stored(s: &Server) {
3518            let body = std::fs::read(format!(
3519                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
3520                env!("CARGO_MANIFEST_DIR")
3521            ))
3522            .expect("A.4");
3523            let answer = s
3524                .client()
3525                .post(s.url("/vcons"))
3526                .bearer_auth(s.key(&[Scope::Write]))
3527                .header("content-type", "application/vcon")
3528                .body(body)
3529                .send()
3530                .await
3531                .expect("an answer");
3532            assert_eq!(answer.status(), 201);
3533        }
3534
3535        fn listed(s: &Server) -> Vec<TenantId> {
3536            let tenants = s.tenants.list(Actor::Cli).expect("listed");
3537            tenants.into_iter().map(|t| t.id).collect()
3538        }
3539
3540        #[tokio::test]
3541        async fn an_empty_tenant_is_removed_with_204_then_unknown() {
3542            let s = server().await;
3543            let op = operator(&s);
3544            let beta = s.tenants.create(Actor::Cli, "beta", None).expect("made");
3545            let path = format!("/admin/tenants/{beta}");
3546            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3547            assert_eq!(answer.status(), 204);
3548            assert_eq!(listed(&s), vec![s.tenant]);
3549            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3550            assert_eq!(answer.status(), 404);
3551            assert_eq!(problem(answer).await, "unknown-tenant");
3552            let removed = admin_log(&s, "tenant_remove");
3553            let statuses: Vec<&Value> = removed.iter().map(|r| &r["status"]).collect();
3554            assert_eq!(statuses, [204, 404]);
3555        }
3556
3557        #[tokio::test]
3558        async fn a_tenant_holding_vcons_is_409_without_force_and_removed_with_it() {
3559            let s = server().await;
3560            let op = operator(&s);
3561            stored(&s).await;
3562            let reader = s.key(&[Scope::Read]);
3563            let path = format!("/admin/tenants/{}", s.tenant);
3564            for query in ["", "?force=false"] {
3565                let path = format!("{path}{query}");
3566                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3567                assert_eq!(answer.status(), 409, "{query}");
3568                assert_eq!(problem(answer).await, "holds-vcons", "{query}");
3569            }
3570            assert_eq!(listed(&s), vec![s.tenant], "still there");
3571
3572            let forced = format!("{path}?force=true");
3573            let answer = call(&s, Method::DELETE, &forced, Some(&op), None).await;
3574            assert_eq!(answer.status(), 204);
3575            assert_eq!(listed(&s), Vec::<TenantId>::new());
3576            let health = s
3577                .client()
3578                .get(s.url("/health"))
3579                .bearer_auth(&reader)
3580                .send()
3581                .await
3582                .expect("an answer");
3583            assert_eq!(health.status(), 401, "its keys went with it");
3584        }
3585
3586        #[tokio::test]
3587        async fn a_legal_hold_is_409_even_with_force() {
3588            let s = server().await;
3589            let op = operator(&s);
3590            stored(&s).await;
3591            let legal = s.key(&[Scope::Legal]);
3592            let hold = s
3593                .client()
3594                .put(s.url("/legal/vcons/01a07da8-c2bb-83e5-b9a2-279e0d16bc46/hold"))
3595                .bearer_auth(&legal)
3596                .send()
3597                .await
3598                .expect("an answer");
3599            assert_eq!(hold.status(), 204);
3600            let path = format!("/admin/tenants/{}?force=true", s.tenant);
3601            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3602            assert_eq!(answer.status(), 409);
3603            assert_eq!(problem(answer).await, "under-hold");
3604            assert_eq!(listed(&s), vec![s.tenant], "still there");
3605            let removed = admin_log(&s, "tenant_remove");
3606            assert_eq!(removed.len(), 1);
3607            assert_eq!(removed[0]["status"], 409);
3608            let read = s
3609                .client()
3610                .get(s.url("/legal/vcons/01a07da8-c2bb-83e5-b9a2-279e0d16bc46"))
3611                .bearer_auth(&legal)
3612                .send()
3613                .await
3614                .expect("an answer");
3615            assert_eq!(read.status(), 200, "the tenant is served again");
3616        }
3617
3618        #[tokio::test]
3619        async fn a_query_it_does_not_take_is_400_and_recorded() {
3620            let s = server().await;
3621            let op = operator(&s);
3622            let queries = [
3623                "force=yes",
3624                "force=TRUE",
3625                "force",
3626                "force=",
3627                "force=true&force=true",
3628                "force=true&other=1",
3629                "other=1",
3630            ];
3631            for query in queries {
3632                let path = format!("/admin/tenants/{}?{query}", s.tenant);
3633                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3634                assert_eq!(answer.status(), 400, "{query}");
3635                assert_eq!(problem(answer).await, "bad-query", "{query}");
3636            }
3637            let refused = admin_log(&s, "tenant_remove");
3638            assert_eq!(refused.len(), queries.len());
3639            assert!(refused.iter().all(|r| r["status"] == 400));
3640            assert_eq!(listed(&s), vec![s.tenant]);
3641        }
3642
3643        #[tokio::test]
3644        async fn a_removal_of_no_tenant_is_404_and_recorded() {
3645            let s = server().await;
3646            let op = operator(&s);
3647            let unknown = TenantId([7; 16]).to_string();
3648            for id in [unknown.as_str(), "acme"] {
3649                let path = format!("/admin/tenants/{id}?force=true");
3650                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3651                assert_eq!(answer.status(), 404, "{id}");
3652                assert_eq!(problem(answer).await, "unknown-tenant", "{id}");
3653            }
3654            let refused = admin_log(&s, "tenant_remove");
3655            assert_eq!(refused.len(), 2);
3656            assert!(refused.iter().all(|r| r["status"] == 404));
3657        }
3658
3659        #[tokio::test]
3660        async fn a_removal_of_a_closing_tenant_is_503() {
3661            let s = server().await;
3662            let op = operator(&s);
3663            s.tenants.close(s.tenant);
3664            let path = format!("/admin/tenants/{}", s.tenant);
3665            let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3666            assert_eq!(answer.status(), 503);
3667            assert_eq!(problem(answer).await, "unavailable");
3668        }
3669
3670        async fn health(s: &Server, token: &str) -> u16 {
3671            let answer = s.client().get(s.url("/health")).bearer_auth(token).send();
3672            answer.await.expect("an answer").status().as_u16()
3673        }
3674
3675        /// Issues a key over HTTP and returns its id and token.
3676        async fn issued(s: &Server, op: &str, body: &str) -> (String, String) {
3677            let path = format!("/admin/tenants/{}/keys", s.tenant);
3678            let answer = call(s, Method::POST, &path, Some(op), Some(body)).await;
3679            assert_eq!(answer.status(), 201, "{body}");
3680            assert_eq!(answer.headers()["cache-control"], "no-store");
3681            let made = json(answer).await;
3682            let id = made["id"].as_str().expect("an id").to_owned();
3683            let token = made["token"].as_str().expect("a token").to_owned();
3684            assert!(made["expires_at"].is_string(), "the expiry of the new key");
3685            assert_eq!(
3686                made.as_object().expect("an object").len(),
3687                3,
3688                "id, token and expires_at, nothing else"
3689            );
3690            assert_eq!(key_id(&token).to_string(), id, "the token names its key");
3691            (id, token)
3692        }
3693
3694        async fn key_list(s: &Server, op: &str) -> (String, Value) {
3695            let path = format!("/admin/tenants/{}/keys", s.tenant);
3696            let answer = call(s, Method::GET, &path, Some(op), None).await;
3697            assert_eq!(answer.status(), 200);
3698            assert_eq!(answer.headers()["content-type"], "application/json");
3699            let text = answer.text().await.expect("text");
3700            let listed = serde_json::from_str(&text).expect("JSON");
3701            (text, listed)
3702        }
3703
3704        #[tokio::test]
3705        async fn a_key_is_issued_with_201_and_its_token_shown_once() {
3706            let s = server().await;
3707            let op = operator(&s);
3708            let body = r#"{"scopes":["read","write"],"label":"ingest"}"#;
3709            let (id, token) = issued(&s, &op, body).await;
3710            assert_eq!(health(&s, &token).await, 200, "the token works");
3711            let (again, other) = issued(&s, &op, body).await;
3712            assert_ne!((&again, &other), (&id, &token), "each key is new");
3713
3714            let (text, listed) = key_list(&s, &op).await;
3715            for token in [&token, &other] {
3716                // vcs_<key id>_<secret>: the secret is base64url, whose
3717                // alphabet includes `_`, so it is all after the second `_`.
3718                let secret = token.splitn(3, '_').nth(2).expect("a secret");
3719                assert_eq!(secret.len(), 43, "the whole 32-byte secret");
3720                assert!(!text.contains(secret), "no token is listed");
3721            }
3722            let first = &listed[0];
3723            assert_eq!(first["id"], id.as_str());
3724            assert_eq!(
3725                first["scopes"],
3726                json!(["write", "read"]),
3727                "in the fixed order"
3728            );
3729            assert_eq!(first["label"], "ingest");
3730            assert_eq!(first["revoked_at"], Value::Null);
3731            let stored = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3732            let stored = stored.expect("listed")[0].created_at;
3733            let stored = stored.format(&Rfc3339).expect("RFC 3339");
3734            assert_eq!(first["created_at"], stored.as_str());
3735            let fields: Vec<&String> = first.as_object().expect("an object").keys().collect();
3736            assert_eq!(
3737                fields,
3738                [
3739                    "created_at",
3740                    "expires_at",
3741                    "id",
3742                    "label",
3743                    "last_used_at",
3744                    "revoked_at",
3745                    "scopes",
3746                    "tenant"
3747                ]
3748            );
3749            assert_eq!(first["tenant"], s.tenant.to_string().as_str());
3750
3751            let made = admin_log(&s, "key_create");
3752            assert_eq!(made.len(), 2);
3753            assert_eq!(made[0]["status"], 201);
3754            assert_eq!(made[0]["target"], id.as_str());
3755            let copied = s.tenant_log("key_create");
3756            assert_eq!(copied.len(), 2, "the tenant's log shows it");
3757            assert_eq!(copied[0]["target"], id.as_str());
3758            assert_eq!(admin_log(&s, "key_list")[0]["status"], 200);
3759        }
3760
3761        #[tokio::test]
3762        async fn a_revoked_key_answers_401_and_the_tenants_log_shows_it() {
3763            let s = server().await;
3764            let op = operator(&s);
3765            let (id, token) = issued(&s, &op, r#"{"scopes":["read"],"label":"a"}"#).await;
3766            let (_, kept) = issued(&s, &op, r#"{"scopes":["read"],"label":"b"}"#).await;
3767            let path = format!("/admin/keys/{id}");
3768            for _ in 0..2 {
3769                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3770                assert_eq!(answer.status(), 204, "again too");
3771            }
3772            assert_eq!(health(&s, &token).await, 401);
3773            assert_eq!(health(&s, &kept).await, 200, "only that key");
3774            let (_, listed) = key_list(&s, &op).await;
3775            assert!(listed[0]["revoked_at"].is_string(), "{listed}");
3776            assert_eq!(listed[1]["revoked_at"], Value::Null);
3777            let revoked = s.tenant_log("key_revoke");
3778            assert_eq!(revoked.len(), 2);
3779            assert!(
3780                revoked
3781                    .iter()
3782                    .all(|r| r["status"] == 204 && r["target"] == id.as_str())
3783            );
3784            assert_eq!(admin_log(&s, "key_revoke").len(), 2);
3785        }
3786
3787        #[tokio::test]
3788        async fn scopes_a_tenant_key_cannot_hold_are_422_and_recorded() {
3789            let s = server().await;
3790            let op = operator(&s);
3791            let path = format!("/admin/tenants/{}/keys", s.tenant);
3792            let scopes = [
3793                "[]",
3794                r#"["admin"]"#,
3795                r#"["read","admin"]"#,
3796                r#"["superuser"]"#,
3797                r#"["read","superuser"]"#,
3798                r#"["Read"]"#,
3799                r#"["read","read"]"#,
3800            ];
3801            for scopes in scopes {
3802                let body = format!(r#"{{"scopes":{scopes},"label":"x"}}"#);
3803                let answer = call(&s, Method::POST, &path, Some(&op), Some(&body)).await;
3804                assert_eq!(answer.status(), 422, "{scopes}");
3805                assert_eq!(problem(answer).await, "bad-scopes", "{scopes}");
3806            }
3807            let refused = admin_log(&s, "key_create");
3808            assert_eq!(refused.len(), scopes.len(), "each recorded once");
3809            assert!(refused.iter().all(|r| r["status"] == 422));
3810            let keys = s.tenants.list_keys(Actor::Cli, Some(s.tenant));
3811            assert_eq!(keys.expect("listed").len(), 0, "no key made");
3812        }
3813
3814        #[tokio::test]
3815        async fn a_key_body_it_does_not_take_is_422_and_recorded() {
3816            let s = server().await;
3817            let op = operator(&s);
3818            let path = format!("/admin/tenants/{}/keys", s.tenant);
3819            let bodies = [
3820                "",
3821                "{}",
3822                r#"{"scopes":["read"]}"#,
3823                r#"{"label":"x"}"#,
3824                r#"{"scopes":"read","label":"x"}"#,
3825                r#"{"scopes":["read"],"label":7}"#,
3826                r#"{"scopes":["read"],"label":"x","tenant":"y"}"#,
3827            ];
3828            for body in bodies {
3829                let answer = call(&s, Method::POST, &path, Some(&op), Some(body)).await;
3830                assert_eq!(answer.status(), 422, "{body}");
3831                assert_eq!(problem(answer).await, "invalid-body", "{body}");
3832            }
3833            let refused = admin_log(&s, "key_create");
3834            assert_eq!(refused.len(), bodies.len());
3835            assert!(refused.iter().all(|r| r["status"] == 422));
3836        }
3837
3838        #[tokio::test]
3839        async fn key_routes_for_no_tenant_or_no_key_are_404_and_recorded() {
3840            let s = server().await;
3841            let op = operator(&s);
3842            let body = Some(r#"{"scopes":["read"],"label":"x"}"#);
3843            let unknown = TenantId([7; 16]).to_string();
3844            for id in [unknown.as_str(), "acme"] {
3845                let path = format!("/admin/tenants/{id}/keys");
3846                let answer = call(&s, Method::POST, &path, Some(&op), body).await;
3847                assert_eq!(answer.status(), 404, "POST {id}");
3848                assert_eq!(problem(answer).await, "unknown-tenant");
3849                let answer = call(&s, Method::GET, &path, Some(&op), None).await;
3850                assert_eq!(answer.status(), 404, "GET {id}");
3851                assert_eq!(problem(answer).await, "unknown-tenant");
3852            }
3853            let unknown_key = KeyId([7; 8]).to_string();
3854            for id in [unknown_key.as_str(), "acme", &unknown_key.to_uppercase()] {
3855                let path = format!("/admin/keys/{id}");
3856                let answer = call(&s, Method::DELETE, &path, Some(&op), None).await;
3857                assert_eq!(answer.status(), 404, "DELETE {id}");
3858                assert_eq!(problem(answer).await, "unknown-key");
3859            }
3860            for (action, count) in [("key_create", 2), ("key_list", 2), ("key_revoke", 3)] {
3861                let refused = admin_log(&s, action);
3862                assert_eq!(refused.len(), count, "{action}");
3863                assert!(refused.iter().all(|r| r["status"] == 404), "{action}");
3864            }
3865        }
3866
3867        #[tokio::test]
3868        async fn requests_during_a_removal_get_503_then_401() {
3869            let s = server().await;
3870            let op = operator(&s);
3871            stored(&s).await;
3872            let uuid = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
3873            let writer = s.key(&[Scope::Write]);
3874            let reader = s.key(&[Scope::Read]);
3875            let legal = s.key(&[Scope::Legal]);
3876            let a4 = std::fs::read(format!(
3877                "{}/../vcon/tests/fixtures/ietf/ab_call_ext_rec.vcon",
3878                env!("CARGO_MANIFEST_DIR")
3879            ))
3880            .expect("A.4");
3881            let requests = || {
3882                let client = s.client();
3883                [
3884                    client
3885                        .post(s.url("/vcons"))
3886                        .bearer_auth(&writer)
3887                        .header("content-type", "application/vcon")
3888                        .body(a4.clone()),
3889                    client
3890                        .get(s.url(&format!("/vcons/{uuid}")))
3891                        .bearer_auth(&reader),
3892                    client
3893                        .get(s.url(&format!("/legal/vcons/{uuid}")))
3894                        .bearer_auth(&legal),
3895                    client.get(s.url("/health")).bearer_auth(&reader),
3896                ]
3897            };
3898
3899            // A request still holding the tenant keeps the removal draining.
3900            let in_flight = s.tenants.store(s.tenant).expect("its store");
3901            let removal = {
3902                let request = s
3903                    .client()
3904                    .delete(s.url(&format!("/admin/tenants/{}?force=true", s.tenant)))
3905                    .bearer_auth(&op);
3906                tokio::spawn(async move { request.send().await.expect("an answer").status() })
3907            };
3908            let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
3909            while s.tenants.store(s.tenant).is_ok() {
3910                assert!(
3911                    tokio::time::Instant::now() < deadline,
3912                    "the removal never began"
3913                );
3914                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
3915            }
3916            for request in requests() {
3917                let answer = request.send().await.expect("an answer");
3918                let url = answer.url().path().to_owned();
3919                assert_eq!(answer.status(), 503, "{url} while removing");
3920                assert_eq!(problem(answer).await, "unavailable", "{url}");
3921            }
3922            assert!(!removal.is_finished(), "still draining");
3923
3924            drop(in_flight);
3925            assert_eq!(removal.await.expect("joined"), 204);
3926            for request in requests() {
3927                let answer = request.send().await.expect("an answer");
3928                let url = answer.url().path().to_owned();
3929                assert_eq!(answer.status(), 401, "{url} once removed");
3930            }
3931        }
3932
3933        #[tokio::test]
3934        async fn a_key_for_a_closing_tenant_is_503() {
3935            let s = server().await;
3936            let op = operator(&s);
3937            s.tenants.close(s.tenant);
3938            let path = format!("/admin/tenants/{}/keys", s.tenant);
3939            let body = Some(r#"{"scopes":["read"],"label":"x"}"#);
3940            let answer = call(&s, Method::POST, &path, Some(&op), body).await;
3941            assert_eq!(answer.status(), 503);
3942            assert_eq!(problem(answer).await, "unavailable");
3943        }
3944
3945        #[tokio::test]
3946        async fn a_body_over_the_limit_is_413() {
3947            let s = server().await;
3948            let op = operator(&s);
3949            let body = format!(r#"{{"name":"{}"}}"#, "x".repeat(super::pipeline::LIMIT));
3950            let answer = call(&s, Method::POST, "/admin/tenants", Some(&op), Some(&body)).await;
3951            assert_eq!(answer.status(), 413);
3952            assert_eq!(problem(answer).await, "too-large");
3953        }
3954    }
3955
3956    mod by_uuid {
3957        use super::pipeline::{START, Server, problem, server, server_keeping};
3958        use crate::access::{Scope, Scopes};
3959        use crate::audit::Actor;
3960        use crate::ids::TenantId;
3961        use crate::retention::Retention;
3962
3963        const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
3964
3965        fn fixture(name: &str) -> Vec<u8> {
3966            let path = format!(
3967                "{}/../vcon/tests/fixtures/ietf/{name}",
3968                env!("CARGO_MANIFEST_DIR")
3969            );
3970            std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
3971        }
3972
3973        fn gzip(body: &[u8]) -> Vec<u8> {
3974            use std::io::Write;
3975            let mut encoder =
3976                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
3977            encoder.write_all(body).expect("gzip");
3978            encoder.finish().expect("gzip")
3979        }
3980
3981        /// A key of this tenant's with these scopes.
3982        fn key_in(s: &Server, tenant: TenantId, scopes: &[Scope]) -> String {
3983            s.tenants
3984                .create_key(Actor::Cli, Some(tenant), Scopes::of(scopes), "test")
3985                .expect("a key")
3986                .token
3987        }
3988
3989        async fn get(s: &Server, token: &str, uuid: &str) -> reqwest::Response {
3990            s.client()
3991                .get(s.url(&format!("/vcons/{uuid}")))
3992                .bearer_auth(token)
3993                .send()
3994                .await
3995                .expect("an answer")
3996        }
3997
3998        async fn post(s: &Server, token: &str, content_type: &str, body: Vec<u8>) -> String {
3999            let answer = s
4000                .client()
4001                .post(s.url("/vcons"))
4002                .bearer_auth(token)
4003                .header("content-type", content_type)
4004                .body(body)
4005                .send()
4006                .await
4007                .expect("an answer");
4008            assert_eq!(answer.status(), 201);
4009            answer.headers()["etag"].to_str().expect("ascii").to_owned()
4010        }
4011
4012        /// A.4, A.6 and A.7 share one uuid, so each runs in its own tenant.
4013        #[tokio::test]
4014        async fn the_core_examples_come_back_byte_for_byte_plain_and_gzipped() {
4015            let s = server().await;
4016            let files = [
4017                "ab_call_ext_rec.vcon",
4018                "ab_call_ext_rec_signed.vcon",
4019                "ab_call_ext_rec_encrypted.vcon",
4020            ];
4021            for (n, file) in files.into_iter().enumerate() {
4022                for gzipped in [false, true] {
4023                    let tenant = s
4024                        .tenants
4025                        .create(Actor::Cli, &format!("t{n}{gzipped}"), None)
4026                        .expect("a tenant");
4027                    let token = key_in(&s, tenant, &[Scope::Write, Scope::Read]);
4028                    let plain = fixture(file);
4029                    let (sent, content_type) = if gzipped {
4030                        (gzip(&plain), "application/vcon+gzip")
4031                    } else {
4032                        (plain, "application/vcon")
4033                    };
4034                    let tag = post(&s, &token, content_type, sent.clone()).await;
4035                    let answer = get(&s, &token, UUID).await;
4036                    assert_eq!(answer.status(), 200, "{file} {gzipped}");
4037                    assert_eq!(answer.headers()["content-type"], content_type);
4038                    assert_eq!(answer.headers()["etag"], tag.as_str());
4039                    assert!(answer.headers().get("content-encoding").is_none());
4040                    let got = answer.bytes().await.expect("body");
4041                    assert_eq!(got.as_ref(), sent.as_slice(), "{file} {gzipped}");
4042                }
4043            }
4044        }
4045
4046        #[tokio::test]
4047        async fn a_uuid_is_found_in_either_case() {
4048            let s = server().await;
4049            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4050            post(
4051                &s,
4052                &token,
4053                "application/vcon",
4054                fixture("ab_call_ext_rec.vcon"),
4055            )
4056            .await;
4057            let answer = get(&s, &token, &UUID.to_uppercase()).await;
4058            assert_eq!(answer.status(), 200);
4059        }
4060
4061        #[tokio::test]
4062        async fn a_uuid_never_stored_is_not_found_and_a_deleted_one_is_gone() {
4063            let s = server().await;
4064            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4065            let answer = get(&s, &token, UUID).await;
4066            assert_eq!(answer.status(), 404);
4067            assert_eq!(problem(answer).await, "not-found");
4068            post(
4069                &s,
4070                &token,
4071                "application/vcon",
4072                fixture("ab_call_ext_rec.vcon"),
4073            )
4074            .await;
4075            s.tenants
4076                .store(s.tenant)
4077                .expect("its store")
4078                .delete(
4079                    &crate::store::Caller {
4080                        key: crate::ids::KeyId([9; 8]),
4081                    },
4082                    UUID.parse().expect("uuid"),
4083                    crate::retention::Retention::Years(7),
4084                )
4085                .expect("deleted");
4086            let answer = get(&s, &token, UUID).await;
4087            assert_eq!(answer.status(), 410);
4088            assert_eq!(problem(answer).await, "gone");
4089        }
4090
4091        #[tokio::test]
4092        async fn a_path_uuid_not_in_text_form_is_a_bad_request_and_recorded() {
4093            let s = server().await;
4094            let token = key_in(&s, s.tenant, &[Scope::Read]);
4095            let simple = UUID.replace('-', "");
4096            for bad in [
4097                "not-a-uuid".to_owned(),
4098                simple.clone(),
4099                format!("%7B{UUID}%7D"),
4100                format!("urn:uuid:{UUID}"),
4101                format!("{UUID}0"),
4102            ] {
4103                let answer = get(&s, &token, &bad).await;
4104                assert_eq!(answer.status(), 400, "{bad}");
4105                assert_eq!(problem(answer).await, "bad-path-uuid");
4106            }
4107            let refused = s.tenant_log("read");
4108            assert_eq!(refused.len(), 5);
4109            assert_eq!(refused[0]["status"], 400);
4110        }
4111
4112        #[tokio::test]
4113        async fn a_key_without_read_is_forbidden() {
4114            let s = server().await;
4115            let token = key_in(&s, s.tenant, &[Scope::Write]);
4116            let answer = get(&s, &token, UUID).await;
4117            assert_eq!(answer.status(), 403);
4118        }
4119
4120        #[tokio::test]
4121        async fn a_read_whose_record_fails_sends_nothing() {
4122            let s = server().await;
4123            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4124            post(
4125                &s,
4126                &token,
4127                "application/vcon",
4128                fixture("ab_call_ext_rec.vcon"),
4129            )
4130            .await;
4131            s.tenants.store(s.tenant).expect("its store").break_audit();
4132            let answer = get(&s, &token, UUID).await;
4133            assert_eq!(answer.status(), 503);
4134            assert_eq!(problem(answer).await, "audit-failed");
4135        }
4136
4137        #[tokio::test]
4138        async fn a_version_whose_file_is_missing_is_damaged() {
4139            let s = server().await;
4140            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4141            let tag = post(
4142                &s,
4143                &token,
4144                "application/vcon",
4145                fixture("ab_call_ext_rec.vcon"),
4146            )
4147            .await;
4148            let object = s
4149                .dir()
4150                .join("tenants")
4151                .join(s.tenant.to_string())
4152                .join("objects")
4153                .join(tag.trim_matches('"'));
4154            std::fs::remove_file(&object).expect("remove the object file");
4155            let answer = get(&s, &token, UUID).await;
4156            assert_eq!(answer.status(), 500);
4157            assert_eq!(problem(answer).await, "damaged");
4158        }
4159
4160        async fn put(
4161            s: &Server,
4162            token: &str,
4163            uuid: &str,
4164            if_match: Option<&str>,
4165            body: Vec<u8>,
4166        ) -> reqwest::Response {
4167            let mut request = s
4168                .client()
4169                .put(s.url(&format!("/vcons/{uuid}")))
4170                .bearer_auth(token)
4171                .header("content-type", "application/vcon")
4172                .body(body);
4173            if let Some(tag) = if_match {
4174                request = request.header("if-match", tag);
4175            }
4176            request.send().await.expect("an answer")
4177        }
4178
4179        /// A writer and reader in the fixture's tenant, with A.4 stored.
4180        async fn stored_a4(s: &Server) -> (String, String) {
4181            let token = key_in(s, s.tenant, &[Scope::Write, Scope::Read]);
4182            let tag = post(
4183                s,
4184                &token,
4185                "application/vcon",
4186                fixture("ab_call_ext_rec.vcon"),
4187            )
4188            .await;
4189            (token, tag)
4190        }
4191
4192        /// An unsigned vCon may be replaced by its signed form, and a signed
4193        /// one is replaced by nothing.
4194        #[tokio::test]
4195        async fn a4_then_a6_by_put_and_a7_after_a6_conflicts() {
4196            let s = server().await;
4197            let (token, a4) = stored_a4(&s).await;
4198            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4199            let answer = put(&s, &token, UUID, Some(&a4), a6.clone()).await;
4200            assert_eq!(answer.status(), 200);
4201            let new_tag = answer.headers()["etag"].to_str().expect("ascii").to_owned();
4202            assert_ne!(new_tag, a4);
4203            let read = get(&s, &token, UUID).await;
4204            assert_eq!(read.headers()["etag"], new_tag.as_str());
4205            assert_eq!(read.bytes().await.expect("body").as_ref(), a6.as_slice());
4206
4207            let a7 = fixture("ab_call_ext_rec_encrypted.vcon");
4208            let answer = put(&s, &token, UUID, Some(&new_tag), a7).await;
4209            assert_eq!(answer.status(), 409);
4210            assert_eq!(problem(answer).await, "immutable");
4211        }
4212
4213        #[tokio::test]
4214        async fn a_put_without_if_match_is_refused_and_recorded() {
4215            let s = server().await;
4216            let (token, _) = stored_a4(&s).await;
4217            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4218            let answer = put(&s, &token, UUID, None, a6).await;
4219            assert_eq!(answer.status(), 428);
4220            assert_eq!(problem(answer).await, "precondition-required");
4221            assert_eq!(s.tenant_log("replace")[0]["status"], 428);
4222        }
4223
4224        #[tokio::test]
4225        async fn an_if_match_that_does_not_name_the_current_version_fails() {
4226            let s = server().await;
4227            let (token, a4) = stored_a4(&s).await;
4228            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4229            let weak = format!("W/{a4}");
4230            let listed = format!("{a4}, \"00000000000000000000000000000000\"");
4231            let stale = format!("\"{}\"", crate::ids::VersionId([7; 16]));
4232            for tag in [
4233                "*",
4234                weak.as_str(),
4235                listed.as_str(),
4236                "garbage",
4237                stale.as_str(),
4238            ] {
4239                let answer = put(&s, &token, UUID, Some(tag), a6.clone()).await;
4240                assert_eq!(answer.status(), 412, "{tag}");
4241                assert_eq!(problem(answer).await, "precondition-failed");
4242            }
4243            let current = get(&s, &token, UUID).await;
4244            assert_eq!(current.headers()["etag"], a4.as_str(), "nothing replaced");
4245        }
4246
4247        #[tokio::test]
4248        async fn a_body_naming_another_uuid_is_unprocessable() {
4249            let s = server().await;
4250            let (token, a4) = stored_a4(&s).await;
4251            let (_, other) =
4252                crate::store::testing::vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "x");
4253            let answer = put(&s, &token, UUID, Some(&a4), other).await;
4254            assert_eq!(answer.status(), 422);
4255            assert_eq!(problem(answer).await, "path-uuid-mismatch");
4256            assert_eq!(s.tenant_log("replace")[0]["status"], 422);
4257        }
4258
4259        #[tokio::test]
4260        async fn a_put_to_a_uuid_never_stored_or_deleted_or_badly_written() {
4261            let s = server().await;
4262            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read]);
4263            let tag = format!("\"{}\"", crate::ids::VersionId([7; 16]));
4264            let a4 = fixture("ab_call_ext_rec.vcon");
4265            let answer = put(&s, &token, UUID, Some(&tag), a4.clone()).await;
4266            assert_eq!(answer.status(), 404);
4267            assert_eq!(problem(answer).await, "not-found");
4268
4269            let answer = put(&s, &token, "not-a-uuid", Some(&tag), a4.clone()).await;
4270            assert_eq!(answer.status(), 400);
4271            assert_eq!(problem(answer).await, "bad-path-uuid");
4272
4273            let a4_tag = post(&s, &token, "application/vcon", a4.clone()).await;
4274            s.tenants
4275                .store(s.tenant)
4276                .expect("its store")
4277                .delete(
4278                    &crate::store::Caller {
4279                        key: crate::ids::KeyId([9; 8]),
4280                    },
4281                    UUID.parse().expect("uuid"),
4282                    crate::retention::Retention::Years(7),
4283                )
4284                .expect("deleted");
4285            let answer = put(&s, &token, UUID, Some(&a4_tag), a4).await;
4286            assert_eq!(answer.status(), 410);
4287            assert_eq!(problem(answer).await, "gone");
4288        }
4289
4290        #[tokio::test]
4291        async fn a_put_needs_write_and_a_vcon_media_type() {
4292            let s = server().await;
4293            let (_, a4) = stored_a4(&s).await;
4294            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4295            let a6 = fixture("ab_call_ext_rec_signed.vcon");
4296            let answer = put(&s, &reader, UUID, Some(&a4), a6.clone()).await;
4297            assert_eq!(answer.status(), 403);
4298            let writer = key_in(&s, s.tenant, &[Scope::Write]);
4299            let answer = s
4300                .client()
4301                .put(s.url(&format!("/vcons/{UUID}")))
4302                .bearer_auth(&writer)
4303                .header("content-type", "text/plain")
4304                .header("if-match", &a4)
4305                .body(a6)
4306                .send()
4307                .await
4308                .expect("an answer");
4309            assert_eq!(answer.status(), 415);
4310        }
4311
4312        async fn delete(s: &Server, token: &str, uuid: &str) -> reqwest::Response {
4313            s.client()
4314                .delete(s.url(&format!("/vcons/{uuid}")))
4315                .bearer_auth(token)
4316                .send()
4317                .await
4318                .expect("an answer")
4319        }
4320
4321        #[tokio::test]
4322        async fn a_delete_answers_204_again_and_again() {
4323            let s = server().await;
4324            let token = key_in(&s, s.tenant, &[Scope::Write, Scope::Read, Scope::Delete]);
4325            post(
4326                &s,
4327                &token,
4328                "application/vcon",
4329                fixture("ab_call_ext_rec.vcon"),
4330            )
4331            .await;
4332            for _ in 0..2 {
4333                let answer = delete(&s, &token, UUID).await;
4334                assert_eq!(answer.status(), 204);
4335                assert!(answer.bytes().await.expect("body").is_empty());
4336            }
4337            assert_eq!(get(&s, &token, UUID).await.status(), 410);
4338            let deletes = s.tenant_log("delete");
4339            assert_eq!(deletes.len(), 2, "Store records each");
4340        }
4341
4342        #[tokio::test]
4343        async fn a_delete_of_a_uuid_never_stored_or_badly_written() {
4344            let s = server().await;
4345            let token = key_in(&s, s.tenant, &[Scope::Delete]);
4346            let answer = delete(&s, &token, UUID).await;
4347            assert_eq!(answer.status(), 404);
4348            assert_eq!(problem(answer).await, "not-found");
4349            let answer = delete(&s, &token, "not-a-uuid").await;
4350            assert_eq!(answer.status(), 400);
4351            assert_eq!(problem(answer).await, "bad-path-uuid");
4352            assert_eq!(
4353                s.tenant_log("delete").last().expect("recorded")["status"],
4354                400
4355            );
4356        }
4357
4358        #[tokio::test]
4359        async fn a_delete_needs_the_delete_scope_and_its_record() {
4360            let s = server().await;
4361            let (writer, _) = stored_a4(&s).await;
4362            let answer = delete(&s, &writer, UUID).await;
4363            assert_eq!(answer.status(), 403);
4364            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4365            s.tenants.store(s.tenant).expect("its store").break_audit();
4366            let answer = delete(&s, &deleter, UUID).await;
4367            assert_eq!(answer.status(), 503);
4368            assert_eq!(problem(answer).await, "audit-failed");
4369        }
4370
4371        /// The purge records of `s`'s tenant whose actor is `token`'s key.
4372        fn purged_by(s: &Server, token: &str) -> usize {
4373            s.tenant_log("purge")
4374                .iter()
4375                .filter(|r| r["actor"] == token[4..20])
4376                .count()
4377        }
4378
4379        #[tokio::test]
4380        async fn a_delete_erases_at_once_under_the_tenants_zero_period() {
4381            let s = server().await;
4382            s.tenants
4383                .set_retention(Actor::Cli, s.tenant, Some(Retention::Days(0)))
4384                .expect("set");
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_uses_the_server_default_when_the_tenant_sets_none() {
4393            let s = server_keeping(Retention::Days(0)).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), 1);
4398        }
4399
4400        #[tokio::test]
4401        async fn a_delete_keeps_a_young_vcon_for_legal_reads() {
4402            let s = server().await;
4403            let (_, _) = stored_a4(&s).await;
4404            let deleter = key_in(&s, s.tenant, &[Scope::Delete]);
4405            assert_eq!(delete(&s, &deleter, UUID).await.status(), 204);
4406            assert_eq!(purged_by(&s, &deleter), 0);
4407        }
4408
4409        #[tokio::test]
4410        async fn a_delete_whose_period_cannot_be_read_deletes_nothing() {
4411            let s = server().await;
4412            let (_, _) = stored_a4(&s).await;
4413            s.tenants
4414                .conn_for_test()
4415                .execute(
4416                    "UPDATE tenant SET retention = '7w' WHERE id = ?1",
4417                    [s.tenant.0],
4418                )
4419                .expect("damaged");
4420            let token = key_in(&s, s.tenant, &[Scope::Delete, Scope::Read]);
4421            let answer = delete(&s, &token, UUID).await;
4422            assert_eq!(answer.status(), 503);
4423            assert_eq!(problem(answer).await, "unavailable");
4424            assert_eq!(get(&s, &token, UUID).await.status(), 200);
4425            assert_eq!(
4426                s.tenant_log("delete").last().expect("recorded")["status"],
4427                503
4428            );
4429        }
4430
4431        async fn health(s: &Server, token: Option<&str>) -> reqwest::Response {
4432            let mut request = s.client().get(s.url("/health"));
4433            if let Some(token) = token {
4434                request = request.bearer_auth(token);
4435            }
4436            request.send().await.expect("an answer")
4437        }
4438
4439        #[tokio::test]
4440        async fn health_needs_a_key_of_any_scope_and_is_counted() {
4441            let s = server().await;
4442            assert_eq!(health(&s, None).await.status(), 401);
4443            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4444            for _ in 0..2 {
4445                let answer = health(&s, Some(&reader)).await;
4446                assert_eq!(answer.status(), 200);
4447                assert_eq!(answer.headers()["content-type"], "application/json");
4448            }
4449            let counted = s.tenant_log("health");
4450            assert_eq!(counted.len(), 1, "one record a minute");
4451            assert_eq!(counted[0]["count"], 2);
4452            assert_eq!(counted[0]["status"], 200);
4453            // The last second of the minute still counts in it; the next
4454            // minute starts a record of its own.
4455            s.clock.set(START + time::Duration::seconds(59));
4456            health(&s, Some(&reader)).await;
4457            s.clock.set(START + time::Duration::minutes(1));
4458            health(&s, Some(&reader)).await;
4459            let counted = s.tenant_log("health");
4460            assert_eq!(
4461                counted
4462                    .iter()
4463                    .map(|r| (
4464                        r["at"].as_str().expect("at"),
4465                        r["count"].as_u64().expect("count")
4466                    ))
4467                    .collect::<Vec<_>>(),
4468                [("2026-10-23T12:00:00Z", 3), ("2026-10-23T12:01:00Z", 1)],
4469                "a record counts the requests of its minute only"
4470            );
4471
4472            let operator = s
4473                .tenants
4474                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4475                .expect("made")
4476                .token;
4477            assert_eq!(health(&s, Some(&operator)).await.status(), 200);
4478            let admin: Vec<_> = s
4479                .tenants
4480                .admin_records()
4481                .into_iter()
4482                .filter(|r| r["action"] == "health")
4483                .collect();
4484            assert_eq!(admin.len(), 1);
4485            assert_eq!(admin[0]["actor"], operator[4..20]);
4486        }
4487
4488        #[tokio::test]
4489        async fn health_is_unavailable_when_the_catalog_does_not_answer() {
4490            let s = server().await;
4491            let reader = key_in(&s, s.tenant, &[Scope::Read]);
4492            s.tenants
4493                .conn_for_test()
4494                .execute_batch("ALTER TABLE tenant RENAME TO gone")
4495                .expect("lose the table");
4496            let answer = health(&s, Some(&reader)).await;
4497            assert_eq!(answer.status(), 503);
4498            assert_eq!(problem(answer).await, "unavailable");
4499        }
4500
4501        #[tokio::test]
4502        async fn health_whose_count_fails_is_unavailable() {
4503            let s = server().await;
4504            let operator = s
4505                .tenants
4506                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4507                .expect("made")
4508                .token;
4509            s.tenants.break_audit();
4510            let answer = health(&s, Some(&operator)).await;
4511            assert_eq!(answer.status(), 503);
4512            assert_eq!(problem(answer).await, "audit-failed");
4513        }
4514    }
4515
4516    /// `GET /openapi.json`: the description, to any valid key.
4517    mod openapi_route {
4518        use super::pipeline::{Server, problem, server};
4519        use crate::access::{Scope, Scopes};
4520        use crate::audit::Actor;
4521
4522        async fn get(s: &Server, token: Option<&str>) -> reqwest::Response {
4523            let mut request = s.client().get(s.url("/openapi.json"));
4524            if let Some(token) = token {
4525                request = request.bearer_auth(token);
4526            }
4527            request.send().await.expect("an answer")
4528        }
4529
4530        fn admin_openapi_records(s: &Server) -> usize {
4531            let mut out = Vec::new();
4532            s.tenants.export_admin(None, &mut out).expect("export");
4533            String::from_utf8(out)
4534                .expect("UTF-8")
4535                .lines()
4536                .filter(|l| l.contains("\"action\":\"openapi\""))
4537                .count()
4538        }
4539
4540        #[tokio::test]
4541        async fn any_valid_key_gets_the_description_as_compiled_and_it_is_recorded() {
4542            let s = server().await;
4543            let operator = s
4544                .tenants
4545                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4546                .expect("an operator key")
4547                .token;
4548            for token in [s.key(&[Scope::Read]), s.key(&[Scope::Write]), operator] {
4549                let answer = get(&s, Some(&token)).await;
4550                assert_eq!(answer.status(), 200);
4551                assert_eq!(answer.headers()["content-type"], "application/json");
4552                assert_eq!(answer.text().await.expect("text"), super::super::OPENAPI);
4553            }
4554            let recorded = s.tenant_log("openapi");
4555            assert_eq!(recorded.len(), 2, "the two tenant keys");
4556            assert!(recorded.iter().all(|r| r["status"] == 200));
4557            assert_eq!(admin_openapi_records(&s), 1, "the operator key");
4558        }
4559
4560        #[tokio::test]
4561        async fn no_key_is_401_and_a_read_that_cannot_be_recorded_503() {
4562            let s = server().await;
4563            let answer = get(&s, None).await;
4564            assert_eq!(answer.status(), 401);
4565            assert_eq!(problem(answer).await, "unauthorized");
4566            let reader = s.key(&[Scope::Read]);
4567            s.tenants.store(s.tenant).expect("its store").break_audit();
4568            let answer = get(&s, Some(&reader)).await;
4569            assert_eq!(answer.status(), 503);
4570            assert_eq!(problem(answer).await, "audit-failed");
4571        }
4572
4573        #[tokio::test]
4574        async fn a_key_of_a_closing_tenant_is_503() {
4575            let s = server().await;
4576            let reader = s.key(&[Scope::Read]);
4577            s.tenants.close(s.tenant);
4578            let answer = get(&s, Some(&reader)).await;
4579            assert_eq!(answer.status(), 503);
4580            assert_eq!(problem(answer).await, "unavailable");
4581        }
4582    }
4583
4584    /// `GET /audit` and `GET /admin/audit`: a log a page at a time, as the
4585    /// command line exports it.
4586    mod audit_routes {
4587        use super::pipeline::{Server, problem, server};
4588        use crate::access::{Scope, Scopes};
4589        use crate::audit::Actor;
4590        use crate::store::testing::vcon;
4591
4592        fn operator(s: &Server) -> String {
4593            s.tenants
4594                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
4595                .expect("an operator key")
4596                .token
4597        }
4598
4599        async fn get(s: &Server, path: &str, token: Option<&str>) -> reqwest::Response {
4600            let mut request = s.client().get(s.url(path));
4601            if let Some(token) = token {
4602                request = request.bearer_auth(token);
4603            }
4604            request.send().await.expect("an answer")
4605        }
4606
4607        async fn body(answer: reqwest::Response) -> Vec<u8> {
4608            assert_eq!(answer.status(), 200);
4609            assert_eq!(answer.headers()["content-type"], "application/jsonl");
4610            answer.bytes().await.expect("body").to_vec()
4611        }
4612
4613        /// The tenant's log as `audit export --tenant` writes it.
4614        fn tenant_export(s: &Server, since: Option<i64>) -> Vec<u8> {
4615            let mut out = Vec::new();
4616            s.tenants
4617                .store(s.tenant)
4618                .expect("its store")
4619                .export(since, &mut out)
4620                .expect("export");
4621            out
4622        }
4623
4624        fn admin_export(s: &Server) -> Vec<u8> {
4625            let mut out = Vec::new();
4626            s.tenants.export_admin(None, &mut out).expect("export");
4627            out
4628        }
4629
4630        async fn three_stored(s: &Server) {
4631            let writer = s.key(&[Scope::Write]);
4632            for n in 1..=3 {
4633                let answer = s
4634                    .client()
4635                    .post(s.url("/vcons"))
4636                    .bearer_auth(&writer)
4637                    .header("content-type", "application/vcon")
4638                    .body(vcon(&format!("01a07da8-c2bb-83e5-b9a2-{n:012x}"), "x").1)
4639                    .send()
4640                    .await
4641                    .expect("an answer");
4642                assert_eq!(answer.status(), 201);
4643            }
4644        }
4645
4646        #[tokio::test]
4647        async fn the_tenant_log_is_its_export_byte_for_byte_a_page_at_a_time() {
4648            let s = server().await;
4649            three_stored(&s).await;
4650            let auditor = s.key(&[Scope::Audit]);
4651            let before = tenant_export(&s, None);
4652            assert_eq!(body(get(&s, "/audit", Some(&auditor)).await).await, before);
4653            let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
4654            assert_eq!(
4655                body(get(&s, "/audit?after=1&limit=2", Some(&auditor)).await).await,
4656                lines[1..3].concat()
4657            );
4658            // The reads are recorded, each after its own page.
4659            let reads = s.tenant_log("audit_read");
4660            assert_eq!(reads.len(), 2);
4661            assert!(reads.iter().all(|r| r["status"] == 200));
4662            // The page is the log as it stood before the read, which then
4663            // records itself after it.
4664            let after = 3;
4665            let expected = tenant_export(&s, Some(after));
4666            assert!(
4667                !expected.is_empty(),
4668                "three stores and two reads leave records past seq 3"
4669            );
4670            let page = body(get(&s, &format!("/audit?after={after}"), Some(&auditor)).await).await;
4671            assert_eq!(
4672                page, expected,
4673                "the page is every record after seq 3, whole"
4674            );
4675        }
4676
4677        #[tokio::test]
4678        async fn the_admin_log_is_its_export_byte_for_byte() {
4679            let s = server().await;
4680            let op = operator(&s);
4681            let before = admin_export(&s);
4682            assert!(!before.is_empty(), "the tenant's creation, at least");
4683            assert_eq!(body(get(&s, "/admin/audit", Some(&op)).await).await, before);
4684            let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
4685            assert_eq!(
4686                body(get(&s, "/admin/audit?limit=1", Some(&op)).await).await,
4687                lines[0]
4688            );
4689            let mut recorded = Vec::new();
4690            s.tenants.export_admin(None, &mut recorded).expect("export");
4691            let reads = String::from_utf8(recorded)
4692                .expect("UTF-8")
4693                .lines()
4694                .filter(|l| l.contains("\"action\":\"audit_read\""))
4695                .count();
4696            assert_eq!(reads, 2);
4697        }
4698
4699        #[tokio::test]
4700        async fn the_tenant_log_needs_a_tenant_key_with_audit() {
4701            let s = server().await;
4702            assert_eq!(get(&s, "/audit", None).await.status(), 401);
4703            for scopes in [
4704                &[Scope::Read][..],
4705                &[Scope::Legal],
4706                &[Scope::Write, Scope::Delete],
4707            ] {
4708                let answer = get(&s, "/audit", Some(&s.key(scopes))).await;
4709                assert_eq!(answer.status(), 403, "{scopes:?}");
4710                assert_eq!(problem(answer).await, "forbidden");
4711            }
4712            let answer = get(&s, "/audit", Some(&operator(&s))).await;
4713            assert_eq!(answer.status(), 403, "an operator key");
4714            let refused = s.tenant_log("audit_read");
4715            assert_eq!(refused.len(), 3, "the tenant keys' refusals");
4716            assert!(refused.iter().all(|r| r["status"] == 403));
4717        }
4718
4719        #[tokio::test]
4720        async fn the_admin_log_needs_an_operator_key() {
4721            let s = server().await;
4722            assert_eq!(get(&s, "/admin/audit", None).await.status(), 401);
4723            let every = s.key(&[
4724                Scope::Write,
4725                Scope::Read,
4726                Scope::Delete,
4727                Scope::Legal,
4728                Scope::Audit,
4729            ]);
4730            let answer = get(&s, "/admin/audit", Some(&every)).await;
4731            assert_eq!(answer.status(), 403);
4732            assert_eq!(problem(answer).await, "forbidden");
4733            assert_eq!(s.tenant_log("audit_read").len(), 1, "recorded");
4734        }
4735
4736        #[tokio::test]
4737        async fn a_query_the_routes_do_not_take_is_a_bad_query_and_recorded() {
4738            let s = server().await;
4739            let auditor = s.key(&[Scope::Audit]);
4740            let op = operator(&s);
4741            let bad = [
4742                "?since=3",
4743                "?after=-1",
4744                "?limit=0",
4745                "?limit=10001",
4746                "?after=1&after=2",
4747            ];
4748            for query in bad {
4749                for (path, token) in [("/audit", &auditor), ("/admin/audit", &op)] {
4750                    let answer = get(&s, &format!("{path}{query}"), Some(token)).await;
4751                    assert_eq!(answer.status(), 400, "{path}{query}");
4752                    assert_eq!(problem(answer).await, "bad-query");
4753                }
4754            }
4755            let refused = s.tenant_log("audit_read");
4756            assert_eq!(refused.len(), bad.len());
4757            assert!(refused.iter().all(|r| r["status"] == 400));
4758            let mut admin = Vec::new();
4759            s.tenants.export_admin(None, &mut admin).expect("export");
4760            let admin_refused = String::from_utf8(admin)
4761                .expect("UTF-8")
4762                .lines()
4763                .filter(|l| l.contains("\"action\":\"audit_read\"") && l.contains("\"status\":400"))
4764                .count();
4765            assert_eq!(admin_refused, bad.len());
4766        }
4767
4768        #[tokio::test]
4769        async fn a_read_that_cannot_be_recorded_is_503() {
4770            let s = server().await;
4771            let auditor = s.key(&[Scope::Audit]);
4772            let op = operator(&s);
4773            s.tenants.store(s.tenant).expect("its store").break_audit();
4774            let answer = get(&s, "/audit", Some(&auditor)).await;
4775            assert_eq!(answer.status(), 503);
4776            assert_eq!(problem(answer).await, "audit-failed");
4777            s.tenants.break_audit();
4778            let answer = get(&s, "/admin/audit", Some(&op)).await;
4779            assert_eq!(answer.status(), 503);
4780            assert_eq!(problem(answer).await, "audit-failed");
4781        }
4782    }
4783
4784    /// `GET /vcons`: a tenant's live vCons, a page at a time.
4785    mod list {
4786        use serde_json::Value;
4787
4788        use super::pipeline::{START, Server, problem, server};
4789        use crate::access::{Scope, Scopes};
4790        use crate::audit::Actor;
4791        use crate::ids::TenantId;
4792        use crate::store::testing::vcon;
4793
4794        fn uuid(n: u32) -> String {
4795            format!("01a07da8-c2bb-83e5-b9a2-{n:012x}")
4796        }
4797
4798        fn key_of(s: &Server, tenant: TenantId, scopes: &[Scope]) -> String {
4799            s.tenants
4800                .create_key(Actor::Cli, Some(tenant), Scopes::of(scopes), "test")
4801                .expect("a key")
4802                .token
4803        }
4804
4805        /// Stores vCon `n` with `writer` and returns its tag, unquoted.
4806        async fn stored(s: &Server, writer: &str, n: u32) -> String {
4807            let answer = s
4808                .client()
4809                .post(s.url("/vcons"))
4810                .bearer_auth(writer)
4811                .header("content-type", "application/vcon")
4812                .body(vcon(&uuid(n), "listed").1)
4813                .send()
4814                .await
4815                .expect("an answer");
4816            assert_eq!(answer.status(), 201);
4817            answer.headers()["etag"]
4818                .to_str()
4819                .expect("text")
4820                .trim_matches('"')
4821                .to_owned()
4822        }
4823
4824        async fn list(s: &Server, token: Option<&str>, query: &str) -> reqwest::Response {
4825            let mut request = s.client().get(s.url(&format!("/vcons{query}")));
4826            if let Some(token) = token {
4827                request = request.bearer_auth(token);
4828            }
4829            request.send().await.expect("an answer")
4830        }
4831
4832        async fn page(s: &Server, reader: &str, query: &str) -> Value {
4833            let answer = list(s, Some(reader), query).await;
4834            assert_eq!(answer.status(), 200, "{query}");
4835            assert_eq!(answer.headers()["content-type"], "application/json");
4836            serde_json::from_str(&answer.text().await.expect("text")).expect("JSON")
4837        }
4838
4839        fn uuids(page: &Value) -> Vec<String> {
4840            page["vcons"]
4841                .as_array()
4842                .expect("a list")
4843                .iter()
4844                .map(|v| v["uuid"].as_str().expect("a uuid").to_owned())
4845                .collect()
4846        }
4847
4848        /// Every vCon the reader's pages list, following `next`.
4849        async fn every_page(s: &Server, reader: &str, limit: u32) -> Vec<String> {
4850            let mut seen = Vec::new();
4851            let mut query = format!("?limit={limit}");
4852            for _ in 0..100 {
4853                let page = page(s, reader, &query).await;
4854                seen.extend(uuids(&page));
4855                match page["next"].as_str() {
4856                    Some(cursor) => query = format!("?limit={limit}&cursor={cursor}"),
4857                    None => return seen,
4858                }
4859            }
4860            panic!("the cursors end")
4861        }
4862
4863        #[tokio::test]
4864        async fn the_list_is_newest_first_with_each_tag_and_time() {
4865            let s = server().await;
4866            let writer = s.key(&[Scope::Write]);
4867            let mut tags = Vec::new();
4868            for n in 1..=3 {
4869                tags.push(stored(&s, &writer, n).await);
4870            }
4871            let reader = s.key(&[Scope::Read]);
4872            let page = page(&s, &reader, "").await;
4873            assert_eq!(uuids(&page), [3, 2, 1].map(uuid));
4874            assert_eq!(page["next"], Value::Null);
4875            for (listed, tag) in page["vcons"]
4876                .as_array()
4877                .expect("a list")
4878                .iter()
4879                .zip(tags.iter().rev())
4880            {
4881                assert_eq!(listed["version"], tag.as_str());
4882                assert_eq!(listed["stored_at"], listed["updated_at"]);
4883                let at = listed["stored_at"].as_str().expect("a time");
4884                assert!(at.ends_with('Z'), "{at}");
4885            }
4886            let recorded = s.tenant_log("list");
4887            assert_eq!(recorded.len(), 1);
4888            assert_eq!(recorded[0]["status"], 200);
4889        }
4890
4891        #[tokio::test]
4892        async fn paging_returns_each_vcon_once_and_a_deleted_one_never() {
4893            let s = server().await;
4894            let writer = s.key(&[Scope::Write]);
4895            for n in 1..=7 {
4896                stored(&s, &writer, n).await;
4897            }
4898            let deleted = s
4899                .client()
4900                .delete(s.url(&format!("/vcons/{}", uuid(4))))
4901                .bearer_auth(s.key(&[Scope::Delete]))
4902                .send()
4903                .await
4904                .expect("an answer");
4905            assert_eq!(deleted.status(), 204);
4906            let reader = s.key(&[Scope::Read]);
4907            for limit in [1, 2, 3, 6, 7, 100] {
4908                assert_eq!(
4909                    every_page(&s, &reader, limit).await,
4910                    [7, 6, 5, 3, 2, 1].map(uuid),
4911                    "limit {limit}"
4912                );
4913            }
4914        }
4915
4916        #[tokio::test]
4917        async fn a_tenant_lists_its_own_vcons_never_another_tenants() {
4918            let s = server().await;
4919            let beta = s.tenants.create(Actor::Cli, "beta", None).expect("made");
4920            let acme_writer = s.key(&[Scope::Write]);
4921            let beta_writer = key_of(&s, beta, &[Scope::Write]);
4922            // Stored a second apart, acme's first: 1, 3, 5, then beta's
4923            // 2, 3, 4. vCon 3 is held by both tenants, each its own.
4924            let mut at = START;
4925            for (writer, n) in [(&acme_writer, 1), (&acme_writer, 3), (&acme_writer, 5)]
4926                .into_iter()
4927                .chain([(&beta_writer, 2), (&beta_writer, 3), (&beta_writer, 4)])
4928            {
4929                at += time::Duration::SECOND;
4930                s.clock.set(at);
4931                stored(&s, writer, n).await;
4932            }
4933            let acme = s.key(&[Scope::Read]);
4934            let beta_reader = key_of(&s, beta, &[Scope::Read]);
4935            assert_eq!(every_page(&s, &acme, 1).await, [5, 3, 1].map(uuid));
4936            assert_eq!(every_page(&s, &beta_reader, 1).await, [4, 3, 2].map(uuid));
4937            // A cursor from the other tenant's list only sets a place.
4938            let beta_page = page(&s, &beta_reader, "?limit=1").await;
4939            let cursor = beta_page["next"].as_str().expect("a cursor");
4940            // Beta's first, vCon 4, was stored after all of acme's, so the
4941            // place is before every acme vCon.
4942            let mixed = page(&s, &acme, &format!("?cursor={cursor}")).await;
4943            assert_eq!(
4944                uuids(&mixed),
4945                [5, 3, 1].map(uuid),
4946                "a foreign cursor sets a place in this tenant's list, and lists all of it after"
4947            );
4948        }
4949
4950        #[tokio::test]
4951        async fn since_and_until_bound_the_first_store_time() {
4952            let s = server().await;
4953            let writer = s.key(&[Scope::Write]);
4954            stored(&s, &writer, 1).await;
4955            let reader = s.key(&[Scope::Read]);
4956            let first = page(&s, &reader, "").await;
4957            let at = first["vcons"][0]["stored_at"]
4958                .as_str()
4959                .expect("a time")
4960                .to_owned();
4961            let at = at.replace(':', "%3A");
4962            assert_eq!(
4963                uuids(&page(&s, &reader, &format!("?since={at}")).await),
4964                vec![uuid(1)]
4965            );
4966            assert_eq!(
4967                uuids(&page(&s, &reader, &format!("?until={at}")).await),
4968                Vec::<String>::new()
4969            );
4970        }
4971
4972        #[tokio::test]
4973        async fn a_query_the_route_does_not_take_is_a_bad_query_and_recorded() {
4974            let s = server().await;
4975            let reader = s.key(&[Scope::Read]);
4976            let bad = [
4977                "?offset=2",
4978                "?limit=0",
4979                "?limit=1001",
4980                "?limit=ten",
4981                "?limit=1&limit=2",
4982                "?cursor=nope",
4983                "?since=yesterday",
4984                "?until=2026-10-25",
4985            ];
4986            for query in bad {
4987                let answer = list(&s, Some(&reader), query).await;
4988                assert_eq!(answer.status(), 400, "{query}");
4989                assert_eq!(problem(answer).await, "bad-query", "{query}");
4990            }
4991            let recorded = s.tenant_log("list");
4992            assert_eq!(recorded.len(), bad.len());
4993            assert!(recorded.iter().all(|r| r["status"] == 400));
4994        }
4995
4996        #[tokio::test]
4997        async fn the_list_needs_a_tenant_key_with_read() {
4998            let s = server().await;
4999            let answer = list(&s, None, "").await;
5000            assert_eq!(answer.status(), 401);
5001            for scopes in [&[Scope::Write][..], &[Scope::Delete], &[Scope::Legal]] {
5002                let answer = list(&s, Some(&s.key(scopes)), "").await;
5003                assert_eq!(answer.status(), 403, "{scopes:?}");
5004                assert_eq!(problem(answer).await, "forbidden");
5005            }
5006            let operator = s
5007                .tenants
5008                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
5009                .expect("an operator key")
5010                .token;
5011            let answer = list(&s, Some(&operator), "").await;
5012            assert_eq!(answer.status(), 403);
5013            let recorded = s.tenant_log("list");
5014            assert_eq!(recorded.len(), 3, "the tenant keys' refusals");
5015            assert!(recorded.iter().all(|r| r["status"] == 403));
5016        }
5017
5018        #[tokio::test]
5019        async fn damage_is_500_and_a_list_that_cannot_be_recorded_503() {
5020            let s = server().await;
5021            let writer = s.key(&[Scope::Write]);
5022            stored(&s, &writer, 1).await;
5023            let reader = s.key(&[Scope::Read]);
5024            let store = s.tenants.store(s.tenant).expect("its store");
5025            store
5026                .conn_for_test()
5027                .execute("DELETE FROM version", [])
5028                .expect("damaged");
5029            let answer = list(&s, Some(&reader), "").await;
5030            assert_eq!(answer.status(), 500);
5031            assert_eq!(problem(answer).await, "damaged");
5032            store.break_audit();
5033            let answer = list(&s, Some(&reader), "").await;
5034            assert_eq!(answer.status(), 503);
5035            assert_eq!(problem(answer).await, "audit-failed");
5036        }
5037    }
5038
5039    /// `GET /key`: a key learns its own id, tenant and scopes, and the
5040    /// request is recorded before the answer goes out.
5041    mod key_info {
5042        use serde_json::Value;
5043
5044        use super::pipeline::{Server, problem, server};
5045        use crate::access::{self, Scope, Scopes};
5046        use crate::audit::Actor;
5047
5048        async fn key(s: &Server, token: Option<&str>) -> reqwest::Response {
5049            let mut request = s.client().get(s.url("/key"));
5050            if let Some(token) = token {
5051                request = request.bearer_auth(token);
5052            }
5053            request.send().await.expect("an answer")
5054        }
5055
5056        /// What the key may do, and nothing else: its id, tenant and scopes.
5057        fn own(token: &str, tenant: Option<String>, scopes: &[&str]) -> Value {
5058            let id = access::parse(token).expect("a token").to_string();
5059            serde_json::json!({ "id": id, "tenant": tenant, "scopes": scopes })
5060        }
5061
5062        #[tokio::test]
5063        async fn a_tenant_key_reads_its_own_record_and_the_read_is_recorded() {
5064            let s = server().await;
5065            let token = s.key(&[Scope::Read, Scope::Delete]);
5066            let answer = key(&s, Some(&token)).await;
5067            assert_eq!(answer.status(), 200);
5068            assert_eq!(answer.headers()["content-type"], "application/json");
5069            assert_eq!(answer.headers()["cache-control"], "no-store");
5070            let body: Value =
5071                serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON");
5072            let tenant = Some(s.tenant.to_string());
5073            assert_eq!(body, own(&token, tenant, &["read", "delete"]));
5074            let records = s.tenant_log("key_info");
5075            assert_eq!(records.len(), 1, "one record per request");
5076            assert_eq!(records[0]["status"], 200);
5077            assert_eq!(records[0]["actor"], token[4..20]);
5078            assert_eq!(records[0]["target"], token[4..20], "the key read");
5079        }
5080
5081        #[tokio::test]
5082        async fn an_operator_key_reads_its_record_in_the_admin_log() {
5083            let s = server().await;
5084            let token = s
5085                .tenants
5086                .create_key(Actor::Cli, None, Scopes::of(&[Scope::Admin]), "op")
5087                .expect("made")
5088                .token;
5089            let answer = key(&s, Some(&token)).await;
5090            assert_eq!(answer.status(), 200);
5091            let body: Value =
5092                serde_json::from_slice(&answer.bytes().await.expect("body")).expect("JSON");
5093            assert_eq!(body, own(&token, None, &["admin"]));
5094            let records: Vec<_> = s
5095                .tenants
5096                .admin_records()
5097                .into_iter()
5098                .filter(|r| r["action"] == "key_info")
5099                .collect();
5100            assert_eq!(records.len(), 1);
5101            assert_eq!(records[0]["status"], 200);
5102            assert_eq!(records[0]["target"], token[4..20]);
5103            assert!(s.tenant_log("key_info").is_empty(), "no tenant's log");
5104        }
5105
5106        #[tokio::test]
5107        async fn no_key_or_a_bad_one_is_401() {
5108            let s = server().await;
5109            for token in [None, Some("vcs_nonsense")] {
5110                let answer = key(&s, token).await;
5111                let sent = if token.is_some() {
5112                    "a bad key"
5113                } else {
5114                    "no key"
5115                };
5116                assert_eq!(answer.status(), 401, "{sent}");
5117                assert_eq!(problem(answer).await, "unauthorized");
5118            }
5119        }
5120
5121        #[tokio::test]
5122        async fn a_read_that_cannot_be_recorded_shows_nothing() {
5123            let s = server().await;
5124            let token = s.key(&[Scope::Read]);
5125            s.tenants.store(s.tenant).expect("its store").break_audit();
5126            let answer = key(&s, Some(&token)).await;
5127            assert_eq!(answer.status(), 503);
5128            assert_eq!(problem(answer).await, "audit-failed");
5129        }
5130
5131        #[tokio::test]
5132        async fn a_key_whose_tenant_is_closing_is_503() {
5133            let s = server().await;
5134            let token = s.key(&[Scope::Read]);
5135            s.tenants.close(s.tenant);
5136            let answer = key(&s, Some(&token)).await;
5137            assert_eq!(answer.status(), 503);
5138            assert_eq!(problem(answer).await, "unavailable");
5139            let refused: Vec<_> = s
5140                .tenants
5141                .admin_records()
5142                .into_iter()
5143                .filter(|r| r["action"] == "key_info")
5144                .collect();
5145            assert_eq!(refused.len(), 1, "the refusal is recorded");
5146            assert_eq!(refused[0]["status"], 503);
5147        }
5148    }
5149
5150    /// The console's files are served through the API's own router, with
5151    /// its headers, and the API itself never asks a browser to keep or
5152    /// share anything.
5153    mod console {
5154        use super::pipeline::server;
5155        use crate::access::Scope;
5156
5157        #[tokio::test]
5158        async fn the_router_serves_the_console_without_a_key() {
5159            let s = server().await;
5160            for (file, _, media_type) in crate::console::FILES {
5161                let path = &crate::console::path_of(file);
5162                let answer = s.client().get(s.url(path)).send().await.expect("an answer");
5163                assert_eq!(answer.status(), 200, "{path}");
5164                assert_eq!(answer.headers()["content-type"], media_type, "{path}");
5165                // The player's page has a policy of its own, which
5166                // api::player_routes holds; every other header is shared.
5167                let shared = usize::from(path == crate::console::PLAYER_PATH);
5168                for (name, value) in &crate::console::HEADERS[shared..] {
5169                    assert_eq!(answer.headers()[*name], *value, "{path} {name}");
5170                }
5171                let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5172                    .join("console")
5173                    .join(file);
5174                let source = std::fs::read(source).expect("the source file");
5175                assert_eq!(answer.bytes().await.expect("body"), source, "{path}");
5176            }
5177        }
5178
5179        /// Every answer under /console carries the headers, a refusal too.
5180        #[tokio::test]
5181        async fn every_other_console_answer_carries_the_headers() {
5182            let s = server().await;
5183            let client = s.client_not_following();
5184            let answers = [
5185                (client.get(s.url("/console/other.js")), 404),
5186                (client.get(s.url("/console/a/b")), 404),
5187                (client.post(s.url("/console/")), 405),
5188                (client.get(s.url("/console")), 308),
5189            ];
5190            for (request, status) in answers {
5191                let answer = request.send().await.expect("an answer");
5192                assert_eq!(answer.status(), status, "{answer:?}");
5193                for (name, value) in crate::console::HEADERS {
5194                    assert_eq!(answer.headers()[name], value, "{status} {name}");
5195                }
5196                if status == 308 {
5197                    assert_eq!(answer.headers()["location"], "/console/");
5198                }
5199            }
5200            let elsewhere = client
5201                .get(s.url("/consoles"))
5202                .send()
5203                .await
5204                .expect("an answer");
5205            assert_eq!(elsewhere.status(), 404);
5206            assert!(
5207                !elsewhere.headers().contains_key("content-security-policy"),
5208                "only console answers carry its headers"
5209            );
5210        }
5211
5212        #[tokio::test]
5213        async fn no_answer_sets_a_cookie_or_allows_another_origin() {
5214            let s = server().await;
5215            let token = s.key(&[Scope::Read]);
5216            for path in ["/console/", "/health", "/key", "/vcons/nonsense"] {
5217                let answer = s
5218                    .client()
5219                    .get(s.url(path))
5220                    .bearer_auth(&token)
5221                    .header("origin", "https://elsewhere.example.com")
5222                    .send()
5223                    .await
5224                    .expect("an answer");
5225                let headers = answer.headers();
5226                assert!(!headers.contains_key("set-cookie"), "{path}");
5227                assert!(
5228                    !headers.contains_key("access-control-allow-origin"),
5229                    "{path}"
5230                );
5231            }
5232        }
5233    }
5234}
5235
5236/// The website documents every problem type at the URL the type names, so
5237/// a client following a `type` finds what it means. These tests hold the
5238/// pages to the code.
5239#[cfg(test)]
5240mod reveal_routes;
5241
5242#[cfg(test)]
5243mod player_routes;
5244
5245#[cfg(test)]
5246mod plane_routes;
5247
5248#[cfg(test)]
5249mod policy_tests;
5250
5251#[cfg(test)]
5252mod tenant_routes;
5253
5254#[cfg(test)]
5255mod session_tests;
5256
5257#[cfg(test)]
5258mod key_life_tests;
5259
5260#[cfg(test)]
5261mod site_pages {
5262    use std::collections::BTreeSet;
5263    use std::path::PathBuf;
5264
5265    use super::*;
5266
5267    /// One of every problem the API can answer. Each list sits behind an
5268    /// exhaustive match, so a new kind of problem fails to compile here
5269    /// until it is listed, and then fails the test until it has its page.
5270    pub(super) fn every_problem() -> Vec<Problem> {
5271        let mut all = vec![
5272            Problem::Unauthorized,
5273            Problem::Forbidden,
5274            Problem::WrongListener,
5275            Problem::TooLarge,
5276            Problem::Timeout,
5277            Problem::BadBody,
5278            Problem::Unavailable,
5279            Problem::AuditFailed,
5280            Problem::UnsupportedMediaType,
5281            Problem::KeyExpired,
5282            Problem::KeyAndSession,
5283            Problem::NoSession,
5284            Problem::BadOrigin,
5285            Problem::BadCsrf,
5286            Problem::BadPathUuid,
5287            Problem::BadPathVersion,
5288            Problem::PreconditionRequired,
5289            Problem::PathUuidMismatch,
5290            Problem::InvalidBody,
5291            Problem::BadQuery,
5292            Problem::UnknownKey,
5293            Problem::RateLimited,
5294            Problem::AtCapacity,
5295            Problem::UnknownTool,
5296            Problem::InvalidArguments,
5297        ];
5298        for problem in &all {
5299            match problem {
5300                Problem::Unauthorized
5301                | Problem::Forbidden
5302                | Problem::WrongListener
5303                | Problem::TooLarge
5304                | Problem::Timeout
5305                | Problem::BadBody
5306                | Problem::Unavailable
5307                | Problem::AuditFailed
5308                | Problem::UnsupportedMediaType
5309                | Problem::KeyExpired
5310                | Problem::KeyAndSession
5311                | Problem::NoSession
5312                | Problem::BadOrigin
5313                | Problem::BadCsrf
5314                | Problem::BadPathUuid
5315                | Problem::BadPathVersion
5316                | Problem::PreconditionRequired
5317                | Problem::PathUuidMismatch
5318                | Problem::InvalidBody
5319                | Problem::BadQuery
5320                | Problem::UnknownKey
5321                | Problem::RateLimited
5322                | Problem::AtCapacity
5323                | Problem::UnknownTool
5324                | Problem::InvalidArguments
5325                | Problem::Invalid(_)
5326                | Problem::Store(_)
5327                | Problem::Tenant(_) => {}
5328            }
5329        }
5330        let invalid = [
5331            Invalid::BadGzip,
5332            Invalid::NotJson,
5333            Invalid::DuplicateMember,
5334            Invalid::AmbiguousForm,
5335            Invalid::NoForm,
5336            Invalid::MissingUuid,
5337            Invalid::BadUuid,
5338            Invalid::MissingCreatedAt,
5339            Invalid::BadPayload,
5340            Invalid::UuidMismatch,
5341            Invalid::BadCritical,
5342            Invalid::UnsupportedExtension,
5343            Invalid::TooDeep,
5344            Invalid::Other,
5345        ];
5346        for kind in invalid {
5347            match kind {
5348                Invalid::BadGzip
5349                | Invalid::NotJson
5350                | Invalid::DuplicateMember
5351                | Invalid::AmbiguousForm
5352                | Invalid::NoForm
5353                | Invalid::MissingUuid
5354                | Invalid::BadUuid
5355                | Invalid::MissingCreatedAt
5356                | Invalid::BadPayload
5357                | Invalid::UuidMismatch
5358                | Invalid::BadCritical
5359                | Invalid::UnsupportedExtension
5360                | Invalid::TooDeep
5361                | Invalid::Other => all.push(Problem::Invalid(kind)),
5362            }
5363        }
5364        let store = [
5365            StoreError::Conflict,
5366            StoreError::Gone,
5367            StoreError::NotFound,
5368            StoreError::NotDeleted,
5369            StoreError::PreconditionFailed,
5370            StoreError::Immutable,
5371            StoreError::LimitReached,
5372            StoreError::Damaged,
5373            StoreError::AuditFailed,
5374            StoreError::Io,
5375        ];
5376        for error in store {
5377            match error {
5378                StoreError::Conflict
5379                | StoreError::Gone
5380                | StoreError::NotFound
5381                | StoreError::NotDeleted
5382                | StoreError::PreconditionFailed
5383                | StoreError::Immutable
5384                | StoreError::LimitReached
5385                | StoreError::Damaged
5386                | StoreError::AuditFailed
5387                | StoreError::Io => all.push(Problem::Store(error)),
5388            }
5389        }
5390        let tenant = [
5391            TenantError::NotFound,
5392            TenantError::NameTaken,
5393            TenantError::BadName,
5394            TenantError::HoldsVcons,
5395            TenantError::UnderHold,
5396            TenantError::LimitReached,
5397            TenantError::AuditFailed,
5398            TenantError::Closing,
5399            TenantError::CliOnly,
5400            TenantError::BadScopes,
5401            TenantError::BadExpiry,
5402            TenantError::BadSetting(crate::settings::SettingError::UnknownName),
5403            TenantError::WrongKey,
5404            TenantError::NoFileBackup,
5405            TenantError::Io,
5406        ];
5407        for error in tenant {
5408            match error {
5409                TenantError::NotFound
5410                | TenantError::NameTaken
5411                | TenantError::BadName
5412                | TenantError::HoldsVcons
5413                | TenantError::UnderHold
5414                | TenantError::LimitReached
5415                | TenantError::AuditFailed
5416                | TenantError::Closing
5417                | TenantError::CliOnly
5418                | TenantError::BadScopes
5419                | TenantError::BadExpiry
5420                | TenantError::BadSetting(_)
5421                | TenantError::WrongKey
5422                | TenantError::NoFileBackup
5423                | TenantError::Io => all.push(Problem::Tenant(error)),
5424            }
5425        }
5426        all
5427    }
5428
5429    fn pages() -> PathBuf {
5430        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../website/content/problems")
5431    }
5432
5433    #[test]
5434    fn every_problem_type_has_its_page_with_its_status_and_title() {
5435        for problem in every_problem() {
5436            let (name, title) = problem.name();
5437            let page = pages().join(format!("{name}.md"));
5438            let text = std::fs::read_to_string(&page)
5439                .unwrap_or_else(|e| panic!("{problem:?}: {}: {e}", page.display()));
5440            let status = problem.status().as_u16();
5441            for line in [
5442                format!("title = \"{name}\""),
5443                format!("status = {status}"),
5444                format!("problem_title = \"{title}\""),
5445            ] {
5446                assert!(
5447                    text.lines().any(|l| l == line),
5448                    "{}: no line `{line}`",
5449                    page.display()
5450                );
5451            }
5452        }
5453    }
5454
5455    /// No page outlives its problem type.
5456    #[test]
5457    fn every_problem_page_is_a_problem_type() {
5458        let names: BTreeSet<String> = every_problem()
5459            .into_iter()
5460            .map(|p| p.name().0.to_owned())
5461            .collect();
5462        let pages: BTreeSet<String> = std::fs::read_dir(pages())
5463            .expect("the problem pages")
5464            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
5465            .filter(|f| f != "_index.md")
5466            .map(|f| f.strip_suffix(".md").unwrap_or(&f).to_owned())
5467            .collect();
5468        assert_eq!(pages, names);
5469    }
5470
5471    /// The `application/vcon` media types `text` names, each with the
5472    /// `+suffix` that follows it, if any.
5473    fn vcon_media_types(text: &str) -> Vec<&str> {
5474        const NAME: &str = "application/vcon";
5475        let mut found = Vec::new();
5476        let mut rest = text;
5477        while let Some(at) = rest.find(NAME) {
5478            let from = &rest[at..];
5479            let end = from[NAME.len()..]
5480                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '+' || c == '-'))
5481                .map_or(from.len(), |n| NAME.len() + n);
5482            found.push(&from[..end]);
5483            rest = &from[end..];
5484        }
5485        found
5486    }
5487
5488    #[test]
5489    fn the_media_type_reader_takes_each_name_with_its_suffix() {
5490        assert_eq!(
5491            vcon_media_types(
5492                "Send `application/vcon`, or \"application/vcon+gzip\"; not application/vcon+json."
5493            ),
5494            [
5495                "application/vcon",
5496                "application/vcon+gzip",
5497                "application/vcon+json"
5498            ],
5499            "each name ends where its suffix does"
5500        );
5501        assert!(
5502            vcon_media_types("application/json and text/plain").is_empty(),
5503            "other media types are not read"
5504        );
5505    }
5506
5507    /// Every Markdown file under `dir`.
5508    fn markdown_under(dir: &std::path::Path, found: &mut Vec<PathBuf>) {
5509        for entry in std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) {
5510            let path = entry.expect("entry").path();
5511            if path.is_dir() {
5512                markdown_under(&path, found);
5513            } else if path.extension().is_some_and(|ext| ext == "md") {
5514                found.push(path);
5515            }
5516        }
5517    }
5518
5519    /// A reader copies a media type from an example into a request. One the
5520    /// API does not take would be refused with `unsupported-media-type`.
5521    /// Found on 0.4.2: the `vcon` crate's README and the library page passed
5522    /// `application/vcon+json`, which the vCon draft does not register.
5523    #[test]
5524    fn every_vcon_media_type_the_pages_name_is_one_the_api_takes() {
5525        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
5526        let mut files = vec![
5527            root.join("README.md"),
5528            root.join("crates/vcon/README.md"),
5529            root.join("crates/vcon-server/README.md"),
5530            root.join("website/static/llms.txt"),
5531        ];
5532        markdown_under(&root.join("website/content"), &mut files);
5533        assert!(
5534            files.iter().any(|f| f.ends_with("docs/library.md")),
5535            "the walk reached the docs pages"
5536        );
5537        let mut named = 0;
5538        let mut refused = Vec::new();
5539        for file in &files {
5540            let text =
5541                std::fs::read_to_string(file).unwrap_or_else(|e| panic!("{}: {e}", file.display()));
5542            for media_type in vcon_media_types(&text) {
5543                named += 1;
5544                if !is_vcon_media_type(media_type) {
5545                    refused.push(format!("{}: {media_type}", file.display()));
5546                }
5547            }
5548        }
5549        assert!(
5550            named > 10,
5551            "the reader found the pages' media types: {named}"
5552        );
5553        assert!(
5554            refused.is_empty(),
5555            "the pages name media types the API refuses: {refused:#?}"
5556        );
5557    }
5558}
5559
5560/// Reading the description, for the tests that hold it to the code.
5561#[cfg(test)]
5562mod description {
5563    use std::sync::OnceLock;
5564
5565    use serde_json::Value;
5566
5567    fn parsed() -> &'static Value {
5568        static PARSED: OnceLock<Value> = OnceLock::new();
5569        PARSED.get_or_init(|| serde_json::from_str(super::OPENAPI).expect("openapi.json is JSON"))
5570    }
5571
5572    /// Whether the description lists `status` for `method` on `route`, a
5573    /// route template as the router writes it. The router's `{*name}`, the
5574    /// rest of a path, is OpenAPI's `{name}`.
5575    pub(super) fn lists(method: &str, route: &str, status: u16) -> bool {
5576        let path = route.replace("{*", "{");
5577        parsed()["paths"][path.as_str()][method.to_ascii_lowercase()]["responses"]
5578            .get(status.to_string())
5579            .is_some()
5580    }
5581
5582    /// Whether the operation needs a key: it does unless it says
5583    /// `security: []`, or names a way that is not the bearer key, as the
5584    /// session routes do.
5585    pub(super) fn keyed(method: &str, path: &str) -> bool {
5586        parsed()["paths"][path][method.to_ascii_lowercase()]["security"]
5587            .as_array()
5588            .is_none_or(|ways| ways.iter().any(|way| way.get("bearer").is_some()))
5589    }
5590
5591    /// Every path and its methods, as the description names them.
5592    pub(super) fn operations() -> Vec<(String, String)> {
5593        let mut all = Vec::new();
5594        for (path, item) in parsed()["paths"].as_object().expect("paths") {
5595            for method in item.as_object().expect("a path item").keys() {
5596                if ["get", "put", "post", "delete", "patch"].contains(&method.as_str()) {
5597                    all.push((method.to_ascii_uppercase(), path.clone()));
5598                }
5599            }
5600        }
5601        all
5602    }
5603
5604    pub(super) fn document() -> &'static Value {
5605        parsed()
5606    }
5607}
5608
5609/// The description against the code: the published copy, the version, the
5610/// problem types and every route and method. Statuses are checked on every
5611/// answer the unit tests produce, in `log_request`.
5612#[cfg(test)]
5613mod openapi_description {
5614    use std::collections::BTreeSet;
5615
5616    use reqwest::Method;
5617
5618    use super::description::{document, keyed, lists, operations};
5619    use super::site_pages::every_problem;
5620    use super::tests::pipeline::server;
5621    use super::*;
5622
5623    #[test]
5624    fn the_website_publishes_the_compiled_description() {
5625        let published = std::fs::read_to_string(format!(
5626            "{}/../../website/static/openapi.json",
5627            env!("CARGO_MANIFEST_DIR")
5628        ))
5629        .expect("the website's copy");
5630        assert!(published == OPENAPI, "website/static/openapi.json differs");
5631    }
5632
5633    #[test]
5634    fn it_is_openapi_3_1_for_this_version() {
5635        let doc = document();
5636        assert!(
5637            doc["openapi"]
5638                .as_str()
5639                .is_some_and(|v| v.starts_with("3.1.")),
5640            "{}",
5641            doc["openapi"]
5642        );
5643        assert_eq!(doc["info"]["version"], env!("CARGO_PKG_VERSION"));
5644        assert!(doc["info"]["title"].as_str().is_some_and(|t| !t.is_empty()));
5645    }
5646
5647    #[test]
5648    fn its_problem_types_are_the_ones_the_api_answers() {
5649        let described: BTreeSet<String> =
5650            document()["components"]["schemas"]["Problem"]["properties"]["type"]["enum"]
5651                .as_array()
5652                .expect("the Problem type list")
5653                .iter()
5654                .map(|t| t.as_str().expect("a URL").to_owned())
5655                .collect();
5656        let answered: BTreeSet<String> = every_problem()
5657            .into_iter()
5658            .map(|p| format!("https://vcon-server.com/problems/{}", p.name().0))
5659            .collect();
5660        assert_eq!(described, answered);
5661    }
5662
5663    /// A path template with sample values, so it reaches its route.
5664    fn concrete(path: &str) -> String {
5665        path.replace("{uuid}", "01a07da8-c2bb-83e5-b9a2-279e0d16bc46")
5666            .replace("{version}", "00112233445566778899aabbccddeeff")
5667            .replace("{id}", "00112233445566778899aabbccddeeff")
5668            .replace("{other}", "no-such-file")
5669    }
5670
5671    /// Every operation the description names is routed (one that needs a
5672    /// key asks for it; one that needs none answers a status it lists), and
5673    /// every other method on its paths is not (405).
5674    #[tokio::test]
5675    async fn every_described_route_is_routed_and_no_other_method() {
5676        let s = server().await;
5677        let described: BTreeSet<(String, String)> = operations().into_iter().collect();
5678        assert!(!described.is_empty());
5679        let paths: BTreeSet<&String> = described.iter().map(|(_, p)| p).collect();
5680        for path in paths {
5681            for method in ["GET", "POST", "PUT", "PATCH", "DELETE"] {
5682                // Not following redirects, so each answer is the route's own.
5683                let answer = s
5684                    .client_not_following()
5685                    .request(
5686                        Method::from_bytes(method.as_bytes()).expect("a method"),
5687                        s.url(&concrete(path)),
5688                    )
5689                    .send()
5690                    .await
5691                    .expect("an answer");
5692                let status = answer.status().as_u16();
5693                if !described.contains(&(method.to_owned(), path.clone())) {
5694                    assert_eq!(status, 405, "{method} {path}");
5695                } else if keyed(method, path) {
5696                    assert_eq!(status, 401, "{method} {path}");
5697                } else {
5698                    assert!(lists(method, path, status), "{method} {path}: {status}");
5699                }
5700            }
5701        }
5702    }
5703}