did-hosting-common 0.8.6

DID Hosting Common, Common methods and structs related to WebVH Content
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! [`TrustTaskRouter`] — Axum `Router` builder that enforces
//! per-route Trust-Task header validation at attach time.
//!
//! ## Why a builder, not a macro
//!
//! Plan decision **D9**: explicit registration via a typed builder.
//! A future reader sees the registered task right next to the handler;
//! no procedural-macro indirection, no string-prefix matching, no
//! version-family heuristics. Exact-match is the only correctness
//! check.
//!
//! ## Usage
//!
//! ```ignore
//! use vti_common::trust_task::{TrustTask, TrustTaskRouter};
//! use axum::routing::{get, post};
//!
//! let install_claim = TrustTask::new("https://trusttasks.org/openvtc/vtc/install/claim/start/1.0")?;
//!
//! let router = TrustTaskRouter::new()
//!     .route_with_task("/v1/install/claim/start", post(claim_start), install_claim)
//!     .route_exempt("/health", get(health))
//!     .into_router();
//! ```

use std::sync::Arc;

use axum::Router;
use axum::routing::MethodRouter;

use super::TrustTask;

/// Builder that wraps an Axum [`Router`] and enforces Trust-Task
/// header validation on each registered route.
pub struct TrustTaskRouter<S = ()> {
    inner: Router<S>,
}

impl<S> Default for TrustTaskRouter<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S> TrustTaskRouter<S>
where
    S: Clone + Send + Sync + 'static,
{
    /// Start a new empty builder.
    pub fn new() -> Self {
        Self {
            inner: Router::new(),
        }
    }

    /// Register a route whose incoming `Trust-Task` header must
    /// **exact-match** `task`. Mismatch → 415
    /// [`AppError::TrustTaskMismatch`]; missing → 400
    /// [`AppError::TrustTaskMissing`].
    ///
    /// [`AppError::TrustTaskMismatch`]: crate::error::AppError::TrustTaskMismatch
    /// [`AppError::TrustTaskMissing`]: crate::error::AppError::TrustTaskMissing
    pub fn route_with_task(
        mut self,
        path: &str,
        method_router: MethodRouter<S>,
        task: TrustTask,
    ) -> Self {
        // `Arc` so each invocation of the cloned closure can cheaply
        // hand out a reference to the same task value. The middleware
        // closure must be `Clone + Send + Sync + 'static` per Axum's
        // `from_fn` bound, which `Arc<TrustTask>` satisfies.
        let task = Arc::new(task);
        let layered = method_router.layer(axum::middleware::from_fn(move |request, next| {
            let task = task.clone();
            async move { super::extractor::validate_header(&task, request, next).await }
        }));
        self.inner = self.inner.route(path, layered);
        self
    }

    /// Register a route in **permissive** mode — clients MAY include
    /// a `Trust-Task` header but are not required to. When present,
    /// the header is validated against `task` and a mismatch returns
    /// 415 [`AppError::TrustTaskMismatch`]; when absent, the request
    /// passes through unchecked.
    ///
    /// This variant exists for the v0.7→v0.8 transition: existing
    /// clients (UI, CLI, didwebvh-cli) don't know about Trust-Task
    /// headers, and a hard-mandatory rollout would break them on
    /// upgrade. New clients that send the header still get the
    /// exact-match correctness guarantee for free. A future release
    /// can re-attach with [`Self::route_with_task`] once the
    /// ecosystem has caught up.
    ///
    /// [`AppError::TrustTaskMismatch`]: crate::error::AppError::TrustTaskMismatch
    pub fn route_with_task_permissive(
        mut self,
        path: &str,
        method_router: MethodRouter<S>,
        task: TrustTask,
    ) -> Self {
        let task = Arc::new(task);
        let layered = method_router.layer(axum::middleware::from_fn(move |request, next| {
            let task = task.clone();
            async move { super::extractor::validate_header_permissive(&task, request, next).await }
        }));
        self.inner = self.inner.route(path, layered);
        self
    }

    /// Permissive registration that accepts **multiple** Trust-Task
    /// versions on one route: `primary` is the route's current Type URI
    /// and `deprecated` lists older versions still accepted on inbound.
    ///
    /// This is the backwards-compatible path for a spec-version bump.
    /// When a spec moves (e.g. `…/0.1` → `…/0.2`), register the route
    /// with the `…/0.2` const as `primary` and `vec![…/0.1]` as
    /// `deprecated`: clients on the new version and clients still sending
    /// the old version both pass, while a mismatch still names the
    /// primary URI as `expected`. Permissive, like
    /// [`Self::route_with_task_permissive`] — a request with no header
    /// passes through unchecked during the migration window.
    ///
    /// [`AppError::TrustTaskMismatch`]: crate::error::AppError::TrustTaskMismatch
    pub fn route_with_tasks_permissive(
        mut self,
        path: &str,
        method_router: MethodRouter<S>,
        primary: TrustTask,
        deprecated: Vec<TrustTask>,
    ) -> Self {
        let mut accepted = Vec::with_capacity(1 + deprecated.len());
        accepted.push(primary);
        accepted.extend(deprecated);
        let accepted = Arc::new(accepted);
        let layered = method_router.layer(axum::middleware::from_fn(move |request, next| {
            let accepted = accepted.clone();
            async move {
                super::extractor::validate_header_permissive_any(&accepted, request, next).await
            }
        }));
        self.inner = self.inner.route(path, layered);
        self
    }

    /// Register a route that bypasses Trust-Task validation. Per spec
    /// §16.2 this is intended **only for `/health`** — operators set
    /// up monitoring against the health endpoint without having to
    /// know about Trust-Task identifiers. Documented as the single
    /// exempt route; if you find yourself reaching for this for a
    /// second endpoint, stop and add a Trust Task instead.
    pub fn route_exempt(mut self, path: &str, method_router: MethodRouter<S>) -> Self {
        self.inner = self.inner.route(path, method_router);
        self
    }

    /// Finalise and yield the underlying [`Router`] ready to be
    /// merged or nested into a parent router.
    pub fn into_router(self) -> Router<S> {
        self.inner
    }
}

impl<S> From<TrustTaskRouter<S>> for Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn from(r: TrustTaskRouter<S>) -> Self {
        r.into_router()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::{get, post};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    async fn ok() -> &'static str {
        "ok"
    }

    fn make_router() -> Router {
        let claim = TrustTask::new("https://trusttasks.org/openvtc/vtc/install/claim/1.0").unwrap();
        TrustTaskRouter::new()
            .route_with_task("/v1/install/claim", post(ok), claim)
            .route_exempt("/health", get(ok))
            .into_router()
    }

    #[tokio::test]
    async fn exact_match_succeeds() {
        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/openvtc/vtc/install/claim/1.0",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn missing_header_returns_400() {
        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["error"], "TrustTaskMissing");
    }

    #[tokio::test]
    async fn mismatched_header_returns_415_with_expected_field() {
        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/openvtc/vtc/auth/login/1.0",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["error"], "TrustTaskMismatch");
        assert_eq!(
            body["expected"],
            "https://trusttasks.org/openvtc/vtc/install/claim/1.0"
        );
        assert_eq!(
            body["received"],
            "https://trusttasks.org/openvtc/vtc/auth/login/1.0"
        );
    }

    #[tokio::test]
    async fn exact_match_is_byte_strict_not_prefix() {
        let app = make_router();
        // Same path family, different version — must not match.
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/openvtc/vtc/install/claim/1.1",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn health_is_exempt() {
        let app = make_router();
        // No header — should still 200.
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ---- permissive variant (T8b) ----

    fn make_permissive_router() -> Router {
        let claim = TrustTask::new("https://trusttasks.org/openvtc/vtc/install/claim/1.0").unwrap();
        TrustTaskRouter::new()
            .route_with_task_permissive("/v1/install/claim", post(ok), claim)
            .into_router()
    }

    /// Permissive mode lets the request through when the client
    /// hasn't opted in to the Trust-Task header.
    #[tokio::test]
    async fn permissive_allows_missing_header() {
        let app = make_permissive_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    /// A client that does send the header is held to the same exact-
    /// match standard as strict mode. Opt-in is binding once chosen.
    #[tokio::test]
    async fn permissive_still_rejects_mismatched_header() {
        let app = make_permissive_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/openvtc/vtc/auth/login/1.0",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn permissive_accepts_exact_match() {
        let app = make_permissive_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/v1/install/claim")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/openvtc/vtc/install/claim/1.0",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    use super::super::HEADER_NAME;

    // ---- multi-version permissive variant (spec-bump backwards compat) ----

    fn make_multiversion_router() -> Router {
        let v2 =
            TrustTask::new("https://trusttasks.org/spec/auth/passkey/login/start/0.2").unwrap();
        let v1 =
            TrustTask::new("https://trusttasks.org/spec/auth/passkey/login/start/0.1").unwrap();
        TrustTaskRouter::new()
            .route_with_tasks_permissive("/login/start", post(ok), v2, vec![v1])
            .into_router()
    }

    async fn login_start_with_header(header: Option<&str>) -> StatusCode {
        let mut builder = Request::builder().method("POST").uri("/login/start");
        if let Some(h) = header {
            builder = builder.header(HEADER_NAME, h);
        }
        make_multiversion_router()
            .oneshot(builder.body(Body::empty()).unwrap())
            .await
            .unwrap()
            .status()
    }

    /// The current (primary) version is accepted.
    #[tokio::test]
    async fn multiversion_accepts_primary() {
        assert_eq!(
            login_start_with_header(Some(
                "https://trusttasks.org/spec/auth/passkey/login/start/0.2"
            ))
            .await,
            StatusCode::OK
        );
    }

    /// The deprecated older version is still accepted on inbound.
    #[tokio::test]
    async fn multiversion_accepts_deprecated_alias() {
        assert_eq!(
            login_start_with_header(Some(
                "https://trusttasks.org/spec/auth/passkey/login/start/0.1"
            ))
            .await,
            StatusCode::OK
        );
    }

    /// Permissive: no header still passes during the migration window.
    #[tokio::test]
    async fn multiversion_allows_missing_header() {
        assert_eq!(login_start_with_header(None).await, StatusCode::OK);
    }

    /// A version we don't accept (e.g. a future 0.3) is rejected, and the
    /// mismatch names the primary as the expected identifier.
    #[tokio::test]
    async fn multiversion_rejects_unaccepted_version_naming_primary() {
        let resp = make_multiversion_router()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/login/start")
                    .header(
                        HEADER_NAME,
                        "https://trusttasks.org/spec/auth/passkey/login/start/0.3",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["error"], "TrustTaskMismatch");
        assert_eq!(
            body["expected"],
            "https://trusttasks.org/spec/auth/passkey/login/start/0.2"
        );
    }
}