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

@@ -3,6 +3,21 @@ on:
push: ~
workflow_dispatch: ~
jobs:
test-offline:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run offline regression tests
run: |
bash tools/test-getopts.sh
bash tools/test-install.sh
bash tools/test-update.sh
bash tools/test-riot.sh
bash tools/test-riot-gpg.sh
bash tools/test-sagent-gpg-pin.sh
bash tools/test-scf.sh
bash tools/test-frigg-client.sh
test-signed-updates:
runs-on: ubuntu-latest
steps:

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
*.zwc
update.sh
/.update.sh.*

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env bash
set -e
THIS_DIR=$( cd "$( dirname "${BASH_SOURCE[0]:-${(%):-%x}}" )" && pwd )
THIS_FILE=$(basename "${BASH_SOURCE}")
@@ -10,6 +11,26 @@ DFS_IGNORE_COMMIT_SIGN=${requested_ignore_commit_sign:-${DFS_IGNORE_COMMIT_SIGN:
DFS_UPDATED_RET=${DFS_UPDATED_RET:-0}
DFS_UPDATE_CHANNEL=${DFS_UPDATE_CHANNEL:-"main"}
if [[ "$DFS_DRY_RUN" == "1" ]]; then
fmt_info "dry-run: would fetch updates for channel $DFS_UPDATE_CHANNEL, verify the selected revision, and refresh update.sh"
exit 0
fi
refresh_updater()
(
if [[ -x ./update.sh ]] && cmp -s ./.update.sh ./update.sh; then
return 0
fi
fmt_info "refreshing update.sh ..."
local updater_tmp
updater_tmp=$(mktemp ./.update.sh.XXXXXXXX)
trap 'rm -f -- "$updater_tmp"' EXIT
# Bash may still be reading the running updater. Keep its inode intact.
cp -p ./.update.sh "$updater_tmp"
chmod +x "$updater_tmp"
mv -f -- "$updater_tmp" ./update.sh
)
signed_commit_timestamp()
{
local commit=$1
@@ -108,7 +129,7 @@ git fetch --all --prune --tags
if [[ -n "$(git status -s)" ]]; then
fmt_error "directory not clean"
apost_beacon "dfs.dirty"
exit
exit 1
fi
# get the specified commit id
@@ -121,7 +142,7 @@ esac
if [[ ! "$DFS_COMMIT" =~ ^[0-9a-f]{40}$ ]]; then
fmt_error "invalid commit id"
apost_beacon "dfs.invalid-commit" "invalid commit id: ${DFS_COMMIT}"
exit
exit 1
fi
installed_commit=$(git rev-parse HEAD)
@@ -133,17 +154,15 @@ fi
# update
if [[ "$installed_commit" == "$DFS_COMMIT" ]]; then
if [[ -z "$DFS_DEV" || "$DFS_DEV" == "0" ]]; then
refresh_updater
fi
fmt_info "nothing to do"
else
fmt_info "checking out to commit $DFS_COMMIT ..."
if [[ -z "$DFS_DEV" || "$DFS_DEV" == "0" ]]; then
git -c advice.detachedHead=false checkout $DFS_COMMIT
# Bash may still be reading the running updater. Keep its inode intact.
updater_tmp=$(mktemp ./.update.sh.XXXXXXXX)
trap 'rm -f -- "$updater_tmp"' EXIT
cp -p ./.update.sh "$updater_tmp"
chmod +x "$updater_tmp"
mv -f -- "$updater_tmp" ./update.sh
refresh_updater
apost_beacon "dfs.updated"
exit "$DFS_UPDATED_RET"
else

View File

@@ -94,19 +94,21 @@ prepare_config()
return
fi
fmt_note "preparing dotfiles configurations ..."
local key value
local key value assignment
for i in "${DFS_CONFIGS[@]}"; do
if [[ "$i" == *"="* ]]; then
key=${i%%=*}
value=${i#*=}
else
key=$i
value=$(eval echo \$$key)
fi
[[ "$key" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] || fmt_fatal "invalid configuration key \"$key\""
if [[ "$i" != *"="* ]]; then value=${!key}; fi
printf -v assignment '%s=%q' "$key" "$value"
HOME_FILES_PATH+=(".config/dotfiles/env")
HOME_FILES_CONTENT+=("$key=$value")
echo -n "$key=$value "
export $key=$value
HOME_FILES_CONTENT+=("$assignment")
printf '%s ' "$assignment"
export "$key=$value"
done
echo
}
@@ -117,6 +119,82 @@ append_hist()
"$DOTFILES/tools/append_zsh_hist.sh" "$@"
}
config_file_target()
{
local filename=$1 target links=0
while [[ -L "$filename" ]]; do
((links+=1))
[[ $links -le 40 ]] || fmt_fatal "too many symlinks resolving \"$1\""
target=$(readlink "$filename") || return
if [[ "$target" == /* ]]; then
filename=$target
else
filename="$(dirname "$filename")/$target"
fi
done
printf '%s\n' "$filename"
}
rewrite_config_file()
(
local filename=$1 content=$2 action=$3
local temporary line ending link_count backup="" write_pending=0
filename=$(config_file_target "$filename") || exit 1
temporary=$(mktemp "${filename}.XXXXXXXX")
cleanup_config_write()
{
local status=$?
trap - EXIT
trap '' HUP INT TERM
if [[ "$write_pending" == 1 ]]; then
if cat "$backup" > "$filename"; then
write_pending=0
else
fmt_error "could not restore \"$filename\"; original content remains in \"$backup\""
fi
fi
if [[ "$write_pending" == 0 && -n "$backup" ]]; then rm -f -- "$backup"; fi
rm -f -- "$temporary"
exit "$status"
}
trap cleanup_config_write EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
cp -p -- "$filename" "$temporary"
# Read each complete or partial line so unrelated content keeps its original
# final newline, permissions, and symlink target.
while true; do
ending=$'\n'
if ! IFS= read -r line; then
ending=""
[[ -n "$line" ]] || break
fi
if [[ "$action" != append && "$line" == "$content" ]]; then continue; fi
printf '%s%s' "$line" "$ending"
done < "$filename" > "$temporary"
if [[ "$action" != uninstall ]]; then
if [[ -s "$temporary" && -n "$(tail -c 1 "$temporary")" ]]; then
printf '\n' >> "$temporary"
fi
printf '%s\n' "$content" >> "$temporary"
fi
if cmp -s -- "$temporary" "$filename"; then return 0; fi
link_count=$(stat -c '%h' "$filename" 2>/dev/null) || link_count=$(stat -f '%l' "$filename")
[[ "$link_count" =~ ^[1-9][0-9]*$ ]] || fmt_fatal "cannot determine hard-link count for \"$filename\""
if (( link_count > 1 )); then
# Replacing the inode would split existing hard links. Keep a complete
# backup until the in-place write has succeeded or been restored.
backup=$(mktemp "${filename}.backup.XXXXXXXX")
cp -p -- "$filename" "$backup"
write_pending=1
cat "$temporary" > "$filename"
write_pending=0
else
mv -f -- "$temporary" "$filename"
fi
)
install_file_content()
{
fmt_note "installing file content ..."
@@ -124,11 +202,18 @@ install_file_content()
local filename="$HOME/${HOME_FILES_PATH[$i]}"
local content="${HOME_FILES_CONTENT[$i]}"
fmt_info "installing \"$content\" into \"$filename\" ..."
mkdir -p $(dirname "$filename")
mkdir -p "$(dirname "$filename")"
if [ ! -f "$filename" ]; then
touch $filename
touch "$filename"
fi
if [[ "${HOME_FILES_PATH[$i]}" == .config/dotfiles/env ]]; then
# The env file can contain multiline values and arbitrary shell
# blocks. Appending lets the requested value win without parsing or
# removing existing shell code, including a repeated older value.
rewrite_config_file "$filename" "$content" append
elif ! grep -qxF -- "$content" "$filename"; then
rewrite_config_file "$filename" "$content" install
fi
grep -qxF -- "$content" "$filename" || echo "$content" >> "$filename"
done
}
@@ -140,7 +225,7 @@ uninstall_file_content()
local content=${HOME_FILES_CONTENT[$i]}
fmt_info "removing \"$content\" from \"$filename\" ..."
if [ -f "$filename" ]; then
grep -vxF -- "$content" "$filename" | tee "$filename"
rewrite_config_file "$filename" "$content" uninstall
fi
done
}
@@ -159,41 +244,40 @@ install_symlink()
fmt_error "\"$src\" does not exist! aborting this job ..."
continue
fi
mkdir -p $(dirname "$dst")
if [ -f "$dst" ]; then
if [ "$(readlink $dst)" -ef "$src" ]; then
mkdir -p "$(dirname "$dst")"
if [[ -e "$dst" || -L "$dst" ]]; then
if [[ -L "$dst" && "$dst" -ef "$src" ]]; then
continue
fi
fmt_warning "\"$dst\" already exists! stat output:"
echo ----------
stat $dst
stat "$dst"
echo ----------
yn=$(ask_for_yN "would you like to replace ${dst}?")
if [[ "$yn" == "1" ]]; then
rm $dst
rm "$dst"
else
fmt_error "aborting this job ..."
continue
fi
fi
ln -s $src $dst
ln -s "$src" "$dst"
done
}
uninstall_symlink()
{
fmt_note "uninstalling symlinks ..."
local src
for src in "${!HOME_SYMLINKS[@]}"; do
local dst=${HOME_SYMLINKS[$src]}
src="$DOTFILES/$src"
dst="$HOME/$dst"
if [ "$(readlink $dst)" -ef "$src" ]; then
local i src dst
for i in "${!HOME_SYMLINKS_SRC[@]}"; do
src="$DOTFILES/${HOME_SYMLINKS_SRC[$i]}"
dst="$HOME/${HOME_SYMLINKS_DST[$i]}"
if [[ -L "$dst" ]] && [[ "$(readlink "$dst")" == "$src" || "$dst" -ef "$src" ]]; then
fmt_info "removing symlink \"$dst\" ..."
echo ----------
stat $dst
stat "$dst"
echo ----------
rm $dst
rm "$dst"
fi
done
}
@@ -214,9 +298,11 @@ install_crontab()
uninstall_crontab()
{
local existing
if [[ -x $(command -v crontab) ]]; then
fmt_note "removing \"$CRON_JOB\" from crontab ..."
( crontab -l | grep -vxF "$CRON_JOB" ) | crontab -
existing=$(crontab -l 2>/dev/null) || return 0
printf '%s\n' "$existing" | grep -vxF "$CRON_JOB" | crontab -
else
fmt_note "crontab does not exist. skipping ..."
fi
@@ -280,7 +366,7 @@ install_update()
uninstall_update()
{
fmt_note "removing update.sh ..."
rm "${DOTFILES}/update.sh"
rm -f "${DOTFILES}/update.sh"
}
install()
@@ -320,7 +406,7 @@ FUNC=install
INSTALL_DEP=0
store_config=0
store_hist=0
for i in ${GOT_OPTS[@]}; do
for i in "${GOT_OPTS[@]}"; do
if [[ "$store_config" == "1" ]]; then
store_config=0
DFS_CONFIGS+=("$i")
@@ -341,4 +427,20 @@ for i in ${GOT_OPTS[@]}; do
* ) fmt_fatal "unknown option \"$i\"" ;;
esac
done
[[ "$store_config" == 0 ]] || fmt_fatal "option -x requires a configuration key or KEY=VALUE"
[[ "$store_hist" == 0 ]] || fmt_fatal "option -H requires a history key"
if [[ "$DFS_DRY_RUN" == 1 ]]; then
if [[ "$FUNC" == install ]]; then prepare_config; fi
fmt_note "dry run: $FUNC dotfiles"
if [[ "$FUNC" == install && "$INSTALL_DEP" == 1 ]]; then fmt_info "would install dependencies"; fi
fmt_info "would $FUNC ${DOTFILES}/update.sh and crontab entry $CRON_JOB"
for i in "${!HOME_FILES_PATH[@]}"; do
fmt_info "would $FUNC ${HOME_FILES_CONTENT[$i]} in $HOME/${HOME_FILES_PATH[$i]}"
done
for i in "${!HOME_SYMLINKS_SRC[@]}"; do
fmt_info "would $FUNC link $HOME/${HOME_SYMLINKS_DST[$i]} to $DOTFILES/${HOME_SYMLINKS_SRC[$i]}"
done
if [[ "$FUNC" == install ]]; then fmt_info "would install tmux/Vim plugins and import requested history"; fi
exit 0
fi
$FUNC

View File

@@ -306,17 +306,13 @@ prepare_ssh_cmd() {
else
local port_param='-p'
fi
CMD=(
"$ssh_bin"
"${PORT:+$port_param}" "$PORT"
"${SSH_OPTIONS[@]}"
"${EXTRA_SSH_OPTIONS[@]}"
"$SCP_SRC"
"$USERNAME${USERNAME:+@}$SERVER"
"$SCP_DST"
"${@:2}"
)
for i in ${!CMD[@]}; do if [[ -z "${CMD[i]}" ]]; then unset CMD[i]; fi; done
CMD=("$ssh_bin")
[[ -z "$PORT" ]] || CMD+=("$port_param" "$PORT")
CMD+=("${SSH_OPTIONS[@]}" "${EXTRA_SSH_OPTIONS[@]}")
[[ -z "$SCP_SRC" ]] || CMD+=("$SCP_SRC")
CMD+=("$USERNAME${USERNAME:+@}$SERVER")
[[ -z "$SCP_DST" ]] || CMD+=("$SCP_DST")
CMD+=("${@:2}")
}
# ssh
@@ -389,11 +385,10 @@ run_sshd()
run_scp() {
local src="$1"
local dst="$2"
local dst_is_remote=1
# whoever is ./*, it can't be the remote; whoever not exists on local, it's possible the remote.
# it is suggested to use ./* for local files.
if [[ "$src" != "./"* && ( "$dst" == "./"* || ( ! -e "$src" && -e "$dst" ) ) ]]; then
dst_is_remote=0
local dst_is_remote="$3"
local SCP_SRC="" SCP_DST=""
if [[ "$SERVER" == *:* ]]; then
SERVER="[$SERVER]"
fi
if [[ "$dst_is_remote" == "1" ]]; then
SCP_SRC="$src"
@@ -429,7 +424,13 @@ remove_hostkey() {
else
key="[$SERVER]:$PORT"
fi
ssh-keygen -R "$key"
CMD=(ssh-keygen -R "$key")
print_cmd
if [[ "$DFS_DRY_RUN" == "1" ]]; then
echo "${CMD[@]}"
else
"${CMD[@]}"
fi
}
# main
@@ -635,6 +636,7 @@ router() {
IFS=',' read -ra remotes <<< "${positional[0]}"
for i in ${!remotes[@]}; do if [[ -z "${remotes[i]}" ]]; then unset remotes[i]; fi; done
remotes=("${remotes[@]}")
if [[ "${#positional[@]}" == "0" || "${#remotes[@]}" == "0" ]]; then
print_help
exit 1
@@ -645,11 +647,34 @@ router() {
|| "${#positional[@]}" -gt 2 ) ]]; then
fmt_fatal "gpg-agent forwarding is only supported for interactive SSH login"
fi
for i in ${!remotes[@]}; do
remote="${remotes[i]}"
local scp_dst_is_remote=1
if [[ "${positional[1]}" == scp ]]; then
test "${#positional[@]}" -eq 4 || fmt_fatal "scp requires exactly two arguments: source and destination"
test -n "${positional[2]}" || fmt_fatal "no source path specified"
test -n "${positional[3]}" || fmt_fatal "no destination path specified"
# Resolve direction once, before any transfer can create or remove a
# local file. A ./ prefix explicitly identifies the local side.
if [[ "${positional[2]}" != "./"* && ( "${positional[3]}" == "./"* \
|| ( ! -e "${positional[2]}" && -e "${positional[3]}" ) ) ]]; then
scp_dst_is_remote=0
fi
fi
local batch_chains=()
local batch_chain first_added batch_index
local remote_index=0
while (( remote_index < ${#remotes[@]} )); do
remote="${remotes[remote_index]}"
batch_chain=${batch_chains[remote_index]:-}
remote_index=$((remote_index + 1))
[[ -n "$remote" ]] || continue
local batch_func="${remote}.batch"
if is_function "$batch_func"; then
[[ "$batch_chain" != *"|$batch_func|"* ]] || fmt_fatal "recursive batch: $remote"
first_added=${#remotes[@]}
"$batch_func"
for ((batch_index=first_added; batch_index<${#remotes[@]}; batch_index++)); do
batch_chains[batch_index]="$batch_chain|$batch_func|"
done
continue
fi
parse_remote "$remote"
@@ -698,10 +723,7 @@ router() {
fi
;;
scp )
test "${#positional[@]}" -eq 4 || fmt_fatal "scp requires exactly two arguments: source and destination"
test -n "${positional[2]}" || fmt_fatal "no source path specified"
test -n "${positional[3]}" || fmt_fatal "no destination path specified"
run_scp "${positional[2]}" "${positional[3]}"
run_scp "${positional[2]}" "${positional[3]}" "$scp_dst_is_remote"
;;
rm )
test "${#positional[@]}" -eq 2 || fmt_fatal "rm requires no arguments"

View File

@@ -25,14 +25,18 @@ usage() {
cat >&2 <<'EOF'
Usage: scf [-r] [-n NUM] SERVICE
Open the configuration file referenced by a systemd service's ExecStart.
Open a readable text file referenced by a systemd service's ExecStart.
SERVICE may be given with or without the .service suffix.
List file arguments, text entry points, file references, then directory entries.
File names and extensions do not determine eligibility.
-r recursively inspect referenced files and directories (maximum reference depth: 3)
-n open candidate NUM directly, without displaying the selection list
Environment:
SCF_MAX_CANDIDATES maximum number of candidates (default: 20)
SCF_MAX_CANDIDATES maximum number of displayed candidates (default: 20)
SCF_MAX_SCAN maximum number of filesystem paths inspected (default: 256)
SCF_MAX_BYTES total bytes parsed for recursive references (default: 1048576)
SCF_MAX_DEPTH maximum reference depth (default: 3)
EOF
exit 2
@@ -120,14 +124,14 @@ if [[ $service != *.service ]]; then
service+=.service
fi
# Keep the argument a unit name, rather than allowing it to become a
# systemctl option. This also makes accidental shell syntax harmless.
if [[ ! $service =~ ^[A-Za-z0-9_.@:%+-]+\.service$ ]]; then
# systemd uses \xHH escapes in unit names derived from paths.
checked_service=${service//\\x[0-9A-Fa-f][0-9A-Fa-f]/_}
if [[ ! $checked_service =~ ^[A-Za-z0-9_.@:%+-]+\.service$ ]]; then
echo "scf: invalid service name: $service_argument" >&2
exit 2
fi
if ! exec_start=$(systemctl show --no-pager --property=ExecStart --value "$service"); then
if ! exec_start=$(systemctl show --no-pager --property=ExecStart --value -- "$service"); then
echo "scf: cannot inspect $service" >&2
exit 1
fi
@@ -139,6 +143,8 @@ fi
# Keep recursion bounded even when configuration files refer to each other.
max_candidates=${SCF_MAX_CANDIDATES:-20}
max_scan=${SCF_MAX_SCAN:-256}
max_bytes=${SCF_MAX_BYTES:-1048576}
max_reference_depth=${SCF_MAX_DEPTH:-3}
if [[ ! $max_candidates =~ ^[0-9]+$ ]]; then
echo "scf: SCF_MAX_CANDIDATES must be a positive integer" >&2
@@ -148,165 +154,518 @@ if [[ ! $max_reference_depth =~ ^[0-9]+$ ]]; then
echo "scf: SCF_MAX_DEPTH must be a non-negative integer" >&2
exit 2
fi
if [[ ! $max_scan =~ ^[0-9]+$ ]]; then
echo "scf: SCF_MAX_SCAN must be a positive integer" >&2
exit 2
fi
if [[ ! $max_bytes =~ ^[0-9]+$ ]]; then
echo "scf: SCF_MAX_BYTES must be a positive integer" >&2
exit 2
fi
# Normalize user-provided decimal values before using Bash arithmetic.
max_candidates=$((10#$max_candidates))
max_scan=$((10#$max_scan))
max_bytes=$((10#$max_bytes))
max_reference_depth=$((10#$max_reference_depth))
if (( max_candidates < 1 )); then
echo "scf: SCF_MAX_CANDIDATES must be a positive integer" >&2
exit 2
fi
declare -A candidate_seen=()
if (( max_scan < 1 )); then
echo "scf: SCF_MAX_SCAN must be a positive integer" >&2
exit 2
fi
if (( max_bytes < 1 )); then
echo "scf: SCF_MAX_BYTES must be a positive integer" >&2
exit 2
fi
declare -A resolved_paths=()
declare -A path_kinds=()
declare -A path_sizes=()
declare -A reference_cache=()
declare -A candidate_path=()
declare -A candidate_rank=()
declare -A candidate_depth=()
declare -A traversal_depth=()
declare -A candidate_source=()
declare -A candidate_source_detail=()
config_paths=()
other_paths=()
candidate_ids=()
recursive_paths=()
recursive_depths=()
declare -A recursive_seen=()
declare -A processed_depth=()
declare -A processed_rank=()
declare -A expanded_directories=()
directory_paths=()
directory_depths=()
directory_sources=()
entry_paths=()
entry_depths=()
entry_sources=()
entry_directories=()
scan_count=0
scan_limited=false
bytes_remaining=$max_bytes
bytes_limited=false
path_pattern="/[^[:space:];,'\"})]+"
path_pattern="\"/([^\"\\\\]|\\\\.)*\"|'/([^'\\\\]|\\\\.)*'|/([^[:space:];,'\"})\\\\]|\\\\.)+"
decode_path() {
local path=$1
local decoded=""
local escape character digits
while [[ $path == *\\* ]]; do
decoded+=${path%%\\*}
path=${path#*\\}
escape=${path:0:1}
path=${path:1}
case $escape in
x)
digits=${path:0:2}
if [[ $digits =~ ^[0-9a-fA-F]{2}$ ]]; then
printf -v character '%b' "\\x$digits"
decoded+=$character
path=${path:2}
else
decoded+='\x'
fi
;;
[0-7])
digits=$escape${path:0:2}
if [[ $digits =~ ^[0-7]{3}$ ]]; then
printf -v character '%b' "\\0$digits"
decoded+=$character
path=${path:2}
else
decoded+="\\$escape"
fi
;;
s|' ') decoded+=' ' ;;
/|\"|\') decoded+=$escape ;;
a|b|e|f|n|r|t|v|\\)
printf -v character '%b' "\\$escape"
decoded+=$character
;;
*) decoded+="\\$escape" ;;
esac
done
printf '%s\n' "$decoded$path"
}
extract_paths() {
grep -a -oE "$path_pattern" || true
local path
while IFS= read -r path; do
if [[ $path == \"*\" || $path == \'*\' ]]; then
path=${path:1:-1}
fi
decode_path "$path"
done < <(grep -a -oE "$path_pattern" || true)
}
has_config_extension() {
local path=$1
[[ $path =~ \.(conf|cfg|cnf|ini|json|toml|ya?ml|xml|properties)$ ]]
# Preserve the context of each path without interpreting shell or Python code.
# Search-path assignments suppress directory expansion, while file references
# on those same lines remain candidates.
extract_references() {
local context path
while IFS=$'\t' read -r context path; do
if [[ $path == \"*\" || $path == \'*\' ]]; then
path=${path:1:-1}
fi
printf '%s\t' "$context"
decode_path "$path"
done < <(
SCF_PATH_PATTERN="$path_pattern" awk '
BEGIN {
pattern = ENVIRON["SCF_PATH_PATTERN"]
# These variables describe runtime search lists, rather than file types.
variables = "(PATH|PYTHONPATH|LD_LIBRARY_PATH|LIBRARY_PATH|MANPATH|INFOPATH|PERL5LIB|RUBYLIB|CLASSPATH|NODE_PATH|PKG_CONFIG_PATH|GI_TYPELIB_PATH|XDG_DATA_DIRS)"
assignment = "(^|[;[:space:]])(export[[:space:]]+)?" variables "[[:space:]]*\\+?="
python = "(sys\\.path(\\[[^]]*\\])?[[:space:]]*\\+?=|sys\\.path\\.(insert|append|extend)[[:space:]]*\\(|site\\.addsitedir[[:space:]]*\\()"
}
function emit(fragment, context, path, key, previous) {
while (match(fragment, pattern)) {
previous = RSTART > 1 ? substr(fragment, RSTART-1, 1) : ""
path = substr(fragment, RSTART, RLENGTH)
fragment = substr(fragment, RSTART + RLENGTH)
# A slash inside a URL, version, or variable expansion is not an
# absolute path token. Quoted absolute paths keep their full value.
if (substr(path, 1, 1) == "/" && previous != "" &&
previous !~ /[[:space:]]/ && !index("=<>({[,", previous)) continue
key = context SUBSEP path
if (!seen[key]++) printf "%s\t%s\n", context, path
}
}
function uncomment(line, i, character, quoted, escaped) {
quoted = quote
for (i = 1; i <= length(line); i++) {
character = substr(line, i, 1)
if (escaped) { escaped = 0; continue }
if (character == "\\" && quoted != "\047") { escaped = 1; continue }
if (quoted != "") {
if (character == quoted) quoted = ""
} else if (character == "\"" || character == "\047") {
quoted = character
} else if (character == "#" && (i == 1 || substr(line, i-1, 1) ~ /[[:space:];]/)) {
return substr(line, 1, i-1)
}
}
return line
}
# End a shell value at its unquoted token boundary. A Python search-path
# call/list may span lines, but statements after it keep their own context.
function consume_search(line, start, i, character, escaped) {
for (i = start; i <= length(line); i++) {
character = substr(line, i, 1)
if (escaped) { escaped = 0; continue }
if (character == "\\" && quote != "\047") { escaped = 1; continue }
if (quote != "") {
if (character == quote) quote = ""
} else if (character == "\"" || character == "\047") {
quote = character
} else if (mode == "shell" && character ~ /[[:space:];]/) {
mode = ""
return i
} else if (mode == "python") {
if (character == "[" || character == "(") balance++
if ((character == "]" || character == ")") && balance > 0) {
balance--
if (method && balance == 0) {
mode = ""
return i+1
}
}
if (character == ";" && balance == 0) {
mode = ""
return i
}
}
}
if (quote == "" && balance == 0 && !escaped) mode = ""
return i
}
{
line = uncomment($0)
if (mode == "" && line ~ /^[[:space:]]*(;|\/\/)/) next
cursor = 1
while (cursor <= length(line) || mode != "") {
if (mode != "") {
stop = consume_search(line, cursor)
emit(substr(line, cursor, stop-cursor), "search")
cursor = stop
if (cursor > length(line)) break
continue
}
rest = substr(line, cursor)
shell_start = 0
python_start = 0
if (match(rest, assignment)) {
shell_start = RSTART
shell_length = RLENGTH
}
if (match(rest, python)) {
python_start = RSTART
python_length = RLENGTH
}
if (!shell_start && !python_start) {
emit(rest, "file")
break
}
if (shell_start && (!python_start || shell_start < python_start)) {
start = shell_start
header_length = shell_length
mode = "shell"
method = 0
} else {
start = python_start
header_length = python_length
mode = "python"
method = substr(rest, start+header_length-1, 1) == "("
}
emit(substr(rest, 1, start-1), "file")
quote = ""
balance = method ? 1 : 0
cursor += start+header_length-1
}
}
'
)
}
is_config_path() {
local path=$1
has_config_extension "$path" \
|| [[ $path == *config* || $path == *configuration* ]]
# Cache both lexical resolution and physical attributes. Callers use the
# globals canonical_path and path_kind so cache updates stay in this shell.
inspect_path() {
local path=$1 controls size
[[ $path == /* ]] || return 1
canonical_path=""
path_kind=""
if [[ -n ${resolved_paths[$path]+cached} ]]; then
canonical_path=${resolved_paths[$path]}
[[ -n $canonical_path ]] || return 1
else
resolved_paths[$path]=""
case $path in
/dev|/dev/*|/proc|/proc/*|/sys|/sys/*) return 1 ;;
esac
canonical_path=$(readlink -f -- "$path") || return 1
case $canonical_path in
/dev|/dev/*|/proc|/proc/*|/sys|/sys/*) return 1 ;;
esac
resolved_paths[$path]=$canonical_path
fi
if [[ -n ${path_kinds[$canonical_path]+cached} ]]; then
path_kind=${path_kinds[$canonical_path]}
[[ $path_kind != skip ]]
return
fi
if (( scan_count >= max_scan )); then
scan_limited=true
return 1
fi
scan_count=$((scan_count + 1))
path_kind=skip
if [[ -d $canonical_path ]]; then
path_kind=directory
elif [[ -f $canonical_path && -r $canonical_path ]]; then
# Inspect a bounded prefix. Allow whitespace, ANSI escapes and UTF-8 bytes,
# but reject NUL and other binary controls even after an ASCII first line.
if controls=$(head -c 65536 -- "$canonical_path" | tr -d '\11\12\14\15\33\40-\176\200-\377' | wc -c) &&
(( controls == 0 )) && size=$(stat -c '%s' -- "$canonical_path"); then
path_kind=text
path_sizes[$canonical_path]=$size
if head -c 2 -- "$canonical_path" | grep -qxF '#!'; then
path_kind=script
fi
fi
fi
path_kinds[$canonical_path]=$path_kind
[[ $path_kind != skip ]]
}
queue_directory() {
directory_paths+=("$1")
directory_depths+=("$2")
directory_sources+=("$3")
}
add_candidate() {
local path=$1
local depth=$2
local source=$3
local source_detail=${4:-}
local path=$1 rank=$2 depth=$3 source=$4 detail=$5
inspect_path "$path" || return 0
[[ $path_kind != directory ]] || return 0
local id=$canonical_path
[[ -f $path ]] || return 1
[[ -n ${candidate_seen[$path]+seen} ]] && return 0
(( ${#candidate_seen[@]} < max_candidates )) || return 1
candidate_seen[$path]=1
candidate_depth[$path]=$depth
candidate_source[$path]=$source
candidate_source_detail[$path]=$source_detail
if is_config_path "$path"; then
config_paths+=("$path")
else
other_paths+=("$path")
if [[ -z ${traversal_depth[$id]+seen} ]] || (( depth < traversal_depth[$id] )); then
traversal_depth[$id]=$depth
if [[ $recursive == true ]] && (( depth < max_reference_depth )); then
recursive_paths+=("$id")
fi
fi
if [[ $recursive == true && -n ${candidate_rank[$id]+seen} ]] &&
(( rank < candidate_rank[$id] && traversal_depth[$id] < max_reference_depth )); then
recursive_paths+=("$id")
fi
if [[ -z ${candidate_rank[$id]+seen} ]]; then
candidate_ids+=("$id")
candidate_path[$id]=$path
elif (( rank > candidate_rank[$id] ||
(rank == candidate_rank[$id] && depth >= candidate_depth[$id]) )); then
return 0
fi
candidate_rank[$id]=$rank
candidate_depth[$id]=$depth
candidate_source[$id]=$source
candidate_source_detail[$id]=$detail
}
enqueue_recursive() {
local path=$1
local depth=$2
[[ $recursive == true ]] || return 0
(( depth <= max_reference_depth )) || return 0
[[ -f $path ]] || return 0
[[ -n ${recursive_seen[$path]+seen} ]] && return 0
recursive_seen[$path]=1
recursive_paths+=("$path")
recursive_depths+=("$depth")
consider_reference() {
local path=$1 rank=$2 depth=$3 source=$4 detail=$5 context=${6:-file}
# Defer directory probing until all known explicit files have been inspected.
if [[ -d $path ]]; then
if [[ $recursive == true && $context != search ]]; then
queue_directory "$path" "$depth" "$source"
fi
else
add_candidate "$path" "$rank" "$depth" "$source" "$detail"
fi
}
expand_directory() {
local directory=$1
local depth=$2
local source=$3
local path
local entries
[[ $recursive == true && -d $directory ]] || return 0
# dotglob also catches hidden configuration files. nullglob prevents the
# literal pattern from being treated as a candidate for an empty directory.
shopt -s dotglob nullglob
entries=("$directory"/*)
shopt -u dotglob nullglob
for path in "${entries[@]}"; do
# A service's configuration often contains runtime directories such as
# Python's bin directory. Only configuration-looking files from a
# directory should consume the candidate budget.
has_config_extension "$path" || continue
add_candidate "$path" "$depth" "$source" "directory $directory" || continue
enqueue_recursive "$path" "$depth"
done
}
consider_initial_path() {
local path=$1
if [[ -f $path ]]; then
add_candidate "$path" 0 "ExecStart" || true
elif [[ -d $path ]]; then
expand_directory "$path" 0 "ExecStart"
local path=$1 depth=$2 source=$3
inspect_path "$path" || return 0
[[ $path_kind == directory ]] || return 0
local id=$canonical_path entry
if [[ -n ${expanded_directories[$id]+seen} ]] &&
(( expanded_directories[$id] <= depth )); then
return 0
fi
expanded_directories[$id]=$depth
shopt -s dotglob nullglob
for entry in "$path"/*; do
# Only expand one level. Referenced subdirectories get their own tasks.
[[ -f $entry ]] || continue
entry_paths+=("$entry")
entry_depths+=("$depth")
entry_sources+=("$source")
entry_directories+=("$path")
done
shopt -u dotglob nullglob
}
# systemctl's ExecStart value contains both `path=` and `argv[]=`. Pull out
# absolute path tokens, then drop the first one (the executable itself).
# NixOS-generated configuration files are normally immutable regular files in
# /nix/store, but the same also works for /etc and /run paths.
mapfile -t initial_paths < <(
# Keep argv[0] separate for each command, so a file used as an entry point
# in one ExecStart can still be a higher-ranked argument in another command.
extract_arguments() {
awk '
{
rest = $0
while (match(rest, /argv\[[0-9]*\]=/)) {
field = substr(rest, RSTART, RLENGTH)
rest = substr(rest, RSTART+RLENGTH)
quote = ""
escaped = 0
for (stop = 1; stop <= length(rest); stop++) {
character = substr(rest, stop, 1)
if (escaped) { escaped = 0; continue }
if (character == "\\") { escaped = 1; continue }
if (quote != "") {
if (character == quote) quote = ""
} else if (character == "\"" || character == "\047") {
quote = character
# systemctl prints the shell command supplied to -c without adding
# quotes. Its semicolons belong to argv until a property boundary.
} else if (character == ";") {
tail = substr(rest, stop)
if (tail ~ /^;[[:space:]]*ignore_errors=(yes|no)[[:space:]]*;[[:space:]]*start_time=/ ||
tail ~ /^;[[:space:]]*argv\[[0-9]*\]=/ ||
tail ~ /^;[[:space:]]*}[[:space:]]*($|\{[[:space:]]*path=)/) break
}
}
value = substr(rest, 1, stop-1)
rest = substr(rest, stop+1)
if (field == "argv[0]=") continue
if (field == "argv[]=") {
sub(/^[[:space:]]*/, "", value)
quote = ""
escaped = 0
for (first = 1; first <= length(value); first++) {
character = substr(value, first, 1)
if (escaped) { escaped = 0; continue }
if (character == "\\") { escaped = 1; continue }
if (quote != "") {
if (character == quote) quote = ""
} else if (character == "\"" || character == "\047") {
quote = character
} else if (character ~ /[[:space:]]/) {
break
}
}
value = substr(value, first)
}
print value
}
}
'
}
mapfile -t entry_points < <(
printf '%s\n' "$exec_start" \
| extract_paths \
| awk '!seen[$0]++'
| grep -oE '(^|\{[[:space:]]*)path=[^;]+' \
| extract_paths | awk '!seen[$0]++'
)
mapfile -t initial_paths < <(
printf '%s\n' "$exec_start" | extract_arguments | extract_paths | awk '!seen[$0]++'
)
if (( ${#initial_paths[@]} > 0 )); then
initial_paths=("${initial_paths[@]:1}")
fi
# Process every explicit argument before entry points or directory contents.
for path in "${initial_paths[@]}"; do
consider_initial_path "$path"
consider_reference "$path" 0 0 ExecStart argument
done
for path in "${entry_points[@]}"; do
add_candidate "$path" 1 0 ExecStart "entry point"
done
paths=("${config_paths[@]}")
if (( ${#paths[@]} == 0 )); then
paths=("${other_paths[@]}")
fi
if [[ $recursive == true ]]; then
for path in "${paths[@]}"; do
enqueue_recursive "$path" 0
done
recursive_index=0
while (( recursive_index < ${#recursive_paths[@]} )); do
path=${recursive_paths[recursive_index]}
depth=${recursive_depths[recursive_index]}
recursive_index=$((recursive_index + 1))
(( depth < max_reference_depth )) || continue
file_index=0
directory_index=0
entry_index=0
while [[ $recursive == true ]]; do
if (( file_index < ${#recursive_paths[@]} )); then
id=${recursive_paths[file_index]}
file_index=$((file_index + 1))
depth=${traversal_depth[$id]}
if [[ -n ${processed_depth[$id]+seen} ]] &&
(( processed_depth[$id] <= depth && processed_rank[$id] <= candidate_rank[$id] )); then
continue
fi
processed_depth[$id]=$depth
processed_rank[$id]=${candidate_rank[$id]}
next_depth=$((depth + 1))
mapfile -t referenced_paths < <(extract_paths < "$path")
for referenced_path in "${referenced_paths[@]}"; do
if [[ -f $referenced_path ]]; then
add_candidate "$referenced_path" "$next_depth" "$path" || continue
enqueue_recursive "$referenced_path" "$next_depth"
elif [[ -d $referenced_path ]]; then
expand_directory "$referenced_path" "$next_depth" "$path"
reference_rank=2
# A directory neighbour does not gain stronger provenance merely by
# mentioning another file. Keep that branch behind explicit references.
if (( candidate_rank[$id] > reference_rank )); then reference_rank=${candidate_rank[$id]}; fi
if [[ -z ${reference_cache[$id]+cached} ]]; then
read_bytes=${path_sizes[$id]}
if (( read_bytes > bytes_remaining )); then
read_bytes=$bytes_remaining
bytes_limited=true
# A cut path on the last line must not become a different candidate.
reference_cache[$id]=$(head -c "$read_bytes" -- "$id" | sed '$d' | extract_references)
else
reference_cache[$id]=$(head -c "$read_bytes" -- "$id" | extract_references)
fi
done
done
paths=("${config_paths[@]}")
if (( ${#paths[@]} == 0 )); then
paths=("${other_paths[@]}")
bytes_remaining=$((bytes_remaining - read_bytes))
fi
while IFS=$'\t' read -r context referenced_path; do
[[ $context == file || $context == search ]] || continue
consider_reference "$referenced_path" "$reference_rank" "$next_depth" "$id" "file reference" "$context"
if [[ $scan_limited == true ]] && (( scan_count >= max_scan )); then break; fi
done <<< "${reference_cache[$id]}"
elif (( entry_index < ${#entry_paths[@]} )); then
if (( scan_count >= max_scan )); then scan_limited=true; break; fi
add_candidate "${entry_paths[entry_index]}" 3 "${entry_depths[entry_index]}" \
"${entry_sources[entry_index]}" "directory ${entry_directories[entry_index]}"
entry_index=$((entry_index + 1))
elif (( directory_index < ${#directory_paths[@]} )); then
if (( scan_count >= max_scan )); then scan_limited=true; break; fi
expand_directory "${directory_paths[directory_index]}" \
"${directory_depths[directory_index]}" "${directory_sources[directory_index]}"
directory_index=$((directory_index + 1))
else
break
fi
done
# Stable insertion by source rank and depth preserves discovery order for ties.
paths=()
for id in "${candidate_ids[@]}"; do
position=${#paths[@]}
while (( position > 0 )); do
previous=${paths[position - 1]}
if (( candidate_rank[$previous] < candidate_rank[$id] ||
(candidate_rank[$previous] == candidate_rank[$id] &&
candidate_depth[$previous] <= candidate_depth[$id]) )); then
break
fi
paths[position]=${paths[position - 1]}
position=$((position - 1))
done
paths[position]=$id
done
if [[ $scan_limited == true ]]; then
printf 'scf: inspection truncated at SCF_MAX_SCAN=%s; increase it to inspect more references\n' "$max_scan" >&2
fi
if [[ $bytes_limited == true ]]; then
printf 'scf: recursive parsing truncated at SCF_MAX_BYTES=%s; increase it to read more text\n' "$max_bytes" >&2
fi
if (( ${#paths[@]} > max_candidates )); then
printf 'scf: showing %s of %s text files (SCF_MAX_CANDIDATES); increase it to show more\n' \
"$max_candidates" "${#paths[@]}" >&2
paths=("${paths[@]:0:max_candidates}")
fi
if (( ${#paths[@]} == 0 )); then
echo "scf: no existing configuration path found in ExecStart of $service" >&2
echo "scf: no existing configuration or script path found in ExecStart of $service" >&2
echo "ExecStart: $exec_start" >&2
exit 1
fi
@@ -320,18 +679,20 @@ if [[ -n $selection_number ]]; then
echo "scf: candidate number $selection_number is out of range (1-${#paths[@]})" >&2
exit 2
fi
config_path=${paths[selection_number - 1]}
selected_id=${paths[selection_number - 1]}
config_path=${candidate_path[$selected_id]}
elif (( ${#paths[@]} > 1 )); then
declare -A displayed_indices=()
for i in "${!paths[@]}"; do
displayed_indices["${paths[i]}"]=$((i + 1))
done
printf '%sscf: multiple possible configuration files for %s:%s\n' \
printf '%sscf: multiple referenced text files for %s:%s\n' \
"$color_prompt" "$service" "$color_reset" >&2
for i in "${!paths[@]}"; do
path=${paths[i]}
source=${candidate_source[$path]}
id=${paths[i]}
path=${candidate_path[$id]}
source=${candidate_source[$id]}
if [[ $source == ExecStart ]]; then
source_label=ExecStart
elif [[ -n ${displayed_indices[$source]+seen} ]]; then
@@ -339,14 +700,14 @@ elif (( ${#paths[@]} > 1 )); then
else
source_label=$source
fi
source_detail=${candidate_source_detail[$path]}
source_detail=${candidate_source_detail[$id]}
if [[ -n $source_detail ]]; then
source_label+=" ($source_detail)"
fi
printf '%s %d) %s%s\n' \
"$color_item" "$((i + 1))" "$path" "$color_reset" >&2
printf '%s depth: %d; derived from: %s%s\n' \
"$color_detail" "${candidate_depth[$path]}" "$source_label" "$color_reset" >&2
printf '%s %s; depth: %d; derived from: %s%s\n' \
"$color_detail" "${path_kinds[$id]}" "${candidate_depth[$id]}" "$source_label" "$color_reset" >&2
done
read -r -p "${color_prompt}Select a file [1]: ${color_reset}" selection
selection=${selection:-1}
@@ -359,9 +720,11 @@ elif (( ${#paths[@]} > 1 )); then
echo "scf: invalid selection" >&2
exit 2
fi
config_path=${paths[selection - 1]}
selected_id=${paths[selection - 1]}
config_path=${candidate_path[$selected_id]}
else
config_path=${paths[0]}
selected_id=${paths[0]}
config_path=${candidate_path[$selected_id]}
fi
if [[ $interactive == false ]]; then

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'