Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
5256 lines (4952 loc) · 193 KB
/
Copy pathcli.rs
File metadata and controls
5256 lines (4952 loc) · 193 KB
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
//! Integration tests for minimal CLI commands.
//!
//! Each test spins up a real minimald `TestServer` on a UDS, then calls
//! the `cmd_*` functions from the `minimal` library as if the user had
//! invoked the CLI. The daemon's state is inspected directly (via
//! `TestClient`) to verify side-effects.
// The in-process daemon's async bodies are deep: rustc's default query depth (128)
// overflows computing their layout (`queries overflow the depth limit!`), as the
// daemon crates themselves already declare.
#![recursion_limit = "256"]
mod common;
use boxes::SessionId;
use common::setup;
use minimal::*;
use minimald_rpc::{ListSessionsResponse, ResourcePool};
use minimald::test_harness::unwrap_ready;
use serde_json_lenient::Value;
use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _};
// --- version ---
#[tokio::test]
async fn version_succeeds_with_daemon_running() {
let (_daemon, args) = setup().await;
cmd_version(&args, &mut std::io::stdout()).await.unwrap();
}
#[tokio::test]
async fn version_succeeds_without_daemon() {
let args = GlobalArgs {
repo_dir: None,
minimal_dir: Some(std::path::PathBuf::from("/nonexistent")),
config_dir: None,
provider: None,
no_input: false,
vm: None,
};
// Should print client version and note daemon is unreachable, but return Ok.
cmd_version(&args, &mut std::io::stdout()).await.unwrap();
}
/// A writer whose reader has gone away, as `min version | head -1` leaves
/// stdout once `head` exits.
struct ClosedPipe;
impl std::io::Write for ClosedPipe {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::BrokenPipe.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn version_reports_broken_pipe_when_output_is_closed() {
let args = GlobalArgs {
repo_dir: None,
minimal_dir: Some(std::path::PathBuf::from("/nonexistent")),
config_dir: None,
provider: None,
no_input: false,
vm: None,
};
// The first line fails before any daemon contact, so no daemon is needed.
let err = cmd_version(&args, &mut ClosedPipe).await.unwrap_err();
assert!(err.chain().any(|cause| {
cause
.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::BrokenPipe)
}));
}
// --- finalize-install ---
/// NET-122: `min finalize-install --show --json` with stdout piped (the
/// way the installer's probe reads it) delivers the whole document and
/// exits 1 on a host with an item not done — here a state dir with no
/// daemon, so the names item waits on one. The exit must not lose the
/// buffered report: `std::process::exit` flushes nothing.
#[tokio::test]
async fn finalize_install_show_json_reaches_a_piped_reader_before_exit() {
let state = tempfile::TempDir::new().unwrap();
let config_dir = tempfile::TempDir::new().unwrap();
let out = tokio::process::Command::new(env!("CARGO_BIN_EXE_min"))
.args(["--minimal-dir".as_ref(), state.path().as_os_str()])
.args(["--config-dir".as_ref(), config_dir.path().as_os_str()])
.args(["--no-input", "finalize-install", "--show", "--json"])
.output()
.await
.expect("the min binary should be invocable");
assert_eq!(
out.status.code(),
Some(1),
"an unfinished host exits 1: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
let report: Value = serde_json_lenient::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("the whole report reaches a piped stdout ({e}): {stdout:?}"));
assert_eq!(report["schema"], "min/v1/finalize-install");
assert_eq!(report["finished"], false);
let names = report["items"]
.as_array()
.unwrap()
.iter()
.find(|item| item["id"] == "names")
.expect("the names item is in every host's report");
assert_eq!(names["state"], "waiting", "{stdout}");
}
/// A daemon whose answerer port is held by a process no channel reaches is
/// the one fact its status verb names, and the names item's cause is that
/// fact — not the no-daemon text a fallback listing with no control socket
/// collapses to. The fallback listing pairs the daemon it reached with the
/// control socket beside its ssh socket on either backend, so the read the
/// cause keys on works against a native minimald the same as against a VM
/// host daemon.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn finalize_install_names_item_names_the_held_port_a_reachable_daemon_reports() {
let (daemon, args) = common::setup().await;
// The control socket beside the daemon's ssh socket, answering the
// status verb with the one fact this test is about: the port is held,
// no channel behind it.
let sock = minimal_client::resolve_socket_path(args.minimal_dir.as_deref(), false).unwrap();
let status = minimald_rpc::BoxControlReply::Status(minimald_rpc::AnswererStatusReply {
answerer: minimald_rpc::ZoneAnswererStatus::PortHeldNoChannel { port: 7_656 },
proxy_down: None,
});
answering_control_sock(
&sock.parent().unwrap().join("control.sock"),
serde_json_lenient::to_string(&status).unwrap(),
);
let out = run_min(&args, &["finalize-install", "--show", "--json"]).await;
assert_eq!(
out.status.code(),
Some(1),
"an unfinished host exits 1: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
let report: Value = serde_json_lenient::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("the whole report reaches a piped stdout ({e}): {stdout:?}"));
let names = report["items"]
.as_array()
.unwrap()
.iter()
.find(|item| item["id"] == "names")
.expect("the names item is in every host's report");
assert_eq!(names["state"], "waiting", "{stdout}");
let cause = names["cause"].as_str().unwrap_or_default();
assert!(
cause.contains("another program holds 127.0.0.1:7656"),
"the cause names the held port the daemon reported, not the \
no-daemon text: {cause}"
);
assert!(
!cause.contains("no daemon is reachable"),
"a reachable daemon's report is not the no-daemon cause: {cause}"
);
drop(daemon);
}
/// A daemon that accepts and never answers must not hang `--show`: the
/// installer probes `min finalize-install --show --script` from a shell
/// with no timeout of its own. The names item's daemon read is one bounded
/// attempt, after which the item is `waiting`.
#[tokio::test]
async fn finalize_install_show_returns_within_its_deadline_on_a_wedged_daemon() {
let state = tempfile::TempDir::new().unwrap();
let config_dir = tempfile::TempDir::new().unwrap();
let sock = minimal_client::resolve_socket_path(Some(state.path()), false).unwrap();
std::fs::create_dir_all(sock.parent().unwrap()).unwrap();
let listener = tokio::net::UnixListener::bind(&sock).unwrap();
// Accept every connection and hold it open, silent.
let wedged = tokio::spawn(async move {
let mut held = Vec::new();
loop {
if let Ok((stream, _)) = listener.accept().await {
held.push(stream);
}
}
});
let started = std::time::Instant::now();
let out = tokio::process::Command::new(env!("CARGO_BIN_EXE_min"))
.args(["--minimal-dir".as_ref(), state.path().as_os_str()])
.args(["--config-dir".as_ref(), config_dir.path().as_os_str()])
.args(["--no-input", "finalize-install", "--show", "--json"])
.output()
.await
.expect("the min binary should be invocable");
let elapsed = started.elapsed();
wedged.abort();
assert!(
elapsed < std::time::Duration::from_secs(20),
"the daemon read is bounded (took {elapsed:?}): {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
let report: Value = serde_json_lenient::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("the report is printed ({e}): {stdout:?}"));
let names = report["items"]
.as_array()
.unwrap()
.iter()
.find(|item| item["id"] == "names")
.expect("the names item is in every host's report");
assert_eq!(names["state"], "waiting", "{stdout}");
}
// --- ls ---
#[test]
fn ls_shows_shared_resource_pool() {
let resp = ListSessionsResponse {
box_networks: Default::default(),
daemon_version: None,
hostname_routing_unavailable: None,
hostname_proxy_port: None,
zone_answerer_port: None,
answerer_bound: false,
resource_pool: Some(ResourcePool {
cpu_cores: 8,
memory_bytes: 16 * 1024 * 1024 * 1024,
}),
sessions: vec![minimald_rpc::ListSessionsEntry {
id: SessionId::nil(),
name: None,
project_path: Some(paths::HostAbsPath::try_new("/p").unwrap()),
status: boxes::BoxState::Active,
git: None,
host_ip_enforcement: None,
shared_port_collisions: Vec::new(),
attrs: None,
}],
};
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
assert!(
text.starts_with("RESOURCE POOL: 8 CPU cores · 16 GiB memory · shared by 1 session\n\n")
);
}
#[test]
fn ls_table_exposes_project_path_and_status() {
let resp = ListSessionsResponse {
box_networks: Default::default(),
daemon_version: None,
hostname_routing_unavailable: None,
hostname_proxy_port: None,
zone_answerer_port: None,
answerer_bound: false,
resource_pool: None,
sessions: vec![minimald_rpc::ListSessionsEntry {
id: SessionId::nil(),
name: Some("s1".to_string()),
project_path: Some(paths::HostAbsPath::try_new("/work/proj").unwrap()),
status: boxes::BoxState::Active,
git: None,
host_ip_enforcement: None,
shared_port_collisions: Vec::new(),
attrs: None,
}],
};
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("STATUS"), "header should list STATUS: {text}");
assert!(
text.contains("PROJECT PATH"),
"header should list PROJECT PATH: {text}"
);
assert!(text.contains("running"), "row should show status: {text}");
assert!(
text.contains("/work/proj"),
"row should show project path: {text}"
);
}
/// The cell under `column` in the row that contains `row_key`, read by
/// the header's positions: `column` up to `next`, the column after it. A
/// cell can hold spaces, so the row is not split on whitespace.
fn ls_cell(text: &str, row_key: &str, column: &str, next: &str) -> String {
let header = text
.lines()
.find(|l| l.contains("SESSION ID"))
.unwrap_or_else(|| panic!("a header in:\n{text}"));
let start = header.find(column).expect("the column in the header");
let end = header.find(next).expect("the next column in the header");
let row = text
.lines()
.find(|l| l.contains(row_key) && !l.contains("SESSION ID"))
.unwrap_or_else(|| panic!("a row for {row_key} in:\n{text}"));
row[start..end].trim().to_string()
}
/// NET-079's proof names the listing, in `min session policy`'s words
/// (T110): a host-address box that runs unenforced shows its posture with
/// `; per-box enforcement none` in the human `min ls`, one decided per box
/// shows its posture alone, and a box the daemon reports no posture for
/// shows `-`.
#[test]
fn ls_table_shows_host_address_enforcement() {
let id = |n: u64| SessionId::parse_str(&format!("00000000-0000-0000-0000-{n:012}")).unwrap();
let entry = |name: &str, n: u64, enforcement| minimald_rpc::ListSessionsEntry {
id: id(n),
name: Some(name.to_string()),
project_path: Some(paths::HostAbsPath::try_new("/work/proj").unwrap()),
status: boxes::BoxState::Active,
git: None,
host_ip_enforcement: enforcement,
shared_port_collisions: Vec::new(),
attrs: None,
};
let posture = |posture| minimald_rpc::BoxNetworkFacts {
loopback_address: Some(std::net::Ipv4Addr::LOCALHOST),
egress_posture: Some(posture),
at_fallback: Some(true),
};
let resp = ListSessionsResponse {
box_networks: [
(id(1), posture(minimald_rpc::EgressPosture::DenyAll)),
(id(2), posture(minimald_rpc::EgressPosture::AllowAllDefault)),
]
.into_iter()
.collect(),
daemon_version: None,
hostname_routing_unavailable: None,
hostname_proxy_port: None,
zone_answerer_port: None,
answerer_bound: false,
resource_pool: None,
sessions: vec![
entry("decided", 1, Some(minimald_rpc::HostIpEnforcement::PerBox)),
entry("unenforced", 2, Some(minimald_rpc::HostIpEnforcement::None)),
entry("own-address", 3, None),
],
};
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
let egress = |name: &str| ls_cell(&text, name, "EGRESS", "TITLE");
assert_eq!(egress("decided"), "deny-all", "got:\n{text}");
assert_eq!(
egress("unenforced"),
"allow-all (default); per-box enforcement none",
"got:\n{text}"
);
assert_eq!(egress("own-address"), "-", "got:\n{text}");
assert!(!text.contains("per_box"), "got:\n{text}");
}
/// NET-129's listing half: a box that yields a declared port at a shared
/// address gets one `warning:` line per port naming the box (by id when it
/// has no name), the port and the holder; a box that yields nothing gets
/// none. `--json` carries the rows under the entry's `shared_port_collisions`
/// key, present only on the entry that yields.
#[test]
fn ls_reports_yielded_shared_address_ports() {
let entry = |name: Option<&str>, n: u64, collisions| minimald_rpc::ListSessionsEntry {
id: SessionId::parse_str(&format!("00000000-0000-0000-0000-{n:012}")).unwrap(),
name: name.map(str::to_string),
project_path: Some(paths::HostAbsPath::try_new("/work/proj").unwrap()),
status: boxes::BoxState::Active,
git: None,
host_ip_enforcement: None,
shared_port_collisions: collisions,
attrs: None,
};
let held = |port| minimald_rpc::SharedPortCollision {
port,
held_by: "first.min.internal".to_string(),
};
let resp = ListSessionsResponse {
box_networks: Default::default(),
daemon_version: None,
hostname_routing_unavailable: None,
hostname_proxy_port: None,
zone_answerer_port: None,
answerer_bound: false,
resource_pool: None,
sessions: vec![
entry(Some("first"), 1, Vec::new()),
entry(Some("second"), 2, vec![held(8080), held(9090)]),
entry(None, 3, vec![held(8080)]),
],
};
let listings = vec![VmListing {
vm: "default".to_string(),
resp: resp.clone(),
control_sock: None,
running: true,
}];
assert_eq!(
shared_port_collision_lines(&listings),
vec![
"warning: second: port 8080 is held by first.min.internal; not forwarded",
"warning: second: port 9090 is held by first.min.internal; not forwarded",
"warning: 00000000-0000-0000-0000-000000000003: port 8080 is held by \
first.min.internal; not forwarded",
]
);
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: true,
},
&resp,
None,
None,
)
.unwrap();
let document: Value = serde_json_lenient::from_slice(&out).unwrap();
let sessions = document["sessions"].as_array().unwrap();
assert!(
sessions[0].get("shared_port_collisions").is_none(),
"a box that yields nothing carries no key: {document}"
);
assert_eq!(
sessions[1]["shared_port_collisions"],
serde_json_lenient::json!([
{"port": 8080, "held_by": "first.min.internal"},
{"port": 9090, "held_by": "first.min.internal"},
]),
"the yielding box lists each port and its holder: {document}"
);
}
/// The multi-VM table carries the same EGRESS cell, after the VM column
/// each row leads with.
#[test]
fn ls_across_vms_table_shows_host_address_enforcement() {
let id = |n: u64| SessionId::parse_str(&format!("00000000-0000-0000-0000-{n:012}")).unwrap();
let entry = |name: &str, n: u64, enforcement| minimald_rpc::ListSessionsEntry {
id: id(n),
name: Some(name.to_string()),
project_path: Some(paths::HostAbsPath::try_new("/work/proj").unwrap()),
status: boxes::BoxState::Active,
git: None,
host_ip_enforcement: enforcement,
shared_port_collisions: Vec::new(),
attrs: None,
};
let posture = |n: u64, posture| {
(
id(n),
minimald_rpc::BoxNetworkFacts {
loopback_address: None,
egress_posture: Some(posture),
at_fallback: None,
},
)
};
let listing = |vm: &str, sessions, box_networks| VmListing {
vm: vm.to_string(),
resp: ListSessionsResponse {
box_networks,
daemon_version: None,
hostname_routing_unavailable: None,
hostname_proxy_port: None,
zone_answerer_port: None,
answerer_bound: false,
resource_pool: None,
sessions,
},
control_sock: None,
running: true,
};
let listings = vec![
listing(
"default",
vec![
entry("decided", 1, Some(minimald_rpc::HostIpEnforcement::PerBox)),
entry("own-address", 3, None),
],
[posture(1, minimald_rpc::EgressPosture::AllowAllDefault)]
.into_iter()
.collect(),
),
listing(
"alpha",
vec![entry(
"unenforced",
2,
Some(minimald_rpc::HostIpEnforcement::None),
)],
[posture(2, minimald_rpc::EgressPosture::DeclaredRules)]
.into_iter()
.collect(),
),
];
let mut out = Vec::new();
format_ls_across_vms(
&mut out,
&LsArgs {
raw: false,
json: false,
},
&listings,
&[None, None],
&[None, None],
)
.unwrap();
let text = String::from_utf8(out).unwrap();
let egress = |name: &str| ls_cell(&text, name, "EGRESS", "TITLE");
assert_eq!(egress("decided"), "allow-all (default)", "got:\n{text}");
assert_eq!(
egress("unenforced"),
"declared rules; per-box enforcement none",
"got:\n{text}"
);
assert_eq!(egress("own-address"), "-", "got:\n{text}");
assert_eq!(ls_cell(&text, "decided", "ADDRESS", "STATUS"), "-");
}
#[tokio::test]
async fn ls_empty() {
let (_daemon, args) = setup().await;
let mut client = connect_daemon(&args).await.unwrap();
use minimald_rpc::ListSessions;
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("No active sessions."));
}
#[tokio::test]
async fn ls_raw_empty() {
let (_daemon, args) = setup().await;
let mut client = connect_daemon(&args).await.unwrap();
use minimald_rpc::ListSessions;
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: true,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
assert!(
text.is_empty(),
"raw output should be empty with no sessions"
);
}
#[tokio::test]
async fn ls_json_empty() {
let (_daemon, args) = setup().await;
let mut client = connect_daemon(&args).await.unwrap();
use minimald_rpc::ListSessions;
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: true,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
let parsed: Value =
serde_json_lenient::from_str(&text).expect("json output should be valid JSON");
assert!(parsed["resource_pool"]["cpu_cores"].as_u64().unwrap() > 0);
assert!(parsed["resource_pool"]["memory_bytes"].as_u64().unwrap() > 0);
assert!(parsed["sessions"].is_array());
assert!(parsed["sessions"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn ls_json_with_sessions() {
let (daemon, args) = setup().await;
let id1 = create_session(&daemon, "json-1").await;
let id2 = create_session(&daemon, "json-2").await;
let mut client = connect_daemon(&args).await.unwrap();
use minimald_rpc::ListSessions;
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: false,
json: true,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
let parsed: Value =
serde_json_lenient::from_str(&text).expect("json output should be valid JSON");
let sessions = parsed["sessions"]
.as_array()
.expect("sessions should be an array");
assert_eq!(sessions.len(), 2);
let ids: Vec<&str> = sessions.iter().map(|s| s["id"].as_str().unwrap()).collect();
assert!(ids.contains(&id1.to_string().as_str()));
assert!(ids.contains(&id2.to_string().as_str()));
}
#[tokio::test]
async fn ls_raw_with_sessions() {
let (daemon, args) = setup().await;
let id1 = create_session(&daemon, "raw-1").await;
let id2 = create_session(&daemon, "raw-2").await;
let mut client = connect_daemon(&args).await.unwrap();
use minimald_rpc::ListSessions;
let resp = client.oneshot_rpc::<ListSessions>(()).await.unwrap();
let mut out = Vec::new();
format_ls(
&mut out,
&LsArgs {
raw: true,
json: false,
},
&resp,
None,
None,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
let lines: Vec<&str> = text.trim_end().lines().collect();
assert_eq!(lines.len(), 2, "raw output should be one line per session");
assert!(lines.contains(&id1.to_string().as_str()));
assert!(lines.contains(&id2.to_string().as_str()));
}
// --- activate + ls ---
#[tokio::test]
async fn activate_creates_session() {
let (daemon, args) = setup().await;
// Create a temp project dir with a minimal.toml so the
// missing-mfile prompt doesn't fire. Mark it as a VCS root so
// the non-VCS upload confirmation (#790) short-circuits instead
// of blocking on stdin when the test binary is attached to a TTY.
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test minimal.toml\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
let activate_args = ActivateArgs {
name: Some("test-session".to_string()),
path: Some(project.path().to_string_lossy().to_string()),
sync: Some(SyncMode::Tarball),
network: Some(CliNetworkMode::NoNet),
ingress: vec![],
dynamic_ingress: None,
dynamic_range: None,
egress: minimal::EgressArgs::default(),
credentialed_upstream: false,
loadout: vec![],
no_loadouts: false,
no_hooks: false,
no_prompt: false,
attach: false,
};
cmd_activate(&args, activate_args).await.unwrap();
// Verify the session was created via TestClient.
let mut client = daemon.server.connect().await;
use minimald_rpc::ListSessions;
let resp = client.call::<ListSessions>(&()).await;
assert_eq!(resp.sessions.len(), 1);
assert_eq!(resp.sessions[0].name.as_deref(), Some("test-session"));
}
// --- activate uploads project files ---
#[tokio::test]
async fn activate_uploads_project_files() {
let (daemon, args) = setup().await;
// Create a temp project dir with a minimal.toml and some files.
// Mark it as a VCS root so the non-VCS upload confirmation (#790)
// short-circuits instead of blocking on stdin when the test
// binary is attached to a TTY.
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
std::fs::write(project.path().join("hello.txt"), "hello world").unwrap();
std::fs::create_dir_all(project.path().join("subdir")).unwrap();
std::fs::write(project.path().join("subdir/nested.txt"), "nested").unwrap();
let activate_args = ActivateArgs {
name: Some("upload-test".to_string()),
path: Some(project.path().to_string_lossy().to_string()),
sync: Some(SyncMode::Tarball),
network: Some(CliNetworkMode::NoNet),
ingress: vec![],
dynamic_ingress: None,
dynamic_range: None,
egress: minimal::EgressArgs::default(),
credentialed_upstream: false,
loadout: vec![],
no_loadouts: false,
no_hooks: false,
no_prompt: false,
attach: false,
};
cmd_activate(&args, activate_args).await.unwrap();
// Look up the session and verify the uploaded files landed in the
// session's workspace directory by reading them back over SFTP. The
// workspace is spelled out: SFTP starts a client at the session's home,
// so a relative path would name the wrong one of the two exports.
let mut sftp_client = daemon.server.connect().await;
let sessions = {
use minimald_rpc::ListSessions;
let resp = sftp_client.call::<ListSessions>(&()).await;
resp.sessions
};
assert_eq!(sessions.len(), 1);
let session_id: SessionId = sessions[0].id;
let sftp = sftp_client.open_sftp(session_id).await;
let hello = sftp.read("/workbench/hello.txt").await.unwrap();
assert_eq!(hello, b"hello world");
let nested = sftp.read("/workbench/subdir/nested.txt").await.unwrap();
assert_eq!(nested, b"nested");
let mfile = sftp.read("/workbench/minimal.toml").await.unwrap();
assert!(mfile.starts_with(b"# test"));
}
/// A dashboard create (`min dash`, the `n` form) whose loadout carries a
/// patch comes up `Active`: the TUI's activate uploads the composition's
/// patches between `ConfigureLoadout` and `FinalizeSession`, as `min session
/// activate` does. Without that upload the daemon's finalize gate refuses
/// the session ("patches upload never completed") and the create fails.
#[tokio::test]
async fn dashboard_activate_uploads_loadout_patches() {
let (daemon, args) = setup().await;
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test minimal.toml\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
let loadout_dir = tempfile::TempDir::new().unwrap();
let patch_source = loadout_dir.path().join("gitconfig");
std::fs::write(&patch_source, "[user]\n\tname = dash\n").unwrap();
let contribution = boxes::wire::request::WireContribution {
patches: vec![boxes::wire::primitives::WireSessionPatch {
patch: boxes::wire::primitives::WireResolvedPatch {
host_path: paths::HostAbsPath::try_new(patch_source.to_str().unwrap()).unwrap(),
destination: paths::SandboxRelPath::try_new(".gitconfig").unwrap(),
},
source: boxes::wire::primitives::WireSource::UserLoadout {
name: "dev".to_string(),
},
}],
..Default::default()
};
let sock = args
.minimal_dir
.as_ref()
.unwrap()
.join("providers/local-minimald0/ssh.sock");
let project_path = paths::HostAbsPath::try_new(project.path().to_str().unwrap()).unwrap();
let upload_root = project_path.as_utf8_path().to_path_buf();
let inputs = minimal::loadouts::ActivationInputs {
contribution,
hook_scripts: Vec::new(),
hook_budget: std::time::Duration::from_secs(30),
user_policy: Default::default(),
initial_policy: Default::default(),
compose_options: Default::default(),
loadout_names: Vec::new(),
};
let activated = minimal::dash::rpc::activate(
&sock,
Some("dash-patched".to_string()),
project_path,
upload_root,
boxes::NetworkMode::NoNet,
minimal::UploadDecision::Upload,
inputs,
)
.await
.expect("a patch-carrying dashboard create finalizes");
let mut client = daemon.server.connect().await;
use minimald_rpc::ListSessions;
let resp = client.call::<ListSessions>(&()).await;
assert_eq!(resp.sessions.len(), 1);
assert_eq!(resp.sessions[0].id, activated.id);
assert_eq!(resp.sessions[0].name.as_deref(), Some("dash-patched"));
}
/// A workspace upload whose unpack fails on the daemon must surface as an
/// `Err`, not a silent success. The daemon relays the failure on
/// extended-data stream 1 and only then closes the channel; the client reads
/// to that close, so the failure cannot be swallowed. Regression test for the
/// silent-upload-failure half of #824.
#[tokio::test]
async fn upload_workspace_files_surfaces_daemon_unpack_error() {
let (_daemon, args) = setup().await;
let mut client = connect_daemon(&args).await.unwrap();
// A well-formed but unknown session id: the daemon can't resolve a
// destination for the upload, reports the failure, and closes.
let project = tempfile::TempDir::new().unwrap();
std::fs::write(project.path().join("hello.txt"), "hello world").unwrap();
let result = client
.upload_workspace_files(SessionId::nil(), project.path())
.await;
assert!(
result.is_err(),
"upload to an unknown session must fail, not report success: {result:?}"
);
}
// --- attach (smart resolution) ---
/// `min session activate` with no positional path but `-C/--repo-dir` set uploads
/// from the repo-dir directory, not the process cwd (#873).
#[tokio::test]
async fn activate_uses_repo_dir_when_no_positional_path() {
let (daemon, mut global) = setup().await;
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test minimal.toml\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
std::fs::write(project.path().join("hello.txt"), "hello world").unwrap();
global.repo_dir = Some(project.path().to_path_buf());
let activate_args = ActivateArgs {
name: Some("repo-dir-test".to_string()),
path: None,
sync: Some(SyncMode::Tarball),
network: Some(CliNetworkMode::NoNet),
ingress: vec![],
dynamic_ingress: None,
dynamic_range: None,
egress: minimal::EgressArgs::default(),
credentialed_upstream: false,
loadout: vec![],
no_loadouts: false,
no_hooks: false,
no_prompt: false,
attach: false,
};
cmd_activate(&global, activate_args).await.unwrap();
let mut client = daemon.server.connect().await;
use minimald_rpc::ListSessions;
let resp = client.call::<ListSessions>(&()).await;
assert_eq!(resp.sessions.len(), 1);
let session = &resp.sessions[0];
let project_canon = project.path().canonicalize().unwrap();
let session_path = session.project_path.as_ref().unwrap();
assert_eq!(
session_path.as_str(),
project_canon.to_str().unwrap(),
"session project_path should match -C/--repo-dir, not cwd"
);
// Spelled out for the same reason as above: the upload lands in the
// workspace, but SFTP's relative paths resolve against the home.
let sftp = client.open_sftp(session.id).await;
let hello = sftp.read("/workbench/hello.txt").await.unwrap();
assert_eq!(hello, b"hello world");
}
// --- dynamic ingress declaration (NET-043/NET-044) ---
/// NET-043: `min session create` carries the box's dynamic ingress stance
/// into the create request's `IngressPolicy`. `--dynamic-ingress allow
/// --dynamic-range 8000-8443` reaches the record the daemon holds as
/// exactly that — mode and range — and the stance alone makes the ingress
/// declaration (no static mapping was given), while a create that set
/// nothing keeps `ingress` `None`: the deny-all default, not an empty
/// declaration. Read back through `GetSessionPolicy`, so what is asserted
/// is the declaration the record stores, not the args the client parsed.
#[tokio::test]
async fn create_carries_dynamic_ingress() {
let (_daemon, args) = setup().await;
for (name, dynamic_ingress, dynamic_range) in [
(
"dyn-allow",
Some(boxes::DynamicIngress::Allow),
Some((8000, 8443)),
),
// The mode alone, with no range and no static mapping, still makes
// the declaration.
("dyn-ask", Some(boxes::DynamicIngress::Ask), None),
("dyn-bare", None, None),
] {
let project = tempfile::TempDir::new().unwrap();
std::fs::create_dir(project.path().join(".git")).unwrap();
std::fs::write(
project.path().join("minimal.toml"),
"# test minimal.toml\n[stack]\nuse = \"shell\"\n",
)
.unwrap();
cmd_activate(
&args,
ActivateArgs {
name: Some(name.to_string()),
path: Some(project.path().to_string_lossy().to_string()),
sync: Some(SyncMode::Tarball),