Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(blob-storage): log S3 signing diagnostics on upload failures (#14356)

Niklas Semmler87cb681f7126
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.ts
index e27b542859..e48b100c59 100644
--- a/packages/shared/src/server/services/StorageService.ts
+++ b/packages/shared/src/server/services/StorageService.ts
@@ -25,6 +25,11 @@ import { backOff } from "exponential-backoff";
import { ServiceUnavailableError } from "../../errors";
import { BufferedStreamUploader } from "./BufferedStreamUploader";
import { S3ChunkedUploadStrategy } from "./S3ChunkedUploadStrategy";
+import {
+ buildS3RequestDiagnostics,
+ isS3SigningError,
+ type S3SigningDiagnosticsContext,
+} from "./s3SigningDiagnostics";
import * as objectstorage from "oci-objectstorage";
import * as common from "oci-common";
import { UploadManager as OciUploadManager } from "oci-objectstorage";
@@ -114,6 +119,69 @@ function createS3RequestHandler(
});
}
+/**
+ * Register a diagnostics middleware on an {@link S3Client} that logs the
+ * framing headers actually sent and the structured error when a request fails
+ * with a signing/authorization error (e.g. `SignatureDoesNotMatch`).
+ *
+ * It runs at the `deserialize` step with `high` priority so it wraps the SDK's
+ * own deserializer: by then the request is fully built and signed (so the
+ * framing headers are final), and the SDK has turned an error response into a
+ * thrown `S3ServiceException` (so we see the typed error, not a raw response).
+ *
+ * Logging is gated to signing-related error codes so unrelated failures
+ * (`NoSuchKey`, `AccessDenied`, throttling, timeouts) don't emit a misleading
+ * signing-themed log or one line per SDK retry. Diagnostics are best-effort and
+ * never alter or mask the original failure.
+ */
+function addS3SigningDiagnosticsMiddleware(
+ client: S3Client,
+ context: S3SigningDiagnosticsContext,
+): void {
+ type S3MiddlewareArgs = { request?: unknown };
+ type S3MiddlewareNext = (args: S3MiddlewareArgs) => Promise<unknown>;
+
+ const diagnosticsMiddleware =
+ (next: S3MiddlewareNext) => async (args: S3MiddlewareArgs) => {
+ try {
+ return await next(args);
+ } catch (err) {
+ try {
+ const diagnostics = buildS3RequestDiagnostics(
+ args.request,
+ err,
+ context,
+ );
+ if (isS3SigningError(diagnostics.error)) {
+ logger.warn(
+ "S3 request failed with a signing/authorization error; emitting diagnostics (helps debug SignatureDoesNotMatch on non-AWS S3-compatible backends such as GCS interop)",
+ diagnostics,
+ );
+ }
+ } catch {
+ // Never let diagnostics logging mask the original failure.
+ }
+ throw err;
+ }
+ };
+
+ client.middlewareStack.add(
+ // Bridge the structural middleware to the SDK's middleware union without
+ // taking a direct dependency on @smithy/types. The handler reads only
+ // `request`, so the unused `input` field of the SDK's arg type is elided.
+ diagnosticsMiddleware as unknown as Parameters<
+ typeof client.middlewareStack.add
+ >[0],
+ {
+ step: "deserialize",
+ priority: "high",
+ name: "langfuseS3SigningDiagnostics",
+ tags: ["LANGFUSE", "DIAGNOSTICS"],
+ override: true,
+ },
+ );
+}
+
function createAzureBlobPipeline(
sharedKeyCredential: StorageSharedKeyCredential,
connectionValidation?: OutboundUrlConnectionValidationOptions,
@@ -595,6 +663,16 @@ class S3StorageService implements StorageService {
requestHandler,
});
+ // Log signing/framing diagnostics for any failed S3 request on the upload
+ // client. Surfaces checksum/`aws-chunked` framing that non-AWS backends
+ // (e.g. GCS) reject with SignatureDoesNotMatch despite valid credentials.
+ addS3SigningDiagnosticsMiddleware(this.client, {
+ bucketName: params.bucketName,
+ endpoint: params.endpoint,
+ region: params.region,
+ forcePathStyle: params.forcePathStyle,
+ });
+
// Create a separate client for generating presigned URLs
// If an external endpoint is provided, use it for the URL client
// Otherwise, use the same client for both operations
diff --git a/packages/shared/src/server/services/s3SigningDiagnostics.test.ts b/packages/shared/src/server/services/s3SigningDiagnostics.test.ts
new file mode 100644
index 0000000000..2ab3b65c29
--- /dev/null
+++ b/packages/shared/src/server/services/s3SigningDiagnostics.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildS3RequestDiagnostics,
+ classifyContentSha256Mode,
+ isS3SigningError,
+ summarizeS3Error,
+ summarizeS3SigningHeaders,
+} from "./s3SigningDiagnostics";
+
+describe("classifyContentSha256Mode", () => {
+ it("reports a single-chunk signed payload for a hex digest", () => {
+ expect(classifyContentSha256Mode("a".repeat(64))).toBe(
+ "single-chunk-sha256",
+ );
+ // mixed case hex is still a valid digest
+ expect(classifyContentSha256Mode("ABCDEF" + "0".repeat(58))).toBe(
+ "single-chunk-sha256",
+ );
+ });
+
+ it("passes streaming/trailer modes through verbatim", () => {
+ expect(
+ classifyContentSha256Mode("STREAMING-UNSIGNED-PAYLOAD-TRAILER"),
+ ).toBe("STREAMING-UNSIGNED-PAYLOAD-TRAILER");
+ expect(
+ classifyContentSha256Mode("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"),
+ ).toBe("STREAMING-AWS4-HMAC-SHA256-PAYLOAD");
+ expect(classifyContentSha256Mode("UNSIGNED-PAYLOAD")).toBe(
+ "UNSIGNED-PAYLOAD",
+ );
+ });
+
+ it("handles absent and unexpected values without throwing", () => {
+ expect(classifyContentSha256Mode(undefined)).toBe("absent");
+ expect(classifyContentSha256Mode("")).toBe("absent");
+ expect(classifyContentSha256Mode("not-a-hash")).toBe("other");
+ });
+});
+
+describe("summarizeS3SigningHeaders", () => {
+ it("flags the checksum/aws-chunked framing that GCS rejects", () => {
+ const summary = summarizeS3SigningHeaders({
+ "Content-Encoding": "aws-chunked",
+ "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
+ "x-amz-trailer": "x-amz-checksum-crc32",
+ "x-amz-sdk-checksum-algorithm": "CRC32",
+ });
+
+ expect(summary.usesAwsChunkedEncoding).toBe(true);
+ expect(summary.hasChecksumTrailer).toBe(true);
+ expect(summary.contentSha256Mode).toBe(
+ "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
+ );
+ expect(summary.checksumHeaders).toEqual(["x-amz-sdk-checksum-algorithm"]);
+ });
+
+ it("reports a clean single-chunk PUT (the curl-equivalent request)", () => {
+ const summary = summarizeS3SigningHeaders({
+ "x-amz-content-sha256": "b".repeat(64),
+ });
+
+ expect(summary.usesAwsChunkedEncoding).toBe(false);
+ expect(summary.hasChecksumTrailer).toBe(false);
+ expect(summary.contentSha256Mode).toBe("single-chunk-sha256");
+ expect(summary.checksumHeaders).toEqual([]);
+ expect(summary.contentEncoding).toBeUndefined();
+ });
+
+ it("is case-insensitive on header names and tolerates missing headers", () => {
+ expect(summarizeS3SigningHeaders(undefined).contentSha256Mode).toBe(
+ "absent",
+ );
+ const summary = summarizeS3SigningHeaders({
+ "X-Amz-Checksum-Crc32": "abc",
+ "X-AMZ-TRAILER": "x-amz-checksum-crc32",
+ });
+ expect(summary.hasChecksumTrailer).toBe(true);
+ expect(summary.checksumHeaders).toEqual(["x-amz-checksum-crc32"]);
+ });
+});
+
+describe("summarizeS3Error", () => {
+ it("extracts structured fields from an AWS SDK service exception", () => {
+ const err = Object.assign(
+ new Error("The request signature we calculated"),
+ {
+ name: "SignatureDoesNotMatch",
+ Code: "SignatureDoesNotMatch",
+ $fault: "client",
+ $metadata: {
+ httpStatusCode: 403,
+ requestId: "req-123",
+ extendedRequestId: "ext-456",
+ },
+ },
+ );
+
+ expect(summarizeS3Error(err)).toEqual({
+ name: "SignatureDoesNotMatch",
+ code: "SignatureDoesNotMatch",
+ fault: "client",
+ httpStatusCode: 403,
+ requestId: "req-123",
+ extendedRequestId: "ext-456",
+ message: "The request signature we calculated",
+ });
+ });
+
+ it("never throws on non-object errors", () => {
+ expect(summarizeS3Error("boom")).toEqual({ message: "boom" });
+ expect(summarizeS3Error(undefined)).toEqual({ message: "undefined" });
+ });
+});
+
+describe("buildS3RequestDiagnostics", () => {
+ const context = {
+ bucketName: "ct-langfuse-test",
+ endpoint: "https://storage.googleapis.com",
+ region: "europe-west1",
+ forcePathStyle: true,
+ };
+
+ it("combines signing context, request framing, and error", () => {
+ const request = {
+ method: "PUT",
+ hostname: "storage.googleapis.com",
+ path: "/ct-langfuse-test/org-123/user-456/secret-key.txt",
+ headers: {
+ "content-encoding": "aws-chunked",
+ "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
+ "x-amz-trailer": "x-amz-checksum-crc32",
+ // Authorization must never be surfaced.
+ authorization: "AWS4-HMAC-SHA256 Credential=GOOG.../...",
+ },
+ };
+
+ const diagnostics = buildS3RequestDiagnostics(
+ request,
+ Object.assign(new Error("mismatch"), { name: "SignatureDoesNotMatch" }),
+ context,
+ );
+
+ expect(diagnostics.region).toBe("europe-west1");
+ expect(diagnostics.forcePathStyle).toBe(true);
+ expect(diagnostics.request.method).toBe("PUT");
+ expect(diagnostics.request.hostname).toBe("storage.googleapis.com");
+ expect(diagnostics.request.usesAwsChunkedEncoding).toBe(true);
+ expect(diagnostics.request.hasChecksumTrailer).toBe(true);
+ expect(diagnostics.error.name).toBe("SignatureDoesNotMatch");
+
+ const serialized = JSON.stringify(diagnostics);
+ // Never surface credentials or the object key (may embed tenant/user ids).
+ expect(serialized).not.toContain("AWS4-HMAC-SHA256");
+ expect(serialized).not.toContain("org-123");
+ expect(serialized).not.toContain("user-456");
+ expect(serialized).not.toContain("secret-key.txt");
+ });
+
+ it("tolerates a non-HttpRequest value without throwing", () => {
+ const diagnostics = buildS3RequestDiagnostics(undefined, "boom", context);
+ expect(diagnostics.request.method).toBeUndefined();
+ expect(diagnostics.request.contentSha256Mode).toBe("absent");
+ expect(diagnostics.error.message).toBe("boom");
+ });
+});
+
+describe("isS3SigningError", () => {
+ it("matches signing/authorization error codes by name or Code", () => {
+ for (const code of [
+ "SignatureDoesNotMatch",
+ "InvalidSignatureException",
+ "AuthorizationQueryParametersError",
+ "AuthorizationHeaderMalformed",
+ "RequestTimeTooSkewed",
+ ]) {
+ expect(isS3SigningError({ name: code })).toBe(true);
+ expect(isS3SigningError({ code })).toBe(true);
+ }
+ });
+
+ it("does not match unrelated S3 errors (so they are not logged)", () => {
+ expect(isS3SigningError({ name: "NoSuchKey", code: "NoSuchKey" })).toBe(
+ false,
+ );
+ expect(
+ isS3SigningError({ name: "AccessDenied", code: "AccessDenied" }),
+ ).toBe(false);
+ expect(isS3SigningError({ name: "SlowDown", code: "SlowDown" })).toBe(
+ false,
+ );
+ expect(isS3SigningError({})).toBe(false);
+ });
+});
diff --git a/packages/shared/src/server/services/s3SigningDiagnostics.ts b/packages/shared/src/server/services/s3SigningDiagnostics.ts
new file mode 100644
index 0000000000..5ad099e488
--- /dev/null
+++ b/packages/shared/src/server/services/s3SigningDiagnostics.ts
@@ -0,0 +1,197 @@
+/**
+ * Pure helpers for diagnosing S3 SigV4 `SignatureDoesNotMatch` failures, with a
+ * focus on Google Cloud Storage and other non-AWS S3-compatible backends.
+ *
+ * Recent AWS SDK versions enable data-integrity checksums and `aws-chunked`
+ * trailer-based upload framing by default. GCS's S3 interop layer does not
+ * verify that framing the way AWS does, so the canonical request it
+ * reconstructs differs from what the SDK signed and it returns
+ * `SignatureDoesNotMatch` (or `412`). This is invisible from the error message
+ * alone: a raw `curl --aws-sigv4` PUT sends a plain single-chunk signed
+ * payload and succeeds, while the SDK request silently fails on the same
+ * credentials.
+ *
+ * These helpers summarize the *signing inputs* of the request that failed so
+ * the difference shows up in logs. They never read credentials (no
+ * `Authorization` header), the secret, or the payload — only the framing
+ * headers and the structured error fields.
+ */
+
+export interface S3SigningDiagnosticsContext {
+ bucketName: string;
+ endpoint?: string;
+ region?: string;
+ forcePathStyle: boolean;
+}
+
+/**
+ * Classify the `x-amz-content-sha256` header into a *mode* without exposing the
+ * actual content hash. The mode is what matters for signature debugging:
+ * a 64-char hex value is a single-chunk signed payload (what a plain PUT or
+ * `curl --aws-sigv4` sends), whereas `STREAMING-*` / `UNSIGNED-PAYLOAD`
+ * indicate chunked or trailer-based framing that GCS rejects.
+ */
+export function classifyContentSha256Mode(value: string | undefined): string {
+ if (!value) return "absent";
+ if (value.startsWith("STREAMING-")) return value;
+ if (value === "UNSIGNED-PAYLOAD") return "UNSIGNED-PAYLOAD";
+ if (/^[0-9a-f]{64}$/i.test(value)) return "single-chunk-sha256";
+ return "other";
+}
+
+function lowercaseHeaderKeys(
+ headers: Record<string, string>,
+): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(headers)) {
+ out[key.toLowerCase()] = value;
+ }
+ return out;
+}
+
+export interface S3SigningHeaderSummary {
+ contentEncoding?: string;
+ contentSha256Mode: string;
+ usesAwsChunkedEncoding: boolean;
+ hasChecksumTrailer: boolean;
+ checksumHeaders: string[];
+}
+
+/**
+ * Summarize the framing headers that determine whether GCS can verify the
+ * SigV4 signature. The presence of `aws-chunked` encoding, an `x-amz-trailer`,
+ * or `x-amz-checksum-*` / `x-amz-sdk-checksum-*` headers is the smoking gun for
+ * a checksum/streaming mismatch.
+ */
+export function summarizeS3SigningHeaders(
+ headers: Record<string, string> | undefined,
+): S3SigningHeaderSummary {
+ const lower = lowercaseHeaderKeys(headers ?? {});
+ const contentEncoding = lower["content-encoding"];
+ return {
+ contentEncoding,
+ contentSha256Mode: classifyContentSha256Mode(lower["x-amz-content-sha256"]),
+ usesAwsChunkedEncoding: (contentEncoding ?? "")
+ .toLowerCase()
+ .includes("aws-chunked"),
+ hasChecksumTrailer: "x-amz-trailer" in lower,
+ checksumHeaders: Object.keys(lower)
+ .filter(
+ (key) =>
+ key.startsWith("x-amz-checksum-") ||
+ key.startsWith("x-amz-sdk-checksum-"),
+ )
+ .sort(),
+ };
+}
+
+export interface S3ErrorSummary {
+ name?: string;
+ code?: string;
+ fault?: string;
+ httpStatusCode?: number;
+ requestId?: string;
+ extendedRequestId?: string;
+ message?: string;
+}
+
+/**
+ * Extract the structured fields an AWS SDK `ServiceException` carries beyond
+ * its message string (`Code`, `$fault`, and the `$metadata` request IDs that
+ * let support correlate the failure with the storage provider's own logs).
+ */
+export function summarizeS3Error(err: unknown): S3ErrorSummary {
+ if (!err || typeof err !== "object") {
+ return { message: String(err) };
+ }
+ const e = err as {
+ name?: string;
+ message?: string;
+ Code?: string;
+ $fault?: string;
+ $metadata?: {
+ httpStatusCode?: number;
+ requestId?: string;
+ extendedRequestId?: string;
+ };
+ };
+ return {
+ name: e.name,
+ code: e.Code,
+ fault: e.$fault,
+ httpStatusCode: e.$metadata?.httpStatusCode,
+ requestId: e.$metadata?.requestId,
+ extendedRequestId: e.$metadata?.extendedRequestId,
+ message: e.message,
+ };
+}
+
+/**
+ * Error `name`/`Code` values that indicate a signing or request-authorization
+ * canonicalization failure — the class of error this diagnostics module exists
+ * to debug. Used to gate logging so unrelated failures (`NoSuchKey`,
+ * `AccessDenied`, `SlowDown`, network timeouts) don't emit a signing-themed
+ * `warn`. These are also non-retryable client (4xx) errors, so gating on them
+ * avoids one log line per SDK retry attempt.
+ */
+const S3_SIGNING_ERROR_CODES = new Set<string>([
+ "SignatureDoesNotMatch",
+ "InvalidSignatureException",
+ "AuthorizationQueryParametersError",
+ "AuthorizationHeaderMalformed", // region mismatch in the credential scope
+ "RequestTimeTooSkewed", // clock skew, breaks the computed signature
+]);
+
+/**
+ * Whether a summarized error is a signing/authorization failure worth a
+ * signing-themed diagnostic log, as opposed to an unrelated S3 error.
+ */
+export function isS3SigningError(error: S3ErrorSummary): boolean {
+ return (
+ (error.name !== undefined && S3_SIGNING_ERROR_CODES.has(error.name)) ||
+ (error.code !== undefined && S3_SIGNING_ERROR_CODES.has(error.code))
+ );
+}
+
+interface MaybeHttpRequest {
+ method?: string;
+ hostname?: string;
+ headers?: Record<string, string>;
+}
+
+export interface S3RequestDiagnostics extends S3SigningDiagnosticsContext {
+ request: {
+ method?: string;
+ hostname?: string;
+ } & S3SigningHeaderSummary;
+ error: S3ErrorSummary;
+}
+
+/**
+ * Build the structured payload logged when an S3 request fails. Combines the
+ * configured signing context (region, endpoint, path-style) with the framing
+ * headers of the request that was actually sent and the structured error,
+ * tolerating any non-`HttpRequest` shape without throwing.
+ *
+ * Deliberately omits the request `path` (the S3 object key, which can embed
+ * tenant/user identifiers) and the query string (which can carry presigned-URL
+ * credentials). `hostname` is kept because it reveals path- vs virtual-hosted
+ * addressing without exposing the key.
+ */
+export function buildS3RequestDiagnostics(
+ request: unknown,
+ err: unknown,
+ context: S3SigningDiagnosticsContext,
+): S3RequestDiagnostics {
+ const req: MaybeHttpRequest =
+ request && typeof request === "object" ? (request as MaybeHttpRequest) : {};
+ return {
+ ...context,
+ request: {
+ method: req.method,
+ hostname: req.hostname,
+ ...summarizeS3SigningHeaders(req.headers),
+ },
+ error: summarizeS3Error(err),
+ };
+}