diff --git a/backend/route_registry.py b/backend/route_registry.py index c10e236..c2c2e40 100644 --- a/backend/route_registry.py +++ b/backend/route_registry.py @@ -136,6 +136,8 @@ ROUTES: tuple[RouteSpec, ...] = ( ), RouteSpec("POST", "profiles/{profile_id}/wardrobe/match", "backend.routes.wardrobe_routes.match_wardrobe", "read"), RouteSpec("POST", "integrations/private-companion/daily-outfit", "backend.routes.integration_routes.private_companion_daily_outfit", "read"), + RouteSpec("GET", "integrations/private-companion/token", "backend.routes.integration_routes.get_private_companion_token_status", "config"), + RouteSpec("POST", "integrations/private-companion/token/rotate", "backend.routes.integration_routes.rotate_private_companion_token", "config"), RouteSpec("GET", "integrations/logs", "backend.routes.integration_routes.list_integration_logs", "read"), RouteSpec("GET", "logs/generation", "backend.routes.log_routes.get_generation_logs", "read"), RouteSpec("GET", "logs/workflows", "backend.routes.log_routes.get_workflow_logs", "read"), diff --git a/backend/routes/integration_routes.py b/backend/routes/integration_routes.py index c1b7284..03338b7 100644 --- a/backend/routes/integration_routes.py +++ b/backend/routes/integration_routes.py @@ -6,10 +6,12 @@ from typing import Any from backend.routes.common import handle_request from backend.services.integration_service import IntegrationService +from backend.services.integration_token_service import IntegrationTokenService from backend.services.wardrobe_service import WardrobeService from core.audit_service import AuditService +from core.config_service import ConfigService from core.identity import RequestContext -from core.security import require_authenticated +from core.security import require_authenticated, require_config_manager from database.db_helper import Database, load_database_settings from database.repositories.integration_repository import IntegrationRepository from database.repositories.material_repository import MaterialRepository @@ -49,6 +51,33 @@ def list_integration_logs( return handle_request(ctx, action) +def get_private_companion_token_status( + ctx: RequestContext, + service: IntegrationTokenService | None = None, +) -> dict: + token_service = service or _create_token_service() + + def action() -> dict[str, Any]: + require_config_manager(ctx) + return token_service.status() + + return handle_request(ctx, action) + + +def rotate_private_companion_token( + ctx: RequestContext, + payload: dict[str, Any] | None = None, + service: IntegrationTokenService | None = None, +) -> dict: + token_service = service or _create_token_service() + + def action() -> dict[str, Any]: + require_config_manager(ctx) + return token_service.rotate(payload or {}, ctx) + + return handle_request(ctx, action) + + def _create_integration_service() -> IntegrationService: database = Database(load_database_settings()) audit_service = AuditService(database) @@ -61,4 +90,10 @@ def _create_integration_service() -> IntegrationService: return IntegrationService( wardrobe_service=wardrobe_service, integration_repository=IntegrationRepository(database), + token_service=IntegrationTokenService(audit_service=audit_service), ) + + +def _create_token_service() -> IntegrationTokenService: + database = Database(load_database_settings()) + return IntegrationTokenService(ConfigService(), audit_service=AuditService(database)) diff --git a/backend/services/integration_service.py b/backend/services/integration_service.py index ed4aca8..a3521a4 100644 --- a/backend/services/integration_service.py +++ b/backend/services/integration_service.py @@ -6,8 +6,10 @@ from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode +from backend.services.integration_token_service import IntegrationTokenService from backend.services.wardrobe_service import WardrobeService from core.identity import RequestContext +from core.secret_service import redact from database.repositories.integration_repository import IntegrationRepository @@ -19,9 +21,11 @@ class IntegrationService: self, wardrobe_service: WardrobeService, integration_repository: IntegrationRepository, + token_service: IntegrationTokenService | None = None, ): self.wardrobe_service = wardrobe_service self.integration_repository = integration_repository + self.token_service = token_service def daily_outfit(self, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]: source = str(payload.get("request_source") or PRIVATE_COMPANION) @@ -33,6 +37,12 @@ class IntegrationService: ) self._record_failure(source, payload, error) raise error + if self.token_service: + try: + self.token_service.verify(source, _request_token(payload)) + except ApiError as exc: + self._record_failure(source, payload, exc) + raise profile_id = str(payload.get("profile_id") or "").strip() if not profile_id: error = ApiError(ErrorCode.VALIDATION_FAILED, "profile_id is required", {"field": "profile_id"}) @@ -64,7 +74,7 @@ class IntegrationService: "integration_name": source, "action": "daily_outfit", "status": "succeeded", - "request": payload, + "request": _redact_request(payload), "response": response, } ) @@ -90,7 +100,7 @@ class IntegrationService: "integration_name": source, "action": "daily_outfit", "status": "failed", - "request": payload, + "request": _redact_request(payload), "response": {"error_code": _error_code(exc)}, "error_message": str(getattr(exc, "message", None) or exc), } @@ -118,6 +128,14 @@ def _wardrobe_match_payload(payload: dict[str, Any], categories: list[str]) -> d return match_payload +def _request_token(payload: dict[str, Any]) -> str | None: + return str(payload.get("integration_token") or payload.get("token") or "").strip() or None + + +def _redact_request(payload: dict[str, Any]) -> dict[str, Any]: + return redact(payload) + + def _fallback_prompt(payload: dict[str, Any]) -> str: parts = ["daily outfit"] for key in ("mood", "weather"): diff --git a/backend/services/integration_token_service.py b/backend/services/integration_token_service.py new file mode 100644 index 0000000..e09d333 --- /dev/null +++ b/backend/services/integration_token_service.py @@ -0,0 +1,198 @@ +"""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:]}" diff --git a/tests/test_integration_service.py b/tests/test_integration_service.py index 2afa8d1..22da705 100644 --- a/tests/test_integration_service.py +++ b/tests/test_integration_service.py @@ -6,10 +6,12 @@ from pathlib import Path from backend.routes.integration_routes import list_integration_logs, private_companion_daily_outfit from backend.services.integration_service import IntegrationService +from backend.services.integration_token_service import IntegrationTokenService from backend.services.material_service import MaterialService from backend.services.profile_service import ProfileService from backend.services.wardrobe_service import WardrobeService from core.audit_service import AuditService +from core.config_service import ConfigService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, SqliteSettings from database.repositories.integration_repository import IntegrationRepository @@ -119,6 +121,47 @@ class IntegrationServiceTests(unittest.TestCase): self.assertIn("white blouse", response["final_prompt"]) self.assertIn("matching shoes", response["final_prompt"]) + def test_daily_outfit_requires_configured_token_and_redacts_logs(self): + token_config = self.tmp.name and Path(self.tmp.name) / "token_config.yaml" + token_config.write_text( + """ +security: + allowed_integration_plugins: + - astrbot_plugin_private_companion +""", + encoding="utf-8", + ) + token_service = IntegrationTokenService(ConfigService(token_config)) + token_service.rotate({"token": "daily-token-value"}, self.ctx) + service = IntegrationService(self.wardrobe_service, self.integration_repository, token_service) + + with self.assertRaises(Exception): + service.daily_outfit( + { + "profile_id": self.profile.profile_id, + "categories": ["top"], + "integration_token": "wrong-token-value", + }, + self.ctx, + ) + + failed_logs = service.list_integration_logs(status="failed") + self.assertEqual(failed_logs[0]["response"]["error_code"], "INTEGRATION_TOKEN_INVALID") + self.assertEqual(failed_logs[0]["request"]["integration_token"], "***MASKED***") + + response = service.daily_outfit( + { + "profile_id": self.profile.profile_id, + "categories": ["top"], + "integration_token": "daily-token-value", + }, + self.ctx, + ) + + self.assertTrue(response["matched"]) + succeeded_logs = service.list_integration_logs(status="succeeded") + self.assertEqual(succeeded_logs[0]["request"]["integration_token"], "***MASKED***") + def test_integration_routes_wrap_responses(self): response = private_companion_daily_outfit( self.ctx, diff --git a/tests/test_integration_token_service.py b/tests/test_integration_token_service.py new file mode 100644 index 0000000..9bbbf79 --- /dev/null +++ b/tests/test_integration_token_service.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from backend.dto.common import ApiError, ErrorCode +from backend.routes.integration_routes import get_private_companion_token_status, rotate_private_companion_token +from backend.services.integration_token_service import IntegrationTokenService +from core.audit_service import AuditService +from core.config_service import ConfigService +from core.identity import RequestContext +from database.db_helper import Database, DatabaseSettings, SqliteSettings + + +class IntegrationTokenServiceTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.config_path = self.root / "config.yaml" + self.config_path.write_text( + """ +security: + allowed_integration_plugins: + - astrbot_plugin_private_companion +""", + encoding="utf-8", + ) + self.database = Database( + DatabaseSettings(sqlite=SqliteSettings(path=str(self.root / "imagestudio.db"))) + ) + self.database.initialize() + self.audit_service = AuditService(self.database) + self.service = IntegrationTokenService(ConfigService(self.config_path), audit_service=self.audit_service) + self.ctx = RequestContext.from_astrbot( + username="admin", + user_id="user_001", + permissions={"can_manage_config"}, + ) + + def tearDown(self): + self.tmp.cleanup() + + def test_rotate_hashes_token_and_accepts_previous_during_grace(self): + first = self.service.rotate({"token": "first-token-value", "grace_seconds": 3600}, self.ctx) + second = self.service.rotate({"token": "second-token-value", "grace_seconds": 3600}, self.ctx) + + self.assertEqual(first["token"], "first-token-value") + self.assertEqual(second["token_preview"], "seco...alue") + self.assertTrue(self.service.status()["integration_token_set"]) + self.assertTrue(self.service.status()["previous_token_set"]) + self.assertEqual( + self.service.verify("astrbot_plugin_private_companion", "second-token-value")["token_slot"], + "current", + ) + self.assertEqual( + self.service.verify("astrbot_plugin_private_companion", "first-token-value")["token_slot"], + "previous", + ) + config_text = self.config_path.read_text(encoding="utf-8") + self.assertNotIn("first-token-value", config_text) + self.assertNotIn("second-token-value", config_text) + + def test_verify_rejects_missing_or_bad_token_when_configured(self): + self.service.rotate({"token": "first-token-value"}, self.ctx) + + for token in (None, "bad-token-value"): + with self.assertRaises(ApiError) as raised: + self.service.verify("astrbot_plugin_private_companion", token) + self.assertEqual(raised.exception.error_code, ErrorCode.INTEGRATION_TOKEN_INVALID) + + def test_verify_is_optional_until_token_is_configured(self): + self.assertFalse(self.service.status()["integration_token_set"]) + result = self.service.verify("astrbot_plugin_private_companion", None) + self.assertFalse(result["required"]) + + def test_token_routes_require_config_permission_and_return_token_once(self): + rotated = rotate_private_companion_token( + self.ctx, + {"token": "route-token-value"}, + self.service, + ) + self.assertTrue(rotated["ok"]) + self.assertEqual(rotated["data"]["token"], "route-token-value") + self.assertTrue(rotated["data"]["status"]["integration_token_set"]) + + status = get_private_companion_token_status(self.ctx, self.service) + self.assertTrue(status["ok"]) + self.assertNotIn("route-token-value", str(status["data"])) + + read_only = RequestContext.from_astrbot(username="viewer", user_id="viewer_001") + denied = rotate_private_companion_token(read_only, {"token": "another-token-value"}, self.service) + self.assertFalse(denied["ok"]) + self.assertEqual(denied["error_code"], "FORBIDDEN") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_route_registry.py b/tests/test_route_registry.py index 770f986..4ba73c8 100644 --- a/tests/test_route_registry.py +++ b/tests/test_route_registry.py @@ -33,6 +33,8 @@ class RouteRegistryTests(unittest.TestCase): self.assertIn(("GET", "materials/{material_id}"), keys) self.assertIn(("DELETE", "profiles/{profile_id}/wardrobe/{wardrobe_item_id}"), keys) self.assertIn(("DELETE", "profiles/{profile_id}/wardrobe/items/{wardrobe_item_id}"), keys) + self.assertIn(("GET", "integrations/private-companion/token"), keys) + self.assertIn(("POST", "integrations/private-companion/token/rotate"), keys) self.assertIn(("GET", "integrations/logs"), keys) self.assertIn(("POST", "workflows/{workflow_id}/start"), keys) self.assertIn(("POST", "workflows/{workflow_id}/cancel"), keys)