You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/06/18 13:51:09 UTC
(tooling-trusted-releases) branch sbp updated: Store quarantined archive inner directory SWHIDs in attestable files
This is an automated email from the ASF dual-hosted git repository.
sbp pushed a commit to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
The following commit(s) were added to refs/heads/sbp by this push:
new 04d61441 Store quarantined archive inner directory SWHIDs in attestable files
04d61441 is described below
commit 04d61441a6927284bbf46ac6a9654d70f1fb5efb
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Thu Jun 18 14:50:04 2026 +0100
Store quarantined archive inner directory SWHIDs in attestable files
---
atr/archives.py | 16 +++++++++++++
atr/attestable.py | 27 +++++++++++++++++++++
atr/models/attestable.py | 1 +
atr/storage/writers/revision.py | 5 ++++
atr/swhid.py | 16 ++++++-------
atr/tasks/quarantine.py | 35 +++++++++++++++++++++------
tests/unit/test_quarantine_task.py | 49 ++++++++++++++++++++++++++++++++++----
7 files changed, 130 insertions(+), 19 deletions(-)
diff --git a/atr/archives.py b/atr/archives.py
index a658fa97..4044ac8b 100644
--- a/atr/archives.py
+++ b/atr/archives.py
@@ -92,6 +92,22 @@ async def list_archive(file_path: safe.StatePath) -> list[str] | None:
return await asyncio.to_thread(_read_archive)
+def single_root_dir(directory: safe.StatePath) -> str | None:
+ subdirs: list[str] = []
+ has_other = False
+ with os.scandir(directory) as scan:
+ for entry in scan:
+ if entry.name.startswith("._"):
+ continue
+ if entry.is_dir(follow_symlinks=False):
+ subdirs.append(entry.name)
+ else:
+ has_other = True
+ if (len(subdirs) == 1) and (not has_other):
+ return subdirs[0]
+ return None
+
+
def _build_extraction_config(max_extract_size: int) -> exarch.SecurityConfig:
cfg = (
exarch.SecurityConfig()
diff --git a/atr/attestable.py b/atr/attestable.py
index 79f9932a..a78c2230 100644
--- a/atr/attestable.py
+++ b/atr/attestable.py
@@ -166,6 +166,27 @@ def compute_file_state_rows(
return rows
+def compute_swhid_dirs(
+ path_to_hash: dict[safe.RelPath, str],
+ previous: models.Attestable | None,
+ extracted: dict[str, str] | None = None,
+) -> dict[str, str]:
+ extracted = extracted or {}
+ carried: dict[str, str] = {}
+ if isinstance(previous, models.AttestableV2):
+ for hash_ref, entry in previous.hashes.items():
+ if entry.swhid_dir_inner is not None:
+ carried[hash_ref] = entry.swhid_dir_inner
+ result: dict[str, str] = {}
+ for content_hash in path_to_hash.values():
+ swhid_dir_inner = extracted.get(content_hash)
+ if swhid_dir_inner is None:
+ swhid_dir_inner = carried.get(content_hash)
+ if swhid_dir_inner is not None:
+ result[content_hash] = swhid_dir_inner
+ return result
+
+
def effective_path_provenance(
path_provenance: dict[safe.RelPath, models.ProvenanceV2] | None,
path_to_hash: dict[safe.RelPath, str],
@@ -360,6 +381,7 @@ async def write_files_data(
base_path: safe.StatePath,
classifications: dict[safe.RelPath, str] | None = None,
effective_path_provenance: dict[str, models.ProvenanceV2] | None = None,
+ swhid_dirs: dict[str, str] | None = None,
) -> None:
result = await _generate_files_data(
path_to_hash,
@@ -371,6 +393,7 @@ async def write_files_data(
base_path,
classifications=classifications,
effective_path_provenance=effective_path_provenance,
+ swhid_dirs=swhid_dirs,
)
file_path = attestable_path(project_key, version_key, revision_number)
await _atomic_write_readonly(file_path.path, result.model_dump_json(indent=2))
@@ -444,6 +467,7 @@ async def _generate_files_data(
base_path: safe.StatePath,
classifications: dict[safe.RelPath, str] | None = None,
effective_path_provenance: dict[str, models.ProvenanceV2] | None = None,
+ swhid_dirs: dict[str, str] | None = None,
) -> models.AttestableV2:
current_hash_to_paths: dict[str, set[safe.RelPath]] = {}
for path_key, hash_ref in path_to_hash.items():
@@ -452,6 +476,9 @@ async def _generate_files_data(
new_hashes = _compute_hashes_with_attribution(
current_hash_to_paths, path_to_size, previous, uploader_uid, revision_number
)
+ for hash_ref, swhid_dir_inner in (swhid_dirs or {}).items():
+ if (entry := new_hashes.get(hash_ref)) is not None:
+ entry.swhid_dir_inner = swhid_dir_inner
if classifications is None:
classifications = await compute_classifications(path_to_hash, release_policy, base_path)
diff --git a/atr/models/attestable.py b/atr/models/attestable.py
index 60185b3e..b9483dbb 100644
--- a/atr/models/attestable.py
+++ b/atr/models/attestable.py
@@ -50,6 +50,7 @@ class HashEntryV2(schema.Strict):
size: int
uploaders: list[Annotated[tuple[str, str], pydantic.BeforeValidator(tuple)]]
basenames: list[str] = schema.factory(list)
+ swhid_dir_inner: str | None = None
class GeneratorV2(enum.Enum):
diff --git a/atr/storage/writers/revision.py b/atr/storage/writers/revision.py
index b8db47ee..3e0153ff 100644
--- a/atr/storage/writers/revision.py
+++ b/atr/storage/writers/revision.py
@@ -93,6 +93,7 @@ async def finalise_revision(
version_key: safe.VersionKey,
was_quarantined: bool = False,
path_provenance: dict[safe.RelPath, atr.models.attestable.ProvenanceV2] | None = None,
+ extracted_swhids: dict[str, str] | None = None,
) -> sql.Revision:
try:
previous_attestable, merge_base_revision_key, _, merged_release = await _lock_and_merge(
@@ -130,6 +131,7 @@ async def finalise_revision(
version_key=version_key,
was_quarantined=was_quarantined,
path_provenance=path_provenance,
+ extracted_swhids=extracted_swhids,
)
@@ -149,6 +151,7 @@ async def _commit_new_revision(
version_key: safe.VersionKey,
was_quarantined: bool = False,
path_provenance: dict[safe.RelPath, atr.models.attestable.ProvenanceV2] | None = None,
+ extracted_swhids: dict[str, str] | None = None,
) -> sql.Revision:
try:
# This is the only place where models.Revision is constructed
@@ -207,6 +210,7 @@ async def _commit_new_revision(
classifications = await attestable.compute_classifications(
path_to_hash, policy_dict, new_revision_dir, archives_base
)
+ swhid_dirs = attestable.compute_swhid_dirs(path_to_hash, previous_attestable, extracted_swhids)
effective_provenance = attestable.effective_path_provenance(path_provenance, path_to_hash, previous_attestable)
await attestable.write_files_data(
@@ -221,6 +225,7 @@ async def _commit_new_revision(
new_revision_dir,
classifications=classifications,
effective_path_provenance=effective_provenance,
+ swhid_dirs=swhid_dirs,
)
if attestable.can_write_file_state_rows(previous_attestable, new_revision.parent_key):
diff --git a/atr/swhid.py b/atr/swhid.py
index e31601db..ebacc3af 100644
--- a/atr/swhid.py
+++ b/atr/swhid.py
@@ -102,7 +102,14 @@ async def content_id_from_file(path: Path) -> Identifier:
async def directory_id(root: Path) -> Identifier:
- return await asyncio.to_thread(_directory_id, root)
+ return await asyncio.to_thread(directory_id_sync, root)
+
+
+def directory_id_sync(root: Path) -> Identifier:
+ digest = _tree_digest(root)
+ if digest is None:
+ digest = _git_object_digest(_TREE, b"")
+ return Identifier(ObjectType.DIRECTORY, digest.hex())
def parse(text: str) -> Identifier:
@@ -166,13 +173,6 @@ def _content_id_from_file(path: Path) -> Identifier:
return Identifier(ObjectType.CONTENT, _blob_digest_of_file(path, size).hex())
-def _directory_id(root: Path) -> Identifier:
- digest = _tree_digest(root)
- if digest is None:
- digest = _git_object_digest(_TREE, b"")
- return Identifier(ObjectType.DIRECTORY, digest.hex())
-
-
def _entry_sort_key(entry: tuple[bytes, bytes, bytes]) -> bytes:
name, mode, _ = entry
# Git orders a directory as though its name carried a trailing slash
diff --git a/atr/tasks/quarantine.py b/atr/tasks/quarantine.py
index 06b16ed1..3a169e15 100644
--- a/atr/tasks/quarantine.py
+++ b/atr/tasks/quarantine.py
@@ -45,6 +45,7 @@ import atr.models.sql as sql
import atr.paths as paths
import atr.storage as storage
import atr.storage.writers.revision as revision
+import atr.swhid as swhid
import atr.tasks.checks as checks
import atr.util as util
@@ -126,7 +127,7 @@ async def validate(task_args: args.QuarantineValidate) -> results.Results | None
file_entries = await _build_file_entries(task_args.archives, quarantine_dir)
try:
- await _extract_archives(task_args.archives, quarantine_dir, project_key, version_key, file_entries)
+ swhid_dirs = await _extract_archives(task_args.archives, quarantine_dir, project_key, version_key, file_entries)
except Exception as exc:
await _mark_failed(
quarantined,
@@ -138,7 +139,7 @@ async def validate(task_args: args.QuarantineValidate) -> results.Results | None
await aioshutil.rmtree(quarantine_dir)
return None
- await _promote(quarantined, project_key, version_key, release.key, str(quarantine_dir))
+ await _promote(quarantined, project_key, version_key, release.key, str(quarantine_dir), swhid_dirs)
return None
@@ -154,7 +155,7 @@ def _backfill_extract_archive(
results_list: list[tuple[str, safe.StatePath, float]],
) -> None:
try:
- elapsed = _extract_archive_to_dir(archive_path, archive_dir, staging_base, extraction_cfg)
+ elapsed, _ = _extract_archive_to_dir(archive_path, archive_dir, staging_base, extraction_cfg)
results_list.append((str(archive_path), archive_dir, elapsed))
except Exception as exc:
log.warning(f"Backfill: failed to extract {archive_path}: {exc}")
@@ -217,14 +218,27 @@ def _extract_archive_to_dir(
archive_dir: safe.StatePath,
staging_base: safe.StatePath,
extraction_cfg: exarch.SecurityConfig,
-) -> float:
+ compute_swhid: bool = False,
+) -> tuple[float, str | None]:
archive_dir_path = archive_dir.path
staging_dir = staging_base / f"archive-extract-{uuid.uuid4().hex}"
staging_dir_path = staging_dir.path
+ swhid_dir_inner: str | None = None
try:
staging_dir_path.mkdir(parents=False, exist_ok=False)
start = time.monotonic()
exarch.extract_archive(str(archive_path), str(staging_dir), extraction_cfg)
+ if compute_swhid:
+ try:
+ root = archives.single_root_dir(staging_dir)
+ if root is not None:
+ swhid_dir_inner = str(swhid.directory_id_sync(staging_dir_path / root))
+ except Exception as exc:
+ log.warning(
+ "Failed to compute archive SWHID metadata",
+ archive_path=str(archive_path),
+ error=str(exc),
+ )
archive_dir_path.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(staging_dir, archive_dir)
@@ -234,7 +248,7 @@ def _extract_archive_to_dir(
else:
raise
_set_archive_permissions(archive_dir)
- return time.monotonic() - start
+ return time.monotonic() - start, swhid_dir_inner
except Exception:
shutil.rmtree(staging_dir, ignore_errors=True)
raise
@@ -246,7 +260,7 @@ async def _extract_archives(
project_key: safe.ProjectKey,
version_key: safe.VersionKey,
file_entries: list[sql.QuarantineFileEntryV1],
-) -> None:
+) -> dict[str, str]:
archives_base = paths.get_archives_dir() / project_key / version_key
staging_base = paths.get_tmp_dir()
await aiofiles.os.makedirs(archives_base, exist_ok=True)
@@ -254,18 +268,20 @@ async def _extract_archives(
extraction_config = archives.extraction_config()
+ swhid_dirs: dict[str, str] = {}
for archive in archive_entries:
archive_dir = archives_base / hashes.filesystem_archives_key(archive.content_hash)
if await aiofiles.os.path.isdir(archive_dir):
continue
archive_path = quarantine_dir / archive.rel_path
try:
- await asyncio.to_thread(
+ _, swhid_dir_inner = await asyncio.to_thread(
_extract_archive_to_dir,
archive_path,
archive_dir,
staging_base,
extraction_config,
+ True,
)
except Exception as exc:
log.exception(f"Failed to extract archive {archive.rel_path}")
@@ -274,6 +290,9 @@ async def _extract_archives(
entry.errors.append(f"Extraction failed: {exc}")
break
raise
+ if swhid_dir_inner is not None:
+ swhid_dirs[archive.content_hash] = swhid_dir_inner
+ return swhid_dirs
def _is_archive_suffix(filename: str) -> bool:
@@ -324,6 +343,7 @@ async def _promote(
version_key: safe.VersionKey,
release_key: str,
quarantine_dir: str,
+ swhid_dirs: dict[str, str],
) -> None:
quarantine_dir_path = pathlib.Path(quarantine_dir)
@@ -372,6 +392,7 @@ async def _promote(
temp_dir_path=quarantine_dir_path,
version_key=version_key,
was_quarantined=True,
+ extracted_swhids=swhid_dirs,
)
async with db.session() as data:
diff --git a/tests/unit/test_quarantine_task.py b/tests/unit/test_quarantine_task.py
index 9d007439..74ddb01e 100644
--- a/tests/unit/test_quarantine_task.py
+++ b/tests/unit/test_quarantine_task.py
@@ -99,7 +99,7 @@ def test_extract_archive_to_dir_accepts_dotenv_anywhere(tmp_path: pathlib.Path)
def test_extract_archive_to_dir_accepts_safe_archive(tmp_path: pathlib.Path) -> None:
archive_path = tmp_path / "safe.tar.gz"
_write_tar_gz(archive_path, [_tar_regular_file("dist/file.txt", b"hello")])
- elapsed = quarantine._extract_archive_to_dir(
+ elapsed, _ = quarantine._extract_archive_to_dir(
safe.StatePath(archive_path, tmp_path),
safe.StatePath(tmp_path / "out", tmp_path),
safe.StatePath(tmp_path, tmp_path),
@@ -108,6 +108,23 @@ def test_extract_archive_to_dir_accepts_safe_archive(tmp_path: pathlib.Path) ->
assert isinstance(elapsed, float)
+def test_extract_archive_to_dir_computes_swhid_for_root_name_outside_relpath_charset(
+ tmp_path: pathlib.Path,
+) -> None:
+ archive_path = tmp_path / "safe.tar.gz"
+ _write_tar_gz(archive_path, [_tar_regular_file("dist root/file.txt", b"hello")])
+ _, swhid_dir_inner = quarantine._extract_archive_to_dir(
+ safe.StatePath(archive_path, tmp_path),
+ safe.StatePath(tmp_path / "out", tmp_path),
+ safe.StatePath(tmp_path, tmp_path),
+ archives.extraction_config(),
+ compute_swhid=True,
+ )
+
+ assert swhid_dir_inner is not None
+ assert swhid_dir_inner.startswith("swh:1:dir:")
+
+
def test_extract_archive_to_dir_rejects_absolute_path(tmp_path: pathlib.Path) -> None:
archive_path = tmp_path / "unsafe.tar.gz"
_write_tar_gz(archive_path, [_tar_regular_file("/etc/passwd", b"x")])
@@ -168,6 +185,29 @@ def test_extract_archive_to_dir_rejects_symlink_escaping_root(tmp_path: pathlib.
)
+def test_extract_archive_to_dir_treats_swhid_failure_as_metadata_warning(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: pathlib.Path,
+) -> None:
+ archive_path = tmp_path / "safe.tar.gz"
+ _write_tar_gz(archive_path, [_tar_regular_file("dist/file.txt", b"hello")])
+
+ def fail_directory_id(_path: pathlib.Path) -> quarantine.swhid.Identifier:
+ raise RuntimeError("swhid failed")
+
+ monkeypatch.setattr(quarantine.swhid, "directory_id_sync", fail_directory_id)
+ _, swhid_dir_inner = quarantine._extract_archive_to_dir(
+ safe.StatePath(archive_path, tmp_path),
+ safe.StatePath(tmp_path / "out", tmp_path),
+ safe.StatePath(tmp_path, tmp_path),
+ archives.extraction_config(),
+ compute_swhid=True,
+ )
+
+ assert swhid_dir_inner is None
+ assert (tmp_path / "out" / "dist" / "file.txt").read_bytes() == b"hello"
+
+
@pytest.mark.asyncio
async def test_extract_archives_discards_staging_dir_on_enotempty_collision(
monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path
@@ -416,7 +456,7 @@ async def test_promote_finalises_revision_and_deletes_quarantined(tmp_path: path
mock.patch.object(quarantine.revision, "finalise_revision", new_callable=mock.AsyncMock) as mock_finalise,
mock.patch.object(quarantine.db, "session", side_effect=session_calls),
):
- await quarantine._promote(quarantined_row, "proj", "1.0", "proj-1.0", quarantine_dir)
+ await quarantine._promote(quarantined_row, "proj", "1.0", "proj-1.0", quarantine_dir, {})
mock_release_data.release.assert_called_once_with(
key="proj-1.0", _release_policy=True, _project_release_policy=True
@@ -427,6 +467,7 @@ async def test_promote_finalises_revision_and_deletes_quarantined(tmp_path: path
assert call_kwargs["project_key"] == "proj"
assert call_kwargs["release"] is release
assert call_kwargs["path_to_hash"] == {"file.txt": "hash1"}
+ assert call_kwargs["extracted_swhids"] == {}
mock_delete_data.delete.assert_awaited_once_with(quarantined_row)
@@ -610,7 +651,7 @@ async def test_validate_success_calls_promote(tmp_path: pathlib.Path):
new_callable=mock.AsyncMock,
return_value=ok_entries,
),
- mock.patch.object(quarantine, "_extract_archives", new_callable=mock.AsyncMock),
+ mock.patch.object(quarantine, "_extract_archives", new_callable=mock.AsyncMock, return_value={}),
mock.patch.object(quarantine, "_promote", new_callable=mock.AsyncMock) as mock_promote,
mock.patch.object(quarantine, "_mark_failed", new_callable=mock.AsyncMock) as mock_mark,
):
@@ -620,7 +661,7 @@ async def test_validate_success_calls_promote(tmp_path: pathlib.Path):
assert result is None
mock_promote.assert_awaited_once_with(
- row, safe.ProjectKey("proj"), safe.VersionKey("1.0"), row.release.key, str(quarantine_dir)
+ row, safe.ProjectKey("proj"), safe.VersionKey("1.0"), row.release.key, str(quarantine_dir), {}
)
mock_mark.assert_not_awaited()
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org