Skip to main content

suminuri_wire/
verified.rs

1//! `Unverified<T>` — the type that makes "I forgot to check the MAC" impossible
2//! to write by accident.
3//!
4//! Upstream's shape is a boolean and an early return:
5//!
6//! ```go
7//! if !opts.IgnoreMac {
8//!     if fileMac != computedMac { return … MacMismatch }
9//! }
10//! return dataKey, nil            // the tree is already decrypted either way
11//! ```
12//!
13//! The tree exists, decrypted, before the check — so every later line is one
14//! `if` away from operating on unauthenticated data, and nothing in the type of
15//! the value records whether the check happened. That is fine in a codebase where
16//! one function owns the whole path, and it is exactly the shape that rots once a
17//! second caller appears.
18//!
19//! Here the decrypted value comes back wrapped. The only way to get at it is
20//! [`Unverified::verify`], which needs the MAC to match, or
21//! [`Unverified::into_inner_ignoring_mac`] — the `--ignore-mac` escape, named so
22//! a reviewer greps for one token rather than noticing a missing branch.
23//!
24//! The ceiling, stated: this is **truly-unrep for the accidental case** — there
25//! is no code path that reaches the value without one of those two calls. It is
26//! not unrepresentable in the absolute sense, because Rust cannot forbid a caller
27//! from *choosing* the named escape (C1: no dependent types to encode "and the
28//! operator authorised it"). What it buys is that the unsafe path can never be
29//! the *default* or the *silent* one.
30
31use crate::WireError;
32use crate::cipher::{DataKey, IvStash};
33use crate::mac::{Mac, verify_mac_field_recording};
34
35/// A decrypted value whose file MAC has not been checked yet.
36///
37/// Carries everything the check needs so a caller cannot be asked for the MAC
38/// inputs at some later point where they are no longer in scope.
39#[must_use = "an Unverified value is unauthenticated until you call verify()"]
40pub struct Unverified<T> {
41    inner: T,
42    computed: Mac,
43    mac_field: String,
44    lastmodified: String,
45    leaves_fed: usize,
46}
47
48impl<T> Unverified<T> {
49    /// Wrap a freshly-decrypted value together with its MAC inputs.
50    pub fn new(
51        inner: T,
52        computed: Mac,
53        mac_field: impl Into<String>,
54        lastmodified: impl Into<String>,
55        leaves_fed: usize,
56    ) -> Self {
57        Self {
58            inner,
59            computed,
60            mac_field: mac_field.into(),
61            lastmodified: lastmodified.into(),
62            leaves_fed,
63        }
64    }
65
66    /// The MAC recomputed from the decrypted contents.
67    pub fn computed_mac(&self) -> &Mac {
68        &self.computed
69    }
70
71    /// How many leaves went into the recomputed MAC. **The denominator.**
72    ///
73    /// A MAC over zero leaves matches another MAC over zero leaves, so a walker
74    /// that silently stopped finding leaves would verify green while checking
75    /// nothing. [`Unverified::verify`] refuses that case outright; this getter
76    /// lets a caller assert a specific expected count on top.
77    pub fn leaves_fed(&self) -> usize {
78        self.leaves_fed
79    }
80
81    /// Check the MAC and release the value.
82    ///
83    /// Refuses a zero-leaf verification as vacuous. That is a deliberate
84    /// divergence from upstream, which would happily verify an empty walk: the
85    /// only file that legitimately has no leaves is an empty document, and
86    /// treating one as authenticated is how a broken walker reads as a green
87    /// gate. A caller that genuinely wants to accept an empty document can say so
88    /// with [`Unverified::verify_allowing_empty`].
89    pub fn verify(self, key: &DataKey) -> Result<T, WireError> {
90        self.verify_recording(key, None)
91    }
92
93    /// [`Unverified::verify`], recording the MAC field's own IV into `stash`.
94    ///
95    /// Pass the same stash the decrypt walk filled. Upstream gets this for free
96    /// because the `mac` field shares one `Cipher` with every leaf; without it a
97    /// no-op re-encrypt leaves every data line untouched and moves the `mac:`
98    /// line alone.
99    pub fn verify_recording(
100        self,
101        key: &DataKey,
102        stash: Option<&mut IvStash>,
103    ) -> Result<T, WireError> {
104        if self.leaves_fed == 0 {
105            return Err(WireError::MacMismatch);
106        }
107        verify_mac_field_recording(
108            key,
109            &self.mac_field,
110            &self.lastmodified,
111            &self.computed,
112            stash,
113        )?;
114        Ok(self.inner)
115    }
116
117    /// [`Unverified::verify`] without the anti-vacuity refusal, for the genuinely
118    /// empty document.
119    pub fn verify_allowing_empty(self, key: &DataKey) -> Result<T, WireError> {
120        verify_mac_field_recording(
121            key,
122            &self.mac_field,
123            &self.lastmodified,
124            &self.computed,
125            None,
126        )?;
127        Ok(self.inner)
128    }
129
130    /// The `--ignore-mac` escape.
131    ///
132    /// Deliberately verbose. sops offers `--ignore-mac` and real operators need
133    /// it — a file whose MAC broke because someone hand-edited `lastmodified` is
134    /// still recoverable, and refusing outright would make us *less* useful than
135    /// what we replace. So the escape exists; it is just impossible to take
136    /// without typing its name.
137    pub fn into_inner_ignoring_mac(self) -> T {
138        self.inner
139    }
140
141    /// Map the wrapped value without unwrapping it, so a caller can keep
142    /// transforming a still-unauthenticated tree without losing the marker.
143    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Unverified<U> {
144        Unverified {
145            inner: f(self.inner),
146            computed: self.computed,
147            mac_field: self.mac_field,
148            lastmodified: self.lastmodified,
149            leaves_fed: self.leaves_fed,
150        }
151    }
152}
153
154impl<T> std::fmt::Debug for Unverified<T> {
155    /// Never prints the wrapped value — it is decrypted plaintext, and this type
156    /// is most likely to be `Debug`-printed exactly when someone is debugging a
157    /// MAC failure over a real file.
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        f.debug_struct("Unverified")
160            .field("computed", &self.computed)
161            .field("leaves_fed", &self.leaves_fed)
162            .field("value", &"***")
163            .finish()
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::leaf::Plaintext;
171    use crate::mac::{MacAccumulator, seal_mac_field};
172
173    fn key() -> DataKey {
174        DataKey::from_bytes(&[5u8; 32]).expect("32")
175    }
176
177    fn wrapped(contents: &[&str], ts: &str) -> (Unverified<Vec<String>>, DataKey) {
178        let k = key();
179        let mut acc = MacAccumulator::new(false);
180        for c in contents {
181            acc.feed(&Plaintext::string(*c));
182        }
183        let fed = acc.leaves_fed();
184        let mac = acc.finish();
185        let field = seal_mac_field(&k, &mac, ts, None).expect("seal");
186        let tree: Vec<String> = contents.iter().map(|s| (*s).to_string()).collect();
187        (Unverified::new(tree, mac, field, ts, fed), k)
188    }
189
190    #[test]
191    fn a_matching_mac_releases_the_value() {
192        let (u, k) = wrapped(&["a", "b"], "2026-08-18T00:00:00Z");
193        assert_eq!(u.verify(&k).expect("verify"), vec!["a", "b"]);
194    }
195
196    #[test]
197    fn a_wrong_key_does_not_release_the_value() {
198        let (u, _) = wrapped(&["a"], "2026-08-18T00:00:00Z");
199        let other = DataKey::from_bytes(&[6u8; 32]).expect("32");
200        assert_eq!(u.verify(&other), Err(WireError::MacUndecryptable));
201    }
202
203    /// The anti-vacuity refusal. Without it, a walker that found no leaves would
204    /// compute the empty digest, match another empty digest, and report success.
205    #[test]
206    fn a_zero_leaf_verification_is_refused_as_vacuous() {
207        let (u, k) = wrapped(&[], "2026-08-18T00:00:00Z");
208        assert_eq!(u.leaves_fed(), 0);
209        assert_eq!(u.verify(&k), Err(WireError::MacMismatch));
210    }
211
212    #[test]
213    fn an_explicitly_empty_document_can_still_be_accepted() {
214        let (u, k) = wrapped(&[], "2026-08-18T00:00:00Z");
215        assert!(u.verify_allowing_empty(&k).is_ok());
216    }
217
218    #[test]
219    fn the_ignore_mac_escape_works_and_is_named() {
220        let (u, _) = wrapped(&["a"], "2026-08-18T00:00:00Z");
221        assert_eq!(u.into_inner_ignoring_mac(), vec!["a"]);
222    }
223
224    #[test]
225    fn map_preserves_the_marker_and_the_denominator() {
226        let (u, k) = wrapped(&["a", "b"], "2026-08-18T00:00:00Z");
227        let mapped = u.map(|v| v.len());
228        assert_eq!(mapped.leaves_fed(), 2);
229        assert_eq!(mapped.verify(&k).expect("verify"), 2);
230    }
231
232    #[test]
233    fn debug_never_prints_the_wrapped_value() {
234        let (u, _) = wrapped(&["hunter2"], "2026-08-18T00:00:00Z");
235        let shown = format!("{u:?}");
236        assert!(
237            !shown.contains("hunter2"),
238            "Unverified Debug leaked plaintext: {shown}"
239        );
240        assert!(shown.contains("leaves_fed: 1"));
241    }
242}