exochain-api 0.2.7

EXOCHAIN constitutional trust fabric — P2P networking and external API types
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
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
499
500
501
502
503
// Copyright 2026 Exochain Foundation
// SPDX-License-Identifier: Apache-2.0

#![allow(clippy::expect_used, clippy::unwrap_used)]

use ciborium::Value;
use exo_api::crosschecked_anchor::{
    ANCHOR_PATH, AnchorCodecError, CrossCheckedAnchorRequestV1, MAX_REQUEST_BODY_BYTES,
    RequestValidationContext, decode_and_validate_request, decode_unverified_replay_locator,
    validate_preferred_cbor,
};
use exo_core::{crypto::KeyPair, types::Hash256};

type RequestMutation = Box<dyn Fn(&mut CrossCheckedAnchorRequestV1)>;

fn encode(value: &Value) -> Vec<u8> {
    let mut encoded = Vec::new();
    ciborium::into_writer(value, &mut encoded).expect("literal CBOR encodes");
    encoded
}

fn bytes32(byte: u8) -> [u8; 32] {
    [byte; 32]
}

fn independently_derive_idempotency(
    authority_did: &str,
    grant_id: [u8; 32],
    scope_alias: [u8; 32],
    action_hash: [u8; 32],
) -> [u8; 32] {
    let bytes = encode(&Value::Array(vec![
        Value::Text("exo.crosschecked.anchor_idempotency.v1".to_owned()),
        Value::Text(authority_did.to_owned()),
        Value::Bytes(grant_id.to_vec()),
        Value::Bytes(scope_alias.to_vec()),
        Value::Bytes(action_hash.to_vec()),
    ]));
    *blake3::hash(&bytes).as_bytes()
}

fn unsigned_request() -> CrossCheckedAnchorRequestV1 {
    let authority_did = "did:exo:crosschecked-fixture-authority".to_owned();
    let grant_id = bytes32(0x31);
    let scope_alias = bytes32(0x42);
    let action_hash = bytes32(0x53);
    CrossCheckedAnchorRequestV1 {
        protocol_version: 1,
        source_code: "crosschecked".to_owned(),
        receipt_format: "action_receipt_v3".to_owned(),
        audience: "crosschecked.production".to_owned(),
        authority_key_id: format!("{authority_did}#anchor-2026"),
        authority_did: authority_did.clone(),
        grant_id,
        scope_alias,
        action_hash_algorithm: "blake3-256".to_owned(),
        action_hash,
        idempotency_key: independently_derive_idempotency(
            &authority_did,
            grant_id,
            scope_alias,
            action_hash,
        ),
        nonce: bytes32(0x64),
        issued_at_ms: 1_800_000_000_000,
        expires_at_ms: 1_800_000_300_000,
        signature_algorithm: "ed25519".to_owned(),
        signature: [0; 64],
    }
}

fn sign_request(request: &mut CrossCheckedAnchorRequestV1, key: &KeyPair) {
    request.signature = *key
        .sign(&request.signing_preimage().expect("signing preimage"))
        .ed25519_bytes()
        .expect("Ed25519 signature");
}

fn context<'a>(key: &'a KeyPair, now_ms: u64) -> RequestValidationContext<'a> {
    RequestValidationContext {
        method: "POST",
        path: ANCHOR_PATH,
        content_type: "application/cbor",
        expected_audience: "crosschecked.production",
        now_ms,
        authority_public_key: key.public_key(),
    }
}

fn canonicalize(value: &mut Value) {
    match value {
        Value::Array(values) => values.iter_mut().for_each(canonicalize),
        Value::Map(entries) => {
            for (key, value) in entries.iter_mut() {
                canonicalize(key);
                canonicalize(value);
            }
            entries.sort_by(|(left, _), (right, _)| {
                let left = encode(left);
                let right = encode(right);
                left.len().cmp(&right.len()).then_with(|| left.cmp(&right))
            });
        }
        _ => {}
    }
}

fn encode_canonical(mut value: Value) -> Vec<u8> {
    canonicalize(&mut value);
    encode(&value)
}

fn signed_body(request: &mut CrossCheckedAnchorRequestV1, key: &KeyPair) -> Vec<u8> {
    sign_request(request, key);
    request.to_canonical_cbor().expect("request body")
}

fn assert_rejected_after_resigning(
    mut request: CrossCheckedAnchorRequestV1,
    key: &KeyPair,
    now_ms: u64,
) {
    let body = signed_body(&mut request, key);
    assert!(decode_and_validate_request(&body, context(key, now_ms)).is_err());
}

fn refresh_idempotency(request: &mut CrossCheckedAnchorRequestV1) {
    request.idempotency_key = independently_derive_idempotency(
        &request.authority_did,
        request.grant_id,
        request.scope_alias,
        request.action_hash,
    );
}

#[test]
fn exact_request_preimage_and_complete_body_hash_are_verified() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let mut request = unsigned_request();
    let expected_preimage = encode(&Value::Array(vec![
        Value::Text("exo.crosschecked.anchor_request.v1".to_owned()),
        Value::Text("POST".to_owned()),
        Value::Text(ANCHOR_PATH.to_owned()),
        Value::Integer(1.into()),
        Value::Text("crosschecked".to_owned()),
        Value::Text("action_receipt_v3".to_owned()),
        Value::Text("crosschecked.production".to_owned()),
        Value::Text("did:exo:crosschecked-fixture-authority".to_owned()),
        Value::Text("did:exo:crosschecked-fixture-authority#anchor-2026".to_owned()),
        Value::Bytes(bytes32(0x31).to_vec()),
        Value::Bytes(bytes32(0x42).to_vec()),
        Value::Text("blake3-256".to_owned()),
        Value::Bytes(bytes32(0x53).to_vec()),
        Value::Bytes(request.idempotency_key.to_vec()),
        Value::Bytes(bytes32(0x64).to_vec()),
        Value::Integer(1_800_000_000_000_u64.into()),
        Value::Integer(1_800_000_300_000_u64.into()),
        Value::Text("ed25519".to_owned()),
    ]));

    assert_eq!(
        request.signing_preimage().expect("preimage"),
        expected_preimage
    );
    sign_request(&mut request, &key);

    let body = request.to_canonical_cbor().expect("canonical request");
    assert!(body.len() <= MAX_REQUEST_BODY_BYTES);
    let validated = decode_and_validate_request(
        &body,
        RequestValidationContext {
            method: "POST",
            path: ANCHOR_PATH,
            content_type: "application/cbor",
            expected_audience: "crosschecked.production",
            now_ms: 1_800_000_000_000,
            authority_public_key: key.public_key(),
        },
    )
    .expect("valid signed request");

    assert_eq!(validated.request, request);
    assert_eq!(validated.canonical_body, body);
    assert_eq!(validated.request_hash, Hash256::digest(&body));
}

#[test]
fn replay_locator_parses_only_a_canonical_static_request_without_authorizing_it() {
    let authority_key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let wrong_key = KeyPair::from_secret_bytes([0x18; 32]).expect("wrong key");
    let mut request = unsigned_request();
    sign_request(&mut request, &wrong_key);
    let body = request.to_canonical_cbor().expect("canonical body");

    let locator = decode_unverified_replay_locator(&body, "POST", ANCHOR_PATH, "application/cbor")
        .expect("canonical static envelope can be located after expiry");

    assert_eq!(locator.source_code, "crosschecked");
    assert_eq!(locator.authority_did, request.authority_did);
    assert_eq!(locator.authority_key_id, request.authority_key_id);
    assert_eq!(locator.idempotency_key, request.idempotency_key);
    assert_eq!(locator.action_hash, request.action_hash);
    assert_eq!(locator.request_hash, Hash256::digest(&body));
    assert_eq!(locator.issued_at_ms, request.issued_at_ms);
    assert_eq!(locator.expires_at_ms, request.expires_at_ms);

    assert_eq!(
        decode_and_validate_request(
            &body,
            context(&authority_key, request.expires_at_ms.saturating_add(1))
        ),
        Err(AnchorCodecError::InvalidValidity),
        "the unverified locator must not be confused with live authorization"
    );
}

#[test]
fn replay_locator_rejects_noncanonical_or_statically_invalid_requests() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let mut request = unsigned_request();
    request.idempotency_key[0] ^= 1;
    let body = signed_body(&mut request, &key);
    assert_eq!(
        decode_unverified_replay_locator(&body, "POST", ANCHOR_PATH, "application/cbor"),
        Err(AnchorCodecError::IdempotencyMismatch)
    );

    let mut request = unsigned_request();
    let body = signed_body(&mut request, &key);
    assert_eq!(
        decode_unverified_replay_locator(&body, "GET", ANCHOR_PATH, "application/cbor"),
        Err(AnchorCodecError::InvalidContext("method"))
    );

    let mut trailing = body;
    trailing.push(0);
    assert!(
        decode_unverified_replay_locator(&trailing, "POST", ANCHOR_PATH, "application/cbor")
            .is_err()
    );
}

#[test]
fn every_request_field_is_closed_and_validated_independently_of_signature() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let now = 1_800_000_000_000;

    let mut mutations: Vec<RequestMutation> = vec![
        Box::new(|request| request.protocol_version = 2),
        Box::new(|request| request.source_code = "other".to_owned()),
        Box::new(|request| request.receipt_format = "action_receipt_v2".to_owned()),
        Box::new(|request| request.audience = "UPPERCASE".to_owned()),
        Box::new(|request| request.authority_did = "did:web:invalid".to_owned()),
        Box::new(|request| request.authority_key_id.push('!')),
        Box::new(|request| request.grant_id = [0; 32]),
        Box::new(|request| request.scope_alias = [0; 32]),
        Box::new(|request| request.action_hash_algorithm = "sha256".to_owned()),
        Box::new(|request| request.action_hash = [0; 32]),
        Box::new(|request| request.idempotency_key[0] ^= 1),
        Box::new(|request| request.nonce = [0; 32]),
        Box::new(move |request| {
            request.issued_at_ms = now + 60_001;
            request.expires_at_ms = request.issued_at_ms + 1;
        }),
        Box::new(|request| request.expires_at_ms = request.issued_at_ms),
        Box::new(|request| request.signature_algorithm = "other".to_owned()),
    ];

    for mutate in mutations.drain(..) {
        let mut request = unsigned_request();
        mutate(&mut request);
        assert_rejected_after_resigning(request, &key, now);
    }

    let mut request = unsigned_request();
    let body = signed_body(&mut request, &key);
    let mut value: Value = ciborium::from_reader(body.as_slice()).expect("request map");
    let Value::Map(entries) = &mut value else {
        panic!("request is a map");
    };
    let (_, Value::Bytes(signature)) = entries
        .iter_mut()
        .find(|(field, _)| field == &Value::Text("signature".to_owned()))
        .expect("signature field")
    else {
        panic!("signature is bytes");
    };
    signature[0] ^= 1;
    let body = encode_canonical(value);
    assert_eq!(
        decode_and_validate_request(&body, context(&key, now)),
        Err(AnchorCodecError::InvalidSignature)
    );
}

#[test]
fn request_time_and_body_boundaries_are_exact() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let now = 1_800_000_000_000;

    let mut request = unsigned_request();
    request.issued_at_ms = now + 60_000;
    request.expires_at_ms = request.issued_at_ms + 300_000;
    let body = signed_body(&mut request, &key);
    decode_and_validate_request(&body, context(&key, now)).expect("inclusive boundaries");

    let mut request = unsigned_request();
    request.issued_at_ms = now + 60_001;
    request.expires_at_ms = request.issued_at_ms + 300_000;
    assert_rejected_after_resigning(request, &key, now);

    let mut request = unsigned_request();
    request.expires_at_ms = request.issued_at_ms + 300_001;
    assert_rejected_after_resigning(request, &key, now);

    assert_ne!(
        decode_and_validate_request(&vec![0; MAX_REQUEST_BODY_BYTES], context(&key, now)),
        Err(AnchorCodecError::InvalidBodyLength)
    );
    assert_eq!(
        decode_and_validate_request(&vec![0; MAX_REQUEST_BODY_BYTES + 1], context(&key, now)),
        Err(AnchorCodecError::InvalidBodyLength)
    );
}

#[test]
fn transport_binding_is_exact() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let now = 1_800_000_000_000;
    let mut request = unsigned_request();
    let body = signed_body(&mut request, &key);

    for invalid in [
        RequestValidationContext {
            method: "GET",
            ..context(&key, now)
        },
        RequestValidationContext {
            path: "/api/v1/anchors/crosschecked/",
            ..context(&key, now)
        },
        RequestValidationContext {
            content_type: "application/cbor; charset=utf-8",
            ..context(&key, now)
        },
        RequestValidationContext {
            expected_audience: "crosschecked.staging",
            ..context(&key, now)
        },
    ] {
        assert!(decode_and_validate_request(&body, invalid).is_err());
    }
}

#[test]
fn request_map_rejects_missing_unknown_nontext_and_wrong_types() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let now = 1_800_000_000_000;
    let mut request = unsigned_request();
    let body = signed_body(&mut request, &key);
    let Value::Map(entries) =
        ciborium::from_reader::<Value, _>(body.as_slice()).expect("decode baseline")
    else {
        panic!("request is a map");
    };

    let mut missing = entries.clone();
    missing.pop();
    let missing = encode_canonical(Value::Map(missing));
    assert!(decode_and_validate_request(&missing, context(&key, now)).is_err());

    let mut unknown = entries.clone();
    let (_, value) = unknown.pop().expect("one field");
    unknown.push((Value::Text("unknown".to_owned()), value));
    let unknown = encode_canonical(Value::Map(unknown));
    assert!(decode_and_validate_request(&unknown, context(&key, now)).is_err());

    let mut nontext = entries.clone();
    nontext[0].0 = Value::Integer(7.into());
    let nontext = encode_canonical(Value::Map(nontext));
    assert!(decode_and_validate_request(&nontext, context(&key, now)).is_err());

    for field in [
        "protocol_version",
        "source_code",
        "receipt_format",
        "audience",
        "authority_did",
        "authority_key_id",
        "grant_id",
        "scope_alias",
        "action_hash_algorithm",
        "action_hash",
        "idempotency_key",
        "nonce",
        "issued_at_ms",
        "expires_at_ms",
        "signature_algorithm",
        "signature",
    ] {
        let mut wrong = entries.clone();
        let (_, value) = wrong
            .iter_mut()
            .find(|(key, _)| key == &Value::Text(field.to_owned()))
            .expect("field exists");
        *value = Value::Null;
        let wrong = encode_canonical(Value::Map(wrong));
        assert!(decode_and_validate_request(&wrong, context(&key, now)).is_err());
    }
}

#[test]
fn audience_did_and_key_id_length_boundaries_are_exact() {
    let key = KeyPair::from_secret_bytes([0x17; 32]).expect("fixed key");
    let now = 1_800_000_000_000;

    let mut request = unsigned_request();
    request.audience = "a".repeat(128);
    let expected_audience = request.audience.clone();
    let body = signed_body(&mut request, &key);
    decode_and_validate_request(
        &body,
        RequestValidationContext {
            expected_audience: &expected_audience,
            ..context(&key, now)
        },
    )
    .expect("128-byte audience");

    let mut request = unsigned_request();
    request.audience = "a".repeat(129);
    let expected_audience = request.audience.clone();
    let body = signed_body(&mut request, &key);
    assert!(
        decode_and_validate_request(
            &body,
            RequestValidationContext {
                expected_audience: &expected_audience,
                ..context(&key, now)
            }
        )
        .is_err()
    );

    let mut request = unsigned_request();
    request.authority_did = format!("did:exo:{}", "a".repeat(248));
    request.authority_key_id = format!("{}#{}", request.authority_did, "z".repeat(64));
    refresh_idempotency(&mut request);
    let body = signed_body(&mut request, &key);
    decode_and_validate_request(&body, context(&key, now))
        .expect("256-byte DID and 64-byte key fragment");

    let mut request = unsigned_request();
    request.authority_did = format!("did:exo:{}", "a".repeat(249));
    request.authority_key_id = format!("{}#key", request.authority_did);
    refresh_idempotency(&mut request);
    assert_rejected_after_resigning(request, &key, now);

    let mut request = unsigned_request();
    request.authority_key_id = format!("{}#{}", request.authority_did, "z".repeat(65));
    assert_rejected_after_resigning(request, &key, now);
}

#[test]
fn deterministic_cbor_validator_rejects_all_ambiguous_forms() {
    for valid in [
        vec![0x00],
        vec![0x17],
        vec![0x18, 0x18],
        vec![0x82, 0x01, 0x02],
        vec![0xa2, 0x61, b'a', 0x01, 0x61, b'b', 0x02],
    ] {
        validate_preferred_cbor(&valid).expect("preferred CBOR");
    }

    let mut depth_33 = vec![0x81; 33];
    depth_33.push(0x00);
    let invalid = [
        vec![],
        vec![0x00, 0x00],
        vec![0x18, 0x01],
        vec![0x19, 0x00, 0xff],
        vec![0x1a, 0x00, 0x00, 0xff, 0xff],
        vec![0x1b, 0, 0, 0, 0, 0, 0, 0, 1],
        vec![0x5f, 0xff],
        vec![0x9f, 0xff],
        vec![0xc0, 0xf6],
        vec![0xf7],
        vec![0xf8, 0x14],
        vec![0xf9, 0x00, 0x00],
        vec![0xa2, 0x61, b'b', 0x01, 0x61, b'a', 0x02],
        vec![0xa2, 0x61, b'a', 0x01, 0x61, b'a', 0x02],
        vec![0x61, 0xff],
        vec![0x58],
        depth_33,
    ];
    for bytes in invalid {
        assert!(
            validate_preferred_cbor(&bytes).is_err(),
            "accepted {bytes:02x?}"
        );
    }
}