Skip to content
Merged
8 changes: 8 additions & 0 deletions services/platform/backend/domains/conversations/api-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { emitHintInTx } from '../../realtime/outbox.ts';
import { createAuditLog } from '../audit_logs/service.ts';
import { FileError, statOrgBlob } from '../files/service.ts';
import { firstForeignUpload } from '../files/upload-intents.ts';
import { assertOwnedAttachments } from './attachment-ownership.ts';
import { completePendingDraftInTx } from './draft.ts';
import { applyConversationRouting } from './routing.ts';
import {
Expand Down Expand Up @@ -513,6 +514,13 @@ export async function queueApiReply(
assertAttachmentLanded(landed, file.size);
}
return transactSerializable(sql, async (tx) => {
// Proven and stamped in this transaction, so a refusal below leaves no
// stamp behind (#4111); the route refused a foreign file before.
await assertOwnedAttachments(
tx,
{ organizationId: args.organizationId, userId: args.actor.userId },
args.attachments,
);
const identities = await tx<
{ email: string }[]
>`SELECT email FROM "user" WHERE id = ${args.actor.userId} AND "emailVerified" = true FOR SHARE`;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// @vitest-environment node

import type { Sql } from 'postgres';
import { afterEach, expect, it, vi } from 'vitest';

import { firstForeignUpload } from '../files/upload-intents.ts';
import { assertOwnedAttachments } from './attachment-ownership.ts';
import { ConversationError } from './service.ts';

/**
* The outbound-mail ownership rule: every attachment must be the sender's
* own upload. The send's transaction asks it with the stamp (the default),
* so a refusal rolls the stamp back; the route asks first without one
* (#4111).
*/

vi.mock(import('../files/upload-intents.ts'), async (importOriginal) => ({
...(await importOriginal()),
firstForeignUpload: vi.fn(),
}));

const sql = {} as Sql;
const scope = { organizationId: 'o1', userId: 'u1' };
const FILES = [{ storageId: 'blob-1' }, { storageId: 'blob-2' }];

afterEach(() => {
vi.clearAllMocks();
});

it('proves every attachment through the stamping proof by default', async () => {
vi.mocked(firstForeignUpload).mockResolvedValue(null);

await assertOwnedAttachments(sql, scope, FILES);

expect(firstForeignUpload).toHaveBeenCalledWith(
sql,
scope,
['blob-1', 'blob-2'],
{},
);
});

it('passes stamp: false through for the early refusal', async () => {
vi.mocked(firstForeignUpload).mockResolvedValue(null);

await assertOwnedAttachments(sql, scope, FILES, { stamp: false });

expect(firstForeignUpload).toHaveBeenCalledWith(
sql,
scope,
['blob-1', 'blob-2'],
{ stamp: false },
);
});

it('refuses a foreign attachment with ATTACHMENT_NOT_OWNED', async () => {
vi.mocked(firstForeignUpload).mockResolvedValue('blob-2');

const refusal = await assertOwnedAttachments(sql, scope, FILES).catch(
(error: unknown) => error,
);

expect(refusal).toBeInstanceOf(ConversationError);
expect(refusal).toMatchObject({ code: 'ATTACHMENT_NOT_OWNED', status: 403 });
});

it('asks nothing for a send without attachments', async () => {
await assertOwnedAttachments(sql, scope, undefined);
await assertOwnedAttachments(sql, scope, []);

expect(firstForeignUpload).not.toHaveBeenCalled();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Sql, TransactionSql } from 'postgres';

import { firstForeignUpload } from '../files/upload-intents.ts';
import { ConversationError } from './service.ts';

/**
* Outbound attachments are client-named blob refs the connector will READ
* and mail out of the organization. Each must be the sender's own upload
* (their upload intent, or a row they registered) — a document's ref, which
* every reader of that document holds, is not theirs to send.
*
* The proof that counts runs inside the transaction that writes the queued
* message (`send.ts`' `sendMessageViaConnectorInTx`, `api-sync.ts`'
* `queueApiReply`), because it STAMPS the intents it proves through
* (`ownsUploadedBlob`): a refusal anywhere in that transaction rolls the
* stamps back with the message, and a rejected-upload reclaim racing the
* send waits on the intent row. The route asks first with `stamp: false`,
* so a foreign attachment is still refused before any other check; a stamp
* the route committed on its own used to outlive every later refusal and
* leave an upload no reclaim could take (#4111).
*/
export async function assertOwnedAttachments(
sql: Sql | TransactionSql,
scope: { organizationId: string; userId: string },
attachments: readonly { storageId: string }[] | undefined,
options: { stamp?: boolean } = {},
): Promise<void> {
if (attachments === undefined || attachments.length === 0) return;
const foreign = await firstForeignUpload(
sql,
scope,
attachments.map((attachment) => attachment.storageId),
options,
);
if (foreign !== null) {
throw new ConversationError(
'ATTACHMENT_NOT_OWNED',
'An attachment is not one of your uploads. Remove it and attach the file again.',
403,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,14 @@ describe('conversations route — an email that carries only files', () => {

expect(res.status).toBe(201);
await expect(res.json()).resolves.toEqual({ messageId: 'm1' });
// The files are still checked as the sender's own uploads.
// The files are still checked as the sender's own uploads — early and
// without a stamp: the send's transaction proves them again and stamps
// there, so a refused send leaves no stamp behind (#4111).
expect(firstForeignUpload).toHaveBeenCalledWith(
expect.anything(),
{ organizationId: 'o1', userId: 'u1' },
['blob-1'],
{ stamp: false },
);
expect(replyToConversation).toHaveBeenCalledWith(
expect.anything(),
Expand Down
31 changes: 11 additions & 20 deletions services/platform/backend/domains/conversations/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { requireOrgMember, type OrgEnv } from '../../auth/org.ts';
import { requireSession } from '../../auth/session.ts';
import { publicOrigin } from '../../core/lib/helpers/public_origin.ts';
import { invalidBodyResponse } from '../../lib/invalid-body-response.ts';
import { firstForeignUpload } from '../files/upload-intents.ts';
import { assertOwnedAttachments } from './attachment-ownership.ts';
import {
IMPROVE_MAX_INPUT_CHARS,
IMPROVE_MAX_INSTRUCTION_CHARS,
Expand Down Expand Up @@ -426,32 +426,23 @@ export function createConversationRoutes(deps: {
});

/**
* Outbound attachments are client-named blob refs the connector will READ
* and mail out of the organization. Each must be the sender's own upload
* (their upload intent, or a row they registered) — a document's ref,
* which every reader of that document holds, is not theirs to send.
* The early refusal of an attachment that is not the sender's own upload
* (`attachment-ownership.ts`): asked without a stamp, because the send's
* own transaction proves it again and stamps there (#4111).
*/
const assertOwnedAttachments = async (
const refuseForeignAttachments = (
c: Context<OrgEnv>,
attachments: readonly { storageId: string }[] | undefined,
): Promise<void> => {
if (attachments === undefined || attachments.length === 0) return;
const foreign = await firstForeignUpload(
): Promise<void> =>
assertOwnedAttachments(
deps.sql,
{
organizationId: c.get('orgId'),
userId: c.get('sessionBundle').user.id,
},
attachments.map((attachment) => attachment.storageId),
attachments,
{ stamp: false },
);
if (foreign !== null) {
throw new ConversationError(
'ATTACHMENT_NOT_OWNED',
'An attachment is not one of your uploads. Remove it and attach the file again.',
403,
);
}
};

/** Send a reply through the conversation's connector (undo window). An
* empty `content` beside files is an attachment-only reply. */
Expand All @@ -468,7 +459,7 @@ export function createConversationRoutes(deps: {
if (!body.success) return invalidBodyResponse(c, body.error);
try {
await loadVisibleConversation(deps.sql, viewer(c), c.req.param('id'));
await assertOwnedAttachments(c, body.data.attachments);
await refuseForeignAttachments(c, body.data.attachments);
const messageId = await replyToConversation(deps.sql, {
conversationId: c.req.param('id'),
organizationId: c.get('orgId'),
Expand Down Expand Up @@ -508,7 +499,7 @@ export function createConversationRoutes(deps: {
.safeParse(await c.req.json());
if (!body.success) return invalidBodyResponse(c, body.error);
try {
await assertOwnedAttachments(c, body.data.attachments);
await refuseForeignAttachments(c, body.data.attachments);
const result = await composeEmailConversation(deps.sql, {
organizationId: c.get('orgId'),
contactId: body.data.contactId,
Expand Down
10 changes: 10 additions & 0 deletions services/platform/backend/domains/conversations/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ const {
addJobInTx,
emitHintInTx,
queueApiReply,
assertOwnedAttachments,
} = vi.hoisted(() => ({
runConnectorAction: vi.fn(),
createAuditLog: vi.fn(async () => undefined),
addJobInTx: vi.fn(async () => 'job-1'),
emitHintInTx: vi.fn(async () => undefined),
queueApiReply: vi.fn(async () => 'm-api'),
assertOwnedAttachments: vi.fn(async () => undefined),
}));

vi.mock('../connectors/service.ts', () => ({ runConnectorAction }));
Expand All @@ -41,6 +43,7 @@ vi.mock('../events/emit.ts', () => ({
emitEvent: vi.fn(async () => undefined),
}));
vi.mock('../../jobs/enqueue.ts', () => ({ addJobInTx }));
vi.mock('./attachment-ownership.ts', () => ({ assertOwnedAttachments }));
vi.mock('./api-sync.ts', async (importOriginal) => ({
...(await importOriginal<typeof import('./api-sync.ts')>()),
queueApiReply,
Expand Down Expand Up @@ -906,6 +909,13 @@ describe('replyToConversation and composeEmailConversation — files alone', ()
}),
],
});
// The files are proven the sender's own inside the send's transaction,
// where the proof's stamp rolls back with any refusal (#4111).
expect(assertOwnedAttachments).toHaveBeenCalledWith(
expect.anything(),
{ organizationId: 'o1', userId: 'u1' },
[FILE],
);
const [payload] = addJobInTx.mock.calls[0]?.slice(2) ?? [];
// An empty plain-text part beside the file: every mail connector sends
// that as a body-less email with its attachment.
Expand Down
9 changes: 9 additions & 0 deletions services/platform/backend/domains/conversations/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { createAuditLog } from '../audit_logs/service.ts';
import { runConnectorAction } from '../connectors/service.ts';
import { getFileUrl } from '../files/service.ts';
import { queueApiReply, retryApiDeliveryAudited } from './api-sync.ts';
import { assertOwnedAttachments } from './attachment-ownership.ts';
import { completePendingDraftInTx } from './draft.ts';
import {
assertAssignableMember,
Expand Down Expand Up @@ -221,6 +222,14 @@ async function sendMessageViaConnectorInTx(
tx: TransactionSql,
args: SendMessageViaConnectorArgs,
): Promise<string> {
// The sender's own uploads, proven in THIS transaction: the proof stamps
// their intents, so a refusal below rolls the stamps back with the queued
// row instead of leaving an upload no reclaim may take (#4111).
await assertOwnedAttachments(
tx,
{ organizationId: args.organizationId, userId: args.actor.userId },
args.attachments,
);
// Locked: the send rewrites the summary from this read (the rule in
// `service.ts`'s module doc), so an inbound message landing meanwhile keeps
// its unread count.
Expand Down
40 changes: 34 additions & 6 deletions services/platform/backend/domains/files/blob-holders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import type { Fragment, Sql } from 'postgres';
import { describe, expect, it } from 'vitest';

import { blobRefHeld } from './blob-holders.ts';
import { blobRefHeld, listedBlobRefHeld } from './blob-holders.ts';

/**
* The one answer to "may these bytes go?" for every lane that deletes bytes
* outside the release seam, as the statement states it: a file row in any
* lifecycle, a document's current file or retained version, or a task's
* attachment or deliverable — each scoped to the organization.
* lifecycle, a document's current file or retained version, or a listed
* holder — a task's attachment or deliverable, a pending outbound mail's
* attachment, a user's chat attachment — each scoped to the organization.
*/

interface Rendered {
Expand Down Expand Up @@ -60,13 +61,13 @@ function rendered(fragment: Fragment): Rendered {
}

describe('blobRefHeld', () => {
it('holds the bytes for a file row, a document (current or retained) or a task of the org', () => {
it('holds the bytes for a file row, a document (current or retained) or a listed holder of the org', () => {
const sql = tag();
const held = rendered(blobRefHeld(sql, 'org_1', sql`i.s3_ref`));
expect(held.text).toBe(
"(EXISTS ( SELECT 1 FROM app.file_metadata held_file WHERE held_file.org_id = ? AND held_file.storage_ref = i.s3_ref ) OR EXISTS ( SELECT 1 FROM app.documents held_doc WHERE held_doc.org_id = ? AND (held_doc.file_ref = i.s3_ref OR held_doc.history_files @> ARRAY[i.s3_ref::text]) ) OR EXISTS ( SELECT 1 FROM app.tasks held WHERE held.org_id = ? AND (coalesce(held.attachments, '[]'::jsonb) || coalesce(held.outputs, '[]'::jsonb)) @> jsonb_build_array(jsonb_build_object('fileId', i.s3_ref::text)) ))",
"(EXISTS ( SELECT 1 FROM app.file_metadata held_file WHERE held_file.org_id = ? AND held_file.storage_ref = i.s3_ref ) OR EXISTS ( SELECT 1 FROM app.documents held_doc WHERE held_doc.org_id = ? AND (held_doc.file_ref = i.s3_ref OR held_doc.history_files @> ARRAY[i.s3_ref::text]) ) OR (EXISTS ( SELECT 1 FROM app.tasks held WHERE held.org_id = ? AND (coalesce(held.attachments, '[]'::jsonb) || coalesce(held.outputs, '[]'::jsonb)) @> jsonb_build_array(jsonb_build_object('fileId', i.s3_ref::text)) ) OR EXISTS ( SELECT 1 FROM app.conversation_messages held_mail WHERE held_mail.org_id = ? AND held_mail.direction = 'outbound' AND held_mail.delivery_state IN ('queued', 'failed') AND held_mail.metadata->'attachments' @> jsonb_build_array(jsonb_build_object('storageId', i.s3_ref::text)) ) OR EXISTS ( SELECT 1 FROM app.messages held_chat WHERE held_chat.org_id = ? AND held_chat.role = 'user' AND held_chat.parts @> jsonb_build_array(jsonb_build_object( 'type', 'attachment', 'fileId', i.s3_ref::text )) )))",
);
expect(held.values).toEqual(['org_1', 'org_1', 'org_1']);
expect(held.values).toEqual(['org_1', 'org_1', 'org_1', 'org_1', 'org_1']);
});

it('takes the ref as a parameter, bound once per arm', () => {
Expand All @@ -78,6 +79,8 @@ describe('blobRefHeld', () => {
'held_doc.file_ref = ? OR held_doc.history_files @> ARRAY[?::text]',
);
expect(held.text).toContain("jsonb_build_object('fileId', ?::text)");
expect(held.text).toContain("jsonb_build_object('storageId', ?::text)");
expect(held.text).toContain("'type', 'attachment', 'fileId', ?::text");
expect(held.values).toEqual([
'org_1',
ref,
Expand All @@ -86,6 +89,31 @@ describe('blobRefHeld', () => {
ref,
'org_1',
ref,
'org_1',
ref,
'org_1',
ref,
]);
});
});

describe('listedBlobRefHeld', () => {
it('lists a task, a pending outbound mail and a user’s chat message of the org (#4111)', () => {
const sql = tag();
const held = rendered(listedBlobRefHeld(sql, 'org_1', sql`r.ref`));
expect(held.text).toBe(
"(EXISTS ( SELECT 1 FROM app.tasks held WHERE held.org_id = ? AND (coalesce(held.attachments, '[]'::jsonb) || coalesce(held.outputs, '[]'::jsonb)) @> jsonb_build_array(jsonb_build_object('fileId', r.ref::text)) ) OR EXISTS ( SELECT 1 FROM app.conversation_messages held_mail WHERE held_mail.org_id = ? AND held_mail.direction = 'outbound' AND held_mail.delivery_state IN ('queued', 'failed') AND held_mail.metadata->'attachments' @> jsonb_build_array(jsonb_build_object('storageId', r.ref::text)) ) OR EXISTS ( SELECT 1 FROM app.messages held_chat WHERE held_chat.org_id = ? AND held_chat.role = 'user' AND held_chat.parts @> jsonb_build_array(jsonb_build_object( 'type', 'attachment', 'fileId', r.ref::text )) ))",
);
expect(held.values).toEqual(['org_1', 'org_1', 'org_1']);
});

it('holds a mail only while it may still be sent, and a chat ref only on a user row', () => {
const sql = tag();
const { text } = rendered(listedBlobRefHeld(sql, 'org_1', sql`r.ref`));
// A sent or delivered message, or an inbound one, holds nothing.
expect(text).toContain(
"held_mail.direction = 'outbound' AND held_mail.delivery_state IN ('queued', 'failed')",
);
expect(text).toContain("held_chat.role = 'user'");
});
});
Loading