#!/usr/bin/env bash set -euo pipefail ROOT=$(cd "$(dirname "$0")/../.." && pwd) # shellcheck disable=SC1090 source "${IP_SSL_TEST_HELPERS:-$ROOT/scripts/lib/ip-ssl.sh}" TEMP=$(mktemp -d) trap 'rm -rf "$TEMP"' EXIT fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } export ACME_LOG="$TEMP/arguments" RELOAD_LOG="$TEMP/reloads" CRON_FILE="$TEMP/crontab" export ISSUE_MODE=ok RENEW_MODE=ok INSTALL_MODE=ok RELOAD_FAIL=0 export SSL_CERT_FILE="$TEMP/ca.pem" ipv4=198.51.100.8 ipv6=2001:4860::1 port=$((20000+RANDOM)) openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3 \ -subj /CN=IP-fixture-CA -keyout "$TEMP/ca.key" -out "$SSL_CERT_FILE" >/dev/null 2>&1 serial=0 touch "$TEMP/ca-index" printf '01\n' > "$TEMP/ca-serial" cat > "$TEMP/ca.conf" </dev/null 2>&1 printf 'subjectAltName=%s\n' "$san" > "$TEMP/ext" if [[ "$name" == expired ]]; then openssl ca -config "$TEMP/ca.conf" -in "$TEMP/$name.csr" -cert "$SSL_CERT_FILE" -keyfile "$TEMP/ca.key" \ -startdate 20200101000000Z -enddate 20200102000000Z -batch -notext \ -extfile "$TEMP/ext" -out "$TEMP/$name.pem" >/dev/null 2>&1 else openssl x509 -req -in "$TEMP/$name.csr" -CA "$SSL_CERT_FILE" -CAkey "$TEMP/ca.key" \ -set_serial "$((++serial))" -days 2 -extfile "$TEMP/ext" -out "$TEMP/$name.pem" >/dev/null 2>&1 fi cat "$SSL_CERT_FILE" >> "$TEMP/$name.pem" done mkdir "$TEMP/mockbin" "$TEMP/acme home" "$TEMP/legacy certificates" export PATH="$TEMP/mockbin:$PATH" printf '13 0 * * * /unrelated-cron\n' > "$CRON_FILE" acme="$TEMP/acme home/acme.sh" legacy="$TEMP/legacy certificates" cert_dir="$TEMP/cert's directory" state="$cert_dir/.xui-ip-ssl" runner="$state/renew-v1" mkdir -p "$cert_dir" "$legacy/$ipv4" "$legacy/${ipv4}_ecc" "$legacy/example.net_ecc" printf "CERT_HOME='%s'\n" "$legacy" > "${acme%/*}/account.conf" printf 'unrelated certificate\n' > "$legacy/example.net_ecc/marker" for suffix in '' _ecc; do printf "Le_Alt='no'\nLe_NextRenewTime='1'\nLe_RealKeyPath='%s/privkey.pem'\nLe_RealFullChainPath='%s/fullchain.pem'\n" \ "$cert_dir" "$cert_dir" > "$legacy/$ipv4$suffix/$ipv4.conf" done cp "$legacy/${ipv4}_ecc/$ipv4.conf" "$TEMP/legacy.conf" cp "${acme%/*}/account.conf" "$TEMP/account.conf" cp "$TEMP/old.pem" "$cert_dir/fullchain.pem" cp "$TEMP/old.key" "$cert_dir/privkey.pem" cat > "$TEMP/mockbin/crontab" <<'MOCK' #!/usr/bin/env bash case "$1" in -l) cat "$CRON_FILE" ;; -) cat > "$CRON_FILE" ;; *) exit 1 ;; esac MOCK cat > "$acme" <<'MOCK' #!/usr/bin/env bash set -euo pipefail action=$1 printf 'CALL\n' >> "$ACME_LOG" printf 'arg=%s\n' "$@" >> "$ACME_LOG" shift home='' cert_home='' account='' domain='' san='' key='' chain='' reload='' while (($#)); do case "$1" in --home) home=$2; shift ;; --cert-home) cert_home=$2; shift ;; --accountconf) account=$2; shift ;; -d) if [[ -z "$domain" ]]; then domain=$2; else san=$2; fi shift ;; --key-file) key=$2; shift ;; --fullchain-file) chain=$2; shift ;; --reloadcmd) reload=$2; shift ;; esac shift done # Like upstream, load the account config after applying command-line arguments. CERT_HOME=${cert_home:-${home:-${0%/*}}} if [[ -z "$account" ]]; then account="${home:-${0%/*}}/account.conf"; fi # shellcheck disable=SC1090 if [[ -f "$account" ]]; then source "$account"; fi entry="$CERT_HOME/${domain}_ecc" conf="$entry/$domain.conf" case "$action" in --version) printf 'v3.1.5\n' ;; --issue|--renew) mkdir -p "$entry" if [[ "$action" == --issue ]]; then printf "Le_Alt='%s'\n" "${san:-no}" > "$conf" if [[ "$ISSUE_MODE" == fail ]]; then exit 1; fi else if [[ "$RENEW_MODE" == skip ]]; then exit 2; fi if [[ -n "${RENEW_BARRIER:-}" ]]; then : > "$RENEW_BARRIER.ready" read -r _ < "$RENEW_BARRIER" fi # Renew reuses stored destinations and advances the schedule before copying. # shellcheck disable=SC1090 source "$conf" printf "Le_NextRenewTime='advanced'\n" >> "$conf" cp "$ISSUED_KEY" "$Le_RealKeyPath" cp "$ISSUED_CERT" "$Le_RealFullChainPath" if [[ "$RENEW_MODE" == fail ]]; then exit 1; fi exit 0 fi printf "Le_NextRenewTime='issued'\n" >> "$conf" ;; --upgrade|--register-account) : ;; --installcert) printf 'Le_RealKeyPath=%q\nLe_RealFullChainPath=%q\n' "$key" "$chain" >> "$conf" [[ -z "$account" || "$account" == */pending/account.conf ]] || exit 1 if [[ "$INSTALL_MODE" == fail ]]; then printf 'broken chain\n' > "$chain"; exit 1; fi if [[ "$INSTALL_MODE" != no-key ]]; then cp "$ISSUED_KEY" "$key"; fi if [[ "$INSTALL_MODE" != no-chain ]]; then cp "$ISSUED_CERT" "$chain"; fi if [[ -n "$reload" ]]; then sh -c "$reload"; fi ;; *) printf 'Unexpected ACME operation: %s\n' "$action" >&2; exit 1 ;; esac MOCK env chmod +x "$acme" "$TEMP/mockbin/crontab" reload="test \"\$RELOAD_FAIL\" = 0 && printf 'reloaded\\n' >> '$RELOAD_LOG'" fixture() { export ISSUED_CERT="$TEMP/$1.pem" ISSUED_KEY="$TEMP/${2:-$1}.key" } issue() { ip_ssl_issue_and_install "$acme" "${1:-$ipv4}" "$ipv6" "$port" "${2:-$cert_dir}" "$reload" } live_is() { cmp "$TEMP/$1.pem" "$cert_dir/fullchain.pem" && cmp "$TEMP/$1.key" "$cert_dir/privkey.pem" } legacy_is_intact() { cmp "$TEMP/legacy.conf" "$legacy/$ipv4/$ipv4.conf" && cmp "$TEMP/legacy.conf" "$legacy/${ipv4}_ecc/$ipv4.conf" && cmp "$TEMP/account.conf" "${acme%/*}/account.conf" && grep -qx 'unrelated certificate' "$legacy/example.net_ecc/marker" } reject() { if "$@" > "$TEMP/rejected" 2>&1; then fail "unexpected success: $*"; fi } fixture new ISSUE_MODE=fail reject issue if ! live_is old || ! legacy_is_intact; then fail 'failed dual-stack order changed prior certificate or ACME state'; fi reject issue 198.51.100.9 "$TEMP/first" [[ ! -e "$legacy/198.51.100.9_ecc" && ! -e "$TEMP/first/fullchain.pem" ]] || fail 'failed first order left public files or a renewable entry' ISSUE_MODE=ok for mode in fail no-key no-chain; do INSTALL_MODE="$mode" reject issue if ! live_is old || ! legacy_is_intact; then fail "$mode installation changed prior certificate or ACME state"; fi done INSTALL_MODE=ok for invalid in v4 dns; do fixture "$invalid" reject issue if ! live_is old || ! legacy_is_intact; then fail 'missing IP SAN changed prior certificate or ACME state'; fi done fixture new old reject issue if ! live_is old || ! legacy_is_intact; then fail 'wrong key changed prior certificate or ACME state'; fi fixture new # Fault hooks are called indirectly by the sourced lifecycle functions. # shellcheck disable=SC2317 chmod() { if [[ "$1" == 600 && "$*" == *'/gen.'* ]]; then return 1; fi command chmod "$@" } reject issue unset -f chmod if ! live_is old || ! legacy_is_intact; then fail 'chmod failure changed prior certificate or ACME state'; fi printf 'PASS: issuance, installation, SAN, key, partial and permission failures preserve prior state\n' # shellcheck disable=SC2317 mv() { if [[ "$*" == *'.xui-retired-'* && "${!#}" == "$legacy/${ipv4}_ecc" ]]; then return 1; fi command mv "$@" } ISSUE_MODE=fail reject issue grep -Fq "$state/pending" "$TEMP/rejected" || fail 'journal location missing from recovery error' compgen -G "$legacy/.xui-retired-*-${ipv4}_ecc" >/dev/null || fail 'only renewal recovery copy was discarded' unset -f mv reject issue legacy_is_intact || fail 'subsequent attempt did not finish ACME recovery' ISSUE_MODE=ok # shellcheck disable=SC2317 mv() { if [[ "${!#}" == "$cert_dir/privkey.pem" || ( "$*" == *'/pending/restore '* && "${!#}" == "$cert_dir/fullchain.pem" ) ]]; then return 1 fi command mv "$@" } reject issue grep -Fq "$state/pending" "$TEMP/rejected" || fail 'live recovery error omitted journal location' cmp "$TEMP/old.pem" "$state/pending/live/fullchain.pem" || fail 'live recovery copy was lost' unset -f mv ISSUE_MODE=fail reject issue if ! live_is old || ! legacy_is_intact; then fail 'subsequent attempt did not finish live restoration'; fi [[ ! -L "$cert_dir/fullchain.pem" ]] || fail 'original regular file type was not recovered' ISSUE_MODE=ok # shellcheck disable=SC2317 mv() { command mv "$@" || return if [[ "${!#}" == "$cert_dir/fullchain.pem" && "$*" == *'/pending/link '* ]]; then kill -KILL "$BASHPID"; fi } reject issue unset -f mv if [[ ! -d "$state/pending" ]] || ! live_is old; then fail 'interrupted transition exposed a mixed pair'; fi ISSUE_MODE=fail reject issue if ! live_is old || ! legacy_is_intact; then fail 'interrupted transition failed to recover'; fi ISSUE_MODE=ok printf 'PASS: restoration failures retain backups and interruptions recover on next run\n' : > "$ACME_LOG" RELOAD_FAIL=1 issue if ! live_is new || [[ ! -f "$state/current/reload-pending" ]]; then fail 'reload failure discarded valid deployment'; fi [[ "$(stat -Lc %a "$cert_dir/privkey.pem")" == 600 ]] || fail 'private key permissions changed' [[ "$(stat -Lc %a "$cert_dir/fullchain.pem")" == 644 ]] || fail 'certificate permissions changed' [[ ! -e "$legacy/$ipv4" && ! -e "$legacy/${ipv4}_ecc" ]] || fail 'old cron can still target live paths' [[ "$(grep -cx 'arg=--listen-v4' "$ACME_LOG")" == 1 && "$(grep -cx 'arg=--listen-v6' "$ACME_LOG")" == 1 ]] || fail 'dual-stack flags absent' [[ "$(grep -cx "arg=$ipv6" "$ACME_LOG")" == 1 ]] || fail 'IPv6 SAN duplicated or missing' grep -Fq '/unrelated-cron' "$CRON_FILE" || fail 'crontab lost an unrelated entry' [[ "$(grep -c 'x-ui managed IP certificate' "$CRON_FILE")" == 1 ]] || fail 'persistent cron missing or duplicated' cmp "$TEMP/account.conf" "${acme%/*}/account.conf" || fail 'global account config changed' grep -qx 'unrelated certificate' "$legacy/example.net_ecc/marker" export RELOAD_FAIL=0 RENEW_MODE=skip "$runner" [[ ! -f "$state/current/reload-pending" && "$(cat "$RELOAD_LOG")" == reloaded ]] || fail 'fresh-shell reload retry failed' printf 'PASS: validated commit preserves modes, retires old live destinations and retries panel reload\n' working=$(readlink "$state/current") working_conf="$state/current/acme/${ipv4}_ecc/$ipv4.conf" cp "$working_conf" "$TEMP/working.conf" RENEW_MODE=ok for invalid in v4 expired; do fixture "$invalid"; reject "$runner"; live_is new || fail "$invalid renewal exposed invalid files"; done fixture later old reject "$runner" live_is new || fail 'wrong renewal key replaced live pair' fixture later for mode in no-key no-chain; do INSTALL_MODE="$mode"; reject "$runner"; done INSTALL_MODE=ok if ! live_is new || ! cmp "$TEMP/working.conf" "$working_conf"; then fail 'rejected renewal committed advanced ACME state'; fi [[ "$(readlink "$state/current")" == "$working" ]] || fail 'rejected renewal changed generation' # Start a fresh TLS process using the unchanged panel paths after rejecting a renewal. ( openssl s_server -quiet -www -accept "127.0.0.1:$port" -cert "$cert_dir/fullchain.pem" \ -key "$cert_dir/privkey.pem" > "$TEMP/tls.log" 2>&1 & tls_pid=$! trap 'if kill -0 "$tls_pid" 2>/dev/null; then kill "$tls_pid"; fi; wait "$tls_pid" 2>/dev/null || [[ $? == 143 ]]' EXIT for ((attempt=0; attempt<100; attempt++)); do kill -0 "$tls_pid" || break if curl --noproxy '*' --silent --fail --cacert "$SSL_CERT_FILE" --connect-timeout 1 --max-time 3 \ --connect-to "$ipv4:$port:127.0.0.1:$port" "https://$ipv4:$port/" >/dev/null; then exit 0; fi sleep .01 done cat "$TEMP/tls.log" >&2 fail 'TLS restart could not load the last known-good certificate' ) # shellcheck disable=SC2317 mv() { if [[ "${!#}" == "$state/current" ]]; then return 1; fi command mv "$@" } reject ip_ssl_scheduled "$cert_dir" unset -f mv if ! live_is new || ! cmp "$TEMP/working.conf" "$working_conf"; then fail 'promotion failure damaged the previous generation'; fi "$runner" if ! live_is later || ! grep -q advanced "$working_conf"; then fail 'valid persistent renewal did not commit files and ACME state'; fi printf 'PASS: actual TLS startup can read last known-good pair after rejected renewals; valid renewal promotes both files\n' # Pause renewal while it holds the destination lock. An unrelated destination # completes during the wait, while two competing manual requests share the lock. export RENEW_BARRIER="$TEMP/renewal" mkfifo "$RENEW_BARRIER" fixture v4 "$runner" > "$TEMP/concurrent-renewal" 2>&1 & renew_pid=$! for ((attempt=0; attempt<500; attempt++)); do [[ ! -f "$RENEW_BARRIER.ready" ]] || break sleep .01 done [[ -f "$RENEW_BARRIER.ready" ]] || fail 'renewal did not reach the deterministic barrier' if flock -n "$state/lock" true; then fail 'renewal was not holding the destination lock'; fi fixture old issue "$ipv4" > "$TEMP/concurrent-manual" 2>&1 & manual_pid=$! fixture new issue 198.51.100.9 > "$TEMP/concurrent-invalid" 2>&1 & invalid_pid=$! issue "$ipv4" "$TEMP/independent" live_is later || fail 'a competing request changed live files while renewal held the lock' printf 'continue\n' > "$RENEW_BARRIER" if wait "$renew_pid"; then fail 'invalid concurrent renewal succeeded'; fi wait "$manual_pid" || { cat "$TEMP/concurrent-manual"; fail 'concurrent manual issuance failed'; } if wait "$invalid_pid"; then fail 'wrong identifier unexpectedly committed'; fi live_is old || fail 'failed operation rolled back newer successful deployment' unset RENEW_BARRIER printf 'PASS: manual, renewal and shared-destination promotion serialize; unrelated destination progresses\n' # Fail the first pointer swap while a second valid operation is waiting to # promote. Its new state must survive cleanup of the earlier transaction. promotion="$TEMP/promotion" mkfifo "$promotion" # shellcheck disable=SC2317 mv() { if [[ "${!#}" == "$state/current" && "${FAIL_PROMOTION:-0}" == 1 ]]; then : > "$promotion.ready" read -r _ < "$promotion" return 1 fi command mv "$@" } fixture new FAIL_PROMOTION=1 issue > "$TEMP/failed-promotion" 2>&1 & failed_pid=$! for ((attempt=0; attempt<500; attempt++)); do [[ ! -f "$promotion.ready" ]] || break sleep .01 done [[ -f "$promotion.ready" ]] || fail 'first operation did not reach promotion' fixture later issue > "$TEMP/waiting-promotion" 2>&1 & waiting_pid=$! if flock -n "$state/lock" true; then fail 'promotion was not holding the destination lock'; fi live_is old || fail 'uncommitted promotion changed live files' printf 'continue\n' > "$promotion" if wait "$failed_pid"; then fail 'injected promotion failure reported success'; fi wait "$waiting_pid" || { cat "$TEMP/waiting-promotion"; fail 'second promotion failed'; } unset -f mv live_is later || fail 'rollback overwrote a newer promotion' printf 'PASS: a failed promotion cannot roll back another operation on the same paths\n' before=$(wc -l < "$ACME_LOG") reject ip_ssl_issue_and_install "$acme" "$ipv4" "$ipv6;touch $TEMP/injected" "$port" "$cert_dir" "$reload" [[ ! -e "$TEMP/injected" && "$(wc -l < "$ACME_LOG")" == "$before" ]] || fail 'invalid IP reached shell or ACME' printf 'PASS: invalid SAN never reaches ACME or a shell command\n' source_function() { source /dev/stdin < <(awk -v name="$2" '$0==name"() {" {body=1} body {print} body && /^}/ {exit}' "$1") } export HOME="$TEMP/home" mkdir -p "$HOME/.acme.sh" "$TEMP/panel" "$TEMP/mockbin" cp "$acme" "$HOME/.acme.sh/acme.sh" cat > "$TEMP/panel/x-ui" <<'PANEL' #!/usr/bin/env bash if [[ "$1" == setting ]]; then printf 'webBasePath: /test/\nport: 2053\n'; else printf 'configured\n' >> "$RELOAD_LOG.panel"; fi PANEL cat > "$TEMP/mockbin/systemctl" <<'SERVICE' #!/usr/bin/env bash printf 'reloaded\n' >> "$RELOAD_LOG" SERVICE chmod +x "$TEMP/panel/x-ui" "$TEMP/mockbin/systemctl" export PATH="$TEMP/mockbin:$PATH" export xui_folder="$TEMP/panel" release=ubuntu export red='' green='' yellow='' blue='' plain='' LOGI() { printf '%s\n' "$*"; } LOGE() { printf '%s\n' "$*" >&2; } apt-get() { :; } restart() { printf 'restarted\n' >> "$RELOAD_LOG.panel"; } curl() { if [[ "$*" == *https://* ]]; then printf '198.51.100.8\n200'; else command curl "$@"; fi } ip() { [[ "$*" != '-6 route get '* ]] || return 0 printf '2: eth0 inet6 2001:4860::1/64 scope global valid_lft forever preferred_lft forever\n' } fixture new source_function "$ROOT/x-ui.sh" confirm source_function "$ROOT/x-ui.sh" ssl_cert_issue_for_ip if ! ssl_cert_issue_for_ip "$TEMP/menu-cert" <<< "$(printf 'y\ny\n%s\ny\n' "$port")" > "$TEMP/menu-output" 2>&1; then cat "$TEMP/menu-output"; fail 'management menu issuance failed' fi grep -Fq 'https://[2001:4860::1]:2053/test/' "$TEMP/menu-output" || fail 'IPv6 access URL is not bracketed' if ! grep -q configured "$RELOAD_LOG.panel" || ! grep -q restarted "$RELOAD_LOG.panel"; then fail 'menu did not configure and restart panel after consent'; fi source_function "$ROOT/install.sh" prompt_or_default source_function "$ROOT/install.sh" setup_ip_certificate export NONINTERACTIVE=1 XUI_ACME_HTTP_PORT="$port" XUI_ACME_EMAIL=ssl-test@example.invalid if ! setup_ip_certificate 198.51.100.8 '2001:4860::1' "$TEMP/installer-cert" "$TEMP/install-output" 2>&1; then cat "$TEMP/install-output"; fail 'installer issuance failed' fi openssl verify -trusted "$TEMP/installer-cert/fullchain.pem" -partial_chain -verify_ip 2001:4860::1 "$TEMP/installer-cert/fullchain.pem" > /dev/null grep -qx 'arg=--upgrade' "$ACME_LOG" || fail 'auto-upgrade registration lost' grep -qx 'arg=--register-account' "$ACME_LOG" || fail 'configured account email ignored' printf 'PASS: real menu and installer functions install both IP SANs, configure panel paths and retain renewal setup\n'