1use crate::error::{Error, ErrorCode, Result, bail};
18use crate::msg::{ProtocolId, VendorId};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25#[repr(u16)]
26pub enum GeneralCode {
27 Success = 0,
29 Failure = 1,
31 BadPrecondition = 2,
33 OutOfRange = 3,
35 BadRequest = 4,
37 Unsupported = 5,
39 Unexpected = 6,
41 ResourceExhausted = 7,
43 Busy = 8,
45 Timeout = 9,
47 Continue = 10,
49 Aborted = 11,
51 InvalidArgument = 12,
53 NotFound = 13,
55 AlreadyExists = 14,
57 PermissionDenied = 15,
59 DataLoss = 16,
61 MessageTooLarge = 17,
64}
65
66impl GeneralCode {
67 pub const fn from_u16(value: u16) -> Result<Self> {
69 Ok(match value {
70 0 => Self::Success,
71 1 => Self::Failure,
72 2 => Self::BadPrecondition,
73 3 => Self::OutOfRange,
74 4 => Self::BadRequest,
75 5 => Self::Unsupported,
76 6 => Self::Unexpected,
77 7 => Self::ResourceExhausted,
78 8 => Self::Busy,
79 9 => Self::Timeout,
80 10 => Self::Continue,
81 11 => Self::Aborted,
82 12 => Self::InvalidArgument,
83 13 => Self::NotFound,
84 14 => Self::AlreadyExists,
85 15 => Self::PermissionDenied,
86 16 => Self::DataLoss,
87 17 => Self::MessageTooLarge,
88 _ => return Err(Error::new(ErrorCode::MessageReserved)),
89 })
90 }
91
92 #[must_use]
97 pub const fn is_success(self) -> bool {
98 matches!(self, Self::Success | Self::Continue)
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104#[repr(u16)]
105pub enum SecureChannelCode {
106 SessionEstablishmentSuccess = 0x0000,
108 NoSharedTrustRoots = 0x0001,
110 InvalidParameter = 0x0002,
112 CloseSession = 0x0003,
114 Busy = 0x0004,
117}
118
119impl SecureChannelCode {
120 #[must_use]
125 pub const fn general(self) -> GeneralCode {
126 match self {
127 Self::SessionEstablishmentSuccess | Self::CloseSession => GeneralCode::Success,
128 Self::NoSharedTrustRoots | Self::InvalidParameter => GeneralCode::Failure,
129 Self::Busy => GeneralCode::Busy,
130 }
131 }
132
133 #[must_use]
135 pub const fn requires_encryption(self) -> bool {
136 matches!(self, Self::CloseSession)
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct StatusReport<'a> {
145 pub general: GeneralCode,
147 pub protocol: ProtocolId,
149 pub protocol_code: u16,
151 pub data: &'a [u8],
153}
154
155pub const NO_PROTOCOL_CODE: u16 = 0xFFFF;
158
159impl<'a> StatusReport<'a> {
160 pub const HEADER_LEN: usize = 8;
162
163 #[must_use]
165 pub const fn secure_channel(code: SecureChannelCode) -> Self {
166 Self {
167 general: code.general(),
168 protocol: ProtocolId::SECURE_CHANNEL,
169 protocol_code: code as u16,
170 data: &[],
171 }
172 }
173
174 #[must_use]
176 pub const fn is_success(&self) -> bool {
177 self.general.is_success()
178 }
179
180 #[must_use]
182 pub fn secure_channel_code(&self) -> Option<SecureChannelCode> {
183 if self.protocol != ProtocolId::SECURE_CHANNEL {
184 return None;
185 }
186 Some(match self.protocol_code {
187 0x0000 => SecureChannelCode::SessionEstablishmentSuccess,
188 0x0001 => SecureChannelCode::NoSharedTrustRoots,
189 0x0002 => SecureChannelCode::InvalidParameter,
190 0x0003 => SecureChannelCode::CloseSession,
191 0x0004 => SecureChannelCode::Busy,
192 _ => return None,
193 })
194 }
195
196 #[must_use]
198 pub const fn encoded_len(&self) -> usize {
199 Self::HEADER_LEN.saturating_add(self.data.len())
200 }
201
202 pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
204 let total = self.encoded_len();
205 let Some(dst) = out.get_mut(..total) else {
206 bail!(BufferTooSmall)
207 };
208 let Some(general) = dst.get_mut(..2) else {
209 bail!(BufferTooSmall)
210 };
211 general.copy_from_slice(&(self.general as u16).to_le_bytes());
212
213 let qualified = (u32::from(self.protocol.vendor.0) << 16) | u32::from(self.protocol.id);
215 let Some(slot) = dst.get_mut(2..6) else {
216 bail!(BufferTooSmall)
217 };
218 slot.copy_from_slice(&qualified.to_le_bytes());
219
220 let Some(slot) = dst.get_mut(6..8) else {
221 bail!(BufferTooSmall)
222 };
223 slot.copy_from_slice(&self.protocol_code.to_le_bytes());
224
225 let Some(slot) = dst.get_mut(8..) else {
226 bail!(BufferTooSmall)
227 };
228 slot.copy_from_slice(self.data);
229 Ok(total)
230 }
231
232 #[expect(
234 clippy::cast_possible_truncation,
235 reason = "Appendix D's ProtocolCode is the low 16 bits of the qualified value just decoded"
236 )]
237 pub fn decode(buf: &'a [u8]) -> Result<Self> {
238 let (Some(general), Some(protocol), Some(code), Some(data)) =
239 (buf.get(..2), buf.get(2..6), buf.get(6..8), buf.get(8..))
240 else {
241 bail!(MessageTruncated)
242 };
243 let (Ok(general), Ok(protocol), Ok(code)) = (
244 <[u8; 2]>::try_from(general),
245 <[u8; 4]>::try_from(protocol),
246 <[u8; 2]>::try_from(code),
247 ) else {
248 bail!(MessageTruncated)
249 };
250 let qualified = u32::from_le_bytes(protocol);
251 Ok(Self {
252 general: GeneralCode::from_u16(u16::from_le_bytes(general))?,
253 protocol: ProtocolId {
254 vendor: VendorId((qualified >> 16) as u16),
255 id: qualified as u16,
256 },
257 protocol_code: u16::from_le_bytes(code),
258 data,
259 })
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn the_specs_worked_example_encodes_exactly() {
269 let report = StatusReport {
272 general: GeneralCode::Failure,
273 protocol: ProtocolId::BDX,
274 protocol_code: 0x0052,
275 data: &[],
276 };
277 let mut buf = [0u8; 16];
278 let n = report.encode(&mut buf).expect("encode");
279 assert_eq!(&buf[..n], &[0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00]);
280 assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
281 }
282
283 #[test]
284 fn a_vendor_protocol_id_keeps_its_vendor() {
285 let report = StatusReport {
286 general: GeneralCode::Failure,
287 protocol: ProtocolId {
288 vendor: VendorId(0xFFF1),
289 id: 0x0042,
290 },
291 protocol_code: 7,
292 data: &[],
293 };
294 let mut buf = [0u8; 16];
295 let n = report.encode(&mut buf).expect("encode");
296 assert_eq!(&buf[2..6], &[0x42, 0x00, 0xF1, 0xFF]);
298 assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
299 }
300
301 #[test]
302 fn pake_finished_is_a_success_report() {
303 let report = StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess);
305 assert_eq!(report.general, GeneralCode::Success);
306 assert!(report.is_success());
307 assert_eq!(
308 report.secure_channel_code(),
309 Some(SecureChannelCode::SessionEstablishmentSuccess)
310 );
311
312 let mut buf = [0u8; 16];
313 let n = report.encode(&mut buf).expect("encode");
314 assert_eq!(&buf[..n], &[0, 0, 0, 0, 0, 0, 0, 0]);
315 }
316
317 #[test]
318 fn each_secure_channel_code_carries_the_general_code_table_19_pairs_it_with() {
319 assert_eq!(
321 SecureChannelCode::SessionEstablishmentSuccess.general(),
322 GeneralCode::Success
323 );
324 assert_eq!(
325 SecureChannelCode::InvalidParameter.general(),
326 GeneralCode::Failure
327 );
328 assert_eq!(
329 SecureChannelCode::NoSharedTrustRoots.general(),
330 GeneralCode::Failure
331 );
332 assert_eq!(
333 SecureChannelCode::CloseSession.general(),
334 GeneralCode::Success
335 );
336 assert_eq!(SecureChannelCode::Busy.general(), GeneralCode::Busy);
337 }
338
339 #[test]
340 fn only_close_session_must_be_encrypted() {
341 assert!(SecureChannelCode::CloseSession.requires_encryption());
342 for code in [
343 SecureChannelCode::SessionEstablishmentSuccess,
344 SecureChannelCode::NoSharedTrustRoots,
345 SecureChannelCode::InvalidParameter,
346 SecureChannelCode::Busy,
347 ] {
348 assert!(
349 !code.requires_encryption(),
350 "{code:?} is sent before a session exists"
351 );
352 }
353 }
354
355 #[test]
356 fn protocol_data_round_trips() {
357 let report = StatusReport {
358 general: GeneralCode::Busy,
359 protocol: ProtocolId::SECURE_CHANNEL,
360 protocol_code: SecureChannelCode::Busy as u16,
361 data: &[0xF4, 0x01],
363 };
364 let mut buf = [0u8; 16];
365 let n = report.encode(&mut buf).expect("encode");
366 assert_eq!(n, 10);
367 let decoded = StatusReport::decode(&buf[..n]).expect("decode");
368 assert_eq!(decoded.data, &[0xF4, 0x01]);
369 }
370
371 #[test]
372 fn a_reserved_general_code_is_refused() {
373 let buf = [0xFF, 0x00, 0, 0, 0, 0, 0, 0];
374 assert_eq!(
375 StatusReport::decode(&buf).unwrap_err().code(),
376 ErrorCode::MessageReserved
377 );
378 }
379
380 #[test]
381 fn truncation_at_every_length_is_an_error_not_a_panic() {
382 let buf = [0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00];
383 for cut in 0..buf.len() {
384 assert!(StatusReport::decode(&buf[..cut]).is_err(), "cut {cut}");
385 }
386 assert!(StatusReport::decode(&buf).is_ok());
387 }
388
389 #[test]
390 fn a_too_small_buffer_is_an_error() {
391 let report = StatusReport::secure_channel(SecureChannelCode::InvalidParameter);
392 let mut buf = [0u8; 7];
393 assert_eq!(
394 report.encode(&mut buf).unwrap_err().code(),
395 ErrorCode::BufferTooSmall
396 );
397 }
398
399 #[test]
400 fn general_codes_round_trip_through_their_numbers() {
401 for (value, code) in [
402 (0u16, GeneralCode::Success),
403 (1, GeneralCode::Failure),
404 (8, GeneralCode::Busy),
405 (10, GeneralCode::Continue),
406 (17, GeneralCode::MessageTooLarge),
407 ] {
408 assert_eq!(GeneralCode::from_u16(value).expect("known"), code);
409 assert_eq!(code as u16, value);
410 }
411 assert!(GeneralCode::from_u16(18).is_err());
412 }
413
414 #[test]
415 fn continue_counts_as_success() {
416 assert!(GeneralCode::Continue.is_success());
417 assert!(GeneralCode::Success.is_success());
418 assert!(!GeneralCode::Failure.is_success());
419 assert!(!GeneralCode::Busy.is_success());
420 }
421}