Introduce an opt-in AES-256-GCM credential store keyed by environment, application and principal. Bind ciphertext to identity, version and key ID with authenticated data; support retained decryption keys and active-key rotation. Use expected-version CAS to reject duplicate or stale writers. Keep token values and scopes encrypted at rest, hide token fields from object repr, and use fixed errors without credential contents. Add tests for identity substitution, authenticated tampering, wrong keys, rotation, persistence, concurrent writers and malformed inputs. Include an opt-in PostgreSQL test using an isolated schema. Validation: 102 passed, 2 skipped (no real PostgreSQL URL), 15 existing uvicorn/websockets deprecation warnings. Python AST and diff checks pass. This is stage 1 only: no public routes or existing OAuth/refresh behavior are changed, no production key/database is initialized, and no ECS runtime deployment or real platform requests were performed. Broker, centralized refresh, access-token-only issuance and unbind lifecycle integration remain subsequent stages. See deployable/CREDENTIAL_MIGRATION.md.
178 lines
8.2 KiB
Python
178 lines
8.2 KiB
Python
"""Server-only encrypted user credentials. Not wired to public routes in stage 1."""
|
|
import base64
|
|
import json
|
|
import math
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
|
|
from .store import INTEGRITY_ERRORS
|
|
|
|
|
|
class CredentialError(RuntimeError):
|
|
"""Safe, fixed messages only; never attach platform responses or key material."""
|
|
|
|
|
|
class CredentialConflict(CredentialError):
|
|
pass
|
|
|
|
|
|
def _identifier(value):
|
|
if not isinstance(value, str) or not value or len(value) > 256:
|
|
raise CredentialError("invalid credential identity")
|
|
if any(ord(c) < 32 for c in value):
|
|
raise CredentialError("invalid credential identity")
|
|
return value
|
|
|
|
|
|
def _key_id(value):
|
|
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", value):
|
|
raise CredentialError("invalid credential key configuration")
|
|
return value
|
|
|
|
|
|
class CredentialKeyring:
|
|
"""AES-256-GCM keyring; active key writes, retained keys decrypt old versions."""
|
|
|
|
def __init__(self, active_key_id, keys):
|
|
self.active_key_id = _key_id(active_key_id)
|
|
if not isinstance(keys, dict) or not keys or len(keys) > 32:
|
|
raise CredentialError("invalid credential key configuration")
|
|
self._keys = {}
|
|
for name, key in keys.items():
|
|
if not isinstance(key, bytes) or len(key) != 32:
|
|
raise CredentialError("invalid credential key configuration")
|
|
self._keys[_key_id(name)] = key
|
|
if self.active_key_id not in self._keys:
|
|
raise CredentialError("invalid credential key configuration")
|
|
|
|
@classmethod
|
|
def from_file(cls, path: Path):
|
|
"""Load an operator-protected, separately backed-up JSON key file."""
|
|
try:
|
|
if path.stat().st_size > 16384:
|
|
raise ValueError()
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
if set(data) != {"active_key_id", "keys"} or not isinstance(data["keys"], dict):
|
|
raise ValueError()
|
|
keys = {name: base64.b64decode(value, validate=True)
|
|
for name, value in data["keys"].items()}
|
|
return cls(data["active_key_id"], keys)
|
|
except (OSError, ValueError, TypeError, KeyError, CredentialError):
|
|
raise CredentialError("cannot load credential key configuration") from None
|
|
|
|
def encrypt(self, plaintext, aad):
|
|
import secrets
|
|
nonce = secrets.token_bytes(12)
|
|
ciphertext = AESGCM(self._keys[self.active_key_id]).encrypt(nonce, plaintext, aad)
|
|
return self.active_key_id, base64.b64encode(nonce + ciphertext).decode("ascii")
|
|
|
|
def decrypt(self, key_id, ciphertext, aad):
|
|
try:
|
|
raw = base64.b64decode(ciphertext, validate=True)
|
|
if len(raw) < 28:
|
|
raise ValueError()
|
|
return AESGCM(self._keys[key_id]).decrypt(raw[:12], raw[12:], aad)
|
|
except Exception:
|
|
raise CredentialError("credential decryption failed") from None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class UserCredential:
|
|
version: int
|
|
access_expires_at: float
|
|
refresh_expires_at: float
|
|
scopes: tuple[str, ...]
|
|
access_token: str = field(repr=False)
|
|
refresh_token: str = field(repr=False)
|
|
|
|
|
|
class CredentialStore:
|
|
"""Opt-in additive schema on the connector Store connection (SQLite or PG).
|
|
|
|
Caller must supply the last read version. Never retries a conflicting write.
|
|
This is internal storage, not a response DTO: never serialize it to clients.
|
|
"""
|
|
|
|
def __init__(self, store, keyring: CredentialKeyring):
|
|
self.db = store.db
|
|
self.keyring = keyring
|
|
with self.db:
|
|
self.db.execute("""CREATE TABLE IF NOT EXISTS work_credentials_v2(
|
|
environment TEXT NOT NULL, app_id TEXT NOT NULL, principal_id TEXT NOT NULL,
|
|
credential_version INTEGER NOT NULL, key_id TEXT NOT NULL,
|
|
ciphertext TEXT NOT NULL, updated_at DOUBLE PRECISION NOT NULL,
|
|
PRIMARY KEY(environment, app_id, principal_id))""")
|
|
|
|
@staticmethod
|
|
def _aad(identity, version, key_id):
|
|
# JSON array preserves identity boundaries (no delimiter collisions).
|
|
return json.dumps(["hainuo-user-credential-v1", *identity, version, key_id],
|
|
ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
|
|
@staticmethod
|
|
def _payload(access_token, refresh_token, access_expires_at, refresh_expires_at, scopes):
|
|
for token in (access_token, refresh_token):
|
|
if not isinstance(token, str) or not token or len(token) > 16384:
|
|
raise CredentialError("invalid credential payload")
|
|
for expiry in (access_expires_at, refresh_expires_at):
|
|
if (isinstance(expiry, bool) or not isinstance(expiry, (int, float))
|
|
or expiry <= 0 or expiry > 253402300799 or not math.isfinite(expiry)):
|
|
raise CredentialError("invalid credential payload")
|
|
if (not isinstance(scopes, (list, tuple)) or len(scopes) > 1024
|
|
or any(not isinstance(s, str) or not s or len(s) > 256 for s in scopes)):
|
|
raise CredentialError("invalid credential payload")
|
|
return {"access_token": access_token, "refresh_token": refresh_token,
|
|
"access_expires_at": access_expires_at, "refresh_expires_at": refresh_expires_at,
|
|
"scopes": sorted(set(scopes))}
|
|
|
|
def save(self, environment, app_id, principal_id, *, expected_version, access_token,
|
|
refresh_token, access_expires_at, refresh_expires_at, scopes):
|
|
identity = tuple(_identifier(v) for v in (environment, app_id, principal_id))
|
|
if type(expected_version) is not int or expected_version < 0 or expected_version >= 2147483647:
|
|
raise CredentialError("invalid credential version")
|
|
payload = self._payload(access_token, refresh_token, access_expires_at, refresh_expires_at, scopes)
|
|
version = expected_version + 1
|
|
key_id = self.keyring.active_key_id
|
|
_, ciphertext = self.keyring.encrypt(
|
|
json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8"),
|
|
self._aad(identity, version, key_id))
|
|
try:
|
|
with self.db:
|
|
if expected_version == 0:
|
|
self.db.execute("INSERT INTO work_credentials_v2 VALUES(?,?,?,?,?,?,?)",
|
|
(*identity, version, key_id, ciphertext, time.time()))
|
|
else:
|
|
count = self.db.execute("""UPDATE work_credentials_v2
|
|
SET credential_version=?,key_id=?,ciphertext=?,updated_at=?
|
|
WHERE environment=? AND app_id=? AND principal_id=? AND credential_version=?""",
|
|
(version, key_id, ciphertext, time.time(), *identity, expected_version)).rowcount
|
|
if count != 1:
|
|
raise CredentialConflict("credential version conflict")
|
|
except INTEGRITY_ERRORS:
|
|
raise CredentialConflict("credential version conflict") from None
|
|
return version
|
|
|
|
def get(self, environment, app_id, principal_id):
|
|
identity = tuple(_identifier(v) for v in (environment, app_id, principal_id))
|
|
row = self.db.execute("""SELECT credential_version,key_id,ciphertext FROM work_credentials_v2
|
|
WHERE environment=? AND app_id=? AND principal_id=?""", identity).fetchone()
|
|
if row is None:
|
|
return None
|
|
try:
|
|
version = row["credential_version"]
|
|
raw = self.keyring.decrypt(row["key_id"], row["ciphertext"],
|
|
self._aad(identity, version, row["key_id"]))
|
|
data = json.loads(raw)
|
|
payload = self._payload(**data)
|
|
return UserCredential(version=version, access_token=payload["access_token"],
|
|
refresh_token=payload["refresh_token"],
|
|
access_expires_at=payload["access_expires_at"],
|
|
refresh_expires_at=payload["refresh_expires_at"],
|
|
scopes=tuple(payload["scopes"]))
|
|
except Exception:
|
|
raise CredentialError("credential decryption failed") from None
|