1use std::path::PathBuf;
35
36use serde_derive::{Deserialize, Serialize};
37use tracing::debug;
38
39use crate::{
40 checks::Check,
41 config::{Challenge, ResolvedSettings, Settings},
42 env::{CommandOutcome, Environment},
43 policy::MergedPolicy,
44};
45
46const GIT_TIMEOUT_MS: u64 = 200;
48const K8S_TIMEOUT_MS: u64 = 300;
53
54const K8S_PROGRAMS: &[&str] = &[
56 "kubectl",
57 "k",
58 "kubecolor",
59 "oc",
60 "helm",
61 "helmfile",
62 "flux",
63 "velero",
66];
67
68#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
70pub enum RiskLevel {
71 #[default]
73 Normal,
74 Elevated,
76 Critical,
78}
79
80#[derive(Debug, Clone, Default)]
82#[allow(clippy::struct_excessive_bools)]
83pub struct RuntimeContext {
84 pub is_ssh: bool,
85 pub is_root: bool,
86 pub root_via_sudo: bool,
89 pub root_via: Option<String>,
92 pub k8s_switch_attempt: Option<String>,
96 pub git_branch: Option<String>,
99 pub git_branch_switched: bool,
102 pub git_unknown: bool,
106 pub git_targets: Vec<String>,
109 pub git_ignore_current_branch: bool,
115 pub git_push_all: bool,
117 pub git_target_unknown: bool,
123 pub k8s_context: Option<String>,
124 pub k8s_unknown: bool,
127 pub k8s_not_checked: bool,
130 pub k8s_namespace: Option<String>,
132 pub aws_profile: Option<String>,
134 pub tf_workspace: Option<String>,
136 pub tf_unknown: bool,
140 pub gcp_project: Option<String>,
143 pub azure_subscription: Option<String>,
145 pub cluster: Option<String>,
149 pub remote_hosts: Vec<String>,
151 pub sensitive_paths: Vec<String>,
154 pub env_signals: Vec<String>,
155 pub risk_level: RiskLevel,
156 pub labels: Vec<String>,
158}
159
160#[derive(Debug, Deserialize, Serialize, Clone)]
162pub struct ContextConfig {
163 #[serde(default = "default_protected_branches")]
164 pub protected_branches: Vec<String>,
165 #[serde(default = "default_production_k8s_patterns")]
166 pub production_k8s_patterns: Vec<String>,
167 #[serde(default = "default_production_env_vars")]
168 pub production_env_vars: std::collections::BTreeMap<String, String>,
169 #[serde(default)]
170 pub sensitive_paths: Vec<String>,
171 #[serde(default)]
172 pub escalation: EscalationConfig,
173}
174
175fn default_protected_branches() -> Vec<String> {
176 vec![
177 "main".into(),
178 "master".into(),
179 "production".into(),
180 "release/*".into(),
181 ]
182}
183
184fn default_production_k8s_patterns() -> Vec<String> {
185 vec![
186 "prod".into(),
187 "production".into(),
188 "prd".into(),
189 "live".into(),
190 ]
191}
192
193fn default_production_env_vars() -> std::collections::BTreeMap<String, String> {
194 let mut m = std::collections::BTreeMap::new();
195 m.insert("NODE_ENV".into(), "production".into());
196 m.insert("RAILS_ENV".into(), "production".into());
197 m.insert("ENVIRONMENT".into(), "production".into());
198 m
199}
200
201impl Default for ContextConfig {
202 fn default() -> Self {
203 Self {
204 protected_branches: default_protected_branches(),
205 production_k8s_patterns: default_production_k8s_patterns(),
206 production_env_vars: default_production_env_vars(),
207 sensitive_paths: vec![],
208 escalation: EscalationConfig::default(),
209 }
210 }
211}
212
213#[derive(Debug, Deserialize, Serialize, Clone)]
218pub struct EscalationConfig {
219 #[serde(default = "default_elevated_challenge")]
220 pub elevated: Challenge,
221 #[serde(default = "default_critical_challenge")]
222 pub critical: Challenge,
223}
224
225const fn default_elevated_challenge() -> Challenge {
226 Challenge::Math
227}
228const fn default_critical_challenge() -> Challenge {
229 Challenge::Yes
230}
231
232impl Default for EscalationConfig {
233 fn default() -> Self {
234 Self {
235 elevated: default_elevated_challenge(),
236 critical: default_critical_challenge(),
237 }
238 }
239}
240
241impl RuntimeContext {
242 #[must_use]
259 pub fn filter_for_groups(
260 &self,
261 matched_groups: &std::collections::HashSet<&str>,
262 config: &ContextConfig,
263 ) -> Self {
264 let keep = |g: &str| matched_groups.contains(g);
265 let keep_git = keep("git");
266 let keep_k8s = keep("kubernetes");
267 let keep_iac = keep("terraform");
268 let opt = |k: bool, v: &Option<String>| if k { v.clone() } else { None };
269
270 let mut filtered = Self {
271 is_ssh: self.is_ssh,
272 is_root: self.is_root,
273 root_via_sudo: self.root_via_sudo,
274 root_via: self.root_via.clone(),
275 k8s_switch_attempt: opt(keep_k8s, &self.k8s_switch_attempt),
276 git_branch: opt(keep_git, &self.git_branch),
277 git_branch_switched: keep_git && self.git_branch_switched,
278 git_unknown: keep_git && self.git_unknown,
279 git_targets: if keep_git {
280 self.git_targets.clone()
281 } else {
282 Vec::new()
283 },
284 git_ignore_current_branch: !keep_git || self.git_ignore_current_branch,
287 git_push_all: keep_git && self.git_push_all,
288 git_target_unknown: keep_git && self.git_target_unknown,
289 k8s_context: opt(keep_k8s, &self.k8s_context),
290 k8s_unknown: keep_k8s && self.k8s_unknown,
291 k8s_not_checked: keep_k8s && self.k8s_not_checked,
292 k8s_namespace: opt(keep_k8s, &self.k8s_namespace),
293 aws_profile: opt(keep("aws") || keep_iac, &self.aws_profile),
296 tf_workspace: opt(keep_iac, &self.tf_workspace),
297 tf_unknown: keep_iac && self.tf_unknown,
298 gcp_project: opt(keep("gcp") || keep_iac, &self.gcp_project),
299 azure_subscription: opt(keep("azure") || keep_iac, &self.azure_subscription),
300 cluster: opt(
301 keep_k8s || keep("aws") || keep("gcp") || keep("azure"),
302 &self.cluster,
303 ),
304 remote_hosts: self.remote_hosts.clone(),
305 sensitive_paths: self.sensitive_paths.clone(),
306 env_signals: self.env_signals.clone(),
307 risk_level: RiskLevel::Normal,
308 labels: Vec::new(),
309 };
310 filtered.refresh(config);
311 filtered
312 }
313
314 pub fn refresh(&mut self, config: &ContextConfig) {
316 self.labels = self.build_labels();
317 self.risk_level = compute_risk_level(self, config);
318 }
319
320 fn build_labels(&self) -> Vec<String> {
321 let mut labels = Vec::new();
322 if self.is_ssh {
323 labels.push("ssh=true".into());
324 }
325 if self.is_root {
326 labels.push(if self.root_via_sudo {
327 format!("root={}", self.root_via.as_deref().unwrap_or("sudo"))
328 } else {
329 "root=true".into()
330 });
331 }
332 if let Some(ref branch) = self.git_branch {
333 let branch = escape_invisible(branch);
334 labels.push(if self.git_branch_switched {
335 format!("branch={branch} (switched in this command)")
336 } else {
337 format!("branch={branch}")
338 });
339 } else if self.git_unknown {
340 labels.push("git=unknown".into());
341 }
342 if !self.git_targets.is_empty() {
343 let t: Vec<String> = self
344 .git_targets
345 .iter()
346 .map(|b| escape_invisible(b))
347 .collect();
348 labels.push(format!("target={}", t.join(",")));
349 }
350 if self.git_target_unknown {
351 labels.push("target=unknown".into());
352 }
353 if self.git_push_all {
354 labels.push("push=all-branches".into());
355 }
356 if let Some(ref k8s) = self.k8s_context {
357 labels.push(self.k8s_switch_attempt.as_ref().map_or_else(
358 || format!("k8s={}", escape_invisible(k8s)),
359 |to| {
360 format!(
361 "k8s={} (kept: the switch to {} may fail)",
362 escape_invisible(k8s),
363 escape_invisible(to)
364 )
365 },
366 ));
367 } else if self.k8s_unknown {
368 labels.push("k8s=unknown".into());
369 } else if self.k8s_not_checked {
370 labels.push("k8s=not checked".into());
371 }
372 for (key, v) in [
373 ("namespace", &self.k8s_namespace),
374 ("aws-profile", &self.aws_profile),
375 ("tf-workspace", &self.tf_workspace),
376 ("gcp-project", &self.gcp_project),
377 ("azure-subscription", &self.azure_subscription),
378 ("cluster", &self.cluster),
379 ] {
380 if let Some(v) = v {
381 labels.push(format!("{key}={}", escape_invisible(v)));
382 }
383 }
384 if self.tf_workspace.is_none() && self.tf_unknown {
385 labels.push("tf-workspace=unknown".into());
386 }
387 for host in &self.remote_hosts {
388 labels.push(format!("remote={}", escape_invisible(host)));
389 }
390 for p in &self.sensitive_paths {
391 labels.push(format!("sensitive-path={}", escape_invisible(p)));
392 }
393 for sig in &self.env_signals {
394 labels.push(format!("env:{}", escape_invisible(sig)));
395 }
396 labels
397 }
398
399 fn branches_to_evaluate(&self) -> Vec<&str> {
401 let mut out: Vec<&str> = self.git_targets.iter().map(String::as_str).collect();
402 if !self.git_ignore_current_branch {
403 if let Some(ref b) = self.git_branch {
404 if !out.contains(&b.as_str()) {
405 out.push(b);
406 }
407 }
408 }
409 out
410 }
411
412 #[must_use]
415 #[allow(clippy::too_many_lines)]
416 pub fn risk_reasons(&self, config: &ContextConfig) -> Vec<(RiskLevel, String)> {
417 let mut reasons = Vec::new();
418 if self.is_root {
419 reasons.push((
420 RiskLevel::Critical,
421 if self.root_via_sudo {
422 format!(
423 "runs as root ({})",
424 self.root_via.as_deref().unwrap_or("sudo")
425 )
426 } else {
427 "running as root".to_string()
428 },
429 ));
430 }
431 for branch in self.branches_to_evaluate() {
432 if branch_matches_any(branch, &config.protected_branches) {
433 reasons.push((
434 RiskLevel::Critical,
435 format!("protected branch `{}`", escape_invisible(branch)),
436 ));
437 }
438 }
439 if self.git_target_unknown && !config.protected_branches.is_empty() {
440 reasons.push((
441 RiskLevel::Critical,
442 "push target unknown until the line runs (this repository has a protected branch)"
443 .to_string(),
444 ));
445 }
446 if self.git_push_all && !config.protected_branches.is_empty() {
447 reasons.push((
448 RiskLevel::Critical,
449 "pushes all branches (--all/--mirror)".to_string(),
450 ));
451 }
452 if let Some(ref k8s) = self.k8s_context {
453 if matches_any_pattern(k8s, &config.production_k8s_patterns) {
454 reasons.push((
455 RiskLevel::Critical,
456 format!("production k8s context `{}`", escape_invisible(k8s)),
457 ));
458 }
459 }
460 for (what, v) in [
461 ("k8s namespace", &self.k8s_namespace),
462 ("AWS profile", &self.aws_profile),
463 ("terraform workspace", &self.tf_workspace),
464 ("gcloud project", &self.gcp_project),
465 ("Azure subscription", &self.azure_subscription),
466 ("cluster", &self.cluster),
467 ] {
468 if let Some(v) = v {
469 if matches_any_pattern(v, &config.production_k8s_patterns) {
470 reasons.push((
471 RiskLevel::Critical,
472 format!("production {what} `{}`", escape_invisible(v)),
473 ));
474 }
475 }
476 }
477 for host in &self.remote_hosts {
478 if matches_any_pattern(host, &config.production_k8s_patterns) {
479 reasons.push((
480 RiskLevel::Critical,
481 format!("runs on production host `{}`", escape_invisible(host)),
482 ));
483 }
484 }
485 for p in &self.sensitive_paths {
486 reasons.push((
487 RiskLevel::Critical,
488 format!("touches sensitive path `{}`", escape_invisible(p)),
489 ));
490 }
491 for sig in &self.env_signals {
492 reasons.push((
493 RiskLevel::Critical,
494 format!("production environment ({sig})"),
495 ));
496 }
497 if self.git_branch.is_none() && self.git_unknown {
498 reasons.push((
499 RiskLevel::Elevated,
500 "git branch unknown (git did not answer in time)".to_string(),
501 ));
502 }
503 if self.k8s_context.is_none() && self.k8s_unknown {
504 reasons.push((
505 RiskLevel::Elevated,
506 "k8s context unknown (kubectl did not answer in time)".to_string(),
507 ));
508 }
509 if self.tf_workspace.is_none() && self.tf_unknown {
510 reasons.push((
511 RiskLevel::Elevated,
512 "terraform workspace unknown (its directory is only known when the command runs)"
513 .to_string(),
514 ));
515 }
516 if self.is_ssh {
517 reasons.push((RiskLevel::Elevated, "SSH session".to_string()));
518 }
519 reasons
520 }
521}
522
523pub fn detect(env: &dyn Environment, config: &ContextConfig) -> RuntimeContext {
528 detect_inner(env, config, None)
529}
530
531pub fn detect_for_command(
545 env: &dyn Environment,
546 config: &ContextConfig,
547 command: &str,
548) -> RuntimeContext {
549 detect_inner(env, config, Some(command))
550}
551
552fn detect_inner(
553 env: &dyn Environment,
554 config: &ContextConfig,
555 command: Option<&str>,
556) -> RuntimeContext {
557 let Some(command) = command else {
558 let seg = SegmentTargets {
561 mentions_k8s: true,
562 git_uses_current: true,
563 ..SegmentTargets::default()
564 };
565 let mut probes = Probes::default();
566 let mut ctx = segment_context(env, config, &seg, &mut probes);
567 ctx.git_ignore_current_branch = false;
568 ctx.refresh(config);
569 return ctx;
570 };
571 let contexts = command_contexts(env, config, command);
572 contexts.full(config)
573}
574
575#[derive(Debug, Clone, Default)]
578pub struct CommandContexts {
579 pub parts: Vec<(SegmentTargets, RuntimeContext)>,
581 pub sensitive_paths: Vec<String>,
583}
584
585impl CommandContexts {
586 #[must_use]
589 pub fn full(&self, config: &ContextConfig) -> RuntimeContext {
590 let parts: Vec<&RuntimeContext> = self.parts.iter().map(|(_, c)| c).collect();
591 let mut ctx = merge_contexts(&parts, config);
592 ctx.sensitive_paths.clone_from(&self.sensitive_paths);
593 ctx.refresh(config);
594 ctx
595 }
596
597 #[must_use]
606 pub fn relevant(
607 &self,
608 config: &ContextConfig,
609 groups_of: &dyn Fn(&str) -> std::collections::HashSet<String>,
610 all_groups: &std::collections::HashSet<&str>,
611 ) -> RuntimeContext {
612 let mut filtered: Vec<RuntimeContext> = Vec::new();
613 for (seg, ctx) in &self.parts {
614 let mut groups = groups_of(&seg.text);
615 if groups.is_empty() {
616 continue;
617 }
618 if seg.place == Place::Pod || seg.mentions_k8s {
621 groups.insert("kubernetes".to_string());
622 }
623 let set: std::collections::HashSet<&str> = groups.iter().map(String::as_str).collect();
624 filtered.push(ctx.filter_for_groups(&set, config));
625 }
626 if filtered.is_empty() {
627 for (seg, ctx) in &self.parts {
628 let mut set = all_groups.clone();
629 if seg.place == Place::Pod {
630 set.insert("kubernetes");
631 }
632 filtered.push(ctx.filter_for_groups(&set, config));
633 }
634 }
635 let refs: Vec<&RuntimeContext> = filtered.iter().collect();
636 let mut ctx = merge_contexts(&refs, config);
637 ctx.sensitive_paths.clone_from(&self.sensitive_paths);
638 ctx.refresh(config);
639 ctx
640 }
641}
642
643#[must_use]
649pub fn command_contexts(
650 env: &dyn Environment,
651 config: &ContextConfig,
652 command: &str,
653) -> CommandContexts {
654 let targets = parse_command_targets(command);
655 let mut segments = targets.segments;
656
657 let parsed = crate::parser::parse(command);
660 if targets.git_invocations == 0 {
661 for s in &parsed.segments {
662 if s.starts_with("git ") && parsed.remote_segments.binary_search(s).is_err() {
663 let args: Vec<String> = s
664 .split(' ')
665 .skip(1)
666 .filter(|w| !w.is_empty())
667 .map(crate::parser::desentinel)
668 .collect();
669 let mut seg = SegmentTargets {
670 text: crate::parser::desentinel(s),
671 ..SegmentTargets::default()
672 };
673 parse_git(&args, &mut seg, &mut LineState::default());
674 segments.push(seg);
675 }
676 }
677 }
678 if segments.is_empty() {
679 segments.push(SegmentTargets {
680 text: command.to_string(),
681 ..SegmentTargets::default()
682 });
683 }
684
685 let mut probes = Probes::default();
686 let parts = segments
687 .into_iter()
688 .map(|seg| {
689 let ctx = segment_context(env, config, &seg, &mut probes);
690 (seg, ctx)
691 })
692 .collect::<Vec<_>>();
693 debug!("command contexts: {parts:?}");
694 CommandContexts {
695 parts,
696 sensitive_paths: sensitive_path_hits(env, &config.sensitive_paths, &parsed),
697 }
698}
699
700#[derive(Default)]
703struct Probes {
704 git: Option<(Option<String>, bool)>,
705 k8s_ambient: Option<K8sProbe>,
706 k8s_by_kubeconfig: std::collections::HashMap<String, K8sProbe>,
707}
708
709type K8sProbe = (Option<String>, bool, bool);
711
712impl Probes {
713 fn git(&mut self, env: &dyn Environment) -> (Option<String>, bool) {
714 self.git
715 .get_or_insert_with(|| detect_git_branch(env))
716 .clone()
717 }
718
719 fn k8s(&mut self, env: &dyn Environment, kubeconfig: Option<&str>) -> K8sProbe {
720 match kubeconfig {
721 Some(kc) => self
722 .k8s_by_kubeconfig
723 .entry(kc.to_string())
724 .or_insert_with(|| detect_k8s_from_kubeconfig(env, kc))
725 .clone(),
726 None => self
727 .k8s_ambient
728 .get_or_insert_with(|| detect_k8s_ambient(env))
729 .clone(),
730 }
731 }
732}
733
734#[allow(clippy::too_many_lines)]
736fn segment_context(
737 env: &dyn Environment,
738 config: &ContextConfig,
739 seg: &SegmentTargets,
740 probes: &mut Probes,
741) -> RuntimeContext {
742 let local = seg.place == Place::Local;
743 let lookup = |key: &str| -> Option<String> {
746 match seg.line_var(key) {
747 Some(v) => v,
748 None if local => env.var(key).filter(|v| !v.is_empty()),
749 None => None,
750 }
751 };
752 let first_of = |keys: &[&str]| keys.iter().find_map(|k| lookup(k));
753
754 let euid_root = env.effective_uid() == Some(0);
755 let mut ctx = RuntimeContext {
756 is_ssh: ["SSH_CONNECTION", "SSH_TTY", "SSH_CLIENT"]
757 .iter()
758 .any(|k| env_var_non_empty(env, k)),
759 is_root: euid_root || seg.sudo_root,
760 root_via_sudo: !euid_root && seg.sudo_root,
761 root_via: (!euid_root && seg.sudo_root)
762 .then(|| seg.root_tool.clone())
763 .flatten(),
764 ..RuntimeContext::default()
765 };
766
767 if let Some(ref b) = seg.git_branch_switch {
770 ctx.git_branch = Some(b.clone());
771 ctx.git_branch_switched = true;
772 let applies = !seg.git_fallbacks.is_empty()
775 && (seg.git_fallbacks_always || !(seg.git_switch_creates || branch_exists(env, b)));
776 if applies && !branch_matches_any(b, &config.protected_branches) {
777 for alt in &seg.git_fallbacks {
778 let candidate = match alt {
779 CtxAlt::Named(n) => Some(n.clone()),
780 CtxAlt::Current if local => probes.git(env).0,
781 _ => None,
782 };
783 if let Some(c) = candidate {
784 if branch_matches_any(&c, &config.protected_branches) {
785 ctx.git_branch_switched = matches!(alt, CtxAlt::Named(_));
786 ctx.git_branch = Some(c);
787 break;
788 }
789 }
790 }
791 }
792 } else if let Some(dir) = seg.git_dir.as_deref().filter(|_| local) {
793 let base = env.current_dir().unwrap_or_default();
796 let path = expand_home(env, dir);
797 let path = if path.is_absolute() {
798 path
799 } else {
800 base.join(path)
801 };
802 let at = crate::agent::CwdEnvironment::new(env, path);
803 match read_git_head(&at) {
804 GitHead::Branch(b) => ctx.git_branch = Some(b),
805 GitHead::Unreadable => ctx.git_unknown = seg.git_uses_current,
806 GitHead::NotFound => {}
807 }
808 } else if local {
809 let (branch, unknown) = probes.git(env);
810 ctx.git_branch = branch;
811 ctx.git_unknown = unknown && seg.git_uses_current;
812 }
813 ctx.git_targets.clone_from(&seg.git_targets);
814 if seg.git_target_unknown && local {
815 ctx.git_target_unknown = unknown_target_may_be_protected(
819 env,
820 config,
821 ctx.git_branch.clone().or_else(|| probes.git(env).0),
822 );
823 }
824 let reset_in_place = local
827 && seg.git_dir.is_none()
828 && seg.git_branch_switch.is_none()
829 && seg
830 .git_reset_to
831 .as_deref()
832 .is_some_and(|r| rev_is_head(env, r));
833 ctx.git_ignore_current_branch = !seg.git_uses_current || reset_in_place;
834 ctx.git_push_all = seg.git_push_all;
835
836 if seg.mentions_k8s || seg.place == Place::Pod {
839 if let Some(ref c) = seg.k8s_context {
840 ctx.k8s_context = Some(c.clone());
841 } else if seg.k8s_context_unknown {
842 ctx.k8s_unknown = true;
843 } else if local || seg.place == Place::Pod {
844 let (c, unknown, not_checked) = probes.k8s(env, seg.kubeconfig.as_deref());
845 ctx.k8s_context = c;
846 ctx.k8s_unknown = unknown;
847 ctx.k8s_not_checked = not_checked;
848 }
849 let all_contexts;
854 let seg = if seg.k8s_all_contexts {
855 let mut s = seg.clone();
856 s.k8s_fallbacks = kubeconfig_contexts(env, seg.kubeconfig.as_deref())
857 .into_iter()
858 .map(CtxAlt::Named)
859 .collect();
860 s.k8s_fallbacks.push(CtxAlt::Unknown);
861 s.k8s_fallbacks_always = true;
862 all_contexts = s;
863 &all_contexts
864 } else {
865 seg
866 };
867 let known_contexts = kubeconfig_contexts(env, seg.kubeconfig.as_deref());
868 let resolvable = seg
869 .k8s_context
870 .as_deref()
871 .is_some_and(|c| known_contexts.iter().any(|k| k == c));
872 let failed_switch = !resolvable
875 && !known_contexts.is_empty()
876 && seg.k8s_context.is_some()
877 && !seg.k8s_all_contexts;
878 if !seg.k8s_fallbacks.is_empty() && (seg.k8s_fallbacks_always || !resolvable) {
879 let prod = |c: &Option<String>| {
880 c.as_deref()
881 .is_some_and(|c| matches_any_pattern(c, &config.production_k8s_patterns))
882 };
883 if !prod(&ctx.k8s_context) {
884 let mut unknown = ctx.k8s_unknown;
885 for alt in &seg.k8s_fallbacks {
886 let (c, u) = match alt {
887 CtxAlt::Named(n) => (Some(n.clone()), false),
888 CtxAlt::Unknown => (None, true),
889 CtxAlt::Current if local || seg.place == Place::Pod => {
890 let (c, u, _) = probes.k8s(env, seg.kubeconfig.as_deref());
891 (c, u)
892 }
893 CtxAlt::Current => (None, false),
894 };
895 if prod(&c) {
896 ctx.k8s_switch_attempt = if seg.k8s_context_list {
899 None
900 } else {
901 seg.k8s_context.clone()
902 };
903 ctx.k8s_context = c;
904 ctx.k8s_unknown = false;
905 unknown = false;
906 break;
907 }
908 unknown |= u;
909 }
910 if unknown && !prod(&ctx.k8s_context) {
911 ctx.k8s_context = None;
913 ctx.k8s_unknown = true;
914 } else if failed_switch && !prod(&ctx.k8s_context) {
915 let before = seg.k8s_fallbacks.iter().find_map(|alt| match alt {
917 CtxAlt::Named(n) => Some(n.clone()),
918 CtxAlt::Current if local => probes.k8s(env, seg.kubeconfig.as_deref()).0,
919 _ => None,
920 });
921 if let Some(b) = before {
922 ctx.k8s_switch_attempt.clone_from(&seg.k8s_context);
923 ctx.k8s_context = Some(b);
924 }
925 }
926 }
927 }
928 }
929 ctx.k8s_namespace.clone_from(&seg.k8s_namespace);
930
931 ctx.aws_profile = seg
934 .aws_profile
935 .clone()
936 .or_else(|| first_of(&["AWS_PROFILE", "AWS_DEFAULT_PROFILE"]));
937 ctx.tf_workspace = seg.tf_workspace.clone().or_else(|| lookup("TF_WORKSPACE"));
938 let selected = |env: &dyn Environment| -> Option<String> {
941 if !(seg.terraform && local) {
942 return None;
943 }
944 let cwd = env.current_dir().ok()?;
945 let base = seg
946 .tf_dir
947 .as_deref()
948 .map_or_else(|| cwd.clone(), |d| expand_home(env, d))
949 .components()
950 .collect::<PathBuf>();
951 let base = if base.is_absolute() {
952 base
953 } else {
954 cwd.join(base)
955 };
956 let data = lookup("TF_DATA_DIR").unwrap_or_else(|| ".terraform".to_string());
957 let file = base.join(data).join("environment");
958 env.read_file(&file)
959 .ok()
960 .map(|w| w.trim().to_string())
961 .filter(|w| !w.is_empty() && w != "default")
962 };
963 if ctx.tf_workspace.is_none() && !seg.tf_dir_unknown {
964 ctx.tf_workspace = selected(env);
965 }
966 let tf_prod = |w: &Option<String>| {
967 w.as_deref()
968 .is_some_and(|w| matches_any_pattern(w, &config.production_k8s_patterns))
969 };
970 if !tf_prod(&ctx.tf_workspace) {
973 for alt in &seg.tf_fallbacks {
974 let w = match alt {
975 CtxAlt::Named(n) => Some(n.clone()),
976 CtxAlt::Current => selected(env).or_else(|| lookup("TF_WORKSPACE")),
977 CtxAlt::Unknown => None,
978 };
979 if tf_prod(&w) {
980 ctx.tf_workspace = w;
981 break;
982 }
983 }
984 }
985 if !ctx
986 .tf_workspace
987 .as_deref()
988 .is_some_and(|w| matches_any_pattern(w, &config.production_k8s_patterns))
989 {
990 if let Some(h) = seg
991 .tf_dir_hints
992 .iter()
993 .find(|h| matches_any_pattern(h, &config.production_k8s_patterns))
994 {
995 ctx.tf_workspace = Some(h.clone());
996 }
997 }
998 ctx.tf_unknown = seg.tf_dir_unknown && ctx.tf_workspace.is_none();
999 ctx.gcp_project = seg.gcp_project.clone().or_else(|| {
1000 first_of(&[
1001 "CLOUDSDK_CORE_PROJECT",
1002 "GOOGLE_CLOUD_PROJECT",
1003 "GOOGLE_PROJECT",
1004 ])
1005 });
1006 ctx.azure_subscription = seg
1007 .azure_subscription
1008 .clone()
1009 .or_else(|| first_of(&["ARM_SUBSCRIPTION_ID", "AZURE_SUBSCRIPTION_ID"]));
1010 ctx.cluster.clone_from(&seg.cluster);
1011 if let Place::Host(ref h) = seg.place {
1012 ctx.remote_hosts.push(h.clone());
1013 }
1014
1015 for (key, expected_val) in &config.production_env_vars {
1017 if let Some(val) = lookup(key) {
1018 if val.eq_ignore_ascii_case(expected_val) {
1019 ctx.env_signals.push(format!("{key}={val}"));
1020 }
1021 }
1022 }
1023
1024 ctx.refresh(config);
1025 ctx
1026}
1027
1028fn merge_contexts(parts: &[&RuntimeContext], config: &ContextConfig) -> RuntimeContext {
1032 let prod = |v: &Option<String>| {
1033 v.as_deref()
1034 .is_some_and(|v| matches_any_pattern(v, &config.production_k8s_patterns))
1035 };
1036 let pick = |f: &dyn Fn(&RuntimeContext) -> &Option<String>| -> Option<String> {
1037 parts
1038 .iter()
1039 .map(|p| f(p))
1040 .find(|v| prod(v))
1041 .or_else(|| parts.iter().map(|p| f(p)).find(|v| v.is_some()))
1042 .cloned()
1043 .flatten()
1044 };
1045 let mut out = RuntimeContext {
1046 is_ssh: parts.iter().any(|p| p.is_ssh),
1047 is_root: parts.iter().any(|p| p.is_root),
1048 ..RuntimeContext::default()
1049 };
1050 out.root_via_sudo = out.is_root && parts.iter().all(|p| !p.is_root || p.root_via_sudo);
1051 out.root_via = parts
1052 .iter()
1053 .find_map(|p| p.root_via.clone())
1054 .filter(|_| out.root_via_sudo);
1055 if let Some(p) = parts.iter().find(|p| prod(&p.k8s_context)) {
1056 out.k8s_switch_attempt.clone_from(&p.k8s_switch_attempt);
1057 }
1058
1059 let uses: Vec<&&RuntimeContext> = parts
1061 .iter()
1062 .filter(|p| !p.git_ignore_current_branch && p.git_branch.is_some())
1063 .collect();
1064 let chosen = uses
1065 .iter()
1066 .find(|p| {
1067 p.git_branch
1068 .as_deref()
1069 .is_some_and(|b| branch_matches_any(b, &config.protected_branches))
1070 })
1071 .or_else(|| uses.first())
1072 .map(|p| **p)
1073 .or_else(|| parts.iter().find(|p| p.git_branch.is_some()).copied());
1074 if let Some(c) = chosen {
1075 out.git_branch.clone_from(&c.git_branch);
1076 out.git_branch_switched = c.git_branch_switched;
1077 }
1078 out.git_unknown = out.git_branch.is_none() && parts.iter().any(|p| p.git_unknown);
1079 for p in parts {
1080 for t in &p.git_targets {
1081 if !out.git_targets.contains(t) {
1082 out.git_targets.push(t.clone());
1083 }
1084 }
1085 for h in &p.remote_hosts {
1086 if !out.remote_hosts.contains(h) {
1087 out.remote_hosts.push(h.clone());
1088 }
1089 }
1090 for s in &p.env_signals {
1091 if !out.env_signals.contains(s) {
1092 out.env_signals.push(s.clone());
1093 }
1094 }
1095 }
1096 out.git_ignore_current_branch = parts.iter().all(|p| p.git_ignore_current_branch);
1097 out.git_push_all = parts.iter().any(|p| p.git_push_all);
1098 out.git_target_unknown = parts.iter().any(|p| p.git_target_unknown);
1099
1100 if let Some(p) = parts.iter().find(|p| prod(&p.k8s_context)) {
1102 out.k8s_context.clone_from(&p.k8s_context);
1103 } else if parts.iter().any(|p| p.k8s_unknown) {
1104 out.k8s_unknown = true;
1105 } else {
1106 out.k8s_context = parts.iter().find_map(|p| p.k8s_context.clone());
1107 }
1108 out.k8s_not_checked =
1109 out.k8s_context.is_none() && !out.k8s_unknown && parts.iter().any(|p| p.k8s_not_checked);
1110 out.k8s_namespace = pick(&|p| &p.k8s_namespace);
1111 out.aws_profile = pick(&|p| &p.aws_profile);
1112 out.tf_workspace = pick(&|p| &p.tf_workspace);
1113 out.tf_unknown = out.tf_workspace.is_none() && parts.iter().any(|p| p.tf_unknown);
1114 out.gcp_project = pick(&|p| &p.gcp_project);
1115 out.azure_subscription = pick(&|p| &p.azure_subscription);
1116 out.cluster = pick(&|p| &p.cluster);
1117 out.refresh(config);
1118 out
1119}
1120
1121fn env_var_non_empty(env: &dyn Environment, key: &str) -> bool {
1122 env.var(key).is_some_and(|v| !v.trim().is_empty())
1123}
1124
1125enum GitHead {
1127 Branch(String),
1129 Unreadable,
1131 NotFound,
1133}
1134
1135fn read_git_head(env: &dyn Environment) -> GitHead {
1139 if env.var("GIT_DIR").is_some_and(|v| !v.is_empty()) {
1140 return GitHead::NotFound;
1141 }
1142 let Ok(cwd) = env.current_dir() else {
1143 return GitHead::NotFound;
1144 };
1145 let head_file = env.find_file_upward(&cwd, ".git/HEAD");
1146 let git_file = env.find_file_upward(&cwd, ".git");
1147 let depth = |p: &Option<PathBuf>, extra: usize| {
1149 p.as_ref()
1150 .map(|p| p.components().count().saturating_sub(extra))
1151 };
1152 let head = match (depth(&head_file, 1), depth(&git_file, 0)) {
1153 (None, None) => return GitHead::NotFound,
1154 (Some(h), Some(g)) if g > h => git_file.and_then(|f| gitdir_head(env, &f)),
1155 (Some(_), _) => head_file,
1156 (None, Some(_)) => git_file.and_then(|f| gitdir_head(env, &f)),
1157 };
1158 let Some(head) = head else {
1159 return GitHead::Unreadable;
1160 };
1161 let Ok(content) = env.read_file(&head) else {
1162 return GitHead::Unreadable;
1163 };
1164 let content = content.trim();
1165 if let Some(r) = content.strip_prefix("ref:") {
1166 let r = r.trim();
1167 return r
1168 .strip_prefix("refs/heads/")
1169 .map_or(GitHead::Unreadable, |b| GitHead::Branch(b.to_string()));
1170 }
1171 if content.len() >= 40 && content.chars().all(|c| c.is_ascii_hexdigit()) {
1172 return GitHead::Branch("HEAD".to_string());
1173 }
1174 GitHead::Unreadable
1175}
1176
1177fn gitdir_head(env: &dyn Environment, git_file: &std::path::Path) -> Option<PathBuf> {
1179 let content = env.read_file(git_file).ok()?;
1180 let dir = content
1181 .lines()
1182 .find_map(|l| l.strip_prefix("gitdir:"))?
1183 .trim();
1184 let dir = PathBuf::from(dir);
1185 let dir = if dir.is_absolute() {
1186 dir
1187 } else {
1188 git_file.parent()?.join(dir)
1189 };
1190 Some(dir.join("HEAD"))
1191}
1192
1193fn rev_is_head(env: &dyn Environment, rev: &str) -> bool {
1197 let Ok(cwd) = env.current_dir() else {
1198 return false;
1199 };
1200 let Some(head) = env.find_file_upward(&cwd, ".git/HEAD") else {
1201 return false;
1202 };
1203 let Some(git_dir) = head.parent() else {
1204 return false;
1205 };
1206 let packed = env
1207 .read_file(&git_dir.join("packed-refs"))
1208 .unwrap_or_default();
1209 let resolve = |name: &str| -> Option<String> {
1210 if let Ok(c) = env.read_file(&git_dir.join(name)) {
1211 let c = c.trim();
1212 return (c.len() >= 40 && c.chars().all(|c| c.is_ascii_hexdigit()))
1213 .then(|| c.to_string());
1214 }
1215 packed.lines().find_map(|l| {
1216 let (sha, r) = l.split_once(' ')?;
1217 (r.trim() == name).then(|| sha.to_string())
1218 })
1219 };
1220 let Ok(head_content) = env.read_file(&head) else {
1221 return false;
1222 };
1223 let head_content = head_content.trim();
1224 let head_sha = head_content
1225 .strip_prefix("ref:")
1226 .map_or_else(|| Some(head_content.to_string()), |r| resolve(r.trim()));
1227 let Some(head_sha) = head_sha.filter(|s| s.len() >= 40) else {
1228 return false;
1229 };
1230 if rev.len() >= 7 && rev.chars().all(|c| c.is_ascii_hexdigit()) {
1231 return head_sha.starts_with(&rev.to_ascii_lowercase());
1232 }
1233 if rev.contains(['~', '^', '@', ':', '$', '`', '{']) || rev.contains("..") {
1234 return false;
1235 }
1236 [
1237 rev.to_string(),
1238 format!("refs/heads/{rev}"),
1239 format!("refs/tags/{rev}"),
1240 format!("refs/remotes/{rev}"),
1241 ]
1242 .iter()
1243 .filter(|n| n.starts_with("refs/"))
1244 .find_map(|n| resolve(n))
1245 .is_some_and(|sha| sha == head_sha)
1246}
1247
1248fn detect_git_branch(env: &dyn Environment) -> (Option<String>, bool) {
1252 let head = read_git_head(env);
1253 if let GitHead::Branch(b) = head {
1254 return (Some(b), false);
1255 }
1256 match env.run_command_outcome(
1257 "git",
1258 &["rev-parse", "--abbrev-ref", "HEAD"],
1259 GIT_TIMEOUT_MS,
1260 ) {
1261 CommandOutcome::Output(b) if !b.is_empty() => (Some(b), false),
1262 CommandOutcome::TimedOut => (None, true),
1263 CommandOutcome::Skipped => (None, matches!(head, GitHead::Unreadable)),
1265 _ => (None, false),
1266 }
1267}
1268
1269const WRITE_PROGRAMS: &[&str] = &[
1271 "rm", "rmdir", "unlink", "shred", "srm", "mv", "cp", "truncate", "tee", "dd", "find", "chmod",
1272 "chown", "ln", "install", "rsync",
1273];
1274
1275#[must_use]
1278#[allow(clippy::too_many_lines)]
1279pub fn sensitive_path_hits(
1280 env: &dyn Environment,
1281 sensitive: &[String],
1282 parsed: &crate::parser::Parsed,
1283) -> Vec<String> {
1284 if sensitive.is_empty() {
1285 return Vec::new();
1286 }
1287 let home = env.home_dir().map(|h| h.display().to_string());
1288 let cwd = env
1289 .current_dir()
1290 .ok()
1291 .map(|c| c.display().to_string())
1292 .unwrap_or_default();
1293 let resolve = |p: &str| -> String {
1294 let p = crate::parser::desentinel(p);
1295 let p = p.trim_matches(|c| c == '"' || c == '\'');
1296 let expanded = match (home.as_deref(), p) {
1297 (Some(h), "~" | "$HOME" | "${HOME}") => h.to_string(),
1298 (Some(h), _) if p.starts_with("~/") => format!("{h}/{}", &p[2..]),
1299 (Some(h), _) if p.starts_with("$HOME/") => format!("{h}/{}", &p[6..]),
1300 (Some(h), _) if p.starts_with("${HOME}/") => format!("{h}/{}", &p[8..]),
1301 _ => p.to_string(),
1302 };
1303 let abs = if expanded.starts_with('/') {
1304 expanded
1305 } else {
1306 format!("{cwd}/{expanded}")
1307 };
1308 crate::parser::normalize_path(&abs)
1309 };
1310 let wanted: Vec<(String, String)> = sensitive
1311 .iter()
1312 .filter(|s| !s.trim().is_empty())
1313 .map(|s| (s.clone(), resolve(s.trim())))
1314 .collect();
1315
1316 let mut hits: Vec<String> = Vec::new();
1317 for seg in &parsed.segments {
1318 if parsed.remote_segments.binary_search(seg).is_ok() {
1319 continue;
1320 }
1321 let words: Vec<&str> = seg.split(' ').filter(|w| !w.is_empty()).collect();
1322 let Some(prog) = words.first() else { continue };
1323 let mut targets: Vec<&str> = Vec::new();
1324 let mut operands: Vec<&str> = Vec::new();
1325 let mut i = 1;
1326 while i < words.len() {
1327 let w = words[i];
1328 if crate::parser::is_redirect_word(w) {
1329 if w.contains('>') {
1330 if let Some(t) = words.get(i + 1) {
1331 targets.push(t);
1332 }
1333 }
1334 i += 2;
1335 continue;
1336 }
1337 if let Some(of) = w.strip_prefix("of=") {
1338 if *prog == "dd" {
1339 targets.push(of);
1340 }
1341 } else if !w.starts_with('-') {
1342 operands.push(w);
1343 }
1344 i += 1;
1345 }
1346 let has = |flags: &[&str]| words.iter().any(|w| flags.contains(w));
1347 if WRITE_PROGRAMS.contains(prog) {
1348 match *prog {
1349 "cp" | "install" | "rsync" | "ln" => targets.extend(operands.last()),
1351 "chmod" if operands.first().is_some_and(|m| is_tightening_mode(m)) => {}
1354 "chmod" | "chown" => targets.extend(operands.iter().skip(1)),
1356 "find"
1357 if words
1358 .iter()
1359 .any(|w| *w == "-delete" || w.starts_with("-exec")) =>
1360 {
1361 targets.extend(
1362 words[1..]
1363 .iter()
1364 .take_while(|w| !w.starts_with('-') && **w != "(" && **w != "!"),
1365 );
1366 }
1367 "find" | "dd" => {}
1368 _ => targets.extend(operands),
1369 }
1370 } else {
1371 match *prog {
1372 "sed"
1374 if words
1375 .iter()
1376 .any(|w| w.starts_with("-i") || w.starts_with("--in-place")) =>
1377 {
1378 targets.extend(operands.iter().skip(1));
1379 }
1380 "curl" | "wget" => {
1382 for (k, w) in words.iter().enumerate() {
1383 if matches!(*w, "-o" | "--output" | "-O" | "--output-document") {
1384 if let Some(f) = words.get(k + 1) {
1385 targets.push(f);
1386 }
1387 }
1388 }
1389 }
1390 "tar" if has(&["--remove-files"]) => targets.extend(operands.iter().skip(1)),
1392 "zip" if has(&["-m", "--move"]) => targets.extend(operands.iter().skip(1)),
1393 _ => {}
1394 }
1395 }
1396 for t in targets {
1397 let t = resolve(t);
1398 let glob_prefix = t.find(['*', '?', '[']).map(|i| t[..i].to_string());
1401 for (shown, s) in &wanted {
1402 let inside = t == *s || t.starts_with(&format!("{s}/"));
1403 let parent = s.starts_with(&format!("{}/", t.trim_end_matches('/'))) || t == "/";
1404 let globbed = glob_prefix
1405 .as_ref()
1406 .is_some_and(|g| s.starts_with(g.as_str()) || g.starts_with(&format!("{s}/")));
1407 let (inside, parent) = (inside || globbed, parent);
1408 if (inside || parent) && !hits.contains(shown) {
1409 hits.push(shown.clone());
1410 }
1411 }
1412 }
1413 }
1414 hits
1415}
1416
1417fn is_tightening_mode(mode: &str) -> bool {
1420 if !mode.is_empty() && mode.chars().all(|c| c.is_ascii_digit()) {
1421 let d: Vec<char> = mode.chars().collect();
1423 if d.len() > 4 || (d.len() == 4 && d[0] != '0') || d.len() < 3 {
1424 return false;
1425 }
1426 return d[d.len() - 2] == '0' && d[d.len() - 1] == '0';
1427 }
1428 !mode.is_empty()
1429 && mode.split(',').all(|part| {
1430 let who_end = part.find(['-', '=', '+']).unwrap_or(part.len());
1431 let (who, rest) = part.split_at(who_end);
1432 let only_go = !who.is_empty() && who.chars().all(|c| c == 'g' || c == 'o');
1433 (only_go && (rest.starts_with('-') || rest == "="))
1434 || (who == "u" && rest.starts_with('='))
1435 || (only_go && rest.starts_with('='))
1436 })
1437}
1438
1439fn any_kubeconfig_exists(env: &dyn Environment, list: &str) -> bool {
1441 list.split(':')
1442 .filter(|p| !p.is_empty())
1443 .any(|p| env.path_exists(&expand_home(env, p)))
1444}
1445
1446fn detect_k8s_from_kubeconfig(env: &dyn Environment, kc: &str) -> K8sProbe {
1450 if let Some(c) = current_context_from_kubeconfig(env, kc) {
1451 return (Some(c), false, false);
1452 }
1453 if !any_kubeconfig_exists(env, kc) {
1454 return (None, true, false);
1455 }
1456 let first = kc.split(':').next().unwrap_or(kc);
1457 match env.run_command_outcome(
1458 "kubectl",
1459 &["config", "current-context", "--kubeconfig", first],
1460 K8S_TIMEOUT_MS,
1461 ) {
1462 CommandOutcome::Output(c) if !c.is_empty() => (Some(c), false, false),
1463 CommandOutcome::TimedOut => (None, true, false),
1464 CommandOutcome::Skipped => (None, false, true),
1465 _ => (None, false, false),
1466 }
1467}
1468
1469fn detect_k8s_ambient(env: &dyn Environment) -> K8sProbe {
1472 let kc_env = env.var("KUBECONFIG").filter(|v| !v.is_empty());
1473 if let Some(ref kc) = kc_env {
1475 if current_context_from_kubeconfig(env, kc).is_none() && !any_kubeconfig_exists(env, kc) {
1476 return (None, true, false);
1477 }
1478 }
1479 match env.run_command_outcome("kubectl", &["config", "current-context"], K8S_TIMEOUT_MS) {
1480 CommandOutcome::Output(c) if !c.is_empty() => (Some(c), false, false),
1481 outcome @ (CommandOutcome::TimedOut | CommandOutcome::Skipped) => {
1482 let timed_out = outcome == CommandOutcome::TimedOut;
1486 let from_file = kc_env.map_or_else(
1487 || {
1488 env.home_dir().and_then(|h| {
1489 current_context_from_kubeconfig(
1490 env,
1491 &h.join(".kube").join("config").display().to_string(),
1492 )
1493 })
1494 },
1495 |kc| current_context_from_kubeconfig(env, &kc),
1496 );
1497 from_file.map_or((None, timed_out, !timed_out), |c| (Some(c), false, false))
1498 }
1499 _ => (None, false, false),
1500 }
1501}
1502
1503fn kubeconfig_contexts(env: &dyn Environment, kubeconfig: Option<&str>) -> Vec<String> {
1506 let list = kubeconfig
1507 .map(str::to_string)
1508 .or_else(|| env.var("KUBECONFIG").filter(|v| !v.is_empty()))
1509 .or_else(|| {
1510 env.home_dir()
1511 .map(|h| h.join(".kube").join("config").display().to_string())
1512 })
1513 .unwrap_or_default();
1514 let mut out = Vec::new();
1515 for raw in list.split(':').filter(|p| !p.is_empty()) {
1516 let Ok(content) = env.read_file(&expand_home(env, raw)) else {
1517 continue;
1518 };
1519 let mut in_contexts = false;
1520 for line in content.lines() {
1521 if !line.starts_with([' ', '\t', '-']) && !line.trim().is_empty() {
1522 in_contexts = line.trim_end() == "contexts:";
1523 continue;
1524 }
1525 if !in_contexts {
1526 continue;
1527 }
1528 let t = line.trim_start().trim_start_matches('-').trim_start();
1529 if let Some(v) = t.strip_prefix("name:") {
1530 let v = v
1531 .split(" #")
1532 .next()
1533 .unwrap_or("")
1534 .trim()
1535 .trim_matches(|c| c == '"' || c == '\'');
1536 if !v.is_empty() {
1537 out.push(v.to_string());
1538 }
1539 }
1540 }
1541 }
1542 out
1543}
1544
1545fn branch_exists(env: &dyn Environment, branch: &str) -> bool {
1548 let Ok(cwd) = env.current_dir() else {
1549 return false;
1550 };
1551 let Some(head) = env.find_file_upward(&cwd, ".git/HEAD") else {
1552 return false;
1553 };
1554 let Some(git_dir) = head.parent() else {
1555 return false;
1556 };
1557 if env
1558 .read_file(&git_dir.join("refs").join("heads").join(branch))
1559 .is_ok()
1560 {
1561 return true;
1562 }
1563 env.read_file(&git_dir.join("packed-refs")).is_ok_and(|p| {
1564 p.lines()
1565 .any(|l| l.split_whitespace().nth(1) == Some(&format!("refs/heads/{branch}")))
1566 })
1567}
1568
1569#[must_use]
1574pub fn protected_force_with_lease(
1575 env: &dyn Environment,
1576 config: &ContextConfig,
1577 command: &str,
1578 parsed: &crate::parser::Parsed,
1579) -> Option<String> {
1580 let lease = |s: &str| {
1581 s.contains("push")
1582 && (s.contains("--force-with-lease") || s.contains("--force-if-includes"))
1583 };
1584 if !parsed.segments.iter().any(|s| lease(s)) {
1585 return None;
1586 }
1587 let protected = |b: &String| branch_matches_any(b, &config.protected_branches);
1588 let targets = parse_command_targets(command);
1589 for seg in targets
1590 .segments
1591 .iter()
1592 .filter(|s| s.git && s.git_force_lease)
1593 {
1594 if let Some(t) = seg.git_targets.iter().find(|t| protected(t)) {
1595 return Some(t.clone());
1596 }
1597 let local = seg.place == Place::Local;
1598 let current = || match seg.git_branch_switch {
1599 Some(ref b) => Some(b.clone()),
1600 None if local => detect_git_branch(env).0,
1601 None => None,
1602 };
1603 if seg.git_uses_current {
1604 if let Some(b) = current().filter(protected) {
1605 return Some(b);
1606 }
1607 }
1608 if seg.git_target_unknown
1612 && local
1613 && unknown_target_may_be_protected(env, config, current())
1614 {
1615 return Some(UNKNOWN_PUSH_TARGET.to_string());
1616 }
1617 }
1618 None
1619}
1620
1621pub const UNKNOWN_PUSH_TARGET: &str = "(unknown)";
1624
1625fn unknown_target_may_be_protected(
1629 env: &dyn Environment,
1630 config: &ContextConfig,
1631 current: Option<String>,
1632) -> bool {
1633 current.is_some_and(|b| branch_matches_any(&b, &config.protected_branches))
1634 || config
1635 .protected_branches
1636 .iter()
1637 .filter(|p| !p.contains(['*', '?', '[']))
1638 .any(|p| branch_exists(env, p))
1639}
1640
1641fn current_context_from_kubeconfig(env: &dyn Environment, list: &str) -> Option<String> {
1645 for raw in list.split(':').filter(|p| !p.is_empty()) {
1646 let path = expand_home(env, raw);
1647 let Ok(content) = env.read_file(&path) else {
1648 continue;
1649 };
1650 for line in content.lines() {
1651 if let Some(rest) = line.strip_prefix("current-context:") {
1652 let v = rest
1653 .split(" #")
1654 .next()
1655 .unwrap_or("")
1656 .trim()
1657 .trim_matches(|c| c == '"' || c == '\'');
1658 if !v.is_empty() {
1659 return Some(v.to_string());
1660 }
1661 }
1662 }
1663 }
1664 None
1665}
1666
1667fn expand_home(env: &dyn Environment, p: &str) -> PathBuf {
1668 let rest = p
1669 .strip_prefix("~/")
1670 .or_else(|| p.strip_prefix("$HOME/"))
1671 .or_else(|| p.strip_prefix("${HOME}/"));
1672 match (rest, env.home_dir()) {
1673 (Some(rest), Some(home)) => home.join(rest),
1674 _ => PathBuf::from(p),
1675 }
1676}
1677
1678pub(crate) fn compute_risk_level(ctx: &RuntimeContext, config: &ContextConfig) -> RiskLevel {
1680 ctx.risk_reasons(config)
1681 .into_iter()
1682 .map(|(level, _)| level)
1683 .max()
1684 .unwrap_or(RiskLevel::Normal)
1685}
1686
1687#[must_use]
1690pub fn branch_matches_any(branch: &str, patterns: &[String]) -> bool {
1694 let cleaned = strip_invisible(branch);
1695 let branch = cleaned.as_str();
1696 patterns.iter().any(|pattern| {
1697 if pattern.contains('*') || pattern.contains('?') {
1698 glob_match(pattern.as_bytes(), branch.as_bytes())
1699 } else {
1700 branch == pattern
1701 }
1702 })
1703}
1704
1705#[must_use]
1710pub fn matches_any_pattern(value: &str, patterns: &[String]) -> bool {
1711 let lower = strip_invisible(value).to_ascii_lowercase();
1712 let segments = split_segments(&lower);
1713 patterns.iter().any(|p| {
1714 let p = p.to_ascii_lowercase();
1715 if p.contains('*') || p.contains('?') {
1716 return glob_match(p.as_bytes(), lower.as_bytes());
1717 }
1718 let needle = split_segments(&p);
1719 !needle.is_empty()
1720 && segments
1721 .windows(needle.len())
1722 .any(|w| w == needle.as_slice())
1723 })
1724}
1725
1726#[must_use]
1729pub const fn is_invisible(c: char) -> bool {
1730 matches!(
1731 c,
1732 '\u{00ad}'
1733 | '\u{034f}'
1734 | '\u{061c}'
1735 | '\u{115f}'
1736 | '\u{1160}'
1737 | '\u{17b4}'
1738 | '\u{17b5}'
1739 | '\u{180e}'
1740 | '\u{200b}'..='\u{200f}'
1741 | '\u{202a}'..='\u{202e}'
1742 | '\u{2060}'..='\u{2064}'
1743 | '\u{2066}'..='\u{206f}'
1744 | '\u{3164}'
1745 | '\u{feff}'
1746 | '\u{ffa0}'
1747 | '\u{fe00}'..='\u{fe0f}'
1748 )
1749}
1750
1751#[must_use]
1753pub fn strip_invisible(s: &str) -> String {
1754 s.chars().filter(|c| !is_invisible(*c)).collect()
1755}
1756
1757#[must_use]
1761pub fn escape_invisible(s: &str) -> String {
1762 use std::fmt::Write as _;
1763 if !s
1764 .chars()
1765 .any(|c| is_invisible(c) || (c.is_control() && c != '\t' && c != '\n'))
1766 {
1767 return s.to_string();
1768 }
1769 let mut out = String::with_capacity(s.len() + 8);
1770 for c in s.chars() {
1771 if is_invisible(c) || (c.is_control() && c != '\t' && c != '\n') {
1772 let _ = write!(out, "\\u{{{:x}}}", c as u32);
1773 } else {
1774 out.push(c);
1775 }
1776 }
1777 out
1778}
1779
1780#[must_use]
1786pub const fn is_text_joiner(c: char) -> bool {
1787 matches!(c, '\u{200c}' | '\u{200d}' | '\u{fe0e}' | '\u{fe0f}')
1788}
1789
1790#[must_use]
1798pub fn escape_invisible_text(s: &str) -> String {
1799 use std::fmt::Write as _;
1800 let escaped = |c: char| {
1801 !is_text_joiner(c) && (is_invisible(c) || (c.is_control() && c != '\t' && c != '\n'))
1802 };
1803 if !s.chars().any(escaped) {
1804 return s.to_string();
1805 }
1806 let mut out = String::with_capacity(s.len() + 8);
1807 for c in s.chars() {
1808 if escaped(c) {
1809 let _ = write!(out, "\\u{{{:x}}}", c as u32);
1810 } else {
1811 out.push(c);
1812 }
1813 }
1814 out
1815}
1816
1817fn split_segments(s: &str) -> Vec<&str> {
1818 s.split(|c: char| !c.is_ascii_alphanumeric())
1819 .filter(|seg| !seg.is_empty())
1820 .collect()
1821}
1822
1823const fn glob_match(pattern: &[u8], text: &[u8]) -> bool {
1825 let (mut p, mut t) = (0usize, 0usize);
1826 let (mut star, mut mark) = (None::<usize>, 0usize);
1827 while t < text.len() {
1828 if p < pattern.len() && (pattern[p] == b'?' || pattern[p] == text[t]) {
1829 p += 1;
1830 t += 1;
1831 } else if p < pattern.len() && pattern[p] == b'*' {
1832 star = Some(p);
1833 mark = t;
1834 p += 1;
1835 } else if let Some(s) = star {
1836 p = s + 1;
1837 mark += 1;
1838 t = mark;
1839 } else {
1840 return false;
1841 }
1842 }
1843 while p < pattern.len() && pattern[p] == b'*' {
1844 p += 1;
1845 }
1846 p == pattern.len()
1847}
1848
1849#[must_use]
1852pub fn escalate_challenge(
1853 base: &Challenge,
1854 risk_level: RiskLevel,
1855 escalation: &EscalationConfig,
1856) -> Challenge {
1857 let context_min = match risk_level {
1858 RiskLevel::Normal => return *base,
1859 RiskLevel::Elevated => &escalation.elevated,
1860 RiskLevel::Critical => &escalation.critical,
1861 };
1862
1863 base.stricter(*context_min)
1865}
1866
1867#[derive(Debug, Clone, PartialEq, Eq)]
1873pub struct EffectiveChallenge {
1874 pub base: Challenge,
1876 pub challenge: Challenge,
1878 pub reasons: Vec<String>,
1880}
1881
1882impl EffectiveChallenge {
1883 #[must_use]
1885 pub fn is_escalated(&self) -> bool {
1886 self.challenge.is_stricter_than(self.base)
1887 }
1888
1889 #[must_use]
1893 pub fn note(&self) -> Option<String> {
1894 if !self.is_escalated() {
1895 return None;
1896 }
1897 let mut s = format!("Escalated to {} (from {})", self.challenge, self.base);
1898 if !self.reasons.is_empty() {
1899 s.push_str(": ");
1900 s.push_str(&self.reasons.join(", "));
1901 }
1902 Some(s)
1903 }
1904}
1905
1906#[must_use]
1920pub fn effective_challenge(
1921 settings: &Settings,
1922 resolved: &ResolvedSettings,
1923 checks: &[&Check],
1924 context: &RuntimeContext,
1925 merged_policy: &MergedPolicy,
1926) -> EffectiveChallenge {
1927 let base = resolved.challenge;
1928 let mut floors: Vec<(Challenge, String)> = Vec::new();
1929
1930 if let Some(sev) = checks.iter().map(|c| c.severity).max() {
1932 if let Some(floor) = resolved.severity_escalation.challenge_for_severity(sev) {
1933 floors.push((floor, format!("severity {sev}")));
1934 }
1935 }
1936
1937 for check in checks {
1939 if let Some(&floor) = settings.group_escalation.get(&check.from) {
1940 floors.push((floor, format!("`{}` group escalation", check.from)));
1941 }
1942 }
1943
1944 for check in checks {
1946 if let Some(&floor) = settings.check_escalation.get(&check.id) {
1947 floors.push((floor, format!("`{}` check escalation", check.id)));
1948 }
1949 }
1950
1951 let policy_label = merged_policy.sources_label();
1956 let credited = |reason: String| match &policy_label {
1957 Some(label) => format!("{reason} ({label})"),
1958 None => reason,
1959 };
1960 let context_floor = escalate_challenge(&base, context.risk_level, &settings.context.escalation);
1961 if context.risk_level != RiskLevel::Normal {
1962 for (level, reason) in context.risk_reasons(&settings.context) {
1963 if level == context.risk_level {
1964 floors.push((context_floor, credited(reason)));
1965 }
1966 }
1967 }
1968
1969 for check in checks {
1974 if let Some(&floor) = merged_policy.challenge_overrides.get(&check.id) {
1975 if let Some(label) = merged_policy.rule_label_for(&check.id) {
1976 floors.push((floor, format!("{label} for `{}`", check.id)));
1977 continue;
1978 }
1979 let label = policy_label
1980 .clone()
1981 .unwrap_or_else(|| "project policy (.shellfirm.yaml)".to_string());
1982 let context_reasons: Vec<String> = context
1983 .risk_reasons(&settings.context)
1984 .into_iter()
1985 .filter(|(level, _)| *level == context.risk_level)
1986 .map(|(_, reason)| format!("{reason} ({label})"))
1987 .collect();
1988 if context_reasons.is_empty() {
1989 floors.push((floor, format!("context risk ({label})")));
1990 }
1991 for reason in context_reasons {
1992 floors.push((floor, reason));
1993 }
1994 }
1995 }
1996
1997 let challenge = floors.iter().fold(base, |acc, (f, _)| acc.stricter(*f));
1998
1999 let mut reasons: Vec<String> = Vec::new();
2000 if challenge.is_stricter_than(base) {
2001 for (floor, reason) in floors {
2002 if floor == challenge && !reasons.contains(&reason) {
2003 reasons.push(reason);
2004 }
2005 }
2006 }
2007 let labelled: Vec<String> = reasons.clone();
2010 reasons.retain(|r| {
2011 !labelled.iter().any(|l| {
2012 l.strip_prefix(r.as_str())
2013 .is_some_and(|rest| rest.starts_with(" ("))
2014 })
2015 });
2016
2017 EffectiveChallenge {
2018 base,
2019 challenge,
2020 reasons,
2021 }
2022}
2023
2024#[must_use]
2026pub fn deny_reasons(
2027 settings: &Settings,
2028 checks: &[&Check],
2029 merged_policy: &MergedPolicy,
2030) -> Vec<String> {
2031 let mut reasons = Vec::new();
2032 for check in checks {
2033 if settings.deny_patterns_ids.contains(&check.id) {
2034 reasons.push(format!("`{}` is on your deny list", check.id));
2035 } else if merged_policy.is_denied(&check.id) {
2036 reasons.push(format!(
2037 "`{}` is denied by the {}",
2038 check.id,
2039 merged_policy
2040 .label_for(&check.id)
2041 .unwrap_or_else(|| "project policy (.shellfirm.yaml)".to_string())
2042 ));
2043 }
2044 }
2045 reasons.dedup();
2046 reasons
2047}
2048
2049#[derive(Debug, Clone, Default, PartialEq, Eq)]
2055pub enum Place {
2056 #[default]
2058 Local,
2059 Host(String),
2063 Container,
2065 Pod,
2069}
2070
2071#[derive(Debug, Clone, Default, PartialEq, Eq)]
2077#[allow(clippy::struct_excessive_bools)]
2078pub struct SegmentTargets {
2079 pub text: String,
2082 pub place: Place,
2084 pub sudo_root: bool,
2086 pub root_tool: Option<String>,
2088 pub terraform: bool,
2091 pub tf_fallbacks: Vec<CtxAlt>,
2094 pub tf_dir: Option<String>,
2097 pub tf_dir_unknown: bool,
2099 pub cluster: Option<String>,
2101 pub git_dir: Option<String>,
2104 pub chdir: Option<String>,
2107 pub git: bool,
2109 pub git_uses_current: bool,
2111 pub git_target_unknown: bool,
2114 pub git_force_lease: bool,
2117 pub git_reset_to: Option<String>,
2119 pub git_targets: Vec<String>,
2121 pub git_push_all: bool,
2123 pub git_branch_switch: Option<String>,
2125 pub mentions_k8s: bool,
2127 pub switch_only: bool,
2130 pub k8s_context: Option<String>,
2132 pub k8s_context_unknown: bool,
2134 pub kubeconfig: Option<String>,
2136 pub k8s_namespace: Option<String>,
2138 pub aws_profile: Option<String>,
2140 pub tf_workspace: Option<String>,
2142 pub gcp_project: Option<String>,
2144 pub azure_subscription: Option<String>,
2146 pub env: Vec<(String, Option<String>)>,
2149 pub k8s_fallbacks: Vec<CtxAlt>,
2154 pub k8s_fallbacks_always: bool,
2157 pub k8s_context_list: bool,
2160 pub k8s_all_contexts: bool,
2163 pub git_fallbacks: Vec<CtxAlt>,
2165 pub git_fallbacks_always: bool,
2167 pub git_switch_creates: bool,
2169 pub tf_dir_hints: Vec<String>,
2173}
2174
2175impl SegmentTargets {
2176 #[allow(clippy::option_option)]
2178 fn line_var(&self, key: &str) -> Option<Option<String>> {
2179 self.env
2180 .iter()
2181 .rev()
2182 .find(|(k, _)| k == key)
2183 .map(|(_, v)| v.clone().filter(|v| !v.is_empty()))
2184 }
2185}
2186
2187#[derive(Debug, Clone, Default, PartialEq, Eq)]
2190#[allow(clippy::struct_excessive_bools)]
2191pub struct CommandTargets {
2192 pub git_invocations: usize,
2194 pub git_uses_current: bool,
2196 pub git_targets: Vec<String>,
2198 pub git_push_all: bool,
2200 pub mentions_k8s: bool,
2202 pub k8s_context: Option<String>,
2205 pub kubeconfig: Option<String>,
2207 pub sudo_root: bool,
2209 pub remote_hosts: Vec<String>,
2211 pub segments: Vec<SegmentTargets>,
2213}
2214
2215#[derive(Debug, Clone, Default)]
2217#[allow(clippy::struct_excessive_bools)]
2218struct LineState {
2219 k8s_context: Option<String>,
2220 k8s_unknown: bool,
2221 k8s_fallbacks: Vec<CtxAlt>,
2223 k8s_switch_certain: bool,
2225 k8s_namespace: Option<String>,
2226 git_branch: Option<String>,
2227 git_fallbacks: Vec<CtxAlt>,
2229 git_switch_certain: bool,
2230 git_switch_creates: bool,
2232 tf_workspace: Option<String>,
2233 tf_fallbacks: Vec<CtxAlt>,
2235 tf_switch_certain: bool,
2236 gcp_project: Option<String>,
2237 azure_subscription: Option<String>,
2238 env: Vec<(String, Option<String>)>,
2239 vars: std::collections::HashMap<String, Vec<String>>,
2242 cwd: Option<String>,
2244 lists_contexts: bool,
2248 pipe_values: Option<Vec<String>>,
2251}
2252
2253impl LineState {
2254 fn k8s_alt(&self) -> CtxAlt {
2256 if self.k8s_unknown {
2257 CtxAlt::Unknown
2258 } else {
2259 self.k8s_context
2260 .clone()
2261 .map_or(CtxAlt::Current, CtxAlt::Named)
2262 }
2263 }
2264
2265 fn git_alt(&self) -> CtxAlt {
2267 self.git_branch
2268 .clone()
2269 .map_or(CtxAlt::Current, CtxAlt::Named)
2270 }
2271}
2272
2273#[derive(Debug, Clone, PartialEq, Eq)]
2276pub enum CtxAlt {
2277 Current,
2279 Named(String),
2281 Unknown,
2283}
2284
2285#[derive(Debug, Clone, Default)]
2287struct Inherit {
2288 place: Place,
2289 sudo_root: bool,
2290 root_tool: Option<String>,
2291 env: Vec<(String, Option<String>)>,
2292 k8s_context: Option<String>,
2294 k8s_unknown: bool,
2295 kubeconfig: Option<String>,
2296 k8s_namespace: Option<String>,
2297 k8s_fallbacks: Vec<CtxAlt>,
2300 k8s_fallbacks_always: bool,
2301}
2302
2303#[must_use]
2305pub fn parse_command_targets(command: &str) -> CommandTargets {
2306 let mut out = CommandTargets::default();
2307 let mut state = LineState {
2308 lists_contexts: lists_kube_contexts(command),
2309 ..LineState::default()
2310 };
2311 parse_into(command, &mut out, &mut state, &Inherit::default(), 0);
2312 for s in &out.segments {
2313 if s.git {
2314 out.git_invocations += 1;
2315 }
2316 if s.place == Place::Local {
2317 out.git_uses_current |= s.git_uses_current;
2318 out.sudo_root |= s.sudo_root;
2319 }
2320 for t in &s.git_targets {
2321 if !out.git_targets.contains(t) {
2322 out.git_targets.push(t.clone());
2323 }
2324 }
2325 out.git_push_all |= s.git_push_all;
2326 out.mentions_k8s |= s.mentions_k8s;
2327 if let Place::Host(ref h) = s.place {
2328 if !out.remote_hosts.contains(h) {
2329 out.remote_hosts.push(h.clone());
2330 }
2331 }
2332 }
2333 if let Some(s) = out
2334 .segments
2335 .iter()
2336 .find(|s| s.place == Place::Local && s.mentions_k8s && !s.switch_only)
2337 {
2338 out.k8s_context.clone_from(&s.k8s_context);
2339 out.kubeconfig.clone_from(&s.kubeconfig);
2340 }
2341 out
2342}
2343
2344fn lists_kube_contexts(command: &str) -> bool {
2348 command.contains("get-contexts")
2349 || [
2350 "$(kubectx)",
2351 "`kubectx`",
2352 "kubectx |",
2353 "kubectx|",
2354 "kubectl config view",
2355 ]
2356 .iter()
2357 .any(|p| command.contains(p))
2358}
2359
2360fn is_literal_name(v: &str) -> bool {
2363 !v.is_empty()
2364 && v.chars()
2365 .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '@' | '/'))
2366}
2367
2368fn parse_into(
2369 command: &str,
2370 out: &mut CommandTargets,
2371 state: &mut LineState,
2372 inh: &Inherit,
2373 depth: usize,
2374) {
2375 if depth > 6 {
2376 return;
2377 }
2378 let mut pending_cd_failure: Option<Option<String>> = None;
2379 for (segment, op) in tokenize_segments_with_ops(command) {
2380 let before_k8s = state.k8s_alt();
2381 let before_k8s_fallbacks = state.k8s_fallbacks.clone();
2382 let before_git = state.git_alt();
2383 let before_git_fallbacks = state.git_fallbacks.clone();
2384 let k8s_before = (state.k8s_context.clone(), state.k8s_unknown);
2385 let git_before = state.git_branch.clone();
2386 let tf_before = state.tf_workspace.clone();
2387 let tf_before_fallbacks = state.tf_fallbacks.clone();
2388 let cd_failed_dir = pending_cd_failure.take();
2391 let cwd_after_cd = cd_failed_dir
2392 .as_ref()
2393 .map(|before| std::mem::replace(&mut state.cwd, before.clone()));
2394 let cwd_before = state.cwd.clone();
2395 parse_segment(&segment, out, state, inh, depth);
2396 state.pipe_values = if op == "|" {
2397 literal_output_lines(&segment)
2398 } else {
2399 None
2400 };
2401 if let Some(after) = cwd_after_cd {
2402 if state.cwd == cwd_before {
2403 state.cwd = after;
2404 }
2405 }
2406 let is_cd = segment
2407 .first()
2408 .is_some_and(|t| matches!(program_name(t), "cd" | "pushd"));
2409 if is_cd && op == "||" && state.cwd != cwd_before {
2410 pending_cd_failure = Some(cwd_before);
2411 }
2412 if state.tf_workspace != tf_before {
2413 let mut alts = vec![tf_before.map_or(CtxAlt::Current, CtxAlt::Named)];
2414 alts.extend(tf_before_fallbacks);
2415 alts.dedup();
2416 state.tf_fallbacks = alts;
2417 state.tf_switch_certain = op == "&&";
2418 } else if op != "&&" {
2419 state.tf_switch_certain = false;
2420 }
2421 if (state.k8s_context.clone(), state.k8s_unknown) != k8s_before {
2424 let mut alts = vec![before_k8s];
2425 alts.extend(before_k8s_fallbacks);
2426 alts.dedup();
2427 state.k8s_fallbacks = alts;
2428 let kubie_subshell = segment.first().is_some_and(|t| program_name(t) == "kubie");
2431 state.k8s_switch_certain = op == "&&" && !kubie_subshell;
2432 } else if op != "&&" {
2433 state.k8s_switch_certain = false;
2434 }
2435 if state.git_branch != git_before {
2436 let mut alts = vec![before_git];
2437 alts.extend(before_git_fallbacks);
2438 alts.dedup();
2439 state.git_fallbacks = alts;
2440 state.git_switch_certain = op == "&&";
2441 } else if op != "&&" {
2442 state.git_switch_certain = false;
2443 }
2444 }
2445}
2446
2447fn literal_output_lines(segment: &[String]) -> Option<Vec<String>> {
2450 let (prog, args) = segment.split_first()?;
2451 let literal = |w: &String| !w.contains(['$', '`', '*', '?']) && !w.contains("{}");
2452 let lines: Vec<String> = match program_name(prog) {
2453 "echo" => {
2454 let args: Vec<&String> = args
2455 .iter()
2456 .filter(|a| !matches!(a.as_str(), "-n" | "-e" | "-E"))
2457 .collect();
2458 if args.is_empty() || !args.iter().all(|a| literal(a)) {
2459 return None;
2460 }
2461 vec![args
2462 .iter()
2463 .map(|a| a.as_str())
2464 .collect::<Vec<_>>()
2465 .join(" ")]
2466 }
2467 "printf" => {
2468 let (fmt, rest) = args.split_first()?;
2469 if !rest.iter().all(literal) {
2470 return None;
2471 }
2472 if rest.is_empty() {
2473 if !literal(fmt) || fmt.contains('%') {
2474 return None;
2475 }
2476 fmt.split("\\n").map(str::to_string).collect()
2477 } else if fmt == "%s\\n" || fmt == "%s" {
2478 rest.to_vec()
2479 } else {
2480 return None;
2481 }
2482 }
2483 _ => return None,
2484 };
2485 let lines: Vec<String> = lines.into_iter().filter(|l| !l.is_empty()).collect();
2486 (!lines.is_empty()).then_some(lines)
2487}
2488
2489fn is_assignment(tok: &str) -> Option<(String, String)> {
2490 let (name, value) = tok.split_once('=')?;
2491 let mut chars = name.chars();
2492 let first = chars.next()?;
2493 if !(first.is_ascii_alphabetic() || first == '_')
2494 || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
2495 {
2496 return None;
2497 }
2498 Some((name.to_string(), value.to_string()))
2499}
2500
2501fn program_name(tok: &str) -> &str {
2502 let tok = tok.strip_prefix('\\').unwrap_or(tok);
2503 tok.rsplit('/').next().unwrap_or(tok)
2504}
2505
2506fn quote_token(s: &str) -> String {
2508 if !s.is_empty()
2509 && s.chars()
2510 .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%~^*{}[]".contains(c))
2511 {
2512 s.to_string()
2513 } else {
2514 format!("'{}'", s.replace('\'', "'\\''"))
2515 }
2516}
2517
2518fn quote_join(tokens: &[String]) -> String {
2519 tokens
2520 .iter()
2521 .map(|t| quote_token(t))
2522 .collect::<Vec<_>>()
2523 .join(" ")
2524}
2525
2526fn is_root_user(user: &str) -> bool {
2528 matches!(user, "root" | "#0" | "0")
2529}
2530
2531fn dash_c_value(args: &[String]) -> Option<(usize, String)> {
2533 let mut i = 0;
2534 while i < args.len() {
2535 let a = args[i].as_str();
2536 if a == "-c" || a == "--command" {
2537 return args.get(i + 1).map(|v| (i, v.clone()));
2538 }
2539 if let Some(v) = a.strip_prefix("--command=") {
2540 return Some((i, v.to_string()));
2541 }
2542 if a.len() > 2
2544 && a.starts_with('-')
2545 && !a.starts_with("--")
2546 && a.ends_with('c')
2547 && a[1..].chars().all(|c| c.is_ascii_alphabetic())
2548 {
2549 return args.get(i + 1).map(|v| (i, v.clone()));
2550 }
2551 i += 1;
2552 }
2553 None
2554}
2555
2556enum Wrap {
2558 Skip(usize),
2560 Done,
2562}
2563
2564#[allow(clippy::too_many_lines, clippy::many_single_char_names)]
2567fn unwrap_one(
2568 tokens: &[String],
2569 i: usize,
2570 seg: &mut SegmentTargets,
2571 segment_env: &mut Vec<(String, Option<String>)>,
2572 ctx: &mut Recurse<'_>,
2573) -> Option<Wrap> {
2574 let n = tokens.len();
2575 let tok = &tokens[i];
2576 let prog = program_name(tok);
2577 let mut j = i + 1;
2578 let skip_flags = |mut j: usize, value_flags: &[&str]| {
2579 while let Some(t) = tokens.get(j) {
2580 if t == "--" {
2581 return j + 1;
2582 }
2583 if !t.starts_with('-') || t == "-" {
2584 break;
2585 }
2586 j += if value_flags.contains(&t.as_str()) {
2587 2
2588 } else {
2589 1
2590 };
2591 }
2592 j
2593 };
2594 match prog {
2595 "sudo" | "doas" => {
2596 let mut as_root = true;
2597 while let Some(opt) = tokens.get(j) {
2598 if !opt.starts_with('-') {
2599 break;
2600 }
2601 if opt == "--" {
2602 j += 1;
2603 break;
2604 }
2605 if opt == "-D" || opt == "--chdir" {
2607 seg.chdir = tokens.get(j + 1).cloned();
2608 } else if let Some(d) = opt
2609 .strip_prefix("--chdir=")
2610 .or_else(|| opt.strip_prefix("-D").filter(|d| !d.is_empty()))
2611 {
2612 seg.chdir = Some(d.to_string());
2613 }
2614 let (words_used, run_as) =
2617 crate::parser::privilege_option(opt, tokens.get(j + 1).map(String::as_str));
2618 if let Some(name) = run_as {
2619 as_root = is_root_user(&name);
2620 }
2621 j += words_used;
2622 }
2623 if as_root {
2624 seg.sudo_root = true;
2625 seg.root_tool = Some(prog.to_string());
2626 }
2627 Some(Wrap::Skip(j))
2628 }
2629 "env" => {
2630 while let Some(opt) = tokens.get(j) {
2631 let split = if opt == "-S" || opt == "--split-string" {
2633 tokens.get(j + 1).map(|v| (v.clone(), j + 2))
2634 } else {
2635 opt.strip_prefix("--split-string=")
2636 .or_else(|| opt.strip_prefix("-S").filter(|v| !v.is_empty()))
2637 .map(|v| (v.to_string(), j + 1))
2638 };
2639 if let Some((text, next)) = split {
2640 let mut payload = text;
2641 if next < n {
2642 payload.push(' ');
2643 payload.push_str("e_join(&tokens[next..]));
2644 }
2645 ctx.recurse(&payload, seg, segment_env);
2646 return Some(Wrap::Done);
2647 }
2648 if matches!(opt.as_str(), "-u" | "--unset") {
2649 if let Some(v) = tokens.get(j + 1) {
2650 segment_env.push((v.clone(), None));
2651 }
2652 j += 2;
2653 } else if matches!(opt.as_str(), "-C" | "--chdir") {
2654 seg.chdir = tokens.get(j + 1).cloned();
2655 j += 2;
2656 } else if let Some(d) = opt
2657 .strip_prefix("--chdir=")
2658 .or_else(|| opt.strip_prefix("-C").filter(|d| !d.is_empty()))
2659 {
2660 seg.chdir = Some(d.to_string());
2661 j += 1;
2662 } else if opt.starts_with('-') {
2663 j += 1;
2664 } else if let Some((k, v)) = is_assignment(opt) {
2665 segment_env.push((k, Some(v)));
2666 j += 1;
2667 } else {
2668 break;
2669 }
2670 }
2671 Some(Wrap::Skip(j))
2672 }
2673 "su" => {
2675 let mut user: Option<&str> = None;
2676 let mut k = j;
2677 while let Some(t) = tokens.get(k) {
2678 match t.as_str() {
2679 "-c"
2680 | "--command"
2681 | "-s"
2682 | "--shell"
2683 | "-g"
2684 | "--group"
2685 | "-G"
2686 | "--supp-group"
2687 | "-w"
2688 | "--whitelist-environment" => k += 2,
2689 s if s.len() > 2
2691 && s.starts_with('-')
2692 && !s.starts_with("--")
2693 && s.ends_with('c') =>
2694 {
2695 k += 2;
2696 }
2697 s if s.starts_with('-') => k += 1,
2698 s => {
2699 if user.is_none() {
2700 user = Some(s);
2701 }
2702 k += 1;
2703 }
2704 }
2705 }
2706 if user.is_none_or(is_root_user) {
2707 seg.sudo_root = true;
2708 seg.root_tool = Some(prog.to_string());
2709 }
2710 if let Some((_, payload)) = dash_c_value(&tokens[j..]) {
2711 ctx.recurse(&payload, seg, segment_env);
2712 }
2713 Some(Wrap::Done)
2714 }
2715 "runuser" => {
2717 let rest = &tokens[j..];
2718 let user = flag_value(rest, &["-u", "--user"]).or_else(|| {
2719 let mut k = 0;
2720 while let Some(t) = rest.get(k) {
2721 if matches!(t.as_str(), "-c" | "--command" | "-g" | "-G" | "-s") {
2722 k += 2;
2723 } else if t.starts_with('-') {
2724 k += 1;
2725 } else {
2726 return Some(t.clone());
2727 }
2728 }
2729 None
2730 });
2731 if user.as_deref().is_none_or(is_root_user) {
2732 seg.sudo_root = true;
2733 seg.root_tool = Some(prog.to_string());
2734 }
2735 if let Some((_, payload)) = dash_c_value(rest) {
2736 ctx.recurse(&payload, seg, segment_env);
2737 return Some(Wrap::Done);
2738 }
2739 Some(Wrap::Skip(skip_flags(
2740 j,
2741 &["-u", "--user", "-g", "--group", "-G", "--supp-group"],
2742 )))
2743 }
2744 "pkexec" => {
2745 let mut as_root = true;
2746 while let Some(t) = tokens.get(j) {
2747 if t == "--user" {
2748 as_root = tokens.get(j + 1).is_some_and(|u| is_root_user(u));
2749 j += 2;
2750 } else if t.starts_with('-') {
2751 j += 1;
2752 } else {
2753 break;
2754 }
2755 }
2756 if as_root {
2757 seg.sudo_root = true;
2758 seg.root_tool = Some(prog.to_string());
2759 }
2760 Some(Wrap::Skip(j))
2761 }
2762 "flock" => {
2764 if let Some((_, payload)) = dash_c_value(&tokens[j..]) {
2765 ctx.recurse(&payload, seg, segment_env);
2766 return Some(Wrap::Done);
2767 }
2768 let j = skip_flags(j, &["-w", "--timeout", "-E", "--conflict-exit-code"]);
2769 Some(Wrap::Skip(j + 1))
2770 }
2771 "script" => {
2773 if let Some((_, payload)) = dash_c_value(&tokens[j..]) {
2774 ctx.recurse(&payload, seg, segment_env);
2775 }
2776 Some(Wrap::Done)
2777 }
2778 "chroot" => {
2779 let j = skip_flags(j, &["--userspec", "--groups"]);
2780 Some(Wrap::Skip(j + 1))
2781 }
2782 "nice" | "ionice" | "timeout" | "chrt" | "taskset" => {
2783 let value_flags: &[&str] = match prog {
2784 "nice" => &["-n", "--adjustment"],
2785 "ionice" => &["-c", "--class", "-n", "--classdata", "-t"],
2786 "timeout" => &["-s", "--signal", "-k", "--kill-after"],
2787 "chrt" => &["-T", "-P", "-D"],
2788 _ => &["-c", "--cpu-list"],
2789 };
2790 let had_list = prog == "taskset"
2791 && tokens[j..]
2792 .iter()
2793 .take_while(|t| t.starts_with('-'))
2794 .any(|t| t == "-c" || t == "--cpu-list");
2795 let mut j = skip_flags(j, value_flags);
2796 let operand = match prog {
2798 "timeout" | "chrt" => true,
2799 "taskset" => !had_list,
2800 _ => false,
2801 };
2802 if operand && j < n {
2803 j += 1;
2804 }
2805 Some(Wrap::Skip(j))
2806 }
2807 "unshare" | "nsenter" => {
2808 if prog == "nsenter" {
2811 seg.sudo_root = true;
2812 seg.root_tool = Some(prog.to_string());
2813 }
2814 let value_flags: &[&str] = if prog == "nsenter" {
2815 &["-t", "--target", "-S", "--setuid", "-G", "--setgid"]
2816 } else {
2817 &["--map-user", "--map-group", "--setgroups", "--propagation"]
2818 };
2819 Some(Wrap::Skip(skip_flags(j, value_flags)))
2820 }
2821 "strace" | "ltrace" => Some(Wrap::Skip(skip_flags(
2822 j,
2823 &[
2824 "-e", "-o", "-p", "-s", "-u", "-E", "-a", "-b", "-I", "-O", "-S", "-P", "-X",
2825 ],
2826 ))),
2827 "xargs" => {
2828 let mut replace: Option<String> = None;
2833 while let Some(t) = tokens.get(j) {
2834 if t == "--" {
2835 j += 1;
2836 break;
2837 }
2838 if !t.starts_with('-') || t == "-" {
2839 break;
2840 }
2841 if t == "-I" || t == "-J" {
2842 replace = tokens.get(j + 1).cloned();
2843 j += 2;
2844 continue;
2845 }
2846 if t == "-i" || t == "--replace" {
2847 replace = Some("{}".to_string());
2848 } else if let Some(r) = t
2849 .strip_prefix("--replace=")
2850 .or_else(|| t.strip_prefix("-I").filter(|r| !r.is_empty()))
2851 .or_else(|| t.strip_prefix("-i").filter(|r| !r.is_empty()))
2852 {
2853 replace = Some(r.to_string());
2854 } else if matches!(
2855 t.as_str(),
2856 "-n" | "-P"
2857 | "-L"
2858 | "-s"
2859 | "-d"
2860 | "-E"
2861 | "-a"
2862 | "--max-args"
2863 | "--max-procs"
2864 | "--max-lines"
2865 | "--delimiter"
2866 | "--arg-file"
2867 ) {
2868 j += 1;
2869 }
2870 j += 1;
2871 }
2872 let piped = ctx.state.pipe_values.take();
2875 if let (Some(r), Some(values)) = (replace.as_ref().filter(|r| !r.is_empty()), piped) {
2876 if j < n {
2877 for v in values.iter().take(16) {
2878 let rewritten: Vec<String> = tokens[j..]
2879 .iter()
2880 .map(|t| t.replace(r.as_str(), v))
2881 .collect();
2882 ctx.recurse("e_join(&rewritten), seg, segment_env);
2883 }
2884 return Some(Wrap::Done);
2885 }
2886 }
2887 match replace.filter(|r| !r.is_empty() && r != "{}") {
2888 Some(r) if j < n => {
2889 let rewritten: Vec<String> = tokens[j..]
2890 .iter()
2891 .map(|t| t.replace(r.as_str(), "{}"))
2892 .collect();
2893 ctx.recurse("e_join(&rewritten), seg, segment_env);
2894 Some(Wrap::Done)
2895 }
2896 _ => Some(Wrap::Skip(j)),
2897 }
2898 }
2899 "parallel" if tokens[j..].iter().any(|t| t == ":::") => {
2902 let k = skip_flags(
2903 j,
2904 &[
2905 "-j",
2906 "--jobs",
2907 "-N",
2908 "-S",
2909 "--sshlogin",
2910 "--delay",
2911 "--timeout",
2912 ],
2913 );
2914 let sep = tokens[k..].iter().position(|t| t == ":::").map(|p| p + k)?;
2915 let cmd = &tokens[k..sep];
2916 if cmd.is_empty() {
2917 return Some(Wrap::Done);
2918 }
2919 for arg in tokens[sep + 1..]
2920 .iter()
2921 .take_while(|t| *t != ":::" && *t != "::::")
2922 .take(16)
2923 {
2924 let mut c: Vec<String> = cmd.to_vec();
2925 if c.iter().any(|t| t.contains("{}")) {
2926 for t in &mut c {
2927 *t = t.replace("{}", arg);
2928 }
2929 } else {
2930 c.push(arg.clone());
2931 }
2932 ctx.recurse("e_join(&c), seg, segment_env);
2933 }
2934 Some(Wrap::Done)
2935 }
2936 "watch" => Some(Wrap::Skip(skip_flags(
2937 j,
2938 &["-n", "--interval", "-d", "-q", "--equexit"],
2939 ))),
2940 "command" | "exec" | "nohup" | "builtin" | "time" | "noglob" | "nocorrect" | "-"
2941 | "setsid" | "stdbuf" | "busybox" | "coproc" => Some(Wrap::Skip(skip_flags(j, &[]))),
2942 "if" | "then" | "else" | "elif" | "do" | "while" | "until" | "!" | "{" | "}" => {
2944 Some(Wrap::Skip(j))
2945 }
2946 _ => None,
2947 }
2948}
2949
2950struct Recurse<'a> {
2952 out: &'a mut CommandTargets,
2953 state: &'a mut LineState,
2954 inh: &'a Inherit,
2955 depth: usize,
2956}
2957
2958impl Recurse<'_> {
2959 fn recurse(
2962 &mut self,
2963 payload: &str,
2964 seg: &SegmentTargets,
2965 segment_env: &[(String, Option<String>)],
2966 ) {
2967 let mut inh = self.inh.clone();
2968 inh.sudo_root = seg.sudo_root;
2969 inh.root_tool.clone_from(&seg.root_tool);
2970 inh.env.extend(segment_env.iter().cloned());
2971 let saved: Vec<(String, Option<Vec<String>>)> = segment_env
2974 .iter()
2975 .map(|(k, v)| {
2976 let old = match v {
2977 Some(v) => self.state.vars.insert(k.clone(), vec![v.clone()]),
2978 None => self.state.vars.remove(k),
2979 };
2980 (k.clone(), old)
2981 })
2982 .collect();
2983 parse_into(payload, self.out, self.state, &inh, self.depth + 1);
2984 for (k, old) in saved.into_iter().rev() {
2985 match old {
2986 Some(v) => self.state.vars.insert(k, v),
2987 None => self.state.vars.remove(&k),
2988 };
2989 }
2990 }
2991}
2992
2993#[allow(clippy::too_many_lines)]
2994fn parse_segment(
2995 tokens: &[String],
2996 out: &mut CommandTargets,
2997 state: &mut LineState,
2998 inh: &Inherit,
2999 depth: usize,
3000) {
3001 let mut seg = SegmentTargets {
3002 text: quote_join(tokens),
3003 place: inh.place.clone(),
3004 sudo_root: inh.sudo_root,
3005 root_tool: inh.root_tool.clone(),
3006 ..SegmentTargets::default()
3007 };
3008 let mut segment_env: Vec<(String, Option<String>)> = Vec::new();
3009
3010 let mut i = 0;
3012 while let Some(tok) = tokens.get(i) {
3013 if let Some((k, v)) = is_assignment(tok) {
3014 segment_env.push((k, Some(v)));
3015 i += 1;
3016 continue;
3017 }
3018 let mut rec = Recurse {
3019 out,
3020 state,
3021 inh,
3022 depth,
3023 };
3024 match unwrap_one(tokens, i, &mut seg, &mut segment_env, &mut rec) {
3025 Some(Wrap::Skip(j)) => i = j.max(i + 1),
3026 Some(Wrap::Done) => return,
3027 None => break,
3028 }
3029 }
3030
3031 let Some(prog_tok) = tokens.get(i) else {
3032 for (k, v) in segment_env {
3034 if let Some(v) = v {
3035 state.vars.insert(k, vec![v]);
3036 }
3037 }
3038 return;
3039 };
3040 let prog = program_name(prog_tok);
3041 let args = &tokens[i + 1..];
3042 if prog == "for" {
3044 if let [var, kw, values @ ..] = args {
3045 if kw == "in" && !values.is_empty() {
3046 state.vars.insert(var.clone(), values.to_vec());
3047 }
3048 }
3049 return;
3050 }
3051 if matches!(prog, "cd" | "pushd") {
3052 if let Some(d) = args
3053 .iter()
3054 .find(|a| !a.starts_with('-') && !a.starts_with('+'))
3055 {
3056 state.cwd = match state.cwd.take() {
3057 Some(c) if !d.starts_with('/') && !d.starts_with('~') => {
3058 (c.len() + d.len() < MAX_TARGET_DIR_LEN)
3060 .then(|| crate::parser::normalize_path(&format!("{c}/{d}")))
3061 }
3062 _ => Some(crate::parser::normalize_path(d)),
3063 };
3064 }
3065 }
3066
3067 match prog {
3071 "export" | "declare" | "typeset" | "readonly" | "local" => {
3072 for t in args {
3073 if let Some((k, v)) = is_assignment(t) {
3074 state.env.push((k, Some(v)));
3075 }
3076 }
3077 return;
3078 }
3079 "unset" => {
3080 for t in args.iter().filter(|t| !t.starts_with('-')) {
3081 state.env.push((t.clone(), None));
3082 }
3083 return;
3084 }
3085 _ => {}
3086 }
3087
3088 seg.env.clone_from(&state.env);
3089 seg.env.extend(inh.env.iter().cloned());
3090 seg.env.extend(segment_env.iter().cloned());
3091 seg.kubeconfig = seg.line_var("KUBECONFIG").flatten();
3092 seg.k8s_namespace.clone_from(&state.k8s_namespace);
3093 seg.tf_workspace.clone_from(&state.tf_workspace);
3094 if !state.tf_switch_certain {
3095 seg.tf_fallbacks.clone_from(&state.tf_fallbacks);
3096 }
3097 seg.gcp_project.clone_from(&state.gcp_project);
3098 seg.azure_subscription.clone_from(&state.azure_subscription);
3099 seg.git_branch_switch.clone_from(&state.git_branch);
3100 if seg.git_branch_switch.is_some() {
3101 seg.git_fallbacks.clone_from(&state.git_fallbacks);
3102 seg.git_fallbacks_always = !state.git_switch_certain;
3103 seg.git_switch_creates = state.git_switch_creates;
3104 }
3105 if seg.place == Place::Pod {
3106 seg.k8s_context.clone_from(&inh.k8s_context);
3107 seg.k8s_context_unknown = inh.k8s_unknown;
3108 seg.kubeconfig.clone_from(&inh.kubeconfig);
3109 seg.k8s_namespace.clone_from(&inh.k8s_namespace);
3110 seg.k8s_fallbacks.clone_from(&inh.k8s_fallbacks);
3111 seg.k8s_fallbacks_always = inh.k8s_fallbacks_always;
3112 }
3113
3114 match prog {
3115 "ansible" | "ansible-playbook" | "pdsh" | "pssh" | "parallel-ssh" | "clush" => {
3120 let value = |flags: &[&str]| -> Option<String> {
3121 args.iter().enumerate().find_map(|(k, a)| {
3122 if flags.contains(&a.as_str()) {
3123 return args.get(k + 1).cloned();
3124 }
3125 flags
3126 .iter()
3127 .find_map(|f| a.strip_prefix(&format!("{f}=")).map(str::to_string))
3128 })
3129 };
3130 let (hosts, payload) = match prog {
3131 "ansible" => {
3132 let module = value(&["-m", "--module-name"]);
3133 let shell_module = module.as_deref().is_none_or(|m| {
3134 matches!(
3135 m.rsplit('.').next().unwrap_or(m),
3136 "shell" | "command" | "raw"
3137 )
3138 });
3139 (
3140 args.iter().find(|a| !a.starts_with('-')).cloned(),
3141 value(&["-a", "--args"]).filter(|_| shell_module),
3142 )
3143 }
3144 "ansible-playbook" => (value(&["-i", "--inventory", "-l", "--limit"]), None),
3145 _ => {
3146 const VAL: &[&str] = &[
3147 "-h", "-H", "-l", "-p", "-t", "-o", "-e", "-x", "-X", "-O", "-w", "-R",
3148 "-f", "-u", "-g", "-L",
3149 ];
3150 let mut k = 0;
3151 while k < args.len() && args[k].starts_with('-') {
3152 k += if VAL.contains(&args[k].as_str()) {
3153 2
3154 } else {
3155 1
3156 };
3157 }
3158 (
3159 value(&["-w", "-H", "-h", "-g"]),
3160 (k < args.len()).then(|| args[k..].join(" ")),
3161 )
3162 }
3163 };
3164 let become_root = prog.starts_with("ansible")
3165 && args.iter().any(|a| matches!(a.as_str(), "-b" | "--become"))
3166 && value(&["--become-user"]).is_none_or(|u| is_root_user(&u));
3167 let host = hosts.unwrap_or_else(|| "*".to_string());
3168 seg.place = Place::Host(host.clone());
3169 seg.env.clear();
3170 if become_root {
3171 seg.sudo_root = true;
3172 seg.root_tool = Some(format!("{prog} --become"));
3173 }
3174 out.segments.push(seg);
3175 if let Some(text) = payload {
3176 let inh = Inherit {
3177 place: Place::Host(host),
3178 sudo_root: become_root,
3179 root_tool: become_root.then(|| format!("{prog} --become")),
3180 ..Inherit::default()
3181 };
3182 parse_into(&text, out, &mut LineState::default(), &inh, depth + 1);
3183 }
3184 return;
3185 }
3186 "ssh" => {
3189 let Some((host, at)) = ssh_host(args) else {
3190 return;
3191 };
3192 seg.place = Place::Host(host.clone());
3193 seg.env.clear();
3194 seg.git_branch_switch = None;
3195 seg.k8s_namespace = None;
3196 seg.tf_workspace = None;
3197 seg.gcp_project = None;
3198 seg.azure_subscription = None;
3199 seg.kubeconfig = None;
3200 seg.sudo_root = false;
3201 seg.root_tool = None;
3202 out.segments.push(seg);
3203 let mut payload = &args[at + 1..];
3204 if payload.first().is_some_and(|a| a == "--") {
3205 payload = &payload[1..];
3206 }
3207 if !payload.is_empty() {
3208 let text = payload.join(" ");
3209 let inh = Inherit {
3210 place: Place::Host(host),
3211 ..Inherit::default()
3212 };
3213 parse_into(&text, out, &mut LineState::default(), &inh, depth + 1);
3214 }
3215 return;
3216 }
3217 "heroku" | "fly" | "flyctl" | "render" => {
3221 let mut words: Vec<&str> = vec![prog];
3222 words.extend(args.iter().map(String::as_str));
3223 if let Some(r) = crate::parser::paas_remote_command(&words) {
3224 seg.place = Place::Host(r.target.clone());
3225 seg.env.clear();
3226 seg.git_branch_switch = None;
3227 seg.sudo_root = false;
3228 seg.root_tool = None;
3229 out.segments.push(seg);
3230 let inh = Inherit {
3231 place: Place::Host(r.target),
3232 ..Inherit::default()
3233 };
3234 parse_into(&r.command, out, &mut LineState::default(), &inh, depth + 1);
3235 return;
3236 }
3237 }
3238 "docker" | "podman" if args.first().is_some_and(|a| a == "exec") => {
3239 const VAL: &[&str] = &[
3240 "-e",
3241 "--env",
3242 "-u",
3243 "--user",
3244 "-w",
3245 "--workdir",
3246 "--env-file",
3247 "--detach-keys",
3248 ];
3249 let mut k = 1;
3250 while k < args.len() && args[k].starts_with('-') {
3251 k += if VAL.contains(&args[k].as_str()) {
3252 2
3253 } else {
3254 1
3255 };
3256 }
3257 seg.place = Place::Container;
3258 seg.env.clear();
3259 seg.git_branch_switch = None;
3260 out.segments.push(seg);
3261 if k + 1 < args.len() {
3262 let text = quote_join(&args[k + 1..]);
3263 let inh = Inherit {
3264 place: Place::Container,
3265 ..Inherit::default()
3266 };
3267 parse_into(&text, out, &mut LineState::default(), &inh, depth + 1);
3268 }
3269 return;
3270 }
3271 _ => {}
3272 }
3273
3274 if prog == "argocd"
3277 && args
3278 .iter()
3279 .any(|a| a == "--kube-context" || a.starts_with("--kube-context="))
3280 {
3281 seg.mentions_k8s = true;
3282 parse_k8s_args(args, &mut seg, state);
3283 }
3284 if K8S_PROGRAMS.contains(&prog) {
3285 seg.mentions_k8s = true;
3286 let end = args.iter().position(|a| a == "--").unwrap_or(args.len());
3288 let helm_ctx = (prog == "helm"
3291 && !args[..end]
3292 .iter()
3293 .any(|a| a == "--kube-context" || a.starts_with("--kube-context=")))
3294 .then(|| seg.line_var("HELM_KUBECONTEXT").flatten())
3295 .flatten();
3296 if let Some(c) = helm_ctx {
3297 let mut with_ctx = vec!["--kube-context".to_string(), c];
3298 with_ctx.extend(args[..end].iter().cloned());
3299 parse_k8s_args(&with_ctx, &mut seg, state);
3300 } else {
3301 parse_k8s_args(&args[..end], &mut seg, state);
3302 }
3303 let is_exec = args[..end]
3304 .iter()
3305 .filter(|a| !a.starts_with('-'))
3306 .any(|a| matches!(a.as_str(), "exec" | "debug" | "run" | "attach"));
3307 if is_exec && end + 1 < args.len() {
3308 let pod = Inherit {
3309 place: Place::Pod,
3310 sudo_root: false,
3311 root_tool: None,
3312 env: Vec::new(),
3313 k8s_context: seg.k8s_context.clone(),
3314 k8s_unknown: seg.k8s_context_unknown,
3315 kubeconfig: seg.kubeconfig.clone(),
3316 k8s_namespace: seg.k8s_namespace.clone(),
3317 k8s_fallbacks: seg.k8s_fallbacks.clone(),
3318 k8s_fallbacks_always: seg.k8s_fallbacks_always,
3319 };
3320 let text = quote_join(&args[end + 1..]);
3321 out.segments.push(seg);
3322 parse_into(&text, out, &mut LineState::default(), &pod, depth + 1);
3323 return;
3324 }
3325 } else if matches!(prog, "kubectx" | "kubens" | "kubie") {
3326 seg.switch_only = true;
3327 let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3328 if prog == "kubie" && pos.first().is_some_and(|v| *v == "exec") && pos.len() >= 4 {
3330 let ctx_name = pos[1].clone();
3331 let ns = pos[2].clone();
3332 let at = args
3333 .iter()
3334 .enumerate()
3335 .filter(|(_, a)| !a.starts_with('-'))
3336 .nth(3)
3337 .map_or(args.len(), |(k, _)| k);
3338 out.segments.push(seg);
3339 let mut st = LineState {
3340 k8s_context: Some(ctx_name),
3341 k8s_namespace: Some(ns),
3342 k8s_switch_certain: true,
3343 ..LineState::default()
3344 };
3345 parse_into("e_join(&args[at..]), out, &mut st, inh, depth + 1);
3346 return;
3347 }
3348 let (what, value) = match (prog, pos.as_slice()) {
3349 ("kubie", [verb, v, ..]) if *verb == "ctx" => ("ctx", Some(*v)),
3350 ("kubie", [verb, v, ..]) if *verb == "ns" => ("ns", Some(*v)),
3351 ("kubectx", [v, ..]) if v.contains('=') => ("", None),
3353 ("kubectx", [v, ..]) => ("ctx", Some(*v)),
3354 ("kubens", [v, ..]) => ("ns", Some(*v)),
3355 _ => ("", None),
3356 };
3357 if args.iter().any(|a| a == "-") && value.is_none() {
3358 if prog == "kubectx" {
3360 state.k8s_context = None;
3361 state.k8s_unknown = true;
3362 } else {
3363 state.k8s_namespace = None;
3364 }
3365 }
3366 match (what, value) {
3367 ("ctx", Some(v)) => {
3368 state.k8s_context = Some(v.clone());
3369 state.k8s_unknown = false;
3370 if let Some(ns) = flag_value(args, &["-n", "--namespace"]) {
3372 state.k8s_namespace = Some(ns);
3373 }
3374 }
3375 ("ns", Some(v)) => state.k8s_namespace = Some(v.clone()),
3376 _ => {}
3377 }
3378 } else if tokens[i..]
3379 .iter()
3380 .any(|t| K8S_PROGRAMS.contains(&program_name(t)))
3381 {
3382 seg.mentions_k8s = true;
3384 let mut scratch = LineState::default();
3385 parse_k8s_args(args, &mut seg, &mut scratch);
3386 if seg.k8s_context.is_none() && !seg.k8s_context_unknown {
3387 seg.k8s_context.clone_from(&state.k8s_context);
3388 seg.k8s_context_unknown = state.k8s_unknown;
3389 seg.k8s_fallbacks.clone_from(&state.k8s_fallbacks);
3390 seg.k8s_fallbacks_always = !state.k8s_switch_certain;
3391 }
3392 }
3393
3394 seg.cluster = cluster_target(prog, args);
3395 let run_dir = seg.chdir.as_deref().map(|d| match state.cwd.as_ref() {
3397 Some(c) if !d.starts_with('/') && !d.starts_with('~') => {
3398 crate::parser::normalize_path(&format!("{c}/{d}"))
3399 }
3400 _ => crate::parser::normalize_path(d),
3401 });
3402 let line_dir = run_dir.or_else(|| state.cwd.clone());
3403 match prog {
3404 "git" => {
3405 parse_git(args, &mut seg, state);
3406 let dash_c = args
3407 .iter()
3408 .take_while(|a| a.starts_with('-'))
3409 .position(|a| a == "-C")
3410 .and_then(|p| args.get(p + 1));
3411 seg.git_dir = match (dash_c, line_dir.as_ref()) {
3412 (Some(d), Some(c)) if !d.starts_with('/') && !d.starts_with('~') => {
3413 Some(crate::parser::normalize_path(&format!("{c}/{d}")))
3414 }
3415 (Some(d), _) => Some(d.clone()),
3416 (None, c) => c.cloned(),
3417 };
3418 }
3419 "aws" => {
3420 if let Some(v) = flag_value(args, &["--profile"]) {
3421 seg.aws_profile = Some(v);
3422 }
3423 }
3424 "gcloud" => {
3425 let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3426 if let Some(v) = flag_value(args, &["--project"]) {
3427 seg.gcp_project = Some(v);
3428 } else if let Some(w) = pos.windows(4).find(|w| {
3429 w[0] == "config" && w[1] == "set" && (w[2] == "project" || w[2] == "core/project")
3430 }) {
3431 state.gcp_project = Some(w[3].clone());
3432 seg.switch_only = true;
3433 } else if let Some(w) = pos.windows(3).find(|w| w[0] == "projects") {
3434 if !matches!(w[1].as_str(), "list" | "create") {
3436 seg.gcp_project = Some(w[2].clone());
3437 }
3438 }
3439 }
3440 "az" => {
3441 let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3442 if pos.len() >= 2 && pos[0] == "account" && pos[1] == "set" {
3443 if let Some(v) = flag_value(args, &["--subscription", "-s", "--name", "-n"]) {
3444 state.azure_subscription = Some(v);
3445 seg.switch_only = true;
3446 }
3447 } else if let Some(v) = flag_value(args, &["--subscription"]) {
3448 seg.azure_subscription = Some(v);
3449 }
3450 }
3451 "terraform" | "tofu" | "terragrunt" => {
3452 seg.terraform = true;
3453 seg.tf_dir.clone_from(&line_dir);
3454 let tg_dir = args
3457 .iter()
3458 .position(|a| matches!(a.as_str(), "--terragrunt-working-dir" | "--working-dir"))
3459 .and_then(|k| args.get(k + 1))
3460 .map(String::as_str);
3461 if let Some(d) = args
3462 .iter()
3463 .find_map(|a| {
3464 a.strip_prefix("-chdir=")
3465 .or_else(|| a.strip_prefix("--chdir="))
3466 .or_else(|| a.strip_prefix("--terragrunt-working-dir="))
3467 .or_else(|| a.strip_prefix("--working-dir="))
3468 })
3469 .or(tg_dir)
3470 {
3471 if d.contains(['$', '`']) {
3473 let values = expand_line_value(d, state);
3474 seg.tf_dir_unknown = values.is_empty();
3475 seg.tf_dir_hints.extend(values);
3476 }
3477 seg.tf_dir = Some(match line_dir {
3478 Some(ref c) if !d.starts_with('/') && !d.starts_with('~') => {
3479 crate::parser::normalize_path(&format!("{c}/{d}"))
3480 }
3481 _ => crate::parser::normalize_path(d),
3482 });
3483 seg.tf_dir_hints.extend(seg.tf_dir.clone());
3484 }
3485 let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3486 if let [ws, verb, name, ..] = pos.as_slice() {
3487 if *ws == "workspace" && matches!(verb.as_str(), "select" | "new") {
3488 state.tf_workspace = Some((*name).clone());
3489 seg.switch_only = true;
3490 }
3491 }
3492 seg.tf_dir_hints.extend(line_dir.clone());
3493 let mut k = 0;
3494 while let Some(a) = args.get(k) {
3495 if let Some(v) = a
3496 .strip_prefix("-chdir=")
3497 .or_else(|| a.strip_prefix("--chdir="))
3498 .or_else(|| a.strip_prefix("-var-file="))
3499 .or_else(|| a.strip_prefix("--var-file="))
3500 {
3501 seg.tf_dir_hints.push(crate::parser::normalize_path(v));
3502 } else if matches!(a.as_str(), "-var-file" | "--var-file") {
3503 seg.tf_dir_hints.extend(args.get(k + 1).cloned());
3504 k += 1;
3505 }
3506 k += 1;
3507 }
3508 }
3509 "sh" | "bash" | "zsh" | "dash" | "ksh" | "mksh" | "yash" | "fish" | "ash" | "nu"
3510 | "nushell" | "elvish" | "xonsh" | "osh" | "ysh" | "pwsh" | "powershell" => {
3511 if let Some(pos) = args.iter().position(|a| {
3512 a.len() > 1
3513 && a.starts_with('-')
3514 && !a.starts_with("--")
3515 && a[1..].chars().all(|c| c.is_ascii_alphabetic())
3516 && (a.contains('c') || a.eq_ignore_ascii_case("-command"))
3517 }) {
3518 if let Some(script) = args.get(pos + 1) {
3519 Recurse {
3520 out,
3521 state,
3522 inh,
3523 depth,
3524 }
3525 .recurse(script, &seg, &segment_env);
3526 return;
3527 }
3528 }
3529 }
3530 "eval" => {
3531 let mut inh = inh.clone();
3532 inh.sudo_root = seg.sudo_root;
3533 inh.root_tool.clone_from(&seg.root_tool);
3534 inh.env.extend(segment_env);
3535 parse_into(&args.join(" "), out, state, &inh, depth + 1);
3536 return;
3537 }
3538 _ => {}
3539 }
3540 out.segments.push(seg);
3541}
3542
3543fn cluster_target(prog: &str, args: &[String]) -> Option<String> {
3548 let pos: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3549 let named = || flag_value(args, &["--name", "-n", "--cluster"]);
3550 match (prog, pos.as_slice()) {
3551 ("eksctl", [verb, kind, rest @ ..])
3552 if matches!(verb.as_str(), "delete" | "upgrade")
3553 && matches!(kind.as_str(), "cluster" | "clusters") =>
3554 {
3555 named().or_else(|| rest.first().map(|s| (*s).clone()))
3556 }
3557 ("aws", [svc, verb, ..])
3558 if svc.as_str() == "eks"
3559 && matches!(verb.as_str(), "delete-cluster" | "update-cluster-version") =>
3560 {
3561 flag_value(args, &["--name"])
3562 }
3563 ("gcloud", [.., c, cl, verb, name] | [.., c, cl, verb, name, _])
3564 if c.as_str() == "container"
3565 && cl.as_str() == "clusters"
3566 && matches!(verb.as_str(), "delete" | "upgrade" | "resize") =>
3567 {
3568 Some((*name).clone())
3569 }
3570 ("az", [svc, verb, ..])
3571 if svc.as_str() == "aks" && matches!(verb.as_str(), "delete" | "stop" | "upgrade") =>
3572 {
3573 named()
3574 }
3575 ("argocd", _) => flag_value(args, &["--server"]),
3577 ("doctl", [k, c, verb, name, ..])
3578 if matches!(k.as_str(), "kubernetes" | "k8s" | "k")
3579 && c.as_str() == "cluster"
3580 && matches!(verb.as_str(), "delete" | "upgrade") =>
3581 {
3582 Some((*name).clone())
3583 }
3584 _ => None,
3585 }
3586}
3587
3588fn flag_value(args: &[String], flags: &[&str]) -> Option<String> {
3590 let mut found = None;
3591 let mut i = 0;
3592 while i < args.len() {
3593 let a = args[i].as_str();
3594 if flags.contains(&a) {
3595 if let Some(v) = args.get(i + 1) {
3596 found = Some(v.clone());
3597 i += 1;
3598 }
3599 } else if let Some((f, v)) = a.split_once('=') {
3600 if flags.contains(&f) {
3601 found = Some(v.to_string());
3602 }
3603 }
3604 i += 1;
3605 }
3606 found
3607}
3608
3609fn ssh_host(args: &[String]) -> Option<(String, usize)> {
3612 const VAL: &[&str] = &[
3613 "-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p",
3614 "-Q", "-R", "-S", "-W", "-w", "-B",
3615 ];
3616 let mut i = 0;
3617 while i < args.len() && args[i].starts_with('-') {
3618 i += if VAL.contains(&args[i].as_str()) {
3619 2
3620 } else {
3621 1
3622 };
3623 }
3624 let host = args.get(i)?;
3625 let host = host.rsplit_once('@').map_or(host.as_str(), |(_, h)| h);
3626 (!host.is_empty()).then(|| (host.to_string(), i))
3627}
3628
3629fn parse_k8s_args(args: &[String], seg: &mut SegmentTargets, state: &mut LineState) {
3630 let positional: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
3634 if let [cfg, verb, rest @ ..] = positional.as_slice() {
3635 if *cfg == "config" && matches!(verb.as_str(), "use-context" | "use") {
3636 if let Some(v) = rest.first() {
3637 state.k8s_context = Some((*v).clone());
3638 state.k8s_unknown = false;
3639 }
3640 seg.switch_only = true;
3641 return;
3642 }
3643 if *cfg == "config"
3644 && verb.as_str() == "set-context"
3645 && args.iter().any(|a| a == "--current")
3646 {
3647 if let Some(ns) = flag_value(args, &["--namespace", "-n"]) {
3648 state.k8s_namespace = Some(ns);
3649 }
3650 seg.switch_only = true;
3651 return;
3652 }
3653 }
3654 let mut explicit_ctx = None;
3655 let mut i = 0;
3656 while i < args.len() {
3657 let a = args[i].as_str();
3658 let next = args.get(i + 1).cloned();
3659 if a == "--context" || a == "--kube-context" || a == "--kubecontext" {
3660 if let Some(v) = next {
3661 explicit_ctx = Some(v);
3662 i += 1;
3663 }
3664 } else if let Some(v) = a
3665 .strip_prefix("--context=")
3666 .or_else(|| a.strip_prefix("--kube-context="))
3667 .or_else(|| a.strip_prefix("--kubecontext="))
3668 {
3669 explicit_ctx = Some(v.to_string());
3670 } else if a == "--kubeconfig" {
3671 if let Some(v) = next {
3672 seg.kubeconfig = Some(v);
3673 i += 1;
3674 }
3675 } else if let Some(v) = a.strip_prefix("--kubeconfig=") {
3676 seg.kubeconfig = Some(v.to_string());
3677 } else if a == "-n" || a == "--namespace" {
3678 if let Some(v) = next {
3679 seg.k8s_namespace = Some(v);
3680 i += 1;
3681 }
3682 } else if let Some(v) = a
3683 .strip_prefix("--namespace=")
3684 .or_else(|| a.strip_prefix("-n="))
3685 {
3686 seg.k8s_namespace = Some(v.to_string());
3687 }
3688 i += 1;
3689 }
3690 if let [verb, kind, name, ..] = positional.as_slice() {
3692 if *verb == "delete" && matches!(kind.as_str(), "ns" | "namespace" | "namespaces") {
3693 seg.k8s_namespace = Some((*name).clone());
3694 }
3695 }
3696 if let Some(ctx) = explicit_ctx {
3697 let mut values = expand_line_value(&ctx, state);
3701 let placeholder = values.iter().any(|v| !is_literal_name(v)) || !is_literal_name(&ctx);
3702 values.retain(|v| is_literal_name(v));
3703 if placeholder && values.is_empty() && state.lists_contexts {
3704 seg.k8s_all_contexts = true;
3705 }
3706 match values.as_slice() {
3707 [] => {
3708 seg.k8s_context = None;
3709 seg.k8s_context_unknown = true;
3710 }
3711 [one] => {
3712 seg.k8s_context = Some(one.clone());
3713 seg.k8s_context_unknown = false;
3714 }
3715 [first, rest @ ..] => {
3716 seg.k8s_context = Some(first.clone());
3717 seg.k8s_context_unknown = false;
3718 seg.k8s_fallbacks = rest.iter().cloned().map(CtxAlt::Named).collect();
3719 seg.k8s_fallbacks_always = true;
3720 seg.k8s_context_list = true;
3721 }
3722 }
3723 } else if seg.place != Place::Pod {
3724 seg.k8s_context.clone_from(&state.k8s_context);
3725 seg.k8s_context_unknown = state.k8s_unknown;
3726 if !state.k8s_fallbacks.is_empty() {
3727 seg.k8s_fallbacks.clone_from(&state.k8s_fallbacks);
3728 seg.k8s_fallbacks_always = !state.k8s_switch_certain;
3729 }
3730 }
3731}
3732
3733fn expand_line_value(word: &str, state: &LineState) -> Vec<String> {
3737 let w = word.trim_matches('"');
3738 if let Some(inner) = w.strip_prefix("$(").and_then(|r| r.strip_suffix(')')) {
3739 let parts: Vec<&str> = inner.split_whitespace().collect();
3740 return match parts.as_slice() {
3741 ["echo" | "printf", x] => vec![(*x).trim_matches(['\'', '"']).to_string()],
3742 _ => Vec::new(),
3743 };
3744 }
3745 if let Some((name, default)) = w
3748 .strip_prefix("${")
3749 .and_then(|r| r.strip_suffix('}'))
3750 .and_then(|r| {
3751 r.split_once(":-")
3752 .or_else(|| r.split_once(":="))
3753 .or_else(|| r.split_once('-'))
3754 .or_else(|| r.split_once('='))
3755 })
3756 {
3757 if let Some(v) = state.vars.get(name) {
3758 return v.clone();
3759 }
3760 if let Some((_, Some(v))) = state.env.iter().rev().find(|(k, _)| k == name) {
3761 return vec![v.clone()];
3762 }
3763 return if default.contains(['$', '`']) {
3764 Vec::new()
3765 } else {
3766 vec![default.to_string()]
3767 };
3768 }
3769 if let Some(name) = w
3770 .strip_prefix("${")
3771 .and_then(|r| r.strip_suffix('}'))
3772 .or_else(|| w.strip_prefix('$'))
3773 {
3774 if let Some(v) = state.vars.get(name) {
3775 return v.clone();
3776 }
3777 if let Some((_, Some(v))) = state.env.iter().rev().find(|(k, _)| k == name) {
3778 return vec![v.clone()];
3779 }
3780 return Vec::new();
3781 }
3782 if w.contains('$') || w.contains('`') {
3783 return Vec::new();
3784 }
3785 vec![w.to_string()]
3786}
3787
3788fn branch_from_ref(r: &str) -> Option<String> {
3791 if r.is_empty() || r.starts_with("refs/tags/") {
3792 return None;
3793 }
3794 if let Some(b) = r.strip_prefix("refs/heads/") {
3795 return Some(b.to_string());
3796 }
3797 if r.starts_with("refs/") {
3798 return None;
3799 }
3800 Some(r.to_string())
3801}
3802
3803fn parse_git(args: &[String], seg: &mut SegmentTargets, state: &mut LineState) {
3804 seg.git = true;
3805 let mut i = 0;
3806 while let Some(a) = args.get(i) {
3808 if !a.starts_with('-') {
3809 break;
3810 }
3811 if matches!(
3812 a.as_str(),
3813 "-C" | "-c" | "--git-dir" | "--work-tree" | "--namespace" | "--config-env"
3814 ) {
3815 i += 2;
3816 } else {
3817 i += 1;
3818 }
3819 }
3820 let Some(verb) = args.get(i) else {
3821 seg.git_uses_current = true;
3822 return;
3823 };
3824 let rest = &args[i + 1..];
3825 match verb.as_str() {
3826 "push" => parse_git_push(rest, seg, state),
3827 "branch" => parse_git_branch(rest, seg),
3828 "checkout" | "switch" => parse_git_switch(rest, seg, state),
3829 "reset" if reset_moves_branch(rest) => {
3831 seg.git_uses_current = true;
3832 seg.git_reset_to = rest.iter().find(|a| !a.starts_with('-')).cloned();
3833 }
3834 "filter-branch" | "filter-repo" | "update-ref" => seg.git_uses_current = true,
3836 "rebase"
3840 if !rest.iter().any(|a| {
3841 matches!(
3842 a.as_str(),
3843 "--abort"
3844 | "--continue"
3845 | "--skip"
3846 | "--quit"
3847 | "--edit-todo"
3848 | "--show-current-patch"
3849 )
3850 }) =>
3851 {
3852 seg.git_uses_current = true;
3853 }
3854 _ => {}
3859 }
3860}
3861
3862fn reset_moves_branch(args: &[String]) -> bool {
3865 for a in args {
3866 if a == "--" {
3867 return false;
3868 }
3869 if a.starts_with('-') {
3870 continue;
3871 }
3872 return a != "HEAD" && a != "@";
3873 }
3874 false
3875}
3876
3877fn parse_git_switch(args: &[String], seg: &mut SegmentTargets, state: &mut LineState) {
3882 if args.iter().any(|a| a == "--") {
3883 return;
3884 }
3885 let mut i = 0;
3886 let mut target: Option<&String> = None;
3887 let mut reset = false;
3888 while i < args.len() {
3889 let a = &args[i];
3890 if matches!(a.as_str(), "-b" | "-B" | "-c" | "-C" | "--orphan") {
3891 reset = matches!(a.as_str(), "-B" | "-C");
3892 target = args.get(i + 1);
3893 break;
3894 }
3895 if !a.starts_with('-') {
3896 target = Some(a);
3897 break;
3898 }
3899 i += 1;
3900 }
3901 let creates = args
3902 .iter()
3903 .any(|a| matches!(a.as_str(), "-b" | "-B" | "-c" | "-C" | "--orphan"));
3904 if let Some(t) = target {
3905 if t != "-" && !t.starts_with('.') && !t.starts_with('/') {
3906 if reset && !seg.git_targets.contains(t) {
3907 seg.git_targets.push(t.clone());
3908 }
3909 state.git_branch = Some(t.clone());
3910 state.git_switch_creates = creates;
3911 }
3912 }
3913}
3914
3915fn parse_git_push(args: &[String], seg: &mut SegmentTargets, state: &LineState) {
3916 let mut positionals: Vec<&str> = Vec::new();
3917 let mut delete = false;
3918 let mut i = 0;
3919 while i < args.len() {
3920 let a = args[i].as_str();
3921 if a == "--" {
3922 positionals.extend(args[i + 1..].iter().map(String::as_str));
3923 break;
3924 }
3925 if a.starts_with("--") {
3926 match a {
3927 "--all" | "--branches" | "--mirror" => seg.git_push_all = true,
3928 "--delete" => delete = true,
3929 _ if a.starts_with("--force-with-lease") || a == "--force-if-includes" => {
3930 seg.git_force_lease = true;
3931 }
3932 "--push-option" | "--repo" | "--receive-pack" | "--exec" => i += 1,
3933 _ => {}
3934 }
3935 } else if a.starts_with('-') && a.len() > 1 {
3936 if a == "-o" {
3937 i += 1;
3938 } else if a[1..].contains('d') {
3939 delete = true;
3940 }
3941 } else {
3942 positionals.push(a);
3943 }
3944 i += 1;
3945 }
3946
3947 if args.iter().any(|a| {
3949 a == "--dry-run" || (a.starts_with('-') && !a.starts_with("--") && a[1..].contains('n'))
3950 }) {
3951 seg.git_force_lease = false;
3952 return;
3953 }
3954 let refspecs = positionals.get(1..).unwrap_or(&[]);
3955 if refspecs.is_empty() {
3956 if !seg.git_push_all {
3957 seg.git_uses_current = true;
3959 }
3960 return;
3961 }
3962 for spec in refspecs {
3963 let spec = spec.strip_prefix('+').unwrap_or(spec);
3964 let dst = if delete {
3965 spec
3966 } else {
3967 refspec_colon(spec).map_or(spec, |at| &spec[at + 1..])
3968 };
3969 if dst == "HEAD" || dst == "@" || names_current_branch(dst) {
3970 seg.git_uses_current = true;
3971 continue;
3972 }
3973 if dst.contains(['$', '`']) || dst.contains("{}") {
3974 let mut values = if dst.contains("{}") {
3977 Vec::new()
3978 } else {
3979 expand_line_value(dst, state)
3980 };
3981 let before = values.len();
3983 values.retain(|v| !names_current_branch(v));
3984 let current = values.len() < before;
3985 if current {
3986 seg.git_uses_current = true;
3987 }
3988 values.retain(|v| !v.contains(['$', '`']) && !v.contains("{}"));
3989 if values.is_empty() && !current {
3990 seg.git_target_unknown = true;
3991 }
3992 for v in values {
3993 if v == "HEAD" || v == "@" {
3994 seg.git_uses_current = true;
3995 } else if let Some(b) = branch_from_ref(&v) {
3996 if !seg.git_targets.contains(&b) {
3997 seg.git_targets.push(b);
3998 }
3999 }
4000 }
4001 continue;
4002 }
4003 if let Some(b) = branch_from_ref(dst) {
4004 if !seg.git_targets.contains(&b) {
4005 seg.git_targets.push(b);
4006 }
4007 }
4008 }
4009}
4010
4011fn refspec_colon(spec: &str) -> Option<usize> {
4014 let mut depth = 0usize;
4015 let mut at = None;
4016 let bytes = spec.as_bytes();
4017 for (i, b) in bytes.iter().enumerate() {
4018 match b {
4019 b'{' | b'(' if i > 0 && bytes[i - 1] == b'$' => depth += 1,
4020 b'}' | b')' => depth = depth.saturating_sub(1),
4021 b':' if depth == 0 => at = Some(i),
4022 _ => {}
4023 }
4024 }
4025 at
4026}
4027
4028fn names_current_branch(dst: &str) -> bool {
4033 let d = dst.trim_matches('"');
4034 let Some(inner) = d
4035 .strip_prefix("$(")
4036 .and_then(|r| r.strip_suffix(')'))
4037 .or_else(|| d.strip_prefix('`').and_then(|r| r.strip_suffix('`')))
4038 else {
4039 return false;
4040 };
4041 let words: Vec<&str> = inner.split_whitespace().collect();
4042 let words = match words.as_slice() {
4043 ["command", rest @ ..] => rest,
4044 w => w,
4045 };
4046 matches!(
4047 words,
4048 ["git_current_branch" | "current_branch"]
4051 | ["git", "branch", "--show-current"]
4052 | ["git", "rev-parse", "--abbrev-ref", "HEAD" | "@"]
4053 | ["git", "symbolic-ref", "--short", "HEAD"]
4054 | ["git", "symbolic-ref", "--short", "-q", "HEAD"]
4055 | ["git", "name-rev", "--name-only", "HEAD"]
4056 )
4057}
4058
4059fn parse_git_branch(args: &[String], seg: &mut SegmentTargets) {
4060 let mut positionals: Vec<&str> = Vec::new();
4061 let mut delete = false;
4062 let mut mv = false;
4063 let mut force = false;
4064 let mut i = 0;
4065 while i < args.len() {
4066 let a = args[i].as_str();
4067 if a.starts_with("--") {
4068 match a {
4069 "--delete" => delete = true,
4070 "--move" | "--copy" => mv = true,
4071 "--force" => force = true,
4072 "--set-upstream-to" | "--contains" | "--no-contains" | "--merged"
4073 | "--no-merged" | "--points-at" | "--format" | "--sort" => i += 1,
4074 _ => {}
4075 }
4076 } else if a.starts_with('-') && a.len() > 1 {
4077 let flags = &a[1..];
4078 if flags.contains('d') || flags.contains('D') {
4079 delete = true;
4080 }
4081 if flags.contains('m')
4082 || flags.contains('M')
4083 || flags.contains('c')
4084 || flags.contains('C')
4085 {
4086 mv = true;
4087 }
4088 if flags.contains('f')
4089 || flags.contains('D')
4090 || flags.contains('M')
4091 || flags.contains('C')
4092 {
4093 force = true;
4094 }
4095 if a == "-u" {
4096 i += 1;
4097 }
4098 } else {
4099 positionals.push(a);
4100 }
4101 i += 1;
4102 }
4103
4104 let mut push = |name: &str| {
4105 if let Some(b) = branch_from_ref(name) {
4106 if !seg.git_targets.contains(&b) {
4107 seg.git_targets.push(b);
4108 }
4109 }
4110 };
4111 if delete {
4112 for p in &positionals {
4113 push(p);
4114 }
4115 } else if mv {
4116 let single = positionals.len() == 1;
4118 for p in &positionals {
4119 push(p);
4120 }
4121 if single {
4122 seg.git_uses_current = true;
4123 }
4124 } else if force {
4125 if let Some(first) = positionals.first() {
4127 push(first);
4128 }
4129 }
4130 }
4133
4134#[must_use]
4141#[allow(clippy::too_many_lines)]
4142pub fn command_target_dirs(command: &str) -> Vec<PathBuf> {
4143 let mut out: Vec<PathBuf> = Vec::new();
4144 let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
4145 let mut cwd: Option<PathBuf> = None;
4146 let push =
4149 |out: &mut Vec<PathBuf>, seen: &mut std::collections::HashSet<PathBuf>, p: PathBuf| {
4150 if out.len() < MAX_TARGET_DIRS && seen.insert(p.clone()) {
4151 out.push(p);
4152 }
4153 };
4154 let rel = |cwd: &Option<PathBuf>, d: &str| -> PathBuf {
4155 let p = PathBuf::from(d);
4156 let joined = if p.is_absolute() || d.starts_with('~') || d.starts_with('/') {
4161 p
4162 } else {
4163 cwd.as_ref().map_or_else(
4164 || p.clone(),
4165 |c| PathBuf::from(format!("{}/{d}", c.display())),
4166 )
4167 };
4168 let n = PathBuf::from(crate::parser::normalize_path(&joined.display().to_string()));
4170 if n.as_os_str().len() > MAX_TARGET_DIR_LEN {
4171 PathBuf::new()
4172 } else {
4173 n
4174 }
4175 };
4176 for seg in tokenize_segments(command) {
4177 let mut i = 0;
4178 while let Some(t) = seg.get(i) {
4179 if let Some((k, v)) = is_assignment(t) {
4180 if k == "GIT_DIR" || k == "GIT_WORK_TREE" {
4181 let p = rel(&cwd, &v);
4182 push(&mut out, &mut seen, p);
4183 }
4184 i += 1;
4185 } else if matches!(
4186 program_name(t),
4187 "sudo" | "env" | "command" | "builtin" | "time" | "nohup"
4188 ) {
4189 let is_env = program_name(t) == "env";
4190 i += 1;
4191 while let Some(a) = seg.get(i).filter(|a| a.starts_with('-')) {
4192 let dir = if is_env && (a == "-C" || a == "--chdir") {
4194 i += 1;
4195 seg.get(i).cloned()
4196 } else if is_env {
4197 a.strip_prefix("--chdir=").map(str::to_string)
4198 } else {
4199 None
4200 };
4201 if let Some(d) = dir {
4202 let p = rel(&cwd, &d);
4203 push(&mut out, &mut seen, p);
4204 }
4205 i += 1;
4206 }
4207 } else {
4208 break;
4209 }
4210 }
4211 let Some(prog_tok) = seg.get(i) else {
4212 continue;
4213 };
4214 if prog_tok.starts_with('/') {
4216 if let Some(parent) = std::path::Path::new(prog_tok).parent() {
4217 push(&mut out, &mut seen, parent.to_path_buf());
4218 }
4219 }
4220 let prog = program_name(prog_tok);
4221 let args = &seg[i + 1..];
4222 match prog {
4223 "cd" | "pushd" => {
4224 if let Some(d) = args
4225 .iter()
4226 .find(|a| !a.starts_with('-') && !a.starts_with('+'))
4227 {
4228 let p = rel(&cwd, d);
4229 if p.as_os_str().is_empty() {
4230 cwd = None;
4231 } else {
4232 push(&mut out, &mut seen, p.clone());
4233 cwd = Some(p);
4234 }
4235 }
4236 }
4237 "git" => {
4238 let mut k = 0;
4239 while let Some(a) = args.get(k) {
4240 if !a.starts_with('-') {
4241 break;
4242 }
4243 let value = match a.as_str() {
4244 "-C" | "--git-dir" | "--work-tree" => {
4245 k += 1;
4246 args.get(k).cloned()
4247 }
4248 _ => a
4249 .strip_prefix("--git-dir=")
4250 .or_else(|| a.strip_prefix("--work-tree="))
4251 .map(str::to_string),
4252 };
4253 if let Some(v) = value {
4254 let p = rel(&cwd, &v);
4255 push(&mut out, &mut seen, p);
4256 }
4257 if a == "-c" || a == "--namespace" || a == "--config-env" {
4258 k += 1;
4259 }
4260 k += 1;
4261 }
4262 }
4263 "terraform" | "tofu" | "terragrunt" => {
4264 for a in args {
4265 if let Some(v) = a
4266 .strip_prefix("-chdir=")
4267 .or_else(|| a.strip_prefix("--chdir="))
4268 {
4269 let p = rel(&cwd, v);
4270 push(&mut out, &mut seen, p);
4271 }
4272 }
4273 }
4274 "make" | "gmake" => {
4275 let mut k = 0;
4276 while let Some(a) = args.get(k) {
4277 let value = if a == "-C" || a == "--directory" {
4278 k += 1;
4279 args.get(k).cloned()
4280 } else {
4281 a.strip_prefix("--directory=").map(str::to_string)
4282 };
4283 if let Some(v) = value {
4284 let p = rel(&cwd, &v);
4285 push(&mut out, &mut seen, p);
4286 }
4287 k += 1;
4288 }
4289 }
4290 _ => {}
4291 }
4292 }
4293 out
4294}
4295
4296#[must_use]
4305pub fn command_work_dir(
4306 command: &str,
4307 cwd: &std::path::Path,
4308 home: Option<&std::path::Path>,
4309) -> Option<PathBuf> {
4310 let targets = parse_command_targets(command);
4311 let dir = targets
4312 .segments
4313 .iter()
4314 .filter(|s| s.place == Place::Local)
4315 .find_map(|s| s.git_dir.clone())
4316 .or_else(|| {
4317 command_target_dirs(command)
4318 .into_iter()
4319 .find(|d| !d.as_os_str().is_empty())
4320 .map(|d| d.display().to_string())
4321 })?;
4322 let rest = dir
4323 .strip_prefix("~/")
4324 .or_else(|| dir.strip_prefix("$HOME/"))
4325 .or_else(|| dir.strip_prefix("${HOME}/"));
4326 let path = match (rest, home) {
4327 (Some(rest), Some(h)) => h.join(rest),
4328 _ if dir == "~" => home?.to_path_buf(),
4329 _ => PathBuf::from(&dir),
4330 };
4331 let text = path.to_string_lossy();
4334 if text.is_empty() || text.starts_with('~') || text.contains(['$', '`']) {
4335 return None;
4336 }
4337 let abs = if path.is_absolute() {
4338 path
4339 } else {
4340 cwd.join(path)
4341 };
4342 Some(PathBuf::from(crate::parser::normalize_path(
4343 &abs.display().to_string(),
4344 )))
4345}
4346
4347const MAX_TARGET_DIRS: usize = 64;
4349
4350const MAX_TARGET_DIR_LEN: usize = 4096;
4352
4353fn tokenize_segments(command: &str) -> Vec<Vec<String>> {
4359 tokenize_segments_with_ops(command)
4360 .into_iter()
4361 .map(|(s, _)| s)
4362 .collect()
4363}
4364
4365fn tokenize_segments_with_ops(command: &str) -> Vec<(Vec<String>, String)> {
4369 tokenize_segments_at(command, 0)
4370}
4371
4372const MAX_TOKENIZE_DEPTH: usize = 32;
4378
4379#[allow(clippy::too_many_lines)]
4381fn tokenize_segments_at(command: &str, level: usize) -> Vec<(Vec<String>, String)> {
4382 let nested = level < MAX_TOKENIZE_DEPTH;
4383 let mut segments: Vec<(Vec<String>, String)> = Vec::new();
4384 let mut current: Vec<String> = Vec::new();
4385 let mut tok = String::new();
4386 let mut in_tok = false;
4387 let mut chars = command.chars().peekable();
4388
4389 let flush_tok = |tok: &mut String, in_tok: &mut bool, current: &mut Vec<String>| {
4390 if *in_tok {
4391 current.push(std::mem::take(tok));
4392 *in_tok = false;
4393 }
4394 };
4395
4396 while let Some(c) = chars.next() {
4397 match c {
4398 '\'' => {
4399 in_tok = true;
4400 for n in chars.by_ref() {
4401 if n == '\'' {
4402 break;
4403 }
4404 tok.push(n);
4405 }
4406 }
4407 '"' => {
4408 in_tok = true;
4409 while let Some(n) = chars.next() {
4410 match n {
4411 '"' => break,
4412 '\\' => {
4413 if let Some(&esc) = chars.peek() {
4414 if matches!(esc, '"' | '\\' | '$' | '`') {
4415 tok.push(esc);
4416 chars.next();
4417 continue;
4418 }
4419 }
4420 tok.push('\\');
4421 }
4422 _ => tok.push(n),
4423 }
4424 }
4425 }
4426 '\\' => {
4427 in_tok = true;
4428 if let Some(n) = chars.next() {
4429 if n != '\n' {
4430 tok.push(n);
4431 }
4432 }
4433 }
4434 '#' if !in_tok && crate::parser::hash_comments() => {
4435 for n in chars.by_ref() {
4436 if n == '\n' {
4437 break;
4438 }
4439 }
4440 flush_tok(&mut tok, &mut in_tok, &mut current);
4441 segments.push((std::mem::take(&mut current), "\n".to_string()));
4442 }
4443 '$' if chars.peek() == Some(&'(') => {
4448 chars.next();
4449 let mut body = String::new();
4450 let mut depth = 1usize;
4451 let mut quote: Option<char> = None;
4452 for n in chars.by_ref() {
4453 match (quote, n) {
4454 (Some(q), _) if n == q => quote = None,
4455 (None, '\'' | '"') => quote = Some(n),
4456 (None, '(') => depth += 1,
4457 (None, ')') => {
4458 depth -= 1;
4459 if depth == 0 {
4460 break;
4461 }
4462 }
4463 _ => {}
4464 }
4465 body.push(n);
4466 }
4467 if nested && !body.starts_with('(') {
4468 segments.extend(tokenize_segments_at(&body, level + 1));
4469 }
4470 tok.push_str("$(");
4471 tok.push_str(body.trim());
4472 tok.push(')');
4473 in_tok = true;
4474 }
4475 '`' => {
4478 let mut body = String::new();
4479 while let Some(n) = chars.next() {
4480 match n {
4481 '`' => break,
4482 '\\' => {
4483 if let Some(e) = chars.next() {
4484 body.push(e);
4485 }
4486 }
4487 _ => body.push(n),
4488 }
4489 }
4490 if nested {
4491 segments.extend(tokenize_segments_at(&body, level + 1));
4492 }
4493 tok.push_str("$(");
4494 tok.push_str(body.trim());
4495 tok.push(')');
4496 in_tok = true;
4497 }
4498 '&' if (in_tok && tok.ends_with(['>', '<'])) || matches!(chars.peek(), Some('>')) => {
4501 in_tok = true;
4502 tok.push(c);
4503 }
4504 '|' if in_tok && tok.ends_with('>') => {
4505 tok.push(c);
4507 }
4508 ';' | '&' | '|' | '\n' | '(' | ')' => {
4509 flush_tok(&mut tok, &mut in_tok, &mut current);
4510 let mut op = c.to_string();
4511 if matches!(c, '&' | '|') && chars.peek() == Some(&c) {
4512 chars.next();
4513 op.push(c);
4514 }
4515 if !current.is_empty() {
4516 segments.push((std::mem::take(&mut current), op));
4517 } else if let Some(last) = segments.last_mut() {
4518 if last.1 == ")" {
4520 last.1 = op;
4521 }
4522 }
4523 }
4524 c if c.is_whitespace() => flush_tok(&mut tok, &mut in_tok, &mut current),
4525 _ => {
4526 in_tok = true;
4527 tok.push(c);
4528 }
4529 }
4530 }
4531 flush_tok(&mut tok, &mut in_tok, &mut current);
4532 if !current.is_empty() {
4533 segments.push((current, String::new()));
4534 }
4535 for (s, _) in &mut segments {
4536 drop_redirections(s);
4537 normalize_command_word(s);
4538 }
4539 segments.retain(|(s, _)| !s.is_empty());
4540 segments
4541}
4542
4543fn redirection_op_len(tok: &str) -> Option<usize> {
4546 let digits = tok.len() - tok.trim_start_matches(|c: char| c.is_ascii_digit()).len();
4547 let rest = &tok[digits..];
4548 let ops = [
4549 "&>>", "&>", ">>", ">&", ">|", "<<<", "<<-", "<<", "<&", "<>", ">", "<",
4550 ];
4551 let op = ops.iter().find(|o| rest.starts_with(**o))?;
4552 (!rest[op.len()..].starts_with('(')).then_some(digits + op.len())
4554}
4555
4556fn drop_redirections(tokens: &mut Vec<String>) {
4560 let mut out = Vec::with_capacity(tokens.len());
4561 let mut it = std::mem::take(tokens).into_iter();
4562 while let Some(t) = it.next() {
4563 match redirection_op_len(&t) {
4564 Some(n) if n == t.len() => {
4566 it.next();
4567 }
4568 Some(_) => {}
4569 None => out.push(t),
4570 }
4571 }
4572 *tokens = out;
4573}
4574
4575fn normalize_command_word(tokens: &mut Vec<String>) {
4578 let at = tokens
4580 .iter()
4581 .position(|t| {
4582 !matches!(
4583 t.as_str(),
4584 "if" | "then" | "else" | "elif" | "do" | "while" | "until" | "!" | "{" | "time"
4585 )
4586 })
4587 .unwrap_or(0);
4588 if let Some(first) = tokens.get_mut(at) {
4589 if first.len() > 1 && first.starts_with('{') && first != "{}" {
4590 first.remove(0);
4591 }
4592 if first.len() > 1
4593 && first.starts_with('=')
4594 && first[1..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '/')
4595 {
4596 first.remove(0);
4597 }
4598 }
4599 if tokens.last().is_some_and(|t| t == "}") {
4601 tokens.pop();
4602 }
4603}
4604
4605#[cfg(test)]
4606mod tests {
4607 use super::*;
4608 use crate::env::MockEnvironment;
4609 use std::collections::HashMap;
4610
4611 fn default_config() -> ContextConfig {
4612 ContextConfig::default()
4613 }
4614
4615 fn env_with_branch(branch: &str) -> MockEnvironment {
4616 let mut cmd_outputs = HashMap::new();
4617 cmd_outputs.insert("git rev-parse --abbrev-ref HEAD".into(), branch.into());
4618 MockEnvironment {
4619 command_outputs: cmd_outputs,
4620 cwd: "/repo".into(),
4621 ..Default::default()
4622 }
4623 }
4624
4625 fn env_with_k8s(ctx: &str) -> MockEnvironment {
4626 let mut cmd_outputs = HashMap::new();
4627 cmd_outputs.insert("kubectl config current-context".into(), ctx.into());
4628 MockEnvironment {
4629 command_outputs: cmd_outputs,
4630 cwd: "/app".into(),
4631 ..Default::default()
4632 }
4633 }
4634
4635 #[test]
4636 fn test_detect_normal_context() {
4637 let env = MockEnvironment {
4638 cwd: "/Users/dev/project".into(),
4639 ..Default::default()
4640 };
4641 let ctx = detect(&env, &default_config());
4642 assert_eq!(ctx.risk_level, RiskLevel::Normal);
4643 assert!(!ctx.is_ssh);
4644 assert!(!ctx.is_root);
4645 }
4646
4647 #[test]
4648 fn test_detect_ssh_session() {
4649 let mut env_vars = HashMap::new();
4650 env_vars.insert("SSH_CONNECTION".into(), "10.0.0.1 22 10.0.0.2 54321".into());
4651 let env = MockEnvironment {
4652 env_vars,
4653 cwd: "/home/user".into(),
4654 ..Default::default()
4655 };
4656 let ctx = detect(&env, &default_config());
4657 assert!(ctx.is_ssh);
4658 assert_eq!(ctx.risk_level, RiskLevel::Elevated);
4659 }
4660
4661 #[test]
4662 fn test_empty_ssh_connection_is_not_ssh() {
4663 let mut env_vars = HashMap::new();
4664 env_vars.insert("SSH_CONNECTION".into(), String::new());
4665 let env = MockEnvironment {
4666 env_vars,
4667 ..Default::default()
4668 };
4669 assert!(!detect(&env, &default_config()).is_ssh);
4670 }
4671
4672 #[test]
4673 fn test_detect_root_user_via_euid() {
4674 let env = MockEnvironment {
4675 euid: Some(0),
4676 cwd: "/root".into(),
4677 ..Default::default()
4678 };
4679 let ctx = detect(&env, &default_config());
4680 assert!(ctx.is_root);
4681 assert!(!ctx.root_via_sudo);
4682 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4683 assert!(ctx.labels.contains(&"root=true".to_string()));
4684 }
4685
4686 #[test]
4687 fn test_euid_env_var_is_not_trusted() {
4688 let mut env_vars = HashMap::new();
4690 env_vars.insert("EUID".into(), "0".into());
4691 let env = MockEnvironment {
4692 env_vars,
4693 euid: Some(1000),
4694 ..Default::default()
4695 };
4696 let ctx = detect(&env, &default_config());
4697 assert!(!ctx.is_root);
4698 }
4699
4700 #[test]
4701 fn test_non_root_uid() {
4702 let env = MockEnvironment {
4703 euid: Some(501),
4704 ..Default::default()
4705 };
4706 assert!(!detect(&env, &default_config()).is_root);
4707 }
4708
4709 #[test]
4710 fn test_real_environment_euid_matches_libc() {
4711 let env = crate::env::RealEnvironment;
4712 #[cfg(unix)]
4713 assert_eq!(env.effective_uid(), Some(unsafe { libc::geteuid() }));
4714 }
4715
4716 #[test]
4717 fn test_sudo_prefix_is_root() {
4718 let env = MockEnvironment::default();
4719 let ctx = detect_for_command(&env, &default_config(), "sudo rm -rf /var/lib/x");
4720 assert!(ctx.is_root);
4721 assert!(ctx.root_via_sudo);
4722 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4723 let ctx = detect_for_command(&env, &default_config(), "sudo -u bob rm -rf /tmp/x");
4724 assert!(!ctx.is_root);
4725 }
4726
4727 #[test]
4728 fn test_detect_protected_branch() {
4729 let env = env_with_branch("main");
4730 let ctx = detect(&env, &default_config());
4731 assert_eq!(ctx.git_branch, Some("main".into()));
4732 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4733 }
4734
4735 #[test]
4736 fn test_detect_production_k8s() {
4737 let env = env_with_k8s("prod-us-east-1");
4738 let ctx = detect(&env, &default_config());
4739 assert_eq!(ctx.k8s_context, Some("prod-us-east-1".into()));
4740 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4741 }
4742
4743 #[test]
4744 fn test_detect_production_env() {
4745 let mut env_vars = HashMap::new();
4746 env_vars.insert("NODE_ENV".into(), "production".into());
4747 let env = MockEnvironment {
4748 env_vars,
4749 cwd: "/app".into(),
4750 ..Default::default()
4751 };
4752 let ctx = detect(&env, &default_config());
4753 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4754 assert_eq!(ctx.env_signals, vec!["NODE_ENV=production"]);
4755 assert!(ctx.labels.contains(&"env:NODE_ENV=production".to_string()));
4756 }
4757
4758 #[test]
4759 fn test_inline_env_assignment_is_signal() {
4760 let env = MockEnvironment::default();
4761 let ctx = detect_for_command(
4762 &env,
4763 &default_config(),
4764 "NODE_ENV=production npm run migrate",
4765 );
4766 assert_eq!(ctx.env_signals, vec!["NODE_ENV=production"]);
4767 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4768 }
4769
4770 #[test]
4771 fn test_feature_branch_is_normal() {
4772 let env = env_with_branch("feature/my-thing");
4773 let ctx = detect(&env, &default_config());
4774 assert_eq!(ctx.risk_level, RiskLevel::Normal);
4775 }
4776
4777 #[test]
4778 fn test_release_wildcard_branch() {
4779 let env = env_with_branch("release/v2.0");
4780 let ctx = detect(&env, &default_config());
4781 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4782 }
4783
4784 #[test]
4785 fn test_escalate_challenge_normal() {
4786 let esc = EscalationConfig::default();
4787 assert_eq!(
4788 escalate_challenge(&Challenge::Math, RiskLevel::Normal, &esc),
4789 Challenge::Math
4790 );
4791 }
4792
4793 #[test]
4794 fn test_escalate_challenge_elevated() {
4795 let esc = EscalationConfig::default();
4796 assert_eq!(
4797 escalate_challenge(&Challenge::Enter, RiskLevel::Elevated, &esc),
4798 Challenge::Math
4799 );
4800 assert_eq!(
4801 escalate_challenge(&Challenge::Math, RiskLevel::Elevated, &esc),
4802 Challenge::Math
4803 );
4804 }
4805
4806 #[test]
4807 fn test_escalate_challenge_critical() {
4808 let esc = EscalationConfig::default();
4809 assert_eq!(
4810 escalate_challenge(&Challenge::Math, RiskLevel::Critical, &esc),
4811 Challenge::Yes
4812 );
4813 }
4814
4815 #[test]
4816 fn test_escalate_cannot_lower() {
4817 let esc = EscalationConfig {
4819 elevated: Challenge::Enter,
4820 critical: Challenge::Enter,
4821 };
4822 for base in [Challenge::Enter, Challenge::Math, Challenge::Yes] {
4823 for risk in [RiskLevel::Normal, RiskLevel::Elevated, RiskLevel::Critical] {
4824 assert!(escalate_challenge(&base, risk, &esc) >= base);
4825 }
4826 }
4827 }
4828
4829 #[test]
4834 fn test_k8s_segment_matching() {
4835 let p = default_production_k8s_patterns();
4836 for prod in [
4837 "prod",
4838 "PROD-EU",
4839 "prod-eu",
4840 "gke_acme_prod_euw1",
4841 "arn:aws:eks:us-east-1:123:cluster/prd-main",
4842 "acme.production.cluster",
4843 "foo-live",
4844 "user@prod",
4845 ] {
4846 assert!(matches_any_pattern(prod, &p), "{prod} should be production");
4847 }
4848 for non in [
4849 "preprod",
4850 "k8s-products-dev",
4851 "reproduce-bug",
4852 "olive-test",
4853 "delivery-dev",
4854 "minikube",
4855 "docker-desktop",
4856 "staging",
4857 "productive",
4858 ] {
4859 assert!(
4860 !matches_any_pattern(non, &p),
4861 "{non} should NOT be production"
4862 );
4863 }
4864 }
4865
4866 #[test]
4867 fn test_k8s_multi_segment_and_glob_patterns() {
4868 let p = vec!["acme-eks".to_string()];
4869 assert!(matches_any_pattern("us-acme-eks-1", &p));
4870 assert!(!matches_any_pattern("acme-eksx", &p));
4871 let g = vec!["*prod*".to_string()];
4872 assert!(matches_any_pattern("preprod", &g));
4873 assert!(!matches_any_pattern("dev", &g));
4874 }
4875
4876 #[test]
4877 fn test_glob_match() {
4878 assert!(glob_match(b"release/*", b"release/v1/x"));
4879 assert!(glob_match(b"a?c", b"abc"));
4880 assert!(!glob_match(b"a?c", b"ac"));
4881 assert!(glob_match(b"*", b""));
4882 assert!(!glob_match(b"main", b"mainx"));
4883 }
4884
4885 #[test]
4890 fn test_k8s_context_flag_overrides_current() {
4891 let env = env_with_k8s("dev");
4892 for cmd in [
4893 "kubectl --context prod-eu delete deploy api",
4894 "kubectl delete deploy api --context=prod-eu",
4895 "helm --kube-context prod-eu uninstall api",
4896 "k --context \"prod-eu\" delete ns payments",
4897 ] {
4898 let ctx = detect_for_command(&env, &default_config(), cmd);
4899 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"), "{cmd}");
4900 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
4901 }
4902 }
4903
4904 #[test]
4905 fn test_inline_kubeconfig_is_read() {
4906 let mut files = HashMap::new();
4907 files.insert(
4908 PathBuf::from("/home/me/.kube/prod"),
4909 "apiVersion: v1\ncurrent-context: prod-eu\nkind: Config\n".to_string(),
4910 );
4911 let mut env = env_with_k8s("dev");
4912 env.files = files;
4913 env.home = Some(PathBuf::from("/home/me"));
4914 let ctx = detect_for_command(
4915 &env,
4916 &default_config(),
4917 "KUBECONFIG=~/.kube/prod kubectl delete ns payments",
4918 );
4919 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"));
4920 let ctx = detect_for_command(
4921 &env,
4922 &default_config(),
4923 "kubectl --kubeconfig /home/me/.kube/prod delete ns payments",
4924 );
4925 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"));
4926 }
4927
4928 #[test]
4929 fn test_kubeconfig_flag_falls_back_to_kubectl() {
4930 let mut env = env_with_k8s("dev");
4931 env.command_outputs.insert(
4932 "kubectl config current-context --kubeconfig /x/cfg".into(),
4933 "prd-1".into(),
4934 );
4935 env.files.insert("/x/cfg".into(), "apiVersion: v1\n".into());
4937 let ctx = detect_for_command(
4938 &env,
4939 &default_config(),
4940 "kubectl --kubeconfig=/x/cfg delete ns a",
4941 );
4942 assert_eq!(ctx.k8s_context.as_deref(), Some("prd-1"));
4943 }
4944
4945 #[test]
4946 fn test_kubectl_timeout_is_unknown_not_normal() {
4947 let mut env = MockEnvironment::default();
4948 env.timed_out_commands
4949 .insert("kubectl config current-context".into());
4950 let ctx = detect_for_command(&env, &default_config(), "kubectl delete deploy api");
4951 assert!(ctx.k8s_context.is_none());
4952 assert!(ctx.k8s_unknown);
4953 assert_eq!(ctx.risk_level, RiskLevel::Elevated);
4954 assert!(ctx.labels.contains(&"k8s=unknown".to_string()));
4955 }
4956
4957 #[test]
4958 fn test_kubectl_timeout_falls_back_to_kubeconfig_file() {
4959 let mut env = MockEnvironment {
4960 home: Some(PathBuf::from("/h")),
4961 ..Default::default()
4962 };
4963 env.timed_out_commands
4964 .insert("kubectl config current-context".into());
4965 env.files.insert(
4966 PathBuf::from("/h/.kube/config"),
4967 "current-context: \"prod-eu\"\n".into(),
4968 );
4969 let ctx = detect_for_command(&env, &default_config(), "kubectl delete deploy api");
4970 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"));
4971 assert!(!ctx.k8s_unknown);
4972 assert_eq!(ctx.risk_level, RiskLevel::Critical);
4973 }
4974
4975 #[test]
4976 fn test_kubectl_failure_is_no_context() {
4977 let env = MockEnvironment::default();
4979 let ctx = detect_for_command(&env, &default_config(), "kubectl delete deploy api");
4980 assert!(ctx.k8s_context.is_none());
4981 assert!(!ctx.k8s_unknown);
4982 assert_eq!(ctx.risk_level, RiskLevel::Normal);
4983 }
4984
4985 #[test]
4986 fn test_non_k8s_command_skips_kubectl_probe() {
4987 let env = env_with_k8s("prod-eu");
4988 let ctx = detect_for_command(&env, &default_config(), "rm -rf ./build");
4989 assert!(ctx.k8s_context.is_none());
4990 assert!(detect(&env, &default_config()).k8s_context.is_some());
4992 }
4993
4994 fn targets(cmd: &str) -> CommandTargets {
4999 parse_command_targets(cmd)
5000 }
5001
5002 #[test]
5003 fn test_push_targets() {
5004 for (cmd, expected) in [
5005 ("git push -f origin main", vec!["main"]),
5006 ("git push --force origin main", vec!["main"]),
5007 ("git push origin +main", vec!["main"]),
5008 ("git push --force origin HEAD:main", vec!["main"]),
5009 ("git push origin feature:refs/heads/main", vec!["main"]),
5010 ("git push --delete origin main", vec!["main"]),
5011 ("git push origin :main", vec!["main"]),
5012 ("git push -d origin release/1.0", vec!["release/1.0"]),
5013 ("git -C repo push -f origin main", vec!["main"]),
5014 ("git -c core.x=y push --force origin main", vec!["main"]),
5015 ("git push -o ci.skip origin main", vec!["main"]),
5016 (
5017 "git push --force-with-lease=main:abc origin main",
5018 vec!["main"],
5019 ),
5020 ("git push origin main dev", vec!["main", "dev"]),
5021 ("git push origin v1.0:refs/tags/v1.0", vec![]),
5022 ] {
5023 let t = targets(cmd);
5024 assert_eq!(t.git_targets, expected, "{cmd}");
5025 }
5026 }
5027
5028 #[test]
5029 fn test_push_without_refspec_uses_current() {
5030 for cmd in [
5031 "git push -f",
5032 "git push --force origin",
5033 "git push origin HEAD",
5034 ] {
5035 let t = targets(cmd);
5036 assert!(t.git_uses_current, "{cmd}");
5037 assert!(t.git_targets.is_empty(), "{cmd}");
5038 }
5039 let t = targets("git push --mirror origin");
5040 assert!(t.git_push_all);
5041 }
5042
5043 #[test]
5044 fn test_branch_delete_targets() {
5045 assert_eq!(targets("git branch -D main").git_targets, vec!["main"]);
5046 assert_eq!(
5047 targets("git branch --delete --force feature/x main").git_targets,
5048 vec!["feature/x", "main"]
5049 );
5050 assert_eq!(
5051 targets("git branch -f main HEAD~3").git_targets,
5052 vec!["main"]
5053 );
5054 assert!(targets("git branch new-thing").git_targets.is_empty());
5055 assert!(!targets("git branch -D feature").git_uses_current);
5056 }
5057
5058 #[test]
5059 fn test_push_target_main_from_feature_branch_is_critical() {
5060 let env = env_with_branch("feature/login");
5061 let ctx = detect_for_command(&env, &default_config(), "git push -f origin main");
5062 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5063 assert!(ctx.labels.contains(&"target=main".to_string()));
5064 let ctx = detect_for_command(&env, &default_config(), "git push --force origin HEAD:main");
5065 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5066 let ctx = detect_for_command(&env, &default_config(), "git branch -D main");
5067 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5068 }
5069
5070 #[test]
5071 fn test_push_feature_from_main_is_not_protected() {
5072 let env = env_with_branch("main");
5073 let ctx = detect_for_command(&env, &default_config(), "git push -f origin feature/login");
5074 assert_eq!(ctx.risk_level, RiskLevel::Normal);
5075 let ctx = detect_for_command(&env, &default_config(), "git branch -D feature/login");
5076 assert_eq!(ctx.risk_level, RiskLevel::Normal);
5077 let ctx = detect_for_command(&env, &default_config(), "git push -f");
5079 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5080 let ctx = detect_for_command(&env, &default_config(), "git reset --hard HEAD~1");
5082 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5083 let ctx = detect_for_command(&env, &default_config(), "git reset --hard");
5085 assert_eq!(ctx.risk_level, RiskLevel::Normal);
5086 }
5087
5088 #[test]
5089 fn test_local_only_git_commands_do_not_escalate_on_protected_branch() {
5090 let env = env_with_branch("main");
5091 for cmd in [
5092 "git cherry-pick abc123",
5093 "git rebase --continue",
5094 "git checkout -- README.md",
5095 "git worktree remove --force ../wt",
5096 "git stash clear",
5097 "git gc --prune=now",
5098 "git branch -d feature/login",
5099 "git clean -fdx",
5100 ] {
5101 let ctx = detect_for_command(&env, &default_config(), cmd);
5102 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{cmd}: {ctx:?}");
5103 assert!(ctx.labels.contains(&"branch=main".to_string()), "{cmd}");
5105 }
5106 for cmd in [
5107 "git push -f",
5108 "git push --force-with-lease",
5109 "git filter-branch --tree-filter x HEAD",
5110 "git rebase -i HEAD~3",
5112 "git branch -D main",
5113 "git reset --hard origin/main~2",
5114 ] {
5115 let ctx = detect_for_command(&env, &default_config(), cmd);
5116 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5117 }
5118 }
5119
5120 #[test]
5121 fn test_remote_git_command_ignores_local_branch() {
5122 let env = env_with_branch("main");
5123 let ctx = detect_for_command(&env, &default_config(), "ssh build-box git push -f");
5124 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{ctx:?}");
5125 assert!(
5126 ctx.labels.contains(&"remote=build-box".to_string()),
5127 "{ctx:?}"
5128 );
5129 }
5130
5131 #[test]
5132 fn test_git_branch_from_head_file_without_subprocess() {
5133 let mut env = MockEnvironment {
5134 cwd: "/repo/src".into(),
5135 ..Default::default()
5136 };
5137 env.files
5138 .insert("/repo/.git/HEAD".into(), "ref: refs/heads/main\n".into());
5139 let ctx = detect_for_command(
5140 &crate::env::NoContextEnvironment::new(&env),
5141 &default_config(),
5142 "git push -f",
5143 );
5144 assert_eq!(ctx.git_branch.as_deref(), Some("main"));
5145 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5146 let mut env = MockEnvironment {
5148 cwd: "/wt".into(),
5149 ..Default::default()
5150 };
5151 env.files.insert(
5152 "/wt/.git".into(),
5153 "gitdir: /repo/.git/worktrees/wt\n".into(),
5154 );
5155 env.files.insert(
5156 "/repo/.git/worktrees/wt/HEAD".into(),
5157 "ref: refs/heads/release/1.0\n".into(),
5158 );
5159 let ctx = detect_for_command(&env, &default_config(), "git push -f");
5160 assert_eq!(ctx.git_branch.as_deref(), Some("release/1.0"));
5161 }
5162
5163 #[test]
5164 fn test_git_timeout_is_unknown_not_normal() {
5165 let mut env = MockEnvironment {
5166 cwd: "/tmp/test".into(),
5167 ..Default::default()
5168 };
5169 env.timed_out_commands
5170 .insert("git rev-parse --abbrev-ref HEAD".into());
5171 let ctx = detect_for_command(&env, &default_config(), "git push -f");
5172 assert!(ctx.git_unknown);
5173 assert_eq!(ctx.risk_level, RiskLevel::Elevated);
5174 assert!(ctx.labels.contains(&"git=unknown".to_string()), "{ctx:?}");
5175 let reasons = ctx.risk_reasons(&default_config());
5176 assert!(reasons
5177 .iter()
5178 .any(|(_, r)| r.contains("git branch unknown")));
5179 }
5180
5181 #[test]
5182 fn test_context_switch_earlier_in_line_applies() {
5183 let env = env_with_k8s("dev");
5184 for cmd in [
5185 "kubectl config use-context prod-eu && kubectl delete deploy api",
5186 "kubectx prod-eu; kubectl delete deploy api",
5187 ] {
5188 let ctx = detect_for_command(&env, &default_config(), cmd);
5189 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"), "{cmd}");
5190 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
5191 }
5192 let mut env = env_with_k8s("dev");
5194 env.files
5195 .insert("/kc/prod".into(), "current-context: prod-eu\n".into());
5196 let ctx = detect_for_command(
5197 &env,
5198 &default_config(),
5199 "export KUBECONFIG=/kc/prod; kubectl delete deploy api",
5200 );
5201 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"));
5202 let env = env_with_branch("feature/login");
5204 let ctx = detect_for_command(&env, &default_config(), "git checkout main && git push -f");
5205 assert_eq!(ctx.git_branch.as_deref(), Some("main"));
5206 assert!(ctx.git_branch_switched);
5207 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5208 assert!(ctx.labels.iter().any(|l| l.contains("switched")), "{ctx:?}");
5209 let env = MockEnvironment::default();
5211 let ctx = detect_for_command(
5212 &env,
5213 &default_config(),
5214 "export NODE_ENV=production; kubectl cordon n1",
5215 );
5216 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5217 }
5218
5219 #[test]
5220 fn test_cloud_and_iac_production_targets() {
5221 let env = MockEnvironment::default();
5222 let cfg = default_config();
5223 for (cmd, label) in [
5224 (
5225 "AWS_PROFILE=prod aws s3 rb s3://b --force",
5226 "aws-profile=prod",
5227 ),
5228 (
5229 "aws --profile production rds delete-db-instance x",
5230 "aws-profile=production",
5231 ),
5232 ("TF_WORKSPACE=prod terraform destroy", "tf-workspace=prod"),
5233 (
5234 "terraform workspace select prod; terraform destroy",
5235 "tf-workspace=prod",
5236 ),
5237 (
5238 "gcloud --project acme-prod sql instances delete db",
5239 "gcp-project=acme-prod",
5240 ),
5241 (
5242 "gcloud config set project acme-prod && gcloud sql instances delete db",
5243 "gcp-project=acme-prod",
5244 ),
5245 ("kubectl delete deploy api -n prod", "namespace=prod"),
5246 (
5247 "kubectl --namespace=production delete deploy api",
5248 "namespace=production",
5249 ),
5250 (
5251 "az account set --subscription prod-sub; az group delete -n x",
5252 "azure-subscription=prod-sub",
5253 ),
5254 ] {
5255 let ctx = detect_for_command(&env, &cfg, cmd);
5256 assert!(
5257 ctx.labels.contains(&label.to_string()),
5258 "{cmd}: {:?}",
5259 ctx.labels
5260 );
5261 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
5262 }
5263 let ctx = detect_for_command(&env, &cfg, "aws --profile dev s3 rb s3://b --force");
5264 assert_eq!(ctx.risk_level, RiskLevel::Normal);
5265 let ctx = detect_for_command(&env, &cfg, "AWS_PROFILE=prod rm -rf build");
5267 let groups: std::collections::HashSet<&str> = ["fs"].into_iter().collect();
5268 assert_eq!(
5269 ctx.filter_for_groups(&groups, &cfg).risk_level,
5270 RiskLevel::Normal
5271 );
5272 }
5273
5274 #[test]
5275 fn test_remote_payload_does_not_use_local_k8s_context() {
5276 let env = env_with_k8s("prod-eu");
5277 let ctx = detect_for_command(
5278 &env,
5279 &default_config(),
5280 "ssh bastion kubectl delete ns payments",
5281 );
5282 assert!(ctx.k8s_context.is_none(), "{ctx:?}");
5283 let ctx = detect_for_command(
5284 &env,
5285 &default_config(),
5286 "docker exec web kubectl delete ns x",
5287 );
5288 assert!(ctx.k8s_context.is_none(), "{ctx:?}");
5289 let ctx = detect_for_command(
5291 &env,
5292 &default_config(),
5293 "ssh deploy@prod-db 'rm -rf /var/lib/x'",
5294 );
5295 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5296 assert!(
5297 ctx.labels.contains(&"remote=prod-db".to_string()),
5298 "{ctx:?}"
5299 );
5300 }
5301
5302 #[test]
5303 fn test_sensitive_paths() {
5304 let mut cfg = default_config();
5305 cfg.sensitive_paths = vec!["~/.ssh".into(), "/srv".into()];
5306 let env = MockEnvironment {
5307 cwd: "/home/dev/.ssh".into(),
5308 home: Some("/home/dev".into()),
5309 ..Default::default()
5310 };
5311 for cmd in [
5312 "rm -rf ~/.ssh",
5313 "rm id_ed25519",
5314 "rm -rf /home/dev/.ssh/keys",
5315 "echo x > ~/.ssh/authorized_keys",
5316 "mv /srv/app /tmp/",
5317 "cp evil /srv/app/config",
5318 "rm -rf ~",
5319 "cd /srv && rm -rf app",
5320 ] {
5321 let ctx = detect_for_command(&env, &cfg, cmd);
5322 assert!(!ctx.sensitive_paths.is_empty(), "{cmd}");
5323 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
5324 }
5325 let env = MockEnvironment {
5326 cwd: "/home/dev/projects".into(),
5327 home: Some("/home/dev".into()),
5328 ..Default::default()
5329 };
5330 for cmd in [
5331 "rm -rf build",
5332 "cp ~/.ssh/id_ed25519.pub /tmp/",
5333 "ls ~/.ssh",
5334 "ssh host rm -rf /srv/app",
5335 ] {
5336 let ctx = detect_for_command(&env, &cfg, cmd);
5337 assert!(ctx.sensitive_paths.is_empty(), "{cmd}: {ctx:?}");
5338 }
5339 }
5340
5341 #[test]
5342 fn test_invisible_characters_in_branch() {
5343 let env = env_with_branch("main\u{200b}");
5344 let ctx = detect_for_command(&env, &default_config(), "git push -f");
5345 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5346 assert!(
5347 ctx.labels.contains(&"branch=main\\u{200b}".to_string()),
5348 "{:?}",
5349 ctx.labels
5350 );
5351 assert_eq!(escape_invisible("a\u{202e}b"), "a\\u{202e}b");
5352 assert_eq!(escape_invisible("plain"), "plain");
5353 assert_eq!(
5355 escape_invisible_text("m\u{200c}k \u{1F469}\u{200d}\u{1F4BB} \u{2764}\u{fe0f}"),
5356 "m\u{200c}k \u{1F469}\u{200d}\u{1F4BB} \u{2764}\u{fe0f}"
5357 );
5358 assert_eq!(
5359 escape_invisible_text("a\u{202e}b\u{200b}"),
5360 "a\\u{202e}b\\u{200b}"
5361 );
5362 assert_eq!(escape_invisible_text("a\u{1b}[2Jb"), "a\\u{1b}[2Jb");
5363 assert!(branch_matches_any("ma\u{2060}in", &["main".to_string()]));
5364 }
5365
5366 #[test]
5367 fn test_targets_in_compound_and_nested_commands() {
5368 let t = targets("cd repo && git push -f origin main; echo done");
5369 assert_eq!(t.git_targets, vec!["main"]);
5370 let t = targets("bash -c 'git push -f origin main'");
5371 assert_eq!(t.git_targets, vec!["main"]);
5372 let t = targets("sudo -E env FOO=1 kubectl --context=prod delete ns a");
5373 assert_eq!(t.k8s_context.as_deref(), Some("prod"));
5374 assert!(t.sudo_root);
5375 assert!(t.mentions_k8s);
5376 let t = targets("echo 'kubectl --context prod' # comment");
5377 assert!(!t.mentions_k8s);
5378 }
5379
5380 #[test]
5385 fn test_risk_reasons() {
5386 let ctx = RuntimeContext {
5387 is_ssh: true,
5388 git_branch: Some("main".into()),
5389 ..Default::default()
5390 };
5391 let reasons: Vec<String> = ctx
5392 .risk_reasons(&default_config())
5393 .into_iter()
5394 .map(|(_, r)| r)
5395 .collect();
5396 assert_eq!(reasons, vec!["protected branch `main`", "SSH session"]);
5397 }
5398
5399 #[test]
5400 fn test_effective_challenge_note() {
5401 let e = EffectiveChallenge {
5402 base: Challenge::Math,
5403 challenge: Challenge::Yes,
5404 reasons: vec!["protected branch `main`".into(), "SSH session".into()],
5405 };
5406 assert_eq!(
5407 e.note().unwrap(),
5408 "Escalated to Yes (from Math): protected branch `main`, SSH session"
5409 );
5410 let same = EffectiveChallenge {
5411 base: Challenge::Math,
5412 challenge: Challenge::Math,
5413 reasons: vec![],
5414 };
5415 assert!(same.note().is_none());
5416 }
5417
5418 fn full_context() -> RuntimeContext {
5423 let mut ctx = RuntimeContext {
5424 is_ssh: true,
5425 git_branch: Some("main".into()),
5426 k8s_context: Some("prod-us-east-1".into()),
5427 env_signals: vec!["NODE_ENV=production".into()],
5428 ..Default::default()
5429 };
5430 ctx.refresh(&default_config());
5431 ctx
5432 }
5433
5434 #[test]
5435 fn test_filter_git_command_hides_k8s() {
5436 let ctx = full_context();
5437 let groups: std::collections::HashSet<&str> = ["git"].into_iter().collect();
5438 let filtered = ctx.filter_for_groups(&groups, &default_config());
5439
5440 assert_eq!(filtered.git_branch, Some("main".into()));
5441 assert!(filtered.k8s_context.is_none());
5442 assert!(filtered.labels.contains(&"branch=main".to_string()));
5443 assert!(!filtered.labels.iter().any(|l| l.starts_with("k8s=")));
5444 }
5445
5446 #[test]
5447 fn test_filter_k8s_command_hides_branch() {
5448 let ctx = full_context();
5449 let groups: std::collections::HashSet<&str> = ["kubernetes"].into_iter().collect();
5450 let filtered = ctx.filter_for_groups(&groups, &default_config());
5451
5452 assert!(filtered.git_branch.is_none());
5453 assert_eq!(filtered.k8s_context, Some("prod-us-east-1".into()));
5454 assert!(!filtered.labels.iter().any(|l| l.starts_with("branch=")));
5455 assert!(filtered.labels.contains(&"k8s=prod-us-east-1".to_string()));
5456 }
5457
5458 #[test]
5459 fn test_filter_fs_command_global_only() {
5460 let ctx = full_context();
5461 let groups: std::collections::HashSet<&str> = ["fs"].into_iter().collect();
5462 let filtered = ctx.filter_for_groups(&groups, &default_config());
5463
5464 assert!(filtered.git_branch.is_none());
5465 assert!(filtered.k8s_context.is_none());
5466 assert!(filtered.is_ssh);
5467 assert!(filtered.labels.contains(&"ssh=true".to_string()));
5468 assert!(!filtered.labels.iter().any(|l| l.starts_with("branch=")));
5469 assert!(!filtered.labels.iter().any(|l| l.starts_with("k8s=")));
5470 }
5471
5472 #[test]
5473 fn test_filter_compound_git_and_k8s() {
5474 let ctx = full_context();
5475 let groups: std::collections::HashSet<&str> = ["git", "kubernetes"].into_iter().collect();
5476 let filtered = ctx.filter_for_groups(&groups, &default_config());
5477
5478 assert_eq!(filtered.git_branch, Some("main".into()));
5479 assert_eq!(filtered.k8s_context, Some("prod-us-east-1".into()));
5480 assert!(filtered.labels.contains(&"branch=main".to_string()));
5481 assert!(filtered.labels.contains(&"k8s=prod-us-east-1".to_string()));
5482 }
5483
5484 #[test]
5485 fn test_filter_global_signals_never_hidden() {
5486 let mut ctx = RuntimeContext {
5487 is_ssh: true,
5488 is_root: true,
5489 git_branch: Some("main".into()),
5490 k8s_context: Some("prod".into()),
5491 env_signals: vec!["NODE_ENV=production".into()],
5492 ..Default::default()
5493 };
5494 ctx.refresh(&default_config());
5495 let groups: std::collections::HashSet<&str> = ["fs"].into_iter().collect();
5497 let filtered = ctx.filter_for_groups(&groups, &default_config());
5498
5499 assert!(filtered.is_ssh);
5500 assert!(filtered.is_root);
5501 assert_eq!(filtered.env_signals, vec!["NODE_ENV=production"]);
5502 assert!(filtered.labels.contains(&"ssh=true".to_string()));
5503 assert!(filtered.labels.contains(&"root=true".to_string()));
5504 }
5505
5506 #[test]
5507 fn test_filter_risk_level_recomputed() {
5508 let mut ctx = RuntimeContext {
5510 git_branch: Some("main".into()),
5511 ..Default::default()
5512 };
5513 ctx.refresh(&default_config());
5514 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5515 let groups: std::collections::HashSet<&str> = ["fs"].into_iter().collect();
5517 let filtered = ctx.filter_for_groups(&groups, &default_config());
5518
5519 assert!(filtered.git_branch.is_none());
5520 assert_eq!(filtered.risk_level, RiskLevel::Normal);
5521 }
5522
5523 fn relevant(env: &MockEnvironment, cmd: &str) -> RuntimeContext {
5530 relevant_in(env, cmd)
5531 }
5532
5533 fn relevant_in(env: &dyn Environment, cmd: &str) -> RuntimeContext {
5534 let cfg = default_config();
5535 let groups_of = |text: &str| -> std::collections::HashSet<String> {
5536 let mut g = std::collections::HashSet::new();
5537 let p = crate::parser::parse(text);
5538 for s in &p.segments {
5539 let first = s.split(' ').next().unwrap_or("");
5540 let group = match first {
5541 "kubectl" | "helm" => "kubernetes",
5542 "git" => "git",
5543 "terraform" | "pulumi" => "terraform",
5544 "aws" => "aws",
5545 "rm" => "fs",
5546 _ => continue,
5547 };
5548 if s.contains("delete")
5549 || s.contains("destroy")
5550 || s.contains("cordon")
5551 || s.contains(" -f")
5552 || s.contains("--hard")
5553 || s.contains("rb ")
5554 || first == "rm"
5555 {
5556 g.insert(group.to_string());
5557 }
5558 }
5559 g
5560 };
5561 let all: std::collections::HashSet<&str> = ["kubernetes", "git", "terraform", "fs", "aws"]
5562 .into_iter()
5563 .collect();
5564 command_contexts(env, &cfg, cmd).relevant(&cfg, &groups_of, &all)
5565 }
5566
5567 fn env_branch_k8s(branch: &str, k8s: &str) -> MockEnvironment {
5568 let mut env = env_with_branch(branch);
5569 env.command_outputs
5570 .insert("kubectl config current-context".into(), k8s.into());
5571 env
5572 }
5573
5574 #[test]
5575 fn test_switch_after_the_risky_command_does_not_apply() {
5576 let env = env_branch_k8s("main", "prod-eu");
5577 for cmd in [
5578 "kubectl delete deploy api; kubectx dev",
5579 "kubectl delete deploy api && kubectl config use-context dev",
5580 "kubectl delete deploy api && kubectl config use dev",
5581 "kubectx prod-eu && kubectl delete deploy api && kubectx dev",
5582 "git push -f; git checkout feature/login",
5583 "git reset --hard HEAD~1 && git checkout feature/login",
5584 "TF_WORKSPACE=prod terraform destroy; terraform workspace select dev",
5585 "terraform workspace select prod && terraform destroy && terraform workspace select dev",
5586 "export NODE_ENV=production; kubectl cordon n1; unset NODE_ENV",
5587 ] {
5588 let ctx = relevant(&env, cmd);
5589 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5590 assert!(
5591 !ctx.labels.iter().any(|l| l == "k8s=dev"),
5592 "{cmd}: {:?}",
5593 ctx.labels
5594 );
5595 }
5596 let env = env_branch_k8s("feature/login", "dev");
5598 for cmd in [
5599 "kubectl delete deploy api && kubectx prod-eu",
5600 "git push -f; git checkout main",
5601 "terraform destroy; terraform workspace select prod",
5602 "kubectl cordon n1; export NODE_ENV=production",
5603 ] {
5604 let ctx = relevant(&env, cmd);
5605 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{cmd}: {ctx:?}");
5606 }
5607 let ctx = relevant(&env, "kubectl delete deploy api && kubectx prod-eu");
5608 assert!(ctx.labels.contains(&"k8s=dev".to_string()), "{ctx:?}");
5609 for cmd in [
5611 "kubectx prod-eu && kubectl delete deploy api",
5612 "kubie ctx prod-eu && kubectl delete deploy api",
5613 "kubectl config use prod-eu && kubectl delete deploy api",
5614 "if kubectx prod-eu; then kubectl delete deploy api; fi",
5615 "git checkout main && git push -f",
5616 "terraform workspace select prod; terraform destroy",
5617 ] {
5618 let ctx = relevant(&env, cmd);
5619 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5620 }
5621 let mut env = MockEnvironment::default();
5623 env.env_vars.insert("NODE_ENV".into(), "production".into());
5624 let ctx = relevant(&env, "unset NODE_ENV; kubectl cordon n1");
5625 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{ctx:?}");
5626 }
5627
5628 #[test]
5629 fn test_kubectl_exec_payload_keeps_cluster_context() {
5630 let env = env_branch_k8s("main", "prod-eu");
5631 for cmd in [
5632 "kubectl exec -it api-1 -- rm -rf /data",
5633 "kubectl -n prod exec api-1 -- sh -c 'rm -rf /data'",
5634 ] {
5635 let ctx = relevant(&env, cmd);
5636 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5637 assert!(
5638 !ctx.labels.iter().any(|l| l.starts_with("branch=")),
5639 "{ctx:?}"
5640 );
5641 }
5642 let env = env_branch_k8s("main", "dev");
5643 for cmd in [
5644 "kubectl --context prod-eu exec api-1 -- rm -rf /data",
5645 "kubectl exec --context=prod-eu api-1 -- rm -rf /data",
5646 ] {
5647 let ctx = relevant(&env, cmd);
5648 assert!(
5649 ctx.labels.contains(&"k8s=prod-eu".to_string()),
5650 "{cmd}: {ctx:?}"
5651 );
5652 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
5653 }
5654 }
5655
5656 #[test]
5657 fn test_wrappers_keep_context_and_root() {
5658 let env = env_with_k8s("prod-eu");
5659 for cmd in [
5660 "su -c 'kubectl cordon n1'",
5661 "runuser -l root -c 'kubectl cordon n1'",
5662 "flock /tmp/l -c 'kubectl cordon n1'",
5663 "script -c 'kubectl cordon n1' /dev/null",
5664 "env -S 'kubectl cordon n1'",
5665 "sudo su -c 'kubectl delete deploy api'",
5666 "chrt -f 10 kubectl cordon n1",
5667 "taskset -c 0 kubectl cordon n1",
5668 "nsenter -t 1 -m -- kubectl cordon n1",
5669 "nocorrect kubectl cordon n1",
5670 ] {
5671 let ctx = relevant(&env, cmd);
5672 assert!(
5673 ctx.labels.contains(&"k8s=prod-eu".to_string()),
5674 "{cmd}: {ctx:?}"
5675 );
5676 }
5677 let env = MockEnvironment::default();
5678 for cmd in [
5679 "su -c 'rm -rf ./build'",
5680 "su - root -c 'rm -rf ./build'",
5681 "pkexec rm -rf ./build",
5682 "runuser -u root -- rm -rf ./build",
5683 "sudo su -c 'rm -rf ./build'",
5684 ] {
5685 let ctx = relevant(&env, cmd);
5686 assert!(ctx.is_root, "{cmd}: {ctx:?}");
5687 }
5688 for cmd in [
5689 "su - postgres -c 'rm -rf ./build'",
5690 "runuser -u nobody -- rm -rf ./build",
5691 "pkexec --user bob rm -rf ./build",
5692 ] {
5693 assert!(!relevant(&env, cmd).is_root, "{cmd}");
5694 }
5695 }
5696
5697 #[test]
5698 fn test_ssh_payload_explicit_signals() {
5699 let env = env_branch_k8s("main", "dev");
5700 for cmd in [
5701 "ssh bastion kubectl --context prod-eu delete deploy api",
5702 "ssh bastion 'kubectl --context prod-eu delete deploy api'",
5703 "ssh bastion TF_WORKSPACE=prod terraform destroy",
5704 "ssh bastion 'git push -f origin main'",
5705 "ssh bastion sudo rm -rf /etc",
5706 ] {
5707 let ctx = relevant(&env, cmd);
5708 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5709 }
5710 let ctx = relevant(&env, "ssh bastion 'git push -f'");
5712 assert!(ctx.git_branch.is_none(), "{ctx:?}");
5713 let env = env_with_k8s("prod-eu");
5714 let ctx = relevant(&env, "ssh bastion kubectl delete ns payments");
5715 assert!(ctx.k8s_context.is_none(), "{ctx:?}");
5716 }
5717
5718 #[test]
5719 fn test_more_cloud_signals() {
5720 let env = MockEnvironment::default();
5721 for cmd in [
5722 "AWS_PROFILE=prod terraform destroy",
5723 "export AWS_PROFILE=prod; terraform destroy",
5724 "AWS_DEFAULT_PROFILE=prod aws s3 rb s3://b --force",
5725 "gcloud projects delete acme-prod",
5726 "az account set -s prod-sub && az group delete -n x",
5727 ] {
5728 let ctx = command_contexts(&env, &default_config(), cmd).full(&default_config());
5729 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5730 }
5731 let ctx = relevant(&env, "AWS_PROFILE=prod terraform destroy");
5732 assert!(
5733 ctx.labels.contains(&"aws-profile=prod".to_string()),
5734 "{ctx:?}"
5735 );
5736 let env = env_with_k8s("dev");
5738 let ctx = relevant(&env, "kubectl delete ns prod");
5739 assert!(
5740 ctx.labels.contains(&"namespace=prod".to_string()),
5741 "{ctx:?}"
5742 );
5743 }
5744
5745 #[test]
5746 fn test_k8s_unknown_and_not_checked_and_ssh_client() {
5747 let env = env_with_k8s("dev");
5749 let ctx = relevant(&env, "KUBECONFIG=/nonexistent kubectl delete deploy api");
5750 assert!(ctx.labels.contains(&"k8s=unknown".to_string()), "{ctx:?}");
5751 let mut env = env_with_k8s("dev");
5752 env.env_vars
5753 .insert("KUBECONFIG".into(), "/nonexistent".into());
5754 let ctx = relevant(&env, "kubectl delete deploy api");
5755 assert!(ctx.labels.contains(&"k8s=unknown".to_string()), "{ctx:?}");
5756 let base = MockEnvironment::default();
5758 let env = crate::env::NoContextEnvironment::new(&base);
5759 let ctx = relevant_in(&env, "kubectl delete deploy api");
5760 assert!(
5761 ctx.labels.contains(&"k8s=not checked".to_string()),
5762 "{ctx:?}"
5763 );
5764 let mut env = MockEnvironment::default();
5766 env.env_vars
5767 .insert("SSH_CLIENT".into(), "1.2.3.4 5 22".into());
5768 assert!(detect(&env, &default_config()).is_ssh);
5769 }
5770
5771 #[test]
5772 fn test_clustered_dash_c_and_target_dirs() {
5773 let env = MockEnvironment::default();
5774 let ctx = relevant(&env, "su -lc 'rm -rf ./build'");
5775 assert!(ctx.is_root, "{ctx:?}");
5776 let ctx = relevant(&env, "script -qc 'rm -rf ./build' /dev/null");
5777 assert!(!ctx.is_root, "{ctx:?}");
5778 let dirs = command_target_dirs(
5779 "cd ../infra && cd envs; git -C ../app push; terraform -chdir=prod plan; make -C sub; GIT_DIR=/r/.git git log",
5780 );
5781 let dirs: Vec<String> = dirs.iter().map(|d| d.display().to_string()).collect();
5782 assert_eq!(
5783 dirs,
5784 vec![
5785 "../infra",
5786 "../infra/envs",
5787 "../infra/app",
5788 "../infra/envs/prod",
5789 "../infra/envs/sub",
5790 "/r/.git"
5791 ]
5792 );
5793 assert!(is_tightening_mode("600"));
5794 assert!(is_tightening_mode("0400"));
5795 assert!(is_tightening_mode("go-rwx"));
5796 assert!(!is_tightening_mode("644"));
5797 assert!(!is_tightening_mode("4700"));
5798 assert!(!is_tightening_mode("u+x"));
5799 }
5800
5801 fn env_with_kubeconfig(branch: &str, current: &str) -> MockEnvironment {
5802 let mut env = env_branch_k8s(branch, current);
5803 env.home = Some(PathBuf::from("/home/u"));
5804 env.files.insert(
5805 PathBuf::from("/home/u/.kube/config"),
5806 format!(
5807 "apiVersion: v1\nkind: Config\ncurrent-context: {current}\ncontexts:\n- name: prod-eu\n context:\n cluster: c1\n- context:\n cluster: c2\n name: dev\nclusters: []\n"
5808 ),
5809 );
5810 env
5811 }
5812
5813 #[test]
5814 fn test_a_switch_that_may_fail_keeps_the_old_context() {
5815 let env = env_with_kubeconfig("main", "prod-eu");
5816 for cmd in [
5818 "kubectx nope; kubectl delete deploy api",
5819 "kubectl config use-context does-not-exist; kubectl delete deploy api",
5820 "kubectx dev || kubectl delete deploy api",
5821 "kubectx dev; kubectl delete deploy api",
5822 "kubectx dev & kubectl delete deploy api",
5823 "kubectx nope && kubectl delete deploy api",
5824 "kubectx dev && kubectl get pods; kubectl delete deploy api",
5825 "kubectx nope; kubectx dev; kubectl delete deploy api",
5826 ] {
5827 let ctx = relevant(&env, cmd);
5828 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5829 assert!(
5831 ctx.labels
5832 .iter()
5833 .any(|l| l == "k8s=prod-eu"
5834 || l.starts_with("k8s=prod-eu (kept: the switch to ")),
5835 "{cmd}: {:?}",
5836 ctx.labels
5837 );
5838 }
5839 for cmd in [
5841 "kubectx dev && kubectl delete deploy api",
5842 "kubectl config use-context dev && kubectl delete deploy api",
5843 "kubectx nope; kubectx dev && kubectl delete deploy api",
5844 ] {
5845 let ctx = relevant(&env, cmd);
5846 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{cmd}: {ctx:?}");
5847 }
5848 let env = env_with_kubeconfig("main", "dev");
5850 for cmd in [
5851 "git checkout no-such-branch; git push -f",
5852 "git checkout feature/login || git push -f",
5853 "git switch nope; git reset --hard HEAD~1",
5854 "git checkout nope && git push -f",
5855 ] {
5856 let ctx = relevant(&env, cmd);
5857 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5858 assert!(
5859 ctx.labels.iter().any(|l| l.starts_with("branch=main")),
5860 "{cmd}: {:?}",
5861 ctx.labels
5862 );
5863 }
5864 let ctx = relevant(&env, "git checkout -b fix && git push -f");
5865 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{ctx:?}");
5866 }
5867
5868 #[test]
5869 fn test_variable_contexts_and_terraform_dirs() {
5870 let env = env_with_kubeconfig("feature/login", "dev");
5871 for cmd in [
5872 "for c in prod-eu dev; do kubectl --context $c delete deploy api; done",
5873 "C=prod-eu; kubectl --context $C delete deploy api",
5874 "kubectl --context \"$(echo prod-eu)\" delete deploy api",
5875 "terraform -chdir=envs/prod destroy",
5876 "terraform destroy -var-file=prod.tfvars",
5877 "cd envs/prod && terraform destroy",
5878 ] {
5879 let ctx = relevant(&env, cmd);
5880 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}: {ctx:?}");
5881 }
5882 let ctx = relevant(&env, "kubectl --context $UNSET delete deploy api");
5883 assert!(ctx.labels.contains(&"k8s=unknown".to_string()), "{ctx:?}");
5884 assert_eq!(ctx.risk_level, RiskLevel::Elevated, "{ctx:?}");
5885 let ctx = relevant(&env, "terraform -chdir=envs/dev destroy");
5886 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{ctx:?}");
5887 }
5888
5889 #[test]
5890 fn test_force_with_lease_to_a_protected_branch() {
5891 let cfg = default_config();
5892 let env = env_with_branch("main");
5893 let lease = |env: &MockEnvironment, cmd: &str| {
5894 protected_force_with_lease(env, &cfg, cmd, &crate::parser::parse(cmd))
5895 };
5896 assert_eq!(
5897 lease(&env, "git push --force-with-lease").as_deref(),
5898 Some("main")
5899 );
5900 assert_eq!(
5901 lease(&env, "git push --force-with-lease origin main").as_deref(),
5902 Some("main")
5903 );
5904 assert_eq!(
5905 lease(&env, "git push --force-with-lease origin feature/x"),
5906 None
5907 );
5908 assert_eq!(lease(&env, "git push origin main"), None);
5909 let env = env_with_branch("feature/login");
5910 assert_eq!(lease(&env, "git push --force-with-lease"), None);
5911 assert_eq!(
5912 lease(
5913 &env,
5914 "git push --force-if-includes --force-with-lease origin HEAD:main"
5915 )
5916 .as_deref(),
5917 Some("main")
5918 );
5919 }
5920
5921 #[test]
5922 fn test_force_with_lease_to_a_computed_target() {
5923 let cfg = default_config();
5924 let env = env_with_branch("main");
5925 let lease =
5926 |cmd: &str| protected_force_with_lease(&env, &cfg, cmd, &crate::parser::parse(cmd));
5927 for cmd in [
5928 "git push --force-with-lease origin $(git branch --show-current)",
5929 "git push --force-with-lease origin $(git_current_branch)",
5930 "for b in main dev; do git push --force-with-lease origin $b; done",
5931 "echo main | xargs -I{} git push --force-with-lease origin {}",
5932 ] {
5933 assert_eq!(lease(cmd).as_deref(), Some("main"), "{cmd}");
5934 }
5935 for cmd in [
5938 "git push --force-with-lease origin $B",
5939 "git push --force-if-includes origin $B",
5940 "git push --force-with-lease origin +$B",
5941 "git push --force-with-lease origin $(cat /tmp/branchname)",
5942 ] {
5943 assert_eq!(lease(cmd).as_deref(), Some(UNKNOWN_PUSH_TARGET), "{cmd}");
5944 }
5945 assert_eq!(lease("git push --force-with-lease origin feature/x"), None);
5946 }
5947
5948 #[test]
5949 fn test_oh_my_zsh_current_branch_helpers_on_a_feature_branch() {
5950 let cfg = default_config();
5953 let env = env_with_branch("feature/login");
5954 let lease =
5955 |cmd: &str| protected_force_with_lease(&env, &cfg, cmd, &crate::parser::parse(cmd));
5956 for cmd in [
5957 "git push --force-with-lease origin $(git_current_branch)",
5958 "git push --force-with-lease origin \"$(git_current_branch)\"",
5959 "git push --set-upstream --force-with-lease origin $(current_branch)",
5960 "git push --force-with-lease origin $(command git_current_branch)",
5961 "[[ \"$#\" != 1 ]] && local b=\"$(git_current_branch)\"; git push --force-with-lease origin \"${b:=$1}\"",
5962 "git push --force-with-lease origin `git_current_branch`",
5963 ] {
5964 assert_eq!(lease(cmd), None, "{cmd}");
5965 let t = parse_command_targets(cmd);
5966 assert!(
5967 t.segments.iter().any(|s| s.git_uses_current)
5968 && !t.segments.iter().any(|s| s.git_target_unknown),
5969 "{cmd}: {t:?}"
5970 );
5971 }
5972 assert_eq!(
5974 lease("git push --force-with-lease origin \"${B:=main}\"").as_deref(),
5975 Some("main")
5976 );
5977 }
5978
5979 #[test]
5980 fn test_hosting_platform_runs_are_remote_and_production_escalates() {
5981 let cfg = default_config();
5982 let env = MockEnvironment {
5983 cwd: "/app".into(),
5984 ..Default::default()
5985 };
5986 let ctx = detect_for_command(
5987 &env,
5988 &cfg,
5989 "heroku pg:psql --command 'DELETE FROM users' -a shop-prod",
5990 );
5991 assert!(
5992 ctx.labels.iter().any(|l| l == "remote=heroku:shop-prod"),
5993 "{:?}",
5994 ctx.labels
5995 );
5996 assert_eq!(ctx.risk_level, RiskLevel::Critical);
5997 let ctx = detect_for_command(&env, &cfg, "fly ssh console -a web-dev -C 'ls'");
5998 assert!(
5999 ctx.labels.iter().any(|l| l == "remote=fly:web-dev"),
6000 "{:?}",
6001 ctx.labels
6002 );
6003 assert_ne!(ctx.risk_level, RiskLevel::Critical);
6004 }
6005
6006 #[test]
6007 fn test_unknown_push_target_is_labelled_unknown_not_main() {
6008 let cfg = default_config();
6012 let mut env = env_with_branch("feature/login");
6013 env.files.insert(
6014 "/repo/.git/HEAD".into(),
6015 "ref: refs/heads/feature/login\n".into(),
6016 );
6017 env.files
6018 .insert("/repo/.git/refs/heads/main".into(), "0123abcd\n".into());
6019 let mut escalated = 0;
6020 for cmd in [
6021 "git push --force-with-lease origin $B",
6022 "git push --force-with-lease origin $(cat /tmp/branchname)",
6023 "git push -f origin \"$@\"",
6024 ] {
6025 let ctx = detect_for_command(&env, &cfg, cmd);
6026 assert!(
6027 !ctx.git_targets.iter().any(|t| t == "main"),
6028 "{cmd}: {ctx:?}"
6029 );
6030 if ctx.git_target_unknown {
6031 escalated += 1;
6032 assert_eq!(ctx.risk_level, RiskLevel::Critical, "{cmd}");
6033 assert!(ctx.labels.iter().any(|l| l == "target=unknown"), "{cmd}");
6034 assert!(
6035 !ctx.labels.iter().any(|l| l.contains("target=main")),
6036 "{cmd}"
6037 );
6038 let reasons: Vec<String> =
6039 ctx.risk_reasons(&cfg).into_iter().map(|(_, r)| r).collect();
6040 assert!(
6041 reasons.iter().all(|r| !r.contains("`main`")),
6042 "{cmd}: {reasons:?}"
6043 );
6044 }
6045 }
6046 assert!(escalated >= 2, "unknown targets still escalate");
6047 let env = env_with_branch("feature/login");
6049 let ctx = detect_for_command(&env, &cfg, "git push --force-with-lease origin $B");
6050 assert!(!ctx.git_target_unknown, "{ctx:?}");
6051 }
6052
6053 #[test]
6054 fn test_redirections_are_not_arguments() {
6055 let t = parse_command_targets("git push -f >/dev/null 2>&1");
6056 assert!(t.git_uses_current, "{t:?}");
6057 assert!(t.git_targets.is_empty(), "{t:?}");
6058 let t = parse_command_targets("git push -f origin main > /dev/null");
6059 assert_eq!(t.git_targets, vec!["main".to_string()]);
6060 let t = parse_command_targets("git reset --hard 2>&1");
6061 assert!(!t.git_uses_current, "{t:?}");
6062 let t = parse_command_targets("git reset --hard </dev/null &>log");
6063 assert!(!t.git_uses_current, "{t:?}");
6064 assert_eq!(
6065 tokenize_segments("diff b 2>/dev/null")[0],
6066 vec!["diff".to_string(), "b".to_string()]
6067 );
6068 }
6069
6070 #[test]
6071 fn test_discard_with_other_risky_command_is_not_protected_branch() {
6072 let env = env_with_branch("main");
6073 for cmd in [
6074 "rm -rf build && git reset --hard",
6075 "git reset --hard && rm -rf build",
6076 "rm -rf node_modules && git checkout -- .",
6077 ] {
6078 let ctx = relevant(&env, cmd);
6079 assert_eq!(ctx.risk_level, RiskLevel::Normal, "{cmd}: {ctx:?}");
6080 }
6081 let ctx = relevant(&env, "rm -rf build && git reset --hard HEAD~1");
6082 assert_eq!(ctx.risk_level, RiskLevel::Critical);
6083 }
6084
6085 #[test]
6086 fn test_child_shell_sees_prefix_assignment() {
6087 let t = parse_command_targets("B=feature; B=main bash -c 'git push -f origin $B'");
6088 assert!(t.git_targets.contains(&"main".to_string()), "{t:?}");
6089 let t = parse_command_targets("B=main; B=feature bash -c 'git push -f origin $B'");
6090 assert_eq!(t.git_targets, vec!["feature".to_string()]);
6091 }
6092
6093 #[test]
6094 fn test_velero_argocd_and_tf_chdir_contexts() {
6095 let t = parse_command_targets("velero backup delete nightly --kubecontext prod-eu");
6096 assert_eq!(t.segments[0].k8s_context.as_deref(), Some("prod-eu"));
6097 assert!(t.mentions_k8s);
6098 let t = parse_command_targets("argocd app delete api --kube-context prod-eu");
6099 assert_eq!(t.segments[0].k8s_context.as_deref(), Some("prod-eu"));
6100 let t = parse_command_targets("argocd app delete api --server argocd.prod.example.com");
6101 assert_eq!(
6102 t.segments[0].cluster.as_deref(),
6103 Some("argocd.prod.example.com")
6104 );
6105 let t = parse_command_targets("terraform -chdir=$ENV destroy");
6106 assert!(t.segments[0].tf_dir_unknown);
6107 let t = parse_command_targets("ENV=envs/dev; terraform -chdir=$ENV destroy");
6108 assert!(!t.segments.iter().any(|s| s.tf_dir_unknown));
6109 }
6110
6111 #[test]
6112 fn test_literal_context_loop_is_not_a_failed_switch() {
6113 let env = env_with_k8s("dev");
6114 let ctx = relevant(
6115 &env,
6116 "for c in dev prod-eu; do kubectl --context $c delete deploy api; done",
6117 );
6118 assert_eq!(ctx.k8s_context.as_deref(), Some("prod-eu"));
6119 assert!(
6120 !ctx.labels.iter().any(|l| l.contains("may fail")),
6121 "{:?}",
6122 ctx.labels
6123 );
6124 }
6125
6126 #[test]
6127 fn test_target_dirs_are_bounded_and_normalized() {
6128 let cmd = "cd a && ".repeat(5000) + "rm -rf /";
6129 let dirs = command_target_dirs(&cmd);
6130 assert!(dirs.len() <= MAX_TARGET_DIRS, "{}", dirs.len());
6131 assert!(dirs
6132 .iter()
6133 .all(|d| d.as_os_str().len() <= MAX_TARGET_DIR_LEN));
6134 assert_eq!(
6135 command_target_dirs("cd a && cd .. && cd b"),
6136 vec![PathBuf::from("a"), PathBuf::from("."), PathBuf::from("b")]
6137 );
6138 assert!(command_target_dirs("env -C /srv/app make").contains(&PathBuf::from("/srv/app")));
6139 assert!(command_target_dirs("/srv/app/scripts/deploy prod")
6140 .contains(&PathBuf::from("/srv/app/scripts")));
6141 }
6142}