Skip to main content

hyprstream_rpc/
sensitive.rs

1//! Wire-compatible bytes whose diagnostic representation never exposes contents.
2
3/// Serialization intentionally preserves the bytes for the authenticated wire
4/// protocol. Debug is redacted; callers must not log serialized values either.
5#[derive(Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6#[serde(transparent)]
7pub struct SensitiveBytes(Vec<u8>);
8
9/// Domain types over wire `Data` enforce their own byte budget at decode,
10/// before any owned copy is materialized by generated readers.
11pub trait BoundedWireBytes: Sized {
12    fn from_wire_bytes(bytes: &[u8]) -> anyhow::Result<Self>;
13}
14
15impl SensitiveBytes {
16    pub fn new(bytes: Vec<u8>) -> Self {
17        Self(bytes)
18    }
19}
20
21impl BoundedWireBytes for SensitiveBytes {
22    /// Bounded wire decode: reject before any owned copy when the peer sent
23    /// more than the mediated-evidence cap. The outer envelope frame has its
24    /// own (larger) bound; this enforces the stated evidence budget at the
25    /// field boundary so generated dispatch never materializes an oversized
26    /// buffer ahead of verification.
27    fn from_wire_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
28        use crate::envelope::MAX_MEDIATED_EVIDENCE_BYTES;
29        anyhow::ensure!(
30            bytes.len() <= MAX_MEDIATED_EVIDENCE_BYTES,
31            "sensitive wire bytes exceed the mediated evidence cap"
32        );
33        Ok(Self(bytes.to_vec()))
34    }
35}
36
37impl From<Vec<u8>> for SensitiveBytes {
38    fn from(bytes: Vec<u8>) -> Self {
39        Self::new(bytes)
40    }
41}
42
43impl std::ops::Deref for SensitiveBytes {
44    type Target = [u8];
45
46    fn deref(&self) -> &Self::Target {
47        &self.0
48    }
49}
50
51impl std::fmt::Debug for SensitiveBytes {
52    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        formatter.write_str("SensitiveBytes([REDACTED])")
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn debug_redacts_contents_without_changing_wire_bytes() {
63        let value = SensitiveBytes::new(b"secret-credential".to_vec());
64        assert_eq!(format!("{value:?}"), "SensitiveBytes([REDACTED])");
65        assert_eq!(&*value, b"secret-credential");
66    }
67
68    #[test]
69    fn wire_decode_rejects_oversized_before_copy() {
70        use super::BoundedWireBytes;
71        use crate::envelope::MAX_MEDIATED_EVIDENCE_BYTES;
72        let oversized = vec![0u8; MAX_MEDIATED_EVIDENCE_BYTES + 1];
73        assert!(SensitiveBytes::from_wire_bytes(&oversized).is_err());
74        let exact = vec![0u8; MAX_MEDIATED_EVIDENCE_BYTES];
75        assert!(SensitiveBytes::from_wire_bytes(&exact).is_ok());
76    }
77}