forked from mtusi2026/mtusi2026lab7
50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
"""Проверяет политику mTLS каждой реплики из внутренней сети Compose."""
|
|
|
|
import http.client
|
|
from pathlib import Path
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
|
|
CERTIFICATES = Path("/certificates")
|
|
|
|
|
|
class ApiConnection(http.client.HTTPSConnection):
|
|
def __init__(self, address: str, context: ssl.SSLContext):
|
|
super().__init__("api", 8080, timeout=4, context=context)
|
|
self.address = address
|
|
|
|
def connect(self):
|
|
raw = socket.create_connection((self.address, self.port), self.timeout)
|
|
self.sock = self._context.wrap_socket(raw, server_hostname=self.host)
|
|
|
|
|
|
def request(address: str, identity: str | None) -> int:
|
|
context = ssl.create_default_context(cafile=str(CERTIFICATES / "ca.crt"))
|
|
if identity:
|
|
context.load_cert_chain(CERTIFICATES / f"{identity}.crt",
|
|
CERTIFICATES / f"{identity}.key")
|
|
connection = ApiConnection(address, context)
|
|
try:
|
|
connection.request("GET", "/health/live")
|
|
return connection.getresponse().status
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def main() -> None:
|
|
assert len(sys.argv[1:]) >= 2, "Нужны минимум две API-реплики"
|
|
for address in sys.argv[1:]:
|
|
assert request(address, "load-balancer") == 200
|
|
for identity in (None, "foreign-client", "wrong-role"):
|
|
try:
|
|
request(address, identity)
|
|
except (ssl.SSLError, ConnectionError, http.client.RemoteDisconnected):
|
|
continue
|
|
raise AssertionError(f"Реплика приняла запрещённую identity: {identity}")
|
|
print("PASS: mTLS allow/deny на всех API-репликах")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|