feat: unify scf discovery and fix shell tooling bugs

- scf: discover referenced text files with source-based ordering; cache canonical paths and bound scans, parsing and candidate display
- config: rewrite config includes atomically
- installer: preserve configuration contents, permissions and links; fix dry-run
- updater: recover stale updater scripts and report update failures
- riot: fix riot batches, dry runs, empty arguments and IPv6 SCP paths
- frigg: propagate Frigg authentication failures
- add offline regression tests and CI coverage

Signed-off-by: Dict Xiong <me@dxng.cn>
This commit is contained in:
Dict Xiong
2026-11-18 09:25:33 +08:00
parent 02ea21c839
commit 277c124d3b
13 changed files with 1834 additions and 251 deletions

View File

@@ -55,6 +55,7 @@ handle_resp()
fmt_info "try to register you hostname and uuid"
fmt_info "hostname: $hostname"
fmt_info "uuid: $uuid"
return 1
else
echo $resp >&2
fmt_fatal "server returned an error"

62
tools/test-frigg-client.sh Executable file
View File

@@ -0,0 +1,62 @@
#!/usr/bin/env bash
set -euo pipefail
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
fixture=$(mktemp -d "${TMPDIR:-/tmp}/frigg-client.XXXXXXXX")
trap 'rm -rf -- "$fixture"' EXIT
mock_bin="$fixture/bin"
test_home="$fixture/home"
mkdir -p "$mock_bin" "$test_home/.config/dotfiles"
printf 'fixture-uuid\n' > "$test_home/.config/dotfiles/uuid"
# Restrict PATH to the mock curl and the commands needed by the client.
for tool in bash dirname tr grep cat; do
ln -s "$(command -v "$tool")" "$mock_bin/$tool"
done
cat > "$mock_bin/curl" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$MOCK_RESPONSE"
exit "$MOCK_CURL_STATUS"
EOF
chmod +x "$mock_bin/curl"
run_client() {
env -i HOME="$test_home" PATH="$mock_bin" DFS_HOSTNAME=fixture.invalid \
DFS_DDNS_IP4=auto MOCK_RESPONSE="$response" MOCK_CURL_STATUS="$curl_status" \
"$mock_bin/bash" "$source_dir/frigg-client.sh" "$@"
}
expect_failure() {
local expected_status=$1
shift
local status=0
run_client "$@" > "$fixture/stdout" 2> "$fixture/stderr" || status=$?
if [[ $status -ne $expected_status ]]; then
printf 'Expected exit %s, got %s for %s\n' "$expected_status" "$status" "$*" >&2
exit 1
fi
}
for operation in beacon ddns; do
response=200
curl_status=0
run_client "$operation" fixture.beacon > "$fixture/stdout" 2> "$fixture/stderr"
grep -Fxq '200' "$fixture/stdout"
# A rejected request must reach the caller as a failure.
response=403
expect_failure 1 "$operation" fixture.beacon
[[ ! -s "$fixture/stdout" ]]
grep -Fq 'authentification failed' "$fixture/stderr"
response=500
expect_failure 1 "$operation" fixture.beacon
grep -Fq 'server returned an error' "$fixture/stderr"
# Transport failures retain curl's exit status, even with a success body.
response=200
curl_status=22
expect_failure 22 "$operation" fixture.beacon
done
echo 'frigg client tests passed'

245
tools/test-install.sh Executable file
View File

@@ -0,0 +1,245 @@
#!/usr/bin/env bash
set -euo pipefail
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
fixture=$(mktemp -d)
trap 'rm -rf -- "$fixture"' EXIT
test_home="$fixture/home"
remote="$fixture/remote"
client="$test_home/dotfiles"
mock_bin="$fixture/bin"
real_git=$(command -v git)
real_cat=$(command -v cat)
real_stat=$(command -v stat)
mkdir -p "$test_home" "$remote" "$mock_bin"
git -C "$source_dir" archive HEAD | tar -x -C "$remote"
cp "$source_dir/install.sh" "$source_dir/.update.sh" "$source_dir/.gitignore" "$remote/"
env GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -C "$remote" init -q -b dev
git -C "$remote" add .
env GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -C "$remote" \
-c user.name=Fixture -c user.email=fixture@example.invalid \
-c commit.gpgsign=false commit -qm fixture
git clone -q "$remote" "$client"
release=$(git -C "$client" rev-parse HEAD)
cat > "$mock_bin/curl" <<'EOF'
#!/usr/bin/env bash
printf 'curl\n' >> "$TEST_CALLS"
printf '%s\n' "$TEST_RELEASE"
EOF
cat > "$mock_bin/git" <<'EOF'
#!/usr/bin/env bash
case "$1" in
fetch) printf 'fetch\n' >> "$TEST_CALLS" ;;
clone) echo 'unexpected plugin clone' >&2; exit 1 ;;
esac
exec "$TEST_GIT" "$@"
EOF
cat > "$mock_bin/crontab" <<'EOF'
#!/usr/bin/env bash
printf 'crontab %s\n' "$*" >> "$TEST_CALLS"
case "$1" in
-l) [[ -f "$TEST_CRONTAB" ]] && cat "$TEST_CRONTAB" ;;
-) cat > "$TEST_CRONTAB" ;;
*) exit 1 ;;
esac
EOF
cat > "$mock_bin/cat" <<'EOF'
#!/usr/bin/env bash
if [[ "$1" == "$TEST_WRITE_TARGET".???????? ]]; then
case "$TEST_FAIL_WRITE" in
1|2) printf 'partial write\n'; exit 74 ;;
HUP|INT|TERM|TERM-restore-failure)
printf 'partial write\n'
printf 'signal %s\n' "$TEST_FAIL_WRITE" >> "$TEST_CALLS"
kill -s "${TEST_FAIL_WRITE%%-*}" "$PPID"
exit 0
;;
esac
fi
if [[ ( "$TEST_FAIL_WRITE" == 2 || "$TEST_FAIL_WRITE" == TERM-restore-failure ) \
&& "$1" == "$TEST_WRITE_TARGET".backup.???????? ]]; then
exit 75
fi
exec "$TEST_CAT" "$@"
EOF
cat > "$mock_bin/stat" <<'EOF'
#!/usr/bin/env bash
if [[ "$TEST_BSD_STAT" == 1 ]]; then
case "$1" in
-c) exit 1 ;;
-f) shift 2; exec "$TEST_STAT" -c '%h' "$@" ;;
esac
fi
exec "$TEST_STAT" "$@"
EOF
for command in ping vim tmux zsh; do
printf '#!/usr/bin/env bash\necho "unexpected dependency execution" >&2\nexit 1\n' > "$mock_bin/$command"
done
chmod +x "$mock_bin/"*
: > "$fixture/calls"
run_install() {
env -i HOME="$test_home" PATH="$mock_bin:$PATH" \
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \
DFS_IGNORE_COMMIT_SIGN=1 DFS_ORPHAN=1 DFS_UPDATE_CHANNEL=dev \
TEST_CALLS="$fixture/calls" TEST_RELEASE="$release" \
TEST_GIT="$real_git" TEST_CRONTAB="$fixture/crontab" \
TEST_CAT="$real_cat" TEST_STAT="$real_stat" \
TEST_WRITE_TARGET="$test_home/.tmux.conf" \
TEST_FAIL_WRITE="${TEST_FAIL_WRITE:-0}" TEST_BSD_STAT="${TEST_BSD_STAT:-0}" \
bash "$client/install.sh" "$@" > "$fixture/output" 2>&1
}
expect_failure() {
if run_install "$@"; then
echo "expected installer to reject arguments: $*" >&2
exit 1
fi
}
# Dry-run must avoid dependency installation, remote requests, files, and prompts.
run_install -a --dry-run -x 'DFS_AUDIT_VALUE=hello world'
grep -Fq 'dry run: install' "$fixture/output"
run_install -r --dry-run < /dev/null
grep -Fq 'dry run: uninstall' "$fixture/output"
[[ ! -s "$fixture/calls" && ! -e "$fixture/crontab" ]]
[[ ! -e "$client/update.sh" && ! -e "$test_home/.zshrc" && ! -e "$test_home/.config" ]]
expect_failure -x
expect_failure -H
expect_failure --dry-run -x 'BAD-KEY=value'
[[ ! -s "$fixture/calls" ]]
mkdir -p "$test_home/state" "$test_home/.vim/bundle/Vundle.vim" \
"$test_home/.tmux/plugins/tpm" "$test_home/.config/dotfiles"
printf '# user configuration without newline' > "$test_home/state/zshrc"
chmod 640 "$test_home/state/zshrc"
ln "$test_home/state/zshrc" "$test_home/state/zshrc-linked"
ln -s state/zshrc "$test_home/.zshrc"
printf 'set -g history-limit 99\n' > "$test_home/.tmux.conf"
chmod 640 "$test_home/.tmux.conf"
ln "$test_home/.tmux.conf" "$test_home/state/tmux-linked"
printf 'source ~/dotfiles/.vimrc2\n' > "$test_home/.vimrc"
printf '[user]\n email = local@example.invalid\n' > "$test_home/.gitconfig"
printf 'SOURCED_VALUE="local source"\n' > "$test_home/state/local-env"
cat > "$test_home/.config/dotfiles/env" <<'EOF'
# local settings
KEEP_VALUE="keep me"
source "$HOME/state/local-env"
DFS_AUDIT_VALUE="old
multiline value"
if true; then
DFS_AUDIT_VALUE=conditional
fi
EOF
cp "$test_home/.config/dotfiles/env" "$fixture/original-env"
# Preserve hard links, including a relative symlink to a hard-linked target.
# Emulate BSD stat here to exercise the macOS link-count fallback.
TEST_BSD_STAT=1 run_install -q -x 'DFS_AUDIT_VALUE=hello world'
[[ -L "$test_home/.zshrc" && "$(readlink "$test_home/.zshrc")" == state/zshrc ]]
[[ "$test_home/.zshrc" -ef "$test_home/state/zshrc-linked" ]]
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
[[ "$(ls -l "$test_home/state/zshrc")" == '-rw-r-----'* ]]
[[ "$(ls -l "$test_home/.tmux.conf")" == '-rw-r-----'* ]]
printf '# user configuration without newline\nsource ~/dotfiles/.zshrc2\n' > "$fixture/expected-zshrc"
cmp "$fixture/expected-zshrc" "$test_home/state/zshrc"
cmp "$fixture/expected-zshrc" "$test_home/state/zshrc-linked"
grep -Fxq 'source-file ~/dotfiles/.tmux.conf2' "$test_home/state/tmux-linked"
[[ -L "$test_home/.ssh/authorized_keys2" && -L "$test_home/.eid/authorized_certificates" ]]
[[ $(grep -c '^0 \* \* \* \* ' "$fixture/crontab") == 1 ]]
env -i HOME="$test_home" PATH="$PATH" bash -c \
'source "$HOME/.config/dotfiles/env"; [[ $DFS_AUDIT_VALUE == "hello world" && $KEEP_VALUE == "keep me" && $SOURCED_VALUE == "local source" ]]'
head -n "$(wc -l < "$fixture/original-env")" "$test_home/.config/dotfiles/env" > "$fixture/preserved-env"
cmp "$fixture/original-env" "$fixture/preserved-env"
# Repeated writes replace the key, even when an older value already occurred.
for value in one two one; do run_install -q -x "DFS_AUDIT_VALUE=$value"; done
env -i HOME="$test_home" PATH="$PATH" bash -c \
'source "$HOME/.config/dotfiles/env"; [[ $DFS_AUDIT_VALUE == one ]]'
[[ $(grep -cF 'source ~/dotfiles/.zshrc2' "$test_home/.zshrc") == 1 ]]
[[ $(grep -c '^0 \* \* \* \* ' "$fixture/crontab") == 1 ]]
# Shell metacharacters and embedded newlines remain literal configuration data.
value=$'line one; $(false)\nline two "quoted" \\ end'
run_install -q -x "DFS_AUDIT_VALUE=$value"
printf '%s' "$value" > "$fixture/expected-value"
env -i HOME="$test_home" PATH="$PATH" bash -c \
'source "$HOME/.config/dotfiles/env"; printf "%s" "$DFS_AUDIT_VALUE"' > "$fixture/actual-value"
cmp "$fixture/expected-value" "$fixture/actual-value"
# Uninstall only removes its own entries, including an include-only file.
rm "$test_home/.ssh/authorized_keys2"
printf 'user supplied authorized key\n' > "$test_home/.ssh/authorized_keys2"
printf '12 3 * * * echo keep\n' >> "$fixture/crontab"
printf 'y\n' | run_install -r
[[ -L "$test_home/.zshrc" ]]
[[ "$test_home/.zshrc" -ef "$test_home/state/zshrc-linked" ]]
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
printf '# user configuration without newline\n' > "$fixture/expected-zshrc"
cmp "$fixture/expected-zshrc" "$test_home/state/zshrc"
cmp "$fixture/expected-zshrc" "$test_home/state/zshrc-linked"
grep -Fxq 'set -g history-limit 99' "$test_home/.tmux.conf"
! grep -Fq '.tmux.conf2' "$test_home/state/tmux-linked"
[[ "$(ls -l "$test_home/state/zshrc")" == '-rw-r-----'* ]]
[[ "$(ls -l "$test_home/.tmux.conf")" == '-rw-r-----'* ]]
[[ ! -s "$test_home/.vimrc" ]]
grep -Fq 'local@example.invalid' "$test_home/.gitconfig"
! grep -Fq '.gitconfig2' "$test_home/.gitconfig"
grep -Fxq 'user supplied authorized key' "$test_home/.ssh/authorized_keys2"
[[ ! -e "$test_home/.eid/authorized_certificates" && ! -L "$test_home/.eid/authorized_certificates" ]]
grep -Fxq '12 3 * * * echo keep' "$fixture/crontab"
[[ $(wc -l < "$fixture/crontab") -eq 1 ]]
printf 'y\n' | run_install -r
cmp "$fixture/expected-zshrc" "$test_home/state/zshrc"
[[ "$test_home/.zshrc" -ef "$test_home/state/zshrc-linked" ]]
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
# A user-replaced link must also survive repeated uninstall.
printf 'custom certificates\n' > "$test_home/state/certificates"
ln -s ../state/certificates "$test_home/.eid/authorized_certificates"
printf 'y\n' | run_install -r
[[ -L "$test_home/.eid/authorized_certificates" ]]
grep -Fxq 'custom certificates' "$test_home/.eid/authorized_certificates"
# A failed in-place write restores the original bytes without splitting links.
cp "$test_home/.tmux.conf" "$fixture/original-tmux"
TEST_FAIL_WRITE=1 expect_failure -q
cmp "$fixture/original-tmux" "$test_home/.tmux.conf"
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
[[ "$(ls -l "$test_home/.tmux.conf")" == '-rw-r-----'* ]]
backups=("$test_home"/.tmux.conf.backup.*)
[[ ! -e "${backups[0]}" ]]
# Caught signals during the in-place write restore the original shared inode.
# The mock signals only its direct parent and exits immediately, so every case
# completes synchronously without background jobs or interactive prompts.
for signal in HUP INT TERM; do
TEST_FAIL_WRITE="$signal" expect_failure -q
grep -Fxq "signal $signal" "$fixture/calls"
cmp "$fixture/original-tmux" "$test_home/.tmux.conf"
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
[[ "$(ls -l "$test_home/.tmux.conf")" == '-rw-r-----'* ]]
backups=("$test_home"/.tmux.conf.backup.*)
[[ ! -e "${backups[0]}" ]]
done
# If restoration also fails, retain a complete backup and report its path.
for failure in 2 TERM-restore-failure; do
TEST_FAIL_WRITE="$failure" expect_failure -q
backups=("$test_home"/.tmux.conf.backup.*)
[[ ${#backups[@]} -eq 1 && -f "${backups[0]}" ]]
cmp "$fixture/original-tmux" "${backups[0]}"
grep -Fq -- "${backups[0]}" "$fixture/output"
[[ "$test_home/.tmux.conf" -ef "$test_home/state/tmux-linked" ]]
cat "${backups[0]}" > "$test_home/.tmux.conf"
rm "${backups[0]}"
done
grep -Fxq 'signal TERM-restore-failure' "$fixture/calls"
run_install -q
grep -Fxq 'source-file ~/dotfiles/.tmux.conf2' "$test_home/state/tmux-linked"
printf 'y\n' | run_install -r
cmp "$fixture/original-tmux" "$test_home/state/tmux-linked"
echo 'installer regression tests passed'

178
tools/test-riot.sh Executable file
View File

@@ -0,0 +1,178 @@
#!/usr/bin/env bash
set -euo pipefail
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
fixture=$(mktemp -d /tmp/riot-cli.XXXXXX)
trap 'rm -rf -- "$fixture"' EXIT
mkdir -p "$fixture/bin" "$fixture/home"
cat > "$fixture/bin/ssh" <<'EOF'
#!/usr/bin/env bash
printf 'COMMAND=%s\n' "${0##*/}" >> "$MOCK_COMMAND_LOG"
printf 'ARG=%s\n' "$@" >> "$MOCK_COMMAND_LOG"
EOF
cp "$fixture/bin/ssh" "$fixture/bin/scp"
cp "$fixture/bin/ssh" "$fixture/bin/ssh-keygen"
chmod +x "$fixture/bin/ssh" "$fixture/bin/scp" "$fixture/bin/ssh-keygen"
run_riot() {
env -i HOME="$fixture/home" PATH="$fixture/bin:$PATH" \
MOCK_COMMAND_LOG="$fixture/command.log" RIOT_TRUST_CLIENT=0 \
MOCK_SCP_LOG="$fixture/scp.log" MOCK_SCP_COUNT="$fixture/scp.count" \
MOCK_SCP_MUTATION="${scp_mutation:-none}" MOCK_SCP_FAIL_CALL="${scp_fail_call:-0}" \
"$source_dir/scripts/riot" "$@"
}
cd "$fixture"
# Removing a host key must follow the same dry-run contract as SSH commands.
run_riot -D example.test rm > "$fixture/out" 2> "$fixture/err"
grep -Fxq 'ssh-keygen -R [example.test]:12022' "$fixture/out"
test ! -e "$fixture/command.log"
run_riot example.test rm > "$fixture/out" 2> "$fixture/err"
grep -Fxq 'COMMAND=ssh-keygen' "$fixture/command.log"
grep -Fxq 'ARG=[example.test]:12022' "$fixture/command.log"
# The built-in batch appends seventeen remotes to the processing queue.
run_riot -D nasps > "$fixture/out" 2> "$fixture/err"
test "$(wc -l < "$fixture/out")" -eq 17
grep -Fq 'root@g1' "$fixture/out"
grep -Fq 'dictxiong@g15' "$fixture/out"
tail -n 1 "$fixture/out" | grep -Fq 'root@g17'
cat > "$fixture/riot-config.sh" <<'EOF'
first.batch() { remotes+=(inside.example); }
nested.batch() { remotes+=(first); }
empty.batch() { remotes+=("" tail.example); }
loop.batch() { remotes+=(loop); }
left.batch() { remotes+=(right); }
right.batch() { remotes+=(left); }
pair.batch() { remotes+=(one.example two.example); }
EOF
# Appended and nested batches are processed in queue order. Repeated use of
# a batch is valid when it is not part of a recursive expansion.
: > "$fixture/command.log"
run_riot 'first,,outside.example,nested,first,empty' > "$fixture/out" 2> "$fixture/err"
grep '^ARG=root@' "$fixture/command.log" > "$fixture/hosts"
cat > "$fixture/expected" <<'EOF'
ARG=root@outside.example
ARG=root@inside.example
ARG=root@inside.example
ARG=root@tail.example
ARG=root@inside.example
EOF
diff -u "$fixture/expected" "$fixture/hosts"
for batch in loop left; do
if run_riot -D "$batch" > "$fixture/out" 2> "$fixture/err"; then
echo "expected recursive batch $batch to fail" >&2
exit 1
fi
grep -Fq 'recursive batch:' "$fixture/err"
done
# Optional internal placeholders must not remove explicit empty command args.
: > "$fixture/command.log"
run_riot example.test ssh printf '%s' '' 'two words' > "$fixture/out" 2> "$fixture/err"
tail -n 4 "$fixture/command.log" > "$fixture/args"
printf 'ARG=printf\nARG=%%s\nARG=\nARG=two words\n' > "$fixture/expected"
diff -u "$fixture/expected" "$fixture/args"
# SCP needs brackets around IPv6 hosts in both directions. SSH retains its
# original destination format and uses the separate port option.
run_riot -D '[2001:db8::1]:2222' scp ./local /remote > "$fixture/out" 2> "$fixture/err"
grep -Fq ' ./local root@[2001:db8::1]:/remote' "$fixture/out"
run_riot -D '[2001:db8::1]:2222' scp /remote ./local > "$fixture/out" 2> "$fixture/err"
grep -Fq ' root@[2001:db8::1]:/remote ./local' "$fixture/out"
run_riot -D '[2001:db8::1]:2222' ssh > "$fixture/out" 2> "$fixture/err"
grep -Fq 'ssh -p 2222 ' "$fixture/out"
grep -Fq ' root@2001:db8::1' "$fixture/out"
# Assert the actual operands, then change the local source between transfers.
# Each target must retain the direction selected before the first transfer.
cat > "$fixture/bin/scp" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
operands=()
while (( $# > 0 )); do
case $1 in
-P|-o) shift 2 ;;
-r) shift ;;
*) operands+=("$1"); shift ;;
esac
done
[[ ${#operands[@]} -eq 2 ]] || { echo 'expected exactly two SCP operands' >&2; exit 1; }
printf 'SOURCE=%s\nDESTINATION=%s\n' "${operands[@]}" >> "$MOCK_SCP_LOG"
call=0
[[ ! -f $MOCK_SCP_COUNT ]] || read -r call < "$MOCK_SCP_COUNT"
call=$((call + 1))
printf '%s\n' "$call" > "$MOCK_SCP_COUNT"
case $MOCK_SCP_MUTATION in
create) touch foo ;;
remove) rm -f foo ;;
esac
[[ $call -ne $MOCK_SCP_FAIL_CALL ]] || exit 42
EOF
chmod +x "$fixture/bin/scp"
reset_scp_log() {
: > "$fixture/scp.log"
rm -f "$fixture/scp.count"
}
for remotes in one.example,two.example pair; do
rm -f foo
reset_scp_log
scp_mutation=create run_riot "$remotes" scp foo . > "$fixture/out" 2> "$fixture/err"
cat > "$fixture/expected" <<'EOF'
SOURCE=root@one.example:foo
DESTINATION=.
SOURCE=root@two.example:foo
DESTINATION=.
EOF
diff -u "$fixture/expected" "$fixture/scp.log"
# Removing an initially local file must not turn the next upload into a
# download, even when both local arguments were initially present.
touch foo
reset_scp_log
scp_mutation=remove run_riot "$remotes" scp foo . > "$fixture/out" 2> "$fixture/err"
cat > "$fixture/expected" <<'EOF'
SOURCE=foo
DESTINATION=root@one.example:.
SOURCE=foo
DESTINATION=root@two.example:.
EOF
diff -u "$fixture/expected" "$fixture/scp.log"
# The ./ prefix continues to force the local side in either position.
touch foo
reset_scp_log
scp_mutation=remove run_riot "$remotes" scp foo ./destination > "$fixture/out" 2> "$fixture/err"
cat > "$fixture/expected" <<'EOF'
SOURCE=root@one.example:foo
DESTINATION=./destination
SOURCE=root@two.example:foo
DESTINATION=./destination
EOF
diff -u "$fixture/expected" "$fixture/scp.log"
rm -f foo
reset_scp_log
scp_mutation=create run_riot "$remotes" scp ./foo . > "$fixture/out" 2> "$fixture/err"
cat > "$fixture/expected" <<'EOF'
SOURCE=./foo
DESTINATION=root@one.example:.
SOURCE=./foo
DESTINATION=root@two.example:.
EOF
diff -u "$fixture/expected" "$fixture/scp.log"
reset_scp_log
scp_status=0
scp_fail_call=1 run_riot "$remotes" scp ./foo /remote > "$fixture/out" 2> "$fixture/err" || scp_status=$?
[[ $scp_status -eq 42 && $(cat "$fixture/scp.count") -eq 1 ]]
done
echo 'riot command tests passed'

View File

@@ -1,83 +1,520 @@
#!/usr/bin/env bash
set -euo pipefail
THIS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
SCF="$THIS_DIR/../scripts/scf"
TEST_DIR=$(mktemp -d /tmp/scf.XXXXXX)
trap 'rm -rf "$TEST_DIR"' EXIT
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
scf="$source_dir/scripts/scf"
fixture=$(mktemp -d /tmp/scf.XXXXXX)
trap 'rm -rf -- "$fixture"' EXIT
mock_bin="$fixture/bin"
data_dir="$fixture/data"
unit_dir="$fixture/units"
mkdir -p "$mock_bin" "$data_dir" "$unit_dir"
MOCK_BIN="$TEST_DIR/bin"
DATA_DIR="$TEST_DIR/data"
MOCK_SYSTEMCTL_LOG="$TEST_DIR/systemctl.log"
MOCK_MAIN="$DATA_DIR/main.yaml"
MOCK_CHILD="$DATA_DIR/child.conf"
MOCK_NOTE="$DATA_DIR/notes.txt"
mkdir -p "$MOCK_BIN" "$DATA_DIR"
export MOCK_SYSTEMCTL_LOG MOCK_MAIN MOCK_CHILD MOCK_NOTE
export MOCK_UNIT_DIR="$unit_dir" MOCK_SYSTEMCTL_LOG="$fixture/systemctl.log"
MOCK_VIRTUAL_GUARD=""
MOCK_PROBE_ROOT=""
MOCK_PROBE_LOG=""
REAL_GREP=$(command -v grep)
REAL_HEAD=$(command -v head)
printf 'include %s\n' "$MOCK_CHILD" > "$MOCK_MAIN"
printf 'child configuration\n' > "$MOCK_CHILD"
printf 'not a configuration candidate\n' > "$MOCK_NOTE"
cat > "$MOCK_BIN/systemctl" <<'EOF'
cat > "$mock_bin/systemctl" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' "$*" >> "$MOCK_SYSTEMCTL_LOG"
service=${@: -1}
case "$service" in
demo.service)
printf 'path=/usr/bin/demo ; argv[0]=demo ; argv[1]=%s ; argv[2]=%s ;\n' \
"$MOCK_MAIN" "$MOCK_NOTE"
;;
empty.service)
printf 'path=/usr/bin/empty ; argv[0]=empty ;\n'
;;
*)
exit 1
;;
esac
unit=${@: -1}
cat "$MOCK_UNIT_DIR/$unit"
EOF
chmod +x "$MOCK_BIN/systemctl"
chmod +x "$mock_bin/systemctl"
run_scf() {
PATH="$MOCK_BIN:$PATH" "$SCF" "$@"
write_unit() {
local name=$1 executable=$2 argument
shift 2
{
printf '{ path=%s ; argv[]=%s' "$executable" "$executable"
for argument in "$@"; do
argument=${argument//\\/\\\\}
argument=${argument//\"/\\\"}
printf ' "%s"' "$argument"
done
printf ' ; }\n'
} > "$unit_dir/$name.service"
}
# A service name without .service is accepted, and non-interactive mode prints
# the only configuration candidate instead of opening an editor.
output=$(run_scf demo 2> "$TEST_DIR/stderr")
grep -Fxq 'include '"$MOCK_CHILD" <<< "$output"
grep -Fq -- '--property=ExecStart --value demo.service' "$MOCK_SYSTEMCTL_LOG"
run_scf() {
env -i HOME="$fixture" PATH="$mock_bin:$PATH" \
MOCK_UNIT_DIR="$unit_dir" MOCK_SYSTEMCTL_LOG="$MOCK_SYSTEMCTL_LOG" \
MOCK_VIRTUAL_GUARD="$MOCK_VIRTUAL_GUARD" \
MOCK_PROBE_ROOT="$MOCK_PROBE_ROOT" MOCK_PROBE_LOG="$MOCK_PROBE_LOG" \
REAL_GREP="$REAL_GREP" REAL_HEAD="$REAL_HEAD" \
SCF_MAX_CANDIDATES="${SCF_MAX_CANDIDATES-20}" \
SCF_MAX_DEPTH="${SCF_MAX_DEPTH-3}" SCF_MAX_SCAN="${SCF_MAX_SCAN-256}" \
SCF_MAX_BYTES="${SCF_MAX_BYTES-1048576}" \
"$scf" "$@" 2> "$fixture/stderr"
}
# Recursive mode discovers configuration files referenced by the first one.
output=$(run_scf -r -n 2 demo)
grep -Fxq 'child configuration' <<< "$output"
expect_file() {
local expected=$1
shift
if ! run_scf "$@" > "$fixture/stdout"; then
cat "$fixture/stderr" >&2
echo "expected scf to select $expected for $*" >&2
exit 1
fi
cmp "$expected" "$fixture/stdout"
}
# Decimal values with a leading zero must not be treated as invalid octal.
output=$(SCF_MAX_DEPTH=08 SCF_MAX_CANDIDATES=08 run_scf demo)
grep -Fxq 'include '"$MOCK_CHILD" <<< "$output"
if run_scf -n 08 demo > "$TEST_DIR/out" 2> "$TEST_DIR/stderr"; then
echo 'expected scf -n 08 to fail because only one candidate exists' >&2
expect_failure() {
local message=$1
shift
if run_scf "$@" > "$fixture/stdout"; then
echo "expected scf to fail for $*" >&2
exit 1
fi
grep -Fq -- "$message" "$fixture/stderr"
}
binary="$data_dir/program"
main="$data_dir/main.yaml"
child="$data_dir/child.conf"
note="$data_dir/notes.unknown"
plain="$data_dir/extensionless"
empty="$data_dir/empty"
script="$data_dir/runner"
other_script="$data_dir/other.cjs"
execution_marker="$fixture/script-was-executed"
printf '\177ELF\000binary payload\n' > "$binary"
printf 'main file\ninclude %s\n' "$child" > "$main"
printf 'child file\n' > "$child"
printf 'unknown suffix text\n' > "$note"
printf 'extensionless text without a shebang\n' > "$plain"
: > "$empty"
printf '#!/bin/sh\n# startup script\ntouch %s\n' "$execution_marker" > "$script"
printf '// executable text without a shebang\n' > "$other_script"
chmod +x "$script"
chmod 644 "$other_script"
ln -s "$script" "$data_dir/script-link"
# Direct text arguments retain argv order, independent of suffix or shebang.
# Recursive references are listed after the direct arguments.
write_unit demo "$binary" "$main" "$note"
expect_file "$main" demo
grep -Fq -- '--property=ExecStart --value -- demo.service' "$MOCK_SYSTEMCTL_LOG"
expect_file "$note" -n 2 demo
expect_file "$child" -r -n 3 demo
write_unit arbitrary "$binary" "$note" "$main" "$plain" "$empty"
expect_file "$note" arbitrary
expect_file "$main" -n 2 arbitrary
expect_file "$plain" -n 3 arbitrary
expect_file "$empty" -n 4 arbitrary
expect_failure 'out of range (1-4)' -n 5 arbitrary
# Text executable entry points follow direct arguments. Executable bits and
# script suffixes do not determine whether readable text can be selected.
write_unit script "$script" "$note"
expect_file "$note" script
expect_file "$script" -n 2 script
write_unit plain-script "$other_script"
expect_file "$other_script" plain-script
write_unit linked-script "$data_dir/script-link"
expect_file "$script" linked-script
test ! -e "$execution_marker"
# A relative executable name must not cause the first absolute argument to be
# discarded. Every ExecStart entry in a oneshot unit contributes candidates.
write_unit relative systemd-tmpfiles "$main"
expect_file "$main" relative
write_unit first "$script"
write_unit second "$binary" "$note"
write_unit third "$other_script"
cat "$unit_dir/first.service" "$unit_dir/second.service" "$unit_dir/third.service" \
> "$unit_dir/multiple.service"
expect_file "$note" multiple
expect_file "$script" -n 2 multiple
expect_file "$other_script" -n 3 multiple
expect_failure 'out of range (1-3)' -n 4 multiple
write_unit role-first "$other_script" "$script"
write_unit role-second "$script"
cat "$unit_dir/role-first.service" "$unit_dir/role-second.service" > "$unit_dir/roles.service"
expect_file "$script" roles
expect_file "$other_script" -n 2 roles
expect_failure 'out of range (1-2)' -n 3 roles
write_unit binary "$binary" "$binary"
if run_scf binary > "$fixture/stdout"; then
echo 'expected binary-only service to have no text candidate' >&2
exit 1
fi
grep -Fq 'candidate number 8 is out of range' "$TEST_DIR/stderr"
test ! -s "$fixture/stdout"
printf 'ASCII prefix line\n\022non-text payload\n' > "$data_dir/control-payload"
write_unit control-payload "$binary" "$data_dir/control-payload"
if run_scf control-payload > "$fixture/stdout"; then
echo 'expected a control-byte payload to be excluded without a NUL byte' >&2
exit 1
fi
test ! -s "$fixture/stdout"
printf '\344\270\255\346\226\207 UTF-8 text\n' > "$data_dir/utf8"
write_unit utf8-empty "$binary" "$data_dir/utf8" "$empty"
expect_file "$data_dir/utf8" utf8-empty
expect_file "$empty" -n 2 utf8-empty
# Invalid service names are rejected before systemctl is invoked.
# Literal ANSI escape sequences are valid text in both scripts and logs.
printf '#!/bin/sh\nprintf "\033[31mred\033[0m\\n"\ntouch %s\n' \
"$execution_marker" > "$data_dir/ansi-script"
bash -n "$data_dir/ansi-script"
printf '\033[32mservice started\033[0m\n' > "$data_dir/ansi-log"
write_unit ansi-script "$data_dir/ansi-script"
write_unit ansi-log "$binary" "$data_dir/ansi-log"
expect_file "$data_dir/ansi-script" ansi-script
expect_file "$data_dir/ansi-log" ansi-log
test ! -e "$execution_marker"
# systemctl leaves shell -c commands unquoted. Internal semicolons and shell
# assignments must survive until the actual ExecStart metadata boundary.
printf '{ path=%s ; argv[]=%s -c true; pid=0; status=ready; flags=on; cat "%s" ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0 ; }\n' \
"$binary" "$binary" "$note" > "$unit_dir/shell-semicolons.service"
expect_file "$note" shell-semicolons
printf '{ path=%s ; argv[]=%s -c f() { true; }; cat "%s" ; }\n' \
"$binary" "$binary" "$note" > "$unit_dir/shell-braces.service"
expect_file "$note" shell-braces
printf '{ path=%s ; argv[]=%s -c f() { true; ignore_errors=no ; }; cat "%s" ; }\n' \
"$binary" "$binary" "$note" > "$unit_dir/shell-field-name.service"
expect_file "$note" shell-field-name
# Preserve semicolons in quoted filenames, indexed argv fields, and multiple
# ExecStart records on a single line without merging their executable roles.
semicolon="$data_dir/semicolon ; ignore_errors=no ; }"
printf 'semicolon filename\n' > "$semicolon"
write_unit semicolon "$binary" "$semicolon"
expect_file "$semicolon" semicolon
printf '{ path=%s ; argv[0]=%s ; argv[1]=-c ; argv[2]=true; cat "%s" ; }\n' \
"$binary" "$binary" "$note" > "$unit_dir/indexed-argv.service"
expect_file "$note" indexed-argv
printf '{ path=%s ; argv[]=%s -c true; cat "%s" ; } { path=%s ; argv[]=%s "%s" ; }\n' \
"$binary" "$binary" "$note" "$script" "$script" "$plain" \
> "$unit_dir/inline-records.service"
expect_file "$note" inline-records
expect_file "$plain" -n 2 inline-records
expect_file "$script" -n 3 inline-records
expect_failure 'out of range (1-3)' -n 4 inline-records
# Decoded newlines can produce blank path records. They must not become empty
# associative-array subscripts or prevent a later real file from being found.
printf '%s\n' 'pattern = "/\n"' "'/\\n'" "$note" > "$data_dir/escaped-references"
write_unit escaped-references "$binary" "$data_dir/escaped-references"
# Three probes cover the binary, input text, and real reference. Any incidental
# root-directory task is deferred beyond that budget instead of being scanned.
SCF_MAX_SCAN=3 expect_file "$note" -r -n 2 escaped-references
# Preserve quoted paths and common systemd/shell encodings, including literal
# quotes and backslashes in existing names.
mkdir "$data_dir/space dir"
spaced="$data_dir/space dir/plain file"
quoted="$data_dir/quoted \"file\""
backslash="$data_dir/literal\\space"
printf 'spaced text\n' > "$spaced"
printf 'quoted text\n' > "$quoted"
printf 'backslash text\n' > "$backslash"
write_unit spaced "$binary" "$spaced"
write_unit quoted "$binary" "$quoted"
write_unit backslash "$binary" "$backslash"
expect_file "$spaced" spaced
expect_file "$quoted" quoted
expect_file "$backslash" backslash
for encoding in hex octal shell; do
case $encoding in
hex) encoded=${spaced// /\\x20} ;;
octal) encoded=${spaced// /\\040} ;;
shell) encoded=${spaced// /\\ } ;;
esac
printf '{ path=%s ; argv[]=%s --file %s ; }\n' "$binary" "$binary" "$encoded" \
> "$unit_dir/$encoding.service"
expect_file "$spaced" "$encoding"
done
# All directory text entries are eligible, in C filename order. Explicit
# recursive file references outrank entries found by scanning a directory.
directory="$data_dir/items"
mkdir "$directory"
printf 'unknown directory text\n' > "$directory/10.notes"
printf 'extensionless directory text\n' > "$directory/20-plain"
: > "$directory/30-empty"
printf 'PEM-shaped text\n' > "$directory/40.pem"
cp "$binary" "$directory/50.binary"
printf '#!/bin/sh\n# directory script\n' > "$directory/60-runner"
printf 'table inet unit_test {}\n' > "$directory/70.nft"
printf 'alloy text\n' > "$directory/80.alloy"
write_unit directory "$binary" "$directory"
index=1
for expected in "$directory/10.notes" "$directory/20-plain" "$directory/30-empty" \
"$directory/40.pem" "$directory/60-runner" "$directory/70.nft" "$directory/80.alloy"; do
expect_file "$expected" -r -n "$index" directory
index=$((index + 1))
done
expect_failure 'out of range (1-7)' -r -n 8 directory
if run_scf directory > "$fixture/stdout"; then
echo 'expected directories to require recursive mode' >&2
exit 1
fi
wrapper="$data_dir/wrapper"
explicit="$data_dir/explicit.unusual"
printf 'direct argument without references\n' > "$data_dir/direct"
printf 'explicit recursive text\n' > "$explicit"
printf '#!/bin/sh\n%s\n%s\n' "$directory" "$explicit" > "$wrapper"
write_unit ranked "$wrapper" "$data_dir/direct"
expect_file "$data_dir/direct" -r ranked
expect_file "$wrapper" -r -n 2 ranked
expect_file "$explicit" -r -n 3 ranked
expect_file "$directory/10.notes" -r -n 4 ranked
mkdir "$data_dir/weak-directory"
printf 'external directory reference\n' > "$data_dir/directory-child.unknown"
printf 'directory document\n%s\n' "$data_dir/directory-child.unknown" > "$data_dir/weak-directory/entry"
write_unit weak-source "$binary" "$data_dir/weak-directory"
expect_file "$data_dir/weak-directory/entry" -r weak-source
expect_file "$data_dir/directory-child.unknown" -r -n 2 weak-source
expect_failure 'out of range (1-2)' -r -n 3 weak-source
# References are ordered by depth before discovery order and cycles terminate.
chain="$data_dir/chain"
middle="$data_dir/middle"
deep="$data_dir/deep.odd"
printf '#!/bin/sh\n%s\n' "$middle" > "$chain"
printf 'middle text\n%s\n' "$deep" > "$middle"
printf 'deep text\n' > "$deep"
write_unit chain "$chain"
expect_file "$chain" -r chain
expect_file "$middle" -r -n 2 chain
expect_file "$deep" -r -n 3 chain
SCF_MAX_DEPTH=1 expect_failure 'out of range (1-2)' -r -n 3 chain
printf 'sibling text\n' > "$data_dir/sibling"
printf '#!/bin/sh\n%s\n%s\n' "$middle" "$data_dir/sibling" > "$data_dir/branching"
write_unit branching "$data_dir/branching"
expect_file "$middle" -r -n 2 branching
expect_file "$data_dir/sibling" -r -n 3 branching
expect_file "$deep" -r -n 4 branching
printf '\n%s\n' "$chain" >> "$deep"
expect_failure 'out of range (1-3)' -r -n 4 chain
SCF_MAX_DEPTH=0 expect_failure 'out of range (1-1)' -r -n 2 chain
# A directory can expose a known file at a shallower traversal depth even
# though the earlier explicit reference retains its stronger display rank.
promotion="$data_dir/promotion"
mkdir -p "$promotion/jobs"
printf '#!/bin/sh\n%s\n%s\n' "$promotion/first" "$promotion/jobs" > "$promotion/entry"
printf 'first reference\n%s\n' "$promotion/jobs/target" > "$promotion/first"
printf 'target text\n%s\n' "$promotion/child" > "$promotion/jobs/target"
printf 'child reached through a shallower directory entry\n' > "$promotion/child"
write_unit promotion "$promotion/entry"
SCF_MAX_DEPTH=2 expect_file "$promotion/child" -r -n 4 promotion
SCF_MAX_DEPTH=2 expect_failure 'out of range (1-4)' -r -n 5 promotion
# Recursive parsing has a byte budget independent of candidate eligibility.
# A partial final path must be discarded even when its prefix names a file.
byte_entry="$data_dir/byte-entry"
byte_large="$data_dir/byte-large"
byte_prefix="$data_dir/byte-tail"
byte_tail="$data_dir/byte-tail-suffix"
large_first_line='large text remains selectable'
printf '#!/bin/sh\n%s\n' "$byte_large" > "$byte_entry"
printf '%s\n%s\n' "$large_first_line" "$byte_tail" > "$byte_large"
printf 'truncated path prefix must not be selected\n' > "$byte_prefix"
printf 'tail file beyond the small byte budget\n' > "$byte_tail"
byte_limit=$(( $(wc -c < "$byte_entry") + ${#large_first_line} + 1 + ${#byte_prefix} ))
write_unit byte-budget "$byte_entry"
SCF_MAX_BYTES="$byte_limit" expect_file "$byte_large" -r -n 2 byte-budget
test "$(grep -cF 'SCF_MAX_BYTES' "$fixture/stderr")" -eq 1
SCF_MAX_BYTES="$byte_limit" expect_failure 'out of range (1-2)' -r -n 3 byte-budget
test "$(grep -cF 'SCF_MAX_BYTES' "$fixture/stderr")" -eq 1
SCF_MAX_BYTES=4096 SCF_MAX_SCAN=3 expect_file "$byte_tail" -r -n 3 byte-budget
SCF_MAX_BYTES=0 expect_failure 'SCF_MAX_BYTES' byte-budget
SCF_MAX_BYTES=invalid expect_failure 'SCF_MAX_BYTES' byte-budget
# A shallower symlink discovery can rescan a file's references. Reuse its
# parsed references so the total budget is charged once per canonical file.
byte_cache="$data_dir/byte-cache"
mkdir -p "$byte_cache/jobs"
printf '#!/bin/sh\n%s\n%s\n' "$byte_cache/first" "$byte_cache/jobs" > "$byte_cache/entry"
printf 'first text\n%s\n' "$byte_cache/target" > "$byte_cache/first"
printf 'target text\n%s\n' "$byte_cache/child" > "$byte_cache/target"
printf 'child text\n%s\n' "$byte_cache/grandchild" > "$byte_cache/child"
printf 'grandchild reached using cached references\n' > "$byte_cache/grandchild"
ln -s "$byte_cache/target" "$byte_cache/jobs/target"
byte_cache_limit=0
for file in entry first target child; do
byte_cache_limit=$((byte_cache_limit + $(wc -c < "$byte_cache/$file")))
done
write_unit byte-cache "$byte_cache/entry"
SCF_MAX_DEPTH=3 SCF_MAX_BYTES="$byte_cache_limit" \
expect_file "$byte_cache/grandchild" -r -n 5 byte-cache
if grep -Fq 'SCF_MAX_BYTES' "$fixture/stderr"; then
echo 'expected canonical reference-cache hits not to consume parsing bytes' >&2
exit 1
fi
# Canonical physical paths deduplicate aliases without changing source order.
ln -s "$note" "$data_dir/note-link"
ln -s "$data_dir/note-link" "$data_dir/second-link"
write_unit aliases "$binary" "$note" "$data_dir/note-link" "$data_dir/second-link" "$plain"
expect_file "$note" aliases
expect_file "$plain" -n 2 aliases
expect_failure 'out of range (1-2)' -n 3 aliases
SCF_MAX_SCAN=3 expect_file "$plain" -n 2 aliases
if grep -Fq 'SCF_MAX_SCAN' "$fixture/stderr"; then
echo 'expected aliases to share the physical scan budget' >&2
exit 1
fi
printf '#!/bin/sh\n%s\n%s\n%s\n%s\n' "$note" "$data_dir/note-link" \
"$data_dir/second-link" "$plain" > "$data_dir/alias-wrapper"
write_unit alias-wrapper "$data_dir/alias-wrapper"
SCF_MAX_SCAN=3 expect_file "$plain" -r -n 3 alias-wrapper
if grep -Fq 'SCF_MAX_SCAN' "$fixture/stderr"; then
echo 'expected recursive aliases not to truncate physical discovery' >&2
exit 1
fi
# Search-path assignments in wrappers do not recursively enumerate packages.
# An explicitly referenced file and an ordinary directory named bin still do.
runtime="$data_dir/runtime"
ordinary_bin="$data_dir/ordinary/bin"
mkdir -p "$runtime/bin" "$runtime/site-packages" "$ordinary_bin"
printf 'wrapped program text\n' > "$runtime/bin/wrapped"
printf 'unrelated tool text\n' > "$runtime/bin/zzz-tool"
printf 'Python library text\n' > "$runtime/site-packages/module.py"
printf 'ordinary bin text\n' > "$ordinary_bin/item"
runtime_wrapper="$data_dir/runtime-wrapper"
printf '#!/bin/sh\nexport PATH=%s; %s\nPYTHONPATH=%s\n%s\n' \
"$runtime/bin" "$runtime/bin/wrapped" "$runtime/site-packages" "$ordinary_bin" > "$runtime_wrapper"
write_unit runtime "$runtime_wrapper"
expect_file "$runtime_wrapper" -r runtime
expect_file "$runtime/bin/wrapped" -r -n 2 runtime
expect_file "$ordinary_bin/item" -r -n 3 runtime
expect_failure 'out of range (1-3)' -r -n 4 runtime
write_unit explicit-bin "$binary" "$runtime/bin"
expect_file "$runtime/bin/wrapped" -r explicit-bin
expect_file "$runtime/bin/zzz-tool" -r -n 2 explicit-bin
# A directory assignment is not necessarily a runtime search path. Comments
# and command-prefix assignments also must not hide later ordinary references.
assets="$data_dir/assets"
mkdir "$assets"
printf 'ordinary asset directory text\n' > "$assets/item"
printf '#!/bin/sh\nCONFIG_PATH=%s\n' "$assets" > "$data_dir/config-path-wrapper"
printf "#!/bin/sh\nexport PATH=%s # user's tools\n%s\n" \
"$runtime/bin" "$assets" > "$data_dir/comment-wrapper"
printf '#!/bin/sh\nPATH=%s exec app --assets %s\n' \
"$runtime/bin" "$assets" > "$data_dir/prefix-wrapper"
for name in config-path comment prefix; do
write_unit "$name" "$data_dir/$name-wrapper"
expect_file "$assets/item" -r -n 2 "$name"
expect_failure 'out of range (1-2)' -r -n 3 "$name"
done
printf 'import sys\nsys.path = [\n "%s",\n "%s",\n]\nassets = "%s"\n' \
"$runtime/bin" "$runtime/site-packages" "$assets" > "$data_dir/python-list"
write_unit python-list "$data_dir/python-list"
expect_file "$assets/item" -r -n 2 python-list
expect_failure 'out of range (1-2)' -r -n 3 python-list
for method in insert append; do
if [[ $method == insert ]]; then
call="insert(0, \"$runtime/bin\")"
else
call="append(\"$runtime/site-packages\")"
fi
printf 'import sys\nsys.path.%s; assets = "%s"\n' "$call" "$assets" > "$data_dir/python-$method"
write_unit "python-$method" "$data_dir/python-$method"
expect_file "$assets/item" -r -n 2 "python-$method"
expect_failure 'out of range (1-2)' -r -n 3 "python-$method"
done
printf '#!/bin/sh\nPATH=\n%s\n' "$assets" > "$data_dir/empty-path-wrapper"
write_unit empty-path "$data_dir/empty-path-wrapper"
expect_file "$assets/item" -r -n 2 empty-path
expect_failure 'out of range (1-2)' -r -n 3 empty-path
# Escaped unit names and option boundaries are accepted, malformed names fail
# before systemctl is called.
write_unit 'unit-escaped\x2dname' "$binary" "$note"
expect_file "$note" 'unit-escaped\x2dname'
write_unit -example "$binary" "$note"
expect_file "$note" -- -example.service
grep -Fq -- '--value -- -example.service' "$MOCK_SYSTEMCTL_LOG"
before=$(wc -l < "$MOCK_SYSTEMCTL_LOG")
if run_scf 'demo; touch /tmp/unexpected' > "$TEST_DIR/out" 2> "$TEST_DIR/stderr"; then
echo 'expected an invalid service name to fail' >&2
exit 1
fi
grep -Fq 'invalid service name' "$TEST_DIR/stderr"
after=$(wc -l < "$MOCK_SYSTEMCTL_LOG")
test "$before" -eq "$after"
for invalid in 'bad\xZZ.service' 'bad\x2.service' 'bad\name.service' 'demo; touch /tmp/unexpected'; do
expect_failure 'invalid service name' "$invalid"
done
test "$(wc -l < "$MOCK_SYSTEMCTL_LOG")" -eq "$before"
SCF_MAX_CANDIDATES=08 SCF_MAX_DEPTH=08 SCF_MAX_SCAN=08 expect_file "$main" demo
expect_failure 'out of range' -n 08 demo
# A service without a referenced file reports a useful failure.
if run_scf empty > "$TEST_DIR/out" 2> "$TEST_DIR/stderr"; then
echo 'expected a service without a config path to fail' >&2
exit 1
# Guard probes into virtual filesystems so a regression cannot read a device
# or its own output pipe. Redirecting stdout to a regular file exercises the
# /dev/stdout -f edge case, including ordinary-looking symlink aliases.
virtual_file="$data_dir/output-alias"
virtual_dir="$data_dir/kernel-alias"
ln -s /dev/stdout "$virtual_file"
ln -s /proc "$virtual_dir"
MOCK_VIRTUAL_GUARD="$fixture/virtual-guard"
virtual_probes="$fixture/virtual-probes"
printf 'for argument in "$@"; do\n case "$argument" in\n' > "$MOCK_VIRTUAL_GUARD"
printf ' /dev|/dev/*|/proc|/proc/*|/sys|/sys/*|"%s"|"%s"|"%s"/*)\n' \
"$virtual_file" "$virtual_dir" "$virtual_dir" >> "$MOCK_VIRTUAL_GUARD"
printf ' printf "%%s\\n" "$argument" >> "%s"\n exit 99 ;;\n esac\ndone\n' \
"$virtual_probes" >> "$MOCK_VIRTUAL_GUARD"
for command in head grep; do
cat > "$mock_bin/$command" <<'EOF'
#!/usr/bin/env bash
if [[ -n "$MOCK_VIRTUAL_GUARD" ]]; then source "$MOCK_VIRTUAL_GUARD" "$@"; fi
if [[ -n "$MOCK_PROBE_ROOT" ]]; then
for argument in "$@"; do
if [[ $argument == "$MOCK_PROBE_ROOT/"* && -f $argument ]]; then
readlink -f -- "$argument" >> "$MOCK_PROBE_LOG"
fi
done
fi
grep -Fq 'no existing configuration path found' "$TEST_DIR/stderr"
if [[ ${0##*/} == grep ]]; then exec "$REAL_GREP" "$@"; fi
exec "$REAL_HEAD" "$@"
EOF
chmod +x "$mock_bin/$command"
done
virtual_wrapper="$data_dir/virtual-runner"
printf '#!/bin/sh\n%s\n' "$note" > "$virtual_wrapper"
printf '%s\n' /dev/stdout /proc/version /sys/kernel/kexec_loaded /dev /proc /sys \
"$virtual_file" "$virtual_dir" >> "$virtual_wrapper"
write_unit virtual "$virtual_wrapper"
expect_file "$virtual_wrapper" -r virtual
expect_file "$note" -r -n 2 virtual
expect_failure 'out of range (1-2)' -r -n 3 virtual
for executable in /dev/stdout "$virtual_file"; do
write_unit virtual-entry "$executable" "$note"
expect_file "$note" virtual-entry
done
test ! -e "$virtual_probes"
# Candidate display limits do not restrict discovery through a wrapper chain.
# A separate scan budget bounds unique physical probes and reports truncation.
MOCK_PROBE_ROOT="$data_dir"
MOCK_PROBE_LOG="$fixture/probes"
: > "$MOCK_PROBE_LOG"
SCF_MAX_CANDIDATES=1 expect_file "$chain" -r chain
grep -Fq 'SCF_MAX_CANDIDATES' "$fixture/stderr"
grep -Fxq "$deep" "$MOCK_PROBE_LOG"
mkdir "$data_dir/many"
for ((i=1; i<=60; i++)); do
printf 'directory entry %s\n' "$i" > "$data_dir/many/job-$i"
done
probe_wrapper="$data_dir/probe-wrapper"
printf '#!/bin/sh\n%s\n' "$data_dir/many" > "$probe_wrapper"
write_unit probes "$probe_wrapper"
: > "$MOCK_PROBE_LOG"
SCF_MAX_CANDIDATES=128 expect_file "$probe_wrapper" -r probes
single_reads=$(wc -l < "$MOCK_PROBE_LOG")
printf '%s\n%s\n' "$data_dir/many" "$data_dir/many" >> "$probe_wrapper"
: > "$MOCK_PROBE_LOG"
SCF_MAX_CANDIDATES=128 expect_file "$probe_wrapper" -r probes
test "$(wc -l < "$MOCK_PROBE_LOG")" -eq "$single_reads"
: > "$MOCK_PROBE_LOG"
SCF_MAX_SCAN=6 SCF_MAX_CANDIDATES=128 expect_file "$probe_wrapper" -r probes
grep -Fq 'SCF_MAX_SCAN' "$fixture/stderr"
test "$(sort -u "$MOCK_PROBE_LOG" | wc -l)" -le 6
write_unit argument-budget "$probe_wrapper" "$data_dir/many" "$note"
SCF_MAX_SCAN=2 expect_file "$note" -r argument-budget
grep -Fq 'SCF_MAX_SCAN' "$fixture/stderr"
test ! -e "$execution_marker"
echo 'scf tests passed'

View File

@@ -12,7 +12,7 @@ cleanup() {
}
trap cleanup EXIT
mkdir -m 700 "$GNUPGHOME"
unset DFS_IGNORE_COMMIT_SIGN DFS_UPDATE_GPG_KEY_FILE DFS_UPDATE_CHANNEL
unset DFS_IGNORE_COMMIT_SIGN DFS_UPDATE_GPG_KEY_FILE DFS_UPDATE_CHANNEL DFS_DRY_RUN
old_signer=old@example.invalid
new_signer=new@example.invalid
@@ -128,7 +128,7 @@ git -C "$remote" commit -q --allow-empty --no-gpg-sign -m 'Unsigned commit'
reject_update 'has no trusted signature or signed release tag'
without_gpg="$fixture/bin-without-gpg"
mkdir "$without_gpg"
for tool in bash dirname basename git grep mktemp cp chmod mv rm; do
for tool in bash dirname basename git grep mktemp cp chmod mv rm cmp; do
ln -s "$(command -v "$tool")" "$without_gpg/$tool"
done
PATH="$without_gpg" reject_update 'gpg not found. Set DFS_IGNORE_COMMIT_SIGN=1'

138
tools/test-update.sh Executable file
View File

@@ -0,0 +1,138 @@
#!/usr/bin/env bash
set -euo pipefail
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
fixture=$(mktemp -d)
trap 'rm -rf -- "$fixture"' EXIT
test_home="$fixture/home"
remote="$fixture/remote"
client="$test_home/dotfiles"
mock_bin="$fixture/bin"
mkdir -p "$test_home" "$remote/tools" "$mock_bin"
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null
cp "$source_dir/.update.sh" "$remote/.update.sh"
cp "$source_dir/.gitignore" "$remote/.gitignore"
cp "$source_dir/tools/common.sh" "$remote/tools/common.sh"
cat > "$remote/tools/frigg-client.sh" <<'EOF'
#!/usr/bin/env bash
[[ "${DFS_ORPHAN:-0}" == 1 ]] && exit 0
printf '%s\n' "$*" >> "$DOTFILES_TEST_SIDE_EFFECTS"
EOF
chmod +x "$remote/tools/frigg-client.sh"
git init -q -b dev "$remote"
git -C "$remote" config user.name 'Dotfiles Test'
git -C "$remote" config user.email fixture@example.invalid
git -C "$remote" config commit.gpgsign false
git -C "$remote" add .
git -C "$remote" commit -qm 'Installed revision'
git clone -q "$remote" "$client"
cp "$client/.update.sh" "$client/update.sh"
chmod +x "$client/update.sh"
initial_commit=$(git -C "$client" rev-parse HEAD)
cat > "$mock_bin/curl" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$DOTFILES_TEST_RELEASE"
EOF
cat > "$mock_bin/cp" <<'EOF'
#!/usr/bin/env bash
exit 74
EOF
chmod +x "$mock_bin/curl" "$mock_bin/cp"
update() {
env -i HOME="$test_home" PATH="$PATH" \
GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \
DFS_IGNORE_COMMIT_SIGN=1 DFS_UPDATE_CHANNEL=dev DFS_DDNS_ENABLE=0 DFS_ORPHAN=1 \
DOTFILES_TEST_SIDE_EFFECTS="$fixture/side-effects" \
"$@" bash "$client/update.sh"
}
expect_failure() {
local expected=$1
shift
if update "$@" > "$fixture/update.log" 2>&1; then
printf 'Expected update failure: %s\n' "$expected" >&2
exit 1
fi
grep -Fq -- "$expected" "$fixture/update.log"
}
# Refused updates must return an error and preserve the installed checkout.
printf 'user work\n' > "$client/untracked-file"
expect_failure 'directory not clean'
grep -Fxq 'user work' "$client/untracked-file"
rm "$client/untracked-file"
expect_failure 'invalid commit id' PATH="$mock_bin:$PATH" \
DFS_UPDATE_CHANNEL=main DOTFILES_TEST_RELEASE=invalid
test "$(git -C "$client" rev-parse HEAD)" = "$initial_commit"
# Dry-run must skip fetch, DNS updates, beacons, and updater repairs.
git -C "$client" remote set-url origin "$fixture/missing-remote"
ln "$client/update.sh" "$fixture/running-updater"
printf '\n# stale updater\n' >> "$client/update.sh"
update DFS_DRY_RUN=1 DFS_DDNS_ENABLE=1 DFS_ORPHAN=0 > "$fixture/update.log" 2>&1
grep -Fq 'dry-run:' "$fixture/update.log"
test ! -e "$fixture/side-effects"
test "$fixture/running-updater" -ef "$client/update.sh"
grep -Fxq '# stale updater' "$client/update.sh"
expect_failure 'does not appear to be a git repository'
test "$(git -C "$client" rev-parse HEAD)" = "$initial_commit"
git -C "$client" remote set-url origin "$remote"
# A retry repairs a stale updater even when the checkout already matches.
update > "$fixture/update.log" 2>&1
grep -Fq 'refreshing update.sh' "$fixture/update.log"
cmp "$client/update.sh" "$client/.update.sh"
test ! "$fixture/running-updater" -ef "$client/update.sh"
grep -Fxq '# stale updater' "$fixture/running-updater"
chmod -x "$client/update.sh"
update > "$fixture/update.log" 2>&1
test -x "$client/update.sh"
# SIGKILL can leave a temporary file behind. It must not block the next update.
printf 'interrupted refresh\n' > "$client/.update.sh.interrupted"
printf '\n# Updated updater fixture.\n' >> "$remote/.update.sh"
git -C "$remote" commit -qam 'New revision'
candidate=$(git -C "$remote" rev-parse HEAD)
# A failed refresh returns its error. Retrying finishes the interrupted update.
status=0
update PATH="$mock_bin:$PATH" > "$fixture/update.log" 2>&1 || status=$?
test "$status" -eq 74
grep -Fq 'refreshing update.sh' "$fixture/update.log"
test "$(git -C "$client" rev-parse HEAD)" = "$candidate"
if cmp -s "$client/update.sh" "$client/.update.sh"; then
printf '%s\n' 'Expected the failed refresh to leave the old updater' >&2
exit 1
fi
update > "$fixture/update.log" 2>&1
cmp "$client/update.sh" "$client/.update.sh"
test -x "$client/update.sh"
# An atomic replacement failure is also recoverable and cleans its temporary copy.
mkdir "$fixture/failing-mv"
printf '#!/usr/bin/env bash\nexit 73\n' > "$fixture/failing-mv/mv"
chmod +x "$fixture/failing-mv/mv"
printf '\n# Revision for replacement failure.\n' >> "$remote/.update.sh"
git -C "$remote" commit -qam 'Replacement failure revision'
status=0
update PATH="$fixture/failing-mv:$PATH" > "$fixture/update.log" 2>&1 || status=$?
test "$status" -eq 73
temporary_files=("$client"/.update.sh.*)
test "${#temporary_files[@]}" -eq 1
test "${temporary_files[0]}" = "$client/.update.sh.interrupted"
update > "$fixture/update.log" 2>&1
cmp "$client/update.sh" "$client/.update.sh"
# Successful updates preserve the installer's special restart status.
printf '\n# Next revision.\n' >> "$remote/.update.sh"
git -C "$remote" commit -qam 'Next revision'
status=0
update DFS_UPDATED_RET=85 > "$fixture/update.log" 2>&1 || status=$?
test "$status" -eq 85
test "$(git -C "$client" rev-parse HEAD)" = "$(git -C "$remote" rev-parse HEAD)"
cmp "$client/update.sh" "$client/.update.sh"
echo 'updater recovery tests passed'