Skip to main content

agentmux_srv_core/backend/jobs/
reporters.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The cloud reporters the operator pinned (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md ยง4.2).
5//!
6//! A reporter is a name and a public key. Nothing is built in: no key for anyone's private jobs is compiled into the
7//! public app. The file is the same shape as the widget and template publisher pins (name to base64 key), so it is
8//! read and written by the same functions, and a key is shown by its fingerprint.
9
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12
13use serde::{Deserialize, Serialize};
14
15use crate::backend::widget::signature::{self as sig, Pins};
16
17/// Beside the template pins, in the job templates' data folder.
18pub const REPORTERS_FILE: &str = "job-reporters.json";
19
20/// A reporter, for Settings.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
22#[ts(export, export_to = "../../../frontend/types/rpc/")]
23pub struct ReporterPin {
24    pub name: String,
25    pub fingerprint: String,
26}
27
28/// Where a manifest's reporter stands against the pins: what approving it would do.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
30#[serde(rename_all = "snake_case")]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32pub enum ReporterState {
33    /// Not pinned yet: approving pins it.
34    New,
35    /// Already pinned, under this name and key.
36    Pinned,
37    /// The name is pinned to another key: approving is refused until the operator forgets that key.
38    NameTaken,
39    /// The key is pinned under another name: approving is refused.
40    KeyTaken,
41}
42
43pub struct Reporters {
44    path: PathBuf,
45    pins: Mutex<Pins>,
46}
47
48/// `acme-ci`: what a reporter may be called.
49pub(crate) fn is_name(s: &str) -> bool {
50    !s.is_empty() && s.len() <= 40 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
51}
52
53/// Whether `key` is a 32-byte Ed25519 public key in base64.
54pub(crate) fn is_public_key(key: &str) -> bool {
55    use base64::Engine;
56    base64::engine::general_purpose::STANDARD.decode(key.trim()).is_ok_and(|b| b.len() == 32)
57}
58
59impl Reporters {
60    /// The pins in `path`, none when there is no file.
61    pub fn open(path: &Path) -> Self {
62        Self { path: path.to_path_buf(), pins: Mutex::new(sig::read_pins(path)) }
63    }
64
65    fn pins(&self) -> std::sync::MutexGuard<'_, Pins> {
66        self.pins.lock().unwrap_or_else(|e| e.into_inner())
67    }
68
69    pub fn list(&self) -> Vec<ReporterPin> {
70        self.pins().iter().map(|(name, key)| ReporterPin { name: name.clone(), fingerprint: sig::fingerprint(key) }).collect()
71    }
72
73    /// What pinning `name` to `public_key` would do, as `add` would decide it.
74    pub fn state_of(&self, name: &str, public_key: &str) -> ReporterState {
75        let key = public_key.trim();
76        let pins = self.pins();
77        match pins.get(name) {
78            Some(existing) if existing == key => ReporterState::Pinned,
79            Some(_) => ReporterState::NameTaken,
80            None if pins.values().any(|k| k == key) => ReporterState::KeyTaken,
81            None => ReporterState::New,
82        }
83    }
84
85    /// Pin `name` to `public_key` (base64, a 32-byte Ed25519 key). Pinning a name again to another key is refused:
86    /// the operator forgets the old one first, so a key never changes without being seen.
87    pub fn add(&self, name: &str, public_key: &str) -> Result<ReporterPin, String> {
88        if !is_name(name) {
89            return Err("a reporter's name is lowercase letters, digits and -, up to 40".to_string());
90        }
91        let key = public_key.trim();
92        if !is_public_key(key) {
93            return Err("that isn't a 32-byte Ed25519 public key in base64".to_string());
94        }
95        let mut pins = self.pins();
96        if let Some(existing) = pins.get(name).filter(|existing| existing.as_str() != key) {
97            return Err(format!("{name:?} is pinned to another key ({}); forget it first", sig::fingerprint(existing)));
98        }
99        if let Some((other, _)) = pins.iter().find(|(n, k)| k.as_str() == key && n.as_str() != name) {
100            return Err(format!("that key is already pinned as {other:?}"));
101        }
102        pins.insert(name.to_string(), key.to_string());
103        sig::write_pins(&self.path, &pins)?;
104        Ok(ReporterPin { name: name.to_string(), fingerprint: sig::fingerprint(key) })
105    }
106
107    pub fn forget(&self, name: &str) -> Result<(), String> {
108        let mut pins = self.pins();
109        if pins.remove(name).is_none() {
110            return Err(format!("no reporter named {name:?} is pinned"));
111        }
112        sig::write_pins(&self.path, &pins)
113    }
114
115    /// The fingerprint of `public_key` if it is pinned, else `None`.
116    pub fn fingerprint_of_pinned(&self, public_key: &str) -> Option<String> {
117        let key = public_key.trim();
118        self.pins().values().any(|k| k == key).then(|| sig::fingerprint(key))
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use crate::backend::widget::signature::test_keys;
126
127    #[test]
128    fn a_reporter_is_pinned_listed_and_forgotten() {
129        let dir = tempfile::tempdir().unwrap();
130        let path = dir.path().join(REPORTERS_FILE);
131        let reporters = Reporters::open(&path);
132        let key = test_keys::public_key(1);
133        let pin = reporters.add("acme-ci", &key).unwrap();
134        assert_eq!(pin.fingerprint, sig::fingerprint(&key));
135        assert_eq!(reporters.list(), vec![pin.clone()]);
136        // It survives a restart.
137        assert_eq!(Reporters::open(&path).fingerprint_of_pinned(&key), Some(pin.fingerprint));
138        reporters.forget("acme-ci").unwrap();
139        assert!(Reporters::open(&path).list().is_empty());
140        assert!(reporters.forget("acme-ci").is_err());
141    }
142
143    #[test]
144    fn a_name_keeps_its_key_and_a_key_has_one_name() {
145        let dir = tempfile::tempdir().unwrap();
146        let reporters = Reporters::open(&dir.path().join(REPORTERS_FILE));
147        let (a, b) = (test_keys::public_key(1), test_keys::public_key(2));
148        reporters.add("acme-ci", &a).unwrap();
149        assert!(reporters.add("acme-ci", &a).is_ok(), "pinning the same pair again changes nothing");
150        assert!(reporters.add("acme-ci", &b).unwrap_err().contains("forget it first"));
151        assert!(reporters.add("other", &a).unwrap_err().contains("already pinned"));
152        assert_eq!(reporters.list().len(), 1);
153    }
154
155    #[test]
156    fn only_a_name_and_a_32_byte_key_are_accepted() {
157        let dir = tempfile::tempdir().unwrap();
158        let reporters = Reporters::open(&dir.path().join(REPORTERS_FILE));
159        let key = test_keys::public_key(1);
160        for bad in ["", "Acme", "a b", "../x", &"x".repeat(41)] {
161            assert!(reporters.add(bad, &key).is_err(), "{bad:?}");
162        }
163        for bad in ["", "not base64!", "AAAA"] {
164            assert!(reporters.add("acme-ci", bad).is_err(), "{bad:?}");
165        }
166        assert!(reporters.list().is_empty());
167    }
168}