"""Integration token rotation and verification.""" from __future__ import annotations import hashlib import hmac import secrets from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any from backend.dto.common import ApiError, ErrorCode from backend.services.settings_service import _dump_yaml from core.audit_service import AuditService from core.config_service import ConfigService from core.identity import RequestContext from core.interop import PRIVATE_COMPANION from database.db_helper import _load_yaml_subset DEFAULT_GRACE_SECONDS = 24 * 60 * 60 MAX_GRACE_SECONDS = 7 * 24 * 60 * 60 class IntegrationTokenService: def __init__( self, config_service: ConfigService | None = None, *, audit_service: AuditService | None = None, ): self.config_service = config_service or ConfigService() self.audit_service = audit_service def status(self) -> dict[str, Any]: security = self._security() return { "integration_token_set": _current_token_set(security), "previous_token_set": _previous_token_set(security), "allowed_integration_plugins": _allowed_plugins(security), "rotated_at": security.get("integration_token_rotated_at"), "previous_expires_at": security.get("previous_integration_token_expires_at"), } def rotate(self, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]: token = _token_or_generate(payload.get("token")) grace_seconds = _grace_seconds(payload.get("grace_seconds")) config = self._load_config() security = dict(config.get("security") or {}) now = _now() current_hash = str(security.get("integration_token_hash") or "").strip() current_salt = str(security.get("integration_token_salt") or "").strip() if current_hash and current_salt: security["previous_integration_token_hash"] = current_hash security["previous_integration_token_salt"] = current_salt security["previous_integration_token_expires_at"] = _format_time(now + timedelta(seconds=grace_seconds)) else: security.pop("previous_integration_token_hash", None) security.pop("previous_integration_token_salt", None) security.pop("previous_integration_token_expires_at", None) salt = secrets.token_hex(16) security["integration_token_hash"] = _hash_token(token, salt) security["integration_token_salt"] = salt security["integration_token_rotated_at"] = _format_time(now) security["integration_token_set"] = True security.pop("integration_token", None) config["security"] = security self._write_config(config) public_status = self.status() if self.audit_service: self.audit_service.record( ctx=ctx, action="rotate_integration_token", target_type="integration", target_id=PRIVATE_COMPANION, after_snapshot=public_status, metadata={"grace_seconds": grace_seconds}, ) return { "token": token, "token_preview": _token_preview(token), "status": public_status, } def verify(self, source: str, token: Any) -> dict[str, Any]: security = self._security() normalized_source = str(source or "").strip() allowed_plugins = _allowed_plugins(security) if allowed_plugins and normalized_source not in allowed_plugins: raise ApiError( ErrorCode.INTEGRATION_TOKEN_INVALID, "integration plugin is not allowed", {"request_source": normalized_source}, ) if not _current_token_set(security): return {"valid": True, "required": False, "token_slot": "not_configured"} candidate = str(token or "").strip() if not candidate: raise ApiError(ErrorCode.INTEGRATION_TOKEN_INVALID, "integration token is required", {}) if _matches_hash(candidate, security.get("integration_token_salt"), security.get("integration_token_hash")): return {"valid": True, "required": True, "token_slot": "current"} if _previous_token_set(security) and _matches_hash( candidate, security.get("previous_integration_token_salt"), security.get("previous_integration_token_hash"), ): return {"valid": True, "required": True, "token_slot": "previous"} legacy_token = str(security.get("integration_token") or "").strip() if legacy_token and hmac.compare_digest(candidate, legacy_token): return {"valid": True, "required": True, "token_slot": "legacy"} raise ApiError(ErrorCode.INTEGRATION_TOKEN_INVALID, "integration token is invalid", {}) def _security(self) -> dict[str, Any]: return dict(self._load_config().get("security") or {}) def _load_config(self) -> dict[str, Any]: path = self.config_service.config_path if not path.exists(): return {} return _load_yaml_subset(path.read_text(encoding="utf-8")) def _write_config(self, config: dict[str, Any]) -> None: path: Path = self.config_service.config_path path.parent.mkdir(parents=True, exist_ok=True) path.write_text(_dump_yaml(config), encoding="utf-8") def _current_token_set(security: dict[str, Any]) -> bool: return bool(security.get("integration_token_hash") or security.get("integration_token")) def _previous_token_set(security: dict[str, Any]) -> bool: if not (security.get("previous_integration_token_hash") and security.get("previous_integration_token_salt")): return False expires_at = _parse_time(security.get("previous_integration_token_expires_at")) return expires_at is None or expires_at > _now() def _allowed_plugins(security: dict[str, Any]) -> list[str]: plugins = security.get("allowed_integration_plugins") if isinstance(plugins, list): normalized = [str(plugin).strip() for plugin in plugins if str(plugin).strip()] return normalized or [PRIVATE_COMPANION] return [PRIVATE_COMPANION] def _token_or_generate(value: Any) -> str: token = str(value or "").strip() or secrets.token_urlsafe(32) if len(token) < 16: raise ApiError(ErrorCode.VALIDATION_FAILED, "integration token must be at least 16 characters", {"field": "token"}) return token def _grace_seconds(value: Any) -> int: try: seconds = int(value) except (TypeError, ValueError): seconds = DEFAULT_GRACE_SECONDS return min(max(seconds, 0), MAX_GRACE_SECONDS) def _hash_token(token: str, salt: str) -> str: return hmac.new(salt.encode("utf-8"), token.encode("utf-8"), hashlib.sha256).hexdigest() def _matches_hash(token: str, salt: Any, digest: Any) -> bool: normalized_salt = str(salt or "").strip() normalized_digest = str(digest or "").strip() if not normalized_salt or not normalized_digest: return False return hmac.compare_digest(_hash_token(token, normalized_salt), normalized_digest) def _now() -> datetime: return datetime.now(timezone.utc) def _format_time(value: datetime) -> str: return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") def _parse_time(value: Any) -> datetime | None: text = str(value or "").strip() if not text: return None if text.endswith("Z"): text = text[:-1] + "+00:00" try: parsed = datetime.fromisoformat(text) except ValueError: return None if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc) return parsed.astimezone(timezone.utc) def _token_preview(token: str) -> str: return f"{token[:4]}...{token[-4:]}"