test(36-02): update test fixtures for granular scopes and rebuild embedded admin dist

This commit is contained in:
Jakub Zych
2026-11-24 19:49:38 +01:00
parent 336664684b
commit 3781c9792d
12 changed files with 404 additions and 186 deletions

View File

@@ -23,6 +23,8 @@ const createdToken = {
description: 'View everything',
read_only: true,
known: true,
plugin_id: '',
group: '',
},
],
created_at: '2026-01-10T12:00:00Z',
@@ -40,6 +42,8 @@ const scopes = [
description: 'Everything',
read_only: false,
known: true,
plugin_id: '',
group: '',
},
{
name: 'admin:read',
@@ -47,6 +51,8 @@ const scopes = [
description: 'View everything',
read_only: true,
known: true,
plugin_id: '',
group: '',
},
]
@@ -102,17 +108,9 @@ async function fillName(value: string): Promise<void> {
await flushPromises()
}
async function pickAdminRead(): Promise<void> {
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
}
async function openCreateAtStep2(routes: Record<string, Route> = {}): Promise<void> {
await openCreate(routes)
await fillName('Agent')
await pickAdminRead()
await click('[data-action="create-token-submit"]', dialog()!)
expect(dialog()!.querySelector<HTMLInputElement>('[data-token-plaintext]')!.value).toBe(PLAIN)
}
@@ -207,16 +205,15 @@ describe('ApiTokenCreateDialog step 1', () => {
expect(document.activeElement).toBe(dialog()!.querySelector('#api-token-name'))
})
it('shows scopes skeleton and disables submit while pending', async () => {
it('shows scopes skeleton and disables submit while pending, then defaults to Read-only (D-08)', async () => {
const pending = deferred()
await openCreate({ [`GET ${SCOPES}`]: pending.route })
expect(dialog()!.querySelector('[data-scope-picker]')!.querySelectorAll('[aria-hidden="true"]').length).toBe(3)
expect(dialog()!.querySelector('[data-scope-loading]')).toBeTruthy()
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(true)
pending.release(envelope(scopes))
await flushPromises()
expect(dialog()!.querySelector('[data-scope="admin:read"]')).toBeTruthy()
// No scope selected yet — submit stays disabled (WR-02).
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(true)
expect(dialog()!.querySelector('[data-access-tier="read_only"]')!.getAttribute('data-state')).toBe('checked')
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(false)
})
it('shows scopes failure alert when the scopes request fails', async () => {
@@ -233,26 +230,15 @@ describe('ApiTokenCreateDialog step 1', () => {
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(true)
})
it('star checked disables others; unchecking restores without picks; no preselection', async () => {
it('defaults to Read-only and switches cleanly to Full (*) with scope_all_includes note', async () => {
await openCreate()
const star = dialog()!.querySelector<HTMLInputElement>('[data-scope="*"] input')!
const admin = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
expect(star.checked).toBe(false)
expect(admin.checked).toBe(false)
admin.checked = true
admin.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
star.checked = true
star.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
expect(admin.disabled).toBe(true)
expect(admin.checked).toBe(false)
expect(dialog()!.querySelector('[data-access-tier="read_only"]')!.getAttribute('data-state')).toBe('checked')
expect(dialog()!.querySelector('[data-scope-all-note]')).toBeNull()
await click('[data-access-tier="full"]', dialog()!)
expect(dialog()!.querySelector('[data-access-tier="full"]')!.getAttribute('data-state')).toBe('checked')
expect(dialog()!.textContent).toContain('Pełny dostęp obejmuje wszystkie pozostałe zakresy.')
star.checked = false
star.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
expect(admin.disabled).toBe(false)
expect(admin.checked).toBe(false)
await click('[data-access-tier="read_only"]', dialog()!)
expect(dialog()!.querySelector('[data-scope-all-note]')).toBeNull()
})
it('preselects 90d and previews 30, 90, 365 and never', async () => {
@@ -292,7 +278,6 @@ describe('ApiTokenCreateDialog step 1', () => {
},
},
})
await pickAdminRead()
await click('[data-action="create-token-submit"]', dialog()!)
expect(dialog()!.textContent).toContain('Podaj nazwę tokenu.')
expect(dialog()!.querySelector('#api-token-name')!.getAttribute('aria-invalid')).toBe('true')
@@ -309,7 +294,6 @@ describe('ApiTokenCreateDialog step 1', () => {
},
})
await fillName('Busy')
await pickAdminRead()
const submit = dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!
submit.click()
await flushPromises()
@@ -341,7 +325,6 @@ describe('ApiTokenCreateDialog step 1', () => {
},
})
await fillName('Keep me')
await pickAdminRead()
await click('[data-action="create-token-submit"]', dialog()!)
expect(toasts.value[0]).toMatchObject({
text: 'Nie udało się utworzyć tokenu. Spróbuj ponownie.',
@@ -358,7 +341,6 @@ describe('ApiTokenCreateDialog step 1', () => {
it('posts selected scopes and never leaves plaintext after Done', async () => {
const { calls } = await openCreate()
await fillName('CI')
await pickAdminRead()
await click('[data-action="create-token-submit"]', dialog()!)
const [post] = requestsTo(calls, 'POST', TOKENS)
expect(await post!.clone().json()).toEqual({
@@ -468,18 +450,17 @@ describe('ApiTokenCreateDialog mounted directly', () => {
return { wrapper, calls }
}
it('opens with the scopes from one GET', async () => {
it('opens with the scopes from one GET and selects Read-only by default', async () => {
const { calls } = await openDialog()
expect(dialog()).toBeTruthy()
expect(requestsTo(calls, 'GET', SCOPES)).toHaveLength(1)
expect(dialog()!.querySelector('[data-scope="*"]')).toBeTruthy()
expect(dialog()!.querySelector('[data-scope="admin:read"]')).toBeTruthy()
expect(dialog()!.querySelector('[data-access-tier="full"]')).toBeTruthy()
expect(dialog()!.querySelector('[data-access-tier="read_only"]')!.getAttribute('data-state')).toBe('checked')
})
it('creates a token with one POST, shows the plaintext and emits created', async () => {
const { wrapper, calls } = await openDialog()
await fillName('CI runner')
await pickAdminRead()
await click('[data-action="create-token-submit"]', dialog()!)
const posts = requestsTo(calls, 'POST', TOKENS)

View File

@@ -22,6 +22,8 @@ const existingToken = {
description: 'View everything',
read_only: true,
known: true,
plugin_id: '',
group: '',
},
],
created_at: '2026-01-10T12:00:00Z',
@@ -43,6 +45,8 @@ const starToken = {
description: 'Everything',
read_only: false,
known: true,
plugin_id: '',
group: '',
},
],
last_used_at: '2026-02-01T08:30:00Z',
@@ -61,6 +65,8 @@ const unknownScopeToken = {
description: '',
read_only: false,
known: false,
plugin_id: '',
group: '',
},
],
expired: true,
@@ -90,6 +96,8 @@ const scopes = [
description: 'Everything',
read_only: false,
known: true,
plugin_id: '',
group: '',
},
{
name: 'admin:read',
@@ -97,6 +105,20 @@ const scopes = [
description: 'View everything',
read_only: true,
known: true,
plugin_id: '',
group: '',
},
]
const pluginOnlyScopes = [
{
name: 'acme',
label: 'Acme',
description: 'Manage Acme items.',
read_only: false,
known: true,
plugin_id: 'acme.blog',
group: 'Acme',
},
]
@@ -162,11 +184,6 @@ describe('ApiTokensPanel', () => {
nameInput.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
const getsBeforeCreate = requestsTo(calls, 'GET', TOKENS).length
await click('[data-action="create-token-submit"]', dialog()!)
const [post] = requestsTo(calls, 'POST', TOKENS)
@@ -370,36 +387,34 @@ describe('ApiTokensPanel', () => {
await flushPromises()
}
it('disables other scopes when * is checked and posts only ["*"]', async () => {
it('switches to Full (*) tier, shows scope_all_includes note, and posts only ["*"]', async () => {
const { calls } = await openCreateDialog()
await fillName('Full')
const star = dialog()!.querySelector<HTMLInputElement>('[data-scope="*"] input')!
star.checked = true
star.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
expect(dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!.disabled).toBe(true)
await click('[data-access-tier="full"]', dialog()!)
expect(dialog()!.textContent).toContain('Pełny dostęp obejmuje wszystkie pozostałe zakresy.')
await click('[data-action="create-token-submit"]', dialog()!)
const [post] = requestsTo(calls, 'POST', TOKENS)
expect(await post!.clone().json()).toEqual({ name: 'Full', expires: '90d', scopes: ['*'] })
})
it('keeps submit disabled until a scope is selected', async () => {
await openCreateDialog()
await fillName('No scope')
it('keeps submit disabled when Custom starts empty until a scope is applied', async () => {
await openCreateDialog({ [`GET ${SCOPES}`]: envelope(pluginOnlyScopes) })
await fillName('Scoped')
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(
true,
)
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
await click('[data-action="customize-scopes"]', dialog()!)
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="acme"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
await click('[data-action="scope-picker-apply"]', dialog()!)
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(
false,
)
})
it('renders a 422 on scopes and focuses the first scope checkbox', async () => {
it('renders a 422 on scopes and focuses the scope access control', async () => {
await openCreateDialog({
[`POST ${TOKENS}`]: {
status: 422,
@@ -413,13 +428,10 @@ describe('ApiTokensPanel', () => {
},
})
await fillName('Scoped')
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
await click('[data-action="create-token-submit"]', dialog()!)
expect(dialog()!.textContent).toContain('Wybierz co najmniej jeden zakres.')
expect(document.activeElement).toBe(dialog()!.querySelector('[data-scope="*"] input'))
expect(dialog()!.querySelector('[data-scope-summary]')!.getAttribute('aria-invalid')).toBe('true')
expect(document.activeElement).toBe(dialog()!.querySelector('[data-access-tier="read_only"]'))
})
it('shows Copied on clipboard success and copy_failed on rejection', async () => {
@@ -430,10 +442,6 @@ describe('ApiTokensPanel', () => {
})
await openCreateDialog()
await fillName('Copy me')
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
await click('[data-action="create-token-submit"]', dialog()!)
await click('[data-action="copy-token"]', dialog()!)
expect(writeText).toHaveBeenCalledWith(createdToken.token)
@@ -453,10 +461,6 @@ describe('ApiTokensPanel', () => {
it('asks before closing step 2 without a copy and keeps the step on cancel', async () => {
await openCreateDialog()
await fillName('Guard')
const scope = dialog()!.querySelector<HTMLInputElement>('[data-scope="admin:read"] input')!
scope.checked = true
scope.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
await click('[data-action="create-token-submit"]', dialog()!)
expect(dialog()!.querySelector('[data-token-plaintext]')).toBeTruthy()
keydown(dialog()!, 'Escape')

View File

@@ -1,5 +1,8 @@
{
"data": {
"backend::lang.api_tokens.access_level": {
"other": "Poziom dostępu"
},
"backend::lang.api_tokens.close_uncopied_confirm": {
"other": "Zamknąć bez kopiowania? Tego tokenu nie będzie można już zobaczyć."
},
@@ -90,6 +93,24 @@
"backend::lang.api_tokens.gone": {
"other": "Ten token już nie istnieje. Lista została odświeżona."
},
"backend::lang.api_tokens.group_clear": {
"other": "Wyczyść"
},
"backend::lang.api_tokens.group_clear_named": {
"other": "Wyczyść wybrane zakresy w grupie :group"
},
"backend::lang.api_tokens.group_select_all": {
"other": "Wszystkie"
},
"backend::lang.api_tokens.group_select_all_named": {
"other": "Zaznacz wszystkie zakresy w grupie :group"
},
"backend::lang.api_tokens.group_select_read": {
"other": "Odczyt"
},
"backend::lang.api_tokens.group_select_read_named": {
"other": "Zaznacz zakresy tylko do odczytu w grupie :group"
},
"backend::lang.api_tokens.hint": {
"other": "Token kończący się na :last4"
},
@@ -159,9 +180,117 @@
"backend::lang.api_tokens.scope_all_includes": {
"other": "Pełny dostęp obejmuje wszystkie pozostałe zakresy."
},
"backend::lang.api_tokens.scope_also_admin_read": {
"other": "Zezwól także na odczyt ze wszystkich pozostałych wtyczek"
},
"backend::lang.api_tokens.scope_also_admin_read_hint": {
"other": "Blokuje jako zaznaczone wszystkie poniższe zakresy tylko do odczytu. Pozostaw odznaczone, aby wykluczyć odczyt wybranych zasobów."
},
"backend::lang.api_tokens.scope_count": {
"one": ":count zakres",
"few": ":count zakresy",
"many": ":count zakresów",
"other": ":count zakresu"
},
"backend::lang.api_tokens.scope_customize": {
"other": "Dostosuj zakresy…"
},
"backend::lang.api_tokens.scope_empty_readonly_body": {
"other": "Przełącz na Wszystkie zakresy, aby zobaczyć dostępne zakresy zapisu."
},
"backend::lang.api_tokens.scope_empty_readonly_title": {
"other": "Brak zakresów tylko do odczytu na tej liście"
},
"backend::lang.api_tokens.scope_empty_search_body": {
"other": "Żadne wtyczki, grupy ani zakresy nie pasują do „:query”. Wyczyść wyszukiwanie lub wpisz inne słowo."
},
"backend::lang.api_tokens.scope_empty_search_title": {
"other": "Brak pasujących zakresów"
},
"backend::lang.api_tokens.scope_empty_selected_body": {
"other": "Przełącz na Wszystkie zakresy, aby wybrać uprawnienia."
},
"backend::lang.api_tokens.scope_empty_selected_title": {
"other": "Nie wybrano jeszcze żadnych zakresów"
},
"backend::lang.api_tokens.scope_filter_all": {
"other": "Wszystkie (:count)"
},
"backend::lang.api_tokens.scope_filter_label": {
"other": "Filtruj zakresy"
},
"backend::lang.api_tokens.scope_filter_read_only": {
"other": "Tylko odczyt (:count)"
},
"backend::lang.api_tokens.scope_filter_reset": {
"other": "Pokaż wszystkie zakresy"
},
"backend::lang.api_tokens.scope_filter_selected": {
"other": "Wybrane (:count)"
},
"backend::lang.api_tokens.scope_more": {
"other": "+:count więcej"
},
"backend::lang.api_tokens.scope_picker_apply": {
"other": "Zastosuj zakresy"
},
"backend::lang.api_tokens.scope_picker_back": {
"other": "Wróć do tokenu"
},
"backend::lang.api_tokens.scope_picker_description": {
"other": "Wybierz zakresy, których może używać ten token."
},
"backend::lang.api_tokens.scope_picker_discard": {
"other": "Odrzuć zmiany"
},
"backend::lang.api_tokens.scope_picker_none_selected": {
"other": "Wybierz co najmniej jeden zakres, aby zastosować."
},
"backend::lang.api_tokens.scope_picker_selected": {
"other": "Wybrano: :scopes"
},
"backend::lang.api_tokens.scope_picker_selected_admin_read": {
"other": "Cały odczyt + :scopes"
},
"backend::lang.api_tokens.scope_picker_title": {
"other": "Dostosuj zakresy"
},
"backend::lang.api_tokens.scope_plugin_count": {
"one": ":count wtyczce",
"few": ":count wtyczkach",
"many": ":count wtyczkach",
"other": ":count wtyczki"
},
"backend::lang.api_tokens.scope_search_clear": {
"other": "Wyczyść wyszukiwanie"
},
"backend::lang.api_tokens.scope_search_label": {
"other": "Szukaj zakresów"
},
"backend::lang.api_tokens.scope_search_placeholder": {
"other": "Szukaj wtyczek, grup lub zakresów…"
},
"backend::lang.api_tokens.scope_summary_admin_read_only": {
"other": "Tylko odczyt w całym panelu"
},
"backend::lang.api_tokens.scope_summary_admin_read_plus": {
"other": "Cały odczyt + :scopes w :plugins"
},
"backend::lang.api_tokens.scope_summary_empty": {
"other": "Nie wybrano jeszcze żadnych zakresów. Kliknij Dostosuj zakresy, aby określić dostęp."
},
"backend::lang.api_tokens.scope_summary_line": {
"other": ":scopes w :plugins"
},
"backend::lang.api_tokens.scope_unavailable": {
"other": "Zakres :name nie jest dla Ciebie dostępny."
},
"backend::lang.api_tokens.scope_write_count": {
"one": ":count zakres zapisu",
"few": ":count zakresy zapisu",
"many": ":count zakresów zapisu",
"other": ":count zakresu zapisu"
},
"backend::lang.api_tokens.scopes": {
"other": "Zakresy"
},
@@ -186,6 +315,15 @@
"backend::lang.api_tokens.state_revoked": {
"other": "Unieważniony"
},
"backend::lang.api_tokens.tier_custom": {
"other": "Własny"
},
"backend::lang.api_tokens.tier_full": {
"other": "Pełny (*)"
},
"backend::lang.api_tokens.tier_read_only": {
"other": "Tylko odczyt"
},
"backend::lang.api_tokens.token_label": {
"other": "Nowy token"
},
@@ -195,6 +333,9 @@
"backend::lang.api_tokens.unknown_scope_hint": {
"other": "Ten zakres nie jest już zarejestrowany i nic nie przyznaje."
},
"backend::lang.api_tokens.via_admin_read": {
"other": "przez admin:read"
},
"backend::lang.auth.invalid": {
"other": "Nieprawidłowe dane logowania"
},
@@ -438,6 +579,12 @@
"backend::lang.list.sort_descending": {
"other": "Sortuj malejąco"
},
"backend::lang.mcp_connect.scope_picker_description": {
"other": "Wybierz zakresy, których aplikacja :client może używać w Twoim imieniu."
},
"backend::lang.mcp_connect.subline": {
"other": "Agent otrzyma Twoje uprawnienia w granicach wybranego dostępu. Nigdy nie dostanie szerszego dostępu niż Twoje konto."
},
"backend::lang.messages.form.create": {
"other": "Nowy rekord"
},

View File

@@ -1,7 +1,8 @@
// Smoke tests of the MCP consent card (Phase 32.2 UI-SPEC C1): a signed-in
// administrator opens /connect?request=…, keeps the ticks and clicks Allow,
// and the browser leaves for the server-issued redirect_uri through
// window.location.assign, never through the router. Fixtures are neutral.
// Smoke tests of the MCP consent card (Phase 32.2 UI-SPEC C1 + Phase 36 C4):
// a signed-in administrator opens /connect?request=…, keeps the safe Read-only
// default and clicks Allow, and the browser leaves for the server-issued
// redirect_uri through window.location.assign, never through the router.
// Fixtures are neutral.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
import type { MCPConsent } from '../../src/api/types'
@@ -15,8 +16,24 @@ function consentView(overrides: Partial<MCPConsent> = {}): MCPConsent {
client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'agent.example.test', logo_url: '' },
admin: { login: 'dev', name: 'Dana Dev', email: 'dev@example.test' },
scopes: [
{ name: 'admin:read', label: 'Read the admin', description: 'Read every admin list.', read_only: true, known: true },
{ name: 'acme', label: 'Acme', description: 'Use the acme tools.', read_only: false, known: true },
{
name: 'admin:read',
label: 'Read the admin',
description: 'Read every admin list.',
read_only: true,
known: true,
plugin_id: '',
group: '',
},
{
name: 'acme',
label: 'Acme',
description: 'Use the acme tools.',
read_only: false,
known: true,
plugin_id: 'acme.blog',
group: 'Acme',
},
],
offline_access: true,
consent_required: true,
@@ -47,8 +64,8 @@ afterEach(() => {
enableAutoUnmount(afterEach)
describe('consent card (UI-SPEC C1)', () => {
it('Allow posts the ticked scopes and Stay connected, then leaves for redirect_uri without the router', async () => {
describe('consent card (UI-SPEC C1 / Phase 36 C4)', () => {
it('Allow defaults to Read-only (admin:read) and Stay connected, then leaves for redirect_uri without the router', async () => {
const { wrapper, calls, router } = await mountApp('/connect?request=req1', consentRoutes())
const push = vi.spyOn(router, 'push')
const replace = vi.spyOn(router, 'replace')
@@ -60,9 +77,8 @@ describe('consent card (UI-SPEC C1)', () => {
expect(wrapper.find('nav[aria-label="backend::lang.nav.plugins"]').exists()).toBe(false)
expect(card.find('[data-connect-host]').text()).toBe('agent.example.test')
const scopeBoxes = card.findAll('[data-scope] input[type="checkbox"]')
expect(scopeBoxes).toHaveLength(2)
expect(scopeBoxes.map((box) => (box.element as HTMLInputElement).checked)).toEqual([true, true])
expect(card.find('[data-access-tier="read_only"]').attributes('data-state')).toBe('checked')
expect(card.find('[data-scope-summary]').text()).toContain('admin:read')
const offline = card.find('[data-connect-offline] input[type="checkbox"]')
expect((offline.element as HTMLInputElement).checked).toBe(true)
@@ -75,7 +91,7 @@ describe('consent card (UI-SPEC C1)', () => {
const posts = requestsTo(calls, 'POST', `${API}/mcp/consent/req1`)
expect(posts).toHaveLength(1)
expect(posts[0]!.headers.get('X-Requested-With')).toBe('XMLHttpRequest')
expect(await posts[0]!.json()).toEqual({ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: true })
expect(await posts[0]!.json()).toEqual({ decision: 'allow', scopes: ['admin:read'], offline_access: true })
expect(assign).toHaveBeenCalledWith(REDIRECT)
for (const spy of [push, replace]) {
expect(spy).not.toHaveBeenCalledWith(REDIRECT)

View File

@@ -1,12 +1,12 @@
// Unit tests of the MCP consent card (Phase 32.2 UI-SPEC C1) and its UI
// backstops: the * rule, no auto-allow, the decision navigation through
// window.location.assign (never the router), forbidden redirect schemes, the
// switch-account round trip, every C1 state and the focus rules. Fixtures
// are neutral acme.* data; no application names appear in framework tests.
// Unit tests of the MCP consent card (Phase 32.2 UI-SPEC C1 + Phase 36 C4) and
// its UI backstops: 3-tier access control, no auto-allow, the decision
// navigation through window.location.assign (never the router), forbidden
// redirect schemes, the switch-account round trip, every state and focus rules.
// Fixtures are neutral acme.* data; no application names appear in framework tests.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
import { setBundle, t } from '../../src/app/i18n'
import type { MCPConsent } from '../../src/api/types'
import type { AdminAPITokenScope, MCPConsent } from '../../src/api/types'
import { currentUser } from '../../src/state/useAuth'
import { langFixture } from '../fixtures/typed'
import { API, mountApp, notFound, requestsTo, resetState, type Reply, type Route } from '../helpers'
@@ -22,9 +22,33 @@ const strings = {
'backend::lang.mcp_connect.heading': { other: 'Allow :client to use your account?' },
}
const SCOPE_ALL = { name: '*', label: 'Full access', description: 'Everything you can do.', read_only: false, known: true }
const SCOPE_READ = { name: 'admin:read', label: 'Read the admin', description: 'Read every admin list.', read_only: true, known: true }
const SCOPE_ACME = { name: 'acme', label: 'Acme', description: 'Use the acme tools.', read_only: false, known: true }
const SCOPE_ALL: AdminAPITokenScope = {
name: '*',
label: 'Full access',
description: 'Everything you can do.',
read_only: false,
known: true,
plugin_id: '',
group: '',
}
const SCOPE_READ: AdminAPITokenScope = {
name: 'admin:read',
label: 'Read the admin',
description: 'Read every admin list.',
read_only: true,
known: true,
plugin_id: '',
group: '',
}
const SCOPE_ACME: AdminAPITokenScope = {
name: 'acme',
label: 'Acme',
description: 'Use the acme tools.',
read_only: false,
known: true,
plugin_id: 'acme.blog',
group: 'Acme',
}
function consentView(overrides: Partial<MCPConsent> = {}): MCPConsent {
return {
@@ -40,9 +64,15 @@ function consentView(overrides: Partial<MCPConsent> = {}): MCPConsent {
}
const ok = (data: unknown): Reply => ({ body: { data, meta: {} } })
const failure = (status: number, code: string): Reply => ({ status, body: { error: { code, message: code, details: {} } } })
const failure = (status: number, code: string): Reply => ({
status,
body: { error: { code, message: code, details: {} } },
})
function routes(view: MCPConsent | Route = consentView(), decide: Route = ok({ redirect_uri: REDIRECT })): Record<string, Route> {
function routes(
view: MCPConsent | Route = consentView(),
decide: Route = ok({ redirect_uri: REDIRECT }),
): Record<string, Route> {
return {
[`GET ${CONSENT}`]: typeof view === 'function' || 'body' in view ? (view as Route) : ok(view),
[`POST ${CONSENT}`]: decide,
@@ -71,16 +101,18 @@ async function open(path = '/connect?request=req1', r: Record<string, Route> = r
return { ...mounted, push: vi.spyOn(mounted.router, 'push'), replace: vi.spyOn(mounted.router, 'replace') }
}
function boxes(wrapper: VueWrapper) {
return wrapper.findAll('[data-scope] input[type="checkbox"]').map((box) => box.element as HTMLInputElement)
const pickerDialog = () => document.body.querySelector<HTMLElement>('[data-scope-picker-dialog]')
async function clickTier(tier: 'full' | 'read_only' | 'custom'): Promise<void> {
document.body.querySelector<HTMLElement>(`[data-access-tier="${tier}"]`)?.click()
await flushPromises()
}
function box(wrapper: VueWrapper, name: string) {
return wrapper.find(`[data-scope="${name}"] input[type="checkbox"]`)
}
async function tick(wrapper: VueWrapper, name: string, on: boolean) {
await box(wrapper, name).setValue(on)
async function tickPickerScope(name: string, on: boolean): Promise<void> {
const input = pickerDialog()!.querySelector<HTMLInputElement>(`[data-scope="${name}"] input[type="checkbox"]`)!
input.checked = on
input.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
}
async function postedBodies(calls: Request[]) {
@@ -97,21 +129,28 @@ function expectRouterUntouched(...spies: Array<{ mock: { calls: unknown[][] } }>
}
describe('ready state', () => {
it('lists the returned scopes in order with the read-only pill, the host and Stay connected ticked', async () => {
it('defaults to Read-only (admin:read) with the read-only pill, the host and Stay connected ticked', async () => {
const { wrapper } = await open()
const card = wrapper.find('[data-connect-state="ready"]')
expect(card.exists()).toBe(true)
expect(card.find('h1').text()).toBe('Allow Acme Agent to use your account?')
expect(wrapper.findAll('[data-scope]').map((row) => row.attributes('data-scope'))).toEqual(['admin:read', 'acme'])
expect(boxes(wrapper).map((b) => b.checked)).toEqual([true, true])
expect(wrapper.find('[data-scope="admin:read"]').text()).toContain(t('backend::lang.api_tokens.read_only'))
expect(wrapper.find('[data-scope="acme"]').text()).not.toContain(t('backend::lang.api_tokens.read_only'))
expect(card.findAll('[data-access-tier]').map((item) => item.attributes('data-access-tier'))).toEqual([
'read_only',
'custom',
])
expect(card.find('[data-access-tier="read_only"]').attributes('data-state')).toBe('checked')
expect(card.find('[data-scope-summary]').text()).toContain('Read the admin')
expect(card.find('[data-scope-summary]').text()).toContain('admin:read')
expect(card.find('[data-scope-summary]').text()).toContain(t('backend::lang.api_tokens.read_only'))
expect(card.find('[data-connect-host]').text()).toBe('agent.example.test')
expect(card.find('[data-connect-admin]').text()).toBe('Dana Dev (dev@example.test)')
expect((card.find('[data-connect-offline] input').element as HTMLInputElement).checked).toBe(true)
expect(card.find('[data-previously-allowed]').exists()).toBe(false)
// Deny on the left, Allow on the right.
expect(card.findAll('[data-action="deny"], [data-action="allow"]').map((b) => b.attributes('data-action'))).toEqual(['deny', 'allow'])
expect(card.findAll('[data-action="deny"], [data-action="allow"]').map((b) => b.attributes('data-action'))).toEqual([
'deny',
'allow',
])
expect(card.find('[data-action="allow"]').attributes('type')).toBe('submit')
})
@@ -153,52 +192,56 @@ describe('ready state', () => {
})
})
describe('the * rule (UI backstop)', () => {
it('starts with * unticked, clears and disables the others when ticked, posts ["*"] and re-enables them when unticked', async () => {
const { wrapper, calls } = await open('/connect?request=req1', routes(consentView({ scopes: [SCOPE_ALL, SCOPE_READ, SCOPE_ACME] })))
expect(boxes(wrapper).map((b) => b.checked)).toEqual([false, true, true])
describe('the 3-tier access control & Customize modal (UI backstop)', () => {
it('defaults to Read-only when * is also offered, switches to Full (*) with note, and posts ["*"]', async () => {
const { wrapper, calls } = await open(
'/connect?request=req1',
routes(consentView({ scopes: [SCOPE_ALL, SCOPE_READ, SCOPE_ACME] })),
)
expect(wrapper.find('[data-access-tier="read_only"]').attributes('data-state')).toBe('checked')
expect(wrapper.find('[data-scope-all-note]').exists()).toBe(false)
await tick(wrapper, '*', true)
expect(boxes(wrapper).map((b) => b.checked)).toEqual([true, false, false])
expect(boxes(wrapper).map((b) => b.disabled)).toEqual([false, true, true])
expect(wrapper.find('[data-scope="acme"]').classes()).toContain('cursor-not-allowed')
await clickTier('full')
expect(wrapper.find('[data-access-tier="full"]').attributes('data-state')).toBe('checked')
expect(wrapper.find('[data-scope-all-note]').text()).toBe(t('backend::lang.api_tokens.scope_all_includes'))
// Unticking * re-enables the others with their previous ticks cleared.
await tick(wrapper, '*', false)
expect(boxes(wrapper).map((b) => b.checked)).toEqual([false, false, false])
expect(boxes(wrapper).map((b) => b.disabled)).toEqual([false, false, false])
expect(wrapper.find('[data-scope-all-note]').exists()).toBe(false)
expect(wrapper.find('[data-action="allow"]').attributes('disabled')).toBeDefined()
await tick(wrapper, '*', true)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['*'], offline_access: true }])
})
it('ticks * from the start when it is the only scope shown', async () => {
it('starts on Full (*) when * is the only scope shown', async () => {
const { wrapper } = await open('/connect?request=req1', routes(consentView({ scopes: [SCOPE_ALL] })))
expect(boxes(wrapper).map((b) => b.checked)).toEqual([true])
expect(wrapper.find('[data-access-tiers]').exists()).toBe(false)
expect(wrapper.find('[data-scope-all-note]').exists()).toBe(true)
})
it('posts the ticked names in catalog order and keeps Allow disabled with nothing ticked', async () => {
const { wrapper, calls } = await open('/connect?request=req1', routes(consentView({ scopes: [SCOPE_ALL, SCOPE_READ, SCOPE_ACME] })))
await tick(wrapper, 'admin:read', false)
await tick(wrapper, 'acme', false)
const allow = wrapper.find('[data-action="allow"]')
expect(allow.attributes('disabled')).toBeDefined()
it('opens Custom modal when empty, requires >=1 scope to apply, and posts selected scopes in catalog order', async () => {
const { wrapper, calls } = await open(
'/connect?request=req1',
routes(consentView({ scopes: [SCOPE_ALL, SCOPE_READ, SCOPE_ACME] })),
)
await clickTier('custom')
expect(pickerDialog()).toBeTruthy()
expect(pickerDialog()!.querySelector<HTMLButtonElement>('[data-action="scope-picker-apply"]')!.disabled).toBe(true)
await tickPickerScope('acme', true)
const adminRead = pickerDialog()!.querySelector<HTMLInputElement>('[data-admin-read-checkbox]')!
adminRead.checked = true
adminRead.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
const apply = pickerDialog()!.querySelector<HTMLButtonElement>('[data-action="scope-picker-apply"]')!
expect(apply.disabled).toBe(false)
apply.click()
await flushPromises()
expect(pickerDialog()).toBeNull()
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
await tick(wrapper, 'acme', true)
await tick(wrapper, 'admin:read', true)
expect(allow.attributes('disabled')).toBeUndefined()
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: true }])
expect(await postedBodies(calls)).toEqual([
{ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: true },
])
})
})
@@ -225,14 +268,17 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
await flushPromises()
const [post] = requestsTo(calls, 'POST', CONSENT)
expect(post!.headers.get('X-Requested-With')).toBe('XMLHttpRequest')
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: false }])
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['admin:read'], offline_access: false }])
expect(assign).toHaveBeenCalledTimes(1)
expect(assign).toHaveBeenCalledWith(REDIRECT)
expectRouterUntouched(push, replace)
})
it('Deny posts the documented body and leaves through window.location.assign', async () => {
const { wrapper, calls, push, replace } = await open('/connect?request=req1', routes(consentView(), ok({ redirect_uri: DENIED })))
const { wrapper, calls, push, replace } = await open(
'/connect?request=req1',
routes(consentView(), ok({ redirect_uri: DENIED })),
)
await wrapper.find('[data-action="deny"]').trigger('click')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'deny', scopes: [], offline_access: false }])
@@ -245,7 +291,7 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
expect(wrapper.find('[data-connect-offline]').exists()).toBe(false)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: false }])
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['admin:read'], offline_access: false }])
})
it('switches to Returning with a continue link for a web URI only', async () => {
@@ -258,8 +304,13 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
expect(wrapper.find('[data-action="allow"]').exists()).toBe(false)
expect(document.activeElement).toBe(card.find('h1').element)
const customView = consentView({ client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'myagent:/callback', logo_url: '' } })
const custom = await open('/connect?request=req1', routes(customView, ok({ redirect_uri: 'myagent:/callback?code=1' })))
const customView = consentView({
client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'myagent:/callback', logo_url: '' },
})
const custom = await open(
'/connect?request=req1',
routes(customView, ok({ redirect_uri: 'myagent:/callback?code=1' })),
)
await custom.wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).toHaveBeenLastCalledWith('myagent:/callback?code=1')
@@ -269,7 +320,9 @@ describe('no auto-allow and the decision navigation (UI backstop)', () => {
})
it('leaves for a redirect whose host matches the shown one as the browser compares hosts', async () => {
const view = consentView({ client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'Agent.Example.Test:443', logo_url: '' } })
const view = consentView({
client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'Agent.Example.Test:443', logo_url: '' },
})
const { wrapper } = await open('/connect?request=req1', routes(view))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
@@ -313,31 +366,34 @@ describe('submit failures', () => {
'https://agent.example.test.evil.example/callback?code=abc123',
'https://agent.example.test:8443/callback?code=abc123',
'myagent:/callback?code=1',
])(
'treats the redirect %j as a submit failure',
async (uri) => {
const { wrapper, push, replace } = await open('/connect?request=req1', routes(consentView(), ok({ redirect_uri: uri })))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).not.toHaveBeenCalled()
expect(wrapper.find('[data-connect-state="ready"]').exists()).toBe(true)
const alert = wrapper.find('[data-connect-error="decide_failed"]')
expect(alert.attributes('role')).toBe('alert')
expect(document.activeElement).toBe(alert.element)
expect(push).not.toHaveBeenCalled()
expect(replace).not.toHaveBeenCalled()
},
)
])('treats the redirect %j as a submit failure', async (uri) => {
const { wrapper, push, replace } = await open(
'/connect?request=req1',
routes(consentView(), ok({ redirect_uri: uri })),
)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).not.toHaveBeenCalled()
expect(wrapper.find('[data-connect-state="ready"]').exists()).toBe(true)
const alert = wrapper.find('[data-connect-error="decide_failed"]')
expect(alert.attributes('role')).toBe('alert')
expect(document.activeElement).toBe(alert.element)
expect(push).not.toHaveBeenCalled()
expect(replace).not.toHaveBeenCalled()
})
it('422 on Allow shows scopes required and keeps the ticks', async () => {
const { wrapper } = await open('/connect?request=req1', routes(consentView(), failure(422, 'no_grantable_scopes')))
it('422 on Allow shows scopes required, marks summary invalid and clears on selection change', async () => {
const { wrapper } = await open(
'/connect?request=req1',
routes(consentView({ scopes: [SCOPE_ALL, SCOPE_READ, SCOPE_ACME] }), failure(422, 'no_grantable_scopes')),
)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(wrapper.find('[data-connect-error="scopes_required"]').exists()).toBe(true)
expect(wrapper.find('[data-scope-picker]').attributes('aria-invalid')).toBe('true')
expect(boxes(wrapper).map((b) => b.checked)).toEqual([true, true])
// Changing a tick clears the error.
await tick(wrapper, 'acme', false)
expect(wrapper.find('[data-scope-summary]').attributes('aria-invalid')).toBe('true')
expect(wrapper.find('[data-access-tier="read_only"]').attributes('data-state')).toBe('checked')
// Changing the selected tier clears the error.
await clickTier('full')
expect(wrapper.find('[data-connect-error="scopes_required"]').exists()).toBe(false)
})
@@ -367,7 +423,10 @@ describe('submit failures', () => {
})
it('401 on submit expires the session and returns to login with the request', async () => {
const { wrapper, router } = await open('/connect?request=req1', routes(consentView(), failure(401, 'unauthenticated')))
const { wrapper, router } = await open(
'/connect?request=req1',
routes(consentView(), failure(401, 'unauthenticated')),
)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(currentUser.value).toBeNull()
@@ -400,7 +459,10 @@ describe('other states', () => {
for (const path of ['/connect', '/connect?request=', '/connect?request=%20']) {
const { wrapper, calls } = await open(path)
expect(wrapper.find('[data-connect-state="expired"]').exists(), path).toBe(true)
expect(calls.filter((request) => new URL(request.url).pathname.startsWith(`${API}/mcp/consent`)), path).toHaveLength(0)
expect(
calls.filter((request) => new URL(request.url).pathname.startsWith(`${API}/mcp/consent`)),
path,
).toHaveLength(0)
wrapper.unmount()
}
})
@@ -436,10 +498,13 @@ describe('other states', () => {
})
it('offers only Deny, full width, when no scope is grantable', async () => {
const { wrapper, calls } = await open('/connect?request=req1', routes(consentView({ scopes: [] }), ok({ redirect_uri: DENIED })))
const { wrapper, calls } = await open(
'/connect?request=req1',
routes(consentView({ scopes: [] }), ok({ redirect_uri: DENIED })),
)
const card = wrapper.find('[data-connect-state="ready"]')
expect(card.find('[data-connect-none-grantable]').attributes('role')).toBe('alert')
expect(card.find('[data-scope-picker]').exists()).toBe(false)
expect(card.find('[data-scope-summary]').exists()).toBe(false)
expect(card.find('[data-connect-offline]').exists()).toBe(false)
expect(card.find('[data-action="allow"]').exists()).toBe(false)
expect(card.find('[data-action="deny"]').classes()).toContain('flex-1')
@@ -456,7 +521,12 @@ describe('other states', () => {
const other = `${API}/mcp/consent/req2`
const { wrapper, router } = await open('/connect?request=req1', {
...routes(),
[`GET ${other}`]: ok(consentView({ request_id: 'req2', client: { id: 'c2', name: 'Other Agent', redirect_host: 'other.example.test', logo_url: '' } })),
[`GET ${other}`]: ok(
consentView({
request_id: 'req2',
client: { id: 'c2', name: 'Other Agent', redirect_host: 'other.example.test', logo_url: '' },
}),
),
})
await router.push('/connect?request=req2')
await flushPromises()