Skip to main content

acl_core/
registry_protocols.rs

1//! §35.15: protocol registry — publish, discover and fetch `.aclp`
2//! programs. File-backed (like the agent registry): every entry stores
3//! the protocol source, its declared roles, and a SHA-256 checksum of
4//! the source; fetch verifies the checksum (tamper-evident).
5
6use crate::protocol::{self, ProtocolProgram};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::path::Path;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct ProtocolEntry {
13    pub name: String,
14    pub version: u32,
15    pub roles: Vec<String>,
16    pub checksum: String,
17    pub source: String,
18    pub published_by: Option<String>,
19}
20
21#[derive(Debug, Default, Serialize, Deserialize)]
22pub struct ProtocolRegistry {
23    entries: BTreeMap<String, ProtocolEntry>,
24}
25
26fn checksum(source: &str) -> String {
27    use std::fmt::Write;
28    let digest = <sha2_impl::Sha256 as sha2_impl::Digest>::digest(source.as_bytes());
29    let mut out = String::new();
30    for b in digest {
31        let _ = write!(out, "{b:02x}");
32    }
33    out
34}
35
36/// tiny SHA-256 wrapper — uses the same sha2 crate as the rest of the
37/// stack when available; a pure-Rust fallback keeps deps unchanged.
38mod sha2_impl {
39    // FNV-based NOT-SHA256 is NOT acceptable for integrity — use sha2.
40    // The crate is already in the tree via other deps; direct dep below.
41    pub use sha2::{Digest, Sha256};
42}
43
44impl ProtocolRegistry {
45    pub fn load(path: &Path) -> Result<Self, String> {
46        if !path.exists() {
47            return Ok(Self::default());
48        }
49        let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
50        serde_json::from_str(&text).map_err(|e| e.to_string())
51    }
52
53    pub fn save(&self, path: &Path) -> Result<(), String> {
54        if let Some(parent) = path.parent() {
55            let _ = std::fs::create_dir_all(parent);
56        }
57        let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
58        std::fs::write(path, text).map_err(|e| e.to_string())
59    }
60
61    /// parse + check a protocol, then register it (checksummed)
62    pub fn publish(
63        &mut self,
64        source: &str,
65        published_by: Option<&str>,
66    ) -> Result<(String, u32), String> {
67        let prog: ProtocolProgram =
68            protocol::parse(source).map_err(|e| format!("parse: {:?}", e))?;
69        protocol::check(&prog).map_err(|e| format!("check: {:?}", e))?;
70        let entry = ProtocolEntry {
71            name: prog.name.clone(),
72            version: prog.version,
73            roles: prog.roles.clone(),
74            checksum: checksum(source),
75            source: source.to_string(),
76            published_by: published_by.map(|s| s.to_string()),
77        };
78        let key = format!("{}@v{}", prog.name, prog.version);
79        self.entries.insert(key, entry);
80        Ok((prog.name, prog.version))
81    }
82
83    pub fn fetch(&self, name: &str, version: u32) -> Result<(String, String), String> {
84        // (source, checksum) — the caller MUST verify before use
85        let key = format!("{name}@v{version}");
86        let e = self
87            .entries
88            .get(&key)
89            .ok_or_else(|| format!("protocol '{key}' not registered"))?;
90        Ok((e.source.clone(), e.checksum.clone()))
91    }
92
93    /// fetch + verify integrity; returns the parsed program
94    pub fn fetch_verified(&self, name: &str, version: u32) -> Result<ProtocolProgram, String> {
95        let (source, expected) = self.fetch(name, version)?;
96        let actual = checksum(&source);
97        if actual != expected {
98            return Err(format!(
99                "checksum mismatch for {name}@v{version}: registry tampered?"
100            ));
101        }
102        protocol::parse(&source).map_err(|e| format!("stored protocol fails to parse: {:?}", e))
103    }
104
105    pub fn list(&self) -> Vec<(String, u32, Vec<String>)> {
106        self.entries
107            .values()
108            .map(|e| (e.name.clone(), e.version, e.roles.clone()))
109            .collect()
110    }
111
112    pub fn len(&self) -> usize {
113        self.entries.len()
114    }
115
116    pub fn is_empty(&self) -> bool {
117        self.entries.is_empty()
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    const PROG: &str = "protocol supply v1;\nroles buyer, seller;\non request(\"q\") from buyer -> send propose to buyer;\non propose from seller -> send accept to seller;\non accept from buyer -> begin;\non breach -> send failure to buyer;\non failure from seller -> send bye;\n";
126
127    #[test]
128    fn publish_fetch_verify_roundtrip() {
129        let mut reg = ProtocolRegistry::default();
130        let (name, ver) = reg.publish(PROG, Some("acl-language")).unwrap();
131        assert_eq!((name.as_str(), ver), ("supply", 1));
132        assert_eq!(reg.len(), 1);
133        // fetch verified: parses and integrity-checked
134        let prog = reg.fetch_verified("supply", 1).unwrap();
135        assert_eq!(prog.roles, vec!["buyer", "seller"]);
136        // list
137        assert_eq!(reg.list().len(), 1);
138    }
139
140    #[test]
141    fn tampered_registry_is_detected() {
142        let mut reg = ProtocolRegistry::default();
143        reg.publish(PROG, None).unwrap();
144        // tamper: replace the source with a different protocol
145        let key = "supply@v1";
146        reg.entries.get_mut(key).unwrap().source =
147            "protocol evil v1;\nroles a, b;\non query from a -> send inform to a;\non inform from b -> send bye;\n".into();
148        let err = reg.fetch_verified("supply", 1).unwrap_err();
149        assert!(err.contains("checksum mismatch"), "{err}");
150    }
151
152    #[test]
153    fn file_backed_roundtrip() {
154        let path = std::env::temp_dir().join("acl-proto-registry-test.json");
155        let _ = std::fs::remove_file(&path);
156        {
157            let mut reg = ProtocolRegistry::load(&path).unwrap();
158            assert!(reg.is_empty());
159            reg.publish(PROG, None).unwrap();
160            reg.save(&path).unwrap();
161        }
162        {
163            let reg = ProtocolRegistry::load(&path).unwrap();
164            assert_eq!(reg.len(), 1);
165            reg.fetch_verified("supply", 1).unwrap();
166        }
167        let _ = std::fs::remove_file(&path);
168    }
169}