Skip to main content

pg_core/client/rust/
stream.rs

1//! Streaming mode.
2
3use alloc::string::ToString;
4
5use crate::artifacts::{PublicKey, SigningKeyExt, UserSecretKey, VerifyingKey};
6use crate::client::*;
7use crate::error::Error;
8use crate::identity::{EncryptionPolicy, Policy};
9use ibe::kem::cgw_kv::CGWKV;
10use ibs::gg::{Identity, Signature, Signer, Verifier, SIG_BYTES};
11
12use aead::KeyInit;
13use aead_stream::{DecryptorBE32, EncryptorBE32};
14use aes_gcm::Aes128Gcm;
15use alloc::vec::Vec;
16use futures::io::{AsyncRead, AsyncWrite};
17use futures::io::{AsyncReadExt, AsyncWriteExt};
18use futures::TryFutureExt;
19use rand::{CryptoRng, RngCore};
20
21/// Configures an [`Sealer`] to process a payload stream.
22#[derive(Debug)]
23pub struct SealerStreamConfig {
24    /// Segment size.
25    segment_size: u32,
26    /// AEAD key.
27    key: [u8; KEY_SIZE],
28    /// AEAD nonce.
29    nonce: [u8; STREAM_NONCE_SIZE],
30}
31
32/// Configures an [`Unsealer`] to process a payload stream.
33#[derive(Debug)]
34pub struct UnsealerStreamConfig {
35    segment_size: u32,
36}
37
38impl SealerConfig for SealerStreamConfig {}
39impl UnsealerConfig for UnsealerStreamConfig {}
40impl crate::client::sealed::SealerConfig for SealerStreamConfig {}
41impl crate::client::sealed::UnsealerConfig for UnsealerStreamConfig {}
42
43impl<'r, Rng: RngCore + CryptoRng> Sealer<'r, Rng, SealerStreamConfig> {
44    /// Construct a new [`Sealer`] that can process streaming payloads.
45    pub fn new(
46        pk: &PublicKey<CGWKV>,
47        policies: &EncryptionPolicy,
48        pub_sign_key: &SigningKeyExt,
49        rng: &'r mut Rng,
50    ) -> Result<Self, Error> {
51        let (header, ss) = Header::new(pk, policies, rng)?;
52
53        let (segment_size, _) = stream_mode_checked(&header)?;
54        let Algorithm::Aes128Gcm(iv) = header.algo;
55
56        let mut key = [0u8; KEY_SIZE];
57        let mut nonce = [0u8; STREAM_NONCE_SIZE];
58
59        key.copy_from_slice(&ss.0[..KEY_SIZE]);
60        nonce.copy_from_slice(&iv.0[..STREAM_NONCE_SIZE]);
61
62        Ok(Sealer {
63            rng,
64            header,
65            pub_sign_key: crate::client::canonical_signing_key(pub_sign_key),
66            priv_sign_key: None,
67            config: SealerStreamConfig {
68                segment_size,
69                key,
70                nonce,
71            },
72        })
73    }
74
75    /// Optional: Add a size hint.
76    ///
77    /// This can help the receiver save some reallocations.
78    pub fn with_size_hint(mut self, size_hint: (u64, Option<u64>)) -> Self {
79        self.header.mode = Mode::Streaming {
80            segment_size: self.config.segment_size,
81            size_hint,
82        };
83
84        self
85    }
86
87    /// Seals payload data from an [`AsyncRead`] into an [`AsyncWrite`].
88    pub async fn seal<R, W>(self, mut r: R, mut w: W) -> Result<(), Error>
89    where
90        R: AsyncRead + Unpin,
91        W: AsyncWrite + Unpin,
92    {
93        w.write_all(&PRELUDE).await?;
94        w.write_all(&VERSION_2.to_be_bytes()).await?;
95
96        let header_vec = crate::bincode_compat::serialize(&self.header)?;
97        w.write_all(&u32::try_from(header_vec.len())?.to_be_bytes())
98            .await?;
99        w.write_all(&header_vec).await?;
100
101        let mut signer = Signer::default().chain(&header_vec);
102        let header_sig = signer.clone().sign(&self.pub_sign_key.key.0, self.rng);
103        let header_sig_ext = SignatureExt {
104            sig: header_sig,
105            pol: self.pub_sign_key.policy.clone(),
106        };
107        let header_sig_bytes = crate::bincode_compat::serialize(&header_sig_ext)?;
108
109        w.write_all(&u32::try_from(header_sig_bytes.len())?.to_be_bytes())
110            .await?;
111        w.write_all(&header_sig_bytes).await?;
112
113        let aead = Aes128Gcm::new_from_slice(&self.config.key)?;
114        let mut enc = EncryptorBE32::from_aead(aead, &self.config.nonce.into());
115
116        // Check for a private signing key, otherwise fall back to the public one.
117        let pub_pol_bytes = crate::bincode_compat::serialize(&self.pub_sign_key.policy)?;
118        let signing_key = self.priv_sign_key.unwrap_or(self.pub_sign_key);
119
120        let pol_bytes = crate::bincode_compat::serialize(&signing_key.policy)?;
121        let pol_len = pol_bytes.len() + pub_pol_bytes.len();
122
123        if pol_len + POL_SIZE_SIZE > self.config.segment_size as usize {
124            return Err(Error::ConstraintViolation);
125        }
126
127        let mut buf = vec![0; self.config.segment_size as usize + TAG_SIZE];
128
129        buf[..POL_SIZE_SIZE].copy_from_slice(&u32::try_from(pol_len)?.to_be_bytes());
130        buf[POL_SIZE_SIZE..POL_SIZE_SIZE + pol_bytes.len()].copy_from_slice(&pol_bytes);
131        buf[POL_SIZE_SIZE + pol_bytes.len()..POL_SIZE_SIZE + pol_len]
132            .copy_from_slice(&pub_pol_bytes);
133
134        let mut buf_tail = POL_SIZE_SIZE + pol_len;
135        let mut start = buf_tail;
136
137        // First segment: DEM.K (pol_len || pol || pub_pol || m_0 || sig_0 )
138        // Other segments: DEM.K (m_i || sig_0)
139        //
140        // `pub_pol` is the sender's public signing policy, the same value that
141        // goes into the header signature outside the AEAD. It sits inside the
142        // length-delimited policy region because that is the one place a reader
143        // skips wholesale: `pol_len` covers both policies and the reader drains
144        // the region before splitting the segment at `len - SIG_BYTES`. Anything
145        // appended after `sig_0` would be read as message or signature bytes.
146        // The message signature covers the message only — the region is excluded
147        // from it here and stays excluded.
148
149        let mut counter: u32 = 0;
150
151        loop {
152            let read = r
153                .read(&mut buf[buf_tail..self.config.segment_size as usize])
154                .await?;
155            buf_tail += read;
156
157            if buf_tail == self.config.segment_size as usize {
158                buf.truncate(buf_tail);
159
160                signer.update(&buf[start..]);
161                let sig = signer
162                    .clone()
163                    .chain(counter.to_be_bytes())
164                    .chain([0x00])
165                    .sign(&signing_key.key.0, self.rng);
166                crate::bincode_compat::serialize_into_vec(&mut buf, &sig)?;
167
168                enc.encrypt_next_in_place(b"", &mut buf)?;
169
170                w.write_all(&buf).await?;
171
172                buf_tail = 0;
173                start = 0;
174                counter = counter.checked_add(1).unwrap(); // cannot fail, otherwise
175                                                           // encrypt_next_in_place would have
176                                                           // failed too.                                                // encrypt_next_in_place not failing
177            } else if read == 0 {
178                buf.truncate(buf_tail);
179
180                signer.update(&buf[start..]);
181                let sig_final = signer
182                    .chain(counter.to_be_bytes())
183                    .chain([0x01])
184                    .sign(&signing_key.key.0, self.rng);
185                crate::bincode_compat::serialize_into_vec(&mut buf, &sig_final)?;
186
187                enc.encrypt_last_in_place(b"", &mut buf)?;
188
189                w.write_all(&buf).await?;
190                break;
191            }
192        }
193
194        w.flush().await?;
195        w.close().await?;
196
197        Ok(())
198    }
199}
200
201impl<R> Unsealer<R, UnsealerStreamConfig>
202where
203    R: AsyncRead + Unpin,
204{
205    /// Create a new [`Unsealer`] that starts reading from an [`AsyncRead`].
206    ///
207    /// Errors if the bytestream is not a legitimate PostGuard bytestream.
208    pub async fn new(mut r: R, pk: &VerifyingKey) -> Result<Self, Error> {
209        let mut preamble = [0u8; PREAMBLE_SIZE];
210        r.read_exact(&mut preamble)
211            .map_err(|_e| Error::NotPostGuard)
212            .await?;
213
214        let (version, header_len) = preamble_checked(&preamble)?;
215        let mut header_raw = Vec::with_capacity(header_len);
216
217        // Limit reader to not read past header
218        let mut r = r.take(header_len as u64);
219
220        r.read_to_end(&mut header_raw)
221            .map_err(|_e| Error::ConstraintViolation)
222            .await?;
223
224        let mut r = r.into_inner();
225
226        let mut header_sig_len_bytes = [0u8; SIG_SIZE_SIZE];
227        r.read_exact(&mut header_sig_len_bytes)
228            .map_err(|_e| Error::FormatViolation("no header signature length".to_string()))
229            .await?;
230        let header_sig_len = u32::from_be_bytes(header_sig_len_bytes) as usize;
231
232        // Bound the length prefix to a sane maximum before it sizes an
233        // allocation, mirroring the MAX_HEADER_SIZE check in preamble_checked.
234        if header_sig_len > MAX_SIG_SIZE {
235            return Err(Error::ConstraintViolation);
236        }
237
238        let mut header_sig_raw = Vec::with_capacity(header_sig_len);
239        let mut r = r.take(header_sig_len as u64);
240
241        r.read_to_end(&mut header_sig_raw).await?;
242
243        let h_sig_ext: SignatureExt = crate::bincode_compat::deserialize(&header_sig_raw)?;
244
245        let verifier = Verifier::default().chain(&header_raw);
246        let pub_id = h_sig_ext.pol.derive_ibs()?;
247
248        if !verifier.clone().verify(&pk.0, &h_sig_ext.sig, &pub_id) {
249            return Err(Error::IncorrectSignature);
250        }
251
252        let header: Header = crate::bincode_compat::deserialize(&header_raw)?;
253        let (segment_size, _) = stream_mode_checked(&header)?;
254
255        Ok(Unsealer {
256            version,
257            header,
258            pub_id: h_sig_ext.pol,
259            config: UnsealerStreamConfig { segment_size },
260            r: r.into_inner(), // This (new) reader is locked to the payload.
261            verifier,
262            vk: pk.clone(),
263        })
264    }
265
266    /// Unseal the remaining data (which is now only payload) into an [`AsyncWrite`].
267    pub async fn unseal<W: AsyncWrite + Unpin>(
268        mut self,
269        ident: &str,
270        usk: &UserSecretKey<CGWKV>,
271        mut w: W,
272    ) -> Result<VerificationResult, Error> {
273        let rec_info = self
274            .header
275            .recipients
276            .get(ident)
277            .ok_or_else(|| Error::UnknownIdentifier(ident.to_string()))?;
278
279        let ss = rec_info.decaps(usk)?;
280        let key = &ss.0[..KEY_SIZE];
281        let aead = Aes128Gcm::new_from_slice(key)?;
282
283        let Algorithm::Aes128Gcm(iv) = self.header.algo;
284        // aead-stream takes the nonce as a fixed-size array; IV_SIZE (12) covers
285        // STREAM_NONCE_SIZE (7), so the prefix is always there.
286        let nonce =
287            iv.0.first_chunk::<STREAM_NONCE_SIZE>()
288                .expect("IV_SIZE >= STREAM_NONCE_SIZE");
289
290        let mut dec = DecryptorBE32::from_aead(aead, nonce.into());
291
292        let bufsize: usize = self.config.segment_size as usize + SIG_BYTES + TAG_SIZE;
293        let mut buf = vec![0u8; bufsize];
294        let mut buf_tail = 0;
295        let mut counter: u32 = 0;
296        let mut pol_id: Option<(Policy, Identity)> = None;
297
298        fn extract_policy(
299            buf: &mut Vec<u8>,
300            pub_id: &Policy,
301        ) -> Result<Option<(Policy, Identity)>, Error> {
302            if buf.len() < POL_SIZE_SIZE {
303                return Err(Error::FormatViolation(alloc::string::String::from(
304                    "policy length",
305                )));
306            }
307            let pol_len = u32::from_be_bytes(buf[..POL_SIZE_SIZE].try_into()?) as usize;
308            let pol_end = POL_SIZE_SIZE.checked_add(pol_len).ok_or_else(|| {
309                Error::FormatViolation(alloc::string::String::from("policy length overflow"))
310            })?;
311            if buf.len() < pol_end {
312                return Err(Error::FormatViolation(alloc::string::String::from(
313                    "policy truncated",
314                )));
315            }
316            let pol_bytes = &buf[POL_SIZE_SIZE..pol_end];
317            let (pol, read): (Policy, usize) =
318                crate::bincode_compat::deserialize_with_len(pol_bytes)?;
319
320            // The rest of the region, if the sealer wrote one, is a copy of the
321            // sender's public signing policy. The header signature outside the
322            // AEAD claims a policy too; if they disagree, that block was
323            // swapped. An exhausted region means the sealer predates the copy.
324            // Both readings are authenticated against the DEM key and reach no
325            // further, so the exhausted case is not the safe half of the two —
326            // see the note on `MessageAndSignature` in `client/rust/mod.rs`.
327            if read < pol_bytes.len() {
328                let sealed_pub_pol: Policy =
329                    crate::bincode_compat::deserialize(&pol_bytes[read..])?;
330
331                if &sealed_pub_pol != pub_id {
332                    return Err(Error::IncorrectSignature);
333                }
334            }
335
336            let id = pol.derive_ibs()?;
337
338            buf.drain(..pol_end);
339
340            Ok(Some((pol, id)))
341        }
342
343        fn verify_segment<'a>(
344            seg: &'a [u8],
345            verifier: &mut Verifier,
346            vk: &VerifyingKey,
347            id: &Identity,
348            counter: u32,
349            is_last: bool,
350        ) -> Result<&'a [u8], Error> {
351            if seg.len() < SIG_BYTES {
352                return Err(Error::FormatViolation(alloc::string::String::from(
353                    "segment too short for signature",
354                )));
355            }
356
357            let (m, sig_bytes) = seg.split_at(seg.len() - SIG_BYTES);
358            let sig: Signature = crate::bincode_compat::deserialize(sig_bytes)?;
359            verifier.update(m);
360
361            if !verifier
362                .clone()
363                .chain(counter.to_be_bytes())
364                .chain([is_last as u8])
365                .verify(&vk.0, &sig, id)
366            {
367                return Err(Error::IncorrectSignature);
368            }
369
370            Ok(m)
371        }
372
373        loop {
374            let read = self.r.read(&mut buf[buf_tail..bufsize]).await?;
375            buf_tail += read;
376
377            if buf_tail == bufsize {
378                dec.decrypt_next_in_place(b"", &mut buf)?;
379
380                if counter == 0 {
381                    pol_id = extract_policy(&mut buf, &self.pub_id)?;
382                }
383
384                let m = verify_segment(
385                    &buf,
386                    &mut self.verifier,
387                    &self.vk,
388                    &pol_id.as_ref().unwrap().1,
389                    counter,
390                    false,
391                )?;
392
393                w.write_all(m).await?;
394
395                buf_tail = 0;
396                buf.resize(bufsize, 0);
397                counter += 1;
398            } else if read == 0 {
399                buf.truncate(buf_tail);
400                dec.decrypt_last_in_place(b"", &mut buf)?;
401
402                if counter == 0 {
403                    pol_id = extract_policy(&mut buf, &self.pub_id)?;
404                }
405
406                let m = verify_segment(
407                    &buf,
408                    &mut self.verifier,
409                    &self.vk,
410                    &pol_id.as_ref().unwrap().1,
411                    counter,
412                    true,
413                )?;
414
415                w.write_all(m).await?;
416
417                break;
418            }
419        }
420
421        w.close().await?;
422
423        let private_id = pol_id.unwrap().0;
424        let private = if self.pub_id == private_id {
425            None
426        } else {
427            Some(private_id)
428        };
429
430        Ok(VerificationResult {
431            public: self.pub_id,
432            private,
433        })
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::{Sealer, SealerStreamConfig, Unsealer, UnsealerStreamConfig};
440    use crate::client::VerificationResult;
441    use crate::error::Error;
442    use crate::test::TestSetup;
443    use crate::{PREAMBLE_SIZE, SYMMETRIC_CRYPTO_DEFAULT_CHUNK, TAG_SIZE};
444    use aead::KeyInit;
445    use aead_stream::{DecryptorBE32, EncryptorBE32};
446    use aes_gcm::Aes128Gcm;
447    use alloc::string::String;
448    use alloc::vec::Vec;
449    use futures::{executor::block_on, io::AllowStdIo};
450    use ibe::kem::cgw_kv::CGWKV;
451    use rand::{thread_rng, Rng, RngCore};
452    use std::io::Cursor;
453    use tokio::io::AsyncReadExt;
454
455    const LENGTHS: &[u32] = &[
456        1,
457        512,
458        SYMMETRIC_CRYPTO_DEFAULT_CHUNK - 3,
459        SYMMETRIC_CRYPTO_DEFAULT_CHUNK,
460        SYMMETRIC_CRYPTO_DEFAULT_CHUNK + 3,
461        3 * SYMMETRIC_CRYPTO_DEFAULT_CHUNK,
462        3 * SYMMETRIC_CRYPTO_DEFAULT_CHUNK + 16,
463        3 * SYMMETRIC_CRYPTO_DEFAULT_CHUNK - 17,
464    ];
465
466    fn seal_helper(setup: &TestSetup, plain: &[u8]) -> Vec<u8> {
467        let mut rng = rand::thread_rng();
468
469        let mut input = AllowStdIo::new(Cursor::new(plain));
470        let mut output = AllowStdIo::new(Vec::new());
471
472        let signing_key = &setup.signing_keys[0];
473
474        block_on(async {
475            Sealer::<_, SealerStreamConfig>::new(
476                &setup.ibe_pk,
477                &setup.policy,
478                signing_key,
479                &mut rng,
480            )
481            .unwrap()
482            .seal(&mut input, &mut output)
483            .await
484            .unwrap();
485        });
486
487        output.into_inner()
488    }
489
490    fn unseal_helper(setup: &TestSetup, ct: &[u8]) -> (Vec<u8>, VerificationResult) {
491        let mut input = AllowStdIo::new(Cursor::new(ct));
492        let mut output = AllowStdIo::new(Vec::new());
493
494        // sometimes decrypt as Bob, sometimes decrypt as Charlie
495        let (id, usk_id) = if thread_rng().gen::<bool>() {
496            ("Bob", setup.usks[2].clone())
497        } else {
498            ("Charlie", setup.usks[3].clone())
499        };
500
501        let vr = block_on(async {
502            let unsealer = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk)
503                .await
504                .unwrap();
505
506            // Normally, a user would need to retrieve a usk here via the PKG,
507            // but in this case we own the master key pair.
508            unsealer.unseal(id, &usk_id, &mut output).await.unwrap()
509        });
510
511        (output.into_inner(), vr)
512    }
513
514    fn seal_and_unseal(setup: &TestSetup, plain: Vec<u8>) {
515        let ct = seal_helper(setup, &plain);
516        let (plain2, vr) = unseal_helper(setup, &ct);
517
518        assert_eq!(&plain, &plain2);
519        assert_eq!(&vr.public, &setup.signing_keys[0].policy);
520        assert_eq!(vr.private, None);
521    }
522
523    fn rand_vec(length: usize) -> Vec<u8> {
524        let mut vec = vec![0u8; length];
525        rand::thread_rng().fill_bytes(&mut vec);
526        vec
527    }
528
529    #[test]
530    fn test_reflection_seal_unsealer() {
531        let mut rng = rand::thread_rng();
532        let setup = TestSetup::new(&mut rng);
533
534        for l in LENGTHS {
535            seal_and_unseal(&setup, rand_vec(*l as usize));
536        }
537    }
538
539    #[test]
540    #[should_panic]
541    fn test_corrupt_header() {
542        let mut rng = rand::thread_rng();
543        let setup = TestSetup::new(&mut rng);
544
545        let plain = rand_vec(100);
546        let mut ct = seal_helper(&setup, &plain);
547
548        // Flip a byte that is guaranteed to be in the header.
549        ct[PREAMBLE_SIZE + 2] = !ct[PREAMBLE_SIZE + 2];
550
551        // This should panic, because of the header signature.
552        let _plain2 = unseal_helper(&setup, &ct);
553    }
554
555    #[test]
556    #[should_panic]
557    fn test_corrupt_payload() {
558        let mut rng = rand::thread_rng();
559        let setup = TestSetup::new(&mut rng);
560
561        let plain = rand_vec(100);
562        let mut ct = seal_helper(&setup, &plain);
563
564        // Flip a byte that is guaranteed to be in the encrypted payload.
565        let ct_len = ct.len();
566        ct[ct_len - TAG_SIZE - 5] = !ct[ct_len - TAG_SIZE - 5];
567
568        // This should panic, because of the AEAD.
569        let _plain2 = unseal_helper(&setup, &ct);
570    }
571
572    #[test]
573    #[should_panic]
574    fn test_corrupt_tag() {
575        let mut rng = rand::thread_rng();
576        let setup = TestSetup::new(&mut rng);
577
578        let plain = rand_vec(100);
579        let mut ct = seal_helper(&setup, &plain);
580
581        let len = ct.len();
582        ct[len - 5] = !ct[len - 5];
583
584        // This should panic as well.
585        let _plain2 = unseal_helper(&setup, &ct);
586    }
587
588    #[tokio::test]
589    async fn test_tokio_file() -> Result<(), Error> {
590        use futures::AsyncWriteExt;
591        use tokio::fs::{File, OpenOptions};
592        use tokio_util::compat::TokioAsyncReadCompatExt;
593
594        let mut rng = rand::thread_rng();
595        let setup = TestSetup::new(&mut rng);
596
597        let signing_key = &setup.signing_keys[0];
598
599        let in_name = std::env::temp_dir().join("foo.txt");
600        let out_name = std::env::temp_dir().join("foo.enc");
601        let orig_name = std::env::temp_dir().join("foo2.txt");
602
603        let mut file = OpenOptions::new()
604            .create(true)
605            .write(true)
606            .truncate(true)
607            .open(&in_name)
608            .await?
609            .compat();
610
611        file.write_all(b"SECRET DATA").await?;
612        file.close().await?;
613
614        let mut in_file = File::open(&in_name).await?.compat();
615        let mut out_file = OpenOptions::new()
616            .create(true)
617            .write(true)
618            .truncate(true)
619            .open(&out_name)
620            .await?
621            .compat();
622
623        Sealer::<_, SealerStreamConfig>::new(&setup.ibe_pk, &setup.policy, signing_key, &mut rng)?
624            .seal(&mut in_file, &mut out_file)
625            .await?;
626
627        in_file.close().await?;
628        out_file.close().await?;
629
630        let mut out_file = File::open(&out_name).await?.compat();
631        let mut orig_file = OpenOptions::new()
632            .create(true)
633            .write(true)
634            .truncate(true)
635            .open(&orig_name)
636            .await?
637            .compat();
638
639        let id = "Bob";
640        let usk = &setup.usks[2];
641
642        Unsealer::<_, UnsealerStreamConfig>::new(&mut out_file, &setup.ibs_pk)
643            .await?
644            .unseal(id, usk, &mut orig_file)
645            .await?;
646
647        out_file.close().await?;
648        orig_file.close().await?;
649
650        let mut buf = String::new();
651        File::open(&orig_name)
652            .await?
653            .read_to_string(&mut buf)
654            .await?;
655
656        assert_eq!(buf.as_bytes(), b"SECRET DATA");
657
658        Ok(())
659    }
660
661    #[tokio::test]
662    async fn test_cursor() -> Result<(), Error> {
663        use futures::io::Cursor;
664
665        let mut rng = rand::thread_rng();
666        let setup = TestSetup::new(&mut rng);
667
668        let signing_key = &setup.signing_keys[0];
669
670        let mut input = Cursor::new(b"SECRET DATA");
671        let mut encrypted = Vec::new();
672
673        Sealer::<_, SealerStreamConfig>::new(&setup.ibe_pk, &setup.policy, signing_key, &mut rng)?
674            .seal(&mut input, &mut encrypted)
675            .await?;
676
677        let mut original = Vec::new();
678        let id = "Bob";
679        let usk = &setup.usks[2];
680        Unsealer::<_, UnsealerStreamConfig>::new(&mut Cursor::new(encrypted), &setup.ibs_pk)
681            .await?
682            .unseal(id, usk, &mut original)
683            .await?;
684
685        assert_eq!(input.into_inner().to_vec(), original);
686        Ok(())
687    }
688
689    #[tokio::test]
690    async fn test_stream_unseal_rejects_empty_input() {
691        use futures::io::Cursor;
692
693        let mut rng = rand::thread_rng();
694        let setup = TestSetup::new(&mut rng);
695
696        // Empty reader must not panic — the preamble read should fail cleanly.
697        let mut input = Cursor::new(Vec::<u8>::new());
698        let res = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk).await;
699        assert!(matches!(res, Err(Error::NotPostGuard)));
700    }
701
702    #[tokio::test]
703    async fn test_stream_unseal_rejects_truncated_preamble() {
704        use futures::io::Cursor;
705
706        let mut rng = rand::thread_rng();
707        let setup = TestSetup::new(&mut rng);
708
709        // A few bytes — enough to look like the start of a preamble but
710        // not enough to finish reading one.
711        let mut input = Cursor::new(vec![0u8; PREAMBLE_SIZE - 1]);
712        let res = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk).await;
713        assert!(matches!(res, Err(Error::NotPostGuard)));
714    }
715
716    #[tokio::test]
717    async fn test_stream_unseal_rejects_garbage_input() {
718        use futures::io::Cursor;
719
720        let mut rng = rand::thread_rng();
721        let setup = TestSetup::new(&mut rng);
722
723        // 4 KiB of zeros — the prelude check rejects this before any unchecked
724        // length-prefixed read can panic.
725        let mut input = Cursor::new(vec![0u8; 4096]);
726        let res = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk).await;
727        assert!(res.is_err());
728    }
729
730    #[tokio::test]
731    async fn test_stream_unseal_rejects_flipped_prelude() {
732        use futures::io::Cursor;
733
734        let mut rng = rand::thread_rng();
735        let setup = TestSetup::new(&mut rng);
736        let mut ct = seal_helper(&setup, b"SECRET DATA");
737
738        // Flip a byte in the prelude — must be rejected as NotPostGuard,
739        // never panic.
740        ct[0] = ct[0].wrapping_add(1);
741
742        let mut input = Cursor::new(ct);
743        let res = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk).await;
744        assert!(matches!(res, Err(Error::NotPostGuard)));
745    }
746
747    /// Splits a sealed streaming container into the header bytes, the header
748    /// signature block and the payload.
749    fn split_container(ct: &[u8]) -> (&[u8], &[u8], &[u8]) {
750        use crate::util::preamble_checked;
751        use crate::SIG_SIZE_SIZE;
752
753        let (_, header_len) =
754            preamble_checked(&ct[..PREAMBLE_SIZE]).expect("preamble should parse");
755        let sig_len_at = PREAMBLE_SIZE + header_len;
756        let sig_len = u32::from_be_bytes(
757            ct[sig_len_at..sig_len_at + SIG_SIZE_SIZE]
758                .try_into()
759                .unwrap(),
760        ) as usize;
761        let sig_at = sig_len_at + SIG_SIZE_SIZE;
762
763        (
764            &ct[PREAMBLE_SIZE..sig_len_at],
765            &ct[sig_at..sig_at + sig_len],
766            &ct[sig_at + sig_len..],
767        )
768    }
769
770    /// The attack: keep the preamble, header and payload byte for byte, and
771    /// replace only the header signature block with one made over the same
772    /// header bytes by another signing key, carrying that key's policy.
773    fn swap_header_signature(
774        ct: &[u8],
775        attacker: &crate::artifacts::SigningKeyExt,
776        rng: &mut (impl rand::RngCore + rand::CryptoRng),
777    ) -> Vec<u8> {
778        use crate::client::header::SignatureExt;
779        use ibs::gg::Signer;
780
781        let (header_bytes, _, payload) = split_container(ct);
782
783        let h_sig_ext = SignatureExt {
784            sig: Signer::default()
785                .chain(header_bytes)
786                .sign(&attacker.key.0, rng),
787            pol: attacker.policy.clone(),
788        };
789        let h_sig_ext_bytes = crate::bincode_compat::serialize(&h_sig_ext).unwrap();
790
791        let mut out = ct[..PREAMBLE_SIZE + header_bytes.len()].to_vec();
792        out.extend_from_slice(&(h_sig_ext_bytes.len() as u32).to_be_bytes());
793        out.extend_from_slice(&h_sig_ext_bytes);
794        out.extend_from_slice(payload);
795
796        out
797    }
798
799    /// A container sealed before the policy region carried the public signing
800    /// policy: same bytes, but with the region narrowed back to the signing
801    /// policy alone and the single segment re-encrypted.
802    fn strip_pub_pol(
803        ct: &[u8],
804        ident: &str,
805        usk: &crate::artifacts::UserSecretKey<CGWKV>,
806    ) -> Vec<u8> {
807        use crate::client::{Algorithm, Header};
808        use crate::identity::Policy;
809        use crate::{KEY_SIZE, POL_SIZE_SIZE, STREAM_NONCE_SIZE};
810
811        let (header_bytes, _, payload) = split_container(ct);
812        let header: Header = crate::bincode_compat::deserialize(header_bytes).unwrap();
813        let ss = header.recipients.get(ident).unwrap().decaps(usk).unwrap();
814
815        let Algorithm::Aes128Gcm(iv) = header.algo;
816        let aead = Aes128Gcm::new_from_slice(&ss.0[..KEY_SIZE]).unwrap();
817        let nonce = iv.0.first_chunk::<STREAM_NONCE_SIZE>().unwrap();
818
819        // The helper seals a message that fits in one segment, so the payload
820        // is a single final segment.
821        let mut plain = payload.to_vec();
822        DecryptorBE32::from_aead(aead.clone(), nonce.into())
823            .decrypt_last_in_place(b"", &mut plain)
824            .unwrap();
825
826        let pol_len = u32::from_be_bytes(plain[..POL_SIZE_SIZE].try_into().unwrap()) as usize;
827        let region = &plain[POL_SIZE_SIZE..POL_SIZE_SIZE + pol_len];
828        let (_, read): (Policy, usize) =
829            crate::bincode_compat::deserialize_with_len(region).unwrap();
830        assert!(
831            read < pol_len,
832            "the sealer wrote no public policy into the region — nothing to strip"
833        );
834
835        let mut legacy = (read as u32).to_be_bytes().to_vec();
836        legacy.extend_from_slice(&region[..read]);
837        legacy.extend_from_slice(&plain[POL_SIZE_SIZE + pol_len..]);
838
839        EncryptorBE32::from_aead(aead, nonce.into())
840            .encrypt_last_in_place(b"", &mut legacy)
841            .unwrap();
842
843        let mut out = ct[..ct.len() - payload.len()].to_vec();
844        out.extend_from_slice(&legacy);
845
846        out
847    }
848
849    fn try_unseal(setup: &TestSetup, ct: &[u8]) -> Result<(Vec<u8>, VerificationResult), Error> {
850        let mut input = AllowStdIo::new(Cursor::new(ct));
851        let mut output = AllowStdIo::new(Vec::new());
852
853        let vr = block_on(async {
854            Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk)
855                .await?
856                .unseal("Bob", &setup.usks[2], &mut output)
857                .await
858        })?;
859
860        Ok((output.into_inner(), vr))
861    }
862
863    /// Replacing the header signature with one made by another signing key over
864    /// the same header bytes must be rejected: the copy of the public signing
865    /// policy inside the AEAD-protected policy region no longer matches the one
866    /// the block claims.
867    #[test]
868    fn test_stream_unseal_rejects_swapped_header_signature() {
869        let mut rng = rand::thread_rng();
870        let setup = TestSetup::new(&mut rng);
871        let ct = seal_helper(&setup, b"SECRET DATA");
872
873        // Charlie's name-only key — a key the PKG hands to whoever authenticates
874        // as Charlie, which is exactly what makes the swap cheap.
875        let swapped = swap_header_signature(&ct, &setup.signing_keys[4], &mut rng);
876
877        block_on(async {
878            let mut input = AllowStdIo::new(Cursor::new(&swapped));
879            let unsealer = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk)
880                .await
881                .expect("the swapped header signature still verifies — that is the attack");
882            assert_eq!(
883                unsealer.pub_id, setup.policies[4],
884                "the container now claims the attacker as public sender"
885            );
886        });
887
888        match try_unseal(&setup, &swapped) {
889            Err(Error::IncorrectSignature) => {}
890            other => panic!(
891                "expected IncorrectSignature, got {:?}",
892                other.map(|(m, vr)| (m.len(), vr))
893            ),
894        }
895    }
896
897    /// A container sealed by a pg-core that predates the copy has a policy
898    /// region holding the signing policy and nothing else. It must still
899    /// unseal, and report the same sender it always did.
900    #[test]
901    fn test_stream_unseal_accepts_container_without_public_policy() {
902        let mut rng = rand::thread_rng();
903        let setup = TestSetup::new(&mut rng);
904        let ct = seal_helper(&setup, b"SECRET DATA");
905        let legacy = strip_pub_pol(&ct, "Bob", &setup.usks[2]);
906
907        let (plain, vr) = try_unseal(&setup, &legacy)
908            .expect("a container without the public policy must still open");
909
910        assert_eq!(&plain, b"SECRET DATA");
911        assert_eq!(&vr.public, &setup.signing_keys[0].policy);
912        assert_eq!(vr.private, None);
913    }
914
915    #[tokio::test]
916    async fn test_stream_unseal_rejects_oversized_sig_len() {
917        use crate::util::preamble_checked;
918        use crate::{MAX_SIG_SIZE, SIG_SIZE_SIZE};
919        use futures::io::Cursor;
920
921        let mut rng = rand::thread_rng();
922        let setup = TestSetup::new(&mut rng);
923        let mut ct = seal_helper(&setup, b"SECRET DATA");
924
925        // The header-signature length prefix sits right after the header. Overwrite
926        // it with a value larger than MAX_SIG_SIZE and assert the unsealer rejects it
927        // with a ConstraintViolation before allocating a buffer of that size.
928        let (_, header_len) =
929            preamble_checked(&ct[..PREAMBLE_SIZE]).expect("preamble should parse");
930        let sig_len_off = PREAMBLE_SIZE + header_len;
931        assert!(sig_len_off + SIG_SIZE_SIZE <= ct.len());
932        assert!((MAX_SIG_SIZE as u64) < u32::MAX as u64);
933        ct[sig_len_off..sig_len_off + SIG_SIZE_SIZE].copy_from_slice(&u32::MAX.to_be_bytes());
934
935        let mut input = Cursor::new(ct);
936        let res = Unsealer::<_, UnsealerStreamConfig>::new(&mut input, &setup.ibs_pk).await;
937        assert!(
938            matches!(res, Err(Error::ConstraintViolation)),
939            "expected ConstraintViolation, got {res:?}"
940        );
941    }
942}