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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! Zero-trust floor (ADR ZC-0012): the enforcement defaults and counters.
//!
//! Every decision here takes the broker state, so a test pins one broker
//! without touching process env (the same pattern as
//! `BrokerState::enforce_node_sig_override`). An explicit env var always wins;
//! with it unset the default depends on whether the broker has a hub:
//!
//! | knob | env unset, hub configured | env unset, no hub |
//! |------------------------------|---------------------------------------|-------------------|
//! | `ZAKURO_ENFORCE_NODE_SIG` | enforce once a roster has been loaded | permissive |
//! | `ZAKURO_REQUIRE_VOUCHER` | required | optional |
//! | `ZAKURO_REQUIRE_SIG_V2` | off | off |
//! | `ZAKURO_EARN_BINDING` | `observe` | `observe` |
//! | `ZAKURO_REQUIRE_WORKER_KEY` | off | off |
//! | `ZAKURO_ROSTER_MAX_AGE` | 86400 s (only with a hub + enforcement) | n/a |
//!
//! `ZAKURO_EARN_BINDING=enforce` is safe once `earn_binding.unknown_job` stays
//! 0 on a mesh: every earn is then bound by a record of this node's own
//! (`bound`) or by the hub's receipt for the requester's debit
//! (`bound_by_receipt`, see `earn_receipt`).
//!
//! "Hub configured" means a non-blank `ZAKURO_API_URL` AND `ZAKURO_API_KEY`.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
use super::BrokerState;
/// Default roster staleness bound: a day.
pub const ROSTER_MAX_AGE_DEFAULT_SECS: u64 = 86_400;
/// Parse an on/off env value: `1|true|yes|on` -> `Some(true)`,
/// `0|false|no|off` -> `Some(false)`, anything else (including unset and
/// empty) -> `None`, i.e. "not decided, use the default".
pub(crate) fn parse_flag(v: Option<&str>) -> Option<bool> {
match v?.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Some(true),
"0" | "false" | "no" | "off" => Some(false),
_ => None,
}
}
fn env_flag(name: &str) -> Option<bool> {
parse_flag(std::env::var(name).ok().as_deref())
}
/// What `/peer/earn` does with an earn it cannot tie to a job this node ran.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EarnBindingMode {
/// Book as today, log and count the class (default: a missed path would
/// silently cost an owner real payouts).
Observe,
/// Refuse non-bound earns with 409.
Enforce,
}
impl EarnBindingMode {
pub(crate) fn parse(v: Option<&str>) -> Self {
match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
Some("enforce") => Self::Enforce,
_ => Self::Observe,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Observe => "observe",
Self::Enforce => "enforce",
}
}
}
/// Counters and per-broker test overrides for the zero-trust floor.
pub struct ZeroTrust {
/// Unix secs this process started: the replay floor (see `ReplayGuard`).
pub started_at: u64,
/// Unix secs of the last successful roster fetch (0 = unknown). Seeded
/// from the cache file at start-up so it survives a restart.
pub roster_fetched_at: AtomicU64,
/// Requests accepted on the v1 signature alone.
pub sig_v1_only_seen: AtomicU64,
/// Worker registrations without a key from a non-loopback address.
pub keyless_worker_nonloopback: AtomicU64,
/// `/peer/earn` classification counters.
pub earn_bound: AtomicU64,
pub earn_unknown_job: AtomicU64,
pub earn_over_amount: AtomicU64,
pub earn_wrong_requester: AtomicU64,
/// Earns with no record on this node that a hub receipt bound
/// (`earn_receipt`), and the receipts that did not, by reason.
pub earn_bound_by_receipt: AtomicU64,
/// Of those, receipts bound by `executor.node_key` (the rest by worker name).
pub earn_bound_by_node_key: AtomicU64,
pub earn_receipt_fetch_failed: AtomicU64,
pub earn_receipt_unverified: AtomicU64,
pub earn_receipt_not_settled: AtomicU64,
pub earn_receipt_wrong_executor: AtomicU64,
pub earn_receipt_reused: AtomicU64,
/// Offers whose voucher named a requester node / offer hash that did not
/// match what arrived (refused 402), and vouchers that carry neither
/// (accepted: minted by a hub or a requester without the binding).
pub voucher_binding_refused: AtomicU64,
pub voucher_unbound_seen: AtomicU64,
/// Voucher redeems the hub answered with a terminal refusal (409: it
/// never minted that nonce): dropped from the retry queue.
pub voucher_redeem_refused: AtomicU64,
/// Peer results by receipt state, counted by the requester before paying.
pub receipt_verified: AtomicU64,
pub receipt_missing: AtomicU64,
pub receipt_invalid: AtomicU64,
pub(crate) voucher_override: OnceLock<bool>,
pub(crate) sig_v2_override: OnceLock<bool>,
pub(crate) earn_mode_override: OnceLock<EarnBindingMode>,
pub(crate) worker_key_override: OnceLock<bool>,
pub(crate) roster_max_age_override: OnceLock<u64>,
pub(crate) earn_after_receipt_override: OnceLock<bool>,
}
impl Default for ZeroTrust {
fn default() -> Self {
Self::new()
}
}
impl ZeroTrust {
pub fn new() -> Self {
Self {
started_at: super::node_identity::now_secs(),
roster_fetched_at: AtomicU64::new(0),
sig_v1_only_seen: AtomicU64::new(0),
keyless_worker_nonloopback: AtomicU64::new(0),
earn_bound: AtomicU64::new(0),
earn_unknown_job: AtomicU64::new(0),
earn_over_amount: AtomicU64::new(0),
earn_wrong_requester: AtomicU64::new(0),
earn_bound_by_receipt: AtomicU64::new(0),
earn_bound_by_node_key: AtomicU64::new(0),
earn_receipt_fetch_failed: AtomicU64::new(0),
earn_receipt_unverified: AtomicU64::new(0),
earn_receipt_not_settled: AtomicU64::new(0),
earn_receipt_wrong_executor: AtomicU64::new(0),
earn_receipt_reused: AtomicU64::new(0),
voucher_binding_refused: AtomicU64::new(0),
voucher_unbound_seen: AtomicU64::new(0),
voucher_redeem_refused: AtomicU64::new(0),
receipt_verified: AtomicU64::new(0),
receipt_missing: AtomicU64::new(0),
receipt_invalid: AtomicU64::new(0),
voucher_override: OnceLock::new(),
sig_v2_override: OnceLock::new(),
earn_mode_override: OnceLock::new(),
worker_key_override: OnceLock::new(),
roster_max_age_override: OnceLock::new(),
earn_after_receipt_override: OnceLock::new(),
}
}
pub(crate) fn bump(c: &AtomicU64) {
c.fetch_add(1, Ordering::Relaxed);
}
pub fn load(c: &AtomicU64) -> u64 {
c.load(Ordering::Relaxed)
}
/// Record a successful roster fetch (or the cache file's own timestamp).
pub fn note_roster_fetched(&self, at: u64) {
self.roster_fetched_at.store(at, Ordering::Relaxed);
}
}
impl BrokerState {
/// A hub is configured: a non-blank API URL and API key.
pub fn hub_configured(&self) -> bool {
let set = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.trim().is_empty());
set(&self.config.api_url) && set(&self.config.api_key)
}
/// Are `/peer/*` node signatures enforced? Test override, else
/// `ZAKURO_ENFORCE_NODE_SIG`, else: enforce iff a hub is configured AND a
/// roster has been loaded (from the hub or the disk cache). A hubless or
/// local broker has no roster to check against and stays permissive.
pub fn node_sig_enforced(&self) -> bool {
self.enforce_node_sig_override
.get()
.copied()
.or_else(|| env_flag("ZAKURO_ENFORCE_NODE_SIG"))
.unwrap_or_else(|| self.hub_configured() && !self.node_roster.is_empty())
}
/// Are dashboard vouchers required for foreign jobs? Test override, else
/// `ZAKURO_REQUIRE_VOUCHER`, else: iff a hub is configured.
pub fn voucher_required(&self) -> bool {
self.zt
.voucher_override
.get()
.copied()
.or_else(|| env_flag("ZAKURO_REQUIRE_VOUCHER"))
.unwrap_or_else(|| self.hub_configured())
}
/// `ZAKURO_REQUIRE_SIG_V2`: refuse requests that carry only the v1 signature.
pub fn require_sig_v2(&self) -> bool {
self.zt
.sig_v2_override
.get()
.copied()
.or_else(|| env_flag("ZAKURO_REQUIRE_SIG_V2"))
.unwrap_or(false)
}
/// `ZAKURO_EARN_BINDING=observe|enforce` (default observe).
pub fn earn_binding_mode(&self) -> EarnBindingMode {
self.zt
.earn_mode_override
.get()
.copied()
.unwrap_or_else(|| {
EarnBindingMode::parse(std::env::var("ZAKURO_EARN_BINDING").ok().as_deref())
})
}
/// `ZAKURO_REQUIRE_WORKER_KEY`: refuse keyless non-loopback registrations.
pub fn require_worker_key(&self) -> bool {
self.zt
.worker_key_override
.get()
.copied()
.or_else(|| env_flag("ZAKURO_REQUIRE_WORKER_KEY"))
.unwrap_or(false)
}
/// `ZAKURO_EARN_AFTER_RECEIPT`: this broker, as a requester, sends the
/// payout of a job whose debit it tracks only once the hub has committed
/// the debit and answered its receipt, and attaches that receipt. Off by
/// default: the payout then goes out right after the job, as before, and an
/// executor that never saw the job classifies it `unknown_job`.
pub fn earn_after_receipt(&self) -> bool {
self.zt
.earn_after_receipt_override
.get()
.copied()
.or_else(|| env_flag("ZAKURO_EARN_AFTER_RECEIPT"))
.unwrap_or(false)
}
/// `ZAKURO_ROSTER_MAX_AGE` seconds (default one day).
pub fn roster_max_age_secs(&self) -> u64 {
self.zt
.roster_max_age_override
.get()
.copied()
.unwrap_or_else(|| {
std::env::var("ZAKURO_ROSTER_MAX_AGE")
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(ROSTER_MAX_AGE_DEFAULT_SECS)
})
}
/// Seconds since the roster was last fetched successfully, `None` when
/// that was never recorded.
pub fn roster_age_secs(&self) -> Option<u64> {
match self.zt.roster_fetched_at.load(Ordering::Relaxed) {
0 => None,
at => Some(super::node_identity::now_secs().saturating_sub(at)),
}
}
/// With a hub configured and enforcement on, a roster older than
/// [`roster_max_age_secs`](Self::roster_max_age_secs) is not trusted: a node
/// revoked since cannot be told from a live one. An unknown age (roster
/// set without a fetch) is not stale.
pub fn roster_stale(&self) -> bool {
self.hub_configured()
&& self.node_sig_enforced()
&& self
.roster_age_secs()
.is_some_and(|a| a > self.roster_max_age_secs())
}
/// The zc build the hub roster lists for node `fp` (`zc://node-<fp>` or
/// bare), when it sent one.
pub fn hub_build_for(&self, fp: &str) -> Option<crate::build_id::BuildId> {
let fp = super::node_identity::strip_node_arg(fp);
self.node_builds.iter().find_map(|e| {
(super::node_identity::fingerprint_of_pubkey_b64(e.key()).as_deref() == Some(fp))
.then(|| e.value().clone())
})
}
/// The `zero_trust` object served on `/health`.
pub fn zero_trust_health(&self) -> serde_json::Value {
let zt = &self.zt;
serde_json::json!({
"node_sig": if self.node_sig_enforced() { "enforced" } else { "permissive" },
"voucher": if self.voucher_required() { "required" } else { "optional" },
"sig_v2": if self.require_sig_v2() { "required" } else { "optional" },
"sig_v1_only_seen": ZeroTrust::load(&zt.sig_v1_only_seen),
"roster_age_secs": self.roster_age_secs(),
"roster_stale": self.roster_stale(),
"keyless_worker_nonloopback": ZeroTrust::load(&zt.keyless_worker_nonloopback),
"worker_key": if self.require_worker_key() { "required" } else { "optional" },
"earn_binding": {
"mode": self.earn_binding_mode().as_str(),
"bound": ZeroTrust::load(&zt.earn_bound),
"unknown_job": ZeroTrust::load(&zt.earn_unknown_job),
"over_amount": ZeroTrust::load(&zt.earn_over_amount),
"wrong_requester": ZeroTrust::load(&zt.earn_wrong_requester),
"bound_by_receipt": ZeroTrust::load(&zt.earn_bound_by_receipt),
"bound_by_node_key": ZeroTrust::load(&zt.earn_bound_by_node_key),
"receipt_rejected": {
"fetch_failed": ZeroTrust::load(&zt.earn_receipt_fetch_failed),
"unverified": ZeroTrust::load(&zt.earn_receipt_unverified),
"not_settled": ZeroTrust::load(&zt.earn_receipt_not_settled),
"wrong_executor": ZeroTrust::load(&zt.earn_receipt_wrong_executor),
"reused": ZeroTrust::load(&zt.earn_receipt_reused),
},
},
"voucher_binding": {
"refused": ZeroTrust::load(&zt.voucher_binding_refused),
"unbound_seen": ZeroTrust::load(&zt.voucher_unbound_seen),
},
// Refused on the first try (not queued) plus dropped from the retry queue.
"voucher_redeem_refused":
ZeroTrust::load(&zt.voucher_redeem_refused) + self.voucher_retry.refused(),
"receipts": {
"verified": ZeroTrust::load(&zt.receipt_verified),
"missing": ZeroTrust::load(&zt.receipt_missing),
"invalid": ZeroTrust::load(&zt.receipt_invalid),
},
"voucher_redeem_queue": self.voucher_retry.depth(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flag_parsing() {
for t in ["1", "true", "TRUE", "yes", "on", " On "] {
assert_eq!(parse_flag(Some(t)), Some(true), "{t}");
}
for f in ["0", "false", "no", "off", "OFF"] {
assert_eq!(parse_flag(Some(f)), Some(false), "{f}");
}
for u in ["", "maybe", "2"] {
assert_eq!(parse_flag(Some(u)), None, "{u}");
}
assert_eq!(parse_flag(None), None);
}
#[test]
fn earn_mode_defaults_to_observe() {
assert_eq!(EarnBindingMode::parse(None), EarnBindingMode::Observe);
assert_eq!(EarnBindingMode::parse(Some("")), EarnBindingMode::Observe);
assert_eq!(
EarnBindingMode::parse(Some("bogus")),
EarnBindingMode::Observe
);
assert_eq!(
EarnBindingMode::parse(Some("Enforce")),
EarnBindingMode::Enforce
);
}
}