Skip to content

Commit 426ab26

Browse files
committed
test(qa): cover gateway plugin approvals
1 parent ed8d1e7 commit 426ab26

2 files changed

Lines changed: 271 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
title: Gateway plugin approval lifecycle
2+
3+
scenario:
4+
id: gateway-plugin-approvals
5+
surface: gateway
6+
category: gateway.approvals-and-remote-execution
7+
coverage:
8+
primary:
9+
- gateway.plugin-approvals
10+
objective: Prove that a real Gateway routes one plugin approval to a capable reviewer and records one consistent terminal decision.
11+
successCriteria:
12+
- The Gateway generates a plugin-prefixed approval ID and reports approval-client delivery.
13+
- A distinct admin reviewer with the approvals capability receives the matching requested event.
14+
- The pending inventory contains the request while waitDecision remains blocked.
15+
- The reviewer resolution produces identical waitDecision and resolved-event outcomes.
16+
- The resolved request leaves the pending approval inventory.
17+
docsRefs:
18+
- docs/gateway/protocol.md
19+
- docs/help/testing.md
20+
codeRefs:
21+
- src/gateway/server-methods/plugin-approval.ts
22+
- src/gateway/server-methods/approval-shared.ts
23+
- src/gateway/server-request-context.ts
24+
- test/e2e/qa-lab/runtime/gateway-plugin-approvals.e2e.test.ts
25+
execution:
26+
kind: vitest
27+
path: test/e2e/qa-lab/runtime/gateway-plugin-approvals.e2e.test.ts
28+
summary: Run authenticated requester and reviewer clients over real Gateway WebSockets through request, wait, resolve, and cleanup.
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
// Proves the plugin approval lifecycle through authenticated Gateway WebSockets.
2+
import path from "node:path";
3+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { GATEWAY_CLIENT_CAPS } from "../../../../packages/gateway-protocol/src/client-info.js";
6+
import { ADMIN_SCOPE, APPROVALS_SCOPE } from "../../../../src/gateway/method-scopes.js";
7+
import {
8+
connectGatewayClient,
9+
disconnectGatewayClient,
10+
} from "../../../../src/gateway/test-helpers.e2e.js";
11+
import {
12+
getFreePort,
13+
installGatewayTestHooks,
14+
startGatewayServer,
15+
} from "../../../../src/gateway/test-helpers.js";
16+
import { loadOrCreateDeviceIdentity } from "../../../../src/infra/device-identity.js";
17+
import { setLoggerOverride } from "../../../../src/logging.js";
18+
19+
type Cleanup = () => Promise<void> | void;
20+
21+
type ApprovalEvent = {
22+
event?: string;
23+
payload?: unknown;
24+
};
25+
26+
type ApprovalRecord = {
27+
id: string;
28+
request: {
29+
allowedDecisions?: string[];
30+
pluginId?: string | null;
31+
};
32+
};
33+
34+
type ApprovalDecision = {
35+
createdAtMs: number;
36+
decision: string;
37+
expiresAtMs: number;
38+
id: string;
39+
terminalReason: string | null;
40+
};
41+
42+
function requireRecord(value: unknown, label: string): Record<string, unknown> {
43+
if (!isRecord(value)) {
44+
throw new Error(`expected ${label}`);
45+
}
46+
return value;
47+
}
48+
49+
installGatewayTestHooks({ scope: "suite" });
50+
51+
describe("gateway plugin approvals QA", () => {
52+
const cleanup: Cleanup[] = [];
53+
54+
afterEach(async () => {
55+
for (const step of cleanup.splice(0).toReversed()) {
56+
await step();
57+
}
58+
});
59+
60+
it("delivers a generated request to a distinct reviewer and resolves one terminal decision", async () => {
61+
let stage = "fixture setup";
62+
const markStage = (next: string) => {
63+
stage = next;
64+
console.info(`[gateway-plugin-approvals] stage=${stage}`);
65+
};
66+
67+
try {
68+
// Keep normal test logs quiet while exposing the existing ws-control
69+
// handshake phase if this real connection fails before hello-ok.
70+
setLoggerOverride({ level: "silent", consoleLevel: "warn", consoleStyle: "compact" });
71+
72+
const stateDir = process.env.OPENCLAW_STATE_DIR;
73+
if (!stateDir) {
74+
throw new Error("OPENCLAW_STATE_DIR is required for gateway QA fixtures");
75+
}
76+
const reviewerIdentity = loadOrCreateDeviceIdentity({
77+
path: path.join(stateDir, "test-device-identities", "plugin-approval-reviewer.sqlite"),
78+
});
79+
const requesterIdentity = loadOrCreateDeviceIdentity({
80+
path: path.join(stateDir, "test-device-identities", "plugin-approval-requester.sqlite"),
81+
});
82+
expect(reviewerIdentity.deviceId).not.toBe(requesterIdentity.deviceId);
83+
84+
markStage("gateway start");
85+
const port = await getFreePort();
86+
const token = "gateway-plugin-approvals-qa-token";
87+
const url = `ws://127.0.0.1:${port}`;
88+
const server = await startGatewayServer(port, {
89+
bind: "loopback",
90+
auth: { mode: "token", token },
91+
controlUiEnabled: false,
92+
sidecarStartup: "defer",
93+
});
94+
cleanup.push(() => server.close());
95+
96+
const approvalEvents: ApprovalEvent[] = [];
97+
markStage("reviewer connect");
98+
const reviewer = await connectGatewayClient({
99+
url,
100+
token,
101+
clientDisplayName: "plugin approval reviewer",
102+
scopes: [ADMIN_SCOPE],
103+
caps: [GATEWAY_CLIENT_CAPS.APPROVALS],
104+
deviceIdentity: reviewerIdentity,
105+
onEvent: (event) => {
106+
if (
107+
event.event === "plugin.approval.requested" ||
108+
event.event === "plugin.approval.resolved"
109+
) {
110+
approvalEvents.push(event);
111+
}
112+
},
113+
timeoutMs: 60_000,
114+
});
115+
cleanup.push(() => disconnectGatewayClient(reviewer));
116+
117+
markStage("requester connect");
118+
const requester = await connectGatewayClient({
119+
url,
120+
token,
121+
clientDisplayName: "plugin approval requester",
122+
scopes: [APPROVALS_SCOPE],
123+
deviceIdentity: requesterIdentity,
124+
timeoutMs: 60_000,
125+
});
126+
cleanup.push(() => disconnectGatewayClient(requester));
127+
128+
markStage("approval request");
129+
const accepted = await requester.request<{
130+
deliveryRoute: string;
131+
id: string;
132+
status: string;
133+
}>("plugin.approval.request", {
134+
pluginId: "qa-plugin",
135+
title: "Allow fixture mutation",
136+
description: "The QA fixture requests one bounded mutation.",
137+
allowedDecisions: ["allow-once"],
138+
twoPhase: true,
139+
timeoutMs: 30_000,
140+
});
141+
expect(accepted).toMatchObject({
142+
status: "accepted",
143+
deliveryRoute: "approval-client",
144+
});
145+
expect(accepted.id).toMatch(/^plugin:[0-9a-f-]{36}$/);
146+
147+
markStage("requested event");
148+
await vi.waitFor(() => {
149+
expect(
150+
approvalEvents.filter((event) => event.event === "plugin.approval.requested"),
151+
).toHaveLength(1);
152+
});
153+
const requestedEvent = approvalEvents.find(
154+
(event) => event.event === "plugin.approval.requested",
155+
);
156+
expect(
157+
requireRecord(requestedEvent?.payload, "plugin approval requested event"),
158+
).toMatchObject({
159+
id: accepted.id,
160+
request: {
161+
pluginId: "qa-plugin",
162+
allowedDecisions: ["allow-once", "deny"],
163+
},
164+
});
165+
166+
markStage("pending inventory");
167+
const pending = await reviewer.request<ApprovalRecord[]>("plugin.approval.list", {});
168+
expect(pending).toEqual([
169+
expect.objectContaining({
170+
id: accepted.id,
171+
request: expect.objectContaining({
172+
pluginId: "qa-plugin",
173+
allowedDecisions: ["allow-once", "deny"],
174+
}),
175+
}),
176+
]);
177+
178+
markStage("wait decision pending");
179+
let waitSettled = false;
180+
const waitDecision = requester
181+
.request<ApprovalDecision>(
182+
"plugin.approval.waitDecision",
183+
{ id: accepted.id },
184+
{ timeoutMs: 10_000 },
185+
)
186+
.finally(() => {
187+
waitSettled = true;
188+
});
189+
await new Promise((resolve) => setTimeout(resolve, 25));
190+
expect(waitSettled).toBe(false);
191+
192+
markStage("reviewer resolve");
193+
await expect(
194+
reviewer.request("plugin.approval.resolve", {
195+
id: accepted.id,
196+
decision: "allow-once",
197+
}),
198+
).resolves.toEqual({ ok: true });
199+
200+
markStage("terminal decision");
201+
const terminalDecision = await waitDecision;
202+
await vi.waitFor(() => {
203+
expect(
204+
approvalEvents.filter((event) => event.event === "plugin.approval.resolved"),
205+
).toHaveLength(1);
206+
});
207+
const resolvedEvent = approvalEvents.find(
208+
(event) => event.event === "plugin.approval.resolved",
209+
);
210+
const resolvedPayload = requireRecord(
211+
resolvedEvent?.payload,
212+
"plugin approval resolved event",
213+
);
214+
const waitTerminalDecision = {
215+
id: terminalDecision.id,
216+
decision: terminalDecision.decision,
217+
};
218+
const eventTerminalDecision = {
219+
id: resolvedPayload.id,
220+
decision: resolvedPayload.decision,
221+
};
222+
expect(waitTerminalDecision).toEqual({
223+
id: accepted.id,
224+
decision: "allow-once",
225+
});
226+
expect(eventTerminalDecision).toEqual(waitTerminalDecision);
227+
expect(terminalDecision.createdAtMs).toEqual(expect.any(Number));
228+
expect(terminalDecision.expiresAtMs).toEqual(expect.any(Number));
229+
expect(terminalDecision.expiresAtMs).toBeGreaterThan(terminalDecision.createdAtMs);
230+
expect(terminalDecision.terminalReason).toBe("user");
231+
232+
markStage("pending inventory empty");
233+
await expect(reviewer.request<ApprovalRecord[]>("plugin.approval.list", {})).resolves.toEqual(
234+
[],
235+
);
236+
} catch (error) {
237+
const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
238+
throw new Error(`[gateway-plugin-approvals] failed stage=${stage}: ${detail}`, {
239+
cause: error,
240+
});
241+
}
242+
}, 120_000);
243+
});

0 commit comments

Comments
 (0)