diff --git a/backend/route_registry.py b/backend/route_registry.py index 99090b8..c4e9910 100644 --- a/backend/route_registry.py +++ b/backend/route_registry.py @@ -108,6 +108,7 @@ ROUTES: tuple[RouteSpec, ...] = ( RouteSpec("POST", "materials/{material_id}/recognize", "backend.routes.material_routes.recognize_material", "materials"), RouteSpec("POST", "materials/{material_id}/re-recognize", "backend.routes.material_routes.re_recognize_material", "materials"), RouteSpec("POST", "materials/{material_id}/confirm", "backend.routes.material_routes.confirm_material", "materials"), + RouteSpec("POST", "assets/import-pack", "backend.routes.asset_routes.import_asset_pack", "materials"), RouteSpec("GET", "profiles/{profile_id}/wardrobe", "backend.routes.wardrobe_routes.list_wardrobe_items", "read"), RouteSpec("POST", "profiles/{profile_id}/wardrobe/import-material", "backend.routes.wardrobe_routes.import_wardrobe_material", "materials"), RouteSpec("POST", "profiles/{profile_id}/wardrobe/items", "backend.routes.wardrobe_routes.import_wardrobe_material", "materials"), diff --git a/backend/routes/asset_routes.py b/backend/routes/asset_routes.py new file mode 100644 index 0000000..9a98bb0 --- /dev/null +++ b/backend/routes/asset_routes.py @@ -0,0 +1,36 @@ +"""Asset import route handlers.""" + +from __future__ import annotations + +from typing import Any + +from backend.dto.common import ApiError, ErrorCode +from backend.routes.common import handle_request +from backend.services.asset_import_service import AssetImportService +from core.identity import RequestContext +from core.security import require_permission + + +def import_asset_pack( + ctx: RequestContext, + payload: dict[str, Any], + service: AssetImportService | None = None, +) -> dict: + asset_service = service or AssetImportService() + + def action() -> dict[str, Any]: + require_permission(ctx, "can_manage_materials") + package_uri = str(payload.get("package_uri") or "").strip() + if not package_uri: + raise ApiError(ErrorCode.VALIDATION_FAILED, "package_uri is required", {"field": "package_uri"}) + return asset_service.plan_import_pack(package_uri, dry_run=_as_bool(payload.get("dry_run"), default=True)) + + return handle_request(ctx, action) + + +def _as_bool(value: Any, *, default: bool = False) -> bool: + if value is None: + return default + if isinstance(value, bool): + return value + return str(value).strip().lower() in {"1", "true", "yes", "on"} diff --git a/backend/services/asset_import_service.py b/backend/services/asset_import_service.py new file mode 100644 index 0000000..2280114 --- /dev/null +++ b/backend/services/asset_import_service.py @@ -0,0 +1,71 @@ +"""Dry-run planning for ImageStudio asset pack imports.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from backend.dto.common import ApiError, ErrorCode +from core.config_service import ConfigService +from core.storage import VfsStorage + + +_MANIFEST_FILENAMES = {"manifest.json", "imagestudio-pack.json", "pack.json"} + + +class AssetImportService: + def __init__(self, config_service: ConfigService | None = None): + self.storage = VfsStorage(config_service) + + def plan_import_pack(self, package_uri: str, *, dry_run: bool = True) -> dict[str, Any]: + if not dry_run: + raise ApiError( + ErrorCode.VALIDATION_FAILED, + "asset pack import execution is not enabled; run with dry_run=true", + {"field": "dry_run"}, + ) + + root, relative = self.storage.split_uri(package_uri) + package_path = self.storage.resolve_uri(package_uri) + if not package_path.exists(): + raise ApiError(ErrorCode.MEDIA_NOT_FOUND, "asset pack not found", {"uri": package_uri}) + + files, total_bytes = _path_file_stats(package_path) + return { + "dry_run": True, + "status": "planned", + "package_uri": package_uri, + "files": files, + "bytes": total_bytes, + "manifest_candidates": _manifest_candidates(root, relative, package_path), + "import_enabled": False, + "execution_enabled": False, + } + + +def _manifest_candidates(root: str, relative: Path, package_path: Path) -> list[str]: + if package_path.is_file(): + return [_storage_uri(root, relative)] if package_path.name in _MANIFEST_FILENAMES else [] + + candidates: list[str] = [] + for child in package_path.rglob("*"): + if child.is_file() and child.name in _MANIFEST_FILENAMES: + child_relative = relative / child.relative_to(package_path) + candidates.append(_storage_uri(root, child_relative)) + return sorted(candidates) + + +def _storage_uri(root: str, relative: Path) -> str: + return f"storage://{root}/{relative.as_posix()}" + + +def _path_file_stats(path: Path) -> tuple[int, int]: + if path.is_file(): + return 1, path.stat().st_size + files = 0 + total = 0 + for child in path.rglob("*"): + if child.is_file(): + files += 1 + total += child.stat().st_size + return files, total diff --git a/tests/test_route_registry.py b/tests/test_route_registry.py index 7827531..a956f5d 100644 --- a/tests/test_route_registry.py +++ b/tests/test_route_registry.py @@ -31,6 +31,7 @@ class RouteRegistryTests(unittest.TestCase): self.assertIn(("POST", "nodes/{node_id}/complete"), keys) self.assertIn(("POST", "nodes/{node_id}/mark-completed"), keys) self.assertIn(("POST", "materials/{material_id}/re-recognize"), keys) + self.assertIn(("POST", "assets/import-pack"), keys) self.assertIn(("POST", "profiles/{profile_id}/archive"), keys) self.assertIn(("POST", "profiles/{profile_id}/wardrobe/items"), keys) self.assertIn(("GET", "settings/snapshots"), keys) diff --git a/tests/test_s2_routes.py b/tests/test_s2_routes.py index da7ca43..1291e03 100644 --- a/tests/test_s2_routes.py +++ b/tests/test_s2_routes.py @@ -4,6 +4,7 @@ import tempfile import unittest from pathlib import Path +from backend.routes.asset_routes import import_asset_pack from backend.routes.dashboard_routes import get_dashboard_summary from backend.routes.branch_routes import create_workflow_branch, list_workflow_branches, switch_workflow_branch from backend.routes.image_routes import ( @@ -62,6 +63,7 @@ from backend.routes.workflow_routes import ( list_profile_workflows, start_workflow, ) +from backend.services.asset_import_service import AssetImportService from backend.services.dashboard_service import DashboardService from backend.services.image_service import ImageService from backend.services.media_service import MediaService @@ -146,6 +148,7 @@ storage: ) self.settings_service = SettingsService(self.config_service, audit_service=self.audit_service) self.media_service = MediaService(self.config_service) + self.asset_import_service = AssetImportService(self.config_service) self.web_hosting_service = WebHostingService() self.ctx = RequestContext.from_astrbot( username="admin", @@ -650,6 +653,41 @@ database: self.assertFalse(execution["ok"]) self.assertEqual(execution["error_code"], "VALIDATION_FAILED") + def test_asset_import_pack_dry_run_is_safe(self): + pack = self.root / "materials" / "pack" + pack.mkdir(parents=True, exist_ok=True) + (pack / "manifest.json").write_text('{"name":"demo"}', encoding="utf-8") + (pack / "image.bin").write_bytes(b"123") + + planned = import_asset_pack( + self.ctx, + {"package_uri": "storage://materials/pack", "dry_run": True}, + self.asset_import_service, + ) + + self.assertTrue(planned["ok"]) + self.assertTrue(planned["data"]["dry_run"]) + self.assertEqual(planned["data"]["files"], 2) + self.assertIn("storage://materials/pack/manifest.json", planned["data"]["manifest_candidates"]) + self.assertFalse(planned["data"]["import_enabled"]) + self.assertNotIn(str(self.root), str(planned["data"])) + + execution = import_asset_pack( + self.ctx, + {"package_uri": "storage://materials/pack", "dry_run": False}, + self.asset_import_service, + ) + self.assertFalse(execution["ok"]) + self.assertEqual(execution["error_code"], "VALIDATION_FAILED") + + unsafe = import_asset_pack( + self.ctx, + {"package_uri": str(pack)}, + self.asset_import_service, + ) + self.assertFalse(unsafe["ok"]) + self.assertEqual(unsafe["error_code"], "VALIDATION_FAILED") + def test_media_signing_rejects_unsafe_or_missing_uri(self): unsafe = sign_media( self.ctx,