From 32dcb75ef8f892c0bd5d25281e0047bd27e5a4e7 Mon Sep 17 00:00:00 2001 From: Matti Nannt Date: Tue, 27 Feb 2024 13:20:49 +0100 Subject: [PATCH] fix: health endpoint s3 connection (#2136) --- apps/web/app/health/page.tsx | 9 ++++++--- packages/lib/storage/service.ts | 26 ++++++++++++-------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/apps/web/app/health/page.tsx b/apps/web/app/health/page.tsx index 47faf1f105..80935f6ae9 100644 --- a/apps/web/app/health/page.tsx +++ b/apps/web/app/health/page.tsx @@ -3,7 +3,7 @@ import { Metadata } from "next"; import { prisma } from "@formbricks/database"; import { IS_S3_CONFIGURED } from "@formbricks/lib/constants"; -import { testS3Connection } from "@formbricks/lib/storage/service"; +import { testS3BucketAccess } from "@formbricks/lib/storage/service"; export const dynamic = "force-dynamic"; // no caching @@ -31,8 +31,11 @@ const checkS3Connection = async () => { // dont try connecting if not in use return; } - - await testS3Connection(); + try { + await testS3BucketAccess(); + } catch (e) { + throw new Error("S3 Bucket cannot be accessed"); + } }; export default async function HealthPage() { diff --git a/packages/lib/storage/service.ts b/packages/lib/storage/service.ts index dd1a3d8325..4bd1b19e33 100644 --- a/packages/lib/storage/service.ts +++ b/packages/lib/storage/service.ts @@ -2,7 +2,7 @@ import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, - ListBucketsCommand, + HeadBucketCommand, ListObjectsCommand, PutObjectCommand, S3Client, @@ -50,23 +50,21 @@ export const getS3Client = () => { return s3ClientInstance; }; -export const testS3Connection = async () => { +export const testS3BucketAccess = async () => { + const s3Client = getS3Client(); + try { - const s3Client = getS3Client(); - const cmd = new ListBucketsCommand({}); - const result = await s3Client.send(cmd); + // Attempt to retrieve metadata about the bucket + const headBucketCommand = new HeadBucketCommand({ + Bucket: S3_BUCKET_NAME, + }); - if (!result.Buckets) { - throw new Error("Access denied to any buckets"); - } + await s3Client.send(headBucketCommand); - const bucketNames = result.Buckets.map((b) => b.Name); - - if (!bucketNames.includes(S3_BUCKET_NAME)) { - throw new Error("Access denied to bucket"); - } + return true; } catch (error) { - throw new Error(`S3: ${error}`); + console.error("Failed to access S3 bucket:", error); + throw new Error(`S3 Bucket Access Test Failed: ${error}`); } };