subc-daemon 0.46.0

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Spawn authority attestation, driven through real server connections: what
//! `route.open` attests about its opener (`caller` on `route.bind`) and its
//! target (`target` on the reply), the epoch fence at bind commit, and the
//! authority changes that close routes. The first-party mark is false on
//! every wire in this file's own tests, and each pins that where it reads an
//! attestation; the nested `first_party_mark` tests raise and lower it.

use super::claims::tests::{
    mint, network_primary, network_primary_with_hello, request, rig, swap_candidate, Net, Rig,
};
use super::*;
use serde_json::{json, Value};
use subc_control::{ClaimPresentRequest, ClaimPurpose};
use subc_protocol::manifest::{
    CapabilityDeclarations, Concurrency, ExecutionMode, IdentityScope, ProviderRole, Tool,
};
use subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY;

const OPEN_CORR: u64 = 41;

#[path = "first_party_mark_tests.rs"]
mod first_party_mark;

#[tokio::test]
async fn origins_widening_fences_routes_and_pending_binds() {
    let rig = rig().await;
    let (mut target, spawn, _module, _) =
        network_primary_with_hello(&rig, "widening-target", false).await;
    spawn.authority.initialize_origin(
        subc_protocol::peer::CallerOrigin::Development,
        Default::default(),
        Some(false),
    );
    let entries = serde_json::from_value(json!({"provider":{"items":["one"]}})).unwrap();
    let mut manifest = tool_manifest("widening-target", &[], &[]);
    manifest.provider_declarations = Some(entries);
    hello(&mut target, manifest).await;
    let mut opener = Net::new(rig.router.clone()).await;
    let (_, reply) = open(&mut opener, &mut target, "widening-target", false).await;
    assert_eq!(reply.header.ty, FrameType::Response);
    let mut pending_opener = Net::new(rig.router.clone()).await;
    pending_opener
        .send(open_frame("widening-target", false, None))
        .await;
    let pending_bind = next_bind(&mut target).await;
    let entries = serde_json::from_value(json!({"provider":{"items":["one"]}})).unwrap();
    rig.handler
        .approve_spawn_declarations(&spawn.authority, &entries);
    assert_eq!(spawn.authority.capture().unwrap().approved.entries, entries);
    assert_eq!(
        rig.handler
            .forwarding
            .published_spawn_epoch(&spawn.authority.key()),
        1
    );
    assert!(rig
        .handler
        .forwarding
        .route_authority_for_test(connection_of(&rig, &opener))
        .is_empty());
    let closed = loop {
        let frame = opener.recv().await.expect("route.closed");
        if frame.header.ty == FrameType::Push && body(&frame)["op"] == "route.closed" {
            break body(&frame);
        }
    };
    let reason: RouteCloseReason = serde_json::from_value(closed["reason"].clone()).unwrap();
    assert!(reason.may_reopen());
    ack(&mut target, &pending_bind).await;
    let refused = open_reply(&mut pending_opener).await;
    assert_eq!(
        body(&refused)["code"],
        subc_protocol::error_codes::STALE_AUTHORITY_EPOCH
    );
    let (_, reply) = open(&mut pending_opener, &mut target, "widening-target", false).await;
    assert_eq!(body(&reply)["target"]["authority_epoch"], 1);
    assert_eq!(
        body(&reply)["target"]["approved_declarations_digest"],
        spawn.authority.capture().unwrap().approved.digest
    );
    assert_eq!(body(&reply)["target"]["first_party"], false);
}

fn text(frame: &Frame) -> String {
    String::from_utf8_lossy(&frame.body).into_owned()
}

fn body(frame: &Frame) -> Value {
    serde_json::from_slice(&frame.body).unwrap_or_else(|_| panic!("{}", text(frame)))
}

/// A routable manifest declaring `provides` capabilities and denying
/// `denies`.
fn tool_manifest(module_id: &str, provides: &[&str], denies: &[&str]) -> ModuleManifest {
    ModuleManifest::builder(module_id, "1.0.0")
        .provides(vec![ProviderRole::ToolProvider {
            tools: vec![Tool {
                name: "read".into(),
                description: None,
                execution_mode: ExecutionMode::Pure,
                schema: json!({"type": "object"}),
            }],
            identity_scope: vec![IdentityScope::Session],
            concurrency: Concurrency::ModuleManaged,
            emits_push: false,
            sub_supervises: false,
        }])
        .capabilities(Some(CapabilityDeclarations {
            provides: provides.iter().map(|cap| cap.to_string()).collect(),
            requires: Vec::new(),
            must_never_reach: denies.iter().map(|cap| cap.to_string()).collect(),
        }))
        .build()
}

fn hello_frame(manifest: ModuleManifest) -> Frame {
    let hello = subc_protocol::ModuleHelloBody {
        manifest,
        protocol_ver: PROTOCOL_VERSION,
        control_ops: None,
        launch_nonce: None,
    };
    Frame::build(
        FrameType::Hello,
        control_flags(),
        0,
        0,
        3,
        serde_json::to_vec(&hello).unwrap(),
    )
    .unwrap()
}

async fn hello(net: &mut Net, manifest: ModuleManifest) -> Frame {
    let ack = net.call(hello_frame(manifest)).await;
    assert_eq!(ack.header.ty, FrameType::HelloAck, "{}", text(&ack));
    ack
}

/// An unsupervised module serving the tool role, with `capabilities`.
async fn unsupervised_target(rig: &Rig, module_id: &str, capabilities: &[&str]) -> Net {
    let mut net = Net::new(rig.router.clone()).await;
    hello(&mut net, tool_manifest(module_id, capabilities, &[])).await;
    net
}

/// A supervised spawn's own registration serving the tool role.
async fn supervised_target(
    rig: &Rig,
    module_id: &str,
    capabilities: &[&str],
) -> (
    Net,
    Arc<crate::supervise::RegistrationSpawn>,
    crate::supervise::SupervisedModule,
) {
    let (mut net, spawn, module, _) = network_primary_with_hello(rig, module_id, false).await;
    hello(&mut net, tool_manifest(module_id, capabilities, &[])).await;
    (net, spawn, module)
}

/// A connection bound by a claim the fixture's primary registration minted.
async fn claimed(rig: &mut Rig, purpose: ClaimPurpose) -> Net {
    let claim = mint(rig, purpose).await.claim;
    let mut net = Net::new(rig.router.clone()).await;
    let reply = net.call(request(ClaimPresentRequest::new(claim))).await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    net
}

fn open_frame(
    module_id: &str,
    busy_refusals: bool,
    consumer_identity: Option<subc_control::ConsumerIdentity>,
) -> Frame {
    open_frame_scoped(module_id, busy_refusals, consumer_identity, None)
}

fn open_frame_scoped(
    module_id: &str,
    busy_refusals: bool,
    consumer_identity: Option<subc_control::ConsumerIdentity>,
    scope: Option<subc_protocol::scope::ScopeSelector>,
) -> Frame {
    let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
        busy_refusals: busy_refusals.then_some(true),
        target: RouteTarget::ToolProvider {
            module_id: module_id.into(),
        },
        identity: BindIdentity::new("attestation".to_string(), "session".to_string()),
        consumer_identity,
        consumer_capabilities: None,
        role_versions: None,
        admission_facts: None,
        scope,
    })
    .unwrap();
    Frame::build(FrameType::Request, control_flags(), 0, 0, OPEN_CORR, body).unwrap()
}

/// The next `route.bind` the target receives, skipping anything else.
async fn next_bind(target: &mut Net) -> Frame {
    loop {
        let frame = target
            .recv()
            .await
            .expect("the target must receive the bind");
        if frame.header.ty == FrameType::Request
            && frame.header.channel == 0
            && body(&frame)["op"] == "route.bind"
        {
            return frame;
        }
    }
}

async fn ack(target: &mut Net, bind: &Frame) {
    let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
    target
        .send(
            Frame::build(
                FrameType::Response,
                control_flags(),
                0,
                0,
                bind.header.corr,
                body,
            )
            .unwrap(),
        )
        .await;
}

/// The opener's answer to its `route.open`.
async fn open_reply(opener: &mut Net) -> Frame {
    loop {
        let frame = opener.recv().await.expect("the opener must be answered");
        if frame.header.corr == OPEN_CORR
            && frame.header.channel == 0
            && matches!(frame.header.ty, FrameType::Response | FrameType::Error)
        {
            return frame;
        }
    }
}

/// Open a route and let the target accept it: the bind and the reply.
async fn open(
    opener: &mut Net,
    target: &mut Net,
    module_id: &str,
    busy_refusals: bool,
) -> (Value, Frame) {
    opener
        .send(open_frame(module_id, busy_refusals, None))
        .await;
    let bind = next_bind(target).await;
    ack(target, &bind).await;
    let reply = open_reply(opener).await;
    (body(&bind), reply)
}

fn connection_of(rig: &Rig, net: &Net) -> ConnectionId {
    net.connection_id(&rig.handler)
}

async fn catalog_entry(rig: &Rig, module_id: &str) -> Value {
    let mut reader = Net::new(rig.router.clone()).await;
    let reply = reader
        .call(request(
            json!({"op": "catalog.list", "module_id": module_id}),
        ))
        .await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    let modules = body(&reply)["modules"].as_array().unwrap().clone();
    assert_eq!(modules.len(), 1);
    modules[0].clone()
}

#[tokio::test]
async fn relay_seams_record_reply_and_catalog_share_approved_declarations() {
    let rig = rig().await;
    let (mut target, spawn, _module, _) =
        network_primary_with_hello(&rig, "declaration-target", false).await;
    let mut manifest = tool_manifest("declaration-target", &[], &[]);
    manifest.provider_declarations =
        Some(serde_json::from_value(json!({"provider": {"version": 1}})).unwrap());
    hello(&mut target, manifest).await;
    let record = spawn.authority.capture().unwrap();
    let empty_digest = "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a";
    assert!(record.approved.entries.is_empty());
    assert_eq!(record.approved.digest, empty_digest);
    let entry = catalog_entry(&rig, "declaration-target").await;
    assert_eq!(entry["approved_declarations"], json!({}));
    assert_eq!(
        entry["requested_declarations"],
        json!({"provider": {"version": 1}})
    );
    assert_eq!(
        entry["approved_declarations_digest"],
        record.approved.digest
    );
    assert_eq!(entry["incarnation"], record.incarnation);
    assert_eq!(entry["spawn"], record.key.spawn);
    assert_eq!(entry["first_party"], false);
    let mut opener = Net::new(rig.router.clone()).await;
    for busy_refusals in [false, true] {
        let (_, reply) = open(
            &mut opener,
            &mut target,
            "declaration-target",
            busy_refusals,
        )
        .await;
        assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
        let target = &body(&reply)["target"];
        assert_eq!(
            target["approved_declarations_digest"],
            entry["approved_declarations_digest"]
        );
        assert_eq!(target["spawn"], entry["spawn"]);
        assert_eq!(target["incarnation"], entry["incarnation"]);
        assert_eq!(target["first_party"], false);
    }
}

#[tokio::test]
async fn relay_seams_authority_change_preserves_each_openers_close_reasons() {
    let mut rig = rig().await;
    let (mut target, spawn, _module) = supervised_target(&rig, "close-target", &[]).await;
    let mut modern = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let mut legacy = claimed(&mut rig, ClaimPurpose::Helper).await;
    for (opener, accepts) in [(&mut modern, true), (&mut legacy, false)] {
        let frame = open_frame("close-target", false, None);
        let mut value = body(&frame);
        subc_control::RouteOpenRequestExt::new()
            .with_accepts_close_reasons(accepts.then(|| vec!["authority_changed".into()]))
            .write_to(&mut value)
            .unwrap();
        let frame = Frame::build(
            FrameType::Request,
            control_flags(),
            0,
            0,
            OPEN_CORR,
            serde_json::to_vec(&value).unwrap(),
        )
        .unwrap();
        opener.send(frame).await;
        let bind = next_bind(&mut target).await;
        ack(&mut target, &bind).await;
        let reply = open_reply(opener).await;
        assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    }
    rig.handler.change_spawn_authority(&spawn.authority);
    assert!(
        spawn.authority.alive(),
        "a live authority change, not an exit"
    );
    for (opener, expected) in [
        (&mut modern, RouteCloseReason::AuthorityChanged),
        (&mut legacy, RouteCloseReason::Reload),
    ] {
        let closed = loop {
            let frame = opener.recv().await.expect("route.closed push");
            if frame.header.ty == FrameType::Push && body(&frame)["op"] == "route.closed" {
                break body(&frame);
            }
        };
        let reason: RouteCloseReason = serde_json::from_value(closed["reason"].clone()).unwrap();
        assert_eq!(reason, expected, "{closed}");
        assert!(reason.may_reopen());
        assert_eq!(closed["terminal"], false);
        assert!(rig
            .handler
            .forwarding
            .route_authority_for_test(connection_of(&rig, opener))
            .is_empty());
    }
}

#[tokio::test]
async fn caller_attestation_claim_bound_own_identity_is_refused() {
    let mut rig = rig().await;
    let _target =
        unsupervised_target(&rig, "attest-target", &[CALLER_ATTESTATION_CAPABILITY]).await;
    let nonce = rig.handler.supervisor.spawn_nonce("claims-module").unwrap();
    let mut opener = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let identity = ConsumerIdentity {
        module_id: "claims-module".into(),
        launch_nonce: nonce,
    };
    assert!(rig
        .handler
        .attest_route_open_consumer(connection_of(&rig, &opener), Some(&identity))
        .is_none());
    opener
        .send(open_frame("attest-target", false, Some(identity)))
        .await;
    let reply = open_reply(&mut opener).await;
    assert_eq!(reply.header.ty, FrameType::Error, "{}", text(&reply));
    assert_eq!(body(&reply)["code"], "bad_consumer_identity");
}

#[tokio::test]
async fn caller_attestation_claim_bound_without_identity_preserves_capture() {
    let mut rig = rig().await;
    let opener = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let attested = rig
        .handler
        .attest_route_open_consumer(connection_of(&rig, &opener), None)
        .expect("a live claim attests its owner without a nonce identity");
    assert!(matches!(
        attested.principal,
        Principal::Reserved { ref module_id } if module_id == "claims-module"
    ));
    let (record, claim) = attested.spawn.as_ref().expect("the launch is captured");
    assert!(Arc::ptr_eq(record, &rig.spawn.authority));
    assert_eq!(*claim, subc_protocol::peer::CallerClaim::Own);
    assert!(attested.capture().unwrap().is_some());
}

#[tokio::test]
async fn caller_attestation_claim_bound_openers_attest_their_spawn_and_claim() {
    let mut rig = rig().await;
    let mut target =
        unsupervised_target(&rig, "attest-target", &[CALLER_ATTESTATION_CAPABILITY]).await;
    let spawn = rig.spawn.authority.spawn_number();
    for (purpose, claim) in [
        (ClaimPurpose::SelfConnection, "own"),
        (ClaimPurpose::Helper, "brokered"),
        (ClaimPurpose::Relay, "relay"),
    ] {
        let mut opener = claimed(&mut rig, purpose).await;
        let (bind, reply) = open(&mut opener, &mut target, "attest-target", false).await;
        assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
        assert_eq!(
            bind["principal"],
            json!({"kind":"reserved","module_id":"claims-module"}),
            "{bind}"
        );
        let caller = &bind["caller"];
        assert_eq!(caller["claim"], claim, "{bind}");
        assert_eq!(caller["spawn"], spawn, "{bind}");
        assert_eq!(caller["authority_epoch"], 0, "{bind}");
        assert_eq!(
            caller["incarnation"],
            rig.handler.supervisor.daemon_incarnation()
        );
        assert_eq!(caller["origin"], "other");
        assert_eq!(
            caller["approved_declarations_digest"],
            "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
        );
        // No spawn is first-party yet: the daemon never raises the mark.
        assert_eq!(caller["first_party"], false, "{bind}");
        assert!(caller.get("declaration").is_none(), "{bind}");
        assert!(caller.get("declaration_digest").is_none(), "{bind}");
    }
}

#[tokio::test]
async fn caller_attestation_nonce_consumer_attests_legacy() {
    let rig = rig().await;
    let mut target =
        unsupervised_target(&rig, "legacy-target", &[CALLER_ATTESTATION_CAPABILITY]).await;
    let nonce = rig
        .handler
        .supervisor
        .spawn_nonce("claims-module")
        .expect("an ungated launch receives a nonce");
    let mut opener = Net::new(rig.router.clone()).await;
    opener
        .send(open_frame(
            "legacy-target",
            false,
            Some(subc_control::ConsumerIdentity {
                module_id: "claims-module".into(),
                launch_nonce: nonce,
            }),
        ))
        .await;
    let bind = next_bind(&mut target).await;
    let caller = &body(&bind)["caller"];
    assert_eq!(caller["claim"], "legacy", "{}", text(&bind));
    assert_eq!(caller["spawn"], rig.spawn.authority.spawn_number());
    assert_eq!(caller["first_party"], false);
}

#[tokio::test]
async fn caller_attestation_nonce_withdrawn_mid_open_keeps_the_resolved_record() {
    let rig = rig().await;
    let mut target =
        unsupervised_target(&rig, "withdrawn-target", &[CALLER_ATTESTATION_CAPABILITY]).await;
    let nonce = rig
        .handler
        .supervisor
        .spawn_nonce("claims-module")
        .expect("an ungated launch receives a nonce");
    // The nonce is withdrawn, as a swap promotion or a respawn withdraws
    // it, right after the open's attestation resolved it.
    let supervisor = rig.handler.supervisor.clone();
    rig.handler.after_nonce_attestation_for_test(move || {
        supervisor.set_spawn_nonce("claims-module", "withdrawn".into());
    });
    let mut opener = Net::new(rig.router.clone()).await;
    opener
        .send(open_frame(
            "withdrawn-target",
            false,
            Some(subc_control::ConsumerIdentity {
                module_id: "claims-module".into(),
                launch_nonce: nonce,
            }),
        ))
        .await;
    let bind = next_bind(&mut target).await;
    assert_eq!(
        rig.handler
            .supervisor
            .spawn_nonce("claims-module")
            .as_deref(),
        Some("withdrawn"),
        "the withdrawal ran inside the open"
    );
    // The open carries the record it was authorized with: its caller key
    // and spawn epoch, never a bare reserved principal.
    let caller = &body(&bind)["caller"];
    assert_eq!(caller["claim"], "legacy", "{}", text(&bind));
    assert_eq!(caller["spawn"], rig.spawn.authority.spawn_number());
    assert_eq!(caller["authority_epoch"], 0);
}

#[tokio::test]
async fn caller_attestation_is_absent_for_direct_callers_and_undeclared_targets() {
    let mut rig = rig().await;
    let mut declared =
        unsupervised_target(&rig, "declared-target", &[CALLER_ATTESTATION_CAPABILITY]).await;
    let mut undeclared = unsupervised_target(&rig, "undeclared-target", &[]).await;
    let mut direct = Net::new(rig.router.clone()).await;
    let (bind, _) = open(&mut direct, &mut declared, "declared-target", false).await;
    assert!(bind.get("caller").is_none(), "a direct caller: {bind}");
    let mut own = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let (bind, _) = open(&mut own, &mut undeclared, "undeclared-target", false).await;
    assert!(bind.get("caller").is_none(), "an undeclared target: {bind}");
}

#[tokio::test]
async fn caller_attestation_rides_the_modern_and_the_legacy_bind_encoder() {
    let mut rig = rig().await;
    let mut modern = unsupervised_target(
        &rig,
        "modern-target",
        &[
            CALLER_ATTESTATION_CAPABILITY,
            subc_protocol::scope::BIND_NO_PROJECT_CAPABILITY,
        ],
    )
    .await;
    let mut legacy = unsupervised_target(
        &rig,
        "legacy-encoder-target",
        &[CALLER_ATTESTATION_CAPABILITY],
    )
    .await;
    let mut own = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let (bind, _) = open(&mut own, &mut modern, "modern-target", false).await;
    assert!(bind["identity"].get("project_root").is_none(), "{bind}");
    assert_eq!(bind["caller"]["claim"], "own", "{bind}");
    let (bind, _) = open(&mut own, &mut legacy, "legacy-encoder-target", false).await;
    assert!(bind["identity"].get("project_root").is_some(), "{bind}");
    assert_eq!(bind["caller"]["claim"], "own", "{bind}");
}

#[tokio::test]
async fn caller_attestation_reply_target_reports_the_reserved_endpoint() {
    let rig = rig().await;
    let mut unsupervised = unsupervised_target(&rig, "plain-target", &[]).await;
    let (mut supervised, spawn, _module) = supervised_target(&rig, "spawn-target", &[]).await;
    let mut opener = Net::new(rig.router.clone()).await;
    let incarnation = rig.handler.supervisor.daemon_incarnation();
    // Both reply constructions: the one prebuilt at reservation, and the one
    // rebuilt at commit for an opener that asked for busy refusals.
    for busy_refusals in [false, true] {
        let (_, reply) = open(
            &mut opener,
            &mut unsupervised,
            "plain-target",
            busy_refusals,
        )
        .await;
        let target = &body(&reply)["target"];
        assert_eq!(
            target,
            &json!({"incarnation": incarnation, "kind": "unsupervised", "first_party": false}),
            "busy_refusals {busy_refusals}: {}",
            text(&reply)
        );
        let (_, reply) = open(&mut opener, &mut supervised, "spawn-target", busy_refusals).await;
        let target = &body(&reply)["target"];
        assert_eq!(
            target,
            &json!({
                "incarnation": incarnation,
                "kind": "spawn",
                "spawn": spawn.authority.spawn_number(),
                "authority_epoch": 0,
                "first_party": false,
                "approved_declarations_digest":
                    "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
            }),
            "busy_refusals {busy_refusals}: {}",
            text(&reply)
        );
    }
}

#[tokio::test]
async fn caller_attestation_reply_target_never_reports_a_prefix_childs_owner() {
    let mut rig = rig().await;
    let mut child = super::claims::tests::prefix_connection(&mut rig, "claims:worker").await;
    // The prefix child registers over a claim bound to its owner's spawn,
    // but it is never that spawn's own registration.
    hello(&mut child, tool_manifest("claims:worker", &[], &[])).await;
    let mut opener = Net::new(rig.router.clone()).await;
    for busy_refusals in [false, true] {
        let (_, reply) = open(&mut opener, &mut child, "claims:worker", busy_refusals).await;
        assert_eq!(
            body(&reply)["target"],
            json!({
                "incarnation": rig.handler.supervisor.daemon_incarnation(),
                "kind": "prefix",
                "first_party": false,
            }),
            "{}",
            text(&reply)
        );
    }
}

#[tokio::test]
async fn caller_attestation_flow_scope_attests_relay_for_a_self_claim_carrier() {
    use subc_protocol::scope::{ScopeKind, ScopeRecord, ScopeSelector, FLOW_SCOPES_CAPABILITY};
    let mut rig = super::claims::tests::rig_with(|handler| {
        handler.with_scope_authority_owners(vec!["claims-module".into()])
    })
    .await;
    let mut target = unsupervised_target(
        &rig,
        "flow-target",
        &[CALLER_ATTESTATION_CAPABILITY, FLOW_SCOPES_CAPABILITY],
    )
    .await;
    // The carrier owns a flow scope and opens a route under it on its own
    // `self` connection: the route acts for the flow's code, not the carrier.
    let mut record = ScopeRecord::new("flow-scope", 1, ScopeKind::Head);
    record.attributes.flow_id = Some("flow:7".into());
    let synced = rig
        .primary
        .call(
            &rig.router,
            request(ModuleControlRequestFromModule::ScopeSync {
                generation: 1,
                scopes: vec![record],
            }),
        )
        .await;
    assert_eq!(synced.header.ty, FrameType::Response, "{}", text(&synced));
    let mut own = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    own.send(open_frame_scoped(
        "flow-target",
        false,
        None,
        Some(ScopeSelector::new(
            Principal::Reserved {
                module_id: "claims-module".into(),
            },
            "flow-scope".to_string(),
            Some(1),
        )),
    ))
    .await;
    if let Ok(reply) = tokio::time::timeout(Duration::from_millis(300), open_reply(&mut own)).await
    {
        panic!(
            "the open was answered before any bind: {} (sync: {})",
            text(&reply),
            text(&synced)
        );
    }
    let bind = body(&next_bind(&mut target).await);
    assert!(bind.to_string().contains("flow:7"), "{bind}");
    let caller = &bind["caller"];
    assert_eq!(caller["claim"], "relay", "{bind}");
    assert_eq!(caller["first_party"], false, "{bind}");
    assert!(caller.get("declaration").is_none(), "{bind}");
}

#[tokio::test]
async fn caller_attestation_stale_caller_epoch_settles_as_a_refusal() {
    let mut rig = rig().await;
    let mut target = unsupervised_target(
        &rig,
        "stale-caller-target",
        &[CALLER_ATTESTATION_CAPABILITY],
    )
    .await;
    let mut own = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    own.send(open_frame("stale-caller-target", false, None))
        .await;
    let bind = next_bind(&mut target).await;
    assert_eq!(body(&bind)["caller"]["authority_epoch"], 0);
    // The caller's authority changes after it was captured for this bind.
    rig.handler.change_spawn_authority(&rig.spawn.authority);
    ack(&mut target, &bind).await;
    let reply = open_reply(&mut own).await;
    assert_eq!(reply.header.ty, FrameType::Error, "{}", text(&reply));
    assert_eq!(
        body(&reply)["code"],
        subc_protocol::error_codes::STALE_AUTHORITY_EPOCH
    );
    // The shared module connection survives, and a new open binds at the
    // new epoch.
    let (bind, reply) = open(&mut own, &mut target, "stale-caller-target", false).await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    assert_eq!(bind["caller"]["authority_epoch"], 1, "{bind}");
}

#[tokio::test]
async fn caller_attestation_stale_target_epoch_settles_without_closing_the_module() {
    let rig = rig().await;
    let (mut target, spawn, _module) = supervised_target(&rig, "stale-target", &[]).await;
    let mut opener = Net::new(rig.router.clone()).await;
    opener.send(open_frame("stale-target", false, None)).await;
    let bind = next_bind(&mut target).await;
    rig.handler.change_spawn_authority(&spawn.authority);
    ack(&mut target, &bind).await;
    let reply = open_reply(&mut opener).await;
    assert_eq!(reply.header.ty, FrameType::Error, "{}", text(&reply));
    assert_eq!(
        body(&reply)["code"],
        subc_protocol::error_codes::STALE_AUTHORITY_EPOCH
    );
    let (_, reply) = open(&mut opener, &mut target, "stale-target", false).await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    assert_eq!(body(&reply)["target"]["authority_epoch"], 1);
}

#[tokio::test]
async fn caller_attestation_authority_change_closes_unscoped_routes_of_the_spawn() {
    let mut rig = rig().await;
    let (mut target, target_spawn, _module) = supervised_target(&rig, "change-target", &[]).await;
    let mut own = claimed(&mut rig, ClaimPurpose::SelfConnection).await;
    let (_, reply) = open(&mut own, &mut target, "change-target", false).await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    // The route recorded both its caller's and its target's spawn at the
    // epochs it was attested at.
    let routes = rig
        .handler
        .forwarding
        .route_authority_for_test(connection_of(&rig, &own));
    assert_eq!(routes.len(), 1);
    let (caller, target_pair) = routes[0].clone();
    assert_eq!(caller.unwrap().key, rig.spawn.authority.key());
    assert_eq!(target_pair.unwrap().key, target_spawn.authority.key());

    rig.handler.change_spawn_authority(&rig.spawn.authority);
    let closed = loop {
        let frame = own.recv().await.expect("route.closed push");
        if frame.header.ty == FrameType::Push && body(&frame)["op"] == "route.closed" {
            break body(&frame);
        }
    };
    let reason: RouteCloseReason = serde_json::from_value(closed["reason"].clone()).unwrap();
    // The reason is `authority_changed`, or another reason that permits
    // reopening for an opener that did not declare it accepts that one.
    assert!(
        reason.may_reopen(),
        "a live spawn's authority change permits reopening: {closed}"
    );
    loop {
        let frame = target.recv().await.expect("module GOODBYE");
        if frame.header.ty == FrameType::Goodbye && frame.header.channel != 0 {
            break;
        }
    }
    assert!(rig
        .handler
        .forwarding
        .route_authority_for_test(connection_of(&rig, &own))
        .is_empty());
}

#[tokio::test]
async fn caller_attestation_registration_end_is_an_authority_change() {
    let rig = rig().await;
    let (target, spawn, _module) = supervised_target(&rig, "ending-target", &[]).await;
    let key = spawn.authority.key();
    assert_eq!(rig.handler.forwarding.published_spawn_epoch(&key), 0);
    drop(target);
    tokio::time::timeout(Duration::from_secs(5), async {
        while rig.handler.forwarding.published_spawn_epoch(&key) == 0 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the ended registration must publish a new epoch");
}

/// HELLO for `module_id` on a fresh connection, presenting the launch nonce
/// of the module's live spawn and requesting `declarations`.
async fn nonce_hello(rig: &Rig, module_id: &str, declarations: serde_json::Value) -> (Net, Frame) {
    let nonce = rig
        .handler
        .supervisor
        .spawn_nonce(module_id)
        .expect("an ungated launch receives a nonce");
    let mut manifest = tool_manifest(module_id, &[], &[]);
    manifest.provider_declarations = Some(serde_json::from_value(declarations).unwrap());
    let hello = subc_protocol::ModuleHelloBody {
        manifest,
        protocol_ver: PROTOCOL_VERSION,
        control_ops: None,
        launch_nonce: Some(nonce),
    };
    let mut net = Net::new(rig.router.clone()).await;
    let reply = net
        .call(
            Frame::build(
                FrameType::Hello,
                control_flags(),
                0,
                0,
                3,
                serde_json::to_vec(&hello).unwrap(),
            )
            .unwrap(),
        )
        .await;
    (net, reply)
}

/// Close `net` and wait until the daemon has torn its connection down.
async fn close_and_settle(rig: &Rig, net: Net) {
    let connection = connection_of(rig, &net);
    drop(net);
    tokio::time::timeout(Duration::from_secs(5), async {
        while rig
            .handler
            .caller_endpoints
            .lock()
            .unwrap()
            .contains_key(&connection)
        {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the closed connection must be torn down");
    // Teardown publishes an ended registration's authority change after it
    // forgets the connection; give that step time to land if it is coming.
    tokio::time::sleep(Duration::from_millis(300)).await;
}

#[tokio::test]
async fn spawn_authority_hello_refused_as_duplicate_leaves_the_live_spawns_routes_open() {
    let rig = rig().await;
    let (mut target, spawn, _module) = supervised_target(&rig, "duplicate-target", &[]).await;
    let mut opener = Net::new(rig.router.clone()).await;
    let (_, reply) = open(&mut opener, &mut target, "duplicate-target", false).await;
    assert_eq!(reply.header.ty, FrameType::Response, "{}", text(&reply));
    let key = spawn.authority.key();
    assert_eq!(rig.handler.forwarding.published_spawn_epoch(&key), 0);

    let (duplicate, refused) = nonce_hello(&rig, "duplicate-target", json!({})).await;
    assert_eq!(refused.header.ty, FrameType::Error, "{}", text(&refused));
    assert_eq!(body(&refused)["code"], "duplicate_module_id");
    // While the refused connection is open, only the live registration is
    // the spawn's.
    assert_eq!(
        rig.handler.forwarding.connection_for_spawn(&key).unwrap(),
        Some(connection_of(&rig, &target))
    );
    assert!(rig
        .handler
        .forwarding
        .target_authority_for_connection(connection_of(&rig, &duplicate))
        .unwrap()
        .is_none());
    close_and_settle(&rig, duplicate).await;

    assert!(spawn.authority.alive());
    assert_eq!(
        rig.handler.forwarding.published_spawn_epoch(&key),
        0,
        "the refused connection's close is no authority change of the live spawn"
    );
    assert_eq!(spawn.authority.epoch_for_test(), 0);
    assert_eq!(
        rig.handler
            .forwarding
            .route_authority_for_test(connection_of(&rig, &opener))
            .len(),
        1,
        "the live spawn's route stays open"
    );
}

#[tokio::test]
async fn spawn_authority_refused_hello_leaves_the_spawns_declarations_unfrozen() {
    let rig = rig().await;
    // Another connection already holds the module id, so the spawn's own
    // nonce HELLO is refused as a duplicate.
    let holder = unsupervised_target(&rig, "unfrozen-target", &[]).await;
    let (_net, spawn, _module, _) =
        network_primary_with_hello(&rig, "unfrozen-target", false).await;
    let (_refused_net, refused) =
        nonce_hello(&rig, "unfrozen-target", json!({"provider": {"v": 1}})).await;
    assert_eq!(refused.header.ty, FrameType::Error, "{}", text(&refused));
    assert_eq!(body(&refused)["code"], "duplicate_module_id");

    // The HELLO that does register the spawn still freezes its own request.
    let own = serde_json::from_value(json!({"provider": {"v": 2}})).unwrap();
    assert!(
        spawn.authority.freeze_declarations(own).is_some(),
        "a refused HELLO must not freeze the spawn's requested declarations"
    );
    drop(holder);
}

#[tokio::test]
async fn caller_attestation_deny_edges_read_the_opening_spawns_own_registration() {
    let rig = rig().await;
    let target = unsupervised_target(&rig, "guarded-target", &["guarded-cap/v1"]).await;
    let mut swap = swap_candidate(&rig, "deny-module").await;
    // Only the warming candidate denies the capability; the active
    // registration under the same id does not.
    let mut capabilities =
        json!({"provides": [], "requires": [], "must_never_reach": ["guarded-cap/v1"]});
    let update = swap
        .candidate
        .call(request(json!({
            "op": "catalog.update",
            "provides": [],
            "capabilities": capabilities.take(),
            "ready": false,
        })))
        .await;
    assert_eq!(update.header.ty, FrameType::Response, "{}", text(&update));
    let claim = super::claims::tests::net_mint(&mut swap.candidate, ClaimPurpose::SelfConnection)
        .await
        .claim;
    let mut opener = Net::new(rig.router.clone()).await;
    let present = opener.call(request(ClaimPresentRequest::new(claim))).await;
    assert_eq!(present.header.ty, FrameType::Response, "{}", text(&present));
    opener.send(open_frame("guarded-target", false, None)).await;
    let reply = open_reply(&mut opener).await;
    assert_eq!(reply.header.ty, FrameType::Error, "{}", text(&reply));
    assert_eq!(body(&reply)["code"], "capability_forbidden");
    drop(target);
}

#[tokio::test]
async fn spawn_authority_record_dies_at_the_child_exit_observation() {
    let rig = rig().await;
    let (_net, spawn, module, _) = network_primary(&rig, "exiting-module").await;
    assert!(spawn.authority.alive());
    let pid = module.status().unwrap().pid.expect("the child is running");
    let killed = std::process::Command::new("kill")
        .args(["-9", &pid.to_string()])
        .status()
        .unwrap();
    assert!(killed.success());
    tokio::time::timeout(Duration::from_secs(5), async {
        while spawn.authority.alive() {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the exit observation must mark the record dead");
    assert!(
        spawn.authority.capture().is_none(),
        "a dead record attests nothing"
    );
    assert!(spawn.authority.epoch_for_test() > 0);
}

#[tokio::test]
async fn caller_attestation_capability_is_advertised_and_fixed_at_hello() {
    let rig = rig().await;
    let mut declared = Net::new(rig.router.clone()).await;
    let ack = hello(
        &mut declared,
        tool_manifest("frozen-declared", &[CALLER_ATTESTATION_CAPABILITY], &[]),
    )
    .await;
    assert!(
        text(&ack).contains(CALLER_ATTESTATION_CAPABILITY),
        "HELLO_ACK must advertise the capability: {}",
        text(&ack)
    );
    let mut undeclared = unsupervised_target(&rig, "frozen-undeclared", &[]).await;
    let role = serde_json::to_value(&tool_manifest("role", &[], &[]).provides).unwrap();
    for (net, provides) in [
        (&mut declared, json!([])),
        (&mut undeclared, json!([CALLER_ATTESTATION_CAPABILITY])),
    ] {
        let reply = net
            .call(request(json!({
                "op": "catalog.update",
                "provides": role.clone(),
                "capabilities": {"provides": provides, "requires": [], "must_never_reach": []},
            })))
            .await;
        assert_eq!(reply.header.ty, FrameType::Error, "{}", text(&reply));
        assert_eq!(
            body(&reply)["code"],
            error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY
        );
    }
}

#[tokio::test]
async fn spawn_authority_promoted_candidate_keeps_its_launch_generation() {
    let rig = rig().await;
    let mut swap = swap_candidate(&rig, "promoted-module").await;
    let candidate = rig
        .handler
        .supervisor
        .registration_for_test("promoted-module")
        .unwrap();
    assert!(candidate.is_candidate());
    let generation = candidate.authority.spawn_number();
    let incarnation = candidate.authority.capture().unwrap().incarnation;
    let incumbent = catalog_entry(&rig, "promoted-module").await;
    assert_ne!(incumbent["spawn"], generation);
    let candidate_registration = rig
        .handler
        .registry
        .get_module_by_connection(swap.candidate_id)
        .unwrap()
        .unwrap();
    let candidate_entry = rig
        .handler
        .catalog_discovery_entry(&candidate_registration, true)
        .unwrap();
    assert_eq!(candidate_entry.spawn, Some(generation));
    assert_eq!(
        candidate_entry.incarnation.as_deref(),
        Some(incarnation.as_str())
    );
    let ready = swap
        .candidate
        .call(request(
            json!({"op":"catalog.update","provides":[],"ready":true}),
        ))
        .await;
    assert_eq!(ready.header.ty, FrameType::Response, "{}", text(&ready));
    assert_eq!(
        tokio::time::timeout(Duration::from_secs(5), &mut swap.swap)
            .await
            .unwrap()
            .unwrap()
            .unwrap(),
        crate::supervise::SwapOutcome::Cutover
    );
    assert_eq!(swap.module.status().unwrap().spawn_generation, generation);
    let promoted = catalog_entry(&rig, "promoted-module").await;
    assert_eq!(promoted["incarnation"], incarnation);
    assert_eq!(promoted["spawn"], generation);
    assert_eq!(promoted["first_party"], false);
    assert_eq!(
        promoted["approved_declarations_digest"],
        candidate_entry.approved_declarations_digest.unwrap()
    );
}

#[test]
fn caller_attestation_federated_and_flow_scopes_attest_relay() {
    use subc_protocol::scope::{ScopeKind, ScopeStamp};
    let federated = ScopeStamp::new(Principal::Direct, "remote", 1, ScopeKind::Federated);
    let head = ScopeStamp::new(Principal::Direct, "head", 1, ScopeKind::Head);
    let mut flow = head.clone();
    flow.attributes.flow_id = Some("flow".into());
    assert!(caller_attestation::scope_acts_for_another(&federated));
    assert!(caller_attestation::scope_acts_for_another(&flow));
    assert!(!caller_attestation::scope_acts_for_another(&head));

    let record = crate::spawn_authority::SpawnAuthorityRecord::new("incarnation", 4, "carrier");
    let own = crate::spawn_authority::CallerCapture {
        authority: record.capture().unwrap(),
        claim: subc_protocol::peer::CallerClaim::Own,
    };
    let relayed = own.relayed().attestation("target").unwrap();
    assert_eq!(relayed.claim, subc_protocol::peer::CallerClaim::Relay);
    assert!(!relayed.first_party);
}