🪢 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
fix(blob-storage): normalize storage regions (#16911)
Max Deichmann734325b7cca1
diff --git a/fern/apis/server/definition/blob-storage-integrations.yml b/fern/apis/server/definition/blob-storage-integrations.ymlindex b4915aa822..d1d0a58033 100644--- a/fern/apis/server/definition/blob-storage-integrations.yml+++ b/fern/apis/server/definition/blob-storage-integrations.yml@@ -115,7 +115,7 @@ types:docs: Custom endpoint URL (required for S3_COMPATIBLE type)region:type: string- docs: Storage region+ docs: "Storage region used by S3-compatible clients (AWS, GCS, Cloudflare R2, MinIO, Azure location IDs such as eastus, OCI). Leading and trailing whitespace is removed. The remaining value must be 1-63 letters, numbers, or hyphens, and cannot start or end with a hyphen. Examples: us-east-1, europe-west1, eastus, auto."accessKeyId:type: optional<string>docs: Access key ID for authenticationdiff --git a/packages/shared/src/server/services/StorageService.test.ts b/packages/shared/src/server/services/StorageService.test.tsindex 7c4fe79ae8..a1b8a313db 100644--- a/packages/shared/src/server/services/StorageService.test.ts+++ b/packages/shared/src/server/services/StorageService.test.ts@@ -5,10 +5,72 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { S3Client } from "@aws-sdk/client-s3";+import { BLOB_STORAGE_REGION_INVALID_MESSAGE } from "../../utils/stringChecks";import { env } from "../../env";import { resolveMediaStorageEndpoints } from "../s3";import { StorageServiceFactory } from "./StorageService";+describe("S3StorageService region normalization", () => {+ it("trims a persisted region before configuring the AWS client", async () => {+ const service = StorageServiceFactory.getInstance({+ accessKeyId: "test-access-key",+ secretAccessKey: "test-secret-key",+ bucketName: "test-bucket",+ endpoint: undefined,+ region: " us-west-2",+ forcePathStyle: false,+ useAzureBlob: false,+ useGoogleCloudStorage: false,+ useOCIObjectStorage: false,+ awsSse: undefined,+ awsSseKmsKeyId: undefined,+ });+ const client = (service as unknown as { client: S3Client }).client;++ await expect(client.config.region()).resolves.toBe("us-west-2");+ });++ it("rejects malformed persisted regions before creating an AWS client", () => {+ expect(() =>+ StorageServiceFactory.getInstance({+ accessKeyId: "test-access-key",+ secretAccessKey: "test-secret-key",+ bucketName: "test-bucket",+ endpoint: undefined,+ region: "us west-2",+ forcePathStyle: false,+ useAzureBlob: false,+ useGoogleCloudStorage: false,+ useOCIObjectStorage: false,+ awsSse: undefined,+ awsSseKmsKeyId: undefined,+ }),+ ).toThrow(BLOB_STORAGE_REGION_INVALID_MESSAGE);+ });++ it.each(["europe-west1", "eastus", "auto"])(+ "configures an S3-compatible client with region %s",+ async (region) => {+ const service = StorageServiceFactory.getInstance({+ accessKeyId: "test-access-key",+ secretAccessKey: "test-secret-key",+ bucketName: "test-bucket",+ endpoint: "https://storage.googleapis.com",+ region,+ forcePathStyle: true,+ useAzureBlob: false,+ useGoogleCloudStorage: false,+ useOCIObjectStorage: false,+ awsSse: undefined,+ awsSseKmsKeyId: undefined,+ });+ const client = (service as unknown as { client: S3Client }).client;++ await expect(client.config.region()).resolves.toBe(region);+ },+ );+});+describe("resolveMediaStorageEndpoints", () => {it("keeps the existing endpoint for both server access and signed URLs by default", () => {expect(diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.tsindex 57296a1af9..f878e5a822 100644--- a/packages/shared/src/server/services/StorageService.ts+++ b/packages/shared/src/server/services/StorageService.ts@@ -21,6 +21,7 @@ import {import { Storage, Bucket, GetSignedUrlConfig } from "@google-cloud/storage";import { logger } from "../logger";import { env } from "../../env";+import { normalizeBlobStorageRegion } from "../../utils/stringChecks";import { backOff } from "exponential-backoff";import { ServiceUnavailableError } from "../../errors";import {@@ -763,12 +764,16 @@ class S3StorageService implements StorageService {: undefined;const requestHandler = createS3RequestHandler(params.connectionValidation);+ const region =+ params.region === undefined+ ? undefined+ : normalizeBlobStorageRegion(params.region);// Create the main client for S3 operations using the internal endpointthis.client = new S3Client({credentials,endpoint: params.endpoint,- region: params.region,+ region,forcePathStyle: params.forcePathStyle,// Restore pre-v3.729 default so CompleteMultipartUpload doesn't send a// composite CRC32 header, which GCS's S3-compat layer rejects with 412.@@ -780,7 +785,7 @@ class S3StorageService implements StorageService {addS3DiagnosticsMiddleware(this.client, {bucketName: params.bucketName,endpoint: params.endpoint,- region: params.region,+ region,forcePathStyle: params.forcePathStyle,});@@ -791,7 +796,7 @@ class S3StorageService implements StorageService {? new S3Client({credentials,endpoint: params.externalEndpoint,- region: params.region,+ region,forcePathStyle: params.forcePathStyle,requestChecksumCalculation: "WHEN_REQUIRED",responseChecksumValidation: "WHEN_REQUIRED",diff --git a/packages/shared/src/utils/stringChecks.test.ts b/packages/shared/src/utils/stringChecks.test.tsindex 36dd1b4cf5..a274a42a74 100644--- a/packages/shared/src/utils/stringChecks.test.ts+++ b/packages/shared/src/utils/stringChecks.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";-import { truncate } from "./stringChecks";+import {+ BLOB_STORAGE_REGION_INVALID_MESSAGE,+ normalizeBlobStorageRegion,+ truncate,+} from "./stringChecks";function hasLoneSurrogate(s: string): boolean {for (let i = 0; i < s.length; i++) {@@ -16,6 +20,38 @@ function hasLoneSurrogate(s: string): boolean {return false;}+describe("normalizeBlobStorageRegion", () => {+ it.each([+ ["us-west-2", "AWS"],+ ["europe-west1", "GCP"],+ ["us-central1", "GCP"],+ ["US", "GCS multi-region"],+ ["eastus", "Azure"],+ ["westeurope", "Azure"],+ ["germanywestcentral", "Azure"],+ ["auto", "GCS/R2 signing region"],+ ["wnam", "Cloudflare R2"],+ ["us-ashburn-1", "OCI"],+ ["us-west-004", "Backblaze"],+ ])("accepts %s (%s)", (region) => {+ expect(normalizeBlobStorageRegion(` ${region} `)).toBe(region);+ });++ it.each([+ "us west-2",+ "East US",+ "US-CENTRAL1+US-EAST1",+ "us_west_2",+ "-us-west-2",+ "us-west-2-",+ "a".repeat(64),+ ])("rejects %s", (region) => {+ expect(() => normalizeBlobStorageRegion(region)).toThrow(+ BLOB_STORAGE_REGION_INVALID_MESSAGE,+ );+ });+});+describe("truncate", () => {it("returns the string unchanged when at or under the limit", () => {expect(truncate("hello", 16)).toBe("hello");diff --git a/packages/shared/src/utils/stringChecks.ts b/packages/shared/src/utils/stringChecks.tsindex 6bea5411e2..69730e3686 100644--- a/packages/shared/src/utils/stringChecks.ts+++ b/packages/shared/src/utils/stringChecks.ts@@ -17,6 +17,23 @@ export const MULTILINE_VARIABLE_REGEX = /{{[^{}\n]*\n[^{}]*}}/g;// Regex to find unclosed variablesexport const UNCLOSED_VARIABLE_REGEX = /{{(?!{)(?![^{]*}})/g;+// Smithy host-label check used by S3-compatible clients. AWS, GCS XML/S3,+// Cloudflare R2, MinIO, Azure location IDs (eastus), and OCI region ids all+// fit this pattern. Spaces, underscores, and GCP dual-region `+` syntax are+// rejected because they throw inside the AWS SDK and can terminate the process.+export const BLOB_STORAGE_REGION_REGEX = /^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$/;++export const BLOB_STORAGE_REGION_INVALID_MESSAGE =+ "Region must be 1-63 letters, numbers, or hyphens, and cannot start or end with a hyphen";++export function normalizeBlobStorageRegion(region: string): string {+ const normalizedRegion = region.trim();+ if (!BLOB_STORAGE_REGION_REGEX.test(normalizedRegion)) {+ throw new Error(BLOB_STORAGE_REGION_INVALID_MESSAGE);+ }+ return normalizedRegion;+}+export function isValidVariableName(variable: string): boolean {return VARIABLE_REGEX.test(variable);}diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex a4534889ff..d5d76263f5 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -9774,7 +9774,12 @@ components:description: Custom endpoint URL (required for S3_COMPATIBLE type)region:type: string- description: Storage region+ description: >-+ Storage region used by S3-compatible clients (AWS, GCS, Cloudflare+ R2, MinIO, Azure location IDs such as eastus, OCI). Leading and+ trailing whitespace is removed. The remaining value must be 1-63+ letters, numbers, or hyphens, and cannot start or end with a hyphen.+ Examples: us-east-1, europe-west1, eastus, auto.accessKeyId:type: stringnullable: truediff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.tsindex a471d24f7b..96e638648d 100644--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts@@ -258,6 +258,24 @@ describe("Blob Storage Integration tRPC Router", () => {vi.clearAllMocks();});+ describe("region normalization", () => {+ it("persists a trimmed region", async () => {+ const { caller, project } = await prepare();++ await caller.blobStorageIntegration.update({+ projectId: project.id,+ ...baseConfig,+ region: " us-west-2",+ });++ const integration = await prisma.blobStorageIntegration.findUnique({+ where: { projectId: project.id },+ select: { region: true },+ });+ expect(integration?.region).toBe("us-west-2");+ });+ });+describe("runNow", () => {it("creates a success audit log when a manual run is queued", async () => {const add = vi.fn().mockResolvedValue(undefined);diff --git a/web/src/features/blobstorage-integration/components/StorageProviderFields.tsx b/web/src/features/blobstorage-integration/components/StorageProviderFields.tsxindex d28443df31..60e14bf03b 100644--- a/web/src/features/blobstorage-integration/components/StorageProviderFields.tsx+++ b/web/src/features/blobstorage-integration/components/StorageProviderFields.tsx@@ -126,7 +126,7 @@ export const StorageProviderFields = ({<FormDescription>{integrationType === "S3"? "AWS region (e.g., us-east-1)"- : "S3 compatible storage region"}+ : "S3 compatible storage region (e.g. europe-west1, auto)"}</FormDescription><FormMessage /></FormItem>diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex 2d33f07d6f..033cf6fe71 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -6,6 +6,8 @@ import {type AnalyticsIntegrationExportSource,BlobStorageIntegrationFileType,type ObservationFieldGroupFull,+ BLOB_STORAGE_REGION_INVALID_MESSAGE,+ normalizeBlobStorageRegion,} from "@langfuse/shared";import { assertPersistedExportSourceAllowed } from "@/src/features/analytics-integrations/server/exportSource";import { encrypt } from "@langfuse/shared/encryption";@@ -70,6 +72,12 @@ export async function upsertBlobStorageIntegration(params: {const accessKeyId = data.accessKeyId?.trim() || null;const secretAccessKey = data.secretAccessKey?.trim() || null;+ let region: string;+ try {+ region = normalizeBlobStorageRegion(data.region);+ } catch {+ throw new InvalidRequestError(BLOB_STORAGE_REGION_INVALID_MESSAGE);+ }if (data.endpoint) {try {@@ -96,7 +104,7 @@ export async function upsertBlobStorageIntegration(params: {type: data.type,bucketName: data.bucketName,endpoint: data.endpoint,- region: data.region,+ region,accessKeyId,prefix: data.prefix,exportFrequency: data.exportFrequency,diff --git a/web/src/features/blobstorage-integration/types.ts b/web/src/features/blobstorage-integration/types.tsindex 2d94338bb2..fa1effa141 100644--- a/web/src/features/blobstorage-integration/types.ts+++ b/web/src/features/blobstorage-integration/types.ts@@ -5,6 +5,8 @@ import {BlobStorageExportMode,AnalyticsIntegrationExportSource,OBSERVATION_FIELD_GROUPS_FULL,+ BLOB_STORAGE_REGION_INVALID_MESSAGE,+ BLOB_STORAGE_REGION_REGEX,} from "@langfuse/shared";import {validateAzureContainerName,@@ -17,7 +19,14 @@ export const blobStorageIntegrationFormSchemaBase = z.object({type: z.enum(BlobStorageIntegrationType),bucketName: z.string().min(1, { message: "Bucket name is required" }),endpoint: z.url().optional().nullable(),- region: z.string().default("auto"),+ region: z+ .string()+ .trim()+ .min(1, { message: "Region is required" })+ .regex(BLOB_STORAGE_REGION_REGEX, {+ message: BLOB_STORAGE_REGION_INVALID_MESSAGE,+ })+ .default("auto"),accessKeyId: z.string().optional(),secretAccessKey: z.string().nullable().optional(),prefix: zdiff --git a/web/src/features/blobstorage-integration/validation.clienttest.ts b/web/src/features/blobstorage-integration/validation.clienttest.tsindex 93621a371a..f5789c3958 100644--- a/web/src/features/blobstorage-integration/validation.clienttest.ts+++ b/web/src/features/blobstorage-integration/validation.clienttest.ts@@ -4,8 +4,54 @@ import {AZURE_CONTAINER_NAME_REGEX,validateAzureContainerName,} from "./validation";+import { blobStorageIntegrationFormSchemaBase } from "./types";+import { CreateBlobStorageIntegrationRequest } from "@/src/features/public-api/types/blob-storage-integrations";import { z } from "zod";+describe("blob storage region normalization", () => {+ it("trims regions submitted through the settings form", () => {+ expect(+ blobStorageIntegrationFormSchemaBase.shape.region.parse(" us-west-2"),+ ).toBe("us-west-2");+ });++ it("trims regions submitted through the public API", () => {+ expect(+ CreateBlobStorageIntegrationRequest.shape.region.parse(" us-west-2"),+ ).toBe("us-west-2");+ });++ it.each(["europe-west1", "eastus", "auto", "US", "wnam"])(+ "accepts S3-compatible provider region %s",+ (region) => {+ expect(+ blobStorageIntegrationFormSchemaBase.shape.region.parse(region),+ ).toBe(region);+ expect(+ CreateBlobStorageIntegrationRequest.shape.region.parse(region),+ ).toBe(region);+ },+ );++ it.each([+ "us west-2",+ "East US",+ "US-CENTRAL1+US-EAST1",+ "-us-west-2",+ "us-west-2-",+ "a".repeat(64),+ ])("rejects a region the S3 client cannot use: %s", (region) => {+ expect(+ blobStorageIntegrationFormSchemaBase.shape.region.safeParse(region)+ .success,+ ).toBe(false);+ expect(+ CreateBlobStorageIntegrationRequest.shape.region.safeParse(region)+ .success,+ ).toBe(false);+ });+});+describe("AZURE_CONTAINER_NAME_REGEX", () => {const valid = ["abc",diff --git a/web/src/features/public-api/types/blob-storage-integrations.ts b/web/src/features/public-api/types/blob-storage-integrations.tsindex 3dccb10eff..52e0ee4126 100644--- a/web/src/features/public-api/types/blob-storage-integrations.ts+++ b/web/src/features/public-api/types/blob-storage-integrations.ts@@ -2,6 +2,8 @@ import { z } from "zod";import {AnalyticsIntegrationExportSource,OBSERVATION_FIELD_GROUPS_FULL,+ BLOB_STORAGE_REGION_INVALID_MESSAGE,+ BLOB_STORAGE_REGION_REGEX,} from "@langfuse/shared";import {validateAzureContainerName,@@ -99,7 +101,9 @@ export const CreateBlobStorageIntegrationRequest = ztype: BlobStorageIntegrationType,bucketName: z.string().min(1),endpoint: z.string().nullable().optional(),- region: z.string(),+ region: z.string().trim().min(1).regex(BLOB_STORAGE_REGION_REGEX, {+ message: BLOB_STORAGE_REGION_INVALID_MESSAGE,+ }),accessKeyId: z.string().nullable().optional(),secretAccessKey: z.string().nullable().optional(),prefix: zdiff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 04db1da74a..cb9c07bfa4 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -66,6 +66,7 @@ import { BLOB_INTEGRATION_DISABLED_METRIC } from "../features/blobstorage/isCustimport {BlobStorageIntegrationType,BlobStorageIntegrationFileType,+ BLOB_STORAGE_REGION_INVALID_MESSAGE,LEGACY_BLOB_EXPORTER_CUTOFF,} from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";@@ -239,6 +240,51 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ describe("invalid persisted region", () => {+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ afterEach(() => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("persists the error before any S3 upload starts", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ const { projectId } = await createOrgProjectAndApiKey();++ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: projectId,+ accessKeyId,+ secretAccessKey: encrypt(secretAccessKey),+ region: "us west-2",+ endpoint: endpoint ?? null,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: "daily",+ exportSource: "EVENTS",+ lastSyncAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),+ },+ });++ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job),+ ).rejects.toThrow(BLOB_STORAGE_REGION_INVALID_MESSAGE);++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(row.lastError).toBe(BLOB_STORAGE_REGION_INVALID_MESSAGE);+ expect(row.lastErrorAt).not.toBeNull();+ expect(row.enabled).toBe(true);+ });+ });+// A classified customer fault disables the integration on its first// occurrence and resolves the job; everything else keeps retrying as before.describe("customer-fault disable", () => {