🪢 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(security): encrypt blob storage secretAccessKey in public API (#11395)
Steffen Schmitzf45bc5ffe8fb
diff --git a/packages/shared/prisma/migrations/20260106120000_add_encrypt_blob_storage_secrets_background_migration/migration.sql b/packages/shared/prisma/migrations/20260106120000_add_encrypt_blob_storage_secrets_background_migration/migration.sqlnew file mode 100644index 0000000000..44ca370ef0--- /dev/null+++ b/packages/shared/prisma/migrations/20260106120000_add_encrypt_blob_storage_secrets_background_migration/migration.sql@@ -0,0 +1,2 @@+INSERT INTO background_migrations (id, name, script, args)+VALUES ('01a0c890-2094-8e2f-c773-cf4d14638fa4', '20260106_encrypt_blob_storage_secrets', 'encryptBlobStorageSecrets', '{}');diff --git a/web/src/__tests__/async/blob-storage-integration-api.servertest.ts b/web/src/__tests__/async/blob-storage-integration-api.servertest.tsindex 64d4d9a745..35a66045cd 100644--- a/web/src/__tests__/async/blob-storage-integration-api.servertest.ts+++ b/web/src/__tests__/async/blob-storage-integration-api.servertest.ts@@ -11,6 +11,7 @@ import {createAndAddApiKeysToDb,createBasicAuthHeader,} from "@langfuse/shared/src/server";+import { decrypt } from "@langfuse/shared/encryption";// Schemas based on Fern schema definitionconst BlobStorageIntegrationResponseSchema = z.object({@@ -464,6 +465,38 @@ describe("Blob Storage Integrations API", () => {expect(response.body.exportMode).toBe("FROM_CUSTOM_DATE");expect(response.body.exportStartDate).toBeDefined();});++ it("should store secretAccessKey encrypted in database", async () => {+ const testSecretKey = "my-super-secret-key-12345";+ const requestBody = {+ ...validBlobStorageConfig,+ projectId: testProject1Id,+ secretAccessKey: testSecretKey,+ };++ const response = await makeZodVerifiedAPICall(+ BlobStorageIntegrationResponseSchema,+ "PUT",+ "/api/public/integrations/blob-storage",+ requestBody,+ createBasicAuthHeader(testApiKey, testApiSecretKey),+ );++ expect(response.status).toBe(200);++ // Query database directly to check how secretAccessKey is stored+ const savedIntegration = await prisma.blobStorageIntegration.findUnique({+ where: { projectId: testProject1Id },+ });++ expect(savedIntegration).toBeDefined();++ // Verify secretAccessKey is NOT stored in plaintext+ expect(savedIntegration?.secretAccessKey).not.toBe(testSecretKey);++ // Verify the encrypted value can be decrypted back to the original+ expect(decrypt(savedIntegration!.secretAccessKey!)).toBe(testSecretKey);+ });});describe("DELETE /api/public/integrations/blob-storage/{id}", () => {diff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex 695d0cfc6d..59e70a27ad 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -13,6 +13,7 @@ import {UnauthorizedError,ForbiddenError,} from "@langfuse/shared";+import { encrypt } from "@langfuse/shared/encryption";export default withMiddlewares({GET: handleGetBlobStorageIntegrations,@@ -151,7 +152,9 @@ async function handleUpsertBlobStorageIntegration(endpoint: validatedData.endpoint || null,region: validatedData.region,accessKeyId: validatedData.accessKeyId || null,- secretAccessKey: validatedData.secretAccessKey || null,+ secretAccessKey: validatedData.secretAccessKey+ ? encrypt(validatedData.secretAccessKey)+ : null,prefix: validatedData.prefix,exportFrequency: validatedData.exportFrequency,enabled: validatedData.enabled,diff --git a/worker/src/backgroundMigrations/encryptBlobStorageSecrets.ts b/worker/src/backgroundMigrations/encryptBlobStorageSecrets.tsnew file mode 100644index 0000000000..d7ce4693ee--- /dev/null+++ b/worker/src/backgroundMigrations/encryptBlobStorageSecrets.ts@@ -0,0 +1,154 @@+import { IBackgroundMigration } from "./IBackgroundMigration";+import { logger } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { encrypt, decrypt } from "@langfuse/shared/encryption";++/**+ * Background migration to encrypt previously stored unencrypted secretAccessKey values+ * in the blob_storage_integrations table.+ *+ * Background:+ * - The public API endpoint previously stored secretAccessKey without encryption+ * - The tRPC endpoint correctly encrypted secrets+ * - This migration encrypts any unencrypted secrets+ *+ * Detection:+ * - Encrypted format: `<iv_hex>:<encrypted_hex>:<authTag_hex>` (contains colons)+ * - Unencrypted: Cloud provider secrets (AWS/Azure/GCP) never contain colons+ * - We try to decrypt; if it fails with "Invalid or corrupted cipher format", it's unencrypted+ *+ * This migration is idempotent and can be safely re-run if interrupted.+ */+export default class EncryptBlobStorageSecrets implements IBackgroundMigration {+ private isAborted = false;++ async validate(+ _args: Record<string, unknown>,+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {+ // No special prerequisites - encryption key is validated at decrypt/encrypt time+ return { valid: true, invalidReason: undefined };+ }++ async run(_args: Record<string, unknown>): Promise<void> {+ const startTime = Date.now();+ logger.info(+ "[Background Migration] Starting blob storage secrets encryption migration",+ );++ try {+ // Fetch all integrations with non-null secretAccessKey+ const integrations = await prisma.blobStorageIntegration.findMany({+ where: { secretAccessKey: { not: null } },+ select: { projectId: true, secretAccessKey: true },+ });++ const total = integrations.length;+ if (total === 0) {+ logger.info(+ "[Background Migration] No integrations to check, migration complete",+ );+ return;+ }+ logger.info(+ `[Background Migration] Found ${total} blob storage integrations to check`,+ );++ let encrypted = 0;+ let alreadyEncrypted = 0;+ let errors = 0;++ for (const integration of integrations) {+ // Check for abort signal+ if (this.isAborted) {+ logger.info(+ `[Background Migration] Migration aborted after processing ${encrypted + alreadyEncrypted} integrations`,+ );+ return;+ }++ if (!integration.secretAccessKey) {+ continue;+ }++ try {+ // Try to decrypt - if it succeeds, already encrypted+ decrypt(integration.secretAccessKey);+ alreadyEncrypted++;+ logger.debug(+ `[Background Migration] Integration ${integration.projectId} already encrypted, skipping`,+ );+ } catch (error) {+ if (+ error instanceof Error &&+ error.message === "Invalid or corrupted cipher format"+ ) {+ // Unencrypted - needs encryption+ try {+ const encryptedValue = encrypt(integration.secretAccessKey);+ await prisma.blobStorageIntegration.update({+ where: { projectId: integration.projectId },+ data: { secretAccessKey: encryptedValue },+ });+ encrypted++;+ logger.info(+ `[Background Migration] Encrypted secretAccessKey for project ${integration.projectId}`,+ );+ } catch (encryptError) {+ errors++;+ logger.error(+ `[Background Migration] Failed to encrypt secret for ${integration.projectId}: ${encryptError}`,+ { error: encryptError },+ );+ }+ } else {+ // Different error (wrong key, corrupted data) - log and skip+ errors++;+ logger.error(+ `[Background Migration] Unexpected decryption error for ${integration.projectId}: ${error}`,+ { error },+ );+ }+ }+ }++ const duration = Date.now() - startTime;+ logger.info(+ `[Background Migration] Blob storage secrets encryption completed in ${duration}ms: ` ++ `${encrypted} encrypted, ${alreadyEncrypted} already encrypted, ${errors} errors`,+ );+ } catch (error) {+ logger.error(+ "[Background Migration] Blob storage secrets encryption failed",+ { error },+ );+ throw error;+ }+ }++ async abort(): Promise<void> {+ logger.info(+ "[Background Migration] Aborting EncryptBlobStorageSecrets migration",+ );+ this.isAborted = true;+ }+}++async function main() {+ const migration = new EncryptBlobStorageSecrets();+ await migration.validate({});+ await migration.run({});+}++if (require.main === module) {+ main()+ .then(() => {+ process.exit(0);+ })+ .catch((error) => {+ logger.error(+ `[Background Migration] Migration execution failed: ${error}`,+ error,+ );+ process.exit(1);+ });+}