58 lines
2.1 KiB
Nix
58 lines
2.1 KiB
Nix
# The store's value for Grafana's datasource-encryption key, seeded once from
|
|
# the file an earlier release generated in the container.
|
|
#
|
|
# Grafana cannot read datasource secrets encrypted with another key, so a store
|
|
# with no value takes the file's, and a new key is minted only when there is no
|
|
# file either. The store is written with `-cas=0`, so a value it holds is never
|
|
# replaced and a lost race reads the winner's back. The file stays, unused.
|
|
#
|
|
# `grafana_secret_key` sets `GRAFANA_KEY` and returns 0, or returns 1 when the
|
|
# store does not log in, answer or take a value; nothing is minted then.
|
|
#
|
|
# Pure function — NOT a NixOS module. Call it from a unit's `script`, with
|
|
# `bao` and `coreutils` on its `path` and the `BAO_*` client environment set:
|
|
#
|
|
# script = ''
|
|
# ${import ./lib/grafana-secret-key.nix { }}
|
|
# grafana_secret_key secret/swarm/services/foo/secret-key /path/to/seed openssl rand -hex 32 || exit 1
|
|
# '';
|
|
{ }:
|
|
''
|
|
# <store leaf> <seed file> <mint command…>
|
|
grafana_secret_key() {
|
|
local leaf="$1" seed="$2" candidate err
|
|
shift 2
|
|
GRAFANA_KEY=""
|
|
err="$(mktemp)"
|
|
|
|
if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then
|
|
cat "$err" >&2
|
|
rm -f "$err"
|
|
echo "could not log in to the swarm secret store." >&2
|
|
return 1
|
|
fi
|
|
export BAO_TOKEN
|
|
|
|
if ! GRAFANA_KEY="$(bao kv get -field=value "$leaf" 2>"$err")" || [ -z "$GRAFANA_KEY" ]; then
|
|
if [ -s "$seed" ]; then
|
|
candidate="$(tr -d '\n' < "$seed")"
|
|
echo "storing the key at $seed in $leaf."
|
|
else
|
|
candidate="$("$@")"
|
|
echo "no earlier key; minting one in $leaf."
|
|
fi
|
|
if ! printf '%s' "$candidate" | bao kv put -cas=0 "$leaf" value=- >/dev/null 2>"$err"; then
|
|
cat "$err" >&2
|
|
echo "could not create $leaf; reading it back in case another run created it." >&2
|
|
fi
|
|
if ! GRAFANA_KEY="$(bao kv get -field=value "$leaf" 2>"$err")" || [ -z "$GRAFANA_KEY" ]; then
|
|
cat "$err" >&2
|
|
rm -f "$err"
|
|
echo "the store did not return $leaf." >&2
|
|
GRAFANA_KEY=""
|
|
return 1
|
|
fi
|
|
fi
|
|
rm -f "$err"
|
|
}
|
|
''
|