Files
Atrium/backend/tests/test_skill_pack_unit.py
T
tobayahandClaude Opus 5.5 1adb783d4a fix(skills): import przyjmuje naglowki SKILL.md w stylu Claude Code
52 z 57 realnych skilli ma opis z drugim dwukropkiem (description: Use when ... SKIP: x),
ktory scisly YAML odrzuca, a Claude Code czyta jako jeden tekst. Gdy YAML zawodzi,
naglowek z samych linii klucz: tekst (plus wciete kontynuacje) jest czytany jako
teksty; wartosc zaczynajaca sie od znaku YAML ([, ", !, *, ...) jest parsowana osobno
i zepsuta nadal odrzuca calosc. Na skillach autora: 50/57 przechodzi, 6 odpada za
skrypty (zgodnie z decyzja: skill bez kodu), 1 za opis > 1024 znaki (limit standardu).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJbh3fPYdfdLG3MU6f
2026-11-06 14:16:48 +01:00

471 lines
20 KiB
Python

"""`skill_pack.read_pack`: one test per archive rule, on ZIPs built in memory (DB-free)."""
from __future__ import annotations
import io
import os
import stat
import warnings
import zipfile
import pytest
from app.services import skill_pack
from app.services.skill_pack import PackRejected, read_pack
def _zip(entries, *, compression=zipfile.ZIP_DEFLATED) -> bytes:
"""`entries`: (name or ZipInfo, bytes). Names are written raw — see `_raw`."""
buf = io.BytesIO()
with warnings.catch_warnings():
warnings.simplefilter("ignore") # the duplicate-name test writes one twice on purpose
with zipfile.ZipFile(buf, "w", compression) as zf:
for name, data in entries:
zf.writestr(name, data)
return buf.getvalue()
def _raw(name: str) -> zipfile.ZipInfo:
# On Windows the ZipInfo constructor rewrites `\` to `/`; setting the attribute afterwards keeps
# the name exactly as an attacker's archive would carry it.
info = zipfile.ZipInfo("placeholder")
info.filename = name
return info
def _code(data: bytes) -> str:
with pytest.raises(PackRejected) as caught:
read_pack(data)
return caught.value.code
SKILL = b"---\nname: nda\ndescription: Przeglad NDA\n---\n# NDA\n"
def _lying_size(data: bytes, declared: int) -> bytes:
"""Rewrite every header's uncompressed size to `declared` — a bomb's header lies about it."""
out = bytearray(data)
for sig, off in ((b"PK\x03\x04", 22), (b"PK\x01\x02", 24)):
at = out.find(sig)
while at != -1:
out[at + off:at + off + 4] = declared.to_bytes(4, "little")
at = out.find(sig, at + 4)
return bytes(out)
def test_a_member_lying_about_its_size_is_refused_without_inflating_it():
import tracemalloc
bomb = _lying_size(_zip([("s/notes.txt", b"\0" * (40 * 1024 * 1024))]), 1000)
tracemalloc.start()
try:
assert _code(bomb) == "pack_not_zip"
peak = tracemalloc.get_traced_memory()[1]
finally:
tracemalloc.stop()
# An unbounded `zf.read` inflates all 40 MB before trimming to the declared 1000 bytes.
assert peak < 5 * 1024 * 1024, peak
def test_a_clean_pack_is_read():
pack = read_pack(_zip([("nda/SKILL.md", SKILL), ("nda/resources/a.txt", b"x")]))
assert pack.files == {"nda/SKILL.md": SKILL, "nda/resources/a.txt": b"x"}
(skill,) = pack.skills
assert (skill.path, skill.name, skill.description, skill.body, skill.info_only) \
== ("nda/SKILL.md", "nda", "Przeglad NDA", "# NDA\n", {})
def test_every_code_has_both_languages_and_rides_in_problem_details():
err = PackRejected("pack_link", ["b", "a"])
# Polish detail + English `en`, the shape the console's coreRefusal words in either language.
assert err.extra == {"code": "pack_link", "files": ["a", "b"], "en": "The pack contains a link."}
assert err.detail == "Paczka zawiera dowiązanie."
assert err.status_code == 422
for pl, en in skill_pack.MESSAGES.values():
assert pl and en and pl != en
def test_more_than_10_mb_is_refused():
assert _code(b"\0" * (skill_pack.MAX_PACK_BYTES + 1)) == "pack_too_large"
def test_not_a_zip_is_refused():
assert _code(b"plain text, not an archive") == "pack_not_zip"
def test_more_than_200_files_is_refused():
data = _zip([(f"s/{i}.md", b"x") for i in range(skill_pack.MAX_FILES + 1)])
assert _code(data) == "pack_too_many_files"
def test_200_files_is_accepted():
assert len(read_pack(_zip([(f"s/{i}.md", b"x") for i in range(200)])).files) == 200
def test_more_than_50_mb_unpacked_is_refused():
data = _zip([("s/big.txt", b"\0" * (skill_pack.MAX_UNPACKED_BYTES + 1))])
assert len(data) < skill_pack.MAX_PACK_BYTES
assert _code(data) == "pack_unpacked_too_large"
def test_a_file_compressed_over_100_to_1_is_refused():
assert _code(_zip([("s/bomb.txt", b"\0" * 1_000_000)])) == "pack_compression_ratio"
def test_zip64_is_refused():
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf, zf.open("s/SKILL.md", "w", force_zip64=True) as f:
f.write(b"# x")
assert _code(buf.getvalue()) == "pack_zip64"
@pytest.mark.parametrize("name", ["s/../SKILL.md", "../SKILL.md"])
def test_a_dot_dot_segment_is_refused(name):
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
@pytest.mark.parametrize("name", ["/etc/SKILL.md", "C:/SKILL.md"])
def test_an_absolute_path_is_refused(name):
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
def test_a_backslash_is_refused():
assert _code(_zip([(_raw("s\\SKILL.md"), b"x")])) == "pack_bad_path"
def test_a_symlink_is_refused():
info = zipfile.ZipInfo("s/link.md")
info.external_attr = (stat.S_IFLNK | 0o777) << 16
assert _code(_zip([(info, b"/etc/passwd")])) == "pack_link"
def test_a_duplicate_name_is_refused():
assert _code(_zip([("s/SKILL.md", b"a"), ("s/SKILL.md", b"b")])) == "pack_duplicate_name"
def test_names_differing_only_in_case_are_refused():
with pytest.raises(PackRejected) as caught:
read_pack(_zip([("s/Notes.md", b"a"), ("s/notes.md", b"b")]))
assert caught.value.code == "pack_case_collision"
assert caught.value.files == ["s/Notes.md", "s/notes.md"]
# --- file rules (2.2) ---------------------------------------------------------------------------
def _office(*parts: str, content_types: bool = True) -> bytes:
names = (["[Content_Types].xml"] if content_types else []) + list(parts)
return _zip([(n, b"<x/>") for n in names])
def _files_code(path: str, data: bytes) -> tuple[str, list[str]]:
with pytest.raises(PackRejected) as caught:
read_pack(_zip([("s/SKILL.md", b"# x"), (path, data)]))
return caught.value.code, caught.value.files
@pytest.mark.parametrize("ext", sorted(skill_pack.ALLOWED_TYPES))
def test_every_allowed_extension_is_accepted(ext):
data = {".pdf": b"%PDF-1.7\n", ".docx": _office("word/document.xml"),
".xlsx": _office("xl/workbook.xml")}.get(ext, "zażółć;gęślą".encode("cp1250"))
assert read_pack(_zip([(f"s/r/a{ext}", data)])).files[f"s/r/a{ext}"] == data
def test_the_extension_is_matched_case_insensitively():
assert read_pack(_zip([("s/r/A.PDF", b"%PDF-1.4")]))
@pytest.mark.parametrize("path", ["s/run.sh", "s/tool.py", "s/LICENSE", "s/inner.zip"])
def test_an_extension_off_the_list_is_refused(path):
assert _files_code(path, b"x") == ("pack_file_type", [path])
def test_a_pdf_without_the_pdf_signature_is_refused():
assert _files_code("s/r/a.pdf", b"MZ\x90\x00")[0] == "pack_signature_mismatch"
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
def test_an_office_file_that_is_not_a_zip_is_refused(ext):
assert _files_code(f"s/r/a{ext}", b"%PDF-1.7")[0] == "pack_signature_mismatch"
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
def test_an_office_zip_without_content_types_is_refused(ext):
assert _files_code(f"s/r/a{ext}", _office("x.xml", content_types=False))[0] \
== "pack_signature_mismatch"
def test_binary_content_under_a_text_extension_is_refused():
assert _files_code("s/r/notes.txt", b"\x7fELF\x02\x01\x00")[0] == "pack_signature_mismatch"
@pytest.mark.parametrize("path, part", [("s/r/a.docx", "word/vbaProject.bin"),
("s/r/a.xlsx", "xl/VBAProject.bin")])
def test_an_office_file_with_macros_is_refused(path, part):
assert _files_code(path, _office(part)) == ("pack_macros", [path])
@pytest.mark.parametrize("path", ["s/r/a.txt", "s/r/a.json", "s/r/a.md"])
def test_a_zip_under_a_text_extension_is_refused(path):
assert _files_code(path, _zip([("x.txt", b"x")])) == ("pack_nested_zip", [path])
def test_the_inside_of_an_office_file_obeys_the_compression_limit():
data = _zip([("[Content_Types].xml", b"<x/>"), ("word/bomb.xml", b"\0" * 1_000_000)])
assert _files_code("s/r/a.docx", data) == ("pack_compression_ratio", ["s/r/a.docx"])
def test_the_inside_of_an_office_file_obeys_the_path_rules():
data = _zip([("[Content_Types].xml", b"<x/>"), (_raw("../evil.xml"), b"x")])
assert _files_code("s/r/a.xlsx", data) == ("pack_bad_path", ["s/r/a.xlsx"])
@pytest.mark.parametrize("types", [
b'<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>',
b'<Override PartName="/word/document.xml" ContentType="application/vnd.ms-word.document.'
b'macroEnabled.main+xml"/>',
b'<Override PartName="/word/activeX/a.xml" ContentType="application/vnd.ms-office.activeX+xml"/>',
])
def test_macros_declared_only_in_the_content_types_are_refused(types):
data = _zip([("[Content_Types].xml", b"<Types>" + types + b"</Types>"),
("word/renamed.dat", b"code")])
assert _files_code("s/r/a.docx", data) == ("pack_macros", ["s/r/a.docx"])
@pytest.mark.parametrize("manifest", [
b'<Default Extension="bin" ContentType="application/vnd.ms-office.&#x76;baProject"/>',
'<Default ContentType="application/vnd.ms-office.vbaProject"/>'.encode("utf-16"),
b"<Types>\xff\xfe</Types>",
])
def test_a_content_types_part_a_substring_search_could_misread_is_refused(manifest):
data = _zip([("[Content_Types].xml", manifest)])
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
def test_an_oversized_content_types_part_is_refused():
data = _zip([("[Content_Types].xml", os.urandom(skill_pack.MAX_MANIFEST_BYTES + 1))],
compression=zipfile.ZIP_STORED)
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
def test_only_the_content_types_of_an_office_file_are_inflated(monkeypatch):
calls = []
pack = _zip([("s/r/a.docx", _office("word/document.xml"))]) # built before the spy: writes open too
real = zipfile.ZipFile.open # every inflating read goes through `open` (`_bounded_read`)
monkeypatch.setattr(zipfile.ZipFile, "open", lambda self, name, *a, **k: calls.append(name)
or real(self, name, *a, **k))
read_pack(pack)
assert [getattr(c, "filename", c) for c in calls] == ["s/r/a.docx", "[Content_Types].xml"]
# --- SKILL.md (2.3) -----------------------------------------------------------------------------
def _skill(text: str, path: str = "s/SKILL.md") -> tuple[str, list[str]]:
with pytest.raises(PackRejected) as caught:
read_pack(_zip([(path, text.encode("utf-8"))], compression=zipfile.ZIP_STORED))
return caught.value.code, caught.value.files
def _fm(**fields) -> str:
return "---\n" + "".join(f"{k}: {v}\n" for k, v in fields.items()) + "---\nbody\n"
def test_crlf_and_a_bom_are_read_like_lf():
pack = read_pack(_zip([("s/SKILL.md", b"\xef\xbb\xbf" + SKILL.replace(b"\n", b"\r\n"))]))
assert pack.skills[0].name == "nda" and pack.skills[0].body == "# NDA\n"
def test_a_skill_md_that_is_not_utf8_is_refused():
with pytest.raises(PackRejected) as caught:
read_pack(_zip([("s/SKILL.md", "---\nname: zażółć\n---\n".encode("cp1250"))]))
assert caught.value.code == "skill_not_utf8"
def test_a_frontmatter_over_8_kb_is_refused():
big = "x" * (skill_pack.MAX_FRONTMATTER_BYTES + 1)
assert _skill(_fm(name="a", description=big)) == ("skill_frontmatter_too_large", ["s/SKILL.md"])
def test_a_date_in_the_frontmatter_stays_a_string_jsonb_can_store():
import json
pack = read_pack(_zip([("s/SKILL.md", _fm(name="a", description="d", updated="2025-01-01").encode())]))
assert pack.skills[0].frontmatter["updated"] == "2025-01-01"
json.dumps(pack.skills[0].frontmatter, allow_nan=False)
def test_a_claude_code_style_description_with_colons_is_read_as_one_string():
# Strict YAML refuses the second `: `; Claude Code (and most real SKILL.md files) do not.
doc = ("---\nname: tworzenie-skilli\ndescription: Use when X — `a: b`. SKIP: literówka\n"
" ciąg dalszy\nallowed-tools: Read, Glob\n---\n# Body\n")
s = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0]
assert s.description == "Use when X — `a: b`. SKIP: literówka ciąg dalszy"
assert s.frontmatter["allowed-tools"] == "Read, Glob"
def test_in_flat_text_a_quoted_or_list_value_is_still_read_as_yaml():
doc = '---\nname: a\ndescription: d. SKIP: x\npaths: ["**/*.gs", "*.json"]\nargument-hint: "[review]"\n---\nb'
fm = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0].frontmatter
assert fm["paths"] == ["**/*.gs", "*.json"] and fm["argument-hint"] == "[review]"
@pytest.mark.parametrize("head", ["name: a\ndescription: d: e\n- list item", "name: a\n orphan\nx: [unclosed",
"name: a\ndescription: d: e\nx: !!python/object:os.system ls",
"name: a\ndescription: d: e\nx: *undefined"])
def test_a_broken_frontmatter_that_is_not_flat_text_is_still_refused(head):
assert _skill(f"---\n{head}\n---\nbody")[0] == "skill_frontmatter_invalid"
@pytest.mark.parametrize("value", ["!!binary aGVsbG8=", "!!set {a: null}", ".nan", "!!timestamp 2025-01-01"])
def test_frontmatter_values_json_cannot_carry_are_refused(value):
assert _skill(_fm(name="a", description="d", x=value))[0] == "skill_frontmatter_invalid"
@pytest.mark.parametrize("yaml_text", [
"name: &n a\ndescription: *n\n", # anchor + alias
"name: a\ndescription: d\nx: &anchor 1\n", # an anchor alone is refused too
])
def test_yaml_anchors_and_aliases_are_refused(yaml_text):
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_alias"
@pytest.mark.parametrize("yaml_text", ["name: [unclosed\n", "x: !!python/object:os.system ls\n",
"[" * 5000 + "\n"])
def test_a_frontmatter_that_is_not_safe_yaml_is_refused(yaml_text):
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_invalid"
@pytest.mark.parametrize("yaml_text", ["- a\n- b\n", "just a string\n"])
def test_a_frontmatter_that_is_not_a_mapping_is_refused(yaml_text):
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_not_mapping"
@pytest.mark.parametrize("text", ["# no frontmatter at all\n", _fm(name="a"), _fm(description="d"),
_fm(name="a", description='""'), _fm(name=1, description="d")])
def test_a_missing_name_or_description_is_refused(text):
assert _skill(text)[0] == "skill_missing_field"
@pytest.mark.parametrize("name", ["Nda", "nda_review", "nda--x", "-nda", "przegląd", "a" * 65])
def test_a_name_that_is_not_kebab_up_to_64_is_refused(name):
assert _skill(_fm(name=name, description="d"))[0] == "skill_bad_name"
def test_a_64_character_name_is_accepted():
assert read_pack(_zip([("s/SKILL.md", _fm(name="a" * 64, description="d").encode())]))
def test_a_description_over_1024_characters_is_refused():
assert _skill(_fm(name="a", description="d" * 1025))[0] == "skill_description_too_long"
def test_a_body_over_30000_characters_is_refused():
text = "---\nname: a\ndescription: d\n---\n" + "ż" * (skill_pack.MAX_BODY + 1)
assert _skill(text)[0] == "skill_body_too_long"
def test_permission_fields_are_kept_as_information_only():
text = ("---\nname: a\ndescription: d\nallowed-tools: [Bash, WebFetch]\nmodel: opus\n"
"permissionMode: bypassPermissions\nlicense: MIT\n---\n")
(skill,) = read_pack(_zip([("s/SKILL.md", text.encode())])).skills
assert skill.info_only == {"allowed-tools": ["Bash", "WebFetch"], "model": "opus",
"permissionMode": "bypassPermissions"}
assert skill.frontmatter["license"] == "MIT"
def _plugin(*extra) -> bytes:
return _zip([("p/.claude-plugin/plugin.json", b'{"name": "p"}'),
("p/skills/nda/SKILL.md", SKILL), ("p/commands/review.md", b"# c"), *extra])
def test_a_plugin_contributes_its_skills():
assert [s.path for s in read_pack(_plugin()).skills] == ["p/skills/nda/SKILL.md"]
def test_a_plugin_with_a_script_is_refused_with_the_list():
with pytest.raises(PackRejected) as caught:
read_pack(_plugin(("p/scripts/run.sh", b"rm -rf /"), ("p/skills/nda/helper.py", b"x")))
assert caught.value.code == "pack_plugin_code"
assert caught.value.files == ["p/scripts/run.sh", "p/skills/nda/helper.py"]
@pytest.mark.parametrize("path", ["p/hooks/hooks.json", "p/.mcp.json", "p/bin/tool.md"])
def test_a_plugin_with_hooks_or_mcp_servers_is_refused(path):
with pytest.raises(PackRejected) as caught:
read_pack(_plugin((path, b"{}")))
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", [path])
@pytest.mark.parametrize("key", ["hooks", "mcpServers"])
def test_a_plugin_manifest_declaring_code_inline_is_refused(key):
data = _zip([("p/.claude-plugin/plugin.json", f'{{"name": "p", "{key}": {{}}}}'.encode()),
("p/skills/nda/SKILL.md", SKILL)])
with pytest.raises(PackRejected) as caught:
read_pack(data)
assert (caught.value.code, caught.value.files) == ("pack_plugin_code",
["p/.claude-plugin/plugin.json"])
def test_a_plugin_nested_in_another_is_judged_against_its_own_root():
data = _zip([(".claude-plugin/plugin.json", b'{"name": "outer"}'),
("inner/.claude-plugin/plugin.json", b'{"name": "inner"}'),
("inner/hooks/hooks.json", b"{}")])
with pytest.raises(PackRejected) as caught:
read_pack(data)
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", ["inner/hooks/hooks.json"])
# --- content sum, build_pack, agent packs (2.4) ------------------------------------------------
_ORIGINAL = ("---\r\nname: nda\r\nmetadata: {version: 2, author: Zespół}\r\ndescription: Przeglăd\r\n"
"license: proprietary\r\n---\r\n# Przeglăd NDA\r\n").encode()
_DOCX = _office("word/document.xml")
def _sum(pack, i=0):
return skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[i]))
def test_a_skill_with_a_docx_hashes_the_same_after_export_and_import():
original = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx", _DOCX)]))
content = skill_pack.skill_content(original, original.skills[0])
assert content.folder == "nda" and content.files == {"resources/playbook.docx": _DOCX}
again = read_pack(skill_pack.build_pack([content]))
assert again.kind == "skill" and "atrium-pack.json" not in again.files
assert _sum(again) == _sum(original)
# Only spelling is normalised away: a changed file is a changed skill.
other = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx",
_office("word/other.xml"))]))
assert _sum(other) != _sum(original)
def test_an_agent_pack_round_trips_with_its_skills():
skills = [skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n",
{"r/a.txt": b"x"}),
skill_pack.SkillContent("dpa", {"name": "dpa", "description": "e"}, "# b\n", {})]
agent = skill_pack.AgentDoc(name="Asystent umów", description="Przegląda umowy", body="Bądź zwięzły.\n",
frontmatter={"name": "Asystent umów", "description": "Przegląda umowy",
"kind": "assistant", "tools": ["search"], "model": "sonnet"})
pack = read_pack(skill_pack.build_pack(skills, agent))
assert pack.kind == "agent" and pack.agent == agent
assert [skill_pack.skill_content(pack, s) for s in pack.skills] == sorted(skills, key=lambda s: s.folder)
def _tampered(change) -> tuple[str, list[str]]:
content = skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n", {"a.txt": b"x"})
with zipfile.ZipFile(io.BytesIO(skill_pack.build_pack([content]))) as zf:
entries = {n: zf.read(n) for n in zf.namelist()}
change(entries)
with pytest.raises(PackRejected) as caught:
read_pack(_zip(entries.items()))
return caught.value.code, caught.value.files
def test_a_file_whose_sum_differs_from_the_manifest_is_refused():
assert _tampered(lambda e: e.update({"nda/a.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/a.txt"])
def test_a_file_missing_from_the_manifest_is_refused():
assert _tampered(lambda e: e.update({"nda/b.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/b.txt"])
def test_a_malformed_manifest_is_refused():
assert _tampered(lambda e: e.update({"atrium-pack.json": b'{"format": 1}'}))[0] \
== "pack_manifest_invalid"