vta-service 0.38.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
// Helpers share the same `Result<_, Response>` shape as the slice
// handlers (see `vault.rs` for the same allow). The Response is owned
// and emitted on the same stack frame as the Err — boxing buys nothing.
#![allow(clippy::result_large_err)]

//! Shared helpers for the trust-task dispatcher and its per-slice
//! handler modules.
//!
//! Centralises:
//! - The `TRANSPORT_TRUST_TASK` audit-log channel label.
//! - Payload parsing (`parse_payload<T>`).
//! - `AppError` → reject-response mapping (`app_error_to_reject`).
//! - Reject + success document construction (`reject_with`,
//!   `success_response`, `error_response`).
//! - Wire-shape error helpers used by the dispatcher itself
//!   (`body_parse_error_response`, `method_not_found`).
//! - `not_implemented_yet` placeholder for Phase 3 slice stubs.
//!
//! All helpers are `pub(super)` — visible to the dispatcher (`mod.rs`)
//! and to the per-slice handler modules, but not to the wider crate.
//! Callers outside `routes::trust_tasks` should not depend on these
//! shapes; the entry point is `dispatch_trust_task` in `mod.rs`.

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::Value;
use trust_tasks_https::status_for_code;
use trust_tasks_rs::{
    ErrorPayload, ErrorResponse, RejectReason, StandardCode, TrustTask, TrustTaskCode, TypeUri,
};
use uuid::Uuid;
use vta_sdk::protocols::trust_task_reject_reasons as reasons;

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::server::AppState;
use vti_common::acl::Capability;
// The SDK owns the spelling of every `details` member both sides touch,
// so the service cannot drift from the client that reads it.
use vta_sdk::protocols::trust_task_reject_details as details;

/// Transport label passed to operations for audit-log discrimination
/// between the legacy REST path (`"rest"`) and the new trust-task
/// envelope (`"trust-task"`).
pub(super) const TRANSPORT_TRUST_TASK: &str = "trust-task";

/// The transport-neutral result of dispatching a Trust Task: the framework
/// HTTP status code plus the serialised result/error document bytes.
///
/// Both transports render from this one value — the REST route turns it into
/// an `axum::Response` via [`IntoResponse`]; the DIDComm `handle_trust_task`
/// reads [`body`](Self::body) straight as the reply envelope, with no
/// round-trip through an `axum::Response` to re-extract the JSON. The body
/// stays raw bytes (not a `serde_json::Value`) so the wire output is
/// byte-identical to direct document serialisation: serde_json has no
/// `preserve_order` feature here, so a `Value` round-trip would alphabetise
/// object keys and change the bytes.
pub(crate) struct TrustTaskOutcome {
    pub(crate) status: StatusCode,
    pub(crate) body: Vec<u8>,
}

impl IntoResponse for TrustTaskOutcome {
    fn into_response(self) -> Response {
        (
            self.status,
            [(axum::http::header::CONTENT_TYPE, "application/json")],
            self.body,
        )
            .into_response()
    }
}

/// Parse a trust-task document's `payload` field as the typed body
/// `T`, or return a `MalformedRequest` rejection response.
///
/// Consolidates the per-handler boilerplate where the only thing that
/// changes is the target type.
pub(super) fn parse_payload<T: serde::de::DeserializeOwned>(
    doc: &TrustTask<Value>,
) -> Result<T, TrustTaskOutcome> {
    serde_json::from_value::<T>(doc.payload.clone()).map_err(|e| {
        reject_with(
            doc,
            RejectReason::MalformedRequest {
                reason: format!("payload parse: {e}"),
            },
        )
    })
}

/// A `taskFailed` carrying a machine-readable `details.reason`.
///
/// See the `NotFound` / `Conflict` / `Gone` arms of [`app_error_to_reject`] for
/// why the code alone is not enough.
fn task_failed_because(message: String, reason: &str) -> RejectReason {
    RejectReason::TaskFailed {
        reason: message,
        details: Some(serde_json::json!({ "reason": reason })),
    }
}

/// Map an `AppError` (the operation-layer error type) into a routed
/// trust-task error response with the appropriate framework reject
/// code:
///
/// - `Authentication` / `Unauthorized` / `Forbidden` → `permission_denied`
/// - `Validation` / `TrustTaskMalformed` / `InvalidCursor` → `malformed_request`
/// - `NotFound` / `Conflict` / `Gone` → `task_failed`, each discriminated by a
///   `details.reason` from [`vta_sdk::protocols::trust_task_reject_reasons`]
/// - `ServiceError` at `502` / `504` → `task_failed`, `details.reason`
///   `upstream_unavailable`: a peer failed, not this VTA
/// - everything else → `internal_error`
pub(super) fn app_error_to_reject(doc: &TrustTask<Value>, err: AppError) -> TrustTaskOutcome {
    let message = err.to_string();
    let reason = match err {
        AppError::Authentication(_) | AppError::Unauthorized(_) | AppError::Forbidden(_) => {
            RejectReason::PermissionDenied { reason: message }
        }
        // A rejected pagination cursor is a caller fault, not a server
        // one — REST already answers 400. Left in the `internal_error`
        // fallback it would tell a consumer to retry the same cursor,
        // when the correct response is to restart from the first page.
        AppError::Validation(_) | AppError::TrustTaskMalformed(_) | AppError::InvalidCursor => {
            RejectReason::MalformedRequest { reason: message }
        }
        // These three have no standard code of their own — §8.3 defines no
        // `notFound` / `conflict` / `gone` — so all of them ride out under
        // `taskFailed`. That is the correct wire code, but it is not enough on
        // its own: a caller cannot tell "the row you asked for is absent" (very
        // often a *normal* state it knows how to handle) from "this operation
        // genuinely failed", and it loses the distinction the REST path keeps
        // in an HTTP status and the DIDComm protocol-message path keeps in a
        // problem-report code.
        //
        // So the discriminator goes in `details.reason`, the channel the
        // consent gate already established for exactly this problem, and
        // `VtaClient::trust_task_error` maps it back to the same typed
        // `VtaError` variant the other two transports produce.
        //
        // Concretely: a VTA that has never had an approval rule has no
        // `approvals` policy row, which is the shipping default. Every `pnm
        // approvals` subcommand reads it through `policy/get/0.1` and is
        // written to treat a missing row as an empty model — but with the type
        // erased, that arm could never fire, so the whole surface failed on a
        // fresh VTA, `require` included. That made the first rule
        // uncreatable: `require` has to read the row before writing it.
        //
        // `Gone` rides here rather than in the `internal_error` fallback for a
        // related reason: a consumed single-use resource is a terminal
        // *caller-visible* outcome, and reporting it as an internal error tells
        // the client to retry something that can never succeed again.
        AppError::NotFound(_) => task_failed_because(message, reasons::NOT_FOUND),
        AppError::Conflict(_) => task_failed_because(message, reasons::CONFLICT),
        AppError::Gone(_) => task_failed_because(message, reasons::GONE),
        // Framework 0.5.0, *What a `message` May Not Say*: a `message` MUST NOT
        // reveal consumer-internal state. That rule is now normative for every
        // code, and `internalError` is where this service leaked hardest — the
        // cause went out verbatim, so a caller learned things like "ATM not
        // configured — server cannot pack DIDComm envelopes" or "log entry has
        // no update_keys": the deployment's shape, its configuration, and which
        // internal invariant just broke.
        //
        // The producer needs one fact from an `internalError`: the failure was
        // not its doing, so re-sending an identical document may work. The
        // cause is what the *operator* needs, and it goes to the log where the
        // operator is.
        //
        // Every other arm above is safe to pass through: they describe the
        // caller's own request back to it (`not found`, `malformed`,
        // `permission denied`), which is not consumer-internal state.
        // A peer this VTA had to reach — a DID-hosting server, another agent —
        // did not answer or refused. Left in the catch-all below it went out as
        // `internalError`, which tells the producer "this VTA broke" and points
        // everyone at the wrong machine: a join that failed because the hosting
        // server never answered its TSP request read, in openvtc, as an
        // unexplained internal error in the user's own VTA.
        //
        // The cause still does not go on the wire. A bad-gateway message can
        // carry a peer's URL, its transport error and, from `send_rest`, the
        // body it sent back — the same class of detail the `Internal` arm
        // keeps off the wire. What the producer can act on is the *kind* of
        // failure, so that is what the fixed text and `details.reason` say;
        // which peer, and how it failed, is in the operator's log.
        AppError::ServiceError { status, message }
            if status == StatusCode::BAD_GATEWAY || status == StatusCode::GATEWAY_TIMEOUT =>
        {
            tracing::error!(cause = %message, "trust task failed: an upstream peer did not answer or refused");
            task_failed_because(
                UPSTREAM_UNAVAILABLE_MESSAGE.to_string(),
                reasons::UPSTREAM_UNAVAILABLE,
            )
        }
        AppError::Internal(cause) => {
            tracing::error!(cause = %cause, "trust task failed with an internal error");
            RejectReason::InternalError {
                reason: OPAQUE_INTERNAL_ERROR.to_string(),
            }
        }
        other => {
            tracing::error!(cause = %other, "trust task failed with an internal error");
            RejectReason::InternalError {
                reason: OPAQUE_INTERNAL_ERROR.to_string(),
            }
        }
    };
    reject_with(doc, reason)
}

/// Build a routed rejection document for the given reason and wrap it
/// in an HTTP response. The framework computes the status code from
/// the reject's standard code.
/// What an `internalError` says on the wire.
///
/// Fixed text on purpose. Framework 0.5.0 forbids revealing consumer-internal
/// state in a `message`, and an internal failure's cause is nothing but that.
/// It tells the producer the one thing it can act on — the failure was not its
/// document's fault — and nothing an unauthenticated caller could probe with.
pub(super) const OPAQUE_INTERNAL_ERROR: &str =
    "the consumer could not complete this task; the request itself was accepted";

/// What an upstream failure says on the wire. Fixed for the same reason as
/// [`OPAQUE_INTERNAL_ERROR`]; see the `ServiceError` arm of
/// [`app_error_to_reject`].
pub(super) const UPSTREAM_UNAVAILABLE_MESSAGE: &str = "a service this VTA depends on did not answer or refused the request; \
     the VTA's log names which one and why";

/// Framework 0.5.0, *Bounding `details`*: where a specification declares no
/// bound, 4096 bytes of JCS and 16 immediate members apply.
const DETAILS_MAX_JCS_BYTES: usize = 4096;
/// Companion to [`DETAILS_MAX_JCS_BYTES`].
const DETAILS_MAX_MEMBERS: usize = 16;

/// Drop a `details` that exceeds the framework's bound, keeping the `code`.
///
/// `details` was the one error-payload member with no size bound, and it
/// travels in the direction no producer-side bound reaches — the producer set
/// a body limit on what it *sent*, and nothing limits what comes back. This
/// service had a live instance: a policy denial puts the Rego module's
/// `explanation` on the wire, and that string is written by whoever authored
/// the policy, with no length anybody checked.
///
/// An oversized `details` is **ignored, never grounds to discard the `code`** —
/// the code is what the receiving party actually needs, and dropping the whole
/// rejection because its annex was too long would turn a verbose policy into an
/// unexplained failure.
fn bound_details(details: Option<Value>) -> Option<Value> {
    let details = details?;
    let too_many_members = details
        .as_object()
        .is_some_and(|o| o.len() > DETAILS_MAX_MEMBERS);
    let too_large = serde_json_canonicalizer::to_string(&details)
        .map(|jcs| jcs.len() > DETAILS_MAX_JCS_BYTES)
        // Uncanonicalisable is worse than oversized: it cannot be bounded, so
        // it does not go out.
        .unwrap_or(true);
    if too_many_members || too_large {
        tracing::warn!(
            members = details.as_object().map(serde_json::Map::len),
            "error `details` exceeds the framework bound and was dropped; the code still went out"
        );
        return None;
    }
    Some(details)
}

/// The capability gate every gated task goes through.
///
/// # Why this reads the ACL rather than the token
///
/// A caller's role rides in their access token; their *narrowing* does not. It is
/// read from the entry, per call, on purpose:
///
/// - A capability set is a **restriction**, and a restriction that takes effect
///   at the subject's next token mint is a restriction with a fifteen-minute hole
///   in it. Narrowing an entry stops the next call, not the next login.
/// - The alternative — a `capabilities` claim in the JWT — would put the set in
///   `AuthClaims`, a published struct built by literal in 130 places, and would
///   still leave every unexpired token holding what it held before.
///
/// The read is one keyspace hit on the tasks that are capability-gated, which are
/// already reading vault or memory keyspaces to do their work.
///
/// # An entry that is not there
///
/// Falls back to the role's own set. The offline CLI synthesizes claims under a
/// `cli:<channel>` DID that is deliberately in no ACL, and DIDs authenticated
/// before an entry existed behave as they always did. This gate narrows what an
/// entry says to narrow; it is not an authorization check of its own, and the
/// authenticated role is what it defers to.
pub(super) async fn require_capability(
    state: &AppState,
    auth: &AuthClaims,
    doc: &TrustTask<Value>,
    cap: Capability,
    what: &str,
) -> Result<(), TrustTaskOutcome> {
    let allowed = match vti_common::acl::get_acl_entry(&state.acl_ks, &auth.did).await {
        Ok(Some(entry)) => vti_common::acl::entry_has_capability(&entry, cap),
        // No entry: the role decides, exactly as before this gate existed.
        Ok(None) => vti_common::acl::role_has_capability(&auth.role, cap),
        // A store error must not become a grant. It also must not leak: the
        // caller is told the capability is missing, and the operator gets the
        // real reason in the log.
        Err(e) => {
            tracing::error!(
                error = %e, did = %auth.did,
                "could not read the ACL entry for a capability check; refusing"
            );
            false
        }
    };

    if allowed {
        return Ok(());
    }
    Err(reject_with(
        doc,
        RejectReason::PermissionDenied {
            reason: format!(
                "{what} denied: {} does not carry the {cap:?} capability",
                auth.did
            ),
        },
    ))
}

pub(super) fn reject_with(doc: &TrustTask<Value>, reason: RejectReason) -> TrustTaskOutcome {
    // Bound `details` here rather than at each of the thirty construction
    // sites: this is the one funnel every rejection passes through, so a new
    // site cannot be added that skips the check.
    let reason = match reason {
        RejectReason::TaskFailed { reason, details } => RejectReason::TaskFailed {
            reason,
            details: bound_details(details),
        },
        other => other,
    };
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), reason);
    error_response(routed)
}

/// Reject with a **specification-extended** code (SPEC.md §8.5,
/// `<slug>:<local>`) rather than one of the framework's standard codes.
///
/// [`RejectReason`] cannot express one: every variant maps to a
/// [`StandardCode`](trust_tasks_rs::StandardCode), so a task whose own
/// specification declares an error code has no way to put it on the wire
/// through [`reject_with`] — the nearest fit, `TaskFailed`, says "attempted
/// and could not complete", which is the wrong thing to tell a producer whose
/// request was refused before anything was attempted. The framework itself is
/// not the limitation: `ErrorPayload::new` takes any [`TrustTaskCode`], and
/// `TrustTask::reject_with` takes a payload. This is the missing seam between
/// the two.
///
/// Use it only for a code the task's specification actually declares. A code
/// invented here is one no consumer can look up, which is worse than
/// `taskFailed` — that at least means something everywhere.
///
/// `details` passes through [`bound_details`] exactly as in [`reject_with`],
/// so this cannot become the construction site that skips the framework's
/// size bound.
pub(super) fn reject_with_code(
    doc: &TrustTask<Value>,
    code: TrustTaskCode,
    message: impl Into<String>,
    details: Option<Value>,
) -> TrustTaskOutcome {
    let mut payload = ErrorPayload::new(code).with_message(message);
    if let Some(d) = bound_details(details) {
        payload = payload.with_details(d);
    }
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), payload);
    error_response(routed)
}

/// Build a routed success document with the given payload and wrap
/// it in an HTTP 200 response.
pub(super) fn success_response<R: serde::Serialize>(
    doc: &TrustTask<Value>,
    payload: R,
) -> TrustTaskOutcome {
    let response_doc = doc.respond_with(format!("urn:uuid:{}", Uuid::new_v4()), payload);
    let body = match serde_json::to_vec(&response_doc) {
        Ok(b) => b,
        Err(e) => {
            tracing::error!(error = %e, "failed to serialise success response doc");
            return reject_with(
                doc,
                RejectReason::InternalError {
                    reason: format!("response serialisation: {e}"),
                },
            );
        }
    };
    TrustTaskOutcome {
        status: StatusCode::OK,
        body,
    }
}

/// Build a routed `task_failed` rejection for a URI we know about but
/// haven't implemented yet. Kept available for Phase 3+ slices that
/// land their match arms before the handler body — each new slice can
/// stub via this helper, then replace with a real handler.
#[allow(dead_code)]
pub(super) fn not_implemented_yet(doc: TrustTask<Value>, reason: &str) -> TrustTaskOutcome {
    let reject = RejectReason::TaskFailed {
        reason: reason.to_string(),
        details: None,
    };
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), reject);
    error_response(routed)
}

/// Build an `unsupported_type` rejection for a type URI this VTA has never
/// heard of.
///
/// The narrow arm of [`method_not_found`], which reaches it only after ruling
/// out the family being served at another version.
fn unsupported_type(doc: TrustTask<Value>, type_uri: &str) -> TrustTaskOutcome {
    // The message is the framework's own `RejectReason::UnsupportedType`
    // rendering, kept byte-identical so a consumer matching on it does not
    // break; `details.requestedType` is the same fact machine-readably, which
    // is the half the framework's shape leaves out. A client otherwise has to
    // recover the URI by string-slicing a human-readable sentence.
    reject_with_code(
        &doc,
        TrustTaskCode::Standard(StandardCode::UnsupportedType),
        format!("unsupported type: {type_uri}"),
        Some(serde_json::json!({ details::REQUESTED_TYPE: type_uri })),
    )
}

/// The family of a Trust Task Type URI: everything before its trailing
/// version segment.
///
/// `…/spec/provision/integration/0.3` → `…/spec/provision/integration`. The
/// version is always the last path segment (SPEC §3.1), so a plain
/// `rsplit_once('/')` is the whole rule — no version grammar to parse, and a
/// URI with no `/` simply has no family rather than panicking.
fn task_family(type_uri: &str) -> Option<&str> {
    type_uri.rsplit_once('/').map(|(family, _version)| family)
}

/// Versions of `type_uri`'s family that this VTA *does* dispatch, sorted.
///
/// Derived from the dispatch table itself ([`super::dispatched_uris`]) rather
/// than a hand-kept list, for the same reason `trust-task-discovery` is: a
/// second source of truth for "what we support" goes stale the first time a
/// handler is added without remembering it exists, and a migration hint that
/// names a version the VTA does not serve is worse than no hint.
fn served_versions_of_family(type_uri: &str) -> Vec<&'static str> {
    let Some(family) = task_family(type_uri) else {
        return Vec::new();
    };
    let mut served: Vec<&'static str> = super::dispatched_uris()
        .into_iter()
        .filter(|uri| task_family(uri) == Some(family))
        .collect();
    served.sort_unstable();
    served.dedup();
    served
}

/// Reject a type URI this dispatcher has no arm for.
///
/// Two different failures wear one code if you let them. "I have never heard
/// of this task" and "I know this task, at a different version" send the
/// operator to completely different places — the first to whether the feature
/// exists at all, the second to which side is out of date — and only the
/// second is recoverable by upgrading something.
///
/// So when the unknown URI's family matches something this VTA dispatches, the
/// rejection is `unsupportedVersion` (SPEC's code for exactly this: "the
/// consumer recognizes the type but not at this MAJOR.MINOR") and names the
/// versions actually served, in `message` for a human and in
/// `details.servedVersions` for a client. Otherwise it stays
/// `unsupportedType`.
///
/// This exists because of a live incident (2026-08-31): #1147 cut
/// `provision/integration` 0.2 → 0.3 with no dual-accept window — the two
/// response schemas are mutually exclusive, so there could not be one — and an
/// operator whose VTA predated the cut got
///
/// ```text
/// unsupported type: https://trusttasks.org/spec/provision/integration/0.3
/// ```
///
/// against a VTA that was serving 0.2 two lines further down its own dispatch
/// table. Accurate, and it reads as "this VTA cannot do provisioning" rather
/// than "this VTA is older than your client". The VTA knew the answer; it just
/// did not say it.
///
/// A family this build does not compile in at all (`provision/integration` is
/// `#[cfg(feature = "webvh")]`) has no served versions and so still gets
/// `unsupportedType` — correct, if terse: there is no version to migrate to,
/// and naming absent features would report the build's configuration to a
/// caller that has no use for it.
pub(super) fn method_not_found(doc: TrustTask<Value>, type_uri: &str) -> TrustTaskOutcome {
    let served = served_versions_of_family(type_uri);
    if served.is_empty() {
        return unsupported_type(doc, type_uri);
    }

    reject_with_code(
        &doc,
        TrustTaskCode::Standard(StandardCode::UnsupportedVersion),
        format!(
            "unsupported version: {type_uri} — this VTA serves {}",
            served.join(", ")
        ),
        Some(serde_json::json!({
            details::REQUESTED_TYPE: type_uri,
            details::SERVED_VERSIONS: served,
        })),
    )
}

/// Wrap a routed `ErrorResponse` in an HTTP response with the right
/// status code per the framework's status table.
pub(super) fn error_response(err_doc: ErrorResponse) -> TrustTaskOutcome {
    let status = StatusCode::from_u16(status_for_code(&err_doc.payload.code))
        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let body = serde_json::to_vec(&err_doc).unwrap_or_else(|_| Vec::new());
    TrustTaskOutcome { status, body }
}

/// The framework's error-document Type URI — the one `TrustTask::reject_with`
/// stamps on every *routed* rejection this service emits.
///
/// Named here because `trust-tasks-rs` keeps `trust_task_error_type_uri()`
/// `pub(crate)`, so the only unrouted path — where there is no request document
/// to reject from — has to write the value out. It said `0.1` while every
/// routed reject went out as `0.3` (the framework has emitted `0.3` since its
/// own 0.3 release, for the §8.2 `inResponseTo` member that `0.2`'s
/// `additionalProperties: false` payload schema cannot admit). One service
/// emitting two versions is a trap for exactly the consumer that pins one of
/// them, which is not hypothetical: a client matching `0.1`/`0.2` by
/// enumeration read every `0.3` rejection as a *success*.
///
/// Now `0.5`, tracking `trust-tasks-rs` 0.9. The framework moved twice for the
/// same reason it moved to `0.3`: a new standard code that the older payload
/// schema's `code` enum does not list and whose extended-code pattern does not
/// match, so a document carrying it would fail to validate as the older
/// version. `0.4` carries `idConflict` (framework 0.4, SPEC §8.3) and `0.5`
/// carries `cancelled`. SPEC §5.2 forward-minor compatibility means a consumer
/// pinned to `0.3` SHOULD still accept these.
///
/// The constant is pinned by `unrouted_and_routed_errors_agree_on_the_type_uri`
/// below, which compares it against a real `reject_with`. When the framework
/// bumps the version, that test fails rather than this service silently
/// speaking two dialects again — which is exactly how this bump was caught.
fn framework_error_type_uri() -> TypeUri {
    "https://trusttasks.org/spec/trust-task-error/0.5"
        .parse()
        .expect("framework error Type URI parses")
}

/// Build a framework error document for a body-parse failure.
/// Unrouted (no issuer / recipient) — the framework permits this on
/// malformed-body failures since the producer can correlate on the
/// response `id`.
pub(super) fn body_parse_error_response(reason: &str) -> TrustTaskOutcome {
    malformed_request_response(format!(
        "body did not parse as a Trust Task document: {reason}"
    ))
}

/// An unrouted `malformedRequest` carrying `reason` **verbatim**.
///
/// Split out of [`body_parse_error_response`] because not every malformed
/// request is a malformed *document*. A transport binding can refuse a payload
/// whose document would have parsed perfectly — a TSP frame that is not wrapped
/// in the binding envelope, say — and telling that sender "body did not parse as
/// a Trust Task document" sends them to inspect a document that is fine. During
/// a binding cutover that is the single most misleading thing this service could
/// say, so the wording stays the caller's.
pub(crate) fn malformed_request_response(reason: String) -> TrustTaskOutcome {
    let reject = RejectReason::MalformedRequest { reason };
    let payload: ErrorPayload = reject.into();
    let type_uri: TypeUri = framework_error_type_uri();
    let err = ErrorResponse {
        id: format!("urn:uuid:{}", Uuid::new_v4()),
        thread_id: None,
        // Unrouted: there is no parent thread to name either, for the same
        // reason there is no issuer — the body never parsed.
        parent_thread_id: None,
        type_uri,
        issuer: None,
        recipient: None,
        issued_at: Some(chrono::Utc::now()),
        expires_at: None,
        payload,
        context: None,
        // No ceremony, for the same reason as `parent_thread_id` above: SPEC
        // §7.1 carries the member forward from the request so a rejection stays
        // inside the enactment it belonged to, and here there is no request to
        // carry it from — the body never parsed into one. The *routed* rejects
        // get this right for free, because `reject_with` copies it.
        ceremony: None,
        proof: None,
        extra: Default::default(),
    };
    error_response(err)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn doc() -> TrustTask<Value> {
        let uri: TypeUri = vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0
            .parse()
            .expect("update uri");
        TrustTask::new("urn:uuid:test", uri, json!({}))
    }

    fn message_of(outcome: TrustTaskOutcome) -> String {
        let doc: Value = serde_json::from_slice(&outcome.body).expect("error doc parses");
        doc["payload"]["message"]
            .as_str()
            .expect("payload carries a message")
            .to_string()
    }

    fn details_of(outcome: TrustTaskOutcome) -> Value {
        let doc: Value = serde_json::from_slice(&outcome.body).expect("error doc parses");
        doc["payload"]["details"].clone()
    }

    /// The regression: three distinct outcomes all leave as `taskFailed`, so
    /// without a discriminator a caller cannot tell an absent resource from a
    /// genuine failure — and an absent resource is very often a normal state.
    ///
    /// `pnm approvals list` is the case that broke. A VTA that has never had an
    /// approval rule has no `approvals` policy row (the shipping default); the
    /// CLI reads it and treats a missing row as an empty model, but with the
    /// type erased that arm could never fire. Every `pnm approvals` subcommand
    /// failed on a fresh VTA, `require` among them — so the first rule could
    /// not be created, because `require` reads the row before writing it.
    ///
    /// REST keeps this distinction in an HTTP status and DIDComm
    /// protocol-messages keep it in a problem-report code. This is what stops
    /// the Trust-Task transport being the one that loses it.
    #[test]
    fn a_not_found_is_discriminated_from_a_plain_task_failure() {
        let outcome = app_error_to_reject(&doc(), AppError::NotFound("policy `x`".into()));
        assert_eq!(details_of(outcome)["reason"], reasons::NOT_FOUND);
    }

    #[test]
    fn a_conflict_is_discriminated_from_a_plain_task_failure() {
        let outcome = app_error_to_reject(&doc(), AppError::Conflict("already exists".into()));
        assert_eq!(details_of(outcome)["reason"], reasons::CONFLICT);
    }

    #[test]
    fn a_gone_is_discriminated_from_a_plain_task_failure() {
        let outcome = app_error_to_reject(&doc(), AppError::Gone("carve-out closed".into()));
        assert_eq!(details_of(outcome)["reason"], reasons::GONE);
    }

    /// The reasons must stay distinct. Collapsing any pair would let a caller
    /// act on the wrong one — retrying a `Gone` that can never succeed, or
    /// reading a `Conflict` as "absent" and creating a duplicate.
    #[test]
    fn the_reasons_are_distinct() {
        let all = [
            reasons::NOT_FOUND,
            reasons::CONFLICT,
            reasons::GONE,
            reasons::UPSTREAM_UNAVAILABLE,
        ];
        let mut seen = std::collections::BTreeSet::new();
        for r in all {
            assert!(seen.insert(r), "`{r}` is used for more than one outcome");
        }
    }

    /// A family split on its trailing version segment, nothing else.
    ///
    /// Written against synthetic paths rather than real Type URIs: a URI
    /// literal anywhere under `vta-service/src` is counted by
    /// `produced_census` as a document this service emits, and a test fixture
    /// is not one.
    #[test]
    fn task_family_strips_only_the_version_segment() {
        assert_eq!(
            task_family("scheme://host/spec/a/b/0.3"),
            Some("scheme://host/spec/a/b")
        );
        assert_eq!(
            task_family("scheme://host/spec/a/b/c-d/1.0"),
            Some("scheme://host/spec/a/b/c-d")
        );
        assert_eq!(task_family("no-slashes-at-all"), None);
    }

    /// The migration hint is derived from the live dispatch table.
    ///
    /// Asserted against a URI the table definitely carries — a hard-coded
    /// expectation here would be the second source of truth the function
    /// exists to avoid.
    #[test]
    fn served_versions_come_from_the_dispatch_table() {
        let served = crate::trust_tasks::dispatched_uris();
        let real = served
            .first()
            .expect("the dispatch table is not empty")
            .to_string();
        let family = task_family(&real).expect("a task URI has a family");
        let bogus = format!("{family}/99.99");

        let found = served_versions_of_family(&bogus);
        assert!(
            found.contains(&real.as_str()),
            "{real} is dispatched, so a bogus version of its family should name it; got {found:?}"
        );
    }

    /// A type this VTA has never heard of still gets `unsupportedType`.
    ///
    /// The version arm must not swallow the plain case: "I do not implement
    /// this" and "I implement this at another version" are different answers
    /// and only the second is fixed by upgrading something.
    #[test]
    fn an_unknown_family_is_still_unsupported_type() {
        // The URI `produced_census::NOT_PRODUCED` already carries as its
        // negative fixture. Reused rather than minting a second one, so the
        // census has one entry to explain instead of two.
        let outcome = method_not_found(doc(), "https://trusttasks.org/spec/does-not-exist/9.9");
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(parsed["payload"]["code"], "unsupportedType");
        assert!(parsed["payload"]["details"].get("servedVersions").is_none());
    }

    /// A known family at an unknown version names the versions served.
    ///
    /// REGRESSION (2026-08-31): #1147 cut `provision/integration` 0.2 → 0.3
    /// with no dual-accept window, and a VTA still on 0.2 answered a 0.3
    /// client with a bare `unsupported type` — while carrying 0.2 in the very
    /// table it had just failed to match. The operator read it as "this VTA
    /// cannot provision" and went looking in the wrong place.
    #[test]
    fn a_known_family_at_an_unknown_version_names_what_is_served() {
        let real = crate::trust_tasks::dispatched_uris()
            .first()
            .expect("the dispatch table is not empty")
            .to_string();
        let family = task_family(&real).expect("a task URI has a family");
        let bogus = format!("{family}/99.99");

        let outcome = method_not_found(doc(), &bogus);
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");

        assert_eq!(parsed["payload"]["code"], "unsupportedVersion");
        let message = parsed["payload"]["message"]
            .as_str()
            .expect("a message")
            .to_string();
        assert!(
            message.contains(&real),
            "the message must name the served version; got {message}"
        );
        assert_eq!(parsed["payload"]["details"]["servedVersions"][0], real);
    }

    /// An extended code reaches the wire in its `<slug>:<local>` spelling.
    ///
    /// `RejectReason` cannot express one — every variant maps to a standard
    /// code — so before `reject_with_code` a task whose own specification
    /// declared an error code had to render it as prose in `message` and let
    /// the caller string-match, which is the thing machine-readable codes
    /// exist to prevent.
    #[test]
    fn an_extended_code_survives_to_the_wire() {
        let code: TrustTaskCode = "provision/integration:contextRequired"
            .parse()
            .expect("a legal extended code");
        let outcome = reject_with_code(
            &doc(),
            code,
            "which context?",
            Some(json!({ "candidates": ["a", "b"] })),
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"],
            "provision/integration:contextRequired"
        );
        assert_eq!(parsed["payload"]["details"]["candidates"][1], "b");
    }

    /// The `details` bound is enforced on this path too.
    ///
    /// `reject_with`'s comment calls itself "the one funnel every rejection
    /// passes through, so a new site cannot be added that skips the check" —
    /// `reject_with_code` is a second funnel, and this is what keeps that
    /// sentence true.
    #[test]
    fn an_extended_code_rejection_bounds_its_details_too() {
        let code: TrustTaskCode = "provision/integration:contextRequired"
            .parse()
            .expect("a legal extended code");
        let huge = json!({ "explanation": "x".repeat(DETAILS_MAX_JCS_BYTES + 1) });
        let outcome = reject_with_code(&doc(), code, "which context?", Some(huge));
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"], "provision/integration:contextRequired",
            "an oversized annex must never cost the code: {parsed}"
        );
        assert!(
            parsed["payload"]["details"].is_null(),
            "the oversized details should have been dropped: {parsed}"
        );
    }

    /// An oversized `details` is dropped, and the `code` still goes out.
    ///
    /// The live instance this bound exists for: a policy denial puts the Rego
    /// module's `explanation` on the wire, and that string is authored by
    /// whoever wrote the policy with no length anybody checks.
    #[test]
    fn an_oversized_details_is_dropped_but_the_code_survives() {
        let huge = serde_json::json!({ "explanation": "x".repeat(DETAILS_MAX_JCS_BYTES + 1) });
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(huge),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"], "taskFailed",
            "an oversized annex must never cost the code: {parsed}"
        );
        assert!(
            parsed["payload"].get("details").is_none_or(Value::is_null),
            "the oversized details must not go out: {parsed}"
        );
    }

    /// Too many members is the other half of the bound, and is not implied by
    /// the byte count — sixteen short members are small and still refused.
    #[test]
    fn a_details_with_too_many_members_is_dropped() {
        let mut wide = serde_json::Map::new();
        for i in 0..=DETAILS_MAX_MEMBERS {
            wide.insert(format!("k{i}"), serde_json::json!(1));
        }
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(Value::Object(wide)),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(parsed["payload"]["code"], "taskFailed");
        assert!(parsed["payload"].get("details").is_none_or(Value::is_null));
    }

    /// A `details` inside the bound is untouched — the bound must not become a
    /// reason nothing useful is ever returned.
    #[test]
    fn a_small_details_still_goes_out() {
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(serde_json::json!({ "reason": "auth:consent_required" })),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["details"]["reason"], "auth:consent_required",
            "{parsed}"
        );
    }

    /// An `internalError` says nothing about the consumer's internals.
    ///
    /// Framework 0.5.0, *What a `message` May Not Say*: a `message` MUST NOT
    /// reveal consumer-internal state, now normative for every code. This
    /// service used to pass the cause through verbatim, so a caller — on the
    /// unauthenticated routes, not yet anybody — learned the deployment's
    /// shape from its failures.
    ///
    /// The earlier version of this test asserted the opposite, that the cause
    /// *was* on the wire; its subject was a doubled "internal error:" prefix,
    /// which the fixed text also settles.
    #[test]
    fn an_internal_error_reveals_no_internal_state() {
        let secret = "log entry has no update_keys";
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::Internal(secret.into()),
        ));
        assert!(
            !message.contains(secret),
            "the cause must reach the operator's log, never the wire: {message}"
        );
        assert!(
            message.contains(OPAQUE_INTERNAL_ERROR),
            "the producer still needs to be told the failure was not its \
             document's doing: {message}"
        );
        assert!(
            !message.contains("internal error: internal error"),
            "{message}"
        );
    }

    /// Every `AppError` that is not a caller-facing class lands on the same
    /// opaque text, not just `Internal`.
    ///
    /// The catch-all arm was the quieter leak: it rendered whatever `Display`
    /// the error happened to have, so a variant added later would start
    /// publishing itself without anyone choosing to.
    #[test]
    fn the_catch_all_arm_is_opaque_too() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::SecretStore("vault backend at 10.0.0.7 refused the token".into()),
        ));
        assert!(!message.contains("10.0.0.7"), "{message}");
        assert!(!message.contains("vault backend"), "{message}");
        assert!(message.contains(OPAQUE_INTERNAL_ERROR), "{message}");
    }

    /// REGRESSION (2026-09-21): an openvtc join failed because the DID-hosting
    /// server never answered the VTA's TSP request, and the user saw only
    /// "internal error: the consumer could not complete this task" — a
    /// failure in *their own VTA*, by that wording. An upstream failure is a
    /// `taskFailed` with its own reason, and still says nothing about which
    /// peer or how.
    #[test]
    fn an_upstream_failure_is_named_as_one_without_its_cause() {
        for status in [StatusCode::BAD_GATEWAY, StatusCode::GATEWAY_TIMEOUT] {
            let err = || AppError::ServiceError {
                status,
                message: "bad gateway: `did:webvh:QmHost:dids.example` at \
                          https://10.0.0.7/trust-tasks did not answer"
                    .into(),
            };
            let parsed: Value = serde_json::from_slice(&app_error_to_reject(&doc(), err()).body)
                .expect("error doc parses");
            assert_eq!(parsed["payload"]["code"], "taskFailed", "{status}");
            assert_eq!(
                parsed["payload"]["details"]["reason"],
                reasons::UPSTREAM_UNAVAILABLE,
                "{status}"
            );
            let message = message_of(app_error_to_reject(&doc(), err()));
            assert!(message.contains(UPSTREAM_UNAVAILABLE_MESSAGE), "{message}");
            assert!(!message.contains("10.0.0.7"), "{message}");
            assert!(!message.contains("QmHost"), "{message}");
            assert!(!message.contains(OPAQUE_INTERNAL_ERROR), "{message}");
        }
    }

    /// Only the gateway statuses are upstream failures. Any other
    /// `ServiceError` (a key-derivation or attestation failure) is this VTA's
    /// own and stays opaque.
    #[test]
    fn other_service_errors_stay_internal() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::ServiceError {
                status: StatusCode::INTERNAL_SERVER_ERROR,
                message: "key derivation failed at m/26'/2'".into(),
            },
        ));
        assert!(message.contains(OPAQUE_INTERNAL_ERROR), "{message}");
        assert!(!message.contains("m/26'"), "{message}");
    }

    /// The unrouted body-parse error must claim the same document type as a
    /// routed one. It cannot ask the framework — `trust_task_error_type_uri()`
    /// is `pub(crate)` there — so it names the version, and this compares that
    /// against what `reject_with` actually stamps. A framework bump fails here
    /// instead of splitting this service into two dialects, which is how the
    /// unrouted path came to say `0.1` while every routed reject said `0.3`.
    #[test]
    fn unrouted_and_routed_errors_agree_on_the_type_uri() {
        let routed = doc().reject_with(
            "urn:uuid:routed",
            RejectReason::InternalError {
                reason: "probe".into(),
            },
        );
        assert_eq!(
            framework_error_type_uri(),
            routed.type_uri,
            "the unrouted body-parse error names a different document type than \
             the framework stamps on a routed rejection"
        );
    }

    /// …and the bytes on the wire carry it, not just the value we compute.
    #[test]
    fn the_body_parse_error_goes_out_as_a_framework_error_document() {
        let outcome = body_parse_error_response("not json");
        let doc: Value = serde_json::from_slice(&outcome.body).expect("error doc parses");
        assert_eq!(
            doc["type"].as_str().expect("type present"),
            framework_error_type_uri().to_string()
        );
    }

    /// The other arms pair a differently-worded reject reason with the variant,
    /// so their `Display` is not redundant and stays — a `NotFound` still reads
    /// "task failed: not found: …", naming both the framework's verdict and ours.
    /// Pinned so a future tidy-up does not strip the cause along with the stutter.
    #[test]
    fn a_not_found_keeps_the_cause_the_operator_needs() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::NotFound("SCID QmNope not found".into()),
        ));
        assert!(message.contains("SCID QmNope not found"), "{message}");
    }

    /// `Gone` must not fall through to the `internal_error` catch-all. A
    /// consumed single-use resource is a terminal outcome the *caller* has to
    /// act on; `internal_error` reads as "server bug, try again", which is the
    /// one instruction that can never work here.
    #[test]
    fn a_gone_is_a_task_failure_not_an_internal_error() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::Gone("carve-out has already been used".into()),
        ));
        assert!(
            message.contains("carve-out has already been used"),
            "{message}"
        );
        assert!(
            !message.starts_with("internal error"),
            "a consumed resource must not report as a server fault: {message}"
        );
    }
}