Repository navigation
Conversation
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]>
|
Skipping CI for Draft Pull Request. |
|
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. DetailsInstructions 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. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
PR needs rebase. DetailsInstructions 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. |
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) pluspurego, 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 andUniversalValuemarshal/unmarshal (the old table carried anoverrideRoundtripUvfield 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 withnet.JoinHostPortas the oraclepkg/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""explicitlypkg/api/util:DNSSafeShortenToNCharacters— 10 rows became one recomputed-oracle property, which also documents that the ends-alphanumeric guarantee only holds for inputs >= maxLengthpkg/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 poolpkg/util/solverpicker: the 897-lineTestPicktable. 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 specificationTables 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:
ldap.EscapeDNmust survive parse + DER round-trip (complementsFuzzRoundTripRDNSequence, which skips special characters)RenewalTimebounds and renewal-windows invariantsJoinWithEscapeCSV/SplitWithEscapeCSVround trip (previously no direct tests)SignatureAlgorithmend-to-end: predicted algorithms must actually work in a CSRParseSingleCertificateChain: order/duplicate invariance, broken-chain rejection, and cross-sign determinisminternal/cron(previously one 29-line test): generated cron expressions with independently computed match sets, checked againstNext()in UTC and a DST timezoneWhat it found
Real flaws, all filed:
[""]and silently corrupt\r\ninternal/cronreturns the zero time for leap-day schedules beyond its 5-year horizonwindowDuration: 0sWhere 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/util45.5% -> 66.7%,pkg/util/pki74.5% -> 76.4%, certificate-shim 92.0% -> 93.6%, policies 77.7% -> 78.3%;internal/apis/certmanager/validation/utilandpkg/api/utilunchanged 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:
SignatureAlgorithmpredicts whatcrypto/x509will do, so x509 itself is the oracle;ValidNameserverre-implements whatnet.JoinHostPortalready defines. Disagreement is a bug by definition.overrideRoundtripUvencoding "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.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