Skip to content

Commit 0417abd

Browse files
authored
fix(reef): redact relay errors containing credentials (#119603)
1 parent c2d8b3b commit 0417abd

2 files changed

Lines changed: 179 additions & 13 deletions

File tree

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

Lines changed: 133 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,126 @@ describe("ReefTransportClient response body bounds", () => {
339339
});
340340
});
341341

342+
describe("ReefTransportClient credential redaction", () => {
343+
it("redacts setup tokens and bearer sessions from loopback relay errors", async () => {
344+
const setupToken = "reef.token[abc]+?/";
345+
const session = `reef-session-${"a".repeat(96)}-tail`;
346+
const sessionPrefix = session.slice(0, 6);
347+
const sessionSuffix = session.slice(-4);
348+
const receivedAuthorization: string[] = [];
349+
const receivedSignatures: string[] = [];
350+
const receivedTokens: string[] = [];
351+
const server = http.createServer((request, response) => {
352+
const chunks: Buffer[] = [];
353+
request.on("data", (chunk: Buffer) => chunks.push(chunk));
354+
request.on("end", () => {
355+
const authorization = request.headers.authorization ?? "";
356+
receivedAuthorization.push(authorization);
357+
const signatureHeader = request.headers["x-reef-sig"];
358+
const signature = typeof signatureHeader === "string" ? signatureHeader : "";
359+
if (signature) {
360+
receivedSignatures.push(signature);
361+
}
362+
const body = Buffer.concat(chunks).toString("utf8");
363+
const token = body ? (JSON.parse(body) as { token?: unknown }).token : undefined;
364+
if (typeof token === "string") {
365+
receivedTokens.push(token);
366+
}
367+
const reflectedCredential =
368+
authorization || (typeof token === "string" ? token : "") || signature;
369+
response.writeHead(401, { "content-type": "application/json" });
370+
response.end(
371+
JSON.stringify({ error: `${reflectedCredential} relay rejected`, marker: "safe" }),
372+
);
373+
});
374+
});
375+
await new Promise<void>((resolve, reject) => {
376+
server.once("error", reject);
377+
server.listen(0, "127.0.0.1", resolve);
378+
});
379+
const address = server.address();
380+
if (!address || typeof address === "string") {
381+
throw new Error("Reef credential redaction test server did not bind a TCP port");
382+
}
383+
384+
const client = createClient(fetch, () => ts, `http://127.0.0.1:${address.port}`);
385+
try {
386+
const tokenError = await client.authComplete(setupToken).catch((error: unknown) => error);
387+
const createHandleError = await client
388+
.createHandle(session, "approve")
389+
.catch((error: unknown) => error);
390+
const sessionError = await client.listOwnHandles(session).catch((error: unknown) => error);
391+
const signedError = await client.listFriends().catch((error: unknown) => error);
392+
393+
expect(tokenError).toMatchObject({ name: "ReefRelayError", status: 401 });
394+
expect(createHandleError).toMatchObject({ name: "ReefRelayError", status: 401 });
395+
expect(sessionError).toMatchObject({ name: "ReefRelayError", status: 401 });
396+
expect(tokenError).toMatchObject({ message: expect.stringContaining("relay rejected") });
397+
expect(createHandleError).toMatchObject({
398+
message: expect.stringContaining("relay rejected"),
399+
});
400+
expect(sessionError).toMatchObject({ message: expect.stringContaining("relay rejected") });
401+
expect(signedError).toMatchObject({
402+
name: "ReefRelayError",
403+
status: 401,
404+
message: expect.stringContaining("relay rejected"),
405+
});
406+
expect((tokenError as Error).message).not.toContain(setupToken);
407+
expect((createHandleError as Error).message).not.toContain(session);
408+
expect((sessionError as Error).message).not.toContain(session);
409+
expect((createHandleError as Error).message).not.toContain(sessionPrefix);
410+
expect((createHandleError as Error).message).not.toContain(sessionSuffix);
411+
expect((sessionError as Error).message).not.toContain(sessionPrefix);
412+
expect((sessionError as Error).message).not.toContain(sessionSuffix);
413+
expect(receivedAuthorization).toContain(`Bearer ${session}`);
414+
expect(receivedSignatures).toHaveLength(1);
415+
expect(receivedSignatures[0]).toBeTruthy();
416+
expect((signedError as Error).message).not.toContain(receivedSignatures[0]);
417+
expect(receivedTokens).toContain(setupToken);
418+
} finally {
419+
await new Promise<void>((resolve, reject) => {
420+
server.close((error) => (error ? reject(error) : resolve()));
421+
});
422+
}
423+
});
424+
425+
it("redacts signed body credentials across bounded error text", async () => {
426+
const code = "friend.code[123]+?/";
427+
const prefix = "x".repeat(32_760);
428+
const suffix = "y".repeat(32);
429+
const receivedBodies: string[] = [];
430+
const client = createClient(async (_url, init) => {
431+
const body = init?.body;
432+
receivedBodies.push(
433+
body instanceof Uint8Array
434+
? new TextDecoder().decode(body)
435+
: typeof body === "string"
436+
? body
437+
: "",
438+
);
439+
const responseBody = JSON.stringify({ error: `${prefix}${code}${suffix}` });
440+
const splitAt = responseBody.indexOf(code) + Math.floor(code.length / 2);
441+
return new Response(
442+
new ReadableStream({
443+
start(controller) {
444+
controller.enqueue(new TextEncoder().encode(responseBody.slice(0, splitAt)));
445+
controller.enqueue(new TextEncoder().encode(responseBody.slice(splitAt)));
446+
controller.close();
447+
},
448+
}),
449+
{ status: 401, headers: { "content-type": "application/json" } },
450+
);
451+
});
452+
453+
const error = await client.requestFriend("bob", code).catch((failure: unknown) => failure);
454+
455+
expect(error).toMatchObject({ name: "ReefRelayError", status: 401 });
456+
expect(receivedBodies).toHaveLength(1);
457+
expect(receivedBodies[0]).toContain(`"code":"${code}"`);
458+
expect((error as Error).message).not.toContain(code);
459+
});
460+
});
461+
342462
const INBOX_WEBSOCKET_MAX_PAYLOAD_BYTES = 64 * 1024;
343463

344464
class ControlledSocket {
@@ -587,12 +707,16 @@ describe("ReefInboxConnection recovery", () => {
587707
const socket = new ControlledSocket();
588708
const states: string[] = [];
589709
const errors: string[] = [];
710+
let socketUrl = "";
590711
const client = createClient(async () => Response.json({ entries: [], cursor: 0 }));
591712
const abort = new AbortController();
592713
const inbox = new ReefInboxConnection(
593714
client,
594715
async () => {},
595-
() => socket as unknown as WebSocketLike,
716+
(url) => {
717+
socketUrl = url;
718+
return socket as unknown as WebSocketLike;
719+
},
596720
{
597721
onState: (state) => states.push(state),
598722
onError: (error) => {
@@ -604,11 +728,17 @@ describe("ReefInboxConnection recovery", () => {
604728

605729
const running = inbox.start(abort.signal);
606730
socket.emit("open");
607-
socket.emit("close", { code: 1008, reason: "policy" });
731+
const signature = new URL(socketUrl).searchParams.get("sig");
732+
if (!signature) {
733+
throw new Error("Reef WebSocket test URL did not contain a signature");
734+
}
735+
socket.emit("close", { code: 1008, reason: `policy ${signature}` });
608736
await running;
609737

610738
expect(states).toEqual(["connected", "disconnected"]);
611-
expect(errors).toEqual(["reef inbox socket closed unexpectedly code=1008 reason=policy"]);
739+
expect(errors).toEqual([
740+
"reef inbox socket closed unexpectedly code=1008 reason=policy <redacted>",
741+
]);
612742
});
613743

614744
it("resets reconnect backoff after a socket completes catch-up", async () => {

‎extensions/reef/src/transport.ts‎

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { toStringifiedError as asError } from "openclaw/plugin-sdk/error-runtime";
22
import { buildTimeoutAbortSignal } from "openclaw/plugin-sdk/extension-shared";
3+
import { redactSensitiveText } from "openclaw/plugin-sdk/logging-core";
34
import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
45
import WebSocket from "ws";
56
import { sha256Hex, signDeviceRequest, utf8 } from "../protocol/index.js";
@@ -27,6 +28,16 @@ const REEF_WS_HANDSHAKE_MS = 30_000;
2728
// stops producing bytes must not pin inbox recovery forever.
2829
const REEF_RELAY_REQUEST_TIMEOUT_MS = 15_000;
2930

31+
function redactReefRelayErrorMessage(message: string, secrets: readonly string[]): string {
32+
let redacted = message;
33+
for (const secret of secrets) {
34+
if (secret.length > 0) {
35+
redacted = redacted.replaceAll(secret, "<redacted>");
36+
}
37+
}
38+
return redactSensitiveText(redacted, { mode: "tools" });
39+
}
40+
3041
export class ReefRelayError extends Error {
3142
constructor(
3243
readonly status: number,
@@ -106,7 +117,7 @@ export class ReefTransportClient {
106117
}
107118

108119
async authComplete(token: string): Promise<{ session: string; expires: number }> {
109-
return await this.unsigned("POST", "/v1/auth/complete", { token });
120+
return await this.unsigned("POST", "/v1/auth/complete", { token }, {}, [token]);
110121
}
111122

112123
async createHandle(
@@ -123,20 +134,29 @@ export class ReefTransportClient {
123134
request_policy: requestPolicy,
124135
},
125136
{ authorization: `Bearer ${session}` },
137+
[session],
126138
);
127139
}
128140

129141
listOwnHandles(
130142
session: string,
131143
): Promise<{ handles: Array<{ handle: string; key_epoch: number; request_policy: string }> }> {
132-
return this.unsigned("GET", "/v1/handles", undefined, { authorization: `Bearer ${session}` });
144+
return this.unsigned("GET", "/v1/handles", undefined, { authorization: `Bearer ${session}` }, [
145+
session,
146+
]);
133147
}
134148

135149
mintFriendCode(): Promise<{ code: string; expires: number }> {
136150
return this.signed("POST", "/v1/friend-codes");
137151
}
138152
requestFriend(to: string, code?: string): Promise<{ status: string }> {
139-
return this.signed("POST", "/v1/friends/request", code ? { to, code } : { to });
153+
return this.signed(
154+
"POST",
155+
"/v1/friends/request",
156+
code ? { to, code } : { to },
157+
undefined,
158+
code ? [code] : [],
159+
);
140160
}
141161
respondFriend(friend: RelayFriend, accept: boolean): Promise<{ peer: string; status: string }> {
142162
return this.signed("POST", "/v1/friends/respond", {
@@ -174,7 +194,13 @@ export class ReefTransportClient {
174194
return url.toString();
175195
}
176196

177-
async signed<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
197+
async signed<T>(
198+
method: string,
199+
path: string,
200+
body?: unknown,
201+
signal?: AbortSignal,
202+
secrets: readonly string[] = [],
203+
): Promise<T> {
178204
const bytes = body === undefined ? new Uint8Array() : utf8(JSON.stringify(body));
179205
const auth = this.auth(path, bytes, method);
180206
return await this.request(
@@ -187,6 +213,7 @@ export class ReefTransportClient {
187213
"x-reef-sig": auth.signature,
188214
},
189215
signal,
216+
[auth.signature, ...secrets],
190217
);
191218
}
192219

@@ -210,9 +237,10 @@ export class ReefTransportClient {
210237
path: string,
211238
body?: unknown,
212239
headers: Record<string, string> = {},
240+
secrets: readonly string[] = [],
213241
): Promise<T> {
214242
const bytes = body === undefined ? new Uint8Array() : utf8(JSON.stringify(body));
215-
return await this.request(method, path, bytes, headers);
243+
return await this.request(method, path, bytes, headers, undefined, secrets);
216244
}
217245

218246
private async request<T>(
@@ -221,6 +249,7 @@ export class ReefTransportClient {
221249
bytes: Uint8Array,
222250
headers: Record<string, string>,
223251
signal?: AbortSignal,
252+
secrets: readonly string[] = [],
224253
): Promise<T> {
225254
const url = new URL(path, this.relayUrl).toString();
226255
const timeout = buildTimeoutAbortSignal({
@@ -253,7 +282,7 @@ export class ReefTransportClient {
253282
{ maxBytes: REEF_RELAY_ERROR_JSON_MAX_BYTES },
254283
);
255284
if (typeof parsed.error === "string" && parsed.error) {
256-
message = parsed.error;
285+
message = redactReefRelayErrorMessage(parsed.error, secrets);
257286
}
258287
} catch {
259288
if (timeout.signal?.aborted) {
@@ -440,7 +469,9 @@ export class ReefInboxConnection {
440469

441470
private live(signal?: AbortSignal, onReady?: () => void): Promise<void> {
442471
return new Promise((resolve, reject) => {
443-
const socket = this.webSocketFactory(this.client.websocketUrl());
472+
const url = this.client.websocketUrl();
473+
const signature = new URL(url).searchParams.get("sig") ?? "";
474+
const socket = this.webSocketFactory(url);
444475
const workAbort = new AbortController();
445476
// Emit each state transition at most once per socket and never after this
446477
// invocation settles, so late events from an abandoned socket cannot
@@ -579,7 +610,7 @@ export class ReefInboxConnection {
579610
if (aborting || finished) {
580611
return;
581612
}
582-
disconnect(reefInboxCloseError(event));
613+
disconnect(reefInboxCloseError(event, [signature]));
583614
});
584615
socket.addEventListener("error", (event) =>
585616
disconnect(new Error(event.message?.trim() || "reef inbox socket error")),
@@ -591,8 +622,13 @@ export class ReefInboxConnection {
591622
}
592623
}
593624

594-
function reefInboxCloseError(event: { code?: number; reason?: string }): Error {
625+
function reefInboxCloseError(
626+
event: { code?: number; reason?: string },
627+
secrets: readonly string[] = [],
628+
): Error {
595629
const code = Number.isInteger(event.code) ? ` code=${event.code}` : "";
596-
const reason = event.reason?.trim() ? ` reason=${event.reason.trim()}` : "";
630+
const reason = event.reason?.trim()
631+
? ` reason=${redactReefRelayErrorMessage(event.reason.trim(), secrets)}`
632+
: "";
597633
return new Error(`reef inbox socket closed unexpectedly${code}${reason}`);
598634
}

0 commit comments

Comments
 (0)