forked from mtusi2026/mtusi2026lab7
93 lines
2.2 KiB
Bash
Executable File
93 lines
2.2 KiB
Bash
Executable File
#!/bin/sh
|
|
|
|
set -eu
|
|
|
|
umask 077
|
|
|
|
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
|
|
openbao_runtime_dir="$repo_dir/.runtime/openbao"
|
|
openbao_operator_file="$openbao_runtime_dir/operator/init.json"
|
|
|
|
BAO_BIN=${BAO_BIN:-$repo_dir/scripts/bao-docker.sh}
|
|
BAO_ADDR=${BAO_ADDR:-https://localhost:8200}
|
|
BAO_CACERT=${BAO_CACERT:-$repo_dir/.runtime/security/openbao/ca.crt}
|
|
|
|
export BAO_ADDR BAO_CACERT
|
|
|
|
fail() {
|
|
echo "$*" >&2
|
|
exit 1
|
|
}
|
|
|
|
require_command() {
|
|
command -v "$1" >/dev/null 2>&1 || fail "required command not found: $1"
|
|
}
|
|
|
|
require_file() {
|
|
[ -f "$1" ] || fail "required file not found: $1"
|
|
}
|
|
|
|
require_private_file() {
|
|
require_file "$1"
|
|
if ! permissions=$(stat -c '%a' "$1" 2>/dev/null); then
|
|
permissions=$(stat -f '%Lp' "$1")
|
|
fi
|
|
case "$permissions" in
|
|
600|400) ;;
|
|
*) fail "file must have permissions 0600 or 0400: $1" ;;
|
|
esac
|
|
}
|
|
|
|
require_runtime_path() {
|
|
case "$1" in
|
|
"$openbao_runtime_dir"/*) ;;
|
|
*) fail "runtime credentials must stay under $openbao_runtime_dir" ;;
|
|
esac
|
|
}
|
|
|
|
json_field() {
|
|
file=$1
|
|
expression=$2
|
|
python3 - "$file" "$expression" <<'PY'
|
|
import json
|
|
import sys
|
|
|
|
with open(sys.argv[1], encoding="utf-8") as source:
|
|
value = json.load(source)
|
|
|
|
for component in sys.argv[2].split("."):
|
|
value = value[component]
|
|
|
|
if isinstance(value, bool):
|
|
print(str(value).lower())
|
|
else:
|
|
print(value)
|
|
PY
|
|
}
|
|
|
|
load_operator_token() {
|
|
require_private_file "$openbao_operator_file"
|
|
BAO_TOKEN=$(json_field "$openbao_operator_file" root_token)
|
|
export BAO_TOKEN
|
|
}
|
|
|
|
openbao_status() {
|
|
status_file=$1
|
|
"$BAO_BIN" status -format=json >"$status_file" 2>/dev/null || true
|
|
[ -s "$status_file" ] || fail "OpenBao is not reachable at $BAO_ADDR"
|
|
}
|
|
|
|
require_unsealed() {
|
|
mkdir -p "$openbao_runtime_dir"
|
|
chmod 0700 "$openbao_runtime_dir"
|
|
status_file=$(mktemp "$openbao_runtime_dir/.status.XXXXXX")
|
|
chmod 0600 "$status_file"
|
|
openbao_status "$status_file"
|
|
initialized=$(json_field "$status_file" initialized)
|
|
sealed=$(json_field "$status_file" sealed)
|
|
rm -f "$status_file"
|
|
[ "$initialized" = "true" ] || fail "OpenBao is not initialized"
|
|
[ "$sealed" = "false" ] || fail "OpenBao is sealed"
|
|
}
|