diff --git a/server/src/__tests__/slack-form-retirement-work.test.ts b/server/src/__tests__/slack-form-retirement-work.test.ts index f3f509088cd..2ef3b751586 100644 --- a/server/src/__tests__/slack-form-retirement-work.test.ts +++ b/server/src/__tests__/slack-form-retirement-work.test.ts @@ -1,3 +1,9 @@ +import { readSlackIdleIncomingProof } from "../services/chat-channels/slack/idle-incoming.js"; +import { idleChatHistoryChecksForOwner } from "../services/chat-channels/idle-history-proof.js"; +import { registerConnectionEventWake, hasConnectionEventWakeReceiver } from "../services/connection-event-wake.js"; +import { slackConfiguredBindingsFingerprint } from "../services/chat-channels/slack/configured-coverage.js"; +import { verifyCloudControlAssertion, CLOUD_CONTROL_AUDIENCE, CLOUD_CONTROL_JWS_TYPE } from "../services/cloud-runtime-identity.js"; +import type { VerifiedIdleCapabilities } from "../services/idle-incoming-wake-capability.js"; import { retainSlackFormOpeningProof } from "../services/chat-channels/slack/form-opening-proof.js"; import { readSlackFormRetainedConsumer } from "../services/chat-channels/slack/cloud-consumer.js"; import { parseSlackFormAckWork, transferSlackFormAckReceipt } from "../services/chat-channels/slack/form-ack-work.js"; @@ -92,8 +98,106 @@ if (process.env.SLACK_GATE_EXPECT_PRELOAD === "1" && !external) throw new Error( const errors = closed.flatMap(value => value.status === "rejected" ? [value.reason] : []); if (errors.length) throw new AggregateError(errors, "retirement auxiliary closure failure"); }); + function signedRetainedHistoryCapabilities(): VerifiedIdleCapabilities { + const key=generateKeyPairSync("ed25519"),kid="retained-history-current",now=Math.floor(Date.now()/1000),generation="e".repeat(64); + const capabilities={incomingWake:{version:1,ownerId:randomUUID(),generation,routes:["slack-broker-events-v1"], + slackBroker:{version:1,instanceId:identity.instanceId,generation,bindingsFingerprint:slackConfiguredBindingsFingerprint([]),entries:[]}}}; + const encode=(value:unknown)=>Buffer.from(JSON.stringify(value)).toString("base64url"); + const body=encode({alg:"EdDSA",typ:CLOUD_CONTROL_JWS_TYPE,kid})+"."+encode({v:1,iss:"paperclip-cloud",aud:CLOUD_CONTROL_AUDIENCE, + sub:identity.instanceId,action:"task-drain:read",requestId:randomUUID(),iat:now,exp:now+60,idleCapabilities:capabilities}); + const claims=verifyCloudControlAssertion({compactJws:body+"."+sign(null,Buffer.from(body),key.privateKey).toString("base64url"),expectedAction:"task-drain:read", + env:{PAPERCLIP_CLOUD_STACK_ID:identity.instanceId,PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS:JSON.stringify({keys:[{...key.publicKey.export({format:"jwk"}),kid,use:"sig",alg:"EdDSA"}]})}}); + if(!claims.idleCapabilities)throw new Error("Actual signed retained-history capability absent"); + return claims.idleCapabilities as VerifiedIdleCapabilities; + } + async function finishedHistory(ownerAlreadyTransferred=false) { + // The original owner reaches its real normal transferred state. Additional + // rows explicitly represent already-committed historical custody, not live + // provider calls or a fabricated provider result in this tested journey. + if(!ownerAlreadyTransferred)await acceptSlackFormRetirementLocally(db,await row(),identity,compactJws); + const receipt=slackFormRetirementReceipt(binding,identity.environment,actorId); + const protocol=async(input:{operation:Record})=>input.operation.refreshRetirementReceipt?{retirementReceiptJws:compactJws} + :input.operation.acceptedRetirementReceipt?{acceptedRetirementDigest:receipt.receiptId}:{releasedRetirementDigest:receipt.receiptId}; + if(!ownerAlreadyTransferred){await transferSlackFormRetirement(db,await row(),identity,protocol);await transferSlackFormRetirement(db,await row(),identity,protocol);} + expect(slackFormRetirementHistoryReceipt(await row())).not.toBeNull(); + const history=Array.from({length:1005},(_,index)=>({id:`b1000000-0000-4000-8000-${String(index).padStart(12,"0")}`,companyId,endpointId, + kind:"slack_form_grant",providerActionId:"slack-form-grant-history:"+index,status:"cancelled", + payload:{binding,environment:identity.environment,subject:actorId},result:{phase:"transferred",nextAttemptAt:null, + retirement:{version:1,binding,instanceId:identity.instanceId,environment:identity.environment,subject:actorId,receiptDigest:receipt.receiptId,receipt}}})); + for(const entry of history)expect(slackFormRetirementHistoryReceipt(entry)).not.toBeNull(); + await db.insert(chatActions).values(history); + return{history,receipt}; + } + async function inspectHistory(abortBeforeRead?:number) { + const capabilities=signedRetainedHistoryCapabilities(),unregister=registerConnectionEventWake(db,()=>{}); + let reads=0,selects=0; + try { + return await db.transaction(async tx=>{ + const select=vi.spyOn(tx,"select"); + const started=performance.now(),remaining=()=>{ + const left=2000-(performance.now()-started);if(left<=0)throw new Error("Incoming wake inspection budget exhausted");return Math.max(1,Math.floor(left)); + }; + const beforeRead=async()=>{ + reads++;if(reads===abortBeforeRead)throw new Error("Controlled existing inspection budget exhausted before next page"); + if(reads*2>64)throw new Error("Incoming wake query budget exhausted"); + await tx.execute(sql`SELECT set_config('statement_timeout', ${`${remaining()}ms`}, true)`);remaining(); + }; + try { + const proof=await readSlackIdleIncomingProof(tx,{capabilities,identity,receiverBound:hasConnectionEventWakeReceiver(db),registeredOptions:()=>false,beforeRead,remaining}); + const check=idleChatHistoryChecksForOwner(proof?.completedActionIds).find(value=>value.reason==="chat_actions"); + if(!check)throw new Error("Actual chat action owner query absent"); + await beforeRead();const query=typeof check.query==="string"?sql.raw(check.query):check.query; + const blockers=await tx.execute<{count:number}>(sql`SELECT count(*)::int AS count FROM (${query}) retained_history_blockers`); + return{proof,blockers:blockers[0]!.count,reads}; + }finally{selects=select.mock.calls.length;select.mockRestore();} + }); + }finally{unregister();if(abortBeforeRead!==undefined){expect(reads).toBe(abortBeforeRead);expect(selects).toBe(abortBeforeRead-1);}} + } + it("more than one page of valid finished Slack custody remains provable by the real incoming and action owners",async()=>{ + const{history}=await finishedHistory();const result=await inspectHistory(); + expect(result.proof?.completedActionIds).toEqual([actionId,...history.map(entry=>entry.id)].sort()); + expect(result.proof?.endpointIds).toEqual([]);expect(result.proof?.connectionIds).toEqual([]); + expect(result.blockers).toBe(0);expect(result.reads).toBeGreaterThanOrEqual(5); + },15000); + for(const fault of ["unfinished","malformed","foreign_company"] as const)it(`a ${fault} receipt after the first completed history page still blocks the actual action owner`,async()=>{ + const{history,receipt}=await finishedHistory(),id="ffffffff-ffff-4fff-bfff-ffffffffffff",last=history.at(-1)!; + const payload=fault==="foreign_company"?{...last.payload,binding:{...binding,companyId:randomUUID()}}:last.payload; + const result=fault==="unfinished"?{phase:"issued",nextAttemptAt:null}:fault==="malformed" + ?{...last.result,retirement:{...last.result.retirement,receipt:{...receipt,receiptId:"not-a-retirement-digest"}}}:last.result; + await db.insert(chatActions).values({...last,id,providerActionId:"slack-form-grant-history:last",status:fault==="unfinished"?"issued":last.status,payload,result}); + const inspected=await inspectHistory();expect(inspected.proof?.completedActionIds).toHaveLength(1006); + expect(inspected.proof?.completedActionIds).not.toContain(id);expect(inspected.blockers).toBe(1); + },15000); + it("a deadline before the next history page refuses proof without issuing that read",async()=>{ + await finishedHistory();await expect(inspectHistory(4)).rejects.toThrow("Controlled existing inspection budget exhausted before next page"); + },15000); + + it("a finished session on a later page certifies only its exact earlier open and submit actions",async()=>{ + const ack=await acceptedAckForRefresh("ffffffff-ffff-4fff-bfff-fffffffffffe"); + const readAck=async()=>(await db.select().from(chatActions).where(eq(chatActions.id,ack.id)))[0]!; + const work=parseSlackFormAckWork((await readAck()).result?.formAck); + if(!work.receipt)throw new Error("Normal retained ACK fixture lost its receipt"); + const digest=slackFormFinalizedReceiptDigest(work.receipt); + const protocol=async(input:{operation:Record})=>input.operation.refreshAckReceipt?{ackReceiptJws:ack.currentJws} + :input.operation.acceptedAckReceipt?{acceptedReceiptDigest:digest,needsTerminalOriginal:false}:{releasedAckDigest:digest}; + await transferSlackFormAckReceipt(db,{companyId,actionId:ack.id,instanceId:identity.instanceId,protocol}); + await transferSlackFormAckReceipt(db,{companyId,actionId:ack.id,instanceId:identity.instanceId,protocol}); + const finished=await readAck();expect(parseSlackFormAckWork(finished.result?.formAck).phase).toBe("transferred"); + const openId="00000000-0000-4000-8000-000000000001",submitId="00000000-0000-4000-8000-000000000002"; + const payload={interactionId:finished.payload.interactionId,publicationId:finished.payload.publicationId}; + await db.insert(chatActions).values([ + {id:openId,companyId,endpointId,kind:"question_form_open",status:"processed",providerActionId:"slack-history-linked-open",payload}, + {id:submitId,companyId,endpointId,kind:"question_form_submit",status:"processed",providerActionId:"slack-history-linked-submit",payload}]); + await db.update(chatActions).set({payload:{...finished.payload,openActionRowId:openId,submitActionRowId:submitId}}).where(eq(chatActions.id,ack.id)); + await finishedHistory(true); + const proof=await inspectHistory();expect(proof.proof?.completedActionIds).toHaveLength(1009);expect(proof.blockers).toBe(0); + expect(proof.proof?.completedActionIds).toEqual(expect.arrayContaining([ack.id,openId,submitId])); + await db.update(chatActions).set({payload:{...payload,publicationId:"changed-retained-publication"}}).where(eq(chatActions.id,openId)); + const changed=await inspectHistory();expect(changed.proof?.completedActionIds).not.toContain(openId);expect(changed.blockers).toBe(1); + },15000); + // Seed retained accepted ACK custody, as in the existing GC controls; this is not a provider-delivery proof. - async function acceptedAckForRefresh() { + async function acceptedAckForRefresh(appReceiptId=randomUUID()) { await acceptSlackFormRetirementLocally(db, await row(), identity, compactJws); const digest = slackFormRetirementReceipt(binding, identity.environment, actorId).receiptId; const retire = async (input: { operation: Record }) => input.operation.refreshRetirementReceipt @@ -101,7 +205,7 @@ if (process.env.SLACK_GATE_EXPECT_PRELOAD === "1" && !external) throw new Error( ? { acceptedRetirementDigest: digest } : { releasedRetirementDigest: digest }; await transferSlackFormRetirement(db, await row(), identity, retire); await transferSlackFormRetirement(db, await row(), identity, retire); - const id = randomUUID(), operationId = "e".repeat(64), deliveryId = `slack_form_${operationId}`, now = new Date().toISOString(); + const id = appReceiptId, operationId = "e".repeat(64), deliveryId = `slack_form_${operationId}`, now = new Date().toISOString(); const originalBody = JSON.stringify({ type: "block_actions", user: { id: "UTEST" } }); const timestamp = String(Math.floor(Date.now() / 1000)); const original = { rawBody: Buffer.from(originalBody).toString("base64"), timestamp, diff --git a/server/src/services/chat-channels/idle-history-proof.ts b/server/src/services/chat-channels/idle-history-proof.ts index 5e2ca3ffce4..31e23ecd1db 100644 --- a/server/src/services/chat-channels/idle-history-proof.ts +++ b/server/src/services/chat-channels/idle-history-proof.ts @@ -136,9 +136,10 @@ export const idleChatHistoryChecks = [ export function idleChatHistoryChecksForOwner(completedActionIds: readonly string[] = []): readonly { reason: string; query: string | SQL }[] { if (!completedActionIds.length) return idleChatHistoryChecks; const ids = [...new Set(completedActionIds)]; - if (ids.length > 1000 || ids.some(id => !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(id))) throw new Error("Invalid completed chat action identity"); + if (ids.some(id => !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(id))) throw new Error("Invalid completed chat action identity"); const normal = completedAction("a"); - const completed = sql`(${sql.raw(normal)}) OR (${sql.raw(actionGraph("a"))} AND a.id IN (${sql.join(ids.map(id => sql`${id}::uuid`), sql`, `)}))`; + // One bound UUID array; no retained-history-sized SQL literal/parameter list. + const completed = sql`(${sql.raw(normal)}) OR (${sql.raw(actionGraph("a"))} AND a.id IN (SELECT completed.id FROM unnest(${sql.param(ids)}::uuid[]) AS completed(id)))`; return idleChatHistoryChecks.map(check => { if (check.reason !== "chat_actions" && check.reason !== "chat_deliveries") return check; const pieces = check.query.split(normal); diff --git a/server/src/services/chat-channels/slack/form-idle-history.ts b/server/src/services/chat-channels/slack/form-idle-history.ts index 2cf31d1210a..da10215d85b 100644 --- a/server/src/services/chat-channels/slack/form-idle-history.ts +++ b/server/src/services/chat-channels/slack/form-idle-history.ts @@ -7,44 +7,71 @@ import { parseSlackFormBinding, parseSlackFormPublicEnrollment, sameSlackFormBin import { parseSlackFormAckWork, assertSlackFormReceiptHistory } from "./form-ack-work.js"; export type SlackFormHistoryRow = Pick; -export function completedSlackFormHistoryActionIds(rows: readonly SlackFormHistoryRow[], companyId: string, endpointId: string, coverage?: { requirements: readonly SlackConfiguredRequirement[]; verified: VerifiedIdleCapabilities; expected: { instanceId: string; generation: string; environment: string } }): readonly string[] { - const scoped = rows.filter(row => row.companyId === companyId && row.endpointId === endpointId); - const completed = new Set(); +export type SlackFormHistoryCoverage = { requirements: readonly SlackConfiguredRequirement[]; verified: VerifiedIdleCapabilities; + expected: { instanceId: string; generation: string; environment: string }; currentOwners?: ReadonlyMap }; + +/** Prepare bounded current coverage once; history pages retain no protocol rows. + * Session-related actions are supplied from the same page or indexed DB joins. + */ +export function createSlackFormHistoryClassifier(coverage?: SlackFormHistoryCoverage) { const matched = coverage ? matchSlackConfiguredCoverage(coverage.requirements, coverage.verified, coverage.expected) : undefined; - for (const row of scoped) { - if (!["slack_form_owner", "slack_form_grant"].includes(row.kind) || row.result?.nextAttemptAt !== null) continue; - try { - if (row.result?.phase === "transferred") { - if (slackFormRetirementHistoryReceipt(row)) completed.add(row.id); - continue; - } - const binding = parseSlackFormBinding(row.payload.binding); - if (binding.companyId !== companyId || binding.endpointId !== endpointId) continue; - if (!coverage || !matched?.endpointIds.includes(endpointId) || !matched.connectionIds.includes(binding.connectionId) - || row.payload.environment !== coverage.expected.environment || !coverage.requirements.some(requirement => sameSlackFormBinding(requirement.binding, binding))) continue; - if (row.kind === "slack_form_owner" && row.result?.phase === "enrolled" || row.kind === "slack_form_grant" && row.result?.phase === "published") completed.add(row.id); - } catch { continue; } - } - for (const session of scoped) { - if (session.kind !== "slack_form_session" || !["processed", "cancelled", "failed"].includes(session.status)) continue; - try { - const binding = parseSlackFormBinding(session.payload.binding), work = parseSlackFormAckWork(session.result?.formAck); - if (session.status === "failed" && work.receipt?.outcome !== "no_effect") continue; - if (binding.companyId !== companyId || binding.endpointId !== endpointId || work.phase !== "transferred" || !work.receiptJws || !work.receipt - || session.result?.nextAttemptAt !== null) continue; - const receipt = work.receipt; - assertSlackFormReceiptHistory(session, receipt); - completed.add(session.id); - for (const action of scoped) { - if (!["question_form_open", "question_form_submit"].includes(action.kind) || action.status !== "processed" - || action.conversationId !== session.conversationId || action.principalId !== session.principalId) continue; - const expected = action.kind === "question_form_open" ? session.payload.openActionRowId : session.payload.submitActionRowId; - if (action.id === expected && action.payload.interactionId === session.payload.interactionId - && action.payload.publicationId === session.payload.publicationId) completed.add(action.id); - } - } catch { continue; } - } - return [...completed].sort(); + const endpoints = new Set(matched?.endpointIds), connections = new Set(matched?.connectionIds); + const bindings = new Map(coverage?.requirements.map(requirement => [ + `${requirement.binding.companyId}:${requirement.binding.endpointId}`, requirement.binding])); + return (rows: readonly SlackFormHistoryRow[], companyId: string, endpointId: string, check?: () => void): readonly string[] => { + const scoped: SlackFormHistoryRow[] = [], byId = new Map(); + for (const row of rows) { + check?.(); + if (row.companyId !== companyId || row.endpointId !== endpointId) continue; + const prior = byId.get(row.id); + if (prior && !isDeepStrictEqual(prior, row)) return []; + if (!prior) { scoped.push(row); byId.set(row.id, row); } + } + const completed = new Set(); + for (const row of scoped) { + check?.(); + if (!["slack_form_owner", "slack_form_grant"].includes(row.kind) || row.result?.nextAttemptAt !== null) continue; + try { + if (row.result?.phase === "transferred") { + if (slackFormRetirementHistoryReceipt(row)) completed.add(row.id); + continue; + } + const binding = parseSlackFormBinding(row.payload.binding); + const current = bindings.get(`${companyId}:${endpointId}`); + if (binding.companyId !== companyId || binding.endpointId !== endpointId || !coverage + || !endpoints.has(endpointId) || !connections.has(binding.connectionId) + || row.payload.environment !== coverage.expected.environment || !current || !sameSlackFormBinding(current, binding)) continue; + if (row.kind === "slack_form_owner" && row.result?.phase === "enrolled") { + // Owner uniqueness was certified separately. A new or changed owner + // between keyset passes remains unclassified for the fresh shared gate. + if (!coverage.currentOwners || isDeepStrictEqual(coverage.currentOwners.get(row.id), row)) completed.add(row.id); + } else if (row.kind === "slack_form_grant" && row.result?.phase === "published") completed.add(row.id); + } catch { continue; } + } + for (const session of scoped) { + check?.(); + if (session.kind !== "slack_form_session" || !["processed", "cancelled", "failed"].includes(session.status)) continue; + try { + const binding = parseSlackFormBinding(session.payload.binding), work = parseSlackFormAckWork(session.result?.formAck); + if (session.status === "failed" && work.receipt?.outcome !== "no_effect") continue; + if (binding.companyId !== companyId || binding.endpointId !== endpointId || work.phase !== "transferred" || !work.receiptJws || !work.receipt + || session.result?.nextAttemptAt !== null) continue; + assertSlackFormReceiptHistory(session, work.receipt); + completed.add(session.id); + for (const [kind, id] of [["question_form_open", session.payload.openActionRowId], ["question_form_submit", session.payload.submitActionRowId]] as const) { + const action = typeof id === "string" ? byId.get(id) : undefined; + if (action?.kind === kind && action.status === "processed" && action.conversationId === session.conversationId + && action.principalId === session.principalId && action.payload.interactionId === session.payload.interactionId + && action.payload.publicationId === session.payload.publicationId) completed.add(action.id); + } + } catch { continue; } + } + return [...completed].sort(); + }; +} + +export function completedSlackFormHistoryActionIds(rows: readonly SlackFormHistoryRow[], companyId: string, endpointId: string, coverage?: SlackFormHistoryCoverage): readonly string[] { + return createSlackFormHistoryClassifier(coverage)(rows, companyId, endpointId); } export function completedSlackFormSessionReceipt(session: Pick) { diff --git a/server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts b/server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts index a02a1184ae2..ef7f9e3f13c 100644 --- a/server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts +++ b/server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts @@ -10,12 +10,21 @@ it("the same validated bound action identity appears in action and delivery quer for (const reason of ["chat_actions", "chat_deliveries"]) { const check = checks.find(check => check.reason === reason); if (!check || typeof check.query === "string") throw new Error("Parameterized owner query missing"); const rendered = new PgDialect().sqlToQuery(check.query); - expect(rendered.params).toEqual([id]); + expect(rendered.params).toEqual([[id]]); expect(rendered.sql).not.toContain(id); expect(rendered.sql).toContain("e.company_id = a.company_id"); expect(rendered.sql).toContain("d.company_id = a.company_id"); - expect(rendered.sql).toContain("a.id IN ($1::uuid)"); + expect(rendered.sql).toContain("unnest($1::uuid[])"); } expect(() => idleChatHistoryChecksForOwner(["foreign' OR true"])).toThrow(); - expect(() => idleChatHistoryChecksForOwner(Array.from({ length: 1001 }, (_, index) => `11111111-1111-4111-8111-${String(index).padStart(12, "0")}`))).toThrow(); + +}); + +it("retained completion identity counts do not become SQL literal or parameter ceilings",()=>{ + const ids=Array.from({length:65536},(_,index)=>`11111111-1111-4111-8111-${String(index).padStart(12,"0")}`); + const check=idleChatHistoryChecksForOwner(ids).find(value=>value.reason==="chat_actions"); + if(!check||typeof check.query==="string")throw new Error("Parameterized owner query absent"); + const rendered=new PgDialect().sqlToQuery(check.query); + expect(rendered.params).toEqual([ids]);expect(rendered.sql).not.toContain(ids[0]); + expect(rendered.sql).toContain("unnest($1::uuid[])"); }); diff --git a/server/src/services/chat-channels/slack/idle-incoming.test.ts b/server/src/services/chat-channels/slack/idle-incoming.test.ts index c252fff411f..777ce540fde 100644 --- a/server/src/services/chat-channels/slack/idle-incoming.test.ts +++ b/server/src/services/chat-channels/slack/idle-incoming.test.ts @@ -1,3 +1,4 @@ +import { slackFormRetirementReceipt } from "./ack-retirement-receipt.js"; import { generateKeyPairSync, randomUUID, sign } from "node:crypto"; import { expect, it } from "vitest"; import type { Db } from "@paperclipai/db"; @@ -44,8 +45,20 @@ it("genuinely signed forms-events-only coverage keeps default commands and gener const result = projectSlackIdleIncomingRows({ ...rows(), capabilities: verifiedPartial(), identity: { instanceId: binding.instanceId, environment: "test" }, registeredOptions: () => false }); expect(result).toEqual({ endpointIds: [], connectionIds: [], completedActionIds: [] }); }); -it("foreign company and1001 rows never become current Slack completion authority", () => { +it("foreign company and duplicate current owners never become current Slack completion authority", () => { const current = rows(), capabilities = verifiedPartial(), common = { capabilities, identity: { instanceId: binding.instanceId, environment: "test" as const }, registeredOptions: () => false }; expect(projectSlackIdleIncomingRows({ ...current, ...common, endpoints: [{ ...current.endpoints[0]!, connection: { ...current.endpoints[0]!.connection, companyId: "foreign" } }] })).toBeUndefined(); expect(projectSlackIdleIncomingRows({ ...current, ...common, actions: Array.from({ length: 1001 }, () => current.actions[0]!) })).toBeUndefined(); }); + +it("retained completed receipts exceed one history page without enlarging the current endpoint cap", () => { + const current=rows(),receipt=slackFormRetirementReceipt(binding,"test","actor"); + const history:SlackFormHistoryRow[]=Array.from({length:1005},()=>({id:randomUUID(),companyId:binding.companyId,endpointId:binding.endpointId, + kind:"slack_form_grant",principalId:null,conversationId:null,status:"cancelled",providerActionId:"slack-form-grant:"+randomUUID(), + payload:{binding,subject:"actor",environment:"test"},result:{phase:"transferred",nextAttemptAt:null, + retirement:{version:1,binding,instanceId:binding.instanceId,environment:"test",subject:"actor",receiptDigest:receipt.receiptId,receipt}}})); + const common={capabilities:verifiedPartial(),identity:{instanceId:binding.instanceId,environment:"test" as const},registeredOptions:()=>false}; + const result=projectSlackIdleIncomingRows({...current,...common,actions:[...current.actions,...history]}); + expect(result?.completedActionIds).toEqual(history.map(row=>row.id).sort()); + expect(projectSlackIdleIncomingRows({...current,...common,endpoints:Array.from({length:1001},()=>current.endpoints[0]!)})).toBeUndefined(); +}); diff --git a/server/src/services/chat-channels/slack/idle-incoming.ts b/server/src/services/chat-channels/slack/idle-incoming.ts index 37d72521acd..262416c7e1d 100644 --- a/server/src/services/chat-channels/slack/idle-incoming.ts +++ b/server/src/services/chat-channels/slack/idle-incoming.ts @@ -1,10 +1,11 @@ import { isDeepStrictEqual } from "node:util"; -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, eq, gt, inArray, sql } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; import { chatActions, chatEndpoints, toolConnections, type Db } from "@paperclipai/db"; import type { VerifiedIdleCapabilities } from "../../idle-incoming-wake-capability.js"; import { parseSlackFormBinding, parseSlackFormPublicEnrollment, slackFormSetupRecord, sameSlackFormBinding } from "./cloud-forms.js"; import { matchSlackConfiguredCoverage, type SlackConfiguredRequirement } from "./configured-coverage.js"; -import { completedSlackFormHistoryActionIds, type SlackFormHistoryRow } from "./form-idle-history.js"; +import { createSlackFormHistoryClassifier, type SlackFormHistoryRow } from "./form-idle-history.js"; import type { SlackFormConnectorIdentity } from "./cloud-consumer.js"; export type SlackIdleEndpoint = Pick & { setup: unknown; capabilities: unknown }; @@ -18,12 +19,14 @@ function object(value: unknown): Record { function flag(value: Record, key: string): boolean { const v = value[key]; if (typeof v !== "boolean") throw new Error("Unknown Slack configured capability"); return v; } -export function projectSlackIdleIncomingRows(input: { +type SlackIncomingRowsInput = { endpoints: readonly { endpoint: SlackIdleEndpoint; connection: SlackIdleConnection }[]; actions: readonly SlackFormHistoryRow[]; capabilities: VerifiedIdleCapabilities; identity: SlackFormConnectorIdentity; registeredOptions(endpointId: string): boolean; check?(): void; -}): SlackIdleIncomingProjection | undefined { - if (input.endpoints.length > 1000 || input.actions.length > 1000 || !input.capabilities.incomingWake?.routes.includes("slack-broker-events-v1")) return; - const requirements: SlackConfiguredRequirement[] = [], endpointIds = new Set(); +}; +function slackIncomingContext(input: SlackIncomingRowsInput) { + if (input.endpoints.length > 1000 || !input.capabilities.incomingWake?.routes.includes("slack-broker-events-v1")) return; + const requirements: SlackConfiguredRequirement[] = [], endpointIds = new Set(), currentOwners = new Map(); + const groups = groupHistory(input.actions); try { for (const { endpoint, connection } of input.endpoints) { input.check?.(); @@ -40,25 +43,54 @@ export function projectSlackIdleIncomingRows(input: { runtimeGeneration: descriptor.runtimeGeneration, bindingId: descriptor.bindingId, teamId: descriptor.teamId, appId: descriptor.appId }); const { credentialFingerprint: _, eventBindingId, ...base } = binding; if (!isDeepStrictEqual({ ...base, bindingId: eventBindingId }, enrollment)) return; - const owners = input.actions.filter(row => row.companyId === endpoint.companyId && row.endpointId === endpoint.id && row.kind === "slack_form_owner" + const owners = (groups.get(`${endpoint.companyId}:${endpoint.id}`) ?? []).filter(row => row.companyId === endpoint.companyId && row.endpointId === endpoint.id && row.kind === "slack_form_owner" && /^slack-form-owner:[a-f0-9]{64}$/.test(row.providerActionId) && row.result?.phase === "enrolled" && row.result.nextAttemptAt === null && row.result.desiredActive !== false && ["issued", "processed"].includes(row.status) && row.payload.environment === input.identity.environment && row.payload.subject === setup.slackCloudSubject && isDeepStrictEqual(row.payload.binding, binding) && isDeepStrictEqual(row.payload.enrollment, enrollment)); if (owners.length !== 1) return; + currentOwners.set(owners[0]!.id, owners[0]!); requirements.push({ binding, capabilities: { actions: flag(capabilities, "actions"), modals: flag(capabilities, "modals"), slashCommands: flag(capabilities, "slashCommands") }, registeredOptions }); } const expected = { ...input.identity, generation: input.capabilities.incomingWake.generation }; const matched = matchSlackConfiguredCoverage(requirements, input.capabilities, expected); - const completed = new Set(); - for (const { endpoint } of input.endpoints) { - input.check?.(); - const ids = completedSlackFormHistoryActionIds(input.actions, endpoint.companyId, endpoint.id, - { requirements, verified: input.capabilities, expected }); - for (const id of ids) { if (!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(id)) return; completed.add(id); } - } - return Object.freeze({ endpointIds: Object.freeze([...(matched?.endpointIds ?? [])]), connectionIds: Object.freeze([...(matched?.connectionIds ?? [])]), completedActionIds: Object.freeze([...completed].sort()) }); + return { requirements, expected, matched, currentOwners }; } catch { return; } } + +function groupHistory(rows: readonly SlackFormHistoryRow[]) { + const groups = new Map(); + for (const row of rows) { + const key = `${row.companyId}:${row.endpointId}`, group = groups.get(key); + if (group) group.push(row); else groups.set(key, [row]); + } + return groups; +} +function projection(context: NonNullable>, completed: Set): SlackIdleIncomingProjection { + return Object.freeze({ endpointIds: Object.freeze([...(context.matched?.endpointIds ?? [])]), + connectionIds: Object.freeze([...(context.matched?.connectionIds ?? [])]), completedActionIds: Object.freeze([...completed].sort()) }); +} +export function projectSlackIdleIncomingRows(input: SlackIncomingRowsInput): SlackIdleIncomingProjection | undefined { + try { + const context = slackIncomingContext(input); + if (!context) return; + const classify = createSlackFormHistoryClassifier({ requirements: context.requirements, verified: input.capabilities, expected: context.expected, currentOwners: context.currentOwners }); + const groups = groupHistory(input.actions), completed = new Set(); + for (const { endpoint } of input.endpoints) { + input.check?.(); + for (const id of classify(groups.get(`${endpoint.companyId}:${endpoint.id}`) ?? [], endpoint.companyId, endpoint.id, input.check)) { + if (!uuid.test(id)) return; completed.add(id); + } + } + return projection(context, completed); + } catch { return; } +} +const uuid = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i; +const pageSize = 1000; +const historyOpen = alias(chatActions, "slack_idle_history_open"), historySubmit = alias(chatActions, "slack_idle_history_submit"); +const relatedId = (key: "openActionRowId" | "submitActionRowId") => sql`CASE + WHEN ${chatActions.payload}->>${key} ~* '^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$' + THEN (${chatActions.payload}->>${key})::uuid ELSE NULL END`; + export async function readSlackIdleIncomingProof(tx: Pick, input: { capabilities?: VerifiedIdleCapabilities; identity?: SlackFormConnectorIdentity; receiverBound: boolean; beforeRead(): Promise; remaining(): number; registeredOptions(endpointId: string): boolean; @@ -74,15 +106,70 @@ export async function readSlackIdleIncomingProof(tx: Pick, input: input.remaining(); if (endpoints.length > 1000) return; if (!endpoints.length && broker.entries.length) return; if (!endpoints.length) return Object.freeze({ endpointIds: [], connectionIds: [], completedActionIds: [] }); - await input.beforeRead(); - const actions = await tx.select({ action: chatActions }).from(chatActions).innerJoin(chatEndpoints, - and(eq(chatEndpoints.id, chatActions.endpointId), eq(chatEndpoints.companyId, chatActions.companyId))) - .where(and(eq(chatEndpoints.provider, "slack"), inArray(chatActions.endpointId, endpoints.map(value => value.endpoint.id)), - inArray(chatActions.kind, ["slack_form_owner", "slack_form_grant", "slack_form_session", "question_form_open", "question_form_submit"]))) - .orderBy(chatActions.id).limit(1001); - input.remaining(); if (actions.length > 1000) return; - const projection = projectSlackIdleIncomingRows({ endpoints, actions: actions.map(row => row.action), capabilities: input.capabilities, - identity: input.identity, registeredOptions: input.registeredOptions, check: () => { input.remaining(); } }); + // Retain only bounded current-owner candidates. Old enrolled generations do + // not become current coverage, and duplicate exact owners on ANY page fail. + const endpointsById = new Map(endpoints.map(value => [value.endpoint.id, value])); + const currentOwners = new Map(); + let ownerCursor: string | undefined; + for (;;) { + await input.beforeRead(); + const page = await tx.select({ action: chatActions }).from(chatActions).innerJoin(chatEndpoints, + and(eq(chatEndpoints.id, chatActions.endpointId), eq(chatEndpoints.companyId, chatActions.companyId))) + .where(and(eq(chatEndpoints.provider, "slack"), inArray(chatActions.endpointId, endpoints.map(value => value.endpoint.id)), + eq(chatActions.kind, "slack_form_owner"), sql`${chatActions.result}->>'phase'='enrolled'`, + ownerCursor ? gt(chatActions.id, ownerCursor) : undefined)) + .orderBy(chatActions.id).limit(pageSize); + input.remaining(); + for (const { action } of page) { + input.remaining(); + const scope = endpointsById.get(action.endpointId); + if (!scope || action.companyId !== scope.endpoint.companyId || scope.endpoint.status !== "active" + || scope.connection.status !== "active" || !scope.connection.enabled) continue; + try { + const setup = slackFormSetupRecord(scope.endpoint.setup), binding = parseSlackFormBinding(setup.slackCloudForms); + if (!/^slack-form-owner:[a-f0-9]{64}$/.test(action.providerActionId) || !["issued", "processed"].includes(action.status) + || action.result?.nextAttemptAt !== null || action.result.desiredActive === false || action.payload.environment !== input.identity.environment + || action.payload.subject !== setup.slackCloudSubject || !sameSlackFormBinding(parseSlackFormBinding(action.payload.binding), binding)) continue; + const enrollment = parseSlackFormPublicEnrollment(action.payload.enrollment); + const { credentialFingerprint: _, eventBindingId, ...base } = binding; + if (!isDeepStrictEqual({ ...base, bindingId: eventBindingId }, enrollment)) continue; + const owners = currentOwners.get(action.endpointId) ?? []; + owners.push(action); if (owners.length > 1) return; + currentOwners.set(action.endpointId, owners); + } catch { continue; } + } + if (page.length < pageSize) break; + ownerCursor = page.at(-1)!.action.id; + } + const common = { endpoints, capabilities: input.capabilities, identity: input.identity, + registeredOptions: input.registeredOptions, check: () => { input.remaining(); } }; + const context = slackIncomingContext({ ...common, actions: [...currentOwners.values()].flat() }); + if (!context) return; + const classify = createSlackFormHistoryClassifier({ requirements: context.requirements, verified: input.capabilities, expected: context.expected, currentOwners: context.currentOwners }); + const completed = new Set(); let cursor: string | undefined; + for (;;) { + await input.beforeRead(); + // Indexed primary-key joins supply only the two referenced actions. A + // session/page boundary never requires an all-history JSON accumulator or + // one extra read per historical session. + const page = await tx.select({ action: chatActions, open: historyOpen, submit: historySubmit }).from(chatActions) + .innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatActions.endpointId), eq(chatEndpoints.companyId, chatActions.companyId))) + .leftJoin(historyOpen, and(eq(chatActions.kind, "slack_form_session"), eq(historyOpen.kind, "question_form_open"), eq(historyOpen.id, relatedId("openActionRowId")), eq(historyOpen.companyId, chatActions.companyId), eq(historyOpen.endpointId, chatActions.endpointId))) + .leftJoin(historySubmit, and(eq(chatActions.kind, "slack_form_session"), eq(historySubmit.kind, "question_form_submit"), eq(historySubmit.id, relatedId("submitActionRowId")), eq(historySubmit.companyId, chatActions.companyId), eq(historySubmit.endpointId, chatActions.endpointId))) + .where(and(eq(chatEndpoints.provider, "slack"), inArray(chatActions.endpointId, endpoints.map(value => value.endpoint.id)), + inArray(chatActions.kind, ["slack_form_owner", "slack_form_grant", "slack_form_session", "question_form_open", "question_form_submit"]), + cursor ? gt(chatActions.id, cursor) : undefined)).orderBy(chatActions.id).limit(pageSize); + input.remaining(); + const groups = groupHistory(page.flatMap(row => [row.action, ...(row.open ? [row.open] : []), ...(row.submit ? [row.submit] : [])])); + for (const rows of groups.values()) { + input.remaining(); const first = rows[0]!; + for (const id of classify(rows, first.companyId, first.endpointId, () => { input.remaining(); })) { + if (!uuid.test(id)) return; completed.add(id); + } + } + if (page.length < pageSize) break; + cursor = page.at(-1)!.action.id; + } input.remaining(); - return projection; + return projection(context, completed); }