Skip to main content

vcon_server/
api.rs

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