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
12 changes: 12 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,15 @@ condition = "AND"
paths = [ '''(?:^|[/\\])scripts[/\\]bench_compare\.py$''' ]
regexTarget = "line"
regexes = [ '''^\s*_V0_4_3_API_COMPATIBILITY\s*=\s*V0_4_3_API_COMPATIBILITY\s*$''' ]

# This immutable run retains base64-encoded Criterion Tukey fences (four
# floating-point statistics), both directly and in its complete-run payload.
# Match only the Tukey field token, including after payload decoding, in this
# exact historical artifact. Keep other fields and default detectors active.
# Gitleaks can end a scan chunk within the token, before its closing quote.
[[rules.allowlists]]
description = "Frozen Criterion Tukey statistics"
condition = "AND"
paths = [ '''(?:^|[/\\])docs[/\\]performance-runs[/\\]runs[/\\]2e55909621d0aacbfa7670f678574ae750311ba29353e6e9ebb11461414876a2[/\\]run\.json$''' ]
regexTarget = "match"
regexes = [ '''^tukey\.json":\s*"[A-Za-z0-9+/]+={0,2}"?$''' ]
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ osv-scanner = "2.7.1"
[tool.research-repo-tools.toolchain.cargo]
cargo-edit = "0.13.14"
cargo-llvm-cov = "0.9.1"
cargo-machete = "0.9.2"
cargo-machete = "0.10.1"
cargo-nextest = "0.9.152"
clippy-sarif = "0.8.0"
dprint = "0.64.3"
dprint = "0.65.0"
git-cliff = "2.14.2"
rumdl = "0.3.4"
sarif-fmt = "0.8.0"
Expand Down
37 changes: 8 additions & 29 deletions src/exact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2599,16 +2599,18 @@ mod tests {
}

#[test]
fn det_sign_exact_overflow_determinant_finite_entries() {
// Entries near f64::MAX are finite, but the f64 determinant overflows
// to infinity. The fast filter is inconclusive and the direct `BigInt`
// expansion computes the correct positive sign.
fn overflowing_determinant_has_exact_sign_but_no_finite_f64_conversion() {
// The exact determinant is big² > 0, beyond the binary64 range.
let big = f64::MAX / 2.0;
assert!(big.is_finite());
let m = Matrix::<3>::try_from_rows([[0.0, 0.0, 1.0], [big, 0.0, 1.0], [0.0, big, 1.0]])
.unwrap();
// det = big^2 > 0
assert_eq!(m.det_sign_exact(), DeterminantSign::Positive);
assert_unrepresentable(&m.det_exact_f64(), None, UnrepresentableReason::NotFinite);
assert_unrepresentable(
&m.det_exact_rounded_f64(),
None,
UnrepresentableReason::NotFinite,
);
}

// -----------------------------------------------------------------------
Expand Down Expand Up @@ -2696,29 +2698,6 @@ mod tests {
assert!((det - (-2.0)).abs() <= f64::EPSILON);
}

#[test]
fn det_exact_f64_overflow_returns_err() {
// Entries near f64::MAX produce a determinant too large for f64.
let big = f64::MAX / 2.0;
let m = Matrix::<3>::try_from_rows([[0.0, 0.0, 1.0], [big, 0.0, 1.0], [0.0, big, 1.0]])
.unwrap();
// det = big^2, which overflows f64.
assert_unrepresentable(&m.det_exact_f64(), None, UnrepresentableReason::NotFinite);
}

#[test]
fn det_exact_rounded_f64_overflow_returns_err() {
let big = f64::MAX / 2.0;
let m = Matrix::<3>::try_from_rows([[0.0, 0.0, 1.0], [big, 0.0, 1.0], [0.0, big, 1.0]])
.unwrap();

assert_unrepresentable(
&m.det_exact_rounded_f64(),
None,
UnrepresentableReason::NotFinite,
);
}

#[test]
fn det_exact_f64_underflow_returns_err_for_nonzero_exact_result() {
let tiny = f64::from_bits(1);
Expand Down
31 changes: 12 additions & 19 deletions src/ldlt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,30 +208,23 @@ impl<const D: usize> Ldlt<D> {
pivot_col,
);
}
if pivot < 0.0 {
return Self::non_finite_factor_error(rows)
.unwrap_or_else(|| LaError::not_positive_semidefinite_negative(pivot_col, pivot));
}
if pivot == 0.0 {
return Self::zero_pivot_failure(rows, pivot_col, tolerance);
}
Self::non_finite_factor_error(rows).unwrap_or_else(|| {
LaError::singular_numerical(pivot_col, FactorizationKind::Ldlt, pivot, tolerance)
})
}

/// Classify a zero pivot after checking factor storage and every coupling.
fn zero_pivot_failure(rows: &[[f64; D]; D], pivot_col: usize, tolerance: f64) -> LaError {
if let Some(error) = Self::non_finite_factor_error(rows) {
return error;
}
for (row, values) in rows.iter().enumerate().skip(pivot_col + 1) {
let coupling = values[pivot_col];
if coupling != 0.0 {
return LaError::not_positive_semidefinite_zero_coupling(pivot_col, row, coupling);
if pivot < 0.0 {
return LaError::not_positive_semidefinite_negative(pivot_col, pivot);
}
if pivot == 0.0 {
for (row, values) in rows.iter().enumerate().skip(pivot_col + 1) {
let coupling = values[pivot_col];
if coupling != 0.0 {
return LaError::not_positive_semidefinite_zero_coupling(
pivot_col, row, coupling,
);
}
}
}
LaError::singular_numerical(pivot_col, FactorizationKind::Ldlt, 0.0, tolerance)
LaError::singular_numerical(pivot_col, FactorizationKind::Ldlt, pivot.abs(), tolerance)
}

/// Determinant of the original matrix.
Expand Down
2 changes: 1 addition & 1 deletion tests/tooling/support_evidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def __init__(self, root: Path) -> None:
"head_sha": COMMIT,
"status": "completed",
"conclusion": "success",
"labels": NATIVE_RUNNERS.get(name, ["ubuntu-latest"]),
"labels": NATIVE_RUNNERS.get(name, ["ubuntu-latest"]).copy(),
"steps": [{"number": number, "name": step, "status": "completed", "conclusion": "success"} for number, step in enumerate(steps, 1)],
}
for name, steps, identifier in gates
Expand Down
37 changes: 33 additions & 4 deletions tests/tooling/test_candidate_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def test_staging_retry_keeps_original_draft_before_any_upload(tmp_path: Path, mo
(final / name).write_bytes(name.encode())
for name in ("publication.json", "acquisition.sha256", "publication.sha256"):
(owner / name).write_bytes(b"a" * 64)
monkeypatch.setattr(candidate, "verify", lambda *_args: final / "acceptance.json")
monkeypatch.setattr(candidate, "verify", lambda *_args, **_kwargs: final / "acceptance.json")
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: SHA)
monkeypatch.setattr(candidate, "archive", lambda *_args: final / "archive.tar.gz")
monkeypatch.setattr(candidate, "parse_candidate_policy", lambda *_args: SimpleNamespace(tag=TAG))
Expand Down Expand Up @@ -255,7 +255,7 @@ def test_staging_rejects_malformed_owner_digest_before_provider_access(tmp_path:
prepared = tmp_path / "target.json"
prepared.write_bytes(serialize_release_target(ReleaseTarget(candidate.REPOSITORY, TAG, 42, SHA, TAG)))
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: SHA)
monkeypatch.setattr(candidate, "verify", lambda *_args: pytest.fail("invalid assertions must stop before revalidation"))
monkeypatch.setattr(candidate, "verify", lambda *_args, **_kwargs: pytest.fail("invalid assertions must stop before revalidation"))
monkeypatch.setattr(candidate, "revalidate_release_target", lambda *_args, **_kwargs: pytest.fail("invalid assertions must stop before provider access"))
with pytest.raises(ValueError, match="full SHA-256 assertions"):
candidate.stage(root, owner, "reviewed", prepared)
Expand All @@ -275,7 +275,7 @@ def test_shared_batch_retains_domain_transfer_and_original_asset_ids(tmp_path: P
target = ReleaseTarget(candidate.REPOSITORY, TAG, 42, SHA, TAG)
prepared = tmp_path / "target.json"
prepared.write_bytes(serialize_release_target(target))
monkeypatch.setattr(candidate, "verify", lambda *_args: final / "acceptance.json")
monkeypatch.setattr(candidate, "verify", lambda *_args, **_kwargs: final / "acceptance.json")
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: SHA)
monkeypatch.setattr(candidate, "archive", lambda *_args: final / "archive.tar.gz")
monkeypatch.setattr(candidate, "parse_candidate_policy", lambda *_args: SimpleNamespace(tag=TAG))
Expand Down Expand Up @@ -339,7 +339,7 @@ def test_initial_stage_requires_the_exact_prepared_target(tmp_path: Path, monkey
owner.mkdir()
final = candidate.final_directory(owner, SHA, "reviewed")
final.mkdir(parents=True)
monkeypatch.setattr(candidate, "verify", lambda *_args: final / "acceptance.json")
monkeypatch.setattr(candidate, "verify", lambda *_args, **_kwargs: final / "acceptance.json")
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: SHA)
monkeypatch.setattr(candidate, "archive", lambda *_args: final / "archive.tar.gz")
monkeypatch.setattr(candidate, "parse_candidate_policy", lambda *_args: SimpleNamespace(tag=TAG))
Expand Down Expand Up @@ -474,3 +474,32 @@ def shared(arguments: list[str]) -> int:
assert first.read_bytes() == b"reviewed"
assert second.read_bytes() == b"retry-2"
assert ["--acceptance" in arguments for arguments in requests] == [False, True, False]


def test_existing_review_pins_one_commit_and_its_acceptance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
root, owner = tmp_path / "checkout", tmp_path / "owner"
root.mkdir()
other_commit = "c" * 40
accepted = candidate.final_directory(owner, SHA, "reviewed") / "acceptance.json"
accepted.parent.mkdir(parents=True)
previous = b"original reviewed acceptance\r\n"
accepted.write_bytes(previous)
for name in ("acquisition.sha256", "publication.sha256"):
(owner / name).write_bytes(b"a" * 64)

revisions = iter((SHA, other_commit))
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: next(revisions))

def shared(arguments: list[str]) -> int:
assert arguments[arguments.index("--commit") + 1] == SHA
assert Path(arguments[arguments.index("--output") + 1]) == accepted
expected = Path(arguments[arguments.index("--acceptance") + 1])
assert expected != accepted
assert expected.read_bytes() == previous
return 0

monkeypatch.setattr(candidate, "shared_main", shared)
assert candidate.verify_existing(root, owner, "reviewed") == accepted
assert accepted.read_bytes() == previous
assert next(revisions) == other_commit
assert not candidate.final_directory(owner, other_commit, "reviewed").exists()
27 changes: 24 additions & 3 deletions tests/tooling/test_release_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ def test_registry_dispatch_sends_only_the_existing_reviewed_snapshot(tmp_path: P
monkeypatch.setattr(candidate, "record_path", lambda *_args: publication)
verified: list[Path] = []

def verify(*_args: object) -> Path:
def verify(_root: Path, _owner: Path, _selection: str, *, commit: str) -> Path:
assert commit == SHA
verified.append(accepted)
assert accepted.read_bytes() == reviewed
if failure == "changed-review":
Expand Down Expand Up @@ -313,12 +314,32 @@ def test_downstream_checks_never_create_missing_review(tmp_path: Path, monkeypat
root.mkdir()
owner.mkdir()
monkeypatch.setattr(candidate, "resolve_revision", lambda *_args: SHA)
monkeypatch.setattr(candidate, "verify", lambda *_args: pytest.fail("tagging or publication must not create a new review"))
monkeypatch.setattr(candidate, "shared_main", lambda *_args: pytest.fail("tagging or publication must not create a new review"))
with pytest.raises(FileNotFoundError, match=r"acceptance\.json"):
candidate.verify_existing(root, owner, "reviewed")
assert list(owner.iterdir()) == []


def test_capture_cli_reports_success_only_after_owner_registration(
owner_record: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
root, owner = owner_record
candidate.remember_owner(root, owner)
other = owner.parent / "other owner"
other.mkdir()
for source in owner.iterdir():
(other / source.name).write_bytes(source.read_bytes())
monkeypatch.chdir(root)
monkeypatch.setattr(sys, "argv", ["release_candidate.py", "capture", str(other)])
monkeypatch.setattr(candidate, "capture", lambda *_args, **_kwargs: {"owner_directory": str(other)})

with pytest.raises(ValueError, match="immutable output differs"):
candidate.main()

assert capsys.readouterr().out == ""
assert candidate.selected_owner(root) == owner.resolve()


@pytest.mark.parametrize("owner_argument", [[], [""]])
def test_cli_recovers_the_registered_owner_without_shell_context(
owner_record: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], owner_argument: list[str]
Expand Down Expand Up @@ -369,7 +390,7 @@ def test_publish_recipe_requires_review_before_reaching_publication(tmp_path: Pa
"from tooling import release_candidate as candidate\n"
f"candidate.resolve_revision = lambda *_args: {SHA!r}\n"
'def unexpected(*_args):\n raise RuntimeError("attempted to create a new review")\n'
"candidate.verify = unexpected\ncandidate.main()\n",
"candidate.shared_main = unexpected\ncandidate.main()\n",
encoding="utf-8",
newline="\n",
)
Expand Down
53 changes: 48 additions & 5 deletions tests/tooling/test_security_integration.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
"""Check that the consumer Gitleaks exception preserves secret detection."""

import base64
import hashlib
import json
from pathlib import Path
from typing import TYPE_CHECKING

import pytest
from research_repo_tools.process import run_command

if TYPE_CHECKING:
import subprocess

REPO_ROOT = Path(__file__).resolve().parents[2]
FROZEN_RUN = "docs/performance-runs/runs/2e55909621d0aacbfa7670f678574ae750311ba29353e6e9ebb11461414876a2/run.json"
LEAK_FOUND = 3


@pytest.mark.parametrize(
("relative", "credential", "status"),
[
("scripts/bench_compare.py", False, 0),
("scripts/bench_compare.py", True, 1),
("scripts/other.py", False, 1),
("scripts/bench_compare.py", True, LEAK_FOUND),
("scripts/other.py", False, LEAK_FOUND),
],
)
def test_historical_alias_exception_is_limited_to_its_assignment_and_path(tmp_path: Path, relative: str, *, credential: bool, status: int) -> None:
Expand All @@ -27,7 +35,41 @@ def test_historical_alias_exception_is_limited_to_its_assignment_and_path(tmp_pa
token = hashlib.sha256(b"public Gitleaks regression fixture").hexdigest()
contents += "api_" + f'key = "{token}"\n'
source.write_text(contents, encoding="utf-8")
result = run_command(
result = scan_secrets(tmp_path)
assert result.returncode == status, result.stderr


@pytest.mark.parametrize("representation", ["direct", "chunk", "payload"])
@pytest.mark.parametrize(
("relative", "credential", "status"),
[(FROZEN_RUN, False, 0), (FROZEN_RUN, True, LEAK_FOUND), ("docs/performance-runs/other.json", False, LEAK_FOUND)],
)
def test_frozen_statistics_exception_preserves_other_secret_detection(
tmp_path: Path, representation: str, relative: str, *, credential: bool, status: int
) -> None:
"""Only the frozen run's encoded numerical fields are exempted."""
fences = b"[23.01652962024839,23.323939759650607,24.143700131389842,24.451110270792054]"
encoded = base64.b64encode(fences).decode("ascii")
record = {}
if credential:
record["api_" + "key"] = hashlib.sha256(b"public Gitleaks regression fixture").hexdigest()
record["tukey.json"] = encoded
if representation == "payload":
payload = json.dumps({"raw_files": record}).encode("utf-8")
record = {"payload": base64.b64encode(payload).decode("ascii")}
source = tmp_path / relative
source.parent.mkdir(parents=True, exist_ok=True)
contents = json.dumps(record, indent=2) + "\n"
if representation == "chunk":
contents = contents.removesuffix('"\n}\n')
source.write_text(contents, encoding="utf-8", newline="\n")
result = scan_secrets(tmp_path)
assert result.returncode == status, result.stderr


def scan_secrets(root: Path) -> subprocess.CompletedProcess[str]:
"""Exercise the installed scanner with the real consumer policy."""
return run_command(
"uv",
[
"run",
Expand All @@ -42,10 +84,11 @@ def test_historical_alias_exception_is_limited_to_its_assignment_and_path(tmp_pa
"--config",
str(REPO_ROOT / ".gitleaks.toml"),
"--redact",
"--exit-code",
str(LEAK_FOUND),
"--ignore-gitleaks-allow",
str(tmp_path),
str(root),
],
cwd=REPO_ROOT,
check=False,
)
assert result.returncode == status
Loading
Loading