secure-exec-sidecar 0.3.2

Native Secure Exec sidecar runtime
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
mod support;

use nix::libc;
use secure_exec_sidecar::wire::{
    EventPayload, GetSignalStateRequest, GuestRuntimeKind, KillProcessRequest,
    ProcessSnapshotStatus, RequestPayload, ResponsePayload, SignalDispositionAction,
    SignalHandlerRegistration, StreamChannel,
};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use support::{
    assert_node_available, authenticate_wire, create_vm_wire_with_metadata, execute_wire,
    new_sidecar, open_session_wire, temp_dir, wire_request, wire_vm, write_fixture,
};

fn wait_for_process_output(
    sidecar: &mut secure_exec_sidecar::NativeSidecar<support::RecordingBridge>,
    connection_id: &str,
    session_id: &str,
    vm_id: &str,
    process_id: &str,
    expected: &str,
) {
    let ownership = wire_vm(connection_id, session_id, vm_id);
    let deadline = Instant::now() + Duration::from_secs(10);

    loop {
        assert!(
            Instant::now() < deadline,
            "timed out waiting for process output containing {expected:?}"
        );
        let event = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(100))
            .expect("poll sidecar event");
        let Some(event) = event else {
            continue;
        };
        if let EventPayload::ProcessOutputEvent(output) = event.payload {
            if output.process_id == process_id
                && String::from_utf8_lossy(&output.chunk).contains(expected)
            {
                return;
            }
        }
    }
}

fn wait_for_process_status(
    sidecar: &mut secure_exec_sidecar::NativeSidecar<support::RecordingBridge>,
    connection_id: &str,
    session_id: &str,
    vm_id: &str,
    process_id: &str,
    expected: ProcessSnapshotStatus,
) {
    let ownership = wire_vm(connection_id, session_id, vm_id);
    let deadline = Instant::now() + Duration::from_secs(10);

    loop {
        let snapshot = sidecar
            .dispatch_wire_blocking(wire_request(
                1,
                ownership.clone(),
                RequestPayload::GetProcessSnapshotRequest,
            ))
            .expect("query process snapshot");
        match snapshot.response.payload {
            ResponsePayload::ProcessSnapshotResponse(snapshot) => {
                if snapshot
                    .processes
                    .iter()
                    .find(|entry| entry.process_id == process_id)
                    .is_some_and(|entry| entry.status == expected)
                {
                    return;
                }
            }
            other => panic!("unexpected process snapshot response: {other:?}"),
        }

        assert!(
            Instant::now() < deadline,
            "timed out waiting for process status {expected:?}"
        );
        let _ = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(25))
            .expect("pump process events while waiting for status");
    }
}

fn embedded_runtime_signal_routes_sigterm_and_process_kill() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-signal-routing");
    let cwd = temp_dir("embedded-runtime-signal-routing-cwd");
    let entry = cwd.join("signal-routing.mjs");

    write_fixture(
        &entry,
        [
            "let sigtermCount = 0;",
            "process.on('SIGHUP', () => {});",
            "process.on('SIGWINCH', () => {});",
            "process.on('SIGTERM', () => {",
            "  sigtermCount += 1;",
            "  console.log(`sigterm:${sigtermCount}`);",
            "  if (sigtermCount === 1) {",
            "    process.kill(process.pid, 'SIGTERM');",
            "    return;",
            "  }",
            "  process.exit(0);",
            "});",
            "console.log('signal-handlers-ready');",
            "setInterval(() => {}, 25);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-signal-routing");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::new(),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-routing",
        GuestRuntimeKind::JavaScript,
        &entry,
        Vec::new(),
    );

    wait_for_process_output(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-routing",
        "signal-handlers-ready",
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    let registration_deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let signal_state = sidecar
            .dispatch_wire_blocking(wire_request(
                5,
                ownership.clone(),
                RequestPayload::GetSignalStateRequest(GetSignalStateRequest {
                    process_id: String::from("signal-routing"),
                }),
            ))
            .expect("query signal state");
        let ready = match signal_state.response.payload {
            ResponsePayload::SignalStateResponse(snapshot) => {
                snapshot.handlers.get(&(libc::SIGTERM as u32))
                    == Some(&SignalHandlerRegistration {
                        action: SignalDispositionAction::User,
                        mask: vec![],
                        flags: 0,
                    })
            }
            other => panic!("unexpected signal state response: {other:?}"),
        };
        if ready {
            break;
        }
        let _ = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(25))
            .expect("pump signal registration events");
        assert!(
            Instant::now() < registration_deadline,
            "timed out waiting for SIGTERM registration"
        );
    }

    sidecar
        .dispatch_wire_blocking(wire_request(
            6,
            ownership.clone(),
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("signal-routing"),
                signal: String::from("SIGTERM"),
            }),
        ))
        .expect("deliver SIGTERM");

    let event_deadline = Instant::now() + Duration::from_secs(10);
    let mut saw_first_sigterm = false;
    let mut saw_second_sigterm = false;
    let mut exit_code = None;

    while exit_code.is_none() {
        let event = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(100))
            .expect("poll signal events");
        let Some(event) = event else {
            assert!(
                Instant::now() < event_deadline,
                "timed out waiting for SIGTERM delivery"
            );
            continue;
        };

        match event.payload {
            EventPayload::ProcessOutputEvent(output) if output.process_id == "signal-routing" => {
                let chunk = String::from_utf8_lossy(&output.chunk);
                saw_first_sigterm |= chunk.contains("sigterm:1");
                saw_second_sigterm |= chunk.contains("sigterm:2");
            }
            EventPayload::ProcessExitedEvent(exited) if exited.process_id == "signal-routing" => {
                exit_code = Some(exited.exit_code);
            }
            _ => {}
        }
    }

    assert!(saw_first_sigterm, "expected control-plane SIGTERM delivery");
    assert!(
        saw_second_sigterm,
        "expected guest process.kill(SIGTERM) delivery"
    );
    assert_eq!(exit_code, Some(0));
}

fn embedded_runtime_signal_stop_continue_updates_kernel_state_and_guest_handler() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-signal-stop-cont");
    let cwd = temp_dir("embedded-runtime-signal-stop-cont-cwd");
    let entry = cwd.join("signal-stop-cont.mjs");

    write_fixture(
        &entry,
        [
            "let sigcontCount = 0;",
            "process.on('SIGCONT', () => {",
            "  sigcontCount += 1;",
            "  console.log(`sigcont:${sigcontCount}`);",
            "});",
            "console.log('ready');",
            "setInterval(() => {}, 25);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-signal-stop-cont");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::new(),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-stop-cont",
        GuestRuntimeKind::JavaScript,
        &entry,
        Vec::new(),
    );

    wait_for_process_output(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-stop-cont",
        "ready",
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    sidecar
        .dispatch_wire_blocking(wire_request(
            5,
            ownership.clone(),
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("signal-stop-cont"),
                signal: String::from("SIGSTOP"),
            }),
        ))
        .expect("deliver SIGSTOP");
    wait_for_process_status(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-stop-cont",
        ProcessSnapshotStatus::Stopped,
    );

    sidecar
        .dispatch_wire_blocking(wire_request(
            6,
            ownership.clone(),
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("signal-stop-cont"),
                signal: String::from("SIGCONT"),
            }),
        ))
        .expect("deliver SIGCONT");
    wait_for_process_status(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-stop-cont",
        ProcessSnapshotStatus::Running,
    );
    wait_for_process_output(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "signal-stop-cont",
        "sigcont:1",
    );

    sidecar
        .dispatch_wire_blocking(wire_request(
            7,
            ownership,
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("signal-stop-cont"),
                signal: String::from("SIGTERM"),
            }),
        ))
        .expect("terminate stopped/continued process");
}

fn embedded_runtime_kill_process_rejects_invalid_signal_without_killing_process() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-invalid-signal");
    let cwd = temp_dir("embedded-runtime-invalid-signal-cwd");
    let entry = cwd.join("invalid-signal.mjs");

    write_fixture(
        &entry,
        [
            "console.log('invalid-signal-ready');",
            "setInterval(() => {}, 25);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-invalid-signal");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::new(),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "invalid-signal",
        GuestRuntimeKind::JavaScript,
        &entry,
        Vec::new(),
    );

    wait_for_process_output(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "invalid-signal",
        "invalid-signal-ready",
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    let invalid_signal = sidecar
        .dispatch_wire_blocking(wire_request(
            5,
            ownership.clone(),
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("invalid-signal"),
                signal: String::from("SIGBOGUS"),
            }),
        ))
        .expect("dispatch invalid signal");
    let ResponsePayload::RejectedResponse(response) = invalid_signal.response.payload else {
        panic!("unexpected invalid signal response");
    };
    assert_eq!(response.code, "invalid_state");
    assert!(
        response.message.contains("unsupported kill_process signal"),
        "unexpected invalid signal rejection: {}",
        response.message
    );

    wait_for_process_status(
        &mut sidecar,
        &connection_id,
        &session_id,
        &vm_id,
        "invalid-signal",
        ProcessSnapshotStatus::Running,
    );

    sidecar
        .dispatch_wire_blocking(wire_request(
            6,
            ownership,
            RequestPayload::KillProcessRequest(KillProcessRequest {
                process_id: String::from("invalid-signal"),
                signal: String::from("SIGTERM"),
            }),
        ))
        .expect("terminate invalid-signal process");
}

fn embedded_runtime_process_kill_signal_zero_checks_child_liveness() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-process-kill-sig0");
    let cwd = temp_dir("embedded-runtime-process-kill-sig0-cwd");
    let entry = cwd.join("process-kill-sig0.mjs");

    write_fixture(
        &entry,
        [
            "const { spawn, spawnSync } = require('node:child_process');",
            "const live = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 5000)'], { stdio: 'ignore' });",
            "console.log(`live:${process.kill(live.pid, 0)}`);",
            "live.kill('SIGTERM');",
            "const stale = spawnSync(process.execPath, ['-e', ''], { encoding: 'utf8' });",
            "if (typeof stale.pid !== 'number') {",
            "  throw new Error('spawnSync result did not include child pid');",
            "}",
            "let staleResult = 'alive';",
            "try {",
            "  process.kill(stale.pid, 0);",
            "} catch (error) {",
            "  staleResult = error && typeof error.code === 'string' ? error.code : 'error';",
            "}",
            "console.log(`stale:${staleResult}`);",
            "process.exit(staleResult === 'alive' ? 1 : 0);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-process-kill-sig0");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::new(),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "process-kill-sig0",
        GuestRuntimeKind::JavaScript,
        &entry,
        Vec::new(),
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    let deadline = Instant::now() + Duration::from_secs(10);
    let mut saw_live = false;
    let mut saw_stale_esrch = false;
    let mut exit_code = None;

    while exit_code.is_none() || !saw_live || !saw_stale_esrch {
        let event = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(100))
            .expect("poll process.kill signal-zero events");
        let Some(event) = event else {
            assert!(
                Instant::now() < deadline,
                "timed out waiting for process.kill signal-zero output"
            );
            continue;
        };

        match event.payload {
            EventPayload::ProcessOutputEvent(output)
                if output.process_id == "process-kill-sig0" =>
            {
                let chunk = String::from_utf8_lossy(&output.chunk);
                saw_live |= chunk.contains("live:true");
                saw_stale_esrch |= chunk.contains("stale:ESRCH");
            }
            EventPayload::ProcessExitedEvent(exited)
                if exited.process_id == "process-kill-sig0" =>
            {
                exit_code = Some(exited.exit_code);
            }
            _ => {}
        }

        assert!(
            Instant::now() < deadline,
            "timed out waiting for process.kill signal-zero completion"
        );
    }

    assert!(saw_live, "live child should be visible to signal 0");
    assert!(
        saw_stale_esrch,
        "stale child PID should throw ESRCH for signal 0"
    );
    assert_eq!(exit_code, Some(0));
}

fn embedded_runtime_process_group_kill_terminates_detached_tree() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-process-group-kill");
    let cwd = temp_dir("embedded-runtime-process-group-kill-cwd");
    let parent_entry = cwd.join("group-parent.mjs");
    let child_entry = cwd.join("group-child.mjs");

    write_fixture(
        &child_entry,
        [
            "import { spawn } from 'node:child_process';",
            "const makeChild = () => spawn(",
            "  process.execPath,",
            "  ['-e', 'setTimeout(() => {}, 100000)'],",
            "  { stdio: ['ignore', 'ignore', 'ignore'] },",
            ");",
            "const first = makeChild();",
            "const second = makeChild();",
            "console.log(`group-ready:${first.pid}:${second.pid}`);",
            "setInterval(() => {}, 1000);",
        ]
        .join("\n"),
    );
    write_fixture(
        &parent_entry,
        [
            "import { spawn } from 'node:child_process';",
            "const child = spawn(process.execPath, ['./group-child.mjs'], {",
            "  detached: true,",
            "  stdio: ['ignore', 'pipe', 'pipe'],",
            "});",
            "let buffered = '';",
            "const grandchildPids = await new Promise((resolve, reject) => {",
            "  child.on('error', reject);",
            "  child.stdout.on('data', (chunk) => {",
            "    buffered += chunk.toString();",
            "    const match = buffered.match(/group-ready:(\\d+):(\\d+)/);",
            "    if (match) {",
            "      resolve([Number(match[1]), Number(match[2])]);",
            "    }",
            "  });",
            "});",
            "const closePromise = new Promise((resolve) => {",
            "  child.on('close', (code, signal) => resolve({ code, signal }));",
            "});",
            "const killResult = process.kill(-child.pid, 'SIGKILL');",
            "console.log('kill-returned:' + killResult);",
            "const closed = await closePromise;",
            "console.log('group-close:' + closed.code + ':' + closed.signal);",
            "const errorCode = (error) => {",
            "  if (error && typeof error.code === 'string' && error.syscall === 'kill') {",
            "    return error.code;",
            "  }",
            "  return 'missing-errno-error';",
            "};",
            "const probe = (pid) => {",
            "  try {",
            "    process.kill(pid, 0);",
            "    return 'alive';",
            "  } catch (error) {",
            "    return errorCode(error);",
            "  }",
            "};",
            "console.log('probe-child:' + probe(child.pid));",
            "console.log('probe-grandchild-a:' + probe(grandchildPids[0]));",
            "console.log('probe-grandchild-b:' + probe(grandchildPids[1]));",
            "let missingGroup;",
            "try {",
            "  process.kill(-999999, 'SIGKILL');",
            "  missingGroup = 'no-error';",
            "} catch (error) {",
            "  missingGroup = errorCode(error);",
            "}",
            "console.log('probe-missing-group:' + missingGroup);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-process-group-kill");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::new(),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "group-kill-parent",
        GuestRuntimeKind::JavaScript,
        &parent_entry,
        Vec::new(),
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    let deadline = Instant::now() + Duration::from_secs(30);
    let mut stdout = String::new();
    let mut stderr = String::new();
    let mut exit_code = None;

    while exit_code.is_none() {
        let event = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(100))
            .expect("poll process group kill events");
        let Some(event) = event else {
            assert!(
                Instant::now() < deadline,
                "timed out waiting for group kill completion\nstdout:\n{stdout}\nstderr:\n{stderr}"
            );
            continue;
        };

        match event.payload {
            EventPayload::ProcessOutputEvent(output)
                if output.process_id == "group-kill-parent" =>
            {
                let chunk = String::from_utf8_lossy(&output.chunk);
                match output.channel {
                    StreamChannel::Stdout => stdout.push_str(&chunk),
                    StreamChannel::Stderr => stderr.push_str(&chunk),
                }
            }
            EventPayload::ProcessExitedEvent(exited)
                if exited.process_id == "group-kill-parent" =>
            {
                exit_code = Some(exited.exit_code);
            }
            _ => {}
        }

        assert!(
            Instant::now() < deadline,
            "timed out waiting for group kill completion\nstdout:\n{stdout}\nstderr:\n{stderr}"
        );
    }

    assert_eq!(
        exit_code,
        Some(0),
        "group kill parent should exit cleanly\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("kill-returned:true"),
        "group kill should report success\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("group-close:"),
        "detached child should emit close after group kill\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("probe-child:ESRCH"),
        "killed group leader should probe as ESRCH\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("probe-grandchild-a:ESRCH"),
        "first grandchild should be killed with the group\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("probe-grandchild-b:ESRCH"),
        "second grandchild should be killed with the group\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("probe-missing-group:ESRCH"),
        "missing process group should raise ESRCH\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
}

fn embedded_runtime_signal_delivers_sigchld_on_child_exit() {
    assert_node_available();

    let mut sidecar = new_sidecar("embedded-runtime-signal-sigchld");
    let cwd = temp_dir("embedded-runtime-signal-sigchld-cwd");
    let parent_entry = cwd.join("parent.mjs");
    let child_entry = cwd.join("child.mjs");

    write_fixture(
        &child_entry,
        [
            "await new Promise((resolve) => setTimeout(resolve, 200));",
            "console.log('child-exit');",
        ]
        .join("\n"),
    );
    write_fixture(
        &parent_entry,
        [
            "import { spawn } from 'node:child_process';",
            "let sigchldCount = 0;",
            "process.on('SIGCHLD', () => {",
            "  sigchldCount += 1;",
            "  console.log(`sigchld:${sigchldCount}`);",
            "});",
            "console.log('sigchld-registered');",
            "const child = spawn('node', ['./child.mjs'], { stdio: ['ignore', 'ignore', 'ignore'] });",
            "await new Promise((resolve, reject) => {",
            "  child.on('error', reject);",
            "  child.on('close', (code) => {",
            "    if (code !== 0) {",
            "      reject(new Error(`child exit ${code}`));",
            "      return;",
            "    }",
            "    resolve();",
            "  });",
            "});",
            "const deadline = Date.now() + 2000;",
            "while (sigchldCount === 0 && Date.now() < deadline) {",
            "  await new Promise((resolve) => setTimeout(resolve, 10));",
            "}",
            "if (sigchldCount === 0) {",
            "  throw new Error('SIGCHLD was not delivered');",
            "}",
            "console.log(`sigchld-final:${sigchldCount}`);",
        ]
        .join("\n"),
    );

    let connection_id = authenticate_wire(&mut sidecar, "conn-embedded-runtime-signal-sigchld");
    let session_id = open_session_wire(&mut sidecar, 2, &connection_id);
    let allowed_builtins = serde_json::to_string(&[
        "assert",
        "buffer",
        "child_process",
        "console",
        "crypto",
        "events",
        "fs",
        "path",
        "querystring",
        "stream",
        "string_decoder",
        "timers",
        "url",
        "util",
        "zlib",
    ])
    .expect("serialize builtins");
    let (vm_id, _) = create_vm_wire_with_metadata(
        &mut sidecar,
        3,
        &connection_id,
        &session_id,
        GuestRuntimeKind::JavaScript,
        &cwd,
        HashMap::from([(
            String::from("env.AGENTOS_ALLOWED_NODE_BUILTINS"),
            allowed_builtins,
        )]),
    );

    execute_wire(
        &mut sidecar,
        4,
        &connection_id,
        &session_id,
        &vm_id,
        "sigchld-parent",
        GuestRuntimeKind::JavaScript,
        &parent_entry,
        Vec::new(),
    );

    let ownership = wire_vm(&connection_id, &session_id, &vm_id);
    let deadline = Instant::now() + Duration::from_secs(10);
    let mut signal_registered = false;
    let mut saw_registered_output = false;
    let mut saw_sigchld_output = false;
    let mut saw_final_output = false;
    let mut exit_code = None;

    while exit_code.is_none() || !signal_registered {
        let signal_state = sidecar
            .dispatch_wire_blocking(wire_request(
                5,
                ownership.clone(),
                RequestPayload::GetSignalStateRequest(GetSignalStateRequest {
                    process_id: String::from("sigchld-parent"),
                }),
            ))
            .expect("query SIGCHLD state");
        match signal_state.response.payload {
            ResponsePayload::SignalStateResponse(snapshot) => {
                if snapshot.handlers.get(&(libc::SIGCHLD as u32))
                    == Some(&SignalHandlerRegistration {
                        action: SignalDispositionAction::User,
                        mask: vec![],
                        flags: 0,
                    })
                {
                    signal_registered = true;
                }
            }
            other => panic!("unexpected signal state response: {other:?}"),
        }

        let event = sidecar
            .poll_event_wire_blocking(&ownership, Duration::from_millis(100))
            .expect("poll SIGCHLD process");
        if let Some(event) = event {
            match event.payload {
                EventPayload::ProcessOutputEvent(output)
                    if output.process_id == "sigchld-parent" =>
                {
                    let chunk = String::from_utf8_lossy(&output.chunk);
                    saw_registered_output |= chunk.contains("sigchld-registered");
                    saw_sigchld_output |= chunk.contains("sigchld:1");
                    saw_final_output |= chunk.contains("sigchld-final:1");
                }
                EventPayload::ProcessExitedEvent(exited)
                    if exited.process_id == "sigchld-parent" =>
                {
                    exit_code = Some(exited.exit_code);
                }
                _ => {}
            }
        }

        assert!(
            Instant::now() < deadline,
            "timed out waiting for SIGCHLD registration/output"
        );
    }

    assert!(signal_registered, "SIGCHLD should be registered");
    assert!(
        saw_registered_output,
        "parent should report SIGCHLD registration"
    );
    assert!(saw_sigchld_output, "parent should receive SIGCHLD output");
    assert!(saw_final_output, "parent should report final SIGCHLD count");
    assert_eq!(exit_code, Some(0));
}

#[test]
fn embedded_runtime_signal_suite() {
    embedded_runtime_signal_routes_sigterm_and_process_kill();
    embedded_runtime_signal_stop_continue_updates_kernel_state_and_guest_handler();
    embedded_runtime_kill_process_rejects_invalid_signal_without_killing_process();
    embedded_runtime_process_kill_signal_zero_checks_child_liveness();
    embedded_runtime_process_group_kill_terminates_detached_tree();
    embedded_runtime_signal_delivers_sigchld_on_child_exit();
}