Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): show readable upload errors and log the S3 rejection (#8783)
teo29f28f4c6f86
diff --git a/apps/web/src/lib/queries/email/attachment.test.tsx b/apps/web/src/lib/queries/email/attachment.test.tsxindex 900485eaae..a7f2d33825 100644--- a/apps/web/src/lib/queries/email/attachment.test.tsx+++ b/apps/web/src/lib/queries/email/attachment.test.tsx@@ -197,6 +197,36 @@ describe('useUploadDraftAttachmentsMutation', () => {expect(onAttachmentUploadFailed).toHaveBeenCalledWith(attachment);expect(toastFailureMock).toHaveBeenCalledWith('Failed to save attachments');});++ it('fails with readable copy when S3 rejects the content upload', async () => {+ const storage = await vi.importActual<+ typeof import('@service-storage/util/uploadToPresignedUrl')+ >('@service-storage/util/uploadToPresignedUrl');+ uploadToPresignedUrlMock.mockImplementation(storage.uploadToPresignedUrl);+ fetchMock.mockResolvedValue(+ new Response(+ '<?xml version="1.0" encoding="UTF-8"?>\n<Error><Code>AccessDenied</Code><Message>no VPC endpoint policy allows the s3:PutObject action</Message><RequestId>9T8VG69R5KVNCQFK</RequestId></Error>',+ { status: 403 }+ )+ );+ const onAttachmentUploadFailed = vi.fn();+ const attachment = file();++ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);+ await expect(+ mutation.mutateAsync({+ draftID: 'draft-1',+ attachments: [attachment],+ onAttachmentUploadFailed,+ })+ ).rejects.toThrow(/^Upload failed$/);+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://bucket/att-1',+ expect.objectContaining({ method: 'PUT' })+ );+ expect(onAttachmentUploadFailed).toHaveBeenCalledWith(attachment);+ });+it('uploads native clipboard bytes with the real size and checksum', async () => {const attachment = createNativeStagedUploadFile('pasteboard', {token: 'paste-stage-fixture',diff --git a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.tsindex 02bdb6d7e3..556ca25259 100644--- a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts@@ -1,10 +1,12 @@import { isTauri } from '@core/util/platform';import { platformFetch } from '@core/util/platformFetch';+import { Telemetry } from '@macro-inc/observability';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { uploadToPresignedUrl } from './uploadToPresignedUrl';vi.mock('@core/util/platform', () => ({ isTauri: vi.fn(() => false) }));vi.mock('@core/util/platformFetch', () => ({ platformFetch: vi.fn() }));+vi.mock('@macro-inc/observability', () => ({ Telemetry: { warn: vi.fn() } }));class FakeXhr {static instances: FakeXhr[] = [];@@ -74,14 +76,6 @@ describe('uploadToPresignedUrl with progress', () => {expect(platformFetch).not.toHaveBeenCalled();});- it('returns the response body as a server error', async () => {- const pending = uploadToPresignedUrl({ ...params(), onProgress: vi.fn() });- xhr().respond(403, 'SignatureDoesNotMatch');- expect((await pending)._unsafeUnwrapErr()).toEqual([- { code: 'SERVER_ERROR', message: 'SignatureDoesNotMatch' },- ]);- });-it('rejects on network failure, like fetch', async () => {const pending = uploadToPresignedUrl({ ...params(), onProgress: vi.fn() });xhr().onerror?.();@@ -122,3 +116,94 @@ describe('uploadToPresignedUrl with progress', () => {expect(FakeXhr.instances).toHaveLength(0);});});++describe('uploadToPresignedUrl when S3 rejects the upload', () => {+ const presignedUrl = `https://macro-email-attachments-dev.s3.us-east-1.amazonaws.com/draft/01a16ebf/0acf54cf?${new URLSearchParams(+ {+ 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',+ 'X-Amz-Credential':+ 'ASIAEXAMPLEKEYID1234/20261024/us-east-1/s3/aws4_request',+ 'X-Amz-Date': '20261024T162943Z',+ 'X-Amz-Expires': '120',+ 'X-Amz-Security-Token': 'session-token-secret',+ 'X-Amz-Signature': 'signature-secret',+ 'X-Amz-SignedHeaders': 'content-type;host;x-amz-checksum-sha256',+ 'x-id': 'PutObject',+ }+ )}`;+ const s3Message =+ 'User: arn:aws:sts::569036502058:assumed-role/email-service-role-2-dev/05c4b09c72544171a6d8cb73f1f8fdfe is not authorized to perform: s3:PutObject on resource: "arn:aws:s3:::macro-email-attachments-dev/draft/01a16ebf/0acf54cf" because no VPC endpoint policy allows the s3:PutObject action';+ const accessDenied = `<?xml version="1.0" encoding="UTF-8"?>\n<Error><Code>AccessDenied</Code><Message>${s3Message}</Message><RequestId>9T8VG69R5KVNCQFK</RequestId><HostId>eogGpUstWUuZTwAMK8B2b2AqUTtW8f</HostId></Error>`;+ const signatureMismatch = `<?xml version="1.0" encoding="UTF-8"?>\n<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>ASIAEXAMPLEKEYID1234</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA256\n20261024T162943Z</StringToSign><SignatureProvided>signature-secret</SignatureProvided><CanonicalRequest>PUT\n/draft/01a16ebf/0acf54cf\nX-Amz-Security-Token=session-token-secret</CanonicalRequest><RequestId>5659KZAZESK3P7X3</RequestId><HostId>4YO3CdvNnyscQZp</HostId></Error>`;++ const transports = {+ fetch: (body: string) => {+ vi.mocked(platformFetch).mockResolvedValue(+ new Response(body, { status: 403 })+ );+ return uploadToPresignedUrl({ ...params(), presignedUrl });+ },+ xhr: (body: string) => {+ const pending = uploadToPresignedUrl({+ ...params(),+ presignedUrl,+ onProgress: vi.fn(),+ });+ xhr().respond(403, body);+ return pending;+ },+ };++ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-24T16:29:53Z'));+ });+ afterEach(() => vi.useRealTimers());++ it.each(Object.entries(transports))(+ 'returns readable copy and logs the S3 error over %s',+ async (_, upload) => {+ const result = await upload(accessDenied);++ expect(result._unsafeUnwrapErr()).toEqual([+ { code: 'SERVER_ERROR', message: 'Upload failed' },+ ]);+ expect(Telemetry.warn).toHaveBeenCalledExactlyOnceWith(+ 'storage_upload.rejected',+ {+ 'storage_upload.status': 403,+ 'storage_upload.s3_code': 'AccessDenied',+ 'storage_upload.s3_message': s3Message,+ 'storage_upload.s3_request_id': '9T8VG69R5KVNCQFK',+ 'storage_upload.url_age_seconds': 10,+ 'storage_upload.url_expires_seconds': 120,+ 'storage_upload.credential_prefix': 'ASIA',+ }+ );+ }+ );++ it.each(Object.entries(transports))(+ 'keeps the signature, token, and access key out of the error and the log over %s',+ async (_, upload) => {+ const result = await upload(signatureMismatch);++ expect(Telemetry.warn).toHaveBeenCalledWith(+ 'storage_upload.rejected',+ expect.objectContaining({+ 'storage_upload.s3_code': 'SignatureDoesNotMatch',+ })+ );+ const observed = JSON.stringify([+ result._unsafeUnwrapErr(),+ vi.mocked(Telemetry.warn).mock.calls,+ ]);+ for (const secret of [+ 'signature-secret',+ 'session-token-secret',+ 'ASIAEXAMPLEKEYID1234',+ ])+ expect(observed).not.toContain(secret);+ }+ );+});diff --git a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.tsindex 825d04e5e8..5760a6ac30 100644--- a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts+++ b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts@@ -1,6 +1,8 @@import { isTauri } from '@core/util/platform';import { platformFetch } from '@core/util/platformFetch';import type { ResultError } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';+import { differenceInSeconds, isValid, parseISO } from 'date-fns';import { err, ok, type Result } from 'neverthrow';type UploadResult = Result<void, ResultError<'SERVER_ERROR'>[]>;@@ -42,6 +44,7 @@ export async function uploadToPresignedUrl({}onProgress?.(null);+ const sentAt = Date.now();const response = await platformFetch(presignedUrl, {method: 'PUT',body: blob,@@ -50,13 +53,48 @@ export async function uploadToPresignedUrl({});if (!response.ok) {- const message = await response.text();- return err([{ code: 'SERVER_ERROR', message: message }]);+ return rejected({+ presignedUrl,+ sentAt,+ status: response.status,+ body: await response.text(),+ });}return ok(undefined);}+/**+ * S3 error bodies can echo the access key, signature, and session token, so+ * only allowlisted fields reach the log and none reach the caller.+ */+function rejected(input: {+ presignedUrl: string;+ sentAt: number;+ status: number;+ body: string;+}): UploadResult {+ const element = (name: string) =>+ input.body.match(new RegExp(`<${name}>([^<]*)</${name}>`))?.[1];+ const query = new URL(input.presignedUrl).searchParams;+ const signedAt = parseISO(query.get('X-Amz-Date') ?? '');+ Telemetry.warn('storage_upload.rejected', {+ 'storage_upload.status': input.status,+ 'storage_upload.s3_code': element('Code'),+ 'storage_upload.s3_message': element('Message'),+ 'storage_upload.s3_request_id': element('RequestId'),+ 'storage_upload.url_age_seconds': isValid(signedAt)+ ? differenceInSeconds(input.sentAt, signedAt)+ : undefined,+ 'storage_upload.url_expires_seconds':+ Number(query.get('X-Amz-Expires')) || undefined,+ 'storage_upload.credential_prefix': query+ .get('X-Amz-Credential')+ ?.slice(0, 4),+ });+ return err([{ code: 'SERVER_ERROR', message: 'Upload failed' }]);+}+/** `fetch` can't report upload progress, so the browser path uses XHR. */function uploadWithXhr({presignedUrl,@@ -73,6 +111,7 @@ function uploadWithXhr({}): Promise<UploadResult> {return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest();+ const sentAt = Date.now();const abort = () => xhr.abort();const settle = () => signal?.removeEventListener('abort', abort);@@ -83,7 +122,14 @@ function uploadWithXhr({onProgress(blob.size);resolve(ok(undefined));} else {- resolve(err([{ code: 'SERVER_ERROR', message: xhr.responseText }]));+ resolve(+ rejected({+ presignedUrl,+ sentAt,+ status: xhr.status,+ body: xhr.responseText,+ })+ );}};// Mirror fetch, which rejects on network failure and abort.