Skip to content

Experiment: property-based tests with hegel-go - #9149

Draft
wallrj wants to merge 14 commits into
cert-manager:masterfrom
wallrj:hegel-go-trial
Draft

wallrj wants to merge 14 commits into
cert-manager:masterfrom
wallrj:hegel-go-trial

Conversation

@wallrj

@wallrj wallrj commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Not for merge as-is — this is an experiment in property-based testing with hegel-go, opened as a draft so people can get a feel for what the tests look like and what they found. It is too big for a single code review; if there is appetite, I would split it into per-package PRs and open a separate discussion about adding the dependency.

What hegel-go is

A Hypothesis-style property-based testing library for Go: it generates random inputs for a property, and when the property fails it shrinks the input to a minimal counterexample. It drives a native Rust engine, so thousands of cases run in milliseconds.

Dependency cost, for the eventual discussion: hegel.dev/go/hegel (v0.6.30, beta, MIT) plus purego, with an embedded platform-specific shared library (Linux amd64/arm64, macOS arm64, Windows amd64/arm64). Test-only. It writes a .hegel/ example database, gitignored in the first commit.

What's here

Each commit is self-contained and reviewable on its own. Two kinds of change:

Tables replaced by properties — where every row instantiated one law or a recomputable oracle:

  • pkg/util/pki/asn1_util_test.go: OID parse round-trip and UniversalValue marshal/unmarshal (the old table carried an overrideRoundtripUv field for its one exception; that exception is now stated as its own law)
  • internal/apis/certmanager/validation/util: ValidNameserver — 12 rows of {IPv4, IPv6, DNS} x {port forms} became one law with net.JoinHostPort as the oracle
  • pkg/util/pki/generate_test.go: key generation and encoding tables — the "empty key encoding" row actually set PKCS1, so the default-encoding path was never tested; the property draws "" explicitly
  • pkg/api/util: DNSSafeShortenToNCharacters — 10 rows became one recomputed-oracle property, which also documents that the ends-alphanumeric guarantee only holds for inputs >= maxLength
  • pkg/util/pki/csr_test.go: TestEncodeX509Chain — 8 rows, one concatenation rule, with the issue The certificate request has failed to complete and will be retried: Failed to decode returned certificate: error decoding certificate PEM block #4142 same-CN certificate kept in the generator pool
  • pkg/util/solverpicker: the 897-line TestPick table. The replacement states, for the first time anywhere, Pick's specificity ordering (dnsNames beat dnsZones beat label-only; more zone segments then more labels within a tier; first solver wins ties) and checks Pick against it as a loop-independent specification

Tables that pin external bytes (OpenSSL fixtures), policy choices (default signature digests, hash stability) or named regressions were deliberately kept.

New properties for untested or law-shaped code:

  • LiteralSubject parsing: arbitrary DN values escaped with ldap.EscapeDN must survive parse + DER round-trip (complements FuzzRoundTripRDNSequence, which skips special characters)
  • RenewalTime bounds and renewal-windows invariants
  • Policy chains (trigger/readiness) must never panic for corrupt/mismatched Secret and CertificateRequest data
  • ingress-shim: annotations the shim accepts must produce a Certificate admission accepts
  • JoinWithEscapeCSV/SplitWithEscapeCSV round trip (previously no direct tests)
  • SAN and NameConstraints extension marshal/unmarshal round trips
  • SignatureAlgorithm end-to-end: predicted algorithms must actually work in a CSR
  • ParseSingleCertificateChain: order/duplicate invariance, broken-chain rejection, and cross-sign determinism
  • internal/cron (previously one 29-line test): generated cron expressions with independently computed match sets, checked against Next() in UTC and a DST timezone

What it found

Real flaws, all filed:

Where a property found a bug that is not yet fixed, the failing input class is excluded from generation and documented in the test with a pointer to the issue, so the branch is green.

Coverage

Compared with master: pkg/util 45.5% -> 66.7%, pkg/util/pki 74.5% -> 76.4%, certificate-shim 92.0% -> 93.6%, policies 77.7% -> 78.3%; internal/apis/certmanager/validation/util and pkg/api/util unchanged with their tables deleted. No previously covered statement lost coverage anywhere; the newly covered statements are almost all error branches no example test ever reached.

How the candidates were chosen

A property test needs two things: generatable inputs and an oracle — a way to say what must be true of the output without re-implementing the function. Candidates were picked by looking for places where an oracle comes for free:

  1. Law-shaped code. Round trips (marshal/unmarshal, parse/format, join/split), inverse pairs and normalisers with fixed points. The oracle is identity: feed the output back through and compare. That gave the subject, SAN, NameConstraints, OID, UniversalValue, CSV and chain properties.
  2. Trust boundaries. Anywhere outside data enters: CRD specs, Ingress annotations, Secret data, PEM blobs. The minimum oracle is "never panic"; the stronger one is cross-layer consistency — one layer's output must satisfy the next layer's contract. The ingress-shim property (annotations the shim accepts must produce a Certificate admission accepts) and the policy-chain crash test are this shape, and found most of the bugs.
  3. Two implementations that must agree. SignatureAlgorithm predicts what crypto/x509 will do, so x509 itself is the oracle; ValidNameserver re-implements what net.JoinHostPort already defines. Disagreement is a bug by definition.
  4. Tables whose rows all instantiate one rule. If every row of a table test can be recomputed from its input by an obvious rule, the table is a property written out longhand — the giveaway is copy-pasted rows, cross-product row names, or a field like overrideRoundtripUv encoding "the law, except here". Tables that pin external bytes (OpenSSL fixtures), policy choices or named regressions were kept: those rows are the specification, not instances of it.
  5. Thinly tested pure code. Pure, deterministic, cheap-to-call functions with few or no tests (the cron fork had one 29-line test; the CSV helpers none). Generation is trivial there, so even weak invariants (bounds, alignment, monotonicity) buy real coverage — measurably, mostly of error branches no example ever reached.

Excluded: reconcilers with I/O, functions whose expected output is a policy choice with no independent oracle, and validation functions whose error list is itself the specification.

with claude fable-5

wallrj and others added 14 commits August 14, 2026 19:18
Trial of the hegel.dev/go/hegel property-based testing library on two
pure-logic areas of pkg/util/pki:

- subject_hegel_test.go: arbitrary DN attribute values, escaped with
  ldap.EscapeDN, must survive UnmarshalSubjectStringToRDNSequence and a
  DER round trip. Complements FuzzRoundTripRDNSequence, which skips
  special characters and unknown types.
- renewaltime_hegel_test.go: RenewalTime must stay within the
  certificate lifetime for any renewBefore/renewBeforePercentage
  combination, and with a daily cron window must return either the
  plain renewal time or a cron occurrence, never earlier than the
  plain time.

All properties hold at 5000 generated cases per test (~1.3s total).
Ignore the .hegel/ example database directory.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
Two more property tests targeting places where outside input enters
cert-manager:

- crash_hegel_test.go: the trigger and readiness policy chains must
  never panic for any Certificate/Secret/CertificateRequest
  combination, including corrupt, truncated and mismatched PEM in
  Secret data and garbage revision annotations. Passes at 2000 cases.
- helper_hegel_test.go: annotations an Ingress author controls must
  either be rejected by translateAnnotations or produce a Certificate
  that admission validation accepts. This property found five
  annotation keys where the shim accepts values the API server later
  rejects (ip-sans, email-sans, duration, renew-before, common-name);
  those keys are excluded from generation and documented in the test
  until translateAnnotations validates them.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
JoinWithEscapeCSV and SplitWithEscapeCSV had no direct unit tests,
despite forming a production round trip between Certificate subject
fields written to Secret annotations and ingress-shim annotations
parsed back into subject fields.

The property found two counterexample classes, excluded and documented
in the test until fixed:

- [""] joins to the empty string, which SplitWithEscapeCSV rejects
- values containing \r\n come back as \n because encoding/csv
  silently normalizes line endings inside quoted fields

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
TestParseObjectIdentifier was seven rows, three of which asserted the
same strconv error; TestMarshalAndUnmarshalUniversalValue was a
round-trip law written out longhand, complete with an
overrideRoundtripUv field for its one exception.

Replace both with properties: any OID formatted by the standard
library parses back to itself and any non-numeric component is
rejected; each string form of UniversalValue marshals to exactly the
stdlib encoding, round-trips, and the Bytes-form normalization
exception is now stated as its own law rather than a table override.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
The twelve rows enumerated {IPv4, IPv6, DNS name} x {no port, trailing
colon, explicit port}; all of them instantiate one law, stated once in
the property: any host with an explicit port is returned unchanged as
JoinHostPort(host, port), any bare host gets default port 53, and the
result is a fixed point. The error rows survive as three explicit
example checks.

ValidDNS01Nameserver remains untested; noted for a follow-up.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
MarshalSANs/UnmarshalSANs must round-trip any GeneralNames value, and
the extension must be critical exactly when the certificate has no
subject. The existing TestMarshalAndUnmarshalSANs table pins
OpenSSL-generated fixtures for interoperability, so it stays; this
property states the law its per-row marshal/unmarshal loop spells out.

Writing the generator surfaced a sharp edge: OtherName.Value is
written verbatim by the asn1 encoder, so it must be the pre-wrapped
[0] EXPLICIT element exactly as buildSANsFromSpec constructs it -
MarshalSANs accepts unwrapped values but produces an extension that
UnmarshalSANs rejects.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
TestGeneratePrivateKeyForCertificate was fourteen rows enumerating
algorithm/size combinations; TestPrivateKeyEncodings was three rows,
two of them identical - the row named 'empty key encoding' actually
set PKCS1, so the default-encoding path was never tested as such.

Replace both with two properties: any valid algorithm/size/encoding
spec generates a key of the requested type and size, encodes to the
PEM block type implied by the algorithm and encoding (including the
previously untested empty encoding, drawn explicitly), and decodes
back to the same public key; and any out-of-range RSA size,
unsupported ECDSA size or unknown algorithm is rejected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
The ten rows all instantiate one recomputable rule: the longest prefix
of in[:maxLength] ending in an ASCII alphanumeric byte. State it once
against that oracle, generating inputs over a mixed alphabet including
multi-byte characters the table never covered.

The property also documents a subtlety the table danced around: the
'last char is alphanumeric' guarantee only holds for inputs of at
least maxLength bytes, because shorter inputs are returned unchanged.

TestComputeSecureUniqueDeterministicNameFromData stays as a table: its
hardcoded SHA-256 values pin hash stability, which a property cannot.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
Any NameConstraints value must unmarshal back to itself, with the
requested criticality. The existing table stays: its fixtures pin
OpenSSL-generated DER for interoperability, which a property cannot.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
For any valid key spec, with signatureAlgorithm unset or one the
admission webhook allows for the key algorithm, the predicted
public-key and signature algorithms must actually work: a CSR created
with the generated key and predicted signature algorithm parses back
with exactly those algorithms.

The TestSignatureAlgorithmForCertificate table stays: its rows pin
which default digest each key size gets, which is policy, not law.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
All eight rows instantiate one recomputable rule: the output is the
concatenated PEM of the input certificates in order, skipping nils and
self-signed certificates. The generator pool includes a certificate
whose subject equals its issuer's subject, preserving coverage of the
issue cert-manager#4142 regression row.

Also add properties for ParseSingleCertificateChainPEM: for any chain
depth, with or without the root included, with any duplicates, in any
input order, the parsed bundle is the leaf-to-top chain with the
correct CA; chains with a gap or an unrelated self-signed certificate
are rejected. Its table stays for the named regressions and the
100-certificate case.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
internal/cron is a fork of robfig/cron with a single 29-line test,
despite being the engine behind spec.renewal.windows. Generate cron
expressions with independently computed matching sets for each field
form (star, lists, ranges, steps) and check Next(): strictly after,
minute-aligned, matches all field sets and the standard day rule (dom
AND dow when either is '*', OR otherwise), a fixed point from one
second earlier, and minimal via a drawn in-between time - in UTC and
in a DST-observing timezone.

All properties hold at 1000 cases. A separate probe confirmed the
inherited robfig search-horizon limitation: '0 0 29 2 *' returns the
zero time between 2096 and 2103 because the next leap day (2104) is
more than 5 years away; the renewal-windows filters degrade this to a
WindowError rather than a panic.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
Bundles containing a cross-signed intermediate (same subject and key,
signed by two roots) are how CAs ship trust-path transitions. The
property confirms ParseSingleCertificateChainPEM handles them
deterministically regardless of input order - it rejects them as
'malformed or broken' in every permutation and subset. Whether such
bundles should instead be accepted (picking one path) is a product
question; the property pins the current contract either way.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
TestPick was the largest table in the repo: 897 lines of nested
solver literals encoding a specificity ordering that was written down
nowhere except in Pick's branch structure. The property states that
ordering once - dnsNames beat dnsZones beat label-only matches,
more zone segments then more labels within a tier, first solver wins
ties (including against nil-selector solvers) - and checks Pick
against it as a loop-independent specification: the winner is
eligible, unbeaten, first with its score, and paired with the first
compatible challenge. The selectors package serves as the scoring
oracle. Generated inputs cover every domain shape the table used,
including wildcards. Holds at 2000 cases.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
@cert-manager-prow

Copy link
Copy Markdown
Contributor

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@cert-manager-prow

Copy link
Copy Markdown
Contributor

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@cert-manager-prow cert-manager-prow Bot added do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. labels Aug 15, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign thatsmrtalbot for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cert-manager-prow cert-manager-prow Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Aug 25, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

PR needs rebase.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant