Skip to main content

ore_rs/
block_ore.rs

1//! [`BlockOre`]: block ORE as a vitaminc order scheme, and the routing of
2//! each space to an engine.
3
4use std::cmp::Ordering;
5use std::num::NonZeroUsize;
6
7use vitaminc_context::Context;
8use vitaminc_hmac::{HmacSha256Prf, WeakKeyError};
9use vitaminc_ore::{OrderKeyInit, OrderPlaintext, OrderQuery, OrderScheme, OrderTarget};
10use vitaminc_prf::{BlockVisitor, Prf, PrfEncoding, PrfKeyInit};
11use vitaminc_protected::Protected;
12use zeroize::{ZeroizeOnDrop, Zeroizing};
13
14use crate::ciphertext::parse_header;
15use crate::scheme::bit2_w6::{OreAes128Bit6, MAX_BYTES};
16use crate::scheme::chained::{Options, OreAes128Bit6Chained, Padding, DEFAULT_MAX_STR_BYTES};
17use crate::{OreError, OreScheme, Query, Term};
18
19/// The PRF domain the ORE key is derived under, once per scheme key.
20pub const ORE_KEY: &str = "vitaminc/ore/block-ore/key/v2";
21
22/// The 16-byte ORE key the scheme is keyed with: the scheme key through
23/// HMAC-SHA256 under [`ORE_KEY`], with no salt. Made once, with the
24/// scheme; each space's salt is bound afterwards by the engines. `None`
25/// only if HMAC refused, which it cannot once keyed: the scheme then
26/// refuses every space ([`OreError::InitFailed`]) rather than panic.
27fn ore_key(prf: &HmacSha256Prf) -> Option<Zeroizing<[u8; 16]>> {
28    let material = prf
29        .prf_bytes_vec(
30            Protected::new(Vec::new()),
31            PrfEncoding::new(ORE_KEY),
32            Context::empty(),
33            BlockVisitor,
34        )
35        .into_result()
36        .ok()
37        .map(Zeroizing::new)?;
38    let mut key = Zeroizing::new([0u8; 16]);
39    key.copy_from_slice(&material[..16]);
40    Some(key)
41}
42
43/// Block ORE as a vitaminc order scheme, the typed front door: every
44/// target, routed to the engine its width wants when a space is opened.
45///
46/// vitaminc decides the encoding of every kind of value and seals it as an
47/// [`OrderPlaintext`] that only it can build, so a scheme here is never
48/// handed bytes that skipped the encoding. A caller opens a space on
49/// [`BlockOre`] with a target and a context, encrypts values there, and
50/// compares terms and queries through the space; it never names an engine.
51///
52/// One scheme, two engines. [`BlockOre`] routes a space to an engine by
53/// its target's width, once, when the space is opened:
54///
55/// - up to ten bytes, the packed-prefix Bit6 engine
56///   ([`OreAes128Bit6`]): the integers to 64 bits, `f64` and dates;
57/// - wider, or of no fixed width, the chained engine
58///   ([`OreAes128Bit6Chained`]): 128-bit integers, uuids, timestamps,
59///   decimals, text and bytes.
60///
61/// Every term carries its engine in its wire header, so a comparison
62/// dispatches on the bytes and refuses a pair from two engines, which no
63/// space produces. The legacy scheme has no adapter: it is for stored data,
64/// and the README says not to put new data on it.
65///
66/// **Keys.** [`OrderKeyInit`] keys the scheme from a 32-byte key, from
67/// which one 16-byte ORE key is derived with HMAC-SHA256 under
68/// [`ORE_KEY`] when the scheme is made. Each space is then keyed from that
69/// key under the salt vitaminc derives, `PAE("vitaminc/ore/v1",
70/// "block-ore", domain, context)`, through the engines' own salt stage, so
71/// two targets or two contexts never share key material.
72///
73/// **Padding.** Text is padded under the scheme's policy
74/// ([`BlockOre::with_text_padding`], [`Padding::default`] unless set), so a
75/// text term reveals a length bucket, and text that ends in NUL is refused
76/// ([`OreError::TrailingNul`]). Bytes are never padded, since NUL padding
77/// would refuse every value that ends in a zero byte, so a bytes term
78/// reveals the exact length. Fixed-width targets have nothing to hide.
79/// Text and bytes are refused past the scheme's ceiling
80/// ([`BlockOre::with_max_bytes`], [`DEFAULT_MAX_STR_BYTES`] unless set),
81/// which counts the marker byte vitaminc puts before them.
82///
83/// A term is the serialised ciphertext, left and right halves; a query is
84/// the left half alone. Both are compared by the scheme, never byte by
85/// byte: a term carries a random nonce, so one value has many terms,
86/// which compare `Equal`.
87///
88/// # Examples
89///
90/// ```
91/// use std::cmp::Ordering;
92/// use ore_rs::BlockOre;
93/// use vitaminc_ore::target::{I32, Text};
94/// use vitaminc_ore::{OrderEncrypt, OrderKeyInit};
95/// use vitaminc_protected::Protected;
96/// # let key_bytes = [7u8; 32];
97///
98/// let scheme = BlockOre::new(Protected::new(key_bytes));
99///
100/// // A space of `i32`s under one context, keyed once for all its terms.
101/// let quantity = scheme.target(I32).context(("orders", "quantity"));
102/// let stored = quantity.encrypt(42i16)?;
103/// let query = quantity.encrypt_query(41i16)?;
104/// assert_eq!(quantity.compare_query(&query, &stored), Some(Ordering::Less));
105/// let bytes: &[u8] = stored.as_ref();
106///
107/// // Text goes to the chained engine; the caller does not choose.
108/// let names = scheme.target(Text).context("names");
109/// let alice = names.encrypt_checked("alice")?;
110/// let bob = names.encrypt_checked("bob")?;
111/// assert_eq!(names.compare(&alice, &bob), Some(Ordering::Less));
112/// # let _ = bytes;
113/// # Ok::<(), Box<dyn std::error::Error>>(())
114/// ```
115pub struct BlockOre {
116    key: Option<Zeroizing<[u8; 16]>>,
117    text_padding: Padding,
118    max_bytes: NonZeroUsize,
119}
120
121impl BlockOre {
122    /// The padding policy of every `Text` space this scheme opens;
123    /// [`Padding::default`] unless set. Stored terms and the queries that
124    /// compare with them must share a policy, so set it once, with the
125    /// key.
126    pub fn with_text_padding(mut self, padding: Padding) -> Self {
127        self.text_padding = padding;
128        self
129    }
130
131    /// The longest text or bytes value, in bytes, every space of this
132    /// scheme encrypts, counting the marker byte vitaminc puts before it;
133    /// [`DEFAULT_MAX_STR_BYTES`] unless set. A longer one is refused
134    /// ([`OreError::TooLong`]). Fixed-width spaces are not bounded by it.
135    ///
136    /// The ceiling must be one the chained engine accepts: no longer than
137    /// the space's padding can pad within the wire format's limit, [`MAX_STR_BYTES`](crate::scheme::chained::MAX_STR_BYTES)
138    /// (49151 bytes). A `Bytes` space is unpadded, so it takes any ceiling
139    /// from 1 to 49151. A `Text` space pads the ceiling under
140    /// [`Self::with_text_padding`]. Under [`Padding::PowerOfTwo`], the
141    /// default, the longest is 32768 (or the floor, if that is higher),
142    /// since a longer value would pad to 65536 bytes. Under
143    /// [`Padding::Fixed`] the lower of the ceiling and the fixed length
144    /// applies, so any ceiling opens while the fixed length is itself
145    /// within the wire format's limit. Outside that range a `Text`
146    /// or `Bytes` space fails to open ([`OreError::InitFailed`]), and so
147    /// does every encryption in it; the scheme does not check the ceiling
148    /// when it is set.
149    pub fn with_max_bytes(mut self, max_bytes: NonZeroUsize) -> Self {
150        self.max_bytes = max_bytes;
151        self
152    }
153
154    /// The padding policy of this scheme's text spaces.
155    pub fn text_padding(&self) -> Padding {
156        self.text_padding
157    }
158
159    /// The ceiling on text and bytes values.
160    pub fn max_bytes(&self) -> NonZeroUsize {
161        self.max_bytes
162    }
163
164    /// The ORE key, or the refusal [`ore_key`] stands for.
165    fn key(&self) -> Result<Protected<[u8; 16]>, OreError> {
166        self.key
167            .as_deref()
168            .map(|key| Protected::new(*key))
169            .ok_or(OreError::InitFailed)
170    }
171}
172
173// Opaque Debug: never render key material.
174impl std::fmt::Debug for BlockOre {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.debug_struct("BlockOre")
177            .field("text_padding", &self.text_padding)
178            .field("max_bytes", &self.max_bytes)
179            .finish_non_exhaustive()
180    }
181}
182
183/// What [`BlockOre`] keeps for one space: the engine the space's target
184/// wants, keyed under the space's salt, and the target, so a plaintext of
185/// another is refused. `Send + Sync`, so a space is shared across threads
186/// as it is. Wiped on drop: each engine wipes its keys.
187pub struct BlockOreSpace {
188    engine: Engine,
189    target: OrderTarget,
190}
191
192enum Engine {
193    // Boxed: an engine holds AES key schedules and a nonce generator, and
194    // a space is opened once, so the pointer costs nothing per term.
195    Bit6(Box<OreAes128Bit6>),
196    Chained(Box<OreAes128Bit6Chained>),
197}
198
199// Dropping a space drops its boxed engine, which wipes its own keys. The
200// derive cannot see through the `Box`, so the match below names every
201// engine instead: one added without `ZeroizeOnDrop` does not compile.
202impl ZeroizeOnDrop for BlockOreSpace {}
203
204#[allow(dead_code)]
205fn engines_wipe_on_drop(engine: &Engine) {
206    fn wipes<T: ZeroizeOnDrop>(_: &T) {}
207    match engine {
208        Engine::Bit6(e) => wipes(&**e),
209        Engine::Chained(e) => wipes(&**e),
210    }
211}
212
213impl std::fmt::Debug for BlockOreSpace {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        let engine = match &self.engine {
216            Engine::Bit6(_) => "Bit6",
217            Engine::Chained(_) => "Chained",
218        };
219        f.debug_struct("BlockOreSpace")
220            .field("engine", &engine)
221            .field("target", &self.target)
222            .finish()
223    }
224}
225
226impl BlockOreSpace {
227    /// [`OreError::TargetMismatch`] unless `plaintext` was encoded as the
228    /// space's target. Without it, text handed to a `U128` space would be
229    /// padded under that space's defaults, not the scheme's policy.
230    fn check_target(&self, plaintext: &OrderPlaintext) -> Result<(), OreError> {
231        if plaintext.target() == self.target {
232            Ok(())
233        } else {
234            Err(OreError::TargetMismatch)
235        }
236    }
237}
238
239/// Which engine a target's terms are made by: Bit6 for a fixed width of
240/// up to [`MAX_BYTES`], chained for the rest.
241fn engine_for(target: OrderTarget) -> EngineKind {
242    match target.width() {
243        Some(width) if width <= MAX_BYTES => EngineKind::Bit6,
244        _ => EngineKind::Chained,
245    }
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249enum EngineKind {
250    Bit6,
251    Chained,
252}
253
254/// The engine a serialised term or query was made by, from its wire
255/// header. `None` for bytes with no v2 header, the legacy scheme's
256/// included.
257fn engine_of(bytes: &[u8]) -> Option<EngineKind> {
258    let ((version, scheme_id, _), _) = parse_header(bytes).ok()?;
259    if version != crate::scheme::bit2_w6::WIRE.version {
260        return None;
261    }
262    if scheme_id == crate::scheme::bit2_w6::WIRE.scheme_id {
263        Some(EngineKind::Bit6)
264    } else if scheme_id == crate::scheme::chained::SCHEME_ID {
265        Some(EngineKind::Chained)
266    } else {
267        None
268    }
269}
270
271impl OrderScheme for BlockOre {
272    const NAME: &'static str = "block-ore";
273    type Term = Term;
274    type Error = OreError;
275    type Space = BlockOreSpace;
276
277    /// Key the engine the target's width wants under `salt`. A `Bytes`
278    /// space never pads, and a `Text` space pads under the scheme's
279    /// policy, as does any other target of no fixed width, so one vitaminc
280    /// adds later cannot reveal its exact length. All of them keep the
281    /// scheme's ceiling, and fail to open ([`OreError::InitFailed`]) under
282    /// a ceiling the chained engine refuses (see
283    /// [`BlockOre::with_max_bytes`]). A fixed-width space on the chained
284    /// engine takes neither the padding nor the ceiling, so no setting of
285    /// either keeps it from opening.
286    fn open(&self, target: OrderTarget, salt: &Context<'_>) -> Result<BlockOreSpace, OreError> {
287        let key = self.key()?;
288        let engine = match engine_for(target) {
289            EngineKind::Bit6 => Engine::Bit6(Box::new(OreAes128Bit6::init_with_salt(key, salt)?)),
290            EngineKind::Chained => {
291                let options = match target {
292                    OrderTarget::Bytes => Options::default()
293                        .with_salt(salt)
294                        .with_padding(Padding::None)
295                        .with_max_bytes(self.max_bytes),
296                    // A fixed width: the engine goes in unpadded with no
297                    // ceiling, so the defaults are only there to pass
298                    // the engine's own check.
299                    target if target.width().is_some() => Options::default().with_salt(salt),
300                    // Text, and any target of no fixed width.
301                    _ => Options::default()
302                        .with_salt(salt)
303                        .with_padding(self.text_padding)
304                        .with_max_bytes(self.max_bytes),
305                };
306                Engine::Chained(Box::new(OreAes128Bit6Chained::init_with(key, options)?))
307            }
308        };
309        Ok(BlockOreSpace { engine, target })
310    }
311
312    /// A plaintext of another target than the space's is refused
313    /// ([`OreError::TargetMismatch`]): the space's engine is keyed and
314    /// configured for its own target alone. [`vitaminc_ore::OrderSpace`]
315    /// never hands one over; a direct call can.
316    fn encrypt_plaintext(
317        &self,
318        space: &BlockOreSpace,
319        plaintext: &OrderPlaintext,
320    ) -> Result<Term, OreError> {
321        space.check_target(plaintext)?;
322        match &space.engine {
323            Engine::Bit6(engine) => engine.encrypt_plaintext(plaintext),
324            Engine::Chained(engine) => engine.encrypt_plaintext(plaintext),
325        }
326    }
327
328    /// The engine's comparison, chosen by the terms' wire headers. `None`
329    /// for a term that is not a well-formed v2 ciphertext, or two terms
330    /// of different engines, which no space makes. Two well-formed terms
331    /// of different targets or contexts under one engine compare as
332    /// noise, which the scheme cannot tell; a space keeps its terms
333    /// together.
334    fn compare(a: &Term, b: &Term) -> Option<Ordering> {
335        match (engine_of(a.as_bytes()), engine_of(b.as_bytes())) {
336            (Some(EngineKind::Bit6), Some(EngineKind::Bit6)) => {
337                OreAes128Bit6::compare_raw_slices(a.as_bytes(), b.as_bytes())
338            }
339            (Some(EngineKind::Chained), Some(EngineKind::Chained)) => {
340                OreAes128Bit6Chained::compare_raw_slices(a.as_bytes(), b.as_bytes())
341            }
342            _ => None,
343        }
344    }
345}
346
347impl OrderQuery for BlockOre {
348    type Query = Query;
349
350    /// Refuses a plaintext of another target, as
351    /// [`OrderScheme::encrypt_plaintext`] does.
352    fn encrypt_query(
353        &self,
354        space: &BlockOreSpace,
355        plaintext: &OrderPlaintext,
356    ) -> Result<Query, OreError> {
357        space.check_target(plaintext)?;
358        match &space.engine {
359            Engine::Bit6(engine) => engine.encrypt_query_plaintext(plaintext),
360            Engine::Chained(engine) => engine.encrypt_query_plaintext(plaintext),
361        }
362    }
363
364    /// The order of the queried value against the stored one, through the
365    /// engine the two wire headers name; `None` as [`OrderScheme::compare`]
366    /// is `None`.
367    fn compare_query(query: &Query, term: &Term) -> Option<Ordering> {
368        match (engine_of(query.as_bytes()), engine_of(term.as_bytes())) {
369            (Some(EngineKind::Bit6), Some(EngineKind::Bit6)) => {
370                OreAes128Bit6::compare_left_to_full(query.as_bytes(), term.as_bytes())
371            }
372            (Some(EngineKind::Chained), Some(EngineKind::Chained)) => {
373                OreAes128Bit6Chained::compare_left_to_full(query.as_bytes(), term.as_bytes())
374            }
375            _ => None,
376        }
377    }
378}
379
380vitaminc_ore::supports_every_target!(BlockOre);
381
382impl OrderKeyInit for BlockOre {
383    type Key = Protected<[u8; 32]>;
384    type KeyError = WeakKeyError;
385
386    fn new(key: Self::Key) -> Self {
387        Self {
388            key: ore_key(&HmacSha256Prf::new(key)),
389            text_padding: Padding::default(),
390            max_bytes: DEFAULT_MAX_STR_BYTES,
391        }
392    }
393
394    fn try_from_bytes(key: Protected<Vec<u8>>) -> Result<Self, WeakKeyError> {
395        Ok(Self {
396            key: ore_key(&HmacSha256Prf::try_from_bytes(key)?),
397            text_padding: Padding::default(),
398            max_bytes: DEFAULT_MAX_STR_BYTES,
399        })
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use crate::scheme::chained::MAX_STR_BYTES;
407    use crate::scheme::decompose::num_blocks_6bit;
408    use crate::testing::{ceiling, fixed_padding, salt, text_pt, u128_pt, u64_pt};
409    use vitaminc_ore::target::{Bytes, Date, Decimal, Text, I32, I64, U128};
410    use vitaminc_ore::{test_support, OrderEncrypt, OrderError, OrderTerm, QueryTerm};
411
412    use OrderTarget as T;
413
414    fn key() -> Protected<[u8; 32]> {
415        Protected::new([7; 32])
416    }
417
418    fn other_key() -> Protected<[u8; 32]> {
419        Protected::new([8; 32])
420    }
421
422    fn scheme() -> BlockOre {
423        BlockOre::new(key())
424    }
425
426    /// The engine named by a term's or query's header.
427    fn engine(bytes: &[u8]) -> EngineKind {
428        engine_of(bytes).expect("a v2 header")
429    }
430
431    /// The checks vitaminc-ore asks of a real scheme: every target it
432    /// takes orders, keys and salts separate, nothing is empty, and the
433    /// query side agrees with the term side.
434    #[test]
435    fn the_scheme_keeps_the_order_scheme_contract() {
436        test_support::conformance(&scheme(), &BlockOre::new(other_key()));
437        test_support::query_conformance(&scheme(), &BlockOre::new(other_key()));
438        test_support::static_target::<BlockOre, I32>();
439        test_support::static_target::<BlockOre, Text>();
440        test_support::static_target::<BlockOre, U128>();
441    }
442
443    /// A space's target picks the engine, by width: up to ten bytes is
444    /// Bit6, the rest chained. The caller never names one.
445    #[test]
446    fn spaces_are_routed_to_an_engine_by_width() {
447        let s = scheme();
448        let bit6 = [
449            T::I16,
450            T::U16,
451            T::I32,
452            T::U32,
453            T::I64,
454            T::U64,
455            T::F64,
456            T::Date,
457        ];
458        let chained = [
459            T::I128,
460            T::U128,
461            T::Uuid,
462            T::Timestamp,
463            T::Decimal,
464            T::Text,
465            T::Bytes,
466        ];
467        for t in bit6 {
468            assert_eq!(engine_for(t), EngineKind::Bit6, "{t:?}");
469            s.target(t).context("c").open().expect("block ore");
470        }
471        for t in chained {
472            assert_eq!(engine_for(t), EngineKind::Chained, "{t:?}");
473            s.target(t).context("c").open().expect("block ore");
474        }
475        for t in OrderTarget::ALL {
476            assert!(
477                bit6.contains(t) || chained.contains(t),
478                "{:?} is unrouted",
479                t
480            );
481        }
482
483        let i64s = s.target(I64).context("c");
484        let term = i64s.encrypt(42i64).expect("block ore");
485        assert_eq!(engine(term.as_bytes()), EngineKind::Bit6);
486        assert_eq!(term.as_bytes().len(), 295);
487        let query = i64s.encrypt_query(42i64).expect("block ore");
488        assert_eq!(engine(query.as_bytes()), EngineKind::Bit6);
489
490        let wide = s.target(U128).context("c");
491        let term = wide.encrypt(42u128).expect("block ore");
492        assert_eq!(engine(term.as_bytes()), EngineKind::Chained);
493        assert_eq!(term.as_bytes().len(), 7 + 25 * 22 + 16);
494    }
495
496    /// Terms compare within a space as the values do, through both
497    /// comparators, and a query is deterministic where a term is not.
498    #[test]
499    fn terms_and_queries_compare_within_a_space() {
500        let s = scheme();
501        let prices = s.target(Decimal).context(("orders", "total"));
502        let values = [
503            rust_decimal::Decimal::MIN,
504            rust_decimal::Decimal::new(-150, 2),
505            rust_decimal::Decimal::ZERO,
506            rust_decimal::Decimal::new(150, 2),
507            rust_decimal::Decimal::MAX,
508        ];
509        let terms: Vec<OrderTerm<Term, Decimal>> = values
510            .iter()
511            .map(|v| prices.encrypt(*v).expect("block ore"))
512            .collect();
513        let queries: Vec<QueryTerm<Query, Decimal>> = values
514            .iter()
515            .map(|v| prices.encrypt_query(*v).expect("block ore"))
516            .collect();
517        for (i, a) in terms.iter().enumerate() {
518            for (j, b) in terms.iter().enumerate() {
519                assert_eq!(prices.compare(a, b), Some(i.cmp(&j)), "{i} vs {j}");
520                assert_eq!(
521                    prices.compare_query(&queries[i], b),
522                    Some(i.cmp(&j)),
523                    "query {i} vs {j}"
524                );
525            }
526            assert_eq!(
527                queries[i],
528                prices.encrypt_query(values[i]).expect("block ore")
529            );
530            assert_ne!(
531                a.as_bytes(),
532                prices.encrypt(values[i]).expect("block ore").as_bytes()
533            );
534        }
535
536        let dates = s.target(Date).context("d");
537        let (a, b) = (
538            dates
539                .encrypt(jiff::civil::date(2022, 1, 1))
540                .expect("block ore"),
541            dates
542                .encrypt(jiff::civil::date(2022, 1, 2))
543                .expect("block ore"),
544        );
545        assert_eq!(dates.compare(&a, &b), Some(Ordering::Less));
546
547        // A date from jiff is sealed as its day count since 1970-01-01, the
548        // encoding stored terms were made with. The query is deterministic,
549        // so a change to that encoding (another epoch, say) fails here even
550        // though it would keep the order above.
551        let space = s.open(T::Date, dates.salt()).expect("a date space");
552        for (date, days) in [
553            (jiff::civil::date(1970, 1, 1), 0),
554            (jiff::civil::date(1969, 12, 31), -1),
555            (jiff::civil::date(2022, 1, 1), 18_993),
556        ] {
557            assert_eq!(
558                dates.encrypt_query(date).expect("block ore").as_bytes(),
559                BlockOre::encrypt_query(&s, &space, &crate::testing::date_pt(days))
560                    .expect("block ore")
561                    .as_bytes(),
562                "{date} is not day {days}"
563            );
564        }
565    }
566
567    /// A comparison dispatches on the wire header: two engines' terms
568    /// never meet, and bytes with no v2 header are not terms at all.
569    #[test]
570    fn comparisons_dispatch_on_the_header_and_refuse_a_mix() {
571        let s = scheme();
572        let narrow = s
573            .target(T::I64)
574            .context("c")
575            .encrypt_checked(1i64)
576            .expect("block ore");
577        let wide = s
578            .target(T::U128)
579            .context("c")
580            .encrypt_checked(1u128)
581            .expect("block ore");
582        let narrow_query = s
583            .target(T::I64)
584            .context("c")
585            .encrypt_query_checked(1i64)
586            .expect("block ore");
587        assert_eq!(BlockOre::compare(narrow.raw(), wide.raw()), None);
588        assert_eq!(BlockOre::compare(wide.raw(), narrow.raw()), None);
589        assert_eq!(
590            BlockOre::compare_query(narrow_query.raw(), wide.raw()),
591            None
592        );
593        assert_eq!(
594            BlockOre::compare(narrow.raw(), narrow.raw()),
595            Some(Ordering::Equal)
596        );
597        assert_eq!(
598            BlockOre::compare_query(narrow_query.raw(), narrow.raw()),
599            Some(Ordering::Equal)
600        );
601        let headerless = Term::from_bytes(vec![0u8; 16]);
602        assert_eq!(BlockOre::compare(&headerless, narrow.raw()), None);
603        assert_eq!(BlockOre::compare(narrow.raw(), &headerless), None);
604        let mut other_version = narrow.raw().clone().into_bytes();
605        other_version[0] = 0x03;
606        assert_eq!(
607            BlockOre::compare(&Term::from_bytes(other_version), narrow.raw()),
608            None
609        );
610    }
611
612    /// Text is padded under the scheme's policy and bytes are not, and
613    /// both are refused past the ceiling, which counts vitaminc's marker.
614    #[test]
615    fn text_is_padded_and_bytes_are_not() {
616        let s = scheme();
617        let text = s.target(Text).context("c");
618        let bytes = s.target(Bytes).context("c");
619        let text_len = |v: &str| text.encrypt_checked(v).expect("block ore").as_bytes().len();
620        let bytes_len = |v: &[u8]| bytes.encrypt(v).expect("block ore").as_bytes().len();
621        let chained_len = |n: usize| 7 + 25 * num_blocks_6bit(n) + 16;
622        // Text: the 16-byte floor, then powers of two, counting the marker.
623        assert_eq!(text_len(""), chained_len(16));
624        assert_eq!(text_len("alice"), chained_len(16));
625        assert_eq!(text_len(&"a".repeat(15)), chained_len(16));
626        assert_eq!(text_len(&"a".repeat(16)), chained_len(32));
627        // Bytes: the exact length, marker included; a trailing NUL is fine.
628        assert_eq!(bytes_len(b""), chained_len(1));
629        assert_eq!(bytes_len(b"alice"), chained_len(6));
630        assert!(bytes.encrypt(&b"x\0"[..]).is_ok());
631        assert!(matches!(
632            text.encrypt_checked("x\0"),
633            Err(OrderError::Backend(OreError::TrailingNul))
634        ));
635
636        let unpadded = BlockOre::new(key()).with_text_padding(Padding::None);
637        assert_eq!(unpadded.text_padding(), Padding::None);
638        let text = unpadded.target(Text).context("c");
639        assert_eq!(
640            text.encrypt_checked("alice")
641                .expect("block ore")
642                .as_bytes()
643                .len(),
644            chained_len(6)
645        );
646
647        let small = BlockOre::new(key()).with_max_bytes(ceiling(8));
648        assert_eq!(small.max_bytes().get(), 8);
649        let text = small.target(Text).context("c");
650        let bytes = small.target(Bytes).context("c");
651        assert!(text.encrypt_checked("1234567").is_ok());
652        assert!(matches!(
653            text.encrypt_checked("12345678"),
654            Err(OrderError::Backend(OreError::TooLong))
655        ));
656        assert!(bytes.encrypt(&[0u8; 7][..]).is_ok());
657        assert!(matches!(
658            bytes.encrypt(&[0u8; 8][..]),
659            Err(OreError::TooLong)
660        ));
661        // Fixed-width spaces are not subject to the ceiling.
662        assert!(small.target(U128).context("c").encrypt(u128::MAX).is_ok());
663    }
664
665    /// A ceiling the chained engine refuses closes the text and bytes
666    /// spaces, with the documented error, and no fixed-width space: those
667    /// take no ceiling.
668    #[test]
669    fn a_ceiling_out_of_range_closes_only_text_and_bytes_spaces() {
670        for max in [MAX_STR_BYTES + 1, 60000] {
671            let s = BlockOre::new(key()).with_max_bytes(ceiling(max));
672            for t in [T::U128, T::I128, T::Uuid, T::Timestamp, T::Decimal] {
673                if let Err(e) = s.target(t).context("c").open() {
674                    panic!("{:?} under {}: {:?}", t, max, e);
675                }
676            }
677            assert!(s.target(U128).context("c").encrypt(u128::MAX).is_ok());
678            for t in [T::Text, T::Bytes] {
679                assert!(
680                    matches!(s.target(t).context("c").open(), Err(OreError::InitFailed)),
681                    "{:?} under {}",
682                    t,
683                    max
684                );
685            }
686        }
687        // The edges the docs give: unpadded bytes take up to 49151, text
688        // under the default padding up to 32768.
689        let s = BlockOre::new(key()).with_max_bytes(ceiling(MAX_STR_BYTES));
690        s.target(Bytes)
691            .context("c")
692            .open()
693            .expect("bytes at the wire limit");
694        assert!(matches!(
695            s.target(Text).context("c").open(),
696            Err(OreError::InitFailed)
697        ));
698        let s = BlockOre::new(key()).with_max_bytes(ceiling(32768));
699        s.target(Text).context("c").open().expect("text at 32768");
700        let s = BlockOre::new(key()).with_max_bytes(ceiling(32769));
701        assert!(matches!(
702            s.target(Text).context("c").open(),
703            Err(OreError::InitFailed)
704        ));
705    }
706
707    /// The text padding goes to `Text` spaces alone: a policy the chained
708    /// engine refuses closes the text space and nothing else, and a fixed
709    /// length bounds text under a ceiling no other policy could pad.
710    #[test]
711    fn the_text_padding_closes_only_text_spaces() {
712        let s = BlockOre::new(key()).with_text_padding(Padding::PowerOfTwo {
713            min_bytes: u16::MAX,
714        });
715        assert!(matches!(
716            s.target(Text).context("c").open(),
717            Err(OreError::InitFailed)
718        ));
719        for t in [
720            T::Bytes,
721            T::U128,
722            T::I128,
723            T::Uuid,
724            T::Timestamp,
725            T::Decimal,
726        ] {
727            if let Err(e) = s.target(t).context("c").open() {
728                panic!("{:?} under an unpaddable text policy: {:?}", t, e);
729            }
730        }
731
732        let s = BlockOre::new(key())
733            .with_text_padding(fixed_padding(8))
734            .with_max_bytes(ceiling(60000));
735        let text = s.target(Text).context("c");
736        assert!(text.encrypt_checked("1234567").is_ok());
737        assert!(matches!(
738            text.encrypt_checked("12345678"),
739            Err(OrderError::Backend(OreError::ExceedsPadding))
740        ));
741    }
742
743    /// A space refuses a plaintext of another target, so a direct trait
744    /// call cannot put text through a `U128` space's defaults. vitaminc's
745    /// own spaces never hand one over.
746    #[test]
747    fn a_space_refuses_a_plaintext_of_another_target() {
748        let s = BlockOre::new(key()).with_text_padding(fixed_padding(64));
749        let ctx = salt(b"c");
750        let wide = OrderScheme::open(&s, T::U128, &ctx).unwrap();
751        let narrow = OrderScheme::open(&s, T::I64, &ctx).unwrap();
752        let text = OrderScheme::open(&s, T::Text, &ctx).unwrap();
753        for space in [&wide, &narrow] {
754            assert!(matches!(
755                s.encrypt_plaintext(space, &text_pt("alice")),
756                Err(OreError::TargetMismatch)
757            ));
758            assert!(matches!(
759                s.encrypt_query(space, &text_pt("alice")),
760                Err(OreError::TargetMismatch)
761            ));
762        }
763        assert!(matches!(
764            s.encrypt_plaintext(&text, &u128_pt(5)),
765            Err(OreError::TargetMismatch)
766        ));
767        assert!(matches!(
768            s.encrypt_plaintext(&narrow, &u64_pt(5)),
769            Err(OreError::TargetMismatch)
770        ));
771        assert!(s.encrypt_plaintext(&wide, &u128_pt(5)).is_ok());
772        assert!(s.encrypt_query(&wide, &u128_pt(5)).is_ok());
773        assert!(s.encrypt_plaintext(&text, &text_pt("alice")).is_ok());
774    }
775
776    /// The default ceiling is 1024 bytes with the marker, so 1023 of value.
777    #[test]
778    fn text_and_bytes_are_refused_past_1023_bytes() {
779        let s = scheme();
780        let text = s.target(Text).context("c");
781        let bytes = s.target(Bytes).context("c");
782        assert!(text.encrypt_checked("a".repeat(1023).as_str()).is_ok());
783        assert!(matches!(
784            text.encrypt_checked("a".repeat(1024).as_str()),
785            Err(OrderError::Backend(OreError::TooLong))
786        ));
787        assert!(bytes.encrypt(&vec![1u8; 1023][..]).is_ok());
788        assert!(matches!(
789            bytes.encrypt(&vec![1u8; 1024][..]),
790            Err(OreError::TooLong)
791        ));
792    }
793
794    /// Terms of two spaces never compare `Equal`: another target, another
795    /// context or another key is another salt, through the engines' own
796    /// salt stage.
797    #[test]
798    fn terms_compare_only_within_one_scheme_key_target_and_context() {
799        let s = scheme();
800        let a = s
801            .target(T::I32)
802            .context("c")
803            .encrypt_checked(1i32)
804            .expect("block ore");
805        let other_target = s
806            .target(T::U32)
807            .context("c")
808            .encrypt_checked(1u32)
809            .expect("block ore");
810        let other_context = s
811            .target(T::I32)
812            .context("d")
813            .encrypt_checked(1i32)
814            .expect("block ore");
815        let other_key = BlockOre::new(other_key())
816            .target(T::I32)
817            .context("c")
818            .encrypt_checked(1i32)
819            .expect("block ore");
820        for other in [&other_target, &other_context, &other_key] {
821            assert_ne!(
822                BlockOre::compare(a.raw(), other.raw()),
823                Some(Ordering::Equal)
824            );
825        }
826        let same = s
827            .target(T::I32)
828            .context("c")
829            .encrypt_checked(1i32)
830            .expect("block ore");
831        assert_eq!(
832            BlockOre::compare(a.raw(), same.raw()),
833            Some(Ordering::Equal)
834        );
835    }
836
837    /// The bytes of a query under a fixed key and context are pinned, so
838    /// the key derivation (HMAC under [`ORE_KEY`], then the engines' salt
839    /// stage under the space's salt) cannot drift without this failing.
840    #[test]
841    fn queries_under_a_fixed_key_are_pinned() {
842        let s = scheme();
843        let narrow = s
844            .target(I32)
845            .context("pinned")
846            .encrypt_query(1i32)
847            .expect("block ore");
848        let wide = s
849            .target(U128)
850            .context("pinned")
851            .encrypt_query(1u128)
852            .expect("block ore");
853        assert_eq!(hex::encode(narrow.as_bytes()), PINNED_BIT6_QUERY);
854        assert_eq!(hex::encode(wide.as_bytes()), PINNED_CHAINED_QUERY);
855    }
856
857    const PINNED_BIT6_QUERY: &str = "0202000634253e3a0f361d11a1e27e55c72c1525ac3ffe1a36a3bbb1bb643141e98603df6b5a25da12f46901b6b637bb7aed66d4d4a76be3ce72496bc48fa83d17112c74f7a61caa32d176ae7eeb5471898519f199ae79a74418ca5b9717455df9637516f3fe3a60b4de";
858    const PINNED_CHAINED_QUERY: &str = "0203001600000033112033270b3037360909143b3315002330121f171068031d6c3431c9e1c1daf685de3fb173bb12f9c71ea7c9f565e9cb85fc2cc3646b890ce0b376aba6a79411da2b86ca300c8b4ba04b50c8740751b104772292236a5dc099d4fe537cadcdc048d70da884a4220976c3337777023933f38b33280b9ca99619da619597f5ee558913b5a1ce3a02a91c2c550c2488c6ba9ac71017bb1598978b2a991d82bbfeed0155b8fc616cf7f4c58a191b85d42d74383089ae8a9a2d930ca7495b3c8b9c4282e01cbacbbe98aa38d6ade89c6288479cf2ae0ecfd1abda089bf13b91b3506967dc6b4b2acdf366442f8c3c39df57b1a1be6745a445c79c24a71a2a7a175e06d2f67e375b08b6f5c854d132cc954d447dc6abfd05da818a58fa1852b8fc936633aced31052f4caf9a5373d238f7ba3fd6f38d147caaab184ffb50dc125d447e1ca3153321eb76ec4e6414e6e3ec566a2992add3ee02f5d0a68123b708c25fe675521ea600188475076ff3de8effb700c603df81b7";
859
860    /// A short key is refused as a PRF refuses it; a scheme that could not
861    /// derive its key refuses every space rather than panic.
862    #[test]
863    fn a_scheme_is_keyed_like_a_prf() {
864        assert!(BlockOre::try_from_bytes(Protected::new(vec![7u8; 8])).is_err());
865        let from_bytes = BlockOre::try_from_bytes(Protected::new(vec![7u8; 32])).expect("32 bytes");
866        let a = scheme()
867            .target(I32)
868            .context("c")
869            .encrypt_query(1i32)
870            .expect("block ore");
871        let b = from_bytes
872            .target(I32)
873            .context("c")
874            .encrypt_query(1i32)
875            .expect("block ore");
876        assert_eq!(a, b, "the same key material keys the same scheme");
877
878        let keyless = BlockOre {
879            key: None,
880            text_padding: Padding::default(),
881            max_bytes: DEFAULT_MAX_STR_BYTES,
882        };
883        assert!(matches!(
884            keyless.target(I32).context("c").open(),
885            Err(OreError::InitFailed)
886        ));
887        assert!(matches!(
888            keyless.target(I32).context("c").encrypt(1i32),
889            Err(OreError::InitFailed)
890        ));
891    }
892
893    /// A space is `Send + Sync` and opens its engine once; the scheme and
894    /// its space never show key material.
895    #[test]
896    fn a_space_is_shared_across_threads_and_debugs_without_the_key() {
897        fn is_send_sync<X: Send + Sync>(_: &X) {}
898        let s = scheme();
899        is_send_sync(&s);
900        let space = s.target(I64).context("c");
901        is_send_sync(&space);
902        space.open().expect("block ore");
903        let shared = &space;
904        let terms: Vec<_> = std::thread::scope(|scope| {
905            let handles: Vec<_> = (0..4i64)
906                .map(|i| scope.spawn(move || shared.encrypt(i).expect("block ore")))
907                .collect();
908            handles
909                .into_iter()
910                .map(|h| h.join().expect("a thread"))
911                .collect()
912        });
913        for pair in terms.windows(2) {
914            assert_eq!(space.compare(&pair[0], &pair[1]), Some(Ordering::Less));
915        }
916        let shown = format!("{s:?} {space:?}");
917        assert!(!shown.contains("key"), "{}", shown);
918        assert!(shown.contains("BlockOre"), "{}", shown);
919    }
920
921    /// A value with no order term as the space's target is refused by
922    /// vitaminc before the scheme sees it.
923    #[test]
924    fn a_value_with_no_term_is_refused() {
925        let s = scheme();
926        assert!(matches!(
927            s.target(T::I32).context("c").encrypt_checked(true),
928            Err(OrderError::Term(_))
929        ));
930        assert!(matches!(
931            s.target(Date).context("c").encrypt_checked("not a date"),
932            Err(OrderError::Term(_))
933        ));
934    }
935}