Lab7: HTTPS, mTLS, OpenBao, трек 2 PKI на оценку 5
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Wladislava1
2026-11-17 00:25:48 +03:00
parent 20afc2c790
commit 54dcf70ea6
88 changed files with 8930 additions and 58 deletions
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Отрицательные проверки внутреннего mTLS к API (docker network)."""
from __future__ import annotations
import ssl
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def check(cond, msg):
if not cond:
raise SystemExit("FAIL: " + msg)
def probe(client_cert: str | None, client_key: str | None, ca: str, expect_ok: bool) -> None:
"""curl из контейнера в сети lab к api:8443 с заданным client cert."""
cmd = [
"docker",
"run",
"--rm",
"--network",
"mtusi-lab7-net",
"-v",
f"{ROOT / 'certs'}:/certs:ro",
"curlimages/curl:8.10.1",
"-sS",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"--cacert",
"/certs/ca.crt",
"--connect-timeout",
"3",
"--max-time",
"5",
]
if client_cert and client_key:
cmd.extend(["--cert", client_cert, "--key", client_key])
cmd.append("https://api:8443/health/ready")
# Map host paths already under /certs; pass container paths.
if client_cert:
cmd = [
"docker",
"run",
"--rm",
"--network",
"mtusi-lab7-net",
"-v",
f"{ROOT / 'certs'}:/certs:ro",
"curlimages/curl:8.10.1",
"-sS",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"--cacert",
"/certs/ca.crt",
"--cert",
client_cert,
"--key",
client_key,
"--connect-timeout",
"3",
"--max-time",
"5",
"https://api:8443/health/ready",
]
else:
cmd = [
"docker",
"run",
"--rm",
"--network",
"mtusi-lab7-net",
"-v",
f"{ROOT / 'certs'}:/certs:ro",
"curlimages/curl:8.10.1",
"-sS",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"--cacert",
"/certs/ca.crt",
"--connect-timeout",
"3",
"--max-time",
"5",
"https://api:8443/health/ready",
]
proc = subprocess.run(cmd, capture_output=True, text=True)
ok = proc.returncode == 0 and proc.stdout.strip() == "200"
check(ok == expect_ok, f"mtls probe cert={client_cert} ok={ok} expected={expect_ok} out={proc.stdout!r} err={proc.stderr[-200:]!r}")
def main():
# Без client cert → отказ
probe(None, None, "/certs/ca.crt", expect_ok=False)
# Правильная identity lb → успех
probe("/certs/lb.crt", "/certs/private/lb.key", "/certs/ca.crt", expect_ok=True)
# Чужой leaf того же CA (api-client) → отказ identity
probe("/certs/api-client.crt", "/certs/private/api-client.key", "/certs/ca.crt", expect_ok=False)
print("PASS: mTLS rejects missing/wrong identity; lb identity accepted")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Allow/deny OpenBao policy для API AppRole (без печати token)."""
from __future__ import annotations
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CA = ROOT / "certs" / "ca.crt"
ADDR = "https://127.0.0.1:8200"
def ctx():
c = ssl.create_default_context(cafile=str(CA))
c.check_hostname = False
return c
def call(method, path, body=None, token=None):
data = None
headers = {"Accept": "application/json"}
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
if token:
headers["X-Vault-Token"] = token
req = urllib.request.Request(ADDR + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, context=ctx(), timeout=5) as response:
raw = response.read().decode("utf-8")
return response.status, json.loads(raw) if raw else {}
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8")
return exc.code, json.loads(raw) if raw else {}
def main():
role = (ROOT / "secrets/bao_api_role_id").read_text(encoding="utf-8").strip()
secret = (ROOT / "secrets/bao_api_secret_id").read_text(encoding="utf-8").strip()
code, payload = call("POST", "/v1/auth/approle/login", {"role_id": role, "secret_id": secret})
if code >= 400 or "auth" not in payload:
raise SystemExit("FAIL: approle login")
token = payload["auth"]["client_token"]
ok_code, _ = call("GET", "/v1/secret/data/messenger/api", token=token)
deny_code, _ = call("GET", "/v1/secret/data/messenger/worker", token=token)
if ok_code != 200:
raise SystemExit(f"FAIL: allow path status {ok_code}")
if deny_code not in (403, 404):
raise SystemExit(f"FAIL: deny path expected 403/404 got {deny_code}")
print("PASS: AppRole allow api secret; deny worker secret")
return 0
if __name__ == "__main__":
raise SystemExit(main())