portolan-python 0.1.3__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: portolan-python
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: A lightweight Python implementation of the Portolan specification.
5
5
  Author: Portolan contributors
6
6
  License: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "portolan-python"
3
- version = "0.1.3"
3
+ version = "0.1.4"
4
4
  description = "A lightweight Python implementation of the Portolan specification."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -3,12 +3,17 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
7
+ import shutil
8
+ import tempfile
6
9
  from collections.abc import Callable
10
+ from contextlib import contextmanager
7
11
  from dataclasses import dataclass
8
12
  from pathlib import Path
9
13
  from typing import Any
14
+ from urllib.error import HTTPError
10
15
  from urllib.parse import urljoin, urlparse
11
- from urllib.request import Request, urlopen
16
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
12
17
 
13
18
  JsonObject = dict[str, Any]
14
19
 
@@ -70,6 +75,7 @@ def download_registry_catalog(
70
75
  catalog_url: str,
71
76
  output_dir: Path,
72
77
  *,
78
+ expected_catalog_id: str | None = None,
73
79
  fetch_json: Callable[[str], JsonObject] | None = None,
74
80
  ) -> Path:
75
81
  """Download a published catalog snapshot for local workflows."""
@@ -77,17 +83,34 @@ def download_registry_catalog(
77
83
  fetch = fetch_json or _fetch_json
78
84
  catalog = fetch(catalog_url)
79
85
  catalog_id = str(catalog.get("id") or _fallback_catalog_id(catalog_url))
80
- if catalog_id in {"", ".", ".."} or Path(catalog_id).name != catalog_id or "\\" in catalog_id:
81
- raise ValueError(f"Catalog id must be a safe directory name: {catalog_id}")
86
+ _validate_catalog_id(catalog_id)
87
+ if expected_catalog_id is not None:
88
+ _validate_catalog_id(expected_catalog_id)
89
+ if catalog_id != expected_catalog_id:
90
+ raise ValueError(
91
+ f"Catalog id '{catalog_id}' does not match registry id '{expected_catalog_id}'"
92
+ )
82
93
  catalog_root = output_dir / catalog_id
83
- _write_catalog_tree(catalog_url, catalog, catalog_url, catalog_root, fetch)
94
+ output_dir.mkdir(parents=True, exist_ok=True)
95
+ with _catalog_lock(output_dir, catalog_id):
96
+ _validate_catalog_root(output_dir, catalog_root)
97
+ staging_root = Path(
98
+ tempfile.mkdtemp(prefix=f".{catalog_id}.staging-", dir=output_dir.resolve())
99
+ )
100
+ try:
101
+ _write_catalog_tree(catalog_url, catalog, catalog_url, staging_root, fetch)
102
+ _publish_snapshot(staging_root, catalog_root, output_dir)
103
+ except BaseException:
104
+ shutil.rmtree(staging_root, ignore_errors=True)
105
+ raise
84
106
  return catalog_root
85
107
 
86
108
 
87
109
  def _fetch_json(url: str) -> JsonObject:
88
110
  _validate_remote_url(url)
89
111
  request = Request(url, headers={"User-Agent": "portolan-python"})
90
- with urlopen(request, timeout=30) as response:
112
+ opener = build_opener(_SameOriginRedirectHandler(url))
113
+ with opener.open(request, timeout=30) as response:
91
114
  data = json.loads(response.read().decode("utf-8"))
92
115
  if not isinstance(data, dict):
93
116
  raise TypeError(f"Expected JSON object from {url}")
@@ -100,6 +123,75 @@ def _validate_remote_url(url: str) -> None:
100
123
  raise ValueError(f"Registry URL must use HTTP or HTTPS: {url}")
101
124
 
102
125
 
126
+ class _SameOriginRedirectHandler(HTTPRedirectHandler):
127
+ def __init__(self, original_url: str) -> None:
128
+ self._origin = _url_origin(original_url)
129
+ super().__init__()
130
+
131
+ def redirect_request(
132
+ self,
133
+ req: Request,
134
+ fp: Any,
135
+ code: int,
136
+ msg: str,
137
+ headers: Any,
138
+ newurl: str,
139
+ ) -> Request | None:
140
+ if _url_origin(newurl) != self._origin:
141
+ raise HTTPError(newurl, code, f"Redirect changed origin: {newurl}", headers, fp)
142
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
143
+
144
+
145
+ def _url_origin(url: str) -> tuple[str, str]:
146
+ parsed = urlparse(url)
147
+ return parsed.scheme.lower(), parsed.netloc.lower()
148
+
149
+
150
+ def _validate_catalog_id(catalog_id: str) -> None:
151
+ if catalog_id in {"", ".", ".."} or Path(catalog_id).name != catalog_id or "\\" in catalog_id:
152
+ raise ValueError(f"Catalog id must be a safe directory name: {catalog_id}")
153
+
154
+
155
+ @contextmanager
156
+ def _catalog_lock(output_dir: Path, catalog_id: str) -> Any:
157
+ lock_path = output_dir.resolve() / f".{catalog_id}.lock"
158
+ try:
159
+ descriptor = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
160
+ except FileExistsError as err:
161
+ raise RuntimeError(f"Catalog download is already in progress: {catalog_id}") from err
162
+ os.close(descriptor)
163
+ try:
164
+ yield
165
+ finally:
166
+ lock_path.unlink(missing_ok=True)
167
+
168
+
169
+ def _validate_catalog_root(output_dir: Path, catalog_root: Path) -> None:
170
+ if catalog_root.is_symlink():
171
+ raise ValueError(f"Catalog directory must not be a symlink: {catalog_root}")
172
+ if not catalog_root.resolve().is_relative_to(output_dir.resolve()):
173
+ raise ValueError(f"Catalog directory escapes output directory: {catalog_root}")
174
+
175
+
176
+ def _publish_snapshot(staging_root: Path, catalog_root: Path, output_dir: Path) -> None:
177
+ _validate_catalog_root(output_dir, catalog_root)
178
+ backup_root = Path(
179
+ tempfile.mkdtemp(prefix=f".{catalog_root.name}.backup-", dir=output_dir.resolve())
180
+ )
181
+ backup_root.rmdir()
182
+ had_previous = catalog_root.exists()
183
+ if had_previous:
184
+ catalog_root.rename(backup_root)
185
+ try:
186
+ staging_root.rename(catalog_root)
187
+ except BaseException:
188
+ if had_previous:
189
+ backup_root.rename(catalog_root)
190
+ raise
191
+ if had_previous:
192
+ shutil.rmtree(backup_root)
193
+
194
+
103
195
  def _write_catalog_tree(
104
196
  document_url: str,
105
197
  document: JsonObject,
@@ -137,9 +229,7 @@ def _write_catalog_tree(
137
229
  child_target = _target_document_path(root_url, child_url, output_root)
138
230
  owner = targets.get(child_target)
139
231
  if owner is not None and owner != child_url:
140
- raise ValueError(
141
- f"Registry documents map to the same local path: {owner}, {child_url}"
142
- )
232
+ raise ValueError(f"Registry documents map to the same local path: {owner}, {child_url}")
143
233
  child = fetch_json(child_url)
144
234
  if child.get("type") in {"Catalog", "Collection"}:
145
235
  _write_catalog_tree(
@@ -5,10 +5,13 @@ from __future__ import annotations
5
5
  import json
6
6
  from pathlib import Path
7
7
  from typing import Any
8
+ from urllib.error import HTTPError
9
+ from urllib.request import Request
8
10
 
9
11
  import pytest
10
12
 
11
13
  from portolan import download_registry_catalog, load_registry_entries
14
+ from portolan.registry import _SameOriginRedirectHandler
12
15
 
13
16
  pytestmark = pytest.mark.unit
14
17
 
@@ -266,14 +269,82 @@ def test_download_registry_catalog_rejects_symlink_escape(tmp_path: Path) -> Non
266
269
  child_url: _collection("linked", {}),
267
270
  }
268
271
 
269
- with pytest.raises(ValueError, match="escapes catalog root"):
272
+ download_registry_catalog(
273
+ root_url,
274
+ output_dir,
275
+ fetch_json=lambda url: responses[url],
276
+ )
277
+
278
+ assert not (outside_dir / "collection.json").exists()
279
+ assert (catalog_root / "linked" / "collection.json").exists()
280
+
281
+
282
+ def test_download_registry_catalog_rejects_catalog_root_symlink(tmp_path: Path) -> None:
283
+ output_dir = tmp_path / "output"
284
+ outside_dir = tmp_path / "outside"
285
+ output_dir.mkdir()
286
+ outside_dir.mkdir()
287
+ (output_dir / "demo").symlink_to(outside_dir, target_is_directory=True)
288
+
289
+ with pytest.raises(ValueError, match="Catalog directory must not be a symlink"):
270
290
  download_registry_catalog(
271
- root_url,
291
+ "https://example.test/demo/catalog.json",
272
292
  output_dir,
273
- fetch_json=lambda url: responses[url],
293
+ fetch_json=lambda url: {"type": "Catalog", "id": "demo", "links": []},
274
294
  )
275
295
 
276
- assert not (outside_dir / "collection.json").exists()
296
+ assert list(outside_dir.iterdir()) == []
297
+
298
+
299
+ def test_download_registry_catalog_rejects_registry_id_mismatch(tmp_path: Path) -> None:
300
+ with pytest.raises(ValueError, match="does not match registry id"):
301
+ download_registry_catalog(
302
+ "https://example.test/demo/catalog.json",
303
+ tmp_path,
304
+ expected_catalog_id="selected-catalog",
305
+ fetch_json=lambda url: {"type": "Catalog", "id": "other-catalog", "links": []},
306
+ )
307
+
308
+ assert not (tmp_path / "selected-catalog").exists()
309
+
310
+
311
+ def test_download_registry_catalog_preserves_snapshot_when_child_fetch_fails(
312
+ tmp_path: Path,
313
+ ) -> None:
314
+ catalog_root = tmp_path / "demo"
315
+ catalog_root.mkdir()
316
+ previous = catalog_root / "catalog.json"
317
+ previous.write_text('{"id": "previous"}\n', encoding="utf-8")
318
+ root_url = "https://example.test/demo/catalog.json"
319
+
320
+ def fetch_json(url: str) -> dict[str, Any]:
321
+ if url == root_url:
322
+ return {
323
+ "type": "Catalog",
324
+ "id": "demo",
325
+ "links": [{"rel": "child", "href": "./missing.json"}],
326
+ }
327
+ raise HTTPError(url, 503, "Unavailable", hdrs=None, fp=None)
328
+
329
+ with pytest.raises(HTTPError):
330
+ download_registry_catalog(root_url, tmp_path, fetch_json=fetch_json)
331
+
332
+ assert previous.read_text(encoding="utf-8") == '{"id": "previous"}\n'
333
+ assert not list(tmp_path.glob(".demo.staging-*"))
334
+
335
+
336
+ def test_same_origin_redirect_handler_rejects_cross_origin_redirect() -> None:
337
+ handler = _SameOriginRedirectHandler("https://example.test/demo/catalog.json")
338
+
339
+ with pytest.raises(HTTPError, match="Redirect changed origin"):
340
+ handler.redirect_request(
341
+ Request("https://example.test/demo/child.json"),
342
+ fp=None,
343
+ code=302,
344
+ msg="Found",
345
+ headers={},
346
+ newurl="http://127.0.0.1/private",
347
+ )
277
348
 
278
349
 
279
350
  def test_download_registry_catalog_rejects_local_path_collisions(tmp_path: Path) -> None:
@@ -468,7 +468,7 @@ wheels = [
468
468
 
469
469
  [[package]]
470
470
  name = "portolan-python"
471
- version = "0.1.3"
471
+ version = "0.1.4"
472
472
  source = { editable = "." }
473
473
 
474
474
  [package.optional-dependencies]