diff --git a/desktop/e2e/fixtures/mock-devsy.cjs b/desktop/e2e/fixtures/mock-devsy.cjs index b79922e3b5..ca70346a23 100755 --- a/desktop/e2e/fixtures/mock-devsy.cjs +++ b/desktop/e2e/fixtures/mock-devsy.cjs @@ -77,6 +77,14 @@ function defaultState() { context: "default", }, ], + secrets: [ + { name: "E2E_API_TOKEN", context: "default", backend: "file", availability: "available", attached: true, created: "2026-04-20T08:00:00Z" }, + { name: "E2E_STAGING_TOKEN", context: "staging", backend: "keyring", availability: "available", attached: false }, + ], + envVars: [ + { name: "E2E_API_URL", context: "default", value: "https://variables.example.test/api", attached: true }, + { name: "E2E_STAGE_NAME", context: "staging", value: "staging", attached: false }, + ], tasks: {}, deletedTasks: {}, } @@ -86,6 +94,8 @@ function loadState() { try { const data = fs.readFileSync(STATE_FILE, "utf8") const state = JSON.parse(data) + state.secrets ??= defaultState().secrets + state.envVars ??= defaultState().envVars state.tasks = state.tasks || {} state.deletedTasks = state.deletedTasks || {} return state @@ -121,6 +131,10 @@ function saveState(state, deletedTaskIds = []) { const state = loadState() const rawArgs = process.argv.slice(2) +// Context is a global flag and can precede the root command. +const contextIndex = rawArgs.indexOf("--context") +const variableContext = contextIndex >= 0 ? rawArgs[contextIndex + 1] : "default" +if (contextIndex >= 0) rawArgs.splice(contextIndex, 2) if (rawArgs[0] === "--version") { process.stdout.write("v0.1.0-test\n") @@ -864,6 +878,30 @@ switch (cmd) { } break + case "secret": + case "env": { + const rows = cmd === "secret" ? state.secrets : state.envVars + if (sub === "protection" && extra === "status") { + out({ availability: "available", keySource: "file", remembered: false, + rememberedAvailable: true, fileEntries: state.secrets.filter((row) => row.backend === "file") }) + } else if (sub === "list") out(rows) + else if (["set", "delete", "attach", "detach"].includes(sub)) { + const index = rows.findIndex((row) => row.name === extra && row.context === variableContext) + if (sub === "set") { + const row = cmd === "secret" + ? { name: extra, context: variableContext, backend: "file", availability: "available", attached: false } + : { name: extra, context: variableContext, value: rawArgs[rawArgs.indexOf("--value") + 1] ?? "", attached: false } + if (cmd === "secret" && rawArgs.includes("--stdin")) fs.readFileSync(0, "utf8") + if (index >= 0) rows[index] = { ...rows[index], ...row, attached: rows[index].attached } + else rows.push(row) + } else if (sub === "delete" && index >= 0) rows.splice(index, 1) + else if (index >= 0) rows[index].attached = sub === "attach" + saveState(state) + out("") + } else out("") + break + } + case "version": out("v0.1.0-test") break diff --git a/desktop/e2e/variables.e2e.ts b/desktop/e2e/variables.e2e.ts new file mode 100644 index 0000000000..7a75e88d3b --- /dev/null +++ b/desktop/e2e/variables.e2e.ts @@ -0,0 +1,134 @@ +import type { ElectronApplication, Page } from "@playwright/test" +import { expect, test } from "@playwright/test" +import { launchApp } from "./electron-app.js" + +let app: ElectronApplication +let page: Page + +async function navigate(hash: string) { + await page.evaluate((route) => { + window.location.hash = route + }, hash) + await expect( + page.getByRole("heading", { name: "Workspace Variables", exact: true }), + ).toBeVisible() +} + +test.beforeAll(async () => { + ;({ app, page } = await launchApp()) +}) +test.afterAll(async () => { + await app.close() +}) + +test("unified navigation uses URL tabs and replaces legacy routes", async () => { + const sidebar = page.locator('[data-sidebar="sidebar"]') + await sidebar.locator('a[href="#/variables"]').click() + await expect( + page.getByRole("tab", { name: "Secrets", exact: true }), + ).toHaveAttribute("aria-selected", "true") + await expect( + sidebar.locator('a[href="#/secrets"], a[href="#/env"]'), + ).toHaveCount(0) + await page + .getByRole("tab", { name: "Environment Variables", exact: true }) + .click() + await expect(page).toHaveURL(/#\/variables\?tab=env$/) + await navigate("/secrets") + await expect(page).toHaveURL(/#\/variables\?tab=secrets$/) + await navigate("/env") + await expect(page).toHaveURL(/#\/variables\?tab=env$/) +}) + +test("legacy keyboard shortcuts select both variables tabs", async () => { + await navigate("/variables?tab=env") + const modifier = process.platform === "darwin" ? "Meta" : "Control" + await page.keyboard.press(`${modifier}+6`) + await expect(page).toHaveURL(/#\/variables\?tab=secrets$/) + await page.keyboard.press(`${modifier}+7`) + await expect(page).toHaveURL(/#\/variables\?tab=env$/) +}) + +test("environment values start masked and details allow explicit editing", async () => { + await navigate("/variables?tab=env") + const row = page.getByRole("row").filter({ hasText: "E2E_API_URL" }) + await expect(row).toContainText("••••••••") + await expect(row).not.toContainText("https://variables.example.test/api") + await row + .getByRole("button", { name: "Show value for E2E_API_URL", exact: true }) + .click() + await expect(row).toContainText("https://variables.example.test/api") + await row + .getByRole("button", { name: "Hide value for E2E_API_URL", exact: true }) + .click() + await row.getByRole("button", { name: "E2E_API_URL", exact: true }).click() + const details = page.getByRole("dialog", { + name: "Environment variable details", + }) + await expect(details).toBeVisible() + await expect(details.getByLabel("Value", { exact: true })).toHaveValue( + "https://variables.example.test/api", + ) + await page.keyboard.press("Escape") + await expect(details).not.toBeVisible() +}) + +test("secret details expose metadata and replacement uses a password input", async () => { + await navigate("/variables?tab=secrets") + const row = page.getByRole("row").filter({ hasText: "E2E_API_TOKEN" }) + await row.getByRole("button", { name: "E2E_API_TOKEN", exact: true }).click() + const details = page.getByRole("dialog", { name: "Secret details" }) + await expect(details).toContainText("default") + await expect(details).toContainText("Available") + await details.getByRole("button", { name: "Replace secret value" }).click() + const replacement = page.getByRole("dialog", { name: "Replace secret value" }) + await expect( + replacement.getByLabel("New value", { exact: true }), + ).toHaveAttribute("type", "password") + await replacement.getByRole("button", { name: "Cancel", exact: true }).click() + await page.keyboard.press("Escape") +}) + +test("add dialogs validate duplicate names and clear canceled secret input", async () => { + await navigate("/variables?tab=secrets") + await page.getByRole("button", { name: "Add secret", exact: true }).click() + const secretDialog = page.getByRole("dialog", { + name: "Add secret", + exact: true, + }) + await secretDialog.getByLabel("Name", { exact: true }).fill("E2E_API_TOKEN") + await secretDialog + .getByLabel("Value", { exact: true }) + .fill("discarded-secret") + await expect(secretDialog).toContainText( + "A secret with this name already exists", + ) + await expect( + secretDialog.getByRole("button", { name: "Save", exact: true }), + ).toBeDisabled() + await secretDialog + .getByRole("button", { name: "Cancel", exact: true }) + .click() + await page.getByRole("button", { name: "Add secret", exact: true }).click() + await expect(secretDialog.getByLabel("Value", { exact: true })).toHaveValue( + "", + ) + await secretDialog + .getByRole("button", { name: "Cancel", exact: true }) + .click() + await page + .getByRole("tab", { name: "Environment Variables", exact: true }) + .click() + await page.getByRole("button", { name: "Add variable", exact: true }).click() + const envDialog = page.getByRole("dialog", { + name: "Add environment variable", + }) + await envDialog.getByLabel("Name", { exact: true }).fill("E2E_API_URL") + await expect(envDialog).toContainText( + "A variable with this name already exists", + ) + await expect( + envDialog.getByRole("button", { name: "Save", exact: true }), + ).toBeDisabled() + await envDialog.getByRole("button", { name: "Cancel", exact: true }).click() +}) diff --git a/desktop/src/main/__tests__/cli.test.ts b/desktop/src/main/__tests__/cli.test.ts index 36872183dc..8b6d02b081 100644 --- a/desktop/src/main/__tests__/cli.test.ts +++ b/desktop/src/main/__tests__/cli.test.ts @@ -104,6 +104,103 @@ describe("CliRunner", () => { } }) + it("prefers an invocation credential over the session without changing either source", async () => { + const mock = vi.mocked(execFile) as unknown as ReturnType + mock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, callback: ExecCb) => + callback(null, { stdout: "", stderr: "" }), + ) + cli.setSessionPassphrase("session-private") + const env = { DEVSY_SECRETS_PASSPHRASE: "explicit-private" } + await cli.runRaw(["secret", "protection", "remove-passphrase"], { env }) + expect(mock.mock.calls[0][2].env.DEVSY_SECRETS_PASSPHRASE).toBe( + "explicit-private", + ) + expect(mock.mock.calls[0][1]).not.toContain("explicit-private") + expect(env.DEVSY_SECRETS_PASSPHRASE).toBe("explicit-private") + await cli.runRaw(["secret", "list"]) + expect(mock.mock.calls[1][2].env.DEVSY_SECRETS_PASSPHRASE).toBe( + "session-private", + ) + }) + + it.each(["run", "runRaw"] as const)( + "%s preserves unlock errors without invoking the handler when prompting is disabled", + async (method) => { + const mock = vi.mocked(execFile) as unknown as ReturnType + mock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, callback: ExecCb) => + callback( + Object.assign(new Error("failed"), { + stderr: JSON.stringify({ + kind: "error", + outcome: "error", + code: "unlock_required", + message: "Unlock required", + }), + }), + { stdout: "", stderr: "" }, + ), + ) + const unlock = vi.fn(async () => "private") + cli.setUnlockHandler(unlock) + await expect( + cli[method](["secret", "protection", "remember"], { + allowUnlockPrompt: false, + }), + ).rejects.toMatchObject({ cliError: { code: "unlock_required" } }) + expect(mock).toHaveBeenCalledOnce() + expect(unlock).not.toHaveBeenCalled() + }, + ) + + it.each(["unlock_required", "unlock_failed"])( + "stdin protection preserves session state on %s and never opens a global prompt", + async (code) => { + const child = fakeChild() + const mockSpawn = vi.mocked(spawn) as unknown as ReturnType + mockSpawn.mockReturnValue(child) + const unlock = vi.fn(async () => "private") + cli.setUnlockHandler(unlock) + cli.setSessionPassphrase("session-private") + const operation = cli.runRawStdin( + ["secret", "protection", "change-passphrase", "--stdin"], + "new-private", + { + allowUnlockPrompt: false, + env: { DEVSY_SECRETS_PASSPHRASE: "old-private" }, + }, + ) + const rejected = expect(operation).rejects.toMatchObject({ + cliError: { + code, + message: "Failed *** with ***", + hint: "***", + context: { "***": "***" }, + }, + }) + await vi.waitFor(() => expect(mockSpawn).toHaveBeenCalledOnce()) + child.stderr.emit( + "data", + JSON.stringify({ + kind: "error", + outcome: "error", + code, + message: "Failed old-private with new-private", + hint: "old-private", + context: { "new-private": "old-private" }, + }), + ) + child.emit("close", 1) + await rejected + expect(unlock).not.toHaveBeenCalled() + expect(cli.hasSessionPassphrase()).toBe(true) + expect(mockSpawn.mock.calls[0][1]).not.toContain("old-private") + expect(mockSpawn.mock.calls[0][1]).not.toContain("new-private") + expect(child.stdin.written).toBe("new-private") + }, + ) + it("prompts on a structured unlock requirement and retries exactly once without leaking credentials", async () => { const mock = vi.mocked(execFile) as unknown as ReturnType let attempts = 0 diff --git a/desktop/src/main/__tests__/ipc-secret-session.test.ts b/desktop/src/main/__tests__/ipc-secret-session.test.ts index 5664967e0e..663bc2f974 100644 --- a/desktop/src/main/__tests__/ipc-secret-session.test.ts +++ b/desktop/src/main/__tests__/ipc-secret-session.test.ts @@ -81,8 +81,8 @@ function setup(timeoutMs = 5 * 60 * 1000) { unlock = handler }, run: vi.fn(async () => ({})), - runRaw: vi.fn(async () => ""), - runRawStdin: vi.fn(async () => ""), + runRaw: vi.fn(async (..._args: unknown[]) => ""), + runRawStdin: vi.fn(async (..._args: unknown[]) => ""), setSessionPassphrase: vi.fn(), hasSessionPassphrase: () => false, } @@ -143,13 +143,261 @@ describe("secret unlock IPC lifecycle", () => { expect(cli.run).toHaveBeenCalledOnce() }) + it("explicit unlock uses the shared prompt, verifies availability, and never returns credentials", async () => { + const { cli, event, requestId } = setup() + cli.run.mockResolvedValueOnce({ availability: "available" }) + const operation = handlers.get("secret_unlock_request")?.(event) + await handlers.get("secret_unlock_submit")?.(event, { + requestId: requestId(), + passphrase: "unlock-private", + }) + await expect(operation).resolves.toEqual({ ok: true }) + expect(cli.run).toHaveBeenCalledExactlyOnceWith( + ["secret", "protection", "status"], + { + env: { DEVSY_SECRETS_PASSPHRASE: "unlock-private" }, + allowUnlockPrompt: false, + }, + ) + expect(cli.setSessionPassphrase).toHaveBeenCalledExactlyOnceWith( + "unlock-private", + ) + }) + + it("explicit unlock refuses unavailable credentials without caching or exposing them", async () => { + const { cli, event, requestId } = setup() + cli.run.mockResolvedValueOnce({ + availability: "locked", + reasonCode: "unlock_failed", + }) + const operation = handlers.get("secret_unlock_request")?.(event) + await handlers.get("secret_unlock_submit")?.(event, { + requestId: requestId(), + passphrase: "unlock-private", + }) + await expect(operation).resolves.toMatchObject({ + ok: false, + cliError: { code: "unlock_failed" }, + }) + expect(cli.setSessionPassphrase).not.toHaveBeenCalled() + }) + + it("explicit unlock cannot restore a credential cleared during availability verification", async () => { + const { cli, event, requestId } = setup() + let finish!: (status: object) => void + cli.run.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve + }), + ) + const operation = handlers.get("secret_unlock_request")?.(event) + await handlers.get("secret_unlock_submit")?.(event, { + requestId: requestId(), + passphrase: "unlock-private", + }) + await vi.waitFor(() => expect(cli.run).toHaveBeenCalledOnce()) + await handlers.get("secret_session_clear")?.(event) + finish({ availability: "available" }) + await expect(operation).resolves.toEqual({ + ok: false, + message: "Secret unlock canceled.", + }) + expect(cli.setSessionPassphrase).toHaveBeenCalledExactlyOnceWith(undefined) + }) + + it("explicit unlock cancellation skips verification and session changes", async () => { + const { cli, event, requestId } = setup() + const operation = handlers.get("secret_unlock_request")?.(event) + await handlers.get("secret_unlock_submit")?.(event, { + requestId: requestId(), + }) + await expect(operation).resolves.toEqual({ + ok: false, + message: "Secret unlock canceled.", + }) + expect(cli.run).not.toHaveBeenCalled() + expect(cli.setSessionPassphrase).not.toHaveBeenCalled() + }) + + it.each([null, 123, true, {}, []])( + "rejects invalid current passphrase %j before confirmation", + async (currentPassphrase) => { + const { cli, event } = setup() + expect( + await handlers.get("secret_protection_action")?.(event, { + action: "remove-passphrase", + currentPassphrase, + }), + ).toEqual({ ok: false, message: "Enter a valid current passphrase." }) + expect(dialog.showMessageBox).not.toHaveBeenCalled() + expect(cli.runRaw).not.toHaveBeenCalled() + }, + ) + + it.each(["set-passphrase", "change-passphrase"])( + "%s sends current credential only through env and new credential only through stdin", + async (action) => { + const { cli, event } = setup() + expect( + await handlers.get("secret_protection_action")?.(event, { + action, + currentPassphrase: "old-private", + newPassphrase: "new-private", + }), + ).toEqual({ ok: true }) + expect(cli.runRawStdin).toHaveBeenCalledExactlyOnceWith( + ["secret", "protection", action, "--stdin"], + "new-private", + { + env: { DEVSY_SECRETS_PASSPHRASE: "old-private" }, + allowUnlockPrompt: false, + }, + ) + expect(cli.setSessionPassphrase).toHaveBeenCalledExactlyOnceWith( + "new-private", + ) + }, + ) + + it.each(["remove-passphrase", "remember", "forget"])( + "%s uses explicit credential env and suppresses global unlock", + async (action) => { + const { cli, event } = setup() + expect( + await handlers.get("secret_protection_action")?.(event, { + action, + currentPassphrase: "old-private", + }), + ).toEqual({ ok: true }) + expect(cli.runRaw).toHaveBeenCalledExactlyOnceWith( + ["secret", "protection", action], + { + env: { DEVSY_SECRETS_PASSPHRASE: "old-private" }, + allowUnlockPrompt: false, + }, + ) + if (action === "remove-passphrase") + expect(cli.setSessionPassphrase).toHaveBeenCalledExactlyOnceWith( + undefined, + ) + else expect(cli.setSessionPassphrase).not.toHaveBeenCalled() + }, + ) + + it("preserves structured errors while redacting both credentials and leaving session state alone", async () => { + const { cli, event } = setup() + cli.runRawStdin.mockRejectedValueOnce( + Object.assign(new Error("new-private"), { + cliError: { + code: "unlock_failed", + message: "Unable to unlock old-private", + hint: "Do not reuse new-private", + context: { "old-private": "new-private" }, + }, + }), + ) + const result = await handlers.get("secret_protection_action")?.(event, { + action: "change-passphrase", + currentPassphrase: "old-private", + newPassphrase: "new-private", + }) + expect(result).toMatchObject({ + ok: false, + message: "Unable to unlock ***", + cliError: { + code: "unlock_failed", + hint: "Do not reuse ***", + context: { "***": "***" }, + }, + }) + expect(JSON.stringify(result)).not.toContain("old-private") + expect(JSON.stringify(result)).not.toContain("new-private") + expect(cli.setSessionPassphrase).not.toHaveBeenCalled() + }) + + it("lists environment variables in an explicit captured context", async () => { + const { cli, event } = setup() + const rows = [{ name: "PORT", value: "8080", context: "captured" }] + cli.run.mockResolvedValueOnce(rows) + expect( + await handlers.get("env_list")?.(event, { context: "captured" }), + ).toEqual(rows) + expect(cli.run).toHaveBeenCalledWith([ + "--context", + "captured", + "env", + "list", + ]) + }) + it("preserves default environment listing with missing arguments", async () => { + const { cli, event } = setup() + await handlers.get("env_list")?.(event) + expect(cli.run).toHaveBeenLastCalledWith(["env", "list"]) + await handlers.get("env_list")?.(event, {}) + expect(cli.run).toHaveBeenLastCalledWith(["env", "list"]) + }) + it("rejects an empty environment listing context before executing CLI", async () => { + const { cli, event } = setup() + for (const context of ["", " ", null, 23, {}]) { + await expect( + handlers.get("env_list")?.(event, { context }), + ).rejects.toThrow("A valid context is required.") + } + expect(cli.run).not.toHaveBeenCalled() + }) + it.each(["env_set", "secret_set", "secret_delete"])( + "%s routes an explicit row context to the CLI and preserves omitted context", + async (channel) => { + const { cli, event } = setup() + const args = { name: "TOKEN", value: "private", context: "row-context" } + const command = + channel === "env_set" + ? ["env", "set", "TOKEN", "--value", "private"] + : channel === "secret_set" + ? ["secret", "set", "TOKEN", "--stdin"] + : ["secret", "delete", "TOKEN"] + expect(await handlers.get(channel)?.(event, args)).toEqual({ ok: true }) + const run = channel === "secret_set" ? cli.runRawStdin : cli.runRaw + expect(run.mock.calls[0][0]).toEqual([ + "--context", + "row-context", + ...command, + ]) + expect( + await handlers.get(channel)?.(event, { + name: "TOKEN", + value: "private", + }), + ).toEqual({ ok: true }) + expect(run.mock.calls[1][0]).toEqual(command) + }, + ) + + it.each(["env_set", "secret_set", "secret_delete"])( + "%s rejects an invalid supplied context before CLI execution", + async (channel) => { + const { cli, event } = setup() + for (const context of [null, 23, {}, "", " "]) + expect( + await handlers.get(channel)?.(event, { + name: "TOKEN", + value: "private", + context, + }), + ).toMatchObject({ ok: false, message: "A valid context is required." }) + expect(cli.runRaw).not.toHaveBeenCalled() + expect(cli.runRawStdin).not.toHaveBeenCalled() + }, + ) + it.each([{}, 123, true, [], undefined, null, " "])( "rejects invalid protection passphrase %j without running the CLI", async (passphrase) => { const { cli, event } = setup() const result = await handlers.get("secret_protection_action")?.(event, { action: "change-passphrase", - passphrase, + newPassphrase: passphrase, }) expect(result).toEqual({ ok: false, @@ -177,7 +425,7 @@ describe("secret unlock IPC lifecycle", () => { }) const result = await handlers.get("secret_protection_action")?.(event, { action, - passphrase: "private", + newPassphrase: "private", }) expect(result).toEqual({ ok: false, @@ -198,12 +446,13 @@ describe("secret unlock IPC lifecycle", () => { expect( await handlers.get("secret_protection_action")?.(event, { action: "change-passphrase", - passphrase: "private", + newPassphrase: "private", }), ).toEqual({ ok: true }) expect(cli.runRawStdin).toHaveBeenCalledWith( ["secret", "protection", "change-passphrase", "--stdin"], "private", + { allowUnlockPrompt: false }, ) expect(cli.setSessionPassphrase).toHaveBeenCalledWith("private") expect( @@ -224,7 +473,7 @@ describe("secret unlock IPC lifecycle", () => { ) const operation = handlers.get("secret_protection_action")?.(event, { action, - passphrase: "private", + newPassphrase: "private", }) await vi.waitFor(() => expect(cli.runRawStdin).toHaveBeenCalledOnce()) await handlers.get("secret_session_clear")?.(event) @@ -250,7 +499,7 @@ describe("secret unlock IPC lifecycle", () => { ) const operation = handlers.get("secret_protection_action")?.(event, { action: "change-passphrase", - passphrase: "private", + newPassphrase: "private", }) expect(cli.runRawStdin).not.toHaveBeenCalled() await handlers.get("secret_session_clear")?.(event) @@ -307,7 +556,7 @@ describe("secret unlock IPC lifecycle", () => { ) const operation = handlers.get("secret_protection_action")?.(event, { action, - passphrase: "private", + newPassphrase: "private", }) await vi.waitFor(() => expect(run).toHaveBeenCalledOnce()) webContents.mainFrame.url = "https://untrusted.example/" @@ -321,6 +570,7 @@ describe("secret unlock IPC lifecycle", () => { const { cli } = setup() for (const name of [ "secret_protection_action", + "secret_unlock_request", "secret_protection_status", "secret_session_clear", "secret_unlock_submit", @@ -337,7 +587,7 @@ describe("secret unlock IPC lifecycle", () => { expect( await handlers.get(name)?.( {}, - { action: "remove-passphrase", passphrase: "private" }, + { action: "remove-passphrase", newPassphrase: "private" }, ), ).toEqual({ ok: false, diff --git a/desktop/src/main/cli.ts b/desktop/src/main/cli.ts index 2bc72e89ee..157da3aecc 100644 --- a/desktop/src/main/cli.ts +++ b/desktop/src/main/cli.ts @@ -43,6 +43,8 @@ export interface StreamLine { export interface CliInvocationOptions { env?: NodeJS.ProcessEnv stdin?: string + /** Explicit credential workflows handle unlock errors in their own dialog. */ + allowUnlockPrompt?: boolean /** Internal retry guard: never repeatedly prompt for one invocation. */ unlockRetried?: boolean } @@ -285,6 +287,7 @@ export class CliRunner { options: CliInvocationOptions, ): Promise { if ( + options.allowUnlockPrompt === false || !this.commandNeedsSecret(args) || options.unlockRetried || (error as { cliError?: CLIError })?.cliError?.code !== @@ -636,7 +639,11 @@ export class CliRunner { } } this.release() - if (cliError?.code === "unlock_failed") this.sessionPassphrase = undefined + if ( + cliError?.code === "unlock_failed" && + options.allowUnlockPrompt !== false + ) + this.sessionPassphrase = undefined if ( code !== 0 && cliError?.code === "unlock_required" && @@ -828,7 +835,11 @@ export class CliRunner { : undefined, } : undefined - if (cliError?.code === "unlock_failed") this.sessionPassphrase = undefined + if ( + cliError?.code === "unlock_failed" && + options.allowUnlockPrompt !== false + ) + this.sessionPassphrase = undefined const message = cliError ? cliError.message : this.sanitizeMessage(stderr || error.message) diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts index c127546743..79147783f3 100644 --- a/desktop/src/main/ipc.ts +++ b/desktop/src/main/ipc.ts @@ -17,7 +17,7 @@ import type { WorkspaceActivity } from "../shared/workspace-operation.js" import { hashWorkspaceRef, trackEvent } from "./analytics.js" import type { AppNavigationController } from "./app-navigation.js" import { sanitizeAppSettingsPatch } from "./app-settings.js" -import type { CliRunner, StreamLine } from "./cli.js" +import type { CliInvocationOptions, CliRunner, StreamLine } from "./cli.js" import { loadCatalog } from "./image-catalog.js" import type { LogStore } from "./log-store.js" import { mainLog } from "./logging.js" @@ -352,7 +352,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { const secretSession = new SecretSession(deps.secretSessionTimeoutMs) // Clearing the session revokes cache updates from protection operations already in flight. let secretCacheGeneration = 0 - cli.setUnlockHandler(async () => { + const requestSecretUnlock = async () => { const win = getMainWindow() return secretSession.request( (requestId) => { @@ -394,7 +394,8 @@ export function registerIpcHandlers(deps: IpcDependencies): { } : undefined, ) - }) + } + cli.setUnlockHandler(requestSecretUnlock) const secretDocumentURL = !app.isPackaged && process.env.ELECTRON_RENDERER_URL ? process.env.ELECTRON_RENDERER_URL @@ -571,6 +572,58 @@ export function registerIpcHandlers(deps: IpcDependencies): { credentialSubmissions.delete(requestId) } }) + ipcMain.handle("secret_unlock_request", async (event) => { + if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) + return secretRequestDenied + const generation = secretCacheGeneration + const passphrase = await requestSecretUnlock() + if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) + return secretRequestDenied + if (passphrase === undefined || generation !== secretCacheGeneration) + return { ok: false, message: "Secret unlock canceled." } + try { + const status = await cli.run<{ + availability: string + reasonCode?: string + }>(["secret", "protection", "status"], { + env: { DEVSY_SECRETS_PASSPHRASE: passphrase }, + allowUnlockPrompt: false, + }) + if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) + return secretRequestDenied + if (generation !== secretCacheGeneration) + return { ok: false, message: "Secret unlock canceled." } + if (status.availability !== "available") { + const message = "The secret store could not be unlocked." + return { + ok: false, + message, + cliError: { + code: (status.reasonCode ?? "unlock_failed").replaceAll( + passphrase, + "***", + ), + message, + }, + } + } + updateProtectedSessionCredential(event, generation, passphrase) + return { ok: true } + } catch (err) { + const error = (err as { cliError?: CLIError } | null)?.cliError + const message = "The secret store could not be unlocked." + return { + ok: false, + message, + cliError: error + ? { + code: error.code.replaceAll(passphrase, "***"), + message, + } + : undefined, + } + } + }) ipcMain.handle("secret_protection_status", async (event) => { if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) return secretRequestDenied @@ -615,7 +668,14 @@ export function registerIpcHandlers(deps: IpcDependencies): { ipcMain.handle( "secret_protection_action", - async (event, args: { action: string; passphrase?: string }) => { + async ( + event, + args: { + action: string + newPassphrase?: string + currentPassphrase?: string + }, + ) => { const win = getMainWindow() if (!win || !isTrustedSecretIpcSender(event, win, secretDocumentURL)) return secretRequestDenied @@ -629,7 +689,20 @@ export function registerIpcHandlers(deps: IpcDependencies): { if (!args || typeof args !== "object" || !allowed.includes(args.action)) return { ok: false, message: "Unknown protection action." } const action = args.action - const passphrase = args.passphrase + const { newPassphrase, currentPassphrase } = args + if ( + currentPassphrase !== undefined && + typeof currentPassphrase !== "string" + ) + return { ok: false, message: "Enter a valid current passphrase." } + if (newPassphrase !== undefined && typeof newPassphrase !== "string") + return { ok: false, message: "Enter a non-empty passphrase." } + const options: CliInvocationOptions = { + allowUnlockPrompt: false, + ...(currentPassphrase !== undefined + ? { env: { DEVSY_SECRETS_PASSPHRASE: currentPassphrase } } + : {}), + } const cacheGeneration = secretCacheGeneration const changesPassphrase = [ "set-passphrase", @@ -638,7 +711,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { try { const command = ["secret", "protection", action] if (changesPassphrase) { - if (typeof passphrase !== "string" || !passphrase.trim()) + if (typeof newPassphrase !== "string" || !newPassphrase.trim()) return { ok: false, message: "Enter a non-empty passphrase." } } const descriptions: Record = { @@ -666,17 +739,44 @@ export function registerIpcHandlers(deps: IpcDependencies): { confirmation.response, ) if (approvalFailure) return approvalFailure - if (changesPassphrase && typeof passphrase === "string") { - await cli.runRawStdin([...command, "--stdin"], passphrase) - updateProtectedSessionCredential(event, cacheGeneration, passphrase) + if (changesPassphrase && typeof newPassphrase === "string") { + await cli.runRawStdin([...command, "--stdin"], newPassphrase, options) + updateProtectedSessionCredential( + event, + cacheGeneration, + newPassphrase, + ) } else { - await cli.runRaw(command) + await cli.runRaw(command, options) if (action === "remove-passphrase") updateProtectedSessionCredential(event, cacheGeneration, undefined) } return { ok: true } } catch (err) { - const cliError = (err as { cliError?: CLIError }).cliError + // Preserve structured recovery information without sending credential + // material (or arbitrary error properties) back across the IPC boundary. + const redact = (value: string) => + [currentPassphrase, newPassphrase].reduce( + (text, credential) => + credential ? text.replaceAll(credential, "***") : text, + value, + ) + const error = (err as { cliError?: CLIError } | null)?.cliError + const cliError = error + ? { + code: redact(error.code), + message: redact(error.message), + hint: error.hint ? redact(error.hint) : undefined, + context: error.context + ? Object.fromEntries( + Object.entries(error.context).map(([key, value]) => [ + redact(key), + redact(value), + ]), + ) + : undefined, + } + : undefined return { ok: false, message: cliError?.message ?? "Secret protection operation failed.", @@ -1556,6 +1656,13 @@ export function registerIpcHandlers(deps: IpcDependencies): { await cli.runRaw(["context", "delete", args.name]) }) + function variableContextArgs(context: string | undefined): string[] { + if (context === undefined) return [] + if (typeof context !== "string" || !context.trim()) + throw new Error("A valid context is required.") + return ["--context", context] + } + ipcMain.handle("secret_list", async (event) => { if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) return secretRequestDenied @@ -1566,13 +1673,19 @@ export function registerIpcHandlers(deps: IpcDependencies): { // the IPC boundary (see provider_init above). ipcMain.handle( "secret_set", - async (event, args: { name: string; value: string }) => { + async (event, args: { name: string; value: string; context?: string }) => { if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) return secretRequestDenied trackEvent("secret_set") try { await cli.runRawStdin( - ["secret", "set", args.name, "--stdin"], + [ + ...variableContextArgs(args.context), + "secret", + "set", + args.name, + "--stdin", + ], args.value, ) return { ok: true } as const @@ -1584,19 +1697,27 @@ export function registerIpcHandlers(deps: IpcDependencies): { }, ) - ipcMain.handle("secret_delete", async (event, args: { name: string }) => { - if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) - return secretRequestDenied - trackEvent("secret_delete") - try { - await cli.runRaw(["secret", "delete", args.name]) - return { ok: true } as const - } catch (err) { - const cliError = (err as { cliError?: CLIError }).cliError - const message = err instanceof Error ? err.message : String(err) - return { ok: false, message, cliError } as const - } - }) + ipcMain.handle( + "secret_delete", + async (event, args: { name: string; context?: string }) => { + if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) + return secretRequestDenied + trackEvent("secret_delete") + try { + await cli.runRaw([ + ...variableContextArgs(args.context), + "secret", + "delete", + args.name, + ]) + return { ok: true } as const + } catch (err) { + const cliError = (err as { cliError?: CLIError }).cliError + const message = err instanceof Error ? err.message : String(err) + return { ok: false, message, cliError } as const + } + }, + ) ipcMain.handle( "secret_attach", @@ -1646,16 +1767,25 @@ export function registerIpcHandlers(deps: IpcDependencies): { }, ) - ipcMain.handle("env_list", async () => cli.run(["env", "list"])) + ipcMain.handle("env_list", async (_event, args?: { context?: string }) => + cli.run([...variableContextArgs(args?.context), "env", "list"]), + ) // Returns an envelope rather than throwing so a structured cliError survives // the IPC boundary (see provider_init above). ipcMain.handle( "env_set", - async (_event, args: { name: string; value: string }) => { + async (_event, args: { name: string; value: string; context?: string }) => { trackEvent("env_set") try { - await cli.runRaw(["env", "set", args.name, "--value", args.value]) + await cli.runRaw([ + ...variableContextArgs(args.context), + "env", + "set", + args.name, + "--value", + args.value, + ]) return { ok: true } as const } catch (err) { const cliError = (err as { cliError?: CLIError }).cliError diff --git a/desktop/src/renderer/src/App.svelte b/desktop/src/renderer/src/App.svelte index e25c24825c..3285d6ba9a 100644 --- a/desktop/src/renderer/src/App.svelte +++ b/desktop/src/renderer/src/App.svelte @@ -53,6 +53,7 @@ import MachineDetailPage from "./pages/MachineDetailPage.svelte" import ContextsPage from "./pages/ContextsPage.svelte" import SecretsPage from "./pages/SecretsPage.svelte" import EnvPage from "./pages/EnvPage.svelte" +import VariablesPage from "./pages/VariablesPage.svelte" import SettingsPage from "./pages/SettingsPage.svelte" import SshKeysPage from "./pages/SshKeysPage.svelte" import TerminalsPage from "./pages/TerminalsPage.svelte" @@ -69,6 +70,7 @@ const routes = { "/machines": MachinesPage, "/machines/:id": MachineDetailPage, "/contexts": ContextsPage, + "/variables": VariablesPage, "/secrets": SecretsPage, "/env": EnvPage, "/settings": SettingsPage, @@ -89,8 +91,8 @@ const NAV_KEYS: Record = { 3: "/providers", 4: "/machines", 5: "/contexts", - 6: "/secrets", - 7: "/env", + 6: "/variables?tab=secrets", + 7: "/variables?tab=env", 8: "/terminals", 9: "/ssh-keys", 0: "/settings", @@ -138,6 +140,7 @@ function screenName(path: string): string { "/machines": "machines", "/machines/:id": "machine_detail", "/contexts": "contexts", + "/variables": "workspace_variables", "/secrets": "secrets", "/env": "env", "/settings": "settings", diff --git a/desktop/src/renderer/src/lib/components/layout/Breadcrumbs.svelte b/desktop/src/renderer/src/lib/components/layout/Breadcrumbs.svelte index fe78274a2b..26ddf66bc3 100644 --- a/desktop/src/renderer/src/lib/components/layout/Breadcrumbs.svelte +++ b/desktop/src/renderer/src/lib/components/layout/Breadcrumbs.svelte @@ -12,6 +12,7 @@ const LABELS: Record = { providers: "Providers", machines: "Machines", contexts: "Contexts", + variables: "Workspace Variables", secrets: "Secrets", env: "Env Vars", terminals: "Terminals", diff --git a/desktop/src/renderer/src/lib/components/layout/CommandPalette.svelte b/desktop/src/renderer/src/lib/components/layout/CommandPalette.svelte index 1de2fa84a4..0c6a911fb6 100644 --- a/desktop/src/renderer/src/lib/components/layout/CommandPalette.svelte +++ b/desktop/src/renderer/src/lib/components/layout/CommandPalette.svelte @@ -25,7 +25,7 @@ const CATEGORY_ICONS: Record = { Providers: Plug, Machines: Server, Secrets: Lock, - "Env Vars": Braces, + "Environment Variables": Braces, "SSH Keys": KeyRound, } @@ -86,14 +86,14 @@ let allItems = $derived.by(() => { label: "Secrets", description: "Manage secrets", category: "Navigation", - href: "/secrets", + href: "/variables?tab=secrets", }, { id: "nav-env", - label: "Env Vars", + label: "Environment Variables", description: "Manage environment variables", category: "Navigation", - href: "/env", + href: "/variables?tab=env", }, { id: "nav-terminals", @@ -150,21 +150,21 @@ let allItems = $derived.by(() => { for (const s of $secrets) { items.push({ - id: `secret-${s.name}`, + id: `secret-${s.context}-${s.name}`, label: s.name, description: "Secret", category: "Secrets", - href: "/secrets", + href: "/variables?tab=secrets", }) } for (const e of $envVars) { items.push({ - id: `env-${e.name}`, + id: `env-${e.context}-${e.name}`, label: e.name, description: "Environment variable", - category: "Env Vars", - href: "/env", + category: "Environment Variables", + href: "/variables?tab=env", }) } diff --git a/desktop/src/renderer/src/lib/components/layout/SecretProtectionPanel.svelte b/desktop/src/renderer/src/lib/components/layout/SecretProtectionPanel.svelte deleted file mode 100644 index 42c95a9108..0000000000 --- a/desktop/src/renderer/src/lib/components/layout/SecretProtectionPanel.svelte +++ /dev/null @@ -1,82 +0,0 @@ - -
-

Secret protection

-

Availability: {status.availability?.replaceAll("_", " ") ?? "unknown"}. File store: {status.keySource === "passphrase" ? "Passphrase protected" : status.keySource ? "Automatic key" : "Not initialized"}. Remembered credential: {status.rememberedAvailable === false ? "OS keychain unavailable" : status.remembered ? "Yes" : "No"}. Session: {status.sessionUnlocked ? "Unlocked" : "No session credential"}.

- - - {#if passphrase.length > 0 && passphrase.length < 12}

Choose a long passphrase; at least 12 characters is recommended.

{/if} -
- - - - - -
-

All file-backed secrets share this protection. Remembering lets Devsy recover the credential from your OS keychain. Environment variables remain independent.

- {#if status.keySource === "passphrase"} -

Forgotten passphrase? Check for a remembered credential first. Without the passphrase, the encrypted file cannot be recovered. Run devsy secret protection reset-file-store in a terminal to review and confirm removal of every file-backed secret across all contexts. Keyring secrets and environment variables are unaffected.

- {/if} - {#if error}{/if} -
diff --git a/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.svelte b/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.svelte index b8483ef0d0..a22fd806dc 100644 --- a/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.svelte +++ b/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.svelte @@ -136,8 +136,8 @@ function cancel() {
{ event.preventDefault(); void submit() }} class="space-y-4"> - -

Once approved, remembering may finish even if you cancel unlocking. Use Forget in Settings to remove the saved credential.

+ +

Once approved, remembering may finish even if you cancel unlocking. Use Forget this device in Secret security to remove the saved passphrase.

{#if error}{/if} diff --git a/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.test.ts b/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.test.ts index b29f79d6c6..ae573e0800 100644 --- a/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.test.ts +++ b/desktop/src/renderer/src/lib/components/layout/SecretUnlockDialog.test.ts @@ -151,7 +151,7 @@ describe("SecretUnlockDialog", () => { request("remember-request") const input = await screen.findByLabelText("Secrets passphrase") await fireEvent.input(input, { target: { value: "private credential" } }) - await fireEvent.click(screen.getByLabelText("Remember in OS keychain")) + await fireEvent.click(screen.getByLabelText("Remember on this device")) await fireEvent.click(screen.getByText("Unlock and retry")) await fireEvent.click(screen.getByText("Cancel")) expect(invoke).toHaveBeenLastCalledWith("secret_unlock_submit", { @@ -234,7 +234,7 @@ describe("SecretUnlockDialog", () => { request("reloaded-request") const input = await screen.findByLabelText("Secrets passphrase") await fireEvent.input(input, { target: { value: "private credential" } }) - await fireEvent.click(screen.getByLabelText("Remember in OS keychain")) + await fireEvent.click(screen.getByLabelText("Remember on this device")) await fireEvent.click(screen.getByText("Unlock and retry")) oldPage.unmount() notices = [ @@ -308,7 +308,7 @@ describe("SecretUnlockDialog", () => { request("timed-out-save") const input = await screen.findByLabelText("Secrets passphrase") await fireEvent.input(input, { target: { value: "private credential" } }) - await fireEvent.click(screen.getByLabelText("Remember in OS keychain")) + await fireEvent.click(screen.getByLabelText("Remember on this device")) await fireEvent.click(screen.getByText("Unlock and retry")) notices = [ { diff --git a/desktop/src/renderer/src/lib/components/layout/Sidebar.svelte b/desktop/src/renderer/src/lib/components/layout/Sidebar.svelte index bf741cfb17..4b9285c3d5 100644 --- a/desktop/src/renderer/src/lib/components/layout/Sidebar.svelte +++ b/desktop/src/renderer/src/lib/components/layout/Sidebar.svelte @@ -5,7 +5,6 @@ import { Layers, LayoutDashboard, KeyRound, - Lock, Plug, Search, Server, @@ -33,8 +32,7 @@ const SHORTCUT_BY_HREF: Record = { "/providers": "3", "/machines": "4", "/contexts": "5", - "/secrets": "6", - "/env": "7", + "/variables": "6", "/terminals": "8", "/ssh-keys": "9", "/settings": "0", @@ -89,18 +87,11 @@ let mainNav: NavItem[] = $derived([ shortcut: SHORTCUT_BY_HREF["/contexts"], }, { - href: "/secrets", - label: "Secrets", - icon: Lock, - badge: $secrets.length, - shortcut: SHORTCUT_BY_HREF["/secrets"], - }, - { - href: "/env", - label: "Env Vars", + href: "/variables", + label: "Variables", icon: Braces, - badge: $envVars.length, - shortcut: SHORTCUT_BY_HREF["/env"], + badge: $secrets.length + $envVars.length, + shortcut: SHORTCUT_BY_HREF["/variables"], }, { href: "/terminals", diff --git a/desktop/src/renderer/src/lib/components/variables/AddEnvironmentVariableDialog.svelte b/desktop/src/renderer/src/lib/components/variables/AddEnvironmentVariableDialog.svelte new file mode 100644 index 0000000000..d4cf9f6157 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/AddEnvironmentVariableDialog.svelte @@ -0,0 +1,120 @@ + + + { if (saving) event.preventDefault() }} onInteractOutside={(event) => { if (saving) event.preventDefault() }} onCloseAutoFocus={(event) => { if (initiatingControl?.isConnected) { event.preventDefault(); initiatingControl.focus() } }}> + + Add environment variable + Store non-sensitive plaintext configuration in your current context. Use Secrets for credentials. + + { event.preventDefault(); save() }}> +
+ + +

+ {#if duplicate && !saved}A variable with this name already exists in this context. Edit the existing row.{:else if name && !valid}Use letters, digits, and underscores, starting with a letter or underscore.{/if} +

+
+

An empty value is allowed.

+
+ {#if error}{/if} + {#if !saved}{/if} + +
+
diff --git a/desktop/src/renderer/src/lib/components/variables/AddSecretDialog.svelte b/desktop/src/renderer/src/lib/components/variables/AddSecretDialog.svelte new file mode 100644 index 0000000000..fb8d31b84f --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/AddSecretDialog.svelte @@ -0,0 +1,121 @@ + + + open, (next) => { if (!busy) open = next }}> + { e.preventDefault(); returnFocus?.focus() }} class="sm:max-w-md" onEscapeKeydown={(e) => { if (busy) e.preventDefault() }} onInteractOutside={(e) => { if (busy) e.preventDefault() }}> + + Add secret + Store a sensitive value securely in the active context. + +
{ e.preventDefault(); save() }}> +
+ + +

+ {#if duplicate}A secret with this name already exists. Use its row menu to replace the value. + {:else if name && !nameValid}Start with a letter or underscore; use letters, digits, and underscores. + {:else}For example, DB_PASSWORD.{/if} +

+
+
+ + +
+
+ + +
+ {#if error}{/if} + + + + +
+
+
diff --git a/desktop/src/renderer/src/lib/components/variables/EnvironmentVariableDetailsSheet.svelte b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariableDetailsSheet.svelte new file mode 100644 index 0000000000..5be0ea7d78 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariableDetailsSheet.svelte @@ -0,0 +1,97 @@ + + + { if (initiatingControl?.isConnected) { event.preventDefault(); initiatingControl.focus() } }}> + Environment variable detailsValues are stored as non-sensitive plaintext configuration. + {#if variable} +
+
Name
{variable.name}
Context
{variable.context}
+
{ event.preventDefault(); save() }}> + + {#if error}{/if} + +
+
{#key reset} variable && onattachment(variable, checked)} />{/key}
+ {#if attachmentError}{/if} + +
+ {/if} +
+
diff --git a/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.svelte b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.svelte new file mode 100644 index 0000000000..5c6d28eff2 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.svelte @@ -0,0 +1,130 @@ + +
+

Environment variables are stored as non-sensitive plaintext configuration. Use Secrets for passwords, tokens, and other credentials.

+ + {#if $envLoading} + {:else if $envError} + {:else if $envVars.length === 0}

No environment variables yet.

+ {:else if rows.length === 0}

No environment variables match "{search}"

+ {:else} + + NameContextValueInjectActions + + {#each rows as row (variableIdentity(row.context, row.name))} + {@const key = variableIdentity(row.context, row.name)} + showDetails(row)}> + + {row.context} +
{revealed[key] ? row.value : "••••••••"}
+
event.stopPropagation()} role="presentation">{#key resets[key]} setAttached(row, checked)} />{/key}
{#if errors[key]}{/if}
+
event.stopPropagation()} role="presentation">{#snippet child({ props })}{/snippet} showDetails(row)}>View details showDetails(row)}>Edit value requestDelete(row)}>Delete
+
+ {/each} +
+
+ {/if} +
+ + + diff --git a/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.test.ts b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.test.ts new file mode 100644 index 0000000000..050fc0eb61 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/EnvironmentVariablesPanel.test.ts @@ -0,0 +1,381 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/svelte" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +const mocks = vi.hoisted(() => ({ + envAttach: vi.fn().mockResolvedValue(undefined), + envDetach: vi.fn().mockResolvedValue(undefined), + envDelete: vi.fn().mockResolvedValue(undefined), + refreshEnv: vi.fn().mockResolvedValue(undefined), + envSet: vi.fn().mockResolvedValue(undefined), + envList: vi.fn().mockResolvedValue([]), +})) +vi.mock("$lib/ipc/commands.js", () => ({ + envAttach: mocks.envAttach, + envDelete: mocks.envDelete, + envDetach: mocks.envDetach, + envSet: mocks.envSet, + envList: mocks.envList, +})) +vi.mock("$lib/stores/env.js", async () => { + const { writable } = await import("svelte/store") + return { + envLoading: writable(false), + envError: writable(null), + initEnv: mocks.refreshEnv, + envVars: writable([ + { name: "ATTACHED", value: "one", context: "default", attached: true }, + { name: "DETACHED", value: "two", context: "default", attached: false }, + { + name: "STAGING_ONLY", + value: "three", + context: "staging", + attached: false, + }, + ]), + refreshEnv: mocks.refreshEnv, + } +}) + +vi.mock("$lib/stores/contexts.js", async () => ({ + activeContext: (await import("svelte/store")).writable("default"), +})) + +import { activeContext } from "$lib/stores/contexts.js" +import { envError, envVars } from "$lib/stores/env.js" +import AddDialog from "./AddEnvironmentVariableDialog.svelte" +import EnvPage from "./EnvironmentVariablesPanel.svelte" + +describe("EnvPage managed environment attachments", () => { + beforeEach(() => { + vi.clearAllMocks() + activeContext.set("default") + envError.set(null) + envVars.set([ + { name: "ATTACHED", value: "one", context: "default", attached: true }, + { name: "DETACHED", value: "two", context: "default", attached: false }, + { + name: "STAGING_ONLY", + value: "three", + context: "staging", + attached: false, + }, + ]) + }) + afterEach(() => { + cleanup() + }) + + it("renders attachment state and sends attach/detach intent", async () => { + render(EnvPage) + + expect( + screen + .getByRole("switch", { name: "Inject ATTACHED into workspaces" }) + .getAttribute("aria-checked"), + ).toBe("true") + const detached = screen.getByRole("switch", { + name: "Inject DETACHED into workspaces", + }) + expect(detached.getAttribute("aria-checked")).toBe("false") + + await fireEvent.click(detached) + await waitFor(() => + expect(mocks.envAttach).toHaveBeenCalledWith("DETACHED", "default"), + ) + expect(mocks.refreshEnv).toHaveBeenCalled() + + await fireEvent.click( + screen.getByRole("switch", { name: "Inject ATTACHED into workspaces" }), + ) + await waitFor(() => + expect(mocks.envDetach).toHaveBeenCalledWith("ATTACHED", "default"), + ) + }) + + it("uses the context displayed on a stale row", async () => { + render(EnvPage) + + await fireEvent.click( + screen.getByRole("switch", { + name: "Inject STAGING_ONLY into workspaces", + }), + ) + await waitFor(() => + expect(mocks.envAttach).toHaveBeenCalledWith("STAGING_ONLY", "staging"), + ) + }) + + it("deletes using the context displayed on a stale row", async () => { + render(EnvPage) + + await fireEvent.click(screen.getByRole("button", { name: "STAGING_ONLY" })) + await fireEvent.click( + screen.getByRole("button", { name: "Delete variable" }), + ) + await fireEvent.click(screen.getByRole("button", { name: /^Delete$/ })) + + await waitFor(() => + expect(mocks.envDelete).toHaveBeenCalledWith("STAGING_ONLY", "staging"), + ) + }) +}) + +describe("environment table value workflows", () => { + afterEach(cleanup) + beforeEach(() => { + vi.clearAllMocks() + activeContext.set("default") + envError.set(null) + envVars.set([ + { + name: "SHARED", + value: "default-value", + context: "default", + attached: false, + }, + { + name: "SHARED", + value: "staging-value", + context: "staging", + attached: false, + }, + ]) + }) + it("reveals only the exact context and name", async () => { + render(EnvPage) + expect(screen.queryByText("default-value")).toBeNull() + await fireEvent.click( + screen.getAllByRole("button", { name: "Show value for SHARED" })[1], + ) + expect(screen.getByText("staging-value")).toBeTruthy() + expect(screen.queryByText("default-value")).toBeNull() + }) + it("shows load error and retry", async () => { + envError.set("offline") + render(EnvPage) + await fireEvent.click(screen.getByRole("button", { name: "Retry" })) + expect(mocks.refreshEnv).toHaveBeenCalled() + }) + it("updates the selected row context with an empty value", async () => { + render(EnvPage) + await fireEvent.click(screen.getAllByRole("button", { name: "SHARED" })[1]) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Update value" })) + await waitFor(() => + expect(mocks.envSet).toHaveBeenCalledWith("SHARED", "", "staging"), + ) + }) + it("rejects duplicate Add instead of silently updating", async () => { + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "SHARED" }, + }) + expect(screen.getByRole("alert").textContent).toContain("already exists") + expect( + screen.getByRole("button", { name: "Save" }).hasAttribute("disabled"), + ).toBe(true) + expect(mocks.envSet).not.toHaveBeenCalled() + }) + it("rejects a duplicate discovered in the fresh list without overwriting", async () => { + mocks.envList.mockResolvedValueOnce([ + { name: "NEW", value: "existing", context: "default" }, + ]) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "replacement" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain("already exists"), + ) + expect(mocks.envList).toHaveBeenCalledOnce() + expect(mocks.refreshEnv).toHaveBeenCalledOnce() + expect(mocks.envSet).not.toHaveBeenCalled() + expect(mocks.envAttach).not.toHaveBeenCalled() + }) + it("checks duplicates in the captured context after switching active context", async () => { + envVars.set([]) + activeContext.set("context-a") + mocks.envList.mockImplementationOnce(async (context) => + context === "context-a" + ? [{ name: "EXISTING", value: "keep-me", context: "context-a" }] + : [], + ) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "EXISTING" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "overwrite" }, + }) + activeContext.set("context-b") + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain("already exists"), + ) + expect(mocks.envList).toHaveBeenCalledWith("context-a") + expect(mocks.envSet).not.toHaveBeenCalled() + expect(mocks.envAttach).not.toHaveBeenCalled() + }) + it("fails closed when a fresh duplicate check is unavailable", async () => { + mocks.envList.mockRejectedValueOnce(new Error("offline")) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain( + "Unable to check existing variables", + ), + ) + expect(mocks.envSet).not.toHaveBeenCalled() + expect(mocks.envAttach).not.toHaveBeenCalled() + expect( + screen.getByRole("button", { name: "Save" }).hasAttribute("disabled"), + ).toBe(false) + }) + it("allows the same name in another context", async () => { + mocks.envList.mockResolvedValueOnce([ + { name: "NEW", value: "staging-only", context: "staging" }, + ]) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "default-value" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(mocks.envSet).toHaveBeenCalledWith( + "NEW", + "default-value", + "default", + ), + ) + }) + it("creates an empty value after a successful fresh duplicate check", async () => { + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "EMPTY" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(mocks.envSet).toHaveBeenCalledWith("EMPTY", "", "default"), + ) + expect(mocks.envList).toHaveBeenCalledOnce() + expect(mocks.envList.mock.invocationCallOrder[0]).toBeLessThan( + mocks.envSet.mock.invocationCallOrder[0], + ) + }) + it("adopts a late-loaded context once and keeps it for creation and attachment", async () => { + activeContext.set("") + envVars.set([]) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "LATE" }, + }) + activeContext.set("staging") + await fireEvent.click( + screen.getByRole("switch", { name: "Inject into workspaces" }), + ) + activeContext.set("production") + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(mocks.envSet).toHaveBeenCalledWith("LATE", "", "staging"), + ) + expect(mocks.envAttach).toHaveBeenCalledWith("LATE", "staging") + }) + it("rejects creation while the active context is still missing", async () => { + activeContext.set("") + envVars.set([]) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "WAITING" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + expect(screen.getByRole("alert").textContent).toContain( + "No active context is available yet", + ) + expect(mocks.envList).not.toHaveBeenCalled() + expect(mocks.envSet).not.toHaveBeenCalled() + expect(mocks.envAttach).not.toHaveBeenCalled() + }) + it("reports saved variable with failed attachment and prevents duplicate resubmit", async () => { + mocks.envAttach.mockRejectedValueOnce(new Error("offline")) + render(AddDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.click( + screen.getByRole("switch", { name: "Inject into workspaces" }), + ) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain("was saved"), + ) + expect(mocks.envSet).toHaveBeenCalledWith("NEW", "", "default") + expect(screen.queryByRole("button", { name: "Save" })).toBeNull() + }) + it("restores attachment state on failed mutation", async () => { + mocks.envAttach.mockRejectedValueOnce(new Error("offline")) + render(EnvPage) + const toggle = screen.getAllByRole("switch", { + name: "Inject SHARED into workspaces", + })[1] + await fireEvent.click(toggle) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain( + "could not be updated", + ), + ) + expect( + screen + .getAllByRole("switch", { name: "Inject SHARED into workspaces" })[1] + .getAttribute("aria-checked"), + ).toBe("false") + }) +}) + +it("keeps create and attachment in the context captured when add opened", async () => { + let complete!: () => void + mocks.envSet.mockImplementationOnce( + () => + new Promise((resolve) => { + complete = resolve + }), + ) + envVars.set([]) + activeContext.set("default") + render(AddDialog, { open: true }) + activeContext.set("staging") + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "CAPTURED" }, + }) + await fireEvent.click( + screen.getByRole("switch", { name: "Inject into workspaces" }), + ) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + activeContext.set("production") + await waitFor(() => + expect(mocks.envSet).toHaveBeenCalledWith("CAPTURED", "", "default"), + ) + complete() + await waitFor(() => + expect(mocks.envAttach).toHaveBeenCalledWith("CAPTURED", "default"), + ) + expect(mocks.envSet).toHaveBeenCalledWith("CAPTURED", "", "default") + cleanup() +}) diff --git a/desktop/src/renderer/src/lib/components/variables/SecretDetailsSheet.svelte b/desktop/src/renderer/src/lib/components/variables/SecretDetailsSheet.svelte new file mode 100644 index 0000000000..b17f33063b --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretDetailsSheet.svelte @@ -0,0 +1,107 @@ + + + open, (next) => { if (!busy) open = next }}> + { returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null }} onCloseAutoFocus={(e) => { e.preventDefault(); returnFocus?.focus() }} onEscapeKeydown={(e) => { if (busy) e.preventDefault() }} onInteractOutside={(e) => { if (busy) e.preventDefault() }}> + + Secret details + Manage metadata and replace the value without revealing it. + + {#if secret} +
+
+
Name
{secret.name}
+
Context
{secret.context}
+
Storage
{secretStorage(secret)}
+
Availability
{secretAvailability(secret)}
+
+
+ + {#key attachmentReset} + { if (secret) onAttachmentChange(secret, checked) }} /> + {/key} +
+ {#if attachmentError}{/if} + +
+ {/if} + replaceOpen, (next) => { if (!busy) replaceOpen = next }}> + { replaceReturnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null }} onCloseAutoFocus={(e) => { e.preventDefault(); replaceReturnFocus?.focus() }} class="sm:max-w-md" onEscapeKeydown={(e) => { if (busy) e.preventDefault() }} onInteractOutside={(e) => { if (busy) e.preventDefault() }}> + + Replace secret value + Replace the value of {secret?.name} in {secret?.context}. Its name and attachment settings are preserved. + +
{ e.preventDefault(); replace() }}> + + + {#if error}{/if} + + + + +
+
+
+
+
diff --git a/desktop/src/renderer/src/lib/components/variables/SecretDialogs.test.ts b/desktop/src/renderer/src/lib/components/variables/SecretDialogs.test.ts new file mode 100644 index 0000000000..393ada0df3 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretDialogs.test.ts @@ -0,0 +1,126 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/svelte" +import { writable } from "svelte/store" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +const mocks = vi.hoisted(() => ({ + set: vi.fn(), + attach: vi.fn(), + refresh: vi.fn(), + success: vi.fn(), + info: vi.fn(), +})) +vi.mock("$lib/ipc/commands.js", () => ({ + secretSet: mocks.set, + secretAttach: mocks.attach, +})) +vi.mock("$lib/stores/secrets.js", () => ({ + secretsError: writable(null), + secrets: writable([{ name: "EXISTING", context: "staging" }]), + refreshSecrets: mocks.refresh, +})) +vi.mock("$lib/stores/contexts.js", () => ({ + activeContext: writable("staging"), +})) +vi.mock("$lib/stores/toasts.js", () => ({ + toasts: { success: mocks.success, info: mocks.info }, +})) + +import AddSecretDialog from "./AddSecretDialog.svelte" +import SecretDetailsSheet from "./SecretDetailsSheet.svelte" + +describe("Secret dialogs", () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.set.mockResolvedValue(undefined) + mocks.attach.mockResolvedValue(undefined) + mocks.refresh.mockResolvedValue(undefined) + }) + afterEach(cleanup) + it("rejects duplicate add instead of replacing", async () => { + render(AddSecretDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "EXISTING" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "sensitive" }, + }) + expect( + screen.getByText(/A secret with this name already exists/), + ).toBeTruthy() + expect( + (screen.getByRole("button", { name: "Save" }) as HTMLButtonElement) + .disabled, + ).toBe(true) + expect(mocks.set).not.toHaveBeenCalled() + }) + it("preserves whitespace and reports saved-but-not-attached without rollback", async () => { + mocks.attach.mockRejectedValueOnce(new Error("unavailable")) + render(AddSecretDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: " value " }, + }) + await fireEvent.click(screen.getByRole("switch")) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(mocks.set).toHaveBeenCalledWith("NEW", " value ", "staging"), + ) + expect(mocks.attach).toHaveBeenCalledWith("NEW", "staging") + await waitFor(() => + expect(mocks.info).toHaveBeenCalledWith( + "Secret saved, but Devsy could not enable workspace injection.", + ), + ) + }) + it("clears submitted plaintext after save failure and keeps the dialog open", async () => { + mocks.set.mockRejectedValueOnce(new Error("could echo sensitive")) + render(AddSecretDialog, { open: true }) + await fireEvent.input(screen.getByLabelText("Name"), { + target: { value: "NEW" }, + }) + await fireEvent.input(screen.getByLabelText("Value"), { + target: { value: "sensitive" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Save" })) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain("Unable to save"), + ) + expect((screen.getByLabelText("Value") as HTMLInputElement).value).toBe("") + expect(screen.queryByText("could echo sensitive")).toBeNull() + }) + it("explicit replacement passes the displayed row context", async () => { + render(SecretDetailsSheet, { + open: true, + secret: { + name: "OLD", + context: "production", + backend: "file", + availability: "locked", + }, + onAttachmentChange: vi.fn(), + }) + await fireEvent.click( + screen.getByRole("button", { name: "Replace secret value" }), + ) + await fireEvent.input(screen.getByLabelText("New value"), { + target: { value: "replacement" }, + }) + await fireEvent.click(screen.getByRole("button", { name: "Replace" })) + await waitFor(() => + expect(mocks.set).toHaveBeenCalledWith( + "OLD", + "replacement", + "production", + ), + ) + await waitFor(() => expect(screen.queryByLabelText("New value")).toBeNull()) + }) +}) diff --git a/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.svelte b/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.svelte new file mode 100644 index 0000000000..a7018c9293 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.svelte @@ -0,0 +1,144 @@ + + + + { if (busy) event.preventDefault() }} onInteractOutside={(event) => { if (busy) event.preventDefault() }}> + + {titles[action]} + + {#if action === "remove-passphrase"}File-backed secrets will be re-encrypted using Devsy's automatic key mode. + {:else if action === "remember"}Devsy stores the passphrase in your operating system credential manager. + {:else if action === "forget"}Remove automatic access on this device. Secrets may remain available in this desktop session. + {:else}This protection applies to file-backed secrets across all contexts.{/if} + + +
{ event.preventDefault(); void submit() }}> + {#if needsCurrent} + + {#if error && errorField === "currentPassphrase"}{/if} + {/if} + {#if setsPassphrase} + + + {#if newPassphrase.length > 0 && newPassphrase.length < 12}

Choose a long passphrase; at least 12 characters is recommended.

{/if} + {/if} + {#if error && errorField !== "currentPassphrase"}{/if} + + + + +
+
+
diff --git a/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.test.ts b/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.test.ts new file mode 100644 index 0000000000..5e3277c743 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretProtectionActionDialog.test.ts @@ -0,0 +1,127 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/svelte" +import { beforeEach, describe, expect, it, vi } from "vitest" +import { secretProtectionAction } from "$lib/ipc/commands.js" +import { refreshSecretProtection } from "$lib/stores/secret-protection.js" +import { refreshSecrets } from "$lib/stores/secrets.js" +import type { SecretProtectionStatus } from "$lib/types/index.js" +import SecretProtectionActionDialog from "./SecretProtectionActionDialog.svelte" + +vi.mock("$lib/ipc/commands.js", () => ({ secretProtectionAction: vi.fn() })) +vi.mock("$lib/stores/secret-protection.js", () => ({ + refreshSecretProtection: vi.fn(async () => {}), +})) +vi.mock("$lib/stores/secrets.js", () => ({ + refreshSecrets: vi.fn(async () => {}), +})) +vi.mock("$lib/stores/toasts.js", () => ({ toasts: { success: vi.fn() } })) + +const locked: SecretProtectionStatus = { + availability: "locked", + keySource: "passphrase", + remembered: false, + rememberedAvailable: true, + sessionUnlocked: false, + fileEntries: [], +} +describe("SecretProtectionActionDialog", () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(secretProtectionAction).mockResolvedValue({ ok: true }) + }) + it("keeps failed removal inline, clears submitted credentials, and permits retry", async () => { + vi.mocked(secretProtectionAction).mockResolvedValueOnce({ + ok: false, + cliError: { code: "unlock_failed", message: "internal details" }, + }) + const page = render(SecretProtectionActionDialog, { + open: true, + action: "remove-passphrase", + status: locked, + }) + const input = await screen.findByLabelText("Current passphrase") + await fireEvent.input(input, { target: { value: "incorrect" } }) + await fireEvent.click( + screen.getByRole("button", { name: "Remove protection" }), + ) + await screen.findByText("That passphrase didn't unlock this secret store.") + expect((input as HTMLInputElement).value).toBe("") + expect(secretProtectionAction).toHaveBeenCalledWith({ + action: "remove-passphrase", + currentPassphrase: "incorrect", + }) + expect(refreshSecrets).not.toHaveBeenCalled() + await fireEvent.input(input, { target: { value: "correct" } }) + await fireEvent.click( + screen.getByRole("button", { name: "Remove protection" }), + ) + await waitFor(() => expect(refreshSecrets).toHaveBeenCalledOnce()) + expect(refreshSecretProtection).toHaveBeenCalledOnce() + await waitFor(() => + expect(screen.queryByLabelText("Current passphrase")).toBeNull(), + ) + page.unmount() + }) + it("validates confirmation before IPC and permits short matching passphrases", async () => { + const page = render(SecretProtectionActionDialog, { + open: true, + action: "set-passphrase", + status: locked, + }) + await fireEvent.input(await screen.findByLabelText("New passphrase"), { + target: { value: "short" }, + }) + await fireEvent.click( + screen.getByRole("button", { name: "Use a passphrase" }), + ) + await screen.findByText("Passphrases do not match.") + expect(secretProtectionAction).not.toHaveBeenCalled() + await fireEvent.input(screen.getByLabelText("Confirm new passphrase"), { + target: { value: "short" }, + }) + await fireEvent.click( + screen.getByRole("button", { name: "Use a passphrase" }), + ) + await waitFor(() => + expect(secretProtectionAction).toHaveBeenCalledWith({ + action: "set-passphrase", + newPassphrase: "short", + }), + ) + page.unmount() + }) + it("omits current input only when availability is verified", async () => { + const page = render(SecretProtectionActionDialog, { + open: true, + action: "change-passphrase", + status: { ...locked, availability: "available" }, + }) + await screen.findByLabelText("New passphrase") + expect(screen.queryByLabelText("Current passphrase")).toBeNull() + page.unmount() + const cached = render(SecretProtectionActionDialog, { + open: true, + action: "change-passphrase", + status: { ...locked, sessionUnlocked: true, remembered: true }, + }) + await screen.findByLabelText("Current passphrase") + cached.unmount() + }) + it("handles native cancellation without an error or false success", async () => { + vi.mocked(secretProtectionAction).mockResolvedValue({ + ok: false, + message: "Secret protection change canceled.", + }) + const page = render(SecretProtectionActionDialog, { + open: true, + action: "forget", + status: locked, + }) + await fireEvent.click( + await screen.findByRole("button", { name: "Forget this device" }), + ) + await waitFor(() => expect(secretProtectionAction).toHaveBeenCalled()) + expect(screen.queryByRole("alert")).toBeNull() + expect(refreshSecrets).not.toHaveBeenCalled() + page.unmount() + }) +}) diff --git a/desktop/src/renderer/src/lib/components/variables/SecretSecurityBanner.svelte b/desktop/src/renderer/src/lib/components/variables/SecretSecurityBanner.svelte new file mode 100644 index 0000000000..ee83a536c6 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretSecurityBanner.svelte @@ -0,0 +1,56 @@ + + +{#if message && ($secretProtectionStatus || $secretProtectionError)} +
+

{message}

+ {#if view === "passphrase_locked"}

Unlock them to use their values in workspace operations.

{/if} +
+ {#if view === "passphrase_locked"}{/if} + +
+ {#if error}{/if} +
+{/if} diff --git a/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.svelte b/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.svelte new file mode 100644 index 0000000000..a88a6d872f --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.svelte @@ -0,0 +1,139 @@ + + + + + + Secret Security + Protection for shared file-backed secrets across all contexts. Environment variables and keyring-backed secrets are managed separately. + + {#if $secretProtectionLoading && !$secretProtectionStatus}

Loading security status…

{/if} + {#if $secretProtectionError}{/if} +
+
Status
{statusLabel}
+
Protection
{secretProtectionModeLabel($secretProtectionStatus)}
+
Remembered on device
{$secretProtectionStatus?.rememberedAvailable === false ? "Unavailable" : $secretProtectionStatus?.remembered ? "Yes" : "No"}
+
+ {#if healthy && $secretProtectionStatus} +

Passphrase protection

+ + {#if view === "passphrase_locked"}{/if} +
+ {#if protectedStore} + {#if !$secretProtectionStatus.remembered} +

Device access

+

Devsy stores the passphrase in your operating system credential manager.

+ {#if !$secretProtectionStatus.remembered && $secretProtectionStatus.rememberedAvailable} + {:else if !$secretProtectionStatus.rememberedAvailable}

Your operating system credential manager is unavailable.

{/if} +
+ {/if} +

Remove protection

+ {/if} + {:else if $secretProtectionStatus}

Devsy needs attention to access the shared secret store. Review recovery options before changing protection.

{/if} + {#if $secretProtectionStatus?.remembered} +

Device access

+ {/if} + {#if $secretProtectionStatus?.sessionUnlocked} +

Advanced

Removes the passphrase held by this desktop session. Other available credentials may still unlock the store.

+ {/if} + + {#if error}{/if} +
+
+ + + + Recovery optionsA passphrase remembered on this device may still unlock the store. Without a valid credential, encrypted file contents cannot be decrypted. +

Resetting permanently removes every file-backed secret across all contexts. Keyring-backed secrets, environment variables, and external secret sources are separate.

+

Review and confirm a reset in your terminal:

+ devsy secret protection reset-file-store + {#if recoveryError}{/if} + +
+
diff --git a/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.test.ts b/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.test.ts new file mode 100644 index 0000000000..2e0cd29dbf --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretSecuritySheet.test.ts @@ -0,0 +1,145 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/svelte" +import { beforeEach, describe, expect, it, vi } from "vitest" +import { secretSessionClear, secretUnlockRequest } from "$lib/ipc/commands.js" +import { + refreshSecretProtection, + secretProtectionError, + secretProtectionLoading, + secretProtectionStatus, +} from "$lib/stores/secret-protection.js" +import type { SecretProtectionStatus } from "$lib/types/index.js" +import SecretSecurityBanner from "./SecretSecurityBanner.svelte" +import SecretSecuritySheet from "./SecretSecuritySheet.svelte" + +vi.mock("$lib/ipc/commands.js", () => ({ + secretSessionClear: vi.fn(async () => undefined), + secretUnlockRequest: vi.fn(async () => ({ ok: true })), + secretProtectionAction: vi.fn(async () => ({ ok: true })), +})) +vi.mock("$lib/stores/secret-protection.js", async () => { + const { writable } = await import("svelte/store") + return { + secretProtectionStatus: writable(null), + secretProtectionLoading: writable(false), + secretProtectionError: writable(null), + refreshSecretProtection: vi.fn(async () => {}), + } +}) +vi.mock("$lib/stores/secrets.js", () => ({ + refreshSecrets: vi.fn(async () => {}), +})) +vi.mock("$lib/stores/toasts.js", () => ({ toasts: { success: vi.fn() } })) +const available: SecretProtectionStatus = { + availability: "available", + keySource: "passphrase", + remembered: false, + rememberedAvailable: true, + sessionUnlocked: true, + fileEntries: [], +} + +describe("Secret Security", () => { + beforeEach(() => { + secretProtectionStatus.set(available) + secretProtectionLoading.set(false) + secretProtectionError.set(null) + vi.clearAllMocks() + }) + it("refreshes protection after clearing session access without treating void as failure", async () => { + const page = render(SecretSecuritySheet, { open: true }) + await fireEvent.click( + await screen.findByRole("button", { name: "Clear session passphrase" }), + ) + await waitFor(() => expect(secretSessionClear).toHaveBeenCalledOnce()) + await waitFor(() => + expect(refreshSecretProtection).toHaveBeenCalledTimes(2), + ) + expect(screen.queryByRole("alert")).toBeNull() + page.unmount() + }) + it("disables mutations when a refresh failed and cached status remains", async () => { + secretProtectionError.set("Unable to load secret security status.") + const page = render(SecretSecuritySheet, { open: true }) + const change = await screen.findByRole("button", { + name: "Change passphrase", + }) + expect((change as HTMLButtonElement).disabled).toBe(true) + page.unmount() + }) + it("retains a failed explicit unlock message after reopening the sheet", async () => { + vi.mocked(secretUnlockRequest).mockResolvedValueOnce({ + ok: false, + cliError: { code: "unlock_failed", message: "internal" }, + }) + secretProtectionStatus.set({ + ...available, + availability: "locked", + sessionUnlocked: false, + }) + const page = render(SecretSecuritySheet, { open: true }) + await fireEvent.click(await screen.findByRole("button", { name: "Unlock" })) + await screen.findByText("That passphrase didn't unlock this secret store.") + page.unmount() + }) + it("offers truthful session clearing even when device access is remembered", async () => { + const page = render(SecretSecuritySheet, { open: true }) + await screen.findByRole("button", { name: "Clear session passphrase" }) + secretProtectionStatus.set({ ...available, remembered: true }) + await screen.findByRole("button", { name: "Forget this device" }) + expect( + screen.getByRole("button", { name: "Clear session passphrase" }), + ).toBeTruthy() + expect(screen.queryByLabelText("New passphrase")).toBeNull() + page.unmount() + }) + it("retains Forget and session clearing when the encrypted store is unreadable", async () => { + secretProtectionStatus.set({ + ...available, + remembered: true, + availability: "unknown", + reasonCode: "store_corrupt", + }) + const page = render(SecretSecuritySheet, { open: true }) + await screen.findByRole("button", { name: "Forget this device" }) + expect( + screen.getByRole("button", { name: "Clear session passphrase" }), + ).toBeTruthy() + expect( + screen.queryByRole("button", { name: "Change passphrase" }), + ).toBeNull() + page.unmount() + }) + it("keeps the destructive recovery command behind Recovery options", async () => { + const page = render(SecretSecuritySheet, { open: true }) + await screen.findByRole("button", { name: "Recovery options" }) + expect( + screen.queryByText("devsy secret protection reset-file-store"), + ).toBeNull() + await fireEvent.click( + screen.getByRole("button", { name: "Recovery options" }), + ) + await screen.findByText("devsy secret protection reset-file-store") + expect( + screen.getByText(/every file-backed secret across all contexts/), + ).toBeTruthy() + expect(screen.queryByRole("button", { name: "Reset" })).toBeNull() + page.unmount() + }) + it("hides a healthy banner and exposes security management while locked", async () => { + const onManageSecurity = vi.fn() + const page = render(SecretSecurityBanner, { onManageSecurity }) + expect(screen.queryByRole("status")).toBeNull() + secretProtectionStatus.set({ + ...available, + availability: "locked", + sessionUnlocked: false, + }) + await screen.findByText("File-backed secrets are locked") + await fireEvent.click( + screen.getByRole("button", { name: "Manage security" }), + ) + expect(onManageSecurity).toHaveBeenCalledOnce() + expect(screen.getByRole("button", { name: "Unlock" })).toBeTruthy() + page.unmount() + }) +}) diff --git a/desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.svelte b/desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.svelte new file mode 100644 index 0000000000..51cafca200 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.svelte @@ -0,0 +1,157 @@ + +
+
+
+ {#if onManageSecurity}{/if} +
+ {#if $secretsLoading} + {:else if $secretsError} + {:else if $secrets.length === 0}

No secrets stored.

+ {:else if filtered.length === 0}

No secrets match "{search}"

+ {:else} +
+ + NameContextStorageStatus + InjectInject automatically into workspace setup and new Devsy-managed terminal/SSH sessions. Changes apply on the next applicable workspace start/recreation or new session. + Actions + + {#each filtered as secret (variableIdentity(secret.context, secret.name))} + {@const key = variableIdentity(secret.context, secret.name)} + details(secret)}> + + {secret.context}{secretStorage(secret)} + {secretAvailability(secret)} + + e.stopPropagation()}> + {#key resets[key] ?? 0} setAttached(secret, checked)} />{/key} + {#if errors[key]}{/if} + + + e.stopPropagation()}> + {#snippet child({ props })}{/snippet} + details(secret)}>View details details(secret, true)}>Replace value requestDelete(secret)}>Delete + + + {/each} +
+ {/if} +
+ + + deleteOpen, (next) => { if (!deleting) deleteOpen = next }} title="Delete secret" description={`Permanently delete secret '${pendingDelete?.name ?? ""}' in ${pendingDelete?.context ?? ""} and its value. This cannot be undone.`} confirmLabel="Delete" loading={deleting} onconfirm={remove}>{#if deleteError}{/if} diff --git a/desktop/src/renderer/src/pages/SecretsPage.test.ts b/desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.test.ts similarity index 60% rename from desktop/src/renderer/src/pages/SecretsPage.test.ts rename to desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.test.ts index d263d1c609..dcd6edf86c 100644 --- a/desktop/src/renderer/src/pages/SecretsPage.test.ts +++ b/desktop/src/renderer/src/lib/components/variables/SecretsVariablesPanel.test.ts @@ -51,7 +51,7 @@ vi.mock("$lib/stores/secrets.js", async () => { } }) -import SecretsPage from "./SecretsPage.svelte" +import SecretsPage from "$lib/components/variables/SecretsVariablesPanel.svelte" describe("SecretsPage managed secret attachments", () => { beforeEach(() => { @@ -107,14 +107,70 @@ describe("SecretsPage managed secret attachments", () => { it("shows availability states while keeping locked secret metadata usable", () => { render(SecretsPage) - expect(screen.getByRole("status").textContent).toContain( - "One secret value is locked", - ) + expect(screen.getByRole("table")).toBeTruthy() expect(screen.getByText("Locked")).toBeTruthy() expect(screen.getByText("Missing value")).toBeTruthy() - expect(screen.getByText("Backend unavailable")).toBeTruthy() + expect(screen.getByText("Unavailable")).toBeTruthy() expect( screen.getByRole("switch", { name: "Inject LOCKED_KEY into workspaces" }), ).toBeTruthy() }) + it("sorts rows by name and searches context", async () => { + render(SecretsPage) + const names = Array.from( + screen.getByRole("table").querySelectorAll("tbody tr"), + ).map((row) => row.querySelector("button")?.textContent?.trim()) + expect(names).toEqual([ + "ATTACHED", + "BACKEND_KEY", + "DETACHED", + "LOCKED_KEY", + "MISSING_KEY", + "STAGING_ONLY", + ]) + await fireEvent.input( + screen.getByRole("textbox", { name: "Search secrets" }), + { target: { value: "staging" } }, + ) + expect(screen.getByRole("button", { name: "STAGING_ONLY" })).toBeTruthy() + expect(screen.queryByRole("button", { name: "ATTACHED" })).toBeNull() + }) + + it("restores the switch after an attachment failure", async () => { + mocks.secretAttach.mockRejectedValueOnce(new Error("Failed request")) + render(SecretsPage) + await fireEvent.click( + screen.getByRole("switch", { name: "Inject DETACHED into workspaces" }), + ) + await waitFor(() => + expect(screen.getByRole("alert").textContent).toContain( + "Unable to update workspace injection. Try again.", + ), + ) + expect( + screen + .getByRole("switch", { name: "Inject DETACHED into workspaces" }) + .getAttribute("aria-checked"), + ).toBe("false") + expect(screen.queryByText("Secret details")).toBeNull() + }) + + it("deletes the exact row context after explicit confirmation", async () => { + render(SecretsPage) + const actions = screen.getByRole("button", { + name: "Actions for STAGING_ONLY", + }) + await fireEvent.click(actions) + const menuItem = await screen.findByRole("menuitem", { + name: "Delete", + }) + await fireEvent.click(menuItem) + await fireEvent.click(screen.getByRole("button", { name: "Delete" })) + await waitFor(() => + expect(mocks.secretDelete).toHaveBeenCalledWith( + "STAGING_ONLY", + "staging", + ), + ) + }) }) diff --git a/desktop/src/renderer/src/lib/components/variables/secret-presentation.ts b/desktop/src/renderer/src/lib/components/variables/secret-presentation.ts new file mode 100644 index 0000000000..defc064569 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/variables/secret-presentation.ts @@ -0,0 +1,24 @@ +import type { Secret } from "$lib/types/index.js" + +export function secretStorage(secret: Secret): string { + return secret.backend === "keyring" + ? "OS keychain" + : secret.backend === "file" + ? "Encrypted file" + : "Unknown" +} + +export function secretAvailability(secret: Secret): string { + switch (secret.availability ?? (secret.orphaned ? "missing" : "unknown")) { + case "available": + return "Available" + case "locked": + return "Locked" + case "missing": + return "Missing value" + case "backend_unavailable": + return "Unavailable" + default: + return "Unknown" + } +} diff --git a/desktop/src/renderer/src/lib/ipc/commands.test.ts b/desktop/src/renderer/src/lib/ipc/commands.test.ts index 3600371ada..f1ff9808ad 100644 --- a/desktop/src/renderer/src/lib/ipc/commands.test.ts +++ b/desktop/src/renderer/src/lib/ipc/commands.test.ts @@ -10,6 +10,8 @@ import { envAttach, envDelete, envDetach, + envList, + envSet, machineCreate, machineDelete, machineStatus, @@ -17,7 +19,13 @@ import { providerAdd, providerSetOptions, secretAttach, + secretDelete, secretDetach, + secretProtectionAction, + secretProtectionStatus, + secretSessionClear, + secretSet, + secretUnlockRequest, sshKeyGenerate, sshKeyList, workspaceDelete, @@ -394,3 +402,92 @@ describe("IPC commands", () => { }) }) }) + +describe("typed variable and protection commands", () => { + beforeEach(() => { + resetTauriMocks() + mockInvoke.mockResolvedValue({ ok: true }) + }) + it("transports row context for secret mutations and env update", async () => { + await secretSet("TOKEN", "value", "other") + expect(mockInvoke).toHaveBeenLastCalledWith("secret_set", { + name: "TOKEN", + value: "value", + context: "other", + }) + await secretDelete("TOKEN", "other") + expect(mockInvoke).toHaveBeenLastCalledWith("secret_delete", { + name: "TOKEN", + context: "other", + }) + await envSet("PORT", "", "other") + expect(mockInvoke).toHaveBeenLastCalledWith("env_set", { + name: "PORT", + value: "", + context: "other", + }) + }) + it("transports explicit context for environment listing", async () => { + const rows = [{ name: "PORT", value: "8080", context: "other" }] + mockInvoke.mockResolvedValue(rows) + expect(await envList("other")).toEqual(rows) + expect(mockInvoke).toHaveBeenLastCalledWith("env_list", { + context: "other", + }) + }) + it("preserves the default environment listing invocation", async () => { + mockInvoke.mockResolvedValue([]) + expect(await envList()).toEqual([]) + expect(mockInvoke).toHaveBeenLastCalledWith("env_list") + }) + it("preserves omitted context payloads", async () => { + await secretSet("TOKEN", "value") + expect(mockInvoke).toHaveBeenLastCalledWith("secret_set", { + name: "TOKEN", + value: "value", + }) + }) + it("passes explicit current/new fields and retains structured failures", async () => { + const failure = { + ok: false, + cliError: { code: "unlock_failed", message: "failure" }, + } + mockInvoke.mockResolvedValue(failure) + expect( + await secretProtectionAction({ + action: "change-passphrase", + currentPassphrase: "current", + newPassphrase: "next", + }), + ).toEqual(failure) + expect(mockInvoke).toHaveBeenLastCalledWith("secret_protection_action", { + action: "change-passphrase", + currentPassphrase: "current", + newPassphrase: "next", + }) + }) + it("wraps status, unlock request and session clear channels", async () => { + mockInvoke.mockResolvedValue({ + availability: "locked", + keySource: "passphrase", + }) + await secretProtectionStatus() + expect(mockInvoke).toHaveBeenLastCalledWith("secret_protection_status") + await secretUnlockRequest() + expect(mockInvoke).toHaveBeenLastCalledWith("secret_unlock_request") + mockInvoke.mockResolvedValue(undefined) + await secretSessionClear() + expect(mockInvoke).toHaveBeenLastCalledWith("secret_session_clear") + }) +}) + +describe("protection read and clear denial", () => { + it("rejects a status denial instead of storing it as status", async () => { + mockInvoke.mockResolvedValue({ ok: false, message: "Request denied." }) + await expect(secretProtectionStatus()).rejects.toThrow("Request denied.") + }) + it("surfaces session-clear denial", async () => { + mockInvoke.mockResolvedValue({ ok: false, message: "Request denied." }) + await expect(secretSessionClear()).rejects.toThrow("Request denied.") + }) +}) diff --git a/desktop/src/renderer/src/lib/ipc/commands.ts b/desktop/src/renderer/src/lib/ipc/commands.ts index 246f00ff3e..28783a3b2b 100644 --- a/desktop/src/renderer/src/lib/ipc/commands.ts +++ b/desktop/src/renderer/src/lib/ipc/commands.ts @@ -11,6 +11,9 @@ import type { ProviderVersion, ProviderVersionCheckResult, Secret, + SecretProtectionActionInput, + SecretProtectionActionResult, + SecretProtectionStatus, SshKeyInfo, Workspace, } from "$lib/types/index.js" @@ -331,16 +334,64 @@ export async function contextDelete(name: string): Promise { return invoke("context_delete", { name }) } +export async function secretProtectionStatus(): Promise { + const result = await invoke( + "secret_protection_status", + ) + if ("ok" in result) { + unwrapEnvelope(result) + throw new Error("Unable to load secret security status.") + } + return result +} + +export function secretProtectionAction( + input: SecretProtectionActionInput, +): Promise { + return invoke("secret_protection_action", { + ...input, + }) +} + +export function secretUnlockRequest(): Promise { + return invoke("secret_unlock_request") +} + +export async function secretSessionClear(): Promise { + const result = await invoke( + "secret_session_clear", + ) + if (result) unwrapEnvelope(result) +} + export async function secretList(): Promise { return invoke("secret_list") } -export async function secretSet(name: string, value: string): Promise { - unwrapEnvelope(await invoke("secret_set", { name, value })) +export async function secretSet( + name: string, + value: string, + context?: string, +): Promise { + unwrapEnvelope( + await invoke("secret_set", { + name, + value, + ...(context === undefined ? {} : { context }), + }), + ) } -export async function secretDelete(name: string): Promise { - unwrapEnvelope(await invoke("secret_delete", { name })) +export async function secretDelete( + name: string, + context?: string, +): Promise { + unwrapEnvelope( + await invoke("secret_delete", { + name, + ...(context === undefined ? {} : { context }), + }), + ) } export async function secretAttach( @@ -361,12 +412,24 @@ export async function secretDetach( ) } -export async function envList(): Promise { - return invoke("env_list") +export async function envList(context?: string): Promise { + return context === undefined + ? invoke("env_list") + : invoke("env_list", { context }) } -export async function envSet(name: string, value: string): Promise { - unwrapEnvelope(await invoke("env_set", { name, value })) +export async function envSet( + name: string, + value: string, + context?: string, +): Promise { + unwrapEnvelope( + await invoke("env_set", { + name, + value, + ...(context === undefined ? {} : { context }), + }), + ) } export async function envDelete(name: string, context: string): Promise { diff --git a/desktop/src/renderer/src/lib/stores/env.test.ts b/desktop/src/renderer/src/lib/stores/env.test.ts new file mode 100644 index 0000000000..324e1d5f61 --- /dev/null +++ b/desktop/src/renderer/src/lib/stores/env.test.ts @@ -0,0 +1,40 @@ +import { get } from "svelte/store" +import { beforeEach, expect, it, vi } from "vitest" + +const mocks = vi.hoisted(() => ({ envList: vi.fn() })) +vi.mock("$lib/ipc/commands.js", () => mocks) + +import { envError, envLoading, envVars, initEnv, refreshEnv } from "./env.js" + +beforeEach(() => { + vi.resetAllMocks() + envVars.set([]) + envError.set(null) +}) +it("surfaces load failures and clears the error after retry", async () => { + mocks.envList + .mockRejectedValueOnce(new Error("offline")) + .mockResolvedValueOnce([]) + await initEnv() + expect(get(envError)).toBe("offline") + expect(get(envLoading)).toBe(false) + await refreshEnv() + expect(get(envError)).toBeNull() +}) +it("ignores an older load that finishes after a newer request", async () => { + let resolveOld!: (rows: unknown[]) => void + mocks.envList + .mockReturnValueOnce( + new Promise((resolve) => { + resolveOld = resolve + }), + ) + .mockResolvedValueOnce([]) + const old = refreshEnv() + await refreshEnv() + resolveOld([ + { name: "OLD", context: "default", value: "old", attached: false }, + ]) + await old + expect(get(envVars)).toEqual([]) +}) diff --git a/desktop/src/renderer/src/lib/stores/env.ts b/desktop/src/renderer/src/lib/stores/env.ts index 31302d3cb2..69d2856f9d 100644 --- a/desktop/src/renderer/src/lib/stores/env.ts +++ b/desktop/src/renderer/src/lib/stores/env.ts @@ -1,25 +1,27 @@ import { writable } from "svelte/store" import { envList } from "$lib/ipc/commands.js" import type { EnvVar } from "$lib/types/index.js" +import { extractErrorMessage } from "$lib/utils/error.js" export const envVars = writable([]) export const envLoading = writable(true) +export const envError = writable(null) +let requestGeneration = 0 export async function refreshEnv(): Promise { + const generation = ++requestGeneration + envError.set(null) try { - envVars.set(await envList()) - } catch { - // IPC not available + const result = await envList() + if (generation === requestGeneration) envVars.set(result) + } catch (error) { + if (generation === requestGeneration) + envError.set(extractErrorMessage(error)) } } export async function initEnv(): Promise { envLoading.set(true) - try { - envVars.set(await envList()) - } catch { - // IPC not available - } finally { - envLoading.set(false) - } + await refreshEnv() + envLoading.set(false) } diff --git a/desktop/src/renderer/src/lib/stores/secret-protection.test.ts b/desktop/src/renderer/src/lib/stores/secret-protection.test.ts new file mode 100644 index 0000000000..18f327a66f --- /dev/null +++ b/desktop/src/renderer/src/lib/stores/secret-protection.test.ts @@ -0,0 +1,64 @@ +import { get } from "svelte/store" +import { beforeEach, describe, expect, it } from "vitest" +import { mockInvoke, resetTauriMocks } from "$lib/__mocks__/tauri.js" +import type { SecretProtectionStatus } from "$lib/types/index.js" +import { + initSecretProtection, + refreshSecretProtection, + secretProtectionError, + secretProtectionLoading, + secretProtectionStatus, +} from "./secret-protection.js" + +const status: SecretProtectionStatus = { + availability: "locked", + keySource: "passphrase", + remembered: false, + rememberedAvailable: true, + fileEntries: [], + sessionUnlocked: false, +} +describe("secret protection store", () => { + beforeEach(() => { + resetTauriMocks() + secretProtectionStatus.set(null) + secretProtectionError.set(null) + secretProtectionLoading.set(false) + }) + it("loads metadata and exposes failures with retry", async () => { + mockInvoke + .mockRejectedValueOnce(new Error("raw text")) + .mockResolvedValueOnce(status) + await initSecretProtection() + expect(get(secretProtectionError)).toBe( + "Unable to load secret security status.", + ) + expect(get(secretProtectionLoading)).toBe(false) + await refreshSecretProtection() + expect(get(secretProtectionStatus)).toEqual(status) + expect(get(secretProtectionError)).toBeNull() + }) + it("ignores an older refresh completing after the latest request", async () => { + let resolveOlder!: (value: SecretProtectionStatus) => void + mockInvoke + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveOlder = resolve + }), + ) + .mockResolvedValueOnce(status) + const older = refreshSecretProtection() + await refreshSecretProtection() + resolveOlder({ ...status, availability: "available" }) + await older + expect(get(secretProtectionStatus)?.availability).toBe("locked") + expect(get(secretProtectionLoading)).toBe(false) + }) + it("retains existing metadata when a refresh fails", async () => { + secretProtectionStatus.set(status) + mockInvoke.mockRejectedValue(new Error("failed")) + await refreshSecretProtection() + expect(get(secretProtectionStatus)).toEqual(status) + }) +}) diff --git a/desktop/src/renderer/src/lib/stores/secret-protection.ts b/desktop/src/renderer/src/lib/stores/secret-protection.ts new file mode 100644 index 0000000000..dcf24a6d3e --- /dev/null +++ b/desktop/src/renderer/src/lib/stores/secret-protection.ts @@ -0,0 +1,31 @@ +import { writable } from "svelte/store" +import { secretProtectionStatus as loadStatus } from "$lib/ipc/commands.js" +import type { SecretProtectionStatus } from "$lib/types/index.js" + +// Only metadata belongs here. Credentials remain local to operation dialogs. +export const secretProtectionStatus = writable( + null, +) +export const secretProtectionLoading = writable(false) +export const secretProtectionError = writable(null) +let requestGeneration = 0 + +export async function refreshSecretProtection(): Promise { + const generation = ++requestGeneration + secretProtectionLoading.set(true) + try { + const status = await loadStatus() + if (generation !== requestGeneration) return + secretProtectionStatus.set(status) + secretProtectionError.set(null) + } catch { + if (generation !== requestGeneration) return + secretProtectionError.set("Unable to load secret security status.") + } finally { + if (generation === requestGeneration) secretProtectionLoading.set(false) + } +} + +export async function initSecretProtection(): Promise { + await refreshSecretProtection() +} diff --git a/desktop/src/renderer/src/lib/types/index.ts b/desktop/src/renderer/src/lib/types/index.ts index baa62b48c6..e34ba9da73 100644 --- a/desktop/src/renderer/src/lib/types/index.ts +++ b/desktop/src/renderer/src/lib/types/index.ts @@ -149,6 +149,49 @@ export interface Context { options?: Record } +export type SecretAvailability = + | "available" + | "locked" + | "missing" + | "backend_unavailable" + | "unknown" + +export interface SecretProtectionFileEntry { + name: string + context: string + backend?: "file" +} + +export interface SecretProtectionStatus { + availability: SecretAvailability + reasonCode?: string + /** Exact Go file-key source values; keyring/file are automatic modes. */ + keySource: "" | "passphrase" | "keyring" | "file" + remembered: boolean + rememberedAvailable: boolean + fileEntries: SecretProtectionFileEntry[] + sessionUnlocked: boolean +} + +export type SecretProtectionAction = + | "set-passphrase" + | "change-passphrase" + | "remove-passphrase" + | "remember" + | "forget" + +export interface SecretProtectionActionInput { + action: SecretProtectionAction + newPassphrase?: string + currentPassphrase?: string +} + +export interface SecretProtectionActionResult { + ok: boolean + message?: string + cliError?: import("$shared/cli-error.js").CLIError +} + export interface Secret { name: string context: string @@ -156,12 +199,7 @@ export interface Secret { lastUsed?: string orphaned?: boolean /** Whether Devsy can currently read this secret's value. */ - availability?: - | "available" - | "locked" - | "missing" - | "backend_unavailable" - | "unknown" + availability?: SecretAvailability backend?: "keyring" | "file" attached?: boolean } diff --git a/desktop/src/renderer/src/lib/variables/identity.ts b/desktop/src/renderer/src/lib/variables/identity.ts new file mode 100644 index 0000000000..8faa3341ce --- /dev/null +++ b/desktop/src/renderer/src/lib/variables/identity.ts @@ -0,0 +1,4 @@ +/** Stable identity even when contexts or names contain separators. */ +export function variableIdentity(context: string, name: string): string { + return JSON.stringify([context, name]) +} diff --git a/desktop/src/renderer/src/lib/variables/secret-errors.test.ts b/desktop/src/renderer/src/lib/variables/secret-errors.test.ts new file mode 100644 index 0000000000..e872b45c65 --- /dev/null +++ b/desktop/src/renderer/src/lib/variables/secret-errors.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest" +import { mapSecretError } from "./secret-errors.js" + +describe("secret errors", () => { + it.each(["unlock_required", "unlock_failed"])( + "places %s under the current field", + (code) => { + const error = Object.assign(new Error("raw backend text"), { + cliError: { code, message: "raw backend text" }, + }) + expect(mapSecretError(error).field).toBe("currentPassphrase") + expect(mapSecretError(error).message).not.toContain("raw backend") + }, + ) + it.each(["secret_backend_unavailable", "backend_unavailable"])( + "maps %s", + (code) => { + expect(mapSecretError({ cliError: { code } }).recovery).toBe( + "manage_security", + ) + }, + ) + it.each(["secret_store_corrupt", "store_corrupt"])( + "offers recovery for %s", + (code) => { + expect(mapSecretError({ cliError: { code } }).recovery).toBe("recovery") + }, + ) + it("recognizes native cancellation", () => { + expect( + mapSecretError({ + ok: false, + message: "Secret protection change canceled.", + }).cancelled, + ).toBe(true) + }) + it("recognizes explicit unlock cancellation", () => { + expect( + mapSecretError({ ok: false, message: "Secret unlock canceled." }) + .cancelled, + ).toBe(true) + }) + it("recognizes structured cancellation", () => { + expect(mapSecretError({ cliError: { code: "canceled" } }).cancelled).toBe( + true, + ) + }) + it("does not classify a backend failure as native cancellation", () => { + expect( + mapSecretError({ + message: "Secret protection change canceled.", + cliError: { code: "UNKNOWN" }, + }).cancelled, + ).toBe(false) + }) + it("never promotes unknown raw messages", () => { + expect( + mapSecretError(new Error("credential sensitive raw value")).message, + ).toBe("The secret protection change could not be completed.") + expect(mapSecretError(null).field).toBeUndefined() + }) +}) diff --git a/desktop/src/renderer/src/lib/variables/secret-errors.ts b/desktop/src/renderer/src/lib/variables/secret-errors.ts new file mode 100644 index 0000000000..1f0e57065b --- /dev/null +++ b/desktop/src/renderer/src/lib/variables/secret-errors.ts @@ -0,0 +1,73 @@ +import type { SecretProtectionActionResult } from "$lib/types/index.js" + +export interface UserFacingSecretError { + message: string + field?: "currentPassphrase" | "newPassphrase" + recovery?: "retry" | "manage_security" | "recovery" + cancelled: boolean +} + +/** Structured codes determine primary copy; raw backend messages stay out of UI. */ +export function mapSecretError(error: unknown): UserFacingSecretError { + const result = + error && typeof error === "object" + ? (error as { message?: unknown; cliError?: { code?: string } }) + : undefined + const code = result?.cliError?.code + switch (code) { + case "unlock_required": + return { + message: "Enter your current passphrase to continue.", + field: "currentPassphrase", + cancelled: false, + } + case "unlock_failed": + return { + message: "That passphrase didn't unlock this secret store.", + field: "currentPassphrase", + cancelled: false, + } + case "secret_backend_unavailable": + case "backend_unavailable": + return { + message: + "Devsy can't access the key or credential service required by this secret store.", + recovery: "manage_security", + cancelled: false, + } + case "secret_store_corrupt": + case "store_corrupt": + return { + message: "Devsy couldn't read the encrypted secret store.", + recovery: "recovery", + cancelled: false, + } + case "secret_not_found": + return { + message: "The secret value could not be found.", + recovery: "manage_security", + cancelled: false, + } + case "canceled": + return { message: "Secret protection change canceled.", cancelled: true } + } + // Native cancellation has no CLI error because the CLI never ran. + if ( + !code && + (result?.message === "Secret protection change canceled." || + result?.message === "Secret unlock canceled.") + ) { + return { message: "Secret protection change canceled.", cancelled: true } + } + return { + message: "The secret protection change could not be completed.", + recovery: "retry", + cancelled: false, + } +} + +export function presentSecretProtectionError( + result: SecretProtectionActionResult, +): UserFacingSecretError { + return mapSecretError(result) +} diff --git a/desktop/src/renderer/src/lib/variables/secret-protection-state.test.ts b/desktop/src/renderer/src/lib/variables/secret-protection-state.test.ts new file mode 100644 index 0000000000..79fe200759 --- /dev/null +++ b/desktop/src/renderer/src/lib/variables/secret-protection-state.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest" +import type { SecretProtectionStatus } from "$lib/types/index.js" +import { variableIdentity } from "./identity.js" +import { + getSecretProtectionViewState, + secretProtectionModeLabel, + secretProtectionStateLabel, +} from "./secret-protection-state.js" + +const base: SecretProtectionStatus = { + keySource: "passphrase", + availability: "available", + remembered: false, + rememberedAvailable: true, + fileEntries: [], + sessionUnlocked: false, +} + +describe("protection presentation state", () => { + it.each([ + [ + { + keySource: "", + availability: "unknown", + reasonCode: "file_store_uninitialized", + }, + "uninitialized", + ], + [{ keySource: "file" }, "automatic_available"], + [{ keySource: "keyring" }, "automatic_available"], + [{ availability: "locked" }, "passphrase_locked"], + [{ sessionUnlocked: true }, "passphrase_available"], + [{ remembered: true }, "passphrase_available"], + [ + { rememberedAvailable: false, availability: "backend_unavailable" }, + "backend_unavailable", + ], + [ + { availability: "missing", reasonCode: "file_store_missing" }, + "file_store_missing", + ], + [{ availability: "unknown", reasonCode: "store_corrupt" }, "store_corrupt"], + [{ reasonCode: "ownership_unknown" }, "ownership_unknown"], + [{ keySource: "future" }, "unknown"], + [{ availability: "unknown" }, "unknown"], + ])("maps %j to %s", (override, expected) => { + expect( + getSecretProtectionViewState({ + ...base, + ...override, + } as SecretProtectionStatus), + ).toBe(expected) + }) + it("does not confuse an inaccessible remembered service with unavailable values", () => { + expect( + getSecretProtectionViewState({ + ...base, + rememberedAvailable: false, + sessionUnlocked: true, + }), + ).toBe("passphrase_available") + }) + it("does not infer value access from stale session or remembered flags", () => { + expect( + getSecretProtectionViewState({ + ...base, + availability: "locked", + remembered: true, + sessionUnlocked: true, + }), + ).toBe("passphrase_locked") + }) + it("labels automatic modes using the exact Go source", () => { + expect(secretProtectionModeLabel({ ...base, keySource: "keyring" })).toBe( + "Automatic key", + ) + expect(secretProtectionModeLabel({ ...base, keySource: "file" })).toBe( + "Automatic key", + ) + expect(secretProtectionModeLabel(null)).toBe("Unknown") + expect(secretProtectionStateLabel("passphrase_locked")).toBe("Locked") + }) + it("handles unloaded status", () => + expect(getSecretProtectionViewState(null)).toBe("unknown")) + it("uses both row dimensions without separator collisions", () => { + expect(variableIdentity("a:b", "c")).not.toBe(variableIdentity("a", "b:c")) + expect(variableIdentity("a", "TOKEN")).not.toBe( + variableIdentity("b", "TOKEN"), + ) + }) +}) diff --git a/desktop/src/renderer/src/lib/variables/secret-protection-state.ts b/desktop/src/renderer/src/lib/variables/secret-protection-state.ts new file mode 100644 index 0000000000..9d1a041169 --- /dev/null +++ b/desktop/src/renderer/src/lib/variables/secret-protection-state.ts @@ -0,0 +1,81 @@ +import type { SecretProtectionStatus } from "$lib/types/index.js" + +export type SecretProtectionViewState = + | "uninitialized" + | "automatic_available" + | "passphrase_available" + | "passphrase_locked" + | "file_store_missing" + | "backend_unavailable" + | "store_corrupt" + | "ownership_unknown" + | "unknown" + +export function getSecretProtectionViewState( + status: SecretProtectionStatus | null, +): SecretProtectionViewState { + if (!status) return "unknown" + switch (status.reasonCode) { + case "ownership_unknown": + return "ownership_unknown" + case "store_corrupt": + return "store_corrupt" + case "file_store_missing": + return "file_store_missing" + case "file_store_uninitialized": + return "uninitialized" + } + if (status.availability === "missing") return "file_store_missing" + if (status.availability === "backend_unavailable") + return "backend_unavailable" + if (status.keySource === "passphrase") { + if (status.availability === "locked") return "passphrase_locked" + if (status.availability === "available") return "passphrase_available" + } + if ( + (status.keySource === "keyring" || status.keySource === "file") && + status.availability === "available" + ) + return "automatic_available" + return "unknown" +} + +export function secretProtectionStateLabel( + state: SecretProtectionViewState, +): string { + switch (state) { + case "uninitialized": + return "Not initialized" + case "automatic_available": + case "passphrase_available": + return "Available" + case "passphrase_locked": + return "Locked" + case "file_store_missing": + return "Missing secret store" + case "backend_unavailable": + return "Unavailable" + case "store_corrupt": + return "Unreadable secret store" + case "ownership_unknown": + return "Needs attention" + case "unknown": + return "Unknown" + } +} + +export function secretProtectionModeLabel( + status: SecretProtectionStatus | null, +): string { + switch (status?.keySource) { + case "passphrase": + return "Passphrase" + case "keyring": + case "file": + return "Automatic key" + case "": + return "Not initialized" + default: + return "Unknown" + } +} diff --git a/desktop/src/renderer/src/pages/EnvPage.svelte b/desktop/src/renderer/src/pages/EnvPage.svelte index 186aba0610..6e62543f93 100644 --- a/desktop/src/renderer/src/pages/EnvPage.svelte +++ b/desktop/src/renderer/src/pages/EnvPage.svelte @@ -1,272 +1,8 @@ - -
-
-

Environment Variables

- - - {#snippet child({ props })} - - {/snippet} - - - - - {nameExists ? "Update Environment Variable" : "Add Environment Variable"} - - - Stored in plaintext in your current Devsy context. Enable "Inject into workspaces" to add it automatically when workspaces start. - - -
{ e.preventDefault(); handleCreate() }} class="space-y-4"> -
- - (newName = e.currentTarget.value)} - disabled={saving} - /> - {#if newName && !nameValid} -

- Only letters, digits, and underscores are allowed. -

- {:else if nameExists} -

- "{newName.trim()}" already exists. Saving will update its value. -

- {/if} -
-
- - (newValue = e.currentTarget.value)} - disabled={saving} - /> -
- - - - -
-
-
-
- - {#if $envLoading} -
- {#each Array(2) as _} - - {/each} -
- {:else if $envVars.length === 0} -
- -

No environment variables stored.

-
- {:else} -
- - (searchTerm = e.currentTarget.value)} - /> -
- {#if filteredEnvVars.length === 0} -
- -

No environment variables matching "{searchTerm}"

-
- {:else} -
- {#each filteredEnvVars as envVar (`${envVar.context}\x00${envVar.name}`)} -
-
-
- -

{envVar.name}

-
-
- - -
-
-

- {revealed[envVar.name] ? envVar.value : "••••••••"} -

-
-
-

Inject into workspaces

-

Context: {envVar.context}. Applies when a workspace starts or is recreated.

-
- setAttached(envVar, checked)} - /> -
- {#if attachmentErrors[`${envVar.context}\x00${envVar.name}`]} -

- Failed to update attachment: {attachmentErrors[`${envVar.context}\x00${envVar.name}`]} -

- {/if} -
- {/each} -
- {/if} - {/if} -
- - diff --git a/desktop/src/renderer/src/pages/EnvPage.test.ts b/desktop/src/renderer/src/pages/EnvPage.test.ts deleted file mode 100644 index b7e2b12633..0000000000 --- a/desktop/src/renderer/src/pages/EnvPage.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { - cleanup, - fireEvent, - render, - screen, - waitFor, -} from "@testing-library/svelte" -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" - -const mocks = vi.hoisted(() => ({ - envAttach: vi.fn().mockResolvedValue(undefined), - envDetach: vi.fn().mockResolvedValue(undefined), - envDelete: vi.fn().mockResolvedValue(undefined), - refreshEnv: vi.fn().mockResolvedValue(undefined), -})) -vi.mock("$lib/ipc/commands.js", () => ({ - envAttach: mocks.envAttach, - envDelete: mocks.envDelete, - envDetach: mocks.envDetach, - envSet: vi.fn(), -})) -vi.mock("$lib/stores/env.js", async () => { - const { writable } = await import("svelte/store") - return { - envLoading: writable(false), - envVars: writable([ - { name: "ATTACHED", value: "one", context: "default", attached: true }, - { name: "DETACHED", value: "two", context: "default", attached: false }, - { - name: "STAGING_ONLY", - value: "three", - context: "staging", - attached: false, - }, - ]), - refreshEnv: mocks.refreshEnv, - } -}) - -import EnvPage from "./EnvPage.svelte" - -describe("EnvPage managed environment attachments", () => { - beforeEach(() => { - vi.clearAllMocks() - }) - afterEach(() => { - cleanup() - }) - - it("renders attachment state and sends attach/detach intent", async () => { - render(EnvPage) - - expect( - screen - .getByRole("switch", { name: "Inject ATTACHED into workspaces" }) - .getAttribute("aria-checked"), - ).toBe("true") - const detached = screen.getByRole("switch", { - name: "Inject DETACHED into workspaces", - }) - expect(detached.getAttribute("aria-checked")).toBe("false") - - await fireEvent.click(detached) - await waitFor(() => - expect(mocks.envAttach).toHaveBeenCalledWith("DETACHED", "default"), - ) - expect(mocks.refreshEnv).toHaveBeenCalled() - - await fireEvent.click( - screen.getByRole("switch", { name: "Inject ATTACHED into workspaces" }), - ) - await waitFor(() => - expect(mocks.envDetach).toHaveBeenCalledWith("ATTACHED", "default"), - ) - }) - - it("uses the context displayed on a stale row", async () => { - render(EnvPage) - - await fireEvent.click( - screen.getByRole("switch", { - name: "Inject STAGING_ONLY into workspaces", - }), - ) - await waitFor(() => - expect(mocks.envAttach).toHaveBeenCalledWith("STAGING_ONLY", "staging"), - ) - }) - - it("deletes using the context displayed on a stale row", async () => { - render(EnvPage) - - await fireEvent.click( - screen.getByRole("button", { - name: "Delete environment variable STAGING_ONLY", - }), - ) - await fireEvent.click(screen.getByRole("button", { name: /^Delete$/ })) - - await waitFor(() => - expect(mocks.envDelete).toHaveBeenCalledWith("STAGING_ONLY", "staging"), - ) - }) -}) diff --git a/desktop/src/renderer/src/pages/SecretsPage.svelte b/desktop/src/renderer/src/pages/SecretsPage.svelte index f8bed55e23..e290ef7a5a 100644 --- a/desktop/src/renderer/src/pages/SecretsPage.svelte +++ b/desktop/src/renderer/src/pages/SecretsPage.svelte @@ -1,285 +1,8 @@ - -
-
-

Secrets

- - - {#snippet child({ props })} - - {/snippet} - - - - {nameExists ? "Replace Secret" : "Add Secret"} - - Stored securely in your configured Devsy secrets backend and injected into workspaces on demand. - - -
{ e.preventDefault(); handleCreate() }} class="space-y-4"> -
- - (newName = e.currentTarget.value)} - disabled={saving} - /> - {#if newName && !nameValid} -

- Only letters, digits, and underscores are allowed. -

- {:else if nameExists} -

- A secret named "{newName.trim()}" already exists. Saving will - replace its value. This cannot be undone. -

- {/if} -
-
- - (newValue = e.currentTarget.value)} - disabled={saving} - /> -
- - - - -
-
-
-
- - {#if $secretsLoading} -
- {#each Array(2) as _} - - {/each} -
- {:else if $secretsError} -
- Unable to load secrets: {$secretsError} -
- {:else if $secrets.length === 0} -
- -

No secrets stored.

-
- {:else} - {#if lockedSecretCount > 0} -
- {lockedSecretCount === 1 ? "One secret value is locked" : `${lockedSecretCount} secret values are locked`}. Secret names, contexts, and attachment settings are still available. Unlock the configured secrets backend to use these values in workspaces. -
- {/if} -
- - (searchTerm = e.currentTarget.value)} - /> -
- {#if filteredSecrets.length === 0} -
- -

No secrets matching "{searchTerm}"

-
- {:else} -
- {#each filteredSecrets as secret (`${secret.context}\x00${secret.name}`)} -
-
-
- -

{secret.name}

-
-
- {#if secret.availability === "locked"} - Locked - {:else if secret.availability === "missing" || (secret.availability === undefined && secret.orphaned)} - Missing value - {:else if secret.availability === "backend_unavailable"} - Backend unavailable - {:else if secret.availability === "unknown"} - Availability unknown - {/if} - -
-
-
-
-

Inject into workspaces

-

Context: {secret.context}. Available to lifecycle commands and new Devsy terminal/SSH sessions after workspace setup or recreation.

-
- {#key attachmentResets[`${secret.context}\x00${secret.name}`] ?? 0} - setAttached(secret, checked)} - /> - {/key} -
- {#if attachmentErrors[`${secret.context}\x00${secret.name}`]} -

- Failed to update attachment: {attachmentErrors[`${secret.context}\x00${secret.name}`]} -

- {/if} -
- {/each} -
- {/if} - {/if} -
- - diff --git a/desktop/src/renderer/src/pages/SettingsPage.svelte b/desktop/src/renderer/src/pages/SettingsPage.svelte index edb9682f8f..3d323bf329 100644 --- a/desktop/src/renderer/src/pages/SettingsPage.svelte +++ b/desktop/src/renderer/src/pages/SettingsPage.svelte @@ -1,5 +1,15 @@ + +
+
+
+

Workspace Variables

+

Manage secrets and non-sensitive configuration used by your workspaces.

+
+ +
+ + + + Secrets + Environment Variables + + + (securityOpen = true)} /> + (securityOpen = true)} /> + + + + + + +
diff --git a/desktop/src/renderer/src/pages/VariablesPage.test.ts b/desktop/src/renderer/src/pages/VariablesPage.test.ts new file mode 100644 index 0000000000..3767af8c15 --- /dev/null +++ b/desktop/src/renderer/src/pages/VariablesPage.test.ts @@ -0,0 +1,89 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/svelte" +import { get, writable } from "svelte/store" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +const { refreshProtection, replace } = vi.hoisted(() => ({ + refreshProtection: vi.fn(async () => {}), + replace: vi.fn(async (_path: string) => {}), +})) +vi.mock("$lib/router.js", () => ({ querystring: writable(""), replace })) +vi.mock("$lib/stores/secret-protection.js", () => ({ + initSecretProtection: refreshProtection, +})) +vi.mock("$lib/components/variables/SecretsVariablesPanel.svelte", () => ({ + default: vi.fn(), +})) +vi.mock("$lib/components/variables/EnvironmentVariablesPanel.svelte", () => ({ + default: vi.fn(), +})) +vi.mock("$lib/components/variables/SecretSecurityBanner.svelte", () => ({ + default: vi.fn(), +})) +vi.mock("$lib/components/variables/SecretSecuritySheet.svelte", () => ({ + default: vi.fn(), +})) + +import { querystring } from "$lib/router.js" +import VariablesPage from "./VariablesPage.svelte" + +const query = querystring as ReturnType> + +describe("Workspace Variables navigation", () => { + beforeEach(() => { + vi.clearAllMocks() + query.set("") + replace.mockImplementation(async (path) => + query.set(path.split("?")[1] ?? ""), + ) + }) + afterEach(cleanup) + + it.each(["", "tab=invalid"])( + "defaults to Secrets for query %s", + async (qs) => { + query.set(qs) + render(VariablesPage) + expect( + screen.getByRole("heading", { name: "Workspace Variables" }), + ).toBeTruthy() + expect(screen.getByRole("button", { name: "Add secret" })).toBeTruthy() + expect( + screen + .getByRole("tab", { name: "Secrets" }) + .getAttribute("aria-selected"), + ).toBe("true") + await vi.waitFor(() => expect(refreshProtection).toHaveBeenCalledOnce()) + }, + ) + + it("honors the environment deep link and shows only its primary action", () => { + query.set("tab=env") + render(VariablesPage) + expect(screen.getByRole("button", { name: "Add variable" })).toBeTruthy() + expect(screen.queryByRole("button", { name: "Add secret" })).toBeNull() + expect( + screen + .getByRole("tab", { name: "Environment Variables" }) + .getAttribute("aria-selected"), + ).toBe("true") + expect(refreshProtection).not.toHaveBeenCalled() + }) + + it("updates the URL on tab selection and responds to history query changes", async () => { + render(VariablesPage) + await fireEvent.click( + screen.getByRole("tab", { name: "Environment Variables" }), + ) + await vi.waitFor(() => + expect(replace).toHaveBeenCalledWith("/variables?tab=env"), + ) + expect(get(query)).toBe("tab=env") + await vi.waitFor(() => + expect(screen.getByRole("button", { name: "Add variable" })).toBeTruthy(), + ) + query.set("tab=secrets") + await vi.waitFor(() => + expect(screen.getByRole("button", { name: "Add secret" })).toBeTruthy(), + ) + }) +}) diff --git a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/secrets.mdx b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/secrets.mdx index 83bc1eab58..0a833ae0f7 100644 --- a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/secrets.mdx +++ b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/secrets.mdx @@ -60,6 +60,29 @@ backend is locked. Its availability status is separate from the backend that owns the value. Operations that need plaintext, including `get` and workspace startup, still fail when a required value cannot be read. +### Managing Variables in Desktop + +Open **Workspace Variables** to manage configuration in two tabs: +**Secrets** and **Environment Variables**. Each table shows the name, context, +and workspace injection setting. Secret rows also show their storage backend +and availability. Secret values are never displayed. + +Use **Add secret** or **Add variable** to create an entry. To change an existing +entry, open its details and choose **Replace secret value** for a secret or edit +the environment value. Names are scoped to a context, so the same name in another +context is a separate entry. Desktop checks for existing names when adding; +the CLI `set` commands continue to create or update values. + +Locked secrets remain visible, and you can change their **Inject into +workspaces** setting without unlocking. This changes the context attachment, +not the stored value. Reading, replacing, or deleting file-backed values can +still require unlocking. A locked file store does not prevent access to +available keyring-backed secrets or managed environment variables. + +Environment values are masked by default in Desktop and can be revealed for +an individual row. Masking only hides the display: environment variables are +stored in plaintext and are intended for non-sensitive configuration. + ## External Secret Sources An external secret source lets Devsy resolve a value at workspace startup @@ -270,8 +293,8 @@ devsy secret detach sops:project/API_TOKEN ``` Attachments are context-scoped and contain only the secret reference, never -the value. The Desktop Secrets page shows and changes the same attachment -state. Devsy resolves an attached secret on `workspace up`, makes it available +the value. The Desktop Workspace Variables **Secrets** tab shows and changes +the same attachment state. Devsy resolves an attached secret on `workspace up`, makes it available to lifecycle commands, and supplies it to each new Devsy-managed SSH session and its child processes. This includes `devsy workspace ssh` and the Desktop workspace terminal. It does not set a global container environment variable @@ -412,22 +435,33 @@ devsy secret protection remove-passphrase `status` reports the file store's protection mode and availability, including whether a remembered credential is available. -In Desktop Settings, changing file-store protection or its remembered -credential requires confirmation in a native application dialog. Canceling +In Desktop, open **Manage security** from the **Secrets** tab or the compact +**Secret Security** section in Settings. The security sheet shows the file +store's protection and availability and whether a credential is remembered on +this device. Protection applies to file-backed secrets across all contexts. + +Changing file-store protection or its remembered credential requires +confirmation in a native application dialog. Canceling the dialog leaves protection and the remembered credential unchanged. Choosing to remember a passphrase while unlocking also requires native confirmation and an active unlock request. -**Clear session credential** removes the Desktop's cached passphrase. An -approved protection change already running may finish, but it will not restore +Use **Remember on this device** to save a verified passphrase in the operating +system credential store. **Forget this device** removes that saved credential; +it does not change file-store protection or delete secrets. A passphrase +already cached by the running Desktop application may still provide access. + +The advanced **Clear session passphrase** action removes the Desktop's +in-memory passphrase. Other available credentials may still unlock the store. An approved protection change already running +may finish, but it will not restore the cleared session credential. Remembered OS-keychain credentials remain -until you choose **Forget**. +until you choose **Forget this device**. While an unlock submission is running, another credential submission for that request is rejected. You can still cancel unlocking. If an approved Remember action then succeeds, Desktop reports that the credential was saved even though unlocking was canceled. The main process retains this notice across a page -reload until Desktop displays and acknowledges it. Use **Forget** in Settings +reload until Desktop displays and acknowledges it. Use **Forget this device** to remove the credential. Passphrase protection applies to all values in the file backend. It is not a @@ -457,8 +491,15 @@ devsy secret protection forget `remember` verifies the current passphrase before saving it. `forget` removes only the remembered credential; it does not change encryption or delete -secrets. If the passphrase is lost, the encrypted file store cannot be -recovered. Reset the complete file-backed store with explicit confirmation: +secrets. + +In Desktop, **Recovery options** explains how to restore access and provides +the reset command to copy. A remembered device credential may still unlock +the store if you have forgotten the passphrase. Without a valid credential, +the encrypted file contents cannot be decrypted. Resetting removes every +file-backed secret entry across all contexts; use it only after reviewing the +recovery options. Reset the complete file-backed store from the CLI with +explicit confirmation: ```shell devsy secret protection reset-file-store @@ -509,8 +550,9 @@ devsy env detach LOG_LEVEL ``` Attachments are context-scoped and contain only the variable name. The Desktop -Environment Variables page shows and changes the same attachment state. Managed -environment variables are non-sensitive plaintext values; use `devsy secret` +Workspace Variables **Environment Variables** tab shows and changes the same +attachment state. Managed environment variables are non-sensitive plaintext +values; use `devsy secret` for secrets. An explicit `devsy workspace up --env LOG_LEVEL` still works for one invocation. @@ -535,4 +577,4 @@ entry. Conversion does not provide crash-atomic recovery across the two stores. Sensitive values use `devsy secret attach` instead; attached secrets are injected through the protected secret-delivery paths described above, and the -Desktop Secrets page manages their attachment state. +Desktop Workspace Variables **Secrets** tab manages their attachment state.