forked from mtusi2026/mtusi2026lab7
feat: rotate and revoke credentials on the running stand
Add operator commands for leaf and secret rotation, identity revocation and CRL renewal without rebuilding images, and a drill under load. A rejected PostgreSQL role password is now 503 instead of 500. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -234,3 +234,208 @@ def test_command_exits_1_when_not_active(
|
||||
assert "bao: OpenBao is not active in 1 s (sys/health 429)" in out, out
|
||||
assert "/v1/sys/seal-status" in state.paths
|
||||
assert not operator_dir.exists()
|
||||
|
||||
|
||||
# отзыв токенов роли (change rotation-revocation, design, решение 8; спек
|
||||
# secret-store, «Отзыв токенов identity оператором»): accessor → (роль входа,
|
||||
# серийный номер leaf) и токен без роли (root); «исчезнувший» accessor есть в
|
||||
# списке, но его поиск отвечает 403, а отзыв другого — 400
|
||||
ROOT_TOKEN = "s.root-of-the-test" # noqa: S105
|
||||
OLD_SERIAL = 0x01AC0000000000000000000000000001
|
||||
NEW_SERIAL = 0x01AC0000000000000000000000000002
|
||||
ACCESSORS: dict[str, tuple[str, int] | None] = {
|
||||
"acc-relay-old": ("relay", OLD_SERIAL),
|
||||
"acc-relay-new": ("relay", NEW_SERIAL),
|
||||
"acc-relay-vanishing": ("relay", OLD_SERIAL),
|
||||
"acc-worker": ("worker", OLD_SERIAL),
|
||||
"acc-root": None,
|
||||
"acc-gone": None,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Tokens:
|
||||
sealed: bool = False
|
||||
revoked: list[str] = field(default_factory=list)
|
||||
paths: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _tokens_handler(
|
||||
state: _Tokens,
|
||||
) -> type[http.server.BaseHTTPRequestHandler]:
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def _send(self, status: int, payload: dict[str, Any]) -> None:
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
state.paths.append(self.path)
|
||||
if self.path == "/v1/sys/seal-status":
|
||||
self._send(
|
||||
200,
|
||||
{"initialized": True, "sealed": state.sealed},
|
||||
)
|
||||
else:
|
||||
self._send(200, {})
|
||||
|
||||
def do_LIST(self) -> None: # noqa: N802
|
||||
assert self.headers["X-Vault-Token"] == ROOT_TOKEN
|
||||
assert self.path == "/v1/auth/token/accessors"
|
||||
self._send(200, {"data": {"keys": list(ACCESSORS)}})
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
assert self.headers["X-Vault-Token"] == ROOT_TOKEN
|
||||
size = int(self.headers.get("Content-Length") or 0)
|
||||
accessor = json.loads(self.rfile.read(size))["accessor"]
|
||||
if self.path == "/v1/auth/token/lookup-accessor":
|
||||
if accessor == "acc-gone":
|
||||
self._send(403, {"errors": ["invalid accessor"]})
|
||||
return
|
||||
info = ACCESSORS[accessor]
|
||||
if info is None:
|
||||
data: dict[str, Any] = {
|
||||
"path": "auth/token/root",
|
||||
"display_name": "root",
|
||||
"meta": None,
|
||||
}
|
||||
else:
|
||||
data = {
|
||||
"path": "auth/cert/login",
|
||||
"display_name": f"cert-{info[0]}",
|
||||
"meta": {"serial_number": str(info[1])},
|
||||
}
|
||||
self._send(200, {"data": data})
|
||||
elif accessor == "acc-relay-vanishing":
|
||||
self._send(400, {"errors": ["invalid accessor"]})
|
||||
else:
|
||||
assert self.path == "/v1/auth/token/revoke-accessor"
|
||||
state.revoked.append(accessor)
|
||||
self._send(204, {})
|
||||
|
||||
def log_message(self, *_args: Any) -> None:
|
||||
return None
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _token_store(stand: Path, state: _Tokens) -> Iterator[str]:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(stand / "openbao.crt", stand / "openbao.key")
|
||||
server = http.server.ThreadingHTTPServer(
|
||||
("127.0.0.1", 0),
|
||||
_tokens_handler(state),
|
||||
)
|
||||
server.daemon_threads = True
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield f"https://localhost:{server.server_address[1]}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _revoke_tokens(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
state: _Tokens,
|
||||
*args: str,
|
||||
) -> int:
|
||||
operator_dir = tmp_path / "op"
|
||||
operator_dir.mkdir()
|
||||
(operator_dir / "root-token").write_text(ROOT_TOKEN)
|
||||
with _token_store(pki, state) as address:
|
||||
return bao.main(
|
||||
[*_argv(address, pki, operator_dir), "revoke-tokens", *args],
|
||||
)
|
||||
|
||||
|
||||
def _assert_no_secrets(out: str) -> None:
|
||||
assert ROOT_TOKEN not in out
|
||||
for accessor in ACCESSORS:
|
||||
assert accessor not in out, out
|
||||
|
||||
|
||||
def test_revoke_tokens_of_role(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Все токены роли: чужая роль, root и исчезнувшие accessors не тронуты;
|
||||
вывод — роль и число, без токенов и accessors."""
|
||||
state = _Tokens()
|
||||
code = _revoke_tokens(bao, pki, tmp_path, state, "--role", "relay")
|
||||
out = capsys.readouterr().out
|
||||
assert code == 0, out
|
||||
assert state.revoked == ["acc-relay-old", "acc-relay-new"]
|
||||
assert "role relay: revoked 2 tokens" in out, out
|
||||
_assert_no_secrets(out)
|
||||
|
||||
|
||||
def test_revoke_tokens_keep_serial(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Токен, выданный указанному leaf, остаётся; номер — шестнадцатеричный,
|
||||
как у `openssl x509 -serial`."""
|
||||
state = _Tokens()
|
||||
code = _revoke_tokens(
|
||||
bao,
|
||||
pki,
|
||||
tmp_path,
|
||||
state,
|
||||
"--role",
|
||||
"relay",
|
||||
"--keep-serial",
|
||||
f"{NEW_SERIAL:032X}",
|
||||
)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 0, out
|
||||
assert state.revoked == ["acc-relay-old"]
|
||||
assert "role relay: revoked 1 tokens, kept 1" in out, out
|
||||
_assert_no_secrets(out)
|
||||
|
||||
|
||||
def test_revoke_tokens_sealed(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Запечатан — код 2 с подсказкой, ничего не отозвано."""
|
||||
state = _Tokens(sealed=True)
|
||||
code = _revoke_tokens(bao, pki, tmp_path, state, "--role", "relay")
|
||||
out = capsys.readouterr().out
|
||||
assert code == 2, out # noqa: PLR2004
|
||||
assert "make bao_unseal" in out
|
||||
assert state.revoked == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"args",
|
||||
[("--role", "mallory"), (), ("--role", "relay", "--keep-serial", "zz")],
|
||||
)
|
||||
def test_revoke_tokens_bad_arguments(
|
||||
bao: ModuleType,
|
||||
pki: Path,
|
||||
tmp_path: Path,
|
||||
args: tuple[str, ...],
|
||||
) -> None:
|
||||
"""Роль — только из таблицы ROLES, серийный номер — hex: код 2 до
|
||||
обращения к OpenBao."""
|
||||
state = _Tokens()
|
||||
with pytest.raises(SystemExit) as error:
|
||||
_revoke_tokens(bao, pki, tmp_path, state, *args)
|
||||
assert error.value.code == 2 # noqa: PLR2004
|
||||
assert state.paths == []
|
||||
|
||||
Reference in New Issue
Block a user