Repository navigation
Add proxy capture stack and QA Lab inspector - #64895
Conversation
🔒 Aisle Security AnalysisWe found 7 potential security issue(s) in this PR:
1. 🟠 Unbounded request/response body buffering in debug proxy capture can cause memory/disk exhaustion
DescriptionThe debug proxy capture functionality buffers and persists entire HTTP request/response bodies without any size limit. When capture is enabled (via Key issues:
Vulnerable code (unbounded response buffering): void params.response
.clone()
.arrayBuffer()
.then((buffer) => {
const responsePayload = persistEventPayload(store, {
data: Buffer.from(buffer),
contentType: params.response.headers.get("content-type") ?? undefined,
});Impact:
Because this is controlled by environment variables, it is particularly risky when the proxy/capture is enabled in production-like contexts (QA lab, monitoring plugins, etc.). RecommendationAdd hard limits and prefer streaming capture to avoid buffering full payloads. Suggested approach:
Example (limit response capture): const MAX = settings.maxCaptureBytes ?? 10 * 1024 * 1024;
const cloned = params.response.clone();
const reader = cloned.body?.getReader();
let total = 0;
const chunks: Uint8Array[] = [];
while (reader) {
const { value, done } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > MAX) {
// record truncated preview + metadata
break;
}
chunks.push(value);
}
const data = Buffer.concat(chunks.map((c) => Buffer.from(c)));Also apply similar limits in 2. 🟠 Unauthenticated forward proxy with unrestricted CONNECT tunneling (network pivot/SSRF)
DescriptionThe new debug proxy server (
Vulnerable code: // binds to user-supplied host
const host = params.host?.trim() || "127.0.0.1";
server.listen(params.port ?? 0, host, ...);
// CONNECT tunnel to arbitrary host/port
const parsed = parseConnectTarget(req.url);
const upstreamSocket = net.connect(port, hostname, () => {
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
clientSocket.pipe(upstreamSocket);
upstreamSocket.pipe(clientSocket);
});RecommendationMitigate open-proxy abuse by applying defense in depth:
Example (loopback-only enforcement): import { isIP } from "node:net";
function isLoopbackHost(host: string): boolean {
const h = host.trim().toLowerCase();
return h === "127.0.0.1" || h === "localhost" || h === "::1";
}
const host = params.host?.trim() || "127.0.0.1";
if (!isLoopbackHost(host) && !params.settings.allowRemoteProxy) {
throw new Error("Refusing to bind debug proxy to non-loopback host without explicit override");
}If remote binding is truly needed, require an auth token and validate it on every request/CONNECT before proxying. 3. 🟠 Unauthenticated capture purge/delete endpoints enable CSRF/unauthorized data destruction
DescriptionThe QA Lab HTTP server exposes destructive capture-management endpoints without any authentication/authorization or CSRF defenses:
These endpoints:
Vulnerable code: if (req.method === "POST" && url.pathname === "/api/capture/delete-sessions") {
const body = (await readJson(req)) as { sessionIds?: unknown };
...
result: captureStore.deleteSessions(sessionIds),
}
if (req.method === "POST" && url.pathname === "/api/capture/purge") {
result: captureStore.purgeAll(),
}RecommendationAdd protection for all state-changing endpoints (including these capture endpoints):
Example (token + origin check): function requireAdmin(req: IncomingMessage) {
const expected = process.env.QA_LAB_ADMIN_TOKEN;
const auth = req.headers.authorization;
if (!expected || auth !== `Bearer ${expected}`) throw new Error("unauthorized");
const origin = req.headers.origin;
if (origin && origin !== publicBaseUrl) throw new Error("bad origin");
}
if (req.method === "POST" && url.pathname === "/api/capture/purge") {
requireAdmin(req);
writeJson(res, 200, { result: captureStore.purgeAll() });
return;
}4. 🟠 Privileged CA trust installation uses attacker-controlled certificate path (env override + symlink reuse)
DescriptionThe macOS CA installation script can be run with elevated privileges (to write to Impact when an admin runs
This enables an attacker to:
Vulnerable code (trusting path derived from env + no validation): const settings = resolveDebugProxySettings();
const ca = await ensureDebugProxyCa(settings.certDir);
...
spawnSync(security, [
"add-trusted-cert",
"-k",
"/Library/Keychains/System.keychain",
ca.certPath,
]);RecommendationTreat CA generation/trust as a privileged operation and harden file/path handling. Mitigations (recommended to combine):
import fs from "node:fs";
function assertSafeFile(p: string) {
const st = fs.lstatSync(p);
if (!st.isFile() || st.isSymbolicLink()) throw new Error(`Unsafe CA path: ${p}`);
// optionally enforce uid/gid match and mode <= 0o644 (and key <= 0o600)
}
// before trusting:
assertSafeFile(ca.certPath);
5. 🟠 Unauthenticated QA Lab capture APIs expose stored proxy-capture payloads (headers/bodies/blobs) and allow destructive actions
DescriptionThe QA Lab HTTP server adds multiple unauthenticated endpoints that expose the Debug Proxy Capture store contents, including raw captured payloads and headers. Impact:
Because Vulnerable code (no auth/ACL checks before returning capture data): if (req.method === "GET" && url.pathname === "/api/capture/blob") {
const blobId = url.searchParams.get("id")?.trim();
const content = captureStore.readBlob(blobId);
writeJson(res, 200, { id: blobId, content });
return;
}Additionally, the server may listen on a caller-supplied host: server.listen(params?.port ?? 0, params?.host ?? "127.0.0.1", () => resolve());RecommendationAdd access control for all
Example (token gate): function requireToken(req: IncomingMessage, expected: string): boolean {
const header = req.headers.authorization;
return typeof header === "string" && header === `Bearer ${expected}`;
}
// before handling /api/capture/*
if (url.pathname.startsWith("/api/capture/")) {
const token = process.env.QA_LAB_TOKEN;
if (!token || !requireToken(req, token)) {
writeError(res, 401, "Unauthorized");
return;
}
}6. 🟡 Path traversal / arbitrary file read via unvalidated capture blobId
Description
Vulnerable code: const blobPath = path.join(this.blobDir, `${row.blobId}.bin.gz`);
return fs.existsSync(blobPath) ? readCaptureBlobText(blobPath) : null;RecommendationValidate
Example fix: function assertValidBlobId(blobId: string): string {
const trimmed = blobId.trim();
if (!/^[a-f0-9]{24}$/.test(trimmed)) {
throw new Error("Invalid blob id");
}
return trimmed;
}
readBlob(blobId: string): string | null {
const safeId = assertValidBlobId(blobId);
const blobPath = path.resolve(this.blobDir, `${safeId}.bin.gz`);
const rel = path.relative(this.blobDir, blobPath);
if (rel.startsWith("..") || path.isAbsolute(rel)) {
return null;
}
return fs.existsSync(blobPath) ? readCaptureBlobText(blobPath) : null;
}Also consider returning an error for invalid IDs in the HTTP layer ( 7. 🟡 Captured proxy traffic persisted to disk without redaction (potential credential/token leakage)
DescriptionThe debug proxy capture implementation records full request/response headers and body previews (plus full payload blobs) into a local SQLite DB / blob store without any filtering. This can capture and persist sensitive secrets such as:
Vulnerable code (records headers and first 8KB of bodies): headersJson: JSON.stringify(req.headers),
dataText: body.subarray(0, 8192).toString("utf8"),
...
headersJson: JSON.stringify(upstreamRes.headers),
dataText: responseBody.subarray(0, 8192).toString("utf8"),While this is a debug feature, the change makes it easy to unintentionally retain secrets on disk, and the DB/blob files are created with default permissions (no explicit hardening). RecommendationReduce the risk of secrets being written to disk:
Example header redaction: function redactHeaders(headers: Record<string, unknown>) {
const redacted = { ...headers } as Record<string, unknown>;
for (const key of Object.keys(redacted)) {
const k = key.toLowerCase();
if (["authorization","cookie","set-cookie","x-api-key"].includes(k)) {
redacted[key] = "[REDACTED]";
}
}
return redacted;
}
// when recording
headersJson: JSON.stringify(redactHeaders(req.headers as Record<string, unknown>)),Also document prominently that running the proxy will store secrets and provide a simple purge command (already exists) plus a retention policy. Analyzed PR: #64895 at commit Last updated on: 2026-04-11T17:32:03Z |
Greptile SummaryThis PR adds a proxy capture core (SQLite store, CA, blob storage, proxy server), wires transport capture across provider and channel extensions, and adds a QA Lab capture backend with a UI inspector/timeline. The infrastructure design is solid, but every extension that adds capture hooks bypasses the newly-created
Confidence Score: 4/5Safe to merge after resolving the SDK boundary violations; the boundary break is an architectural correctness issue, not a runtime crash, but it creates enforcement debt that hardens with each passing merge. One P1 (extension boundary violations across five extension packages) and two P2s remain. The P1 doesn't cause a runtime failure today but actively violates the documented plugin SDK contract and leaves captureHttpExchange/captureWsEvent/resolveEffectiveDebugProxyUrl/createDebugProxyWebSocketAgent as undeclared, unversioned public surfaces — which the architecture guide explicitly calls out as the kind of thing that makes later cleanup a major-version break. extensions/discord/src/monitor/gateway-plugin.ts, extensions/telegram/src/fetch.ts, extensions/openai/realtime-voice-provider.ts, extensions/mattermost/src/mattermost/monitor-websocket.ts, extensions/microsoft/speech-provider.ts, extensions/qa-lab/src/lab-server.ts, src/plugin-sdk/proxy-capture.ts Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-plugin.ts
Line: 10-11
Comment:
**Extension boundary violation: direct `src/**` imports**
Extensions must import through `openclaw/plugin-sdk/*`, never from `src/**` directly (see `extensions/CLAUDE.md` and project architecture rules). `captureHttpExchange`, `captureWsEvent`, `resolveEffectiveDebugProxyUrl`, and `createDebugProxyWebSocketAgent` are missing from `src/plugin-sdk/proxy-capture.ts`. These functions should be exported there and every extension import should be rewritten to `openclaw/plugin-sdk/proxy-capture`.
The same violation appears in `extensions/telegram/src/fetch.ts` (lines 14–15), `extensions/openai/realtime-voice-provider.ts` (lines 11–12), `extensions/mattermost/src/mattermost/monitor-websocket.ts` (lines 8–9), and `extensions/microsoft/speech-provider.ts` (line 16), plus `extensions/qa-lab/src/lab-server.ts` lines 17–19 (those three functions are already in the SDK but still imported via direct relative paths).
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-plugin.ts
Line: 246
Comment:
**`wsFlowId` shared across reconnection attempts**
`wsFlowId` is allocated once in `createGatewayPlugin` and captured in the class closure. The gateway plugin configures `reconnect: { maxAttempts: 50 }`, so `startAsync` (and its WebSocket construction + event listeners) can run up to 50 times while sharing this single flow ID. Every `ws-open`, `ws-frame`, and `ws-close` event from all reconnection attempts will be grouped under the same flow, making it impossible to distinguish distinct connection lifetimes in the capture store.
Move the `randomUUID()` call inside the WebSocket setup block (inside `startAsync`) so each connection attempt gets its own flow ID.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/discord/src/monitor/gateway-plugin.ts
Line: 363-378
Comment:
**Double capture when global fetch patch is active**
When `initializeDebugProxyCapture` is called (i.e. `OPENCLAW_DEBUG_PROXY_ENABLED=1`), `globalThis.fetch` is already patched by `installDebugProxyGlobalFetchPatch` to call `captureHttpExchange`. The `fetchImpl` here calls the global `fetch` (now patched) **and then** calls `captureHttpExchange` explicitly, recording each request twice in the capture store. The same issue is present in the proxy-path branch a few lines below.
Consider guarding the explicit call with `if (!settings.enabled)` (inverse) or checking that the transport is undici-based (which bypasses the global fetch patch).
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "Refine QA Lab capture UI" | Re-trigger Greptile |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c5e001e18d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74e2103974
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Addressed the two new concrete follow-ups in Fixed in this push:
Focused validation run after the fix:
The broader Aisle security hardening sweep is still separate from this narrow follow-up. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c52790645f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
openclaw/extensions/qa-lab/src/lab-server.ts
Lines 480 to 482 in 681ba3d
The containment check uses candidate.startsWith(distDir), which is bypassable for sibling paths sharing the same prefix (for example, requesting /../dist2/secret.txt when distDir ends in dist). That lets tryResolveUiAsset serve files outside the intended UI directory instead of falling back to index.html, creating a directory traversal exposure on the QA Lab HTTP server.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
openclaw/extensions/qa-lab/src/lab-server.ts
Lines 480 to 482 in f90acf7
The containment guard uses candidate.startsWith(distDir), which is only a string-prefix check and can be bypassed by sibling paths that share the prefix (for example .../dist-other/...). That means crafted paths like /../dist-other/file can be treated as in-root and served when present, leaking files outside the intended UI bundle directory. Use a real path-boundary check (for example path.relative + ../absolute validation) instead of raw startsWith.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Addressed the new QA Lab asset-path follow-up in Fixed in this push:
Focused validation run after the fix:
The broader Aisle security sweep remains a separate hardening track from these narrow correctness follow-ups. |
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
…64895) * Add proxy capture core and CLI * Expand transport capture coverage * Add QA Lab capture backend * Refine QA Lab capture UI * Fix proxy capture review feedback * Fix proxy run cleanup and TTS capture * Fix proxy capture transport follow-ups * Fix debug proxy CONNECT target parsing * Harden QA Lab asset path containment
Summary
Commit structure
99c33cace0Add proxy capture core and CLI1bc11e3b7aExpand transport capture coverage41daa6899aAdd QA Lab capture backendc5e001e18dRefine QA Lab capture UIValidation
node scripts/test-projects.mjs src/proxy-capture/store.sqlite.test.ts src/proxy-capture/runtime.test.ts src/proxy-capture/coverage.test.ts src/cli/proxy-cli.test.tsnode scripts/test-projects.mjs src/agents/provider-transport-fetch.test.ts src/agents/openai-ws-connection.test.ts extensions/telegram/src/fetch.test.ts extensions/discord/src/monitor/provider.rest-proxy.test.ts extensions/microsoft/speech-provider.test.ts extensions/openai/tts.test.tsnode scripts/test-projects.mjs extensions/qa-lab/src/lab-server.test.tspnpm qa:lab:buildnode scripts/test-projects.mjs extensions/qa-lab/src/lab-server.test.ts src/agents/provider-transport-fetch.test.ts src/proxy-capture/runtime.test.ts src/proxy-capture/coverage.test.tsNotes
src/auto-reply/*, so the scoped commits were recorded with direct targeted validation for this stack