Skip to content

Commit 6d3a834

Browse files
saravmajesticclaude
andcommitted
fix(workspace): carry the validated credential and path instead of re-deriving
Round-3 review findings on #1320. Both are the same shape: a value is validated once, then re-derived after an await gap instead of the validated value being carried through. Credential (ABA). The previous fix compared a credential digest before and after `listDatamates()`, which cannot distinguish "unchanged" from "changed and changed back" — an A->B->A switch passed the comparison while the answer had been served as B. `req()` now accepts `actAs`, and the pin's validation request is handed the exact credential its cache key was built from. There is nothing left to compare when the request and the key are the same credential by construction, so the before/after check is deleted rather than elaborated. `actAs` is additive: every other `req()` and `listDatamates()` call site is untouched and still resolves the ambient credential. The one behavioural difference is documented at the option — a caller passing `actAs` skips the `isConfigured()` gate, which is a file-existence check on the file it has just read, so deleting the credentials file mid-flight no longer aborts that single request. Path. Containment was checked against the caller's directory string, then the identifier was resolved from that same string after the credential and network awaits. A symlink swapped in the gap would be resolved by the second call and not the first, so the path that was authorised and the path that was used need not be the same. `resolveWithinRoot` returns the canonical directory it validated and the caller carries it forward. `withinRoot` stays as the boolean predicate, now expressed in terms of it, so its contract and tests are unchanged. Tests: the verification request carries the captured credential; an A->B->A swap mid-request cannot mis-attribute the answer; the canonical path is what callers receive, including for a directory that does not exist yet. Verified the two failures in `test/altimate/tools/datamate-list-integrations` are pre-existing — they reproduce on a clean tree with these changes stashed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 44af950 commit 6d3a834

5 files changed

Lines changed: 135 additions & 46 deletions

File tree

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

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,27 @@ async function req<T>(
162162
* exchanges and covers the request body too, so a call that uploads
163163
* megabytes (a skill bundle) needs its own. */
164164
timeoutMs?: number
165+
/** Act as THIS credential rather than resolving the ambient one.
166+
*
167+
* `creds()` reads the credentials afresh on every call, so a caller that
168+
* needs its request and its own bookkeeping to be about the same principal
169+
* cannot get that by reading them itself — the request would resolve them
170+
* again, and an account switch in between makes the two disagree. Comparing
171+
* before and after does not close it either: A→B→A passes the comparison
172+
* while the request was served as B. Passing the captured credential is the
173+
* only form that cannot drift.
174+
*
175+
* Callers that pass this have already read the credential, so the
176+
* `isConfigured()` gate inside `creds()` — a file-existence check on the
177+
* same file they just read — is skipped. The one behavioural difference:
178+
* deleting the credentials file mid-flight no longer aborts THIS request.
179+
* It still completes as the principal it captured, and the next call fails
180+
* at its own credential read. */
181+
actAs?: { url: string; instance: string; apiKey: string }
165182
} = {},
166183
): Promise<T> {
167184
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS
168-
const { url, instance, apiKey } = await creds()
185+
const { url, instance, apiKey } = opts.actAs ?? (await creds())
169186
const qs = opts.query ? "?" + new URLSearchParams(opts.query).toString() : ""
170187
const basePath = opts.base ?? "/datamate-project-bindings"
171188
const target = `${url}${basePath}${subpath}${qs}`
@@ -530,14 +547,21 @@ export namespace WorkspaceApi {
530547
* gets. (M5) Filters out non-integer / non-positive ids so a corrupt row
531548
* doesn't reach the picker as a "NaN" label that the caller then binds
532549
* against. */
533-
export async function listDatamates(): Promise<DatamateRef[]> {
550+
/** `actAs` pins the request to a specific credential — see `req`'s `actAs`. Omitted, this
551+
* resolves the ambient credential as every other call does. */
552+
export async function listDatamates(actAs?: {
553+
url: string
554+
instance: string
555+
apiKey: string
556+
}): Promise<DatamateRef[]> {
534557
// Accept THREE response envelopes — today's ``{datamates: [...]}``, a
535558
// bare ``[...]``, and a generic ``{data: [...]}`` — so a backend
536559
// contract change (or compat layer) doesn't silently empty the picker.
537560
// (cubic-dev-ai round 3.)
538561
type Row = { id: number | string; name: string; memory_enabled?: boolean; user_id?: number }
539562
const body = await req<Row[] | { datamates?: Row[]; data?: Row[] }>("GET", "/", {
540563
base: "/datamates",
564+
...(actAs ? { actAs } : {}),
541565
})
542566
let rows: Row[]
543567
if (Array.isArray(body)) {

‎packages/opencode/src/altimate/workspace/pin.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
// session look like a half-populated pin, and the fail-closed rule below would then break
2222
// `--workspace` outright. The two mechanisms are kept apart deliberately, and `readPin` additionally
2323
// stands down outside `serve`.
24+
import { realpathSync } from "node:fs"
2425
import path from "node:path"
2526
import { Filesystem } from "@/util/filesystem"
2627
import { Log } from "@/altimate/util/log"
@@ -63,7 +64,31 @@ export type PinState = { kind: "absent" } | { kind: "invalid"; reason: string }
6364
* project's skills and memory to the pinned workspace.
6465
*/
6566
export function withinRoot(directory: string, root: string): boolean {
66-
return Filesystem.containsReal(root, directory)
67+
return resolveWithinRoot(directory, root) !== null
68+
}
69+
70+
/**
71+
* `withinRoot`, but returning the CANONICAL directory it validated — or `null` when the directory
72+
* is not contained.
73+
*
74+
* Exists because containment is checked once, early, and the caller then does async work
75+
* (credentials, a network round trip) before it needs the directory again. Re-deriving it from the
76+
* caller-supplied string at that point re-opens the window: a symlink swapped in between would be
77+
* resolved the second time and not the first, so the path that was authorised and the path that is
78+
* used need not be the same one. Callers keep this value and use it instead of the raw argument.
79+
*
80+
* The canonical form is the one `resolveProjectIdentifier` would compute — `realpath` where it
81+
* resolves, the normalised absolute path otherwise, so a directory that does not exist yet (which
82+
* `containsReal` accepts, having walked to its nearest existing ancestor) still yields something
83+
* stable to carry forward.
84+
*/
85+
export function resolveWithinRoot(directory: string, root: string): string | null {
86+
if (!Filesystem.containsReal(root, directory)) return null
87+
try {
88+
return realpathSync(directory)
89+
} catch {
90+
return path.resolve(directory)
91+
}
6792
}
6893

6994
/**

‎packages/opencode/src/altimate/workspace/state.ts‎

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import { Log } from "@/altimate/util/log"
2121
// this module's import graph free of the API client at load time.
2222
import type { Binding, ProjectBindingLookup } from "./api-client"
2323
// altimate_change — the IDE extension's workspace pin; see ./pin.ts
24-
import { readPinLogged, withinRoot, type ValidPin } from "./pin"
24+
import { readPinLogged, resolveWithinRoot, type ValidPin } from "./pin"
2525
import { resolveProjectIdentifier } from "./detect"
2626

2727
const CACHE_VERSION = 1
@@ -460,8 +460,8 @@ async function isTransientApiFailure(err: unknown): Promise<boolean> {
460460
* repo remote and project path do not change for the life of a `serve` process. */
461461
const projectIdentifierCache = new Map<string, ReturnType<typeof resolveProjectIdentifier>>()
462462

463-
/** Bounded because the key is a caller-supplied directory. `withinRoot` proves containment, not
464-
* existence, and `serve` is unsecured by default — so a local caller can ask about an unlimited
463+
/** Bounded because the key derives from a caller-supplied directory. `resolveWithinRoot` proves
464+
* containment, not existence, and `serve` is unsecured by default — so a local caller can ask about an unlimited
465465
* number of distinct nonexistent subpaths under the pinned root and grow this map forever. In
466466
* normal use a `serve` process sees one directory, so the ceiling is never approached. */
467467
const PROJECT_IDENTIFIER_CACHE_MAX = 256
@@ -490,12 +490,17 @@ function cachedProjectIdentifier(directory: string): ReturnType<typeof resolvePr
490490
* Correctness was never at stake; this just stops the duplicate round trips. */
491491
const pinValidationInFlight = new Map<string, Promise<{ id: number; name: string }[]>>()
492492

493-
function listDatamatesOnce(cacheKey: string): Promise<{ id: number; name: string }[]> {
493+
function listDatamatesOnce(
494+
cacheKey: string,
495+
actAs: { url: string; instance: string; apiKey: string },
496+
): Promise<{ id: number; name: string }[]> {
494497
const existing = pinValidationInFlight.get(cacheKey)
498+
// Safe to share: `cacheKey` contains the credential digest, so two callers only ever join the
499+
// same request when they are acting as the same credential.
495500
if (existing) return existing
496501
const started = (async () => {
497502
const { WorkspaceApi } = await import("./api-client")
498-
return WorkspaceApi.listDatamates()
503+
return WorkspaceApi.listDatamates(actAs)
499504
})()
500505
pinValidationInFlight.set(cacheKey, started)
501506
// Only the caller that STARTED this request clears it, and only if the slot still holds its own
@@ -520,7 +525,11 @@ async function resolvePinnedBinding(directory: string, pin: ValidPin): Promise<B
520525
// The pin is scoped to the tree `serve` was launched for. `serve` resolves an instance per
521526
// request from the `x-opencode-directory` header and runs unsecured by default, so without this
522527
// any local caller could have an unrelated directory's memory attributed to the pinned workspace.
523-
if (!withinRoot(directory, pin.root)) {
528+
// Keep the path containment actually validated. Everything below awaits — credentials, a network
529+
// round trip — and re-deriving the directory from the caller's string afterwards would authorise
530+
// one path and then use whatever that string resolves to later.
531+
const canonicalDirectory = resolveWithinRoot(directory, pin.root)
532+
if (canonicalDirectory === null) {
524533
log.warn("ignoring workspace pin for a directory outside the pinned root", { directory })
525534
return { status: "unknown" }
526535
}
@@ -552,24 +561,17 @@ async function resolvePinnedBinding(directory: string, pin: ValidPin): Promise<B
552561
let accessible: { id: number; name: string }[] | null = null
553562
let transient = false
554563
try {
555-
accessible = await listDatamatesOnce(cacheKey)
556-
// `listDatamates` does NOT use the snapshot above: `api-client`'s `req()` reads the
557-
// credentials again itself to build the `Authorization` header. So the answer that just
558-
// came back was authorized by whatever credential was current AT THE TIME OF THE REQUEST,
559-
// which is not necessarily the one this cache key was derived from. Caching it under the
560-
// old digest would file the new principal's visibility under the old principal — the same
561-
// class of hole the digest was added to close. Confirm the credential is unchanged before
562-
// trusting the result; if it moved, fail closed and let the next call resolve cleanly under
563-
// stable credentials.
564-
const after = await AltimateApi.getCredentials().catch(() => null)
565-
const accountAfter = after?.altimateApiKey
566-
? createHash("sha256").update(after.altimateApiKey).digest("hex").slice(0, 16)
567-
: null
568-
if (accountAfter !== account) {
569-
log.warn("credentials changed while verifying the pinned workspace; not caching the result")
570-
pinValidation.delete(cacheKey)
571-
return { status: "unknown" }
572-
}
564+
// The request acts as the credential this cache key was derived from, rather than resolving
565+
// the ambient one again. An earlier version compared the credential before and after the
566+
// call instead; that cannot distinguish "unchanged" from "changed and changed back", so an
567+
// A->B->A switch passed the comparison while the answer had been served as B. There is
568+
// nothing left to compare when the request and the key are the same credential by
569+
// construction.
570+
accessible = await listDatamatesOnce(cacheKey, {
571+
url: creds.altimateUrl,
572+
instance: creds.altimateInstanceName,
573+
apiKey: creds.altimateApiKey,
574+
})
573575
} catch (err) {
574576
// Unreachable and unauthorized are different answers and must not collapse: only the former
575577
// earns the stale grace below.
@@ -602,7 +604,7 @@ async function resolvePinnedBinding(directory: string, pin: ValidPin): Promise<B
602604
// down over a network blip.
603605
}
604606

605-
const ident = cachedProjectIdentifier(directory)
607+
const ident = cachedProjectIdentifier(canonicalDirectory)
606608
// Logged on success as well as on every refusal: a silently-working pin is indistinguishable
607609
// from a pin that was never read, which is exactly the ambiguity that makes this hard to support.
608610
log.info("resolved the workspace pinned by the IDE extension", {

‎packages/opencode/test/altimate/workspace/pin.test.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
// Unit coverage for the IDE extension's workspace pin parser. Pure: no cache, no network, no
44
// instance context — `readPin` reads an env bag it is handed, so every case is a plain assertion.
55
import { afterAll, describe, expect, test } from "bun:test"
6-
import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"
6+
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"
77
import os from "node:os"
88
import path from "node:path"
9-
import { readPin, withinRoot } from "../../../src/altimate/workspace/pin"
9+
import { readPin, resolveWithinRoot, withinRoot } from "../../../src/altimate/workspace/pin"
1010

1111
const ROOT = path.resolve("/tmp/pin-root")
1212

@@ -95,6 +95,35 @@ describe("withinRoot — symlink containment", () => {
9595
})
9696
})
9797

98+
describe("resolveWithinRoot — the validated path is what callers carry forward", () => {
99+
const sandbox2 = mkdtempSync(path.join(os.tmpdir(), "pin-canon-"))
100+
const root2 = path.join(sandbox2, "root")
101+
mkdirSync(path.join(root2, "pkg"), { recursive: true })
102+
103+
afterAll(() => rmSync(sandbox2, { recursive: true, force: true }))
104+
105+
test("returns the resolved path, not the caller's spelling", () => {
106+
// `resolveBindingOutcome` validates containment, then awaits credentials and a network call
107+
// before it needs the directory again. Re-deriving it from the caller's string at that point
108+
// would let a symlink swapped in the gap change which path is used. The canonical form is
109+
// captured once, here.
110+
const messy = path.join(root2, ".", "pkg", "..", "pkg")
111+
const got = resolveWithinRoot(messy, root2)
112+
expect(got).toBe(realpathSync(path.join(root2, "pkg")))
113+
})
114+
115+
test("a directory that does not exist yet still yields a stable path", () => {
116+
const got = resolveWithinRoot(path.join(root2, "not-created-yet"), root2)
117+
expect(got).toBe(path.resolve(root2, "not-created-yet"))
118+
})
119+
120+
test("returns null for anything outside the root, matching withinRoot", () => {
121+
const outside = path.resolve("/tmp/definitely-elsewhere")
122+
expect(resolveWithinRoot(outside, root2)).toBeNull()
123+
expect(withinRoot(outside, root2)).toBe(false)
124+
})
125+
})
126+
98127
describe("withinRoot", () => {
99128
test("the root itself and its descendants are in scope", () => {
100129
expect(withinRoot(ROOT, ROOT)).toBe(true)

‎packages/opencode/test/altimate/workspace/state-pin.test.ts‎

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -215,27 +215,36 @@ describe("resolveBindingOutcome — extension pin", () => {
215215
expect((await resolveBindingOutcome(ROOT)).status).toBe("unknown")
216216
})
217217

218-
test("a credential change DURING verification is not cached under the old account", async () => {
219-
// `listDatamates` does not use the snapshot the cache key was built from — `api-client`'s
220-
// `req()` reads credentials again itself. So the answer can be authorized by a different
221-
// principal than the key names, and filing it under the old digest would reopen the hole the
222-
// digest closed.
218+
test("the verification request acts as the credential the cache key was built from", async () => {
219+
// `req()` resolves credentials per call, so reading them here and letting the request read
220+
// them again cannot guarantee both saw the same principal. The request is handed the captured
221+
// credential instead; this asserts it actually arrives.
223222
setPin()
224-
let swapped = false
225-
;(WorkspaceApi as unknown as { listDatamates: () => Promise<unknown> }).listDatamates =
226-
async () => {
227-
// Rotate the credential mid-request, as an account switch would.
228-
if (!swapped) {
229-
swapped = true
230-
stubCreds("rotated-key")
231-
}
223+
let sawActAs: { apiKey?: string } | undefined
224+
;(WorkspaceApi as unknown as { listDatamates: (a?: unknown) => Promise<unknown> }).listDatamates =
225+
async (actAs?: unknown) => {
226+
sawActAs = actAs as { apiKey?: string }
232227
return [{ id: 237, name: "activity_test" }]
233228
}
234-
expect((await resolveBindingOutcome(ROOT)).status).toBe("unknown")
229+
expect((await resolveBindingOutcome(ROOT)).status).toBe("bound")
230+
expect(sawActAs?.apiKey).toBe("k")
231+
})
235232

236-
// And nothing was memoized: with stable credentials the next call verifies for real.
237-
stubList([{ id: 237, name: "activity_test" }])
233+
test("an A->B->A credential swap during verification cannot mis-attribute the answer", async () => {
234+
// The ABA case a before/after comparison cannot see: the digest matches at both ends while the
235+
// request was served as B. Threading the credential removes the question — the request carries
236+
// A, so the answer is A's regardless of what the ambient credential did meanwhile.
237+
setPin()
238+
let sawActAs: { apiKey?: string } | undefined
239+
;(WorkspaceApi as unknown as { listDatamates: (a?: unknown) => Promise<unknown> }).listDatamates =
240+
async (actAs?: unknown) => {
241+
sawActAs = actAs as { apiKey?: string }
242+
stubCreds("rotated-key") // A -> B
243+
stubCreds("k") // B -> A, which a before/after check would read as "unchanged"
244+
return [{ id: 237, name: "activity_test" }]
245+
}
238246
expect((await resolveBindingOutcome(ROOT)).status).toBe("bound")
247+
expect(sawActAs?.apiKey).toBe("k")
239248
})
240249

241250
test("concurrent resolutions share one listDatamates request", async () => {

0 commit comments

Comments
 (0)