Repository navigation
fix(credentials): clean up empty legacy credentials.json on upgrade #3119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
d0ec779
0a089df
8e22ede
a6561ad
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -383,6 +383,75 @@ export function removeLegacyCredentialsFile(): void { | |
| secureUnlink(legacyFile); | ||
| } | ||
|
|
||
| /** | ||
| * Securely remove the legacy plaintext credentials.json *iff* it carries | ||
| * no migratable credential payload — i.e. it's an empty `{}`, contains | ||
| * only keys outside `KNOWN_CREDENTIAL_ENV_KEYS`, or every allowlisted key | ||
| * has a blank/non-string value. Used by the onboard completion path to | ||
| * clean up the stale empty file left behind on upgrades from pre-gateway | ||
| * NemoClaw versions (#3105). | ||
| * | ||
| * Refuses to act on a missing/symlinked/oversized/non-JSON/non-object | ||
| * file — those are either nothing-to-do or "leave for inspection" cases | ||
| * that the regular migration path already handles. Returns `true` only | ||
| * if the file was actually removed. | ||
| */ | ||
| export function removeLegacyCredentialsFileIfEmpty(): boolean { | ||
| const legacyFile = getCredsFile(); | ||
|
|
||
| try { | ||
| rejectSymlinksOnPath(path.dirname(legacyFile)); | ||
| } catch { | ||
| return false; | ||
| } | ||
|
|
||
| let fd: number; | ||
| try { | ||
| fd = fs.openSync(legacyFile, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); | ||
| } catch { | ||
| return false; | ||
| } | ||
|
|
||
| let raw: string; | ||
| try { | ||
| const stat = fs.fstatSync(fd); | ||
| if (!stat.isFile()) return false; | ||
| if (stat.size > LEGACY_CREDS_FILE_MAX_BYTES) return false; | ||
| raw = fs.readFileSync(fd, "utf-8"); | ||
| } catch { | ||
| return false; | ||
| } finally { | ||
| try { | ||
| fs.closeSync(fd); | ||
| } catch { | ||
| /* fd already closed; ignore */ | ||
| } | ||
| } | ||
|
|
||
| let parsed: unknown; | ||
| try { | ||
| parsed = JSON.parse(raw); | ||
| } catch { | ||
| return false; | ||
| } | ||
|
|
||
| if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { | ||
| return false; | ||
| } | ||
|
|
||
| const allowed = new Set<string>(KNOWN_CREDENTIAL_ENV_KEYS); | ||
| for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) { | ||
| if (!allowed.has(key)) continue; | ||
| if (typeof value !== "string") continue; | ||
| if (normalizeCredentialValue(value)) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| secureUnlink(legacyFile); | ||
|
Comment on lines
+415
to
+459
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't inspect one inode and delete another. The emptiness check is done on the fd-backed inode you read here, but Line 459 deletes by pathname after that fd has been closed. If another process replaces 🤖 Prompt for AI Agents |
||
| return true; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| /** | ||
| * Read a secret value from a TTY without echoing typed characters | ||
| * (asterisks are written instead). Resolves to the trimmed answer or | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| // Post-upgrade stale-file cleanup. | ||
| // | ||
| // As NemoClaw evolves, host-side state migrates: older versions wrote files | ||
| // under the user's home that newer versions no longer use. Each entry in | ||
| // STALE_FILES owns the safety logic for one specific stale file and reports | ||
| // back when it actually removed something. The runner invokes them all once | ||
| // during the onboard completion path so a fresh post-upgrade onboard sweeps | ||
| // every leftover in a single uniform pass. Adding a future cleanup is one | ||
| // entry on STALE_FILES; the loop does not change. If a future leftover is a | ||
| // folder or symlink instead of a file, widen the shape at that point. | ||
|
|
||
| import { removeLegacyCredentialsFileIfEmpty } from "./credentials"; | ||
|
|
||
| interface StaleHostFile { | ||
| /** Human-readable description for the success log line. */ | ||
| readonly description: string; | ||
| /** | ||
| * Atomically inspect-and-remove the file iff its safety guards | ||
| * permit it. Returns true iff the file was actually removed. | ||
| * Splitting "is-removable?" from "remove" would be TOCTOU-unsafe, | ||
| * so each entry exposes a single combined operation. | ||
| */ | ||
| readonly tryRemove: () => boolean; | ||
| } | ||
|
|
||
| const STALE_FILES: readonly StaleHostFile[] = [ | ||
| { | ||
| description: "~/.nemoclaw/credentials.json (no migratable credentials)", | ||
| tryRemove: removeLegacyCredentialsFileIfEmpty, | ||
| }, | ||
| ]; | ||
|
|
||
| /** | ||
| * Sweep every registered stale host file left behind by older NemoClaw | ||
| * versions. Best-effort: a failure inside one entry is logged to stderr | ||
| * but never aborts the others or the surrounding onboard. Logs a single | ||
| * line to stdout per file actually removed so the user can audit what | ||
| * changed. Safe to call after a successful onboard regardless of which | ||
| * migration paths fired earlier — every entry is a no-op when its | ||
| * target doesn't exist or doesn't satisfy the entry's safety rules. | ||
| */ | ||
| export function cleanupStaleHostFiles(): void { | ||
| for (const file of STALE_FILES) { | ||
| try { | ||
| if (file.tryRemove()) { | ||
| console.log(` Removed stale ${file.description}.`); | ||
| } | ||
| } catch (error) { | ||
| console.error( | ||
| ` Skipped stale-file cleanup ${file.description}: ${ | ||
| error instanceof Error ? error.message : String(error) | ||
| }`, | ||
| ); | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import fs from "node:fs"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { KNOWN_CREDENTIAL_ENV_KEYS } from "../dist/lib/credentials.js"; | ||
| import { cleanupStaleHostFiles } from "../dist/lib/host-artifact-cleanup.js"; | ||
|
|
||
| const TRACKED_ENV_KEYS = [...KNOWN_CREDENTIAL_ENV_KEYS]; | ||
|
|
||
| function clearTrackedEnv() { | ||
| for (const key of TRACKED_ENV_KEYS) { | ||
| delete process.env[key]; | ||
| } | ||
| } | ||
|
|
||
| function captureConsole<T>(fn: () => T): { result: T; stdout: string[]; stderr: string[] } { | ||
| const stdout: string[] = []; | ||
| const stderr: string[] = []; | ||
| const origLog = console.log; | ||
| const origErr = console.error; | ||
| console.log = (...args: unknown[]) => { | ||
| stdout.push(args.map((a) => String(a)).join(" ")); | ||
| }; | ||
| console.error = (...args: unknown[]) => { | ||
| stderr.push(args.map((a) => String(a)).join(" ")); | ||
| }; | ||
| try { | ||
| const result = fn(); | ||
| return { result, stdout, stderr }; | ||
| } finally { | ||
| console.log = origLog; | ||
| console.error = origErr; | ||
| } | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| clearTrackedEnv(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| clearTrackedEnv(); | ||
| vi.restoreAllMocks(); | ||
| vi.unstubAllEnvs(); | ||
| }); | ||
|
|
||
| describe("cleanupStaleHostFiles (post-upgrade sweep, #3105)", () => { | ||
| it("removes an empty legacy credentials.json and logs the removal", () => { | ||
| const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cleanup-")); | ||
| const credsDir = path.join(home, ".nemoclaw"); | ||
| const legacyFile = path.join(credsDir, "credentials.json"); | ||
| fs.mkdirSync(credsDir, { recursive: true }); | ||
| fs.writeFileSync(legacyFile, "{}", { mode: 0o600 }); | ||
| vi.stubEnv("HOME", home); | ||
|
|
||
| const { stdout, stderr } = captureConsole(() => cleanupStaleHostFiles()); | ||
|
|
||
| expect(fs.existsSync(legacyFile)).toBe(false); | ||
| expect(stdout.join("\n")).toMatch(/Removed stale .*credentials\.json/); | ||
| expect(stderr).toEqual([]); | ||
| }); | ||
|
|
||
| it("keeps a credentials.json carrying real credentials and logs nothing", () => { | ||
| const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cleanup-")); | ||
| const credsDir = path.join(home, ".nemoclaw"); | ||
| const legacyFile = path.join(credsDir, "credentials.json"); | ||
| fs.mkdirSync(credsDir, { recursive: true }); | ||
| const payload = JSON.stringify({ NVIDIA_API_KEY: "nvapi-real" }); | ||
| fs.writeFileSync(legacyFile, payload, { mode: 0o600 }); | ||
| vi.stubEnv("HOME", home); | ||
|
|
||
| const { stdout, stderr } = captureConsole(() => cleanupStaleHostFiles()); | ||
|
|
||
| expect(fs.existsSync(legacyFile)).toBe(true); | ||
| expect(fs.readFileSync(legacyFile, "utf-8")).toBe(payload); | ||
| expect(stdout).toEqual([]); | ||
| expect(stderr).toEqual([]); | ||
| }); | ||
|
|
||
| it("is a no-op (and emits no log) when no stale file exists", () => { | ||
| const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cleanup-")); | ||
| vi.stubEnv("HOME", home); | ||
|
|
||
| const { stdout, stderr } = captureConsole(() => cleanupStaleHostFiles()); | ||
|
|
||
| expect(stdout).toEqual([]); | ||
| expect(stderr).toEqual([]); | ||
| }); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.