From b9d39eb90fa4705fc56eb1ced48302d29b94936c Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 14:51:08 +0330 Subject: [PATCH 01/10] feat(node): add managed TLS certificates and external TLS termination support - Default new installs to Let's Encrypt IP certificates - Support domain, custom, self-signed, and external TLS options - Add certificate validation, source-aware renewal, and restart hooks - Display SHA-256 certificate pins and panel configuration guidance - Preserve existing certificate paths during upgrades - Restrict plaintext maintenance listeners to private addresses - Keep API-key authentication independent of certificate issuer - Add TLS tests, CI coverage, migration plan, and documentation --- .github/workflows/command-tests.yml | 12 +- README.md | 19 + pg-node-service.sh | 63 ++- pg-node.sh | 486 ++++++++++++++++-------- tests/integration_pgnode_service_tls.sh | 64 ++++ tests/unit_pgnode_service.sh | 2 +- tests/unit_pgnode_tls.sh | 119 ++++++ 7 files changed, 592 insertions(+), 173 deletions(-) create mode 100644 tests/integration_pgnode_service_tls.sh create mode 100644 tests/unit_pgnode_tls.sh diff --git a/.github/workflows/command-tests.yml b/.github/workflows/command-tests.yml index c64e103..bab949e 100644 --- a/.github/workflows/command-tests.yml +++ b/.github/workflows/command-tests.yml @@ -16,6 +16,8 @@ on: - "tests/unit_lib_github.sh" - "tests/unit_pasarguard.sh" - "tests/unit_pgnode.sh" + - "tests/unit_pgnode_tls.sh" + - "tests/integration_pgnode_service_tls.sh" - "tests/unit_pgnode_service.sh" - "tests/unit_restore_archive_safety.sh" - "tests/unit_lib_system.sh" @@ -32,6 +34,8 @@ on: - "tests/unit_lib_system.sh" - "tests/unit_pasarguard.sh" - "tests/unit_pgnode.sh" + - "tests/unit_pgnode_tls.sh" + - "tests/integration_pgnode_service_tls.sh" - "tests/unit_pgnode_service.sh" - "tests/unit_restore_archive_safety.sh" workflow_dispatch: @@ -43,8 +47,8 @@ jobs: timeout-minutes: 5 steps: - uses: actions/checkout@v4 - - name: Install archive tooling for restore-safety tests - run: sudo apt-get update && sudo apt-get install -y zip unzip + - name: Install unit and transport test dependencies + run: sudo apt-get update && sudo apt-get install -y zip unzip openssl jq python3 socat - name: Run lib/common.sh unit tests run: bash tests/unit_lib_common.sh - name: Run lib/env.sh unit tests @@ -57,6 +61,10 @@ jobs: run: bash tests/unit_pasarguard.sh - name: Run pg-node.sh unit tests run: bash tests/unit_pgnode.sh + - name: Run node certificate-management unit tests + run: bash tests/unit_pgnode_tls.sh + - name: Run node maintenance transport integration tests + run: bash tests/integration_pgnode_service_tls.sh - name: Run pg-node-service.sh unit tests run: bash tests/unit_pgnode_service.sh - name: Run restore archive-safety unit tests diff --git a/README.md b/README.md index ea1a424..e4e5e83 100644 --- a/README.md +++ b/README.md @@ -108,3 +108,22 @@ Use `help` to view all commands: `pg-node help` + +### Node certificate management + +New `pg-node install` runs default to Let's Encrypt IP certificates. Unattended +installation requires `--ssl-ip YOUR_PUBLIC_IPV4`; optionally add `--ssl-ipv6`. +Use `--ssl-domain DOMAIN`, paired `--cert-path`/`--key-path`, or explicit +`--self-signed` to choose another source. `--ssl-http-port` (`--ssl-port`) changes +the local HTTP-01 listener; public port 80 must still reach it. + +`--no-ssl` is exclusively for private backends behind an external TLS web server. +The panel must use the web server's TLS endpoints for both node and maintenance +requests. API-key authentication stays required. Certificate source metadata is +stored under the instance data directory; `renew-cert` follows that source and +`show-cert` displays its identity, expiry, fingerprint and legacy PEM. + +Old unattended commands relying on implicit self-signed certificates must add +`--self-signed`. Routine updates preserve certificate paths and files. See +[the node TLS deployment guide](https://github.com/PasarGuard/node/blob/main/docs/node-tls.md) +for nginx examples, verification fields, renewal, private bindings and rollback. diff --git a/pg-node-service.sh b/pg-node-service.sh index 7a44109..1f1887e 100755 --- a/pg-node-service.sh +++ b/pg-node-service.sh @@ -77,15 +77,25 @@ describe_certificate() { return 0 } -# Decide the socat client-certificate verification level: require a client cert -# only for CA-signed certificates. -tls_verify_level() { - local cert_file="$1" - if check_certificate "$cert_file" >/dev/null 2>&1; then - echo "verify=1" - else - echo "verify=0" - fi +# Server issuer classification must never enable mutual TLS. API keys authenticate clients. +tls_verify_level() { echo "verify=0"; } + +private_backend_host() { + command -v python3 >/dev/null 2>&1 || { log "python3 is required to validate private NODE_HOST"; return 1; } + python3 - "$1" <<'PYHOST' +import ipaddress, sys +try: + value = sys.argv[1].strip() + if '%' in value: raise ValueError('zones are not allowed') + addr = ipaddress.ip_address(value) + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped: addr = addr.ipv4_mapped + allowed = ('127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16') if addr.version == 4 else ('::1/128', 'fc00::/7') + if not any(addr in ipaddress.ip_network(n) for n in allowed): raise ValueError('address is not a private backend') + print(addr) +except ValueError as err: + print('Invalid plaintext NODE_HOST: ' + str(err), file=sys.stderr) + sys.exit(1) +PYHOST } # Byte length of a string. ${#s} counts characters, so a multibyte UTF-8 body @@ -126,6 +136,17 @@ if [[ -z "$API_KEY" ]]; then exit 1 fi +case "${TLS_ENABLED-true}" in + true|TRUE|True|1|t|T) TLS_ENABLED=true ;; + false|FALSE|False|0|f|F) TLS_ENABLED=false ;; + *) log "Invalid TLS_ENABLED: expected a boolean"; exit 1 ;; +esac +if [[ "$TLS_ENABLED" == false ]]; then + NODE_HOST=$(private_backend_host "${NODE_HOST-127.0.0.1}") || exit 1 + command -v socat >/dev/null 2>&1 || { log "socat is required for external TLS backend mode"; exit 1; } +else + NODE_HOST="${NODE_HOST-0.0.0.0}" + [[ "${NODE_HOST,,}" != localhost ]] || NODE_HOST=127.0.0.1 if [[ -z "${SSL_CERT_FILE:-}" || -z "${SSL_KEY_FILE:-}" ]]; then log "TLS required: set SSL_CERT_FILE and SSL_KEY_FILE in the env file" exit 1 @@ -147,6 +168,7 @@ fi describe_certificate "$SSL_CERT_FILE" log "TLS enabled on port $API_PORT with cert=$SSL_CERT_FILE key=$SSL_KEY_FILE" +fi log "API key protection enabled" json_escape() { @@ -390,7 +412,7 @@ handle_connection() { # Check if we should use socat (recommended) or openssl s_server if command -v socat >/dev/null 2>&1; then - log "Starting HTTPS server with socat on port $API_PORT..." + log "Starting service with socat on $NODE_HOST:$API_PORT (TLS_ENABLED=$TLS_ENABLED)..." # For socat, we need to handle the case where we're called as a subprocess if [[ "${1:-}" == "--handle-connection" ]]; then @@ -401,21 +423,22 @@ if command -v socat >/dev/null 2>&1; then exit 0 fi - # Determine verify level based on certificate type - verify_level=$(tls_verify_level "$SSL_CERT_FILE") - if [[ "$verify_level" == "verify=1" ]]; then - log "Enabling client certificate verification (CA-signed certificate detected)" + family=4 + bind_host="$NODE_HOST" + if [[ "$NODE_HOST" == *:* ]]; then family=6; bind_host="[$NODE_HOST]"; fi + if [[ "$TLS_ENABLED" == false ]]; then + listen="TCP${family}-LISTEN:${API_PORT},bind=${bind_host},reuseaddr,fork" else - log "Disabling client certificate verification (self-signed or invalid certificate)" + listen="OPENSSL-LISTEN:${API_PORT},pf=ip${family},bind=${bind_host},cert=${SSL_CERT_FILE},key=${SSL_KEY_FILE},verify=0,reuseaddr,fork" fi - - exec socat \ - "OPENSSL-LISTEN:${API_PORT},cert=${SSL_CERT_FILE},key=${SSL_KEY_FILE},${verify_level},reuseaddr,fork" \ - EXEC:"'$0' --handle-connection" + exec socat "$listen" EXEC:"'$0' --handle-connection" + else log "socat not available, using openssl s_server" log "Install socat with your system package manager for better performance" + openssl_bind="${NODE_HOST}:${API_PORT}" + [[ "$NODE_HOST" != *:* ]] || openssl_bind="[${NODE_HOST}]:${API_PORT}" # Main server loop with openssl s_server log "Bash REST API listening on https://localhost:${API_PORT}" @@ -424,7 +447,7 @@ else if coproc OPENSSL { openssl s_server \ -quiet \ - -accept "$API_PORT" \ + -accept "$openssl_bind" \ -cert "$SSL_CERT_FILE" \ -key "$SSL_KEY_FILE" \ -ign_eof \ diff --git a/pg-node.sh b/pg-node.sh index 0a69c29..b3119ca 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -699,38 +699,7 @@ install_node() { mkdir -p "$APP_DIR" colorized_echo green " ✓ Directories created" colorized_echo cyan "" - colorized_echo yellow "A self-signed certificate will be generated by default." - if [ "${INSTALL_SELF_SIGNED:-false}" = true ]; then - use_public_cert="" - elif [ -n "${INSTALL_CERT_PATH:-}" ] && [ -n "${INSTALL_KEY_PATH:-}" ]; then - use_public_cert="y" - elif [ "$AUTO_CONFIRM" = true ]; then - use_public_cert="" - else - read -r -p "Do you want to use your own public certificate instead? (Y/n): " use_public_cert - fi - if [[ "$use_public_cert" =~ ^[Yy]$ ]]; then - if [ -n "${INSTALL_CERT_PATH:-}" ] && [ -f "$INSTALL_CERT_PATH" ]; then - cp "$INSTALL_CERT_PATH" "$SSL_CERT_FILE" - colorized_echo blue "Certificate copied to $SSL_CERT_FILE" - else - read_and_save_file "Please paste the content OR the path to the Client Certificate file." "$SSL_CERT_FILE" 1 - colorized_echo blue "Certificate saved to $SSL_CERT_FILE" - fi - - if [ -n "${INSTALL_KEY_PATH:-}" ] && [ -f "$INSTALL_KEY_PATH" ]; then - cp "$INSTALL_KEY_PATH" "$SSL_KEY_FILE" - colorized_echo blue "Private key copied to $SSL_KEY_FILE" - else - read_and_save_file "Please paste the content OR the path to the Private Key file." "$SSL_KEY_FILE" 1 - colorized_echo blue "Private key saved to $SSL_KEY_FILE" - fi - # cp/paste create the key with the default umask (0644); restrict it. - harden_secret_file "$SSL_KEY_FILE" - else - gen_self_signed_cert - colorized_echo blue "self-signed certificate successfully generated" - fi + choose_node_certificate || exit 1 if [ -n "${INSTALL_API_KEY:-}" ]; then API_KEY="$INSTALL_API_KEY" elif [ "$AUTO_CONFIRM" = true ]; then @@ -821,6 +790,12 @@ install_node() { else sed -i 's/^# \(SERVICE_PROTOCOL *=.*\)/SERVICE_PROTOCOL= "grpc"/' "$APP_DIR/.env" fi + sed -i '/^[[:space:]]*TLS_ENABLED[[:space:]]*=/d' "$ENV_FILE" + echo "TLS_ENABLED=$TLS_ENABLED" >>"$ENV_FILE" + if [ "$TLS_ENABLED" = false ]; then + sed -i '/^[[:space:]]*NODE_HOST[[:space:]]*=/d' "$ENV_FILE" + echo 'NODE_HOST=127.0.0.1' >>"$ENV_FILE" + fi colorized_echo green ".env file modified successfully" # Modifying compose file colorized_echo blue "Modifying docker-compose.yml..." @@ -833,21 +808,7 @@ install_node() { colorized_echo yellow " ⚠ Failed to set container name (may not be critical)" fi fi - container_path="" - existing_volume=$(yq eval -r ".services[\"$service_name\"].volumes[0]" "$APP_DIR/docker-compose.yml" 2>/dev/null) - if [ -n "$existing_volume" ] && [ "$existing_volume" != "null" ]; then - # Extract container path (everything after the colon) - if [[ "$existing_volume" == *:* ]]; then - container_path="${existing_volume#*:}" - else - # If no colon found, use the existing volume as container path - container_path="$existing_volume" - fi - fi - # For custom names, keep host/container paths aligned to the APP_NAME data dir - if [ "$APP_NAME" != "pg-node" ] || [ -z "$container_path" ]; then - container_path="$DATA_DIR" - fi + container_path="$DATA_DIR" colorized_echo cyan " Command: yq eval ...volumes[0] = \"${DATA_DIR}:${container_path}\"..." if yq eval ".services[\"$service_name\"].volumes[0] = \"${DATA_DIR}:${container_path}\"" -i "$APP_DIR/docker-compose.yml" 2>/dev/null; then colorized_echo green " ✓ Volume path configured: ${DATA_DIR}:${container_path}" @@ -855,8 +816,8 @@ install_node() { colorized_echo yellow " ⚠ Failed to configure volume (may not be critical)" fi # Keep SSL paths in .env aligned with the mapped volume (important for node-serviced on host) - ssl_cert_env="${container_path}/certs/ssl_cert.pem" - ssl_key_env="${container_path}/certs/ssl_key.pem" + ssl_cert_env="$SSL_CERT_FILE" + ssl_key_env="$SSL_KEY_FILE" sed -i "s|^SSL_CERT_FILE *=.*|SSL_CERT_FILE= ${ssl_cert_env}|" "$APP_DIR/.env" sed -i "s|^SSL_KEY_FILE *=.*|SSL_KEY_FILE= ${ssl_key_env}|" "$APP_DIR/.env" if [ "$node_version" != "latest" ]; then @@ -986,12 +947,12 @@ sync_env_ssl_paths() { local current_cert current_key updated=false current_cert=$(grep -E '^[[:space:]]*SSL_CERT_FILE[[:space:]]*=' "$ENV_FILE" | head -n1 | sed "s/^[[:space:]]*SSL_CERT_FILE[[:space:]]*=[[:space:]]*//;s/[\"']//g") current_key=$(grep -E '^[[:space:]]*SSL_KEY_FILE[[:space:]]*=' "$ENV_FILE" | head -n1 | sed "s/^[[:space:]]*SSL_KEY_FILE[[:space:]]*=[[:space:]]*//;s/[\"']//g") - if [[ -z "$current_cert" || "$current_cert" =~ /var/lib/pg-node/ ]]; then + if [[ -z "$current_cert" || "$current_cert" = /var/lib/pg-node/certs/ssl_cert.pem ]]; then sed -i "s|^[[:space:]]*SSL_CERT_FILE[[:space:]]*=.*|SSL_CERT_FILE= ${desired_cert}|" "$ENV_FILE" grep -q '^[[:space:]]*SSL_CERT_FILE[[:space:]]*=' "$ENV_FILE" || echo "SSL_CERT_FILE= ${desired_cert}" >>"$ENV_FILE" updated=true fi - if [[ -z "$current_key" || "$current_key" =~ /var/lib/pg-node/ ]]; then + if [[ -z "$current_key" || "$current_key" = /var/lib/pg-node/certs/ssl_key.pem ]]; then sed -i "s|^[[:space:]]*SSL_KEY_FILE[[:space:]]*=.*|SSL_KEY_FILE= ${desired_key}|" "$ENV_FILE" grep -q '^[[:space:]]*SSL_KEY_FILE[[:space:]]*=' "$ENV_FILE" || echo "SSL_KEY_FILE= ${desired_key}" >>"$ENV_FILE" updated=true @@ -1071,6 +1032,20 @@ install_command() { INSTALL_SELF_SIGNED=true shift ;; + --ssl-ip | --ssl-ipv6 | --ssl-domain | --ssl-http-port | --ssl-port) + [ -n "${2:-}" ] || { cert_error "$1 requires a value"; return 1; } + case "$1" in + --ssl-ip) INSTALL_SSL_IP="$2";; + --ssl-ipv6) INSTALL_SSL_IPV6="$2";; + --ssl-domain) INSTALL_SSL_DOMAIN="$2";; + *) INSTALL_SSL_HTTP_PORT="$2";; + esac + shift 2 + ;; + --no-ssl) + INSTALL_NO_SSL=true + shift + ;; --api-port) INSTALL_API_PORT="$2" shift 2 @@ -1093,6 +1068,7 @@ install_command() { ;; esac done + validate_ssl_selection || return 1 # Check if node is already installed if is_node_installed; then colorized_echo red "node is already installed at $APP_DIR" @@ -1113,6 +1089,7 @@ install_command() { if ! command -v curl >/dev/null 2>&1; then install_package curl fi + command -v openssl >/dev/null 2>&1 || install_package openssl if ! command -v docker >/dev/null 2>&1; then install_docker fi @@ -1176,7 +1153,6 @@ install_command() { install_node_script install_completion up_node - show_node_logs local install_service_choice="" if [ -n "${INSTALL_SERVICE_CHOICE:-}" ]; then install_service_choice="$INSTALL_SERVICE_CHOICE" @@ -1192,8 +1168,8 @@ install_command() { fi colorized_echo blue "================================" colorized_echo magenta " node is set up with the following IP: $NODE_IP and Port: $SERVICE_PORT." - colorized_echo magenta "Please use the following Certificate in pasarguard Panel (it's located in ${DATA_DIR}/certs):" - cat "$SSL_CERT_FILE" + register_node_acme_reload || return 1 + show_node_certificate colorized_echo blue "================================" colorized_echo magenta "Next, use the API Key (UUID v4) in pasarguard Panel: " colorized_echo red "${API_KEY}" @@ -1367,7 +1343,6 @@ install_service_command() { exit 1 fi ensure_env_exists - sync_env_ssl_paths get_occupied_ports local api_port existing_api_port="" local default_api_port=62051 @@ -1884,7 +1859,7 @@ _node_completions() local cur cmds COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" + cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert show-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" COMPREPLY=( $(compgen -W "$cmds" -- "$cur") ) return 0 } @@ -1912,6 +1887,7 @@ commands=( core-update geofiles renew-cert + show-cert version-script script-version edit @@ -1999,7 +1975,7 @@ usage() { colorized_echo yellow " edit-env $(tput sgr0)✓ Edit .env file (via nano or vi)" colorized_echo yellow " core-update $(tput sgr0)✓ Update/Change Xray core" colorized_echo yellow " geofiles $(tput sgr0)✓ Download geoip and geosite files for specific regions" - colorized_echo yellow " renew-cert $(tput sgr0)✓ Regenerate SSL/TLS certificate" + colorized_echo yellow " renew-cert $(tput sgr0)✓ Renew or validate the active certificate source" colorized_echo yellow " version-script $(tput sgr0)✓ Show script version and commit" colorized_echo yellow " completion $(tput sgr0)✓ Install bash/zsh tab completion" echo @@ -2022,6 +1998,12 @@ usage() { colorized_echo yellow " --service-port PORT $(tput sgr0)✓ Set service port" colorized_echo yellow " --cert-path PATH $(tput sgr0)✓ Set public certificate path" colorized_echo yellow " --key-path PATH $(tput sgr0)✓ Set private key path" + echo " show-cert Display identity, expiry, SHA-256 fingerprint and legacy PEM" + echo " --ssl-ip IPV4 Let's Encrypt IP certificate (default; required unattended)" + echo " --ssl-ipv6 IPV6 Add IPv6 SAN (requires --ssl-ip)" + echo " --ssl-domain DOMAIN Let's Encrypt domain certificate" + echo " --ssl-http-port PORT HTTP challenge port (alias: --ssl-port; public port 80 must reach it)" + echo " --no-ssl Private backend behind external TLS termination only" colorized_echo yellow " --self-signed $(tput sgr0)✓ Generate self-signed certificate" colorized_echo yellow " --api-port PORT $(tput sgr0)✓ Set API port for node service" colorized_echo yellow " --install-service $(tput sgr0)✓ Install systemd service" @@ -2118,110 +2100,311 @@ geofiles_command() { fi } -renew_cert_command() { - check_running_as_root - # Check if node is installed - if ! is_node_installed; then - colorized_echo red "✗ Node is not installed. Please install node first." - exit 1 - fi - colorized_echo cyan "================================" - colorized_echo cyan "Renewing SSL/TLS Certificate" - colorized_echo cyan "================================" - colorized_echo yellow "This will create a new SSL/TLS certificate for your node." - - # Check if existing certificate is self-signed (generated by script) - local is_self_signed=false - if [ -f "$SSL_CERT_FILE" ]; then - # Check if certificate is self-signed (subject == issuer) - local subject=$(openssl x509 -in "$SSL_CERT_FILE" -noout -subject 2>/dev/null | sed 's/^subject= *//') - local issuer=$(openssl x509 -in "$SSL_CERT_FILE" -noout -issuer 2>/dev/null | sed 's/^issuer= *//') - if [ "$subject" = "$issuer" ]; then - is_self_signed=true +# Node certificate management is deliberately independent of panel verification. +cert_error() { colorized_echo red "$*" >&2; return 1; } + +node_env_value() { + [ -f "$ENV_FILE" ] || return 0 + sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "$ENV_FILE" | head -n1 | tr -d '\r\"\047' | sed 's/[[:space:]]*$//' +} + +load_active_cert_paths() { + local value + value=$(node_env_value SSL_CERT_FILE) + [ -z "$value" ] || SSL_CERT_FILE="$value" + value=$(node_env_value SSL_KEY_FILE) + [ -z "$value" ] || SSL_KEY_FILE="$value" +} + +# Never source certificate metadata as executable shell code. +cert_metadata() { jq -r --arg key "$1" '.[$key] // empty' "$DATA_DIR/certs/source.json"; } + +save_cert_source() { + local stage + stage=$(mktemp "$DATA_DIR/certs/.source.XXXXXX") || return 1 + jq -n --arg source "$1" --arg identifier "${2:-}" --arg ipv6 "${3:-}" --arg port "${4:-80}" \ + '{source:$source, identifier:$identifier, ipv6:$ipv6, http_port:$port}' >"$stage" || return 1 + chmod 600 "$stage" + mv -f "$stage" "$DATA_DIR/certs/source.json" +} + +validate_node_cert_pair() ( + set -o pipefail + local cert="$1" key="$2" identity="${3:-}" ipv6="${4:-}" + local cert_pub key_pub start end now + openssl x509 -in "$cert" -noout >/dev/null 2>&1 || { cert_error "Invalid certificate: $cert"; return 1; } + cert_pub=$(openssl x509 -in "$cert" -pubkey -noout | openssl pkey -pubin -outform DER | openssl dgst -sha256) || return 1 + key_pub=$(openssl pkey -in "$key" -passin pass: -pubout -outform DER | openssl dgst -sha256) || return 1 + [ "$cert_pub" = "$key_pub" ] || { cert_error "Certificate and private key do not match"; return 1; } + start=$(openssl x509 -in "$cert" -startdate -noout); start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$cert" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 + now=$(date +%s) + [ "$start" -le "$now" ] && [ "$end" -gt "$now" ] || { cert_error "Certificate is expired or not yet valid"; return 1; } + # SAN is mandatory; never rely on Common Name fallback. + openssl x509 -in "$cert" -noout -ext subjectAltName | grep -qE 'DNS:|IP Address:' || { cert_error "Certificate requires SANs"; return 1; } + local id flag + for id in "$identity" "$ipv6"; do + [ -n "$id" ] || continue + if is_ip_address "$id"; then flag=-checkip; else + flag=-checkhost + openssl x509 -in "$cert" -noout -ext subjectAltName | grep -q 'DNS:' || return 1 fi + openssl x509 -in "$cert" -noout "$flag" "$id" | grep -q 'does match certificate' || { cert_error "Certificate SAN does not match $id"; return 1; } + done +) + +# Stage and validate before touching either active file. Keep backups for rollback. +deploy_node_cert_pair() { + local cert="$1" key="$2" identity="${3:-}" ipv6="${4:-}" + validate_node_cert_pair "$cert" "$key" "$identity" "$ipv6" || return 1 + mkdir -p "$(dirname "$SSL_CERT_FILE")" "$(dirname "$SSL_KEY_FILE")" || return 1 + chmod 700 "$(dirname "$SSL_KEY_FILE")" || return 1 + local stage_cert stage_key + stage_cert=$(mktemp "${SSL_CERT_FILE}.stage.XXXXXX") || return 1 + stage_key=$(mktemp "${SSL_KEY_FILE}.stage.XXXXXX") || return 1 + cp "$cert" "$stage_cert" && cp "$key" "$stage_key" || return 1 + chmod 644 "$stage_cert" && chmod 600 "$stage_key" || return 1 + if [ -f "$SSL_CERT_FILE" ]; then cp -p "$SSL_CERT_FILE" "${SSL_CERT_FILE}.previous" || return 1; fi + if [ -f "$SSL_KEY_FILE" ]; then cp -p "$SSL_KEY_FILE" "${SSL_KEY_FILE}.previous" || return 1; fi + if ! mv -f "$stage_key" "$SSL_KEY_FILE" || ! mv -f "$stage_cert" "$SSL_CERT_FILE"; then + [ ! -f "${SSL_CERT_FILE}.previous" ] || cp -p "${SSL_CERT_FILE}.previous" "$SSL_CERT_FILE" + [ ! -f "${SSL_KEY_FILE}.previous" ] || cp -p "${SSL_KEY_FILE}.previous" "$SSL_KEY_FILE" + cert_error "Deployment failed; restored previous certificate files" + return 1 fi - - # Only backup if it's a self-signed certificate (generated by script) - if [ "$is_self_signed" = true ] && [ -f "$SSL_CERT_FILE" ]; then - # Clean up old backups first (keep only the 2 most recent) - local cert_backups=($(ls -t "${SSL_CERT_FILE}.backup."* 2>/dev/null | tail -n +3 2>/dev/null)) - local key_backups=($(ls -t "${SSL_KEY_FILE}.backup."* 2>/dev/null | tail -n +3 2>/dev/null)) - - if [ ${#cert_backups[@]} -gt 0 ] || [ ${#key_backups[@]} -gt 0 ]; then - colorized_echo blue "Cleaning up old backups (keeping 2 most recent)..." - for backup in "${cert_backups[@]}"; do - if [ -f "$backup" ]; then - rm -f "$backup" 2>/dev/null && colorized_echo cyan " Removed old backup: $(basename "$backup")" - fi - done - for backup in "${key_backups[@]}"; do - if [ -f "$backup" ]; then - rm -f "$backup" 2>/dev/null && colorized_echo cyan " Removed old backup: $(basename "$backup")" - fi - done - fi - - # Create new backup - local backup_cert="${SSL_CERT_FILE}.backup.$(date +%Y%m%d_%H%M%S)" - local backup_key="${SSL_KEY_FILE}.backup.$(date +%Y%m%d_%H%M%S)" - colorized_echo blue "Backing up existing self-signed certificate..." - cp "$SSL_CERT_FILE" "$backup_cert" 2>/dev/null || true - if [ -f "$SSL_KEY_FILE" ]; then - cp "$SSL_KEY_FILE" "$backup_key" 2>/dev/null || true - fi - colorized_echo green " ✓ Backup created: $(basename "$backup_cert")" - if [ -f "$backup_key" ]; then - colorized_echo green " ✓ Backup created: $(basename "$backup_key")" - fi - elif [ -f "$SSL_CERT_FILE" ]; then - # User-provided certificate - don't backup, just warn - colorized_echo yellow "⚠ Existing certificate appears to be user-provided (not self-signed)." - colorized_echo yellow " It will be replaced with a new self-signed certificate." - if [ "$AUTO_CONFIRM" != true ]; then - read -p "Continue? (y/N): " confirm - if [[ ! "$confirm" =~ ^[Yy]$ ]]; then - colorized_echo yellow "Cancelled." - exit 0 - fi - fi +} + +get_node_acme() { + if [ -x "${HOME}/.acme.sh/acme.sh" ]; then printf '%s\n' "${HOME}/.acme.sh/acme.sh" + elif [ -x /root/.acme.sh/acme.sh ]; then printf '%s\n' /root/.acme.sh/acme.sh + elif command -v acme.sh >/dev/null 2>&1; then command -v acme.sh + else return 1; fi +} + +ensure_node_acme() { + local package installer + for package in socat openssl; do command -v "$package" >/dev/null 2>&1 || install_package "$package" || return 1; done + if ! command -v crontab >/dev/null 2>&1; then + case "${OS:-}" in Ubuntu*|Debian*) package=cron;; *) package=cronie;; esac + install_package "$package" || return 1 + fi + if ! get_node_acme >/dev/null; then + installer=$(mktemp) || return 1 + curl -fsSL https://get.acme.sh -o "$installer" && sh "$installer" || return 1 + rm -f "$installer" + fi + local acme + acme=$(get_node_acme) || return 1 + "$acme" --install-cronjob || return 1 +} + +validate_ssl_selection() { + local count=0 + [ "${INSTALL_SELF_SIGNED:-false}" != true ] || count=$((count+1)) + [ "${INSTALL_NO_SSL:-false}" != true ] || count=$((count+1)) + [ -z "${INSTALL_SSL_IP:-}" ] || count=$((count+1)) + [ -z "${INSTALL_SSL_DOMAIN:-}" ] || count=$((count+1)) + if [ -n "${INSTALL_CERT_PATH:-}${INSTALL_KEY_PATH:-}" ]; then + [ -n "${INSTALL_CERT_PATH:-}" ] && [ -n "${INSTALL_KEY_PATH:-}" ] || { cert_error "Use --cert-path and --key-path together"; return 1; } + count=$((count+1)) + fi + [ "$count" -le 1 ] || { cert_error "Conflicting certificate selections"; return 1; } + [ -z "${INSTALL_SSL_IPV6:-}" ] || [ -n "${INSTALL_SSL_IP:-}" ] || { cert_error "--ssl-ipv6 requires --ssl-ip"; return 1; } + local port="${INSTALL_SSL_HTTP_PORT:-80}" + [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] && [ "$port" -le 65535 ] || { cert_error "Invalid SSL HTTP challenge port"; return 1; } + if [ "$count" -eq 0 ] && { [ "$AUTO_CONFIRM" = true ] || [ ! -t 0 ]; }; then + cert_error "Unattended IP issuance requires --ssl-ip IPV4. Old unattended commands must add --self-signed to keep self-signed behavior." + return 1 fi - - # Generate new certificate - gen_self_signed_cert - - # Ask user if they want to restart the node - if docker ps --format '{{.Names}}' | grep -q "^$APP_NAME$"; then - colorized_echo cyan "" - colorized_echo yellow "The node needs to be restarted to apply the new certificate." - local restart_choice="" - if [ "$AUTO_CONFIRM" = true ]; then - restart_choice="n" +} + +choose_node_certificate() { + validate_ssl_selection || return 1 + if [ -z "${INSTALL_SSL_IP:-}${INSTALL_SSL_DOMAIN:-}${INSTALL_CERT_PATH:-}" ] && [ "${INSTALL_SELF_SIGNED:-false}" != true ] && [ "${INSTALL_NO_SSL:-false}" != true ]; then + echo "1) Let's Encrypt IP certificate (default)" + echo "2) Let's Encrypt domain certificate" + echo "3) Custom certificate and key paths" + echo "4) Self-signed certificate" + echo "5) External web server terminates TLS (advanced)" + local selection + read -r -p "Certificate [1]: " selection + case "${selection:-1}" in + 1) read -r -p "Public IPv4 [${NODE_IP_V4:-}]: " INSTALL_SSL_IP + INSTALL_SSL_IP="${INSTALL_SSL_IP:-${NODE_IP_V4:-}}" + read -r -p "Optional public IPv6: " INSTALL_SSL_IPV6 ;; + 2) read -r -p "Domain: " INSTALL_SSL_DOMAIN + [ -n "$INSTALL_SSL_DOMAIN" ] || { cert_error "Domain is required"; return 1; } ;; + 3) read -r -p "Certificate path: " INSTALL_CERT_PATH + read -r -p "Key path: " INSTALL_KEY_PATH + [ -n "$INSTALL_CERT_PATH" ] && [ -n "$INSTALL_KEY_PATH" ] || return 1 ;; + 4) INSTALL_SELF_SIGNED=true ;; + 5) INSTALL_NO_SSL=true ;; + *) cert_error "Invalid certificate selection"; return 1 ;; + esac + fi + TLS_ENABLED=true + if [ "${INSTALL_NO_SSL:-false}" = true ]; then + TLS_ENABLED=false + save_cert_source external_tls + elif [ "${INSTALL_SELF_SIGNED:-false}" = true ]; then + local active_cert="$SSL_CERT_FILE" active_key="$SSL_KEY_FILE" stage + stage=$(mktemp -d "$DATA_DIR/certs/.self-signed.XXXXXX") || return 1 + SSL_CERT_FILE="$stage/fullchain.pem"; SSL_KEY_FILE="$stage/privkey.pem" + gen_self_signed_cert || return 1 + SSL_CERT_FILE="$active_cert"; SSL_KEY_FILE="$active_key" + deploy_node_cert_pair "$stage/fullchain.pem" "$stage/privkey.pem" || return 1 + rm -rf "$stage" + save_cert_source self_signed + elif [ -n "${INSTALL_CERT_PATH:-}" ]; then + SSL_CERT_FILE="$DATA_DIR/certs/custom/fullchain.pem"; SSL_KEY_FILE="$DATA_DIR/certs/custom/privkey.pem" + deploy_node_cert_pair "$INSTALL_CERT_PATH" "$INSTALL_KEY_PATH" || return 1 + save_cert_source custom + else + local source=acme_domain identifier="${INSTALL_SSL_DOMAIN:-}" ipv6="${INSTALL_SSL_IPV6:-}" + if [ -n "${INSTALL_SSL_IP:-}" ]; then source=acme_ip; identifier="$INSTALL_SSL_IP"; fi + if [ "$source" = acme_ip ]; then + command -v python3 >/dev/null 2>&1 || install_package python3 || return 1 + python3 - "$identifier" "$ipv6" <<'PYIP' || return 1 +import ipaddress, sys +try: + for value, version in zip(sys.argv[1:], (4, 6)): + if version == 6 and not value: continue + addr = ipaddress.ip_address(value) + if addr.version != version or not addr.is_global or '%' in value: + raise ValueError('ACME requires public IPv4 and optional public IPv6 identifiers') +except ValueError as err: + print(err, file=sys.stderr) + sys.exit(1) +PYIP else - read -p "Do you want to restart the node now? (y/N): " restart_choice + [[ "$identifier" =~ ^([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$ ]] || { cert_error "Invalid domain identifier"; return 1; } fi - if [[ "$restart_choice" =~ ^[Yy]$ ]]; then - colorized_echo blue "Restarting node to apply new certificate..." - restart_command -n --no-restart-service - colorized_echo green "✓ Node restarted with new certificate" - else - colorized_echo yellow "Skipped restart. Please restart the node manually to apply the new certificate." - colorized_echo yellow "You can restart it later with: $APP_NAME restart" + local dir="$identifier" + [ "$source" != acme_ip ] || dir=ip + SSL_CERT_FILE="$DATA_DIR/certs/$dir/fullchain.pem"; SSL_KEY_FILE="$DATA_DIR/certs/$dir/privkey.pem" + issue_node_acme "$source" "$identifier" "$ipv6" "${INSTALL_SSL_HTTP_PORT:-80}" || return 1 + save_cert_source "$source" "$identifier" "$ipv6" "${INSTALL_SSL_HTTP_PORT:-80}" + fi +} + +issue_node_acme() { + local source="$1" identifier="$2" ipv6="$3" port="$4" acme + ensure_node_acme || return 1 + get_occupied_ports + if is_port_occupied "$port"; then cert_error "Challenge port $port is in use. Configure challenge routing or free it explicitly; no services were stopped."; return 1; fi + [ "$port" = 80 ] || colorized_echo yellow "Route public TCP port 80 to local challenge port $port." + acme=$(get_node_acme) || return 1 + local args=(--issue -d "$identifier" --standalone --server letsencrypt --httpport "$port" --force) + [ -z "$ipv6" ] || args+=(-d "$ipv6") + [ "$source" != acme_ip ] || args+=(--certificate-profile shortlived --days 6) + "$acme" "${args[@]}" || { cert_error "ACME issuance failed; existing certificates were preserved. Retry explicitly."; return 1; } + stage_node_acme "$acme" "$identifier" || return 1 + deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" +} + +stage_node_acme() { + local acme="$1" identifier="$2" reload="${3:-:}" stage="$DATA_DIR/certs/.acme-staging" + mkdir -p "$stage" && chmod 700 "$stage" || return 1 + local ecc + for ecc in '--ecc' ''; do + # Remove only staging files so a failed install cannot look successful. + rm -f "$stage/fullchain.pem" "$stage/privkey.pem" + local args=(--installcert -d "$identifier" --key-file "$stage/privkey.pem" --fullchain-file "$stage/fullchain.pem" --reloadcmd "$reload") + [ -z "$ecc" ] || args+=("$ecc") + if "$acme" "${args[@]}" && [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; then + chmod 600 "$stage/privkey.pem" || return 1 + printf '%s' "$ecc" >"$stage/key-type" + return 0 fi + done + cert_error "ACME deployment failed; active certificate files were preserved" +} + +register_node_acme_reload() { + [ -f "$DATA_DIR/certs/source.json" ] || return 0 + case "$(cert_metadata source)" in acme_ip|acme_domain) ;; *) return 0;; esac + local acme hook + acme=$(get_node_acme) || return 1 + # printf %q protects paths with spaces and custom instance names in shell hooks. + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + stage_node_acme "$acme" "$(cert_metadata identifier)" "$hook" +} + +show_node_certificate() { + local source=legacy + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + colorized_echo cyan "Certificate source: $source" + if [ "$source" = external_tls ]; then + colorized_echo yellow "Configure the panel with the web server's TLS address and ports. Manage its certificate on the web server." + return 0 fi - - colorized_echo cyan "" - colorized_echo cyan "================================" - colorized_echo green "✓ Certificate renewal completed!" - colorized_echo cyan "================================" - colorized_echo magenta "Please use the following Certificate in pasarguard Panel (it's located in ${DATA_DIR}/certs):" + openssl x509 -in "$SSL_CERT_FILE" -noout -subject -issuer -dates -ext subjectAltName || return 1 + local pin + pin=$(set -o pipefail; openssl x509 -in "$SSL_CERT_FILE" -outform DER | openssl dgst -sha256 | awk '{print tolower($NF)}') || { + cert_error "Could not calculate the certificate SHA-256 pin" + return 1 + } + [[ "$pin" =~ ^[0-9a-f]{64}$ ]] || { cert_error "Invalid certificate SHA-256 pin"; return 1; } + colorized_echo cyan "SHA-256 certificate pin (leaf DER): $pin" + case "$source" in + acme_*) colorized_echo green 'Recommended panel fields: server_ca="", certificate_sha256=null (system trust)' ;; + *) colorized_echo yellow "For self-signed certificates, set certificate_sha256=$pin and server_ca=\"\". Check the panel address matches a SAN." ;; + esac + colorized_echo cyan 'PEM for older panels:' cat "$SSL_CERT_FILE" - colorized_echo cyan "================================" - restart_command +} + +restart_node_cert_services() { + detect_compose + $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" restart || return 1 + if service_installed; then + systemctl restart "$SERVICE_NAME" || return 1 + fi +} + +renew_cert_command() { + check_running_as_root + ensure_env_exists + load_active_cert_paths + local source=legacy + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + if [ "$source" = legacy ]; then + local subject issuer + subject=$(openssl x509 -in "$SSL_CERT_FILE" -noout -subject 2>/dev/null | sed 's/^subject= *//') + issuer=$(openssl x509 -in "$SSL_CERT_FILE" -noout -issuer 2>/dev/null | sed 's/^issuer= *//') + if [ -n "$subject" ] && [ "$subject" = "$issuer" ]; then source=self_signed; fi + fi + case "$source" in + acme_ip|acme_domain) + local acme identifier ipv6 + acme=$(get_node_acme) || return 1 + identifier=$(cert_metadata identifier); ipv6=$(cert_metadata ipv6) + if [ "${1:-}" != --deploy-acme ]; then + # The registered reload hook validates, deploys and restarts both listeners. + local args=(--renew -d "$identifier" --force) + if [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" = --ecc ]; then args+=(--ecc); fi + "$acme" "${args[@]}" || return 1 + return 0 + fi + deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 + ;; + self_signed) + INSTALL_SELF_SIGNED=true + choose_node_certificate || return 1 ;; + custom|legacy) + validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" || return 1 + colorized_echo yellow "Custom/legacy certificates are externally renewed. Validated current files; no certificate was regenerated." + ;; + external_tls) colorized_echo yellow "Manage and renew the certificate on the TLS web server."; return 0 ;; + *) cert_error "Unknown certificate source: $source"; return 1 ;; + esac + restart_node_cert_services || { cert_error "Certificate deployed but listener restart failed"; return 1; } + show_node_certificate } pg_node_main() { - # Bring existing env SSL paths in line with the current APP_NAME (safe no-op if not installed/default) - sync_env_ssl_paths + # Upgrades keep the active certificate paths and files unchanged. + load_active_cert_paths case "$1" in install) @@ -2261,6 +2444,9 @@ pg_node_main() { shift geofiles_command "$@" ;; + show-cert) + show_node_certificate + ;; renew-cert) shift renew_cert_command "$@" diff --git a/tests/integration_pgnode_service_tls.sh b/tests/integration_pgnode_service_tls.sh new file mode 100644 index 0000000..1be5949 --- /dev/null +++ b/tests/integration_pgnode_service_tls.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Real HTTP/TLS sockets and authentication; no host services or ACME accounts. +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +python3 - "$ROOT_DIR/pg-node-service.sh" <<'PY' +import http.client, os, pathlib, shutil, signal, socket, ssl, subprocess, sys, tempfile, time +with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + script = root / 'service.sh' + shutil.copyfile(sys.argv[1], script) + script.chmod(0o700) + def openssl(*args): + subprocess.run(['openssl', *map(str, args)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + # Use a CA-signed leaf to ensure issuer classification never requires mTLS. + openssl('req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-days', '1', '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign', '-subj', '/CN=test-ca', '-keyout', root/'ca.key', '-out', root/'ca.pem') + openssl('req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-subj', '/CN=test-leaf', '-keyout', root/'leaf.key', '-out', root/'leaf.csr') + (root/'ext').write_text('subjectAltName=IP:127.0.0.1\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n') + openssl('x509', '-req', '-in', root/'leaf.csr', '-CA', root/'ca.pem', '-CAkey', root/'ca.key', '-CAcreateserial', '-days', '1', '-extfile', root/'ext', '-out', root/'leaf.pem') + def environment(enabled, host, port): + envfile = root/'service.env' + envfile.write_text(f'API_KEY=test-key\nTLS_ENABLED={enabled}\nNODE_HOST={host}\nAPI_PORT={port}\nSSL_CERT_FILE={root / "leaf.pem" if enabled == "true" else root / "absent.pem"}\nSSL_KEY_FILE={root / "leaf.key" if enabled == "true" else root / "absent.key"}\n') + return dict(os.environ, ENV_FILE=str(envfile)) + for enabled in ('true', 'false'): + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + with (root/'service.log').open('wb') as log: + process = subprocess.Popen(['bash', str(script)], env=environment(enabled, '127.0.0.1', port), stdout=log, stderr=log, start_new_session=True) + try: + def request(key=None): + if enabled == 'true': + client = http.client.HTTPSConnection('127.0.0.1', port, timeout=1, context=ssl.create_default_context(cafile=str(root/'ca.pem'))) + else: + client = http.client.HTTPConnection('127.0.0.1', port, timeout=1) + try: + client.request('GET', '/', headers={'Connection': 'close', **({'x-api-key': key} if key else {})}) + response = client.getresponse() + response.read() + return response.status + finally: + client.close() + deadline = time.monotonic() + 5 + while True: + try: + assert request() == 401 + break + except (OSError, http.client.HTTPException): + if process.poll() is not None or time.monotonic() >= deadline: + raise AssertionError((root/'service.log').read_text()) + time.sleep(.03) + assert request('wrong') == 401 + assert request('test-key') == 200 + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=5) + for enabled, host in [('invalid', '127.0.0.1'), ('false', '0.0.0.0'), ('false', '::'), ('false', '8.8.8.8'), ('false', 'fe80::1'), ('false', '::ffff:8.8.8.8')]: + result = subprocess.run(['bash', str(script)], env=environment(enabled, host, 62050), capture_output=True, timeout=3) + assert result.returncode != 0, (enabled, host) + for host in ('::1', '10.1.1.1', '172.16.0.1', '192.168.0.1', 'fd00::1', '::ffff:192.168.1.1'): + result = subprocess.run(['bash', '-c', 'PG_NODE_SERVICE_SOURCE_ONLY=true source "$1"; private_backend_host "$2"', '_', str(script), host], capture_output=True, timeout=3) + assert result.returncode == 0, (host, result.stderr) +print('Maintenance transport tests passed') +PY diff --git a/tests/unit_pgnode_service.sh b/tests/unit_pgnode_service.sh index c427284..9fc12b3 100644 --- a/tests/unit_pgnode_service.sh +++ b/tests/unit_pgnode_service.sh @@ -46,7 +46,7 @@ fi # tls_verify_level: client-cert verification on only for CA-signed certs. check_certificate() { return 0; } -assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=1" "tls_verify_level: CA-signed -> verify=1" +assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=0" "tls_verify_level: CA-signed keeps API-key authentication" check_certificate() { return 2; } assert_eq "$(tls_verify_level /tmp/cert.pem)" "verify=0" "tls_verify_level: self-signed -> verify=0" check_certificate() { return 1; } diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh new file mode 100644 index 0000000..74e53f4 --- /dev/null +++ b/tests/unit_pgnode_tls.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export APP_TMP_DIR="$WORK_DIR/tmp" APP_NAME=pg-node-tls-test APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR/certs" +curl() { :; } +export PG_NODE_SOURCE_ONLY=true +source "$ROOT_DIR/pg-node.sh" +colorized_echo() { printf '%s\n' "$*"; } +check_running_as_root() { :; } +get_occupied_ports() { OCCUPIED_PORTS=""; } +AUTO_CONFIRM=true +expect_fail() { if "$@"; then echo "FAIL: accepted $*" >&2; exit 1; fi; } +expect_fail validate_ssl_selection +INSTALL_SSL_IPV6=2001:db8::1 +expect_fail validate_ssl_selection +unset INSTALL_SSL_IPV6 +INSTALL_SELF_SIGNED=true INSTALL_SSL_IP=192.0.2.1 +expect_fail validate_ssl_selection +unset INSTALL_SELF_SIGNED +INSTALL_SSL_HTTP_PORT=0 +expect_fail validate_ssl_selection +INSTALL_SSL_HTTP_PORT=8080 +validate_ssl_selection +unset INSTALL_SSL_IP +INSTALL_CERT_PATH=/not-found +expect_fail validate_ssl_selection +unset INSTALL_CERT_PATH +# Generate a real valid pair; preserve full chain bytes and permissions on deployment. +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj '/CN=unused' \ + -addext 'subjectAltName=IP:192.0.2.1,IP:2001:db8::1,DNS:node.example.com' \ + -keyout "$WORK_DIR/key" -out "$WORK_DIR/cert" >/dev/null 2>&1 +validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.1 2001:db8::1 +validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" node.example.com +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" wrong.example.com +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.2 +openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:prime256v1 -out "$WORK_DIR/wrong-key" +expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" +openssl x509 -in "$WORK_DIR/cert" -signkey "$WORK_DIR/key" -days -1 -out "$WORK_DIR/expired" >/dev/null 2>&1 +expect_fail validate_node_cert_pair "$WORK_DIR/expired" "$WORK_DIR/key" +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 1 -subj '/CN=node.example.com' \ + -keyout "$WORK_DIR/no-san-key" -out "$WORK_DIR/no-san" >/dev/null 2>&1 +expect_fail validate_node_cert_pair "$WORK_DIR/no-san" "$WORK_DIR/no-san-key" node.example.com + +deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.1 +cmp "$WORK_DIR/cert" "$SSL_CERT_FILE" +[ "$(stat -c %a "$SSL_KEY_FILE")" = 600 ] +expect_fail deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Self-signed output exposes the leaf certificate pin, not a PEM-file checksum. +save_cert_source self_signed +cert_output=$(show_node_certificate) +expected_pin=$(openssl x509 -in "$WORK_DIR/cert" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':' | tr '[:upper:]' '[:lower:]') +[[ "$cert_output" == *"SHA-256 certificate pin (leaf DER): $expected_pin"* ]] +[[ "$cert_output" == *"certificate_sha256=$expected_pin and server_ca=\"\""* ]] +active_cert="$SSL_CERT_FILE" +SSL_CERT_FILE="$WORK_DIR/no-certificate" +expect_fail show_node_certificate +SSL_CERT_FILE="$active_cert" +# Mock ACME: ECC fails, RSA succeeds; confirm installation tries both and preserves old files on failure. +acme_calls="$WORK_DIR/acme-calls" +mock_acme() { + printf '%s\n' "$*" >>"$acme_calls" + [[ " $* " != *' --ecc '* ]] || return 1 + local key='' cert='' + while [ $# -gt 0 ]; do + case "$1" in --key-file) key="$2"; shift;; --fullchain-file) cert="$2"; shift;; esac + shift + done + [ -z "$key" ] || cp "$WORK_DIR/key" "$key" + [ -z "$cert" ] || cp "$WORK_DIR/cert" "$cert" +} +ensure_node_acme() { :; } +get_node_acme() { echo mock_acme; } +issue_node_acme acme_ip 192.0.2.1 2001:db8::1 8080 +grep -q -- '--certificate-profile shortlived --days 6' "$acme_calls" +grep -q -- '--httpport 8080' "$acme_calls" +grep -q -- '--ecc' "$acme_calls" +mock_acme() { return 1; } +expect_fail issue_node_acme acme_ip 192.0.2.1 '' 80 +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Renewal never changes source implicitly; hook must restart both node and maintenance. +printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" +save_cert_source external_tls +renew_cert_command +save_cert_source custom +restart_called=false +detect_compose() { :; } +restart_node_cert_services() { restart_called=true; } +renew_cert_command +[ "$restart_called" = true ] +cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +save_cert_source acme_ip 192.0.2.1 '' 80 +restart_called=false +renew_cert_command --deploy-acme +[ "$restart_called" = true ] +# Restart both actual deployment targets; propagate individual restart failures. +unset -f restart_node_cert_services +# Restore just this function from the checkout without executing the installer. +eval "$(sed -n '/^restart_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" +COMPOSE=mock_compose +compose_called=false +maintenance_called=false +mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME restart" ]]; } +service_installed() { SERVICE_NAME="$APP_NAME-service"; return 0; } +systemctl() { maintenance_called=true; [ "$*" = "restart $APP_NAME-service" ]; } +restart_node_cert_services +[ "$compose_called" = true ] && [ "$maintenance_called" = true ] +systemctl() { return 1; } +expect_fail restart_node_cert_services +mock_compose() { return 1; } +expect_fail restart_node_cert_services +# Upgrade loading honors managed paths unchanged. +SSL_CERT_FILE=/wrong; SSL_KEY_FILE=/wrong +load_active_cert_paths +[ "$SSL_CERT_FILE" != /wrong ] +echo 'TLS installer tests passed' From 755b7f0b1b110d59964dab4cb771f50b693e00ea Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 17:38:54 +0330 Subject: [PATCH 02/10] feat(tls): implement certificate deployment locking and enhance validation checks --- pg-node.sh | 96 ++++++++++++++++++++++++++++++++++++---- tests/unit_pgnode_tls.sh | 72 ++++++++++++++++++++++++++++-- 2 files changed, 156 insertions(+), 12 deletions(-) diff --git a/pg-node.sh b/pg-node.sh index d23a735..01dff9b 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -756,7 +756,7 @@ install_node() { mkdir -p "$APP_DIR" colorized_echo green " ✓ Directories created" colorized_echo cyan "" - choose_node_certificate || exit 1 + with_node_cert_lock prepare_install_node_certificate || exit 1 if [ -n "${INSTALL_API_KEY:-}" ]; then API_KEY="$INSTALL_API_KEY" elif [ "$AUTO_CONFIRM" = true ]; then @@ -2394,17 +2394,46 @@ validate_node_cert_pair() ( done ) +# Nested certificate operations (including synchronous ACME reload hooks) share +# the same open lock descriptor. Never unlink the lock file: waiters use its inode. +with_node_cert_lock() { + local lock_file="$DATA_DIR/certs/.deployment.lock" status=0 + mkdir -p "$DATA_DIR/certs" || return 1 + if [[ "${PG_NODE_CERT_LOCK_FD:-}" =~ ^[0-9]+$ ]] && + [ "$(readlink "/proc/self/fd/$PG_NODE_CERT_LOCK_FD")" = "$lock_file" ] && + flock -n "$PG_NODE_CERT_LOCK_FD"; then + "$@" + return $? + fi + local PG_NODE_CERT_LOCK_FD + exec {PG_NODE_CERT_LOCK_FD}>"$lock_file" || return 1 + if flock -x "$PG_NODE_CERT_LOCK_FD"; then + export PG_NODE_CERT_LOCK_FD + "$@" || status=$? + else + status=1 + fi + exec {PG_NODE_CERT_LOCK_FD}>&- + return "$status" +} + # Stage and validate before touching either active file. Keep backups for rollback. deploy_node_cert_pair() { + with_node_cert_lock deploy_node_cert_pair_locked "$@" +} + +deploy_node_cert_pair_locked() ( local cert="$1" key="$2" identity="${3:-}" ipv6="${4:-}" validate_node_cert_pair "$cert" "$key" "$identity" "$ipv6" || return 1 mkdir -p "$(dirname "$SSL_CERT_FILE")" "$(dirname "$SSL_KEY_FILE")" || return 1 chmod 700 "$(dirname "$SSL_KEY_FILE")" || return 1 - local stage_cert stage_key + local stage_cert="" stage_key="" + trap 'rm -f -- "$stage_cert" "$stage_key"' EXIT stage_cert=$(mktemp "${SSL_CERT_FILE}.stage.XXXXXX") || return 1 stage_key=$(mktemp "${SSL_KEY_FILE}.stage.XXXXXX") || return 1 cp "$cert" "$stage_cert" && cp "$key" "$stage_key" || return 1 chmod 644 "$stage_cert" && chmod 600 "$stage_key" || return 1 + validate_node_cert_pair "$stage_cert" "$stage_key" "$identity" "$ipv6" || return 1 if [ -f "$SSL_CERT_FILE" ]; then cp -p "$SSL_CERT_FILE" "${SSL_CERT_FILE}.previous" || return 1; fi if [ -f "$SSL_KEY_FILE" ]; then cp -p "$SSL_KEY_FILE" "${SSL_KEY_FILE}.previous" || return 1; fi if ! mv -f "$stage_key" "$SSL_KEY_FILE" || ! mv -f "$stage_cert" "$SSL_CERT_FILE"; then @@ -2413,7 +2442,7 @@ deploy_node_cert_pair() { cert_error "Deployment failed; restored previous certificate files" return 1 fi -} +) get_node_acme() { if [ -x "${HOME}/.acme.sh/acme.sh" ]; then printf '%s\n' "${HOME}/.acme.sh/acme.sh" @@ -2459,6 +2488,19 @@ validate_ssl_selection() { fi } +# Retained paths can point outside the instance's bind mount. Copy the selected +# active pair into that mount before writing its paths to .env. +prepare_install_node_certificate() { + choose_node_certificate || return 1 + if [ "$TLS_ENABLED" = true ] && + { [[ "$SSL_CERT_FILE" != "$DATA_DIR/"* ]] || [[ "$SSL_KEY_FILE" != "$DATA_DIR/"* ]]; }; then + local cert="$SSL_CERT_FILE" key="$SSL_KEY_FILE" + SSL_CERT_FILE="$DATA_DIR/certs/ssl_cert.pem" + SSL_KEY_FILE="$DATA_DIR/certs/ssl_key.pem" + deploy_node_cert_pair "$cert" "$key" || return 1 + fi +} + choose_node_certificate() { validate_ssl_selection || return 1 if [ -z "${INSTALL_SSL_IP:-}${INSTALL_SSL_DOMAIN:-}${INSTALL_CERT_PATH:-}" ] && [ "${INSTALL_SELF_SIGNED:-false}" != true ] && [ "${INSTALL_NO_SSL:-false}" != true ]; then @@ -2529,6 +2571,10 @@ PYIP } issue_node_acme() { + with_node_cert_lock issue_node_acme_locked "$@" +} + +issue_node_acme_locked() { local source="$1" identifier="$2" ipv6="$3" port="$4" acme ensure_node_acme || return 1 get_occupied_ports @@ -2544,16 +2590,34 @@ issue_node_acme() { } stage_node_acme() { + with_node_cert_lock stage_node_acme_locked "$@" +} + +stage_node_acme_locked() { local acme="$1" identifier="$2" reload="${3:-:}" stage="$DATA_DIR/certs/.acme-staging" mkdir -p "$stage" && chmod 700 "$stage" || return 1 local ecc for ecc in '--ecc' ''; do - # Remove only staging files so a failed install cannot look successful. - rm -f "$stage/fullchain.pem" "$stage/privkey.pem" - local args=(--installcert -d "$identifier" --key-file "$stage/privkey.pem" --fullchain-file "$stage/fullchain.pem" --reloadcmd "$reload") + local key_target=no cert_target=no + if [ "$reload" = : ]; then + # Remove only staging files so a failed install cannot look successful. + rm -f "$stage/fullchain.pem" "$stage/privkey.pem" + key_target="$stage/privkey.pem"; cert_target="$stage/fullchain.pem" + fi + # For automatic renewals ACME invokes the hook without writing staging. + # The hook copies ACME's exported source paths while holding our lock. + local args=(--installcert -d "$identifier" --key-file "$key_target" --fullchain-file "$cert_target" --reloadcmd "$reload") [ -z "$ecc" ] || args+=("$ecc") - if "$acme" "${args[@]}" && [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; then - chmod 600 "$stage/privkey.pem" || return 1 + if "$acme" "${args[@]}" && + { [ "$reload" != : ] || { [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; }; }; then + if [ "$reload" = : ]; then + chmod 600 "$stage/privkey.pem" || return 1 + # Do not leave staging as an unattended ACME write target while + # installation is still preparing the permanent reload hook. + local reset_args=(--installcert -d "$identifier" --key-file no --fullchain-file no --reloadcmd :) + [ -z "$ecc" ] || reset_args+=("$ecc") + "$acme" "${reset_args[@]}" || return 1 + fi printf '%s' "$ecc" >"$stage/key-type" return 0 fi @@ -2562,6 +2626,10 @@ stage_node_acme() { } register_node_acme_reload() { + with_node_cert_lock register_node_acme_reload_locked "$@" +} + +register_node_acme_reload_locked() { [ -f "$DATA_DIR/certs/source.json" ] || return 0 case "$(cert_metadata source)" in acme_ip|acme_domain) ;; *) return 0;; esac local acme hook @@ -2604,6 +2672,10 @@ restart_node_cert_services() { } renew_cert_command() { + with_node_cert_lock renew_cert_command_locked "$@" +} + +renew_cert_command_locked() { check_running_as_root ensure_env_exists load_active_cert_paths @@ -2627,6 +2699,14 @@ renew_cert_command() { "$acme" "${args[@]}" || return 1 return 0 fi + if [ -n "${CERT_FULLCHAIN_PATH:-}${CERT_KEY_PATH:-}" ]; then + [ -n "${CERT_FULLCHAIN_PATH:-}" ] && [ -n "${CERT_KEY_PATH:-}" ] || return 1 + local stage="$DATA_DIR/certs/.acme-staging" + mkdir -p "$stage" && chmod 700 "$stage" || return 1 + cp "$CERT_FULLCHAIN_PATH" "$stage/fullchain.pem" && + cp "$CERT_KEY_PATH" "$stage/privkey.pem" && + chmod 600 "$stage/privkey.pem" || return 1 + fi deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 ;; self_signed) diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index 74e53f4..8a99b90 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -38,8 +38,16 @@ expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" wrong.examp expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.2 openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:prime256v1 -out "$WORK_DIR/wrong-key" expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" -openssl x509 -in "$WORK_DIR/cert" -signkey "$WORK_DIR/key" -days -1 -out "$WORK_DIR/expired" >/dev/null 2>&1 -expect_fail validate_node_cert_pair "$WORK_DIR/expired" "$WORK_DIR/key" +# Advance validation's clock past notAfter; newer OpenSSL rejects -days -1. +( + expiry=$(openssl x509 -in "$WORK_DIR/cert" -enddate -noout) + future=$(date -d "${expiry#*=}" +%s) + date() { + if [ "$*" = +%s ]; then printf '%s\n' "$((future + 1))" + else command date "$@"; fi + } + expect_fail validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" +) openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 1 -subj '/CN=node.example.com' \ -keyout "$WORK_DIR/no-san-key" -out "$WORK_DIR/no-san" >/dev/null 2>&1 expect_fail validate_node_cert_pair "$WORK_DIR/no-san" "$WORK_DIR/no-san-key" node.example.com @@ -49,6 +57,45 @@ cmp "$WORK_DIR/cert" "$SSL_CERT_FILE" [ "$(stat -c %a "$SSL_KEY_FILE")" = 600 ] expect_fail deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/wrong-key" cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Concurrent deployments cannot interleave their key and certificate moves. +move_log="$WORK_DIR/moves" +( + mv() { + if [ "${*: -1}" = "$SSL_KEY_FILE" ]; then + echo key >>"$move_log" + sleep 0.1 + elif [ "${*: -1}" = "$SSL_CERT_FILE" ]; then + echo cert >>"$move_log" + fi + command mv "$@" + } + deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" & + first=$! + deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" & + second=$! + wait "$first" + wait "$second" +) +[ "$(cat "$move_log")" = "$(printf 'key\ncert\nkey\ncert')" ] +# Failure closes the descriptor and removes temporary files. +( + cp() { return 1; } + expect_fail deploy_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" +) +flock -n "$DATA_DIR/certs/.deployment.lock" true +# Synchronous reload subprocesses inherit ownership without deadlocking. +with_node_cert_lock bash -c 'flock -n "$PG_NODE_CERT_LOCK_FD" && ! flock -n "$DATA_DIR/certs/.deployment.lock" true' +[ -z "$(find "$DATA_DIR/certs" -name '*.stage.*' -print)" ] +# Selected certificates outside the data mount are relocated with matching paths. +( + choose_node_certificate() { TLS_ENABLED=true; } + SSL_CERT_FILE="$WORK_DIR/cert"; SSL_KEY_FILE="$WORK_DIR/key" + with_node_cert_lock prepare_install_node_certificate + [ "$SSL_CERT_FILE" = "$DATA_DIR/certs/ssl_cert.pem" ] + [ "$SSL_KEY_FILE" = "$DATA_DIR/certs/ssl_key.pem" ] + cmp "$WORK_DIR/cert" "$SSL_CERT_FILE" + cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +) # Self-signed output exposes the leaf certificate pin, not a PEM-file checksum. save_cert_source self_signed cert_output=$(show_node_certificate) @@ -62,6 +109,11 @@ SSL_CERT_FILE="$active_cert" # Mock ACME: ECC fails, RSA succeeds; confirm installation tries both and preserves old files on failure. acme_calls="$WORK_DIR/acme-calls" mock_acme() { + # ACME staging is owned by the same lock as certificate deployment. + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'FAIL: ACME ran without the deployment lock' >&2 + return 1 + fi printf '%s\n' "$*" >>"$acme_calls" [[ " $* " != *' --ecc '* ]] || return 1 local key='' cert='' @@ -69,6 +121,8 @@ mock_acme() { case "$1" in --key-file) key="$2"; shift;; --fullchain-file) cert="$2"; shift;; esac shift done + [ "$key" != no ] || key='' + [ "$cert" != no ] || cert='' [ -z "$key" ] || cp "$WORK_DIR/key" "$key" [ -z "$cert" ] || cp "$WORK_DIR/cert" "$cert" } @@ -88,13 +142,23 @@ renew_cert_command save_cert_source custom restart_called=false detect_compose() { :; } -restart_node_cert_services() { restart_called=true; } +restart_node_cert_services() { + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'FAIL: deployment lock released before restart' >&2 + return 1 + fi + restart_called=true +} renew_cert_command [ "$restart_called" = true ] cmp "$WORK_DIR/key" "$SSL_KEY_FILE" save_cert_source acme_ip 192.0.2.1 '' 80 +# ACME's cron must not write shared staging before the locked reload hook. +mock_acme() { printf '%s\n' "$*" >>"$acme_calls"; } +register_node_acme_reload +grep -q -- '--key-file no --fullchain-file no' "$acme_calls" restart_called=false -renew_cert_command --deploy-acme +CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme [ "$restart_called" = true ] # Restart both actual deployment targets; propagate individual restart failures. unset -f restart_node_cert_services From 342441ef63f015c5612fdb688b59aebc5d80c14f Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 19:29:20 +0330 Subject: [PATCH 03/10] fix: preserve installed SANs during self-signed certificate renewal --- pg-node.sh | 6 ++++++ tests/unit_pgnode_tls.sh | 42 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/pg-node.sh b/pg-node.sh index 01dff9b..cc85805 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -2710,6 +2710,12 @@ renew_cert_command_locked() { deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 ;; self_signed) + # Reuse the active certificate's names, including on unattended renewals. + local INSTALL_SAN_ENTRIES + INSTALL_SAN_ENTRIES=$(set -o pipefail; openssl x509 -in "$SSL_CERT_FILE" -noout -ext subjectAltName | + tr ',' '\n' | sed -n 's/^[[:space:]]*DNS:/DNS:/p; s/^[[:space:]]*IP Address:/IP:/p' | + paste -sd, -) || { cert_error "Could not read existing certificate SANs"; return 1; } + [ -n "$INSTALL_SAN_ENTRIES" ] || { cert_error "Existing certificate requires DNS or IP SANs for renewal"; return 1; } INSTALL_SELF_SIGNED=true choose_node_certificate || return 1 ;; custom|legacy) diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index 8a99b90..97fd82c 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -30,7 +30,7 @@ expect_fail validate_ssl_selection unset INSTALL_CERT_PATH # Generate a real valid pair; preserve full chain bytes and permissions on deployment. openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj '/CN=unused' \ - -addext 'subjectAltName=IP:192.0.2.1,IP:2001:db8::1,DNS:node.example.com' \ + -addext 'subjectAltName=IP:192.0.2.1,IP:2001:db8::1,DNS:node.example.com,DNS:*.example.net' \ -keyout "$WORK_DIR/key" -out "$WORK_DIR/cert" >/dev/null 2>&1 validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" 192.0.2.1 2001:db8::1 validate_node_cert_pair "$WORK_DIR/cert" "$WORK_DIR/key" node.example.com @@ -152,6 +152,46 @@ restart_node_cert_services() { renew_cert_command [ "$restart_called" = true ] cmp "$WORK_DIR/key" "$SSL_KEY_FILE" +# Renewal preserves installed DNS, wildcard, IPv4 and IPv6 SANs without prompting. +( + ENV_FILE="$WORK_DIR/renew.env" + SSL_CERT_FILE="$WORK_DIR/renew.pem" SSL_KEY_FILE="$WORK_DIR/renew.key" + printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" + NODE_IP=198.51.100.2 NODE_IP_V4=198.51.100.2 NODE_IP_V6='' + read() { + if [[ "$*" == *'Enter additional SAN entries'* ]]; then + touch "$WORK_DIR/san-prompt" + return 1 + fi + builtin read "$@" + } + for mode in self_signed legacy; do + cp "$WORK_DIR/cert" "$SSL_CERT_FILE" + cp "$WORK_DIR/key" "$SSL_KEY_FILE" + if [ "$mode" = legacy ]; then + rm -f "$DATA_DIR/certs/source.json" + AUTO_CONFIRM=true + else + save_cert_source self_signed + AUTO_CONFIRM=false + fi + restart_called=false + renew_cert_command "$ENV_FILE" + restart_called=false + expect_fail renew_cert_command >"$acme_calls"; } From 342999eabe066739660222fb7babe9e344e5fa29 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 20:29:03 +0330 Subject: [PATCH 04/10] fix(node): preserve running installer version for ACME reload hooks --- pg-node.sh | 28 ++++++++++++---- tests/run_all.sh | 1 + tests/unit_pgnode_script_install.sh | 52 +++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 7 deletions(-) create mode 100644 tests/unit_pgnode_script_install.sh diff --git a/pg-node.sh b/pg-node.sh index cc85805..be65fe6 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -262,19 +262,30 @@ configure_firewall_for_port() { colorized_echo yellow "$hint" } -# Download and install the pg-node CLI script to /usr/local/bin. +# Install this pg-node CLI version to /usr/local/bin, including branch installs. install_node_script() { print_script_execution_header "pg-node" "$SCRIPT_COMMIT_SHA" "install" colorized_echo blue "Installing node script" TARGET_PATH="/usr/local/bin/$APP_NAME" TEMP_FILE=$(create_temp_file "pg-node-script" ".sh") - # Download script to temp file first - colorized_echo cyan " Downloading script from GitHub..." - if ! github_download_file "$(github_raw_url "$FETCH_REPO" "pg-node.sh")" "$TEMP_FILE"; then - colorized_echo red "✗ Failed to download script from $(github_raw_url "$FETCH_REPO" "pg-node.sh")" + # The ACME hook immediately invokes the installed CLI. Fetching main here + # can replace a branch installer with an older CLI that treats renew-cert + # as self-signed renewal and ignores --deploy-acme. + colorized_echo cyan " Copying the running installer..." + local script_source="${BASH_SOURCE[0]:-}" + if [ -f "$script_source" ]; then + if ! cp "$script_source" "$TEMP_FILE"; then + rm -f "$TEMP_FILE" + return 1 + fi + elif [ -n "${BASH_EXECUTION_STRING:-}" ]; then + # Support the documented bash -c "$(curl ...)" installation form. + printf '%s\n' "$BASH_EXECUTION_STRING" >"$TEMP_FILE" || return 1 + else + colorized_echo red "✗ Cannot locate the running installer" rm -f "$TEMP_FILE" - exit 1 + return 1 fi # Replace APP_NAME in the script - the script has APP_NAME="" on line 5 @@ -283,7 +294,10 @@ install_node_script() { sed -i "s|^APP_NAME=.*|APP_NAME=\"$APP_NAME\"|" "$TEMP_FILE" fi - install_shared_libs_from_repo "$FETCH_REPO" common.sh system.sh docker.sh github.sh + if ! install_shared_libs_from_repo "$FETCH_REPO" common.sh system.sh docker.sh github.sh; then + rm -f "$TEMP_FILE" + return 1 + fi # Remove old file if it exists if [ -f "$TARGET_PATH" ]; then diff --git a/tests/run_all.sh b/tests/run_all.sh index 1c417ec..bb3d170 100755 --- a/tests/run_all.sh +++ b/tests/run_all.sh @@ -13,6 +13,7 @@ SUITES=( "unit_lib_system.sh" "unit_pasarguard.sh" "unit_pgnode.sh" + "unit_pgnode_script_install.sh" "unit_pgnode_tls.sh" "integration_pgnode_service_tls.sh" "unit_pgnode_service.sh" diff --git a/tests/unit_pgnode_script_install.sh b/tests/unit_pgnode_script_install.sh new file mode 100644 index 0000000..c114d09 --- /dev/null +++ b/tests/unit_pgnode_script_install.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export ROOT_DIR WORK_DIR +export APP_TMP_DIR="$WORK_DIR/tmp" APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" +export PG_NODE_SOURCE_ONLY=true PG_NODE_SCRIPT_DIR="$ROOT_DIR" +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR" "$WORK_DIR/bin" +# Block source-time IP detection and any accidental network requests. +curl() { :; } +export -f curl + +cat >"$WORK_DIR/install-harness.sh" <<'HARNESS' +colorized_echo() { :; } +print_script_execution_header() { :; } +github_download_file() { echo 'Unexpected script download' >&2; return 1; } +install_shared_libs_from_repo() { :; } +# Redirect the production install destination without touching system files. +mv() { + [ "$2" = "/usr/local/bin/$APP_NAME" ] + TARGET_PATH="$WORK_DIR/bin/$APP_NAME" + command mv "$1" "$TARGET_PATH" +} +rm() { + local arg + for arg in "$@"; do + case "$arg" in /usr/*) echo 'Unexpected system file removal' >&2; return 1;; esac + done + command rm "$@" +} +APP_NAME="pg-node-install-regression" +install_node_script +sed "s|^APP_NAME=.*|APP_NAME=\"$APP_NAME\"|" "$EXPECTED_SCRIPT" >"$WORK_DIR/expected.sh" +cmp "$WORK_DIR/expected.sh" "$TARGET_PATH" +[ -x "$TARGET_PATH" ] +# The installed copy must retain the ACME deployment handler. +grep -q -- '--deploy-acme' "$TARGET_PATH" +HARNESS + +# File/checkout invocation must preserve the running version. +export EXPECTED_SCRIPT="$ROOT_DIR/pg-node.sh" +bash -c 'source "$ROOT_DIR/pg-node.sh"; source "$WORK_DIR/install-harness.sh"' + +# Reproduce bash -c "$(curl ...)": the script has no backing source file. +cat "$ROOT_DIR/pg-node.sh" >"$WORK_DIR/inline.sh" +printf '\nsource "$WORK_DIR/install-harness.sh"\n' >>"$WORK_DIR/inline.sh" +export EXPECTED_SCRIPT="$WORK_DIR/inline.sh" +bash -c "$(cat "$WORK_DIR/inline.sh")" @ install-script + +echo 'Node script installation tests passed' From db93ab9f5d1dd26c4a0cb78dac6f688bbe56f805 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 20:44:20 +0330 Subject: [PATCH 05/10] fix(node): clarify certificate guidance and avoid duplicate PEM output --- pg-node.sh | 10 +++++++++- tests/unit_pgnode_tls.sh | 7 ++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/pg-node.sh b/pg-node.sh index be65fe6..33107e1 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -2522,6 +2522,8 @@ choose_node_certificate() { echo "2) Let's Encrypt domain certificate" echo "3) Custom certificate and key paths" echo "4) Self-signed certificate" + echo " For local IPs, use a self-signed or private CA certificate containing the local IPs." + echo " This option generates a self-signed certificate; import a private CA certificate with option 3." echo "5) External web server terminates TLS (advanced)" local selection read -r -p "Certificate [1]: " selection @@ -2674,6 +2676,7 @@ show_node_certificate() { *) colorized_echo yellow "For self-signed certificates, set certificate_sha256=$pin and server_ca=\"\". Check the panel address matches a SAN." ;; esac colorized_echo cyan 'PEM for older panels:' + colorized_echo yellow 'If multiple PEM certificate blocks appear below, copy only the first block (the node certificate) into the panel certificate field, including its BEGIN CERTIFICATE and END CERTIFICATE lines.' cat "$SSL_CERT_FILE" } @@ -2711,6 +2714,7 @@ renew_cert_command_locked() { local args=(--renew -d "$identifier" --force) if [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" = --ecc ]; then args+=(--ecc); fi "$acme" "${args[@]}" || return 1 + show_node_certificate || return 1 return 0 fi if [ -n "${CERT_FULLCHAIN_PATH:-}${CERT_KEY_PATH:-}" ]; then @@ -2740,7 +2744,11 @@ renew_cert_command_locked() { *) cert_error "Unknown certificate source: $source"; return 1 ;; esac restart_node_cert_services || { cert_error "Certificate deployed but listener restart failed"; return 1; } - show_node_certificate + if [ "${1:-}" = --deploy-acme ]; then + colorized_echo green "ACME certificate deployed; node listeners restarted." + else + show_node_certificate + fi } # Main CLI dispatch handler for pg-node. diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index 97fd82c..79415ed 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -198,8 +198,13 @@ mock_acme() { printf '%s\n' "$*" >>"$acme_calls"; } register_node_acme_reload grep -q -- '--key-file no --fullchain-file no' "$acme_calls" restart_called=false -CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme +CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme >"$WORK_DIR/deploy-output" [ "$restart_called" = true ] +# The internal hook does not duplicate the installer's certificate output. +! grep -q -- 'BEGIN CERTIFICATE' "$WORK_DIR/deploy-output" +# Explicit renewal still prints the resulting certificate once. +renew_cert_command >"$WORK_DIR/renew-output" +[ "$(grep -c -- 'BEGIN CERTIFICATE' "$WORK_DIR/renew-output")" = 1 ] # Restart both actual deployment targets; propagate individual restart failures. unset -f restart_node_cert_services # Restore just this function from the checkout without executing the installer. From 2725867c2fa71fee4fc003a6560836ae33e2d3d7 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Tue, 17 Nov 2026 11:52:08 +0330 Subject: [PATCH 06/10] feat(node): add certificate hot reload and managed ACME renewal --- README.md | 7 + docs/ssl-and-certificates.md | 47 +++- pg-node.sh | 357 ++++++++++++++++++++++-- tests/integration_pgnode_service_tls.sh | 12 +- tests/run_all.sh | 1 + tests/unit_pgnode_renewal.sh | 116 ++++++++ tests/unit_pgnode_tls.sh | 57 ++-- 7 files changed, 551 insertions(+), 46 deletions(-) create mode 100644 tests/unit_pgnode_renewal.sh diff --git a/README.md b/README.md index a8ab00a..0e5d274 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,11 @@ The panel must use the web server's TLS endpoints for both node and maintenance requests. API-key authentication stays required. Certificate source metadata is stored under the instance data directory; `renew-cert` follows that source and `show-cert` displays its identity, expiry, fingerprint and legacy PEM. +Renewal uses SIGHUP and verifies fresh TLS connections, with no restart fallback. +`certificate-status --json` reports local deployment and renewal state. +Upgrade both node and node-serviced to releases supporting certificate hot reload +before enabling this workflow on an existing installation with +`sudo pg-node certificate-renewal-enable`. Old unattended commands relying on implicit self-signed certificates must add `--self-signed`. Routine updates preserve certificate paths and files. See @@ -232,6 +237,8 @@ The following flags can be supplied to `pasarguard install`: | `pg-node core-update` | Updates or switches the installed Xray-core binary version. | | `pg-node geofiles` | Downloads official `geoip.dat` and `geosite.dat` routing assets. | | `pg-node renew-cert` | Renews or validates certificates according to their configured source. | +| `pg-node certificate-status [--json]` | Reports local renewal state, expiry, verified fingerprint and errors. | +| `pg-node certificate-renewal-enable` | Enables the managed ACME scheduler after both services support SIGHUP reload. | | `pg-node show-cert` | Displays certificate identity, expiry, fingerprint, and legacy PEM. | | `pg-node service-install` | Registers and enables the companion `systemd` service daemon. | | `pg-node service-status` | Inspects systemd service status (`pg-node-service.service`). | diff --git a/docs/ssl-and-certificates.md b/docs/ssl-and-certificates.md index f5af569..051c6aa 100644 --- a/docs/ssl-and-certificates.md +++ b/docs/ssl-and-certificates.md @@ -130,7 +130,52 @@ To renew or validate a node certificate according to its saved source: ```bash sudo pg-node renew-cert ``` -ACME sources renew through acme.sh; self-signed sources regenerate. Custom and legacy sources validate existing files without replacement. These sources then restart the node container and companion service. External TLS sources are renewed on the web server. Use `sudo pg-node show-cert` to inspect the active certificate and fingerprint. +ACME sources renew through acme.sh. Self-signed sources regenerate only when you +explicitly run `renew-cert`, preserving the 3,650-day lifetime and installed SANs. +The command prints the new fingerprint: update the saved panel pin. Established +connections continue, but new pinned connections fail until the pin matches. +Custom and legacy sources validate the operator-maintained files. External TLS +certificates and graceful frontend reloads remain managed on the web server. + +Certificate deployment preserves configured file paths and container mappings, +sends SIGHUP to the Compose `node` process and the systemd maintenance main +process, and verifies their fingerprints through fresh TLS handshakes. Only an +installed maintenance service is checked. Success requires all deployed endpoints +to match. Reload failures retain previous file backups (`.previous`) and retry the +reload without issuance. There is no automatic restart fallback. + +**Rollout prerequisite:** first upgrade both node and node-serviced to versions +supporting certificate reload on SIGHUP. That initial software upgrade requires a +restart. Enabling hooks against older versions can terminate them on SIGHUP. +After the upgrade, enable or migrate an existing managed ACME installation: + +```bash +sudo pg-node certificate-renewal-enable +sudo pg-node certificate-status +sudo pg-node certificate-status --json +``` + +New managed ACME installations register one per-instance cron entry. It ticks +every five minutes and checks normal renewal eligibility hourly. Certificate +storage is isolated under `$DATA_DIR/certs/acme`, outside the shared ACME cron +scan. Migration copies this certificate's existing ACME directory before disabling +its old shared renewal entry; unrelated certificates and cron jobs stay intact. +The fallback renewal time is two thirds of the issued lifetime. The scheduler +updates only the isolated domain configuration with this fallback, clearing the +old fixed-day setting so supported acme.sh CA renewal guidance can take precedence. Transient failures retry with exponential backoff and jitter +from five minutes up to one hour, honoring longer reported Retry-After delays. +Configuration rejections suspend issuance until `.env` or source metadata changes, +or an operator runs `renew-cert` to retry explicitly. Self-signed, custom, and +external certificates are never regenerated by scheduled jobs. + +Atomic local state lives in `$DATA_DIR/certs/renewal-status.json`; private ACME +diagnostics are in `acme-last-attempt.log`, alongside `renewal.log`. These remain +available without panel connectivity. Status distinguishes the last verified +active fingerprint from the files currently on disk, reports current file date +validity separately, and never treats a past successful reload as proof that an +expired file is still valid. Use `show-cert` for identity, fingerprint and legacy +PEM output. For custom replacements, place the complete matching pair at the +configured paths before invoking `renew-cert`. ### Expiration Monitoring During startup, `pg-node-service` inspects the certificate validity window for CA-signed certificates (where Subject and Issuer differ): diff --git a/pg-node.sh b/pg-node.sh index 33107e1..c854fd9 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -53,7 +53,7 @@ bootstrap_pg_node_shared_libs() { # outdated copy can never be sourced (the files are small). Best-effort: if the # refresh fails (e.g. no network) any existing copy is kept and the presence # check below still guards against a genuinely missing library. -if [ "$running_from_checkout" = false ]; then +if [ "$running_from_checkout" = false ] && [[ " $* " != *" certificate-"* && " $* " != *" renew-cert "* ]]; then bootstrap_pg_node_shared_libs || true fi @@ -128,8 +128,12 @@ done set -- "${ARGS[@]}" COMMAND="${1:-}" # Fetch IP address from ifconfig.io API -NODE_IP_V4=$(curl -s -4 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") -NODE_IP_V6=$(curl -s -6 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") +NODE_IP_V4='' NODE_IP_V6='' +case "$COMMAND" in + certificate-*|renew-cert|show-cert) ;; + *) NODE_IP_V4=$(curl -s -4 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "") + NODE_IP_V6=$(curl -s -6 --fail --max-time 5 ifconfig.io 2>/dev/null || echo "");; +esac NODE_IP="${NODE_IP_V4:-}" if [ -z "$NODE_IP" ]; then NODE_IP="${NODE_IP_V6:-}" @@ -1322,6 +1326,13 @@ install_command() { colorized_echo blue "================================" colorized_echo magenta " node is set up with the following IP: $NODE_IP and Port: $SERVICE_PORT." register_node_acme_reload || return 1 + if [ "${TLS_ENABLED:-true}" = false ]; then + write_node_cert_status external_tls + elif verify_node_cert_services; then + write_node_cert_status deployed + else + write_node_cert_status unverified 'Initial TLS endpoint verification failed; inspect service logs' + fi show_node_certificate colorized_echo blue "================================" colorized_echo magenta "Next, use the API Key (UUID v4) in pasarguard Panel: " @@ -1351,6 +1362,7 @@ uninstall_command() { if service_installed; then uninstall_service_command fi + remove_node_cert_scheduler || return 1 uninstall_completion uninstall_node_script uninstall_node @@ -2100,7 +2112,7 @@ _node_completions() local cur cmds COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert show-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" + cmds="up down restart status logs install update uninstall install-script uninstall-script core-update geofiles renew-cert certificate-status certificate-renewal-enable show-cert version-script script-version edit edit-env completion service-install service-uninstall service-restart service-status service-logs service-update service-start service-stop" COMPREPLY=( $(compgen -W "$cmds" -- "$cur") ) return 0 } @@ -2129,6 +2141,8 @@ commands=( core-update geofiles renew-cert + certificate-status + certificate-renewal-enable show-cert version-script script-version @@ -2248,6 +2262,8 @@ usage() { colorized_echo yellow " --service-port PORT $(tput sgr0)✓ Set service port" colorized_echo yellow " --cert-path PATH $(tput sgr0)✓ Set public certificate path" colorized_echo yellow " --key-path PATH $(tput sgr0)✓ Set private key path" + echo " certificate-renewal-enable Enable managed ACME scheduler after upgrading both services" + echo " certificate-status [--json] Show local renewal and deployment status" echo " show-cert Display identity, expiry, SHA-256 fingerprint and legacy PEM" echo " --ssl-ip IPV4 Let's Encrypt IP certificate (default; required unattended)" echo " --ssl-ipv6 IPV6 Add IPv6 SAN (requires --ssl-ip)" @@ -2395,6 +2411,13 @@ validate_node_cert_pair() ( end=$(openssl x509 -in "$cert" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 now=$(date +%s) [ "$start" -le "$now" ] && [ "$end" -gt "$now" ] || { cert_error "Certificate is expired or not yet valid"; return 1; } + # Parse every PEM block, rejecting a malformed/truncated full chain. + local begins ends + begins=$(grep -c '^-----BEGIN CERTIFICATE-----' "$cert") + ends=$(grep -c '^-----END CERTIFICATE-----' "$cert") + [ "$begins" -eq "$ends" ] && openssl crl2pkcs7 -nocrl -certfile "$cert" -outform DER >/dev/null 2>&1 || { + cert_error 'Invalid certificate chain'; return 1; + } # SAN is mandatory; never rely on Common Name fallback. openssl x509 -in "$cert" -noout -ext subjectAltName | grep -qE 'DNS:|IP Address:' || { cert_error "Certificate requires SANs"; return 1; } local id flag @@ -2458,6 +2481,12 @@ deploy_node_cert_pair_locked() ( fi ) +validate_node_acme_chain() { + openssl verify -purpose sslserver -untrusted "$1" "$1" >/dev/null 2>&1 || { + cert_error 'ACME full chain does not verify against configured system trust'; return 1; + } +} + get_node_acme() { if [ -x "${HOME}/.acme.sh/acme.sh" ]; then printf '%s\n' "${HOME}/.acme.sh/acme.sh" elif [ -x /root/.acme.sh/acme.sh ]; then printf '%s\n' /root/.acme.sh/acme.sh @@ -2474,12 +2503,12 @@ ensure_node_acme() { fi if ! get_node_acme >/dev/null; then installer=$(mktemp) || return 1 - curl -fsSL https://get.acme.sh -o "$installer" && sh "$installer" || return 1 + curl -fsSL https://get.acme.sh -o "$installer" && sh "$installer" -- --nocron || return 1 rm -f "$installer" fi local acme acme=$(get_node_acme) || return 1 - "$acme" --install-cronjob || return 1 + mkdir -p "$DATA_DIR/certs/acme" && chmod 700 "$DATA_DIR/certs/acme" || return 1 } validate_ssl_selection() { @@ -2599,9 +2628,10 @@ issue_node_acme_locked() { acme=$(get_node_acme) || return 1 local args=(--issue -d "$identifier" --standalone --server letsencrypt --httpport "$port" --force) [ -z "$ipv6" ] || args+=(-d "$ipv6") - [ "$source" != acme_ip ] || args+=(--certificate-profile shortlived --days 6) - "$acme" "${args[@]}" || { cert_error "ACME issuance failed; existing certificates were preserved. Retry explicitly."; return 1; } + [ "$source" != acme_ip ] || args+=(--certificate-profile shortlived --days 4) + run_node_acme "$acme" "${args[@]}" || { cert_error "ACME issuance failed; existing certificates were preserved. Retry explicitly."; return 1; } stage_node_acme "$acme" "$identifier" || return 1 + validate_node_acme_chain "$DATA_DIR/certs/.acme-staging/fullchain.pem" || return 1 deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" } @@ -2624,7 +2654,7 @@ stage_node_acme_locked() { # The hook copies ACME's exported source paths while holding our lock. local args=(--installcert -d "$identifier" --key-file "$key_target" --fullchain-file "$cert_target" --reloadcmd "$reload") [ -z "$ecc" ] || args+=("$ecc") - if "$acme" "${args[@]}" && + if run_node_acme "$acme" "${args[@]}" && { [ "$reload" != : ] || { [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; }; }; then if [ "$reload" = : ]; then chmod 600 "$stage/privkey.pem" || return 1 @@ -2632,7 +2662,7 @@ stage_node_acme_locked() { # installation is still preparing the permanent reload hook. local reset_args=(--installcert -d "$identifier" --key-file no --fullchain-file no --reloadcmd :) [ -z "$ecc" ] || reset_args+=("$ecc") - "$acme" "${reset_args[@]}" || return 1 + run_node_acme "$acme" "${reset_args[@]}" || return 1 fi printf '%s' "$ecc" >"$stage/key-type" return 0 @@ -2650,9 +2680,11 @@ register_node_acme_reload_locked() { case "$(cert_metadata source)" in acme_ip|acme_domain) ;; *) return 0;; esac local acme hook acme=$(get_node_acme) || return 1 + migrate_node_acme_storage "$acme" "$(cert_metadata identifier)" || return 1 # printf %q protects paths with spaces and custom instance names in shell hooks. printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" - stage_node_acme "$acme" "$(cert_metadata identifier)" "$hook" + stage_node_acme "$acme" "$(cert_metadata identifier)" "$hook" || return 1 + install_node_cert_scheduler } show_node_certificate() { @@ -2680,12 +2712,261 @@ show_node_certificate() { cat "$SSL_CERT_FILE" } -restart_node_cert_services() { +# ACME certificate storage is private to this deployment, outside the shared +# client's cron scan. Account/CA configuration remains managed by acme.sh. +run_node_acme() { + local acme="$1"; shift + "$acme" --cert-home "$DATA_DIR/certs/acme" "$@" +} + +# Move only this certificate out of the shared scheduler. The original client +# command disables its old renewal entry after a complete copy has succeeded. +migrate_node_acme_storage() { + local acme="$1" identifier="$2" base old suffix + base=$(dirname "$(readlink -f "$acme")") + mkdir -p "$DATA_DIR/certs/acme" || return 1 + for suffix in _ecc ''; do + old="$base/$identifier$suffix" + if [ -f "$old/$identifier.conf" ]; then + if [ ! -d "$DATA_DIR/certs/acme/$identifier$suffix" ]; then + cp -a "$old" "$DATA_DIR/certs/acme/" || return 1 + fi + local args=(--remove -d "$identifier") + [ -z "$suffix" ] || args+=(--ecc) + "$acme" "${args[@]}" || return 1 + fi + done +} + +node_cert_fingerprint() ( + set -o pipefail + openssl x509 -in "$1" -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print tolower($NF)}' +) + +node_cert_status_value() { + [ -f "$DATA_DIR/certs/renewal-status.json" ] || return 0 + jq -r --arg key "$1" '.[$key] // empty' "$DATA_DIR/certs/renewal-status.json" +} + +# Status describes verified listeners separately from the files on disk. A +# failed partial reload must never claim the replacement is active everywhere. +write_node_cert_status() ( + local state="$1" error="${2:-}" next="${3:-0}" failures="${4:-}" stage old='{}' + local file="$DATA_DIR/certs/renewal-status.json" pin='' expiry='' source=legacy now + now=$(date +%s) + [ ! -f "$file" ] || old=$(cat "$file") + failures="${failures:-$(printf '%s' "$old" | jq -r '.failures // 0')}" + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + pin=$(node_cert_fingerprint "$SSL_CERT_FILE") || pin='' + expiry=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout 2>/dev/null) || expiry='' + expiry="${expiry#*=}" + stage=$(mktemp "$DATA_DIR/certs/.status.XXXXXX") || return 1 + trap 'rm -f "$stage"' EXIT + jq -n --argjson old "$old" --arg source "$source" --arg state "$state" \ + --arg error "$error" --arg pin "$pin" --arg expiry "$expiry" \ + --argjson now "$now" --argjson next "$next" --argjson failures "$failures" \ + '$old + {source:$source, deployment_state:$state, error:$error, + file_fingerprint:$pin, file_expiry:$expiry, next_attempt:$next, failures:$failures} + | if $state == "attempting" then .last_attempt=$now else . end + | if $state == "deployed" then .active_fingerprint=$pin | .expiry=$expiry | + .last_success=$now | .failures=0 | .error="" else . end' >"$stage" || return 1 + chmod 600 "$stage" && mv -f "$stage" "$file" +) + +certificate_status_command() { + [ "$#" -eq 0 ] || { [ "$#" -eq 1 ] && [ "$1" = --json ]; } || { cert_error 'Usage: certificate-status [--json]'; return 1; } + load_active_cert_paths + local source=legacy status='{}' expiry='' valid=false + [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + [ ! -f "$DATA_DIR/certs/renewal-status.json" ] || status=$(cat "$DATA_DIR/certs/renewal-status.json") + expiry=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout 2>/dev/null) || expiry='' + # Date validity is live; a persisted success does not make expired files valid. + if validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" >/dev/null 2>&1; then valid=true; fi + status=$(jq -n --argjson old "$status" --arg source "$source" --arg expiry "${expiry#*=}" \ + --argjson valid "$valid" '$old + {source:$source, files_currently_valid:$valid, file_expiry:$expiry} + | .deployment_state //= "unknown" | .active_fingerprint //= null | .expiry //= null + | .last_attempt //= null | .last_success //= null | .next_attempt //= null | .error //= ""') || return 1 + if [ "${1:-}" = --json ]; then printf '%s\n' "$status" + else printf '%s\n' "$status" | jq -r 'to_entries[] | "\(.key): \(.value)"'; fi +} + +reload_node_cert_services() { detect_compose - $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" restart || return 1 + local failed=0 + $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" kill --signal SIGHUP node || failed=1 if service_installed; then - systemctl restart "$SERVICE_NAME" || return 1 + systemctl kill --kill-whom=main --signal=SIGHUP "$SERVICE_NAME" || failed=1 + fi + return "$failed" +} + +# Each invocation opens a new TLS socket, with no session cache or resumption. +verify_node_cert_endpoint() ( + set -o pipefail + local host="$1" port="$2" expected="$3" identity="$4" peer connect + [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ] || return 1 + connect="$host:$port" + [[ "$host" != *:* ]] || connect="[$host]:$port" + peer=$(timeout 10 openssl s_client -connect "$connect" -servername "$identity" -showcerts /dev/null | + openssl x509 -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print tolower($NF)}') || return 1 + [ "$peer" = "$expected" ] +) + +verify_node_cert_services() { + local pin identity host port attempt + pin=$(node_cert_fingerprint "$SSL_CERT_FILE") || return 1 + identity=$(cert_metadata identifier 2>/dev/null) || identity='' + host=$(node_env_value NODE_HOST); host="${host:-127.0.0.1}" + case "$host" in 0.0.0.0) host=127.0.0.1;; ::|'[::]') host=::1;; esac + local ports=("$(node_env_value SERVICE_PORT)") + if service_installed; then ports+=("$(node_env_value API_PORT)"); fi + for port in "${ports[@]}"; do + for attempt in 1 2 3 4 5; do + if verify_node_cert_endpoint "$host" "$port" "$pin" "${identity:-$host}"; then break; fi + [ "$attempt" -lt 5 ] || return 1 + sleep 1 + done + done +} + +finish_node_cert_deployment() { + if ! validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE"; then + write_node_cert_status invalid_files 'Current certificate files are invalid or expired; no reload attempted' "$(( $(date +%s) + 300 ))" + return 1 + fi + if reload_node_cert_services && verify_node_cert_services; then + write_node_cert_status deployed '' "$(( $(date +%s) + 3600 ))" || return 1 + colorized_echo green 'Certificate hot reload verified on all configured TLS endpoints.' + else + write_node_cert_status reload_pending 'Reload or endpoint verification failed; no restart attempted' "$(( $(date +%s) + 300 ))" || return 1 + cert_error 'Certificate reload incomplete. Retained files and backups; retrying reload without issuance.' + return 1 + fi +} + +# One cron entry per deployment. The installed command preserves DATA_DIR and +# APP_DIR; % must be escaped even within shell quotes in a crontab. +install_node_cert_scheduler() { + local entry entries stage + printf -v entry '*/5 * * * * env %q %q %q certificate-renewal-tick >>%q 2>&1 # pg-node-cert:%s' \ + "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" "$DATA_DIR/certs/renewal.log" "$APP_NAME" + entry="${entry//%/\\%}" + touch "$DATA_DIR/certs/renewal.log" && chmod 600 "$DATA_DIR/certs/renewal.log" || return 1 + entries=$(crontab -l 2>/dev/null) || entries='' + stage=$(mktemp) || return 1 + printf '%s\n' "$entries" | sed "/# pg-node-cert:${APP_NAME}$/d" >"$stage" + printf '%s\n' "$entry" >>"$stage" + crontab "$stage" + local result=$? + rm -f "$stage" + return "$result" +} + +remove_node_cert_scheduler() { + local entries stage + entries=$(crontab -l 2>/dev/null) || return 0 + stage=$(mktemp) || return 1 + printf '%s\n' "$entries" | sed "/# pg-node-cert:${APP_NAME}$/d" >"$stage" + crontab "$stage" + local result=$? + rm -f "$stage" + return "$result" +} + +node_cert_config_digest() { + { cat "$DATA_DIR/certs/source.json" "$ENV_FILE"; } | sha256sum | awk '{print $1}' +} + +certificate_renewal_tick() { + check_running_as_root + with_node_cert_lock certificate_renewal_tick_locked +} + +certificate_renewal_tick_locked() { + local source state next now digest + [ -f "$DATA_DIR/certs/source.json" ] || return 0 + source=$(cert_metadata source) + case "$source" in acme_ip|acme_domain) ;; *) return 0;; esac + load_active_cert_paths + now=$(date +%s); next=$(node_cert_status_value next_attempt) + state=$(node_cert_status_value deployment_state) + digest=$(node_cert_config_digest) || return 1 + if [ "$state" = suspended ]; then + [ "$(cat "$DATA_DIR/certs/.suspended-config" 2>/dev/null)" != "$digest" ] || return 0 + elif [ "${next:-0}" -gt "$now" ]; then return 0; fi + case "$state" in + reload_pending) finish_node_cert_deployment;; + deployment_pending) renew_cert_command_locked --deploy-acme;; + *) renew_node_acme_scheduled;; + esac +} + +# acme.sh evaluates ARI during --renew. Supply an exact lifetime-based fallback +# without --days, which would pin its schedule and reject later CA windows. +# Only the isolated, locked domain configuration is edited, never sourced here. +set_node_acme_fallback() ( + local identifier="$1" due="$2" suffix='' config stage + [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" != --ecc ] || suffix=_ecc + config="$DATA_DIR/certs/acme/$identifier$suffix/$identifier.conf" + [ -f "$config" ] || return 0 + stage=$(mktemp "${config}.stage.XXXXXX") || return 1 + trap 'rm -f "$stage"' EXIT + sed '/^Le_RenewalDays=/d; /^Le_NextRenewTime=/d' "$config" >"$stage" || return 1 + printf "Le_NextRenewTime='%s'\n" "$due" >>"$stage" + chmod 600 "$stage" && mv -f "$stage" "$config" +) + +renew_node_acme_scheduled() { + local acme identifier rc=0 start end now failures delay retry_after + acme=$(get_node_acme) || { node_cert_config_digest >"$DATA_DIR/certs/.suspended-config"; write_node_cert_status suspended 'ACME client is missing'; return 1; } + identifier=$(cert_metadata identifier) + if [ -z "$identifier" ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME identifier is missing'; return 1 fi + now=$(date +%s) + start=$(openssl x509 -in "$SSL_CERT_FILE" -startdate -noout); start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 + set_node_acme_fallback "$identifier" "$((start+(end-start)*2/3))" || return 1 + write_node_cert_status attempting || return 1 + local args=(--renew -d "$identifier") + [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" != --ecc ] || args+=(--ecc) + # acme.sh honors ARI and CA polling delays. Keep private diagnostic output + # local; only fixed, sanitized messages go into machine-readable status. + (umask 077; run_node_acme "$acme" "${args[@]}" >"$DATA_DIR/certs/acme-last-attempt.log" 2>&1) || rc=$? + # A hook may already have recorded a partial reload. Never issue again. + case "$(node_cert_status_value deployment_state)" in reload_pending|deployment_pending) return 1;; esac + if [ "$rc" -eq 0 ] || [ "$rc" -eq 2 ]; then + if [ "$(node_cert_status_value deployment_state)" = deployed ]; then return 0; fi + if [ "$rc" -eq 0 ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME completed without running the deployment hook; run certificate-renewal-enable' + return 1 + fi + write_node_cert_status waiting '' "$((now+3600))" + return 0 + fi + if grep -Eqi 'unauthorized|rejectedIdentifier|invalidContact|accountDoesNotExist|Invalid domain|Challenge port .* in use' "$DATA_DIR/certs/acme-last-attempt.log"; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME configuration rejected; correct configuration or run renew-cert' + return 1 + fi + failures=$(node_cert_status_value failures); failures=$((${failures:-0}+1)) + delay=300 + local i + for ((i=1; i/dev/null) || retry_after=0 + [ "$retry_after" -le "$((now+delay))" ] || delay=$((retry_after-now)) + fi + write_node_cert_status retry_pending 'Transient ACME failure; see acme-last-attempt.log' "$((now+delay))" "$failures" + return 1 } renew_cert_command() { @@ -2696,8 +2977,15 @@ renew_cert_command_locked() { check_running_as_root ensure_env_exists load_active_cert_paths + case "${1:-}" in + ''|--deploy-acme) [ "$#" -le 1 ] || return 1;; + *) cert_error 'Usage: renew-cert [--deploy-acme]'; return 1;; + esac local source=legacy [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) + if [ "${1:-}" = --deploy-acme ]; then + case "$source" in acme_ip|acme_domain) ;; *) cert_error 'ACME hook requires a managed ACME source'; return 1;; esac + fi if [ "$source" = legacy ]; then local subject issuer subject=$(openssl x509 -in "$SSL_CERT_FILE" -noout -subject 2>/dev/null | sed 's/^subject= *//') @@ -2710,13 +2998,24 @@ renew_cert_command_locked() { acme=$(get_node_acme) || return 1 identifier=$(cert_metadata identifier); ipv6=$(cert_metadata ipv6) if [ "${1:-}" != --deploy-acme ]; then - # The registered reload hook validates, deploys and restarts both listeners. - local args=(--renew -d "$identifier" --force) - if [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" = --ecc ]; then args+=(--ecc); fi - "$acme" "${args[@]}" || return 1 + # An explicit retry first completes any pending deployment. + if [ "$(node_cert_status_value deployment_state)" = deployment_pending ]; then + renew_cert_command_locked --deploy-acme + return $? + fi + if [ "$(node_cert_status_value deployment_state)" = reload_pending ]; then + finish_node_cert_deployment + return $? + fi + write_node_cert_status attempting || return 1 + # The registered hook deploys and verifies both listeners. + # Explicit retry clears suspension but still honors CA due times. + register_node_acme_reload || return 1 + renew_node_acme_scheduled || return 1 show_node_certificate || return 1 return 0 fi + write_node_cert_status deployment_pending 'Certificate staging or validation pending; previous active observation retained' "$(( $(date +%s) + 300 ))" || return 1 if [ -n "${CERT_FULLCHAIN_PATH:-}${CERT_KEY_PATH:-}" ]; then [ -n "${CERT_FULLCHAIN_PATH:-}" ] && [ -n "${CERT_KEY_PATH:-}" ] || return 1 local stage="$DATA_DIR/certs/.acme-staging" @@ -2725,9 +3024,11 @@ renew_cert_command_locked() { cp "$CERT_KEY_PATH" "$stage/privkey.pem" && chmod 600 "$stage/privkey.pem" || return 1 fi + validate_node_acme_chain "$DATA_DIR/certs/.acme-staging/fullchain.pem" || return 1 deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 ;; self_signed) + write_node_cert_status attempting || return 1 # Reuse the active certificate's names, including on unattended renewals. local INSTALL_SAN_ENTRIES INSTALL_SAN_ENTRIES=$(set -o pipefail; openssl x509 -in "$SSL_CERT_FILE" -noout -ext subjectAltName | @@ -2735,17 +3036,20 @@ renew_cert_command_locked() { paste -sd, -) || { cert_error "Could not read existing certificate SANs"; return 1; } [ -n "$INSTALL_SAN_ENTRIES" ] || { cert_error "Existing certificate requires DNS or IP SANs for renewal"; return 1; } INSTALL_SELF_SIGNED=true - choose_node_certificate || return 1 ;; + choose_node_certificate || return 1 + colorized_echo yellow "Update the panel pin to $(node_cert_fingerprint "$SSL_CERT_FILE"). Established connections continue; new pinned connections fail until the saved pin matches." + ;; custom|legacy) + write_node_cert_status attempting || return 1 validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" || return 1 colorized_echo yellow "Custom/legacy certificates are externally renewed. Validated current files; no certificate was regenerated." ;; external_tls) colorized_echo yellow "Manage and renew the certificate on the TLS web server."; return 0 ;; *) cert_error "Unknown certificate source: $source"; return 1 ;; esac - restart_node_cert_services || { cert_error "Certificate deployed but listener restart failed"; return 1; } + finish_node_cert_deployment || return 1 if [ "${1:-}" = --deploy-acme ]; then - colorized_echo green "ACME certificate deployed; node listeners restarted." + colorized_echo green "ACME certificate deployed; TLS hot reload verified." else show_node_certificate fi @@ -2797,6 +3101,17 @@ pg_node_main() { show-cert) show_node_certificate ;; + certificate-status) + shift + certificate_status_command "$@" + ;; + certificate-renewal-enable) + check_running_as_root + register_node_acme_reload + ;; + certificate-renewal-tick) + certificate_renewal_tick + ;; renew-cert) shift renew_cert_command "$@" diff --git a/tests/integration_pgnode_service_tls.sh b/tests/integration_pgnode_service_tls.sh index 1be5949..7673ec3 100644 --- a/tests/integration_pgnode_service_tls.sh +++ b/tests/integration_pgnode_service_tls.sh @@ -3,7 +3,7 @@ set -euo pipefail ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" python3 - "$ROOT_DIR/pg-node-service.sh" <<'PY' -import http.client, os, pathlib, shutil, signal, socket, ssl, subprocess, sys, tempfile, time +import hashlib, http.client, os, pathlib, re, shutil, signal, socket, ssl, subprocess, sys, tempfile, time with tempfile.TemporaryDirectory() as tmp: root = pathlib.Path(tmp) script = root / 'service.sh' @@ -50,6 +50,16 @@ with tempfile.TemporaryDirectory() as tmp: time.sleep(.03) assert request('wrong') == 401 assert request('test-key') == 200 + if enabled == 'true': + # Exercise the manager's real fresh-handshake verifier, with + # both the matching leaf pin and an unexpected replacement. + manager = pathlib.Path(sys.argv[1]).with_name('pg-node.sh').read_text() + verifier = re.search(r'^verify_node_cert_endpoint\(\) \(.*?^\)', manager, re.M | re.S).group() + pin = hashlib.sha256(ssl.PEM_cert_to_DER_cert((root/'leaf.pem').read_text())).hexdigest() + for expected, code in ((pin, 0), ('0'*64, 1)): + result = subprocess.run(['bash', '-c', verifier + '\nverify_node_cert_endpoint "$@"', '_', + '127.0.0.1', str(port), expected, 'localhost'], capture_output=True, timeout=15) + assert result.returncode == code, result.stderr.decode() finally: if process.poll() is None: os.killpg(process.pid, signal.SIGTERM) diff --git a/tests/run_all.sh b/tests/run_all.sh index bb3d170..6935e95 100755 --- a/tests/run_all.sh +++ b/tests/run_all.sh @@ -15,6 +15,7 @@ SUITES=( "unit_pgnode.sh" "unit_pgnode_script_install.sh" "unit_pgnode_tls.sh" + "unit_pgnode_renewal.sh" "integration_pgnode_service_tls.sh" "unit_pgnode_service.sh" "unit_restore_archive_safety.sh" diff --git a/tests/unit_pgnode_renewal.sh b/tests/unit_pgnode_renewal.sh new file mode 100644 index 0000000..b6f5c07 --- /dev/null +++ b/tests/unit_pgnode_renewal.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +export APP_TMP_DIR="$WORK_DIR/tmp" APP_DIR="$WORK_DIR/app" DATA_DIR="$WORK_DIR/data" PG_NODE_SOURCE_ONLY=true +mkdir -p "$APP_TMP_DIR" "$APP_DIR" "$DATA_DIR/certs" +curl() { :; } +source "$ROOT_DIR/pg-node.sh" +check_running_as_root() { :; } +colorized_echo() { printf '%s\n' "$*"; } +expect_fail() { if "$@"; then echo "FAIL: accepted $*" >&2; exit 1; fi; } +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 6 -subj '/CN=test' \ + -addext 'subjectAltName=IP:192.0.2.1' -keyout "$SSL_KEY_FILE" -out "$SSL_CERT_FILE" >/dev/null 2>&1 +printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\nSERVICE_PORT=62050\nAPI_PORT=62051\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" +# A controllable clock leaves certificate parsing on the real date command. +clock_now=$(command date +%s) +date() { if [ "$*" = +%s ]; then echo "$clock_now"; else command date "$@"; fi; } +acme_calls="$WORK_DIR/acme-calls" +get_node_acme() { echo mock_acme; } +mock_acme() { + [[ " $* " == *" --cert-home $DATA_DIR/certs/acme "* ]] + # Scheduler and synchronous hook retain the certificate lock. + ! flock -n "$DATA_DIR/certs/.deployment.lock" true + echo call >>"$acme_calls" + case "$acme_result" in + skip) return 2;; + transient) echo 'network failed secret-token'; return 1;; + ca_delay) echo 'Retry-After: 7200'; return 1;; + config) echo 'rejectedIdentifier secret-token'; return 1;; + success) finish_node_cert_deployment;; + esac +} +reload_calls="$WORK_DIR/reloads" +reload_node_cert_services() { echo signal >>"$reload_calls"; return 0; } +verify_node_cert_services() { [ "$verify_ok" = true ]; } +verify_ok=true +# Scheduler ignores every operator-managed source, even expired self-signed files. +for source in self_signed custom external_tls; do + save_cert_source "$source" + certificate_renewal_tick + [ ! -e "$acme_calls" ] +done +save_cert_source acme_ip 192.0.2.1 '' 80 +# Exact fallback stays unpinned so acme.sh can honor CA renewal windows. +mkdir -p "$DATA_DIR/certs/acme/192.0.2.1" +printf "Le_RenewalDays='6'\nLe_NextRenewTime='1'\nLe_Domain='192.0.2.1'\n" >"$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +acme_result=skip +certificate_renewal_tick +[ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+3600))" ] +! grep -q '^Le_RenewalDays=' "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +grep -q "Le_NextRenewTime='$((clock_now+4*86400))'" "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq 1 ] +clock_now=$((clock_now+3600)); acme_result=transient +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value failures)" -eq 1 ] +next=$(node_cert_status_value next_attempt) +[ "$next" -ge "$((clock_now+300))" ] && [ "$next" -le "$((clock_now+360))" ] +! grep -q secret-token "$DATA_DIR/certs/renewal-status.json" +clock_now="$next" +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value failures)" -eq 2 ] +next=$(node_cert_status_value next_attempt) +[ "$next" -ge "$((clock_now+600))" ] && [ "$next" -le "$((clock_now+720))" ] +clock_now="$next"; acme_result=ca_delay +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+7200))" ] +clock_now=$((clock_now+7200)); acme_result=config +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = suspended ] +previous_calls=$(wc -l <"$acme_calls") +clock_now=$((clock_now+10000)) +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +# Configuration changes resume checks; retries may not expose ACME output in status. +printf '\n# corrected challenge routing\n' >>"$ENV_FILE" +acme_result=skip +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq "$((previous_calls+1))" ] +# Success requires both fresh endpoint checks. A partial reload preserves the last +# verified observation and retries only signalling, without any ACME invocation. +clock_now=$(command date +%s) +write_node_cert_status deployed +active_pin=$(node_cert_status_value active_fingerprint) +verify_ok=false +expect_fail finish_node_cert_deployment +[ "$(node_cert_status_value active_fingerprint)" = "$active_pin" ] +[ "$(node_cert_status_value deployment_state)" = reload_pending ] +previous_calls=$(wc -l <"$acme_calls") +clock_now=$((clock_now+300)); verify_ok=true +certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +[ "$(stat -c %a "$DATA_DIR/certs/renewal-status.json")" = 600 ] +[ -z "$(find "$DATA_DIR/certs" -name '.status.*' -print)" ] +certificate_status_command --json | jq -e '.files_currently_valid and .last_success != null' >/dev/null +clock_now=$((clock_now+7*86400)) +certificate_status_command --json | jq -e '.files_currently_valid == false' >/dev/null +expect_fail certificate_status_command --bogus +# Invalid trailing PEM blocks cannot be mistaken for a valid full chain. +clock_now=$(command date +%s) +cp "$SSL_CERT_FILE" "$WORK_DIR/broken-chain" +printf '\n-----BEGIN CERTIFICATE-----\ninvalid\n' >>"$WORK_DIR/broken-chain" +expect_fail validate_node_cert_pair "$WORK_DIR/broken-chain" "$SSL_KEY_FILE" +# Idempotent scheduler registration preserves unrelated jobs and removes only ours. +cronfile="$WORK_DIR/crontab" +printf '0 0 * * * echo unrelated\n' >"$cronfile" +crontab() { if [ "$1" = -l ]; then cat "$cronfile"; else cp "$1" "$cronfile"; fi; } +install_node_cert_scheduler +install_node_cert_scheduler +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 1 ] +grep -q '^\*/5 ' "$cronfile" +remove_node_cert_scheduler +[ "$(cat "$cronfile")" = '0 0 * * * echo unrelated' ] +echo 'Certificate renewal scheduler tests passed' diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index 79415ed..fa815a7 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -127,30 +127,33 @@ mock_acme() { [ -z "$cert" ] || cp "$WORK_DIR/cert" "$cert" } ensure_node_acme() { :; } +validate_node_acme_chain() { :; } get_node_acme() { echo mock_acme; } issue_node_acme acme_ip 192.0.2.1 2001:db8::1 8080 -grep -q -- '--certificate-profile shortlived --days 6' "$acme_calls" +grep -q -- '--certificate-profile shortlived --days 4' "$acme_calls" grep -q -- '--httpport 8080' "$acme_calls" grep -q -- '--ecc' "$acme_calls" mock_acme() { return 1; } expect_fail issue_node_acme acme_ip 192.0.2.1 '' 80 cmp "$WORK_DIR/key" "$SSL_KEY_FILE" -# Renewal never changes source implicitly; hook must restart both node and maintenance. +# Renewal never changes source implicitly; hook must reload both node and maintenance. printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\n' "$SSL_CERT_FILE" "$SSL_KEY_FILE" >"$ENV_FILE" save_cert_source external_tls renew_cert_command save_cert_source custom -restart_called=false +verify_node_cert_services() { return 0; } +install_node_cert_scheduler() { :; } +reload_called=false detect_compose() { :; } -restart_node_cert_services() { +reload_node_cert_services() { if flock -n "$DATA_DIR/certs/.deployment.lock" true; then - echo 'FAIL: deployment lock released before restart' >&2 + echo 'FAIL: deployment lock released before reload' >&2 return 1 fi - restart_called=true + reload_called=true } renew_cert_command -[ "$restart_called" = true ] +[ "$reload_called" = true ] cmp "$WORK_DIR/key" "$SSL_KEY_FILE" # Renewal preserves installed DNS, wildcard, IPv4 and IPv6 SANs without prompting. ( @@ -175,9 +178,12 @@ cmp "$WORK_DIR/key" "$SSL_KEY_FILE" save_cert_source self_signed AUTO_CONFIRM=false fi - restart_called=false + reload_called=false renew_cert_command "$ENV_FILE" - restart_called=false + reload_called=false expect_fail renew_cert_command >"$acme_calls"; } +mock_acme() { + printf '%s\n' "$*" >>"$acme_calls" + if [[ " $* " == *' --renew '* ]]; then + CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme + fi +} register_node_acme_reload grep -q -- '--key-file no --fullchain-file no' "$acme_calls" -restart_called=false +reload_called=false CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme >"$WORK_DIR/deploy-output" -[ "$restart_called" = true ] +[ "$reload_called" = true ] # The internal hook does not duplicate the installer's certificate output. ! grep -q -- 'BEGIN CERTIFICATE' "$WORK_DIR/deploy-output" # Explicit renewal still prints the resulting certificate once. renew_cert_command >"$WORK_DIR/renew-output" -[ "$(grep -c -- 'BEGIN CERTIFICATE' "$WORK_DIR/renew-output")" = 1 ] -# Restart both actual deployment targets; propagate individual restart failures. -unset -f restart_node_cert_services +[ "$(grep -c -- '^-----BEGIN CERTIFICATE-----' "$WORK_DIR/renew-output")" = 1 ] || { cat "$WORK_DIR/renew-output"; exit 1; } +# Signal both actual deployment targets; propagate individual failures. +unset -f reload_node_cert_services # Restore just this function from the checkout without executing the installer. -eval "$(sed -n '/^restart_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" +eval "$(sed -n '/^reload_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" COMPOSE=mock_compose compose_called=false maintenance_called=false -mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME restart" ]]; } +mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME kill --signal SIGHUP node" ]]; } service_installed() { SERVICE_NAME="$APP_NAME-service"; return 0; } -systemctl() { maintenance_called=true; [ "$*" = "restart $APP_NAME-service" ]; } -restart_node_cert_services +systemctl() { maintenance_called=true; [ "$*" = "kill --kill-whom=main --signal=SIGHUP $APP_NAME-service" ]; } +reload_node_cert_services [ "$compose_called" = true ] && [ "$maintenance_called" = true ] systemctl() { return 1; } -expect_fail restart_node_cert_services +expect_fail reload_node_cert_services mock_compose() { return 1; } -expect_fail restart_node_cert_services +expect_fail reload_node_cert_services # Upgrade loading honors managed paths unchanged. SSL_CERT_FILE=/wrong; SSL_KEY_FILE=/wrong load_active_cert_paths From 81d9dc9566d0444811312bd311e4a446ced5b479 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Tue, 17 Nov 2026 11:54:31 +0330 Subject: [PATCH 07/10] fix(node): remove panel certificate configuration guidance --- docs/ssl-and-certificates.md | 3 +-- pg-node.sh | 5 ----- tests/unit_pgnode_tls.sh | 3 ++- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/docs/ssl-and-certificates.md b/docs/ssl-and-certificates.md index 051c6aa..ff14bdf 100644 --- a/docs/ssl-and-certificates.md +++ b/docs/ssl-and-certificates.md @@ -132,8 +132,7 @@ sudo pg-node renew-cert ``` ACME sources renew through acme.sh. Self-signed sources regenerate only when you explicitly run `renew-cert`, preserving the 3,650-day lifetime and installed SANs. -The command prints the new fingerprint: update the saved panel pin. Established -connections continue, but new pinned connections fail until the pin matches. +The command prints the new certificate fingerprint. Custom and legacy sources validate the operator-maintained files. External TLS certificates and graceful frontend reloads remain managed on the web server. diff --git a/pg-node.sh b/pg-node.sh index c854fd9..dbbc808 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -2703,10 +2703,6 @@ show_node_certificate() { } [[ "$pin" =~ ^[0-9a-f]{64}$ ]] || { cert_error "Invalid certificate SHA-256 pin"; return 1; } colorized_echo cyan "SHA-256 certificate pin (leaf DER): $pin" - case "$source" in - acme_*) colorized_echo green 'Recommended panel fields: server_ca="", certificate_sha256=null (system trust)' ;; - *) colorized_echo yellow "For self-signed certificates, set certificate_sha256=$pin and server_ca=\"\". Check the panel address matches a SAN." ;; - esac colorized_echo cyan 'PEM for older panels:' colorized_echo yellow 'If multiple PEM certificate blocks appear below, copy only the first block (the node certificate) into the panel certificate field, including its BEGIN CERTIFICATE and END CERTIFICATE lines.' cat "$SSL_CERT_FILE" @@ -3037,7 +3033,6 @@ renew_cert_command_locked() { [ -n "$INSTALL_SAN_ENTRIES" ] || { cert_error "Existing certificate requires DNS or IP SANs for renewal"; return 1; } INSTALL_SELF_SIGNED=true choose_node_certificate || return 1 - colorized_echo yellow "Update the panel pin to $(node_cert_fingerprint "$SSL_CERT_FILE"). Established connections continue; new pinned connections fail until the saved pin matches." ;; custom|legacy) write_node_cert_status attempting || return 1 diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index fa815a7..fce952b 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -101,7 +101,8 @@ save_cert_source self_signed cert_output=$(show_node_certificate) expected_pin=$(openssl x509 -in "$WORK_DIR/cert" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':' | tr '[:upper:]' '[:lower:]') [[ "$cert_output" == *"SHA-256 certificate pin (leaf DER): $expected_pin"* ]] -[[ "$cert_output" == *"certificate_sha256=$expected_pin and server_ca=\"\""* ]] +[[ "$cert_output" != *certificate_sha256* ]] +[[ "$cert_output" != *server_ca* ]] active_cert="$SSL_CERT_FILE" SSL_CERT_FILE="$WORK_DIR/no-certificate" expect_fail show_node_certificate From 2de0d8074d27e933e4a890f41aae0aa2602a9b61 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Tue, 17 Nov 2026 19:49:44 +0330 Subject: [PATCH 08/10] fix(node): harden certificate deployment and renewal recovery --- pg-node.sh | 44 +++++++++++++++++++------ tests/unit_pgnode.sh | 14 ++++++-- tests/unit_pgnode_renewal.sh | 29 ++++++++++++++--- tests/unit_pgnode_tls.sh | 63 +++++++++++++++++++++++++++++++++--- 4 files changed, 130 insertions(+), 20 deletions(-) diff --git a/pg-node.sh b/pg-node.sh index 04a848f..92505ca 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -1325,18 +1325,24 @@ install_command() { fi colorized_echo blue "================================" colorized_echo magenta " node is set up with the following IP: $NODE_IP and Port: $SERVICE_PORT." - register_node_acme_reload || return 1 - if [ "${TLS_ENABLED:-true}" = false ]; then + local registration_failed=0 + if ! register_node_acme_reload; then + registration_failed=1 + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME reload registration or scheduler installation failed; run certificate-renewal-enable' + colorized_echo red 'Managed renewal setup failed. The scheduler was not installed successfully; run certificate-renewal-enable after correcting the error.' + elif [ "${TLS_ENABLED:-true}" = false ]; then write_node_cert_status external_tls elif verify_node_cert_services; then write_node_cert_status deployed else write_node_cert_status unverified 'Initial TLS endpoint verification failed; inspect service logs' fi - show_node_certificate + show_node_certificate || registration_failed=1 colorized_echo blue "================================" colorized_echo magenta "Next, use the API Key (UUID v4) in pasarguard Panel: " colorized_echo red "${API_KEY}" + return "$registration_failed" } # Uninstall node containers, configuration, scripts, and optionally data directories. uninstall_command() { @@ -2756,12 +2762,19 @@ run_node_acme() { # Move only this certificate out of the shared scheduler. The original client # command disables its old renewal entry after a complete copy has succeeded. migrate_node_acme_storage() { - local acme="$1" identifier="$2" base old suffix + local acme="$1" identifier="$2" base old suffix hook encoded_hook + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + encoded_hook=$(printf '%s' "$hook" | openssl base64 -A) || return 1 base=$(dirname "$(readlink -f "$acme")") mkdir -p "$DATA_DIR/certs/acme" || return 1 for suffix in _ecc ''; do old="$base/$identifier$suffix" if [ -f "$old/$identifier.conf" ]; then + # Compare saved data without sourcing or executing the shared config. + # acme.sh stores reload commands as either plain text or base64. + grep -Fqx -e "Le_ReloadCmd='$hook'" \ + -e "Le_ReloadCmd='__ACME_BASE64__START_${encoded_hook}__ACME_BASE64__END_'" \ + "$old/$identifier.conf" || continue if [ ! -d "$DATA_DIR/certs/acme/$identifier$suffix" ]; then cp -a "$old" "$DATA_DIR/certs/acme/" || return 1 fi @@ -2827,8 +2840,8 @@ certificate_status_command() { reload_node_cert_services() { detect_compose local failed=0 - $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" kill --signal SIGHUP node || failed=1 - if service_installed; then + $COMPOSE -f "$COMPOSE_FILE" -p "$APP_NAME" restart node || failed=1 + if service_installed && systemctl is-active --quiet "$SERVICE_NAME"; then systemctl kill --kill-whom=main --signal=SIGHUP "$SERVICE_NAME" || failed=1 fi return "$failed" @@ -2853,7 +2866,7 @@ verify_node_cert_services() { host=$(node_env_value NODE_HOST); host="${host:-127.0.0.1}" case "$host" in 0.0.0.0) host=127.0.0.1;; ::|'[::]') host=::1;; esac local ports=("$(node_env_value SERVICE_PORT)") - if service_installed; then ports+=("$(node_env_value API_PORT)"); fi + if service_installed && systemctl is-active --quiet "$SERVICE_NAME"; then ports+=("$(node_env_value API_PORT)"); fi for port in "${ports[@]}"; do for attempt in 1 2 3 4 5; do if verify_node_cert_endpoint "$host" "$port" "$pin" "${identity:-$host}"; then break; fi @@ -2872,8 +2885,8 @@ finish_node_cert_deployment() { write_node_cert_status deployed '' "$(( $(date +%s) + 3600 ))" || return 1 colorized_echo green 'Certificate hot reload verified on all configured TLS endpoints.' else - write_node_cert_status reload_pending 'Reload or endpoint verification failed; no restart attempted' "$(( $(date +%s) + 300 ))" || return 1 - cert_error 'Certificate reload incomplete. Retained files and backups; retrying reload without issuance.' + write_node_cert_status reload_pending 'Node restart, maintenance reload or endpoint verification failed' "$(( $(date +%s) + 300 ))" || return 1 + cert_error 'Certificate reload incomplete. Retained files and backups; retrying deployment until renewal is due.' return 1 fi } @@ -2929,7 +2942,18 @@ certificate_renewal_tick_locked() { [ "$(cat "$DATA_DIR/certs/.suspended-config" 2>/dev/null)" != "$digest" ] || return 0 elif [ "${next:-0}" -gt "$now" ]; then return 0; fi case "$state" in - reload_pending) finish_node_cert_deployment;; + reload_pending) + local start end + start=$(openssl x509 -in "$SSL_CERT_FILE" -startdate -noout) || return 1 + start=$(date -d "${start#*=}" +%s) || return 1 + end=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout) || return 1 + end=$(date -d "${end#*=}" +%s) || return 1 + if [ "$now" -ge "$((start+(end-start)*2/3))" ]; then + renew_node_acme_scheduled + else + finish_node_cert_deployment + fi + ;; deployment_pending) renew_cert_command_locked --deploy-acme;; *) renew_node_acme_scheduled;; esac diff --git a/tests/unit_pgnode.sh b/tests/unit_pgnode.sh index 1ee736c..98fc81e 100644 --- a/tests/unit_pgnode.sh +++ b/tests/unit_pgnode.sh @@ -372,8 +372,10 @@ run_install_command() { detect_compose() { :; } curl() { echo "curl $*" >> "$INSTALL_CALLS"; release_api_reply "$@"; } install_node() { echo "install_node $1" >> "$INSTALL_CALLS"; } - register_node_acme_reload() { :; } - show_node_certificate() { :; } + register_node_acme_reload() { return "${INSTALL_REGISTRATION_STATUS:-0}"; } + show_node_certificate() { echo 'certificate information'; } + node_cert_config_digest() { echo test-config; } + write_node_cert_status() { echo "cert_status $*" >>"$INSTALL_CALLS"; } install_node_script() { :; } install_completion() { :; } up_node() { :; } @@ -402,6 +404,14 @@ release_lookup_done() { grep -q "api.github.com/repos/PasarGuard/node/releases" "$INSTALL_CALLS" } +INSTALL_REGISTRATION_STATUS=1 +run_install_command --dev +assert_eq "$INSTALL_STATUS" "1" "install: failed renewal setup returns nonzero" +assert_true "install: failed renewal setup records suspended status" grep -q '^cert_status suspended ' "$INSTALL_CALLS" +assert_true "install: failed renewal setup displays certificate" grep -q 'certificate information' <<<"$INSTALL_OUT" +assert_true "install: failed renewal setup displays API key" grep -q '00000000-0000-4000-8000-000000000000' <<<"$INSTALL_OUT" +assert_true "install: failed renewal setup reports scheduler failure" grep -q 'scheduler was not installed' <<<"$INSTALL_OUT" +unset INSTALL_REGISTRATION_STATUS run_install_command --dev assert_eq "$INSTALL_STATUS" "0" "install --dev: exits 0" assert_eq "$(installed_version)" "dev" "install --dev: installs image tag dev" diff --git a/tests/unit_pgnode_renewal.sh b/tests/unit_pgnode_renewal.sh index b6f5c07..edae2e5 100644 --- a/tests/unit_pgnode_renewal.sh +++ b/tests/unit_pgnode_renewal.sh @@ -17,11 +17,16 @@ printf 'SSL_CERT_FILE=%s\nSSL_KEY_FILE=%s\nSERVICE_PORT=62050\nAPI_PORT=62051\n' clock_now=$(command date +%s) date() { if [ "$*" = +%s ]; then echo "$clock_now"; else command date "$@"; fi; } acme_calls="$WORK_DIR/acme-calls" +acme_validation_failures="$WORK_DIR/acme-validation-failures" get_node_acme() { echo mock_acme; } mock_acme() { - [[ " $* " == *" --cert-home $DATA_DIR/certs/acme "* ]] + if [[ " $* " != *" --cert-home $DATA_DIR/certs/acme "* ]]; then + echo 'wrong cert-home' >>"$acme_validation_failures" + fi # Scheduler and synchronous hook retain the certificate lock. - ! flock -n "$DATA_DIR/certs/.deployment.lock" true + if flock -n "$DATA_DIR/certs/.deployment.lock" true; then + echo 'missing deployment lock' >>"$acme_validation_failures" + fi echo call >>"$acme_calls" case "$acme_result" in skip) return 2;; @@ -48,7 +53,9 @@ printf "Le_RenewalDays='6'\nLe_NextRenewTime='1'\nLe_Domain='192.0.2.1'\n" >"$DA acme_result=skip certificate_renewal_tick [ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+3600))" ] -! grep -q '^Le_RenewalDays=' "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" +if grep -q '^Le_RenewalDays=' "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf"; then + echo 'FAIL: renewal days remain pinned' >&2; exit 1 +fi grep -q "Le_NextRenewTime='$((clock_now+4*86400))'" "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" certificate_renewal_tick [ "$(wc -l <"$acme_calls")" -eq 1 ] @@ -57,7 +64,9 @@ expect_fail certificate_renewal_tick [ "$(node_cert_status_value failures)" -eq 1 ] next=$(node_cert_status_value next_attempt) [ "$next" -ge "$((clock_now+300))" ] && [ "$next" -le "$((clock_now+360))" ] -! grep -q secret-token "$DATA_DIR/certs/renewal-status.json" +if grep -q secret-token "$DATA_DIR/certs/renewal-status.json"; then + echo 'FAIL: status exposes secret-token' >&2; exit 1 +fi clock_now="$next" expect_fail certificate_renewal_tick [ "$(node_cert_status_value failures)" -eq 2 ] @@ -93,6 +102,15 @@ certificate_renewal_tick [ "$(node_cert_status_value deployment_state)" = deployed ] [ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] [ "$(stat -c %a "$DATA_DIR/certs/renewal-status.json")" = 600 ] +# A persistent listener failure must not prevent renewal once disk files are due. +verify_ok=false +expect_fail finish_node_cert_deployment +clock_now=$((clock_now+5*86400)); acme_result=skip +certificate_renewal_tick +[ "$(wc -l <"$acme_calls")" -eq "$((previous_calls+1))" ] +[ "$(node_cert_status_value deployment_state)" = waiting ] +verify_ok=true +write_node_cert_status deployed [ -z "$(find "$DATA_DIR/certs" -name '.status.*' -print)" ] certificate_status_command --json | jq -e '.files_currently_valid and .last_success != null' >/dev/null clock_now=$((clock_now+7*86400)) @@ -113,4 +131,7 @@ install_node_cert_scheduler grep -q '^\*/5 ' "$cronfile" remove_node_cert_scheduler [ "$(cat "$cronfile")" = '0 0 * * * echo unrelated' ] +if [ -s "$acme_validation_failures" ]; then + cat "$acme_validation_failures" >&2; exit 1 +fi echo 'Certificate renewal scheduler tests passed' diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index fce952b..dff47bd 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -213,7 +213,9 @@ reload_called=false CERT_FULLCHAIN_PATH="$WORK_DIR/cert" CERT_KEY_PATH="$WORK_DIR/key" renew_cert_command --deploy-acme >"$WORK_DIR/deploy-output" [ "$reload_called" = true ] # The internal hook does not duplicate the installer's certificate output. -! grep -q -- 'BEGIN CERTIFICATE' "$WORK_DIR/deploy-output" +if grep -q -- 'BEGIN CERTIFICATE' "$WORK_DIR/deploy-output"; then + echo 'FAIL: deployment hook printed PEM' >&2; exit 1 +fi # Explicit renewal still prints the resulting certificate once. renew_cert_command >"$WORK_DIR/renew-output" [ "$(grep -c -- '^-----BEGIN CERTIFICATE-----' "$WORK_DIR/renew-output")" = 1 ] || { cat "$WORK_DIR/renew-output"; exit 1; } @@ -224,15 +226,68 @@ eval "$(sed -n '/^reload_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" COMPOSE=mock_compose compose_called=false maintenance_called=false -mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME kill --signal SIGHUP node" ]]; } +mock_compose() { compose_called=true; [[ "$*" == *"-p $APP_NAME restart node" ]]; } service_installed() { SERVICE_NAME="$APP_NAME-service"; return 0; } -systemctl() { maintenance_called=true; [ "$*" = "kill --kill-whom=main --signal=SIGHUP $APP_NAME-service" ]; } +systemctl() { + [ "$*" != "is-active --quiet $APP_NAME-service" ] || return 0 + maintenance_called=true + [ "$*" = "kill --kill-whom=main --signal=SIGHUP $APP_NAME-service" ] +} reload_node_cert_services [ "$compose_called" = true ] && [ "$maintenance_called" = true ] -systemctl() { return 1; } +systemctl() { [ "$1" = is-active ]; } expect_fail reload_node_cert_services +systemctl() { + [ "$1" != is-active ] || return 1 + maintenance_called=true + return 0 +} +maintenance_called=false +reload_node_cert_services +[ "$maintenance_called" = false ] mock_compose() { return 1; } expect_fail reload_node_cert_services +# Only running maintenance services add their API listener to verification. +eval "$(sed -n '/^verify_node_cert_services() {/,/^}/p' "$ROOT_DIR/pg-node.sh")" +printf 'SERVICE_PORT=62050\nAPI_PORT=62051\n' >>"$ENV_FILE" +verified_ports="$WORK_DIR/verified-ports" +verify_node_cert_endpoint() { echo "$2" >>"$verified_ports"; } +verify_node_cert_services +[ "$(cat "$verified_ports")" = 62050 ] +: >"$verified_ports" +systemctl() { [ "$1" = is-active ]; } +verify_node_cert_services +[ "$(cat "$verified_ports")" = "$(printf '62050\n62051')" ] +# Shared ACME entries belong to this node only when their reload hook matches. +( + shared="$WORK_DIR/shared-acme" + mkdir -p "$shared/192.0.2.1" "$shared/192.0.2.1_ecc" + printf '#!/usr/bin/env bash\nprintf "%%s\\n" "$*" >>"$MIGRATION_CALLS"\n' >"$shared/acme.sh" + chmod +x "$shared/acme.sh" + export MIGRATION_CALLS="$WORK_DIR/migration-calls" + printf "Le_ReloadCmd='systemctl reload nginx'\n" >"$shared/192.0.2.1/192.0.2.1.conf" + printf "Le_ReloadCmd='env DATA_DIR=/another-node /usr/local/bin/pg-node renew-cert --deploy-acme'\n" >"$shared/192.0.2.1_ecc/192.0.2.1.conf" + migrate_node_acme_storage "$shared/acme.sh" 192.0.2.1 + [ ! -e "$MIGRATION_CALLS" ] + [ ! -d "$DATA_DIR/certs/acme/192.0.2.1" ] + [ ! -d "$DATA_DIR/certs/acme/192.0.2.1_ecc" ] + printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" + printf "Le_ReloadCmd='%s'\n" "$hook" >"$shared/192.0.2.1/192.0.2.1.conf" + encoded=$(printf '%s' "$hook" | openssl base64 -A) + printf "Le_ReloadCmd='__ACME_BASE64__START_%s__ACME_BASE64__END_'\n" "$encoded" >"$shared/192.0.2.1_ecc/192.0.2.1.conf" + migrate_node_acme_storage "$shared/acme.sh" 192.0.2.1 + cmp "$shared/192.0.2.1/192.0.2.1.conf" "$DATA_DIR/certs/acme/192.0.2.1/192.0.2.1.conf" + cmp "$shared/192.0.2.1_ecc/192.0.2.1.conf" "$DATA_DIR/certs/acme/192.0.2.1_ecc/192.0.2.1.conf" + [ "$(cat "$MIGRATION_CALLS")" = "$(printf '%s\n' '--remove -d 192.0.2.1 --ecc' '--remove -d 192.0.2.1')" ] +) +# Failed hook staging must leave the scheduler uninstalled. +( + stage_node_acme() { return 1; } + migrate_node_acme_storage() { :; } + install_node_cert_scheduler() { touch "$WORK_DIR/unexpected-scheduler"; } + expect_fail register_node_acme_reload + [ ! -e "$WORK_DIR/unexpected-scheduler" ] +) # Upgrade loading honors managed paths unchanged. SSL_CERT_FILE=/wrong; SSL_KEY_FILE=/wrong load_active_cert_paths From f6ab09d04e104ca6196c641402dba62bb989a0fc Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:48:52 +0000 Subject: [PATCH 09/10] fix(node): preserve certificate reload recovery across ACME renewal failures --- pg-node.sh | 28 +++++++++++++++++++++++----- tests/unit_pgnode_renewal.sh | 22 +++++++++++++++++----- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/pg-node.sh b/pg-node.sh index 92505ca..520516f 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -2975,18 +2975,36 @@ set_node_acme_fallback() ( ) renew_node_acme_scheduled() { - local acme identifier rc=0 start end now failures delay retry_after - acme=$(get_node_acme) || { node_cert_config_digest >"$DATA_DIR/certs/.suspended-config"; write_node_cert_status suspended 'ACME client is missing'; return 1; } + local acme identifier rc=0 start end now failures delay retry_after recovery=false + # Retry the installed files first, even when renewal is due. A skipped or + # failed issuance must leave this recovery scheduled independently of ACME. + case "$(node_cert_status_value deployment_state)" in + reload_pending) + if finish_node_cert_deployment; then return 0; fi + recovery=true + ;; + deployment_pending) renew_cert_command_locked --deploy-acme; return $?;; + esac + acme=$(get_node_acme) || { + if [ "$recovery" = false ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME client is missing' + fi + return 1 + } identifier=$(cert_metadata identifier) if [ -z "$identifier" ]; then - node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" - write_node_cert_status suspended 'ACME identifier is missing'; return 1 + if [ "$recovery" = false ]; then + node_cert_config_digest >"$DATA_DIR/certs/.suspended-config" + write_node_cert_status suspended 'ACME identifier is missing' + fi + return 1 fi now=$(date +%s) start=$(openssl x509 -in "$SSL_CERT_FILE" -startdate -noout); start=$(date -d "${start#*=}" +%s) || return 1 end=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout); end=$(date -d "${end#*=}" +%s) || return 1 set_node_acme_fallback "$identifier" "$((start+(end-start)*2/3))" || return 1 - write_node_cert_status attempting || return 1 + if [ "$recovery" = false ]; then write_node_cert_status attempting || return 1; fi local args=(--renew -d "$identifier") [ "$(cat "$DATA_DIR/certs/.acme-staging/key-type" 2>/dev/null)" != --ecc ] || args+=(--ecc) # acme.sh honors ARI and CA polling delays. Keep private diagnostic output diff --git a/tests/unit_pgnode_renewal.sh b/tests/unit_pgnode_renewal.sh index edae2e5..b4c4984 100644 --- a/tests/unit_pgnode_renewal.sh +++ b/tests/unit_pgnode_renewal.sh @@ -105,12 +105,24 @@ certificate_renewal_tick # A persistent listener failure must not prevent renewal once disk files are due. verify_ok=false expect_fail finish_node_cert_deployment -clock_now=$((clock_now+5*86400)); acme_result=skip +clock_now=$((clock_now+5*86400)) +for acme_result in skip transient ca_delay config; do + expect_fail certificate_renewal_tick + previous_calls=$((previous_calls+1)) + [ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] + [ "$(node_cert_status_value deployment_state)" = reload_pending ] + [ "$(node_cert_status_value active_fingerprint)" = "$active_pin" ] + [ "$(node_cert_status_value next_attempt)" -eq "$((clock_now+300))" ] + clock_now=$((clock_now+300)) +done +# Recovery also survives a missing client and resumes without invoking ACME. +get_node_acme() { return 1; } +expect_fail certificate_renewal_tick +[ "$(node_cert_status_value deployment_state)" = reload_pending ] +clock_now=$((clock_now+300)); verify_ok=true certificate_renewal_tick -[ "$(wc -l <"$acme_calls")" -eq "$((previous_calls+1))" ] -[ "$(node_cert_status_value deployment_state)" = waiting ] -verify_ok=true -write_node_cert_status deployed +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] [ -z "$(find "$DATA_DIR/certs" -name '.status.*' -print)" ] certificate_status_command --json | jq -e '.files_currently_valid and .last_success != null' >/dev/null clock_now=$((clock_now+7*86400)) From c84e51317d2703a42c99026f95c95e43a2a39314 Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:11:46 +0000 Subject: [PATCH 10/10] fix(node): recover unstaged ACME deployments, serialize cron updates, and verify plaintext support --- docs/cli-reference.md | 8 +++++- pg-node.sh | 52 +++++++++++++++++++++--------------- tests/unit_pgnode_renewal.sh | 45 +++++++++++++++++++++++++++++++ tests/unit_pgnode_tls.sh | 15 +++++++++++ 4 files changed, 97 insertions(+), 23 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index ab13050..996dae2 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -278,7 +278,13 @@ sudo pg-node geofiles russia ``` #### `renew-cert` -Renews ACME or self-signed certificates according to the saved source. Custom and legacy certificates are validated without replacement; external TLS certificates are managed on the web server. + + + + +Renews ACME or self-signed certificates according to the saved source. Without `source.json`, a legacy certificate whose subject and issuer match is treated as self-signed and regenerated with a new certificate and key. Custom and other legacy certificates are validated without replacement; external TLS certificates are managed on the web server. + + ```bash sudo pg-node renew-cert ``` diff --git a/pg-node.sh b/pg-node.sh index 520516f..1c616a7 100755 --- a/pg-node.sh +++ b/pg-node.sh @@ -2588,6 +2588,16 @@ prepare_install_node_certificate() { fi } +node_image_supports_plaintext() { + local ref="${node_version:-latest}" config + if [ "$ref" = latest ]; then + ref=$(curl -fsSL https://api.github.com/repos/PasarGuard/node/releases/latest | jq -er '.tag_name') || return 1 + fi + [[ "$ref" =~ ^(dev|v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?)$ ]] || return 1 + config=$(curl -fsSL "https://raw.githubusercontent.com/PasarGuard/node/$ref/.env.example") || return 1 + printf '%s\n' "$config" | grep -Eq '^[[:space:]#]*TLS_ENABLED[[:space:]]*=' +} + choose_node_certificate() { validate_ssl_selection || return 1 if [ -z "${INSTALL_SSL_IP:-}${INSTALL_SSL_DOMAIN:-}${INSTALL_CERT_PATH:-}" ] && [ "${INSTALL_SELF_SIGNED:-false}" != true ] && [ "${INSTALL_NO_SSL:-false}" != true ]; then @@ -2616,6 +2626,10 @@ choose_node_certificate() { fi TLS_ENABLED=true if [ "${INSTALL_NO_SSL:-false}" = true ]; then + node_image_supports_plaintext || { + cert_error "Cannot verify plaintext support for node image ${node_version:-latest}; select a compatible image or enable TLS." + return 1 + } TLS_ENABLED=false save_cert_source external_tls elif [ "${INSTALL_SELF_SIGNED:-false}" = true ]; then @@ -2690,20 +2704,15 @@ stage_node_acme_locked() { for ecc in '--ecc' ''; do local key_target=no cert_target=no if [ "$reload" = : ]; then - # Remove only staging files so a failed install cannot look successful. rm -f "$stage/fullchain.pem" "$stage/privkey.pem" key_target="$stage/privkey.pem"; cert_target="$stage/fullchain.pem" fi - # For automatic renewals ACME invokes the hook without writing staging. - # The hook copies ACME's exported source paths while holding our lock. local args=(--installcert -d "$identifier" --key-file "$key_target" --fullchain-file "$cert_target" --reloadcmd "$reload") [ -z "$ecc" ] || args+=("$ecc") if run_node_acme "$acme" "${args[@]}" && { [ "$reload" != : ] || { [ -s "$stage/fullchain.pem" ] && [ -s "$stage/privkey.pem" ]; }; }; then if [ "$reload" = : ]; then chmod 600 "$stage/privkey.pem" || return 1 - # Do not leave staging as an unattended ACME write target while - # installation is still preparing the permanent reload hook. local reset_args=(--installcert -d "$identifier" --key-file no --fullchain-file no --reloadcmd :) [ -z "$ecc" ] || reset_args+=("$ecc") run_node_acme "$acme" "${reset_args[@]}" || return 1 @@ -2725,7 +2734,6 @@ register_node_acme_reload_locked() { local acme hook acme=$(get_node_acme) || return 1 migrate_node_acme_storage "$acme" "$(cert_metadata identifier)" || return 1 - # printf %q protects paths with spaces and custom instance names in shell hooks. printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" stage_node_acme "$acme" "$(cert_metadata identifier)" "$hook" || return 1 install_node_cert_scheduler @@ -2752,15 +2760,11 @@ show_node_certificate() { cat "$SSL_CERT_FILE" } -# ACME certificate storage is private to this deployment, outside the shared -# client's cron scan. Account/CA configuration remains managed by acme.sh. run_node_acme() { local acme="$1"; shift "$acme" --cert-home "$DATA_DIR/certs/acme" "$@" } -# Move only this certificate out of the shared scheduler. The original client -# command disables its old renewal entry after a complete copy has succeeded. migrate_node_acme_storage() { local acme="$1" identifier="$2" base old suffix hook encoded_hook printf -v hook 'env %q %q %q renew-cert --deploy-acme' "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" @@ -2770,8 +2774,6 @@ migrate_node_acme_storage() { for suffix in _ecc ''; do old="$base/$identifier$suffix" if [ -f "$old/$identifier.conf" ]; then - # Compare saved data without sourcing or executing the shared config. - # acme.sh stores reload commands as either plain text or base64. grep -Fqx -e "Le_ReloadCmd='$hook'" \ -e "Le_ReloadCmd='__ACME_BASE64__START_${encoded_hook}__ACME_BASE64__END_'" \ "$old/$identifier.conf" || continue @@ -2795,8 +2797,6 @@ node_cert_status_value() { jq -r --arg key "$1" '.[$key] // empty' "$DATA_DIR/certs/renewal-status.json" } -# Status describes verified listeners separately from the files on disk. A -# failed partial reload must never claim the replacement is active everywhere. write_node_cert_status() ( local state="$1" error="${2:-}" next="${3:-0}" failures="${4:-}" stage old='{}' local file="$DATA_DIR/certs/renewal-status.json" pin='' expiry='' source=legacy now @@ -2827,7 +2827,6 @@ certificate_status_command() { [ ! -f "$DATA_DIR/certs/source.json" ] || source=$(cert_metadata source) [ ! -f "$DATA_DIR/certs/renewal-status.json" ] || status=$(cat "$DATA_DIR/certs/renewal-status.json") expiry=$(openssl x509 -in "$SSL_CERT_FILE" -enddate -noout 2>/dev/null) || expiry='' - # Date validity is live; a persisted success does not make expired files valid. if validate_node_cert_pair "$SSL_CERT_FILE" "$SSL_KEY_FILE" >/dev/null 2>&1; then valid=true; fi status=$(jq -n --argjson old "$status" --arg source "$source" --arg expiry "${expiry#*=}" \ --argjson valid "$valid" '$old + {source:$source, files_currently_valid:$valid, file_expiry:$expiry} @@ -2847,7 +2846,6 @@ reload_node_cert_services() { return "$failed" } -# Each invocation opens a new TLS socket, with no session cache or resumption. verify_node_cert_endpoint() ( set -o pipefail local host="$1" port="$2" expected="$3" identity="$4" peer connect @@ -2891,9 +2889,10 @@ finish_node_cert_deployment() { fi } -# One cron entry per deployment. The installed command preserves DATA_DIR and -# APP_DIR; % must be escaped even within shell quotes in a crontab. -install_node_cert_scheduler() { +install_node_cert_scheduler() ( + local cron_lock_fd + exec {cron_lock_fd}>/var/lock/pg-node-cert-crontab.lock || return 1 + flock -x "$cron_lock_fd" || return 1 local entry entries stage printf -v entry '*/5 * * * * env %q %q %q certificate-renewal-tick >>%q 2>&1 # pg-node-cert:%s' \ "DATA_DIR=$DATA_DIR" "APP_DIR=$APP_DIR" "/usr/local/bin/$APP_NAME" "$DATA_DIR/certs/renewal.log" "$APP_NAME" @@ -2907,9 +2906,12 @@ install_node_cert_scheduler() { local result=$? rm -f "$stage" return "$result" -} +) -remove_node_cert_scheduler() { +remove_node_cert_scheduler() ( + local cron_lock_fd + exec {cron_lock_fd}>/var/lock/pg-node-cert-crontab.lock || return 1 + flock -x "$cron_lock_fd" || return 1 local entries stage entries=$(crontab -l 2>/dev/null) || return 0 stage=$(mktemp) || return 1 @@ -2918,7 +2920,7 @@ remove_node_cert_scheduler() { local result=$? rm -f "$stage" return "$result" -} +) node_cert_config_digest() { { cat "$DATA_DIR/certs/source.json" "$ENV_FILE"; } | sha256sum | awk '{print $1}' @@ -3099,6 +3101,12 @@ renew_cert_command_locked() { cp "$CERT_FULLCHAIN_PATH" "$stage/fullchain.pem" && cp "$CERT_KEY_PATH" "$stage/privkey.pem" && chmod 600 "$stage/privkey.pem" || return 1 + elif [ ! -s "$DATA_DIR/certs/.acme-staging/fullchain.pem" ] || + [ ! -s "$DATA_DIR/certs/.acme-staging/privkey.pem" ]; then + # Install the already renewed pair from durable ACME storage. + # Restore the permanent hook after staging resets its targets. + stage_node_acme "$acme" "$identifier" || return 1 + register_node_acme_reload || return 1 fi validate_node_acme_chain "$DATA_DIR/certs/.acme-staging/fullchain.pem" || return 1 deploy_node_cert_pair "$DATA_DIR/certs/.acme-staging/fullchain.pem" "$DATA_DIR/certs/.acme-staging/privkey.pem" "$identifier" "$ipv6" || return 1 diff --git a/tests/unit_pgnode_renewal.sh b/tests/unit_pgnode_renewal.sh index b4c4984..e52084e 100644 --- a/tests/unit_pgnode_renewal.sh +++ b/tests/unit_pgnode_renewal.sh @@ -143,6 +143,51 @@ install_node_cert_scheduler grep -q '^\*/5 ' "$cronfile" remove_node_cert_scheduler [ "$(cat "$cronfile")" = '0 0 * * * echo unrelated' ] +# Concurrent instances must preserve each other's entries and unrelated jobs. +crontab() { + if [ "$1" = -l ]; then cat "$cronfile"; sleep 0.1 + else cp "$1" "$cronfile"; fi +} +(APP_NAME=pg-node-one; install_node_cert_scheduler) & +first=$! +(APP_NAME=pg-node-two; install_node_cert_scheduler) & +second=$! +wait "$first"; wait "$second" +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 2 ] +(APP_NAME=pg-node-one; remove_node_cert_scheduler) & +first=$! +(APP_NAME=pg-node-three; install_node_cert_scheduler) & +second=$! +wait "$first"; wait "$second" +[ "$(grep -c 'pg-node-cert:' "$cronfile")" -eq 2 ] +grep -q 'pg-node-cert:pg-node-two$' "$cronfile" +grep -q 'pg-node-cert:pg-node-three$' "$cronfile" +grep -q 'echo unrelated' "$cronfile" +# A retry without hook environment recovers both files without renewal. +get_node_acme() { echo mock_acme; } +unset CERT_FULLCHAIN_PATH CERT_KEY_PATH +rm -rf "$DATA_DIR/certs/.acme-staging" +cp "$SSL_CERT_FILE" "$WORK_DIR/renewed-cert" +cp "$SSL_KEY_FILE" "$WORK_DIR/renewed-key" +stage_node_acme() { + mkdir -p "$DATA_DIR/certs/.acme-staging" + cp "$WORK_DIR/renewed-cert" "$DATA_DIR/certs/.acme-staging/fullchain.pem" + cp "$WORK_DIR/renewed-key" "$DATA_DIR/certs/.acme-staging/privkey.pem" +} +register_node_acme_reload() { :; } +# Synthetic self-signed fixture substitutes for system trust only. +validate_node_acme_chain() { :; } +write_node_cert_status deployment_pending +previous_calls=$(wc -l <"$acme_calls") +renew_cert_command +[ "$(node_cert_status_value deployment_state)" = deployed ] +[ "$(wc -l <"$acme_calls")" -eq "$previous_calls" ] +cmp "$WORK_DIR/renewed-cert" "$SSL_CERT_FILE" +cmp "$WORK_DIR/renewed-key" "$SSL_KEY_FILE" +# Complete staging is used directly on a later retry. +stage_node_acme() { return 1; } +write_node_cert_status deployment_pending +renew_cert_command if [ -s "$acme_validation_failures" ]; then cat "$acme_validation_failures" >&2; exit 1 fi diff --git a/tests/unit_pgnode_tls.sh b/tests/unit_pgnode_tls.sh index dff47bd..b2c107f 100644 --- a/tests/unit_pgnode_tls.sh +++ b/tests/unit_pgnode_tls.sh @@ -28,6 +28,21 @@ unset INSTALL_SSL_IP INSTALL_CERT_PATH=/not-found expect_fail validate_ssl_selection unset INSTALL_CERT_PATH +# Reject unsupported plaintext selections before saving metadata or certificates. +( + INSTALL_NO_SSL=true + node_version=v0.5.7 + curl() { printf '# No plaintext setting\n'; } + expect_fail choose_node_certificate + [ ! -e "$DATA_DIR/certs/source.json" ] + [ ! -e "$SSL_CERT_FILE" ] + node_version=dev + curl() { printf '# TLS_ENABLED = true\n'; } + choose_node_certificate + [ "$TLS_ENABLED" = false ] + [ "$(cert_metadata source)" = external_tls ] + rm "$DATA_DIR/certs/source.json" +) # Generate a real valid pair; preserve full chain bytes and permissions on deployment. openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj '/CN=unused' \ -addext 'subjectAltName=IP:192.0.2.1,IP:2001:db8::1,DNS:node.example.com,DNS:*.example.net' \