Repository navigation
fix(acme): keep ACME server response bodies out of Issuer status - #9202
Conversation
The ACME server is user controlled: spec.acme.server may point at any URL the controller is able to reach. When a request fails, the ACME client copies the response body verbatim into the returned error if that body is not a problem document, and the issuer setup path copied that error into the Issuer's Ready condition and into a Warning Event. Both are persisted to the API server and are readable by anyone who can read the Issuer, which turned the Issuer status into an oracle for HTTP endpoints the reader cannot otherwise reach. Only surface errors which identify themselves as RFC 8555 problem documents, matched against the urn:ietf:params:acme:error: namespace that section 6.7 reserves, and report anything else by status code alone. Genuine ACME errors keep their detail, so operators still see messages such as rate limit explanations. The message is additionally bounded at 1024 bytes, backing off to a rune boundary so that the result is always valid UTF-8. The unabridged error continues to be written to the controller log, keeping full detail available to privileged readers. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: Felix Phipps <[email protected]>
There was a problem hiding this comment.
Pull request overview
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
This PR prevents ACME server-controlled response bodies from being persisted into Issuer status conditions and Kubernetes Warning Events, mitigating information disclosure and unbounded status growth risks.
Changes:
- Introduces
safeErrorMessage()to sanitize ACME errors before writing to Issuer conditions/events. - Adds length-bounding via
truncateMessage()with UTF-8 safety. - Expands
TestAcme_Setupand adds targeted unit tests validating sanitization and truncation behavior.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| pkg/issuer/acme/setup.go | Adds sanitization and truncation utilities and uses them when emitting status/event messages. |
| pkg/issuer/acme/setup_test.go | Updates expectations and adds unit tests to ensure non-ACME bodies are not reflected and messages are bounded. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| func safeErrorMessage(err error) string { | ||
| acmeErr, ok := err.(*acmeapi.Error) | ||
| if !ok { | ||
| // Not a response from the ACME server: this was raised locally or by the | ||
| // Kubernetes API and carries no remote content. | ||
| return truncateMessage(err.Error(), maxACMEErrorMessageLength) | ||
| } |
There was a problem hiding this comment.
Verified: nothing on the Register/GetReg/UpdateReg path wraps today — post/get return the bare *Error (http.go#L172-L199) and the client middleware is pass-through — so this is latent rather than live. Still worth doing, because the failure mode is silently reintroducing the leak. The codebase already uses the unwrap-aware form for this exact type: errors.AsType[*acmeapi.Error](err) at acmeorders/sync.go#L270. Note errors in this file is cert-manager's pkg/util/errors, so the stdlib import needs an alias.
with claude fable-5
There was a problem hiding this comment.
Done in 23d99fe. Used errors.AsType[*acmeapi.Error](err)per @wallrj's pointer to acmeorders/sync.go:270, and aliased cert-manager's pkg/util/errors as cmerrors so the stdlib import can take the bare name — cmerrors is the alias already used in internal/vault/vault.go and the certificaterequests controllers.
Applied in safeErrorMessage only; the two assertions driving 4xx/5xx retry routing are unchanged. Added a test with a %w-wrapped ACME error — reverting to the bare assertion fails it, leaking "registering account: 403 : AKIAIOSFODNN7EXAMPLE".
| return truncateMessage(acmeErr.Error(), maxACMEErrorMessageLength) | ||
| } | ||
|
|
||
| // truncateMessage bounds s to maxLen bytes, appending a marker so that readers | ||
| // can tell the message is incomplete. | ||
| func truncateMessage(s string, maxLen int) string { | ||
| if len(s) <= maxLen { | ||
| return s | ||
| } |
There was a problem hiding this comment.
Prior art in this repo reserves room for the marker so the stated bound is the real bound: truncateString does s[:maxLength-3] + "...". Doing the same here also resolves the mismatched failure message in TestSafeErrorMessage flagged below.
with claude fable-5
There was a problem hiding this comment.
Fixed: maxACMEErrorMessageLength now bounds the whole string, marker included. Couldn't reuse truncateString itself — it's unexported in internal/apis/certmanager/validation, fixed at 100 bytes with no parameter, and its s[:maxLength-3] isn't rune-safe (fine for an ASCII CSR, not for a server-supplied body) — but the convention is the same.
| } | ||
|
|
||
| // trim spaces to make output readable if it ends with whitespace | ||
| return strings.TrimSpace(truncated) + "... (truncated)" |
There was a problem hiding this comment.
The bound now includes the marker.
| // trim spaces to make output readable if it ends with whitespace | ||
| return strings.TrimSpace(truncated) + "... (truncated)" |
There was a problem hiding this comment.
Correct, it is now strings.TrimRight(truncated, " \t\r\n").
| t.Errorf("message leaks server controlled content: %q", got) | ||
| } | ||
| if len(got) > maxACMEErrorMessageLength+len("... (truncated)") { | ||
| t.Errorf("message is %d bytes, want at most %d", len(got), maxACMEErrorMessageLength) |
There was a problem hiding this comment.
Resolved by making the bound real: the assertion is now len(got) > maxACMEErrorMessageLength, which matches the failure text. The suggested changeset is stale.
| // to retrieve an existing account - perhaps we should log different | ||
| // messages in those two scenarios. | ||
| msg := messageAccountRegistrationFailed + err.Error() | ||
| msg := messageAccountRegistrationFailed + safeErrorMessage(err) |
There was a problem hiding this comment.
The condition message is sanitised here, but the non-4xx branches below still return the raw *acmeapi.Error (err: err at L378, and L424 on the update path), and both callers reflect that into a Warning Event:
cert-manager/pkg/controller/issuers/sync.go
Lines 59 to 64 in 9870f9a
(same in pkg/controller/clusterissuers/sync.go#L59-L64): s := messageErrorInitIssuer + err.Error() then recorder.Event(...). So a 5xx from a non-ACME endpoint — a proxy error page, say — still lands, unsanitised and unbounded, in an API-server-persisted Event via ErrInitIssuer. That is the same class of leak this PR sets out to close, one layer up.
Consider having Setup() return a sanitised error (keeping the status-code classification for retry), or sanitising in the two sync callers.
with claude fable-5
There was a problem hiding this comment.
Amended, those now return fmt.Errorf("%s", msg), matching the convention at setup.go:142.
Also added 502 cases on the register and update paths plus a runner assertion that the error returned from Setup never carries the planted secret.
| // errors to use the urn:ietf:params:acme:error: namespace. Anything else is | ||
| // either a raw body the client could not parse or a problem document from | ||
| // some other service, and in both cases it is not safe to reflect. | ||
| if !strings.HasPrefix(strings.ToLower(acmeErr.ProblemType), acmeErrorURNPrefix) { |
There was a problem hiding this comment.
The PR description says this matches the namespace "as isBadNonce already does", but isBadNonce deliberately does the opposite — it matches by suffix precisely because "ACME servers in the wild return their versions of the error" (the pre-RFC-8555 urn:acme:error: namespace):
cert-manager/third_party/forked/acme/http.go
Lines 306 to 314 in 9870f9a
and the forked client's own doc comment calls urn:acme:error:xxx the typical form (types.go#L115). A CA still emitting the legacy namespace would now have its genuine error detail hidden. It fails closed, so this may be an acceptable trade — but consider also accepting the urn:acme:error: prefix so older ACME implementations keep their detail.
with claude fable-5
There was a problem hiding this comment.
Well spotted, I have amended the PR description.
| // in the Kubernetes Events raised alongside it. Both are persisted to the API | ||
| // server and are readable by anyone who can read the Issuer, so they must not | ||
| // carry content chosen by the ACME server. | ||
| func safeErrorMessage(err error) string { |
There was a problem hiding this comment.
Placement: safeErrorMessage is unexported here, but the same reflection exists at sinks that cannot reach it — Order.Status.Reason (a dozen sites in pkg/controller/acmeorders/sync.go) and Challenge.Status.Reason, which copies acmeErr.Detail verbatim and then feeds a Prometheus label:
cert-manager/pkg/controller/acmechallenges/sync.go
Lines 425 to 430 in 9870f9a
cert-manager/internal/collectors/acme_collector.go
Lines 63 to 71 in 9870f9a
There is also prior art for "make an error safe to persist": stabilizeSolverErrorMessage. Suggest moving this helper to a shared package (e.g. pkg/acme/util) so the order/challenge sites can adopt it in follow-ups. Deeper still, the unboundedness could be fixed once at the root: responseError does an uncapped io.ReadAll into Detail (http.go#L326-L341) — an io.LimitReader there bounds every consumer, including the logs, at once.
with claude fable-5
There was a problem hiding this comment.
On the root fix: an io.LimitReader in responseError can't land here — make update-third-party re-syncs third_party/forked/acme from cert-manager/crypto via klone and re-applies only three mechanical seds, so an in-tree edit is silently reverted. That belongs upstream.
The unbounded-read half is already mitigated at the boundary: pkg/acme/client/http.go caps bodies at 16 MiB via http.MaxBytesReader. The Challenge Status.Reason → Prometheus label path you flagged is the more interesting sink, since it widens the audience beyond Issuer readers. Happy to open issues for the upstream change and for the Order/Challenge sites.
| // Cutting on a byte boundary can split a multi-byte rune in half. Drop any | ||
| // trailing partial rune so that the result is always valid UTF-8, which the | ||
| // API server requires of the strings it stores. | ||
| for len(truncated) > 0 { |
There was a problem hiding this comment.
strings.ToValidUTF8(s[:maxLen], "") does this in one line, and actually guarantees what the comment promises — this loop only repairs the cut point, so invalid bytes anywhere else in the string would survive. Combined with the two Copilot suggestions (reserve room for the marker; right-trim only):
const marker = "... (truncated)"
truncated := strings.ToValidUTF8(s[:maxLen-len(marker)], "")
return strings.TrimRight(truncated, " \t\n\r") + markerwith claude fable-5
There was a problem hiding this comment.
Now strings.ToValidUTF8 + strings.TrimRight, with the marker reserved from the budget as suggested. Added a test with an invalid byte mid-string, which the old loop would have passed through.
Address review feedback on the previous commit. The Issuer and ClusterIssuer controllers copy the error returned from Setup into a Warning Event of their own, so sanitising only the status condition left the response body reachable through that Event whenever the ACME server answered with a 5xx. Return the sanitised message from those retry branches instead of the ACME error itself. Neither caller inspects the error's type, so retry behaviour is unchanged. Also accept the pre-RFC 8555 urn:acme:error: namespace, which some CAs still emit and which isBadNonce in the forked ACME client already tolerates. Matching only the namespace reserved by section 6.7 would have withheld genuine error detail from those CAs without any benefit: the endpoints this guards against emit neither namespace. Use errors.AsType rather than a bare type assertion, so that an ACME error wrapped on its way up cannot bypass the check, and make the 1024 byte limit bound the whole message rather than the message plus the truncation marker. strings.ToValidUTF8 replaces the hand rolled trimming of split runes. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: Felix Phipps <[email protected]>
|
@FelixPhipps: The label(s) DetailsIn response to this:
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. |
|
/kind bug |
wallrj
left a comment
There was a problem hiding this comment.
Thanks @FelixPhipps, all my findings and Copilot's are addressed in 23d99fe:
- The non-4xx branches now return the sanitised message, and the callers only ever call
err.Error()and requeue, so nothing depends on the concrete error type. - Legacy
urn:acme:error:namespace accepted viaisACMEProblemType. truncateMessagenow genuinely bounds the whole string, marker included, andstrings.ToValidUTF8covers invalid bytes anywhere in the string — nice test for the mid-string case.errors.AsTypewith thecmerrorsalias matches the house style.
I verified the 16 MiB http.MaxBytesReader cap at pkg/acme/client/http.go#L93, and you're right that third_party/forked/acme edits would be reverted by make update-third-party — the io.LimitReader change belongs upstream. Yes please to the two follow-up issues (upstream responseError cap, and the Order/Challenge Status.Reason sinks — the Prometheus label path especially). Link them here so they're findable from this PR.
Tests pass locally (go test ./pkg/issuer/acme/).
/approve
/lgtm
/label tide/merge-method-squash
with claude fable-5
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: 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 |
…t-manager#9202) * fix(acme): keep ACME server response bodies out of Issuer status The ACME server is user controlled: spec.acme.server may point at any URL the controller is able to reach. When a request fails, the ACME client copies the response body verbatim into the returned error if that body is not a problem document, and the issuer setup path copied that error into the Issuer's Ready condition and into a Warning Event. Both are persisted to the API server and are readable by anyone who can read the Issuer, which turned the Issuer status into an oracle for HTTP endpoints the reader cannot otherwise reach. Only surface errors which identify themselves as RFC 8555 problem documents, matched against the urn:ietf:params:acme:error: namespace that section 6.7 reserves, and report anything else by status code alone. Genuine ACME errors keep their detail, so operators still see messages such as rate limit explanations. The message is additionally bounded at 1024 bytes, backing off to a rune boundary so that the result is always valid UTF-8. The unabridged error continues to be written to the controller log, keeping full detail available to privileged readers. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: Felix Phipps <[email protected]> * fix(acme): sanitise the error returned from ACME issuer setup Address review feedback on the previous commit. The Issuer and ClusterIssuer controllers copy the error returned from Setup into a Warning Event of their own, so sanitising only the status condition left the response body reachable through that Event whenever the ACME server answered with a 5xx. Return the sanitised message from those retry branches instead of the ACME error itself. Neither caller inspects the error's type, so retry behaviour is unchanged. Also accept the pre-RFC 8555 urn:acme:error: namespace, which some CAs still emit and which isBadNonce in the forked ACME client already tolerates. Matching only the namespace reserved by section 6.7 would have withheld genuine error detail from those CAs without any benefit: the endpoints this guards against emit neither namespace. Use errors.AsType rather than a bare type assertion, so that an ACME error wrapped on its way up cannot bypass the check, and make the 1024 byte limit bound the whole message rather than the message plus the truncation marker. strings.ToValidUTF8 replaces the hand rolled trimming of split runes. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: Felix Phipps <[email protected]> --------- Signed-off-by: Felix Phipps <[email protected]> Co-authored-by: Felix Phipps <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
|
/cherry-pick release-1.21 with claude fable-5 |
|
@wallrj: new pull request created: #9239 DetailsIn response to this:
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. |
|
@FelixPhipps This change has been included in v1.21.2, which is now published. If you are able to install the release and verify that the change works as expected in your environment, that would be much appreciated. Thank you for the contribution. |
Description
Problem
The ACME issuer's
Setuppath registers or updates an account againstspec.acme.server, and on failure copies the returned error into places that are persisted to the API server: the Issuer'sReadycondition message, a Warning Event raised on the update path, and — via the error returned to the Issuer and ClusterIssuer controllers — a secondErrInitIssuerWarning Event.spec.acme.serveris user-controlled and may point at any URL the controller can reach. When a request fails, the ACME client'sresponseError()copies the response body verbatim intoError.Detailwhenever that body doesn't parse as a problem document. Reflecting that error into the Issuer status turns it into an oracle for HTTP endpoints the reader cannot otherwise reach:metadata, an admin API, anything on the pod network) lands in
Issuer.status.conditions[Ready].message, readable by anyone withget issuerand persisted to etcd.Solution
Sanitise at the boundary, in cert-manager-owned code.
safeErrorMessage()surfaces an ACME error in full only when it identifies itself as an ACME problem document, matched case-insensitively against theurn:ietf:params:acme:error:namespace reserved by RFC 8555 §6.7 and the pre-RFCurn:acme:error:namespace that some CAs still emit. Anything else — a raw body the client couldn't parse, or an RFC 7807 document from some other service — is reported by status code alone. This fails closed: the degradation is a less specific condition message.The sanitised message is also what
setup()returns on the retryable (5xx) paths, rather than the*acmeapi.Erroritself, so the leak doesn't reappear one layer up in the Event the sync controllers raise. Neither caller inspects the error's type, so retry behaviour is unchanged.Genuine ACME errors keep their detail, so rate-limit and
invalidEmailexplanations still reach operators unchanged. Messages are bounded at 1024 bytes in total, marker included, withstrings.ToValidUTF8guaranteeing the result is valid UTF-8 even when the cut falls mid-rune. The unabridged error continues to be written to the controller log via the existinglog.Errorcalls, keeping full detail available to privileged readers.Locally-raised and Kubernetes API errors (private key generation, EAB Secret lookups) carry no remote content and are unchanged.
Test plan
TestSafeErrorMessage— eight cases: locally-raised errors pass through; conformant problem documents in both the RFC 8555 and pre-RFC namespaces keep their detail; casing variants are recognised; a reflected HTML body, a non-ACME RFC 7807 document, a URN outside the error namespace, and a wrapped ACME error are all reduced to status code. Every case asserts the planted secret is absent and the length is bounded.TestSafeErrorMessageBoundsLength— a conformant server cannot fill the status with an oversizedDetail.TestTruncateMessage— eight cases, including a multi-byte rune split at the byte limit, an invalid byte mid-string, and limits smaller than the truncation marker; all results asserted valid UTF-8 and within the bound.TestAcme_Setupcases cover every sink end to end: the condition, the update-path Warning Event, and the error returned on the 5xx retry paths for both register and update. The shared runner now asserts that the error returned fromSetupnever carries server-controlled content.acmeErr450/acmeErr500carry noProblemType, so they now correctly render as non-conformant.err.Error()fails 8 subtests; reverting the 5xx branches toerr: errfails 2; revertingerrors.AsTypeto a bare type assertion fails 1, leaking"registering account: 403 : AKIAIOSFODNN7EXAMPLE".go test ./pkg/issuer/acme/... ./pkg/controller/issuers/..../pkg/controller/clusterissuers/...,go build ./...,go vet, andgofmtall clean.Release note