🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(blob-storage): slim S3 diagnostics to generic error context (#14479)
Niklas Semmler310f13caa088
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.tsindex ab3857eaf8..7c541d3a5b 100644--- a/packages/shared/src/server/services/StorageService.ts+++ b/packages/shared/src/server/services/StorageService.ts@@ -30,9 +30,7 @@ import {import { S3ChunkedUploadStrategy } from "./S3ChunkedUploadStrategy";import {buildS3RequestDiagnostics,- isS3SigningError,- summarizeCredentialShape,- type S3SigningDiagnosticsContext,+ type S3DiagnosticsContext,} from "./s3SigningDiagnostics";import * as objectstorage from "oci-objectstorage";import * as common from "oci-common";@@ -132,22 +130,15 @@ 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`).+ * structured error and request context when any S3 request fails.*- * 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.+ * Runs at the `deserialize` step so the SDK has already turned an error+ * response into a typed exception with request IDs and status code.+ * Best-effort: never alters or masks the original failure.*/-function addS3SigningDiagnosticsMiddleware(+function addS3DiagnosticsMiddleware(client: S3Client,- context: S3SigningDiagnosticsContext,+ context: S3DiagnosticsContext,): void {type S3MiddlewareArgs = { request?: unknown };type S3MiddlewareNext = (args: S3MiddlewareArgs) => Promise<unknown>;@@ -163,12 +154,7 @@ function addS3SigningDiagnosticsMiddleware(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,- );- }+ logger.warn("S3 request failed; emitting diagnostics", diagnostics);} catch {// Never let diagnostics logging mask the original failure.}@@ -177,16 +163,13 @@ function addS3SigningDiagnosticsMiddleware(};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",+ name: "langfuseS3Diagnostics",tags: ["LANGFUSE", "DIAGNOSTICS"],override: true,},@@ -701,26 +684,11 @@ 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, {+ addS3DiagnosticsMiddleware(this.client, {bucketName: params.bucketName,endpoint: params.endpoint,region: params.region,forcePathStyle: params.forcePathStyle,- // Non-reversible shape of the credentials (length + character-class- // flags, never the value) so a SignatureDoesNotMatch can be triaged as a- // truncated/altered/mismatched secret without another round of re-pasting.- // Derived from the same AND-gated `credentials` the S3Client received, not- // raw params: when only one of id/secret is set, the SDK falls back to the- // default credential chain, and the shape must report `absent` to match —- // otherwise a partial config logs a phantom empty-secret for creds the SDK- // never used.- credentials: summarizeCredentialShape(- credentials?.accessKeyId,- credentials?.secretAccessKey,- ),});// Create a separate client for generating presigned URLsdiff --git a/packages/shared/src/server/services/s3SigningDiagnostics.test.ts b/packages/shared/src/server/services/s3SigningDiagnostics.test.tsindex b6a2c39e3c..98d08cf569 100644--- a/packages/shared/src/server/services/s3SigningDiagnostics.test.ts+++ b/packages/shared/src/server/services/s3SigningDiagnostics.test.ts@@ -1,85 +1,9 @@import { describe, expect, it } from "vitest";import {buildS3RequestDiagnostics,- classifyContentSha256Mode,- isS3SigningError,- summarizeCredentialShape,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(@@ -121,16 +45,12 @@ describe("buildS3RequestDiagnostics", () => {forcePathStyle: true,};- it("combines signing context, request framing, and error", () => {+ it("combines context, request, 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.../...",},};@@ -145,12 +65,9 @@ describe("buildS3RequestDiagnostics", () => {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");@@ -160,128 +77,6 @@ describe("buildS3RequestDiagnostics", () => {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("summarizeCredentialShape", () => {- // A representative GCS HMAC secret: 40 chars, base64 alphabet, no whitespace.- const cleanGcsSecret = "Ab3+/Cd4ef5GH6ij7KL8mn9OP0qr1ST2uv3WX4yz";-- it("reports a clean GCS HMAC credential pair", () => {- const shape = summarizeCredentialShape(- "GOOG1EXAMPLEACCESSKEYID",- cleanGcsSecret,- );-- expect(shape).toEqual({- accessKeyIdPresent: true,- accessKeyIdLength: 23,- accessKeyIdType: "gcs-hmac",- secretPresent: true,- secretLength: 40,- secretLooksBase64: true,- secretHasWhitespace: false,- secretHasSurroundingWhitespace: false,- secretHasNonAscii: false,- });- });-- it("flags a truncated secret (wrong length, the SignatureDoesNotMatch tell)", () => {- const shape = summarizeCredentialShape(- "GOOG1EXAMPLE",- cleanGcsSecret.slice(0, 20),- );- expect(shape.secretLength).toBe(20);- expect(shape.secretPresent).toBe(true);- });-- it("flags stray surrounding whitespace from a sloppy paste", () => {- const shape = summarizeCredentialShape(- "GOOG1EXAMPLE",- ` ${cleanGcsSecret}\n`,- );- expect(shape.secretHasWhitespace).toBe(true);- expect(shape.secretHasSurroundingWhitespace).toBe(true);- });-- it("flags a trailing non-breaking space across every relevant signal", () => {- // U+00A0 (NBSP) is a Unicode space separator: ECMAScript WhiteSpace- // includes it, so `\s` matches it and `trim()` strips it. A trailing NBSP- // therefore lights up all three signals — assert each so none regresses.- const nbsp = String.fromCharCode(0x00a0);- const shape = summarizeCredentialShape(- "GOOG1EXAMPLE",- `${cleanGcsSecret}${nbsp}`,- );- expect(shape.secretHasWhitespace).toBe(true);- expect(shape.secretHasSurroundingWhitespace).toBe(true);- expect(shape.secretHasNonAscii).toBe(true);- expect(shape.secretLooksBase64).toBe(false);- });-- it("flags a non-ascii character that the whitespace checks miss", () => {- // The reason secretHasNonAscii exists separately: a non-whitespace unicode- // char (here a “smart” double quote, U+201C) is neither matched by `\s`- // nor stripped by `trim()`, so only secretHasNonAscii catches it.- const smartQuote = String.fromCharCode(0x201c);- const shape = summarizeCredentialShape(- "GOOG1EXAMPLE",- `${smartQuote}${cleanGcsSecret}`,- );- expect(shape.secretHasNonAscii).toBe(true);- expect(shape.secretHasWhitespace).toBe(false);- expect(shape.secretHasSurroundingWhitespace).toBe(false);- expect(shape.secretLooksBase64).toBe(false);- });-- it("classifies an AWS-style access key id (wrong-provider paste)", () => {- const shape = summarizeCredentialShape(- "AKIAIOSFODNN7EXAMPLE",- cleanGcsSecret,- );- expect(shape.accessKeyIdType).toBe("aws");- });-- it("handles absent credentials (host/instance-role) without throwing", () => {- const shape = summarizeCredentialShape(undefined, undefined);- expect(shape.accessKeyIdPresent).toBe(false);- expect(shape.accessKeyIdType).toBe("absent");- expect(shape.secretPresent).toBe(false);- expect(shape.secretLength).toBe(0);- });-- it("never embeds the secret value", () => {- const shape = summarizeCredentialShape("GOOG1EXAMPLE", cleanGcsSecret);- expect(JSON.stringify(shape)).not.toContain(cleanGcsSecret);- });-});--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.tsindex 213f01789e..485e480cc2 100644--- a/packages/shared/src/server/services/s3SigningDiagnostics.ts+++ b/packages/shared/src/server/services/s3SigningDiagnostics.ts@@ -1,159 +1,15 @@/**- * 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 log the credential values (no- * `Authorization` header, no secret) or the payload — only the framing- * headers, the structured error fields, and a non-reversible *shape* of the- * credentials (length + character-class flags; see {@link S3CredentialShape}).- */--/**- * Non-reversible *shape* of the configured S3 credentials. Surfaced so a- * `SignatureDoesNotMatch` can be triaged when the operator insists the- * key/secret are correct and re-pasting them has not helped.- *- * `SignatureDoesNotMatch` (vs `InvalidAccessKeyId`/`AccessDenied`) means the- * backend matched the access key id but the HMAC computed from the secret did- * not — i.e. the stored secret is not the partner of the stored access key.- * The usual culprits are a truncated or altered paste (wrong length, stray- * whitespace, or a stray non-ascii character such as a "smart" quote or- * zero-width space that survives `trim()`) or a secret from a different/rotated- * key pair. These fields expose exactly those signals without ever logging the- * credential value: only the length, whether it matches the base64 alphabet,- * and whitespace/non-ascii flags. (Note: a non-breaking space is a Unicode- * space separator, so it is caught by both the whitespace flags and- * `secretHasNonAscii`; `secretHasNonAscii` earns its keep on non-whitespace- * characters the others miss.)- *- * The access key id is an identifier (sent in plaintext in every signed- * request's `Authorization` header), not a secret; even so we never log it- * verbatim — we classify it (`gcs-hmac` for `GOOG…`, `aws` for `AKIA`/`ASIA`)- * so a key pasted into the wrong provider's field is obvious.- */-export interface S3CredentialShape {- accessKeyIdPresent: boolean;- accessKeyIdLength: number;- accessKeyIdType: "gcs-hmac" | "aws" | "other" | "absent";- secretPresent: boolean;- secretLength: number;- secretLooksBase64: boolean;- secretHasWhitespace: boolean;- secretHasSurroundingWhitespace: boolean;- secretHasNonAscii: boolean;-}--function classifyAccessKeyIdType(- id: string,-): Exclude<S3CredentialShape["accessKeyIdType"], "absent"> {- if (id.startsWith("GOOG")) return "gcs-hmac";- if (/^A(KIA|SIA)/.test(id)) return "aws";- return "other";-}--/**- * Summarize the credential pair without exposing either value. Null-safe so- * host/instance-role configs (no explicit credentials) report `absent` rather- * than throwing.+ * Lightweight S3 request-failure diagnostics. Logs the structured error fields+ * (requestId, httpStatusCode, error code) and basic request context on any+ * failed S3 request so operators can triage issues with any S3-compatible+ * backend without a second repro.*/-export function summarizeCredentialShape(- accessKeyId: string | undefined,- secretAccessKey: string | undefined,-): S3CredentialShape {- const id = accessKeyId ?? "";- const secret = secretAccessKey ?? "";- return {- accessKeyIdPresent: id.length > 0,- accessKeyIdLength: id.length,- accessKeyIdType: id.length === 0 ? "absent" : classifyAccessKeyIdType(id),- secretPresent: secret.length > 0,- secretLength: secret.length,- secretLooksBase64:- secret.length > 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(secret),- secretHasWhitespace: /\s/.test(secret),- secretHasSurroundingWhitespace: secret !== secret.trim(),- // Anything outside printable ASCII (0x20–0x7E): NBSP, smart quotes, etc.- secretHasNonAscii: /[^\x20-\x7e]/.test(secret),- };-}-export interface S3SigningDiagnosticsContext {+export interface S3DiagnosticsContext {bucketName: string;endpoint?: string;region?: string;forcePathStyle: boolean;- credentials?: S3CredentialShape;-}--/**- * 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 {@@ -197,62 +53,32 @@ export function summarizeS3Error(err: unknown): S3ErrorSummary {};}-/**- * 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 {+export interface S3RequestDiagnostics extends S3DiagnosticsContext {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.+ * configured context (region, endpoint, path-style) with the request method/+ * hostname and the structured error.** 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.+ * credentials).*/export function buildS3RequestDiagnostics(request: unknown,err: unknown,- context: S3SigningDiagnosticsContext,+ context: S3DiagnosticsContext,): S3RequestDiagnostics {const req: MaybeHttpRequest =request && typeof request === "object" ? (request as MaybeHttpRequest) : {};@@ -261,7 +87,6 @@ export function buildS3RequestDiagnostics(request: {method: req.method,hostname: req.hostname,- ...summarizeS3SigningHeaders(req.headers),},error: summarizeS3Error(err),};