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
//! Shared Ed25519 key-lookup registry generic over the ID type.
//!
//! Used by both `ApproverRegistry` (keyed by `ApproverId`) and
//! `SourceIdentityRegistry` (keyed by `AgentId`). The trait surface is
//! intentionally separate per call-site to keep cross-domain keyspaces
//! distinct in the type system.
use ed25519_dalek::VerifyingKey;
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;
/// Errors raised by registry loaders.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum KeyRegistryError {
/// YAML load / parse failure.
#[error("key registry load: {0}")]
Load(String),
/// Pubkey not a valid 32-byte Ed25519 verifying key.
#[error("key registry: pubkey for `{id}` is not a valid 32-byte Ed25519 key")]
BadKey {
/// Offending id (display string).
id: String,
},
}
/// Common Ed25519 key registry, generic over the ID newtype.
pub trait Ed25519KeyRegistry<Id>: Send + Sync
where
Id: Eq + std::hash::Hash + std::fmt::Display,
{
/// Resolve `id` to a trusted Ed25519 verifying key, or `None` if
/// the id is not registered.
fn lookup(&self, id: &Id) -> Option<VerifyingKey>;
}
/// In-memory `HashMap`-backed registry.
pub struct StaticEd25519KeyRegistry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display,
{
keys: HashMap<Id, VerifyingKey>,
}
impl<Id> StaticEd25519KeyRegistry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display,
{
/// Build from an in-memory map.
#[must_use]
pub fn from_map(keys: HashMap<Id, VerifyingKey>) -> Self {
Self { keys }
}
}
impl<Id> Ed25519KeyRegistry<Id> for StaticEd25519KeyRegistry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display + Send + Sync,
{
fn lookup(&self, id: &Id) -> Option<VerifyingKey> {
self.keys.get(id).copied()
}
}
/// Load a YAML map of id → base64-encoded Ed25519 verifying key.
///
/// The `make_id` closure constructs the concrete ID newtype from the
/// raw string key. Used by `StaticApproverRegistry::from_yaml` and
/// `StaticSourceIdentityRegistry::from_yaml`.
pub fn load_ed25519_yaml<Id>(
path: impl AsRef<Path>,
make_id: impl Fn(String) -> Id,
) -> Result<HashMap<Id, VerifyingKey>, KeyRegistryError>
where
Id: Eq + std::hash::Hash + std::fmt::Display,
{
let body = std::fs::read_to_string(path.as_ref())
.map_err(|e| KeyRegistryError::Load(format!("read: {e}")))?;
let raw: HashMap<String, String> =
serde_yaml::from_str(&body).map_err(|e| KeyRegistryError::Load(format!("parse: {e}")))?;
let mut keys = HashMap::with_capacity(raw.len());
for (id_raw, b64) in raw {
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD
.decode(b64)
.map_err(|e| KeyRegistryError::Load(format!("base64 `{id_raw}`: {e}")))?;
let id = make_id(id_raw);
let pk_bytes: [u8; 32] = bytes
.try_into()
.map_err(|_| KeyRegistryError::BadKey { id: id.to_string() })?;
let vk = VerifyingKey::from_bytes(&pk_bytes)
.map_err(|_| KeyRegistryError::BadKey { id: id.to_string() })?;
keys.insert(id, vk);
}
Ok(keys)
}
#[cfg(feature = "hot-reload")]
pub use hot_reload::HotReloadableEd25519Registry;
#[cfg(feature = "hot-reload")]
mod hot_reload {
//! YAML-watching hot-reload wrapper around `Ed25519KeyRegistry<Id>`.
//!
//! Wraps an `Arc<HashMap>` behind `arc-swap` so reads are wait-free.
//! On file modification, debounces ~500ms, re-parses, then atomically
//! swaps the in-memory map. Parse errors keep the previous snapshot and
//! emit a `tracing::warn!` — the registry never panics or serves a
//! partially-loaded state.
use super::{load_ed25519_yaml, Ed25519KeyRegistry, KeyRegistryError};
use arc_swap::ArcSwap;
use ed25519_dalek::VerifyingKey;
use notify::{RecursiveMode, Watcher};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
/// Hot-reloading wrapper around an in-memory Ed25519 key registry.
///
/// Construct with [`HotReloadableEd25519Registry::watch_yaml`].
/// The underlying `notify` watcher fires on file modification,
/// debounces ~500ms, re-parses the YAML, and atomically swaps the
/// in-memory map via `arc-swap`. Reads via [`Ed25519KeyRegistry::lookup`]
/// are wait-free and never block.
#[non_exhaustive]
pub struct HotReloadableEd25519Registry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display + Send + Sync + 'static,
{
keys: Arc<ArcSwap<HashMap<Id, VerifyingKey>>>,
// Keep the watcher alive for the full lifetime of the registry.
_watcher: Box<dyn Watcher + Send + Sync>,
}
impl<Id> HotReloadableEd25519Registry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display + Send + Sync + Clone + 'static,
{
/// Build from a YAML file path.
///
/// Performs an initial load (fails fast on parse error) then starts
/// watching the file for changes. `make_id` constructs the concrete
/// ID newtype from the raw YAML key string.
pub fn watch_yaml(
path: impl AsRef<Path>,
make_id: impl Fn(String) -> Id + Send + Sync + 'static,
) -> Result<Self, KeyRegistryError> {
let path = path.as_ref().to_path_buf();
let initial = load_ed25519_yaml(&path, &make_id)?;
let keys = Arc::new(ArcSwap::from_pointee(initial));
let keys_for_watch = keys.clone();
let path_for_watch = path.clone();
let make_id_arc: Arc<dyn Fn(String) -> Id + Send + Sync> = Arc::new(make_id);
let mut watcher =
notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
let event = match res {
Ok(e) => e,
Err(err) => {
tracing::warn!(
target: "klieo.ops.key_registry.hot_reload",
error = %err,
"watcher error; keeping previous snapshot"
);
return;
}
};
if !event.kind.is_modify() && !event.kind.is_create() {
return;
}
// Debounce: editors often emit several events per save.
// Sleeping on the notify dispatcher thread is acceptable
// because reloads should be rare and non-latency-critical.
std::thread::sleep(Duration::from_millis(500));
match load_ed25519_yaml(&path_for_watch, |s| (make_id_arc)(s)) {
Ok(new_keys) => {
keys_for_watch.store(Arc::new(new_keys));
tracing::info!(
target: "klieo.ops.key_registry.hot_reload",
path = %path_for_watch.display(),
"key registry reloaded"
);
}
Err(err) => {
tracing::warn!(
target: "klieo.ops.key_registry.hot_reload",
path = %path_for_watch.display(),
error = %err,
"reload failed; keeping previous snapshot"
);
}
}
})
.map_err(|e| KeyRegistryError::Load(format!("watcher init: {e}")))?;
watcher
.watch(&path, RecursiveMode::NonRecursive)
.map_err(|e| KeyRegistryError::Load(format!("watch start: {e}")))?;
Ok(Self {
keys,
_watcher: Box::new(watcher),
})
}
}
impl<Id> Ed25519KeyRegistry<Id> for HotReloadableEd25519Registry<Id>
where
Id: Eq + std::hash::Hash + std::fmt::Display + Send + Sync + 'static,
{
fn lookup(&self, id: &Id) -> Option<VerifyingKey> {
self.keys.load().get(id).copied()
}
}
}