Repository navigation
Expand file tree
/
Copy pathtui.rs
More file actions
2165 lines (2002 loc) · 86.8 KB
/
Copy pathtui.rs
File metadata and controls
2165 lines (2002 loc) · 86.8 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
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::time::Duration;
use std::path::Path;
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use crate::executor::{plan_display, LeafPrivilege, LeafView};
use crate::protocol::{Plan, RedirTarget, Response, RunAs, Status, Stream, ValidatedRequest};
/// Quote a single token for safe, paste-able POSIX shell. Anything outside a
/// conservative unquoted-safe set is wrapped in single quotes (with embedded
/// single quotes escaped as `'\''`), so a token like `a;b` or `$x` cannot be
/// re-parsed by the shell. This is what makes the `Command:` one-liner copyable.
pub fn shquote(a: &str) -> String {
let safe = !a.is_empty()
&& a.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_./:=@%+,-".contains(&b));
if safe {
a.to_string()
} else {
format!("'{}'", a.replace('\'', "'\\''"))
}
}
/// Join argv into a shell command string with each token safely quoted.
pub fn shell_join(argv: &[String]) -> String {
argv.iter()
.map(|a| shquote(a))
.collect::<Vec<_>>()
.join(" ")
}
/// Join a pipeline of stages into a shell-like display string with ` | ` separators.
pub fn pipeline_join(pipeline: &[Vec<String>]) -> String {
pipeline
.iter()
.map(|argv| shell_join(argv))
.collect::<Vec<_>>()
.join(" | ")
}
/// A one-line, copy-paste-executable shell rendering of a request's command:
/// the `Steps:` block flattened onto one line. Both are printed from the same
/// [`Lay`] tree, so they carry exactly the same parentheses and must parse, as
/// shell, to the same tree (see [`steps_shell_text`]). `setenv`/`chdir` become
/// scoped subshells, pipes and mixed-operator chains are parenthesized, and
/// `run-as` is threaded onto each leaf as `sudo`/`sudo -u` (matching the
/// executor's per-leaf escalation) — so a privilege-free plan pastes and runs as
/// you, and a privileged one pastes and runs with auth. Used for the `Command:`
/// line, logs, and the compact banner.
pub fn command_summary(req: &ValidatedRequest) -> String {
lay_command(&request_layout(req))
}
/// The `Steps:` block as plain shell text — uncoloured, unnumbered, one step per
/// line, indented by parenthesis depth. This is what bash reads if the block is
/// pasted, and it must parse to the same tree as [`command_summary`]: the
/// operator reviews one and may paste the other, so they can never disagree.
pub fn steps_shell_text(req: &ValidatedRequest) -> String {
steps_lines(&request_layout(req), &style_for(true))
.iter()
.map(|l| format!("{}{}{}", " ".repeat(l.depth), l.text, l.comment(&style_for(true))))
.collect::<Vec<_>>()
.join("\n")
}
/// Ambient escalation context: a `privileged` request runs every leaf as root,
/// mirroring the executor, so each leaf gets its own `sudo` (never a single
/// `sudo sh -c '…'`, which would put a shell back on the root path) and reads
/// light red. A `run-as` node overrides it per subtree.
fn ambient_ctx(privileged: bool) -> LayCtx {
LayCtx {
sudo: if privileged { "sudo ".into() } else { String::new() },
accepted: Vec::new(),
esc: Esc {
uid: if privileged { StepUid::Root } else { StepUid::Default },
boundary: false,
},
}
}
fn request_layout(req: &ValidatedRequest) -> Lay {
layout(&req.exec_plan(), &ambient_ctx(req.privileged))
}
/// The shell operators of the display.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Op {
Seq,
And,
Or,
Pipe,
}
impl Op {
fn sym(self) -> &'static str {
match self {
Op::Seq => ";",
Op::And => "&&",
Op::Or => "||",
Op::Pipe => "|",
}
}
}
/// The display layout of a plan, shared by the `Command:` line and the `Steps:`
/// block so both show the same grouping by construction. The grouping rules
/// (see `docs/testing.md`, "How the prompt shows grouping"):
///
/// - a chain holds one operator; a nested chain of the same operator is flattened
/// into it, one of another operator is parenthesized — so every line of a
/// `Steps:` group ends with the same operator;
/// - a pipe is always parenthesized;
/// - a `cd`/`export` scope is `( cd D && ( body ) )`: nothing leaks out of it,
/// even when the whole plan is the scope (the `Command:` line is pasted into a
/// stateful shell), and a failed `cd` skips the body instead of running it in
/// the previous directory.
enum Lay {
/// One command line: `cmd` (with any `sudo` prefix) plus its redirections.
/// A `scope` leaf is the `cd`/`export` header of a scope, never escalated.
Leaf {
cmd: String,
redir: String,
esc: Esc,
scope: bool,
/// A remark for the `Steps:` block only, printed as a trailing shell
/// comment (e.g. which exit codes count as success). Never part of the
/// `Command:` line.
note: String,
},
/// Explicit parentheses, with redirections applied to the whole group.
Group { inner: Box<Lay>, redir: String },
/// Two or more items joined by one operator.
Chain { op: Op, items: Vec<Lay> },
}
/// The `sudo` prefix and colouring threaded down from the enclosing `run-as`,
/// and the exit codes the enclosing `with-accepted-exit-codes` treats as
/// success (the innermost one wins, as in the executor).
struct LayCtx {
sudo: String,
esc: Esc,
accepted: Vec<i32>,
}
fn layout(plan: &Plan, ctx: &LayCtx) -> Lay {
match plan {
Plan::Exec { argv } => lay_leaf(format!("{}{}", ctx.sudo, shell_join(argv)), ctx),
Plan::Shell { shell, script } => {
let bin = match shell {
crate::protocol::ShellProc::Sh => "sh",
crate::protocol::ShellProc::Bash => "bash",
};
lay_leaf(format!("{}{bin} -c {}", ctx.sudo, shquote(script)), ctx)
}
Plan::Pipe { stages } => lay_group(lay_chain(Op::Pipe, stages, ctx)),
Plan::Run { steps } => lay_chain(Op::And, steps, ctx),
Plan::Alt { steps } => lay_chain(Op::Or, steps, ctx),
Plan::Seq { steps } => lay_chain(Op::Seq, steps, ctx),
Plan::Redirect { stream, target, body } => {
lay_redirect(layout(body, ctx), redir_suffix(*stream, target))
}
Plan::WithStdinFrom { path, body } => {
lay_redirect(layout(body, ctx), format!("< {}", shquote(path)))
}
Plan::Setenv { key, value, body } => {
lay_scope(format!("export {key}={}", shquote(value)), layout(body, ctx))
}
Plan::Chdir { dir, body } => lay_scope(format!("cd {}", shquote(dir)), layout(body, ctx)),
Plan::RunAs { who, body } => {
let ctx2 = match who {
RunAs::Root => LayCtx {
sudo: "sudo ".into(),
esc: Esc { uid: StepUid::Root, boundary: true },
accepted: ctx.accepted.clone(),
},
RunAs::User { name } => LayCtx {
sudo: format!("sudo -u {} ", shquote(name)),
esc: Esc { uid: StepUid::User, boundary: true },
accepted: ctx.accepted.clone(),
},
};
layout(body, &ctx2)
}
Plan::WithAcceptedExitCodes { codes, body } => {
let ctx2 = LayCtx { sudo: ctx.sudo.clone(), esc: ctx.esc, accepted: codes.clone() };
layout(body, &ctx2)
}
}
}
/// A command leaf. Under `with-accepted-exit-codes`, the command is wrapped so
/// that, as shell, an accepted non-zero exit counts as success exactly as it
/// does for the executor's `&&` / `||` / pipe status:
/// `{ cmd || [ $? -eq 1 ]; }`, or with several codes
/// `{ cmd || case $? in 1|2) ;; *) false ;; esac; }`. The `Steps:` block also
/// spells the accepted codes out in a trailing comment.
fn lay_leaf(cmd: String, ctx: &LayCtx) -> Lay {
let mut codes: Vec<i32> = ctx.accepted.iter().copied().filter(|&c| c != 0).collect();
codes.sort_unstable();
codes.dedup();
let (cmd, note) = match codes.as_slice() {
[] => (cmd, String::new()),
[c] => (format!("{{ {cmd} || [ $? -eq {c} ]; }}"), format!("exit {c} accepted")),
cs => {
let list = cs.iter().map(i32::to_string).collect::<Vec<_>>();
(
format!("{{ {cmd} || case $? in {}) ;; *) false ;; esac; }}", list.join("|")),
format!("exits {} accepted", list.join(", ")),
)
}
};
Lay::Leaf { cmd, redir: String::new(), esc: ctx.esc, scope: false, note }
}
/// Parenthesize, unless the layout already is a bare group.
fn lay_group(l: Lay) -> Lay {
match l {
g @ Lay::Group { .. } if matches!(&g, Lay::Group { redir, .. } if redir.is_empty()) => g,
other => Lay::Group { inner: Box::new(other), redir: String::new() },
}
}
fn lay_chain(op: Op, steps: &[Plan], ctx: &LayCtx) -> Lay {
let mut items = Vec::new();
for s in steps {
match layout(s, ctx) {
// Same operator: associative, so flatten into this chain.
Lay::Chain { op: o, items: sub } if o == op => items.extend(sub),
// Another operator: its own group, so a line's operator never
// reaches further than its group.
c @ Lay::Chain { .. } => items.push(lay_group(c)),
other => items.push(other),
}
}
if items.len() == 1 {
return items.pop().expect("one item");
}
Lay::Chain { op, items }
}
fn lay_redirect(l: Lay, suffix: String) -> Lay {
match l {
Lay::Leaf { cmd, redir, esc, scope, note } => {
Lay::Leaf { cmd, redir: join_suffix(redir, &suffix), esc, scope, note }
}
Lay::Group { inner, redir } => Lay::Group { inner, redir: join_suffix(redir, &suffix) },
c @ Lay::Chain { .. } => Lay::Group { inner: Box::new(c), redir: suffix },
}
}
/// `( header && ( body ) )` — the scope's own parentheses keep `cd`/`export` from
/// leaking past it, and `&&` skips the body when the header fails (a failed
/// `cd` must not run the body in the previous directory; the executor refuses
/// it too).
fn lay_scope(header: String, body: Lay) -> Lay {
let head = Lay::Leaf {
cmd: header,
redir: String::new(),
esc: Esc { uid: StepUid::Default, boundary: false },
scope: true,
note: String::new(),
};
Lay::Group {
inner: Box::new(Lay::Chain { op: Op::And, items: vec![head, lay_group(body)] }),
redir: String::new(),
}
}
fn join_suffix(s: String, suffix: &str) -> String {
match (s.is_empty(), suffix.is_empty()) {
(_, true) => s,
(true, false) => suffix.to_string(),
(false, false) => format!("{s} {suffix}"),
}
}
/// The `Command:` one-liner: the layout with every group on one line.
fn lay_command(l: &Lay) -> String {
match l {
Lay::Leaf { cmd, redir, .. } => join_suffix(cmd.clone(), redir),
Lay::Group { inner, redir } => {
let s = lay_command(inner);
// `((` would open an arithmetic command in bash: keep openers apart.
let open = if s.starts_with('(') { "( " } else { "(" };
join_suffix(format!("{open}{s})"), redir)
}
Lay::Chain { op, items } => {
let sep = match op {
Op::Seq => "; ".to_string(),
_ => format!(" {} ", op.sym()),
};
items.iter().map(lay_command).collect::<Vec<_>>().join(&sep)
}
}
}
/// The redirection suffix for a stream/target pair, paths safely quoted.
fn redir_suffix(stream: Stream, target: &RedirTarget) -> String {
match (stream, target) {
(Stream::Stdout, RedirTarget::File { path, mode }) => {
format!("{} {}", redir_arrow(*mode), shquote(path))
}
(Stream::Stderr, RedirTarget::File { path, mode }) => {
format!("2{} {}", redir_arrow(*mode), shquote(path))
}
(Stream::Both, RedirTarget::File { path, mode }) => {
format!("{} {} 2>&1", redir_arrow(*mode), shquote(path))
}
(Stream::Stdout, RedirTarget::DevNull) => "> /dev/null".to_string(),
(Stream::Stderr, RedirTarget::DevNull) => "2> /dev/null".to_string(),
(Stream::Both, RedirTarget::DevNull) => "> /dev/null 2>&1".to_string(),
}
}
fn redir_arrow(mode: crate::protocol::WriteMode) -> &'static str {
match mode {
crate::protocol::WriteMode::Append => ">>",
crate::protocol::WriteMode::Truncate => ">",
}
}
/// Styling for the approval prompt. `bold`/`dim`/`reset` are weight-only. A
/// step's command is colored by the uid it runs as, in two red intensities so
/// the escalation *boundary* stands out from ambient escalation: `root` (light
/// red) = a leaf that runs as root because the whole request is privileged;
/// `root_boundary` (bright red) = the explicit `run-as`/`sudo` leaf; `user`
/// (bright yellow) = a `run-as` to a named non-root user. Operators of an
/// all-escalated group are tinted `root` too. All escapes are empty when
/// NO_COLOR is set (https://no-color.org); output always targets /dev/tty.
#[derive(Clone, Copy)]
struct Style {
bold: &'static str,
dim: &'static str,
reset: &'static str,
/// Ambient root (whole plan privileged) — light red.
root: &'static str,
/// Explicit `run-as`/`sudo` root boundary — bright red.
root_boundary: &'static str,
/// `run-as` to a named non-root user — bright yellow.
user: &'static str,
}
fn style() -> Style {
style_for(std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()))
}
/// Pure split so the NO_COLOR mapping is unit-testable without mutating the
/// process-wide environment.
fn style_for(no_color: bool) -> Style {
if no_color {
Style { bold: "", dim: "", reset: "", root: "", root_boundary: "", user: "" }
} else {
Style {
bold: "\x1b[1m",
dim: "\x1b[2m",
reset: "\x1b[0m",
root: "\x1b[38;5;210m", // light red
root_boundary: "\x1b[38;5;196m", // bright red
user: "\x1b[38;5;226m", // bright yellow
}
}
}
/// Attention cues emitted just before the `Execute?` question so an unfocused or
/// off-screen daemon terminal does not sit silently until the timeout denies the
/// request. The terminal bell (BEL) is the primary cue — terminals map it to an
/// audible beep and, for an unfocused window, the WM/dock urgency hint; the
/// blink wraps the question text as an in-window fallback for terminals that
/// render no bell. Both default on; each is independently suppressed by its own
/// env var (gated separately from NO_COLOR, which governs color/weight).
#[derive(Clone, Copy)]
struct Alert {
bell: &'static str, // "\x07" or ""
blink_on: &'static str, // "\x1b[5m" or ""
blink_off: &'static str, // "\x1b[25m" or ""
}
fn alert() -> Alert {
alert_for(
std::env::var_os("SUDO_PROXY_NO_BELL").is_some_and(|v| !v.is_empty()),
std::env::var_os("SUDO_PROXY_NO_BLINK").is_some_and(|v| !v.is_empty()),
)
}
/// Pure split so the env mapping is unit-testable without mutating the
/// process-wide environment (same pattern as `style_for`). Bell and blink are
/// independent — each honors only its own flag.
fn alert_for(no_bell: bool, no_blink: bool) -> Alert {
Alert {
bell: if no_bell { "" } else { "\x07" },
blink_on: if no_blink { "" } else { "\x1b[5m" },
blink_off: if no_blink { "" } else { "\x1b[25m" },
}
}
/// Upper bound on the command string shown at the approval prompt. A caller
/// could otherwise submit a multi-kilobyte argument that wraps over dozens of
/// lines and pushes the `[y/N]` question off-screen, so the human approves
/// without it in view. Bounded display keeps the prompt anchored; the marker
/// makes truncation explicit so an over-long command reads as suspicious
/// rather than benign.
const MAX_DISPLAY_CMD_CHARS: usize = 1024;
/// Upper bound on the number of plan stages rendered line-by-line at the prompt.
/// A plan with more stages than this has its tail hidden behind an explicit
/// marker, so a wide plan cannot push the `[y/N]` question off-screen — the same
/// anti-flooding rationale as `MAX_DISPLAY_CMD_CHARS`, applied to stage count.
const MAX_DISPLAY_STAGES: usize = 32;
/// Truncate an approval-prompt command string to a bounded number of
/// characters, appending an explicit marker when it was shortened.
pub fn truncate_for_display(s: &str) -> String {
let count = s.chars().count();
if count <= MAX_DISPLAY_CMD_CHARS {
return s.to_string();
}
let head: String = s.chars().take(MAX_DISPLAY_CMD_CHARS).collect();
let hidden = count - MAX_DISPLAY_CMD_CHARS;
format!("{head}… [{hidden} more chars hidden — full command not shown]")
}
#[derive(Debug, PartialEq)]
pub enum PromptResult {
Approved,
/// Approve this request *and*, if the daemon is eligible, grant unattended
/// unprivileged execution for the rest of this session (in-memory, never
/// persisted). Only emitted for unprivileged requests; privileged prompts
/// never offer this. The dispatcher grants the session only when the
/// daemon's `unattended_eligible` policy is set — otherwise this approves
/// the single command and nothing more.
ApprovedAlways,
Denied,
Timeout,
}
/// Asks the user to approve or deny a privilege request. `eligible` reflects
/// the daemon's `unattended_eligible` policy: when set (and the request is
/// unprivileged) the prompt offers the session-scoped `a` answer, otherwise it
/// shows a plain `[y/N]`.
pub trait Prompter: Send + Sync {
fn prompt(
&self,
req: &ValidatedRequest,
eligible: bool,
timeout: Duration,
) -> io::Result<PromptResult>;
}
/// Echoes the result of a completed command back to the user.
pub trait ResultSink: Send + Sync {
fn display(&self, resp: &Response) -> io::Result<()>;
}
pub struct TtyPrompter;
impl Prompter for TtyPrompter {
fn prompt(
&self,
req: &ValidatedRequest,
eligible: bool,
timeout: Duration,
) -> io::Result<PromptResult> {
prompt_tty(req, eligible, timeout)
}
}
pub struct TtyResultSink;
impl ResultSink for TtyResultSink {
fn display(&self, resp: &Response) -> io::Result<()> {
display_result(resp)
}
}
pub struct NoopResultSink;
impl ResultSink for NoopResultSink {
fn display(&self, _resp: &Response) -> io::Result<()> {
Ok(())
}
}
/// Classify a single keypress into an approval decision. Pure (no I/O): the
/// sole source of `ApprovedAlways` is `'a'`/`'A'` on an *unprivileged* request;
/// the sole source of `Approved` is `'y'`/`'Y'`; `None` (the read timed out) is
/// `Timeout`; every other byte denies. This is the transition function the
/// Rung 4 state-machine model and the Rung 5 dispatch contract both target —
/// keeping it free of the TTY writes lets the property test cover it
/// exhaustively over the whole `(Option<u8>, bool)` input domain.
pub(crate) fn classify_key(key: Option<u8>, privileged: bool) -> PromptResult {
match key {
None => PromptResult::Timeout,
Some(b'y' | b'Y') => PromptResult::Approved,
Some(b'a' | b'A') if !privileged => PromptResult::ApprovedAlways,
Some(_) => PromptResult::Denied,
}
}
/// Display a privilege request on /dev/tty and ask for Y/N confirmation.
/// `eligible` gates whether the session-scoped `a` answer is offered (only for
/// unprivileged requests on a daemon whose `unattended_eligible` policy is set).
pub fn prompt_tty(
req: &ValidatedRequest,
eligible: bool,
timeout: Duration,
) -> io::Result<PromptResult> {
let mut tty_w = OpenOptions::new().write(true).open("/dev/tty")?;
let tty_r = File::open("/dev/tty")?;
let st = style();
let Style { bold, dim, reset, .. } = st;
write_request_header(&mut tty_w, req, &st)?;
let client_ver = if req.version.is_empty() { "(unknown)" } else { req.version.as_str() };
writeln!(tty_w, "Client: sudo-proxy {client_ver}")?;
if !req.time.is_empty() {
writeln!(tty_w, "Time: {}", req.time)?;
}
writeln!(tty_w, "ID: {}", req.id)?;
if !req.reason.is_empty() {
writeln!(tty_w, "Reason: {bold}{}{reset}", req.reason)?;
}
let agent_tag = if req.forward_agent {
format!(" {dim}(agent forwarded){reset}")
} else {
String::new()
};
writeln!(
tty_w,
"Command: {bold}{}{reset}{agent_tag}",
truncate_for_display(&command_summary(req))
)?;
// Render every stage the executor will run, each with its run-as context
// and its resolved real binary. This is the structural guarantee the plan
// model buys: the vacuous single `/usr/bin/bash` resolves line is replaced
// by one resolved binary per literal stage, so a bundle of root effects can
// no longer hide inside one opaque command. Built from the same
// `compile_plan` walk the executor uses, so prompt and execution agree.
match plan_display(req) {
Ok(views) => write_plan_stages(&mut tty_w, &req.exec_plan(), &views, req.privileged, &st)?,
Err(e) => writeln!(tty_w, "{bold}⚠ invalid plan: {e}{reset}")?,
}
if !req.env.is_empty() {
let env_display: Vec<String> = req.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
writeln!(tty_w, "Env: {}", env_display.join(" "))?;
}
// Effective privilege, not the raw `privileged` flag: a plan that smuggles
// a `RunAs` node is gated exactly like a top-level privileged request, so
// `a` is never offered for it and root wording is shown when any stage is
// root. `a` is offered only when this daemon is `unattended_eligible` (an
// out-of-band operator opt-in).
let effective_priv = req.effective_privileged();
let offer_always = eligible && !effective_priv;
let (question, choices) = if req.runs_as_root() {
("Execute as root?", "[y/N]")
} else if effective_priv {
// Escalation only to a named non-root user (no root stage).
("Execute with elevated privileges?", "[y/N]")
} else if offer_always {
// The grant is keyed by the request's `session` (issue #8): name it, so
// the operator sees exactly which client `a` opens the gate for.
writeln!(
tty_w,
"{dim}a = approve, and run later unprivileged requests from session \
'{}' on this host without asking until the daemon exits (not saved){reset}",
req.session
)?;
("Execute?", "[y/N/a]")
} else {
("Execute?", "[y/N]")
};
let cues = alert();
write_question_line(&mut tty_w, &cues, question, choices, timeout.as_secs())?;
tty_w.flush()?;
// Read single keypress with timeout (no Enter needed), then classify it
// with the pure decision function so the TTY echo and the security-
// relevant mapping cannot drift apart. Pass effective privilege so `a`
// (ApprovedAlways) can never be produced for a plan that escalates.
let result = classify_key(read_key_timeout(&tty_r, timeout)?, effective_priv);
let label = match result {
PromptResult::Timeout => "Timeout",
PromptResult::Approved => "Approved",
// `a` on an eligible daemon grants the session; pressed when `a` was
// not offered it degrades to a plain approve-once (the dispatcher will
// not grant), so label it honestly.
PromptResult::ApprovedAlways if offer_always => "Approved (unattended for this session name)",
PromptResult::ApprovedAlways => "Approved",
PromptResult::Denied => "Denied",
};
// Answered or timed out: the question no longer needs attention.
write_settled_question_line(&mut tty_w, &cues, question, choices, timeout.as_secs())?;
writeln!(tty_w, "\n→ {label}")?;
writeln!(tty_w, "{bold}━━━━━━━━━━━━━━━━━━━━━━━━━{reset}")?;
Ok(result)
}
/// Why this daemon's terminal accepts injected keystrokes, when the operator
/// started it anyway (`--allow-injectable-tty`, GHSA-cpmp-67wf-gwmx). Set once
/// at startup; every prompt then carries a warning line.
static INJECTABLE_TTY: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
/// Record the injectable-terminal reasons shown in every prompt header.
pub fn set_injectable_tty_warning(reasons: Vec<String>) {
let _ = INJECTABLE_TTY.set(reasons);
}
/// The prompt's warning line for an injectable terminal, or `None`. Each
/// reason is `<mechanism>: <how>`; the line names the mechanisms.
fn injectable_tty_line(reasons: &[String], style: &Style) -> Option<String> {
if reasons.is_empty() {
return None;
}
let Style { bold, reset, .. } = *style;
Some(format!(
"{bold}⚠ Other processes can type into this terminal ({}). \
Approve only what you asked for.{reset}",
reasons
.iter()
.map(|r| r.split(": ").next().unwrap_or(r).trim())
.collect::<Vec<_>>()
.join("; ")
))
}
/// Write the prompt header: the `━━━ Privilege Request ━━━` title, the `From:`
/// line and, when the requester declared one, its self-identification (issue
/// #25). A requester declaring itself an AI (`ai` / `ai:<id>`) gets a single
/// bold yellow `[AI-AGENT REQUEST]` banner above the title — one eye-catcher,
/// the rest of the prompt stays uncolored. The value is client-asserted, so the
/// line says so; an empty one (legacy peer) renders nothing. Writer-generic so
/// the bytes are unit-testable without /dev/tty.
fn write_request_header<W: Write>(w: &mut W, req: &ValidatedRequest, st: &Style) -> io::Result<()> {
let Style { bold, reset, user, .. } = *st;
writeln!(w)?;
if req.requester_is_ai() {
writeln!(w, "{bold}{user}[AI-AGENT REQUEST]{reset}")?;
}
writeln!(w, "{bold}━━━ Privilege Request ━━━{reset}")?;
if let Some(line) = INJECTABLE_TTY.get().and_then(|r| injectable_tty_line(r, st)) {
writeln!(w, "{line}")?;
}
writeln!(
w,
"From: {} @ {}",
req.session,
if req.host.is_empty() { "local" } else { &req.host }
)?;
if !req.requester.is_empty() {
writeln!(w, "Requester: {} (self-declared, not verified)", req.requester)?;
}
Ok(())
}
/// Write the `Execute?` question line, wrapped with the attention cues. The BEL
/// leads (fires when the line first renders); the blink wraps only the text, so
/// the trailing space before the resting cursor does not blink. Kept writer-
/// generic and free of I/O side effects so the emitted bytes are unit-testable
/// against a buffer, without touching /dev/tty.
fn write_question_line<W: Write>(
w: &mut W,
alert: &Alert,
question: &str,
choices: &str,
timeout_secs: u64,
) -> io::Result<()> {
let Alert { bell, blink_on, blink_off } = *alert;
let text = question_text(question, choices, timeout_secs);
write!(w, "{bell}{blink_on}{text}{blink_off} ")
}
fn question_text(question: &str, choices: &str, timeout_secs: u64) -> String {
format!("{question} {choices} ({timeout_secs}s timeout, default=N)")
}
/// Once the prompt is answered or has timed out, redraw the question line
/// without blink: a terminal keeps blinking cells that were drawn blinking, so
/// stopping it means rewriting them. Echo is off while the key is read, so the
/// cursor is still on the question line: return to its start (`\r`), clear it
/// (`ESC [2K`), and print the same text plain. Emits nothing when blink is
/// suppressed. A question wrapped over several lines by a very narrow terminal
/// only has its last line redrawn.
fn write_settled_question_line<W: Write>(
w: &mut W,
alert: &Alert,
question: &str,
choices: &str,
timeout_secs: u64,
) -> io::Result<()> {
if alert.blink_on.is_empty() {
return Ok(());
}
let text = question_text(question, choices, timeout_secs);
write!(w, "\r\x1b[2K{text} ")
}
/// Render a plan below the `Command:` line, in two bands: a deduplicated
/// **Resolves** block (every distinct real binary the plan runs, shown once),
/// then an indented, line-numbered **Steps** block — the structure spread across
/// lines with `&&`/`||`/`|`/`;`, each command colored by uid (red = root), for
/// readability and so the human can reference a line ("decline, change line 3").
/// A single plain unprivileged stage degrades to the classic one-line
/// `Resolves:` form so simple prompts stay simple.
fn write_plan_stages<W: Write>(
w: &mut W,
plan: &Plan,
views: &[LeafView],
privileged: bool,
style: &Style,
) -> io::Result<()> {
// Simple case: one stage, no escalation, not opaque, no redirections — keep
// the familiar single `Resolves:` line.
if !privileged
&& views.len() == 1
&& views[0].privilege == LeafPrivilege::Direct
&& !views[0].opaque
&& views[0].redirects.is_empty()
{
if let Some(name) = views[0].argv.first() {
return write_resolves_line(w, name, views[0].resolved_bin.as_deref(), style);
}
return Ok(());
}
write_resolve_block(w, views, style)?;
write_steps(w, &layout(plan, &ambient_ctx(privileged)), style)?;
Ok(())
}
/// Uid a step runs as, for coloring. `Root` → red, `User` → yellow, `Default` →
/// no color (the daemon's own user).
#[derive(Clone, Copy, PartialEq)]
enum StepUid {
Default,
Root,
User,
}
/// Escalation context threaded through the Steps render: which uid a leaf runs
/// as, and whether it sits at an explicit `run-as`/`sudo` boundary (which gets
/// the brighter shade).
#[derive(Clone, Copy)]
struct Esc {
uid: StepUid,
boundary: bool,
}
fn colorize(esc: Esc, text: &str, style: &Style) -> String {
let color = match esc.uid {
StepUid::Default => "",
// Ambient root is light red; the explicit run-as boundary is bright red.
StepUid::Root if esc.boundary => style.root_boundary,
StepUid::Root => style.root,
StepUid::User => style.user,
};
if color.is_empty() {
text.to_string()
} else {
format!("{color}{text}{}", style.reset)
}
}
/// One line of the `Steps:` block, at a parenthesis depth. A `numbered` line
/// holds a command; a line holding only parentheses is not numbered.
struct StepLine {
depth: usize,
text: String,
numbered: bool,
/// Trailing remark, written after everything else on the line as a shell
/// comment, so operators and parentheses appended to `text` stay before it.
note: String,
}
impl StepLine {
fn comment(&self, style: &Style) -> String {
if self.note.is_empty() {
String::new()
} else {
format!(" {}# {}{}", style.dim, self.note, style.reset)
}
}
}
/// The `Steps:` block — one command per line, indented by parenthesis depth,
/// numbered (0-based, dim, flush-left) so the human can reference a line,
/// coloured by uid. It is valid shell grouping exactly like the `Command:` line.
fn write_steps<W: Write>(w: &mut W, lay: &Lay, style: &Style) -> io::Result<()> {
let lines = steps_lines(lay, style);
if lines.is_empty() {
return Ok(());
}
let Style { dim, reset, bold, .. } = *style;
writeln!(w, "Steps:")?;
let shown = lines.len().min(MAX_DISPLAY_STAGES);
let numbered = lines[..shown].iter().filter(|l| l.numbered).count();
let width = numbered.saturating_sub(1).to_string().len();
let mut n = 0usize;
for ln in &lines[..shown] {
let indent = " ".repeat(ln.depth + 1);
if ln.numbered {
writeln!(w, "{dim}{n:<width$}{reset}{indent}{}{}", ln.text, ln.comment(style))?;
n += 1;
} else {
writeln!(w, "{:width$}{indent}{}{}", "", ln.text, ln.comment(style))?;
}
}
if lines.len() > shown {
let hidden = lines.len() - shown;
writeln!(w, "{bold}… {hidden} more line(s) hidden — see Command:{reset}")?;
}
Ok(())
}
fn steps_lines(lay: &Lay, style: &Style) -> Vec<StepLine> {
let mut out = Vec::new();
steps_emit(lay, 0, false, style, &mut out);
out
}
/// Emit the lines of a layout subtree. `followed` says an operator comes right
/// after this subtree, which decides where a group's `)` goes.
fn steps_emit(lay: &Lay, depth: usize, followed: bool, style: &Style, out: &mut Vec<StepLine>) {
match lay {
Lay::Leaf { cmd, redir, esc, scope, note } => {
let text = if *scope { cmd.clone() } else { colorize(*esc, cmd, style) };
out.push(StepLine { depth, text: join_suffix(text, redir), numbered: true, note: note.clone() });
}
Lay::Chain { op, items } => {
let plain = format!(" {}", op.sym());
// Tint the operator when every command in the chain runs escalated,
// so a contiguous privileged region reads as one coloured block.
let op_str = if lay_all_escalated(lay) && !style.root.is_empty() {
format!("{}{plain}{}", style.root, style.reset)
} else {
plain
};
for (i, item) in items.iter().enumerate() {
let last = i + 1 == items.len();
steps_emit(item, depth, !last, style, out);
if !last {
out.last_mut().expect("an item emits a line").text.push_str(&op_str);
}
}
}
Lay::Group { inner, redir } => {
// Egyptian brackets: `(` ends the line leading into the group, or
// sits on a line of its own when nothing precedes it.
let opener_depth = match out.last_mut() {
Some(prev) => {
prev.text.push_str(" (");
prev.depth
}
None => {
out.push(StepLine { depth, text: "(".into(), numbered: false, note: String::new() });
depth
}
};
steps_emit(inner, depth + 1, false, style, out);
// `)` ends the group's last line when an operator or a redirection
// follows; otherwise it closes on its own line, under its opener.
let close = join_suffix(")".into(), redir);
if followed || !redir.is_empty() {
let last = out.last_mut().expect("a group emits a line");
last.text.push(' ');
last.text.push_str(&close);
} else {
out.push(StepLine { depth: opener_depth, text: close, numbered: false, note: String::new() });
}
}
}
}
/// Whether every command (scope headers aside) in this layout runs escalated.
fn lay_all_escalated(lay: &Lay) -> bool {
fn walk(l: &Lay, seen: &mut bool) -> bool {
match l {
Lay::Leaf { scope: true, .. } => true,
Lay::Leaf { esc, .. } => {
*seen = true;
esc.uid != StepUid::Default
}
Lay::Group { inner, .. } => walk(inner, seen),
Lay::Chain { items, .. } => items.iter().all(|i| walk(i, seen)),
}
}
let mut seen = false;
walk(lay, &mut seen) && seen
}
/// The deduplicated `Resolves:` block: one line per distinct binary the plan
/// runs, in first-seen order, so a binary used by several stages appears once.
/// Entries with the same name *and* resolution collapse; distinct names stay
/// apart even when they share a multi-call binary (`echo` vs `cat` on uutils).
/// Opaque stages (a `Shell` node, or an `Exec` of a shell) render as the
/// opaque-shell marker.
fn write_resolve_block<W: Write>(w: &mut W, views: &[LeafView], style: &Style) -> io::Result<()> {
let Style { bold, reset, .. } = *style;
let mut seen = std::collections::HashSet::new();
let mut entries: Vec<(String, String)> = Vec::new();
for view in views {
let name = view.argv.first().cloned().unwrap_or_default();
let detail = if view.opaque {
match &view.resolved_bin {
Some(p) => format!(
"{bold}opaque — resolves only the shell: {}{reset}",
p.display()
),
None => format!("{bold}opaque — shell not found in PATH{reset}"),
}
} else {
resolve_detail(view.resolved_bin.as_deref(), style)
};
if seen.insert(format!("{name}\u{0}{detail}")) {
entries.push((name, detail));
}
}
if entries.is_empty() {
return Ok(());
}
let width = entries.iter().map(|(n, _)| n.chars().count()).max().unwrap_or(0);
writeln!(w, "Resolves:")?;
for (name, detail) in &entries {
writeln!(w, " {name:<width$} {detail}")?;
}
Ok(())
}
/// The resolution detail for a command name (the text after `Resolves:`),
/// always naming a concrete path. Used by the consolidated resolve block; it
/// mirrors `write_resolves_line`'s symlink display but never elides — the block
/// shows every binary, even one supplied as an already-canonical absolute path.
fn resolve_detail(resolved: Option<&Path>, style: &Style) -> String {
let Style { bold, dim, reset, .. } = *style;
let resolved = match resolved {
Some(p) => p,
None => return format!("{bold}(not found in PATH){reset}"),
};
let resolved_str = resolved.display().to_string();
match std::fs::canonicalize(resolved) {
Ok(canonical) => {
let canonical_str = canonical.display().to_string();
if canonical_str != resolved_str {
format!("{resolved_str} {bold}->{reset} {canonical_str}")
} else {
resolved_str
}
}
Err(_) => format!("{resolved_str} {dim}(canonicalize failed){reset}"),
}
}
/// Write the `Resolves:` line for a command name, given the plan's own
/// resolution of it (`resolve_command` — the file the executor will spawn,
/// never a fresh lookup), then `canonicalize`s the result
/// so symlink redirection — including `/usr/local/bin/foo -> /tmp/evil`
/// when the absolute path was supplied directly — is visible.
///
/// Display rules:
/// - request matches resolved matches canonical: nothing printed.
/// - request differs from resolved (PATH search): show resolved path,
/// appending `-> canonical` if canonical also differs.
/// - request matches resolved but canonical differs (absolute symlink):
/// show `request -> canonical` in bold.
/// - canonicalize fails (broken symlink, EACCES): show what we know and
/// flag `(canonicalize failed)` so the prompt is honest about not
/// having verified the target.
fn write_resolves_line<W: Write>(
w: &mut W,
cmd_name: &str,
resolved: Option<&Path>,
style: &Style,
) -> io::Result<()> {
let Style { bold, dim, reset, .. } = *style;
let resolved = match resolved {
Some(p) => p,
None => {
return writeln!(w, "Resolves: {bold}(not found in PATH){reset}");
}
};
let resolved_str = resolved.display().to_string();
let resolved_differs = resolved_str != *cmd_name;
match std::fs::canonicalize(resolved) {
Ok(canonical) => {
let canonical_str = canonical.display().to_string();
let canonical_differs = canonical_str != resolved_str;
match (resolved_differs, canonical_differs) {
(false, false) => Ok(()),
(true, false) => writeln!(w, "Resolves: {resolved_str}"),
(false, true) => writeln!(
w,
"Resolves: {bold}{resolved_str} -> {canonical_str}{reset}"
),