diff --git a/src/songsplit/container.py b/src/songsplit/container.py new file mode 100644 index 0000000..75a4621 --- /dev/null +++ b/src/songsplit/container.py @@ -0,0 +1,309 @@ +"""Songpack container implementation (packing and secure unpacking). + +Follows Songpack specification v1.0, sections 1, 11, 12, and 13. +""" + +import json +import logging +import os +import re +import shutil +import tempfile +import zipfile +from datetime import UTC, datetime +from pathlib import Path +from typing import Literal + +from songsplit.pipeline.runner import compute_file_sha256 +from songsplit.schema.manifest import ManifestDocument, ManifestFileInfo + +logger = logging.getLogger("songsplit.container") + +# Security limits according to Section 12 +MAX_ENTRIES = 64 +MAX_TOTAL_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB +MAX_JSON_SIZE = 32 * 1024 * 1024 # 32 MB +MAX_STEM_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB +MAX_COMPRESSION_RATIO = 100.0 +MAX_TRACKS = 32 + +RESERVED_WINDOWS_NAMES = { + "CON", + "PRN", + "AUX", + "NUL", + *(f"COM{i}" for i in range(1, 10)), + *(f"LPT{i}" for i in range(1, 10)), +} + +WHITELIST_PATTERNS = [ + re.compile(r"^manifest\.json$"), + re.compile(r"^meta\.json$"), + re.compile(r"^tempo\.json$"), + re.compile(r"^vocals\.json$"), + re.compile(r"^vocals_f0\.json$"), + re.compile(r"^chords\.json$"), + re.compile(r"^tracks/[a-z0-9_]+\.json$"), + re.compile(r"^stems/[a-z0-9_]+\.(wav|flac)$"), + re.compile(r"^export/song\.txt$"), + re.compile(r"^cover\.(jpg|jpeg|png)$"), +] + + +class SongpackSecurityError(Exception): + """Raised when a songpack violates security rules.""" + + +def is_path_safe(rel_path: str) -> bool: + """Check if relative path satisfies Section 12 traversal and platform rules.""" + if "\\" in rel_path or ":" in rel_path: + return False + + parts = rel_path.split("/") + if any(p == ".." or p == "." or not p for p in parts): + return False + + for part in parts: + stem_name = part.split(".")[0].upper() + if stem_name in RESERVED_WINDOWS_NAMES: + return False + + return True + + +def is_whitelisted(rel_path: str) -> bool: + """Check if relative path matches allowed songpack files.""" + return any(pattern.match(rel_path) for pattern in WHITELIST_PATTERNS) + + +def build_manifest_for_dir( + song_dir: Path, variant: Literal["full", "data"] = "full" +) -> ManifestDocument: + """Scan song directory and generate or update manifest.json.""" + manifest_path = song_dir / "manifest.json" + now_iso = datetime.now(UTC).isoformat() + + manifest: ManifestDocument + if manifest_path.exists(): + try: + with open(manifest_path, encoding="utf-8") as f: + manifest = ManifestDocument.model_validate(json.load(f)) + manifest.modified = now_iso + except Exception: + manifest = ManifestDocument(created=now_iso, modified=now_iso) + else: + manifest = ManifestDocument(created=now_iso, modified=now_iso) + + manifest.variant = variant + manifest.audio_included = variant == "full" + + files_list: list[ManifestFileInfo] = [] + + # Map roles + role_mapping = { + "meta.json": ("meta", None), + "tempo.json": ("tempo", None), + "vocals.json": ("vocals", None), + "vocals_f0.json": ("vocals_f0", None), + "chords.json": ("chords", None), + "export/song.txt": ("ultrastar", None), + } + + for root, _, filenames in os.walk(song_dir): + rel_root = Path(root).relative_to(song_dir) + if any(part.startswith(".") for part in rel_root.parts): + continue + + for fname in sorted(filenames): + rel_file = (rel_root / fname).as_posix() if str(rel_root) != "." else fname + file_path = song_dir / rel_file + + if rel_file == "manifest.json" or rel_file.startswith("."): + continue + + # Skip stems in data variant + if variant == "data" and rel_file.startswith("stems/"): + continue + + role: str = "meta" + stem_name: str | None = None + if rel_file in role_mapping: + role, _ = role_mapping[rel_file] + elif rel_file.startswith("tracks/"): + role = "track" + elif rel_file.startswith("stems/"): + role = "stem" + stem_name = Path(fname).stem + elif rel_file.startswith("cover."): + role = "cover" + + sha = compute_file_sha256(file_path) + size = file_path.stat().st_size + files_list.append( + ManifestFileInfo( + path=rel_file, + role=role, # type: ignore[arg-type] + schema_version="1.0" if rel_file.endswith(".json") else None, + sha256=sha, + size=size, + stem=stem_name, # type: ignore[arg-type] + ) + ) + + manifest.files = files_list + return manifest + + +def pack_songpack( + song_dir: Path, + output_path: Path | None = None, + variant: Literal["full", "data"] = "full", +) -> Path: + """Pack song directory into a .songpack archive. + + - manifest.json is guaranteed to be the first ZIP entry. + - Audio stems (.wav, .flac) are stored uncompressed (ZIP_STORED). + - JSON and text files are compressed (ZIP_DEFLATED). + - .cache/ is omitted. + """ + song_dir = song_dir.resolve() + if output_path is None: + output_path = song_dir.parent / f"{song_dir.name}.songpack" + output_path = output_path.resolve() + + # Generate / update manifest.json + manifest = build_manifest_for_dir(song_dir, variant=variant) + manifest_bytes = manifest.model_dump_json(indent=2).encode("utf-8") + + # Atomic write to temporary zip first + temp_zip = output_path.with_suffix(".tmp.zip") + if temp_zip.exists(): + temp_zip.unlink() + + with zipfile.ZipFile(temp_zip, mode="w") as zf: + # First entry MUST be manifest.json (Section 1) + zf.writestr("manifest.json", manifest_bytes, compress_type=zipfile.ZIP_DEFLATED) + + for item in manifest.files: + file_abs = song_dir / item.path + if not file_abs.is_file(): + continue + + compress_type = ( + zipfile.ZIP_STORED + if item.path.endswith((".wav", ".flac")) + else zipfile.ZIP_DEFLATED + ) + zf.write(file_abs, arcname=item.path, compress_type=compress_type) + + temp_zip.replace(output_path) + # Also write manifest.json to song_dir + (song_dir / "manifest.json").write_bytes(manifest_bytes) + logger.info("Created songpack %s (variant: %s)", output_path, variant) + return output_path + + +def unpack_songpack(songpack_path: Path, output_dir: Path) -> Path: + """Securely extract a .songpack archive according to Section 12 rules. + + - Extracts into a temporary directory first. + - Enforces whitelist, path traversal guards, zip bomb / file size limits. + - Moves atomically into destination. + """ + songpack_path = songpack_path.resolve() + if not songpack_path.is_file(): + raise FileNotFoundError(f"Songpack not found: {songpack_path}") + + with tempfile.TemporaryDirectory(prefix="songpack_unpack_") as tmp_dir_str: + tmp_dir = Path(tmp_dir_str) + extracted_dir = tmp_dir / "unpacked" + extracted_dir.mkdir(parents=True, exist_ok=True) + + with zipfile.ZipFile(songpack_path, "r") as zf: + infolist = zf.infolist() + if len(infolist) > MAX_ENTRIES: + raise SongpackSecurityError( + f"Too many archive entries: {len(infolist)} > {MAX_ENTRIES}" + ) + + total_uncompressed_bytes = 0 + track_count = 0 + + for info in infolist: + # Reject directories, symlinks, device files + if info.is_dir(): + continue + # Check for symlink (Unix mode 0o120000) + if (info.external_attr >> 16) & 0o120000 == 0o120000: + raise SongpackSecurityError(f"Symlinks not allowed: {info.filename}") + + rel_path = info.filename + if not is_path_safe(rel_path): + raise SongpackSecurityError(f"Unsafe path detected: {rel_path}") + + if not is_whitelisted(rel_path): + logger.warning("Skipping non-whitelisted file: %s", rel_path) + continue + + if rel_path.startswith("tracks/"): + track_count += 1 + if track_count > MAX_TRACKS: + raise SongpackSecurityError(f"Too many tracks: > {MAX_TRACKS}") + + # Compression ratio check (zip bomb defense) + if info.compress_size > 0: + ratio = info.file_size / info.compress_size + if ratio > MAX_COMPRESSION_RATIO: + raise SongpackSecurityError( + f"Compression ratio too high ({ratio:.1f}:1) for {rel_path}" + ) + + # Size limits per type + if rel_path.endswith(".json") and info.file_size > MAX_JSON_SIZE: + raise SongpackSecurityError( + f"JSON file too large: {info.file_size} > {MAX_JSON_SIZE}" + ) + if rel_path.startswith("stems/") and info.file_size > MAX_STEM_SIZE: + raise SongpackSecurityError( + f"Stem audio too large: {info.file_size} > {MAX_STEM_SIZE}" + ) + + total_uncompressed_bytes += info.file_size + if total_uncompressed_bytes > MAX_TOTAL_SIZE: + raise SongpackSecurityError( + f"Total uncompressed size exceeded: {total_uncompressed_bytes} > {MAX_TOTAL_SIZE}" + ) + + # Extract safely + dest_file = extracted_dir / rel_path + dest_file.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as src, open(dest_file, "wb") as dst: + shutil.copyfileobj(src, dst) + + # Validate extracted manifest + manifest_file = extracted_dir / "manifest.json" + if not manifest_file.exists(): + raise SongpackSecurityError("manifest.json missing in songpack") + + try: + with open(manifest_file, encoding="utf-8") as f: + manifest_doc = ManifestDocument.model_validate(json.load(f)) + if manifest_doc.format != "songpack": + raise SongpackSecurityError(f"Invalid format: {manifest_doc.format}") + except Exception as e: + raise SongpackSecurityError(f"Invalid manifest.json: {e}") from e + + # Atomic copy/move to destination + output_dir = output_dir.resolve() + output_dir.mkdir(parents=True, exist_ok=True) + for item in extracted_dir.iterdir(): + target = output_dir / item.name + if target.exists(): + if target.is_dir(): + shutil.rmtree(target) + else: + target.unlink() + shutil.move(str(item), str(target)) + + logger.info("Successfully unpacked songpack to %s", output_dir) + return output_dir diff --git a/src/songsplit/schema/tempo.py b/src/songsplit/schema/tempo.py index e5a4b78..3e224a2 100644 --- a/src/songsplit/schema/tempo.py +++ b/src/songsplit/schema/tempo.py @@ -27,6 +27,10 @@ class TimeSignatureEntry(EditableItem): denominator: int = Field(default=4, gt=0) +# Backward-compatible alias +TimeSignature = TimeSignatureEntry + + class TempoDocument(SongPackageBase): """Songpack tempo document (tempo.json).""" diff --git a/tests/test_container.py b/tests/test_container.py new file mode 100644 index 0000000..122b9ab --- /dev/null +++ b/tests/test_container.py @@ -0,0 +1,99 @@ +"""Tests for songpack container packing and secure unpacking.""" + +import json +import zipfile +from pathlib import Path + +import pytest + +from songsplit.container import ( + SongpackSecurityError, + build_manifest_for_dir, + pack_songpack, + unpack_songpack, +) + + +def test_build_manifest(tmp_path: Path): + song_dir = tmp_path / "song" + song_dir.mkdir() + (song_dir / "meta.json").write_text('{"schema_version": "1.0"}', encoding="utf-8") + stems_dir = song_dir / "stems" + stems_dir.mkdir() + (stems_dir / "vocals.wav").write_bytes(b"RIFFdummyWAVdata") + + manifest = build_manifest_for_dir(song_dir, variant="full") + assert manifest.format == "songpack" + assert manifest.variant == "full" + assert manifest.audio_included is True + paths = [f.path for f in manifest.files] + assert "meta.json" in paths + assert "stems/vocals.wav" in paths + + manifest_data = build_manifest_for_dir(song_dir, variant="data") + assert manifest_data.variant == "data" + assert manifest_data.audio_included is False + assert "stems/vocals.wav" not in [f.path for f in manifest_data.files] + + +def test_pack_and_unpack_roundtrip(tmp_path: Path): + song_dir = tmp_path / "song" + song_dir.mkdir() + (song_dir / "meta.json").write_text('{"title": "Test Song"}', encoding="utf-8") + (song_dir / "tempo.json").write_text('{"schema_version": "1.0"}', encoding="utf-8") + stems_dir = song_dir / "stems" + stems_dir.mkdir() + (stems_dir / "vocals.wav").write_bytes(b"audio-bytes-vocals") + + tracks_dir = song_dir / "tracks" + tracks_dir.mkdir() + (tracks_dir / "guitar.json").write_text('{"kind": "strumming"}', encoding="utf-8") + + archive_path = tmp_path / "song.songpack" + pack_songpack(song_dir, archive_path) + + assert archive_path.is_file() + + # Check zip properties + with zipfile.ZipFile(archive_path, "r") as zf: + infolist = zf.infolist() + # First entry must be manifest.json + assert infolist[0].filename == "manifest.json" + # Audio stems must be ZIP_STORED + stem_info = zf.getinfo("stems/vocals.wav") + assert stem_info.compress_type == zipfile.ZIP_STORED + # JSON must be ZIP_DEFLATED + meta_info = zf.getinfo("meta.json") + assert meta_info.compress_type == zipfile.ZIP_DEFLATED + + # Unpack + dest_dir = tmp_path / "unpacked_song" + unpack_songpack(archive_path, dest_dir) + + assert (dest_dir / "manifest.json").is_file() + assert (dest_dir / "meta.json").is_file() + assert (dest_dir / "tracks" / "guitar.json").is_file() + assert (dest_dir / "stems" / "vocals.wav").read_bytes() == b"audio-bytes-vocals" + + +def test_unpack_security_traversal(tmp_path: Path): + bad_zip = tmp_path / "traversal.songpack" + with zipfile.ZipFile(bad_zip, "w") as zf: + zf.writestr("manifest.json", '{"format": "songpack", "schema_version": "1.0", "created": "", "modified": ""}') + zf.writestr("../evil.txt", "evil") + + dest = tmp_path / "out" + with pytest.raises(SongpackSecurityError, match="Unsafe path"): + unpack_songpack(bad_zip, dest) + + +def test_unpack_security_max_entries(tmp_path: Path): + bad_zip = tmp_path / "many_entries.songpack" + with zipfile.ZipFile(bad_zip, "w") as zf: + zf.writestr("manifest.json", '{"format": "songpack", "schema_version": "1.0", "created": "", "modified": ""}') + for i in range(70): + zf.writestr(f"tracks/track_{i}.json", "{}") + + dest = tmp_path / "out" + with pytest.raises(SongpackSecurityError, match="Too many archive entries"): + unpack_songpack(bad_zip, dest)