Skip to content

Commit 6f32fa6

Browse files
committed
Preserve managed agent tokens
Prevent token edits from silently replacing permanent or finite expiry values. Treat managed-token revocation as a durable user opt-out while blocking mutations that could desynchronize the orchestrator secret.
1 parent aad2589 commit 6f32fa6

5 files changed

Lines changed: 290 additions & 19 deletions

File tree

‎frontend/src/views/AgentTokens.vue‎

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,11 @@
115115
</div>
116116

117117
<!-- Token List Table -->
118-
<div v-else class="overflow-x-auto">
118+
<div v-else class="space-y-4">
119+
<div v-if="hasManagedTokens" class="alert alert-info" data-test="managed-token-banner">
120+
<span>Managed tokens are provisioned by the orchestrator. You may revoke one to disable the generated credential; Runabot will not automatically recreate it. Other changes must be made through Bot Profile assignments.</span>
121+
</div>
122+
<div class="overflow-x-auto">
119123
<table class="table table-zebra w-full">
120124
<thead>
121125
<tr>
@@ -132,7 +136,10 @@
132136
</thead>
133137
<tbody>
134138
<tr v-for="token in filteredTokens" :key="token.name">
135-
<td class="font-medium">{{ token.name }}</td>
139+
<td class="font-medium">
140+
<span>{{ token.name }}</span>
141+
<span v-if="isManagedToken(token)" class="badge badge-info badge-sm ml-2" data-test="managed-token-badge">Managed</span>
142+
</td>
136143
<td>
137144
<code class="text-sm bg-base-200 px-2 py-1 rounded">{{ token.token_prefix }}</code>
138145
</td>
@@ -169,7 +176,7 @@
169176
</td>
170177
<td>
171178
<span :class="{ 'text-warning': isExpiringSoon(token), 'text-error': isExpired(token) }">
172-
{{ formatDate(token.expires_at) }}
179+
{{ formatExpiry(token.expires_at) }}
173180
</span>
174181
</td>
175182
<td>
@@ -187,17 +194,19 @@
187194
<div class="flex gap-1">
188195
<button
189196
@click="openEditDialog(token)"
190-
:disabled="token.revoked"
197+
:disabled="token.revoked || isManagedToken(token)"
191198
class="btn btn-xs btn-outline"
192-
title="Assign profile pins"
199+
:title="isManagedToken(token) ? managedTokenHelp : 'Assign profile pins'"
200+
:data-test="`token-edit-${token.name}`"
193201
>
194202
Edit
195203
</button>
196204
<button
197205
@click="handleRegenerate(token.name)"
198-
:disabled="token.revoked"
206+
:disabled="token.revoked || isManagedToken(token)"
199207
class="btn btn-xs btn-outline"
200-
title="Regenerate token secret"
208+
:title="isManagedToken(token) ? managedTokenHelp : 'Regenerate token secret'"
209+
:data-test="`token-regenerate-${token.name}`"
201210
>
202211
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
203212
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
@@ -209,6 +218,7 @@
209218
:disabled="token.revoked"
210219
class="btn btn-xs btn-error btn-outline"
211220
title="Revoke token"
221+
:data-test="`token-revoke-${token.name}`"
212222
>
213223
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
214224
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
@@ -218,8 +228,10 @@
218228
<button
219229
v-if="token.revoked || isExpired(token)"
220230
@click="handleDelete(token.name)"
231+
:disabled="isManagedToken(token)"
221232
class="btn btn-xs btn-error"
222-
title="Permanently delete token and free its name for reuse"
233+
:title="isManagedToken(token) ? managedTokenHelp : 'Permanently delete token and free its name for reuse'"
234+
:data-test="`token-delete-${token.name}`"
223235
>
224236
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
225237
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
@@ -231,6 +243,7 @@
231243
</tr>
232244
</tbody>
233245
</table>
246+
</div>
234247
</div>
235248

236249
<!-- Token Secret Display (shown after creation or regeneration) -->
@@ -261,7 +274,7 @@
261274
<h3 class="font-bold text-lg mb-4">Edit Agent Token</h3>
262275
<div class="space-y-4">
263276
<label class="form-control"><span class="label-text font-medium">Token Name</span><input v-model="editForm.name" class="input input-bordered w-full" /></label>
264-
<label class="form-control"><span class="label-text font-medium">Expires In</span><select v-model="editForm.expiresIn" class="select select-bordered w-full"><option value="168h">7 days</option><option value="720h">30 days</option><option value="2160h">90 days</option><option value="8760h">365 days</option></select></label>
277+
<label class="form-control"><span class="label-text font-medium">Expires In</span><select v-model="editForm.expiresIn" class="select select-bordered w-full" data-test="edit-token-expiry"><option value="">Keep existing expiration</option><option value="never">Never (non-expiring)</option><option value="168h">7 days</option><option value="720h">30 days</option><option value="2160h">90 days</option><option value="8760h">365 days</option></select></label>
265278
<div class="form-control"><span class="label-text font-medium">Allowed Servers</span><label class="flex gap-2"><input v-model="editForm.allServers" type="checkbox" class="checkbox checkbox-sm" /> All servers</label><div v-if="!editForm.allServers" class="max-h-32 overflow-y-auto"> <label v-for="server in availableServers" :key="server.name" class="flex gap-2"><input v-model="editForm.selectedServers" type="checkbox" :value="server.name" class="checkbox checkbox-sm" /> {{ server.name }}</label></div></div>
266279
<div class="form-control"><span class="label-text font-medium">Access Profiles</span><select v-model="editForm.accessProfiles" multiple class="select select-bordered w-full min-h-24"><option v-for="profile in profilesStore.profiles" :key="profile.name" :value="profile.name">{{ profile.name }}</option></select></div>
267280
<div class="form-control"><span class="label-text font-medium">Permissions</span><label v-for="permission in ['read', 'write', 'destructive']" :key="permission" class="flex gap-2"><input v-model="editForm.permissions" type="checkbox" :value="permission" :disabled="permission === 'read'" class="checkbox checkbox-sm" /> {{ permission }}</label></div>
@@ -450,7 +463,7 @@ const copied = ref(false)
450463
const createDialog = ref<HTMLDialogElement | null>(null)
451464
const editDialog = ref<HTMLDialogElement | null>(null)
452465
const editingToken = ref(false)
453-
const editForm = ref({ name: '', allServers: true, selectedServers: [] as string[], permissions: ['read'] as string[], expiresIn: '720h', accessProfiles: [] as string[] })
466+
const editForm = ref({ name: '', allServers: true, selectedServers: [] as string[], permissions: ['read'] as string[], expiresIn: '', accessProfiles: [] as string[] })
454467
const editOriginalName = ref('')
455468
456469
const createForm = ref({
@@ -490,6 +503,8 @@ const expiredOrRevokedCount = computed(() => {
490503
return tokens.value.filter(t => t.revoked || isExpired(t)).length
491504
})
492505
506+
const hasManagedTokens = computed(() => tokens.value.some(isManagedToken))
507+
493508
// KPI-card-driven filter (issue #436): 'all' | 'active' | 'expired'
494509
const tokenFilter = ref<'all' | 'active' | 'expired'>('all')
495510
@@ -504,12 +519,29 @@ const filteredTokens = computed(() => {
504519
})
505520
506521
// Helper functions
522+
const managedTokenHelp = 'Managed tokens can only be changed through Bot Profile assignments'
523+
524+
function isManagedTokenName(name: string): boolean {
525+
return name.startsWith('runabot-')
526+
}
527+
528+
function isManagedToken(token: AgentTokenInfo): boolean {
529+
return isManagedTokenName(token.name)
530+
}
531+
532+
function isNonExpiring(expiresAt?: string | null): boolean {
533+
if (!expiresAt) return true
534+
const date = new Date(expiresAt)
535+
return Number.isNaN(date.getTime()) || date.getUTCFullYear() <= 1
536+
}
537+
507538
function isExpired(token: AgentTokenInfo): boolean {
539+
if (isNonExpiring(token.expires_at)) return false
508540
return new Date(token.expires_at) < new Date()
509541
}
510542
511543
function isExpiringSoon(token: AgentTokenInfo): boolean {
512-
if (token.revoked || isExpired(token)) return false
544+
if (token.revoked || isNonExpiring(token.expires_at) || isExpired(token)) return false
513545
const expiresAt = new Date(token.expires_at)
514546
const now = new Date()
515547
const hoursLeft = (expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60)
@@ -520,6 +552,10 @@ function formatDate(dateStr: string): string {
520552
return formatDateTimeShort(dateStr)
521553
}
522554
555+
function formatExpiry(dateStr: string): string {
556+
return isNonExpiring(dateStr) ? 'Never' : formatDate(dateStr)
557+
}
558+
523559
function permissionBadgeClass(perm: string): string {
524560
switch (perm) {
525561
case 'read': return 'badge-info'
@@ -644,8 +680,9 @@ async function handleCreate() {
644680
}
645681
646682
function openEditDialog(token: AgentTokenInfo) {
683+
if (isManagedToken(token)) return
647684
editOriginalName.value = token.name
648-
editForm.value = { name: token.name, allServers: token.allowed_servers.includes('*'), selectedServers: token.allowed_servers.filter(s => s !== '*'), permissions: [...token.permissions], expiresIn: '720h', accessProfiles: [...(token.access_profiles || [])] }
685+
editForm.value = { name: token.name, allServers: token.allowed_servers.includes('*'), selectedServers: token.allowed_servers.filter(s => s !== '*'), permissions: [...token.permissions], expiresIn: '', accessProfiles: [...(token.access_profiles || [])] }
649686
editDialog.value?.showModal()
650687
}
651688
@@ -664,6 +701,7 @@ async function saveEdit() {
664701
665702
// Regenerate token
666703
async function handleRegenerate(name: string) {
704+
if (isManagedTokenName(name)) return
667705
if (!confirm(`Regenerate the secret for token "${name}"? The old secret will stop working immediately.`)) {
668706
return
669707
}
@@ -697,7 +735,10 @@ async function handleRegenerate(name: string) {
697735
698736
// Revoke token
699737
async function handleRevoke(name: string) {
700-
if (!confirm(`Revoke token "${name}"? This action cannot be undone.`)) {
738+
const prompt = isManagedTokenName(name)
739+
? `Revoke managed token "${name}"? This disables the generated credential, and Runabot will not automatically repair or recreate it.`
740+
: `Revoke token "${name}"? This action cannot be undone.`
741+
if (!confirm(prompt)) {
701742
return
702743
}
703744
@@ -729,6 +770,7 @@ async function handleRevoke(name: string) {
729770
730771
// Permanently delete a (revoked or expired) token, freeing its name for reuse
731772
async function handleDelete(name: string) {
773+
if (isManagedTokenName(name)) return
732774
if (!confirm(`Permanently delete token "${name}"? This removes it completely and frees the name for reuse. This action cannot be undone.`)) {
733775
return
734776
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2+
import { flushPromises, mount } from '@vue/test-utils'
3+
import { createPinia } from 'pinia'
4+
5+
const api = vi.hoisted(() => ({
6+
listAgentTokens: vi.fn(),
7+
getProfiles: vi.fn(),
8+
getActiveProfile: vi.fn(),
9+
revokeAgentToken: vi.fn(),
10+
regenerateAgentToken: vi.fn(),
11+
deleteAgentToken: vi.fn(),
12+
updateAgentToken: vi.fn(),
13+
}))
14+
15+
vi.mock('@/services/api', () => ({ default: api }))
16+
17+
import AgentTokens from '@/views/AgentTokens.vue'
18+
19+
const baseToken = {
20+
token_prefix: 'mcp_agt_test',
21+
allowed_servers: ['*'],
22+
permissions: ['read'],
23+
created_at: '2026-01-01T00:00:00Z',
24+
last_used_at: null,
25+
access_profiles: [],
26+
}
27+
28+
async function mountTokens() {
29+
const wrapper = mount(AgentTokens, { global: { plugins: [createPinia()] } })
30+
await new Promise(resolve => setTimeout(resolve, 110))
31+
await flushPromises()
32+
return wrapper
33+
}
34+
35+
describe('AgentTokens managed token contract', () => {
36+
beforeEach(() => {
37+
vi.clearAllMocks()
38+
api.getProfiles.mockResolvedValue({ success: true, data: { profiles: [] } })
39+
api.getActiveProfile.mockResolvedValue({ success: true, data: { active_profile: '' } })
40+
api.revokeAgentToken.mockResolvedValue({ success: true })
41+
api.regenerateAgentToken.mockResolvedValue({ success: true, data: { token: 'rotated' } })
42+
api.deleteAgentToken.mockResolvedValue({ success: true })
43+
api.updateAgentToken.mockResolvedValue({ success: true })
44+
HTMLDialogElement.prototype.showModal = vi.fn()
45+
})
46+
47+
afterEach(() => {
48+
vi.unstubAllGlobals()
49+
})
50+
51+
it('renders zero-time managed tokens as non-expiring and active', async () => {
52+
api.listAgentTokens.mockResolvedValue({
53+
success: true,
54+
data: { tokens: [{ ...baseToken, name: 'runabot-u1010b5', expires_at: '0001-01-01T00:00:00Z', revoked: false }] },
55+
})
56+
57+
const wrapper = await mountTokens()
58+
59+
expect(wrapper.find('[data-test="managed-token-badge"]').text()).toBe('Managed')
60+
expect(wrapper.find('[data-test="managed-token-banner"]').exists()).toBe(true)
61+
expect(wrapper.text()).toContain('Never')
62+
expect(wrapper.text()).toContain('Active')
63+
expect(wrapper.find('[data-test="token-edit-runabot-u1010b5"]').attributes('disabled')).toBeDefined()
64+
expect(wrapper.find('[data-test="token-regenerate-runabot-u1010b5"]').attributes('disabled')).toBeDefined()
65+
expect(wrapper.find('[data-test="token-revoke-runabot-u1010b5"]').attributes('disabled')).toBeUndefined()
66+
expect(wrapper.find('[data-test="token-delete-runabot-u1010b5"]').exists()).toBe(false)
67+
})
68+
69+
it('allows soft revoke but disables permanent deletion of its tombstone', async () => {
70+
api.listAgentTokens.mockResolvedValue({
71+
success: true,
72+
data: { tokens: [{ ...baseToken, name: 'runabot-u1010b5', expires_at: '0001-01-01T00:00:00Z', revoked: false }] },
73+
})
74+
vi.stubGlobal('confirm', vi.fn(() => true))
75+
const wrapper = await mountTokens()
76+
77+
await wrapper.find('[data-test="token-revoke-runabot-u1010b5"]').trigger('click')
78+
await flushPromises()
79+
80+
expect(confirm).toHaveBeenCalledWith(expect.stringContaining('will not automatically repair or recreate it'))
81+
expect(api.revokeAgentToken).toHaveBeenCalledWith('runabot-u1010b5')
82+
83+
await wrapper.unmount()
84+
api.listAgentTokens.mockResolvedValue({
85+
success: true,
86+
data: { tokens: [{ ...baseToken, name: 'runabot-u1010b5', expires_at: '0001-01-01T00:00:00Z', revoked: true }] },
87+
})
88+
const revokedWrapper = await mountTokens()
89+
expect(revokedWrapper.find('[data-test="token-delete-runabot-u1010b5"]').attributes('disabled')).toBeDefined()
90+
})
91+
92+
it('defaults ordinary token edits to preserving the exact expiry', async () => {
93+
api.listAgentTokens.mockResolvedValue({
94+
success: true,
95+
data: { tokens: [{ ...baseToken, name: 'custom-token', expires_at: '2026-12-01T00:00:00Z', revoked: false }] },
96+
})
97+
const wrapper = await mountTokens()
98+
99+
await wrapper.find('[data-test="token-edit-custom-token"]').trigger('click')
100+
expect((wrapper.find('[data-test="edit-token-expiry"]').element as HTMLSelectElement).value).toBe('')
101+
})
102+
})

‎internal/httpapi/tokens.go‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -356,11 +356,6 @@ func (s *Server) handleUpdateToken(w http.ResponseWriter, r *http.Request) {
356356
s.writeError(w, r, http.StatusBadRequest, err.Error())
357357
return
358358
}
359-
expiresAt, err := parseExpiry(req.ExpiresIn)
360-
if err != nil {
361-
s.writeError(w, r, http.StatusBadRequest, err.Error())
362-
return
363-
}
364359
for _, pin := range req.AccessProfiles {
365360
if err := s.validateProfilePin(pin); err != nil {
366361
s.writeError(w, r, http.StatusBadRequest, err.Error())
@@ -372,6 +367,14 @@ func (s *Server) handleUpdateToken(w http.ResponseWriter, r *http.Request) {
372367
s.writeError(w, r, http.StatusNotFound, "agent token not found")
373368
return
374369
}
370+
expiresAt := old.ExpiresAt
371+
if strings.TrimSpace(req.ExpiresIn) != "" {
372+
expiresAt, err = parseExpiry(req.ExpiresIn)
373+
if err != nil {
374+
s.writeError(w, r, http.StatusBadRequest, err.Error())
375+
return
376+
}
377+
}
375378
updated := *old
376379
updated.Name, updated.AllowedServers, updated.Permissions, updated.ExpiresAt = req.Name, req.AllowedServers, req.Permissions, expiresAt
377380
updated.AccessProfiles = append([]string(nil), req.AccessProfiles...)

0 commit comments

Comments
 (0)