From 8140be7ad5745b325579e78bf418182e686c4a6e Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 5 Dec 2026 07:43:22 +0800 Subject: [PATCH] fix(workspace): a blank field in `altimate.json` reads as signed out, not as an unreadable link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `getCredentials()` throws a typed `IncompleteCredentials` with a plain message when only required fields are blank; the strict binding read and `backendConfig()` treat it as signed out. Bad JSON, an unset `${env:…}` or other schema faults still fail closed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvpym19ATbtFL8LaB6b --- packages/opencode/src/altimate/api/client.ts | 26 +++++- .../src/altimate/integrations/backend.ts | 1 + .../opencode/src/altimate/workspace/state.ts | 14 ++- .../opencode/test/altimate/datamate.test.ts | 20 +++- .../test/altimate/integrations.test.ts | 16 ++++ .../altimate/workspace/engine-overlay.test.ts | 93 +++++++++++++++++++ 6 files changed, 163 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 2c361c698f..7ec606efad 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -107,6 +107,22 @@ export namespace AltimateApi { return obj } + /** The credentials file is there but a required field is blank: signed out, not unreadable. */ + export class IncompleteCredentials extends Error { + constructor(readonly fields: string[]) { + super(`Altimate sign-in is incomplete (${fields.join(", ")} must not be blank); sign in again`) + this.name = "IncompleteCredentials" + } + } + + const REQUIRED_FIELDS = ["altimateUrl", "altimateInstanceName", "altimateApiKey"] as const + + function blankRequiredFields(raw: unknown): string[] { + if (!raw || typeof raw !== "object") return [] + const record = raw as Record + return REQUIRED_FIELDS.filter((field) => typeof record[field] === "string" && record[field].trim() === "") + } + export async function getCredentials(): Promise { const scoped = currentCredentials() if (scoped) return scoped @@ -115,7 +131,15 @@ export namespace AltimateApi { throw new Error(`Altimate credentials not found at ${p}`) } const raw = resolveEnvVars(JSON.parse(await Filesystem.readText(p))) - const creds = AltimateCredentials.parse(raw) + const parsed = AltimateCredentials.safeParse(raw) + if (!parsed.success) { + const blank = blankRequiredFields(raw) + // Only blank required fields: a sign-in that was never finished, not a file that can't be read. + if (blank.length > 0 && parsed.error.issues.every((issue) => blank.includes(String(issue.path[0])))) + throw new IncompleteCredentials(blank) + throw parsed.error + } + const creds = parsed.data return { ...creds, altimateUrl: creds.altimateUrl.replace(/\/+$/, ""), diff --git a/packages/opencode/src/altimate/integrations/backend.ts b/packages/opencode/src/altimate/integrations/backend.ts index 60591c3f3a..5479bf42a0 100644 --- a/packages/opencode/src/altimate/integrations/backend.ts +++ b/packages/opencode/src/altimate/integrations/backend.ts @@ -52,6 +52,7 @@ export async function backendConfig(): Promise { if (env.url && env.tenant && env.token) return { apiUrl: env.url.replace(/\/+$/, ""), tenant: env.tenant, token: env.token } const creds = await AltimateApi.getCredentials().catch((e) => { if (e instanceof Error && /credentials not found/i.test(e.message)) return null + if (e instanceof AltimateApi.IncompleteCredentials) return null throw new Error(`Could not read your Altimate login (${e instanceof Error ? e.message : e}). Fix or remove the credentials file, then sign in again.`) }) const apiUrl = (creds?.altimateUrl || "").replace(/\/+$/, "") diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index 27ab89422a..a391f1ed4c 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -303,15 +303,19 @@ export async function readLocalBindingScoped( } /** `readLocalBindingScoped` for the engine overlay, which must not mistake an - * unreadable link for an unlinked directory. Absent credentials or an absent - * cache file still read as unbound; a credentials or cache file that is - * present and cannot be read or parsed throws instead. */ + * unreadable link for an unlinked directory. Absent credentials, credentials + * with a blank required field (signed out) or an absent cache file still read + * as unbound; a credentials or cache file that is present and cannot be read + * or parsed throws instead. */ export async function readLocalBindingScopedStrict( directory: string, ): Promise<{ binding: CachedBinding | null; scope: string | null }> { if (!(await AltimateApi.isConfigured())) return { binding: null, scope: null } - const c = await AltimateApi.getCredentials() - if (!c.altimateApiKey) return { binding: null, scope: null } + const c = await AltimateApi.getCredentials().catch((err) => { + if (err instanceof AltimateApi.IncompleteCredentials) return null + throw err + }) + if (!c?.altimateApiKey) return { binding: null, scope: null } const key = { tenant: c.altimateInstanceName, apiUrl: c.altimateUrl, diff --git a/packages/opencode/test/altimate/datamate.test.ts b/packages/opencode/test/altimate/datamate.test.ts index 3d5e1031f0..26d27a9ecf 100644 --- a/packages/opencode/test/altimate/datamate.test.ts +++ b/packages/opencode/test/altimate/datamate.test.ts @@ -208,15 +208,33 @@ describe("getCredentials", () => { try { // A set-but-empty variable is substituted (only an unset one is "not found"), and a blank // instance name or key is refused: loaded, it sent gateway requests with no usable credential. - const error = String(await AltimateApi.getCredentials().catch((e) => e)) + const thrown = await AltimateApi.getCredentials().catch((e) => e) + const error = String(thrown) expect(error).toContain("altimateInstanceName") expect(error).toContain("must not be blank") expect(error).not.toContain("not found") + // A typed, plain-worded refusal callers can read as signed out, never Zod's issue JSON. + expect(thrown).toBeInstanceOf(AltimateApi.IncompleteCredentials) + expect(thrown.fields).toEqual(["altimateInstanceName"]) + expect(error).toContain("sign in again") + expect(error).not.toContain('"code"') } finally { delete process.env.TEST_EMPTY_VAR } }) + test("a blank field beside another schema fault is not read as an incomplete sign-in", async () => { + const altDir = path.join(testHome, ".altimate") + await fsp.mkdir(altDir, { recursive: true }) + await fsp.writeFile( + path.join(altDir, "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.myaltimate.com", altimateInstanceName: "", altimateApiKey: 7 }), + ) + const thrown = await AltimateApi.getCredentials().catch((e) => e) + expect(thrown).toBeInstanceOf(Error) + expect(thrown).not.toBeInstanceOf(AltimateApi.IncompleteCredentials) + }) + test("leaves literal values unchanged when no substitution syntax present", async () => { const altDir = path.join(testHome, ".altimate") await fsp.mkdir(altDir, { recursive: true }) diff --git a/packages/opencode/test/altimate/integrations.test.ts b/packages/opencode/test/altimate/integrations.test.ts index 14952f6804..51803c620d 100644 --- a/packages/opencode/test/altimate/integrations.test.ts +++ b/packages/opencode/test/altimate/integrations.test.ts @@ -3655,4 +3655,20 @@ describe("saved login", () => { corrupt.mockRestore() } }) + + test("a blank field in the credentials file is signed out; a file that does not parse is still an error", async () => { + const file = AltimateApi.credentialsPath() + fs.mkdirSync(path.dirname(file), { recursive: true }) + try { + for (const field of ["altimateUrl", "altimateInstanceName", "altimateApiKey"]) { + const login = { altimateUrl: "https://api.acme.example", altimateInstanceName: "acme", altimateApiKey: "fake-key" } + fs.writeFileSync(file, JSON.stringify({ ...login, [field]: "" })) + expect(await backend.backendConfig()).toBeNull() + } + fs.writeFileSync(file, "{ not json") + await expect(backend.backendConfig()).rejects.toThrow("Could not read your Altimate login") + } finally { + fs.rmSync(file, { force: true }) + } + }) }) diff --git a/packages/opencode/test/altimate/workspace/engine-overlay.test.ts b/packages/opencode/test/altimate/workspace/engine-overlay.test.ts index 601a853366..499b916117 100644 --- a/packages/opencode/test/altimate/workspace/engine-overlay.test.ts +++ b/packages/opencode/test/altimate/workspace/engine-overlay.test.ts @@ -32,6 +32,9 @@ import type { AttachSnapshot } from "../../../src/altimate/workspace/attach-snap import { Telemetry } from "../../../src/altimate/telemetry" import { log } from "../../../src/altimate/workspace/engine-seams" import { DATAMATE_KEY } from "../../../src/altimate/datamate-transport" +import { AltimateApi } from "../../../src/altimate/api/client" +import { mkdirSync, rmSync, writeFileSync } from "node:fs" +import path from "node:path" const DIR = "/tmp/analytics" const ORIGINAL_FLAG = process.env.ALTIMATE_DISABLE_WORKSPACE @@ -1360,3 +1363,93 @@ describe("telemetry — the attach", () => { expect(String(errors[0].message)).not.toContain("/home/someone") }) }) + +describe("a blank field in altimate.json — signed out, not an unreadable link", () => { + // The real binding read, against a credentials file under the test home. + const credsFile = () => AltimateApi.credentialsPath() + const writeCreds = (content: string) => { + mkdirSync(path.dirname(credsFile()), { recursive: true }) + writeFileSync(credsFile(), content) + } + const creds = (overrides: Record) => + JSON.stringify({ + altimateUrl: "https://api.acme.example", + altimateInstanceName: "acme", + altimateApiKey: "fake-key", + ...overrides, + }) + const realRead = () => { + delete syncInternals.resolveBinding + } + afterEach(() => { + rmSync(credsFile(), { force: true }) + delete process.env.TEST_BLANK_CRED + }) + + for (const field of ["altimateUrl", "altimateInstanceName", "altimateApiKey"]) { + test(`a blank ${field} reads as unbound, with no refusal announced`, async () => { + const h = install({ mcp: { datamate: HOSTED_ENTRY } }) + realRead() + writeCreds(creds({ [field]: " " })) + await syncInternals.config!.get() + await beforeTurn("s1") + expect(settledOutcome("s1")).toEqual({ kind: "unbound" }) + expect(h.toasts).toEqual([]) + expect(h.lines).toEqual([]) + // Left as an unbound directory leaves it: the user's own entry is untouched. + expect(h.config.mcp).toEqual({ datamate: HOSTED_ENTRY }) + expect(h.removes).toBe(0) + expect(managedWorkspace()).toBeNull() + }) + } + + test("a field blank after ${env:…} resolution reads as unbound", async () => { + const h = install({}) + realRead() + process.env.TEST_BLANK_CRED = "" + writeCreds(creds({ altimateApiKey: "${env:TEST_BLANK_CRED}" })) + await beforeTurn("s1") + expect(settledOutcome("s1")).toEqual({ kind: "unbound" }) + expect(h.toasts).toEqual([]) + }) + + test("blanking a field while attached releases the key without a refusal", async () => { + const h = install({}) + await beforeTurn("s1") + expect(settledOutcome("s1")?.kind).toBe("attached") + realRead() + writeCreds(creds({ altimateInstanceName: "" })) + await beforeTurn("s1") + expect(settledOutcome("s1")).toEqual({ kind: "unbound" }) + expect(h.removes).toBe(1) + expect(managedWorkspace()).toBeNull() + expect(h.toasts.map((t) => t.title)).not.toContain('Workspace "analytics": link could not be read') + }) + + test("a credentials file that does not parse still fails closed", async () => { + const h = install({}) + realRead() + writeCreds("{ not json") + await beforeTurn("s1") + expect(settledOutcome("s1")).toEqual({ kind: "connect-failed", error: "the workspace link could not be read" }) + expect(h.toasts.map((t) => t.title)).toEqual(["Workspace link could not be read"]) + }) + + test("an unset ${env:…} variable still fails closed", async () => { + const h = install({}) + realRead() + writeCreds(creds({ altimateApiKey: "${env:TEST_BLANK_CRED}" })) + await beforeTurn("s1") + expect(settledOutcome("s1")?.kind).toBe("connect-failed") + expect(h.toasts.map((t) => t.title)).toEqual(["Workspace link could not be read"]) + }) + + test("a blank field next to another schema fault still fails closed", async () => { + const h = install({}) + realRead() + writeCreds(JSON.stringify({ altimateUrl: "https://api.acme.example", altimateInstanceName: "", altimateApiKey: 7 })) + await beforeTurn("s1") + expect(settledOutcome("s1")?.kind).toBe("connect-failed") + expect(h.toasts).toHaveLength(1) + }) +})