diff --git a/server/src/services/chat-channels/slack/ack-retirement-receipt.ts b/server/src/services/chat-channels/slack/ack-retirement-receipt.ts index 8ec760d7f48..0627f1aa9ac 100644 --- a/server/src/services/chat-channels/slack/ack-retirement-receipt.ts +++ b/server/src/services/chat-channels/slack/ack-retirement-receipt.ts @@ -1,3 +1,4 @@ +import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js"; import { isDeepStrictEqual } from "node:util"; import { createHash } from "node:crypto"; import { parseSlackFormBinding as parseFormBinding, parseSlackFormPublicEnrollment, type SlackFormBinding as FormBinding } from "./cloud-forms.js"; @@ -53,7 +54,7 @@ export function slackFormRetirementHistoryReceipt(row: SlackRetirementHistoryRow if (enrollment.bindingId !== binding.eventBindingId || ["instanceId", "companyId", "endpointId", "publicId", "connectionId", "runtimeGeneration", "teamId", "appId"].some(key => Reflect.get(enrollment, key) !== Reflect.get(binding, key))) throw new Error("Slack retirement enrollment history changed"); } - if (row.kind === "slack_form_owner" && row.providerActionId !== `slack-form-owner:${createHash("sha256").update(JSON.stringify(parseSlackFormPublicEnrollment(row.payload.enrollment))).digest("hex")}`) + if (row.kind === "slack_form_owner" && !isSlackFormEnrollmentActionId(row.providerActionId, parseSlackFormPublicEnrollment(row.payload.enrollment))) throw new Error("Slack retirement history owner changed"); return receipt; } diff --git a/server/src/services/chat-channels/slack/form-enrollment-identity.test.ts b/server/src/services/chat-channels/slack/form-enrollment-identity.test.ts new file mode 100644 index 00000000000..6d7d03da359 --- /dev/null +++ b/server/src/services/chat-channels/slack/form-enrollment-identity.test.ts @@ -0,0 +1,39 @@ +import { createHash } from "node:crypto"; +import { expect, it } from "vitest"; +import { parseSlackFormPublicEnrollment } from "./cloud-forms.js"; +import { slackFormEnrollmentActionId, slackFormEnrollmentCompatibleActionIds, isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js"; + +const enrollment = parseSlackFormPublicEnrollment({ version: 1, instanceId: "instance", companyId: "company", endpointId: "endpoint", + publicId: "p".repeat(43), connectionId: "connection", runtimeGeneration: 1, bindingId: "slack-event:" + "a".repeat(64), teamId: "TTEST", appId: "ATEST" }); +const legacyId = (value: unknown) => `slack-form-owner:${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`; +it("uses a complete typed tuple independent of input and JSONB object order", () => { + const reversed = parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(enrollment).reverse())); + const postgresOrder = parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(enrollment).sort(([a], [b]) => Buffer.byteLength(a) - Buffer.byteLength(b) || a.localeCompare(b)))); + expect(slackFormEnrollmentActionId(reversed)).toBe(slackFormEnrollmentActionId(enrollment)); + expect(slackFormEnrollmentActionId(postgresOrder)).toBe(slackFormEnrollmentActionId(enrollment)); + expect(legacyId(reversed)).not.toBe(legacyId(enrollment)); +}); +it("recognizes only the exact known legacy producer orders for the same full authority tuple", () => { + const e = enrollment; + const connectionFirst = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, endpointId: e.endpointId, + connectionId: e.connectionId, publicId: e.publicId, runtimeGeneration: e.runtimeGeneration, teamId: e.teamId, appId: e.appId, bindingId: e.bindingId }; + const publicFirst = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, endpointId: e.endpointId, + publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration, teamId: e.teamId, appId: e.appId, bindingId: e.bindingId }; + for (const previous of [enrollment, connectionFirst, publicFirst]) + expect(isSlackFormEnrollmentActionId(legacyId(previous), parseSlackFormPublicEnrollment(Object.fromEntries(Object.entries(previous).reverse())))).toBe(true); + expect(slackFormEnrollmentCompatibleActionIds(enrollment)).toHaveLength(4); + expect(isSlackFormEnrollmentActionId(legacyId(Object.fromEntries(Object.entries(enrollment).reverse())), enrollment)).toBe(false); + expect(isSlackFormEnrollmentActionId("slack-form-owner:" + "0".repeat(64), enrollment)).toBe(false); +}); +it("every authority field is bound for canonical and compatible identities", () => { + const variants = { instanceId: "other-instance", companyId: "other-company", endpointId: "other-endpoint", publicId: "q".repeat(43), + connectionId: "other-connection", runtimeGeneration: 2, bindingId: "slack-event:" + "b".repeat(64), teamId: "TOTHER", appId: "AOTHER" }; + for (const [key, value] of Object.entries(variants)) { + const changed = parseSlackFormPublicEnrollment({ ...enrollment, [key]: value }); + for (const id of slackFormEnrollmentCompatibleActionIds(enrollment)) expect(isSlackFormEnrollmentActionId(id, changed)).toBe(false); + } +}); +it("does not accept a different schema version or extra authority keys", () => { + expect(() => parseSlackFormPublicEnrollment({ ...enrollment, version: 2 })).toThrow(); + expect(() => parseSlackFormPublicEnrollment({ ...enrollment, unexpected: "authority" })).toThrow(); +}); diff --git a/server/src/services/chat-channels/slack/form-enrollment-identity.ts b/server/src/services/chat-channels/slack/form-enrollment-identity.ts new file mode 100644 index 00000000000..b5f893449d3 --- /dev/null +++ b/server/src/services/chat-channels/slack/form-enrollment-identity.ts @@ -0,0 +1,27 @@ +import { createHash } from "node:crypto"; +import { parseSlackFormPublicEnrollment, type SlackFormPublicEnrollment } from "./cloud-forms.js"; + +function actionId(value: readonly unknown[] | SlackFormPublicEnrollment): string { + return `slack-form-owner:${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`; +} +export function slackFormEnrollmentActionId(input: SlackFormPublicEnrollment): string { + const e = parseSlackFormPublicEnrollment(input); + return actionId(["slack-form-owner/v2", e.version, e.instanceId, e.companyId, e.endpointId, e.publicId, + e.connectionId, e.runtimeGeneration, e.bindingId, e.teamId, e.appId]); +} +export function slackFormEnrollmentCompatibleActionIds(input: SlackFormPublicEnrollment): readonly string[] { + const e = parseSlackFormPublicEnrollment(input); + const projected: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, + endpointId: e.endpointId, publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration, + bindingId: e.bindingId, teamId: e.teamId, appId: e.appId }; + const bindingDerived: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, + endpointId: e.endpointId, connectionId: e.connectionId, publicId: e.publicId, runtimeGeneration: e.runtimeGeneration, + teamId: e.teamId, appId: e.appId, bindingId: e.bindingId }; + const publicFirstBinding: SlackFormPublicEnrollment = { version: e.version, instanceId: e.instanceId, companyId: e.companyId, + endpointId: e.endpointId, publicId: e.publicId, connectionId: e.connectionId, runtimeGeneration: e.runtimeGeneration, + teamId: e.teamId, appId: e.appId, bindingId: e.bindingId }; + return [slackFormEnrollmentActionId(e), actionId(projected), actionId(bindingDerived), actionId(publicFirstBinding)]; +} +export function isSlackFormEnrollmentActionId(providerActionId: unknown, enrollment: SlackFormPublicEnrollment): boolean { + return typeof providerActionId === "string" && slackFormEnrollmentCompatibleActionIds(enrollment).includes(providerActionId); +} diff --git a/server/src/services/chat-channels/slack/form-owner.ts b/server/src/services/chat-channels/slack/form-owner.ts index 3c42fe9cd64..7ace78276cd 100644 --- a/server/src/services/chat-channels/slack/form-owner.ts +++ b/server/src/services/chat-channels/slack/form-owner.ts @@ -1,10 +1,10 @@ +import { slackFormEnrollmentActionId, slackFormEnrollmentCompatibleActionIds } from "./form-enrollment-identity.js"; import { acceptSlackFormRetirementLocally, transferSlackFormRetirement } from "./form-retirement-work.js"; import { reconcileSlackFormNormalAck } from "./form-ack-work.js"; import { HttpError } from "../../../errors.js"; import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv, PaperclipCloudConnectorError } from "../../paperclip-cloud-connector.js"; -import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, inArray, sql } from "drizzle-orm"; import { chatActions, chatEndpoints, chatPublications, issueThreadInteractions, toolConnections, type Db } from "@paperclipai/db"; import { notifyDeliveryWork, DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; import { resolveChatQuestionFormOpen, type ResolvedChatQuestionFormOpen } from "../../chat-question-forms.js"; @@ -17,7 +17,6 @@ import { slackFormConnectorIdentity, type SlackFormConnectorIdentity } from "./c type Tx = Pick; export type SlackFormProtocol = (input: { subject: string; companyId: string; operation: Record }) => Promise; -const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex"); function attention(code: string): never { throw new SlackCloudReceiptError(code, "attention"); } function object(value: unknown): Record { if (!value || typeof value !== "object" || Array.isArray(value)) return attention("form_owner_response_invalid"); @@ -45,8 +44,11 @@ export async function stageSlackFormEnrollment(tx: Tx, input: { enrollment: Slac || endpoint.publicId !== enrollment.publicId || endpoint.connectionId !== enrollment.connectionId || setup?.runtimeGeneration !== enrollment.runtimeGeneration || setup?.slackCloudInstanceId !== enrollment.instanceId || setup?.slackCloudSubject !== input.subject || !isDeepStrictEqual(projectSlackFormPublicEnrollment(endpoint), enrollment)) return attention("form_owner_current_enrollment_changed"); - const providerActionId = `slack-form-owner:${hash(enrollment)}`; - const [existing] = await tx.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.companyId, endpoint.companyId), eq(chatActions.providerActionId, providerActionId))).for("update"); + const providerActionId = slackFormEnrollmentActionId(enrollment); + const existingRows = await tx.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.companyId, endpoint.companyId), + inArray(chatActions.providerActionId, [...slackFormEnrollmentCompatibleActionIds(enrollment)]))).for("update"); + if (existingRows.length > 1) return attention("form_owner_identity_ambiguous"); + const [existing] = existingRows; const payload = { enrollment, subject: input.subject, environment: input.environment }; if (existing) { if (existing.kind !== "slack_form_owner" || !Object.keys(payload).every(key => isDeepStrictEqual(existing.payload[key], Reflect.get(payload, key)))) return attention("form_owner_custody_changed"); diff --git a/server/src/services/chat-channels/slack/form-retirement-work.ts b/server/src/services/chat-channels/slack/form-retirement-work.ts index b5f2c0ab7a8..24a6781f4db 100644 --- a/server/src/services/chat-channels/slack/form-retirement-work.ts +++ b/server/src/services/chat-channels/slack/form-retirement-work.ts @@ -1,6 +1,6 @@ +import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js"; import { replaceSlackFormReceiptSignature } from "./form-signature-refresh.js"; import { parseSlackFormRetirementReceipt } from "./ack-retirement-receipt.js"; -import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { and, eq, sql } from "drizzle-orm"; import { chatActions, type Db } from "@paperclipai/db"; @@ -24,8 +24,7 @@ export function assertSlackFormRetirementWorkAuthority(row: Row, identity: Slack throw new SlackCloudReceiptError("form_retirement_fingerprint_changed", "attention"); if (row.result?.retirementReceipt !== undefined && !isDeepStrictEqual(row.result.retirementReceipt, receipt)) throw new SlackCloudReceiptError("form_retirement_receipt_changed", "attention"); - const expectedAction = `slack-form-owner:${createHash("sha256").update(JSON.stringify(enrollment)).digest("hex")}`; - if (row.providerActionId !== expectedAction) throw new SlackCloudReceiptError("form_retirement_owner_changed", "attention"); + if (!isSlackFormEnrollmentActionId(row.providerActionId, enrollment)) throw new SlackCloudReceiptError("form_retirement_owner_changed", "attention"); } export function verifyRetainedSlackFormRetirement(compactJws: string) { try { return verifySlackFormRetirementReceipt({ compactJws }); } diff --git a/server/src/services/chat-channels/slack/form-retirement.test.ts b/server/src/services/chat-channels/slack/form-retirement.test.ts index 2588cae8413..32face47804 100644 --- a/server/src/services/chat-channels/slack/form-retirement.test.ts +++ b/server/src/services/chat-channels/slack/form-retirement.test.ts @@ -72,3 +72,17 @@ it("only exact committed transfer discharges history and its retained consumer", expect(() => slackFormRetirementHistoryReceipt({ ...current, result: { ...current.result, retirement: { ...retirement, receiptDigest: "0".repeat(64) } } })).toThrow(); expect(() => slackFormRetirementHistoryReceipt({ ...current, result: { phase: "transferred", nextAttemptAt: null } })).toThrow(); }); + +it("preserves exact legacy custody through JSONB ordering for acceptance, polling and history", () => { + const current = row(); + current.payload = { ...current.payload, enrollment: Object.fromEntries(Object.entries(enrollment).sort(([a], [b]) => Buffer.byteLength(a) - Buffer.byteLength(b) || a.localeCompare(b))) }; + expect(() => assertSlackFormRetirementWorkAuthority(current, identity, receipt)).not.toThrow(); + const input = signed(); + current.result = { phase: "retirement_accepted", retirementReceipt: receipt, retirementReceiptJws: input.compactJws, nextAttemptAt: new Date(0).toISOString() }; + expect(projectSlackFormRetainedOwner(current, identity.instanceId, identity.environment)?.requiresDelivery).toBe(false); + current.status = "processed"; + current.result = { phase: "transferred", nextAttemptAt: null, retirement: { version: 1, binding, instanceId: identity.instanceId, + environment: identity.environment, subject: receipt.subject, receiptDigest: receipt.receiptId, receipt } }; + expect(slackFormRetirementHistoryReceipt(current)).toEqual(receipt); + expect(projectSlackFormRetainedOwner(current, identity.instanceId, identity.environment)).toBeNull(); +}); diff --git a/server/src/services/chat-channels/slack/form-session.ts b/server/src/services/chat-channels/slack/form-session.ts index 14c223c1ea9..4e156eec2fc 100644 --- a/server/src/services/chat-channels/slack/form-session.ts +++ b/server/src/services/chat-channels/slack/form-session.ts @@ -1,3 +1,4 @@ +import { isSlackFormEnrollmentActionId } from "./form-enrollment-identity.js"; import { parseSlackFormRetirementReceipt, slackFormRetirementHistoryReceipt } from "./ack-retirement-receipt.js"; import { createHash } from "node:crypto"; import type { IssueThreadInteraction } from "@paperclipai/shared"; @@ -334,7 +335,7 @@ export function projectSlackFormRetainedOwner(row: SlackFormRetainedRow, current const receipt = parseSlackFormRetirementReceipt(row.result.retirementReceipt), enrollment = parseSlackFormPublicEnrollment(row.payload.enrollment), binding = receipt.binding; if (receipt.binding.instanceId !== currentInstanceId || currentEnvironment !== undefined && receipt.environment !== currentEnvironment) return null; if (row.companyId !== binding.companyId || row.endpointId !== binding.endpointId || row.payload.subject !== receipt.subject - || row.providerActionId !== `slack-form-owner:${createHash("sha256").update(JSON.stringify(enrollment)).digest("hex")}` + || !isSlackFormEnrollmentActionId(row.providerActionId, enrollment) || row.payload.environment !== receipt.environment || typeof row.result.retirementReceiptJws !== "string" || Buffer.byteLength(row.result.retirementReceiptJws, "ascii") > 12000 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(row.result.retirementReceiptJws)