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 pub fn decode(buf: &'a [u8]) -> Result<Self> {
234 let (Some(general), Some(protocol), Some(code), Some(data)) =
235 (buf.get(..2), buf.get(2..6), buf.get(6..8), buf.get(8..))
236 else {
237 bail!(MessageTruncated)
238 };
239 let (Ok(general), Ok(protocol), Ok(code)) = (
240 <[u8; 2]>::try_from(general),
241 <[u8; 4]>::try_from(protocol),
242 <[u8; 2]>::try_from(code),
243 ) else {
244 bail!(MessageTruncated)
245 };
246 let qualified = u32::from_le_bytes(protocol);
247 Ok(Self {
248 general: GeneralCode::from_u16(u16::from_le_bytes(general))?,
249 protocol: ProtocolId {
250 vendor: VendorId((qualified >> 16) as u16),
251 id: qualified as u16,
252 },
253 protocol_code: u16::from_le_bytes(code),
254 data,
255 })
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 #[test]
264 fn the_specs_worked_example_encodes_exactly() {
265 let report = StatusReport {
268 general: GeneralCode::Failure,
269 protocol: ProtocolId::BDX,
270 protocol_code: 0x0052,
271 data: &[],
272 };
273 let mut buf = [0u8; 16];
274 let n = report.encode(&mut buf).expect("encode");
275 assert_eq!(&buf[..n], &[0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00]);
276 assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
277 }
278
279 #[test]
280 fn a_vendor_protocol_id_keeps_its_vendor() {
281 let report = StatusReport {
282 general: GeneralCode::Failure,
283 protocol: ProtocolId {
284 vendor: VendorId(0xFFF1),
285 id: 0x0042,
286 },
287 protocol_code: 7,
288 data: &[],
289 };
290 let mut buf = [0u8; 16];
291 let n = report.encode(&mut buf).expect("encode");
292 assert_eq!(&buf[2..6], &[0x42, 0x00, 0xF1, 0xFF]);
294 assert_eq!(StatusReport::decode(&buf[..n]).expect("decode"), report);
295 }
296
297 #[test]
298 fn pake_finished_is_a_success_report() {
299 let report = StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess);
301 assert_eq!(report.general, GeneralCode::Success);
302 assert!(report.is_success());
303 assert_eq!(
304 report.secure_channel_code(),
305 Some(SecureChannelCode::SessionEstablishmentSuccess)
306 );
307
308 let mut buf = [0u8; 16];
309 let n = report.encode(&mut buf).expect("encode");
310 assert_eq!(&buf[..n], &[0, 0, 0, 0, 0, 0, 0, 0]);
311 }
312
313 #[test]
314 fn each_secure_channel_code_carries_the_general_code_table_19_pairs_it_with() {
315 assert_eq!(
317 SecureChannelCode::SessionEstablishmentSuccess.general(),
318 GeneralCode::Success
319 );
320 assert_eq!(
321 SecureChannelCode::InvalidParameter.general(),
322 GeneralCode::Failure
323 );
324 assert_eq!(
325 SecureChannelCode::NoSharedTrustRoots.general(),
326 GeneralCode::Failure
327 );
328 assert_eq!(
329 SecureChannelCode::CloseSession.general(),
330 GeneralCode::Success
331 );
332 assert_eq!(SecureChannelCode::Busy.general(), GeneralCode::Busy);
333 }
334
335 #[test]
336 fn only_close_session_must_be_encrypted() {
337 assert!(SecureChannelCode::CloseSession.requires_encryption());
338 for code in [
339 SecureChannelCode::SessionEstablishmentSuccess,
340 SecureChannelCode::NoSharedTrustRoots,
341 SecureChannelCode::InvalidParameter,
342 SecureChannelCode::Busy,
343 ] {
344 assert!(
345 !code.requires_encryption(),
346 "{code:?} is sent before a session exists"
347 );
348 }
349 }
350
351 #[test]
352 fn protocol_data_round_trips() {
353 let report = StatusReport {
354 general: GeneralCode::Busy,
355 protocol: ProtocolId::SECURE_CHANNEL,
356 protocol_code: SecureChannelCode::Busy as u16,
357 data: &[0xF4, 0x01],
359 };
360 let mut buf = [0u8; 16];
361 let n = report.encode(&mut buf).expect("encode");
362 assert_eq!(n, 10);
363 let decoded = StatusReport::decode(&buf[..n]).expect("decode");
364 assert_eq!(decoded.data, &[0xF4, 0x01]);
365 }
366
367 #[test]
368 fn a_reserved_general_code_is_refused() {
369 let buf = [0xFF, 0x00, 0, 0, 0, 0, 0, 0];
370 assert_eq!(
371 StatusReport::decode(&buf).unwrap_err().code(),
372 ErrorCode::MessageReserved
373 );
374 }
375
376 #[test]
377 fn truncation_at_every_length_is_an_error_not_a_panic() {
378 let buf = [0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x52, 0x00];
379 for cut in 0..buf.len() {
380 assert!(StatusReport::decode(&buf[..cut]).is_err(), "cut {cut}");
381 }
382 assert!(StatusReport::decode(&buf).is_ok());
383 }
384
385 #[test]
386 fn a_too_small_buffer_is_an_error() {
387 let report = StatusReport::secure_channel(SecureChannelCode::InvalidParameter);
388 let mut buf = [0u8; 7];
389 assert_eq!(
390 report.encode(&mut buf).unwrap_err().code(),
391 ErrorCode::BufferTooSmall
392 );
393 }
394
395 #[test]
396 fn general_codes_round_trip_through_their_numbers() {
397 for (value, code) in [
398 (0u16, GeneralCode::Success),
399 (1, GeneralCode::Failure),
400 (8, GeneralCode::Busy),
401 (10, GeneralCode::Continue),
402 (17, GeneralCode::MessageTooLarge),
403 ] {
404 assert_eq!(GeneralCode::from_u16(value).expect("known"), code);
405 assert_eq!(code as u16, value);
406 }
407 assert!(GeneralCode::from_u16(18).is_err());
408 }
409
410 #[test]
411 fn continue_counts_as_success() {
412 assert!(GeneralCode::Continue.is_success());
413 assert!(GeneralCode::Success.is_success());
414 assert!(!GeneralCode::Failure.is_success());
415 assert!(!GeneralCode::Busy.is_success());
416 }
417}