From dd492444179f9c44845f27e95225403abb39f8eb Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 14 Nov 2026 12:44:36 -0600 Subject: [PATCH] fix(photon): preserve custody across authorized operator changes --- doc/connections/IMESSAGE-PHOTON.md | 4 +- .../photon/channel.integration.test.ts | 38 +++++++++++++++++-- .../imessage-photon/external-runtime.ts | 13 ++++++- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/doc/connections/IMESSAGE-PHOTON.md b/doc/connections/IMESSAGE-PHOTON.md index e8bff377491..e11a7a60f74 100644 --- a/doc/connections/IMESSAGE-PHOTON.md +++ b/doc/connections/IMESSAGE-PHOTON.md @@ -180,7 +180,9 @@ actual history gap stops in Attention. Initial historical messages establish a checkpoint but do not create old tasks automatically. Pause stops execution and external publication while retaining already accepted -pending work. Resume establishes a new intake cutoff, so messages deliberately +pending work. Another authorized operator can resume an existing handoff without +replacing its original ownership. Connection-management permissions are checked +for each configuration change. Resume establishes a new intake cutoff, so messages deliberately suppressed during pause do not become work. Outage recovery catches up eligible missed messages. Disconnect archives the endpoint, stops streams, invalidates interaction authority, and removes owned secret bindings. It does not delete the diff --git a/server/src/__tests__/photon/channel.integration.test.ts b/server/src/__tests__/photon/channel.integration.test.ts index a2e937079dd..2f7b7364458 100644 --- a/server/src/__tests__/photon/channel.integration.test.ts +++ b/server/src/__tests__/photon/channel.integration.test.ts @@ -1,3 +1,4 @@ +import { connectionManagementService } from "../../services/connection-management.js"; import { currentControllerProcess } from "../../services/controller-process-identity.js"; import { photonCoverageFingerprint } from "../../services/chat-channels/imessage-photon/idle-coverage.js"; import { readIdleIncomingWakeProof } from "../../services/idle-incoming-wake.js"; @@ -1029,7 +1030,7 @@ describe("iMessage Photon channel control plane", () => { () => onlinePhotonEnrollment(false, true), 30_000); it("fences late connector loss at the normal Photon SDK intake-placement callback and restores its original handoff", () => onlinePhotonEnrollment(false, false, true), 30_000); - async function resumeOriginalHandoff(phase: "enrolling" | "joining", observeIdleRenewal = false) { + async function resumeOriginalHandoff(phase: "enrolling" | "joining", observeIdleRenewal = false, otherAuthorizedOperator = false) { const renew = vi.fn(async () => true); const signing = generateKeyPairSync("ed25519"), sealing = generateKeyPairSync("x25519"); const connectorConfig = { baseUrl: "https://cloud.example", instanceId: "instance", environment: "test" as const, @@ -1066,8 +1067,10 @@ describe("iMessage Photon channel control plane", () => { return observedOwner; }); const requests: Record[] = []; + const requestSubjects: string[] = []; let endpointId: string | undefined, companyId: string | undefined; - vi.spyOn(connector, "photonReceiverOperation").mockImplementation(async ({ operation }) => { + vi.spyOn(connector, "photonReceiverOperation").mockImplementation(async ({ operation, subject }) => { + requestSubjects.push(subject); requests.push(structuredClone(operation)); if (!endpointId || !companyId || operation.kind !== "enroll") throw new Error("Unexpected controlled broker operation"); const retained = readPhotonExternalState(await photonStateFor(db, { companyId, endpointId }).read(PHOTON_EXTERNAL_STATE)); @@ -1104,13 +1107,32 @@ describe("iMessage Photon channel control plane", () => { const [before] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id)); const [connectionBefore] = await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId)); expect(before.status).toBe("active"); - await t.service.configure(t.endpoint.id, { action: "pause" }, t.userId); + let operatorUserId = t.userId; + if (otherAuthorizedOperator) { + operatorUserId = randomUUID(); + await db.insert(authUsers).values({ id: operatorUserId, name: "Second operator", email: `${operatorUserId}@example.com`, + emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId: t.companyId, principalType: "user", principalId: operatorUserId, + status: "active", membershipRole: "operator" }); + await db.insert(principalPermissionGrants).values({ companyId: t.companyId, principalType: "user", principalId: operatorUserId, + permissionKey: "tools:manage_connections", grantedByUserId: t.userId }); + } + const management = otherAuthorizedOperator ? await connectionManagementService(db).authorize( + { type: "board", userId: operatorUserId, source: "session" }, "connections:configure", + { type: "connection_management", companyId: t.companyId, connectionId: t.endpoint.connectionId, + provider: "imessage-photon", purpose: "chat", operation: "POST /chat-endpoints/:endpointId/configure" }, { mutation: true }) : undefined; + if (management) { + expect(management.responsibleUserId).toBe(operatorUserId); + expect(management.decision).toMatchObject({ allowed: true, action: "connections:configure" }); + expect(operatorUserId).not.toBe(original.identity.subject); + } + await t.service.configure(t.endpoint.id, { action: "pause" }, operatorUserId, management); const [paused] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id)); expect(paused.status).toBe("paused"); expect(Reflect.get(paused.setup, "runtimeGeneration")).toBe(Reflect.get(before.setup, "runtimeGeneration")); expect(readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE))) .toMatchObject({ phase, binding: original.binding, handoffId: original.handoffId, identity: original.identity }); - const outcome = await t.service.configure(t.endpoint.id, { action: "resume" }, t.userId) + const outcome = await t.service.configure(t.endpoint.id, { action: "resume" }, operatorUserId, management) .then(snapshot => ({ snapshot, error: null }), error => ({ snapshot: null, error })); const [resumed] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id)); const [connectionResumed] = await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId)); @@ -1123,6 +1145,12 @@ describe("iMessage Photon channel control plane", () => { expect(cutoff).toBeGreaterThan(Date.parse(original.binding.intakeAfter)); expect(outcome.error, "normal resume must finish original custody under unchanged authority").toBeNull(); expect(outcome.snapshot).toMatchObject({ status: "active" }); + if (otherAuthorizedOperator) { + expect(Reflect.get(paused.setup, "photonExternalSubject")).toBe(original.identity.subject); + expect(Reflect.get(resumed.setup, "photonExternalSubject")).toBe(original.identity.subject); + expect(requestSubjects).toEqual([original.identity.subject]); + await management!.reauthorize(); + } expect(recovered).toMatchObject({ phase: "external", identity: original.identity, binding: original.binding, handoffId: original.handoffId }); expect(requests).toHaveLength(1); expect(requests[0].enrollment).toMatchObject({ intakeAfter: original.binding.intakeAfter, handoffId: original.handoffId }); @@ -1259,6 +1287,8 @@ describe("iMessage Photon channel control plane", () => { phase => resumeOriginalHandoff(phase), 30_000); it("releases idle Cloud-resume ownership and reacquires it for normal authorized delivery", () => resumeOriginalHandoff("enrolling", true), 30_000); + it.each(["enrolling", "joining"] as const)("preserves original Photon %s custody when another authorized operator pauses and resumes", + phase => resumeOriginalHandoff(phase, false, true), 30_000); it("restores group membership queued during pause before admitting fresh messages after resume", async () => { const t = await setup(); await t.start(); diff --git a/server/src/services/chat-channels/imessage-photon/external-runtime.ts b/server/src/services/chat-channels/imessage-photon/external-runtime.ts index cf7e7058f6d..9cdd25981d5 100644 --- a/server/src/services/chat-channels/imessage-photon/external-runtime.ts +++ b/server/src/services/chat-channels/imessage-photon/external-runtime.ts @@ -697,6 +697,15 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: { * retained SDK state is deliberately untouched until its original owner retires. */ export async function stagePhotonExternalConfiguration(db: Pick, endpointId: string, subject: string | null | undefined) { if (!subject) return; - await db.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{photonExternalSubject}', ${JSON.stringify(subject)}::jsonb)` }) - .where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "imessage-photon"))); + const [endpoint] = await db.select({ companyId: chatEndpoints.companyId }).from(chatEndpoints) + .where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "imessage-photon"))).for("no key update"); + if (!endpoint) return; + const [saved] = await db.select({ value: chatSdkState.value }).from(chatSdkState).where(and( + eq(chatSdkState.companyId, endpoint.companyId), eq(chatSdkState.endpointId, endpointId), eq(chatSdkState.stateKey, stateKey))); + const retained = readPhotonExternalState(saved?.value ?? null); + if (retained && (retained.identity.companyId !== endpoint.companyId || retained.identity.endpointId !== endpointId)) + throw conflict("Photon retained configuration owner changed"); + const custodySubject = retained && retained.phase !== "retired" ? retained.identity.subject : subject; + await db.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{photonExternalSubject}', ${JSON.stringify(custodySubject)}::jsonb)` }) + .where(and(eq(chatEndpoints.companyId, endpoint.companyId), eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "imessage-photon"))); }