skrawcz commented on code in PR #741:
URL: https://github.com/apache/burr/pull/741#discussion_r3108339790


##########
scripts/verify_apache_artifacts.py:
##########
@@ -443,59 +684,295 @@ def verify_licenses(artifacts_dir: str, rat_jar_path: 
str, report_only: bool = F
             f"Apache RAT JAR not found: {rat_jar_path}\nDownload from: 
https://creadur.apache.org/rat/download_rat.cgi";
         )
 
-    # Check for java
     if shutil.which("java") is None:
         _fail("Java not found. Required for Apache RAT.")
 
-    # Find all tar.gz artifacts (not wheels)
-    all_files = [
-        f for f in os.listdir(artifacts_dir) if 
os.path.isfile(os.path.join(artifacts_dir, f))
-    ]
-    tar_artifacts = [f for f in all_files if f.endswith(".tar.gz")]
-
+    tar_artifacts = [name for name in _artifact_files(artifacts_dir) if 
name.endswith(".tar.gz")]
     if not tar_artifacts:
         print(f"⚠️  No tar.gz artifacts found in {artifacts_dir}")
+        summary.fail("Apache RAT", "no tar.gz artifacts found")
         return False
 
     print(f"Found {len(tar_artifacts)} tar.gz artifact(s) to check:\n")
 
     all_valid = True
     for artifact_name in tar_artifacts:
         artifact_path = os.path.join(artifacts_dir, artifact_name)
-
-        # Generate report name from artifact name
         report_name = artifact_name.replace(".tar.gz", "").replace(".", "-")
+        if not _check_licenses_with_rat(
+            artifact_path,
+            rat_jar_path,
+            report_name,
+            summary,
+            report_only,
+        ):
+            all_valid = False
+
+    return all_valid
 
-        if not _check_licenses_with_rat(artifact_path, rat_jar_path, 
report_name, report_only):
+
+def _detect_build_command() -> list[str] | None:
+    build_check = subprocess.run(
+        [sys.executable, "-m", "build", "--version"],
+        capture_output=True,
+        text=True,
+        check=False,
+    )
+    if build_check.returncode == 0:
+        return [sys.executable, "-m", "build"]
+    if shutil.which("flit"):
+        return ["flit"]
+    return None
+
+
+def _release_artifact_map(artifacts_dir: str) -> dict[str, list[str]]:
+    artifacts = _artifact_files(artifacts_dir)
+    return {
+        "source": [name for name in artifacts if name.endswith("-src.tar.gz")],
+        "sdist": [name for name in artifacts if 
name.endswith("-sdist.tar.gz")],
+        "wheel": [name for name in artifacts if name.endswith(".whl")],
+    }
+
+
+def _extract_project_root(source_artifact: str, destination: str) -> Path:
+    with tarfile.open(source_artifact, "r:gz") as tar:
+        _safe_extract_tar(tar, destination)
+
+    entries = [entry for entry in Path(destination).iterdir()]
+    if len(entries) == 1 and entries[0].is_dir():
+        return entries[0]
+    return Path(destination)
+
+
+def _load_apache_release_module(project_root: Path):
+    module_path = project_root / "scripts" / "apache_release.py"
+    spec = importlib.util.spec_from_file_location("apache_release_for_verify", 
module_path)
+    if spec is None or spec.loader is None:
+        raise RuntimeError(f"Unable to load release helper from {module_path}")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def _build_reproducible_wheel(project_root: Path, version: str, output_dir: 
str, source_epoch: int) -> tuple[bool, str]:
+    release_module = _load_apache_release_module(project_root)
+    original_env = os.environ.copy()
+    original_cwd = os.getcwd()
+    try:
+        os.environ["SOURCE_DATE_EPOCH"] = str(source_epoch)
+        os.chdir(project_root)
+        wheel_path = release_module._build_wheel_from_current_dir(version, 
output_dir)
+        return True, wheel_path
+    except SystemExit as exc:
+        return False, f"wheel build exited with code {exc.code}"
+    except Exception as exc:
+        return False, str(exc)
+    finally:
+        os.chdir(original_cwd)
+        os.environ.clear()
+        os.environ.update(original_env)
+
+
+def _build_reproducible_artifacts(source_artifact: str, build_tool: list[str], 
output_dir: str) -> tuple[bool, str]:

Review Comment:
   _build_reproducible_artifacts accepts a build_tool parameter but the sdist 
build on line 793 hardcodes flit. Since flit is the required build tool for 
Burr, please remove the build_tool parameter here and in _detect_build_command 
— just use flit directly and fail if it's not available.



##########
scripts/verify_apache_artifacts.py:
##########
@@ -87,354 +237,445 @@ def _verify_artifact_signature(artifact_path: str, 
signature_path: str) -> bool:
             capture_output=True,
             check=False,
         )
-        if result.returncode == 0:
-            print("    ✓ GPG signature is valid")
-            return True
-        else:
-            print("    ✗ GPG signature verification failed")
-            if result.stderr:
-                print(f"    Error: {result.stderr.decode()}")
-            return False
-    except subprocess.CalledProcessError:
-        print("    ✗ Error running GPG")
+    except OSError as exc:
+        print(f"    ✗ Error running GPG: {exc}")
+        summary.fail(check_name, f"gpg unavailable: {exc}")
         return False
 
+    if result.returncode == 0:
+        print("    ✓ GPG signature is valid")
+        summary.pass_(check_name)
+        return True
+
+    print("    ✗ GPG signature verification failed")
+    if result.stderr:
+        print(f"    Error: {result.stderr.decode()}")
+    summary.fail(check_name, result.stderr.decode().strip() or "verification 
failed")
+    return False
+
 
-def _verify_artifact_checksum(artifact_path: str, checksum_path: str) -> bool:
-    """Verify SHA512 checksum of artifact."""
+def _verify_artifact_checksum(
+    artifact_path: str,
+    checksum_path: str,
+    summary: VerificationSummary,
+) -> bool:
+    check_name = f"SHA512 checksum: {os.path.basename(artifact_path)}"
     print(f"  Verifying SHA512 checksum: {os.path.basename(checksum_path)}")
 
     if not os.path.exists(checksum_path):
         print("    ✗ Checksum file not found")
+        summary.fail(check_name, "missing .sha512")
         return False
 
-    # Read expected checksum
-    with open(checksum_path, "r", encoding="utf-8") as f:
-        expected_checksum = f.read().strip().split()[0]
-
-    # Calculate actual checksum
-    sha512_hash = hashlib.sha512()
-    with open(artifact_path, "rb") as f:
-        while chunk := f.read(65536):
-            sha512_hash.update(chunk)
-
-    actual_checksum = sha512_hash.hexdigest()
+    with open(checksum_path, "r", encoding="utf-8") as handle:
+        expected_checksum = handle.read().strip().split()[0]
 
+    actual_checksum = _sha512_for_file(artifact_path)
     if actual_checksum == expected_checksum:
         print("    ✓ SHA512 checksum is valid")
+        summary.pass_(check_name)
         return True
-    else:
-        print("    ✗ SHA512 checksum mismatch!")
-        print(f"    Expected: {expected_checksum}")
-        print(f"    Actual:   {actual_checksum}")
-        return False
+
+    print("    ✗ SHA512 checksum mismatch!")
+    print(f"    Expected: {expected_checksum}")
+    print(f"    Actual:   {actual_checksum}")
+    summary.fail(check_name, "checksum mismatch")
+    return False
 
 
-def _verify_tar_gz_readable(artifact_path: str) -> bool:
-    """Verify tar.gz archive can be read and contains files."""
+def _verify_tar_gz_readable(artifact_path: str, summary: VerificationSummary) 
-> bool:
+    check_name = f"Readable tar.gz: {os.path.basename(artifact_path)}"
     print(f"  Checking archive readability: {os.path.basename(artifact_path)}")
 
     try:
         with tarfile.open(artifact_path, "r:gz") as tar:
             members = tar.getmembers()
-
-            if len(members) == 0:
+            if not members:
                 print("    ✗ Archive is empty (no files)")
+                summary.fail(check_name, "archive is empty")
                 return False
-
             print(f"    ✓ Archive is readable and contains {len(members)} 
files")
+            summary.pass_(check_name, f"{len(members)} members")
             return True
-    except tarfile.TarError as e:
-        print(f"    ✗ Archive is corrupted or unreadable: {e}")
+    except tarfile.TarError as exc:
+        print(f"    ✗ Archive is corrupted or unreadable: {exc}")
+        summary.fail(check_name, str(exc))
         return False
-    except Exception as e:
-        print(f"    ✗ Error reading archive: {e}")
+    except Exception as exc:  # pragma: no cover - defensive
+        print(f"    ✗ Error reading archive: {exc}")
+        summary.fail(check_name, str(exc))
         return False
 
 
-def _verify_wheel_readable(wheel_path: str) -> bool:
-    """Verify wheel can be read and contains expected structure."""
+def _verify_wheel_readable(wheel_path: str, summary: VerificationSummary) -> 
bool:
+    check_name = f"Readable wheel: {os.path.basename(wheel_path)}"
     print(f"  Checking wheel readability: {os.path.basename(wheel_path)}")
 
     try:
-        with zipfile.ZipFile(wheel_path, "r") as whl:
-            file_list = whl.namelist()
-
-            if len(file_list) == 0:
+        with zipfile.ZipFile(wheel_path, "r") as wheel:
+            file_list = wheel.namelist()
+            if not file_list:
                 print("    ✗ Wheel is empty (no files)")
+                summary.fail(check_name, "wheel is empty")
                 return False
 
-            # Check for metadata
-            metadata_files = [f for f in file_list if "METADATA" in f or 
"WHEEL" in f]
+            metadata_files = [name for name in file_list if "METADATA" in name 
or "WHEEL" in name]
             if not metadata_files:
                 print("    ✗ Wheel missing required metadata files")
+                summary.fail(check_name, "missing METADATA/WHEEL")
                 return False
 
             print(f"    ✓ Wheel is readable and contains {len(file_list)} 
files")
+            summary.pass_(check_name, f"{len(file_list)} members")
             return True
-    except zipfile.BadZipFile:
+    except zipfile.BadZipFile as exc:
         print("    ✗ Wheel is corrupted or not a valid ZIP file")
+        summary.fail(check_name, str(exc))
         return False
-    except Exception as e:
-        print(f"    ✗ Error reading wheel: {e}")
+    except Exception as exc:  # pragma: no cover - defensive
+        print(f"    ✗ Error reading wheel: {exc}")
+        summary.fail(check_name, str(exc))
         return False
 
 
-def _verify_artifact_exists(artifact_path: str, min_size: int = 1000) -> bool:
-    """Verify artifact exists and has reasonable size."""
-    if not os.path.exists(artifact_path):
-        print(f"  ✗ Artifact not found: {os.path.basename(artifact_path)}")
-        return False
+def _verify_required_text_files(
+    artifact_name: str,
+    file_bytes: dict[str, bytes],
+    required_files: tuple[str, ...],
+    expected_files: dict[str, bytes],
+    summary: VerificationSummary,
+) -> bool:
+    all_valid = True
+    for required_name in required_files:
+        check_name = f"{artifact_name} contains {required_name}"
+        matches = _find_files_by_basename(file_bytes, required_name)
+        if not matches:
+            print(f"    ✗ Missing {required_name}")
+            summary.fail(check_name, "missing")
+            all_valid = False
+            continue
 
-    file_size = os.path.getsize(artifact_path)
-    if file_size < min_size:
-        print(
-            f"  ✗ Artifact is suspiciously small ({file_size} bytes): 
{os.path.basename(artifact_path)}"
-        )
+        matched_path = matches[0]
+        if file_bytes[matched_path] != expected_files[required_name]:
+            print(f"    ✗ {required_name} content mismatch ({matched_path})")
+            summary.fail(check_name, f"content mismatch at {matched_path}")
+            all_valid = False
+            continue
+
+        print(f"    ✓ {required_name} present and matches repository copy 
({matched_path})")
+        summary.pass_(check_name, matched_path)
+    return all_valid
+
+
+def verify_artifact_contents(artifacts_dir: str, summary: VerificationSummary 
| None = None) -> bool:
+    _print_section("Verifying Artifact Metadata Files")
+
+    if summary is None:
+        summary = VerificationSummary()
+
+    if not os.path.exists(artifacts_dir):
+        _fail(f"Artifacts directory not found: {artifacts_dir}")
+
+    artifacts = _artifact_files(artifacts_dir)
+    if not artifacts:
+        print(f"⚠️  No artifacts found in {artifacts_dir}")
+        summary.fail("Artifact metadata verification", "no artifacts found")
         return False
 
-    print(f"  ✓ Artifact exists: {os.path.basename(artifact_path)} 
({file_size:,} bytes)")
-    return True
+    expected_files = _read_expected_text_files()
+    all_valid = True
 
+    for artifact_name in artifacts:
+        artifact_path = os.path.join(artifacts_dir, artifact_name)
+        print(f"Inspecting metadata files: {artifact_name}")
+        print("-" * 80)
 
-def verify_signatures(artifacts_dir: str) -> bool:
-    """Verify all signatures and checksums in artifacts directory."""
+        if artifact_name.endswith(".tar.gz"):
+            file_bytes = _tar_file_bytes(artifact_path)
+            if not _verify_required_text_files(
+                artifact_name,
+                file_bytes,
+                REQUIRED_TEXT_FILES,
+                expected_files,
+                summary,
+            ):
+                all_valid = False
+        elif artifact_name.endswith(".whl"):
+            file_bytes = _wheel_file_bytes(artifact_path)
+            if not _verify_required_text_files(
+                artifact_name,
+                file_bytes,
+                REQUIRED_TEXT_FILES[1:] + WHEEL_LICENSE_FILES,
+                expected_files,
+                summary,
+            ):
+                all_valid = False
+        else:
+            print(f"    ⚠️  Skipping unsupported artifact type: 
{artifact_name}")
+            summary.skip(f"Artifact metadata: {artifact_name}", "unsupported 
type")
+        print()
+
+    return all_valid
+
+
+def verify_signatures(artifacts_dir: str, summary: VerificationSummary | None 
= None) -> bool:
     _print_section("Verifying Signatures and Checksums")
 
+    if summary is None:
+        summary = VerificationSummary()
+
     if not os.path.exists(artifacts_dir):
         _fail(f"Artifacts directory not found: {artifacts_dir}")
 
-    # Find all artifacts (exclude .asc and .sha512 files)
-    all_files = [
-        f for f in os.listdir(artifacts_dir) if 
os.path.isfile(os.path.join(artifacts_dir, f))
-    ]
-    artifacts = [f for f in all_files if not f.endswith((".asc", ".sha512"))]
-
+    artifacts = _artifact_files(artifacts_dir)
     if not artifacts:
         print(f"⚠️  No artifacts found in {artifacts_dir}")
+        summary.fail("Signature verification", "no artifacts found")
         return False
 
     print(f"Found {len(artifacts)} artifact(s) to verify:\n")
 
     all_valid = True
     for artifact_name in artifacts:
         artifact_path = os.path.join(artifacts_dir, artifact_name)
-
         print(f"Verifying: {artifact_name}")
         print("-" * 80)
 
-        # Check existence and size
-        if not _verify_artifact_exists(artifact_path):
+        if not _verify_artifact_exists(artifact_path, summary):
             all_valid = False
             continue
 
-        # Verify signature
-        signature_path = f"{artifact_path}.asc"
-        if not _verify_artifact_signature(artifact_path, signature_path):
+        if not _verify_artifact_signature(artifact_path, 
f"{artifact_path}.asc", summary):
             all_valid = False
 
-        # Verify checksum
-        checksum_path = f"{artifact_path}.sha512"
-        if not _verify_artifact_checksum(artifact_path, checksum_path):
+        if not _verify_artifact_checksum(artifact_path, 
f"{artifact_path}.sha512", summary):
             all_valid = False
 
-        # Verify archive/wheel structure
         if artifact_name.endswith(".tar.gz"):
-            if not _verify_tar_gz_readable(artifact_path):
+            if not _verify_tar_gz_readable(artifact_path, summary):
                 all_valid = False
         elif artifact_name.endswith(".whl"):
-            if not _verify_wheel_readable(artifact_path):
+            if not _verify_wheel_readable(artifact_path, summary):
                 all_valid = False
 
         print()
 
     return all_valid
 
 
-# ============================================================================
-# License Verification (Apache RAT)
-# ============================================================================
+def _safe_extract_tar(tar_handle: tarfile.TarFile, extract_dir: str) -> None:
+    try:
+        tar_handle.extractall(extract_dir, filter="data")
+    except TypeError:
+        tar_handle.extractall(extract_dir)
+
+
+def _build_rat_command(
+    rat_jar_path: str,
+    extract_dir: str,
+    rat_excludes: str | None,
+    output_style: str | None = None,
+) -> list[str]:
+    command = ["java", "-jar", rat_jar_path]
+    if output_style:
+        command.extend(["--output-style", output_style])
+    if rat_excludes:
+        command.extend(["--input-exclude-file", rat_excludes])
+    command.extend(["--", extract_dir])
+    return command
+
+
+def _rat_scan_target(extract_dir: str) -> tuple[str, str]:
+    extracted_root = Path(extract_dir)
+    entries = [entry for entry in extracted_root.iterdir()]
+    if len(entries) == 1 and entries[0].is_dir():
+        return str(extracted_root), entries[0].name
+    return str(extracted_root), "."
+

Review Comment:
   `_build_reproducible_artifacts` accepts a `build_tool` parameter but the 
sdist build on line 793 hardcodes `flit`. Since flit is the required build tool 
for Burr, please remove the `build_tool` parameter here and in 
`_detect_build_command` — just use flit directly and fail if it's not available.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to