Skip to main content

vcon_server/
api.rs

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