Files
headroom/app/security.py
kristianwind 15bbe02277 Headroom: homelab capacity dashboard
- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json)
- Multi-instance support: flere instanser af samme modultype med adskilte assets
- Community/Enterprise licensing med admin enterprise-toggle
- Capacity forecasting, trends, what-if simulator, alert policies
- MCP server + LLM copilot integration
- Dockerfile + rune.yaml til Yggdrasil
2026-10-23 22:39:27 +02:00

76 lines
2.2 KiB
Python

"""Password hashing, session tokens and API keys (stdlib only)."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import secrets
import time
from typing import Any, Dict, Optional
from .config import get_secret
PBKDF2_ROUNDS = 120_000
SESSION_TTL = 7 * 24 * 3600
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def _b64d(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PBKDF2_ROUNDS)
return f"pbkdf2${PBKDF2_ROUNDS}${salt.hex()}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, rounds, salt, digest = stored.split("$")
if scheme != "pbkdf2":
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), int(rounds)
)
return hmac.compare_digest(candidate.hex(), digest)
except (ValueError, TypeError):
return False
def sign_session(user_id: int, ttl: int = SESSION_TTL) -> str:
payload = {"uid": int(user_id), "exp": int(time.time()) + ttl, "n": secrets.token_hex(4)}
body = _b64e(json.dumps(payload, separators=(",", ":")).encode())
signature = hmac.new(get_secret().encode(), body.encode(), hashlib.sha256).digest()
return f"{body}.{_b64e(signature)}"
def verify_session(token: str) -> Optional[Dict[str, Any]]:
try:
body, signature = token.split(".", 1)
expected = hmac.new(get_secret().encode(), body.encode(), hashlib.sha256).digest()
if not hmac.compare_digest(_b64d(signature), expected):
return None
payload = json.loads(_b64d(body))
if int(payload.get("exp", 0)) < time.time():
return None
return payload
except (ValueError, TypeError, json.JSONDecodeError):
return None
def new_api_key() -> str:
return "hr_" + secrets.token_urlsafe(30)
def api_key_prefix(key: str) -> str:
return key[:12]
def hash_api_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()