# Certificate verification

DEBIAN_FRONTEND="noninteractive" apt install -y --no-install-recommends ssl-cert

# add staging root certificates to the trust store to emulate the production environment
for ca in /usr/share/lacme/letsencrypt-stg-root-*.pem; do
    ln -sT "$ca" "/usr/local/share/ca-certificates/$(basename -s.pem "$ca").crt"
done
update-ca-certificates

# test (modified) trust store for intermediate certificates
openssl verify -no-CAfile -CApath /etc/ssl/certs                     -show_chain /usr/share/lacme/letsencrypt-stg-int-*.pem
openssl verify -no-CApath -CAfile /etc/ssl/certs/ca-certificates.crt -show_chain /usr/share/lacme/letsencrypt-stg-int-*.pem

mv /usr/share/lacme/ca-certificates.crt /usr/share/lacme/ca-certificates.crt.back
! lacme newOrder 2>"$STDERR" || fail
grepstderr -Fxq "Can't open /usr/share/lacme/ca-certificates.crt for reading, No such file or directory"
grepstderr -Fxq "[simpletest-rsa] Error: Received invalid X.509 certificate from ACME server!"

# verification error for unrelated CA bundle
cat /etc/ssl/certs/ssl-cert-snakeoil.pem >/usr/share/lacme/ca-certificates.crt
! lacme newOrder 2>"$STDERR" || fail
grepstderr -Fxq "error 20 at 0 depth lookup: unable to get local issuer certificate"
grepstderr -Fxq "[simpletest-rsa] Error: Received invalid X.509 certificate from ACME server!"

# verification error when the CA bundle contains only the root certificates
cat /usr/share/lacme/letsencrypt-stg-root-*.pem >/usr/share/lacme/ca-certificates.crt
! lacme newOrder 2>"$STDERR" || fail
grepstderr -Fxq "error 20 at 0 depth lookup: unable to get local issuer certificate"
grepstderr -Fxq "[simpletest-rsa] Error: Received invalid X.509 certificate from ACME server!"

# verification error when the CA bundle contains only the intermediate certificates
cat /usr/share/lacme/letsencrypt-stg-int-*.pem >/usr/share/lacme/ca-certificates.crt
! lacme newOrder 2>"$STDERR" || fail
grepstderr -Fxq "error 2 at 1 depth lookup: unable to get issuer certificate"
grepstderr -Fxq "[simpletest-rsa] Error: Received invalid X.509 certificate from ACME server!"

# use saved bundle as custom CAfile
sed -ri 's|^#?CAfile\s*=.*|CAfile = /usr/share/lacme/ca-certificates.crt.back|' /etc/lacme/lacme-certs.conf
lacme newOrder 2>"$STDERR" || fail
test /etc/lacme/simpletest.rsa.crt -nt /etc/lacme/simpletest.rsa.key

# vim: set filetype=sh :