|
| 1 | +import { EventEmitter } from "node:events"; |
| 2 | +import { Command } from "commander"; |
| 3 | +import { beforeEach, describe, expect, it, vi } from "vitest"; |
| 4 | + |
| 5 | +const spawnedChild = Object.assign(new EventEmitter(), { kill: vi.fn() }); |
| 6 | +vi.mock("node:child_process", () => ({ spawn: vi.fn(() => spawnedChild) })); |
| 7 | + |
| 8 | +const gatewayCalls: Array<{ |
| 9 | + method: string; |
| 10 | + params: Record<string, unknown>; |
| 11 | + mode?: string; |
| 12 | + hasDeviceIdentityKey: boolean; |
| 13 | +}> = []; |
| 14 | +vi.mock("../gateway/call.js", () => ({ |
| 15 | + callGateway: vi.fn( |
| 16 | + async (p: { method: string; params: Record<string, unknown>; mode?: string }) => { |
| 17 | + gatewayCalls.push({ |
| 18 | + method: p.method, |
| 19 | + params: p.params, |
| 20 | + mode: p.mode, |
| 21 | + hasDeviceIdentityKey: "deviceIdentity" in p, |
| 22 | + }); |
| 23 | + if (p.method === "attach.grant") { |
| 24 | + const sessionKey = (p.params.sessionKey as string) ?? "agent:main:main"; |
| 25 | + return { |
| 26 | + sessionKey, |
| 27 | + token: "tok-123", |
| 28 | + expiresAtMs: 2_000_000_000_000, |
| 29 | + mcpConfig: { |
| 30 | + mcpServers: { |
| 31 | + openclaw: { |
| 32 | + type: "http", |
| 33 | + url: "http://127.0.0.1:9999/mcp", |
| 34 | + headers: { Authorization: "Bearer ${OPENCLAW_MCP_TOKEN}" }, |
| 35 | + }, |
| 36 | + }, |
| 37 | + }, |
| 38 | + env: { OPENCLAW_MCP_TOKEN: "tok-123" }, |
| 39 | + }; |
| 40 | + } |
| 41 | + return {}; |
| 42 | + }, |
| 43 | + ), |
| 44 | +})); |
| 45 | + |
| 46 | +const logs: string[] = []; |
| 47 | +let exitCode: number | undefined; |
| 48 | +vi.mock("../runtime.js", () => ({ |
| 49 | + defaultRuntime: { |
| 50 | + log: (m: string) => logs.push(m), |
| 51 | + error: (m: string) => logs.push(`ERR:${m}`), |
| 52 | + exit: (c: number) => { |
| 53 | + exitCode = c; |
| 54 | + }, |
| 55 | + }, |
| 56 | +})); |
| 57 | +vi.mock("../config/io.js", () => ({ getRuntimeConfig: () => ({}) })); |
| 58 | + |
| 59 | +import { callGateway } from "../gateway/call.js"; |
| 60 | +import { registerAttachCli } from "./attach-cli.js"; |
| 61 | + |
| 62 | +async function runAttach(...args: string[]) { |
| 63 | + const program = new Command().name("openclaw").exitOverride(); |
| 64 | + await registerAttachCli(program); |
| 65 | + await program.parseAsync(["node", "openclaw", "attach", ...args]); |
| 66 | +} |
| 67 | +const tick = () => |
| 68 | + new Promise<void>((resolve) => { |
| 69 | + setImmediate(resolve); |
| 70 | + }); |
| 71 | + |
| 72 | +describe("openclaw attach (action)", () => { |
| 73 | + beforeEach(() => { |
| 74 | + gatewayCalls.length = 0; |
| 75 | + logs.length = 0; |
| 76 | + exitCode = undefined; |
| 77 | + spawnedChild.removeAllListeners(); |
| 78 | + spawnedChild.kill.mockClear(); |
| 79 | + }); |
| 80 | + |
| 81 | + it("--print-config: mints + writes config + prints launch, does NOT revoke or name a nonexistent command", async () => { |
| 82 | + await runAttach("--print-config", "--session", "agent:main:cli"); |
| 83 | + expect(gatewayCalls.find((c) => c.method === "attach.grant")?.params.sessionKey).toBe( |
| 84 | + "agent:main:cli", |
| 85 | + ); |
| 86 | + // setup mode leaves the grant live (no revoke) and must not point at a revoke command that does not exist |
| 87 | + expect(gatewayCalls.find((c) => c.method === "attach.revoke")).toBeUndefined(); |
| 88 | + const out = logs.join("\n"); |
| 89 | + expect(out).toContain("agent:main:cli"); |
| 90 | + expect(out).toContain("--mcp-config"); |
| 91 | + expect(out).toContain("--strict-mcp-config"); |
| 92 | + expect(out).toContain("OPENCLAW_MCP_TOKEN"); |
| 93 | + expect(out).not.toContain("attach.revoke"); |
| 94 | + }); |
| 95 | + |
| 96 | + it("calls attach.grant in CLI mode with an auto-resolved device identity (operator.admin regression guard)", async () => { |
| 97 | + // Regression guard: attach.grant is operator.admin-scoped. mode BACKEND or an explicit |
| 98 | + // deviceIdentity:null drops the operator device identity → the gateway rejects with |
| 99 | + // "missing scope: operator.admin". This was a real bug found via a live-gateway proof. |
| 100 | + await runAttach("--print-config", "--session", "agent:main:cli"); |
| 101 | + const grant = gatewayCalls.find((c) => c.method === "attach.grant"); |
| 102 | + expect(grant?.mode).toBe("cli"); |
| 103 | + expect(grant?.hasDeviceIdentityKey).toBe(false); |
| 104 | + }); |
| 105 | + |
| 106 | + it("rejects a non-positive --ttl before minting", async () => { |
| 107 | + await runAttach("--ttl", "-5", "--print-config"); |
| 108 | + expect(exitCode).toBe(1); |
| 109 | + expect(gatewayCalls.find((c) => c.method === "attach.grant")).toBeUndefined(); |
| 110 | + }); |
| 111 | + |
| 112 | + it("rejects an empty --ttl rather than silently defaulting", async () => { |
| 113 | + await runAttach("--ttl", "", "--print-config"); |
| 114 | + expect(exitCode).toBe(1); |
| 115 | + expect(gatewayCalls.find((c) => c.method === "attach.grant")).toBeUndefined(); |
| 116 | + }); |
| 117 | + |
| 118 | + it("passes a positive --ttl through to attach.grant", async () => { |
| 119 | + await runAttach("--ttl", "600000", "--print-config"); |
| 120 | + expect(gatewayCalls.find((c) => c.method === "attach.grant")?.params.ttlMs).toBe(600_000); |
| 121 | + }); |
| 122 | + |
| 123 | + it("errors on a malformed attach.grant response instead of crashing", async () => { |
| 124 | + vi.mocked(callGateway).mockResolvedValueOnce({} as never); |
| 125 | + await runAttach("--print-config"); |
| 126 | + expect(exitCode).toBe(1); |
| 127 | + }); |
| 128 | + |
| 129 | + it("spawns Claude Code and revokes the grant when the child exits", async () => { |
| 130 | + await runAttach("--session", "agent:main:spawn"); |
| 131 | + expect(gatewayCalls.find((c) => c.method === "attach.grant")).toBeTruthy(); |
| 132 | + const { spawn } = await import("node:child_process"); |
| 133 | + expect(vi.mocked(spawn).mock.calls[0]?.[1]).toEqual([ |
| 134 | + "--strict-mcp-config", |
| 135 | + "--mcp-config", |
| 136 | + expect.stringContaining(".mcp.json"), |
| 137 | + ]); |
| 138 | + spawnedChild.emit("exit", 0, null); |
| 139 | + await tick(); |
| 140 | + await tick(); |
| 141 | + expect(gatewayCalls.find((c) => c.method === "attach.revoke")?.params.token).toBe("tok-123"); |
| 142 | + expect(exitCode).toBe(0); |
| 143 | + }); |
| 144 | + |
| 145 | + it("revokes once and surfaces a launch failure when the child errors", async () => { |
| 146 | + await runAttach("--session", "agent:main:spawn-err"); |
| 147 | + spawnedChild.emit("error", new Error("ENOENT")); |
| 148 | + await tick(); |
| 149 | + await tick(); |
| 150 | + expect(gatewayCalls.filter((c) => c.method === "attach.revoke")).toHaveLength(1); |
| 151 | + expect(exitCode).toBe(1); |
| 152 | + expect(logs.join("\n")).toContain("Failed to launch"); |
| 153 | + }); |
| 154 | + |
| 155 | + it("warns when revoke fails but still exits with the child status", async () => { |
| 156 | + vi.mocked(callGateway).mockImplementationOnce(async (p) => { |
| 157 | + gatewayCalls.push({ |
| 158 | + method: p.method, |
| 159 | + params: p.params, |
| 160 | + mode: p.mode, |
| 161 | + hasDeviceIdentityKey: "deviceIdentity" in p, |
| 162 | + }); |
| 163 | + return { |
| 164 | + sessionKey: "agent:main:spawn", |
| 165 | + token: "tok-123", |
| 166 | + expiresAtMs: 2_000_000_000_000, |
| 167 | + mcpConfig: { mcpServers: { openclaw: {} } }, |
| 168 | + env: { OPENCLAW_MCP_TOKEN: "tok-123" }, |
| 169 | + } as never; |
| 170 | + }); |
| 171 | + vi.mocked(callGateway).mockImplementationOnce(async (p) => { |
| 172 | + gatewayCalls.push({ |
| 173 | + method: p.method, |
| 174 | + params: p.params, |
| 175 | + mode: p.mode, |
| 176 | + hasDeviceIdentityKey: "deviceIdentity" in p, |
| 177 | + }); |
| 178 | + throw new Error("gateway down"); |
| 179 | + }); |
| 180 | + |
| 181 | + await runAttach("--session", "agent:main:spawn"); |
| 182 | + spawnedChild.emit("exit", 0, null); |
| 183 | + await tick(); |
| 184 | + await tick(); |
| 185 | + |
| 186 | + expect(exitCode).toBe(0); |
| 187 | + expect(logs.join("\n")).toContain("failed to revoke attach grant"); |
| 188 | + }); |
| 189 | + |
| 190 | + it("detaches its signal handlers after the child exits (no listener leak)", async () => { |
| 191 | + const baseInt = process.listenerCount("SIGINT"); |
| 192 | + const baseTerm = process.listenerCount("SIGTERM"); |
| 193 | + await runAttach("--session", "agent:main:spawn"); |
| 194 | + expect(process.listenerCount("SIGINT")).toBe(baseInt + 1); |
| 195 | + spawnedChild.emit("exit", 0, null); |
| 196 | + await tick(); |
| 197 | + await tick(); |
| 198 | + expect(process.listenerCount("SIGINT")).toBe(baseInt); |
| 199 | + expect(process.listenerCount("SIGTERM")).toBe(baseTerm); |
| 200 | + }); |
| 201 | + |
| 202 | + it("errors on a grant with a non-numeric expiresAtMs instead of crashing on toISOString", async () => { |
| 203 | + vi.mocked(callGateway).mockResolvedValueOnce({ |
| 204 | + sessionKey: "agent:main:x", |
| 205 | + token: "tok-123", |
| 206 | + expiresAtMs: "soon", |
| 207 | + mcpConfig: { mcpServers: { openclaw: {} } }, |
| 208 | + env: {}, |
| 209 | + } as never); |
| 210 | + await runAttach("--print-config"); |
| 211 | + expect(exitCode).toBe(1); |
| 212 | + }); |
| 213 | +}); |
0 commit comments