forked from mtusi2026/mtusi2026lab7
Перевести пароли на Argon2id и читать секреты через AppRole.
Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
"""TLS server in front of the local API.
|
||||
|
||||
The proxy requires a client certificate from our CA, the LB URI SAN, and a
|
||||
fingerprint that is still listed in the allow file. Uvicorn stays on 127.0.0.1.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import ssl
|
||||
|
||||
from app import config
|
||||
|
||||
logger = logging.getLogger("messenger.tls")
|
||||
ALLOWED_URI = "spiffe://messenger/lb"
|
||||
|
||||
|
||||
def _allowed_fingerprints() -> set[str]:
|
||||
path = config.MTLS_ALLOW_FILE
|
||||
if not path:
|
||||
return set()
|
||||
try:
|
||||
text = open(path, encoding="utf-8").read()
|
||||
except OSError:
|
||||
logger.warning("mTLS allow file is not readable")
|
||||
return set()
|
||||
return {line.strip().lower() for line in text.splitlines() if line.strip()}
|
||||
|
||||
|
||||
def _identity_ok(ssl_object: ssl.SSLObject) -> bool:
|
||||
cert = ssl_object.getpeercert()
|
||||
if not cert:
|
||||
return False
|
||||
names = [value for kind, value in cert.get("subjectAltName", ()) if kind == "URI"]
|
||||
if ALLOWED_URI not in names:
|
||||
return False
|
||||
der = ssl_object.getpeercert(binary_form=True)
|
||||
if not der:
|
||||
return False
|
||||
fingerprint = hashlib.sha256(der).hexdigest()
|
||||
return fingerprint in _allowed_fingerprints()
|
||||
|
||||
|
||||
async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
try:
|
||||
while True:
|
||||
chunk = await reader.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
writer.write(chunk)
|
||||
await writer.drain()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None:
|
||||
ssl_object = client_writer.get_extra_info("ssl_object")
|
||||
if ssl_object is None or not _identity_ok(ssl_object):
|
||||
client_writer.close()
|
||||
await client_writer.wait_closed()
|
||||
return
|
||||
try:
|
||||
upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", config.PORT)
|
||||
except Exception:
|
||||
client_writer.close()
|
||||
await client_writer.wait_closed()
|
||||
return
|
||||
await asyncio.gather(
|
||||
_pipe(client_reader, upstream_writer),
|
||||
_pipe(upstream_reader, client_writer),
|
||||
)
|
||||
|
||||
|
||||
def _context() -> ssl.SSLContext:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.load_cert_chain(config.TLS_CERT_FILE, config.TLS_KEY_FILE)
|
||||
context.load_verify_locations(config.TLS_CA_FILE)
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
return context
|
||||
|
||||
|
||||
async def serve() -> None:
|
||||
if not (config.TLS_CERT_FILE and config.TLS_KEY_FILE and config.TLS_CA_FILE):
|
||||
raise SystemExit("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required")
|
||||
server = await asyncio.start_server(_handle, "0.0.0.0", config.MTLS_PORT, ssl=_context())
|
||||
logger.info("mTLS proxy listening on %s", config.MTLS_PORT)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
asyncio.run(serve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user