Skip to content

Commit d7ff8d3

Browse files
fix: mask endpoints by route vocabulary, keep the status of a body that fails after the answer
Only known static route words survive in the endpoint label, so an id spelled like a word is still masked; a body refused after the server answered (readBounded's cap) reports that answer's status class. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE
1 parent 0ffaa66 commit d7ff8d3

2 files changed

Lines changed: 60 additions & 14 deletions

File tree

‎packages/opencode/src/altimate/workspace/api-client.ts‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,21 @@ async function creds(): Promise<{ url: string; instance: string; apiKey: string
178178
// `workspace_api_error` (or `workspace_auth_expired` on 401/403) with the endpoint masked of
179179
// ids; the link lifecycle functions below report linked / created / switched / unlinked on the
180180
// success response and `workspace_link_failed` with a reason class otherwise.
181-
/** "METHOD /base/path" with every dynamic segment replaced by ":id". Route words are lowercase
182-
* letters with hyphens or underscores (or a version like v3); anything else — numeric ids,
183-
* uuids, memory and skill public ids — is an identifier and must not reach telemetry. */
181+
/** The static segments of the routes the workspace clients call. Anything not in this list —
182+
* numeric ids, uuids, memory ids, skill public ids however they are spelled — is replaced by
183+
* ":id" in telemetry. A new static word that is missing here is masked too, which only costs
184+
* detail; the list must never be widened with a dynamic value. */
185+
const ROUTE_WORDS = new Set([
186+
"datamate-project-bindings", "bind", "by-remote", "by-path", "datamates", "users", "me",
187+
"memory", "blocks", "skills", "files", "list", "attach", "publish", "sync", "status", "search",
188+
"versions", "lessons", "learned-lessons", "content", "download",
189+
])
190+
191+
/** "METHOD /base/path" with every dynamic segment replaced by ":id" (see ROUTE_WORDS). */
184192
export function endpointOf(method: string, basePath: string, subpath: string): string {
185193
const masked = `${basePath}${subpath}`
186194
.split("/")
187-
.map((seg) => (seg === "" || /^(v\d+|[a-z][a-z_-]*)$/.test(seg) ? seg : ":id"))
195+
.map((seg) => (seg === "" || ROUTE_WORDS.has(seg) ? seg : ":id"))
188196
.join("/")
189197
return `${method} ${masked}`
190198
}
@@ -334,6 +342,7 @@ async function req<T>(
334342
const timeout = setTimeout(() => controller.abort(), timeoutMs)
335343
let res: Response
336344
let text: string
345+
let answered: number | undefined // the status once the server answered, for the catch below
337346
try {
338347
res = await fetch(target, {
339348
method,
@@ -345,6 +354,7 @@ async function req<T>(
345354
signal: controller.signal,
346355
...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
347356
})
357+
answered = res.status
348358
// Keep the AbortController timeout ACTIVE while we read the response body.
349359
// ``fetch()`` resolves after headers arrive; a server can send headers then
350360
// stall the body stream indefinitely, so pulling the body inside the same
@@ -379,13 +389,19 @@ async function req<T>(
379389
`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`,
380390
)
381391
}
382-
// A WorkspaceApiError here came from readBounded(): the server answered, the body was
383-
// over the cap. Everything else is transport.
384-
reportApiError({
385-
endpoint,
386-
kind: err instanceof WorkspaceApiError ? "response" : "network",
387-
workspaceId: bodyWorkspaceId,
388-
})
392+
// The server answered and the body failed afterwards (readBounded's cap, a cut stream):
393+
// classify by the status it answered with, so an oversized 500 is still a 5xx row; only a
394+
// usable status with a bad body is "response". Before any answer it is transport.
395+
if (answered !== undefined) {
396+
reportApiError({
397+
endpoint,
398+
status: answered,
399+
kind: answered >= 500 ? "5xx" : answered >= 400 ? "4xx" : "response",
400+
workspaceId: bodyWorkspaceId,
401+
})
402+
} else {
403+
reportApiError({ endpoint, kind: "network", workspaceId: bodyWorkspaceId })
404+
}
389405
const msg = err instanceof Error ? err.message : String(err)
390406
throw new WorkspaceApiError(`Cannot reach ${target}: ${msg}`)
391407
} finally {

‎packages/opencode/test/altimate/workspace/link-telemetry.test.ts‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,16 @@ writeFileSync(
1515
JSON.stringify({ altimateUrl: API_URL, altimateInstanceName: "acme", altimateApiKey: "test-key" }),
1616
)
1717

18-
const { WorkspaceApi, linkFailureReason, endpointOf, WorkspaceApiError, NotFoundError, ForbiddenError, ConflictError } =
19-
await import("../../../src/altimate/workspace/api-client")
18+
const {
19+
WorkspaceApi,
20+
linkFailureReason,
21+
endpointOf,
22+
altimateRequest,
23+
WorkspaceApiError,
24+
NotFoundError,
25+
ForbiddenError,
26+
ConflictError,
27+
} = await import("../../../src/altimate/workspace/api-client")
2028
const { Telemetry } = await import("../../../src/altimate/telemetry")
2129

2230
type Reply = { status: number; body?: unknown } | { throw: Error } | { hang: true }
@@ -215,13 +223,35 @@ describe("workspace link telemetry", () => {
215223
expect(endpointOf("POST", "/datamates", "/42/skills/pub_Ab12Cd/attach")).toBe(
216224
"POST /datamates/:id/skills/:id/attach",
217225
)
218-
expect(endpointOf("GET", "/dbt", "/v3/validate-credentials")).toBe("GET /dbt/v3/validate-credentials")
226+
// Spelling is not evidence: a public id that looks like a route word is still an id.
227+
expect(endpointOf("GET", "/skills", "/pub-many")).toBe("GET /skills/:id")
228+
expect(endpointOf("GET", "/datamates", "/42/skills/pub_Ab12Cd/files/readme.md")).toBe(
229+
"GET /datamates/:id/skills/:id/files/:id",
230+
)
219231

220232
replies = [{ status: 200 }] // 2xx with an empty body where JSON was required
221233
await expect(WorkspaceApi.listDatamates()).rejects.toThrow(/Empty 200 body/)
222234
expect(of("workspace_api_error")).toEqual([expect.objectContaining({ status_class: "response", status: 200 })])
223235
})
224236

237+
test("a body that fails after the server answered keeps the answer's status class", async () => {
238+
// Oversized 500: readBounded() refuses the body before the status branch; the row is still a 5xx.
239+
globalThis.fetch = (async (_input: string | URL | Request, _init?: RequestInit) =>
240+
new Response("x", { status: 500, headers: { "content-length": "100000000" } })) as typeof globalThis.fetch
241+
await expect(altimateRequest("GET", "/x", { base: "/datamates", boundResponse: true })).rejects.toBeInstanceOf(
242+
WorkspaceApiError,
243+
)
244+
expect(of("workspace_api_error")).toEqual([expect.objectContaining({ status_class: "5xx", status: 500 })])
245+
246+
events = []
247+
globalThis.fetch = (async (_input: string | URL | Request, _init?: RequestInit) =>
248+
new Response("x", { status: 200, headers: { "content-length": "100000000" } })) as typeof globalThis.fetch
249+
await expect(altimateRequest("GET", "/x", { base: "/datamates", boundResponse: true })).rejects.toBeInstanceOf(
250+
WorkspaceApiError,
251+
)
252+
expect(of("workspace_api_error")).toEqual([expect.objectContaining({ status_class: "response", status: 200 })])
253+
})
254+
225255
test("linkFailureReason classifies every error the client throws", () => {
226256
expect(linkFailureReason(new ForbiddenError("f"))).toBe("auth")
227257
expect(linkFailureReason(new WorkspaceApiError("unauthorized", 401))).toBe("auth")

0 commit comments

Comments
 (0)