Skip to content

Scrub the credentials of a presigned URL from the body of an HTTP error - #126229

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/scrub-presigned-credentials-from-http-error-body
Oct 19, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/scrub-presigned-credentials-from-http-error-body

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120407

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Hide the credentials of a presigned S3 URL that the remote server echoes in its error response body, such as the access key id and the signature in a SignatureDoesNotMatch error, in the exception of a failed HTTP request, system.query_log and the server log.

Description

On 26.9.11.2, a url() read or write of a presigned S3 URL that S3 rejects with SignatureDoesNotMatch prints the request's access key id and signature: S3 echoes them in <AWSAccessKeyId> and <SignatureProvided>, and that body is copied into the exception, which reaches the client, system.query_log and the server log. This is the second half of #120407 (comment).

#120407 masks the URI and scrubs the request's own credential strings from the body, but only an Authorization: Bearer token feeds that list. A presigned URL sends its credentials in the query string, so the message shows X-Amz-Signature=[HIDDEN] in the URI and the same signature in the body.

HTTPException::makeExceptionMessage now takes the presigned credentials from the URI it already masks (X-Amz-Signature, X-Amz-Security-Token, S3 Express X-Amz-S3session-Token, Signature, AWSAccessKeyId and the key id of X-Amz-Credential; names matched percent-decoded and case-insensitively, values as sent and percent-decoded) and scrubs them from the reason phrase and the body together with the Bearer token, in one linear pass. The work runs only when an HTTPException is built. ReadWriteBufferFromHTTP::callImpl passes the raw URI, as receiveResponse does, and its range errors, including the plain one for a range GET answered with 201, 202 or 204, scrub the same credentials and the Bearer token; the printed URI is unchanged.

Not covered: GCS names (X-Goog-*, GoogleAccessId); S3's <CanonicalRequestBytes> hex dump (the key id and the session token, not the signature); and a lower-case or percent-encoded name in the URI part, which #121348 handles in the URI masker.

The test answers like S3 from a local endpoint (SigV4 SELECT and INSERT, SigV2, a signature inside the session token, the other token names, an encoded name, a repeated one-letter signature, range reads reflecting the signature and a Bearer token in the reason phrase). Every leg fails on master and passes with this change.


Workflow [PR]
Sync PR [sync-upstream/pr/126229]

Version info

  • Merged into: 26.11.1.183-master (included in 26.11 and later)

groeneai and others added 2 commits October 16, 2026 05:53
S3 answers a presigned request whose signature does not match with a
`SignatureDoesNotMatch` body that echoes the request's credentials outside
URL form: `<AWSAccessKeyId>`, `<SignatureProvided>` (decoded), and
`<CanonicalRequest>`, i.e. the query without the signature, with `&` escaped
as `&amp;`, carrying the raw `X-Amz-Credential` and `X-Amz-Security-Token`.
`HTTPException::makeExceptionMessage` copies that body into the message, which
reaches the client, `system.query_log` and the server log.

ClickHouse#120407 masks the URI there and scrubs `body_secrets` from the body, but only
`requestCredentialSecrets` fills that list, and it returns nothing but an
`Authorization: Bearer` token. A presigned URL sends no such header, so the
message printed `X-Amz-Signature=[HIDDEN]` in the URI and the same signature
in the body. Running the URI masker over the body cannot replace this: it only
rewrites `?name=value` / `&name=value`, misses element text, and matches
nothing after `&amp;` escaping.

`makeExceptionMessage` now derives the presigned credentials from the `uri` it
receives (`presignedURLCredentials`, next to the tolerant query decoder in
`maskSensitiveQueryParameters`, renamed to `decodeQueryComponent`) and scrubs
them together with `body_secrets`. Values are taken as sent and decoded,
since S3 echoes both spellings; for `X-Amz-Credential` only the key id before
the first `/` is a secret. The combined list is sorted longest first, so a
secret contained in a longer one cannot break the longer one's match. The
work runs only when an exception is built, and it covers every
`HTTPException`, including direct constructions. URL metadata such as
`X-Amz-Date` or `Expires` is not scrubbed: its short values would be replaced
throughout the body.

This relies on `uri` arriving unmasked. `ReadWriteBufferFromHTTP::callImpl`
was the one remote-body caller passing `maskedURI(current_uri)`; it now passes
`current_uri.toString()`, and the printed URI is unchanged because
`makeExceptionMessage` applies the same `maskURICredentials` to it.

GCS names (`X-Goog-*`, `GoogleAccessId`) are not included: the echo is known
for S3 only, and a GCS V4 identifier is a percent-encoded e-mail whose raw and
decoded spellings differ.

The test answers like S3 from a local endpoint: SigV4 `SELECT` and `INSERT`,
SigV2, and a signature that is a prefix of the session token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`presignedURLCredentials` added only the decoded key id of
`X-Amz-Credential`, while the other credentials are added both as sent and
percent-decoded, as the header comment promises. An endpoint echoing the
query as sent (S3's `<CanonicalRequest>`) then printed a key id that was sent
with an escape, e.g. `AKIA%56...`. The raw key id ends at the first `/` or
`%2F`, which is exactly where the decoded one ends, and is added when it
differs from the decoded one.

The test sends the SigV4 key id with its `V` percent-encoded and checks both
spellings, in the message and in `system.query_log`.

The comment of `decodeQueryComponent` no longer claims that its result only
feeds the sensitivity decision: it is also a scrub needle now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (two rounds on this change; the last one found nothing)
Finding Verdict
⚠️ An access key id sent with a percent-escape in X-Amz-Credential (AKIA%56...) was scrubbed only in its decoded spelling, so an endpoint echoing the query as sent would print it AGREE, fixed: the key id is added as sent too, and the test sends one
💡 decodeQueryComponent's comment still described a name-only decoder AGREE, fixed
💡 Real S3 also sends the canonical request re-encoded and as a hex dump (<CanonicalRequestBytes>), so the key id and the session token can survive in those spellings Noted: neither form carries the signature, which is scrubbed in both spellings, so nothing that signs a request is left. Stated in the description
💡 Conflicts textually with #126180 in makeExceptionMessage Noted: a different defect (bearer token in the reason phrase); whichever lands second takes the merge
💡 A one-character presigned value is replaced throughout the body Noted: same policy as the merged bearer scrub; nothing is exposed

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b48f73]

Summary: ✅


AI Review

Summary

The PR scrubs presigned S3 credentials from reflected HTTP error reasons and bodies, including parallel and resumed range-read failures. Review of head 1b48f739cf069fd39f7634b032662e9f4e7a0ff5 found no actionable issues remaining; all five prior inline findings are addressed in the current code. The focused regression 05404_http_error_body_presigned_credentials_scrubbed passes in the head's Fast test report.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05404_http_error_body_presigned_credentials_scrubbed against a local endpoint answering like S3 SignatureDoesNotMatch: all 4 legs leak on master every run. Also measured on official 26.8.18.2 and 26.9.11.2 (SELECT and INSERT).
b Root cause explained? makeExceptionMessage scrubs from the body only requestCredentialSecrets(request), which yields nothing but a Bearer token. A presigned URL carries its credentials in the query string, so the values S3 echoes in <AWSAccessKeyId>, <SignatureProvided> and <CanonicalRequest> pass verbatim.
c Fix matches root cause? Yes. The formatter adds the presigned credentials of the URI it already masks to the same value scrub. No body omission, no format-specific denylist.
d Test intent preserved / new tests added? New stateless test (SigV4 SELECT/INSERT, SigV2, contained-secret leg, system.query_log check). It asserts the scrubbed shapes and the kept metadata, not only absence. Existing tests unchanged; 05212 still passes.
e Both directions demonstrated? Master: 4/4 legs FAIL. Fix: 4/4 OK, 50/50 randomized. Six mutations (decoded only, raw only, no key-id branch, key id decoded only, callImpl keeps the masked URI, no sort) each red only their own legs.
f Fix is general across code paths? One site covers every HTTPException (receiveResponse, callImpl, Avro, ACME, proxy resolver, direct constructions). callImpl was the one remote-body caller passing a pre-masked URI and now passes the raw one; its printed URI is unchanged. Also OK through urlCluster (parallel replicas for cluster engines, both local-plan values).
g Fix generalizes across inputs (params/datatypes/wrappers)? SigV4 and SigV2, raw and percent-decoded spellings (also of a percent-encoded access key id), a secret contained in another, malformed % escapes, empty and valueless parameters, no query string. No type wrappers (string-level). GCS names are not included, stated in the description.
h Backward compatible? (maintainer-approved exception only) Yes. Only the exception text of an HTTP error whose URI carries one of the S3 presigned credential names changes. No setting, format or protocol change.
i Invariants and contracts preserved? Building the exception cannot throw on any input (pure string scans, tolerant decoder). body length still reports the original body; getResponseBody() still returns the raw body. The new contract (uri arrives unmasked) is stated at the one site depending on it, and every caller satisfies it.

Session id: cron:clickhouse-impl-slot-6:20261016-061900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @yakov-olkhovskiy, could you review this and add can be tested (CI did not start without it)? A presigned URL carries its credentials in the query string, so the body scrub from #120407, which only gets a Bearer token, leaves the <AWSAccessKeyId> and <SignatureProvided> values that S3 echoes in a SignatureDoesNotMatch body; this adds the presigned credentials of the request URI to that scrub in HTTPException::makeExceptionMessage.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
Comment thread src/IO/HTTPCommon.cpp Resolved
groeneai and others added 2 commits October 17, 2026 03:30
…igned-credentials-from-http-error-body

# Conflicts:
#	src/IO/HTTPCommon.cpp
…he peer does

Three defects of the presigned-URL body scrub, found by the automated review:

1. The scrub replaced each credential in turn over its own output, and kept
   duplicates. `[HIDDEN]` itself contains letters, so a short credential that
   occurs in it (`Signature=D` repeated 18 times) doubled the text on each
   pass: a 456-byte 403 body became a 3.67 MB exception message. Now the
   credentials are deduplicated, every match is located in the original
   text, and each covered run becomes one `[HIDDEN]`, so the output is
   linear in the input and a secret contained in another is still covered
   without ordering them by length.

2. Session tokens under other names were not extracted: botocore's SigV2
   presigner emits `x-amz-security-token`, its S3 Express presigner
   `X-Amz-S3session-Token`.

3. Names were compared as sent, while a peer such as MinIO percent-decodes
   them, so `X-Amz-%53ignature=<sig>` was echoed in `<SignatureProvided>`
   unscrubbed. Names are now decoded and lower-cased before matching, with
   the helper the server-side masker in the same file already uses.

The URI part of the message is still masked by `maskURICredentials`, which
matches names case-sensitively as typed, so it keeps showing the lowercase
SigV2 token and a percent-encoded name; that is that shared masker's policy
and is not changed here. The test checks those two spellings in the body.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/IO/HTTPCommon.cpp Resolved
…HTTP

`HTTPException` derives the credentials to scrub from the URI it is given, so the
two range-error constructors in `initialize` and `readBigAt`, which still passed an
already masked URI, scrubbed only `[HIDDEN]` and left a credential that the server
reflected in its reason phrase visible in the reason and in the diagnostic body.
The URI shown in the message is masked by `HTTPException` itself, as for `callImpl`.

The test gains a parallel range read (`readBigAt`) and a sequential read resumed
with a range after the connection is cut (`initialize`), each answered with 200 and
the signature as the reason phrase. Each leg fails when only its own site is
reverted. The parallel leg pins the HEAD request that tells the reader the source
is seekable, and turns parallel replicas for cluster engines off, since
`urlCluster` reads the file sequentially. The `query_log` check also asserts that
the errors are logged with the scrubbed body, so that it cannot pass on no rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/IO/ReadWriteBufferFromHTTP.cpp Resolved
A resumed sequential read whose range GET is answered with 201, 202 or 204
passes `assertResponseIsOk` and then fails in `ReadWriteBufferFromHTTP::initialize`
with a plain `Exception` that printed the remote reason phrase verbatim, so a
reflected presigned signature reached the client, the server log and
`system.query_log` while the URI next to it was masked. Its reason is now
scrubbed with the same credentials as `HTTPException`, through a small
`scrubRequestCredentials` helper. The exception type is unchanged, so it is
still not retried (measured: one range request with `http_max_tries = 5`).

The three range errors (this one, the retried 200 in `initialize`, and
`readBigAt`) also passed no request secrets, unlike `callImpl`, so a bearer
token from `headers('Authorization' = 'Bearer ...')` reflected in the reason
phrase survived. They now scrub the bearer token of the request's headers too.

Test 05404: a `select_resumed_range_201` leg; the range legs send a bearer
token that the mock reflects next to the signature. The mock now binds a free
port itself and reports it through a file, instead of the shell probing a port
and freeing it again, which lost 1 of 50 parallel runs to `Address already in
use`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 05ff5f3d8 with master 0a3052562 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

151 translation units recompiled, 1153 s compile time in total, 151 of them have a recent master baseline.

Job report

The mock closed the connection after its HEAD reply on the range endpoint
without sending `Connection: close`, so the client returned that connection
to the pool. A range GET of the parallel read could borrow it before the
close reached the client, so the pool's staleness check passed, and fail
with `No message received` ahead of the 416 the leg checks. That is the one
failure in 46 runs of `Stateless tests (amd_tsan, s3 storage, targeted)`.
With the header the client does not pool the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok. We go a really long way to find sensitive parameters...

@alexey-milovidov alexey-milovidov self-assigned this Oct 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit eb86dbf Oct 19, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... and removed comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants