Skip to main content

cbcl_core/
r4.rs

1//! R4: Integrity (Signer trait).
2//!
3//! The trait is defined in the pure core; concrete implementations live
4//! in the effectful shell or downstream crates.
5//!
6//! Verification produces an [`R4Result`] that distinguishes between valid
7//! signatures, unsigned dialects (accepted with warning), and invalid
8//! signatures (rejected).
9
10#![forbid(unsafe_code)]
11
12use crate::canonical::dialect_canonical_bytes;
13use crate::dialect::Dialect;
14use alloc::vec::Vec;
15
16/// Abstraction for Ed25519 (or similar) signing (REQ-090).
17pub trait Signer {
18    /// Sign the given data, returning the signature bytes.
19    fn sign(&self, data: &[u8]) -> Vec<u8>;
20    /// Verify that `sig` is a valid signature over `data`.
21    fn verify(&self, data: &[u8], sig: &[u8]) -> bool;
22}
23
24/// Result of R4 signature verification.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum R4Result {
27    /// Dialect has a valid signature.
28    Valid,
29    /// Dialect has no signature — accepted with warning.
30    Unsigned,
31    /// Dialect has a signature that failed verification.
32    Invalid,
33}
34
35impl R4Result {
36    /// Returns `true` if the dialect should be accepted (valid or unsigned).
37    pub fn is_acceptable(&self) -> bool {
38        matches!(self, R4Result::Valid | R4Result::Unsigned)
39    }
40}
41
42/// Check R4: dialect signature integrity with detailed result.
43///
44/// - `Valid` — signature present and verified against the canonical body.
45/// - `Unsigned` — no signature present (accepted with warning per spec).
46/// - `Invalid` — signature present but verification failed.
47pub fn check_r4(d: &Dialect, signer: &dyn Signer) -> R4Result {
48    let result = {
49        let Some(ref sig) = d.signature else {
50            return R4Result::Unsigned;
51        };
52        let body = dialect_sign_body(d);
53        if signer.verify(&body, sig) {
54            R4Result::Valid
55        } else {
56            R4Result::Invalid
57        }
58    };
59    #[cfg(feature = "tracing")]
60    {
61        let pass = result == R4Result::Valid;
62        tracing::event!(
63            tracing::Level::INFO,
64            constraint = "R4",
65            dialect = %d.name,
66            result = ?result,
67            pass,
68            "constraint_check_result"
69        );
70    }
71    result
72}
73
74/// Verify R4: dialect signature integrity (REQ-091).
75///
76/// Returns `true` only if the dialect has a signature and it verifies.
77/// Unsigned dialects return `false`. Use [`check_r4`] for the three-way result.
78pub fn verify_r4(d: &Dialect, signer: &dyn Signer) -> bool {
79    check_r4(d, signer) == R4Result::Valid
80}
81
82/// Compute the canonical serialized body of a dialect for signing.
83///
84/// Uses RFC 9804 canonical S-expression encoding. The signable S-expression
85/// includes all semantics-relevant fields (name, extends, author, performatives,
86/// resources, examples) and excludes integrity fields (signature, hash, protocol).
87///
88/// Order-dependent — different orderings produce different bodies (r4-002).
89/// Deterministic — same dialect always produces the same body (r4-003).
90pub fn dialect_sign_body(d: &Dialect) -> Vec<u8> {
91    dialect_canonical_bytes(d)
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::dialect::{base_dialect, Dialect, PerformativeDef, ResourceBounds};
98    use crate::sexpr::{Atom, SExpr};
99    use alloc::string::String;
100    use alloc::vec;
101
102    /// Mock signer that accepts signatures equal to `[0xAA, 0xBB]`.
103    struct MockSigner;
104
105    impl Signer for MockSigner {
106        fn sign(&self, _data: &[u8]) -> Vec<u8> {
107            vec![0xAA, 0xBB]
108        }
109        fn verify(&self, _data: &[u8], sig: &[u8]) -> bool {
110            sig == [0xAA, 0xBB]
111        }
112    }
113
114    /// Signer that verifies based on data content (for authority tests).
115    struct AuthoritySigner {
116        trusted_name: &'static str,
117    }
118
119    impl Signer for AuthoritySigner {
120        fn sign(&self, _data: &[u8]) -> Vec<u8> {
121            vec![0xCC, 0xDD]
122        }
123        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
124            // Only verify if the data starts with the trusted dialect name
125            let data_str = core::str::from_utf8(data).unwrap_or("");
126            data_str.starts_with(self.trusted_name) && sig == [0xCC, 0xDD]
127        }
128    }
129
130    fn test_dialect(name: &str) -> Dialect {
131        Dialect {
132            types: Default::default(),
133            roles: Vec::new(),
134            state: None,
135            state_bounds: None,
136            causal_locality: Default::default(),
137            name: String::from(name),
138            extends: vec![],
139            author: Some(String::from("@test-authority")),
140            performatives: vec![PerformativeDef {
141                role: None,
142                name: String::from("greet"),
143                params: vec![],
144                template: SExpr::List(vec![
145                    SExpr::Atom(Atom::Symbol(String::from("effect"))),
146                    SExpr::Atom(Atom::Symbol(String::from("greet-action"))),
147                ]),
148            }],
149            resources: ResourceBounds {
150                max_depth: 8,
151                max_expansion_size: 512,
152            },
153            examples: vec![],
154            signature: None,
155            hash: None,
156            protocol: None,
157            causal_protocol: None,
158            shapes: Vec::new(),
159        }
160    }
161
162    // ---- Basic verify_r4 tests ----
163
164    #[test]
165    fn unsigned_dialect_fails_r4() {
166        let d = base_dialect();
167        assert!(!verify_r4(&d, &MockSigner));
168    }
169
170    #[test]
171    fn signed_dialect_passes_r4() {
172        let mut d = base_dialect();
173        d.signature = Some(vec![0xAA, 0xBB]);
174        assert!(verify_r4(&d, &MockSigner));
175    }
176
177    #[test]
178    fn bad_signature_fails_r4() {
179        let mut d = base_dialect();
180        d.signature = Some(vec![0xFF, 0xFF]);
181        assert!(!verify_r4(&d, &MockSigner));
182    }
183
184    // ---- check_r4 three-way result tests ----
185
186    #[test]
187    fn check_r4_unsigned_returns_unsigned() {
188        let d = base_dialect();
189        assert_eq!(check_r4(&d, &MockSigner), R4Result::Unsigned);
190    }
191
192    #[test]
193    fn check_r4_valid_signature_returns_valid() {
194        let mut d = base_dialect();
195        d.signature = Some(vec![0xAA, 0xBB]);
196        assert_eq!(check_r4(&d, &MockSigner), R4Result::Valid);
197    }
198
199    #[test]
200    fn check_r4_invalid_signature_returns_invalid() {
201        let mut d = base_dialect();
202        d.signature = Some(vec![0xFF, 0xFF]);
203        assert_eq!(check_r4(&d, &MockSigner), R4Result::Invalid);
204    }
205
206    #[test]
207    fn r4_result_acceptability() {
208        assert!(R4Result::Valid.is_acceptable());
209        assert!(R4Result::Unsigned.is_acceptable());
210        assert!(!R4Result::Invalid.is_acceptable());
211    }
212
213    // ---- Test vector r4-001: unknown authority rejection ----
214
215    #[test]
216    fn r4_001_rejects_unknown_authority() {
217        let mut d = test_dialect("test-dialect");
218        d.signature = Some(vec![0xCC, 0xDD]);
219
220        // Signer that only trusts "trusted-dialect"
221        let signer = AuthoritySigner {
222            trusted_name: "trusted-dialect",
223        };
224        // "test-dialect" is not the trusted name, so verification fails
225        assert_eq!(check_r4(&d, &signer), R4Result::Invalid);
226        assert!(!verify_r4(&d, &signer));
227    }
228
229    // ---- Test vector r4-002: different orderings produce different encodings ----
230
231    #[test]
232    fn r4_002_different_orderings_different_encodings() {
233        let mut d1 = test_dialect("test");
234        d1.performatives = vec![
235            PerformativeDef {
236                role: None,
237                name: String::from("a"),
238                params: vec![],
239                template: SExpr::Atom(Atom::Symbol(String::from("a"))),
240            },
241            PerformativeDef {
242                role: None,
243                name: String::from("b"),
244                params: vec![],
245                template: SExpr::Atom(Atom::Symbol(String::from("b"))),
246            },
247        ];
248
249        let mut d2 = test_dialect("test");
250        d2.performatives = vec![
251            PerformativeDef {
252                role: None,
253                name: String::from("b"),
254                params: vec![],
255                template: SExpr::Atom(Atom::Symbol(String::from("b"))),
256            },
257            PerformativeDef {
258                role: None,
259                name: String::from("a"),
260                params: vec![],
261                template: SExpr::Atom(Atom::Symbol(String::from("a"))),
262            },
263        ];
264
265        let body1 = dialect_sign_body(&d1);
266        let body2 = dialect_sign_body(&d2);
267        assert_ne!(
268            body1, body2,
269            "different orderings must produce different encodings"
270        );
271    }
272
273    // ---- Test vector r4-003: deterministic encoding ----
274
275    #[test]
276    fn r4_003_deterministic_encoding() {
277        let d = test_dialect("test");
278        let body1 = dialect_sign_body(&d);
279        let body2 = dialect_sign_body(&d);
280        assert_eq!(body1, body2, "encode(d) == encode(d) must always hold");
281    }
282
283    // ---- Test vector r4-004: hash, signature, protocol fields preserved ----
284
285    #[test]
286    fn r4_004_integrity_fields_preserved() {
287        let d = Dialect {
288            types: Default::default(),
289            roles: Vec::new(),
290            state: None,
291            state_bounds: None,
292            causal_locality: Default::default(),
293            name: String::from("test-integrity-fields"),
294            extends: vec![],
295            author: None,
296            performatives: vec![],
297            resources: ResourceBounds {
298                max_depth: 8,
299                max_expansion_size: 512,
300            },
301            examples: vec![],
302            signature: Some(b"sig123".to_vec()),
303            hash: Some(String::from("f1220abcd1234")),
304            protocol: Some(String::from("ed25519")),
305            causal_protocol: None,
306            shapes: Vec::new(),
307        };
308        assert_eq!(d.hash.as_deref(), Some("f1220abcd1234"));
309        assert_eq!(d.signature.as_deref(), Some(b"sig123".as_slice()));
310        assert_eq!(d.protocol.as_deref(), Some("ed25519"));
311    }
312
313    // ---- dialect_sign_body includes all components ----
314
315    #[test]
316    fn sign_body_includes_name_and_performatives() {
317        let d = test_dialect("my-dialect");
318        let body = dialect_sign_body(&d);
319        let body_str = core::str::from_utf8(&body).unwrap();
320        assert!(body_str.contains("my-dialect"));
321        assert!(body_str.contains("greet"));
322    }
323
324    #[test]
325    fn sign_body_empty_performatives() {
326        let mut d = test_dialect("empty");
327        d.performatives = vec![];
328        let body = dialect_sign_body(&d);
329        let body_str = core::str::from_utf8(&body).unwrap();
330        assert!(body_str.contains("empty"));
331        // Should still contain structural elements (extends, author, resources, etc.)
332        assert!(body_str.contains("performatives"));
333    }
334}