fix(skills): validate directory names and package regular files (#8444)

* fix(skills): constrain skill creation and packaging paths

* fix(skills): report creator and packager errors on stderr

* test(skills): expect packager validation errors on stderr

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
Nan Gao 2026-11-21 19:03:16 +08:00 committed by GitHub
parent d834188dcd
commit 7810b807f2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 281 additions and 53 deletions

View File

@ -72,7 +72,10 @@ def test_package_skill_reports_invalid_utf8_without_traceback(tmp_path: Path, mo
output_dir = tmp_path / "dist"
assert packager.package_skill(skill_dir, output_dir) is None
assert "Validation failed: SKILL.md is not valid UTF-8" in capsys.readouterr().out
captured = capsys.readouterr()
assert "Validation failed: SKILL.md is not valid UTF-8" in captured.err
assert "Validation failed" not in captured.out
assert "Traceback" not in captured.err
assert not list(tmp_path.rglob("*.skill"))

View File

@ -214,7 +214,9 @@ Discovery follows operator-managed directory symlinks, but skips links back to a
Skill Markdown and bundled text resources use UTF-8. Skill-creator CLI and review utilities read and write text explicitly as UTF-8 so localized skills behave consistently across operating systems.
For standalone skill exports, the bundled skill creator's `scripts/package_skill.py` can be run by file path from any directory, or as `python -m scripts.package_skill` from the skill-creator directory. Both entry points validate the skill before writing a `.skill` archive.
For standalone skill creation, `scripts/init_skill.py <skill-name> --path <directory>` creates a new direct child of the chosen directory. Names can be up to 40 characters long and consist of lowercase ASCII letters and digits, optionally grouped with single hyphens (for example, `data-analyzer`). The creator and packager write progress to stdout and report errors on stderr.
For standalone skill exports, the bundled skill creator's `scripts/package_skill.py` can be run by file path from any directory, or as `python -m scripts.package_skill` from the skill-creator directory. Both entry points validate the skill before writing a `.skill` archive. The packager requires a regular `SKILL.md` file and skips symbolic links to files and directories in the skill. Copy any linked resources the skill needs into its directory before packaging.
Custom-skill writes and security-scan staging preserve submitted line endings
on every platform, so the scanner checks the bytes that will be stored.

View File

@ -11,10 +11,13 @@ Examples:
init_skill.py custom-skill --path /custom/location
"""
import re
import sys
from pathlib import Path
MAX_SKILL_NAME_LENGTH = 40
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
@ -202,21 +205,32 @@ def init_skill(skill_name, path):
Returns:
Path to created skill directory, or None if error
"""
# Determine skill directory path
skill_dir = Path(path).resolve() / skill_name
# Check if directory already exists
if skill_dir.exists():
print(f"❌ Error: Skill directory already exists: {skill_dir}")
if (
not isinstance(skill_name, str)
or len(skill_name) > MAX_SKILL_NAME_LENGTH
or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", skill_name)
):
print(
f"❌ Error: Skill name must be 1–{MAX_SKILL_NAME_LENGTH} characters long and contain "
"lowercase ASCII letters or digits separated by optional single hyphens.",
file=sys.stderr,
)
return None
# Create skill directory
try:
root = Path(path).resolve()
skill_dir = root / skill_name
if skill_dir.resolve().parent != root:
print("❌ Error: Skill directory must be a direct child of the requested path.", file=sys.stderr)
return None
skill_dir.mkdir(parents=True, exist_ok=False)
print(f"✅ Created skill directory: {skill_dir}")
except Exception as e:
print(f"❌ Error creating directory: {e}")
except FileExistsError:
print(f"❌ Error: Skill directory already exists: {skill_dir}", file=sys.stderr)
return None
except (OSError, RuntimeError) as e:
print(f"❌ Error creating directory: {e}", file=sys.stderr)
return None
print(f"✅ Created skill directory: {skill_dir}")
# Create SKILL.md from template
skill_title = title_case_skill_name(skill_name)
@ -230,7 +244,7 @@ def init_skill(skill_name, path):
skill_md_path.write_text(skill_content, encoding="utf-8")
print("✅ Created SKILL.md")
except Exception as e:
print(f"❌ Error creating SKILL.md: {e}")
print(f"❌ Error creating SKILL.md: {e}", file=sys.stderr)
return None
# Create resource directories with example files
@ -257,7 +271,7 @@ def init_skill(skill_name, path):
example_asset.write_text(EXAMPLE_ASSET, encoding="utf-8")
print("✅ Created assets/example_asset.txt")
except Exception as e:
print(f"❌ Error creating resource directories: {e}")
print(f"❌ Error creating resource directories: {e}", file=sys.stderr)
return None
# Print next steps
@ -272,11 +286,12 @@ def init_skill(skill_name, path):
def main():
if len(sys.argv) < 4 or sys.argv[2] != '--path':
print("❌ Error: Expected a skill name and --path <path>.", file=sys.stderr)
print("Usage: init_skill.py <skill-name> --path <path>")
print("\nSkill name requirements:")
print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
print(" - Lowercase letters, digits, and hyphens only")
print(" - Max 40 characters")
print(f" - Max {MAX_SKILL_NAME_LENGTH} characters")
print(" - Must match directory name exactly")
print("\nExamples:")
print(" init_skill.py my-new-skill --path skills/public")

View File

@ -11,7 +11,9 @@ Example:
"""
import fnmatch
import stat
import sys
import tempfile
import zipfile
from pathlib import Path
@ -28,7 +30,7 @@ EXCLUDE_FILES = {".DS_Store"}
ROOT_EXCLUDE_DIRS = {"evals"}
def should_exclude(rel_path: Path) -> bool:
def should_exclude(rel_path: Path, *, is_directory: bool = False) -> bool:
"""Check if a path should be excluded from packaging."""
parts = rel_path.parts
if any(part in EXCLUDE_DIRS for part in parts):
@ -37,12 +39,41 @@ def should_exclude(rel_path: Path) -> bool:
# folder name and parts[1] (if present) is the first subdir.
if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS:
return True
if is_directory:
return False
name = rel_path.name
if name in EXCLUDE_FILES:
return True
return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS)
def _is_link(info) -> bool:
# The Windows name-surrogate bit marks path redirects (including junctions).
# Cloud placeholders can be regular files with other reparse tags.
return stat.S_ISLNK(info.st_mode) or bool(getattr(info, "st_reparse_tag", 0) & 0x20000000)
def _write_files(archive, root: Path, destination: Path, staging_dir: Path):
directories = [root]
while directories:
for path in directories.pop().iterdir():
if path == destination or path == staging_dir:
continue
arcname = path.relative_to(root.parent)
info = path.lstat()
is_directory = stat.S_ISDIR(info.st_mode)
if _is_link(info) or should_exclude(arcname, is_directory=is_directory):
print(f" Skipped: {arcname}")
continue
if not path.resolve().is_relative_to(root):
raise ValueError(f"Entry is outside the skill directory: {arcname}")
if is_directory:
directories.append(path)
elif stat.S_ISREG(info.st_mode):
archive.write(path, arcname)
print(f" Added: {arcname}")
def package_skill(skill_path, output_dir=None):
"""
Package a skill folder into a .skill file.
@ -58,25 +89,30 @@ def package_skill(skill_path, output_dir=None):
# Validate skill folder exists
if not skill_path.exists():
print(f"❌ Error: Skill folder not found: {skill_path}")
print(f"❌ Error: Skill folder not found: {skill_path}", file=sys.stderr)
return None
if not skill_path.is_dir():
print(f"❌ Error: Path is not a directory: {skill_path}")
print(f"❌ Error: Path is not a directory: {skill_path}", file=sys.stderr)
return None
# Validate SKILL.md exists
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
print(f"❌ Error: SKILL.md not found in {skill_path}")
try:
manifest_info = skill_md.lstat()
except FileNotFoundError:
print(f"❌ Error: SKILL.md not found in {skill_path}", file=sys.stderr)
return None
if _is_link(manifest_info) or not stat.S_ISREG(manifest_info.st_mode):
print("❌ Error: SKILL.md must be a regular file inside the skill directory.", file=sys.stderr)
return None
# Run validation before packaging
print("🔍 Validating skill...")
valid, message = validate_skill(skill_path)
if not valid:
print(f"❌ Validation failed: {message}")
print(" Please fix the validation errors before packaging.")
print(f"❌ Validation failed: {message}", file=sys.stderr)
print(" Please fix the validation errors before packaging.", file=sys.stderr)
return None
print(f"✅ {message}\n")
@ -84,7 +120,6 @@ def package_skill(skill_path, output_dir=None):
skill_name = skill_path.name
if output_dir:
output_path = Path(output_dir).resolve()
output_path.mkdir(parents=True, exist_ok=True)
else:
output_path = Path.cwd()
@ -92,28 +127,34 @@ def package_skill(skill_path, output_dir=None):
# Create the .skill file (zip format)
try:
with zipfile.ZipFile(skill_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
# Walk through the skill directory, excluding build artifacts
for file_path in skill_path.rglob("*"):
if not file_path.is_file():
continue
arcname = file_path.relative_to(skill_path.parent)
if should_exclude(arcname):
print(f" Skipped: {arcname}")
continue
zipf.write(file_path, arcname)
print(f" Added: {arcname}")
output_path.mkdir(parents=True, exist_ok=True)
try:
output_info = skill_filename.lstat()
except FileNotFoundError:
output_info = None
if output_info and (_is_link(output_info) or not stat.S_ISREG(output_info.st_mode)):
raise ValueError(f"Output must be a regular file: {skill_filename}")
with tempfile.TemporaryDirectory(dir=output_path) as staging:
staging_dir = Path(staging)
staged = staging_dir / skill_filename.name
with zipfile.ZipFile(staged, "w", zipfile.ZIP_DEFLATED) as zipf:
_write_files(zipf, skill_path, skill_filename, staging_dir)
if output_info:
staged.chmod(output_info.st_mode & 0o777)
staged.replace(skill_filename)
print(f"\n✅ Successfully packaged skill to: {skill_filename}")
return skill_filename
except Exception as e:
print(f"❌ Error creating .skill file: {e}")
print(f"❌ Error creating .skill file: {e}", file=sys.stderr)
return None
def main():
if len(sys.argv) < 2:
print("❌ Error: A skill directory is required.", file=sys.stderr)
print("Usage: python scripts/package_skill.py <path/to/skill-folder> [output-directory]")
print("\nExample:")
print(" python scripts/package_skill.py skills/public/my-skill")

View File

@ -1,6 +1,7 @@
"""Exercise the skill packager through its standalone and module entry points."""
"""Exercise the public skill creation and packaging commands."""
import os
import runpy
import subprocess
import sys
import zipfile
@ -11,6 +12,31 @@ import pytest
SKILL_CREATOR = Path(__file__).resolve().parents[2] / "skills/public/skill-creator"
def run_cli(script, *args, cwd, entrypoint="script"):
command = [str(SKILL_CREATOR / "scripts" / f"{script}.py")]
if entrypoint == "module":
command = ["-m", f"scripts.{script}"]
cwd = SKILL_CREATOR
env = {**os.environ, "PYTHONIOENCODING": "utf-8"}
env.pop("PYTHONPATH", None)
return subprocess.run(
[sys.executable, "-B", *command, *args],
cwd=cwd,
env=env,
capture_output=True,
encoding="utf-8",
timeout=15,
)
@pytest.mark.parametrize("script", ["init_skill", "package_skill"])
def test_missing_arguments_report_error_and_show_usage(tmp_path, script):
result = run_cli(script, cwd=tmp_path)
assert result.returncode == 1
assert "Error:" in result.stderr
assert "Usage:" in result.stdout
@pytest.mark.parametrize("entrypoint", ["script", "module"])
@pytest.mark.parametrize("valid", [True, False], ids=["valid", "invalid"])
def test_packager_cli(tmp_path, entrypoint, valid):
@ -21,30 +47,171 @@ def test_packager_cli(tmp_path, entrypoint, valid):
content = "# Missing frontmatter\n"
(skill / "SKILL.md").write_text(content, encoding="utf-8", newline="\n")
output = tmp_path / "dist"
if entrypoint == "script":
command = [str(SKILL_CREATOR / "scripts/package_skill.py")]
cwd = tmp_path
else:
command = ["-m", "scripts.package_skill"]
cwd = SKILL_CREATOR
env = {**os.environ, "PYTHONIOENCODING": "utf-8"}
env.pop("PYTHONPATH", None)
result = subprocess.run(
[sys.executable, "-B", *command, str(skill), str(output)],
cwd=cwd,
env=env,
capture_output=True,
encoding="utf-8",
timeout=15,
result = run_cli(
"package_skill", skill, output, cwd=tmp_path, entrypoint=entrypoint
)
assert result.returncode == (0 if valid else 1), result.stdout + result.stderr
assert "Traceback" not in result.stderr
archive = output / "example-skill.skill"
if valid:
assert result.stderr == ""
assert "Successfully packaged skill" in result.stdout
with zipfile.ZipFile(archive) as package:
assert package.read("example-skill/SKILL.md").decode("utf-8") == content
else:
assert "No YAML frontmatter found" in result.stdout
assert "Validation failed: No YAML frontmatter found" in result.stderr
assert "Please fix the validation errors" in result.stderr
assert "Validation failed" not in result.stdout
assert "Please fix the validation errors" not in result.stdout
assert not archive.exists()
@pytest.mark.parametrize(("source", "diagnostic"), [
("missing", "Skill folder not found"),
("file.txt", "Path is not a directory"),
(".", "SKILL.md not found"),
])
def test_packager_reports_input_errors_on_stderr(tmp_path, source, diagnostic):
(tmp_path / "file.txt").touch()
result = run_cli("package_skill", tmp_path / source, cwd=tmp_path)
assert result.returncode == 1
assert diagnostic in result.stderr
assert diagnostic not in result.stdout
def test_init_creates_skill_under_requested_root(tmp_path):
name = "example-" + "2" * 32
root = tmp_path / "skills"
result = run_cli("init_skill", name, "--path", root, cwd=tmp_path)
assert result.returncode == 0, result.stdout + result.stderr
assert result.stderr == ""
assert "initialized successfully" in result.stdout
skill = root / name
assert (skill / "scripts" / "example.py").is_file()
assert (skill / "references" / "api_reference.md").is_file()
assert (skill / "assets" / "example_asset.txt").is_file()
manifest = skill / "SKILL.md"
assert name in manifest.read_text(encoding="utf-8")
manifest.write_text("Edited by the author.\n", encoding="utf-8")
result = run_cli("init_skill", name, "--path", root, cwd=tmp_path)
assert result.returncode == 1
assert manifest.read_text(encoding="utf-8") == "Edited by the author.\n"
@pytest.mark.parametrize(("filename", "diagnostic"), [
("SKILL.md", "Error creating SKILL.md"),
("example.py", "Error creating resource directories"),
])
def test_init_reports_write_errors_on_stderr(tmp_path, monkeypatch, capsys, filename, diagnostic):
write_text = Path.write_text
def simulate_write_error(path, *args, **kwargs):
if path.name == filename:
raise OSError("simulated write failure")
return write_text(path, *args, **kwargs)
monkeypatch.setattr(Path, "write_text", simulate_write_error)
init_skill = runpy.run_path(str(SKILL_CREATOR / "scripts" / "init_skill.py"))["init_skill"]
assert init_skill("example-skill", tmp_path) is None
out, err = capsys.readouterr()
assert diagnostic in err
assert diagnostic not in out
@pytest.mark.parametrize(
"name",
[
"",
"../sibling",
"nested/child",
r"nested\child",
"Bad Name",
"foo--bar",
"-prefix",
"suffix-",
"x" * 41,
pytest.param(None, id="absolute-path"),
],
)
def test_init_rejects_invalid_name_before_creating_directories(tmp_path, name):
if name is None:
name = str(tmp_path / "absolute-name")
result = run_cli("init_skill", name, "--path", tmp_path / "skills", cwd=tmp_path)
assert result.returncode == 1, result.stdout + result.stderr
assert not list(tmp_path.iterdir())
def test_init_rejects_existing_directory_link(tmp_path):
root = tmp_path / "skills"
root.mkdir()
target = tmp_path / "existing"
target.mkdir()
(root / "my-skill").symlink_to(target, target_is_directory=True)
result = run_cli("init_skill", "my-skill", "--path", root, cwd=tmp_path)
assert result.returncode == 1, result.stdout + result.stderr
assert not list(target.iterdir())
def test_package_includes_regular_files_and_skips_symbolic_links(tmp_path):
# Existing skills may use names up to the validator's 64-character limit.
name = "s" * 64
skill = tmp_path / name
assets = skill / "assets"
assets.mkdir(parents=True)
(skill / "SKILL.md").write_text(
f"---\nname: {name}\ndescription: Example skill.\n---\n", encoding="utf-8"
)
(assets / "example.txt").write_text("Example asset.\n", encoding="utf-8")
(assets / "cached.pyc").touch()
(skill / "evals").mkdir()
(skill / "evals" / "fixture.json").touch()
fixtures = tmp_path / "fixtures"
fixtures.mkdir()
(fixtures / "sample.txt").write_text("Sample fixture.\n", encoding="utf-8")
(assets / "file-link").symlink_to(fixtures / "sample.txt")
(assets / "dir-link").symlink_to(fixtures, target_is_directory=True)
(assets / "internal-link").symlink_to("example.txt")
(assets / "broken-link").symlink_to("missing")
# The default output can be the source directory, including on a repeat run.
for _ in range(2):
result = run_cli("package_skill", skill, cwd=skill)
assert result.returncode == 0, result.stdout + result.stderr
with zipfile.ZipFile(skill / f"{name}.skill") as package:
assert set(package.namelist()) == {
f"{name}/SKILL.md",
f"{name}/assets/example.txt",
}
assert package.read(f"{name}/assets/example.txt") == b"Example asset.\n"
def test_package_requires_regular_manifest(tmp_path):
skill = tmp_path / "example-skill"
skill.mkdir()
template = tmp_path / "template.md"
template.write_text(
"---\nname: example-skill\ndescription: Example skill.\n---\n", encoding="utf-8"
)
(skill / "SKILL.md").symlink_to(template)
output = tmp_path / "dist"
result = run_cli("package_skill", skill, output, cwd=tmp_path)
assert result.returncode == 1, result.stdout + result.stderr
assert not (output / "example-skill.skill").exists()
def test_package_rejects_output_file_link(tmp_path):
skill = tmp_path / "example-skill"
skill.mkdir()
(skill / "SKILL.md").write_text(
"---\nname: example-skill\ndescription: Example skill.\n---\n", encoding="utf-8"
)
target = tmp_path / "sample.txt"
target.write_bytes(b"Example fixture.")
archive = tmp_path / "example-skill.skill"
archive.symlink_to(target)
result = run_cli("package_skill", skill, cwd=tmp_path)
assert result.returncode == 1, result.stdout + result.stderr
assert archive.is_symlink()
assert target.read_bytes() == b"Example fixture."