mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Capture the live Photon receiver before online handoff
This commit is contained in:
1 parent
f0de21cd7f
commit
07166aef61
3 files changed
+57
-3
No files matched your search
@@ -1,3 +1,8 @@
|
||||
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";
|
||||
import type { VerifiedIdleCapabilities } from "../../services/idle-incoming-wake-capability.js";
|
||||
import { verifyCloudControlAssertion, CLOUD_CONTROL_AUDIENCE, CLOUD_CONTROL_JWS_TYPE, CLOUD_RUNTIME_IDENTITY_ISSUER } from "../../services/cloud-runtime-identity.js";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { createServer, type Server } from "node:http";
|
||||
@@ -17,7 +22,7 @@ import { joinConnectionEventWakeEnrollment } from "../../services/connection-eve
|
||||
import { resolveExternalTestDatabaseUrl } from "../helpers/external-test-database.js";
|
||||
import { Readable } from "node:stream";
|
||||
import type { StorageService } from "../../storage/types.js";
|
||||
import { createHash, createPublicKey, randomUUID, generateKeyPairSync, verify } from "node:crypto";
|
||||
import { createHash, createPublicKey, randomUUID, generateKeyPairSync, sign, verify } from "node:crypto";
|
||||
import { mkdtemp, rm, readFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -783,6 +788,9 @@ describe("iMessage Photon channel control plane", () => {
|
||||
t = await setup(); await t.start(); await t.qualify();
|
||||
const localRuntime = t.service.runtime.get(t.endpoint.id);
|
||||
expect(localRuntime).not.toBeNull();
|
||||
const [originalLease] = await db.select().from(chatEndpointLeases).where(and(
|
||||
eq(chatEndpointLeases.endpointId, t.endpoint.id), eq(chatEndpointLeases.leaseKey, "photon_receiver_runtime")));
|
||||
if (!originalLease) throw new Error("Normal existing local Runtime lease is absent");
|
||||
const [before] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, t.endpoint.id));
|
||||
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, t.endpoint.connectionId));
|
||||
expect(before.status).toBe("active");
|
||||
@@ -860,6 +868,39 @@ describe("iMessage Photon channel control plane", () => {
|
||||
expect(errors).toEqual([]);
|
||||
expect(await db.select().from(chatEndpointLeases).where(and(eq(chatEndpointLeases.endpointId, t.endpoint.id),
|
||||
eq(chatEndpointLeases.leaseKey, "photon_receiver_runtime")))).toEqual([]);
|
||||
if (!recovered) throw new Error("Normal online handoff state is absent");
|
||||
const ownerId = randomUUID(), generation = photonHash([ownerId, recovered.handoffId]);
|
||||
const incomingWake = { version: 1, ownerId, generation, routes: ["photon-broker-events-v1"],
|
||||
photonBroker: { version: 1, instanceId: pending.instanceId, generation, count: 1,
|
||||
bindingsFingerprint: photonCoverageFingerprint([{ binding: recovered.binding, handoffId: recovered.handoffId,
|
||||
subject: recovered.identity.subject, deliveredThrough: recovered.acceptedSequence }]) } };
|
||||
// Controlled Cloud signing authority, verified by the normal production
|
||||
// verifier; not a cast of parsed/unverified coverage or Cloud SDK readiness.
|
||||
const pair = generateKeyPairSync("ed25519"), kid = randomUUID(), issued = Math.floor(Date.now() / 1000);
|
||||
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const header = encode({ alg: "EdDSA", typ: CLOUD_CONTROL_JWS_TYPE, kid });
|
||||
const payload = encode({ v: 1, iss: CLOUD_RUNTIME_IDENTITY_ISSUER, aud: CLOUD_CONTROL_AUDIENCE,
|
||||
sub: pending.instanceId, action: "task-drain:read", requestId: randomUUID(), iat: issued, exp: issued + 60,
|
||||
idleCapabilities: { incomingWake } });
|
||||
const compactJws = `${header}.${payload}.${sign(null, Buffer.from(`${header}.${payload}`), pair.privateKey).toString("base64url")}`;
|
||||
const verified = verifyCloudControlAssertion({ compactJws, expectedAction: "task-drain:read", env: {
|
||||
PAPERCLIP_CLOUD_STACK_ID: pending.instanceId,
|
||||
PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS: JSON.stringify({ keys: [{ ...pair.publicKey.export({ format: "jwk" }), kid, use: "sig", alg: "EdDSA" }] }),
|
||||
} }).idleCapabilities;
|
||||
if (!verified) throw new Error("Normal signed Cloud coverage verification produced no capability");
|
||||
const allocations = vi.spyOn(photonOwnedClients, "createOwnedPhotonClient");
|
||||
const closeCalls = vi.mocked(t.f.client.close).mock.calls.length;
|
||||
const retainedBeforeProof = await state.read(PHOTON_EXTERNAL_STATE);
|
||||
await expect(db.transaction(tx => readIdleIncomingWakeProof(tx, { capabilities: verified as VerifiedIdleCapabilities,
|
||||
ownerId, receiverOwner: db })), "normal online handoff must certify incoming wake after its exact local close")
|
||||
.resolves.toMatchObject({ endpointIds: [t.endpoint.id], connectionIds: [connection.id] });
|
||||
expect(recovered.localResource?.id).toBe(recovered.localResourceId);
|
||||
expect(recovered.localResource?.closed).toBe(true);
|
||||
expect(recovered.localResource?.leaseDigest).toBe(photonHash(originalLease.token));
|
||||
expect(recovered.localResource?.controller).toEqual(await currentControllerProcess());
|
||||
expect(await state.read(PHOTON_EXTERNAL_STATE)).toEqual(retainedBeforeProof);
|
||||
expect(allocations).not.toHaveBeenCalled();
|
||||
expect(t.f.client.close).toHaveBeenCalledTimes(closeCalls);
|
||||
} catch (error) { primary = { error }; }
|
||||
finally {
|
||||
const cleanup: unknown[] = [];
|
||||
|
||||
@@ -424,6 +424,15 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true });
|
||||
const context = options.context(runtime), lease = options.ownership(id);
|
||||
if (!context || !lease || lease.context !== context || context.endpointRuntime !== runtime || lease.stopping) throw new Error("Photon normal local resource lease changed");
|
||||
const config = await options.config(record);
|
||||
const controller = await currentControllerProcess();
|
||||
if (controller.hostHash === UNKNOWN_PROCESS_SPACE || !controller.processStartedAt)
|
||||
throw conflict("Photon existing local resource requires its actual process birth and namespace");
|
||||
if (options.currentRuntime(id) !== runtime || options.context(runtime) !== context || options.ownership(id) !== lease
|
||||
|| context.endpointRuntime !== runtime || lease.context !== context || lease.stopping
|
||||
|| runtime.companyId !== record.endpoint.companyId || runtime.endpointId !== id
|
||||
|| lease.companyId !== record.endpoint.companyId || lease.endpointId !== id || lease.leaseKey !== "photon_receiver_runtime")
|
||||
throw conflict("Photon existing local resource ownership changed before handoff capture");
|
||||
const currentIdentity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId,
|
||||
runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject: identity.subject };
|
||||
const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) });
|
||||
@@ -431,7 +440,10 @@ export function createPhotonExternalRuntimeOwner(db: Db, options: {
|
||||
// persistence callbacks still see the exact current object/lease; removing
|
||||
// it first would turn cleanup debt into an obsolete-context no-op.
|
||||
const resourceId = resources.capture(runtime, async () => { await runtime.shutdown(); });
|
||||
const input = { identity: currentIdentity, lease, config: await options.config(record), localResourceId: resourceId };
|
||||
// This Runtime already exists. Capture its exact live process/lease before
|
||||
// handoff, not before its original constructor and never after a crash.
|
||||
const localResource: PhotonResourceDescriptor = { id: resourceId, controller, leaseDigest: photonHash(lease.token), closed: false };
|
||||
const input = { identity: currentIdentity, lease, config, localResourceId: resourceId, localResource };
|
||||
const prepared = await owner.prepare(input);
|
||||
if (prepared.phase === "enrolling") await joinConnectionEventWakeEnrollment(db);
|
||||
await owner.reconcile(input);
|
||||
|
||||
@@ -2,7 +2,8 @@ import { currentProcessSpaceHash, readControllerProcess, UNKNOWN_PROCESS_SPACE }
|
||||
import { proveOwnerGone, type ProcessProbe } from "../../owner-proof.js";
|
||||
import type { PhotonExternalState, PhotonResourceDescriptor } from "./external-contract.js";
|
||||
|
||||
/** Only a descriptor saved before this allocation can prove its process lifetime.
|
||||
/** A descriptor must be reserved before allocation or captured from the exact
|
||||
* still-owned live Runtime before handoff; never reconstructed after a crash.
|
||||
* Controller fencing, platform replacement and TTL never certify socket closure. */
|
||||
export async function photonResourceProcessEnded(state: PhotonExternalState, probe?: ProcessProbe): Promise<boolean> {
|
||||
const resource = state.localResource;
|
||||
|
||||
Reference in new issue
Block a user