test: integracja skilli — agenci, T2 eksportu, import w obie strony, złośliwy ZIP, zamrożone wersje (E2.6, 5.2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tobayah
2026-11-06 02:11:01 +01:00
co-authored by Claude Opus 5.5
parent 4330c13499
commit dac401c47f
3 changed files with 158 additions and 2 deletions
+1 -1
View File
@@ -25,7 +25,7 @@
## Etap 5: testy integracyjne (E2.6)
- [x] 5.1 Napisz `backend/tests/test_skills_integration.py` wzorem `test_providers_integration.py` (pomijany bez `ATRIUM_RUN_INTEGRATION=1`): macierz widoczności (właściciel / inna osoba / administrator × osobisty / firmowy, cudze osobiste = 404), nowa wersja firmowa niewidoczna przed zgodą, przełączenie `skills_firm_publish` na `direct` przez administratora, wiersze audytu po zapisach. Gotowe gdy: bramka zielona, a `pytest --collect-only tests/test_skills_integration.py` zbiera testy bez błędów.
- [ ] 5.2 Dopisz do `test_skills_integration.py`: agent firmowy z osobistym skillem odrzucony, T2 dla eksportu skilla i agenta (osoba bez uprawnień vs administrator vs `everyone`), import → eksport → import daje tę samą sumę, import złośliwego ZIP-a zwraca Problem Details z `code`, rola runtime dostaje błąd z bazy przy UPDATE na `skill_version`. Gotowe gdy: bramka zielona i nowe testy są zbierane przez pytest bez błędów.
- [x] 5.2 Dopisz do `test_skills_integration.py`: agent firmowy z osobistym skillem odrzucony, T2 dla eksportu skilla i agenta (osoba bez uprawnień vs administrator vs `everyone`), import → eksport → import daje tę samą sumę, import złośliwego ZIP-a zwraca Problem Details z `code`, rola runtime dostaje błąd z bazy przy UPDATE na `skill_version`. Gotowe gdy: bramka zielona i nowe testy są zbierane przez pytest bez błędów.
## Etap 6: konsola (E3)
- [ ] 6.1 W `frontend/app.js` dodaj pozycję „Skille i agenci / Skills and agents” w głównym menu obok „Połączone aplikacje” oraz widok listy z zakładkami Moje / Firmy (skille i agenci osobno), z PL/EN, przez `esc()`, API z `document.baseURI`. Gotowe gdy: `node --check frontend/app.js` i bramka zielone, a pozycja menu prowadzi do widoku listy.
+1
View File
@@ -29,3 +29,4 @@
- Brak trasy `GET /agents/{id}/versions/{n}` — serwis jej nie ma (`get_agent` daje listę wersji + aktualną w całości); dołożyć przy 6.3, jeśli edytor agenta będzie potrzebował diffu starszych wersji.
- 5.1: `tests/test_skills_integration.py` (7 testów) — macierz widoczności (cudze osobiste = 404 dla innej osoby i administratora na każdej trasie), firmowy: odczyt wszyscy, zapis inny = 403; v2 firmowa niewidoczna do zgody (+ `base` w kolejce, podwójna prośba 409), odrzucenie, `direct` (tylko administrator przełącza, audyt `publish_approve` „direct”), audyt każdego zapisu (archiwizacja idempotentna). Odpalone na postgres:17 w Dockerze jak job `backend` CI — całość zielona.
- Jak odpalić integrację lokalnie: kontener postgres:17 na 55432, role jak w ci.yml, `alembic upgrade head && python -m app.identity_grants && python -m app.seed`, env DATABASE_URL/MIGRATION_DATABASE_URL/BOOTSTRAP_ADMIN_*. Docker Desktop trzeba wystartować.
- 5.2: 9 nowych testów w `test_skills_integration.py` — agent firmowy z osobistym skillem = 422 `agent_pin_refused` (przy publikacji i przy nowej wersji już firmowego), T2 eksportu skilla i agenta (agent osobisty z firmowym skillem: autor 403 pod `administrator`, administrator 404 na cudzym osobistym), import→eksport→import u innej osoby = ta sama suma, u siebie = `duplicate`, złośliwy ZIP (`pack_bad_path`, `pack_file_type`, `pack_not_zip`) = Problem Details bez zapisu, UPDATE/DELETE na `skill_version` jako rola runtime = permission denied. Odpalone na postgres:17 w Dockerze — całość zielona (poza wiszącym lokalnie `test_deploy_init_add.py`).
+156 -1
View File
@@ -3,17 +3,24 @@
Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. Who sees what is decided in
`services/skills.py` (skills are not org-tree nodes), so this suite pins that rule end to end: the
visibility matrix, a firm skill's next version staying invisible until an administrator approves
it, the `skills_firm_publish` switch, and the audit rows every write leaves.
it, the `skills_firm_publish` switch, and the audit rows every write leaves. Then agents (a firm
agent never pins a personal skill), T2 on export (`skills_firm_export`, for a skill and for an agent
with everything it pins), import round trips keeping one content sum, a malicious pack answered as
Problem Details with a `code`, and the database itself refusing to rewrite a frozen version.
Skills are never deleted (only archived), so every slug is suffixed per run, and every setting is
put back exactly as it was found (`settings_set`).
"""
from __future__ import annotations
import io
import uuid
import zipfile
import pytest
from conftest import bearer, integration, settings_set
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
pytestmark = integration
@@ -219,3 +226,151 @@ def test_every_write_leaves_one_audit_row(admin_client, client, owner):
version_row = _audit(admin_client, "skill.version", sid)[0]
assert version_row["detail"] == f"{skill['slug']} v2 {v2['content_sha256']}"
assert "# Two" not in str(_audit(admin_client, "skill.", sid))
# ── agents ────────────────────────────────────────────────────────────────────
AGENTS = "/api/v1/agents"
def _agent(client, headers, pins: list[str]) -> dict:
r = client.post(AGENTS, json={"name": f"Asystent {RUN}", "instructions": "Pomagaj.",
"skill_version_ids": pins}, headers=headers)
assert r.status_code == 201, r.text
return r.json()
def _current_version_id(api, sid: str, headers=None) -> str:
return api.get(f"{SKILLS}/{sid}", headers=headers).json()["current"]["id"]
def test_a_firm_agent_never_carries_a_personal_skill(admin_client, client, owner, firm_skill):
me = bearer(owner["token"])
personal = _create(client, me)
agent = _agent(client, me, [_current_version_id(client, personal["id"], me)])
with settings_set(admin_client, skills_firm_publish="direct"):
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=me)
assert r.status_code == 422, r.text
assert r.headers["content-type"].startswith("application/problem+json")
assert r.json()["code"] == "agent_pin_refused"
assert client.get(f"{AGENTS}/{agent['id']}", headers=me).json()["scope"] == "personal"
# Repinned to the firm's published version, the same agent goes through.
firm_pin = _current_version_id(client, firm_skill["id"], me)
r = client.post(f"{AGENTS}/{agent['id']}/versions",
json={"skill_version_ids": [firm_pin]}, headers=me)
assert r.status_code == 201, r.text
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=me)
assert r.status_code == 200 and r.json()["agent"]["scope"] == "firm", r.text
# Once firm, a new version may not bring a personal skill back in either.
r = client.post(f"{AGENTS}/{agent['id']}/versions",
json={"skill_version_ids": [_current_version_id(client, personal["id"], me)]},
headers=me)
assert r.status_code == 422 and r.json()["code"] == "agent_pin_refused", r.text
# ── T2: who may export ────────────────────────────────────────────────────────
def test_exporting_a_firm_skill_follows_the_t2_setting(admin_client, client, owner, other,
firm_skill):
path = f"{SKILLS}/{firm_skill['id']}/export"
with settings_set(admin_client, skills_firm_export="administrator"):
assert client.get(path, headers=bearer(other["token"])).status_code == 403
r = client.get(path, headers=bearer(owner["token"])) # one's own: always
assert r.status_code == 200 and r.headers["content-type"] == "application/zip"
assert admin_client.get(path).status_code == 200
with settings_set(admin_client, skills_firm_export="everyone"):
r = client.get(path, headers=bearer(other["token"]))
assert r.status_code == 200 and r.content[:2] == b"PK"
def test_exporting_an_agent_follows_t2_for_the_agent_and_every_pinned_skill(
admin_client, client, owner, other, firm_skill):
# The other person's own agent, pinning the owner's firm skill: theirs, but not all theirs.
mine = bearer(other["token"])
agent = _agent(client, mine, [_current_version_id(client, firm_skill["id"], mine)])
path = f"{AGENTS}/{agent['id']}/export"
with settings_set(admin_client, skills_firm_export="administrator"):
assert client.get(path, headers=mine).status_code == 403
assert admin_client.get(path).status_code == 404 # somebody's personal agent
with settings_set(admin_client, skills_firm_export="everyone"):
r = client.get(path, headers=mine)
assert r.status_code == 200 and r.headers["content-type"] == "application/zip", r.text
# A firm agent: an administrator always, anybody else only under `everyone`.
with settings_set(admin_client, skills_firm_publish="direct"):
r = client.post(f"{AGENTS}/{agent['id']}/publish", headers=mine)
assert r.status_code == 200 and r.json()["agent"]["scope"] == "firm", r.text
with settings_set(admin_client, skills_firm_export="administrator"):
assert client.get(path, headers=bearer(owner["token"])).status_code == 403
assert admin_client.get(path).status_code == 200
with settings_set(admin_client, skills_firm_export="everyone"):
assert client.get(path, headers=bearer(owner["token"])).status_code == 200
# ── import ────────────────────────────────────────────────────────────────────
def _zip(files: dict[str, str]) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
for name, body in files.items():
z.writestr(name, body)
return buf.getvalue()
def _import(client, headers, data: bytes, path: str = f"{SKILLS}/import"):
return client.post(path, content=data, params={"filename": "pack.zip"},
headers={**headers, "Content-Type": "application/zip"})
def test_import_export_import_keeps_the_same_sum(client, owner, other):
slug = _slug("imp")
pack = _zip({f"{slug}/SKILL.md": f"---\nname: {slug}\ndescription: Checks an NDA.\n"
"license: MIT\n---\n# NDA\n\nRead clause 1 first.\n",
f"{slug}/reference.md": "# Clauses\n"})
first = _import(client, bearer(owner["token"]), pack)
assert first.status_code == 200 and first.json()["status"] == "imported", first.text
imported = first.json()["skills"][0]
assert imported["skill"]["slug"] == slug
exported = client.get(f"{SKILLS}/{imported['skill']['id']}/export",
headers=bearer(owner["token"]))
assert exported.status_code == 200, exported.text
# Into somebody else's library: a new skill with the very same content sum.
again = _import(client, bearer(other["token"]), exported.content)
assert again.status_code == 200 and again.json()["status"] == "imported", again.text
assert again.json()["skills"][0]["content_sha256"] == imported["content_sha256"]
# Back into the owner's own: recognised, nothing written.
back = _import(client, bearer(owner["token"]), exported.content)
assert back.status_code == 200 and back.json()["status"] == "duplicate", back.text
assert back.json()["skills"][0]["match"]["id"] == imported["skill"]["id"]
@pytest.mark.parametrize(("files", "code"), [
({"../evil/SKILL.md": "---\nname: evil\ndescription: x\n---\n"}, "pack_bad_path"),
({"evil/SKILL.md": "---\nname: evil\ndescription: x\n---\n", "evil/run.sh": "rm -rf /\n"},
"pack_file_type"),
({"not-a-zip": ""}, "pack_not_zip"),
])
def test_a_malicious_pack_is_refused_as_problem_details(client, owner, files, code):
data = b"not a zip at all" if code == "pack_not_zip" else _zip(files)
before = client.get(SKILLS, headers=bearer(owner["token"])).json()
r = _import(client, bearer(owner["token"]), data)
assert r.status_code == 422, r.text
assert r.headers["content-type"].startswith("application/problem+json")
assert r.json()["code"] == code
assert client.get(SKILLS, headers=bearer(owner["token"])).json() == before
# ── the database backs the rules ──────────────────────────────────────────────
@pytest.mark.parametrize("statement", [
"UPDATE skill_version SET body_md = 'rewritten'",
"DELETE FROM skill_version",
])
def test_the_runtime_role_cannot_rewrite_a_frozen_version(client, statement):
from app.db import engine
with engine.connect() as conn:
with pytest.raises(ProgrammingError, match="permission denied"):
conn.execute(text(statement))
conn.rollback()