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
use crate::core::{AsxError, ErrorCode, ErrorContext, Result};
/// Outcome of signature checking for one inbound message.
///
/// The three states are genuinely distinct and collapsing any two of them
/// loses security-relevant information: "we checked a signature and it is
/// good" is not the same claim as "there was no signature to check".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureVerification {
/// A signature was present and verified against a trusted signer.
Verified,
/// A signature was present and did **not** verify. Always fatal.
Failed,
/// No signature was present, and policy permits unsigned messages.
///
/// The payload's origin is therefore **unauthenticated** — only the
/// transport (TLS) says anything about who sent it. Applications that need
/// non-repudiation must require signatures; see
/// [`As2SignaturePolicy`](crate::as2::As2SignaturePolicy).
NotSigned,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecryptionMaterial {
Available,
Missing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrustEvidence {
pub signature: SignatureVerification,
pub decryption: DecryptionMaterial,
}
impl TrustEvidence {
pub fn verified_and_decryptable() -> Self {
Self {
signature: SignatureVerification::Verified,
decryption: DecryptionMaterial::Available,
}
}
pub fn signature_failed() -> Self {
Self {
signature: SignatureVerification::Failed,
decryption: DecryptionMaterial::Available,
}
}
pub fn missing_decryption_material() -> Self {
Self {
signature: SignatureVerification::Verified,
decryption: DecryptionMaterial::Missing,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UntrustedBytes<T> {
payload: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructurallyParsed<T> {
payload: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CryptographicallyVerified<T> {
payload: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentDecrypted<T> {
payload: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DomainReady<T> {
payload: T,
}
impl<T> UntrustedBytes<T> {
pub fn new(payload: T) -> Self {
Self { payload }
}
pub fn into_inner(self) -> T {
self.payload
}
/// Structurally validate the payload using a caller-supplied validator, then
/// advance to [`StructurallyParsed<U>`].
///
/// The validator receives a shared reference to the raw payload and must
/// return `Ok(U)` (the parsed form) or an `AsxError` on failure. Using a
/// typed `U` allows the parsed form to differ from the raw type `T` — for
/// example, `T = Arc<[u8]>` and `U = ParsedSoapEnvelope`.
///
/// ## Example
///
/// ```rust,ignore
/// let parsed = UntrustedBytes::new(raw_bytes)
/// .parse_with(|bytes| {
/// enforce_payload_limit("stage", bytes.len(), MAX_BYTES)?;
/// if bytes.is_empty() {
/// return Err(AsxError::new(ErrorCode::ParseFailed, "empty payload", ctx));
/// }
/// Ok(bytes.clone())
/// })?;
/// ```
pub fn parse_with<U, E>(
self,
validator: impl FnOnce(T) -> std::result::Result<U, E>,
) -> Result<StructurallyParsed<U>>
where
E: Into<AsxError>,
{
validator(self.payload)
.map(|parsed| StructurallyParsed { payload: parsed })
.map_err(Into::into)
}
/// Advance directly to [`StructurallyParsed<T>`] **without any structural
/// validation**.
///
/// Use this **only** when structural validation was already performed by an
/// external code path before the payload was wrapped in `UntrustedBytes` —
/// for example, after a cryptographic verifier that also enforces payload
/// size and encoding constraints.
///
/// Prefer [`parse_with`](Self::parse_with) when the caller can express the
/// structural invariant as a closure. Using `into_parsed_unchecked`
/// bypasses all structural guarantees and should be auditable at every
/// call site.
pub fn into_parsed_unchecked(self) -> StructurallyParsed<T> {
StructurallyParsed {
payload: self.payload,
}
}
}
impl<T> AsRef<T> for UntrustedBytes<T> {
fn as_ref(&self) -> &T {
&self.payload
}
}
impl<T> StructurallyParsed<T> {
pub fn into_inner(self) -> T {
self.payload
}
/// Advance past signature checking.
///
/// [`SignatureVerification::Failed`] is rejected. [`Verified`] and
/// [`NotSigned`] both advance — the decision of *whether* an unsigned
/// message is acceptable belongs to the trust verifier's policy, which is
/// the component that knows the partner agreement. By the time a value
/// reaches here that policy has already been applied.
///
/// [`Verified`]: SignatureVerification::Verified
/// [`NotSigned`]: SignatureVerification::NotSigned
pub fn verify(
self,
verification: SignatureVerification,
) -> Result<CryptographicallyVerified<T>> {
if verification == SignatureVerification::Failed {
return Err(AsxError::new(
ErrorCode::SecurityVerificationFailed,
"cryptographic verification failed",
ErrorContext::new("trust_state_verify"),
));
}
Ok(CryptographicallyVerified {
payload: self.payload,
})
}
}
impl<T> AsRef<T> for StructurallyParsed<T> {
fn as_ref(&self) -> &T {
&self.payload
}
}
impl<T> CryptographicallyVerified<T> {
pub fn into_inner(self) -> T {
self.payload
}
pub fn decrypt(self, material: DecryptionMaterial) -> Result<ContentDecrypted<T>> {
if material != DecryptionMaterial::Available {
return Err(AsxError::new(
ErrorCode::DecryptionFailed,
"decryption key unavailable",
ErrorContext::new("trust_state_decrypt"),
));
}
Ok(ContentDecrypted {
payload: self.payload,
})
}
}
impl<T> AsRef<T> for CryptographicallyVerified<T> {
fn as_ref(&self) -> &T {
&self.payload
}
}
impl<T> ContentDecrypted<T> {
pub fn into_inner(self) -> T {
self.payload
}
pub fn into_domain_ready(self) -> DomainReady<T> {
DomainReady {
payload: self.payload,
}
}
}
impl<T> AsRef<T> for ContentDecrypted<T> {
fn as_ref(&self) -> &T {
&self.payload
}
}
impl<T> DomainReady<T> {
pub fn into_inner(self) -> T {
self.payload
}
}
impl<T> AsRef<T> for DomainReady<T> {
fn as_ref(&self) -> &T {
&self.payload
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn forward_only_flow_succeeds() {
let trust = TrustEvidence::verified_and_decryptable();
let ready = UntrustedBytes::new(vec![1, 2, 3])
.into_parsed_unchecked()
.verify(trust.signature)
.expect("verify")
.decrypt(trust.decryption)
.expect("decrypt")
.into_domain_ready();
assert_eq!(ready.as_ref(), &vec![1, 2, 3]);
}
#[test]
fn failed_verify_and_decrypt_use_stage_codes() {
let verify_fail = TrustEvidence::signature_failed();
let verify_err = UntrustedBytes::new("x")
.into_parsed_unchecked()
.verify(verify_fail.signature)
.expect_err("verify fails");
assert_eq!(verify_err.code, ErrorCode::SecurityVerificationFailed);
let missing_key = TrustEvidence::missing_decryption_material();
let decrypt_err = UntrustedBytes::new("x")
.into_parsed_unchecked()
.verify(missing_key.signature)
.expect("verify ok")
.decrypt(missing_key.decryption)
.expect_err("decrypt fails");
assert_eq!(decrypt_err.code, ErrorCode::DecryptionFailed);
}
}