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