rite-model 0.7.0

Domain model and intermediate representation for the Rite key ceremony DSL
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
//! Rules over a step's `with:` values that hold in every build.
//!
//! These sit beside [`ActionType::required_with_fields`] and
//! [`ActionType::reads_contract`]: what an action requires of its block, in
//! one place both the resolver and the runtime can read. Keeping them here lets
//! an editor report them, since the language server links the model and the
//! resolver but no backend.
//!
//! Only rules that travel with the document belong here. `RSA-9999` is not a
//! key algorithm on any machine, so rejecting it is portable. Whether *this*
//! binary can generate an ML-DSA key is a property of the build doing the
//! checking, and that question is answered by the action handler instead, at
//! the point where a backend exists to ask.

use serde::{Deserialize, Serialize};

use crate::transcript::{Format, ValidatorSpec, compile_pattern};
use crate::types::{ActionType, CertProfile, SharingScheme};
use rite_sdk::{KeyAlgorithm, KeyUsages, SignAlgorithm, WrapScheme};

/// A `with:` value an action cannot accept.
///
/// The message names the field it is about, so a reader with no span still
/// knows where to look.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParamError {
    /// What is wrong, phrased for the ceremony author.
    pub message: String,
}

/// Check the literal part of a step's `with:` block.
///
/// `with` is the projection produced by
/// [`literal_expr_value`](crate::expression::literal_expr_value), so a field
/// whose value is an expression is *absent* rather than wrong. Nothing here
/// may report a field as missing: required fields are
/// [`ActionType::required_with_fields`]'s job, and a required field is
/// routinely written as `${param.x}`.
#[must_use]
pub fn check(action: ActionType, with: &serde_json::Value) -> Vec<ParamError> {
    match action {
        ActionType::GenerateKey => {
            let mut errors = named_value(with, "algorithm", |name| {
                name.parse::<KeyAlgorithm>()
                    .map_err(|_| format!("unknown key algorithm '{name}'"))
            });
            errors.extend(key_usages(with));
            errors
        }
        ActionType::SignData | ActionType::VerifySignature => {
            named_value(with, "algorithm", |name| {
                name.parse::<SignAlgorithm>()
                    .map_err(|_| format!("unknown signature algorithm '{name}'"))
            })
        }
        ActionType::IssueCertificate => named_value(with, "profile", |name| {
            name.parse::<CertProfile>()
                .map_err(|_| format!("unknown certificate profile '{name}'"))
        }),
        ActionType::WrapKey => {
            let mut errors = fingerprint(with, "expect_recipient");
            errors.extend(scheme(with, |_| Ok(())));
            errors
        }
        // Narrower than `wrap_key`'s vocabulary on purpose: the container is
        // the only thing `encrypt_data` writes, and a name it would refuse
        // mid-ceremony belongs in `rite check` rather than in the room.
        ActionType::EncryptData => {
            named_value(with, "scheme", |name| match name.parse::<WrapScheme>() {
                Ok(WrapScheme::CmsAes256Gcm) => Ok(()),
                Ok(other) => Err(format!(
                    "encrypt_data writes {}, not {other}",
                    WrapScheme::CmsAes256Gcm
                )),
                Err(_) => Err(format!("unknown wrapping scheme '{name}'")),
            })
        }
        ActionType::SplitSecret => {
            let mut errors = named_value(with, "scheme", |name| {
                name.parse::<SharingScheme>()
                    .map(|_| ())
                    .map_err(|e| format!("unknown sharing scheme '{name}'; {e}"))
            });
            // The limit is the named scheme's, or the default's when the
            // scheme is absent or not a literal; a scheme that fails to parse
            // is reported above and the counts are still checked against
            // something.
            let scheme = with
                .get("scheme")
                .and_then(serde_json::Value::as_str)
                .and_then(|name| name.parse::<SharingScheme>().ok())
                .unwrap_or(SharingScheme::RiteSssV1);
            let max = u64::from(scheme.max_shares());
            errors.extend(share_count(with, "threshold", max));
            errors.extend(share_count(with, "shares", max));
            if let (Some(threshold), Some(shares)) = (
                with.get("threshold").and_then(serde_json::Value::as_u64),
                with.get("shares").and_then(serde_json::Value::as_u64),
            ) && shares < threshold
            {
                errors.push(ParamError {
                    message: format!(
                        "'shares' is {shares} and 'threshold' is {threshold}; fewer shares than \
                         the threshold could never reconstruct the secret"
                    ),
                });
            }
            errors
        }
        ActionType::UnwrapKey | ActionType::ImportKey => {
            let mut errors = key_identity(with, "expect_key");
            errors.extend(named_value(with, "algorithm", |name| {
                name.parse::<KeyAlgorithm>()
                    .map_err(|_| format!("unknown key algorithm '{name}'"))
            }));
            errors
        }
        ActionType::EnterValue | ActionType::EnterSecret => entry_shape(with),

        ActionType::ClockCheck
        | ActionType::Confirm
        | ActionType::CheckValue
        | ActionType::OralReadback
        | ActionType::MachineInfo
        | ActionType::ExportPublic
        | ActionType::Attest
        | ActionType::GatherEntropy
        | ActionType::TpmAttest
        | ActionType::PivReadCertificate
        | ActionType::PivSign
        | ActionType::YubikeyAttestSlot
        | ActionType::DecryptData
        | ActionType::CombineShares
        | ActionType::GenerateCsr => Vec::new(),
    }
}

/// A share count or threshold: an integer from 2 to the scheme's limit.
///
/// One is not a split. An absent field is deferred, as everywhere here; a
/// present one that is not an integer is wrong whatever it would have parsed
/// to.
fn share_count(with: &serde_json::Value, field: &'static str, max: u64) -> Vec<ParamError> {
    let Some(value) = with.get(field) else {
        return Vec::new();
    };
    let message = match value.as_u64() {
        Some(n) if (2..=max).contains(&n) => return Vec::new(),
        Some(n) => format!("'{field}' is {n}; it must be from 2 to {max}"),
        None => format!("'{field}' must be an integer from 2 to {max}, found {value}"),
    };
    vec![ParamError { message }]
}

/// The container a step names, checked against the vocabulary rather than left
/// to fail at the backend, and then against what the action itself writes.
///
/// One message for a name outside the vocabulary, whichever action asked, and
/// `accept` for the narrowing an action does on top of that.
fn scheme(
    with: &serde_json::Value,
    accept: impl FnOnce(WrapScheme) -> Result<(), String>,
) -> Vec<ParamError> {
    named_value(with, "scheme", |name| {
        let named = name
            .parse::<WrapScheme>()
            .map_err(|_| format!("unknown wrapping scheme '{name}'"))?;
        accept(named)
    })
}

/// Apply `parse` to a present string field.
///
/// An absent field is deferred, not missing. A field holding something other
/// than a string is wrong whatever the value would have been.
fn named_value<T>(
    with: &serde_json::Value,
    field: &'static str,
    parse: impl FnOnce(&str) -> Result<T, String>,
) -> Vec<ParamError> {
    let Some(value) = with.get(field) else {
        return Vec::new();
    };
    let Some(name) = value.as_str() else {
        return vec![ParamError {
            message: format!("'{field}' must be a string, found {value}"),
        }];
    };
    parse(name)
        .err()
        .map(|message| ParamError { message })
        .into_iter()
        .collect()
}

/// The shape an `enter_value` or `enter_secret` step gives the value it asks
/// for, checked the way the step will build it.
///
/// A field still carrying an expression is absent from the projection, so the
/// rule is built from what is literal, and a conflict between a literal field
/// and one resolved at run time is found there.
fn entry_shape(with: &serde_json::Value) -> Vec<ParamError> {
    let mut errors = Vec::new();
    let mut length = |field: &'static str| -> Option<usize> {
        let value = with.get(field)?;
        match value.as_u64().and_then(|n| usize::try_from(n).ok()) {
            Some(n) if n > 0 => Some(n),
            _ => {
                errors.push(ParamError {
                    message: format!("'{field}' must be a positive integer, found {value}"),
                });
                None
            }
        }
    };
    let mut shape = EntryShape {
        length: length("length"),
        min_length: length("min_length"),
        max_length: length("max_length"),
        format: None,
    };
    match with.get("format").map(FormatSpec::from_json) {
        None => {}
        Some(Ok(format)) => shape.format = Some(format),
        Some(Err(message)) => errors.push(ParamError { message }),
    }
    if let Err(message) = shape.validator() {
        errors.push(ParamError { message });
    }
    errors
}

/// `format:` as a step writes it: the name of a [`Format`], or a pattern.
///
/// A pattern is a format too, one whose argument is the expression, so it is
/// written under the same key rather than beside it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FormatSpec {
    /// `format: hex`
    Named(Format),
    /// `format: { pattern: "..." }`
    Pattern {
        /// A regular expression the whole value must match.
        pattern: String,
    },
}

impl FormatSpec {
    /// Read the field, with a message that says what the two forms are.
    ///
    /// # Errors
    ///
    /// Returns why the value is neither a format name nor a pattern.
    pub fn from_json(value: &serde_json::Value) -> Result<Self, String> {
        if let Some(name) = value.as_str() {
            return name.parse().map(FormatSpec::Named);
        }
        match value.get("pattern").and_then(|p| p.as_str()) {
            Some(pattern) if value.as_object().is_some_and(|m| m.len() == 1) => {
                Ok(FormatSpec::Pattern {
                    pattern: pattern.to_string(),
                })
            }
            _ => Err(format!(
                "'format' must name a format (text, digits, alphanumeric, hex, base64) or be \
                 {{ pattern: \"...\" }}, found {value}"
            )),
        }
    }
}

/// What an `enter_value` or `enter_secret` step says about the value it asks
/// for, as the `with:` fields spell it.
///
/// One place turns these into a [`ValidatorSpec`], so `rite check` and the
/// running step cannot disagree about which combinations mean something.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EntryShape {
    /// `format:`, what kind of value it is.
    pub format: Option<FormatSpec>,
    /// `length:`, an exact length.
    pub length: Option<usize>,
    /// `min_length:`.
    pub min_length: Option<usize>,
    /// `max_length:`.
    pub max_length: Option<usize>,
}

impl EntryShape {
    /// The rule these fields describe.
    ///
    /// Nothing given asks only for a non-empty value. A pattern says the
    /// whole shape, so a length beside it is refused rather than combined
    /// with it in a way the author would have to guess at. Lengths count the
    /// format's own units: characters for text, bytes for an encoding.
    ///
    /// # Errors
    ///
    /// Returns why the fields do not describe one rule, phrased for the
    /// ceremony author.
    pub fn validator(&self) -> Result<ValidatorSpec, String> {
        let bounded =
            self.length.is_some() || self.min_length.is_some() || self.max_length.is_some();
        let format = match &self.format {
            Some(FormatSpec::Pattern { pattern }) => {
                if bounded {
                    return Err("a pattern says the whole shape of the value, so 'length', \
                         'min_length' and 'max_length' cannot be given beside it"
                        .to_string());
                }
                compile_pattern(pattern)?;
                return Ok(ValidatorSpec::Regex(pattern.clone()));
            }
            Some(FormatSpec::Named(format)) => Some(*format),
            None => None,
        };
        let (min_length, max_length) = match (self.length, self.min_length, self.max_length) {
            (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
                return Err(
                    "'length' is exact, so 'min_length' and 'max_length' cannot be given \
                     beside it"
                        .to_string(),
                );
            }
            (Some(length), None, None) => (Some(length), Some(length)),
            (None, min, max) => (min, max),
        };
        if let (Some(min), Some(max)) = (min_length, max_length)
            && min > max
        {
            return Err(format!(
                "'min_length' is {min} and 'max_length' is {max}, so no value fits"
            ));
        }
        match format {
            None if !bounded => Ok(ValidatorSpec::NonEmpty),
            format => Ok(ValidatorSpec::Format {
                format: format.unwrap_or(Format::Text),
                min_length,
                max_length,
            }),
        }
    }
}

/// Check the names under `policy: { usages: [...] }`.
///
/// These are PKCS#11 usages, what the token permits the key to do. The X.509
/// `KeyUsage` extension is a different thing and comes from `profile:` on
/// `issue_certificate`.
fn key_usages(with: &serde_json::Value) -> Vec<ParamError> {
    const FIELD: &str = "policy.usages";
    let Some(usages) = with.get("policy").and_then(|p| p.get("usages")) else {
        return Vec::new();
    };
    let Some(names) = usages.as_array() else {
        return vec![ParamError {
            message: format!("'{FIELD}' must be a list, found {usages}"),
        }];
    };
    names
        .iter()
        .filter_map(|name| {
            let known = name
                .as_str()
                .is_some_and(|name| KeyUsages::usage_named(name).is_some());
            (!known).then(|| ParamError {
                message: format!(
                    "unknown key usage {name} under '{FIELD}'. Supported: {}",
                    KeyUsages::all_names().join(", ")
                ),
            })
        })
        .collect()
}

/// A fingerprint the ceremony declares in advance, `sha256:<64 hex digits>`.
///
/// A value in any other shape can never equal what the runtime computes, so
/// the step would fail in the room, after the keys exist. The runtime renders
/// every fingerprint in lowercase, so uppercase hex is one such shape and is
/// rejected here rather than at the step.
fn fingerprint(with: &serde_json::Value, field: &'static str) -> Vec<ParamError> {
    named_value(with, field, |value| {
        let hex = value.strip_prefix("sha256:").unwrap_or_default();
        if hex.len() == 64 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
            Ok(())
        } else {
            Err(format!(
                "'{field}' must be a fingerprint of the form \
                 'sha256:<64 lowercase hex digits>', found '{value}'"
            ))
        }
    })
}

/// A key's identity the ceremony declares in advance, in whichever form the
/// key has one: `sha256:<64 hex digits>` over the public half of a keypair, or
/// `cmac-aes:<6 hex digits>` for a symmetric key, which has no public half.
///
/// Same argument as [`fingerprint`]: a value in neither shape can never equal
/// what the runtime computes, so the mismatch is worth reporting before the
/// room rather than during it.
fn key_identity(with: &serde_json::Value, field: &'static str) -> Vec<ParamError> {
    named_value(with, field, |value| {
        let lower_hex = |s: &str, len: usize| {
            s.len() == len && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
        };
        let matches_form = match value.split_once(':') {
            Some(("sha256", hex)) => lower_hex(hex, 64),
            Some(("cmac-aes", hex)) => lower_hex(hex, 6),
            _ => false,
        };
        if matches_form {
            Ok(())
        } else {
            Err(format!(
                "'{field}' must name the key either as 'sha256:<64 lowercase hex digits>', \
                 the fingerprint of a public key, or as 'cmac-aes:<6 lowercase hex digits>', \
                 the check value of a symmetric key. Found '{value}'"
            ))
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn sole(action: ActionType, with: &serde_json::Value) -> String {
        let errors = check(action, with);
        let [error] = errors.as_slice() else {
            panic!("expected exactly one error, got {errors:?}");
        };
        error.message.clone()
    }

    #[test]
    fn rejects_a_value_outside_the_vocabulary() {
        assert!(
            sole(ActionType::GenerateKey, &json!({"algorithm": "RSA-9999"}))
                .contains("unknown key algorithm")
        );
        assert!(
            sole(ActionType::SignData, &json!({"algorithm": "RSA-PSS-SHA1"}))
                .contains("unknown signature algorithm")
        );
        assert!(
            sole(
                ActionType::IssueCertificate,
                &json!({"profile": "wildcard"})
            )
            .contains("unknown certificate profile")
        );
        assert!(
            sole(
                ActionType::WrapKey,
                &json!({"expect_recipient": "deadbeef"})
            )
            .contains("sha256:<64 lowercase hex digits>")
        );
    }

    /// The runtime renders every fingerprint in lowercase, so an uppercase one
    /// would pass resolution and then never match, failing in the room against
    /// the very key it names.
    #[test]
    fn rejects_a_fingerprint_that_is_not_lowercase() {
        let upper = format!("sha256:{}", "AB".repeat(32));
        let message = sole(ActionType::WrapKey, &json!({ "expect_recipient": upper }));
        assert!(message.contains("lowercase"), "{message}");

        let lower = format!("sha256:{}", "ab".repeat(32));
        assert!(
            check(ActionType::WrapKey, &json!({ "expect_recipient": lower })).is_empty(),
            "the shape the runtime produces is the shape that passes"
        );
    }

    /// `encrypt_data` takes a narrower vocabulary than `wrap_key`: a scheme it
    /// would refuse mid-ceremony is refused at check time instead.
    #[test]
    fn rejects_a_scheme_encrypt_data_does_not_write() {
        let message = sole(ActionType::EncryptData, &json!({"scheme": "AES-256-KW"}));
        assert!(
            message.contains("encrypt_data writes CMS-AES-256-GCM"),
            "{message}"
        );

        let message = sole(ActionType::EncryptData, &json!({"scheme": "CMS-RSA-CBC"}));
        assert!(message.contains("unknown wrapping scheme"), "{message}");

        assert!(
            check(
                ActionType::EncryptData,
                &json!({"scheme": "CMS-AES-256-GCM"})
            )
            .is_empty()
        );
        assert!(
            check(ActionType::EncryptData, &json!({})).is_empty(),
            "deferred"
        );

        // The same name is fine on a wrap, which does write it.
        assert!(check(ActionType::WrapKey, &json!({"scheme": "AES-256-KW"})).is_empty());
    }

    /// A scheme name outside the vocabulary would fail in the room, after the
    /// keys exist, so resolution rejects it.
    #[test]
    fn rejects_a_wrapping_scheme_outside_the_vocabulary() {
        let message = sole(ActionType::WrapKey, &json!({"scheme": "CMS-RSA-CBC"}));
        assert!(message.contains("unknown wrapping scheme"), "{message}");

        assert!(
            check(
                ActionType::WrapKey,
                &json!({"scheme": "RSA-AES-KEY-WRAP-SHA256"})
            )
            .is_empty()
        );
        assert!(
            check(ActionType::WrapKey, &json!({})).is_empty(),
            "deferred"
        );
    }

    #[test]
    fn accepts_the_vocabulary() {
        for (action, with) in [
            (ActionType::GenerateKey, json!({"algorithm": "RSA-4096"})),
            (ActionType::SignData, json!({"algorithm": "RSA-PSS-SHA256"})),
            (ActionType::IssueCertificate, json!({"profile": "root_ca"})),
            (
                ActionType::UnwrapKey,
                json!({"expect_key": format!("sha256:{}", "ab".repeat(32))}),
            ),
            (
                ActionType::UnwrapKey,
                json!({"algorithm": "AES-256", "expect_key": "cmac-aes:763cbc"}),
            ),
        ] {
            assert!(check(action, &with).is_empty(), "{action} rejected {with}");
        }
    }

    /// `expect_key` names the recovered key in whichever form it has one, so
    /// both are accepted and anything else is refused before the room.
    #[test]
    fn expect_key_takes_a_fingerprint_or_a_check_value() {
        let message = sole(
            ActionType::UnwrapKey,
            &json!({"expect_key": "cmac-aes:763CBC"}),
        );
        assert!(message.contains("lowercase"), "{message}");

        // A check value is three bytes, so a fingerprint's length under the
        // check value's prefix is not a check value.
        let message = sole(
            ActionType::UnwrapKey,
            &json!({"expect_key": format!("cmac-aes:{}", "ab".repeat(32))}),
        );
        assert!(message.contains("6 lowercase hex digits"), "{message}");

        let message = sole(ActionType::UnwrapKey, &json!({"expect_key": "763cbc"}));
        assert!(
            message.contains("sha256:") && message.contains("cmac-aes:"),
            "{message}"
        );
    }

    /// Nothing travels with a wrapped key saying what it is, so `algorithm:`
    /// declares it, and a name outside the vocabulary fails here rather than
    /// after the blob has been decrypted.
    #[test]
    fn rejects_an_unwrap_algorithm_outside_the_vocabulary() {
        let message = sole(ActionType::UnwrapKey, &json!({"algorithm": "AES-192"}));
        assert!(message.contains("unknown key algorithm"), "{message}");
    }

    #[test]
    fn an_absent_field_is_deferred_not_missing() {
        // The projection drops `algorithm: ${param.algo}`, and a required
        // field written as an expression must not be reported here.
        assert!(check(ActionType::GenerateKey, &json!({})).is_empty());
        assert!(check(ActionType::IssueCertificate, &json!({})).is_empty());
    }

    #[test]
    fn rejects_an_unknown_key_usage() {
        let message = sole(
            ActionType::GenerateKey,
            &json!({"policy": {"usages": ["sign", "key_cert_sign"]}}),
        );
        assert!(message.contains("unknown key usage"), "{message}");
        assert!(
            message.contains("wrap"),
            "the message should list what is available: {message}"
        );
    }

    #[test]
    fn accepts_the_pkcs11_usages() {
        let with = json!({"policy": {"usages": ["sign", "verify", "wrap", "unwrap", "derive"]}});
        assert!(check(ActionType::GenerateKey, &with).is_empty());
    }

    #[test]
    fn a_non_string_value_is_rejected_whatever_it_would_have_meant() {
        assert!(
            sole(ActionType::GenerateKey, &json!({"algorithm": 4096})).contains("must be a string")
        );
    }

    #[test]
    fn split_secret_counts_are_bounded_by_the_scheme() {
        assert!(
            check(
                ActionType::SplitSecret,
                &json!({"threshold": 2, "shares": 100})
            )
            .is_empty()
        );
        assert!(
            sole(
                ActionType::SplitSecret,
                &json!({"threshold": 2, "shares": 101})
            )
            .contains("from 2 to 100")
        );
        assert!(
            sole(
                ActionType::SplitSecret,
                &json!({"threshold": 1, "shares": 3})
            )
            .contains("from 2 to 100")
        );
        assert!(
            sole(
                ActionType::SplitSecret,
                &json!({"threshold": 4, "shares": 3})
            )
            .contains("fewer shares than the threshold")
        );
        assert!(
            sole(
                ActionType::SplitSecret,
                &json!({"threshold": "two", "shares": 3})
            )
            .contains("must be an integer")
        );
        assert!(
            sole(
                ActionType::SplitSecret,
                &json!({"scheme": "sss/v9", "threshold": 2, "shares": 3})
            )
            .contains("unknown sharing scheme")
        );
        // A `${param}` threshold is absent from the literal projection and is
        // deferred, not reported.
        assert!(check(ActionType::SplitSecret, &json!({"shares": 3})).is_empty());
    }

    /// One rule from the shape fields, the same one the step will apply.
    #[test]
    fn an_entry_shape_becomes_one_rule() {
        let shape = EntryShape {
            format: Some(FormatSpec::Named(Format::Digits)),
            length: Some(6),
            ..EntryShape::default()
        };
        assert!(matches!(
            shape.validator(),
            Ok(ValidatorSpec::Format {
                format: Format::Digits,
                min_length: Some(6),
                max_length: Some(6),
            })
        ));

        // Bounds alone: the format is text.
        let shape = EntryShape {
            max_length: Some(8),
            ..EntryShape::default()
        };
        assert!(matches!(
            shape.validator(),
            Ok(ValidatorSpec::Format {
                format: Format::Text,
                min_length: None,
                max_length: Some(8),
            })
        ));

        assert!(matches!(
            EntryShape::default().validator(),
            Ok(ValidatorSpec::NonEmpty)
        ));
        assert!(matches!(
            EntryShape {
                format: Some(FormatSpec::Pattern {
                    pattern: "[a-z]+".to_string()
                }),
                ..EntryShape::default()
            }
            .validator(),
            Ok(ValidatorSpec::Regex(_))
        ));
    }

    #[test]
    fn rejects_an_entry_shape_that_is_two_rules() {
        assert!(
            sole(
                ActionType::EnterValue,
                &json!({"format": {"pattern": "[0-9]+"}, "length": 6})
            )
            .contains("pattern")
        );
        assert!(
            sole(
                ActionType::EnterSecret,
                &json!({"length": 6, "min_length": 4})
            )
            .contains("'length' is exact")
        );
        assert!(
            sole(
                ActionType::EnterSecret,
                &json!({"min_length": 8, "max_length": 6})
            )
            .contains("no value fits")
        );
    }

    #[test]
    fn rejects_an_entry_shape_outside_the_vocabulary() {
        assert!(
            sole(ActionType::EnterSecret, &json!({"format": "emoji"})).contains("unknown format")
        );
        assert!(
            sole(
                ActionType::EnterSecret,
                &json!({"format": {"pattern": "[0-9"}})
            )
            .contains("invalid pattern")
        );
        assert!(
            sole(
                ActionType::EnterSecret,
                &json!({"format": {"regex": "[0-9]+"}})
            )
            .contains("'format' must name a format")
        );
        assert!(sole(ActionType::EnterSecret, &json!({"length": 0})).contains("positive integer"));
        assert!(
            sole(ActionType::EnterSecret, &json!({"length": "six"})).contains("positive integer")
        );
        assert!(check(ActionType::EnterSecret, &json!({"message": "PIN"})).is_empty());
        assert!(
            check(
                ActionType::EnterSecret,
                &json!({"message": "Key", "format": "hex", "length": 32})
            )
            .is_empty()
        );
    }
}