Skip to content

Commit 77d9f0c

Browse files
committed
fix(feishu): cancel unread streaming-card error bodies before release
1 parent b6b440d commit 77d9f0c

2 files changed

Lines changed: 163 additions & 0 deletions

File tree

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Feishu streaming card tests exercise error-path response body cancellation
2+
// through a real guarded HTTP transport against a loopback server.
3+
import { createServer, type Server } from "node:http";
4+
import type { AddressInfo } from "node:net";
5+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6+
7+
const loopback = vi.hoisted(() => ({
8+
baseUrl: "",
9+
releases: [] as Array<{ bodyIsNull: boolean; bodyUsed: boolean }>,
10+
authStatus: 200,
11+
createStatus: 200,
12+
settingsStatus: 200,
13+
}));
14+
15+
vi.mock("openclaw/plugin-sdk/ssrf-runtime", async (importOriginal) => {
16+
const actual = await importOriginal<typeof import("openclaw/plugin-sdk/ssrf-runtime")>();
17+
return {
18+
...actual,
19+
fetchWithSsrFGuard: async (...args: Parameters<typeof actual.fetchWithSsrFGuard>) => {
20+
const [params] = args;
21+
const url = new URL(params.url);
22+
const redirected = new URL(`${url.pathname}${url.search}`, loopback.baseUrl).toString();
23+
const guarded = await actual.fetchWithSsrFGuard({
24+
...params,
25+
policy: { allowPrivateNetwork: true },
26+
url: redirected,
27+
});
28+
return {
29+
...guarded,
30+
release: async () => {
31+
loopback.releases.push({
32+
bodyIsNull: guarded.response.body === null,
33+
bodyUsed: guarded.response.bodyUsed,
34+
});
35+
await guarded.release();
36+
},
37+
};
38+
},
39+
};
40+
});
41+
42+
const { FeishuStreamingSession } = await import("./streaming-card.js");
43+
44+
function writeJson(res: import("node:http").ServerResponse, payload: unknown, status = 200): void {
45+
res.writeHead(status, { "content-type": "application/json" });
46+
res.end(JSON.stringify(payload));
47+
}
48+
49+
let server: Server;
50+
51+
beforeAll(async () => {
52+
server = createServer((req, res) => {
53+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
54+
if (url.pathname.includes("/auth/")) {
55+
if (loopback.authStatus === 200) {
56+
writeJson(res, { code: 0, msg: "ok", tenant_access_token: "token", expire: 3600 });
57+
} else {
58+
writeJson(res, { error: "tenant token rejected" }, loopback.authStatus);
59+
}
60+
return;
61+
}
62+
if (url.pathname.endsWith("/settings")) {
63+
if (loopback.settingsStatus === 200) {
64+
writeJson(res, { code: 0, msg: "ok" });
65+
} else {
66+
writeJson(res, { error: "settings rejected" }, loopback.settingsStatus);
67+
}
68+
return;
69+
}
70+
if (loopback.createStatus === 200) {
71+
writeJson(res, { code: 0, msg: "ok", data: { card_id: "card_1" } });
72+
} else {
73+
writeJson(res, { error: "card create rejected" }, loopback.createStatus);
74+
}
75+
});
76+
await new Promise<void>((resolve) => {
77+
server.listen(0, "127.0.0.1", resolve);
78+
});
79+
const address = server.address() as AddressInfo;
80+
loopback.baseUrl = `http://127.0.0.1:${address.port}`;
81+
});
82+
83+
afterAll(async () => {
84+
await new Promise<void>((resolve) => {
85+
server.close(() => resolve());
86+
});
87+
});
88+
89+
beforeEach(() => {
90+
loopback.releases = [];
91+
loopback.authStatus = 200;
92+
loopback.createStatus = 200;
93+
loopback.settingsStatus = 200;
94+
});
95+
96+
describe("feishu streaming card error-path body release", () => {
97+
it("cancels the unread tenant-token error body before release", async () => {
98+
loopback.authStatus = 500;
99+
const session = new FeishuStreamingSession({} as never, {
100+
appId: "app_error_token",
101+
appSecret: "secret",
102+
});
103+
104+
await expect(session.start("chat_id", "open_id")).rejects.toThrow(
105+
"Token request failed with HTTP 500",
106+
);
107+
108+
expect(loopback.releases).toEqual([{ bodyIsNull: false, bodyUsed: true }]);
109+
});
110+
111+
it("cancels the unread create-card error body before release", async () => {
112+
loopback.createStatus = 500;
113+
const session = new FeishuStreamingSession({} as never, {
114+
appId: "app_error_create",
115+
appSecret: "secret",
116+
});
117+
118+
await expect(session.start("chat_id", "open_id")).rejects.toThrow(
119+
"Create card request failed with HTTP 500",
120+
);
121+
122+
expect(loopback.releases).toEqual([
123+
{ bodyIsNull: false, bodyUsed: true },
124+
{ bodyIsNull: false, bodyUsed: true },
125+
]);
126+
});
127+
128+
it("cancels the unread close-settings error body before release", async () => {
129+
const client = {
130+
im: {
131+
message: {
132+
create: async () => ({ code: 0, data: { message_id: "msg_1" } }),
133+
},
134+
},
135+
};
136+
const session = new FeishuStreamingSession(client as never, {
137+
appId: "app_error_close",
138+
appSecret: "secret",
139+
});
140+
await session.start("chat_id", "open_id");
141+
loopback.settingsStatus = 500;
142+
143+
await expect(session.close()).resolves.toBe(false);
144+
145+
expect(loopback.releases).toEqual([
146+
{ bodyIsNull: false, bodyUsed: true },
147+
{ bodyIsNull: false, bodyUsed: true },
148+
{ bodyIsNull: false, bodyUsed: true },
149+
]);
150+
});
151+
});

‎extensions/feishu/src/streaming-card.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,22 @@ function resolveAllowedHostnames(domain?: FeishuDomain): string[] {
128128
return ["open.feishu.cn"];
129129
}
130130

131+
function cancelUnreadResponseBody(response: Response): void {
132+
// A rejected response leaves its body unread; start cancellation before the
133+
// guarded dispatcher is released so the connection is not leaked. Do not
134+
// await: debug capture can tee the stream and deadlock a waiter.
135+
if (!response.bodyUsed) {
136+
void response.body?.cancel().catch(() => undefined);
137+
}
138+
}
139+
131140
async function assertSuccessfulCardKitResponse(
132141
response: Response,
133142
auditContext: string,
134143
action: string,
135144
): Promise<void> {
136145
if (!response.ok) {
146+
cancelUnreadResponseBody(response);
137147
throw new Error(`${action} failed with HTTP ${response.status}`);
138148
}
139149
const data = await readFeishuJsonResponse<CardKitResponse>(response, auditContext);
@@ -174,6 +184,7 @@ async function getToken(creds: Credentials, deps?: FeishuStreamingDeps): Promise
174184
};
175185
try {
176186
if (!response.ok) {
187+
cancelUnreadResponseBody(response);
177188
throw new Error(`Token request failed with HTTP ${response.status}`);
178189
}
179190
data = await readFeishuJsonResponse(response, "feishu.streaming-card.token");
@@ -328,6 +339,7 @@ export class FeishuStreamingSession {
328339
};
329340
try {
330341
if (!createRes.ok) {
342+
cancelUnreadResponseBody(createRes);
331343
throw new Error(`Create card request failed with HTTP ${createRes.status}`);
332344
}
333345
createData = await readFeishuJsonResponse(createRes, "feishu.streaming-card.create");

0 commit comments

Comments
 (0)