Skip to content

fix(hashing): use explicit SHA-2 policy digests and synthetic fixture IDs - #2872

Merged
Daniel Meppiel (danielmeppiel) merged 1 commit into
mainfrom
danielmeppiel-weak-hash-remediation
Sep 7, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 1 commit into
mainfrom
danielmeppiel-weak-hash-remediation

Conversation

@danielmeppiel

Copy link
Copy Markdown
Collaborator

fix(hashing): use explicit SHA-2 policy digests and synthetic fixture IDs

TL;DR

Remove benchmark-only SHA-1 and replace dynamic policy digest construction with explicit SHA-256/384/512 APIs in the existing hash owner. This addresses surviving source patterns associated with SM02167 / py/weak-hashes without changing accepted policy algorithms, pins, cache identities, or real Git object hashing.

Important

Policy hashing already rejected weak algorithms. This is not evidence of an exploitable weak-policy hash, and the private Microsoft CodeQL query pack was not rerun.

Problem (WHY)

  • _make_sha on current main still used SHA-1 only to manufacture synthetic reference/lockfile IDs.
  • [!] Policy verification and compute_policy_hash still called hashlib.new(variable), despite restricting that variable to SHA-256/384/512. Explicit constructors remove this dynamic-API ambiguity without broadening the allowlist.
  • [!] The two reported discovery.py locations (lines 35/89) do not identify hashing calls even at the report's recorded commit, 0ae9a78c6129e41caf87cb75130f9006b31ed98d. The current dynamic sites are discovery._verify_hash_pin and project_config.compute_policy_hash; exact attribution of those two old findings cannot be established from their locations alone.

Source inspection and executable regressions, rather than alert-record state, are the evidence here: "do the work, run a validator (a script, a reference checklist, or a self-check), fix any issues, and repeat until validation passes."

Approach (WHAT)

# Fix
1 Use the existing compute_policy_hash owner for both verification and cache-metadata digests, with explicit SHA-2 constructors.
2 Generate positive, zero-padded 40-character hexadecimal fixture IDs without hashing.
3 Preserve the byte-level contract with regressions and register the required single-owner architecture guard.

Implementation (HOW)

File Intent
src/apm_cli/policy/project_config.py Accept text or raw bytes; retain the allowlist and error wording; dispatch through explicit SHA-2 constructors.
src/apm_cli/policy/discovery.py Delegate pin verification to the same helper already used for cache-metadata digests.
tests/benchmarks/test_git_and_compiler_benchmarks.py Remove SHA-1 and its suppression; check fixture uniqueness, nonzero 40-hex shape, determinism, and parsed tag/branch IDs.
tests/unit/policy/test_policy_hash_pin.py Cover SHA-256/384/512, UTF-8/CRLF and arbitrary bytes, unsupported names, default/bare/normalized pins, cache compatibility, and fail-closed mismatch.
.apm/architecture/owners/contracts-tooling.json Register the existing policy-content hash owner.
scripts/architecture_linter/checks/contracts_test_taxonomy.py Require both discovery digest paths to delegate, rather than introduce local hashing.
tests/integration/test_architecture_owner_rule_mutations.py Prove the new owner guard rejects bypassing that delegation.
tests/unit/scripts/test_architecture_runner.py Keep the registered rule catalog expectation synchronized.
docs/src/content/docs/enterprise/policy-reference.md Clarify the existing exhaustive SHA-2 allowlist in one sentence.

Diagrams

Both discovery digest paths now share the same explicit SHA-2 implementation; dashed nodes identify the changed implementation.

flowchart LR
    subgraph Discovery
        V["_verify_hash_pin"]
        C["_compute_hash_normalized"]
    end
    subgraph Owner["project_config.py"]
        H["compute_policy_hash"]
        S["Explicit SHA-256 / SHA-384 / SHA-512"]
    end
    V --> H
    C --> H
    H --> S
    classDef changed stroke-dasharray: 5 5;
    class H,S changed;
Loading

Trade-offs

  • Use literal SHA-2 constructor calls rather than suppressing the scanner or accepting dynamic algorithm names. The allowlist, default, normalization, mismatch errors, and digests remain unchanged; no cache invalidation or migration is needed.
  • Counter IDs replace hashing only in synthetic fixtures. They are not real Git object IDs or integrity values. No README/changelog entry, manifest/schema change, CodeQL configuration change, alert dismissal, or protection-rule change is included.

Benefits

  1. No SHA-1 or dynamic hashlib.new calls remain in the three affected source/test files.
  2. All three supported policy algorithms retain their existing raw-byte digests and cached-pin compatibility.
  3. A registered, mutation-tested boundary prevents policy verification from bypassing the digest owner.

Validation

Local validation on d8a9bd0d2 plus this commit; this is not a claim about remote CI or the private query pack.

Focused regression and lint evidence

uv run --frozen --extra dev pytest -q -m 'not live' with the selectors below explicitly includes benchmarks:

tests/unit/policy/test_policy_hash_pin.py
tests/unit/policy/test_cache_merged_effective.py
tests/unit/policy/test_discovery_policy_resolution.py
tests/unit/policy/test_discovery_phase3w4.py
tests/benchmarks/test_git_and_compiler_benchmarks.py
tests/unit/scripts/test_architecture_runner.py
tests/integration/test_architecture_owner_rule_mutations.py
743 passed in 162.71s (0:02:42)

Full canonical lint mirror after merging latest main: Ruff check/format over src/, tests/, and architecture-linter sources; pylint R0801; YAML I/O, 2100-line, portable-relative-path guards; auth signals; architecture boundaries. All exited 0. The three grep-style guards used equivalent Python regex/line scans on macOS, not an unavailable rg executable.

uv run --frozen python scripts/check_test_assertions.py:

[+] assertion-quality ratchet clean: AQ001=4, AQ002=12

uv run --frozen python scripts/check_exact_test_duplicates.py:

[+] exact test duplicate ratchet clean: 1208 files, 0 allowed duplicate group(s)

AST inspection confirmed no hashlib.new, hashlib.sha1, or hashlib.md5 calls in the three affected files. Mermaid validated with mmdc 11.15.0. uv.lock is unchanged.

Scenario Evidence

# Scenario (preserved user promise) Principle Test proving it Type
1 Existing SHA-2 pins still verify exactly the same bytes; altered bytes fail closed. Governed by policy tests/unit/policy/test_policy_hash_pin.py::TestVerifyHashPin::test_explicit_sha2_preserves_raw_bytes unit
2 Cached policy remains usable with the matching pin; a different pin is rejected offline. Secure by default tests/unit/policy/test_policy_hash_pin.py::test_existing_sha2_cache_digest_remains_compatible integration (in-process cache/discovery)
3 Unsupported digest names remain rejected rather than silently changing policy enforcement. Governed by policy tests/unit/policy/test_policy_hash_pin.py::TestVerifyHashPin::test_unsupported_algorithms_still_fail_closed unit

How to test

  • Run uv run --frozen --extra dev pytest -q tests/unit/policy/test_policy_hash_pin.py tests/unit/policy/test_cache_merged_effective.py; matching pins/cache entries should pass and mismatches should fail closed.
  • Run uv run --frozen --extra dev pytest -q -m 'not live' tests/benchmarks/test_git_and_compiler_benchmarks.py; all fixture and benchmark cases should pass.
  • Run bash scripts/lint-architecture-boundaries.sh and uv run --frozen --extra dev pytest -q tests/integration/test_architecture_owner_rule_mutations.py -k policy-content-hash; the current source should pass and the in-memory delegation mutation should be detected.

Co-authored-by: Copilot [email protected]

… IDs

Preserve policy pin bytes, normalization and cache compatibility while routing verification through the existing digest owner. Replace benchmark-only SHA-1 IDs with deterministic nonzero 40-character hex IDs.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator Author

Docs sync advisory

Verdict: no_change * Pages affected: 0 additional * LLM calls: 2/15 * Took: not recorded

No further documentation changes are needed. SHA-256/384/512 support, raw-byte pins, normalization, fail-closed outcomes, and cache identities are unchanged. The PR already clarifies the existing exhaustive allowlist in the policy reference. Synthetic benchmark IDs and the internal owner guard have no additional user-facing docs impact. README and the shipped governance resource remain accurate.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

A new unmarked test in the benchmarks module will run in the default suite (benchmarks are deselected by marker), and compute_policy_hash contains redundant/unreachable error handling that should be simplified for maintainability.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review tier: Lite
Findings: 2 Low severity

New issues introduced by this change (2)
Severity Finding
Low severity src/​apm_cli/​policy/​project_config.py — The final ProjectPolicyConfigError raise is currently unreachable because algorithm is already…
Low severity tests/​benchmarks/​test_git_and_compiler_benchmarks.py — This new fixture-shape test is unmarked, but the repo's default pytest selection is `-m 'not…
What changed in this PR

This PR hardens policy hashing by eliminating dynamic hashlib.new(...) calls in policy verification and standardizing SHA-2 digest computation through the existing compute_policy_hash owner, while also removing benchmark-only SHA-1 usage for synthetic fixture IDs.

Changes:

  • Route policy pin verification and cache digest computation through explicit SHA-256/384/512 constructors in compute_policy_hash.
  • Replace benchmark fixture SHA-1 generation with deterministic synthetic 40-hex IDs and add regression assertions around parsed refs.
  • Register and enforce an architecture guard ensuring discovery hashing delegates to the canonical owner; expand unit/integration coverage and clarify the SHA-2 allowlist in docs.
File Description
src/​apm_cli/​policy/​project_config.py Expand compute_policy_hash to accept `str
src/​apm_cli/​policy/​discovery.py Delegate _verify_hash_pin digest computation to compute_policy_hash.
tests/​unit/​policy/​test_policy_hash_pin.py Add unit coverage for explicit SHA-2 behavior, raw-bytes semantics, and cache compatibility.
tests/​benchmarks/​test_git_and_compiler_benchmarks.py Remove SHA-1 fixture hashing; add synthetic ID generation and stronger ref parsing assertions.
.apm/​architecture/​owners/​contracts-tooling.json Register policy-content-hash ownership and its guard.
scripts/​architecture_linter/​checks/​contracts_test_taxonomy.py Add guard enforcing delegation to compute_policy_hash and disallow direct hashlib.* in discovery hashing paths.
tests/​integration/​test_architecture_owner_rule_mutations.py Add mutation proving the new guard catches local hashing bypass.
tests/​unit/​scripts/​test_architecture_runner.py Update expected architecture-rule catalog list to include the new guard.
docs/​src/​content/​docs/​enterprise/​policy-reference.md Clarify the exhaustive SHA-2 allowlist for policy hash pins.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +229 to +231
raise ProjectPolicyConfigError(
f"Refusing to compute policy hash with unsupported algorithm '{algorithm}'"
)
Comment on lines +39 to +40
def test_synthetic_object_ids_preserve_format_and_uniqueness() -> None:
"""Fixture IDs stay deterministic and distinct across all benchmark ranges."""
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 4cd4be7 into main Sep 7, 2026
19 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-weak-hash-remediation branch September 7, 2026 09:09
Ron Izraeli (chkp-roniz) added a commit to chkp-roniz/apm that referenced this pull request Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants