use std::collections::HashSet;
use serde::Deserialize;
use super::{Role, gate};
use crate::parse::Token;
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct Chdir {
flag: String,
#[serde(default)]
valued: HashSet<String>,
}
fn dirs<'a>(spec: &Chdir, tokens: &'a [Token]) -> Vec<&'a str> {
let mut out = Vec::new();
let mut i = 1;
while i < tokens.len() {
let t = tokens[i].as_str();
if t == spec.flag {
out.extend(tokens.get(i + 1).map(Token::as_str));
i += 2;
} else if let Some(v) = t.strip_prefix(spec.flag.as_str()).and_then(|r| r.strip_prefix('=')) {
out.push(v);
i += 1;
} else if spec.valued.contains(t) {
i += 2;
} else if t.starts_with('-') {
i += 1;
} else {
break;
}
}
out
}
fn moved(cur: Option<String>, dir: &str) -> Option<String> {
crate::pathctx::join_cwd(cur.as_deref(), dir)
.or_else(|| if dir.split('/').any(|seg| seg == "..") { Some(crate::pathctx::UNRESOLVED_CWD.to_string()) } else { cur })
}
pub(super) fn should_deny(spec: Option<&Chdir>, tokens: &[Token], rest: impl FnOnce() -> bool) -> bool {
let Some(spec) = spec else { return rest() };
let named = dirs(spec, tokens);
if named.is_empty() {
return rest();
}
let mut cwd = crate::pathctx::cwd();
for dir in named.into_iter().filter(|d| !d.is_empty()).map(spelled) {
let _here = crate::pathctx::enter_cwd(cwd.clone());
if gate(Role::Read, &dir) {
return true;
}
cwd = moved(cwd.clone(), &dir);
}
let _there = crate::pathctx::enter_cwd(cwd);
rest()
}
pub(crate) fn landing(cmd: &str, tokens: &[Token]) -> Option<String> {
let mut cwd = crate::pathctx::cwd();
for dir in super::GATES
.chdir
.get(cmd)
.map(|spec| dirs(spec, tokens))
.unwrap_or_default()
.into_iter()
.filter(|d| !d.is_empty())
.map(spelled)
{
cwd = moved(cwd, &dir);
}
cwd
}
pub(crate) fn moved_into(cur: Option<String>, dir: &str) -> Option<String> {
moved(cur, &spelled(dir))
}
fn spelled(dir: &str) -> String {
for (var, as_path) in [("$PWD", "."), ("${PWD}", "."), ("$HOME", "~"), ("${HOME}", "~")] {
if let Some(rest) = dir.strip_prefix(var)
&& (rest.is_empty() || rest.starts_with('/'))
{
return format!("{as_path}{rest}");
}
}
dir.to_string()
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::{Chdir, dirs};
use crate::parse::Token;
use crate::pathctx::PathCtx;
const ROOT: &str = "/work/projects/app";
fn toks(words: &[&str]) -> Vec<Token> {
words.iter().map(|w| Token::from_raw((*w).to_string())).collect()
}
fn git() -> Chdir {
Chdir { flag: "-C".into(), valued: ["-c".to_string()].into() }
}
fn denied(cmd: &str) -> bool {
let ctx = PathCtx { cwd: Some(ROOT.into()), root: Some(ROOT.into()), session_id: None };
!crate::command_verdict_in(cmd, ctx).is_allowed()
}
#[test]
fn the_scan_collects_every_global_directory_and_stops_at_the_subcommand() {
let t = toks(&["git", "-c", "-C", "-C", "a", "-C=b", "grep", "-C", "3", "x"]);
assert_eq!(dirs(&git(), &t), vec!["a", "b"]);
assert!(dirs(&git(), &toks(&["git", "grep", "-C", "/etc", "x"])).is_empty());
}
#[test]
fn a_relative_operand_is_judged_where_the_command_moved_to() {
for cmd in [
"git -C /etc diff shadow", "git -C /etc diff --no-index shadow /dev/null", "git -C / diff etc/shadow",
"git -C /etc -C . diff shadow", "git -C / -C etc diff shadow", "git -C ~ diff --no-index .ssh/id_rsa /dev/null",
"git -C /etc diff -O shadow", "git -C /etc grep -f shadow x", "git -C sub diff ../../../../etc/shadow",
] {
assert!(denied(cmd), "{cmd}");
}
}
#[test]
fn the_directory_itself_is_gated_as_a_read() {
for cmd in ["git -C ~/.ssh log", "git -C ~/.aws status", "git -C $DIR log -p", "git -C ~/.gnupg log -p"] {
assert!(denied(cmd), "{cmd}");
}
for cmd in ["git -C $HOME/.ssh log -p", "git -C ${HOME}/.aws status", "git -C $PWD/../../../etc diff shadow"] {
assert!(denied(cmd), "{cmd}");
}
for cmd in ["git -C /some/repo status", "git -C ~/projects/other log -p", "git -C $HOME status"] {
assert!(denied(cmd), "{cmd}: a repository outside the project carries its own configuration");
}
assert!(!denied("git -C \"$PWD\" log --oneline"));
}
#[test]
fn ordinary_moves_inside_the_workspace_still_approve() {
for cmd in ["git -C sub diff src/x.rs", "git -C . log --oneline", "git -C sub/dir status", "git -C sub grep -n pat"] {
assert!(!denied(cmd), "{cmd}");
}
}
#[test]
fn a_climb_from_an_unknown_cwd_is_left_unresolved() {
assert_eq!(super::moved(None, "sub"), None);
assert_eq!(super::moved(None, "../x").as_deref(), Some(crate::pathctx::UNRESOLVED_CWD));
assert_eq!(super::moved(None, "/etc").as_deref(), Some("/etc"));
assert_eq!(super::moved(Some(ROOT.into()), "sub").as_deref(), Some("/work/projects/app/sub"));
}
proptest! {
#[test]
fn a_move_and_an_operand_judge_as_their_join(
dir in prop::sample::select(vec!["/etc", "/", "~", "~/.ssh", "sub", "..", "../..", "/tmp", "/work/projects"]),
file in prop::sample::select(vec!["shadow", "etc/shadow", ".ssh/id_rsa", "id_rsa", "x.rs", "../etc/passwd", "hosts"]),
) {
let moved = format!("git -C {dir} diff --no-index {file} /dev/null");
let joined = format!("git diff --no-index {dir}/{file} /dev/null");
prop_assert!(denied(&moved) || !denied(&joined), "{moved} approved while {joined} denies");
}
}
}