#!/bin/bash

# Exercise the whole mod_md certificate lifecycle (account creation, http-01
# challenge, staging, activation, renewal) against a local ACME test server
# (pebble)
#
# Certificates normally need renewing only every couple of months, so
# permission problems in the store would otherwise only be noticed then. Here
# pebble issues certificates that are valid for just a few minutes, so the
# initial issuance and a renewal on top of an already populated store both
# happen within the test.
#
set -eu

DOMAIN=md-test.example
STORE=/etc/apache2/md
PEBBLE_CA=/etc/apache2/md-test-pebble-ca.pem
SITE=md-test
SITE_ROOT=/var/www/md-test
SITE_CONTENT="mod_md test site for md-test.example"
WORK=$(mktemp -d)
HOSTS_MARK="# added by apache2 md-acme autopkgtest"
PEBBLE_PID=

# Later steps build on earlier ones, so stop at the first failure. The cleanup
# handler shows the logs.
fail () {
    echo "FAIL: $*" >&2
    exit 1
}

# APACHE_RUN_USER, as configured in /etc/apache2/envvars
RUN_USER=$(set +eu; . /etc/apache2/envvars >/dev/null 2>&1; echo "${APACHE_RUN_USER:-www-data}")

cleanup()
{
    status=$?
    echo "=== Cleaning up"
    set +e
    if [ "$status" -ne 0 ]; then
        echo "=== Something failed, getting troubleshooting information"
        echo
        echo "=== apache2.service status"
        systemctl status apache2.service
        echo
        echo "=== apache2 error log"
        cat /var/log/apache2/error.log
        echo
        echo "=== $STORE contents"
        ls -lRa "$STORE"
        echo
        echo "=== pebble.log"
        cat "$WORK/pebble.log"
        echo
    fi
    echo "=== Restoring environment to pre-test state as close as possible"
    [ -n "$PEBBLE_PID" ] && kill "$PEBBLE_PID"
    sed -i "/$HOSTS_MARK/d" /etc/hosts
    a2dissite -q "$SITE"
    a2dismod -q md
    a2dismod -q ssl
    rm -f "/etc/apache2/sites-available/$SITE.conf" "$PEBBLE_CA"
    rm -rf "$SITE_ROOT"
    systemctl restart apache2
    rm -rf "$WORK"
}
trap cleanup EXIT

override_systemd_throttling() {
    local svc="${1}"

    mkdir -p "/run/systemd/system/${svc}.service.d"
    cat > "/run/systemd/system/${svc}.service.d/override.conf" <<EOF
[Unit]
StartLimitIntervalSec=0
EOF
    systemctl daemon-reload
}

# poll <timeout seconds> <command...>: retry until the command succeeds.
# Show a dot for each failed attempt, and the last error only on timeout.
poll () {
    local timeout=$1 i output
    shift
    for i in $(seq "$timeout"); do
        if output=$("$@" 2>&1); then
            [ "$i" -eq 1 ] || echo " done!"
            return 0
        fi
        printf .
        sleep 1
    done
    echo
    echo "Command failed after $timeout attempts: $*" >&2
    echo "$output" >&2
    return 1
}

# store_serial <staging|domains>: serial of the certificate in that part of the
# store, in the form curl prints it (openssl prints "serial=0A0B0C", curl
# prints "Serial Number:0a0b0c"). Empty if there is no certificate.
store_serial () {
    openssl x509 -in "$STORE/$1/$DOMAIN/pubcert.pem" -noout -serial 2>/dev/null |
        sed -n 's/^serial=//p' | tr A-F a-f
}

staged () {
    [ -s "$STORE/staging/$DOMAIN/pubcert.pem" ]
}

# staged_new <serial>: a certificate other than <serial> is staged
staged_new () {
    local s
    s=$(store_serial staging) && [ -n "$s" ] && [ "$s" != "$1" ]
}

# fetch_site: request the site over HTTPS, verifying the certificate against
# pebble's root. This fails while Apache still serves mod_md's self-signed
# fallback certificate. The body ends up in $WORK/site-body, and the details of
# the leaf certificate curl received from Apache in $WORK/served-cert.
fetch_site () {
    local certs
    certs=$(curl -fsS --cacert "$WORK/pebble-root.pem" -o "$WORK/site-body" \
        -w '%{certs}' "https://$DOMAIN/") || return 1
    # %{certs} lists the whole chain, starting with the leaf certificate.
    # pebble leaves the subject empty, the name is only in the SAN.
    printf '%s\n' "$certs" | awk '/^Subject:/ { n++ } n == 1' |
        sed 's/^Subject:$/Subject:<empty>/' |
        grep -E '^(Subject|Issuer|Serial Number|Start date|Expire date|X509v3 Subject Alternative Name):' > "$WORK/served-cert"
}

# serial of the certificate received by the last fetch_site
served_serial () {
    sed -n 's/^Serial Number://p' "$WORK/served-cert"
}

# serving_new <serial>: Apache serves a valid certificate other than <serial>.
# Right after a reload, the previous certificate can still be served for a
# moment, so waiting for "the served certificate is the active one" is not
# enough.
serving_new () {
    fetch_site && [ "$(served_serial)" != "$1" ]
}

# check_activated <file>: the certificate received by the last fetch_site is the
# active one in the store, and the site has the expected content. Keep the
# certificate details in <file> for the summary.
check_activated () {
    local serial body
    serial=$(served_serial)
    [ -n "$serial" ] || fail "no serial number in the certificate received by curl"
    [ "$serial" = "$(store_serial domains)" ] ||
        fail "served certificate $serial is not the active one in $STORE/domains/$DOMAIN"
    echo "Certificate received by curl:"
    cp "$WORK/served-cert" "$1"
    cat "$1"
    body=$(cat "$WORK/site-body")
    echo "Site content: $body"
    [ "$body" = "$SITE_CONTENT" ] ||
        fail "unexpected site content: expected '$SITE_CONTENT', got '$body'"
}

# --- pebble: TLS cert for its ACME endpoint, and config ---------------------

override_systemd_throttling apache2

echo "=== Setting up a local CA and the pebble ACME server"

# Use a CA-issued endpoint certificate: Ubuntu's curl/upki revocation check
# rejects a verified chain consisting only of a self-signed certificate.
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=md-test-ca \
    -addext basicConstraints=critical,CA:TRUE \
    -addext keyUsage=critical,keyCertSign,cRLSign \
    -keyout "$WORK/ca-key.pem" -out "$WORK/ca.pem"
openssl req -newkey rsa:2048 -nodes -subj /CN=localhost \
    -keyout "$WORK/pebble-key.pem" -out "$WORK/pebble.csr"
cat > "$WORK/pebble-ext.cnf" <<EOT
subjectAltName=DNS:localhost,IP:127.0.0.1
basicConstraints=critical,CA:FALSE
extendedKeyUsage=serverAuth
EOT
openssl x509 -req -in "$WORK/pebble.csr" -CA "$WORK/ca.pem" -CAkey "$WORK/ca-key.pem" \
    -CAcreateserial -days 1 -extfile "$WORK/pebble-ext.cnf" -out "$WORK/pebble-cert.pem"
# apache2.service has PrivateTmp=yes, so the CA file cannot live under /tmp
install -m 644 "$WORK/ca.pem" "$PEBBLE_CA"

# Short-lived certificates let the test exercise renewal as well as issuance.
# Older pebble releases (e.g. 2.6.0 in resolute) only know
# certificateValidityPeriod, newer ones (e.g. 2.10.0) ignore it and use the
# profile's validityPeriod. Unknown keys are ignored, so set both.
cat > "$WORK/pebble.json" <<EOT
{
  "pebble": {
    "listenAddress": "127.0.0.1:14000",
    "managementListenAddress": "127.0.0.1:15000",
    "certificate": "$WORK/pebble-cert.pem",
    "privateKey": "$WORK/pebble-key.pem",
    "httpPort": 80,
    "certificateValidityPeriod": 300,
    "profiles": {
      "default": {
        "validityPeriod": 300
      }
    }
  }
}
EOT

PEBBLE_VA_NOSLEEP=1 pebble -config "$WORK/pebble.json" > "$WORK/pebble.log" 2>&1 &
PEBBLE_PID=$!
echo "=== Waiting for pebble to become ready"
poll 30 curl -fsS --cacert "$WORK/ca.pem" https://localhost:14000/dir ||
    fail "cannot reach pebble with a verified TLS connection"
# Trust the CA that signs the managed certificate when checking HTTPS later.
curl -fsS --cacert "$WORK/ca.pem" https://localhost:15000/roots/0 -o "$WORK/pebble-root.pem"

echo "=== Configuring Apache for $DOMAIN"
echo "127.0.0.1 $DOMAIN $HOSTS_MARK" >> /etc/hosts

# --- apache: note that MDStoreDir is deliberately not set, we take the default ---

install -d "$SITE_ROOT"
printf '%s\n' "$SITE_CONTENT" > "$SITE_ROOT/index.html"

cat > "/etc/apache2/sites-available/$SITE.conf" <<EOT
MDCertificateAuthority https://localhost:14000/dir
MDCACertificateFile $PEBBLE_CA
MDCertificateAgreement accepted
MDContactEmail admin@$DOMAIN
# certs only live for 5 minutes: renew as soon as possible
MDRenewWindow 90%
# Check often enough to renew the short-lived certificate during the test.
# The default interval is 12 hours, with random jitter.
MDCheckInterval 20s
MDomain $DOMAIN

<VirtualHost *:80>
    ServerName $DOMAIN
    DocumentRoot $SITE_ROOT
</VirtualHost>

<VirtualHost *:443>
    ServerName $DOMAIN
    DocumentRoot $SITE_ROOT
    SSLEngine on
</VirtualHost>
EOT

a2enmod ssl
a2enmod md
a2ensite "$SITE"
systemctl restart apache2
systemctl is-active --quiet apache2

# --- 1. first issuance: account, http-01 challenge, staging ------------------

echo "=== Waiting for the initial certificate issuance"
poll 120 staged || fail "no certificate was staged in $STORE/staging/$DOMAIN"
grep "set VALID by completed challenge" "$WORK/pebble.log" || fail "pebble did not validate the http-01 challenge"

# the staged certificate is only used after a (graceful) restart
echo "=== Activating the initial certificate"
systemctl reload apache2
poll 30 fetch_site || fail "staged certificate was not activated after reload"
check_activated "$WORK/original-served-cert"
SERIAL1=$(served_serial)

# --- 2. renewal on top of the populated store -------------------------------

# Activation moved the certificate out of staging/; a renewal puts a new one
# there. This needs the watchdog to run in the workers and write to the store.
echo "=== Waiting for the certificate renewal"
poll 330 staged_new "$SERIAL1" || fail "certificate was not renewed"
echo "=== Activating the renewed certificate"
systemctl reload apache2
poll 30 serving_new "$SERIAL1" || fail "renewed certificate was not activated after reload"
check_activated "$WORK/renewed-served-cert"

# --- 3. store state ---------------------------------------------------------

echo "=== Checking the store contents and permissions"
for d in domains accounts; do
    [ -d "$STORE/$d" ] || fail "$STORE/$d does not exist"
done
[ -s "$STORE/domains/$DOMAIN/pubcert.pem" ] || fail "no active certificate in the store"
[ -s "$STORE/domains/$DOMAIN/privkey.pem" ] || fail "no active private key in the store"
# the private key must not be readable by the worker user nor by others
if runuser -u "$RUN_USER" -- cat "$STORE/domains/$DOMAIN/privkey.pem" >/dev/null 2>&1; then
    fail "$RUN_USER can read the active private key"#
fi
# only root and the worker user may own anything in the store
if find "$STORE" ! -user root ! -user "$RUN_USER" | grep .; then
    fail "unexpected owner in $STORE"
fi
if grep -E "\[md:(error|crit|alert|emerg)\]" /var/log/apache2/error.log; then
    fail "mod_md errors in error.log"
fi

echo "=== Test summary"
echo "Initial certificate issued and activated"
echo "Certificate renewed and activated"
echo "HTTPS site requests returned the expected content with both certificates"
echo "Store contents and permissions verified"
echo
echo "Original certificate served by Apache:"
cat "$WORK/original-served-cert"
echo
echo "Renewed certificate served by Apache:"
cat "$WORK/renewed-served-cert"
echo
echo "Files in $STORE:"
find "$STORE" -ls
echo
echo "PASS: mod_md certificate lifecycle test passed"
