🙌 OpenHands: AI-Driven Development
feat: allow overwriting a secret value from the edit form (#16134)
Hiep Le5c1b1811f83d
diff --git a/__tests__/api/cloud/secrets-service.test.ts b/__tests__/api/cloud/secrets-service.test.tsindex f609672293..f7fc66b37d 100644--- a/__tests__/api/cloud/secrets-service.test.ts+++ b/__tests__/api/cloud/secrets-service.test.ts@@ -113,6 +113,35 @@ describe("SecretsService against cloud backend", () => {name: "NEW_NAME",description: "renamed",});+ // No value supplied, so nothing overwrites the stored one.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("overwrites the value with a POST following the PUT", async () => {+ // Fresh Response per call: a Response body can only be consumed once.+ fetchMock.mockImplementation(() => Promise.resolve(mockJsonResponse({})));++ await SecretsService.updateSecret(+ "API_KEY",+ "API_KEY",+ "Demo secret",+ "new-value",+ );++ expect(fetchMock).toHaveBeenCalledTimes(2);++ const [putUrl, putInit] = getFetchCall(fetchMock, 0);+ expect(putUrl).toBe(`${cloudBackend.host}/api/v1/secrets/API_KEY`);+ expect(putInit).toMatchObject({ method: "PUT" });++ const [postUrl, postInit] = getFetchCall(fetchMock, 1);+ expect(postUrl).toBe(`${cloudBackend.host}/api/v1/secrets`);+ expect(postInit).toMatchObject({ method: "POST" });+ expect(getJsonBody(postInit)).toEqual({+ name: "API_KEY",+ value: "new-value",+ description: "Demo secret",+ });});it("deletes a secret via direct DELETE /api/v1/secrets/{id}", async () => {diff --git a/__tests__/api/secrets-service.test.ts b/__tests__/api/secrets-service.test.tsindex 3c4fc30ebf..9dbadbed59 100644--- a/__tests__/api/secrets-service.test.ts+++ b/__tests__/api/secrets-service.test.ts@@ -76,6 +76,30 @@ describe("SecretsService", () => {expect(mockDeleteSecret).not.toHaveBeenCalled();});+ it("overwrites the value without reading the existing one", async () => {+ // Arrange+ mockUpsertSecret.mockResolvedValue({+ name: "OpenAI_API_Key",+ description: "Demo secret",+ });++ // Act+ await SecretsService.updateSecret(+ "OpenAI_API_Key",+ "OpenAI_API_Key",+ "Demo secret",+ "new-value",+ );++ // Assert+ expect(mockGetSecret).not.toHaveBeenCalled();+ expect(mockUpsertSecret).toHaveBeenCalledWith({+ name: "OpenAI_API_Key",+ value: "new-value",+ description: "Demo secret",+ });+ });+it("renames secrets by re-upserting and removing the old entry", async () => {// ArrangemockGetSecret.mockResolvedValue("original-value");diff --git a/__tests__/components/features/settings/secrets-settings/secret-form.test.tsx b/__tests__/components/features/settings/secrets-settings/secret-form.test.tsxnew file mode 100644index 0000000000..c95b85bdb0--- /dev/null+++ b/__tests__/components/features/settings/secrets-settings/secret-form.test.tsx@@ -0,0 +1,80 @@+import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SecretsService } from "#/api/secrets-service";+import { SecretForm } from "#/components/features/settings/secrets-settings/secret-form";+import { renderWithProviders } from "../../../../../test-utils";++const renderEditForm = async () => {+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([+ { name: "API_KEY", description: "Demo secret" },+ ]);+ const updateSecret = vi+ .spyOn(SecretsService, "updateSecret")+ .mockResolvedValue(undefined);++ renderWithProviders(+ <SecretForm mode="edit" selectedSecret="API_KEY" onCancel={vi.fn()} />,+ );++ // The description default is applied once the secrets query settles.+ await waitFor(() =>+ expect(screen.getByTestId("description-input")).toHaveValue("Demo secret"),+ );++ return { updateSecret };+};++describe("SecretForm in edit mode", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ it("offers a blank value field labelled for preserving the existing value", async () => {+ // Arrange & Act+ await renderEditForm();++ // Assert+ expect(screen.getByTestId("value-input")).toHaveValue("");+ expect(+ screen.getByText("SECRETS$SECRET_VALUE_LEAVE_BLANK"),+ ).toBeInTheDocument();+ });++ it("keeps the stored value when the value field is left blank", async () => {+ // Arrange+ const { updateSecret } = await renderEditForm();++ // Act+ await userEvent.click(screen.getByTestId("submit-button"));++ // Assert+ await waitFor(() =>+ expect(updateSecret).toHaveBeenCalledWith(+ "API_KEY",+ "API_KEY",+ "Demo secret",+ undefined,+ ),+ );+ });++ it("overwrites the stored value with the one entered", async () => {+ // Arrange+ const { updateSecret } = await renderEditForm();++ // Act+ await userEvent.type(screen.getByTestId("value-input"), "sk-new-value");+ await userEvent.click(screen.getByTestId("submit-button"));++ // Assert+ await waitFor(() =>+ expect(updateSecret).toHaveBeenCalledWith(+ "API_KEY",+ "API_KEY",+ "Demo secret",+ "sk-new-value",+ ),+ );+ });+});diff --git a/src/api/cloud/secrets-service.api.ts b/src/api/cloud/secrets-service.api.tsindex b95ebe596a..89703ebc83 100644--- a/src/api/cloud/secrets-service.api.ts+++ b/src/api/cloud/secrets-service.api.ts@@ -1,6 +1,7 @@import { getActiveBackend } from "../backend-registry/active-store";import type { Backend } from "../backend-registry/types";import type { CustomSecretWithoutValue } from "../secrets-service.types";+import { withRetry } from "../with-retry";import { callCloudProxy } from "./proxy";interface CloudSecretsPage {@@ -46,37 +47,65 @@ export async function fetchCloudSecrets(): Promise<CustomSecretWithoutValue[]> {return secrets;}-export async function createCloudSecret(- name: string,- value: string,- description?: string,-): Promise<void> {- const backend = getActiveCloudBackend();- await callCloudProxy<unknown>({- backend,- method: "POST",- path: "/api/v1/secrets",- body: { name, value, description },- });+export interface SaveCloudSecretOptions {+ /** Name the secret should have after saving. */+ name: string;+ /** New value. Omit to leave the stored value untouched. */+ value?: string;+ description?: string;+ /** Name the secret is currently stored under, when editing an existing one. */+ previousName?: string;}/**- * Rename and/or redescribe an existing cloud secret. The cloud `PUT` endpoint- * does not accept a value field — it only updates name + description — which- * matches what `useUpdateSecret` actually sends from the secret-edit form.+ * Create a cloud secret, or save changes to an existing one.+ *+ * The cloud splits a save across two endpoints, so this issues up to two+ * requests to cover the whole operation:+ *+ * - `PUT /api/v1/secrets/{previousName}` applies the name and description. It+ * is the only endpoint that can rename, and the only one that rejects a+ * collision with `400`. It never touches the value.+ * - `POST /api/v1/secrets` writes the value. It is a documented upsert+ * ("creates a new custom secret, or overwrites it if it already exists") but+ * it is keyed by the name in its body, so it cannot rename, and its `value`+ * field is required, so it cannot express a metadata-only edit.+ *+ * The `PUT` runs first so a rejected rename fails before the value is+ * overwritten — the cloud exposes no way to read a value back, so a value lost+ * to a half-applied save is unrecoverable. Each request is retried on its own:+ * re-running the `PUT` after a failed `POST` would `404` once the rename has+ * landed.*/-export async function updateCloudSecret(- secretToEdit: string,- name: string,- description?: string,-): Promise<void> {+export async function saveCloudSecret({+ name,+ value,+ description,+ previousName,+}: SaveCloudSecretOptions): Promise<void> {const backend = getActiveCloudBackend();- await callCloudProxy<unknown>({- backend,- method: "PUT",- path: `/api/v1/secrets/${encodeURIComponent(secretToEdit)}`,- body: { name, description },- });++ if (previousName !== undefined) {+ await withRetry(() =>+ callCloudProxy<unknown>({+ backend,+ method: "PUT",+ path: `/api/v1/secrets/${encodeURIComponent(previousName)}`,+ body: { name, description },+ }),+ );+ }++ if (value !== undefined) {+ await withRetry(() =>+ callCloudProxy<unknown>({+ backend,+ method: "POST",+ path: "/api/v1/secrets",+ body: { name, value, description },+ }),+ );+ }}export async function deleteCloudSecret(name: string): Promise<void> {diff --git a/src/api/secrets-service.ts b/src/api/secrets-service.tsindex e3a5d1d8e7..accb2f0dcc 100644--- a/src/api/secrets-service.ts+++ b/src/api/secrets-service.ts@@ -2,40 +2,13 @@ import { SettingsClient } from "@openhands/typescript-client/clients";import { isSdkHttpStatusError } from "./agent-server-compatibility";import { getActiveBackend } from "./backend-registry/active-store";import {- createCloudSecret,deleteCloudSecret,fetchCloudSecrets,- updateCloudSecret,+ saveCloudSecret,} from "./cloud/secrets-service.api";import { getAgentServerClientOptions } from "./agent-server-client-options";import { CustomSecretWithoutValue } from "./secrets-service.types";--/**- * Retry helper for API calls with exponential backoff.- */-async function withRetry<T>(- fn: () => Promise<T>,- maxRetries: number = 3,- baseDelayMs: number = 500,-): Promise<T> {- for (let attempt = 0; attempt < maxRetries; attempt += 1) {- try {- return await fn();- } catch (error) {- if (attempt >= maxRetries - 1) {- throw error;- }-- const delay = baseDelayMs * 2 ** attempt;-- await new Promise<void>((resolve) => {- setTimeout(resolve, delay);- });- }- }-- throw new Error("Retry attempts exhausted");-}+import { withRetry } from "./with-retry";export class SecretsService {/**@@ -78,7 +51,7 @@ export class SecretsService {description?: string,): Promise<void> {if (getActiveBackend().backend.kind === "cloud") {- await withRetry(() => createCloudSecret(name, value, description));+ await saveCloudSecret({ name, value, description });return;}await withRetry(() =>@@ -91,32 +64,41 @@ export class SecretsService {}/**- * Update a secret's name and/or description while preserving its value.- * The agent-server only exposes an upsert endpoint, so we fetch the- * existing value and re-upsert it under the updated name/description.+ * Update a secret's name and/or description, and optionally overwrite its+ * value. When no value is given the existing one is preserved: the+ * agent-server only exposes an upsert endpoint, so we fetch the existing+ * value and re-upsert it under the updated name/description.** @param secretToEdit - Existing secret name* @param name - New (or same) secret name* @param description - Optional new description+ * @param value - Optional new value; when omitted the stored value is kept* @throws Error if the API call fails after retries*/static async updateSecret(secretToEdit: string,name: string,description?: string,+ value?: string,): Promise<void> {if (getActiveBackend().backend.kind === "cloud") {- await withRetry(() => updateCloudSecret(secretToEdit, name, description));+ await saveCloudSecret({+ name,+ value,+ description,+ previousName: secretToEdit,+ });return;}const client = new SettingsClient(getAgentServerClientOptions());- const value = await withRetry(() => client.getSecret(secretToEdit));+ const nextValue =+ value ?? (await withRetry(() => client.getSecret(secretToEdit)));await withRetry(() =>client.upsertSecret({name,- value,+ value: nextValue,description,}),);diff --git a/src/api/with-retry.ts b/src/api/with-retry.tsnew file mode 100644index 0000000000..d22f104664--- /dev/null+++ b/src/api/with-retry.ts@@ -0,0 +1,26 @@+/**+ * Retry helper for API calls with exponential backoff.+ */+export async function withRetry<T>(+ fn: () => Promise<T>,+ maxRetries: number = 3,+ baseDelayMs: number = 500,+): Promise<T> {+ for (let attempt = 0; attempt < maxRetries; attempt += 1) {+ try {+ return await fn();+ } catch (error) {+ if (attempt >= maxRetries - 1) {+ throw error;+ }++ const delay = baseDelayMs * 2 ** attempt;++ await new Promise<void>((resolve) => {+ setTimeout(resolve, delay);+ });+ }+ }++ throw new Error("Retry attempts exhausted");+}diff --git a/src/components/features/settings/secrets-settings/secret-form.tsx b/src/components/features/settings/secrets-settings/secret-form.tsxindex 8ab5352f27..9371339bb5 100644--- a/src/components/features/settings/secrets-settings/secret-form.tsx+++ b/src/components/features/settings/secrets-settings/secret-form.tsx@@ -69,9 +69,10 @@ export function SecretForm({secretToEdit: string,name: string,description?: string,+ value?: string,) => {updateSecret(- { secretToEdit, name, description },+ { secretToEdit, name, description, value },{onSettled: onCancel,onSuccess: invalidateSecrets,@@ -106,7 +107,12 @@ export function SecretForm({handleCreateSecret(name, value, description || undefined);} else if (mode === "edit" && selectedSecret) {- handleEditSecret(selectedSecret, name, description || undefined);+ handleEditSecret(+ selectedSecret,+ name,+ description || undefined,+ value || undefined,+ );}}};@@ -133,23 +139,25 @@ export function SecretForm({/>{error && <p className="text-red-500 text-sm">{error}</p>}- {mode === "add" && (- <label className="flex flex-col gap-2.5 w-full min-w-0">- <span className="text-sm">{t(I18nKey.FORM$VALUE)}</span>- <textarea- data-testid="value-input"- name="secret-value"- required- className={cn(- "resize-none",- formControlMultilineFieldClassName,- "placeholder:italic",- "disabled:bg-[var(--oh-surface-raised)] disabled:border-[var(--oh-border-subtle)] disabled:cursor-not-allowed",- )}- rows={8}- />- </label>- )}+ <label className="flex flex-col gap-2.5 w-full min-w-0">+ <span className="text-sm">+ {mode === "add"+ ? t(I18nKey.FORM$VALUE)+ : t(I18nKey.SECRETS$SECRET_VALUE_LEAVE_BLANK)}+ </span>+ <textarea+ data-testid="value-input"+ name="secret-value"+ required={mode === "add"}+ className={cn(+ "resize-none",+ formControlMultilineFieldClassName,+ "placeholder:italic",+ "disabled:bg-[var(--oh-surface-raised)] disabled:border-[var(--oh-border-subtle)] disabled:cursor-not-allowed",+ )}+ rows={8}+ />+ </label><label className="flex flex-col gap-2.5 w-full min-w-0"><div className="flex items-center gap-2">diff --git a/src/hooks/mutation/use-update-secret.ts b/src/hooks/mutation/use-update-secret.tsindex d63eee4a1b..09ec7f367a 100644--- a/src/hooks/mutation/use-update-secret.ts+++ b/src/hooks/mutation/use-update-secret.ts@@ -7,9 +7,11 @@ export const useUpdateSecret = () =>secretToEdit,name,description,+ value,}: {secretToEdit: string;name: string;description?: string;- }) => SecretsService.updateSecret(secretToEdit, name, description),+ value?: string;+ }) => SecretsService.updateSecret(secretToEdit, name, description, value),});diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 54d3655ce5..a430c8707e 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -1291,6 +1291,23 @@"uk": "Значення секрету є обов'язковим","ca": "El valor del secret és obligatori"},+ "SECRETS$SECRET_VALUE_LEAVE_BLANK": {+ "en": "Secret Value (leave blank to preserve the existing value)",+ "ja": "シークレット値(空欄のままにすると既存の値が保持されます)",+ "zh-CN": "密钥值(留空以保留现有值)",+ "zh-TW": "密鑰值(留空以保留現有值)",+ "ko-KR": "비밀 값 (비워 두면 기존 값이 유지됩니다)",+ "no": "Hemmelig verdi (la stå tom for å beholde eksisterende verdi)",+ "it": "Valore del segreto (lascia vuoto per mantenere il valore esistente)",+ "pt": "Valor do segredo (deixe em branco para manter o valor existente)",+ "es": "Valor del secreto (déjalo en blanco para mantener el valor existente)",+ "ar": "قيمة السر (اتركه فارغًا للإبقاء على القيمة الحالية)",+ "fr": "Valeur du secret (laissez vide pour conserver la valeur existante)",+ "tr": "Gizli Değer (mevcut değeri korumak için boş bırakın)",+ "de": "Geheimer Wert (leer lassen, um den vorhandenen Wert beizubehalten)",+ "uk": "Значення секрету (залиште порожнім, щоб зберегти наявне значення)",+ "ca": "Valor del secret (deixa-ho en blanc per mantenir el valor existent)"+ },"SECRETS$ADD_SECRET": {"en": "Add secret","ja": "シークレットを追加",