diff --git a/pasarguard.sh b/pasarguard.sh index 4948399..5442414 100755 --- a/pasarguard.sh +++ b/pasarguard.sh @@ -330,6 +330,119 @@ build_pasarguard_ssl_reload_command() { fi } +# Write a deploy hook for the selected lineage, certificate directory, and backend. +write_pasarguard_certbot_hook() { + printf '#!/usr/bin/env bash\nset -euo pipefail\n' + printf 'LINEAGE=%q\nCERT_DIR=%q\nCOMPOSE_FILE=%q\nAPP_NAME=%q\nBACKEND_SERVICE=%q\n' \ + "$1" "$2" "$COMPOSE_FILE" "$APP_NAME" "$3" + cat <<'CERTBOT_HOOK' + +# Ignore renewals for other Certbot certificates on this host. +[ "${RENEWED_LINEAGE:-$LINEAGE}" = "$LINEAGE" ] || exit 0 +[ -s "$LINEAGE/fullchain.pem" ] && [ -s "$LINEAGE/privkey.pem" ] +mkdir -p "$CERT_DIR" +umask 077 +version_dir=$(mktemp -d "$CERT_DIR/version.XXXXXX") +pending_link="${version_dir}.link" +trap 'rm -f -- "$pending_link"; rm -rf -- "$version_dir"' EXIT + +cert="$version_dir/fullchain.pem" +key="$version_dir/privkey.pem" +cp -- "$LINEAGE/fullchain.pem" "$cert" +cp -- "$LINEAGE/privkey.pem" "$key" + +# Never restart Uvicorn with an incomplete or mismatched certificate pair. +cert_public_key=$(openssl x509 -in "$cert" -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum) +key_public_key=$(openssl pkey -in "$key" -pubout -outform DER | sha256sum) +[ "$cert_public_key" = "$key_public_key" ] +chmod 644 "$cert" +chmod 600 "$key" +# Publish the validated pair with a single rename on the mounted filesystem. +ln -s -- "${version_dir##*/}" "$pending_link" +mv -Tf -- "$pending_link" "$CERT_DIR/current" +trap - EXIT + +if [ "${PASARGUARD_CERTBOT_SETUP:-}" != 1 ]; then + docker compose -f "$COMPOSE_FILE" -p "$APP_NAME" restart "$BACKEND_SERVICE" +fi +CERTBOT_HOOK +} + +# Register a Certbot deploy hook for an existing certificate lineage. Certbot +# runs deploy hooks only after a successful renewal, so the panel is restarted +# only when its certificate has actually changed. +certbot_deploy_command() { + check_running_as_root + + local cert_name="${1:-}" + local lineage="" + local cert_dir="" + local backend_service="" + local hook_dir="/etc/letsencrypt/renewal-hooks/deploy" + local hook_file="${hook_dir}/pasarguard-${APP_NAME}.sh" + local hook_tmp="" + + if [ "$#" -ne 1 ] || [[ ! "$cert_name" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || [[ "$cert_name" == *..* ]]; then + colorized_echo red "Usage: pasarguard certbot-deploy " + return 1 + fi + + if ! command -v certbot >/dev/null 2>&1 || [ ! -f "/etc/letsencrypt/renewal/${cert_name}.conf" ]; then + colorized_echo red "Certbot renewal is not configured for ${cert_name}." + return 1 + fi + lineage="/etc/letsencrypt/live/${cert_name}" + if [ ! -s "${lineage}/fullchain.pem" ] || [ ! -s "${lineage}/privkey.pem" ]; then + colorized_echo red "Certbot certificate or private key is missing from ${lineage}." + return 1 + fi + if [ ! -f "$COMPOSE_FILE" ] || [ ! -f "$ENV_FILE" ]; then + colorized_echo red "PasarGuard installation is missing from ${APP_DIR}." + return 1 + fi + + detect_compose + backend_service=$(detect_pasarguard_backend_service) || { + colorized_echo red "Could not find the panel service in ${COMPOSE_FILE}." + return 1 + } + cert_dir="${DATA_DIR}/certs/${cert_name}" + mkdir -p "$hook_dir" "$cert_dir" + hook_tmp=$(mktemp "${hook_dir}/.pasarguard-hook.XXXXXX") || return 1 + + if ! write_pasarguard_certbot_hook "$lineage" "$cert_dir" "$backend_service" >"$hook_tmp"; then + rm -f "$hook_tmp" + colorized_echo red "Could not generate the Certbot deploy hook." + return 1 + fi + + if ! PASARGUARD_CERTBOT_SETUP=1 bash "$hook_tmp"; then + rm -f "$hook_tmp" + colorized_echo red "Could not deploy the Certbot certificate." + return 1 + fi + + if ! enable_pasarguard_ssl_env "${cert_dir}/current/fullchain.pem" "${cert_dir}/current/privkey.pem" "public"; then + rm -f "$hook_tmp" + colorized_echo red "Could not update the panel SSL settings." + return 1 + fi + if ! mv -f "$hook_tmp" "$hook_file"; then + rm -f "$hook_tmp" + colorized_echo red "Could not install the Certbot deploy hook." + return 1 + fi + if ! chmod 700 "$hook_file"; then + colorized_echo red "Could not enable the Certbot deploy hook." + return 1 + fi + if ! docker compose -f "$COMPOSE_FILE" -p "$APP_NAME" up -d --no-deps --force-recreate "$backend_service"; then + colorized_echo red "Certificate deployed, but the panel restart failed." + return 1 + fi + colorized_echo green "Certbot deploy hook installed at ${hook_file}." +} + # Check if both certificate and private key files exist and have non-zero file sizes. # Arguments: # $1 - Path to SSL certificate file. @@ -616,9 +729,9 @@ enable_pasarguard_ssl_env() { local key_file="$2" local ca_type="${3:-public}" - set_or_uncomment_env_var "UVICORN_SSL_CERTFILE" "$cert_file" true "$ENV_FILE" - set_or_uncomment_env_var "UVICORN_SSL_KEYFILE" "$key_file" true "$ENV_FILE" - set_or_uncomment_env_var "UVICORN_SSL_CA_TYPE" "$ca_type" true "$ENV_FILE" + set_or_uncomment_env_var "UVICORN_SSL_CERTFILE" "$cert_file" true "$ENV_FILE" || return 1 + set_or_uncomment_env_var "UVICORN_SSL_KEYFILE" "$key_file" true "$ENV_FILE" || return 1 + set_or_uncomment_env_var "UVICORN_SSL_CA_TYPE" "$ca_type" true "$ENV_FILE" || return 1 } # Comment out UVICORN_SSL variables in PasarGuard .env to disable SSL termination. @@ -1734,6 +1847,7 @@ uninstall_command() { down_pasarguard fi uninstall_completion + rm -f "/etc/letsencrypt/renewal-hooks/deploy/pasarguard-${APP_NAME}.sh" uninstall_pasarguard_script uninstall_pasarguard uninstall_pasarguard_docker_images @@ -2143,7 +2257,7 @@ _pasarguard_completions() local cur cmds COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - cmds="up down restart status logs cli tui install update uninstall install-script install-node backup backup-service restore core-update edit edit-env version-script script-version help completion" + cmds="up down restart status logs cli tui install update uninstall install-script install-node certbot-deploy backup backup-service restore core-update edit edit-env version-script script-version help completion" COMPREPLY=( $(compgen -W "$cmds" -- "$cur") ) return 0 } @@ -2196,6 +2310,7 @@ usage() { colorized_echo yellow " uninstall $(tput sgr0)– Uninstall pasarguard" colorized_echo yellow " install-script $(tput sgr0)– Install pasarguard script" colorized_echo yellow " install-node $(tput sgr0)– Install PasarGuard node" + colorized_echo yellow " certbot-deploy $(tput sgr0)– Deploy and auto-renew a Certbot certificate" colorized_echo yellow " backup $(tput sgr0)– Manual backup launch" colorized_echo yellow " backup-service $(tput sgr0)– pasarguard Backup service to backup to TG, and a new job in crontab" colorized_echo yellow " restore $(tput sgr0)– Restore database from backup file" @@ -2278,6 +2393,10 @@ pasarguard_main() { shift install_node_command "$@" ;; + certbot-deploy) + shift + certbot_deploy_command "$@" + ;; edit) shift edit_command "$@" diff --git a/tests/unit_pasarguard.sh b/tests/unit_pasarguard.sh index df69bc5..f1899a0 100644 --- a/tests/unit_pasarguard.sh +++ b/tests/unit_pasarguard.sh @@ -743,6 +743,61 @@ assert_true "mirror.sh: has direct-execution guard" \ grep -Fq 'if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then' \ "$ROOT_DIR/iran-sanction/mirror.sh" +# ----------------------------------------------------------------------- +# Certbot deploy hook publishes only complete certificate pairs +# ----------------------------------------------------------------------- +certbot_dir="$WORK_DIR/certbot" +lineage="$certbot_dir/live" +deployed="$certbot_dir/deployed" +hook="$certbot_dir/hook.sh" +export CERTBOT_TEST_DOCKER_LOG="$certbot_dir/docker.log" +mkdir -p "$lineage" "$certbot_dir/previous" + +MSYS2_ARG_CONV_EXCL=/CN= openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=previous.example.com \ + -out "$lineage/fullchain.pem" -keyout "$lineage/privkey.pem" >/dev/null 2>&1 +cp -- "$lineage/fullchain.pem" "$lineage/privkey.pem" "$certbot_dir/previous/" +write_pasarguard_certbot_hook "$lineage" "$deployed" backend >"$hook" + +docker() { + printf '%s\n' "$*" >>"$CERTBOT_TEST_DOCKER_LOG" +} +export -f docker + +assert_true "certbot: setup deploys the initial pair" env PASARGUARD_CERTBOT_SETUP=1 bash "$hook" +previous_version=$(readlink "$deployed/current") +assert_false "certbot: setup skips the restart" test -e "$CERTBOT_TEST_DOCKER_LOG" + +MSYS2_ARG_CONV_EXCL=/CN= openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=renewed.example.com \ + -out "$lineage/fullchain.pem" -keyout "$lineage/privkey.pem" >/dev/null 2>&1 + +# Leave a partial staged key before reporting the write failure. +cp() { + if [[ "$2" == */privkey.pem ]]; then + printf 'incomplete key\n' >"$3" + return 1 + fi + command cp "$@" +} +export -f cp + +assert_false "certbot: renewal reports a key write failure" env RENEWED_LINEAGE="$lineage" bash "$hook" +unset -f cp +assert_eq "$(readlink "$deployed/current")" "$previous_version" "certbot: failed renewal keeps the active version" +assert_true "certbot: previous certificate stays active" \ + cmp -s "$certbot_dir/previous/fullchain.pem" "$deployed/current/fullchain.pem" +assert_true "certbot: previous matching key stays active" \ + cmp -s "$certbot_dir/previous/privkey.pem" "$deployed/current/privkey.pem" +assert_false "certbot: failed renewal skips the restart" test -e "$CERTBOT_TEST_DOCKER_LOG" + +assert_true "certbot: retry publishes the renewed pair" env RENEWED_LINEAGE="$lineage" bash "$hook" +assert_true "certbot: renewed certificate is active" cmp -s "$lineage/fullchain.pem" "$deployed/current/fullchain.pem" +assert_true "certbot: renewed key is active" cmp -s "$lineage/privkey.pem" "$deployed/current/privkey.pem" +assert_eq "$(cat "$CERTBOT_TEST_DOCKER_LOG")" \ + "compose -f $COMPOSE_FILE -p $APP_NAME restart backend" "certbot: successful renewal restarts only the backend" + +unset -f docker +unset CERTBOT_TEST_DOCKER_LOG + # ----------------------------------------------------------------------- # run_all.sh missing suite detection # -----------------------------------------------------------------------