zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Wire envelope v2 (ZAK-0020): framed MAC input, freshness window and a
//! replay cache. v1 (`zakuro_wire::Envelope`) is untouched and stays the
//! default; v2 is opt in with `ZAKURO_WIRE=v2`.
//!
//! The byte layout, key derivation and MAC input follow the ADR exactly and
//! are pinned by its fixed vectors (see the tests). Rejections are opaque
//! ([`Reject`] carries no detail) and keys and MACs are never logged.

use ring::{hkdf, hmac};
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;

/// Version byte of a v2 envelope (v1 is `0x00`).
pub const VERSION_BYTE: u8 = 0x01;
/// Version byte of a v1 envelope.
pub const V1_VERSION_BYTE: u8 = 0x00;
/// MAC domain tag.
const DOMAIN_TAG: &[u8] = b"zakuro-wire-v2";
/// HKDF salt, shared with v1.
const HKDF_SALT: &[u8] = b"zakuro-wire-v1";
/// Default freshness window, seconds.
pub const DEFAULT_MAX_SKEW_S: u64 = 300;
/// Replay cache capacity.
pub const REPLAY_CAP: usize = 100_000;

/// Opaque rejection: nothing about why is exposed to the peer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Reject;

/// Client-side signing mode (`ZAKURO_WIRE`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireMode {
    /// `v1`, unset or anything else: the legacy envelope.
    V1,
    /// `v2`: sign (client) / accept v2 (worker).
    V2,
}

/// Parsed `ZAKURO_WIRE*` configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireConfig {
    /// Signing mode.
    pub mode: WireMode,
    /// Whether a v2 worker still accepts v1 envelopes.
    pub accept_v1: bool,
    /// Freshness window in seconds.
    pub max_skew_s: u64,
}

impl WireConfig {
    /// Read the configuration through `get` (an env lookup).
    pub fn from_env_fn(get: &dyn Fn(&str) -> Option<String>) -> Self {
        let val = |k: &str| get(k).map(|v| v.trim().to_lowercase()).unwrap_or_default();
        let mode = if val("ZAKURO_WIRE") == "v2" {
            WireMode::V2
        } else {
            WireMode::V1
        };
        let max_skew_s = val("ZAKURO_WIRE_MAX_SKEW_S")
            .parse::<u64>()
            .ok()
            .filter(|s| *s > 0)
            .unwrap_or(DEFAULT_MAX_SKEW_S);
        Self {
            mode,
            accept_v1: val("ZAKURO_WIRE_ACCEPT_V1") != "0",
            max_skew_s,
        }
    }

    /// Read the configuration from the process environment.
    pub fn from_env() -> Self {
        Self::from_env_fn(&|k| std::env::var(k).ok())
    }
}

/// A v2 envelope. `resource_limits` is not covered by the MAC (as in v1).
#[derive(Clone, PartialEq)]
pub struct EnvelopeV2 {
    /// Job identifier.
    pub job_id: String,
    /// Tenant identifier.
    pub tenant_id: String,
    /// Milliseconds since the Unix epoch at signing time.
    pub issued_at_ms: u64,
    /// Opaque callable bytes.
    pub callable: Vec<u8>,
    /// Opaque argument bytes.
    pub args: Vec<u8>,
    /// HMAC-SHA-256 (see [`compute_mac`]).
    pub mac: [u8; 32],
    /// Requested CPUs.
    pub cpus: f32,
    /// Requested memory, MB.
    pub memory_mb: u32,
    /// Requested GPUs.
    pub gpus: u32,
    /// Wall-clock timeout, seconds.
    pub timeout_seconds: u32,
}

// Never print payloads or the MAC.
impl std::fmt::Debug for EnvelopeV2 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EnvelopeV2")
            .field("job_id", &self.job_id)
            .field("tenant_id", &self.tenant_id)
            .finish_non_exhaustive()
    }
}

struct Len32;
impl hkdf::KeyType for Len32 {
    fn len(&self) -> usize {
        32
    }
}

/// Per-tenant v2 key: `HKDF-SHA256(master, salt="zakuro-wire-v1",
/// info="payload-v2:<tenant_id>")`, one 32-byte block.
pub fn tenant_key(master: &[u8], tenant_id: &str) -> [u8; 32] {
    let info = format!("payload-v2:{tenant_id}");
    let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, HKDF_SALT).extract(master);
    let info_parts = [info.as_bytes()];
    let okm = prk
        .expand(&info_parts, Len32)
        .expect("32 bytes is a valid HKDF-SHA256 output length");
    let mut out = [0u8; 32];
    okm.fill(&mut out)
        .expect("output buffer matches the requested length");
    out
}

fn mac_input(e: &EnvelopeV2) -> Vec<u8> {
    let mut m = Vec::with_capacity(DOMAIN_TAG.len() + e.callable.len() + e.args.len() + 64);
    m.extend_from_slice(DOMAIN_TAG);
    let mut field = |b: &[u8]| {
        m.extend_from_slice(&(b.len() as u32).to_be_bytes());
        m.extend_from_slice(b);
    };
    field(&[VERSION_BYTE]);
    field(e.tenant_id.as_bytes());
    field(e.job_id.as_bytes());
    field(&e.issued_at_ms.to_be_bytes());
    field(&e.callable);
    field(&e.args);
    m
}

/// HMAC-SHA-256 over the domain tag and the u32-BE-framed fields.
pub fn compute_mac(master: &[u8], e: &EnvelopeV2) -> [u8; 32] {
    let key = hmac::Key::new(hmac::HMAC_SHA256, &tenant_key(master, &e.tenant_id));
    let tag = hmac::sign(&key, &mac_input(e));
    let mut out = [0u8; 32];
    out.copy_from_slice(tag.as_ref());
    out
}

/// Fill in `mac` for an envelope.
pub fn sign(master: &[u8], e: &mut EnvelopeV2) {
    e.mac = compute_mac(master, e);
}

fn put_varint(out: &mut Vec<u8>, mut v: u64) {
    while v >= 0x80 {
        out.push((v as u8 & 0x7f) | 0x80);
        v >>= 7;
    }
    out.push(v as u8);
}

fn put_bytes(out: &mut Vec<u8>, b: &[u8]) {
    put_varint(out, b.len() as u64);
    out.extend_from_slice(b);
}

/// Postcard-compatible encoding (see the ADR).
pub fn encode(e: &EnvelopeV2) -> Vec<u8> {
    let mut o = Vec::with_capacity(e.callable.len() + e.args.len() + 96);
    o.push(VERSION_BYTE);
    put_bytes(&mut o, e.job_id.as_bytes());
    put_bytes(&mut o, e.tenant_id.as_bytes());
    put_varint(&mut o, e.issued_at_ms);
    put_bytes(&mut o, &e.callable);
    put_bytes(&mut o, &e.args);
    o.extend_from_slice(&e.mac);
    o.extend_from_slice(&e.cpus.to_le_bytes());
    put_varint(&mut o, u64::from(e.memory_mb));
    put_varint(&mut o, u64::from(e.gpus));
    put_varint(&mut o, u64::from(e.timeout_seconds));
    o
}

struct Rd<'a>(&'a [u8]);
impl<'a> Rd<'a> {
    fn take(&mut self, n: usize) -> Result<&'a [u8], Reject> {
        if self.0.len() < n {
            return Err(Reject);
        }
        let (a, b) = self.0.split_at(n);
        self.0 = b;
        Ok(a)
    }
    fn varint(&mut self) -> Result<u64, Reject> {
        let mut v: u64 = 0;
        for i in 0..10 {
            let b = self.take(1)?[0];
            let low = u64::from(b & 0x7f);
            if i == 9 && low > 1 {
                return Err(Reject);
            }
            v |= low << (7 * i);
            if b & 0x80 == 0 {
                // Reject non-canonical encodings (trailing zero groups).
                if i > 0 && low == 0 {
                    return Err(Reject);
                }
                return Ok(v);
            }
        }
        Err(Reject)
    }
    fn u32(&mut self) -> Result<u32, Reject> {
        u32::try_from(self.varint()?).map_err(|_| Reject)
    }
    fn bytes(&mut self) -> Result<Vec<u8>, Reject> {
        let n = usize::try_from(self.varint()?).map_err(|_| Reject)?;
        Ok(self.take(n)?.to_vec())
    }
    fn string(&mut self) -> Result<String, Reject> {
        String::from_utf8(self.bytes()?).map_err(|_| Reject)
    }
}

/// Decode a v2 envelope. Trailing bytes and malformed input are rejected.
/// This does not authenticate: call [`verify`] before trusting any field.
pub fn decode(raw: &[u8]) -> Result<EnvelopeV2, Reject> {
    let mut r = Rd(raw);
    if r.take(1)?[0] != VERSION_BYTE {
        return Err(Reject);
    }
    let job_id = r.string()?;
    let tenant_id = r.string()?;
    let issued_at_ms = r.varint()?;
    let callable = r.bytes()?;
    let args = r.bytes()?;
    let mut mac = [0u8; 32];
    mac.copy_from_slice(r.take(32)?);
    let cpus = f32::from_le_bytes(r.take(4)?.try_into().map_err(|_| Reject)?);
    let memory_mb = r.u32()?;
    let gpus = r.u32()?;
    let timeout_seconds = r.u32()?;
    if !r.0.is_empty() {
        return Err(Reject);
    }
    Ok(EnvelopeV2 {
        job_id,
        tenant_id,
        issued_at_ms,
        callable,
        args,
        mac,
        cpus,
        memory_mb,
        gpus,
        timeout_seconds,
    })
}

/// Which wire version a raw body carries (first byte), if any.
pub fn peek_version(raw: &[u8]) -> Option<u8> {
    raw.first()
        .copied()
        .filter(|b| *b == V1_VERSION_BYTE || *b == VERSION_BYTE)
}

/// Bounded in-memory replay cache keyed `(tenant_id, job_id)`. Entries live
/// for 2x the skew; the oldest is evicted when the cap is hit. Only
/// authenticated, fresh envelopes are ever recorded.
pub struct ReplayCache {
    cap: usize,
    inner: Mutex<Inner>,
}

#[derive(Default)]
struct Inner {
    seen: HashMap<(String, String), u64>,
    order: VecDeque<((String, String), u64)>,
}

impl ReplayCache {
    /// New cache with the ADR capacity.
    pub fn new() -> Self {
        Self::with_cap(REPLAY_CAP)
    }
    /// New cache with an explicit capacity (tests).
    pub fn with_cap(cap: usize) -> Self {
        Self {
            cap: cap.max(1),
            inner: Mutex::new(Inner::default()),
        }
    }
    /// Record `(tenant, job)`; `false` if it was already seen and unexpired.
    fn check_and_insert(&self, tenant: &str, job: &str, now_ms: u64, ttl_ms: u64) -> bool {
        let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
        while let Some((k, at)) = g.order.front().cloned() {
            if now_ms.saturating_sub(at) < ttl_ms && g.seen.len() < self.cap {
                break;
            }
            g.order.pop_front();
            if g.seen.get(&k) == Some(&at) {
                g.seen.remove(&k);
            }
        }
        let key = (tenant.to_string(), job.to_string());
        if g.seen.contains_key(&key) {
            return false;
        }
        g.seen.insert(key.clone(), now_ms);
        g.order.push_back((key, now_ms));
        true
    }
}

impl Default for ReplayCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Verify a decoded v2 envelope: MAC (constant time), freshness, then replay.
/// The cache is only touched after the MAC and the timestamp pass.
pub fn verify(
    master: &[u8],
    e: &EnvelopeV2,
    now_ms: u64,
    max_skew_s: u64,
    cache: &ReplayCache,
) -> Result<(), Reject> {
    let key = hmac::Key::new(hmac::HMAC_SHA256, &tenant_key(master, &e.tenant_id));
    hmac::verify(&key, &mac_input(e), &e.mac).map_err(|_| Reject)?;
    let skew_ms = max_skew_s.saturating_mul(1000);
    if now_ms.abs_diff(e.issued_at_ms) > skew_ms {
        return Err(Reject);
    }
    if !cache.check_and_insert(&e.tenant_id, &e.job_id, now_ms, skew_ms.saturating_mul(2)) {
        return Err(Reject);
    }
    Ok(())
}

/// Current time, ms since the Unix epoch.
pub fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    const MASTER: [u8; 32] = [0x11; 32];
    const T0: u64 = 1_760_000_000_000;

    fn sample() -> EnvelopeV2 {
        EnvelopeV2 {
            job_id: "job-1".into(),
            tenant_id: "acme".into(),
            issued_at_ms: T0,
            callable: b"callable-bytes".to_vec(),
            args: b"args-bytes".to_vec(),
            mac: [0; 32],
            cpus: 1.0,
            memory_mb: 1024,
            gpus: 0,
            timeout_seconds: 60,
        }
    }

    #[test]
    fn wire_v2_fixed_vectors() {
        assert_eq!(
            hex::encode(tenant_key(&MASTER, "acme")),
            "b38c960e38b07c76a04fcfad14e1d433c43127dea5dc847eb109be0440e59e32"
        );
        let mut e = sample();
        sign(&MASTER, &mut e);
        assert_eq!(
            hex::encode(e.mac),
            "415981780bfa27bbdb5b06422fb7534290d98b31594d6ac07def49cb827349f2"
        );
        let wire = encode(&e);
        assert_eq!(
            hex::encode(&wire),
            "01056a6f622d310461636d658080b3c19c330e63616c6c61626c652d62797465730a617267732d6279746573415981780bfa27bbdb5b06422fb7534290d98b31594d6ac07def49cb827349f20000803f8008003c"
        );
        assert_eq!(decode(&wire).unwrap(), e);
        assert_eq!(peek_version(&wire), Some(VERSION_BYTE));
    }

    fn signed() -> EnvelopeV2 {
        let mut e = sample();
        sign(&MASTER, &mut e);
        e
    }

    #[test]
    fn wire_v2_accepts_fresh_and_rejects_replay() {
        let c = ReplayCache::new();
        let e = signed();
        assert!(verify(&MASTER, &e, T0 + 1000, 300, &c).is_ok());
        assert_eq!(verify(&MASTER, &e, T0 + 2000, 300, &c), Err(Reject));
        // A different job id from the same tenant is fine.
        let mut e2 = sample();
        e2.job_id = "job-2".into();
        sign(&MASTER, &mut e2);
        assert!(verify(&MASTER, &e2, T0, 300, &c).is_ok());
    }

    #[test]
    fn wire_v2_rejects_stale_and_future_but_does_not_cache_them() {
        let c = ReplayCache::new();
        let e = signed();
        assert_eq!(verify(&MASTER, &e, T0 + 301_000, 300, &c), Err(Reject));
        assert_eq!(verify(&MASTER, &e, T0 - 301_000, 300, &c), Err(Reject));
        assert!(verify(&MASTER, &e, T0 + 300_000, 300, &c).is_ok());
    }

    #[test]
    fn wire_v2_rejects_tamper_and_field_shifting() {
        let c = ReplayCache::new();
        let mut shifted = signed();
        // Move a byte from args to callable: the v1 MAC input would be equal.
        shifted.callable.push(shifted.args.remove(0));
        assert_eq!(verify(&MASTER, &shifted, T0, 300, &c), Err(Reject));
        let mut t = signed();
        t.tenant_id = "other".into();
        assert_eq!(verify(&MASTER, &t, T0, 300, &c), Err(Reject));
        let mut ts = signed();
        ts.issued_at_ms += 1;
        assert_eq!(verify(&MASTER, &ts, T0, 300, &c), Err(Reject));
        assert_eq!(verify(&[0x22; 32], &signed(), T0, 300, &c), Err(Reject));
        // Unauthenticated bytes never reached the cache.
        assert!(verify(&MASTER, &signed(), T0, 300, &c).is_ok());
    }

    #[test]
    fn wire_v2_replay_cache_evicts_oldest_at_cap_and_expires() {
        let c = ReplayCache::with_cap(2);
        assert!(c.check_and_insert("t", "a", 0, 1000));
        assert!(c.check_and_insert("t", "b", 1, 1000));
        assert!(c.check_and_insert("t", "c", 2, 1000)); // evicts a
        assert!(!c.check_and_insert("t", "c", 3, 1000));
        assert!(c.check_and_insert("t", "a", 4, 1000));
        assert!(c.check_and_insert("t", "c", 5000, 1000)); // expired
    }

    #[test]
    fn wire_v2_decode_rejects_malformed() {
        let wire = encode(&signed());
        assert!(decode(&wire[..wire.len() - 1]).is_err());
        let mut extra = wire.clone();
        extra.push(0);
        assert!(decode(&extra).is_err());
        let mut v1 = wire.clone();
        v1[0] = V1_VERSION_BYTE;
        assert!(decode(&v1).is_err());
        assert!(decode(&[]).is_err());
        assert_eq!(peek_version(&v1), Some(V1_VERSION_BYTE));
        assert_eq!(peek_version(&[7]), None);
    }

    #[test]
    fn wire_v2_config_switch() {
        let none = |_: &str| None;
        let c = WireConfig::from_env_fn(&none);
        assert_eq!(
            c,
            WireConfig {
                mode: WireMode::V1,
                accept_v1: true,
                max_skew_s: 300
            }
        );
        let env = |k: &str| match k {
            "ZAKURO_WIRE" => Some(" V2 ".to_string()),
            "ZAKURO_WIRE_ACCEPT_V1" => Some("0".to_string()),
            "ZAKURO_WIRE_MAX_SKEW_S" => Some("60".to_string()),
            _ => None,
        };
        let c = WireConfig::from_env_fn(&env);
        assert_eq!(c.mode, WireMode::V2);
        assert!(!c.accept_v1);
        assert_eq!(c.max_skew_s, 60);
    }
}