aex-core 1.2.0-alpha.1

Core types, traits, and errors for Agent Exchange Protocol (AEX).
Documentation
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
//! On-the-wire formats shared between SDKs and the control plane.
//!
//! This module intentionally defines plain byte formats rather than JSON
//! envelopes. Canonical byte sequences are the source of truth for what
//! gets signed — any framing (JSON, protobuf, HTTP headers) is a transport
//! concern and must not alter the signed bytes.

use crate::{Error, Result};

/// Current wire protocol version. Bumped only when the canonical byte
/// sequence of any message format below changes. Old versions must continue
/// to verify for audit replay.
pub const PROTOCOL_VERSION: &str = "v1";

/// Maximum acceptable clock skew between client and server, in seconds.
/// Messages older/newer than this are rejected to limit replay windows.
pub const MAX_CLOCK_SKEW_SECS: i64 = 300;

/// Check if `issued_at` is within the allowed skew relative to `now`.
/// Overflow-safe: a malicious client sending `i64::MIN` or `i64::MAX`
/// cannot panic the server (release-mode wraparound would previously
/// silently accept those values; debug-mode would panic).
///
/// Returns `true` if the message is fresh enough.
pub fn is_within_clock_skew(now_unix: i64, issued_at_unix: i64) -> bool {
    let diff = (now_unix as i128).saturating_sub(issued_at_unix as i128);
    diff.unsigned_abs() <= MAX_CLOCK_SKEW_SECS as u128
}

/// Minimum nonce length (hex chars). 32 chars = 128 bits of entropy.
pub const MIN_NONCE_LEN: usize = 32;

/// Maximum nonce length (hex chars). Prevents pathological inputs.
pub const MAX_NONCE_LEN: usize = 128;

/// Produce the canonical bytes that a client signs to prove possession of
/// the private key matching `public_key_hex` when registering an agent.
///
/// Format (line-based, LF terminator on each line, no trailing LF on the
/// last line):
///
/// ```text
/// spize-register:v1
/// pub={public_key_hex}
/// org={org}
/// name={name}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
///
/// All inputs must be ASCII. The function validates inputs and returns an
/// error if any field contains characters that could allow canonicalization
/// ambiguity (newlines, NULs, non-ASCII).
pub fn registration_challenge_bytes(
    public_key_hex: &str,
    org: &str,
    name: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(public_key_hex, "public_key_hex")?;
    validate_ascii_line(org, "org")?;
    validate_ascii_line(name, "name")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "spize-register:{version}\npub={pub}\norg={org}\nname={name}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION,
        pub = public_key_hex,
        org = org,
        name = name,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Ensure a string is safe to embed in a single-line canonical field.
fn validate_ascii_line(s: &str, field: &str) -> Result<()> {
    if s.is_empty() {
        return Err(Error::Internal(format!("{} is empty", field)));
    }
    for (i, c) in s.chars().enumerate() {
        if !c.is_ascii() || c == '\n' || c == '\r' || c == '\0' {
            return Err(Error::Internal(format!(
                "{} has invalid char at {}: {:?}",
                field, i, c
            )));
        }
    }
    Ok(())
}

/// Allow-empty variant — used for optional fields (filename, declared_mime).
fn validate_ascii_line_opt(s: &str, field: &str) -> Result<()> {
    if s.is_empty() {
        return Ok(());
    }
    validate_ascii_line(s, field)
}

/// Canonical bytes signed by the **sender** when initiating a transfer.
///
/// Format:
/// ```text
/// spize-transfer-intent:v1
/// sender={sender_agent_id}
/// recipient={recipient}
/// size={size_bytes}
/// mime={declared_mime_or_empty}
/// filename={filename_or_empty}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
pub fn transfer_intent_bytes(
    sender_agent_id: &str,
    recipient: &str,
    size_bytes: u64,
    declared_mime: &str,
    filename: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(sender_agent_id, "sender_agent_id")?;
    validate_ascii_line(recipient, "recipient")?;
    validate_ascii_line_opt(declared_mime, "declared_mime")?;
    validate_ascii_line_opt(filename, "filename")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "spize-transfer-intent:{version}\nsender={sender}\nrecipient={recipient}\nsize={size}\nmime={mime}\nfilename={filename}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION,
        sender = sender_agent_id,
        recipient = recipient,
        size = size_bytes,
        mime = declared_mime,
        filename = filename,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by the **control plane** when issuing a data-
/// plane ticket. A ticket is a short-lived capability that authorises
/// the holder to fetch blob bytes from a data-plane server directly,
/// without the control plane proxying the stream.
///
/// Data-plane servers verify the ticket signature against the control
/// plane's published public key (fetched from `/.well-known/spize-cp.pub`
/// or out-of-band) before streaming bytes.
///
/// ```text
/// spize-data-ticket:v1
/// transfer={transfer_id}
/// recipient={recipient_agent_id}
/// data_plane={data_plane_url}
/// expires={expires_unix}
/// nonce={nonce}
/// ```
pub fn data_ticket_bytes(
    transfer_id: &str,
    recipient_agent_id: &str,
    data_plane_url: &str,
    expires_unix: i64,
    nonce: &str,
) -> Result<Vec<u8>> {
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(data_plane_url, "data_plane_url")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "spize-data-ticket:{version}\ntransfer={tx}\nrecipient={rec}\ndata_plane={dp}\nexpires={exp}\nnonce={nonce}",
        version = PROTOCOL_VERSION,
        tx = transfer_id,
        rec = recipient_agent_id,
        dp = data_plane_url,
        exp = expires_unix,
        nonce = nonce,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by the **recipient** when requesting the blob or
/// acknowledging delivery. Binds the recipient's identity to the specific
/// transfer_id and a fresh nonce to prevent replay.
pub fn transfer_receipt_bytes(
    recipient_agent_id: &str,
    transfer_id: &str,
    action: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(action, "action")?;
    validate_nonce(nonce)?;

    if !matches!(action, "download" | "ack" | "inbox" | "request_ticket") {
        return Err(Error::Internal(format!(
            "action must be 'download', 'ack', 'inbox' or 'request_ticket', got {}",
            action
        )));
    }

    let msg = format!(
        "spize-transfer-receipt:{version}\nrecipient={rec}\ntransfer={tx}\naction={act}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION,
        rec = recipient_agent_id,
        tx = transfer_id,
        act = action,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

fn validate_nonce(nonce: &str) -> Result<()> {
    if nonce.len() < MIN_NONCE_LEN || nonce.len() > MAX_NONCE_LEN {
        return Err(Error::Internal(format!(
            "nonce length {} outside [{}, {}]",
            nonce.len(),
            MIN_NONCE_LEN,
            MAX_NONCE_LEN
        )));
    }
    if !nonce.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(Error::Internal("nonce must be hex".into()));
    }
    Ok(())
}

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

    #[test]
    fn canonical_bytes_stable() {
        let bytes = registration_challenge_bytes(
            "aabbcc",
            "acme",
            "alice",
            "0123456789abcdef0123456789abcdef",
            1_700_000_000,
        )
        .unwrap();
        let expected = "spize-register:v1\npub=aabbcc\norg=acme\nname=alice\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn different_inputs_different_bytes() {
        let a = registration_challenge_bytes(
            "aa", "acme", "alice", "0123456789abcdef0123456789abcdef", 100,
        )
        .unwrap();
        let b = registration_challenge_bytes(
            "aa", "acme", "alice", "0123456789abcdef0123456789abcdef", 101,
        )
        .unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn newline_in_field_rejected() {
        let err = registration_challenge_bytes(
            "aa",
            "ac\nme",
            "alice",
            "0123456789abcdef0123456789abcdef",
            100,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn non_ascii_field_rejected() {
        let err = registration_challenge_bytes(
            "aa",
            "acmè",
            "alice",
            "0123456789abcdef0123456789abcdef",
            100,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn short_nonce_rejected() {
        let err = registration_challenge_bytes("aa", "acme", "alice", "deadbeef", 100)
            .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn non_hex_nonce_rejected() {
        let err = registration_challenge_bytes(
            "aa",
            "acme",
            "alice",
            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
            100,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn empty_pub_rejected() {
        let err = registration_challenge_bytes(
            "",
            "acme",
            "alice",
            "0123456789abcdef0123456789abcdef",
            100,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn transfer_intent_stable() {
        let bytes = transfer_intent_bytes(
            "spize:acme/alice:aabbcc",
            "spize:acme/bob:ddeeff",
            12345,
            "application/pdf",
            "invoice.pdf",
            "0123456789abcdef0123456789abcdef",
            1_700_000_000,
        )
        .unwrap();
        let expected = "spize-transfer-intent:v1\nsender=spize:acme/alice:aabbcc\nrecipient=spize:acme/bob:ddeeff\nsize=12345\nmime=application/pdf\nfilename=invoice.pdf\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn transfer_intent_empty_optionals() {
        let bytes = transfer_intent_bytes(
            "spize:acme/alice:aabbcc",
            "bob@example.com",
            100,
            "",
            "",
            "0123456789abcdef0123456789abcdef",
            1_700_000_000,
        )
        .unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.contains("mime=\n"));
        assert!(s.contains("filename=\n"));
    }

    #[test]
    fn transfer_receipt_stable() {
        let bytes = transfer_receipt_bytes(
            "spize:acme/bob:ddeeff",
            "tx_abc123",
            "ack",
            "0123456789abcdef0123456789abcdef",
            1_700_000_000,
        )
        .unwrap();
        let expected = "spize-transfer-receipt:v1\nrecipient=spize:acme/bob:ddeeff\ntransfer=tx_abc123\naction=ack\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn clock_skew_within_window_accepted() {
        let now = 1_700_000_000;
        assert!(is_within_clock_skew(now, now));
        assert!(is_within_clock_skew(now, now - 300));
        assert!(is_within_clock_skew(now, now + 300));
    }

    #[test]
    fn clock_skew_outside_window_rejected() {
        let now = 1_700_000_000;
        assert!(!is_within_clock_skew(now, now - 301));
        assert!(!is_within_clock_skew(now, now + 301));
    }

    #[test]
    fn clock_skew_extreme_inputs_do_not_panic() {
        // Pre-fix: `(now - issued_at).abs()` overflows on these in debug.
        let now = 1_700_000_000;
        assert!(!is_within_clock_skew(now, i64::MIN));
        assert!(!is_within_clock_skew(now, i64::MAX));
        assert!(!is_within_clock_skew(i64::MAX, i64::MIN));
    }

    #[test]
    fn transfer_receipt_rejects_bad_action() {
        let err = transfer_receipt_bytes(
            "spize:acme/bob:ddeeff",
            "tx_abc",
            "overwrite",
            "0123456789abcdef0123456789abcdef",
            1,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn data_ticket_stable() {
        let bytes = data_ticket_bytes(
            "tx_abc123",
            "spize:acme/bob:ddeeff",
            "https://data.spize.ai",
            1_700_000_100,
            "0123456789abcdef0123456789abcdef",
        )
        .unwrap();
        let expected = "spize-data-ticket:v1\ntransfer=tx_abc123\nrecipient=spize:acme/bob:ddeeff\ndata_plane=https://data.spize.ai\nexpires=1700000100\nnonce=0123456789abcdef0123456789abcdef";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn data_ticket_rejects_newline_url() {
        let err = data_ticket_bytes(
            "tx_abc",
            "spize:acme/bob:ddeeff",
            "https://evil.test\nspoof",
            1,
            "0123456789abcdef0123456789abcdef",
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }
}