Skip to content

Commit 5b11b16

Browse files
committed
fix(reef): fence borrowed runtime authority
Refs #129063
1 parent 42186b1 commit 5b11b16

12 files changed

Lines changed: 296 additions & 102 deletions

‎extensions/reef/runtime-api.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export { setReefRuntime, getReefRuntime, setActiveReef, getActiveReef } from "./src/runtime.js";
1+
export { setReefRuntime, getReefRuntime, getActiveReef } from "./src/runtime.js";

‎extensions/reef/src/channel.test.ts‎

Lines changed: 57 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { AddressInfo } from "node:net";
44
import os from "node:os";
55
import path from "node:path";
66
import { createStartAccountContext } from "openclaw/plugin-sdk/channel-test-helpers";
7+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
78
import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-runtime";
89
import {
910
createPluginStateSyncKeyedStoreForTests,
@@ -30,16 +31,6 @@ import {
3031
import { ReefInboxConnection, ReefTransportClient } from "./transport.js";
3132
import { openReefTrustStore } from "./trust-store.js";
3233

33-
function deferred() {
34-
let resolve!: () => void;
35-
let reject!: (reason?: unknown) => void;
36-
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
37-
resolve = resolvePromise;
38-
reject = rejectPromise;
39-
});
40-
return { promise, resolve, reject };
41-
}
42-
4334
describe("Reef inbound dispatch content", () => {
4435
it("keeps provenance model-visible without storing it in the transcript body", () => {
4536
const content = resolveReefInboundDispatchContent({
@@ -233,7 +224,7 @@ describe("Reef gateway account ownership", () => {
233224
},
234225
};
235226
const controllers: AbortController[] = [];
236-
const inboxDrains: ReturnType<typeof deferred>[] = [];
227+
const inboxDrains: ReturnType<typeof createDeferred<void>>[] = [];
237228
const accountTasks: Promise<unknown>[] = [];
238229
let stateDir = "";
239230

@@ -260,7 +251,7 @@ describe("Reef gateway account ownership", () => {
260251
setReefRuntime(runtime);
261252
vi.spyOn(ReefTransportClient.prototype, "listFriends").mockResolvedValue({ friendships: [] });
262253
vi.spyOn(ReefInboxConnection.prototype, "start").mockImplementation(() => {
263-
const drain = deferred();
254+
const drain = createDeferred<void>();
264255
inboxDrains.push(drain);
265256
return drain.promise;
266257
});
@@ -355,6 +346,53 @@ describe("Reef gateway account ownership", () => {
355346
expect(listFriends).not.toHaveBeenCalled();
356347
});
357348

349+
it("revokes borrowed pairing approval before a paused reconcile reaches the replaced flow", async () => {
350+
startAccount();
351+
await vi.waitFor(() => expect(inboxDrains).toHaveLength(1));
352+
const firstActive = getActiveReef();
353+
const reconcilePaused = createDeferred<void>();
354+
const firstList = vi.fn(async () => {
355+
await reconcilePaused.promise;
356+
return { friendships: [] };
357+
});
358+
firstActive.friends.transport.listFriends = firstList;
359+
const firstSend = vi.spyOn(firstActive.flow, "send").mockResolvedValue("account-a-message");
360+
const stale = reefPlugin.pairing!.notifyApproval!({ cfg, id: "molty" });
361+
await vi.waitFor(() => expect(firstList).toHaveBeenCalledOnce());
362+
363+
startAccount();
364+
await vi.waitFor(() => expect(inboxDrains).toHaveLength(2));
365+
const replacementActive = getActiveReef();
366+
367+
reconcilePaused.resolve();
368+
const staleResult = await stale.catch((error: unknown) => error);
369+
370+
expect(firstSend).not.toHaveBeenCalled();
371+
expect(staleResult).toBeInstanceOf(Error);
372+
expect(getActiveReef()).toBe(replacementActive);
373+
});
374+
375+
it("rejects a borrowed Reef command when shutdown interrupts its friend lookup", async () => {
376+
const account = startAccount();
377+
await vi.waitFor(() => expect(inboxDrains).toHaveLength(1));
378+
const active = getActiveReef();
379+
const listPaused = createDeferred<void>();
380+
const listFriends = vi.fn(async () => {
381+
await listPaused.promise;
382+
return { friendships: [] };
383+
});
384+
active.friends.transport.listFriends = listFriends;
385+
const command = handleReefCommand({ args: "friend list" });
386+
await vi.waitFor(() => expect(listFriends).toHaveBeenCalledOnce());
387+
388+
account.abort.abort();
389+
listPaused.resolve();
390+
391+
await expect(command).rejects.toBeInstanceOf(Error);
392+
inboxDrains[0]!.resolve();
393+
await account.account;
394+
});
395+
358396
it("keeps the replacement account authoritative through stale and failed account teardown", async () => {
359397
const first = startAccount();
360398
await vi.waitFor(() => {
@@ -533,8 +571,8 @@ describe("Reef channel lifecycle", () => {
533571
it("does not activate when the parent aborts during startup reconcile", async () => {
534572
const parent = new AbortController();
535573
const inbox = hangingInbox();
536-
const reconcileStarted = deferred();
537-
const finishReconcile = deferred();
574+
const reconcileStarted = createDeferred<void>();
575+
const finishReconcile = createDeferred<void>();
538576
const onReady = vi.fn(async () => {});
539577
const lifecycle = runReefChannelLifecycle({
540578
parentSignal: parent.signal,
@@ -557,8 +595,8 @@ describe("Reef channel lifecycle", () => {
557595
it("does not reject when startup reconcile fails after the parent aborts", async () => {
558596
const parent = new AbortController();
559597
const inbox = hangingInbox();
560-
const reconcileStarted = deferred();
561-
const finishReconcile = deferred();
598+
const reconcileStarted = createDeferred<void>();
599+
const finishReconcile = createDeferred<void>();
562600
const onReady = vi.fn(async () => {});
563601
const lifecycle = runReefChannelLifecycle({
564602
parentSignal: parent.signal,
@@ -582,7 +620,7 @@ describe("Reef channel lifecycle", () => {
582620
{ phase: "friend reconciliation", completedRequests: 0 },
583621
{ phase: "pairing-candidate surfacing", completedRequests: 1 },
584622
])("promptly aborts a stalled $phase request", async ({ completedRequests }) => {
585-
const requestStarted = deferred();
623+
const requestStarted = createDeferred<void>();
586624
let requests = 0;
587625
const server = http.createServer((_request, response) => {
588626
if (requests++ < completedRequests) {
@@ -644,8 +682,8 @@ describe("Reef channel lifecycle", () => {
644682
it("does not start the inbox when the parent aborts during activation", async () => {
645683
const parent = new AbortController();
646684
const inbox = hangingInbox();
647-
const activationStarted = deferred();
648-
const finishActivation = deferred();
685+
const activationStarted = createDeferred<void>();
686+
const finishActivation = createDeferred<void>();
649687
const lifecycle = runReefChannelLifecycle({
650688
parentSignal: parent.signal,
651689
startInbox: inbox.startInbox,

‎extensions/reef/src/channel.ts‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,12 @@ import {
3232
ReefReceiptNotifier,
3333
} from "./owner-notice.js";
3434
import { isRephrasedReefResend } from "./rejection-resend.js";
35-
import { getActiveReef, getOptionalReefRuntime, getReefRuntime, setActiveReef } from "./runtime.js";
35+
import {
36+
createReefRuntimeAuthority,
37+
getActiveReef,
38+
getOptionalReefRuntime,
39+
getReefRuntime,
40+
} from "./runtime.js";
3641
import { reefSetupContract, reefSetupWizard } from "./setup.js";
3742
import { assertReefIdentityBinding, loadKeys, openStores, ReefInboxCursorStore } from "./state.js";
3843
import {
@@ -255,12 +260,13 @@ export const reefPlugin: ChannelPlugin<ReefAccount> = {
255260
relayUrl: parseReefRelayUrl(ctx.account.config.relayUrl),
256261
};
257262
assertReefIdentityBinding(runtime, identityBinding);
263+
const authority = createReefRuntimeAuthority(ctx.abortSignal);
258264
const transport = new ReefTransportClient(
259265
ctx.account.config.relayUrl,
260266
ctx.account.config.handle!,
261267
keys,
262268
);
263-
const stores = openStores(runtime, keys);
269+
const stores = openStores(runtime, keys, { authoritySignal: authority.signal });
264270
const inboxCursor = new ReefInboxCursorStore(runtime, identityBinding);
265271
const reviews = stores.reviews;
266272
const pairing = createChannelPairingController({
@@ -269,12 +275,15 @@ export const reefPlugin: ChannelPlugin<ReefAccount> = {
269275
accountId: "default",
270276
});
271277
const trust = openReefTrustStore(runtime, ctx.account.config);
272-
const friends = new ReefFriendManager(transport, trust, {
273-
list: pairing.readAllowFromStore,
274-
remove: async (peer) => {
275-
return (await pairing.removeAllowFromStoreEntry(peer)).changed;
278+
const friends = new ReefFriendManager(
279+
transport,
280+
trust,
281+
{
282+
list: pairing.readAllowFromStore,
283+
remove: async (peer) => (await pairing.removeAllowFromStoreEntry(peer)).changed,
276284
},
277-
});
285+
authority.signal,
286+
);
278287
const onIngress = async (message: ReefIngressMessage) => {
279288
const dispatchContent = resolveReefInboundDispatchContent(message);
280289
const budget = autonomyBudget(message.autonomy);
@@ -341,6 +350,7 @@ export const reefPlugin: ChannelPlugin<ReefAccount> = {
341350
replay: stores.replay,
342351
reviews,
343352
delivered: stores.delivered,
353+
authoritySignal: authority.signal,
344354
onIngress,
345355
onOwnerNotice: async (text) =>
346356
ownerNotice({
@@ -440,19 +450,12 @@ export const reefPlugin: ChannelPlugin<ReefAccount> = {
440450
// Attempt the peer-key refresh before recovery can dispatch an agent
441451
// turn. The lifecycle activates only after that attempt is classified.
442452
// The lifecycle owns both the ordering and the reconcile failure policy.
443-
let releaseActiveReef: (() => void) | undefined;
444-
const retireActiveReef = () => releaseActiveReef?.();
445453
const activate = async () => {
446454
await receiptNotifier.notifyRejections(trust.pendingOutboundRejections());
447455
if (ctx.abortSignal.aborted) {
448456
return;
449457
}
450-
releaseActiveReef = setActiveReef({ flow, friends, reviews });
451-
ctx.abortSignal.addEventListener("abort", retireActiveReef, { once: true });
452-
if (ctx.abortSignal.aborted) {
453-
retireActiveReef();
454-
return;
455-
}
458+
authority.activate({ flow, friends, reviews });
456459
ctx.setStatus({ accountId: "default", running: true, connected: false });
457460
};
458461
const inbox = new ReefInboxConnection(
@@ -517,8 +520,7 @@ export const reefPlugin: ChannelPlugin<ReefAccount> = {
517520
onReady: activate,
518521
});
519522
} finally {
520-
ctx.abortSignal.removeEventListener("abort", retireActiveReef);
521-
retireActiveReef();
523+
authority.release();
522524
ctx.setStatus({ accountId: "default", running: false, connected: false });
523525
}
524526
},

‎extensions/reef/src/config-schema.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
22
import reefChannelEntry from "../index.js";
33
import { reefPlugin } from "./channel.js";
44
import { autonomyBudget, parseReefRelayUrl, ReefChannelConfigSchema } from "./config-schema.js";
5-
import { setActiveReef } from "./runtime.js";
5+
import { createReefRuntimeAuthority } from "./runtime.js";
66

77
describe("Reef configuration boundary", () => {
88
it("defaults to the canonical Reef relay", () => {
@@ -80,7 +80,7 @@ describe("Reef configuration boundary", () => {
8080
const setAutonomy = vi.fn();
8181
const decide = vi.fn().mockResolvedValue(true);
8282
const listFriends = vi.fn().mockResolvedValue([]);
83-
setActiveReef({
83+
createReefRuntimeAuthority().activate({
8484
flow: { send: flowSend },
8585
friends: {
8686
mintCode,

‎extensions/reef/src/flow.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ export class ReefMessageFlow {
140140
replay: ReplayStore;
141141
reviews: ReviewApprovalStore;
142142
delivered: ReefDeliveredStore;
143+
authoritySignal?: AbortSignal;
143144
onIngress: (message: ReefIngressMessage) => Promise<void>;
144145
onOwnerNotice: (text: string) => Promise<void>;
145146
},
@@ -157,6 +158,8 @@ export class ReefMessageFlow {
157158
onPlatformSendDispatch?: () => Promise<void>;
158159
} = {},
159160
): Promise<string> {
161+
const signal = this.options.authoritySignal;
162+
signal?.throwIfAborted();
160163
const friend = this.options.trust.get(peer);
161164
if (
162165
!friend ||
@@ -185,6 +188,7 @@ export class ReefMessageFlow {
185188
policyVersion: this.requireGuardConfig().policyVersion,
186189
reviewGate: (request) => this.options.reviews.request(request),
187190
});
191+
signal?.throwIfAborted();
188192
// Persist the exact peer/id/body binding before the relay can return a
189193
// receipt. Only a matching durable record may later authorize a resend turn.
190194
if (!matchesReefPeerIdentity(this.options.trust.get(peer), recipient)) {
@@ -205,7 +209,9 @@ export class ReefMessageFlow {
205209
// Guard/review/encryption are local and may reject safely. Mark ambiguity
206210
// only at the relay boundary so recovery never treats those failures as sent.
207211
await context.onPlatformSendDispatch?.();
208-
await this.options.transport.sendEnvelope(peer, result.envelope);
212+
signal?.throwIfAborted();
213+
await this.options.transport.sendEnvelope(peer, result.envelope, signal);
214+
signal?.throwIfAborted();
209215
return id;
210216
}
211217

‎extensions/reef/src/friends.test.ts‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ describe("ReefFriendManager pairing", () => {
132132

133133
addApproval(store, pairing, pending);
134134
await expect(manager.reconcile()).resolves.toEqual(["alice"]);
135-
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true);
135+
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true, undefined);
136136
expect(store.get("alice")).toMatchObject({
137137
autonomy: "bounded",
138138
ed25519PublicKey: pending.ed25519_pub,
@@ -193,6 +193,33 @@ describe("ReefFriendManager pairing", () => {
193193
expect(fs.existsSync(path.join(stateDir, "requested.json"))).toBe(false);
194194
});
195195

196+
it("preserves ambiguous outbound intent when account authority closes during a relay request", async () => {
197+
const pending = relayFriend("alice", "pending", generateIdentity(), 1, "me");
198+
const requestStarted = deferred<void>();
199+
const relayResult = deferred<{ status: string }>();
200+
const relay = transport(pending);
201+
relay.requestFriend.mockImplementation(async () => {
202+
requestStarted.resolve(undefined);
203+
return await relayResult.promise;
204+
});
205+
const store = trust();
206+
const authority = new AbortController();
207+
const manager = new ReefFriendManager(
208+
relay as unknown as ReefTransportClient,
209+
store,
210+
approvals(),
211+
authority.signal,
212+
);
213+
const request = manager.request("alice");
214+
await requestStarted.promise;
215+
216+
authority.abort();
217+
relayResult.resolve({ status: "pending" });
218+
219+
await expect(request).rejects.toBeInstanceOf(Error);
220+
expect(store.hasOutboundRequest("alice")).toBe(true);
221+
});
222+
196223
it("removes a relay edge created after another process revoked the request", async () => {
197224
const pending = relayFriend("alice", "pending", generateIdentity(), 1, "me");
198225
const requestStarted = deferred<void>();
@@ -343,7 +370,7 @@ describe("ReefFriendManager pairing", () => {
343370
addApproval(store, pairing, reapproval);
344371
await expect(manager.reconcile()).resolves.toEqual(["alice"]);
345372

346-
expect(relay.respondFriend).toHaveBeenCalledWith(reapproval, true);
373+
expect(relay.respondFriend).toHaveBeenCalledWith(reapproval, true, undefined);
347374
expect(store.get("alice")).toMatchObject({
348375
autonomy: "extended",
349376
safetyNumberChanged: false,
@@ -369,7 +396,7 @@ describe("ReefFriendManager pairing", () => {
369396

370397
await expect(manager.reconcile()).resolves.toEqual(["alice"]);
371398

372-
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true);
399+
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true, undefined);
373400
expect(store.get("alice")).toMatchObject({ autonomy: "extended" });
374401
expect(pairing.values).toEqual(new Set());
375402
});
@@ -389,7 +416,7 @@ describe("ReefFriendManager pairing", () => {
389416

390417
await expect(manager.reconcile()).resolves.toEqual([]);
391418

392-
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true);
419+
expect(relay.respondFriend).toHaveBeenCalledWith(pending, true, undefined);
393420
expect(relay.removeFriend).toHaveBeenCalledWith("alice");
394421
expect(store.get("alice")).toBeUndefined();
395422
expect(pairing.values).toEqual(new Set());

0 commit comments

Comments
 (0)