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