forked from mtusi2026/mtusi2026lab7
feat: core func lab7
This commit is contained in:
Executable
+90
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверяет seal, истечение lease и восстановление с тем же Bearer."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from bootstrap_security import OPERATOR, ROOT, TLS
|
||||
from manage_openbao import OpenBao, unseal
|
||||
from rotate_security import wait_ready, wait_replicas
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def api_token(bao):
|
||||
context = ssl.create_default_context(cafile=str(ROOT / "certs/ca.crt"))
|
||||
identity = TLS / "messenger_api"
|
||||
context.load_cert_chain(identity / "tls.crt", identity / "tls.key")
|
||||
request = Request(bao.address + "/v1/auth/cert/login", data=b'{"name":"api"}',
|
||||
headers={"Content-Type": "application/json"})
|
||||
with urlopen(request, context=context, timeout=4) as response:
|
||||
auth = json.load(response)["auth"]
|
||||
return auth["client_token"], auth["lease_duration"]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("BASE_URL", "https://localhost:8443"))
|
||||
args = parser.parse_args()
|
||||
address = os.environ.get("BAO_OPERATOR_ADDR", "https://localhost:8200")
|
||||
bao = OpenBao(address)
|
||||
operator = json.loads((OPERATOR / "bao-init.json").read_text())
|
||||
token = operator["root_token"]
|
||||
client = Client(args.url, str(ROOT / "certs/ca.crt"))
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
text = "OpenBao lifecycle audit"
|
||||
client.message(alice, chat, text)
|
||||
service_token, ttl = api_token(bao)
|
||||
if not 0 < ttl <= 30:
|
||||
raise RuntimeError("Некорректный TTL service token")
|
||||
path = "messenger/data/api"
|
||||
bao.request("GET", path, token=service_token)
|
||||
archived = api_token(bao)[0]
|
||||
bao.request("POST", "auth/token/revoke", {"token": archived}, token=token)
|
||||
try:
|
||||
bao.request("GET", path, token=archived)
|
||||
except HTTPError as error:
|
||||
if error.code != 403:
|
||||
raise
|
||||
else:
|
||||
raise RuntimeError("Отозванный OpenBao token всё ещё работает")
|
||||
print("PASS OpenBao token revoke: старый токен получает 403", flush=True)
|
||||
|
||||
started = time.monotonic()
|
||||
bao.request("PUT", "sys/seal", token=token)
|
||||
try:
|
||||
elapsed = wait_replicas(args.url, 503, 36)
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
client.call("GET", "/api/v1/users/me", 503, actor=alice)
|
||||
print(f"PASS OpenBao sealed: все API-реплики перешли в 503 через {elapsed:.1f} с, liveness 200", flush=True)
|
||||
remaining = ttl + 1 - (time.monotonic() - started)
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
finally:
|
||||
unseal(bao, operator)
|
||||
|
||||
try:
|
||||
bao.request("GET", path, token=service_token)
|
||||
except HTTPError as error:
|
||||
if error.code != 403:
|
||||
raise
|
||||
else:
|
||||
raise RuntimeError("Просроченный OpenBao token ещё работает")
|
||||
wait_ready(args.url)
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages",
|
||||
actor=alice, schema="MessagePage")["json"]
|
||||
if not any(item["text"] == text for item in history["items"]):
|
||||
raise RuntimeError("Подтверждённое сообщение потеряно после unseal")
|
||||
print("PASS OpenBao unseal: token expired 403, обе реплики ready, сессия и сообщение сохранены")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user