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