Complete lab 7 security implementation
This commit is contained in:
+162
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
import hvac
|
||||
|
||||
log = logging.getLogger("messenger.secrets")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_client: Optional[hvac.Client] = None
|
||||
_token_ttl: float = 0.0
|
||||
_token_expires_at: float = 0.0
|
||||
_secrets_cache: dict[str, tuple[float, Any]] = {}
|
||||
_secret_ttl: float = 300.0 # 5 минут
|
||||
_ready: bool = False
|
||||
|
||||
|
||||
def _read_file(path: str) -> Optional[str]:
|
||||
try:
|
||||
return Path(path).read_text().strip()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _role_id() -> Optional[str]:
|
||||
return _read_file(os.environ.get("BAO_ROLE_ID_FILE", "/run/secrets/bao_role_id"))
|
||||
|
||||
|
||||
def _secret_id() -> Optional[str]:
|
||||
return _read_file(os.environ.get("BAO_SECRET_ID_FILE", "/run/secrets/bao_secret_id"))
|
||||
|
||||
|
||||
def _make_client() -> hvac.Client:
|
||||
addr = os.environ.get("BAO_ADDR", "https://openbao:8200")
|
||||
ca = os.environ.get("BAO_CACERT", "/run/secrets/ca.crt")
|
||||
return hvac.Client(url=addr, verify=ca)
|
||||
|
||||
|
||||
def _approle_login(client: hvac.Client) -> None:
|
||||
role_id = _role_id()
|
||||
secret_id = _secret_id()
|
||||
if not role_id or not secret_id:
|
||||
raise RuntimeError("BAO_ROLE_ID_FILE or BAO_SECRET_ID_FILE not set")
|
||||
resp = client.auth.approle.login(role_id=role_id, secret_id=secret_id)
|
||||
auth = resp.get("auth", {})
|
||||
client.token = auth.get("client_token")
|
||||
global _token_ttl, _token_expires_at
|
||||
_token_ttl = float(auth.get("lease_duration", 3600))
|
||||
_token_expires_at = time.monotonic() + _token_ttl
|
||||
log.info("openbao_login_ok", extra={"ttl": _token_ttl})
|
||||
|
||||
|
||||
_last_init_attempt: float = 0.0
|
||||
_INIT_COOLDOWN_SECONDS: float = 5.0
|
||||
|
||||
|
||||
def init_secrets() -> bool:
|
||||
global _client, _ready, _last_init_attempt, _token_ttl, _token_expires_at
|
||||
with _lock:
|
||||
if _ready:
|
||||
return True
|
||||
now = time.monotonic()
|
||||
if now - _last_init_attempt < _INIT_COOLDOWN_SECONDS:
|
||||
return False
|
||||
_last_init_attempt = now
|
||||
try:
|
||||
client = _make_client()
|
||||
try:
|
||||
_approle_login(client)
|
||||
except Exception as exc:
|
||||
log.warning("openbao_login_failed", extra={"error": str(exc)})
|
||||
_ready = False
|
||||
return False
|
||||
path = os.environ.get("BAO_SECRET_PATH_API", "messenger/api")
|
||||
try:
|
||||
resp = client.secrets.kv.v2.read_secret_version(
|
||||
path=path, mount_point="secret"
|
||||
)
|
||||
data = resp.get("data", {}).get("data")
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError("OpenBao returned invalid secret data")
|
||||
except Exception as exc:
|
||||
_client = None
|
||||
_token_ttl = 0.0
|
||||
_token_expires_at = 0.0
|
||||
_secrets_cache.pop(path, None)
|
||||
_ready = False
|
||||
log.warning("openbao_read_api_path_failed", extra={"error": str(exc)})
|
||||
return False
|
||||
|
||||
_client = client
|
||||
_secrets_cache[path] = (time.monotonic(), data)
|
||||
_ready = True
|
||||
log.info("openbao_ready")
|
||||
return True
|
||||
except Exception as exc:
|
||||
log.warning("openbao_init_failed", extra={"error": str(exc)})
|
||||
_ready = False
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_token() -> None:
|
||||
global _client, _token_expires_at, _ready
|
||||
if _client is None:
|
||||
raise RuntimeError("openbao client not initialized")
|
||||
if _token_expires_at - time.monotonic() < _token_ttl * 0.2:
|
||||
try:
|
||||
_client.auth.token.renew_self()
|
||||
_token_expires_at = time.monotonic() + _token_ttl
|
||||
log.info("openbao_token_renewed")
|
||||
except Exception as exc:
|
||||
log.warning("openbao_token_renew_failed", extra={"error": str(exc)})
|
||||
try:
|
||||
_approle_login(_client)
|
||||
except Exception:
|
||||
_ready = False
|
||||
_client = None
|
||||
raise
|
||||
|
||||
|
||||
def get_secret(path: str, *, force_refresh: bool = False) -> Any:
|
||||
global _client, _ready, _token_ttl, _token_expires_at
|
||||
|
||||
if _client is None:
|
||||
_ready = False
|
||||
raise RuntimeError("openbao client not initialized")
|
||||
|
||||
now = time.monotonic()
|
||||
cached = _secrets_cache.get(path)
|
||||
|
||||
if not force_refresh and cached and now - cached[0] < _secret_ttl:
|
||||
return cached[1]
|
||||
|
||||
try:
|
||||
_ensure_token()
|
||||
resp = _client.secrets.kv.v2.read_secret_version(
|
||||
path=path,
|
||||
mount_point="secret",
|
||||
)
|
||||
data = resp.get("data", {}).get("data")
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError("OpenBao returned invalid secret data")
|
||||
|
||||
_secrets_cache[path] = (time.monotonic(), data)
|
||||
return data
|
||||
|
||||
except Exception:
|
||||
_ready = False
|
||||
_client = None
|
||||
_token_ttl = 0.0
|
||||
_token_expires_at = 0.0
|
||||
_secrets_cache.pop(path, None)
|
||||
raise
|
||||
|
||||
def is_ready() -> bool:
|
||||
return _ready
|
||||
Reference in New Issue
Block a user