87 lines
2.3 KiB
Python
87 lines
2.3 KiB
Python
"""Password hashing and opaque token helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import secrets
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
salt = secrets.token_bytes(16)
|
|
derived = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=1)
|
|
return "scrypt$16384$8$1${}${}".format(
|
|
base64.b64encode(salt).decode("ascii"),
|
|
base64.b64encode(derived).decode("ascii"),
|
|
)
|
|
|
|
|
|
def verify_password(password: str, encoded: str | None) -> bool:
|
|
if not encoded:
|
|
return False
|
|
try:
|
|
algorithm, n_value, r_value, p_value, salt_encoded, digest_encoded = encoded.split("$", maxsplit=5)
|
|
except ValueError:
|
|
return False
|
|
if algorithm != "scrypt":
|
|
return False
|
|
salt = base64.b64decode(salt_encoded.encode("ascii"))
|
|
expected = base64.b64decode(digest_encoded.encode("ascii"))
|
|
actual = hashlib.scrypt(
|
|
password.encode("utf-8"),
|
|
salt=salt,
|
|
n=int(n_value),
|
|
r=int(r_value),
|
|
p=int(p_value),
|
|
)
|
|
return hmac.compare_digest(actual, expected)
|
|
|
|
|
|
def generate_token() -> str:
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def hash_token(token: str) -> str:
|
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def token_prefix(token: str) -> str:
|
|
return token[:8]
|
|
|
|
|
|
def mask_secret(value: str, *, prefix: int = 6, suffix: int = 4, mask_char: str = "*") -> str:
|
|
text = (value or "").strip()
|
|
if not text:
|
|
return ""
|
|
if len(text) <= prefix + suffix:
|
|
return mask_char * len(text)
|
|
hidden = len(text) - prefix - suffix
|
|
return f"{text[:prefix]}{mask_char * hidden}{text[-suffix:]}"
|
|
|
|
|
|
def build_audit_event(
|
|
*,
|
|
action: str,
|
|
actor_id: str,
|
|
bot_id: str,
|
|
token_id: str,
|
|
token_ref: str,
|
|
result: str,
|
|
detail: str | None = None,
|
|
) -> dict[str, Any]:
|
|
payload: dict[str, Any] = {
|
|
"event_type": "auth.bot_token",
|
|
"action": action,
|
|
"actor_id": actor_id,
|
|
"bot_id": bot_id,
|
|
"token_id": mask_secret(token_id, prefix=6, suffix=4),
|
|
"token_ref": token_ref,
|
|
"result": result,
|
|
"occurred_at": datetime.now(timezone.utc).isoformat(),
|
|
}
|
|
if detail:
|
|
payload["detail"] = detail
|
|
return payload |