fix(ingest): reserve URL capture names exclusively

Refs #5018.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit de8345aa15)
This commit is contained in:
azizur100389 authored and safishamsi committed 2026-11-07 22:31:44 +00:00
1 parent 4feadeda0d
commit cd54401097
3 files changed
+67 -8

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. | | YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. | | Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is parameterized to avoid unchecked traversal where appropriate. | | Symlink traversal | `os.walk(..., followlinks=False)` is parameterized to avoid unchecked traversal where appropriate. |
| Symlink escape during ingest | `ingest` writes through `lstat` and refuses to replace an existing directory entry, including a symlink, so a crafted source tree cannot redirect writes outside the output directory. | | Symlink escape during ingest | `ingest` checks names with `lstat` and creates capture files exclusively. If another entry takes the selected name, the capture retries with a numbered name. |
| Credentials in persisted text | `security.redact_secrets()` replaces credential-shaped substrings in labels and rationale text before they are written to `graph.json`. | | Credentials in persisted text | `security.redact_secrets()` replaces credential-shaped substrings in labels and rationale text before they are written to `graph.json`. |
| Destructive uninstall | `uninstall --purge` refuses to delete the project folder, the home directory, or a filesystem root, including when `GRAPHIFY_OUT` points outside the project. | | Destructive uninstall | `uninstall --purge` refuses to delete the project folder, the home directory, or a filesystem root, including when `GRAPHIFY_OUT` points outside the project. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. | | Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
+30 -7
View File
@@ -1,11 +1,14 @@
# fetch URLs (tweet/arxiv/pdf/web) and save as annotated markdown # fetch URLs (tweet/arxiv/pdf/web) and save as annotated markdown
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable
from contextlib import suppress
import json import json
import re import re
import uuid import uuid
import urllib.error import urllib.error
import urllib.parse import urllib.parse
from datetime import datetime, timezone from datetime import datetime, timezone
from os import linesep
from pathlib import Path from pathlib import Path
from graphify.security import safe_fetch, safe_fetch_text, validate_url from graphify.security import safe_fetch, safe_fetch_text, validate_url
@@ -226,7 +229,7 @@ def _free_capture_path(target_dir: Path, filename: str) -> Path:
Uses lstat so no existing directory entry is replaced, including a Uses lstat so no existing directory entry is replaced, including a
dangling symlink that a write would otherwise follow out of the corpus. dangling symlink that a write would otherwise follow out of the corpus.
Selection and writing are separate; concurrent captures are not atomic. The writer still needs an exclusive open to reserve the selected name.
""" """
stem, suffix = Path(filename).stem, Path(filename).suffix stem, suffix = Path(filename).stem, Path(filename).suffix
out_path = target_dir / filename out_path = target_dir / filename
@@ -240,11 +243,32 @@ def _free_capture_path(target_dir: Path, filename: str) -> Path:
counter += 1 counter += 1
def _write_capture(target_dir: Path, filename: str, content: str | Callable[[], bytes]) -> Path:
"""Write a capture under a unique name without clobbering another writer."""
out_path = _free_capture_path(target_dir, filename)
# Inspect the destination before fetching, and fetch at most once per capture.
payload = content() if callable(content) else content
if isinstance(payload, str):
# Preserve the newline translation of Path.write_text on Windows.
payload = payload.replace("\n", linesep).encode("utf-8")
while True:
try:
handle = out_path.open("xb")
except FileExistsError:
out_path = _free_capture_path(target_dir, filename)
continue
try:
with handle:
handle.write(payload)
except (OSError, UnicodeError):
with suppress(OSError):
out_path.unlink()
raise
return out_path
def _download_binary(url: str, suffix: str, target_dir: Path) -> Path: def _download_binary(url: str, suffix: str, target_dir: Path) -> Path:
"""Save a sequential capture without replacing an existing directory entry.""" return _write_capture(target_dir, _safe_filename(url, suffix), lambda: safe_fetch(url))
out_path = _free_capture_path(target_dir, _safe_filename(url, suffix))
out_path.write_bytes(safe_fetch(url))
return out_path
def ingest(url: str, target_dir: Path, author: str | None = None, contributor: str | None = None) -> Path: def ingest(url: str, target_dir: Path, author: str | None = None, contributor: str | None = None) -> Path:
@@ -288,8 +312,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
except (urllib.error.HTTPError, urllib.error.URLError, OSError) as exc: except (urllib.error.HTTPError, urllib.error.URLError, OSError) as exc:
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
out_path = _free_capture_path(target_dir, filename) out_path = _write_capture(target_dir, filename, content)
out_path.write_text(content, encoding="utf-8")
print(f"Saved {url_type}: {out_path.name}") print(f"Saved {url_type}: {out_path.name}")
return out_path return out_path
+36
View File
@@ -0,0 +1,36 @@
"""Concurrent URL captures must reserve distinct names."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
import pytest
from graphify import ingest as ingest_mod
@pytest.mark.parametrize("suffix", [".pdf", ""])
def test_concurrent_captures_preserve_both_payloads(tmp_path, monkeypatch, suffix):
preferred = tmp_path / ("example_org_report_pdf.pdf" if suffix else "example_org_report.md")
original_lstat = Path.lstat
both_selected = Barrier(2, timeout=10)
def lstat(path, *args, **kwargs):
try:
return original_lstat(path, *args, **kwargs)
except FileNotFoundError:
if path == preferred:
both_selected.wait()
raise
monkeypatch.setattr(Path, "lstat", lstat)
monkeypatch.setattr(ingest_mod, "validate_url", lambda url: url)
monkeypatch.setattr(ingest_mod, "safe_fetch", lambda url: url.encode())
monkeypatch.setattr(ingest_mod, "_fetch_webpage", lambda url, *_: (url, preferred.name))
urls = [f"https://example.org/report{suffix}?capture={number}" for number in (1, 2)]
with ThreadPoolExecutor(max_workers=2) as pool:
paths = list(pool.map(lambda url: ingest_mod.ingest(url, tmp_path), urls))
assert len(set(paths)) == 2
assert {path.read_text(encoding="utf-8") for path in paths} == set(urls)