fix(validation): restore isolated local checks

This commit is contained in:
2026-10-30 04:21:56 -03:00
parent 82188e8731
commit 3151b0c7dd
36 changed files with 586 additions and 227 deletions
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Inert macOS command fixtures; mutable plist operations stay in the suite root."""
import json
import os
import pathlib
import plistlib
import shlex
import subprocess
import sys
name = pathlib.Path(sys.argv[0]).name
args = sys.argv[1:]
root = pathlib.Path(os.environ["UNLEASH_TEST_ROOT"]).resolve()
with (root / "platform-calls.jsonl").open("a") as log:
log.write(json.dumps([name, *args]) + "\n")
def fixture_path(value):
path = pathlib.Path(value).resolve()
if not path.is_relative_to(root):
sys.exit(f"Fixture refused path outside the suite: {path}")
return path
if name == "sudo":
if len(args) >= 2 and ((args[0] == "profiles" and args[1] in ("-C", "status"))
or (args[0] == "security" and args[1] == "find-identity")):
sys.exit(subprocess.call([str(pathlib.Path(sys.argv[0]).with_name(args[0])), *args[1:]]))
elif name == "profiles":
if args[:1] == ["-C"]:
sys.stdout.buffer.write(plistlib.dumps([]))
sys.exit(0)
if args[:1] == ["status"]:
print("MDM enrollment: No")
sys.exit(0)
elif name == "security" and args[:1] == ["find-identity"]:
sys.exit(0)
elif name == "plutil" and args[:4] == ["-convert", "xml1", "-o", "-"]:
sys.stdout.buffer.write(plistlib.dumps(plistlib.loads(fixture_path(args[-1]).read_bytes())))
sys.exit(0)
elif name == "PlistBuddy":
path = fixture_path(args[-1])
data = plistlib.loads(path.read_bytes())
command = shlex.split(args[1])
action = command[0]
key = command[1].lstrip(":") if len(command) > 1 else None
if action == "Print":
if key:
print(str(data[key]).lower())
else:
sys.stdout.buffer.write(plistlib.dumps(data))
sys.exit(0)
if action == "Add" and key in data:
sys.exit(1)
if action == "Set" and key not in data:
sys.exit(1)
if action in ("Add", "Set"):
data[key] = command[-1] == "true"
elif action == "Delete":
data.pop(key, None)
else:
sys.exit(97)
path.write_bytes(plistlib.dumps(data))
sys.exit(0)
elif name == "launchctl" and args[:1] in (["load"], ["unload"]):
fixture_path(args[-1])
sys.exit(0)
elif name == "host" and args[:2] == ["-t", "a"]:
print(f"{args[2]} has address 203.0.113.10")
sys.exit(0)
elif name == "dscl":
fixture_path(args[1])
sys.exit(1)
elif name in ("diskutil", "pgrep", "pkill", "curl", "pfctl", "host"):
sys.exit(1)
print(f"Blocked platform operation in test: {name} {' '.join(args)}", file=sys.stderr)
sys.exit(97)
+20
View File
@@ -0,0 +1,20 @@
setup_suite() {
local suite_dir
suite_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export UNLEASH_TEST_ROOT="$BATS_SUITE_TMPDIR"
export TMPDIR="$UNLEASH_TEST_ROOT/tmp"
local mock_bin="$UNLEASH_TEST_ROOT/bin"
mkdir -p "$TMPDIR" "$mock_bin"
local tool
for tool in sudo diskutil profiles security launchctl pfctl pkill pgrep killall \
dscacheutil defaults curl host plutil PlistBuddy dscl fdesetup chflags \
osascript ioreg ifconfig systemextensionsctl networksetup; do
cp "$suite_dir/helpers/platform.py" "$mock_bin/$tool"
chmod +x "$mock_bin/$tool"
done
export PATH="$mock_bin:$PATH"
export PB="$mock_bin/PlistBuddy"
export VERSION=2.0.0
export SCRIPT_DIR="$suite_dir/.."
export LIB_DIR="$SCRIPT_DIR/lib"
}
+7
View File
@@ -39,3 +39,10 @@ teardown() {
[ "$status" -eq 0 ]
echo "$output" | grep -q "Test Title"
}
@test "header draws a valid Unicode border for the title width" {
run header Mac
[ "$status" -eq 0 ]
[[ "$output" == *"╔═══════╗"* ]]
[[ "$output" == *"╚═══════╝"* ]]
}
+19
View File
@@ -35,3 +35,22 @@ teardown() {
run grep -c "KEY=new" "$CONFIG_FILE"
[ "$output" -eq 1 ]
}
@test "config preserves spaces and literal replacement characters" {
local value='/tmp/Unleash logs/quoted "name" & \tail'
save_config LOG_FILE old
save_config LOG_FILE "$value"
LOG_FILE=''
load_config
[ "$LOG_FILE" = "$value" ]
}
@test "config unset preserves other keys" {
save_config WEBHOOK 'https://example.com/a?x=1&y=2'
save_config LOG_LEVEL verbose
run cmd_config config unset LOG_LEVEL
[ "$status" -eq 0 ]
run grep -c '^LOG_LEVEL=' "$CONFIG_FILE"
[ "$status" -eq 1 ]
grep -q '^WEBHOOK=https://example.com/a?x=1&y=2$' "$CONFIG_FILE"
}
+10 -10
View File
@@ -5,14 +5,11 @@ setup() {
load '../lib/detect.sh'
}
@test "is_root returns true when EUID is 0" {
[ "$EUID" -eq 0 ] && skip "Already root"
[ "$EUID" -ne 0 ] && skip "Not root"
}
@test "is_root returns false when EUID is not 0" {
[ "$EUID" -ne 0 ] && skip "Not root (expected)"
[ "$EUID" -eq 0 ] && skip "Is root"
@test "is_root reports whether the effective user is root" {
local expected=1
[ "$EUID" -ne 0 ] || expected=0
run is_root
[ "$status" -eq "$expected" ]
}
@test "is_recovery returns false in normal environment" {
@@ -26,6 +23,9 @@ setup() {
}
@test "resolve_data_volume errors on non-existent device" {
run resolve_data_volume 2>/dev/null || true
[ "$status" -eq 0 ]
read() { echo PROMPT_WAS_REACHED; return 1; }
run resolve_data_volume </dev/null
[ "$status" -ne 0 ]
[[ "$output" == *"Cannot select a Data volume without a terminal"* ]]
[[ "$output" != *"PROMPT_WAS_REACHED"* ]]
}
+7 -1
View File
@@ -6,8 +6,14 @@ setup() {
}
@test "harden_live_os exits cleanly" {
run harden_live_os 2>/dev/null || true
mkdir -p "$BATS_TEST_TMPDIR/Users/test/Library/LaunchAgents"
local agents="$BATS_TEST_TMPDIR/Users/test/Library/LaunchAgents"
echo mdm > "$agents/enrollment.plist"
echo normal > "$agents/normal.plist"
run harden_live_os "$BATS_TEST_TMPDIR"
[ "$status" -eq 0 ]
[ ! -f "$agents/enrollment.plist" ]
[ -f "$agents/normal.plist" ]
}
@test "harden_status exits cleanly" {
+4 -2
View File
@@ -6,11 +6,13 @@ setup() {
}
@test "show_history exits cleanly with no logs" {
run show_history 2>/dev/null || true
run show_history "$BATS_TEST_TMPDIR"
[ "$status" -eq 0 ]
}
@test "clear_history does not error with no logs" {
run clear_history 2>/dev/null || true
echo event > "$BATS_TEST_TMPDIR/unleash-monitor.log"
run clear_history "$BATS_TEST_TMPDIR"
[ "$status" -eq 0 ]
[ ! -s "$BATS_TEST_TMPDIR/unleash-monitor.log" ]
}
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bats
setup() {
PROJECT="$BATS_TEST_TMPDIR/project"
mkdir -p "$PROJECT/scripts" "$PROJECT/lib"
cp "$BATS_TEST_DIRNAME/../scripts/check-shell.py" "$PROJECT/scripts/"
cat > "$PROJECT/unleash" <<'SH'
#!/bin/bash
for _lib in sample; do
source "lib/$_lib.sh"
done
sample
SH
printf 'sample() { :; }\n' > "$PROJECT/lib/sample.sh"
printf '#!/bin/bash\n' > "$PROJECT/unleash-standalone.sh"
}
@test "lint reports sourced module findings without executing the application" {
export LINT_TEST_MARKER="$BATS_TEST_TMPDIR/app-executed"
printf 'sample() { echo $missing; }\n: > "$LINT_TEST_MARKER"\n' > "$PROJECT/lib/sample.sh"
run python3 "$PROJECT/scripts/check-shell.py"
[ "$status" -ne 0 ]
[[ "$output" == *"lib/sample.sh:1:"* ]]
[[ "$output" == *"SC2086"* ]]
[ ! -f "$LINT_TEST_MARKER" ]
}
@test "lint checks syntax in every library" {
printf 'sample() {\n' > "$PROJECT/lib/sample.sh"
run python3 "$PROJECT/scripts/check-shell.py"
[ "$status" -ne 0 ]
[[ "$output" == *"sample.sh"* ]]
}
@test "lint does not install tools after an analysis failure" {
cp "$BATS_TEST_DIRNAME/../Makefile" "$PROJECT/Makefile"
local mock_bin="$BATS_TEST_TMPDIR/lint-bin"
mkdir -p "$mock_bin"
ln -s "$(command -v python3)" "$mock_bin/python3"
ln -s "$(command -v bash)" "$mock_bin/bash"
printf '#!/bin/sh\nprintf "[]"\nexit 1\n' > "$mock_bin/shellcheck"
export TEST_BREW_MARKER="$BATS_TEST_TMPDIR/brew-called"
printf '#!/bin/sh\n: > "$TEST_BREW_MARKER"\n' > "$mock_bin/brew"
chmod +x "$mock_bin/shellcheck" "$mock_bin/brew"
run env PATH="$mock_bin" "$(command -v make)" -C "$PROJECT" lint
[ "$status" -ne 0 ]
[ ! -f "$TEST_BREW_MARKER" ]
}
+14 -2
View File
@@ -3,14 +3,26 @@
setup() {
load '../lib/colors.sh'
load '../lib/ma_detect.sh'
mkdir -p "$BATS_TEST_TMPDIR/Users"
}
@test "detect_migration_assistant exits cleanly" {
run detect_migration_assistant 2>/dev/null || true
run detect_migration_assistant "$BATS_TEST_TMPDIR"
[ "$status" -eq 0 ]
}
@test "clean_ma_artifacts does not error without users" {
run clean_ma_artifacts 2>/dev/null || true
run clean_ma_artifacts "$BATS_TEST_TMPDIR"
[ "$status" -eq 0 ]
}
@test "migration audit detects enrollment and MDM cache directories" {
local caches="$BATS_TEST_TMPDIR/Users/test/Library/Caches"
mkdir -p "$caches/com.apple.enrollmenttool" "$caches/com.apple.mdm"
echo cached > "$caches/com.apple.enrollmenttool/record"
echo cached > "$caches/com.apple.mdm/record"
run detect_migration_assistant "$BATS_TEST_TMPDIR"
[ "$status" -eq 1 ]
[[ "$output" == *"enrollment cache files"* ]]
[[ "$output" == *"MDM cache files"* ]]
}
+2 -2
View File
@@ -11,12 +11,12 @@ teardown() {
}
@test "monitor_status exits cleanly when not running" {
run monitor_status 2>/dev/null || true
run monitor_status "$TEST_DIR/monitor.pid"
[ "$status" -eq 0 ]
}
@test "stop_monitor exits cleanly when not running" {
run stop_monitor 2>/dev/null || true
run stop_monitor "$TEST_DIR/monitor.pid"
[ "$status" -eq 0 ]
}
+13
View File
@@ -26,3 +26,16 @@ teardown() {
run deep_status_json 2>/dev/null || true
echo "$output" | grep -q "}"
}
@test "deep_status_json counts a single matching process without subtracting it" {
profiles() {
if [ "$1" = -C ]; then echo '<key>ProfileDisplayName</key>';
else echo 'MDM enrollment: No'; fi
}
sudo() { "$@"; }
pgrep() { echo '42 mdmclient'; }
ps() { echo 'test 42 0.0 0.0 1 1 ? S 00:00 0:00 mdmclient'; }
run deep_status_json
[ "$status" -eq 0 ]
echo "$output" | python3 -c 'import json,sys; assert json.load(sys.stdin)["running_mdm_processes"] == 1'
}
+7 -1
View File
@@ -38,10 +38,16 @@ teardown() {
suppress_enrollment "$TEST_DIR" 2>/dev/null || true
local ldp="$TEST_DIR/private/var/db/com.apple.xpc.launchd/disabled.plist"
[ -f "$ldp" ]
run /usr/libexec/PlistBuddy -c "Print :com.apple.ManagedClient.enroll" "$ldp" 2>/dev/null
run "$PB" -c "Print :com.apple.ManagedClient.enroll" "$ldp"
[ "$output" = "true" ]
}
@test "PlistBuddy fixture rejects writes outside the test suite" {
run "$PB" -c 'Add :test bool true' "$BATS_TEST_DIRNAME/../README.md"
[ "$status" -ne 0 ]
[[ "$output" == *"Fixture refused path outside the suite"* ]]
}
@test "dry-run mode does not write files" {
DRY_RUN=true
suppress_enrollment "$TEST_DIR" 2>/dev/null || true