Files
summercms/admin/tests/views/ConnectView.test.ts

565 lines
25 KiB
TypeScript

// 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 } from '@vue/test-utils'
import { setBundle, t } from '../../src/app/i18n'
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'
const CONSENT = `${API}/mcp/consent/req1`
const REDIRECT = 'https://agent.example.test/callback?code=abc123&state=xyz'
const DENIED = 'https://agent.example.test/callback?error=access_denied&state=xyz'
const strings = {
'backend::lang.mcp_connect.admin_with_email': { other: ':name (:email)' },
'backend::lang.mcp_connect.returning': { other: 'Returning to :host' },
'backend::lang.mcp_connect.continue': { other: 'Continue to :host' },
'backend::lang.mcp_connect.heading': { other: 'Allow :client to use your account?' },
}
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 {
request_id: 'req1',
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: [SCOPE_READ, SCOPE_ACME],
offline_access: true,
consent_required: true,
expires_at: '2026-11-21T12:00:00Z',
...overrides,
}
}
const ok = (data: unknown): Reply => ({ body: { data, meta: {} } })
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> {
return {
[`GET ${CONSENT}`]: typeof view === 'function' || 'body' in view ? (view as Route) : ok(view),
[`POST ${CONSENT}`]: decide,
[`POST ${API}/auth/logout`]: ok({}),
}
}
let assign: ReturnType<typeof vi.fn>
beforeEach(() => {
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
assign = vi.fn()
vi.spyOn(window.location, 'assign').mockImplementation(assign)
})
afterEach(() => {
vi.restoreAllMocks()
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
async function open(path = '/connect?request=req1', r: Record<string, Route> = routes()) {
const mounted = await mountApp(path, r, { attach: true })
return { ...mounted, push: vi.spyOn(mounted.router, 'push'), replace: vi.spyOn(mounted.router, 'replace') }
}
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()
}
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[]) {
return Promise.all(requestsTo(calls, 'POST', CONSENT).map((request) => request.clone().json()))
}
/** The router never sees the server's redirect URI. */
function expectRouterUntouched(...spies: Array<{ mock: { calls: unknown[][] } }>) {
for (const spy of spies) {
for (const call of spy.mock.calls) {
expect(JSON.stringify(call)).not.toContain('agent.example.test')
}
}
}
describe('ready state', () => {
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(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.find('[data-action="allow"]').attributes('type')).toBe('submit')
})
it('shows a same-origin or https logo and the bot mark otherwise', async () => {
for (const [logo, shown] of [
['/storage/logo.png', true],
['https://agent.example.test/logo.png', true],
['http://agent.example.test/logo.png', false],
['//evil.example/logo.png', false],
['javascript:alert(1)', false],
] as const) {
const { wrapper } = await open(
'/connect?request=req1',
routes(consentView({ client: { id: 'c', name: 'Acme Agent', redirect_host: 'agent.example.test', logo_url: logo } })),
)
const img = wrapper.find('[data-connect-state="ready"] img')
expect(img.exists(), logo).toBe(shown)
if (shown) {
expect(img.attributes('src')).toBe(logo)
expect(img.attributes('alt')).toBe('')
}
wrapper.unmount()
}
})
it('falls back to the client id and to the signed-in profile', async () => {
const { wrapper } = await open(
'/connect?request=req1',
routes(
consentView({
client: { id: 'client-1', name: '', redirect_host: 'agent.example.test', logo_url: '' },
admin: { login: '', name: '', email: '' },
}),
),
)
expect(currentUser.value?.login).toBe('dev')
expect(wrapper.find('h1').text()).toBe('Allow client-1 to use your account?')
expect(wrapper.find('[data-connect-admin]').text()).toBe('Dana Dev (dev@example.test)')
})
})
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 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'))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'allow', scopes: ['*'], offline_access: true }])
})
it('starts on Full (*) when * is the only scope shown', async () => {
const { wrapper } = await open('/connect?request=req1', routes(consentView({ scopes: [SCOPE_ALL] })))
expect(wrapper.find('[data-access-tiers]').exists()).toBe(false)
expect(wrapper.find('[data-scope-all-note]').exists()).toBe(true)
})
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(await postedBodies(calls)).toEqual([
{ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: true },
])
})
})
describe('no auto-allow and the decision navigation (UI backstop)', () => {
it('posts nothing on mount for a client allowed before, and focuses neither button', async () => {
const { wrapper, calls } = await open('/connect?request=req1', routes(consentView({ consent_required: false })))
await flushPromises()
expect(wrapper.find('[data-previously-allowed]').exists()).toBe(true)
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
expect(assign).not.toHaveBeenCalled()
const active = document.activeElement as HTMLElement | null
expect(active?.getAttribute('data-action')).not.toBe('allow')
expect(active?.getAttribute('data-action')).not.toBe('deny')
// No hotkey: Enter on the page does not submit.
document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
await flushPromises()
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
})
it('Allow posts the documented body and leaves through window.location.assign, never the router', async () => {
const { wrapper, calls, push, replace } = await open()
await wrapper.find('[data-connect-offline] input').setValue(false)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
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'], 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 })),
)
await wrapper.find('[data-action="deny"]').trigger('click')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'deny', scopes: [], offline_access: false }])
expect(assign).toHaveBeenCalledWith(DENIED)
expectRouterUntouched(push, replace)
})
it('posts offline_access false when the client did not ask for it', async () => {
const { wrapper, calls } = await open('/connect?request=req1', routes(consentView({ offline_access: false })))
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'], offline_access: false }])
})
it('switches to Returning with a continue link for a web URI only', async () => {
const { wrapper } = await open()
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
const card = wrapper.find('[data-connect-state="returning"]')
expect(card.find('h1').text()).toBe('Returning to agent.example.test')
expect(card.find('[data-connect-continue]').attributes('href')).toBe(REDIRECT)
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' })),
)
await custom.wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).toHaveBeenLastCalledWith('myagent:/callback?code=1')
const returning = custom.wrapper.find('[data-connect-state="returning"]')
expect(returning.find('[data-connect-continue]').exists()).toBe(false)
expect(returning.find('h1').text()).toBe('Returning to myagent:/callback')
})
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 { wrapper } = await open('/connect?request=req1', routes(view))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(assign).toHaveBeenCalledWith(REDIRECT)
})
it('disables both buttons and the scopes while a decision is in flight', async () => {
let release: ((reply: Reply) => void) | null = null
const { wrapper, calls } = await open(
'/connect?request=req1',
routes(consentView(), () => new Promise<Reply>((resolve) => (release = resolve))),
)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(wrapper.find('[data-action="allow"]').attributes('disabled')).toBeDefined()
expect(wrapper.find('[data-action="deny"]').attributes('disabled')).toBeDefined()
expect(wrapper.find('[data-action="switch-account"]').attributes('disabled')).toBeDefined()
expect(wrapper.find('fieldset').attributes('disabled')).toBeDefined()
expect(wrapper.find('[data-action="allow"]').text()).toBe('backend::lang.mcp_connect.allowing')
await wrapper.find('[data-action="deny"]').trigger('click')
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
release!(ok({ redirect_uri: REDIRECT }))
await flushPromises()
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(1)
expect(assign).toHaveBeenCalledTimes(1)
})
})
describe('submit failures', () => {
it.each([
'javascript:alert(1)',
'data:text/html,<script>x</script>',
'vbscript:msgbox(1)',
'JavaScript:alert(1)',
'not a uri',
'blob:https://agent.example.test/0b7c',
'file:///etc/passwd',
'about:blank',
'filesystem:https://agent.example.test/temporary/x',
'https://evil.example.test/callback?code=abc123',
'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()
})
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-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)
})
it('422 on Deny and a 5xx are decide failures', async () => {
const deny = await open('/connect?request=req1', routes(consentView(), failure(422, 'unprocessable')))
await deny.wrapper.find('[data-action="deny"]').trigger('click')
await flushPromises()
expect(deny.wrapper.find('[data-connect-error="decide_failed"]').exists()).toBe(true)
expect(deny.wrapper.find('[data-connect-error="scopes_required"]').exists()).toBe(false)
deny.wrapper.unmount()
const broken = await open('/connect?request=req1', routes(consentView(), failure(500, 'server_error')))
await broken.wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(broken.wrapper.find('[data-connect-error="decide_failed"]').exists()).toBe(true)
expect(assign).not.toHaveBeenCalled()
})
it('404 on submit shows Expired and moves focus to its heading', async () => {
const { wrapper } = await open('/connect?request=req1', routes(consentView(), { status: 404, body: notFound }))
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
const card = wrapper.find('[data-connect-state="expired"]')
expect(card.exists()).toBe(true)
expect(document.activeElement).toBe(card.find('h1').element)
expect(assign).not.toHaveBeenCalled()
})
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')),
)
await wrapper.find('[data-connect-state="ready"]').trigger('submit')
await flushPromises()
expect(currentUser.value).toBeNull()
expect(router.currentRoute.value.name).toBe('login')
expect(router.currentRoute.value.query.redirect).toBe('/connect?request=req1')
expect(assign).not.toHaveBeenCalled()
})
})
describe('other states', () => {
it('shows the loading skeleton without buttons until the request answers', async () => {
let release: ((reply: Reply) => void) | null = null
const { wrapper, calls } = await open(
'/connect?request=req1',
routes(() => new Promise<Reply>((resolve) => (release = resolve))),
)
const loading = wrapper.find('[data-connect-state="loading"]')
expect(loading.attributes('aria-busy')).toBe('true')
expect(loading.find('h1').classes()).toContain('sr-only')
expect(wrapper.findAll('button')).toHaveLength(0)
release!(ok(consentView()))
await flushPromises()
expect(wrapper.find('[data-connect-state="ready"]').exists()).toBe(true)
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
// The first settled render never moves focus.
expect(document.activeElement).toBe(document.body)
})
it('goes straight to Expired without a request parameter and without a call', async () => {
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)
wrapper.unmount()
}
})
it('shows Expired with a link home for a 404 on load', async () => {
const { wrapper } = await open('/connect?request=req1', routes({ status: 404, body: notFound }))
const card = wrapper.find('[data-connect-state="expired"]')
expect(card.find('h1').text()).toBe('backend::lang.mcp_connect.expired_heading')
expect(card.find('[data-action="open-admin"]').attributes('href')).toBe('/')
})
it('shows the load error and loads again on Try again', async () => {
let loads = 0
const { wrapper } = await open(
'/connect?request=req1',
routes(() => (++loads === 1 ? failure(500, 'server_error') : ok(consentView()))),
)
const card = wrapper.find('[data-connect-state="load-error"]')
expect(card.find('[role="alert"]').text()).toBe('backend::lang.mcp_connect.load_failed')
await card.find('[data-action="retry"]').trigger('click')
await flushPromises()
expect(loads).toBe(2)
const ready = wrapper.find('[data-connect-state="ready"]')
expect(ready.exists()).toBe(true)
expect(document.activeElement).toBe(ready.find('h1').element)
})
it('401 on load expires the session', async () => {
const { router } = await open('/connect?request=req1', routes(failure(401, 'unauthenticated')))
expect(currentUser.value).toBeNull()
expect(router.currentRoute.value.name).toBe('login')
expect(router.currentRoute.value.query.redirect).toBe('/connect?request=req1')
})
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 card = wrapper.find('[data-connect-state="ready"]')
expect(card.find('[data-connect-none-grantable]').attributes('role')).toBe('alert')
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')
await card.trigger('submit')
await flushPromises()
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
await card.find('[data-action="deny"]').trigger('click')
await flushPromises()
expect(await postedBodies(calls)).toEqual([{ decision: 'deny', scopes: [], offline_access: false }])
expect(assign).toHaveBeenCalledWith(DENIED)
})
it('loads again when the request parameter changes', async () => {
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: '' },
}),
),
})
await router.push('/connect?request=req2')
await flushPromises()
expect(wrapper.find('h1').text()).toBe('Allow Other Agent to use your account?')
expect(wrapper.find('[data-connect-host]').text()).toBe('other.example.test')
})
})
describe('Use another account (UI backstop)', () => {
it('signs out, then replaces to login with the current /connect?request= as redirect', async () => {
const { wrapper, calls, router, replace } = await open()
await wrapper.find('[data-action="switch-account"]').trigger('click')
await flushPromises()
const logout = requestsTo(calls, 'POST', `${API}/auth/logout`)
expect(logout).toHaveLength(1)
expect(requestsTo(calls, 'POST', CONSENT)).toHaveLength(0)
expect(replace).toHaveBeenCalledWith({ name: 'login', query: { redirect: '/connect?request=req1' } })
expect(router.currentRoute.value.name).toBe('login')
expect(router.currentRoute.value.query.redirect).toBe('/connect?request=req1')
expect(currentUser.value).toBeNull()
expect(wrapper.find('[data-login-hint]').exists()).toBe(true)
expect(assign).not.toHaveBeenCalled()
})
it('still reaches login when the logout call fails', async () => {
const { wrapper, router } = await open('/connect?request=req1', {
...routes(),
[`POST ${API}/auth/logout`]: failure(500, 'server_error'),
})
await wrapper.find('[data-action="switch-account"]').trigger('click')
await flushPromises()
expect(router.currentRoute.value.name).toBe('login')
expect(router.currentRoute.value.query.redirect).toBe('/connect?request=req1')
})
})