Files
mtusi2026lab7/scripts/rotate-and-revoke.sh
T
wanderinho 7ee5192cbd
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР7 - БПИ2303 - Стругов - на 4
2026-12-06 23:11:49 +03:00

68 lines
2.8 KiB
Bash
Executable File

#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
. ./infra/openbao/operator.sh
load_operator_token
# Keep staged material after a partial failure so the operator can retry.
stage=secrets/operator/rotation
if [ ! -d "$stage" ]; then
mkdir "$stage"
cp secrets/pki/api.crt "$stage/old.crt"
cp secrets/pki/api.key "$stage/old.key"
fi
[ -s "$stage/old.crt" ] && [ -s "$stage/old.key" ]
if [ ! -s "$stage/api.crt" ] || [ ! -s "$stage/api.key" ]; then
sh scripts/pki.sh --issue api "$stage"
fi
if [ ! -s "$stage/password" ]; then
openssl rand -hex 24 > "$stage/password"
fi
payload=$stage/payload
trap 'rm -f "$payload" "$stage/login"' EXIT
login_status() {
bao_request --cert "$1" --key "$2" -o "$stage/login" -w '%{http_code}' \
-H 'Content-Type: application/json' -d '{"name":"api"}' \
https://bao:8200/v1/auth/cert/login
}
if [ ! -s "$stage/old-token" ]; then
[ "$(login_status "$stage/old.crt" "$stage/old.key")" = 200 ] ||
{ echo "The original leaf could not log in" >&2; exit 1; }
python3 -c 'import json, sys; print(json.load(sys.stdin)["auth"]["client_token"])' \
< "$stage/login" > "$stage/old-token"
fi
replicas=$(docker compose ps -aq api | python3 -c 'import sys; print(max(1, len(sys.stdin.readlines())))')
# Update MinIO first and then both consumers' KV entries.
install -m 644 "$stage/password" "$stage/password.publish"
mv "$stage/password.publish" secrets/minio_api_password.txt
docker compose run --rm --no-deps minio-init
publish_kv api
publish_kv worker
# The role pins the public leaf; replacing it removes trust in the old leaf.
write_cert_role api "$stage/api.crt" > "$payload"
bao_admin -X POST --data-binary "@$payload" https://bao:8200/v1/auth/cert/certs/api
case "$(login_status "$stage/old.crt" "$stage/old.key")" in
400|403) ;;
*) echo "Old certificate was not rejected by OpenBao" >&2; exit 1 ;;
esac
[ "$(login_status "$stage/api.crt" "$stage/api.key")" = 200 ]
install -m 644 "$stage/api.key" "$stage/api.publish.key"
install -m 644 "$stage/api.crt" "$stage/api.publish.crt"
mv "$stage/api.publish.key" secrets/pki/api.key
mv "$stage/api.publish.crt" secrets/pki/api.crt
# File bind mounts retain old inodes until containers are recreated.
docker compose up -d --no-deps --no-build --force-recreate \
--scale "api=$replicas" --wait --wait-timeout 60 api worker
# Non-renewable batch tokens obtained by the old identity can live for 15 s.
sleep 15
expired_status=$(printf 'header = "X-Vault-Token: %s"\n' "$(cat "$stage/old-token")" |
bao_request --config - -o /dev/null -w '%{http_code}' https://bao:8200/v1/secret/data/api)
[ "$expired_status" = 403 ] || { echo "Old token expiry was not confirmed" >&2; exit 1; }
rm -rf "$stage"
echo "MinIO password rotated, new API leaf accepted, old API leaf denied by OpenBao"