Repository navigation
fix(util): reject CSV input that cannot be read back unchanged, round-trip a single empty value - #9157
Conversation
…gle empty value, reject CR
JoinWithEscapeCSV and SplitWithEscapeCSV form a production round trip:
subject fields are joined into Secret annotations and ingress-shim splits
annotation values back into subject fields. Two counterexamples:
- []string{""} joins to the empty string, which SplitWithEscapeCSV then
rejects with "no values found after parsing \"\"" - a single empty
value cannot round-trip.
- A value containing "\r\n" comes back as "\n": encoding/csv's reader
silently normalises line endings inside quoted fields on read, so the
value is changed rather than rejected.
Fix: special-case the single-empty-value join to force explicit quoting
(unambiguous to parse back, since JoinWithEscapeCSV never otherwise
produces a bare unquoted empty field), and reject any value containing
a carriage return at join time instead of writing something that reads
back different from what was given.
Fixes cert-manager#9147
Signed-off-by: hamodywe <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Hi @hamodywe. Thanks for your PR. I'm waiting for a cert-manager member to verify that this patch is reasonable to test. If it is, they should reply with Regular contributors should join the org to skip this step. Once the patch is verified, the new status will be reflected by the I understand the commands that are listed here. 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. |
There was a problem hiding this comment.
Pull request overview
Improves the correctness of the CSV join/split helpers used to serialize subject/SAN-like string slices by fixing a previously failing round-trip edge case and preventing silent value mutation.
Changes:
- Update
JoinWithEscapeCSVto (1) force explicit quoting for the[]string{""}case and (2) reject any value containing\rto avoid silent CRLF normalization on read. - Add unit tests covering the round-trip cases (including the single-empty-value regression) and validating
\rrejection.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| pkg/util/util.go | Adds join-time validation for \r and a special-case encoding for []string{""} to guarantee round-tripping with SplitWithEscapeCSV. |
| pkg/util/util_test.go | Adds regression and round-trip unit tests for the CSV helpers, including explicit coverage for the single-empty-value case and CR rejection. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| // is escaped with quotes if necessary | ||
| func JoinWithEscapeCSV(in []string) (string, error) { | ||
| for _, v := range in { | ||
| if strings.ContainsRune(v, '\r') { |
There was a problem hiding this comment.
Should we instead check for \r\n instead of just \r.. I don't mind it as such but since encoding/csv only normalizes those it might safer to do that.. the blast radius from this is pretty low anway
There was a problem hiding this comment.
You're right, and I checked rather than guessed: a lone \r round-trips through encoding/csv untouched, including a trailing one, and only \r\n gets normalised to \n inside a quoted field.
in="lone\rCR" -> back="lone\rCR" round-trips
in="trailing\r" -> back="trailing\r" round-trips
in="\r" -> back="\r" round-trips
in="crlf\r\nhere" -> back="crlf\nhere" does not
So the check as written turned away values that would have come back exactly as given. Narrowed it to \r\n in c1cf0f9, and added a value with a lone carriage return to the round-trip table so the narrower rule is pinned by a test — that case fails if the check ever goes back to rejecting every \r.
Narrowing the check to the sequence that actually cannot survive the round trip, as raised in review. encoding/csv normalises "\r\n" to "\n" inside a quoted field and leaves a lone carriage return alone, so rejecting every "\r" turned away values that would have come back exactly as they were given. Measured against encoding/csv directly: "lone\rCR", "trailing\r" and "\r" all round-trip unchanged; only "crlf\r\nhere" comes back as "crlf\nhere". The round-trip table now carries a value with a lone carriage return, which pins the narrower rule: that case fails if the check goes back to rejecting every "\r". Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: hamodywe <[email protected]>
|
/ok-to-test |
|
/test pull-cert-manager-master-e2e-v1-36 |
|
/release-note-none |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
pkg/util/util.go:125
- This comment says a “bare, unquoted empty field is never produced by this function for any other input”, but
csv.Writerwill emit unquoted empty fields when the input contains empty elements alongside others (e.g. []string{"", "a"} -> ",a"). The ambiguity you’re addressing here is specifically the empty line output for a single empty field, so the comment should be tightened to avoid stating a false guarantee.
// encoding/csv writes a single empty field as an empty line, which
// SplitWithEscapeCSV cannot distinguish from "no values found" on
// read. Force explicit quoting for this one case so it round-trips;
// a bare, unquoted empty field is never produced by this function
// for any other input, so this is unambiguous to parse back.
pkg/util/util_test.go:292
- The rejection test currently only checks "\r\n" (CRLF). If the intent is to reject carriage returns in general ("\r"), this test should assert that as well (and can keep CRLF as an additional case if desired).
func TestJoinWithEscapeCSVRejectsCRLF(t *testing.T) {
_, err := JoinWithEscapeCSV([]string{"line1\r\nline2"})
if err == nil {
t.Fatal("JoinWithEscapeCSV with a value containing \\r\\n did not return an error, so it would silently corrupt on round trip")
}
Signed-off-by: Hemant Joshi <[email protected]>
|
/label tide/merge-method-squash |
|
Once the tests passes, this looks good to me to merge /lgtm |
wallrj
left a comment
There was a problem hiding this comment.
Thanks @hamodywe — the change is internally sound (the "" encoding is genuinely unambiguous, and the round trip holds under a large fuzz), but the new error path has consequences at the call sites this PR doesn't touch: it can wedge fresh issuance and silently halt post-issuance reconciliation for existing Secrets. Details and a suggested direction in the inline comments; the short version is that the CRLF handling belongs in AnnotationsForCertificate (degrade the one offending annotation) and the rejection belongs on SplitWithEscapeCSV, the parser that receives untrusted input.
A few description nits, since the release note ships verbatim:
- The description names
TestJoinWithEscapeCSVRejectsCarriageReturn, but the test isTestJoinWithEscapeCSVRejectsCRLF. - The title says "reject CR", but only the
\r\npair is rejected — a lone\rround-trips, as your own test shows. - The release-note sentence ("now reject values containing CRLF with new lines instead of silently altering them") doesn't parse; worth rewording before merge.
with claude fable-5
| // rather than writing a value that reads back different from what was | ||
| // given. A carriage return on its own does survive the round trip, so | ||
| // only the pair is rejected. | ||
| return "", fmt.Errorf("value %q contains a CRLF sequence, which cannot round-trip through CSV encoding", v) |
There was a problem hiding this comment.
Thanks for closing the loop from #9149 — the analysis in the description is right, but I think this rejection sits at the wrong layer. It turns a previously-dead error path live at two call sites, with rough consequences:
-
Fresh issuance wedges.
AnnotationsForCertificateis called fromsetValuesbefore the Secret is written. The webhook does no content validation on subject strings and CRLF is legal in a UTF8String, so a CA will sign a certificate with\r\nin a subject field — and that certificate now errors before the Secret Apply. The revision never bumps, the Issuing condition never clears, andfailedIssuanceAttemptsnever increments, so the controller retries on workqueue backoff forever against input it cannot change. Before this PR that input issued fine (the CRLF was CSV-quoted into the annotation). Same hard fail on the temporary-certificate path. -
Post-issuance reconciliation silently halts for existing Secrets on upgrade.
certificateDataAnnotationsForSecretnow errors on a stored certificate containing CRLF;SecretCertificateDetailsAnnotationsMismatchis second in the post-issuance chain and the chain short-circuits, so SecretTemplate metadata, keystores, additional output formats and owner references are never reconciled again for that Secret. The consumer swallows theInvalidCertificateviolation withreturn niland the Certificate stays Ready=True, so the only trace is one log line per resync. -
Smaller: one un-encodable field discards all twelve annotations via the sticky
encodingErr, rather than just the offending one.
Suggestion: keep the guard's intent, but move the CRLF handling up into AnnotationsForCertificate — skip or sanitise the single offending annotation (it is derived metadata, not payload), so issuance keeps working — and put the rejection on SplitWithEscapeCSV instead. That function is the only production parser, and it is fed user-authored Ingress/Gateway annotations; today it still silently normalises a quoted \r\n to \n and drops an unquoted trailing \r (verified against Go's encoding/csv reader), which is exactly the silent corruption this PR set out to close — while the Join-side guard protects output that nothing in-tree ever parses back. Also worth noting JoinWithEscapeCSV is exported, so downstream importers see a total function become partial.
| // No other input produces exactly `""` as the entire output (a literal | ||
| // quote character would be encoded as `""""`), so this is unambiguous | ||
| // to parse back. | ||
| return `""`, nil |
There was a problem hiding this comment.
The uniqueness argument is sound — I checked that no other input joins to exactly "" — but this changes a documented annotation value. On upgrade, an existing Secret whose certificate has a single empty subject value gets a one-time rewrite when the mismatch check compares the recomputed "" against the stored empty string. That converges, but it bumps resourceVersion and wakes watchers, so it deserves a mention in the release note. More awkward: the altNames != "" guard in ingress-shim no longer treats the value as empty, so cert-manager.io/alt-names: '""' copied from a Secret onto an Ingress appends an empty DNS name to spec.dnsNames instead of being ignored (that path splits on commas, not via SplitWithEscapeCSV).
| @@ -105,6 +105,28 @@ func EqualKeyUsagesUnsorted(s1, s2 []cmapi.KeyUsage) bool { | |||
| // JoinWithEscapeCSV returns the given list as a single line of CSV that | |||
| // is escaped with quotes if necessary | |||
There was a problem hiding this comment.
The doc comment is now stale: it mentions neither the error, the "" return, nor that len(in) == 0 is deliberately exempt from the round-trip guarantee — JoinWithEscapeCSV(nil) still returns "", which SplitWithEscapeCSV rejects with "no values found", and that case is hit for nearly every certificate because alt-names/ip-sans/uri-sans are written with keepEmpty=true. The exemption is worth an explicit comment precisely so nobody "fixes" it later: widening this guard to cover the empty slice would change three annotations on every Secret in every cluster and cause a mass rewrite on upgrade.
| func JoinWithEscapeCSV(in []string) (string, error) { | ||
| for _, v := range in { | ||
| if strings.Contains(v, "\r\n") { | ||
| // encoding/csv's reader silently normalises "\r\n" to "\n" inside a |
There was a problem hiding this comment.
House style here is US English in code comments: "normalizes". (The property test on #9149 that found this bug already spells it that way, so the tree would otherwise be inconsistent.)
| return ips | ||
| } | ||
|
|
||
| func TestJoinSplitWithEscapeCSVRoundTrip(t *testing.T) { |
There was a problem hiding this comment.
This table covers the same ground as the round-trip property test on #9149 that found both of these counterexamples. Once both PRs land, I'd rather relax that test's Assume exclusions to \r\n-only than pin the shrinker's counterexamples in a third place (helper_test.go already asserts some of this too). TestJoinWithEscapeCSVRejectsCRLF is worth keeping either way — a rejection isn't expressible as a round-trip property.
…nnotation Follow-up on review: keep the guard's intent, but put it where it cannot block issuance. JoinWithEscapeCSV is total again. Rejecting a CRLF there turned a previously-dead error path live at two call sites that cannot afford one. AnnotationsForCertificate runs between signing and the Secret Apply, so an error stranded a certificate a CA had already signed: the revision never bumped, the Issuing condition never cleared, and failedIssuanceAttempts never incremented, leaving the controller retrying on workqueue backoff against input it cannot change. It also runs inside the post-issuance policy chain, where an error short-circuits the checks that reconcile SecretTemplate metadata, keystores, additional output formats and owner references, with the violation swallowed by the consumer and the Certificate left Ready=True. The rejection now sits on SplitWithEscapeCSV, the only production parser and the one fed user-authored Ingress and Gateway annotations. It rejects exactly the two inputs encoding/csv reads back as something else: a CRLF inside a quoted field, which the reader rewrites as a line feed, and a carriage return at the end of the input, which it drops. A carriage return anywhere else survives the parse unchanged and is left alone. AnnotationsForCertificate drops the single offending annotation instead of discarding all twelve through a sticky error. These annotations are derived metadata, not the issued payload, so a value that cannot be read back costs its own annotation and nothing else. With no failure left to report the error return is gone, so the guarantee that this function cannot block issuance is structural rather than a promise. The empty slice is explicitly exempt from the round-trip check: alt-names, ip-sans and uri-sans are written with keepEmpty=true, and joining to "" is what nearly every Secret already carries. Also documents the `""` encoding and that exemption on JoinWithEscapeCSV so nobody widens it later, and spells "normalizes" the way the rest of the tree does. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: hamodywe <[email protected]>
|
/kind bug |
|
Thanks for this -- the two call sites were the part I hadn't followed through, and you're right that the guard was on the wrong side. Pushed the rework in edc6dfd. What it does now:
One decision I'd like your call on: since nothing can fail there any more, I removed the Description and release note are rewritten. The one-time annotation rewrite for a single empty subject value is in the note now. I left the On the test overlap with #9149 -- agreed, relaxing the
|
wallrj
left a comment
There was a problem hiding this comment.
Thanks @hamodywe — this is exactly the rework I was hoping for, and the description now reads as the design record for the change. Answers to your three open questions:
-
Keep the
errorremoval fromAnnotationsForCertificate. A signature that cannot fail is a stronger statement than an always-nil error — the previous revision's wedge existed precisely because a dead error path was sitting there waiting to come alive. It'sinternal/, both call sites got simpler, and the doc comment now explains why the function must not fail. The larger diff is the fix. -
Leave the
alt-names: '""'ingress-shim edge out. It needs a certificate with exactly one empty DNS name plus a hand-copied annotation; closing it here would widen the PR for a path nobody has hit. If it ever bites, it's a self-contained follow-up. -
Keep
TestJoinSplitWithEscapeCSVRoundTripas the[""]regression for now. Once #9149 lands I'll relax itsAssumeexclusions to cover what this PR fixed, and the table can shrink then.
One observation for the record, not blocking: the blanket strings.Contains(in, "\r\n") also rejects a trailing CRLF used as a line terminator, which encoding/csv previously consumed losslessly — I checked against the reader directly: "GB\r\n" parses to ["GB"] with the value unchanged, so this one input class was accepted before and errors now. It isn't in your "read back as something else" table because the value doesn't change. I'm fine with the over-rejection — the rule stays one line, the error is clear, and an annotation ending in \r\n is vanishingly rare — but it belongs in the record in case anyone ever reports it. I also confirmed the guards are precise where it matters: a quoted trailing "a\r" parses back unchanged and is correctly accepted.
Also verified: the empty-slice exemption is now pinned from three directions (the JoinWithEscapeCSV doc comment, the AnnotationsForCertificate comment, and the existing keepEmpty tests), the revert-check covers both new guards, and prow is green.
with claude fable-5.1
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: hjoshi123, wallrj The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
|
/lgtm |
Fixes #9147.
Reworked after @wallrj's review. The guard is unchanged in intent; it has moved to the layer where it cannot block issuance, and the rejection now sits on the parser rather than the writer.
The bug
JoinWithEscapeCSV/SplitWithEscapeCSVare the round trip that stores certificate subject fields as Secret annotations and reads them back for ingress-shim. The round-trip property test on #9149 found two counterexamples:[""](a single empty value) joins to""— an empty line — whichSplitWithEscapeCSVthen rejects withno values found after parsing "".encoding/csvwriting one empty field is indistinguishable from zero records on read."\r\n"comes back as"\n".encoding/csv's reader normalizes line endings inside a quoted field, so the value changes instead of erroring.What changed since the previous revision
The previous revision rejected CRLF inside
JoinWithEscapeCSV. As the review showed, that turned a previously-dead error path live at two call sites that cannot afford one:AnnotationsForCertificateruns between signing and the Secret Apply, so a CA-signed certificate carrying a CRLF in a subject field wedged: revision never bumps, Issuing condition never clears,failedIssuanceAttemptsnever increments.Ready=True.So the responsibilities are now split:
JoinWithEscapeCSV""; documents that the empty slice is deliberately exempt from the round trip, so nobody widens it later.SplitWithEscapeCSVAnnotationsForCertificateAnnotationsForCertificateno longer returns an error — there is nothing left for it to fail on, and making that structural is a stronger statement than a comment. It costs one branch each at its two call sites (setValues,certificateDataAnnotationsForSecret); it is aninternal/function, so there is no downstream API surface. Happy to restore the(map, error)signature if you would rather keep the shape.What
SplitWithEscapeCSVrejects, exactlyMeasured against
encoding/csvdirectly, only two inputs are read back as something else:encoding/csvreturns"line1\r\nline2"(quoted CRLF)line1\nline2— rewrittenline1\r(trailing CR)line1— droppedline1\rline2(CR elsewhere)line1\rline2— unchanged"line1\rline2"(quoted CR)line1\rline2— unchangedThe title of the previous revision said "reject CR", which was wrong on both counts — a lone
\rround-trips fine, and the rejection is no longer on the join side at all.Known consequence, stated rather than hidden
Encoding a single empty value as
""changes a documented annotation value. For an existing Secret whose certificate has a single empty subject value, the mismatch check recomputes""against the stored empty string and rewrites it once. That converges, but it bumpsresourceVersionand wakes watchers, so it is in the release note.The same value has one awkward edge that this PR does not change:
cert-manager.io/alt-names: '""'copied by hand from a Secret onto an Ingress is no longer treated as empty by thealtNames != ""guard in ingress-shim, because that path splits on commas rather than throughSplitWithEscapeCSV. Reaching it needs a certificate with exactly one, empty, DNS name and a manual copy of the annotation. Happy to add the guard here if you would rather close it in the same PR.Testing
New/changed:
TestSplitWithEscapeCSVRejectsInputItCannotReadBackUnchanged— the two lossy shapes above.TestSplitWithEscapeCSVKeepsACarriageReturnItCanReadBack— pins the narrow rule, so widening the check back to every\rfails here.Test_AnnotationsForCertificateSecret— a subject value containing a CRLF costs its own annotation and nothing else; a single empty subject value stores"".TestJoinWithEscapeCSVRejectsCRLFis gone, since the join side no longer rejects.TestJoinSplitWithEscapeCSVRoundTripstill overlaps the property test on #9149 as you noted; I have left it as the regression for the[""]case and am happy to drop it in favour of relaxing that test'sAssumeexclusions once both land.Revert-checked: with the two guards removed,
TestSplitWithEscapeCSVRejectsInputItCannotReadBackUnchangedfails on both cases and the CRLF annotation case reports the extracert-manager.io/subject-organizations: "\"Example\r\nOrganization\"". With them in place:Release Notes