# The certificate contract's provisioners
# (https://ydentifi.io/docs/certificate-contract), 1 for each role, each
# issuing through its template in templates/: the server's, and the relying
# party's, operator's and metrics scraper's. Sourced by entrypoint.sh.

# ydfi_check_trust_domain succeeds when $1 is a SPIFFE trust domain, as the
# server's YDFI_SERVER_TRUST_DOMAIN takes one: lowercase letters, digits,
# '.', '-' and '_', in labels separated by single dots, on one line. grep
# tests each line on its own, so a value of more than one line is refused
# first.
ydfi_check_trust_domain() {
	case "$1" in
	*"
"*) return 1 ;;
	esac
	printf '%s' "$1" | grep -Eqx '[a-z0-9_-]+(\.[a-z0-9_-]+)*'
}

# ydfi_check_stored_trust_domain succeeds unless the contract's provisioners
# in the CA configuration $1 issue under a trust domain other than $2. A
# provisioner that exists is left as it is, so a CA started under another
# trust domain would issue under the first.
ydfi_check_stored_trust_domain() {
	stored=$(jq -r '[.authority.provisioners[]? | select(.name | startswith("ydfi-")) | .options.x509.templateData.TrustDomain // empty] | unique | join(" ")' "$1")
	if [ -n "$stored" ] && [ "$stored" != "$2" ]; then
		echo "provisioners: the CA's provisioners issue under $stored, not $2; a provisioner that exists is left as it is" >&2
		return 1
	fi
}

# ydfi_role_flags prints the longest and the default lifetime of the role
# $1's certificates, then its provisioner's further flags.
ydfi_role_flags() {
	case "$1" in
	server) echo "720h 24h" ;;
	rp) echo "17520h 17520h --disable-renewal" ;;
	operator | monitoring) echo "2160h 2160h --disable-renewal" ;;
	*) return 1 ;;
	esac
}

# ydfi_add_provisioner adds a provisioner named $1, for the role $2, to the
# CA configuration $ca_json, unless one of its name is there. A provisioner
# that exists is left as it is, its trust domain and renewal included.
ydfi_add_provisioner() {
	name=$1 role=$2
	jq -e --arg n "$name" 'any(.authority.provisioners[]?; .name == $n)' "$ca_json" >/dev/null && return 0
	flags=$(ydfi_role_flags "$role") || return 1
	# shellcheck disable=SC2086 # the role's lifetimes and flags, one word each
	set -- $flags
	longest=$1 default=$2
	shift 2
	step ca provisioner add "$name" --type JWK --create \
		--password-file "$password_file" \
		--x509-template "$templates/$role.tpl" --x509-template-data "$template_data" \
		--x509-max-dur "$longest" --x509-default-dur "$default" "$@" \
		--ca-config "$ca_json" >/dev/null
}

# ydfi_rename_provisioner retires the provisioner $5 of the role $4, in the
# CA configuration $1 keyed with the CA's password in the file $2, through
# the templates in the directory $3, for one of a new name, which it prints:
# ydfi-<role>-<the rename's UTC time, to the second>, so a name retired is
# never given again, as a provisioner of that name would renew what the old
# one issued. The new one issues under the old one's trust domain, with the
# role's lifetimes and renewal; the old one must issue through the role's
# template, as it was added. Once the old one is removed, step-ca, which
# finds a certificate's provisioner by its name, renews no certificate the
# old one issued, a stolen copy's included; revoking the stolen certificate's
# serial does not stop a copy renewed before. The new one is added first:
# should it not be added, the old one is left as it was, and the call fails;
# should the old one then not be removed, the call fails and says so, and the
# removal is finished by hand. The CA takes the change when it next starts.
ydfi_rename_provisioner() {
	ca_json=$1 password_file=$2 templates=$3 role=$4 old=$5
	new="ydfi-$role-$(date -u +%Y%m%d%H%M%S)"
	trust_domain=$(jq -r --arg n "$old" '.authority.provisioners[]? | select(.name == $n) | .options.x509.templateData.TrustDomain // empty' "$ca_json")
	if [ -z "$trust_domain" ]; then
		echo "provisioners: the CA has no provisioner $old of the contract" >&2
		return 1
	fi
	if ! jq -j --arg n "$old" '.authority.provisioners[] | select(.name == $n) | .options.x509.template' "$ca_json" | cmp -s - "$templates/$role.tpl"; then
		echo "provisioners: $old does not issue through the $role template; it is not renamed, and is updated to it when the CA next starts" >&2
		return 1
	fi
	if jq -e --arg n "$new" 'any(.authority.provisioners[]?; .name == $n)' "$ca_json" >/dev/null; then
		echo "provisioners: the CA already has a provisioner named $new; it is not renamed" >&2
		return 1
	fi
	template_data=$(mktemp)
	jq -n --arg td "$trust_domain" '{TrustDomain: $td}' >"$template_data"
	added=0
	ydfi_add_provisioner "$new" "$role" || added=$?
	rm -f "$template_data"
	if [ "$added" != 0 ]; then
		echo "provisioners: $new could not be added; $old is left as it was" >&2
		return "$added"
	fi
	if ! step ca provisioner remove "$old" --ca-config "$ca_json" >/dev/null; then
		echo "provisioners: $new is added, but $old could not be removed and still renews what it issued; it is removed with: step ca provisioner remove $old --ca-config $ca_json" >&2
		return 1
	fi
	echo "$new"
}

# ydfi_role_of prints the role of the contract's provisioner named $1:
# ydfi-<role>, or ydfi-<role>-<the time of its rename>.
ydfi_role_of() {
	role=${1#ydfi-}
	case "$role" in
	*-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) role=${role%-*} ;;
	esac
	printf '%s\n' "$role"
}

# ydfi_stale_templates prints, one a line, the contract's provisioners in the
# CA configuration $1 that issue through a template other than their role's
# in the directory $2, and fails when the configuration cannot be read.
# step-ca keeps each provisioner's template in the configuration, as it was
# when the provisioner was added, so a template changed in the directory
# reaches no provisioner until it is updated. A name is read whole, spaces
# included: one that differs from a role's provisioner by a space is of no
# role.
ydfi_stale_templates() {
	names=$(jq -r '.authority.provisioners[]? | select(.name | startswith("ydfi-")) | .name' "$1") || return 1
	[ -n "$names" ] || return 0
	printf '%s\n' "$names" | while IFS= read -r name; do
		if ! jq -j --arg n "$name" '.authority.provisioners[] | select(.name == $n) | .options.x509.template // empty' "$1" |
			cmp -s - "$2/$(ydfi_role_of "$name").tpl"; then
			printf '%s\n' "$name"
		fi
	done
}

# ydfi_update_templates has each provisioner ydfi_stale_templates names in
# the CA configuration $1 issue through its role's template in the directory
# $2, and prints its name; its trust domain, lifetimes and renewal are left as
# they are. It updates none, and fails, when the configuration cannot be read
# or one of them is of no role of the contract, which it names with the
# command that removes it. The CA takes the change when it next starts.
ydfi_update_templates() {
	stale=$(ydfi_stale_templates "$1" "$2") || return 1
	[ -n "$stale" ] || return 0
	unknown=$(printf '%s\n' "$stale" | while IFS= read -r name; do
		[ -f "$2/$(ydfi_role_of "$name").tpl" ] || printf '%s\n' "$name"
	done)
	if [ -n "$unknown" ]; then
		printf '%s\n' "$unknown" | while IFS= read -r name; do
			echo "provisioners: '$name' is of no role of the contract; no provisioner is updated until it is removed: step ca provisioner remove '$name' --ca-config $1" >&2
		done
		return 1
	fi
	printf '%s\n' "$stale" | while IFS= read -r name; do
		template="$2/$(ydfi_role_of "$name").tpl"
		if ! out=$(step ca provisioner update "$name" --x509-template "$template" --ca-config "$1" 2>&1); then
			printf '%s\n' "$out" >&2
			return 1
		fi
		printf '%s\n' "$name"
	done
}

# ydfi_add_provisioners adds the 4 provisioners to the CA configuration
# $1, keyed with the CA's password in the file $2, through the templates in
# the directory $3, under the trust domain $4. The trust domain is the
# provisioners' own template data, which step-ca keeps in the configuration
# with each template; a request cannot name another. A CA whose provisioners
# issue under another trust domain is refused.
#
# Only the server's certificates renew. A relying party's, operator's or
# scraper's cannot be renewed by whoever holds it, so a stolen one ends at
# its lifetime: the deployer's CA issues each anew before it expires.
# Renewal would let a thief keep a stolen relying party's certificate alive
# past its suspension, with a new serial each time. step-ca still renews,
# whatever any provisioner's or the authority's claims say, a certificate
# under its root that no provisioner issued, as one `ydfi bootstrap` or
# another CA signed: such certificates are replaced through these
# provisioners, and the CA is out of reach of their holders.
ydfi_add_provisioners() {
	ca_json=$1 password_file=$2 templates=$3 trust_domain=$4
	if ! ydfi_check_trust_domain "$trust_domain"; then
		echo "provisioners: '$trust_domain' is not a SPIFFE trust domain" >&2
		return 1
	fi
	ydfi_check_stored_trust_domain "$ca_json" "$trust_domain" || return 1
	template_data=$(mktemp)
	jq -n --arg td "$trust_domain" '{TrustDomain: $td}' >"$template_data"
	added=0
	ydfi_add_provisioner ydfi-server server &&
		ydfi_add_provisioner ydfi-rp rp &&
		ydfi_add_provisioner ydfi-operator operator &&
		ydfi_add_provisioner ydfi-monitoring monitoring || added=$?
	rm -f "$template_data"
	return "$added"
}
