heddle-thread-api 0.28.10

Native Thread clients and durable peer replication over Iroh
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use std::collections::BTreeSet;

use biscuit_verifier::signature_v1::BiscuitBuilderV1Ext;
use crypto::{Ed25519Signer, Signer};
use objects::object::{
    CollaborationActor, ContentHash,
    original_boundary_acceptance::{
        AdmissionBasis, BoundaryOriginalKind, OriginalBoundaryAcceptance, OriginalManifestEntry,
        OriginalPublicationManifest, PublicationIntent,
    },
    thread_authority_admission::{OriginalAuthoritySubject, ThreadAuthorityAdmission},
    thread_genesis_admission::ThreadGenesisAdmission,
    thread_replication::SourceAuthor,
};

use super::*;

fn signer(role: &str) -> Ed25519Signer {
    Ed25519Signer::from_seed(
        &hex::decode(fixture()["keys"][role]["seed_hex"].as_str().expect("seed")).expect("hex"),
    )
    .expect("signer")
}

fn signed_record(
    format: &str,
    canonical: Vec<u8>,
    signature: Vec<u8>,
    key: &[u8],
) -> wire::SignedRecord {
    wire::SignedRecord {
        format: format.into(),
        canonical_record: canonical,
        signatures: vec![wire::RecordSignature {
            public_key: key.to_vec(),
            signature,
        }],
    }
}

/// Genuine owner-attached mint root, publisher and credential all differ from
/// the retained offline author. Both P1 and P2 keep the exact original bytes.
fn boundary_bundle(source: bool) -> wire::NativePublicProofBundleV1 {
    let mut bundle: wire::NativePublicProofBundleV1 = record(
        &fixture(),
        if source {
            "account_source"
        } else {
            "start_thread"
        },
    );
    let template: wire::NativePublicProofBundleV1 = record(&fixture(), "boundary_acceptance");
    let mut boundary = template.genesis_witnesses[0]
        .boundary_acceptance
        .clone()
        .expect("boundary");
    let original = bundle.genesis_witnesses[0]
        .original_genesis
        .as_ref()
        .expect("genesis");
    let (_, genesis) = verify::verify_native_genesis(original).expect("original signature");
    let entry = OriginalManifestEntry::from_genesis(
        &genesis,
        &bundle.genesis_witnesses[0].creator_authority_envelope,
    )
    .expect("original identity");
    let actor = entry.authority.as_ref().expect("account").actor.clone();
    let mut entries = vec![entry];
    if source {
        let (_, operation) = verify::verify_native_operation(
            bundle.authority_witnesses[0]
                .original
                .as_ref()
                .expect("source"),
        )
        .expect("original source signature");
        entries.push(OriginalManifestEntry::from_operation(&operation).expect("source identity"));
    }
    let manifest = OriginalPublicationManifest::new(entries).expect("manifest");
    let intent = PublicationIntent::decode(&boundary.publication_intent).expect("intent");
    assert_eq!(intent.thread, genesis.id().expect("Thread"));
    let publisher = Ed25519Signer::from_seed(&[61; 32]).expect("accepting publisher");
    let mint = Ed25519Signer::from_seed(&[62; 32]).expect("accepting mint root");
    let original_envelope: wire::ThreadControlAuthority = hybrid_codec::strict_decode(
        &bundle.genesis_witnesses[0].creator_authority_envelope,
        65536,
    )
    .expect("original envelope");
    let owner = original_envelope.owner.as_ref().expect("owner");
    let current =
        heddleco_capability_verifier::verify_owner_root(owner.root.as_ref().expect("root"))
            .expect("owner");
    let attachment = wire::MintRootAttachment {
        format_version: 1,
        account_uuid: actor.principal_id.as_bytes().to_vec(),
        owner_state_hash: current.state_hash().to_vec(),
        owner_sequence: current.sequence(),
        owner_key: Some(current.authority_key().clone()),
        mint_root_key: Some(repo::ed25519_verification_key(mint.public_key()).expect("mint key")),
        not_before_unix_seconds: 1000,
        expires_at_unix_seconds: 3600,
        nonce: vec![63; 32],
    };
    let association = wire::SignedOwnerMintRootAttachment {
        owner_signature: Some(wire::AuthorizationSignature {
            signer_key_id: hybrid_codec::key_id(signer("owner").public_key()),
            signature: signer("owner")
                .sign(
                    &heddleco_capability_verifier::creation::mint_root_signing_digest(&attachment)
                        .expect("attachment digest"),
                )
                .expect("owner signature"),
        }),
        attachment: Some(attachment),
    };
    let key = biscuit_auth::KeyPair::from(
        &biscuit_auth::PrivateKey::from_bytes(&[62; 32], biscuit_auth::Algorithm::Ed25519)
            .expect("mint key"),
    );
    let token = biscuit_auth::Biscuit::builder().code(format!(
        "user(\"{}\"); session(\"boundary-acceptor\"); credential_id(\"boundary-credential\"); device_pop_key(\"{}\"); check if operation(\"StartThread\") or operation(\"PublishContent\"); check if resource(\"spool\", \"acme/imports\"); check if time($now), $now < 1970-01-01T01:00:00Z;",
        actor.principal_id, hex::encode(publisher.public_key()),
    )).expect("acceptor restrictions").build_v1(&key).expect("credential");
    let envelope = heddleco_capability_verifier::thread_control_authority::encode(
        owner,
        mint.public_key(),
        Some(
            wire::thread_control_authority::MintRootAssociation::OwnerMintRootAttachment(
                association,
            ),
        ),
        &token,
    )
    .expect("sealed acceptance authority");
    let acceptance = OriginalBoundaryAcceptance {
        version: 1,
        publication_intent: intent.id().expect("intent ID"),
        originals_manifest: manifest.id().expect("manifest ID"),
        original_account: actor.principal_id,
        kinds: if source {
            BTreeSet::from([
                BoundaryOriginalKind::AccountGenesis,
                BoundaryOriginalKind::Source,
            ])
        } else {
            BTreeSet::from([BoundaryOriginalKind::AccountGenesis])
        },
        accepting_publisher: publisher.public_key().try_into().expect("publisher"),
        accepting_author: SourceAuthor::account(
            intent.spool,
            CollaborationActor {
                principal_id: actor.principal_id,
                agent_id: None,
            },
            envelope,
        )
        .expect("acceptor"),
    };
    let signed = crypto::original_boundary_acceptance::SignedBoundaryAcceptance::sign(
        &acceptance,
        &publisher,
    )
    .expect("distinct acceptance signature");
    boundary.signed_acceptance = Some(signed_record(
        objects::object::original_boundary_acceptance::FORMAT,
        signed.canonical,
        signed.signature,
        publisher.public_key(),
    ));
    boundary.originals_manifest = manifest.encode().expect("manifest");
    let witness = signer("witness");
    boundary.original_receipts.clear();
    for entry in &manifest.entries {
        let identity = entry.authority.as_ref().expect("account original");
        let basis = AdmissionBasis::BoundaryAcceptance {
            acceptance: acceptance.id().expect("acceptance ID"),
        };
        let receipt = match &entry.subject {
            objects::object::original_boundary_acceptance::ManifestSubject::Genesis(_) => {
                let receipt = ThreadGenesisAdmission {
                    version: 2,
                    basis,
                    spool: intent.spool,
                    spool_genesis: intent.spool_genesis,
                    thread: entry.thread,
                    owner: identity.actor.principal_id,
                    creator: entry.publisher,
                    authority_digest: ContentHash::compute_typed(
                        objects::object::thread_genesis_admission::ENVELOPE_FORMAT,
                        &bundle.genesis_witnesses[0].creator_authority_envelope,
                    ),
                    executor: witness.public_key().try_into().expect("executor"),
                    admitted_at_ms: 1_100_000,
                };
                let signed = crypto::thread_genesis_admission::SignedGenesisAdmission::sign(
                    &receipt, &witness,
                )
                .expect("receipt");
                signed_record(
                    objects::object::thread_genesis_admission::FORMAT,
                    signed.canonical,
                    signed.signature,
                    witness.public_key(),
                )
            }
            objects::object::original_boundary_acceptance::ManifestSubject::Source(id) => {
                let receipt = ThreadAuthorityAdmission {
                    version: 3,
                    basis,
                    spool: intent.spool,
                    spool_genesis: intent.spool_genesis,
                    thread: entry.thread,
                    subject: OriginalAuthoritySubject::Operation(*id),
                    actor: identity.actor.clone(),
                    publisher: entry.publisher,
                    authority_digest: identity.authority_digest,
                    executor: witness.public_key().try_into().expect("executor"),
                    admitted_at_ms: 1_100_000,
                };
                let signed = crypto::thread_authority_admission::SignedAuthorityAdmission::sign(
                    &receipt, &witness,
                )
                .expect("receipt");
                signed_record(
                    objects::object::thread_authority_admission::FORMAT,
                    signed.canonical,
                    signed.signature,
                    witness.public_key(),
                )
            }
            _ => panic!("genesis/source fixture"),
        };
        boundary.original_receipts.push(receipt);
    }
    boundary
        .original_receipts
        .sort_by_key(|r| api::import_authority::signed_native_digest(r).expect("receipt digest"));
    let binding = boundary.binding.as_mut().expect("binding");
    binding.acceptance_id = acceptance.id().expect("ID").as_bytes().to_vec();
    binding.signed_acceptance_digest = api::import_authority::signed_native_digest(
        boundary.signed_acceptance.as_ref().expect("acceptance"),
    )
    .expect("digest");
    binding.originals_manifest_digest = api::import_authority::boundary_octets_digest(
        "heddle-boundary-originals-manifest-v1",
        &boundary.originals_manifest,
    );
    binding.original_receipt_digests = boundary
        .original_receipts
        .iter()
        .map(|r| api::import_authority::signed_native_digest(r).expect("digest"))
        .collect();
    api::import_authority::verify_boundary_acceptance(&boundary).expect("complete exact evidence");
    let old_genesis = hybrid_codec::canonical(&bundle.genesis_witnesses[0]).expect("payload");
    bundle.genesis_witnesses[0].boundary_acceptance = Some(boundary.clone());
    for signed in &mut bundle.statements {
        let body = signed.body.as_mut().expect("statement");
        if body.purpose == 1 {
            assert_eq!(body.canonical_payload, old_genesis);
            body.canonical_payload =
                hybrid_codec::canonical(&bundle.genesis_witnesses[0]).expect("payload");
        } else {
            let payload = bundle
                .authority_witnesses
                .iter_mut()
                .find(|p| hybrid_codec::canonical(*p).expect("payload") == body.canonical_payload)
                .expect("source payload");
            payload.boundary_acceptances = vec![boundary.clone()];
            body.canonical_payload = hybrid_codec::canonical(payload).expect("payload");
        }
        body.basis = 2;
        body.boundary_acceptance = boundary.binding.clone();
    }
    resign_statements(&mut bundle);
    bundle
}

fn resign_statements(bundle: &mut wire::NativePublicProofBundleV1) {
    for signed in &mut bundle.statements {
        signed.signature = signer("witness")
            .sign(
                &witness_trust::statement_signing_digest(signed.body.as_ref().expect("body"))
                    .expect("digest"),
            )
            .expect("signature");
    }
    bundle.statements.sort_by_key(|s| {
        witness_trust::statement_signing_digest(s.body.as_ref().expect("body")).expect("digest")
    });
}

fn revoke(bundle: &mut wire::NativePublicProofBundleV1, key: &[u8]) {
    let policy = &mut bundle.policies[0];
    let body = policy.body.as_mut().expect("policy");
    body.policy.as_mut().expect("policy").revoked_key_ids = vec![hybrid_codec::key_id(key)];
    body.policy_state_hash = heddleco_capability_verifier::policy::policy_state_hash(body)
        .expect("hash")
        .to_vec();
    policy.owner_signature = Some(wire::AuthorizationSignature {
        signer_key_id: hybrid_codec::key_id(signer("owner").public_key()),
        signature: signer("owner")
            .sign(
                &heddleco_capability_verifier::policy::policy_signature_digest(body)
                    .expect("digest"),
            )
            .expect("signature"),
    });
    for signed in &mut bundle.statements {
        signed.body.as_mut().expect("body").policy_state_hash = body.policy_state_hash.clone();
    }
    resign_statements(bundle);
}

#[test]
fn native_boundary_genesis_fresh_receiver_retains_accepting_authority() {
    let bundle = boundary_bundle(false);
    let originals = vec![
        bundle.genesis_witnesses[0]
            .original_genesis
            .clone()
            .expect("genesis"),
    ];
    local_work::install_bundle("distinct genesis acceptor", bundle, &originals, None);
}

#[test]
fn native_boundary_source_fresh_receiver_retains_accepting_authority() {
    let bundle = boundary_bundle(true);
    let originals = vec![
        bundle.authority_witnesses[0]
            .original
            .clone()
            .expect("source"),
    ];
    local_work::install_bundle("distinct source acceptor", bundle, &originals, None);
}

#[test]
fn native_boundary_acceptor_publisher_and_mint_revocations_reject() {
    for seed in [61, 62] {
        let mut bundle = boundary_bundle(true);
        revoke(
            &mut bundle,
            Ed25519Signer::from_seed(&[seed; 32])
                .expect("acceptor key")
                .public_key(),
        );
        let error = verify_semantics(&bundle, 1_100_000).expect_err("revoked acceptor");
        assert!(
            error
                .to_string()
                .contains("mint root or publisher is revoked"),
            "{error}"
        );
    }
}

#[test]
fn native_boundary_revoked_original_keeps_provenance_and_signatures() {
    let mut bundle = boundary_bundle(true);
    let original = bundle.genesis_witnesses[0]
        .original_genesis
        .clone()
        .expect("original");
    // native-host-witness.md:131–135: "The original binding/envelope and original
    // creator signature remain mandatory." "Never assert historical non-revocation"
    revoke(&mut bundle, &original.signatures[0].public_key);
    verify_semantics(&bundle, 1_100_000).expect("revocation does not erase original provenance");
    let sources = vec![
        bundle.authority_witnesses[0]
            .original
            .clone()
            .expect("source"),
    ];
    local_work::install_bundle("revoked original", bundle.clone(), &sources, None);
    assert_eq!(bundle.genesis_witnesses[0].original_genesis, Some(original));
    for purpose in [1, 2] {
        let mut forged = bundle.clone();
        let record = if purpose == 1 {
            forged.genesis_witnesses[0]
                .original_genesis
                .as_mut()
                .expect("genesis")
        } else {
            forged.authority_witnesses[0]
                .original
                .as_mut()
                .expect("source")
        };
        record.signatures[0].signature[0] ^= 1;
        assert!(
            verify_semantics(&forged, 1_100_000).is_err(),
            "original signature remains mandatory"
        );
    }
}

#[test]
fn ordinary_native_p1_p2_revocations_still_reject() {
    use heddleco_capability_verifier::thread_control_authority::Revocation;

    use crate::hybrid::authority::tests::{bundle as imported, selected};

    for name in ["start_thread", "account_source"] {
        let mut bundle: wire::NativePublicProofBundleV1 = record(&fixture(), name);
        verify_semantics(&bundle, 1_100_000).expect("ordinary control");
        let publisher = bundle.genesis_witnesses[0]
            .original_genesis
            .as_ref()
            .expect("original")
            .signatures[0]
            .public_key
            .clone();
        revoke(&mut bundle, &publisher);
        let limits = heddleco_capability_verifier::VerificationLimits::new(3600).expect("limits");
        let history = AcceptedHistory::from_native_spool(
            &bundle,
            &selected(&imported(), limits),
            1100,
            limits,
        )
        .expect("selected lineage");
        let authority = SelectedAuthority::new_native(
            history,
            bundle.clone(),
            |_: &wire::NativePublicProofBundleV1,
             _: i64,
             _: &repo::thread_replication::hosted_trust::TrustTransaction<'_>| Ok(()),
        );
        for statement in bundle
            .statements
            .iter()
            .map(|s| s.body.as_ref().expect("body"))
        {
            assert!(
                authority.native_revoked(statement, Revocation::Publisher(&publisher)),
                "purpose {}",
                statement.purpose
            );
        }
        assert!(
            verify_semantics(&bundle, 1_100_000).is_err(),
            "ordinary revocation still rejects"
        );
    }
}

#[test]
fn native_boundary_revocation_selects_exact_acceptor_credential_identities() {
    use heddleco_capability_verifier::thread_control_authority::Revocation;

    use crate::hybrid::authority::tests::{bundle as imported, selected};

    let bundle = boundary_bundle(true);
    let limits = heddleco_capability_verifier::VerificationLimits::new(3600).expect("limits");
    let history =
        AcceptedHistory::from_native_spool(&bundle, &selected(&imported(), limits), 1100, limits)
            .expect("selected lineage");
    let authority = SelectedAuthority::new_native(
        history,
        bundle.clone(),
        |_: &wire::NativePublicProofBundleV1,
         _: i64,
         _: &repo::thread_replication::hosted_trust::TrustTransaction<'_>| Ok(()),
    );
    let acceptance = OriginalBoundaryAcceptance::decode(
        bundle.genesis_witnesses[0]
            .boundary_acceptance
            .as_ref()
            .expect("boundary")
            .signed_acceptance
            .as_ref()
            .expect("acceptance")
            .canonical_record
            .as_slice(),
    )
    .expect("acceptance");
    let SourceAuthor::Account {
        authority: envelope,
        ..
    } = acceptance.accepting_author
    else {
        panic!("account");
    };
    let envelope: wire::ThreadControlAuthority =
        hybrid_codec::strict_decode(&envelope, 65536).expect("envelope");
    let root = biscuit_verifier::parse_ed25519_public_keys_hex(
        &hex::encode(&envelope.mint_root_public_key),
        1,
    )
    .expect("mint root")[0];
    let token = biscuit_verifier::signature_v1::verify(&envelope.sealed_biscuit, root)
        .expect("signed credential");
    let facts = biscuit_verifier::inspect_verified_credential(&token, &root).expect("identities");
    assert!(
        !facts.revocation_ids.is_empty(),
        "signed-block identities are exercised"
    );
    let original_envelope: wire::ThreadControlAuthority = hybrid_codec::strict_decode(
        &bundle.genesis_witnesses[0].creator_authority_envelope,
        65536,
    )
    .expect("original envelope");
    let original_root = biscuit_verifier::parse_ed25519_public_keys_hex(
        &hex::encode(&original_envelope.mint_root_public_key),
        1,
    )
    .expect("original root")[0];
    let original_token =
        biscuit_verifier::signature_v1::verify(&original_envelope.sealed_biscuit, original_root)
            .expect("original credential signature");
    let original_facts =
        biscuit_verifier::inspect_verified_credential(&original_token, &original_root)
            .expect("original identities");
    for statement in bundle
        .statements
        .iter()
        .map(|s| s.body.as_ref().expect("body"))
    {
        assert!(!authority.native_revoked(
            statement,
            Revocation::MintRoot(&envelope.mint_root_public_key)
        ));
        assert!(!authority.native_revoked(
            statement,
            Revocation::Publisher(&acceptance.accepting_publisher)
        ));
        for id in facts.revocation_identities() {
            assert!(
                !authority.native_revoked(statement, Revocation::Credential(id)),
                "{id}"
            );
        }
        for id in original_facts.revocation_identities() {
            assert!(
                authority.native_revoked(statement, Revocation::Credential(id)),
                "original {id} is provenance only"
            );
        }
        assert!(authority.native_revoked(statement, Revocation::Credential("unrelated-session")));
        assert!(authority.native_revoked(
            statement,
            Revocation::Publisher(signer("device").public_key())
        ));
        assert!(authority.native_revoked(
            statement,
            Revocation::MintRoot(signer("device").public_key())
        ));
    }
}

#[test]
fn native_boundary_forged_acceptor_key_outside_acceptance_signature_rejects() {
    let mut bundle = boundary_bundle(true);
    let old = hybrid_codec::canonical(&bundle.genesis_witnesses[0]).expect("payload");
    let mut boundary = bundle.genesis_witnesses[0]
        .boundary_acceptance
        .clone()
        .expect("boundary");
    let signed = boundary.signed_acceptance.as_mut().expect("acceptance");
    let wrong = Ed25519Signer::from_seed(&[64; 32]).expect("unrelated signer");
    let bytes = [signed.format.as_bytes(), b"\0", &signed.canonical_record].concat();
    signed.signatures[0].public_key = wrong.public_key().to_vec();
    signed.signatures[0].signature = wrong.sign(&bytes).expect("valid wrong-key signature");
    boundary
        .binding
        .as_mut()
        .expect("binding")
        .signed_acceptance_digest =
        api::import_authority::signed_native_digest(signed).expect("digest");
    // The portable framing gate authenticates the supplied signature, while
    // native selection must also bind that key to the canonical acceptor.
    api::import_authority::verify_boundary_acceptance(&boundary)
        .expect("valid transport signature");
    bundle.genesis_witnesses[0].boundary_acceptance = Some(boundary.clone());
    for signed in &mut bundle.statements {
        let body = signed.body.as_mut().expect("body");
        if body.purpose == 1 {
            assert_eq!(body.canonical_payload, old);
            body.canonical_payload =
                hybrid_codec::canonical(&bundle.genesis_witnesses[0]).expect("payload");
        } else {
            let payload = &mut bundle.authority_witnesses[0];
            payload.boundary_acceptances = vec![boundary.clone()];
            body.canonical_payload = hybrid_codec::canonical(payload).expect("payload");
        }
        body.boundary_acceptance = boundary.binding.clone();
    }
    resign_statements(&mut bundle);
    assert!(
        verify_semantics(&bundle, 1_100_000).is_err(),
        "acceptor must sign its own acceptance"
    );
    use crate::hybrid::authority::PublicEvidence;
    for statement in &bundle.statements {
        assert!(
            bundle
                .native_authorities(statement.body.as_ref().expect("body"))
                .is_none(),
            "unbound acceptor fails closed during identity selection"
        );
    }
}