#!/usr/bin/env bash
#
# Builds the throwaway PKI that the two-CGW test deployment authenticates with,
# and the Kubernetes Secrets that carry it into the two releases.
#
# One self-signed root plus one end-entity certificate per site: the root is
# self-signed because it *is* the trust anchor, the two site certificates are
# signed by it and are what charon presents to its peer. Nothing here is
# committed - the output directory is ignored by git, so a leaked key is
# always a key from someone's own workstation.
#
#   ./mkcerts.sh
#   kubectl apply -n "$NS" -f pki/secrets.yaml
#
# The site certificates are short lived on purpose (30 days by default, see
# LEAF_DAYS): `strongswan_cert_expire_secs` and the X509 Certificate
# Expiration panel of the CGW dashboard then show a number worth reading
# instead of a decade.

set -o errexit
set -o nounset
set -o pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
out="${here}/pki"

# the root outlives the leaves it signs, so that only the leaves have to be
# reissued while a deployment is being kept alive
CA_DAYS="${CA_DAYS:-3650}"
LEAF_DAYS="${LEAF_DAYS:-30}"
# the DN suffix both identities share; leftid/rightid in the values files quote
# the full DN, so changing this means changing those too
DOMAIN="${DOMAIN:-cgw-test}"

if [ -e "${out}" ] && [ "${1:-}" != "--force" ]; then
    echo "${out} exists; re-run with --force to replace the PKI" >&2
    echo "note that replacing it needs the Secrets re-applied and both" >&2
    echo "ipsec containers restarted, charon reads the files once at start" >&2
    exit 1
fi

rm -rf "${out}"
mkdir -p "${out}"
cd "${out}"

echo "==> root CA, valid ${CA_DAYS} days"
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -noenc \
    -days "${CA_DAYS}" -subj "/CN=${DOMAIN} CA" \
    -addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
    -addext "keyUsage=critical,keyCertSign,cRLSign" \
    -keyout ca-key.pem -out ca.pem 2>/dev/null

for site in site-a site-b; do
    echo "==> ${site} certificate, valid ${LEAF_DAYS} days, signed by the root"
    openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -noenc \
        -subj "/CN=${site}.${DOMAIN}" \
        -keyout "${site}-key.pem" -out "${site}.csr" 2>/dev/null
    # id-kp-ipsecIKE (1.3.6.1.5.5.7.3.17) is the extended key usage strongSwan
    # expects on an IKE end-entity certificate
    openssl x509 -req -in "${site}.csr" -CA ca.pem -CAkey ca-key.pem \
        -days "${LEAF_DAYS}" -out "${site}.pem" \
        -extfile <(printf '%s\n' \
            "basicConstraints=critical,CA:FALSE" \
            "keyUsage=critical,digitalSignature" \
            "extendedKeyUsage=1.3.6.1.5.5.7.3.17" \
            "subjectAltName=DNS:${site}.${DOMAIN}") 2>/dev/null
    rm -f "${site}.csr"
done

echo "==> verifying the chain"
openssl verify -CAfile ca.pem site-a.pem site-b.pem

b64() { openssl base64 -A -in "$1"; }

# The CA is the same file on both sides, so one Secret serves both releases;
# a certificate and its key are per release. The whole Secret is mounted as a
# directory, so every key here becomes a file name charon sees - which is why
# `leftcert=` and the `: ECDSA` line in the values files name these exact
# files.
echo "==> pki/secrets.yaml"
{
    cat <<EOF
---
# Generated by mkcerts.sh - do not commit.
apiVersion: v1
kind: Secret
metadata:
  name: cgw-pki-cacerts
  labels:
    app.kubernetes.io/part-of: two-cgw-test
type: Opaque
data:
  ca.pem: $(b64 ca.pem)
EOF
    for site in a b; do
        cat <<EOF
---
apiVersion: v1
kind: Secret
metadata:
  name: cgw-${site}-pki-certs
  labels:
    app.kubernetes.io/part-of: two-cgw-test
type: Opaque
data:
  site-${site}.pem: $(b64 "site-${site}.pem")
---
apiVersion: v1
kind: Secret
metadata:
  name: cgw-${site}-pki-privatekeys
  labels:
    app.kubernetes.io/part-of: two-cgw-test
type: Opaque
data:
  site-${site}-key.pem: $(b64 "site-${site}-key.pem")
EOF
    done
} > secrets.yaml

cat <<EOF

PKI written to ${out}

  kubectl apply -n "\$NS" -f ${out#"${here}/"}/secrets.yaml

then install as described in README.md. The values files reference the Secrets
by name, so they have to exist before the pods start.
EOF
