Skip to main content

agentmux_srv_core/backend/widget/
signature.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Signed widget packages (docs/specs/SPEC_WIDGET_SHARING_2026_10_10.md §2).
5//!
6//! A package may carry `widget.sig`: an Ed25519 signature by its publisher
7//! over its id, version and content hash. The content hash leaves
8//! `widget.sig` out, so signing doesn't change what was approved. srv pins
9//! each publisher (the part of the id before the dot) to the first key the
10//! user approved for it, and reports any later package of that publisher
11//! signed by another key, or not signed, as `key_changed`.
12//!
13//! Job templates share the file format and the verifier under their own
14//! signing domain (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4): the
15//! domain's prefix is part of the signed bytes, so a widget's signature never
16//! passes as a template's, or a template's as a widget's.
17
18use std::collections::BTreeMap;
19use std::path::Path;
20
21use base64::Engine;
22use ed25519_dalek::{Signature, Verifier, VerifyingKey};
23use serde::{Deserialize, Serialize};
24use sha2::{Digest, Sha256};
25
26const SIG_VERSION: u32 = 1;
27
28/// What a signature is for: the prefix of the bytes it signs, and the file
29/// at the package's root it lives in (left out of the package's hash).
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct Domain {
32    pub prefix: &'static [u8],
33    pub sig_file: &'static str,
34}
35
36pub const WIDGET: Domain = Domain { prefix: b"agentmux-widget-sig-v1\0", sig_file: "widget.sig" };
37pub const JOB_TEMPLATE: Domain = Domain { prefix: b"agentmux-job-template-sig-v1\0", sig_file: "template.sig" };
38
39/// A computer-use skill (docs/specs/SPEC_PACKS_2026_11_05.md §5): signed over `<publisher>.<id>`, its version and its content hash.
40pub const COMPUTER_USE_SKILL: Domain = Domain { prefix: b"agentmux-skill-sig-v1\0", sig_file: "skill.sig" };
41
42pub const SIG_FILE: &str = WIDGET.sig_file;
43
44#[derive(Debug, Deserialize)]
45#[serde(rename_all = "camelCase")]
46struct SigFile {
47    sig_version: u32,
48    algorithm: String,
49    public_key: String,
50    signature: String,
51}
52
53/// The bytes a publisher signs for a package of `domain`.
54pub fn signed_message(domain: &Domain, id: &str, version: &str, hash: &str) -> Vec<u8> {
55    let mut m = domain.prefix.to_vec();
56    m.extend_from_slice(id.as_bytes());
57    m.push(0);
58    m.extend_from_slice(version.as_bytes());
59    m.push(0);
60    m.extend_from_slice(hash.as_bytes());
61    m
62}
63
64/// The `domain`'s signature file in `dir`: `None` when there is none, the
65/// publisher's public key (base64) when it verifies, or why it doesn't.
66pub fn check(domain: &Domain, dir: &Path, id: &str, version: &str, hash: &str) -> Option<Result<String, String>> {
67    let file = domain.sig_file;
68    let text = match std::fs::read_to_string(dir.join(file)) {
69        Ok(t) => t,
70        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
71        Err(e) => return Some(Err(format!("can't read {file}: {e}"))),
72    };
73    Some(verify(domain, &text, id, version, hash))
74}
75
76/// Check signature text already read (an imported skill's `skill.sig`): the publisher's public key when it verifies.
77pub fn verify_text(domain: &Domain, text: &str, id: &str, version: &str, hash: &str) -> Result<String, String> {
78    verify(domain, text, id, version, hash)
79}
80
81fn verify(domain: &Domain, text: &str, id: &str, version: &str, hash: &str) -> Result<String, String> {
82    let file = domain.sig_file;
83    let sig: SigFile = serde_json::from_str(text).map_err(|e| format!("{file}: {e}"))?;
84    if sig.sig_version != SIG_VERSION {
85        return Err(format!("{file} is version {}, this AgentMux reads {SIG_VERSION}", sig.sig_version));
86    }
87    if sig.algorithm != "ed25519" {
88        return Err(format!("{file} uses {:?}, this AgentMux reads ed25519", sig.algorithm));
89    }
90    let b64 = base64::engine::general_purpose::STANDARD;
91    let key: [u8; 32] = b64
92        .decode(sig.public_key.trim())
93        .ok()
94        .and_then(|k| k.try_into().ok())
95        .ok_or("publicKey isn't a 32-byte base64 key")?;
96    let signature: [u8; 64] = b64
97        .decode(sig.signature.trim())
98        .ok()
99        .and_then(|s| s.try_into().ok())
100        .ok_or("signature isn't 64 bytes of base64")?;
101    let key = VerifyingKey::from_bytes(&key).map_err(|_| "publicKey isn't a valid Ed25519 key")?;
102    key.verify(&signed_message(domain, id, version, hash), &Signature::from_bytes(&signature))
103        .map_err(|_| "its signature doesn't match its files".to_string())?;
104    Ok(b64.encode(key.as_bytes()))
105}
106
107/// A key as people compare it: the first 10 bytes of its SHA-256, base32,
108/// in groups of four (`K7Q2-MZ4D-PX3A-9TWE`).
109pub fn fingerprint(public_key_b64: &str) -> String {
110    let Ok(key) = base64::engine::general_purpose::STANDARD.decode(public_key_b64) else {
111        return String::new();
112    };
113    let digest = Sha256::digest(&key);
114    let text = base32(&digest[..10]);
115    text.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join("-")
116}
117
118/// RFC 4648 base32, no padding.
119fn base32(bytes: &[u8]) -> String {
120    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
121    let mut out = String::new();
122    let (mut buf, mut bits) = (0u32, 0u32);
123    for &b in bytes {
124        buf = (buf << 8) | u32::from(b);
125        bits += 8;
126        while bits >= 5 {
127            bits -= 5;
128            out.push(ALPHABET[((buf >> bits) & 31) as usize] as char);
129        }
130    }
131    if bits > 0 {
132        out.push(ALPHABET[((buf << (5 - bits)) & 31) as usize] as char);
133    }
134    out
135}
136
137/// The publisher part of a package id (`acme` of `acme.pr-dashboard`).
138pub fn publisher_of(id: &str) -> &str {
139    id.split_once('.').map_or(id, |(p, _)| p)
140}
141
142// ── What the UI sees ────────────────────────────────────────────────────────
143
144#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
145#[serde(rename_all = "snake_case")]
146#[ts(export, export_to = "../../../frontend/types/rpc/")]
147pub enum SignatureState {
148    /// Signed by the key this publisher is pinned to.
149    Signed,
150    /// Signed; the first package of this publisher here.
151    SignedNew,
152    Unsigned,
153    /// Signed by another key than the pinned one, or not signed while the
154    /// publisher is pinned.
155    KeyChanged,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
159#[ts(export, export_to = "../../../frontend/types/rpc/")]
160pub struct WidgetSignatureInfo {
161    pub state: SignatureState,
162    pub publisher: String,
163    /// The fingerprint of the key that signed it.
164    pub fingerprint: Option<String>,
165    /// The fingerprint of the key this publisher is pinned to.
166    pub pinned: Option<String>,
167}
168
169/// A publisher pinned to a key, for Settings.
170#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
171#[ts(export, export_to = "../../../frontend/types/rpc/")]
172pub struct WidgetPublisherPin {
173    pub publisher: String,
174    pub fingerprint: String,
175}
176
177/// publisher → public key (base64).
178pub type Pins = BTreeMap<String, String>;
179
180pub fn describe(id: &str, signer: Option<&str>, pins: &Pins) -> WidgetSignatureInfo {
181    let publisher = publisher_of(id).to_string();
182    let pinned = pins.get(&publisher);
183    let state = match (signer, pinned) {
184        (Some(k), Some(p)) if k == p => SignatureState::Signed,
185        (Some(_), Some(_)) | (None, Some(_)) => SignatureState::KeyChanged,
186        (Some(_), None) => SignatureState::SignedNew,
187        (None, None) => SignatureState::Unsigned,
188    };
189    WidgetSignatureInfo { state, publisher, fingerprint: signer.map(fingerprint), pinned: pinned.map(|p| fingerprint(p)) }
190}
191
192/// The pins that read, each on its own; one this build cannot read is kept on disk by [`write_pins`].
193pub fn read_pins(path: &Path) -> Pins {
194    crate::backend::json_keep::read_entries(path)
195}
196
197/// Writes `pins`, and keeps every pin already on disk that this build cannot read, exactly as it was.
198pub fn write_pins(path: &Path, pins: &Pins) -> Result<(), String> {
199    crate::backend::json_keep::write_entries(path, pins)
200}
201
202/// [`write_pins`] for forgetting `removed`: dropped from the file even when this build cannot read it.
203pub fn write_pins_removing(path: &Path, pins: &Pins, removed: &str) -> Result<(), String> {
204    crate::backend::json_keep::write_entries_removing(path, pins, &[removed])
205}
206
207#[cfg(any(test, feature = "test-support"))]
208pub mod test_keys {
209    use base64::Engine;
210    use ed25519_dalek::{Signer, SigningKey};
211
212    /// A `widget.sig` for `id`/`version`/`hash`, signed by the key from `seed`.
213    pub fn sig_file(seed: u8, id: &str, version: &str, hash: &str) -> String {
214        sig_file_in(&super::WIDGET, seed, id, version, hash)
215    }
216
217    /// The same, for a package of `domain`.
218    pub fn sig_file_in(domain: &super::Domain, seed: u8, id: &str, version: &str, hash: &str) -> String {
219        let key = SigningKey::from_bytes(&[seed; 32]);
220        let b64 = base64::engine::general_purpose::STANDARD;
221        let sig = key.sign(&super::signed_message(domain, id, version, hash));
222        serde_json::json!({
223            "sigVersion": 1,
224            "algorithm": "ed25519",
225            "publicKey": b64.encode(key.verifying_key().as_bytes()),
226            "signature": b64.encode(sig.to_bytes()),
227        })
228        .to_string()
229    }
230
231    pub fn public_key(seed: u8) -> String {
232        base64::engine::general_purpose::STANDARD.encode(SigningKey::from_bytes(&[seed; 32]).verifying_key().as_bytes())
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn a_signature_verifies_only_for_its_own_id_version_and_hash() {
242        let sig = test_keys::sig_file(7, "acme.x", "1.0.0", "abc");
243        assert_eq!(verify(&WIDGET, &sig, "acme.x", "1.0.0", "abc").unwrap(), test_keys::public_key(7));
244        assert!(verify(&WIDGET, &sig, "acme.x", "1.0.1", "abc").is_err());
245        assert!(verify(&WIDGET, &sig, "acme.x", "1.0.0", "abd").is_err());
246        assert!(verify(&WIDGET, &sig, "evil.x", "1.0.0", "abc").is_err());
247        assert!(verify(&WIDGET, "{}", "acme.x", "1.0.0", "abc").is_err());
248    }
249
250    /// Widgets sign the very bytes they signed before domains existed, so
251    /// every widget signature already out there still verifies.
252    #[test]
253    fn a_widget_signs_the_same_bytes_as_before() {
254        assert_eq!(signed_message(&WIDGET, "acme.x", "1.0.0", "abc"), b"agentmux-widget-sig-v1\0acme.x\x001.0.0\0abc".to_vec());
255        assert_eq!(
256            signed_message(&JOB_TEMPLATE, "acme.x", "1.0.0", "abc"),
257            b"agentmux-job-template-sig-v1\0acme.x\x001.0.0\0abc".to_vec()
258        );
259    }
260
261    #[test]
262    fn a_signature_verifies_only_in_its_own_domain() {
263        let widget = test_keys::sig_file(7, "acme.x", "1.0.0", "abc");
264        let template = test_keys::sig_file_in(&JOB_TEMPLATE, 7, "acme.x", "1.0.0", "abc");
265        assert_eq!(verify(&JOB_TEMPLATE, &template, "acme.x", "1.0.0", "abc").unwrap(), test_keys::public_key(7));
266        assert!(verify(&WIDGET, &template, "acme.x", "1.0.0", "abc").is_err(), "a template's signature isn't a widget's");
267        assert!(verify(&JOB_TEMPLATE, &widget, "acme.x", "1.0.0", "abc").is_err(), "a widget's signature isn't a template's");
268    }
269
270    /// The fixture the SDK's `agentmux-widget sign` signed with the same test
271    /// seed: both sides must agree on its hash, its signature and its
272    /// fingerprint (frontend/app/block/widget-sign.test.ts checks the SDK's).
273    #[test]
274    fn the_sdk_signed_fixture_verifies_here() {
275        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../sdk/widget-sdk/fixtures/acme.fixture");
276        let files = crate::backend::widget::packages::hash_files(&dir).unwrap();
277        assert!(!files.contains_key(SIG_FILE));
278        let hash = crate::backend::widget::packages::package_hash(&files);
279        assert_eq!(hash, "2f480223aad83d3e220179f1e67c8bd660d5bec197cd334b71f514661018b202");
280        assert_eq!(check(&WIDGET, &dir, "acme.fixture", "1.0.0", &hash).unwrap().unwrap(), test_keys::public_key(7));
281        assert_eq!(fingerprint(&test_keys::public_key(7)), "72AS-YEXT-VNGO-NLC5");
282    }
283
284    #[test]
285    fn fingerprints_are_grouped_base32() {
286        let f = fingerprint(&test_keys::public_key(7));
287        assert_eq!(f.len(), 19);
288        assert_eq!(f.matches('-').count(), 3);
289        assert!(f.chars().all(|c| c == '-' || c.is_ascii_uppercase() || ('2'..='7').contains(&c)));
290        assert_ne!(f, fingerprint(&test_keys::public_key(8)));
291        assert_eq!(base32(b"foobar"), "MZXW6YTBOI");
292    }
293
294    #[test]
295    fn a_pinned_publisher_flags_another_key_or_no_signature() {
296        let (k1, k2) = (test_keys::public_key(1), test_keys::public_key(2));
297        let mut pins = Pins::new();
298        assert_eq!(describe("acme.x", Some(&k1), &pins).state, SignatureState::SignedNew);
299        assert_eq!(describe("acme.x", None, &pins).state, SignatureState::Unsigned);
300        pins.insert("acme".into(), k1.clone());
301        assert_eq!(describe("acme.y", Some(&k1), &pins).state, SignatureState::Signed);
302        assert_eq!(describe("acme.y", Some(&k2), &pins).state, SignatureState::KeyChanged);
303        assert_eq!(describe("acme.y", None, &pins).state, SignatureState::KeyChanged);
304        assert_eq!(describe("other.y", None, &pins).state, SignatureState::Unsigned);
305    }
306}