Repository navigation
Expand file tree
/
Copy pathtask.rs
More file actions
4009 lines (3767 loc) · 160 KB
/
Copy pathtask.rs
File metadata and controls
4009 lines (3767 loc) · 160 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
//! `min task run <task>`: run a declared project task in an ephemeral
//! session.
//!
//! The activate→exec→end loop as one command: create a session for the
//! project (named `task-<task>-<hex>`), upload the project per the normal
//! activate rules, exec the canonical in-box `min task run <task>` over the
//! native SSH exec channel with the task's output streamed through, exit
//! with the task's exit code, and leave the session's end to the daemon —
//! it owns the box the run created, so it destroys it once the task's exit
//! status is on the wire (NET-131), whether or not this client is still
//! here.
//!
//! Deliberately composed from the same client/RPC primitives `cmd_activate`
//! uses (`BoxConfig`, `CreateSession`, the upload gates,
//! `ConfigureLoadout`, the gating hooks, `FinalizeSession`) rather than
//! refactored out of it: a few duplicated lines of glue keep
//! `cmd_activate`'s diff at zero.
use std::io::Read as _;
use anyhow::{Context as _, bail};
use tokio::io::AsyncWriteExt as _;
use tracing::Instrument as _;
use crate::{BoxListArgs, BoxRmArgs, BoxRunArgs, BoxStopArgs, GlobalArgs, TaskRunArgs};
/// A task's non-zero exit status, carried as a typed error so `main.rs` can
/// downcast it and terminate with the task's own code instead of printing an
/// error — the git-remote helper's `ExitCode` precedent. The task's output
/// has already streamed through, so there is nothing left to say.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TaskExit(pub u8);
impl std::fmt::Display for TaskExit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "task exited with status {}", self.0)
}
}
impl std::error::Error for TaskExit {}
/// Map the bridged exit status to the command result: a reported 0 is
/// success, a reported non-zero becomes the typed [`TaskExit`] main.rs
/// relays as the process exit code, clamped into `u8` the same way the
/// git-remote helper clamps its remote status. A channel that closed
/// WITHOUT reporting a status — a daemon or transport death mid-task —
/// fails closed as an ordinary error (printed to stderr, process exit 1)
/// rather than defaulting to success.
pub(crate) fn exit_outcome(code: Option<u32>) -> Result<(), anyhow::Error> {
match code {
Some(0) => Ok(()),
Some(code) => Err(TaskExit(u8::try_from(code).unwrap_or(1)).into()),
None => Err(anyhow::anyhow!(
"task ended without reporting an exit status"
)),
}
}
/// The exec request a task run with no spec sends: the task, its declared
/// arguments, plus the owns-box flag (NET-131). The flag is what moves the
/// destroy off this client: the daemon ends the session once the task's
/// exit status is on the wire, whether or not this process is still there.
/// `cwd` is the invocation directory relative to the uploaded tree (see
/// [`task_run_cwd`]), where a task declaring `inherit_cwd` starts.
fn task_run_request(task: &str, args: &[String], cwd: String) -> minimald_rpc::exec::ExecRequest {
minimald_rpc::exec::ExecRequest::TaskRun {
task: task.to_string(),
owns_box: true,
args: args.to_vec(),
cwd,
}
}
/// The exec request of a task run whose task is its box's entrypoint (T43).
/// The daemon starts the entrypoint, relays its output and returns its exit
/// code. The task's arguments ride the entrypoint's argv, not the request,
/// and the run owns no box: the box ends when its entrypoint returns, and
/// keeps its record (BOX-038). `cwd` is as for [`task_run_request`]: the
/// entrypoint starts there, for a task that declares `inherit_cwd`.
fn entrypoint_run_request(task: &str, cwd: &str) -> minimald_rpc::exec::ExecRequest {
minimald_rpc::exec::ExecRequest::TaskRun {
task: task.to_string(),
owns_box: false,
args: Vec::new(),
cwd: cwd.to_string(),
}
}
/// The spec of the task box a run creates (BOX-068): the declared task's
/// spec, with the arguments the user typed after the task name appended to
/// its entrypoint, `min task run <task> <args...>`. `None` for an
/// interactive task, whose type denies a terminal.
pub(crate) fn task_box_spec(
task: &str,
declared: &mfile::Task,
flags: mfile::spec::SpecFlags,
args: &[String],
) -> Option<mfile::spec::BoxSpec> {
let mut spec = mfile::spec::BoxSpec::for_task(task, declared, flags)?;
// `--` ends the in-box run's own options, so an argument such as
// `--path` reaches the task and not the in-box parser.
if let mfile::spec::Entrypoint::Exec(argv) = &mut spec.entrypoint
&& !args.is_empty()
{
argv.push("--".to_string());
argv.extend(args.iter().cloned());
}
Some(spec)
}
/// The network a run gives task `task`'s box (NET-060), from
/// [`task_box_network`].
#[derive(Debug)]
pub(crate) struct TaskBoxNetwork {
pub(crate) mode: boxes::NetworkMode,
pub(crate) policy: boxes::BoxPolicy,
/// The hint for each legacy key spelling the project file uses.
pub(crate) hints: Vec<String>,
/// The table of minimal.toml whose `network.mode` the box took, such
/// as `[tasks.build]`. `None` when `--network` or the default set it.
pub(crate) mode_layer: Option<String>,
}
/// The network mode and box policy of task `task`'s box (NET-060). The
/// mode is `--network`, else the `network.mode` the project's
/// `minimal.toml` declares for the task, else `host_ip`. The egress is the
/// one the file declares for the task with the egress flags applied by
/// [`crate::effective_egress`], as an activation applies them. With no flag
/// and no declaration, the box is a `host_ip` box with the default policy.
/// An `own_ip` box with no egress gets the deny-all default where the box
/// is created (NET-074), as an activation's does.
///
/// # Errors
///
/// An invalid egress flag or project file, egress on a `none` box
/// (NET-065), and `own_ip` on a host that runs boxes in a VM.
fn task_box_network(
project: &camino::Utf8Path,
task: &str,
verb: RunVerb,
network: Option<crate::CliNetworkMode>,
flags: &crate::EgressArgs,
kind: paths::HostKind,
) -> Result<TaskBoxNetwork, anyhow::Error> {
let flag_egress = crate::flag_egress(flags)?;
let project_egress = crate::task_project_egress(project, task)?;
let file_policy = project_egress.policy.is_some();
let egress = crate::effective_egress(project_egress.policy, flag_egress, flags.deny_all_egress);
tracing::debug!(
egress = ?egress.policy,
sources = ?egress.sources,
"the task box's effective egress"
);
let (mode, mode_layer) = match (network, project_egress.mode) {
(Some(flag), _) => (flag.into(), None),
(None, Some(mode)) => (mode, project_egress.layer.clone()),
(None, None) => (
crate::parse_network_mode(crate::NETWORK_DEFAULT)
.map_err(anyhow::Error::msg)?
.into(),
None,
),
};
let own_ip_available = kind != paths::HostKind::Minvmd;
refuse_egress_on_none(
mode,
egress.policy.is_some(),
flags,
project_egress.layer.as_deref().filter(|_| file_policy),
own_ip_available,
)?;
// An own-address box on a VM host registers with the VM host daemon
// under the name it will have, before its create (T66). A task box is a
// fresh instance, which the daemon names only at the create, so the
// run refuses rather than create a box that no host row holds. This is
// interim (#3162): the refusal goes when a fresh-instance task box can
// register its host row under the name the daemon gives it at the
// create (T66).
if mode == boxes::NetworkMode::OwnIp && kind == paths::HostKind::Minvmd {
let what = match &mode_layer {
Some(layer) => format!(
"{layer} in {file} sets network.mode = \"own_ip\", which",
file = mfile::MFILE_NAME
),
None => "--network own_ip".to_owned(),
};
// A `none` box refuses egress rules, so it is offered only to a box
// that has none.
let remedy = if egress.policy.is_some() {
"Run it with --network host_ip."
} else {
"Run it with --network host_ip or --network none."
};
bail!(
"Cannot run the task: {what} is not available to `{verb}` on a host that runs \
boxes in a VM. {remedy}",
verb = verb.command(),
);
}
Ok(TaskBoxNetwork {
mode,
policy: boxes::BoxPolicy::new(egress.policy, None),
hints: project_egress.hints,
mode_layer,
})
}
/// Applies the run's other `[network]` override flags to the box's
/// network (BCLI-024): `--dynamic-ingress` and `--dynamic-range` set the
/// ingress policy, `--credentialed-upstream` declares the lane to the
/// Box Egress Proxy, and `--quic443` sets the stance on UDP to port 443.
/// Each flag changes only its own key. `--vpn-network-names` is applied to
/// the spec, by [`crate::add_vpn_network_names`], which refuses it when
/// the box has no spec.
///
/// # Errors
///
/// A dynamic ingress flag on a box that is not `own_ip`, as an activation
/// refuses it.
pub(crate) fn apply_run_overrides(
network: &mut TaskBoxNetwork,
other: &crate::BoxOverrideArgs,
) -> Result<(), anyhow::Error> {
crate::refuse_dynamic_ingress_off_own_ip(
network.mode,
other.dynamic_ingress,
other.dynamic_range,
)?;
if other.dynamic_ingress.is_some() || other.dynamic_range.is_some() {
let ingress = network
.policy
.ingress
.get_or_insert_with(boxes::IngressPolicy::default);
ingress.dynamic_ingress = other.dynamic_ingress;
ingress.dynamic_allowed_range = other.dynamic_range;
}
// A task entry declares no secret grants on this path, so the flag is
// the only source of the declaration, with the default proxy settings.
if other.credentialed_upstream && network.policy.credentialed_upstream.is_none() {
network.policy.credentialed_upstream = Some(boxes::CredentialedUpstream::default());
}
// `--quic443` replaces the stance, and no flag keeps the declared one.
if other.quic443.is_some() {
network.policy.quic443 = other.quic443;
}
Ok(())
}
/// Refuses egress rules on a `none` box (NET-065), before the daemon and in
/// the daemon's own words. The refusal names each place the egress came
/// from: each egress flag given, and `file_layer` in minimal.toml when the
/// file declares egress, since the box keeps that egress without the flags.
/// `own_ip_available` says whether the remedy can offer `--network own_ip`.
/// `min task run`, `min box run` and a session start share it.
///
/// # Errors
///
/// The refusal, when `mode` is `none` and `has_egress` is true.
pub(crate) fn refuse_egress_on_none(
mode: boxes::NetworkMode,
has_egress: bool,
flags: &crate::EgressArgs,
file_layer: Option<&str>,
own_ip_available: bool,
) -> Result<(), anyhow::Error> {
if mode != boxes::NetworkMode::NoNet || !has_egress {
return Ok(());
}
let file_layer = file_layer.map(|layer| format!("{layer} in {}", mfile::MFILE_NAME));
let given = given_egress_flags(flags);
let sources = given
.iter()
.map(|flag| (*flag).to_owned())
.chain(file_layer.clone())
.collect::<Vec<_>>();
let mut remedy = if own_ip_available {
"Run it with --network host_ip or --network own_ip".to_owned()
} else {
"Run it with --network host_ip".to_owned()
};
if file_layer.is_none() {
remedy.push_str(&format!(", or without {}", and_list(&given)));
}
// BCLI-034: a usage error, exit 2.
Err(crate::NetworkFlagRefusal {
message: format!(
"{refusal}. The box's egress rules come from {sources}. {remedy}.",
refusal = boxes::PolicyError::EgressRequiresNetwork { mode },
sources = and_list(&sources),
),
}
.into())
}
/// The egress flags `flags` holds, by name.
fn given_egress_flags(flags: &crate::EgressArgs) -> Vec<&'static str> {
[
(!flags.allow_subnets.is_empty(), "--allow-subnets"),
(!flags.allow_dns_hosts.is_empty(), "--allow-dns-hosts"),
(!flags.allow_protocols.is_empty(), "--allow-protocols"),
(!flags.deny_subnets.is_empty(), "--deny-subnets"),
(flags.deny_all_egress, "--deny-all-egress"),
]
.into_iter()
.filter_map(|(given, flag)| given.then_some(flag))
.collect()
}
/// `items` as one list in a sentence: `a`, `a and b`, `a, b and c`.
fn and_list(items: &[impl AsRef<str>]) -> String {
match items {
[] => String::new(),
[only] => only.as_ref().to_owned(),
[rest @ .., last] => format!(
"{} and {}",
rest.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>()
.join(", "),
last.as_ref()
),
}
}
/// The long flags of `min task run` and `min box run` that set the box's
/// network: `--network` and the egress flags, read from their definitions.
fn run_network_flags() -> Vec<String> {
let egress = <crate::EgressArgs as clap::Args>::augment_args(clap::Command::new("run"));
std::iter::once("network")
.chain(egress.get_arguments().filter_map(clap::Arg::get_long))
.map(|long| format!("--{long}"))
.collect()
}
/// The first task argument that names one of the run's own network flags
/// ([`run_network_flags`]), alone or as `<flag>=<value>`. Clap reads every
/// token after the task's first argument as a task argument, so such a flag
/// reaches the task and never sets the box's network. A token after a `--`
/// is the person's own task argument and is never returned.
///
/// `typed` is the command line as typed, and `args` the task arguments
/// clap read, which are its last tokens. Clap drops a `--` that comes
/// before the task's first argument, so `typed` says whether there was
/// one. A `--` among `args` came after a task argument, and clap keeps it.
pub(crate) fn misplaced_run_flag<'a>(typed: &[String], args: &'a [String]) -> Option<&'a str> {
let before_args = typed
.len()
.checked_sub(args.len())
.filter(|&start| typed[start..] == *args)
.map(|start| &typed[..start]);
if before_args.is_some_and(|before| before.iter().any(|token| token == "--")) {
return None;
}
let flags = run_network_flags();
args.iter()
.take_while(|arg| *arg != "--")
.find(|arg| {
let name = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
flags.iter().any(|flag| flag == name)
})
.map(String::as_str)
}
/// The refusal of a run with one of its own network flags among the
/// task's arguments ([`misplaced_run_flag`]): a usage error, which
/// `main.rs` ends with [`Self::EXIT_CODE`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunFlagMisplaced {
entry: String,
flag: String,
}
impl RunFlagMisplaced {
/// The usage-refusal code of the architecture's exit-code table.
pub const EXIT_CODE: u8 = 2;
/// The refusal for `arg`, a flag alone or as `<flag>=<value>`, among
/// the arguments of `entry`.
#[must_use]
pub fn new(entry: &str, arg: &str) -> Self {
Self {
entry: entry.to_string(),
flag: arg
.split_once('=')
.map_or(arg, |(name, _)| name)
.to_string(),
}
}
}
impl std::fmt::Display for RunFlagMisplaced {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self { entry, flag } = self;
write!(
f,
"Cannot run {entry}: {flag} comes after the task's first argument, so it would \
reach the task as an argument and not set the box's network. Put {flag} before \
{entry} to set the box's network, or put -- between {entry} and its arguments to \
pass it to the task."
)
}
}
impl std::error::Error for RunFlagMisplaced {}
/// Writes what a run prints once its box exists, as `min session activate`
/// prints it: the classifier advisory the create reply carries (NET-079),
/// the deny-all default note for an `own_ip` box with no egress rules on a
/// daemon that has not opted out (NET-074, NET-077), and the masked form
/// of each subnet flag that carries host bits. `mode_layer` is the table
/// that set an `own_ip` mode, when the file set it.
pub(crate) fn write_run_notices(
out: &mut impl std::io::Write,
request: &minimald_rpc::CreateSessionRequest,
created: &minimald_rpc::CreateSessionResponse,
egress: &crate::EgressArgs,
mode_layer: Option<&str>,
) -> std::io::Result<()> {
crate::write_classifier_advisory(out, created)?;
if request.config.network == boxes::NetworkMode::OwnIp
&& request.config.policy.egress.is_none()
&& created.deny_all_opt_out != Some(true)
&& crate::deny_all_default_notice(boxes::EGRESS_DEFAULT_PHASE).is_some()
{
let (why, file_remedy) = match mode_layer {
Some(layer) => (
format!(
"{layer} in {file} sets network.mode = \"own_ip\" and no egress rules, so \
the box gets the deny-all default",
file = mfile::MFILE_NAME
),
format!(", or set network.egress in {layer}"),
),
None => (
"a --network own_ip box with no egress rules gets the deny-all default".to_owned(),
String::new(),
),
};
writeln!(
out,
"This box can reach no external address: {why}. To allow outbound traffic, run it \
again with --allow-subnets or --allow-dns-hosts, for example --allow-dns-hosts \
github.com{file_remedy}."
)?;
}
for line in crate::subnet_notices(egress) {
writeln!(out, "{line}")?;
}
Ok(())
}
/// Asks the daemon to run the entrypoint of task box `id`, and returns the
/// channel that relays it: the task's output, then its exit code.
/// `task_env` holds the task's variables, resolved against this shell, for
/// the in-box `min task run` to read. `cwd` is where the entrypoint starts,
/// relative to the uploaded tree (see [`task_run_cwd`]). Empty is the root.
pub(crate) async fn open_task_box_run(
client: &mut crate::client::Client,
id: boxes::SessionId,
task: &str,
cwd: &str,
task_env: &minimald_rpc::taskenv::TaskEnv,
) -> Result<russh::Channel<russh::client::Msg>, anyhow::Error> {
client
.open_session_exec_channel(id, &entrypoint_run_request(task, cwd).encode(), task_env)
.await
}
/// The invocation directory relative to the upload root, `/`-separated:
/// `sub/inner` for a run started there, empty when the user is at the root.
/// The daemon starts a task that declares `inherit_cwd` at the same place
/// inside the uploaded tree.
fn task_run_cwd(upload_root: &camino::Utf8Path, invocation_dir: &camino::Utf8Path) -> String {
invocation_dir
.strip_prefix(upload_root)
.map(|rel| {
rel.components()
.map(|c| c.as_str())
.collect::<Vec<_>>()
.join("/")
})
.unwrap_or_default()
}
/// The refusal of a run whose entry has a terminal (BCLI-010): `min task
/// run` and `min box run` never give a box a terminal, so the entry starts
/// with `min box start --new` instead. The run refuses it before it creates
/// anything, and `main.rs` ends the command with [`Self::EXIT_CODE`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunNeedsTerminal {
entry: String,
}
impl RunNeedsTerminal {
/// The usage-refusal code of the architecture's exit-code table.
pub const EXIT_CODE: u8 = 2;
#[must_use]
pub fn new(entry: &str) -> Self {
Self {
entry: entry.to_string(),
}
}
}
impl std::fmt::Display for RunNeedsTerminal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let entry = &self.entry;
write!(
f,
"{entry} runs with a terminal. Start it with min box start --new {entry}."
)
}
}
impl std::error::Error for RunNeedsTerminal {}
/// The verb a run came from: `min task run` or `min box run`. Both share
/// one run path ([`run_entry`]). The verb only names the command in the
/// run's span and in its refusals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RunVerb {
Task,
Box,
}
impl RunVerb {
fn command(self) -> &'static str {
match self {
Self::Task => "min task run",
Self::Box => "min box run",
}
}
}
/// What a run creates its box from, whichever verb typed it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RunEntry {
pub verb: RunVerb,
pub entry: String,
pub path: Option<String>,
pub detach: bool,
pub network: Option<crate::CliNetworkMode>,
pub egress: crate::EgressArgs,
/// The rest of activate's override flags (BCLI-024, BCLI-075, BCLI-076).
pub other: crate::BoxOverrideArgs,
pub args: Vec<String>,
}
impl From<TaskRunArgs> for RunEntry {
fn from(args: TaskRunArgs) -> Self {
Self {
verb: RunVerb::Task,
entry: args.task,
path: args.path,
detach: args.detach,
network: args.network,
egress: args.egress,
other: args.other,
args: args.args,
}
}
}
impl From<BoxRunArgs> for RunEntry {
fn from(args: BoxRunArgs) -> Self {
Self {
verb: RunVerb::Box,
entry: args.entry,
path: args.path,
detach: args.detach,
network: args.network,
egress: args.egress,
other: args.other,
args: args.args,
}
}
}
/// Refuses an entry whose spec sets `pty_enabled` (BCLI-010): a run never
/// gives its box a terminal. Today the only such entry is the project's
/// session entry, [`mfile::spec::DEFAULT_SESSION_ENTRY`], when no task
/// takes its name. A task's spec never has a terminal. `file` is the
/// project's `minimal.toml`, when there is one. The check reads nothing
/// else, so it runs before the run creates anything.
fn refuse_terminal_entry(file: Option<&mfile::File>, entry: &str) -> Result<(), anyhow::Error> {
let is_task = file.is_some_and(|file| file.task(entry).is_some());
if is_task || entry != mfile::spec::DEFAULT_SESSION_ENTRY {
return Ok(());
}
let spec = mfile::spec::BoxSpec::for_session(
file.and_then(|file| file.session.as_ref()),
mfile::spec::SpecFlags::default(),
);
if spec.pty_enabled {
return Err(RunNeedsTerminal::new(entry).into());
}
Ok(())
}
/// Detaches a run from the box it started (BCLI-010 `--detach`): prints
/// only the box's id on `out`, closes the box's stdin and lets the channel
/// go. The entrypoint runs on without a client, and the box's log keeps
/// its output.
///
/// The id goes out first, because the entrypoint already runs: a later
/// failure must not leave a running box whose id nobody saw. A failure to
/// close stdin or the channel after that is logged, not fatal. Dropping the
/// channel and the connection closes both anyway.
pub(crate) async fn detach_run(
channel: russh::Channel<russh::client::Msg>,
id: boxes::SessionId,
out: &mut impl std::io::Write,
) -> Result<(), anyhow::Error> {
writeln!(out, "{id}").context("write the box id")?;
out.flush().context("write the box id")?;
if let Err(e) = channel.eof().await {
tracing::warn!(box_id = %id, error = %e, "detached run: closing the box's stdin failed");
}
if let Err(e) = channel.close().await {
tracing::warn!(box_id = %id, error = %e, "detached run: leaving the box's run failed");
}
Ok(())
}
/// `min task run` or `min box run` in a directory with no `minimal.toml`
/// in it or above it. The run ends with exit 4 (`main.rs`), the
/// architecture's code for a thing not found.
#[derive(Debug)]
pub struct ProjectFileNotFound {
/// The refusal, with the command that creates the file.
pub message: String,
}
impl ProjectFileNotFound {
/// The architecture's exit code for a thing not found.
pub const EXIT_CODE: u8 = 4;
}
impl std::fmt::Display for ProjectFileNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ProjectFileNotFound {}
/// `min task run` or `min box run` with a task name that the project's
/// `minimal.toml` does not declare. The run ends with exit 4 (`main.rs`),
/// the architecture's code for a thing not found.
#[derive(Debug)]
pub struct TaskNotFound {
/// The refusal, with the tasks the file declares.
pub message: String,
}
impl TaskNotFound {
/// The architecture's exit code for a thing not found.
pub const EXIT_CODE: u8 = 4;
}
impl std::fmt::Display for TaskNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for TaskNotFound {}
/// `min task run` or `min box run` with a `minimal.toml` that does not
/// load. The run ends with exit 3 (`main.rs`), the code the architecture
/// gives an invalid project file, as for `crate::ProjectFileInvalid`.
#[derive(Debug)]
pub struct TaskFileInvalid {
/// Why the file did not load.
pub error: mfile::Error,
}
impl TaskFileInvalid {
/// The architecture's exit code for an invalid project file.
pub const EXIT_CODE: u8 = 3;
}
impl std::fmt::Display for TaskFileInvalid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The cause is in this text and `source()` returns none, so the
// printer's `{:#}` shows it once.
write!(
f,
"found a broken {name} while resolving tasks: {error}",
name = mfile::MFILE_NAME,
error = self.error,
)
}
}
impl std::error::Error for TaskFileInvalid {}
/// Look up `task` in the project's `minimal.toml`, walking up from `dir`
/// like the activate config discovery does, and return its declaration.
/// Errors name the fix: untrimmed name → the whitespace rejection; no
/// config → `min init`; unknown task → the declared list.
///
/// The declaration comes back rather than being discarded because the
/// client needs its `env_vars` to resolve them here — see
/// [`resolve_task_env`].
pub(crate) fn declared_task(
dir: &camino::Utf8Path,
task: &str,
) -> Result<mfile::Task, anyhow::Error> {
// Rejected before any lookup: the daemon trims the task name out of the
// exec command string, so a name with leading/trailing whitespace can
// never round-trip into the box — even if minimal.toml declares it.
if task.trim() != task {
bail!(untrimmed_task_message(task));
}
let file = match mfile::File::from_dir_recursive(dir.as_std_path()) {
Ok(f) => f,
// BCLI-034: no project file is a thing not found (exit 4).
Err(mfile::Error::NotFound) => {
return Err(ProjectFileNotFound {
message: format!(
"no {name} found at {dir} (or any parent directory); \
run `min init` to create one",
name = mfile::MFILE_NAME,
),
}
.into());
}
// BCLI-078: a project file that does not load exits 3. This path
// also serves `min task run`, which starts no box, so the refusal
// keeps its own text.
Err(error) => return Err(TaskFileInvalid { error }.into()),
};
match file.task(task) {
Some(t) => Ok(t),
// BCLI-034: a task name the file does not declare is a thing not
// found (exit 4). The text is the same as before.
None => Err(TaskNotFound {
message: unknown_task_message(&file, task),
}
.into()),
}
}
/// Resolve a task's declared `env_vars` against the invoking shell, so the
/// values reach the daemon already resolved.
///
/// `{ inherit = true }` means "take this from the invoking process", and
/// the only process that can honour it is this one. The daemon runs
/// elsewhere — on macOS, inside the microVM — so its `std::env::var` reads
/// the daemon's own environment, which the user's `export` never reaches
/// (#585). `[session.vars]` has always resolved here, at activation, which
/// is exactly why the two behaved differently in the same project.
///
/// Literal values are carried too, not just inherited ones: the daemon
/// applies one consistent set rather than resolving half of them itself.
///
/// A variable that is declared `inherit` but unset is refused here, naming
/// the task and the variable, instead of surfacing as the daemon's
/// `failed to spawn process` after a session has already been built.
///
/// # Policy
///
/// Every name goes through [`VarsPolicy::check`] with
/// [`Source::Project`] provenance, and the check happens *before* the
/// lookup. That ordering is the security property: resolving here reads
/// the user's own shell, so a `minimal.toml` naming
/// `env_vars.AWS_SECRET_ACCESS_KEY = { inherit = true }` would otherwise
/// hand a hostile project a real credential. A denied or unapproved name
/// never has its value read at all.
///
/// The full check applies, `allow` included — a task's `env_vars` are
/// declared by the project, and the project is exactly what the policy
/// exists to constrain. `[session.vars]` from the same file has always
/// been gated this way; a task's were the inconsistency.
///
/// - `deny` fails the run, naming the rule's file.
/// - `ignore` drops the name.
/// - `allow` carries it.
/// - anything else is referred to `hooks`, which prompts on a terminal
/// and refuses everywhere else.
///
/// A dropped name goes into [`TaskEnv::drop`] rather than simply being
/// left out. The daemon applies the resolved values by insertion, so a
/// name it is not told about keeps whatever `minimal.toml` declared —
/// which for an `inherit` entry means the daemon resolving it against its
/// own environment, exactly what the user asked not to happen.
///
/// An echo task resolves to nothing at all, whatever it declares. The daemon
/// answers one straight from the declaration and returns before it builds an
/// environment (`crates/minimald/src/exec.rs`), so its `env_vars` are read by
/// no one. Resolving them would fail a run that works today over a variable
/// the task has no use for, and gate one over a name it never sees.
///
/// [`VarsPolicy::check`]: boxes::core::policy::VarsPolicy::check
/// [`Source::Project`]: boxes::core::source::Source::Project
/// [`TaskEnv::drop`]: minimald_rpc::taskenv::TaskEnv::drop
fn resolve_task_env(
task: &mfile::Task,
task_name: &str,
vars_policy: boxes::core::policy::VarsPolicy,
policy_path: &std::path::Path,
source: &boxes::core::source::Source,
hooks: &dyn boxes::core::hooks::PolicyHooks,
env: impl Fn(&str) -> Result<String, std::env::VarError>,
) -> Result<minimald_rpc::taskenv::TaskEnv, anyhow::Error> {
use boxes::core::compose::NameVerdict;
let mut resolved = minimald_rpc::taskenv::TaskEnv::default();
if task.action.as_echo().is_some() {
return Ok(resolved);
}
// Order comes off the map, which is a `BTreeMap` (#1319): which
// variable a user is prompted about first, and which denial is
// reported, are fixed by the declaration's own key order rather than
// by a sort here.
let names: Vec<&str> = task.vars.keys().map(String::as_str).collect();
// The gate is `boxes`' own — the same three passes the session
// composer runs, called with names alone so that no value is read
// before the policy has spoken.
let pairs: Vec<(&str, &boxes::core::source::Source)> =
names.iter().map(|n| (*n, source)).collect();
let (verdicts, _policy) =
match boxes::core::compose::gate_names(&pairs, vars_policy, Some(hooks)) {
Ok(out) => out,
// The gate stops at the first denial and names it. Reported
// here rather than relayed, so the operator gets the task, the
// variable, and the file the rule lives in.
Err(boxes::core::compose::ComposeError::Denied { what, .. }) => {
bail!(denied_task_var_message(task_name, &what, policy_path))
}
Err(e) => {
return Err(anyhow::Error::new(e))
.with_context(|| format!("gating `env_vars` for task '{task_name}'"));
}
};
let mut approved: Vec<&str> = Vec::new();
for (name, verdict) in names.iter().zip(verdicts) {
match verdict {
NameVerdict::Allowed => approved.push(name),
NameVerdict::Ignored => {
resolved.drop.insert((*name).to_string());
}
}
}
// Only now is anything read out of this shell.
for name in approved {
let value = match &task.vars[name] {
mfile::EnvVarValue::Value(v) => v.clone(),
mfile::EnvVarValue::Inherit => env(name).map_err(|_| {
anyhow::anyhow!(
"task '{task_name}' declares `env_vars.{name} = {{ inherit = true }}`, \
but {name} is not set in this shell; export it before running the task"
)
})?,
};
resolved.set.insert(name.to_string(), value);
}
Ok(resolved)
}
/// Gate a task's `env_vars` against the user policy and resolve them
/// against this shell ([`resolve_task_env`]), in the lane the terminal
/// allows: the interactive prompt on a real terminal, the collect-and-refuse
/// [`RefuseAndRecord`] anywhere else. Returns the resolved set and the
/// policy as the prompt left it, which the interactive lane has already
/// saved.
///
/// Shared by `min task run` and `min session run` (inbox#778), so the two
/// verbs pass one gate and print one refusal.
pub(crate) fn gate_task_env(
global: &GlobalArgs,
declared: &mfile::Task,
task_name: &str,
source: &boxes::core::source::Source,
user_policy: boxes::core::policy::UserPolicy,
policy_path: &std::path::Path,
env: impl Fn(&str) -> Result<String, std::env::VarError>,
) -> Result<
(
minimald_rpc::taskenv::TaskEnv,
boxes::core::policy::UserPolicy,
),
anyhow::Error,
> {
// Gated against `[vars]` on the way, `allow` included. Resolving here
// reads the user's own shell, so the project naming a variable is the
// project asking for its value — the same two lanes as an activate: the
// interactive prompt on a real terminal, the collect-and-refuse
// `NoPromptHook` anywhere else.
let non_interactive = global.no_input || !crate::can_prompt_interactively();
if non_interactive {
let hooks = RefuseAndRecord::default();
let task_env = resolve_task_env(
declared,
task_name,
user_policy.vars().clone(),
policy_path,
source,
&hooks,
env,
);
// Checked before the result: the hook refused, so `task_env` is
// the abort error and the names are the useful half of it.
let refused = hooks.into_names();
if !refused.is_empty() {
let count = refused.len();
let snippet = refused_vars_snippet(&refused);
bail!(
"task '{task_name}' declares {count} environment variable{s} that your \
policy does not allow, and stdin/stderr is not a terminal.\n\n\
Add the following to {path}:\n\n{snippet}\n\
Then re-run this command.",
path = policy_path.display(),
s = if count == 1 { "" } else { "s" },
);
}
Ok((task_env?, user_policy))
} else {
let hooks = crate::prompt::InteractivePrompt::new(policy_path, user_policy.clone());
let task_env = resolve_task_env(
declared,
task_name,
user_policy.vars().clone(),
policy_path,
source,
&hooks,
env,
);
// Persist before propagating a refusal: a rule the user chose to
// record is theirs whether or not this run goes on to fail.
let after = hooks.into_final_policy();
if after != user_policy {
match crate::prompt::save_user_policy(policy_path, &after) {
Ok(()) => eprintln!("Updated {}", policy_path.display()),
Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()),
}
}
Ok((task_env?, after))
}
}
/// The `env_vars` of `task` for a `min session run` against a session built
/// from the project at `project_path`, gated and resolved here as
/// `min task run` does them ([`gate_task_env`]) (inbox#778).
///
/// The declaration is read from the project on this host, the only copy the
/// client can read. The daemon runs the task from the session's own copy,
/// taken at activation, so the two can differ. The daemon is told the
/// client resolved the task, and it then refuses an `inherit` this set does
/// not answer rather than reading its own environment for it. A project
/// with no `minimal.toml` here, or one that does not declare `task` (a task
/// a stack provides), yields an empty set for the same reason: the run goes
/// on, and only an `inherit` stops it. A `minimal.toml` that is there but
/// does not load is refused here, as `declared_task` refuses it, so the
/// daemon's refusal never stands in for the real cause.
pub(crate) fn session_run_task_env(
global: &GlobalArgs,
project_path: &camino::Utf8Path,
task: &str,
env: impl Fn(&str) -> Result<String, std::env::VarError>,
) -> Result<minimald_rpc::taskenv::TaskEnv, anyhow::Error> {
// The daemon trims the name it is sent, so the lookup does too.
let task = task.trim();
let file = match mfile::File::from_dir_recursive(project_path.as_std_path()) {
Ok(file) => file,
Err(mfile::Error::NotFound) => {
tracing::debug!(
project = %project_path,
"no minimal.toml for the session's project on this host"
);
return Ok(minimald_rpc::taskenv::TaskEnv::default());
}
Err(e) => bail!(
"found a broken {name} in the session's project at {project_path} \
while resolving tasks: {e}",
name = mfile::MFILE_NAME,
),
};
let Some(declared) = file.task(task) else {
return Ok(minimald_rpc::taskenv::TaskEnv::default());
};
let policy_path = crate::config::user_policy_path(global);
let user_policy = crate::config::read_user_policy(global)?;
let source = boxes::core::source::Source::Project {
path: paths::HostPath::try_new(project_path.to_path_buf())
.context("Invalid project path")?,
};
let (task_env, _) = gate_task_env(
global,
&declared,
task,
&source,
user_policy,
&policy_path,