trust_tasks_rs/transport.rs
1//! [`TransportHandler`] trait — the integration point between the framework's
2//! transport-agnostic document model and a concrete transport binding (REST,
3//! DIDComm, AMQP, ...).
4//!
5//! The contract encodes SPEC.md §4.8.1 and §9.2:
6//!
7//! - In-band `issuer` / `recipient` values are authoritative when present.
8//! - Transport-derived identity fills in absent members.
9//! - When both are present, they MUST be consistent — a mismatch is a
10//! validation failure (the standard error code is `identityMismatch`,
11//! §8.3).
12//!
13//! A handler implementation supplies the *transport-derived* values it
14//! observed for an inbound message via [`TransportHandler::derive_parties`];
15//! the [`TransportHandler::resolve_parties`] default method applies the
16//! precedence rule to produce a single [`ResolvedParties`] value that the
17//! consumer applies for every subsequent framework rule.
18
19use serde::Serialize;
20use thiserror::Error;
21
22use crate::document::{ErrorResponse, TrustTask};
23use crate::error::RejectReason;
24
25/// The result of resolving a document's in-band party identity against the
26/// transport context.
27///
28/// Per SPEC.md §4.8.1, these are the values a consumer applies for every
29/// subsequent framework rule that references the issuer or recipient.
30#[derive(Debug, Clone, PartialEq, Eq, Default)]
31pub struct ResolvedParties {
32 /// The party responsible for the document's content, after precedence.
33 pub issuer: Option<String>,
34 /// The party expected to act upon the document, after precedence.
35 pub recipient: Option<String>,
36}
37
38/// What the transport handler observed about an inbound message's parties.
39///
40/// Returned by [`TransportHandler::derive_parties`]. A field is `None` when
41/// the transport does not authenticate that party — for example, a plain
42/// HTTPS handler with no client certificate sets `issuer = None`.
43#[derive(Debug, Clone, PartialEq, Eq, Default)]
44pub struct TransportContext {
45 /// Transport-authenticated sender identity, if any.
46 pub issuer: Option<String>,
47 /// Transport-authenticated recipient identity, if any.
48 pub recipient: Option<String>,
49}
50
51/// Errors raised when in-band and transport-derived identity disagree
52/// (SPEC.md §7.2 item 6; standard code `identityMismatch`, §8.3).
53#[derive(Debug, Error, Clone, PartialEq, Eq)]
54pub enum ConsistencyError {
55 /// The in-band `issuer` does not match the transport-authenticated sender.
56 #[error("in-band issuer {in_band:?} does not match transport-derived {transport:?}")]
57 IssuerMismatch {
58 /// Value carried in the document's `issuer` member.
59 in_band: String,
60 /// Value derived from the transport.
61 transport: String,
62 },
63 /// The in-band `recipient` does not match the transport-authenticated
64 /// addressee.
65 #[error("in-band recipient {in_band:?} does not match transport-derived {transport:?}")]
66 RecipientMismatch {
67 /// Value carried in the document's `recipient` member.
68 in_band: String,
69 /// Value derived from the transport.
70 transport: String,
71 },
72}
73
74/// A transport binding's plug-in for the framework.
75///
76/// Implementations represent one transport (REST + mTLS, DIDComm, TSP, an
77/// in-memory test loopback, ...) and supply the transport-derived information
78/// the framework needs to apply SPEC.md §4.8.1 precedence.
79///
80/// The trait is sync and object-safe; transports that perform I/O do it
81/// outside the trait (e.g. before constructing the handler with the values it
82/// already extracted from a verified envelope).
83pub trait TransportHandler {
84 /// A stable identifier for this transport binding, suitable for logs and
85 /// audit (SPEC.md §9.1, §9.2 — "A *transport binding* specification
86 /// SHOULD identify itself by a stable URI").
87 fn binding_uri(&self) -> &str;
88
89 /// Identities the transport authenticated for the inbound message under
90 /// consideration.
91 ///
92 /// Implementations construct the handler with whatever the transport
93 /// extracted (peer certificate subject, verified DIDComm sender,
94 /// authenticated routing key, ...) and return it here. Returning a
95 /// fully-empty [`TransportContext`] is valid for transports that provide
96 /// no authenticated identity — the framework then falls back entirely to
97 /// the in-band members and any `proof` they carry.
98 fn derive_parties(&self) -> TransportContext;
99
100 /// Prepare an outbound document for emission over this transport.
101 ///
102 /// Per SPEC.md §9.2 item 1, a producer-side handler MAY strip `issuer` /
103 /// `recipient` when the transport will provide authenticated identity
104 /// for those roles end-to-end. The default implementation leaves the
105 /// document untouched, which is the conservative choice (in-band values
106 /// remain visible to downstream consumers regardless of transport).
107 fn prepare_outbound<P: Serialize>(&self, _doc: &mut TrustTask<P>) {}
108
109 /// Apply SPEC.md §4.8.1 precedence to produce the final
110 /// [`ResolvedParties`] for an inbound document.
111 ///
112 /// Returns [`ConsistencyError`] when an in-band member is present and
113 /// disagrees with the transport-derived value for the same party. The
114 /// caller is responsible for translating the error into an
115 /// `identityMismatch` error response (SPEC.md §8.3).
116 fn resolve_parties<P>(&self, doc: &TrustTask<P>) -> Result<ResolvedParties, ConsistencyError> {
117 let ctx = self.derive_parties();
118
119 let issuer = match (doc.issuer.as_deref(), ctx.issuer.as_deref()) {
120 (Some(in_band), Some(transport)) if in_band != transport => {
121 return Err(ConsistencyError::IssuerMismatch {
122 in_band: in_band.to_string(),
123 transport: transport.to_string(),
124 });
125 }
126 (Some(in_band), _) => Some(in_band.to_string()),
127 (None, Some(transport)) => Some(transport.to_string()),
128 (None, None) => None,
129 };
130
131 let recipient = match (doc.recipient.as_deref(), ctx.recipient.as_deref()) {
132 (Some(in_band), Some(transport)) if in_band != transport => {
133 return Err(ConsistencyError::RecipientMismatch {
134 in_band: in_band.to_string(),
135 transport: transport.to_string(),
136 });
137 }
138 (Some(in_band), _) => Some(in_band.to_string()),
139 (None, Some(transport)) => Some(transport.to_string()),
140 (None, None) => None,
141 };
142
143 Ok(ResolvedParties { issuer, recipient })
144 }
145
146 /// Build a `trust-task-error` response for `doc` that satisfies the
147 /// SPEC.md §8.1 routing rules — most importantly, the rule that under
148 /// [`RejectReason::IdentityMismatch`] the error MUST address the
149 /// transport-authenticated sender and MUST NOT address the contested
150 /// in-band issuer.
151 ///
152 /// Returns `Some(ErrorResponse)` when a routable recipient exists, and
153 /// `None` when the rejection is `identityMismatch` and the transport
154 /// has no authenticated sender for the inbound document — per §8.1, the
155 /// consumer SHOULD NOT emit a response in that case.
156 ///
157 /// The response's `issuer` is the consumer that emits it (§8.1): the
158 /// transport's own identity ([`TransportContext::recipient`]) where the
159 /// transport has one. Otherwise it is the rejected document's in-band
160 /// `recipient`, except under `wrongRecipient`, where that value is by
161 /// definition not this consumer and the `issuer` is left out.
162 fn reject<P>(
163 &self,
164 doc: &TrustTask<P>,
165 id: impl Into<String>,
166 reason: RejectReason,
167 ) -> Option<ErrorResponse> {
168 let not_me = matches!(reason, RejectReason::WrongRecipient { .. });
169 let local = self.derive_parties().recipient;
170 let recipient = match &reason {
171 RejectReason::IdentityMismatch(_) => {
172 // §8.1: transport-authenticated sender only. If the
173 // transport authenticated nothing, the consumer suppresses
174 // the response.
175 let from_transport = self.derive_parties().issuer;
176 from_transport.as_ref()?;
177 from_transport
178 }
179 _ => doc.issuer.clone(),
180 };
181 let mut response = doc.reject_with_recipient(id, reason, recipient);
182 if local.is_some() || not_me {
183 response.issuer = local;
184 }
185 Some(response)
186 }
187}