tightbeam-rs 0.9.0

A secure, high-performance messaging protocol library
Documentation
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use crate::der::{EncodeValue, Tagged};
use crate::error::Result;
use crate::{Frame, Metadata, TightBeamError, Version};

#[cfg(feature = "aead")]
use crate::asn1::OctetString;
#[cfg(feature = "signature")]
use crate::crypto::hash::Digest;
#[cfg(feature = "crypto")]
use crate::crypto::profiles::SecurityProfile;
#[cfg(feature = "signature")]
use crate::crypto::sign::{verify_canonical, PrehashVerifier, SignatureEncoding};
#[cfg(feature = "signature")]
use crate::der::oid::AssociatedOid;
#[cfg(feature = "signature")]
use crate::der::Encode;
#[cfg(feature = "signature")]
use crate::error::ReceivedExpectedError;
#[cfg(feature = "aead")]
use crate::EncryptedContentInfo;
#[cfg(feature = "signature")]
use crate::SignerInfo;

/// Decompresses message bodies.
///
/// A single always-present trait so downstream code compiles identically
/// under every feature combination.
pub trait Inflator {
	/// Decompress `data`, returning the decompressed bytes.
	///
	/// # Errors
	///
	/// Returns an error when the underlying codec rejects the input.
	fn decompress(&self, data: &[u8]) -> Result<Vec<u8>>;
}

/// A marker trait for types that can be used as the body of a TightBeam
/// message.
pub trait Message:
	EncodeValue + Tagged + for<'a> crate::der::Decode<'a> + Clone + PartialEq + core::fmt::Debug + Sized + Send + Sync
{
	/// Minimum version required to send this message type
	const MIN_VERSION: Version = Version::V0;
	/// Whether this message type requires non-repudiation (signing)
	const MUST_BE_NON_REPUDIABLE: bool = false;
	/// Whether this message type requires confidentiality (encryption)
	const MUST_BE_CONFIDENTIAL: bool = false;
	/// Whether this message type requires compression
	const MUST_BE_COMPRESSED: bool = false;
	/// Whether this message type requires prioritization
	const MUST_BE_PRIORITIZED: bool = false;
	/// Whether this message type requires message integrity (hashing)
	const MUST_HAVE_MESSAGE_INTEGRITY: bool = false;
	/// Whether this message type requires frame integrity (hashing)
	const MUST_HAVE_FRAME_INTEGRITY: bool = false;

	/// Whether this message type has a custom security profile that
	/// constrains algorithms.
	const HAS_PROFILE: bool = false;

	/// The security profile that constrains which cryptographic algorithms
	/// can be used with this message type. Defaults to TightbeamProfile.
	#[cfg(feature = "crypto")]
	type Profile: SecurityProfile;
}

/// A trait for types that represent a TightBeam message with associated data.
pub trait TightBeamLike:
	crate::der::Encode
	+ for<'a> crate::der::Decode<'a>
	+ Clone
	+ core::fmt::Debug
	+ PartialEq
	+ Into<Metadata>
	+ Into<Version>
{
}

impl Frame {
	/// Get a reference to the metadata.
	///
	/// For owned, use `From<Frame> for Metadata` which consumes the frame.
	pub fn as_metadata(&self) -> &Metadata {
		&self.metadata
	}
}

#[cfg(feature = "signature")]
impl Frame {
	/// Get a reference to the signature info if present.
	pub fn signature_info(&self) -> Option<&SignerInfo> {
		self.nonrepudiation.as_ref()
	}

	/// Encode the Frame for signature verification (TBS - to-be-signed).
	///
	/// Excludes `nonrepudiation` without cloning the frame: the borrowing
	/// [`TbsScaffold`](crate::frame::TbsScaffold) reuses the derived field
	/// encoders, so these bytes are bit-identical to the DER encoding of the
	/// frame with `nonrepudiation` set to `None`.
	pub fn to_tbs(&self) -> Result<Vec<u8>> {
		let scaffold = crate::frame::TbsScaffold {
			version: &self.version,
			metadata: &self.metadata,
			message: &self.message,
			integrity: self.integrity.as_ref(),
		};

		Ok(scaffold.to_der()?)
	}

	/// Verify the signature of the TightBeam message
	///
	/// This verifies the signature against the entire TightBeam structure
	/// under the canonical convention: the TBS encoding is hashed once with
	/// `D` and the signature is checked against that prehash.
	///
	/// # Arguments
	/// * `verifier` - The verifier to use for signature verification
	///
	/// # Returns
	/// Ok(()) if the signature is valid
	///
	/// # Errors
	/// Returns an error if:
	/// - The TightBeam doesn't contain a signature
	/// - The SignerInfo advertises a digest other than `D`
	/// - Signature verification fails
	pub fn verify<S, D>(&self, verifier: &impl PrehashVerifier<S>) -> Result<()>
	where
		S: SignatureEncoding,
		D: Digest + AssociatedOid,
	{
		// Extract signature info from the Frame
		let signature_info = self.nonrepudiation.as_ref().ok_or(TightBeamError::MissingSignature)?;

		// The canonical convention binds the signature to the digest declared
		// in the SignerInfo; a mismatch is algorithm confusion, not merely a
		// bad signature.
		if signature_info.digest_alg.oid != D::OID {
			return Err(TightBeamError::UnexpectedAlgorithm(ReceivedExpectedError::from((
				signature_info.digest_alg.oid,
				D::OID,
			))));
		}

		let signature_bytes: &[u8] = signature_info.signature.as_bytes();

		// Decode the signature
		let signature = S::try_from(signature_bytes).map_err(|_| TightBeamError::SignatureEncodingError)?;

		// Encode TBS (to-be-signed) structure without cloning - skip the signature field
		let tbs_der = self.to_tbs()?;

		// Verify signature
		verify_canonical::<D, S>(verifier, &tbs_der, &signature)?;

		Ok(())
	}
}

#[cfg(feature = "aead")]
impl Frame {
	/// Get a reference to the encrypted content info if present.
	pub fn encrypted_content_info(&self) -> Option<&EncryptedContentInfo> {
		self.metadata.confidentiality.as_ref()
	}

	/// Decrypt the message body and return the plaintext bytes.
	/// This will consume the frame.
	///
	/// # Arguments
	/// * `decryptor` - The AEAD decryptor to use for decryption
	///
	/// # Returns
	/// The decrypted plaintext as a [`SecretSlice`](crate::crypto::secret::SecretSlice)
	/// that zeroizes on drop. If the frame was compressed, these bytes are
	/// still compressed and need to be decompressed separately. Callers that
	/// need a raw copy opt out explicitly via
	/// [`ToInsecure`](crate::crypto::secret::ToInsecure).
	///
	/// # Errors
	/// Returns an error if:
	/// - The metadata doesn't contain encryption info (V0 metadata)
	/// - Decryption fails
	pub fn decrypt_bytes(
		mut self,
		decryptor: &impl crate::crypto::aead::Decryptor,
	) -> Result<crate::crypto::secret::SecretSlice<u8>> {
		let mut encrypted_content_info = self
			.metadata
			.confidentiality
			.take()
			.ok_or(TightBeamError::MissingEncryptionInfo)?;

		// The encrypted content is stored in the message field - move it into the info
		let message = OctetString::new(core::mem::take(&mut self.message))?;
		encrypted_content_info.encrypted_content = Some(message);

		// Decrypt using the Decryptor trait
		decryptor.decrypt_content(&encrypted_content_info)
	}

	/// Decrypt, decompress (if needed), and decode the message body into a typed message T.
	/// This is a convenience method that combines `decrypt_bytes`, `decompress`, and `decode`.
	///
	/// # Arguments
	/// * `decryptor` - The AEAD decryptor to use for decryption
	/// * `inflator` - Optional inflator for decompressing the data (required if compressed)
	///
	/// # Returns
	/// The decrypted, decompressed, and decoded message of type T
	///
	/// # Errors
	/// Returns an error if:
	/// - The metadata doesn't contain encryption info (V0 metadata)
	/// - Decryption fails
	/// - Decompression fails (if compressed)
	/// - Deserialization of the decrypted data fails
	pub fn decrypt<T>(
		self,
		decryptor: &impl crate::crypto::aead::Decryptor,
		inflator: Option<&dyn Inflator>,
	) -> Result<T>
	where
		T: Message,
	{
		use crate::crypto::secret::ToInsecure;

		let was_compressed = self.metadata.compactness.is_some();
		let plaintext = self.decrypt_bytes(decryptor)?.to_insecure()?;
		let decompressed = Self::decompress(plaintext.into_vec(), was_compressed, inflator)?;

		crate::decode::<T>(&decompressed)
	}

	/// Decrypt the message body in place, turning an encrypted frame into
	/// its cleartext equivalent.
	///
	/// Frame-level `integrity` and `nonrepudiation` cover the encrypted
	/// body and are left untouched: verify them *before* calling, they
	/// will no longer match afterwards.
	///
	/// # Errors
	///
	/// - [`TightBeamError::MissingEncryptionInfo`] -- frame is not encrypted.
	/// - [`TightBeamError::MissingInflator`] -- body is compressed with no inflator.
	/// - Decryption or decompression errors from the underlying implementations.
	pub fn decrypt_in_place(
		&mut self,
		decryptor: &dyn crate::crypto::aead::Decryptor,
		inflator: Option<&dyn Inflator>,
	) -> Result<()> {
		use crate::crypto::secret::ToInsecure;

		let Some(mut encrypted) = self.metadata.confidentiality.take() else {
			return Err(TightBeamError::MissingEncryptionInfo);
		};

		if self.metadata.compactness.is_some() && inflator.is_none() {
			self.metadata.confidentiality = Some(encrypted);
			return Err(TightBeamError::MissingInflator);
		}

		encrypted.encrypted_content = Some(OctetString::new(core::mem::take(&mut self.message))?);

		match decryptor.decrypt_content(&encrypted) {
			Ok(plaintext) => {
				let was_compressed = self.metadata.compactness.take().is_some();
				let plaintext = plaintext.to_insecure()?;

				self.message = Self::decompress(plaintext.into_vec(), was_compressed, inflator)?;

				Ok(())
			}
			Err(err) => {
				if let Some(content) = encrypted.encrypted_content.take() {
					self.message = content.into_bytes();
				}
				self.metadata.confidentiality = Some(encrypted);
				Err(err)
			}
		}
	}
}

impl Frame {
	/// Decompress the message body in place for a cleartext-but-compressed
	/// frame, clearing `compactness` on success.
	///
	/// A frame without `compactness` is returned unchanged. On
	/// decompression failure the frame is restored unchanged.
	///
	/// # Errors
	///
	/// Returns the underlying codec error when the inflator rejects the
	/// body.
	pub fn inflate_in_place(&mut self, inflator: &dyn Inflator) -> Result<()> {
		let Some(compactness) = self.metadata.compactness.take() else {
			return Ok(());
		};

		let compressed = core::mem::take(&mut self.message);
		match inflator.decompress(&compressed) {
			Ok(plaintext) => {
				self.message = plaintext;
				Ok(())
			}
			Err(err) => {
				self.message = compressed;
				self.metadata.compactness = Some(compactness);
				Err(err)
			}
		}
	}
}

impl TightBeamLike for Frame {}

impl From<Frame> for Metadata {
	fn from(mut frame: Frame) -> Self {
		core::mem::take(&mut frame.metadata)
	}
}

crate::impl_from!(Frame, tb => Version: tb.version);

#[cfg(feature = "signature")]
crate::impl_try_from!(Frame, tb => SignerInfo: nonrepudiation, TightBeamError::MissingSignature);

/// Outcome of an integrity verification check.
#[cfg(feature = "digest")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntegrityVerdict {
	/// Recomputed digest matches the stored value.
	Verified,
	/// The frame carries no integrity value to check.
	Absent,
	/// The stored digest was produced by a different algorithm than `D`.
	AlgorithmMismatch,
	/// Recomputed digest differs: the covered bytes changed after digesting.
	Mismatch,
}

#[cfg(feature = "digest")]
impl IntegrityVerdict {
	/// `true` only for [`IntegrityVerdict::Verified`].
	pub fn is_verified(self) -> bool {
		matches!(self, IntegrityVerdict::Verified)
	}
}

#[cfg(feature = "digest")]
impl Frame {
	/// Get a reference to the frame integrity info if present.
	pub fn integrity_info(&self) -> Option<&crate::DigestInfo> {
		self.integrity.as_ref()
	}

	/// Get a reference to the message integrity info if present.
	pub fn message_integrity(&self) -> Option<&crate::DigestInfo> {
		self.metadata.integrity.as_ref()
	}

	/// Check a disclosed [`Opening`](crate::crypto::commitment::Opening)
	/// against this frame's message commitment, reporting which condition
	/// held.
	pub fn message_commitment_verdict<D>(
		&self,
		opening: &crate::crypto::commitment::Opening,
	) -> Result<IntegrityVerdict>
	where
		D: crate::crypto::hash::Digest + crate::der::oid::AssociatedOid,
	{
		let Some(commitment) = self.metadata.integrity.as_ref() else {
			return Ok(IntegrityVerdict::Absent);
		};
		if commitment.algorithm.oid != D::OID {
			return Ok(IntegrityVerdict::AlgorithmMismatch);
		}

		if opening.verify::<D>(commitment)? {
			Ok(IntegrityVerdict::Verified)
		} else {
			Ok(IntegrityVerdict::Mismatch)
		}
	}

	/// Verify a disclosed [`Opening`](crate::crypto::commitment::Opening)
	/// against this frame's message commitment.
	///
	/// Convenience over [`Frame::message_commitment_verdict`]: returns
	/// `Ok(false)` for absence, algorithm mismatch, and digest mismatch alike.
	/// Callers that must distinguish a stripped commitment from a tampered one
	/// use the verdict method.
	pub fn verify_message_commitment<D>(&self, opening: &crate::crypto::commitment::Opening) -> Result<bool>
	where
		D: crate::crypto::hash::Digest + crate::der::oid::AssociatedOid,
	{
		Ok(self.message_commitment_verdict::<D>(opening)?.is_verified())
	}

	/// Check this frame's frame-integrity (FI) digest, reporting which
	/// condition held.
	///
	/// Recomputes `H(SEQUENCE { version, metadata })` with `D` and compares it
	/// against the stored digest.
	pub fn frame_integrity_verdict<D>(&self) -> Result<IntegrityVerdict>
	where
		D: crate::crypto::hash::Digest + crate::der::oid::AssociatedOid,
	{
		let Some(info) = self.integrity.as_ref() else {
			return Ok(IntegrityVerdict::Absent);
		};
		if info.algorithm.oid != D::OID {
			return Ok(IntegrityVerdict::AlgorithmMismatch);
		}

		let scaffold = crate::frame::FrameIntegrityScaffold { version: &self.version, metadata: &self.metadata };
		let recomputed = crate::utils::digest::<D>(&crate::encode(&scaffold)?)?;
		if recomputed.digest.as_bytes() == info.digest.as_bytes() {
			Ok(IntegrityVerdict::Verified)
		} else {
			Ok(IntegrityVerdict::Mismatch)
		}
	}

	/// Verify this frame's frame-integrity (FI) digest.
	///
	/// Convenience over [`Frame::frame_integrity_verdict`]: returns
	/// `Ok(false)` for absence, algorithm mismatch, and digest mismatch alike.
	/// Callers that must distinguish a stripped FI field from a tampered
	/// envelope use the verdict method.
	pub fn verify_frame_integrity<D>(&self) -> Result<bool>
	where
		D: crate::crypto::hash::Digest + crate::der::oid::AssociatedOid,
	{
		Ok(self.frame_integrity_verdict::<D>()?.is_verified())
	}
}

#[cfg(feature = "compress")]
impl Frame {
	/// Get a reference to the compressed data info if present.
	pub fn compressed_data(&self) -> Option<&crate::CompressedData> {
		self.metadata.compactness.as_ref()
	}

	/// Decompress the plaintext bytes if compression was used.
	///
	/// # Arguments
	/// * `plaintext` - The plaintext bytes (may be compressed)
	/// * `was_compressed` - Whether the data was compressed
	/// * `inflator` - The inflator to use for decompression (required if compressed)
	///
	/// # Returns
	/// The decompressed bytes, or the original bytes if not compressed.
	///
	/// # Errors
	/// Returns an error if:
	/// - Compression was used but no inflator was provided
	/// - Decompression fails
	pub fn decompress(plaintext: Vec<u8>, was_compressed: bool, inflator: Option<&dyn Inflator>) -> Result<Vec<u8>> {
		if was_compressed {
			let inflator = inflator.ok_or(TightBeamError::MissingInflator)?;
			inflator.decompress(&plaintext)
		} else {
			Ok(plaintext)
		}
	}
}

#[cfg(not(feature = "compress"))]
impl Frame {
	/// Decompress the plaintext bytes if compression was used.
	///
	/// This is a no-op when the `compress` feature is disabled.
	pub fn decompress(plaintext: Vec<u8>, was_compressed: bool, _inflator: Option<&dyn Inflator>) -> Result<Vec<u8>> {
		if was_compressed {
			Err(TightBeamError::MissingFeature("compress"))
		} else {
			Ok(plaintext)
		}
	}
}

#[cfg(feature = "aead")]
impl TryFrom<Frame> for EncryptedContentInfo {
	type Error = TightBeamError;

	fn try_from(mut frame: Frame) -> core::result::Result<Self, Self::Error> {
		frame
			.metadata
			.confidentiality
			.take()
			.ok_or(TightBeamError::MissingEncryptionInfo)
	}
}

#[cfg(test)]
mod tests {
	#[cfg(not(feature = "std"))]
	use alloc::{
		string::{String, ToString},
		vec,
		vec::Vec,
	};

	use crate::testing::create_test_cipher_key;
	use crate::testing::{create_test_message, create_test_signing_key};
	use crate::Beamable;
	use crate::MessagePriority;

	use super::*;

	// Test data structures
	#[derive(Clone, Debug, PartialEq, der::Sequence)]
	struct SimpleMessage {
		id: u64,
		name: String,
	}

	#[derive(Clone, Debug, PartialEq, der::Sequence)]
	struct NestedMessage {
		value: u32,
		data: Vec<u8>,
		flag: bool,
	}

	/// Pin `decoded` to the type of `original`: with reduced feature sets the
	/// `serde_json` dev-dependency's `PartialEq<Value>` impls for integers make
	/// a bare `assert_eq!` on `decode`'s inferred output ambiguous.
	fn assert_round_trip<T: PartialEq + core::fmt::Debug>(original: &T, decoded: &T) {
		assert_eq!(original, decoded);
	}

	/// Macro to generate encode/decode round-trip tests
	macro_rules! test_encode_decode {
		($($name:ident: $value:expr,)*) => {
			$(
				#[test]
				fn $name() {
					let original = $value;

					// Encode
					let encoded = crate::encode(&original).unwrap();
					assert!(!encoded.is_empty());

					// Decode
					let decoded = crate::decode(&encoded).unwrap();
					assert_round_trip(&original, &decoded);

					// Verify it's valid DER (encode again and compare)
					let re_encoded = crate::encode(&decoded).unwrap();
					assert_eq!(encoded, re_encoded);
				}
			)*
		};
	}

	test_encode_decode! {
		encode_decode_simple_message: SimpleMessage {
			id: 42,
			name: "test".to_string(),
		},
		encode_decode_simple_message_zero: SimpleMessage {
			id: 0,
			name: String::new(),
		},
		encode_decode_simple_message_large: SimpleMessage {
			id: u64::MAX,
			name: "a very long name with many characters".to_string(),
		},
		encode_decode_nested_message: NestedMessage {
			value: 12345,
			data: vec![1, 2, 3, 4, 5],
			flag: true,
		},
		encode_decode_nested_message_false: NestedMessage {
			value: 0,
			data: Vec::new(),
			flag: false,
		},
		encode_decode_u32: 42u32,
		encode_decode_u64: 9876543210u64,
		encode_decode_bool_true: true,
		encode_decode_bool_false: false,
	}

	/// Macro to generate decode failure tests
	macro_rules! test_decode_failure {
		($($name:ident: $data:expr => $type:ty,)*) => {
			$(
				#[test]
				fn $name() {
					let result: Result<$type> = crate::decode($data);
					assert!(result.is_err());
				}
			)*
		};
	}

	test_decode_failure! {
		decode_invalid_der_should_fail: &vec![0xFF, 0xFF, 0xFF] => u32,
		decode_empty_should_fail: &vec![] => u32,
		decode_invalid_sequence: &vec![0x30, 0xFF] => SimpleMessage,
		decode_wrong_type: &vec![0x02, 0x01, 0x2A] => SimpleMessage, // INTEGER instead of SEQUENCE
	}

	#[test]
	fn decode_truncated_should_fail() -> Result<()> {
		// Create a valid encoding then truncate it
		let original = SimpleMessage { id: 100, name: "test".to_string() };
		let mut encoded = crate::encode(&original)?;
		encoded.truncate(5);

		let result: Result<SimpleMessage> = crate::decode(&encoded);
		assert!(result.is_err());

		Ok(())
	}

	/// Macro to generate TightBeam encode/decode round-trip tests
	macro_rules! test_tightbeam_roundtrip {
		($($name:ident: $tightbeam:expr,)*) => {
			$(
				#[test]
				fn $name() -> Result<()> {
					let original = $tightbeam;

					// Encode
					let encoded = crate::encode(&original).unwrap();
					assert!(!encoded.is_empty());

					// Decode
					let decoded: Frame = crate::decode(&encoded).unwrap();
					// Verify round-trip
					assert_eq!(original, decoded);

					// Verify it's valid DER (encode again and compare)
					let re_encoded = crate::encode(&decoded).unwrap();
					assert_eq!(encoded, re_encoded);

					Ok(())
				}
			)*
		};
	}

	test_tightbeam_roundtrip! {
		tightbeam_v0_minimal: {
			let message = create_test_message(None);
			compose! {
				V0:
					id: "test-001",
					order: 1696521600,
					message: message,
			}.unwrap()
		},
		tightbeam_v0_large_value: {
			let message = create_test_message(Some(&("A".repeat(1000))));
			compose! {
				V0:
					id: "test-002",
					order: 1696521700,
					message: message
			}.unwrap()
		},
		tightbeam_v1_encrypted: {
			use crate::crypto::aead::Aes256GcmOid;
			use crate::crypto::sign::ecdsa::Secp256k1Signature;

			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			compose! {
				V1: id: "test-003",
					order: 1696521800,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key
			}.unwrap()
		},
		tightbeam_v2_full: {
			use crate::crypto::aead::Aes256GcmOid;
			use crate::crypto::sign::ecdsa::Secp256k1Signature;
			use crate::crypto::hash::Sha3_256;

			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			compose! {
				V2: id: "test-004",
					order: 1696521900,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: [],
					priority: MessagePriority::HighThroughput,
					lifetime: 3600
			}.unwrap()
		},
	}

	/// Macro to test TightBeam conversions
	macro_rules! test_tightbeam_conversions {
		($($name:ident: $tightbeam:expr => $target:ty,)*) => {
			$(
				#[test]
				fn $name() {
					let tightbeam = $tightbeam;
					let _converted: $target = tightbeam.clone().into();
				}
			)*
		};
	}

	test_tightbeam_conversions! {
		tightbeam_to_metadata_v0: {
			let message = create_test_message(None);
			compose! {
				V0:
					id: "meta-001",
					order: 1000,
					message: message
			}.unwrap()
		} => Metadata,
		tightbeam_to_protocol_version: {
			use crate::crypto::aead::Aes256GcmOid;
			use crate::crypto::sign::ecdsa::Secp256k1Signature;
			use crate::crypto::hash::Sha3_256;

			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			compose! {
				V2:
					id: "ver-001",
					order: 2000,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: [],
					priority: MessagePriority::Expedited,
					lifetime: 60
			}.unwrap()
		} => Version,
	}

	/// Macro to test TightBeam TryFrom conversions (owned only)
	macro_rules! test_tightbeam_try_conversions {
		(success: $($name:ident: $tightbeam:expr => $target:ty,)*) => {
			$(
				#[test]
				fn $name() {
					let tightbeam = $tightbeam;
					let result: Result<$target> = tightbeam.try_into();
					assert!(result.is_ok());
				}
			)*
		};
		(failure: $($name:ident: $tightbeam:expr => $target:ty,)*) => {
			$(
				#[test]
				fn $name() {
					let tightbeam = $tightbeam;
					let result: Result<$target> = tightbeam.try_into();
					assert!(result.is_err());
				}
			)*
		};
	}

	test_tightbeam_try_conversions! {
		success:
		tightbeam_v1_to_signature_info: {
			use crate::crypto::aead::Aes256GcmOid;
			use crate::crypto::sign::ecdsa::Secp256k1Signature;

			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			compose! {
				V1: id: "sig-001",
					order: 3000,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key
			}.unwrap()
		} => SignerInfo,
		tightbeam_v2_to_encryption_info: {
			use crate::crypto::aead::Aes256GcmOid;
			use crate::crypto::sign::ecdsa::Secp256k1Signature;
			use crate::crypto::hash::Sha3_256;

			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let signing_key = create_test_signing_key();

			compose! {
				V2:
					id: "enc-001",
					order: 4000,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher,
					nonrepudiation<Secp256k1Signature, _>: signing_key,
					message_integrity<Sha3_256>: [],
					priority: MessagePriority::LowLatency,
					lifetime: 120
			}.unwrap()
		} => EncryptedContentInfo,
	}

	test_tightbeam_try_conversions! {
		failure: // Do nothing: should fail due to missing fields
		tightbeam_v0_to_signature_info_fails: {
			let message = create_test_message(None);
			compose! {
				V0:
					id: "fail-001",
					order: 5000,
					message: message
			}.unwrap()
		} => SignerInfo,
		tightbeam_v0_to_encryption_info_fails: {
			let message = create_test_message(None);
			compose! {
				V0:
					id: "fail-002",
					order: 6000,
					message: message
			}.unwrap()
		} => EncryptedContentInfo,
	}

	// Test data structures for Profile type testing
	#[cfg(feature = "derive")]
	#[derive(Beamable, Clone, Debug, PartialEq, der::Sequence)]
	#[beam(profile = 1)]
	struct NumericProfileMessage {
		id: u64,
		data: String,
	}

	#[cfg(feature = "derive")]
	#[derive(Beamable, Clone, Debug, PartialEq, der::Sequence)]
	#[beam(profile(crate::crypto::profiles::TightbeamProfile))]
	struct TypeProfileMessage {
		id: u64,
		data: String,
	}

	#[cfg(feature = "derive")]
	#[derive(Beamable, Clone, Debug, PartialEq, der::Sequence)]
	struct NoProfileMessage {
		id: u64,
		data: String,
	}

	#[cfg(feature = "derive")]
	#[test]
	#[allow(clippy::assertions_on_constants)]
	fn test_profile_types() {
		// All message types should have a Profile type that implements SecurityProfile
		fn assert_security_profile<P: crate::crypto::profiles::SecurityProfile>() {}

		assert_security_profile::<<NumericProfileMessage as crate::Message>::Profile>();
		assert_security_profile::<<TypeProfileMessage as crate::Message>::Profile>();
		assert_security_profile::<<NoProfileMessage as crate::Message>::Profile>();

		// Type-based profile should be StandardProfile
		assert_eq!(
			core::any::TypeId::of::<<TypeProfileMessage as crate::Message>::Profile>(),
			core::any::TypeId::of::<crate::crypto::profiles::TightbeamProfile>()
		);

		// Test HAS_PROFILE values
		assert!(!NumericProfileMessage::HAS_PROFILE);
		assert!(TypeProfileMessage::HAS_PROFILE);
		assert!(!NoProfileMessage::HAS_PROFILE);
	}

	#[cfg(all(feature = "signature", feature = "builder", feature = "sha3"))]
	mod tbs_encoding {
		use super::*;
		use crate::testing::create_frame_with_frame_integrity;

		/// Signature validity depends on `to_tbs` staying bit-identical to the
		/// derived DER encoding of a frame with `nonrepudiation` stripped.
		#[test]
		fn tbs_matches_derived_encoding_with_integrity() -> Result<()> {
			let frame = create_frame_with_frame_integrity();

			let mut unsigned = frame.clone();
			unsigned.nonrepudiation = None;

			assert_eq!(frame.to_tbs()?, crate::encode(&unsigned)?);

			Ok(())
		}

		#[test]
		fn tbs_matches_derived_encoding_without_integrity() -> Result<()> {
			let message = create_test_message(None);
			let frame = compose! { V0: id: "tbs-basic", order: 1u64, message: message }?;

			let mut unsigned = frame.clone();
			unsigned.nonrepudiation = None;

			assert_eq!(frame.to_tbs()?, crate::encode(&unsigned)?);

			Ok(())
		}
	}

	#[cfg(all(feature = "builder", feature = "sha3"))]
	mod frame_integrity {
		use super::*;
		use crate::crypto::hash::{Sha3_256, Sha3_512};
		use crate::testing::create_frame_with_frame_integrity;

		#[test]
		fn verifies_intact_envelope() {
			let frame = create_frame_with_frame_integrity();
			assert!(matches!(frame.verify_frame_integrity::<Sha3_256>(), Ok(true)));
		}

		#[test]
		fn rejects_tampered_envelope() {
			let mut frame = create_frame_with_frame_integrity();
			frame.metadata.id = b"tampered".to_vec();
			assert!(matches!(frame.verify_frame_integrity::<Sha3_256>(), Ok(false)));
		}

		#[test]
		fn rejects_algorithm_mismatch() {
			let frame = create_frame_with_frame_integrity();
			assert!(matches!(frame.verify_frame_integrity::<Sha3_512>(), Ok(false)));
		}

		#[test]
		fn absent_integrity_is_false() {
			let message = create_test_message(None);
			let frame = compose! { V0: id: "no-fi", order: 1u64, message: message }.unwrap();
			assert!(matches!(frame.verify_frame_integrity::<Sha3_256>(), Ok(false)));
		}

		#[test]
		fn verdict_reports_verified() {
			let frame = create_frame_with_frame_integrity();
			assert!(matches!(
				frame.frame_integrity_verdict::<Sha3_256>(),
				Ok(IntegrityVerdict::Verified)
			));
		}

		#[test]
		fn verdict_reports_mismatch_on_tamper() {
			let mut frame = create_frame_with_frame_integrity();
			frame.metadata.id = b"tampered".to_vec();
			assert!(matches!(
				frame.frame_integrity_verdict::<Sha3_256>(),
				Ok(IntegrityVerdict::Mismatch)
			));
		}

		#[test]
		fn verdict_reports_algorithm_mismatch() {
			let frame = create_frame_with_frame_integrity();
			assert!(matches!(
				frame.frame_integrity_verdict::<Sha3_512>(),
				Ok(IntegrityVerdict::AlgorithmMismatch)
			));
		}

		#[test]
		fn verdict_reports_absent() -> Result<()> {
			let message = create_test_message(None);
			let frame = compose! { V0: id: "no-fi-verdict", order: 1u64, message: message }?;
			assert!(matches!(
				frame.frame_integrity_verdict::<Sha3_256>(),
				Ok(IntegrityVerdict::Absent)
			));

			Ok(())
		}
	}

	#[cfg(feature = "aead")]
	mod decrypt_in_place {
		use super::*;
		use crate::crypto::aead::Aes256GcmOid;
		use crate::error::Result;
		use crate::testing::TestMessage;

		fn encrypted_frame() -> Result<Frame> {
			let message = create_test_message(Some("in-place"));
			let (_, cipher) = create_test_cipher_key();
			compose! {
				V1: id: "dip-001",
					order: 1u64,
					message: message,
					confidentiality<Aes256GcmOid, _>: cipher
			}
		}

		#[test]
		fn yields_cleartext_frame_with_decodable_body() -> Result<()> {
			let (_, cipher) = create_test_cipher_key();
			let mut frame = encrypted_frame()?;

			frame.decrypt_in_place(&cipher, None)?;

			assert!(frame.metadata.confidentiality.is_none());

			let decoded: TestMessage = crate::decode(&frame.message)?;
			assert_eq!(decoded, create_test_message(Some("in-place")));
			Ok(())
		}

		#[test]
		fn wrong_key_restores_frame() -> Result<()> {
			use crate::crypto::aead::{Aes256Gcm, KeyInit};
			use crate::crypto::common::Key;

			let mut frame = encrypted_frame()?;
			let original = frame.clone();
			let wrong_cipher = Aes256Gcm::new(&Key::<Aes256Gcm>::from([0x44; 32]));

			let result = frame.decrypt_in_place(&wrong_cipher, None);
			assert!(result.is_err());
			assert_eq!(frame, original);
			Ok(())
		}

		#[test]
		fn cleartext_frame_rejected() -> Result<()> {
			let message = create_test_message(None);
			let (_, cipher) = create_test_cipher_key();
			let mut frame = compose! { V0: id: "dip-002", order: 1u64, message: message }?;

			let result = frame.decrypt_in_place(&cipher, None);
			assert!(matches!(result, Err(TightBeamError::MissingEncryptionInfo)));
			Ok(())
		}

		#[test]
		fn compressed_without_inflator_fails_before_mutation() -> Result<()> {
			use crate::cms::compressed_data::CompressedData;
			use crate::cms::content_info::CmsVersion;
			use crate::cms::signed_data::EncapsulatedContentInfo;
			use crate::oids::{COMPRESSION_ZSTD, DATA};
			use crate::spki::AlgorithmIdentifier;

			let (_, cipher) = create_test_cipher_key();
			let mut frame = encrypted_frame()?;
			frame.metadata.compactness = Some(CompressedData {
				version: CmsVersion::V0,
				compression_alg: AlgorithmIdentifier { oid: COMPRESSION_ZSTD, parameters: None },
				encap_content_info: EncapsulatedContentInfo { econtent_type: DATA, econtent: None },
			});

			let original = frame.clone();
			let result = frame.decrypt_in_place(&cipher, None);
			assert!(matches!(result, Err(TightBeamError::MissingInflator)));
			assert_eq!(frame, original);
			Ok(())
		}
	}

	#[cfg(feature = "compress")]
	mod inflate_in_place {
		use super::*;
		use crate::compress::{Compressor, ZstdCompression};
		use crate::error::Result;

		fn compressed_frame(body: &[u8]) -> Result<Frame> {
			let zstd = ZstdCompression::default();
			let (compressed, compression_info) = zstd.compress(body, None)?;

			let mut metadata = Metadata::default();
			metadata.id = b"inf-001".to_vec();
			metadata.compactness = Some(compression_info);

			Ok(Frame {
				version: Version::V0,
				metadata,
				message: compressed,
				integrity: None,
				nonrepudiation: None,
			})
		}

		#[test]
		fn restores_original_body_and_clears_compactness() -> Result<()> {
			let body = b"inflate me".repeat(64);
			let mut frame = compressed_frame(&body)?;

			frame.inflate_in_place(&ZstdCompression::default())?;

			assert!(frame.metadata.compactness.is_none());
			assert_eq!(frame.message, body);
			Ok(())
		}

		#[test]
		fn corrupt_body_restores_frame() -> Result<()> {
			let mut frame = compressed_frame(b"inflate me")?;
			frame.message = vec![0xFF; 8];

			let original = frame.clone();
			let result = frame.inflate_in_place(&ZstdCompression::default());
			assert!(result.is_err());
			assert_eq!(frame, original);
			Ok(())
		}

		#[test]
		fn uncompressed_frame_untouched() -> Result<()> {
			let message = create_test_message(None);
			let mut frame = compose! { V0: id: "inf-002", order: 1u64, message: message }?;
			let original = frame.clone();

			frame.inflate_in_place(&ZstdCompression::default())?;

			assert_eq!(frame, original);
			Ok(())
		}
	}
}