cmvr-visual/backend/tests/test_shared_assets.py

243 lines
15 KiB
Python
Raw Normal View History

from datetime import timedelta
import httpx
from app.models import Asset, utcnow
from app.retention import collect_garbage
async def upload(client, png_bytes, name="reference.png"):
result = await client.post("/api/assets", files={"file": (name, png_bytes, "image/png")})
assert result.status_code == 201, result.text
return result.json()
async def publish(client, asset_id, **kwargs):
result = await client.post(f"/api/assets/{asset_id}/publish", **kwargs)
assert result.status_code == 201, result.text
return result.json()
async def test_publication_snapshot_and_import_have_independent_files(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
await system.client.patch(f"/api/assets/{source['id']}", json={"tags": ["reference"]})
shared = await publish(system.client, source["id"])
assert shared["is_owner"] is True
assert not {"source_asset_id", "asset_id", "source_job_id", "storage_key"} & shared.keys()
assert (await publish(system.client, source["id"]))["id"] == shared["id"]
await system.client.patch(f"/api/assets/{source['id']}", json={"name": "renamed.png", "tags": []})
visible = (await other_client.get("/api/shared-assets?tag=reference&q=reference&kind=image")).json()
assert visible["total"] == 1 and visible["items"][0]["name"] == "reference.png"
assert visible["items"][0]["is_owner"] is False
assert (await other_client.get("/api/shared-assets?mine=true")).json()["total"] == 0
imported = await other_client.post(f"/api/shared-assets/{shared['id']}/import")
assert imported.status_code == 201, imported.text
imported = imported.json()
assert imported["origin"] == "shared" and imported["source_job_id"] is None
assert imported["tags"] == ["reference"] and imported["id"] != source["id"]
from app.v2_models import SharedAsset
async with system.app.state.db.session() as session:
publication = await session.get(SharedAsset, shared["id"])
original = await session.get(Asset, source["id"])
snapshot = await session.get(Asset, publication.asset_id)
private = await session.get(Asset, imported["id"])
paths = [system.settings.asset_root / a.storage_key for a in (original, snapshot, private)]
thumbs = [system.settings.asset_root / a.thumbnail_key for a in (original, snapshot, private)]
assert len(set(paths)) == len(set(thumbs)) == 3
assert snapshot.library_scope == "shared" and private.library_scope == "private"
snapshot_thumbnail = thumbs[1].read_bytes()
paths[0].write_bytes(b"changed after publication")
thumbs[0].write_bytes(b"changed thumbnail")
assert (await other_client.get(shared["preview_url"])).content == png_bytes
assert (await other_client.get(shared["thumbnail_url"])).content == snapshot_thumbnail
assert (await system.client.get("/api/assets")).json()["total"] == 1
for client in (system.client, other_client):
for suffix in ("", "/content", "/thumbnail"):
assert (await client.get(f"/api/assets/{publication.asset_id}{suffix}")).status_code == 404
assert (await system.client.delete(f"/api/assets/{source['id']}")).status_code == 204
paths[0].unlink()
thumbs[0].unlink()
assert (await other_client.get(shared["preview_url"])).content == png_bytes
assert (await other_client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404
assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204
assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204
assert (await other_client.get(shared["preview_url"])).status_code == 404
assert (await other_client.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 404
paths[1].unlink()
thumbs[1].unlink()
assert (await other_client.get(imported["preview_url"])).content == png_bytes
assert (await other_client.get(imported["thumbnail_url"])).status_code == 200
accepted = await other_client.post("/api/jobs", json={"task_type": "defect.generate",
"input": {"prompt": "scratch", "image_asset_id": imported["id"]}})
assert accepted.status_code == 202, accepted.text
async def test_shared_assets_require_auth_and_reject_private_ids_for_jobs(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
shared = await publish(system.client, source["id"])
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as anonymous:
for path in ("/api/shared-assets", shared["preview_url"], shared["thumbnail_url"]):
assert (await anonymous.get(path)).status_code == 401
assert (await anonymous.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 401
assert (await other_client.post(f"/api/assets/{source['id']}/publish")).status_code == 404
from app.v2_models import SharedAsset
async with system.app.state.db.session() as session:
hidden_id = (await session.get(SharedAsset, shared["id"])).asset_id
for client, asset_id in ((other_client, source["id"]), (other_client, shared["id"]),
(other_client, hidden_id), (system.client, hidden_id)):
result = await client.post("/api/jobs", json={"task_type": "defect.generate",
"input": {"prompt": "scratch", "image_asset_id": asset_id}})
assert result.status_code == 404, result.text
ranged = await other_client.get(shared["preview_url"], headers={"Range": "bytes=0-7"})
assert ranged.status_code == 206 and ranged.content == png_bytes[:8]
assert ranged.headers["cache-control"] == "private, no-store"
token = (await other_client.post("/api/auth/tokens", json={"name": "reader", "scopes": ["assets:read"]})).json()["token"]
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test",
headers={"Authorization": "Bearer " + token}) as machine:
assert (await machine.get(shared["preview_url"])).content == png_bytes
assert (await machine.post(f"/api/shared-assets/{shared['id']}/import")).status_code == 403
async def test_copy_quota_failure_does_not_create_assets_or_files(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
system.settings.max_owner_asset_bytes = len(png_bytes)
before = set(system.settings.asset_root.rglob("original*"))
result = await system.client.post(f"/api/assets/{source['id']}/publish")
assert result.status_code == 429, result.text
assert (await other_client.get("/api/shared-assets")).json()["total"] == 0
assert set(system.settings.asset_root.rglob("original*")) == before
system.settings.max_owner_asset_bytes = len(png_bytes) * 3
shared = await publish(system.client, source["id"])
system.settings.max_owner_asset_bytes = len(png_bytes) - 1
before = set(system.settings.asset_root.rglob("original*"))
result = await other_client.post(f"/api/shared-assets/{shared['id']}/import")
assert result.status_code == 429, result.text
assert (await other_client.get("/api/assets")).json()["total"] == 0
assert set(system.settings.asset_root.rglob("original*")) == before
async def test_copy_idempotency_preserves_original_result_and_rejects_path_payloads(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
published = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"})
assert (await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"}))["id"] == published["id"]
another = await upload(system.client, png_bytes, "another.png")
assert (await system.client.post(f"/api/assets/{another['id']}/publish", headers={"Idempotency-Key": "publication"})).status_code == 409
headers = {"Idempotency-Key": "import"}
first = await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers)
assert first.status_code == 201, first.text
assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers)).json()["id"] == first.json()["id"]
assert (await other_client.get("/api/assets")).json()["total"] == 1
assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", json={"path": "../../outside"})).status_code == 422
assert (await system.client.post(f"/api/assets/{another['id']}/publish", json={"storage_key": "/etc/passwd"})).status_code == 422
await other_client.delete(f"/api/assets/{first.json()['id']}")
assert (await other_client.post(f"/api/shared-assets/{published['id']}/import", headers=headers)).status_code == 410
await system.client.delete(f"/api/shared-assets/{published['id']}")
assert (await system.client.post(f"/api/assets/{source['id']}/publish", headers={"Idempotency-Key": "publication"})).status_code == 410
async def test_import_replay_survives_withdrawal_but_fresh_import_does_not(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
shared = await publish(system.client, source["id"])
path = f"/api/shared-assets/{shared['id']}/import"
first = await other_client.post(path, headers={"Idempotency-Key": "independent-import"})
assert first.status_code == 201, first.text
await system.client.delete(f"/api/shared-assets/{shared['id']}")
replay = await other_client.post(path, headers={"Idempotency-Key": "independent-import"})
assert replay.status_code == 201 and replay.json()["id"] == first.json()["id"]
assert (await other_client.post(path)).status_code == 404
async def test_private_deletion_purges_import_recovery_and_preserves_publication_recovery(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
shared = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication"})
imported = await other_client.post(f"/api/shared-assets/{shared['id']}/import",
headers={"Idempotency-Key": "import"})
assert imported.status_code == 201, imported.text
publication_recovery = "/api/submissions/publication?operation=assets.publish"
import_recovery = "/api/submissions/import?operation=shared.import"
assert (await system.client.delete(f"/api/assets/{source['id']}")).status_code == 204
publication = await system.client.get(publication_recovery)
assert publication.status_code == 200 and publication.json()["status"] == "accepted"
assert publication.json()["shared_asset_id"] == shared["id"]
assert (await other_client.get(import_recovery)).json()["asset_id"] == imported.json()["id"]
assert (await other_client.delete(f"/api/assets/{imported.json()['id']}")).status_code == 204
assert (await other_client.get(import_recovery)).status_code == 410
assert (await system.client.get(publication_recovery)).status_code == 200
assert (await other_client.get(shared["preview_url"])).content == png_bytes
async def test_withdrawal_purges_all_publication_keys_and_preserves_independent_import_recovery(system, other_client, png_bytes):
source = await upload(system.client, png_bytes)
shared = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication-a"})
same = await publish(system.client, source["id"], headers={"Idempotency-Key": "publication-b"})
assert same["id"] == shared["id"]
imported = await other_client.post(f"/api/shared-assets/{shared['id']}/import",
headers={"Idempotency-Key": "independent-import"})
assert imported.status_code == 201, imported.text
own_import = await system.client.post(f"/api/shared-assets/{shared['id']}/import",
headers={"Idempotency-Key": "own-import"})
assert own_import.status_code == 201, own_import.text
assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 204
for key in ("publication-a", "publication-b"):
assert (await system.client.get(f"/api/submissions/{key}?operation=assets.publish")).status_code == 410
for client, key, asset in ((other_client, "independent-import", imported.json()),
(system.client, "own-import", own_import.json())):
recovery = await client.get(f"/api/submissions/{key}?operation=shared.import")
assert recovery.status_code == 200 and recovery.json()["status"] == "accepted"
assert recovery.json()["asset_id"] == asset["id"]
assert (await client.get(asset["preview_url"])).content == png_bytes
async def test_retention_protects_active_publications_even_without_reference_row(system, png_bytes):
source = await upload(system.client, png_bytes)
shared = await publish(system.client, source["id"])
from sqlalchemy import delete
from app.v2_models import AssetReference, SharedAsset
async with system.app.state.db.session() as session:
publication = await session.get(SharedAsset, shared["id"])
snapshot = await session.get(Asset, publication.asset_id)
snapshot.deleted_at = utcnow() - timedelta(days=30)
await session.execute(delete(AssetReference).where(AssetReference.asset_id == snapshot.id))
await session.commit()
assert snapshot.id in (await collect_garbage(system.app.state.db, system.settings))["protected"]
async def test_forged_source_storage_path_is_not_copied(system, png_bytes, tmp_path):
source = await upload(system.client, png_bytes)
outside = tmp_path / "outside.png"
outside.write_bytes(png_bytes)
async with system.app.state.db.session() as session:
original = await session.get(Asset, source["id"])
original.storage_key = str(outside)
await session.commit()
result = await system.client.post(f"/api/assets/{source['id']}/publish")
assert result.status_code == 404, result.text
assert (await system.client.get("/api/shared-assets")).json()["total"] == 0
async def test_physical_gc_releases_quota_only_after_files_are_removed(system, png_bytes):
response = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")})
assert response.status_code == 201, response.text
asset_id = response.json()["id"]
system.settings.max_owner_asset_bytes = int(response.request.headers["content-length"])
await system.client.delete(f"/api/assets/{asset_id}")
async with system.app.state.db.session() as session:
asset = await session.get(Asset, asset_id)
asset.deleted_at = utcnow() - timedelta(days=30)
original = system.settings.asset_root / asset.storage_key
await session.commit()
assert asset_id in (await collect_garbage(system.app.state.db, system.settings))["candidates"]
blocked = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")})
assert blocked.status_code == 429, blocked.text
assert original.exists()
maintenance = system.settings.state_root / "maintenance"
maintenance.write_text("test", encoding="utf-8")
try:
report = await collect_garbage(system.app.state.db, system.settings, dry_run=False)
finally:
maintenance.unlink()
assert asset_id in report["deleted"] and not original.exists()
async with system.app.state.db.session() as session:
assert (await session.get(Asset, asset_id)).ready is False
retry = await system.client.post("/api/assets", files={"file": ("reference.png", png_bytes, "image/png")})
assert retry.status_code == 201, retry.text