294 lines
12 KiB
Python
294 lines
12 KiB
Python
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import uuid
|
|
import zipfile
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
|
from app.models import Skill
|
|
from app.services import skill_pack, skills
|
|
from app.services.skill_pack import PackRejected
|
|
|
|
OWNER, OTHER, ADMIN = (SimpleNamespace(id=uuid.uuid4(), is_admin=a) for a in (False, False, True))
|
|
|
|
|
|
def _skill(scope: str, current=None) -> Skill:
|
|
return Skill(id=uuid.uuid4(), slug="nda", name="NDA", owner_id=OWNER.id, scope=scope,
|
|
status="active", origin="authored", current_version_id=current)
|
|
|
|
|
|
class _Db:
|
|
def __init__(self, skill):
|
|
self.skill = skill
|
|
|
|
def get(self, _model, _id):
|
|
return self.skill
|
|
|
|
|
|
@pytest.mark.parametrize("user, scope, sees, edits", [
|
|
(OWNER, "personal", True, True),
|
|
(OTHER, "personal", False, False),
|
|
(ADMIN, "personal", False, False), # an administrator gets no look at working notes
|
|
(OWNER, "firm", True, True),
|
|
(OTHER, "firm", True, False),
|
|
(ADMIN, "firm", True, True),
|
|
])
|
|
def test_visibility_matrix(user, scope, sees, edits):
|
|
skill = _skill(scope)
|
|
assert skills.can_see(user, skill) is sees
|
|
assert skills.can_edit(user, skill) is edits
|
|
|
|
|
|
def test_someone_elses_personal_skill_is_a_404_not_a_403():
|
|
db = _Db(_skill("personal"))
|
|
for user in (OTHER, ADMIN):
|
|
with pytest.raises(NotFoundError):
|
|
skills.get_skill(db, user, db.skill.id)
|
|
with pytest.raises(NotFoundError):
|
|
skills.archive_skill(db, user, db.skill.id, ip=None)
|
|
|
|
|
|
def test_a_firm_skill_is_changed_only_by_its_editors():
|
|
db = _Db(_skill("firm"))
|
|
with pytest.raises(AuthorizationError):
|
|
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
|
|
|
|
|
|
def test_a_non_editor_reads_only_the_current_version():
|
|
approved, pending = uuid.uuid4(), uuid.uuid4()
|
|
skill = _skill("firm", current=approved)
|
|
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
|
|
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
|
|
|
|
|
|
def test_next_n():
|
|
assert skills.next_n(None) == 1
|
|
assert skills.next_n(4) == 5
|
|
|
|
|
|
def test_frontmatter_columns_win_over_metadata():
|
|
head = skills.frontmatter("nda", "Opis", "MIT", {"name": "x", "license": "y", "metadata": {"a": 1}})
|
|
assert head == {"name": "nda", "description": "Opis", "license": "MIT", "metadata": {"a": 1}}
|
|
|
|
|
|
def test_checked_hashes_what_an_export_would_carry():
|
|
files = {"resources/notes.md": b"# Notatki\n"}
|
|
doc, stored, sha = skills.checked("nda", "Przegląd NDA", "Treść\r\n", "proprietary", {}, files)
|
|
assert stored.files == files and doc.body == "Treść\n"
|
|
assert sha == skill_pack.content_sha256(stored)
|
|
pack = skill_pack.read_pack(skill_pack.build_pack([stored]))
|
|
assert skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[0])) == sha
|
|
|
|
|
|
@pytest.mark.parametrize("slug, files, code", [
|
|
("Not Kebab", {}, "skill_bad_name"),
|
|
("nda", {"run.sh": b"echo"}, "pack_file_type"),
|
|
("nda", {"../escape.md": b"x"}, "pack_bad_path"),
|
|
("nda", {"a\\b.md": b"x"}, "pack_bad_path"),
|
|
("nda", {"/abs.md": b"x"}, "pack_bad_path"),
|
|
("nda", {"a//b.md": b"x"}, "pack_bad_path"),
|
|
("nda", {"SKILL.md": b"---\nname: nda\ndescription: x\n---\n"}, "pack_duplicate_name"),
|
|
])
|
|
def test_checked_applies_the_import_rules(slug, files, code):
|
|
with pytest.raises(PackRejected) as caught:
|
|
skills.checked(slug, "Opis", "Treść", "proprietary", {}, files)
|
|
assert caught.value.code == code
|
|
|
|
|
|
def test_every_allowed_extension_has_a_media_type():
|
|
assert set(skills.MEDIA_TYPES) == skill_pack.ALLOWED_TYPES
|
|
|
|
|
|
# ---- publication (T1) ----
|
|
|
|
class _PublishDb:
|
|
def __init__(self):
|
|
self.added = []
|
|
|
|
def scalar(self, _query):
|
|
return None # no pending request for this version yet
|
|
|
|
def add(self, row):
|
|
self.added.append(row)
|
|
|
|
def flush(self):
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def audited(monkeypatch):
|
|
actions = []
|
|
monkeypatch.setattr(skills.audit, "record", lambda _db, **kw: actions.append(kw["action"]))
|
|
return actions
|
|
|
|
|
|
def _version(n=1):
|
|
return SimpleNamespace(id=uuid.uuid4(), n=n)
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["approval", "direct"])
|
|
def test_publication_follows_the_setting(monkeypatch, audited, mode):
|
|
monkeypatch.setattr(skills.settings, "get", lambda _db, key: {"skills_firm_publish": mode}[key])
|
|
skill, version, db = _skill("personal"), _version(), _PublishDb()
|
|
out = skills._publish(db, OWNER, skills.PublishKind.skill, skill, version, ip=None)
|
|
if mode == "direct":
|
|
assert out["status"] == "published" and not db.added
|
|
assert (skill.scope, skill.current_version_id) == ("firm", version.id)
|
|
assert audited == ["skill.publish_approve"]
|
|
else:
|
|
assert out["status"] == "pending" and skill.scope == "personal"
|
|
assert [(r.kind, r.version_id, r.status) for r in db.added] == [
|
|
("skill", version.id, "pending")]
|
|
assert audited == ["skill.publish_request"]
|
|
|
|
|
|
def test_a_new_firm_version_waits_for_approval(monkeypatch, audited):
|
|
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "approval")
|
|
approved = uuid.uuid4()
|
|
skill = _skill("firm", current=approved)
|
|
skills._publish(_PublishDb(), OWNER, skills.PublishKind.skill, skill, _version(2), ip=None)
|
|
assert skill.current_version_id == approved
|
|
|
|
|
|
def test_the_published_version_is_not_published_twice(monkeypatch):
|
|
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
|
|
version = _version()
|
|
skill = _skill("firm", current=version.id)
|
|
with pytest.raises(ConflictError):
|
|
skills._publish(_PublishDb(), OWNER, skills.PublishKind.skill, skill, version, ip=None)
|
|
|
|
|
|
def test_approving_an_older_version_is_refused():
|
|
assert skills.refuses_older(_skill("firm"), 3, _version(2))
|
|
assert not skills.refuses_older(_skill("firm"), 2, _version(3))
|
|
assert not skills.refuses_older(_skill("personal"), None, _version(1))
|
|
|
|
|
|
@pytest.mark.parametrize("call", [
|
|
lambda: skills.decide_publish(None, OTHER, uuid.uuid4(), approve=True),
|
|
lambda: skills.pending_publish_requests(None, OTHER),
|
|
])
|
|
def test_only_an_administrator_decides(call):
|
|
with pytest.raises(AuthorizationError):
|
|
call()
|
|
|
|
|
|
def test_an_imported_slug_takes_the_first_free_number():
|
|
assert skills.free_slug(set(), "x") == "x"
|
|
assert skills.free_slug({"x"}, "x") == "x-2"
|
|
assert skills.free_slug({"x", "x-2"}, "x") == "x-3"
|
|
long = "a" * 64
|
|
assert skills.free_slug({long}, long) == "a" * 62 + "-2"
|
|
|
|
|
|
@pytest.mark.parametrize("user, firm_export, allowed", [
|
|
(OWNER, "administrator", True), # one's own: always
|
|
(OTHER, "administrator", False),
|
|
(ADMIN, "administrator", True),
|
|
(OTHER, "everyone", True),
|
|
])
|
|
def test_t2_decides_who_exports_a_firm_skill(user, firm_export, allowed):
|
|
assert skills.may_export(user, _skill("firm"), firm_export) is allowed
|
|
|
|
|
|
def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
|
agent = skill_pack.build_pack([], skill_pack.AgentDoc(
|
|
name="a", description="d", body="b", frontmatter={"name": "a", "description": "d"}))
|
|
with pytest.raises(PackRejected) as err:
|
|
skills.import_skills(None, OWNER, agent, ip=None)
|
|
assert err.value.code == "pack_is_agent"
|
|
buf = io.BytesIO()
|
|
with zipfile.ZipFile(buf, "w") as zf:
|
|
zf.writestr("notes.md", "hi")
|
|
with pytest.raises(PackRejected) as err:
|
|
skills.import_skills(None, OWNER, buf.getvalue(), ip=None)
|
|
assert err.value.code == "pack_no_skill"
|
|
|
|
|
|
# ---- agents ----
|
|
|
|
def _sv(skill, current=False):
|
|
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1)
|
|
if current:
|
|
skill.current_version_id = version.id
|
|
return version
|
|
|
|
|
|
@pytest.mark.parametrize("user, agent_scope, skill_scope, current, allowed", [
|
|
(OWNER, "personal", "personal", True, True), # one's own working notes
|
|
(OTHER, "personal", "personal", True, False), # somebody else's: invisible
|
|
(OTHER, "personal", "firm", True, True), # the firm's published version
|
|
(OTHER, "personal", "firm", False, False), # ...but not one still waiting for approval
|
|
(OWNER, "personal", "firm", False, True), # its editor reads every version
|
|
(OWNER, "firm", "personal", True, False), # a firm agent never carries a personal skill
|
|
(ADMIN, "firm", "personal", True, False),
|
|
(OWNER, "firm", "firm", True, True),
|
|
(OWNER, "firm", "firm", False, False), # not even its editor's unapproved version
|
|
])
|
|
def test_a_firm_agent_pins_only_the_firms_skills(user, agent_scope, skill_scope, current, allowed):
|
|
skill = _skill(skill_scope)
|
|
assert skills.may_pin(user, agent_scope, skill, _sv(skill, current)) is allowed
|
|
|
|
|
|
def test_a_pin_must_name_a_version_of_that_skill():
|
|
skill = _skill("personal")
|
|
assert not skills.may_pin(OWNER, "personal", skill, _sv(_skill("personal"), True))
|
|
assert not skills.may_pin(OWNER, "personal", None, None)
|
|
|
|
|
|
class _PinDb:
|
|
def __init__(self, *pairs):
|
|
self.rows = {}
|
|
for skill, version in pairs:
|
|
self.rows[skill.id], self.rows[version.id] = skill, version
|
|
|
|
def get(self, _model, key):
|
|
return self.rows.get(key)
|
|
|
|
|
|
def test_refused_pins_are_a_validation_error_naming_them():
|
|
mine, firm = _skill("personal"), _skill("firm")
|
|
v_mine, v_firm = _sv(mine, True), _sv(firm, True)
|
|
db = _PinDb((mine, v_mine), (firm, v_firm))
|
|
assert skills._check_pins(db, OWNER, "personal", [v_mine.id, v_firm.id]) == [v_mine, v_firm]
|
|
unknown = uuid.uuid4()
|
|
with pytest.raises(ValidationError) as err:
|
|
skills._check_pins(db, OWNER, "firm", [v_mine.id, v_firm.id, unknown])
|
|
assert err.value.extra == {"code": "agent_pin_refused",
|
|
"en": "A firm agent pins only the firm's published skill versions.",
|
|
"skill_version_ids": [str(v_mine.id), str(unknown)]}
|
|
with pytest.raises(ValidationError):
|
|
skills._check_pins(db, OWNER, "personal", [v_mine.id, v_mine.id])
|
|
|
|
|
|
def test_an_agent_is_published_through_the_same_path(monkeypatch, audited):
|
|
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "approval")
|
|
agent = SimpleNamespace(id=uuid.uuid4(), name="Asystent", scope="personal", status="active",
|
|
current_version_id=None)
|
|
out = skills._publish(_PublishDb(), OWNER, skills.PublishKind.agent, agent, _version(), ip=None)
|
|
assert out["status"] == "pending" and audited == ["agent.publish_request"]
|
|
|
|
|
|
def test_an_agent_import_takes_only_an_assistant_agent_pack():
|
|
skill = skill_pack.build_pack([skill_pack.SkillContent(
|
|
folder="nda", frontmatter={"name": "nda", "description": "d"}, body="b", files={})])
|
|
with pytest.raises(PackRejected) as err:
|
|
skills.import_agent(None, OWNER, skill, ip=None)
|
|
assert err.value.code == "pack_not_agent"
|
|
compass = skill_pack.build_pack([], skill_pack.AgentDoc(
|
|
name="a", description="d", body="b",
|
|
frontmatter={"name": "a", "description": "d", "kind": "compass.redlines"}))
|
|
with pytest.raises(PackRejected) as err:
|
|
skills.import_agent(None, OWNER, compass, ip=None)
|
|
assert err.value.code == "pack_agent_kind"
|
|
|
|
|
|
def test_an_agent_file_name_is_ascii_kebab():
|
|
assert skills._slugish("Asystent umów NDA!") == "asystent-umow-nda"
|
|
assert skills._slugish("Łódź") == "lodz"
|
|
assert skills._slugish("—") == "agent"
|