#!/bin/sh
# The CA's half of the step-ca recipe with an offline root
# (https://ydentifi.io/docs/step-ca-recipes#recipe-2), run inside the CA's container:
#
#   intermediate.sh request
#       Makes the next intermediate's key in the CA's volume, encrypted with
#       the CA's password, prints its certificate request for offline.sh
#       sign, and names the key's fingerprint on standard error, which
#       offline.sh sign checks the request against. The intermediate is named
#       with the time of its request, so no 2 share a name: step-ca renews
#       an old intermediate as a CA certificate signed by the current one, and
#       a client that follows RFC 5280 does not count a certificate named as
#       its issuer against the current intermediate's path length of 0.
#
#   intermediate.sh install <root fingerprint> [replace-root]
#       Reads what offline.sh sign wrote, the intermediate and then the root,
#       on standard input. Checks that the root is a CA naming itself as its
#       issuer, with the fingerprint offline.sh root printed; that it signed
#       the intermediate; and that the intermediate is a CA over the key the
#       last request made. Once an offline root is installed, a different root
#       is refused unless replace-root is given: a new root means every relying
#       party, operator and scraper is issued its certificate again, and every
#       phone enrols again unless the new root is its backup root and no CA key
#       of the old root is stolen. Puts the intermediate, the
#       root and, last, the key where step-ca reads them, so an install that
#       stops midway is run again; deletes any root key in the volume
#       (step-ca's own initialisation leaves one); and has step-ca reload.
set -eu

STEPPATH=/home/step
password="$STEPPATH/secrets/password"
pending="$STEPPATH/secrets/intermediate_ca_key.next"

fail() {
	echo "intermediate.sh: $*" >&2
	exit 1
}

case "${1:-}" in
request)
	step certificate create "${DOCKER_STEPCA_INIT_NAME:-Ydentifi} Intermediate CA $(date -u +%Y%m%d%H%M%S)" /tmp/intermediate.csr "$pending" \
		--csr --kty EC --crv P-256 --password-file "$password" --force >/dev/null 2>&1
	cat /tmp/intermediate.csr
	rm -f /tmp/intermediate.csr
	step crypto key public "$pending" --password-file "$password" >/tmp/intermediate.pub
	echo "intermediate.sh: the request's key fingerprint is $(step crypto key fingerprint /tmp/intermediate.pub); offline.sh sign takes it" >&2
	rm -f /tmp/intermediate.pub
	;;
install)
	[ $# -eq 2 ] || { [ $# -eq 3 ] && [ "$3" = replace-root ]; } || fail "usage: intermediate.sh install <root fingerprint> [replace-root] < intermediate-and-root.pem"
	expected=$2
	[ -f "$pending" ] || fail "no key is waiting for its certificate; intermediate.sh request makes one"
	work=$(mktemp -d)
	trap 'rm -rf "$work"' EXIT
	awk -v dir="$work" '/-----BEGIN CERTIFICATE-----/ { n++ } n { print > (dir "/" n ".pem") }'
	[ -f "$work/2.pem" ] && [ ! -f "$work/3.pem" ] || fail "standard input must hold 2 certificates: the intermediate, then the root"
	intermediate="$work/1.pem" root="$work/2.pem"
	step certificate inspect "$root" --format json | jq -e '.subject_dn == .issuer_dn and .extensions.basic_constraints.is_ca == true' >/dev/null ||
		fail "the second certificate is not a root: a CA that names itself as its issuer"
	given=$(step certificate fingerprint "$root")
	[ "$given" = "$expected" ] || fail "the root given has the fingerprint $given, not $expected"
	current=$(step certificate fingerprint "$STEPPATH/certs/root_ca.crt")
	if [ ! -f "$STEPPATH/secrets/root_ca_key" ] && [ "$given" != "$current" ] && [ "${3:-}" != replace-root ]; then
		fail "the CA's root is $current; installing under another root replaces the deployment's root, and is done only with replace-root"
	fi
	step certificate verify "$intermediate" --roots "$root" >/dev/null 2>&1 || fail "the root did not sign the intermediate"
	step certificate inspect "$intermediate" --format json | jq -e '.extensions.basic_constraints.is_ca == true' >/dev/null ||
		fail "the intermediate is not a CA"
	[ "$(step certificate key "$intermediate")" = "$(step crypto key public "$pending" --password-file "$password")" ] ||
		fail "the intermediate is not over the key the last request made"
	cp "$intermediate" "$STEPPATH/certs/intermediate_ca.crt.new"
	cp "$root" "$STEPPATH/certs/root_ca.crt.new"
	mv "$STEPPATH/certs/intermediate_ca.crt.new" "$STEPPATH/certs/intermediate_ca.crt"
	mv "$STEPPATH/certs/root_ca.crt.new" "$STEPPATH/certs/root_ca.crt"
	mv "$pending" "$STEPPATH/secrets/intermediate_ca_key"
	rm -f "$STEPPATH/secrets/root_ca_key"
	sed -i "s/\"fingerprint\": \"[0-9a-f]*\"/\"fingerprint\": \"$given\"/" "$STEPPATH/config/defaults.json"
	kill -HUP 1
	echo "intermediate.sh: installed; the root's fingerprint is $given, and no root key is left with the CA"
	;;
*)
	echo "usage: intermediate.sh request | install <root fingerprint> [replace-root] < intermediate-and-root.pem" >&2
	exit 2
	;;
esac
