use super::{Role, gate};
use crate::parse::Token;
pub(crate) mod jj;
mod jq;
mod pax;
mod plist;
#[cfg(test)]
pub(super) const NAMES: &[&str] = &[
"ar_archive", "defaults_domain", "exiftool_mode", "jj_destination", "jj_repository", "jq_program", "jupytext_mode", "mtree_mode",
"ncu_mode", "pax_mode", "plutil_mode", "rdfind_mode", "textutil_mode", "tsc_response_file", "xattr_mode", "xcodebuild_settings",
"yq_program",
];
pub(super) fn dispatch(name: &str, tokens: &[Token]) -> bool {
match name {
"ar_archive" => ar_archive(tokens),
"defaults_domain" => plist::defaults_domain(tokens),
"exiftool_mode" => exiftool_mode(tokens),
"jj_destination" => jj::jj_destination(tokens),
"jj_repository" => jj::jj_repository(tokens),
"jq_program" => jq::jq_program(tokens),
"jupytext_mode" => jupytext_mode(tokens),
"mtree_mode" => mtree_mode(tokens),
"ncu_mode" => ncu_mode(tokens),
"pax_mode" => pax::pax_mode(tokens),
"plutil_mode" => plist::plutil_mode(tokens),
"rdfind_mode" => rdfind_mode(tokens),
"textutil_mode" => textutil_mode(tokens),
"tsc_response_file" => tsc_response_file(tokens),
"xattr_mode" => xattr_mode(tokens),
"xcodebuild_settings" => xcodebuild_settings(tokens),
"yq_program" => jq::yq_program(tokens),
_ => true,
}
}
fn ar_archive(tokens: &[Token]) -> bool {
let mut positionals: Vec<&str> = Vec::new();
let mut keys: Option<&str> = None;
let mut it = tokens[1..].iter().map(Token::as_str);
while let Some(t) = it.next() {
if t == "--plugin" || t == "--target" {
it.next(); continue;
}
if let Some(rest) = t.strip_prefix('-') {
if keys.is_none() && !t.starts_with("--") && !rest.is_empty() {
keys = Some(rest); }
continue; }
if keys.is_none() {
keys = Some(t); continue;
}
positionals.push(t);
}
let key_bytes = keys.map(str::as_bytes).unwrap_or_default();
let op = key_bytes.iter().copied().find(u8::is_ascii_alphabetic);
let archive_idx = usize::from(key_bytes.iter().any(|b| matches!(b, b'a' | b'b' | b'i')));
let Some(archive) = positionals.get(archive_idx) else { return false };
let archive_role = match op {
Some(b'r' | b'q' | b'd' | b'm' | b's') => Role::Write,
_ => Role::Read, };
if gate(archive_role, archive) {
return true;
}
matches!(op, Some(b'r' | b'q')) && positionals.iter().skip(archive_idx + 1).any(|m| gate(Role::Read, m))
}
fn tsc_response_file(tokens: &[Token]) -> bool {
tokens[1..].iter().filter_map(|t| t.as_str().strip_prefix('@')).any(|path| gate(Role::Read, path))
}
fn xattr_mode(tokens: &[Token]) -> bool {
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let writes = args.iter().any(|a| matches!(*a, "-w" | "-d" | "-c"));
let reads_values = args.iter().any(|a| matches!(*a, "-p" | "-l"));
if !writes && !reads_values {
return false; }
let role = if writes { Role::Write } else { Role::Read };
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "-w" {
it.next();
it.next();
continue;
}
if t == "-p" || t == "-d" {
it.next();
continue;
}
if t.starts_with('-') {
continue;
}
if gate(role, t) {
return true;
}
}
false
}
fn exiftool_mode(tokens: &[Token]) -> bool {
const VALUED: &[&str] = &["-o", "-tagsfromfile", "-api", "-charset", "-lang", "-@"];
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let assigns = args.iter().any(|a| a.starts_with('-') && a.contains('=') && !VALUED.contains(a));
let overwrites = args
.iter()
.any(|a| matches!(*a, "-overwrite_original" | "-overwrite_original_in_place" | "-delete_original"));
if !assigns && !overwrites {
let role = if args.iter().any(|a| a.eq_ignore_ascii_case("-r") || a.eq_ignore_ascii_case("-recurse")) {
Role::ReadTree
} else {
Role::Read
};
return args.iter().any(|a| !(a.starts_with('-') && *a != "-") && gate(role, a));
}
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "-o" {
if let Some(v) = it.next()
&& gate(Role::Write, v)
{
return true;
}
continue;
}
if VALUED.contains(&t) {
it.next(); continue;
}
if t.starts_with('-') {
continue;
}
if gate(Role::Write, t) {
return true;
}
}
false
}
fn rdfind_mode(tokens: &[Token]) -> bool {
const ACTIONS: &[&str] = &["-makesymlinks", "-makehardlinks", "-deleteduplicates"];
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let enabled = |flag: &str| args.windows(2).any(|w| w[0] == flag && w[1] == "true");
let acting = ACTIONS.iter().any(|f| enabled(f));
if !acting || enabled("-dryrun") {
return false; }
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t.starts_with('-') {
it.next(); continue;
}
if gate(Role::Write, t) {
return true;
}
}
false
}
fn mtree_mode(tokens: &[Token]) -> bool {
const VALUED: &[&str] = &["-f", "-K", "-k", "-p", "-s", "-N", "-X", "-R"];
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let writes = args.iter().any(|a| matches!(*a, "-u" | "-U" | "-r"));
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "-p" {
let role = if writes { Role::Write } else { Role::Read };
if let Some(v) = it.next()
&& gate(role, v)
{
return true;
}
continue;
}
if t == "-f" || t == "-X" {
if let Some(v) = it.next()
&& gate(Role::Read, v)
{
return true;
}
continue;
}
if VALUED.contains(&t) {
it.next();
}
}
false
}
fn ncu_mode(tokens: &[Token]) -> bool {
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let writes = args.iter().any(|a| matches!(*a, "--upgrade" | "-u"));
let role = if writes { Role::Write } else { Role::Read };
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "--packageFile"
&& let Some(v) = it.next()
&& gate(role, v)
{
return true;
}
}
false
}
fn jupytext_mode(tokens: &[Token]) -> bool {
const VALUED: &[&str] = &["--to", "--from", "--set-formats", "--output", "-o", "--pipe"];
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let writes = args
.iter()
.any(|a| matches!(*a, "--sync" | "--set-formats" | "--update-metadata" | "--to" | "-o" | "--output"));
let role = if writes { Role::Write } else { Role::Read };
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "--output" || t == "-o" {
if let Some(v) = it.next()
&& gate(Role::Write, v)
{
return true;
}
continue;
}
if VALUED.contains(&t) {
it.next(); continue;
}
if t.starts_with('-') {
continue;
}
if gate(role, t) {
return true;
}
}
false
}
fn textutil_mode(tokens: &[Token]) -> bool {
const VALUED: &[&str] = &["-format", "-encoding", "-extension", "-fontname", "-fontsize", "-inputencoding", "-output", "-outputdir"];
let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
let writes = args.iter().any(|a| *a == "-convert" || *a == "-strip");
let has_output = args.iter().any(|a| *a == "-output" || *a == "-outputdir");
let input_role = if writes && !has_output { Role::Write } else { Role::Read };
let mut it = args.iter().copied();
while let Some(t) = it.next() {
if t == "-output" || t == "-outputdir" {
if let Some(v) = it.next()
&& gate(Role::Write, v)
{
return true;
}
continue;
}
if VALUED.contains(&t) {
it.next(); continue;
}
if t.starts_with('-') {
continue; }
if gate(input_role, t) {
return true;
}
}
false
}
const XCODEBUILD_VALUED: &[&str] = &[
"-arch",
"-authenticationKeyID",
"-authenticationKeyIssuerID",
"-authenticationKeyPath",
"-clonedSourcePackagesDirPath",
"-archivePath",
"-buildVersion",
"-configuration",
"-defaultLanguage",
"-defaultPackageRegistryURL",
"-derivedDataPath",
"-destination",
"-destination-timeout",
"-exportFormat",
"-exportLanguage",
"-exportOptionsPlist",
"-exportPath",
"-find-executable",
"-find-library",
"-importComponent",
"-importPath",
"-jobs",
"-localizationPath",
"-maximum-concurrent-test-device-destinations",
"-maximum-concurrent-test-simulator-destinations",
"-maximum-parallel-testing-workers",
"-only-testing",
"-only-testing:TEST-IDENTIFIER",
"-onlyTesting",
"-packageAuthorizationProvider",
"-packageCachePath",
"-packageDependencySCMToRegistryTransformation",
"-packageFingerprintPolicy",
"-packageSigningEntityPolicy",
"-parallel-testing-enabled",
"-parallel-testing-worker-count",
"-prepareDeviceSupport",
"-project",
"-resultBundlePath",
"-resultBundleVersion",
"-resultStreamPath",
"-runDestination",
"-runDestinationTimeout",
"-scheme",
"-scmProvider",
"-sdk",
"-skip-testing",
"-skip-testing:TEST-IDENTIFIER",
"-skipTesting",
"-target",
"-test-enumeration-format",
"-test-enumeration-output-path",
"-test-enumeration-style",
"-test-iterations",
"-test-repetition-relaunch-enabled",
"-test-timeouts-enabled",
"-testLanguage",
"-testPlan",
"-testProductsPath",
"-testRegion",
"-toolchain",
"-workspace",
"-xcconfig",
"-xctestrun",
];
fn xcodebuild_settings(tokens: &[Token]) -> bool {
let mut i = 1;
while i < tokens.len() {
let t = tokens[i].as_str();
if t == "--" {
return tokens[i + 1..].iter().any(|token| xcodebuild_word_refused(token.as_str()));
}
if t.strip_prefix("-defaultPackageRegistryURL")
.is_some_and(|rest| rest.is_empty() || rest.starts_with('='))
{
return true;
}
if let Some(glued) = valued_assignment(t, XCODEBUILD_VALUED) {
i += if glued { 1 } else { 2 };
continue;
}
if t.starts_with('-') && t != "-" {
if t.split_once('=').is_some_and(|(_, value)| leaves_the_project(value)) {
return true;
}
i += 1;
continue;
}
if xcodebuild_word_refused(t) {
return true;
}
i += 1;
}
false
}
fn xcodebuild_word_refused(word: &str) -> bool {
matches!(word, "install" | "installsrc") || setting_key(word).is_some_and(names_a_tool_or_install_root) || leaves_the_project(word)
}
fn setting_key(word: &str) -> Option<&str> {
let end = word.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(word.len());
let key = &word[..end];
if key.is_empty() || key.starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
let mut rest = &word[end..];
while let Some(inner) = rest.strip_prefix('[') {
rest = &inner[inner.find(']')? + 1..];
}
rest.starts_with('=').then_some(key)
}
fn names_a_tool_or_install_root(key: &str) -> bool {
matches!(key, "CC" | "CXX" | "CPLUSPLUS" | "LD" | "LDPLUSPLUS" | "LIBTOOL" | "DSTROOT") || key.ends_with("_EXEC")
}
fn leaves_the_project(text: &str) -> bool {
text.contains(['/', '~', '$', '`']) || text.contains("..")
}
fn valued_assignment(token: &str, valued: &[&str]) -> Option<bool> {
valued.iter().find_map(|flag| {
if token == *flag { Some(false) } else { token.strip_prefix(flag).filter(|rest| rest.starts_with('=')).map(|_| true) }
})
}
#[cfg(test)]
mod tests {
fn allows(command: &str) -> bool {
crate::is_safe_command(command)
}
#[test]
fn a_build_setting_that_names_a_compiler_or_an_install_root_asks() {
for command in [
"xcodebuild build CC=/tmp/y/evil",
"xcodebuild build LD=/tmp/y/evil",
"xcodebuild build SWIFT_EXEC=/tmp/y/evil",
"xcodebuild build DSTROOT=/etc",
"xcodebuild build DSTROOT=/etc install",
"xcodebuild install",
"xcodebuild installsrc",
"xcodebuild -toolchain /tmp/y/Evil.xctoolchain build",
"xcodebuild -xcconfig /tmp/y/evil.xcconfig build",
] {
assert!(!allows(command), "{command}");
}
for command in [
"xcodebuild -project Foo.xcodeproj -scheme Foo -configuration Debug -destination 'platform=macOS' build CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY=\"\"",
"xcodebuild -workspace Foo.xcworkspace -scheme Foo -configuration Release archive -archivePath build/Foo.xcarchive",
"xcodebuild -project Foo.xcodeproj -scheme Foo test -destination 'platform=iOS Simulator,name=iPhone 15' -enableCodeCoverage",
"xcodebuild -project Foo.xcodeproj -scheme Foo clean",
"xcodebuild -project Foo.xcodeproj -scheme Foo analyze",
"xcodebuild -project Foo.xcodeproj -scheme Foo docbuild",
"xcodebuild -scheme install build",
"xcodebuild -destination 'platform=macOS' build",
"xcodebuild -xcconfig Config.xcconfig build",
"xcodebuild -toolchain Local.xctoolchain build",
"xcodebuild build CODE_SIGNING_ALLOWED=NO",
] {
assert!(allows(command), "{command}");
}
}
#[test]
fn a_build_setting_is_judged_by_its_shape_wherever_it_sits() {
for command in [
"xcodebuild build CPLUSPLUS=/tmp/y/evil",
"xcodebuild build LDPLUSPLUS=/tmp/y/evil",
"xcodebuild build LIBTOOL=/tmp/y/evil",
"xcodebuild build CXX=evil",
"xcodebuild build CC=clang-evil",
"xcodebuild build SWIFT_FRONTEND_EXEC=evil",
"xcodebuild build OTHER_CFLAGS=-fplugin=/tmp/y/x.dylib",
"xcodebuild build OTHER_SWIFT_FLAGS=-load-plugin-executable=/tmp/y/evil",
"xcodebuild build SYMROOT=/etc/x",
"xcodebuild build CONFIGURATION_BUILD_DIR=/tmp/y",
"xcodebuild build OBJROOT=/tmp/y",
"xcodebuild build SDKROOT=/tmp/y/evil.sdk",
"xcodebuild build 'SYMROOT=$(HOME)/x'",
"xcodebuild build SYMROOT=~",
"xcodebuild build SYMROOT=..",
"xcodebuild build 'OTHER_CFLAGS[sdk=macosx*]=-fplugin=/tmp/y/x.dylib'",
"xcodebuild -exportArchive CC=/tmp/y/evil build",
"xcodebuild -exportLocalizations CC=/tmp/y/evil build",
"xcodebuild -importLocalizations DSTROOT=/etc build",
"xcodebuild -exportNotarizedApp CC=/tmp/y/evil build",
"xcodebuild -retry-tests-on-failure CC=/tmp/y/evil test",
"xcodebuild build -- CC=/tmp/y/evil",
"xcodebuild -someNewFlag /tmp/y build",
"xcodebuild -someNewFlag=/tmp/y build",
] {
assert!(!allows(command), "{command}");
}
for command in [
"xcodebuild build ONLY_ACTIVE_ARCH=YES",
"xcodebuild build OTHER_LDFLAGS=-ObjC",
"xcodebuild build 'GCC_PREPROCESSOR_DEFINITIONS=DEBUG=1 FOO'",
"xcodebuild build 'ARCHS[sdk=iphonesimulator*]=arm64'",
"xcodebuild build TOOLCHAINS=swift",
"xcodebuild -exportArchive -archivePath build/Foo.xcarchive -exportPath build/out -exportOptionsPlist Export.plist",
"xcodebuild -scheme Foo test -only-testing FooTests/testBar",
"xcodebuild -scheme Foo test -retry-tests-on-failure -test-iterations 3",
] {
assert!(allows(command), "{command}");
}
}
#[test]
fn every_path_flag_is_gated_by_what_the_build_does_with_it() {
for command in [
"xcodebuild -resultStreamPath /etc/x build",
"xcodebuild -testProductsPath /etc/x build-for-testing",
"xcodebuild -testProductsPath /tmp/y/x.xctestproducts test-without-building",
"xcodebuild -test-enumeration-output-path /etc/x test",
"xcodebuild -exportLocalizations -localizationPath /etc/x",
"xcodebuild -importPath ~/.ssh/id_rsa -importComponent x",
"xcodebuild -packageCachePath /tmp/y build",
"xcodebuild -clonedSourcePackagesDirPath /tmp/y build",
"xcodebuild -derivedDataPath /tmp/y build",
"xcodebuild -sdk /tmp/y/evil.sdk build",
"xcodebuild -defaultPackageRegistryURL https://evil.example build",
"xcodebuild -defaultPackageRegistryURL evil.example build",
"xcodebuild -defaultPackageRegistryURL=https://evil.example build",
"xcodebuild -authenticationKeyPath ~/.ssh/id_rsa -allowProvisioningUpdates build",
] {
assert!(!allows(command), "{command}");
}
for command in [
"xcodebuild -resultStreamPath build/stream.json build",
"xcodebuild -derivedDataPath build/DerivedData build",
"xcodebuild -clonedSourcePackagesDirPath build/SourcePackages build",
"xcodebuild -sdk iphonesimulator build",
"xcodebuild -exportLocalizations -localizationPath build/loc -exportLanguage de",
"xcodebuild -testProductsPath build/Foo.xctestproducts test-without-building",
] {
assert!(allows(command), "{command}");
}
}
#[test]
fn the_handler_skips_exactly_the_declared_valued_flags() {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/commands/xcode/xcodebuild.toml")).expect("toml file");
let doc: toml::Value = text.parse().expect("toml");
let command = &doc["command"][0];
let list = |key: &str| -> Vec<String> {
let mut names: Vec<String> = command[key]
.as_array()
.expect("a flag list")
.iter()
.map(|v| v.as_str().expect("flag").to_string())
.collect();
names.sort();
names
};
let mut handler: Vec<String> = super::XCODEBUILD_VALUED.iter().map(|s| (*s).to_string()).collect();
handler.sort();
assert_eq!(handler, list("valued"));
for boolean in ["-exportArchive", "-exportLocalizations", "-importLocalizations", "-exportNotarizedApp", "-retry-tests-on-failure"]
{
assert!(list("standalone").iter().any(|f| f == boolean), "{boolean} is not standalone");
}
}
}