Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Allow existing API tokens to be renamed

[email protected]1d0a0b7f7ea1
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 0b362657c2..23a61ce224 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,10 @@
## Purpose
+API-token names are operator-facing metadata, not agent identity. Renaming an
+existing token must preserve its ID, secret hash, scopes, expiry, and connected
+agent sessions, so lifecycle continuity never depends on a display label.
+
Own unified agent installation, registration, update continuity, profile
management, and fleet control surfaces. Pulse v6 has one host-installed
infrastructure agent binary, `pulse-agent`; host, Docker / Podman,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 9b3718a831..a12427d5eb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -20,6 +20,11 @@
## Purpose
+`PATCH /api/security/tokens/{id}` supports bounded metadata updates. A nonblank
+`name` renames the record without rotating its secret or changing scopes; a
+`scopes` update retains the existing delegation checks, and omitted fields are
+left unchanged. The response returns the complete updated token record.
+
Own canonical runtime payload shapes between backend and frontend, including
the trust boundary that keeps customer-safe support diagnostics and normal
product API routes free of maintainer commercial analytics.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 96d27b6add..316c56d338 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,11 @@
## Purpose
+API-token rename is an authenticated token-management mutation: blank labels
+fail closed, successful changes are persisted and audited as `token_renamed`,
+and neither the plaintext credential nor its stored hash is exposed or
+rotated. Rename UI copy must state that connected agents remain unchanged.
+
Own Pulse's canonical privacy disclosures, outbound usage-data boundary,
and the security-facing settings surfaces that expose authentication posture,
token-management visibility, and privacy controls to operators. Customer-facing
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index f88b75cd63..6208c15425 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,11 @@
## Purpose
+Token display-name changes use the existing API-token persistence boundary.
+The in-memory record must roll back if persistence fails, while the token ID,
+secret hash, scopes, and expiry remain intact so restart and restore preserve
+both credential continuity and the latest successfully stored label.
+
Own the storage and recovery product surfaces, recovery-point persistence and
querying, and the operator-facing storage health presentation layer while
keeping adjacent commercial reporting APIs out of storage/recovery product
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 369194d50f..7f457c701f 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,20 +1,22 @@
{
"version": 1,
- "base_sha": "70469660b3e38895ff28b50d28e320e975a3e908",
- "verified_at": "2026-08-11T14:08:23Z",
+ "base_sha": "83dc17bf71368c64f63824142a1a72368c7f24ab",
+ "verified_at": "2026-08-11T14:17:19Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/api/nodes.ts",
- "frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx",
- "frontend-modern/src/components/Settings/useNodeModalState.ts"
+ "frontend-modern/src/api/security.ts",
+ "frontend-modern/src/components/Settings/APITokenManager.tsx",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx",
+ "frontend-modern/src/components/Settings/useAPITokenManagerState.ts"
],
"content_sha256": {
- "frontend-modern/src/api/nodes.ts": "1f06a674b715cfeef5cfe219e239b54df70e95a09eb2907bc31de8c01dce0012",
- "frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx": "b21eebe819132f039874415c83c99fee1337b34ebf06e73e91aaacc3181fad96",
- "frontend-modern/src/components/Settings/useNodeModalState.ts": "973d4ed2fbe5cef53f4e7853888a351b137ca1bcfa7574ff964c4efa83548eaa"
+ "frontend-modern/src/api/security.ts": "28f831a37a8b5030af96aba86654e152b4b6ecc8e795491c354c64e21acc235a",
+ "frontend-modern/src/components/Settings/APITokenManager.tsx": "c6e1490bc5f03ea22cb318eaed3c8e8aaf85f74327e9c6c3d0bcc9fd497f0a7f",
+ "frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx": "51830fa6bb09b561d0e614614abbb782dcf04c3b5c97533876e27ed9f9031939",
+ "frontend-modern/src/components/Settings/useAPITokenManagerState.ts": "685b7bf347899c221945ecd42038ebd644bba114c47b1c1d115f32abe286fde3"
},
"routes": [
- "/settings/infrastructure"
+ "/settings/security/api"
],
"viewports": [
{
@@ -27,17 +29,18 @@
}
],
"states": [
- "Proxmox VE source dialog on the API inventory strategy with the TLS override absent.",
- "Proxmox VE source dialog on Host Telemetry Agent with the TLS override visible, off by default, and then checked.",
- "Desktop dialog at 1440 by 1000 with the full control label visible, focused, and no page or modal horizontal overflow.",
- "Narrow dialog at 390 by 844 with the checked control and wrapped label reachable in the modal scroll region, no page or modal horizontal overflow, and the surrounding SSL settings unclipped.",
- "Reopened Proxmox host-agent dialog after dismissal with the TLS override reset to off."
+ "API Access with one scoped token in the compact inventory and Rename available alongside scope editing and revocation.",
+ "Rename API token dialog with the existing name selected, explanatory credential-continuity copy visible, and input autofocus confirmed.",
+ "Whitespace-only rename input with Save disabled, followed by a nonblank replacement name with Save enabled.",
+ "Desktop dialog at 1440 by 1000 with a 448-pixel centered panel and no horizontal page overflow.",
+ "Narrow dialog at 390 by 844 with a 358-pixel panel, 308-pixel input, and no page or dialog horizontal overflow.",
+ "Successful rename with the updated inventory label, unchanged Settings read scope, success notification, closed dialog, and focus restored to Rename."
],
"interactions": [
- "Opened Add infrastructure, chose Proxmox VE, and switched from the recommended API inventory path to Host Telemetry Agent.",
- "Clicked the TLS override and confirmed the native checkbox changed from unchecked to checked while retaining focus.",
- "Repeated the host-agent surface inspection at 390 by 844 pixels and scrolled the dialog to the TLS and SSL controls.",
- "Dismissed the dialog with Escape, confirmed focus returned to Add infrastructure, reopened the flow, and confirmed the override did not persist.",
- "Closed the reopened dialog with its named close button."
+ "Created one scoped token in the isolated dev runtime, dismissed the one-time credential reveal without reading or recording the token value, and opened Rename from its inventory card.",
+ "Cleared the name to whitespace and confirmed Save failed closed, then entered a nonblank replacement.",
+ "Inspected and exercised the same dialog at desktop and narrow viewports, including autofocus and overflow boundaries.",
+ "Saved the rename through the live API and confirmed the visible name changed while the token's Settings read scope remained present.",
+ "Confirmed the success notification, dialog dismissal, and focus restoration to the replacement Rename button after the inventory row re-rendered."
]
}
diff --git a/frontend-modern/src/api/__tests__/security.test.ts b/frontend-modern/src/api/__tests__/security.test.ts
index f391cb320c..52356dbfa1 100644
--- a/frontend-modern/src/api/__tests__/security.test.ts
+++ b/frontend-modern/src/api/__tests__/security.test.ts
@@ -257,4 +257,25 @@ describe('SecurityAPI', () => {
);
});
});
+
+ describe('renameToken', () => {
+ it('renames a token without rotating it', async () => {
+ const record: APITokenRecord = {
+ id: 'token/1',
+ name: 'PBS host',
+ prefix: 'pulse',
+ suffix: '1234',
+ createdAt: '',
+ };
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({ record });
+
+ const result = await SecurityAPI.renameToken('token/1', 'PBS host');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1', {
+ method: 'PATCH',
+ body: JSON.stringify({ name: 'PBS host' }),
+ });
+ expect(result).toEqual(record);
+ });
+ });
});
diff --git a/frontend-modern/src/api/security.ts b/frontend-modern/src/api/security.ts
index 922926cd76..a72132eeda 100644
--- a/frontend-modern/src/api/security.ts
+++ b/frontend-modern/src/api/security.ts
@@ -65,4 +65,15 @@ export class SecurityAPI {
method: 'DELETE',
});
}
+
+ static async renameToken(id: string, name: string): Promise<APITokenRecord> {
+ const response = await apiFetchJSON<{ record: APITokenRecord }>(
+ `/api/security/tokens/${encodeURIComponent(id)}`,
+ {
+ method: 'PATCH',
+ body: JSON.stringify({ name }),
+ },
+ );
+ return response.record;
+ }
}
diff --git a/frontend-modern/src/components/Settings/APITokenManager.tsx b/frontend-modern/src/components/Settings/APITokenManager.tsx
index 205f3bd057..3b4d25470a 100644
--- a/frontend-modern/src/components/Settings/APITokenManager.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManager.tsx
@@ -33,6 +33,8 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
const [tokenToRevoke, setTokenToRevoke] = createSignal<APITokenRecord | null>(null);
const [tokenToEdit, setTokenToEdit] = createSignal<APITokenRecord | null>(null);
const [editScopes, setEditScopes] = createSignal<string[]>([]);
+ const [tokenToRename, setTokenToRename] = createSignal<APITokenRecord | null>(null);
+ const [renameInput, setRenameInput] = createSignal('');
let dialogTrigger: HTMLButtonElement | undefined;
const {
API_SCOPE_LABELS,
@@ -52,10 +54,12 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
handleDelete,
handleGenerate,
handleUpdateScopes,
+ handleRename,
hasWildcardTokens,
hasScopeSelection,
isFullAccessSelected,
isGenerating,
+ isRenaming,
isRevealActiveForCurrentToken,
loading,
nameInput,
@@ -87,10 +91,28 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
const restoreDialogTrigger = () => {
const trigger = dialogTrigger;
+ const tokenId = trigger?.dataset.apiTokenId;
+ const action = trigger?.dataset.apiTokenAction;
dialogTrigger = undefined;
- queueMicrotask(() => {
- if (trigger?.isConnected && !trigger.disabled) trigger.focus();
- });
+ window.setTimeout(() => {
+ if (trigger?.isConnected && !trigger.disabled) {
+ trigger.focus();
+ return;
+ }
+ if (!tokenId || !action) return;
+ const replacement = Array.from(
+ document.querySelectorAll<HTMLButtonElement>(
+ 'button[data-api-token-id][data-api-token-action]',
+ ),
+ ).find(
+ (button) =>
+ button.dataset.apiTokenId === tokenId &&
+ button.dataset.apiTokenAction === action &&
+ button.offsetParent !== null &&
+ !button.disabled,
+ );
+ replacement?.focus();
+ }, 0);
};
const openScopeEditor = (token: APITokenRecord, trigger: HTMLButtonElement) => {
@@ -104,6 +126,12 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
setTokenToRevoke(token);
};
+ const openRenameDialog = (token: APITokenRecord, trigger: HTMLButtonElement) => {
+ rememberDialogTrigger(trigger);
+ setRenameInput(token.name ?? '');
+ setTokenToRename(token);
+ };
+
const closeScopeEditor = () => {
if (updatingTokenId() !== null) return;
setTokenToEdit(null);
@@ -154,6 +182,23 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
restoreDialogTrigger();
};
+ const closeRenameDialog = () => {
+ if (isRenaming()) return;
+ setTokenToRename(null);
+ setRenameInput('');
+ restoreDialogTrigger();
+ };
+
+ const renameToken = async () => {
+ const token = tokenToRename();
+ if (!token) return;
+ if (await handleRename(token, renameInput())) {
+ setTokenToRename(null);
+ setRenameInput('');
+ restoreDialogTrigger();
+ }
+ };
+
const renderTokenScopes = (token: APITokenRecord) => {
const rawScopes = effectiveScopes(token);
const scopeBadges = rawScopes.includes('*')
@@ -239,6 +284,8 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
>
<button
type="button"
+ data-api-token-id={token.id}
+ data-api-token-action="edit-scopes"
onClick={(event) => openScopeEditor(token, event.currentTarget)}
disabled={!canManage()}
class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-blue-600 transition hover:bg-blue-50 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-blue-300 dark:hover:bg-blue-900 dark:hover:text-blue-200 ${
@@ -249,6 +296,20 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
</button>
<button
type="button"
+ data-api-token-id={token.id}
+ data-api-token-action="rename"
+ onClick={(event) => openRenameDialog(token, event.currentTarget)}
+ disabled={!canManage()}
+ class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-blue-600 transition hover:bg-blue-50 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-blue-300 dark:hover:bg-blue-900 dark:hover:text-blue-200 ${
+ compact ? 'flex-1 border border-blue-200 dark:border-blue-800' : 'sm:min-h-9'
+ }`}
+ >
+ Rename
+ </button>
+ <button
+ type="button"
+ data-api-token-id={token.id}
+ data-api-token-action="revoke"
onClick={(event) => openRevokeDialog(token, event.currentTarget)}
disabled={!canManage()}
class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-red-600 transition hover:bg-red-50 hover:text-red-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-red-400 dark:hover:bg-red-900 dark:hover:text-red-300 ${
@@ -726,19 +787,25 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
</ExternalTextLink>
</Card>
- <Show when={tokenToEdit() || tokenToRevoke()}>
+ <Show when={tokenToEdit() || tokenToRevoke() || tokenToRename()}>
<APITokenManagerDialogs
tokenToEdit={tokenToEdit}
tokenToRevoke={tokenToRevoke}
+ tokenToRename={tokenToRename}
+ renameInput={renameInput}
editScopes={editScopes}
scopeGroups={scopeGroups}
updatingTokenId={updatingTokenId}
+ isRenaming={isRenaming}
editScopesChanged={editScopesChanged}
onToggleEditScope={toggleEditScope}
onCloseScopeEditor={closeScopeEditor}
onSaveEditedScopes={() => void saveEditedScopes()}
onCancelRevoke={cancelRevoke}
onRevoke={revokeToken}
+ onRenameInput={setRenameInput}
+ onCloseRename={closeRenameDialog}
+ onRename={() => void renameToken()}
/>
</Show>
</div>
diff --git a/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx b/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx
index 5df14a23b2..4f7107fd3c 100644
--- a/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManagerDialogs.tsx
@@ -6,15 +6,21 @@ import type { APITokenRecord } from '@/types/api';
interface APITokenManagerDialogsProps {
tokenToEdit: Accessor<APITokenRecord | null>;
tokenToRevoke: Accessor<APITokenRecord | null>;
+ tokenToRename: Accessor<APITokenRecord | null>;
+ renameInput: Accessor<string>;
editScopes: Accessor<string[]>;
scopeGroups: Accessor<[APIScopeOption['group'], APIScopeOption[]][]>;
updatingTokenId: Accessor<string | null>;
+ isRenaming: Accessor<boolean>;
editScopesChanged: () => boolean;
onToggleEditScope: (scope: string) => void;
onCloseScopeEditor: () => void;
onSaveEditedScopes: () => void;
onCancelRevoke: () => void;
onRevoke: (token: APITokenRecord) => void;
+ onRenameInput: (name: string) => void;
+ onCloseRename: () => void;
+ onRename: () => void;
}
export const APITokenManagerDialogs: Component<APITokenManagerDialogsProps> = (props) => (
@@ -119,6 +125,57 @@ export const APITokenManagerDialogs: Component<APITokenManagerDialogsProps> = (p
</Dialog>
</Show>
+ <Show when={props.tokenToRename()}>
+ <Dialog
+ isOpen={true}
+ onClose={props.onCloseRename}
+ panelClass="max-w-md"
+ ariaLabel="Rename API token"
+ >
+ <form
+ class="w-full p-6"
+ onSubmit={(event) => {
+ event.preventDefault();
+ props.onRename();
+ }}
+ >
+ <h3 class="mb-2 text-lg font-semibold text-base-content">Rename API token</h3>
+ <p class="mb-4 text-sm text-muted">
+ This only changes the name shown in Pulse. The token value and connected agents stay
+ unchanged.
+ </p>
+ <label class="block space-y-2">
+ <span class="text-xs font-semibold uppercase tracking-wide text-muted">Token name</span>
+ <input
+ type="text"
+ value={props.renameInput()}
+ onInput={(event) => props.onRenameInput(event.currentTarget.value)}
+ disabled={props.isRenaming()}
+ class="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
+ autofocus
+ />
+ </label>
+ <div class="mt-5 flex justify-end gap-3">
+ <button
+ type="button"
+ onClick={props.onCloseRename}
+ disabled={props.isRenaming()}
+ class="rounded-md border border-border px-4 py-2 text-sm font-medium text-base-content hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={props.isRenaming() || !props.renameInput().trim()}
+ class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {props.isRenaming() ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </form>
+ </Dialog>
+ </Show>
+
<Show when={props.tokenToRevoke()}>
<Dialog
isOpen={true}
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index e2ffbc3756..e3274e1926 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -25,6 +25,7 @@ import { APITokenManager } from '../APITokenManager';
const listTokensMock = vi.fn();
const createTokenMock = vi.fn();
const updateTokenScopesMock = vi.fn();
+const renameTokenMock = vi.fn();
const deleteTokenMock = vi.fn();
const fetchAgentCapabilitiesManifestMock = vi.fn();
const notificationSuccessMock = vi.fn();
@@ -42,6 +43,7 @@ vi.mock('@/api/security', () => ({
listTokens: (...args: unknown[]) => listTokensMock(...args),
createToken: (...args: unknown[]) => createTokenMock(...args),
updateTokenScopes: (...args: unknown[]) => updateTokenScopesMock(...args),
+ renameToken: (...args: unknown[]) => renameTokenMock(...args),
deleteToken: (...args: unknown[]) => deleteTokenMock(...args),
},
}));
@@ -177,6 +179,7 @@ describe('APITokenManager', () => {
listTokensMock.mockReset();
createTokenMock.mockReset();
updateTokenScopesMock.mockReset();
+ renameTokenMock.mockReset();
deleteTokenMock.mockReset();
notificationSuccessMock.mockReset();
notificationErrorMock.mockReset();
@@ -227,6 +230,7 @@ describe('APITokenManager', () => {
updateTokenScopesMock.mockImplementation(
async (id: string, scopes: string[]): Promise<APITokenRecord> => makeToken({ id, scopes }),
);
+ renameTokenMock.mockImplementation(async (id: string, name: string) => makeToken({ id, name }));
});
afterEach(() => {
@@ -756,6 +760,34 @@ describe('APITokenManager', () => {
).not.toBeInTheDocument();
});
+ it('renames an existing token without revoking it', async () => {
+ listTokensMock.mockResolvedValue([
+ makeToken({
+ id: 'token-pbs',
+ name: 'proxmox-agent-pbs-1785306083',
+ scopes: [AGENT_REPORT_SCOPE],
+ }),
+ ]);
+
+ render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
+
+ const row = await findTokenTableRow('proxmox-agent-pbs-1785306083');
+ const renameButton = within(row).getByRole('button', { name: 'Rename' });
+ fireEvent.click(renameButton);
+
+ const input = await screen.findByRole('textbox', { name: 'Token name' });
+ fireEvent.input(input, { target: { value: 'PBS 01 telemetry' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => {
+ expect(renameTokenMock).toHaveBeenCalledWith('token-pbs', 'PBS 01 telemetry');
+ expect(screen.getAllByText('PBS 01 telemetry').length).toBeGreaterThan(0);
+ expect(document.activeElement).toHaveTextContent('Rename');
+ });
+ expect(deleteTokenMock).not.toHaveBeenCalled();
+ expect(notificationSuccessMock).toHaveBeenCalledWith('Token renamed');
+ });
+
it('surfaces scope denial when token generation is blocked by caller scope', async () => {
createTokenMock.mockRejectedValueOnce(
Object.assign(
diff --git a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
index 81c5c4e9bb..2902383fc0 100644
--- a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
+++ b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
@@ -75,6 +75,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const [loading, setLoading] = createSignal(true);
const [isGenerating, setIsGenerating] = createSignal(false);
const [updatingTokenId, setUpdatingTokenId] = createSignal<string | null>(null);
+ const [isRenaming, setIsRenaming] = createSignal(false);
const [newTokenValue, setNewTokenValue] = createSignal<string | null>(null);
const [newTokenRecord, setNewTokenRecord] = createSignal<APITokenRecord | null>(null);
const [nameInput, setNameInput] = createSignal('');
@@ -415,6 +416,31 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
}
};
+ const handleRename = async (record: APITokenRecord, name: string): Promise<boolean> => {
+ if (!canManage() || isRenaming()) return false;
+ const trimmedName = name.trim();
+ if (!trimmedName) {
+ notificationStore.error('Enter a token name.');
+ return false;
+ }
+
+ setIsRenaming(true);
+ try {
+ const updated = await SecurityAPI.renameToken(record.id, trimmedName);
+ setTokens((previous) => previous.map((token) => (token.id === updated.id ? updated : token)));
+ setNewTokenRecord((current) => (current?.id === updated.id ? updated : current));
+ notificationStore.success('Token renamed');
+ props.onTokensChanged?.();
+ return true;
+ } catch (err) {
+ logger.error('Failed to rename API token', err);
+ notificationStore.error('Unable to rename the API token.');
+ return false;
+ } finally {
+ setIsRenaming(false);
+ }
+ };
+
const isRevealActiveForCurrentToken = () => {
const active = tokenRevealState();
return newTokenValue() !== null && Boolean(active && active.token === newTokenValue());
@@ -472,11 +498,13 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
handleDelete,
handleGenerate,
handleUpdateScopes,
+ handleRename,
hasWildcardTokens,
hasScopeSelection,
isFullAccessSelected,
isGenerating,
updatingTokenId,
+ isRenaming,
isRevealActiveForCurrentToken,
loading,
nameInput,
diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.go
index 5f781bce4c..19141b724c 100644
--- a/internal/api/security_tokens.go
+++ b/internal/api/security_tokens.go
@@ -294,6 +294,7 @@ type createTokenRequest struct {
}
type updateTokenRequest struct {
+ Name *string `json:"name"`
Scopes *[]string `json:"scopes"`
}
@@ -373,7 +374,7 @@ func (r *Router) handleCreateAPIToken(w http.ResponseWriter, req *http.Request)
})
}
-// handleUpdateAPIToken changes an API token's scopes without rotating its secret.
+// handleUpdateAPIToken changes an API token's metadata without rotating its secret.
func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPatch {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -389,23 +390,37 @@ func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request)
var payload updateTokenRequest
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
- r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Failed to decode scope update for token id=%s", tokenID))
+ r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Failed to decode token update for token id=%s", tokenID))
log.Warn().Err(err).Str("token_id", tokenID).Msg("Failed to decode API token update request")
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
- if payload.Scopes == nil {
+ if payload.Scopes == nil && payload.Name == nil {
r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Missing scopes field for token id=%s", tokenID))
http.Error(w, "Scopes field required", http.StatusBadRequest)
return
}
- scopes, err := normalizeRequestedScopes(payload.Scopes)
- if err != nil {
- r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Invalid scope update for token id=%s", tokenID))
- log.Warn().Err(err).Str("token_id", tokenID).Msg("Invalid scopes provided for API token update")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
+ var scopes []string
+ if payload.Scopes != nil {
+ var err error
+ scopes, err = normalizeRequestedScopes(payload.Scopes)
+ if err != nil {
+ r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Invalid scope update for token id=%s", tokenID))
+ log.Warn().Err(err).Str("token_id", tokenID).Msg("Invalid scopes provided for API token update")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ }
+
+ var name string
+ if payload.Name != nil {
+ name = strings.TrimSpace(*payload.Name)
+ if name == "" {
+ r.auditTokenEvent(req, "token_renamed", false, fmt.Sprintf("Blank name rejected for token id=%s", tokenID))
+ http.Error(w, "Token name is required", http.StatusBadRequest)
+ return
+ }
}
config.Mu.Lock()
@@ -432,53 +447,68 @@ func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request)
// narrowing or otherwise mutating a more privileged credential; checking
// the requested scopes prevents widening a token beyond the caller's own
// authority, including when editing itself.
- if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
- for _, scope := range oldRecord.Scopes {
- if !callerToken.HasScope(scope) {
- r.auditTokenEvent(req, "token_updated", false,
- fmt.Sprintf("Scope update denied: caller missing existing scope %q on target token id=%s", scope, tokenID))
- http.Error(w, fmt.Sprintf("Cannot update token with scope %q: your token does not have this scope", scope), http.StatusForbidden)
- return
+ if payload.Scopes != nil {
+ if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
+ for _, scope := range oldRecord.Scopes {
+ if !callerToken.HasScope(scope) {
+ r.auditTokenEvent(req, "token_updated", false,
+ fmt.Sprintf("Scope update denied: caller missing existing scope %q on target token id=%s", scope, tokenID))
+ http.Error(w, fmt.Sprintf("Cannot update token with scope %q: your token does not have this scope", scope), http.StatusForbidden)
+ return
+ }
}
- }
- for _, scope := range scopes {
- if !callerToken.HasScope(scope) {
- r.auditTokenEvent(req, "token_updated", false,
- fmt.Sprintf("Scope update denied: caller cannot grant scope %q on target token id=%s", scope, tokenID))
- http.Error(w, fmt.Sprintf("Cannot grant scope %q: your token does not have this scope", scope), http.StatusForbidden)
- return
+ for _, scope := range scopes {
+ if !callerToken.HasScope(scope) {
+ r.auditTokenEvent(req, "token_updated", false,
+ fmt.Sprintf("Scope update denied: caller cannot grant scope %q on target token id=%s", scope, tokenID))
+ http.Error(w, fmt.Sprintf("Cannot grant scope %q: your token does not have this scope", scope), http.StatusForbidden)
+ return
+ }
}
}
}
- r.config.APITokens[tokenIndex].Scopes = append([]string(nil), scopes...)
+ if payload.Scopes != nil {
+ r.config.APITokens[tokenIndex].Scopes = append([]string(nil), scopes...)
+ }
+ if payload.Name != nil {
+ r.config.APITokens[tokenIndex].Name = name
+ }
if r.persistence != nil {
if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
r.config.APITokens[tokenIndex] = storedRecord
- r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Failed to persist scope update for token id=%s", tokenID))
- log.Error().Err(err).Str("token_id", tokenID).Msg("Failed to persist API token scope update")
+ r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Failed to persist token update for token id=%s", tokenID))
+ log.Error().Err(err).Str("token_id", tokenID).Msg("Failed to persist API token update")
http.Error(w, "Failed to save token", http.StatusInternalServerError)
return
}
}
updatedRecord := r.config.APITokens[tokenIndex]
- r.auditTokenEvent(req, "token_updated", true,
- fmt.Sprintf(
- "Updated API token id=%s old_scopes=%s new_scopes=%s",
- tokenID,
- strings.Join(oldRecord.Scopes, ","),
- strings.Join(updatedRecord.Scopes, ","),
- ))
+ if payload.Scopes != nil {
+ r.auditTokenEvent(req, "token_updated", true,
+ fmt.Sprintf(
+ "Updated API token id=%s old_scopes=%s new_scopes=%s",
+ tokenID,
+ strings.Join(oldRecord.Scopes, ","),
+ strings.Join(updatedRecord.Scopes, ","),
+ ))
+ }
+ if payload.Name != nil {
+ r.auditTokenEvent(req, "token_renamed", true, fmt.Sprintf("Renamed API token id=%s", tokenID))
+ }
- log.Info().
+ logEvent := log.Info().
Str("audit_event", "token_updated").
Str("token_id", tokenID).
Str("token_name", updatedRecord.Name).
- Strs("old_scopes", oldRecord.Scopes).
- Strs("new_scopes", updatedRecord.Scopes).
- Str("client_ip", req.RemoteAddr).
- Msg("API token scopes updated")
+ Str("client_ip", req.RemoteAddr)
+ if payload.Scopes != nil {
+ logEvent = logEvent.
+ Strs("old_scopes", oldRecord.Scopes).
+ Strs("new_scopes", updatedRecord.Scopes)
+ }
+ logEvent.Msg("API token updated")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
@@ -533,6 +563,11 @@ func (r *Router) handleCreateRelayMobileAccessToken(w http.ResponseWriter, req *
})
}
+// handleRenameAPIToken changes token metadata without rotating the credential.
+func (r *Router) handleRenameAPIToken(w http.ResponseWriter, req *http.Request) {
+ r.handleUpdateAPIToken(w, req)
+}
+
// handleDeleteAPIToken removes an API token by ID.
func (r *Router) handleDeleteAPIToken(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
diff --git a/internal/api/security_tokens_handlers_test.go b/internal/api/security_tokens_handlers_test.go
index 58a392404c..c4514deae4 100644
--- a/internal/api/security_tokens_handlers_test.go
+++ b/internal/api/security_tokens_handlers_test.go
@@ -108,6 +108,28 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
t.Fatalf("expected record id %q, got %q", createResp.Record.ID, getResp.Record.ID)
}
+ req = httptest.NewRequest(
+ http.MethodPatch,
+ "/api/security/tokens/"+createResp.Record.ID,
+ strings.NewReader(`{"name":"renamed token"}`),
+ )
+ req = req.WithContext(authpkg.WithUser(req.Context(), "alice"))
+ rr = httptest.NewRecorder()
+ router.handleRenameAPIToken(rr, req)
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected rename status %d, got %d", http.StatusOK, rr.Code)
+ }
+
+ var renameResp struct {
+ Record apiTokenDTO `json:"record"`
+ }
+ if err := json.NewDecoder(rr.Body).Decode(&renameResp); err != nil {
+ t.Fatalf("decode rename response: %v", err)
+ }
+ if renameResp.Record.Name != "renamed token" || cfg.APITokens[0].Name != "renamed token" {
+ t.Fatalf("token rename did not update response and config: response=%q config=%q", renameResp.Record.Name, cfg.APITokens[0].Name)
+ }
+
req = httptest.NewRequest(http.MethodDelete, "/api/security/tokens/", nil)
rr = httptest.NewRecorder()
router.handleDeleteAPIToken(rr, req)
@@ -151,7 +173,7 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
t.Fatalf("query audit events: %v", err)
}
- var sawCreate, sawDelete bool
+ var sawCreate, sawRename, sawDelete bool
for _, event := range events {
if event.EventType == "token_created" && event.Success {
sawCreate = true
@@ -165,6 +187,9 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
if event.EventType == "token_deleted" && event.Success {
sawDelete = true
}
+ if event.EventType == "token_renamed" && event.Success {
+ sawRename = true
+ }
}
if !sawCreate {
t.Fatalf("expected successful token_created audit event")
@@ -172,6 +197,47 @@ func TestSecurityTokens_ListCreateDelete(t *testing.T) {
if !sawDelete {
t.Fatalf("expected successful token_deleted audit event")
}
+ if !sawRename {
+ t.Fatalf("expected successful token_renamed audit event")
+ }
+}
+
+func TestSecurityTokens_RenameRejectsInvalidRequests(t *testing.T) {
+ cfg := &config.Config{APITokens: []config.APITokenRecord{{
+ ID: "token-1",
+ Name: "Original",
+ Hash: "hash",
+ CreatedAt: time.Now(),
+ }}}
+ router := &Router{
+ config: cfg,
+ persistence: config.NewConfigPersistence(t.TempDir()),
+ }
+
+ tests := []struct {
+ name string
+ path string
+ body string
+ want int
+ }{
+ {name: "missing id", path: "/api/security/tokens/", body: `{"name":"New"}`, want: http.StatusBadRequest},
+ {name: "invalid body", path: "/api/security/tokens/token-1", body: `{bad`, want: http.StatusBadRequest},
+ {name: "blank name", path: "/api/security/tokens/token-1", body: `{"name":" "}`, want: http.StatusBadRequest},
+ {name: "not found", path: "/api/security/tokens/missing", body: `{"name":"New"}`, want: http.StatusNotFound},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPatch, test.path, strings.NewReader(test.body))
+ rr := httptest.NewRecorder()
+ router.handleRenameAPIToken(rr, req)
+ if rr.Code != test.want {
+ t.Fatalf("status = %d, want %d", rr.Code, test.want)
+ }
+ })
+ }
+ if cfg.APITokens[0].Name != "Original" {
+ t.Fatalf("invalid rename changed token name to %q", cfg.APITokens[0].Name)
+ }
}
func TestSecurityTokens_Create_WithExpiresIn(t *testing.T) {