Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ node_modules/
apps/studio/dist/
.DS_Store
.cursor/
# Bytecode / local caches (never commit)
__pycache__/
*.py[cod]
*.tsbuildinfo
ext_weights/
.ci-investigate/
*.wav
*.mp3
*.mp4
Expand Down
3 changes: 2 additions & 1 deletion packages/executor/src/groovy/executor/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from groovy.executor.audio import AudioBuffer
from groovy.executor.cache import CacheStore
from groovy.executor.cache import CacheStore, safe_cache_id
from groovy.executor.engine import ExecutionResult, Executor, JobContext
from groovy.executor.signal_integrity import (
ALL_TEMPLATE_INTEGRITY_SPECS,
Expand All @@ -21,6 +21,7 @@
__all__ = [
"AudioBuffer",
"CacheStore",
"safe_cache_id",
"ExecutionResult",
"Executor",
"JobContext",
Expand Down
108 changes: 67 additions & 41 deletions packages/executor/src/groovy/executor/cache.py

Large diffs are not rendered by default.

21 changes: 20 additions & 1 deletion server/src/groovy/server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1800,7 +1800,10 @@ def workflow_provenance(body: ProvenanceRequest) -> dict[str, Any]:

@app.get("/api/cache/{cache_id}/provenance")
def cache_provenance(cache_id: str) -> dict[str, Any]:
record = _executor.cache.read_provenance(cache_id)
try:
record = _executor.cache.read_provenance(cache_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not record:
raise HTTPException(status_code=404, detail="Provenance not found")
return record
Expand All @@ -1810,6 +1813,8 @@ def cache_provenance(cache_id: str) -> dict[str, Any]:
def get_authenticity(report_id: str) -> JSONResponse:
try:
report = _executor.cache.load_authenticity(report_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Authenticity report not found") from exc
return JSONResponse(report.record, headers={"Cache-Control": "no-store"})
Expand All @@ -1819,6 +1824,8 @@ def get_authenticity(report_id: str) -> JSONResponse:
def get_sample_check(report_id: str) -> JSONResponse:
try:
report = _executor.cache.load_sample_check(report_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Sample check report not found") from exc
return JSONResponse(report.record, headers={"Cache-Control": "no-store"})
Expand Down Expand Up @@ -1986,6 +1993,8 @@ def cache_metrics(cache_id: str) -> dict[str, Any]:
try:
metrics = measure_clip(_executor.cache, cache_id, label=cache_id)
return metrics.to_dict()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Cache not found") from exc

Expand All @@ -1994,6 +2003,8 @@ def cache_metrics(cache_id: str) -> dict[str, Any]:
def cache_meta(cache_id: str) -> dict[str, Any]:
try:
return _executor.cache.read_meta(cache_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Cache not found") from exc

Expand All @@ -2008,6 +2019,8 @@ def cache_preview(cache_id: str, format: str = "wav") -> Response:
data = _executor.cache.preview_wav_bytes(cache_id)
return Response(content=data, media_type="audio/wav")
raise HTTPException(status_code=400, detail="Unsupported format")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Cache not found") from exc

Expand All @@ -2016,6 +2029,8 @@ def cache_preview(cache_id: str, format: str = "wav") -> Response:
def cache_waveform(cache_id: str, width: int = 512) -> dict[str, Any]:
try:
return _executor.cache.waveform_peaks(cache_id, width=width)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="Cache not found") from exc

Expand Down Expand Up @@ -2056,6 +2071,8 @@ def cache_trajectory(cache_id: str) -> dict[str, Any]:
def cache_midi_roll(cache_id: str) -> dict[str, Any]:
try:
return _executor.cache.midi_roll(cache_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(status_code=404, detail="MIDI cache not found") from exc

Expand All @@ -2076,6 +2093,8 @@ def compare_analyze(body: CompareAnalyzeRequest) -> dict[str, Any]:
model_id=body.model_id,
question=body.question,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except FileNotFoundError as exc:
raise HTTPException(
status_code=404,
Expand Down
45 changes: 38 additions & 7 deletions server/src/groovy/server/project_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
import shutil
from pathlib import Path

from groovy.executor.project_paths import MEDIA_EXTENSIONS

_SKIP_DIR_NAMES = {".groovy", ".git", "node_modules", ".venv"}

# Hard cap for localhost uploads (video demos can be large; refuse unbounded bodies).
MAX_UPLOAD_BYTES = 512 * 1024 * 1024


def sidecar_path_for_audio(audio_path: Path) -> Path:
return audio_path.with_name(f"{audio_path.stem}.provenance.json")
Expand All @@ -25,18 +30,41 @@ def iter_project_files_named(project_dir: Path, name: str) -> list[Path]:
return matches


def _unique_upload_dest(dest_dir: Path, safe_name: str) -> Path:
"""Avoid silent overwrite: first free ``name``, then ``stem-1.ext``, ``stem-2.ext``, …"""
candidate = dest_dir / safe_name
if not candidate.exists():
return candidate
stem = Path(safe_name).stem
suffix = Path(safe_name).suffix
n = 1
while True:
candidate = dest_dir / f"{stem}-{n}{suffix}"
if not candidate.exists():
return candidate
n += 1


def resolve_uploaded_audio(project_dir: Path, filename: str, payload: bytes) -> str:
"""
Store ``payload`` under assets/uploads/, or reuse an existing project file.

If exactly one same-name, same-size audio already sits next to a
``*.provenance.json`` sidecar, return that path. Otherwise write to uploads
and copy a uniquely named sidecar if one exists.
(unique basename — never silent overwrite) and copy a uniquely named sidecar
if one exists.
"""
safe_name = Path(filename).name
if not safe_name or safe_name in {".", ".."}:
raise ValueError("Missing filename")

suffix = Path(safe_name).suffix.lower()
if suffix not in MEDIA_EXTENSIONS:
raise ValueError(f"Unsupported file type: {suffix or '(none)'}")

if len(payload) > MAX_UPLOAD_BYTES:
raise ValueError(f"File too large (max {MAX_UPLOAD_BYTES} bytes)")

existing = [
path
for path in iter_project_files_named(project_dir, safe_name)
Expand All @@ -47,14 +75,17 @@ def resolve_uploaded_audio(project_dir: Path, filename: str, payload: bytes) ->

dest_dir = project_dir / "assets" / "uploads"
dest_dir.mkdir(parents=True, exist_ok=True)
dest = dest_dir / safe_name
dest = _unique_upload_dest(dest_dir, safe_name)
dest.write_bytes(payload)

sidecar_name = sidecar_path_for_audio(dest).name
dest_sidecar = sidecar_path_for_audio(dest)
candidates = [
path for path in iter_project_files_named(project_dir, sidecar_name) if path != dest_sidecar
]
# Prefer a sidecar named for the *original* basename (export reuse), else dest stem.
sidecar_names = {sidecar_path_for_audio(Path(safe_name)).name, dest_sidecar.name}
candidates: list[Path] = []
for sidecar_name in sidecar_names:
for path in iter_project_files_named(project_dir, sidecar_name):
if path != dest_sidecar and path not in candidates:
candidates.append(path)
if len(candidates) == 1:
shutil.copy2(candidates[0], dest_sidecar)
return f"assets/uploads/{safe_name}"
return f"assets/uploads/{dest.name}"
Binary file not shown.
Binary file removed tests/__pycache__/audio_tolerance.cpython-312.pyc
Binary file not shown.
Binary file removed tests/__pycache__/template_fixtures.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
26 changes: 26 additions & 0 deletions tests/test_project_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from pathlib import Path

import pytest

from groovy.server.project_assets import resolve_uploaded_audio


Expand Down Expand Up @@ -29,3 +31,27 @@ def test_upload_copies_sidecar_into_uploads_when_no_matching_export(tmp_path: Pa
sidecar = tmp_path / "assets" / "uploads" / "take.provenance.json"
assert sidecar.is_file()
assert sidecar.read_text() == '{"ok": true}'


def test_upload_rejects_unsupported_extension(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="Unsupported file type"):
resolve_uploaded_audio(tmp_path, "payload.exe", b"MZ")


def test_upload_rejects_oversized_payload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import groovy.server.project_assets as assets

monkeypatch.setattr(assets, "MAX_UPLOAD_BYTES", 16)
with pytest.raises(ValueError, match="File too large"):
resolve_uploaded_audio(tmp_path, "big.wav", b"x" * 17)


def test_upload_does_not_silently_overwrite(tmp_path: Path) -> None:
dest_dir = tmp_path / "assets" / "uploads"
dest_dir.mkdir(parents=True)
(dest_dir / "take.wav").write_bytes(b"first")

path = resolve_uploaded_audio(tmp_path, "take.wav", b"second")
assert path == "assets/uploads/take-1.wav"
assert (dest_dir / "take.wav").read_bytes() == b"first"
assert (dest_dir / "take-1.wav").read_bytes() == b"second"
61 changes: 61 additions & 0 deletions tests/test_safe_cache_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from __future__ import annotations

import uuid
from pathlib import Path

import numpy as np
import pytest

from groovy.executor.audio import AudioBuffer
from groovy.executor.cache import CacheStore, safe_cache_id


def test_safe_cache_id_accepts_uuid4() -> None:
cid = str(uuid.uuid4())
assert safe_cache_id(cid) == cid


@pytest.mark.parametrize("ok", ["left", "right", "a", "mix-1", "n2"])
def test_safe_cache_id_accepts_short_fixture_ids(ok: str) -> None:
assert safe_cache_id(ok) == ok


@pytest.mark.parametrize(
"bad",
[
"",
"../etc/passwd",
"abc/../def",
"foo/bar",
r"foo\bar",
"..",
"has space-xxxxxxxx",
"-leading-hyphen",
],
)
def test_safe_cache_id_rejects_traversal(bad: str) -> None:
with pytest.raises(ValueError):
safe_cache_id(bad)


def test_cache_store_read_meta_rejects_traversal(tmp_path: Path) -> None:
store = CacheStore(tmp_path)
with pytest.raises(ValueError, match="Invalid cache_id"):
store.read_meta("../secret")


def test_cache_store_roundtrip_uuid(tmp_path: Path) -> None:
store = CacheStore(tmp_path)
pcm = np.zeros((1, 8), dtype=np.float64)
buf = AudioBuffer.from_planar(pcm, sample_rate=48_000)
store.write_audio(buf, pcm)
meta = store.read_meta(buf.id)
assert meta["id"] == buf.id
_, loaded = store.load_audio(buf.id)
assert loaded.shape == pcm.shape


def test_cache_store_provenance_rejects_encoded_traversal(tmp_path: Path) -> None:
store = CacheStore(tmp_path)
with pytest.raises(ValueError, match="Invalid cache_id"):
store.read_provenance("..%2fetc%2fpasswd")
Loading