diff --git a/admin/tests/account/AccountContributions.test.ts b/admin/tests/account/AccountContributions.test.ts index 1943fbd0..8d92a6fb 100644 --- a/admin/tests/account/AccountContributions.test.ts +++ b/admin/tests/account/AccountContributions.test.ts @@ -236,3 +236,161 @@ describe('My account contributions', () => { expect(toasts.value.map((toast) => toast.text)).toEqual(['This action no longer applies.']) }) }) + +// Phase 32.2 UI-SPEC C3: per-item rows and item actions, additive to the +// sections above. +describe('My account item rows (32.2)', () => { + const itemStrings = { + ...strings, + 'backend::lang.myaccount.items_empty': { other: 'Nothing here yet.' }, + 'backend::lang.myaccount.item_action_named': { other: ':action: :title' }, + 'backend::lang.myaccount.item_gone': { other: 'This item is already gone.' }, + } + const itemPath = (item: string, action: string) => + `${API}/account/contribution-items/agents/${encodeURIComponent(item)}/actions/${action}` + + const agents = { + name: 'agents', + label: 'Connected agents', + description: 'Agents you connected.', + status: 'Connector address: https://example.test/mcp', + actions: [], + items: [ + { id: 'client:1', title: 'Acme Agent', subtitle: 'Read the admin, Acme', meta: ['Connected 2026-11-01', 'Never used'] }, + { id: 'client:2', title: 'Bold Agent', subtitle: '', meta: [] }, + ], + item_actions: [ + { name: 'rename', label: 'Rename', confirm: '', danger: false }, + { name: 'revoke', label: 'Revoke', confirm: 'Revoke the connection “:title”?', danger: true }, + ], + items_empty: '', + } + + beforeEach(() => { + setBundle({ ...langFixture.data, ...itemStrings }, 'en') + }) + + it('a section with items null renders exactly as before', async () => { + const legacy = { ...sections[0], items: null, item_actions: null, items_empty: '' } + const before = await openAccount({ [`GET ${CONTRIBUTIONS}`]: envelope([sections[0]]) }) + const beforeHtml = before.wrapper.find('[data-account-contribution="site_link"]').html() + before.wrapper.unmount() + const after = await openAccount({ [`GET ${CONTRIBUTIONS}`]: envelope([legacy]) }) + const card = after.wrapper.find('[data-account-contribution="site_link"]') + expect(card.html()).toBe(beforeHtml) + expect(card.find('[data-account-contribution-status]').text()).toBe('Not linked') + expect(card.find('[data-account-contribution-action="open"]').exists()).toBe(true) + expect(card.find('[role="list"]').exists()).toBe(false) + expect(card.find('[data-account-items-empty]').exists()).toBe(false) + }) + + it('items [] renders the empty block with the section text or the default', async () => { + const { wrapper } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([ + { ...agents, items: [] }, + { ...agents, name: 'other', items: [], items_empty: 'No agents connected yet.' }, + ]), + }) + const [first, second] = wrapper.findAll('[data-account-items-empty]') + expect(first!.text()).toBe('Nothing here yet.') + expect(second!.text()).toBe('No agents connected yet.') + expect(wrapper.find('[data-account-item]').exists()).toBe(false) + expect(wrapper.find('[data-account-contribution="agents"] [data-account-contribution-status]').exists()).toBe(true) + }) + + it('renders one row per item with its text and one button per item action', async () => { + const { wrapper } = await openAccount({ [`GET ${CONTRIBUTIONS}`]: envelope([agents]) }) + const rows = wrapper.findAll('[data-account-item]') + expect(rows.map((row) => row.attributes('data-account-item'))).toEqual(['client:1', 'client:2']) + expect(rows.every((row) => row.attributes('role') === 'listitem')).toBe(true) + expect(rows[0]!.text()).toContain('Read the admin, Acme') + expect(rows[0]!.text()).toContain('Connected 2026-11-01 · Never used') + // Text, never HTML. + expect(rows[1]!.find('b').exists()).toBe(false) + expect(rows[1]!.text()).toContain('Bold Agent') + const buttons = rows[0]!.findAll('[data-account-item-action]') + expect(buttons.map((button) => button.attributes('data-account-item-action'))).toEqual(['rename', 'revoke']) + expect(buttons.map((button) => button.attributes('aria-label'))).toEqual(['Rename: Acme Agent', 'Revoke: Acme Agent']) + expect(buttons[0]!.find('svg').exists()).toBe(false) + expect(buttons[1]!.find('svg').exists()).toBe(true) + }) + + it('a section with error: true shows the error line instead of rows or the empty block', async () => { + setBundle({ ...langFixture.data, ...itemStrings, 'backend::lang.myaccount.section_error': { other: 'This section could not be loaded.' } }, 'en') + const { wrapper } = await openAccount({ [`GET ${CONTRIBUTIONS}`]: envelope([{ ...agents, items: null, error: true }]) }) + const card = wrapper.find('[data-account-contribution="agents"]') + expect(card.find('[data-account-contribution-error]').text()).toBe('This section could not be loaded.') + expect(card.find('[data-account-item]').exists()).toBe(false) + expect(card.find('[data-account-items-empty]').exists()).toBe(false) + }) + + it('a danger item action confirms with :title filled as text and posts the item route', async () => { + const REVOKE = itemPath('client:2', 'revoke') + const { wrapper, calls } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([agents]), + [`POST ${REVOKE}`]: envelope({ message: 'Connection revoked', url: '' }), + }) + await wrapper.find('[data-account-item="client:2"] [data-account-item-action="revoke"]').trigger('click') + await flushPromises() + const dialog = document.body.querySelector('[data-confirm-dialog]') + expect(dialog?.textContent).toContain('Revoke the connection “Bold Agent”?') + expect(dialog?.querySelector('b')).toBeNull() + expect(requestsTo(calls, 'POST', REVOKE)).toHaveLength(0) + dialog!.querySelector('[data-action="confirm"]')!.click() + await flushPromises() + const posts = requestsTo(calls, 'POST', REVOKE) + expect(posts).toHaveLength(1) + expect(posts[0]!.headers.get('X-Requested-With')).toBe('XMLHttpRequest') + expect(toasts.value.map((toast) => [toast.text, toast.tone])).toEqual([['Connection revoked', 'success']]) + expect(requestsTo(calls, 'GET', CONTRIBUTIONS)).toHaveLength(2) + }) + + it('an item action without confirm or danger posts at once', async () => { + const RENAME = itemPath('client:1', 'rename') + const { wrapper, calls } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([agents]), + [`POST ${RENAME}`]: envelope({ message: '', url: '' }), + }) + await wrapper.find('[data-account-item="client:1"] [data-account-item-action="rename"]').trigger('click') + await flushPromises() + expect(document.body.querySelector('[data-confirm-dialog]')).toBeNull() + expect(requestsTo(calls, 'POST', RENAME)).toHaveLength(1) + expect(toasts.value.map((toast) => toast.text)).toEqual(['Action completed.']) + }) + + it('404 shows the item_gone toast and reloads the list', async () => { + const RENAME = itemPath('client:1', 'rename') + const { wrapper, calls } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([agents]), + [`POST ${RENAME}`]: { status: 404, body: { error: { code: 'not_found', message: 'Not found', details: {} } } }, + }) + await wrapper.find('[data-account-item="client:1"] [data-account-item-action="rename"]').trigger('click') + await flushPromises() + expect(toasts.value.map((toast) => [toast.text, toast.tone])).toEqual([['This item is already gone.', 'danger']]) + expect(requestsTo(calls, 'GET', CONTRIBUTIONS)).toHaveLength(2) + }) + + it('409 shows the action_stale toast and reloads the list', async () => { + const RENAME = itemPath('client:1', 'rename') + const { wrapper, calls } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([agents]), + [`POST ${RENAME}`]: { status: 409, body: { error: { code: 'conflict', message: 'Conflict', details: {} } } }, + }) + await wrapper.find('[data-account-item="client:1"] [data-account-item-action="rename"]').trigger('click') + await flushPromises() + expect(toasts.value.map((toast) => [toast.text, toast.tone])).toEqual([['This action no longer applies.', 'danger']]) + expect(requestsTo(calls, 'GET', CONTRIBUTIONS)).toHaveLength(2) + }) + + it("403 shows the server's message and keeps the list", async () => { + const RENAME = itemPath('client:1', 'rename') + const { wrapper, calls } = await openAccount({ + [`GET ${CONTRIBUTIONS}`]: envelope([agents]), + [`POST ${RENAME}`]: { status: 403, body: { error: { code: 'forbidden', message: 'You may not rename this.', details: {} } } }, + }) + await wrapper.find('[data-account-item="client:1"] [data-account-item-action="rename"]').trigger('click') + await flushPromises() + expect(toasts.value.map((toast) => [toast.text, toast.tone])).toEqual([['You may not rename this.', 'danger']]) + expect(requestsTo(calls, 'GET', CONTRIBUTIONS)).toHaveLength(1) + }) +}) diff --git a/admin/tests/app/router.test.ts b/admin/tests/app/router.test.ts index 58e03f4d..e79bdf91 100644 --- a/admin/tests/app/router.test.ts +++ b/admin/tests/app/router.test.ts @@ -183,3 +183,41 @@ describe('preview route (UI-SPEC S3, D-11)', () => { expect(safeRedirect(router.currentRoute.value.query.redirect)).toBe('/acme/demo/widgets/12/preview') }) }) + +describe('connect route (32.2 UI-SPEC C1)', () => { + it('sends an anonymous visitor of /connect to login with the request and returns there after sign-in', async () => { + mockApi({}) + const router = createAdminRouter(createMemoryHistory()) + await router.push('/connect?request=x') + expect(router.currentRoute.value.name).toBe('login') + expect(router.currentRoute.value.query.redirect).toBe('/connect?request=x') + expect(safeRedirect(router.currentRoute.value.query.redirect)).toBe('/connect?request=x') + + // Signed in, the login screen of that redirect moves on to /connect. + await signIn() + const back = createAdminRouter(createMemoryHistory()) + await back.push({ path: '/login', query: { redirect: router.currentRoute.value.query.redirect } }) + expect(back.currentRoute.value.name).toBe('connect') + expect(back.currentRoute.value.fullPath).toBe('/connect?request=x') + expect(back.currentRoute.value.query.request).toBe('x') + }) + + it('is a standalone route that is neither public nor inside the shell', async () => { + await signIn() + const router = await routerAt('/connect?request=abc') + expect(router.currentRoute.value.name).toBe('connect') + expect(router.currentRoute.value.meta.shell).toBeFalsy() + expect(router.currentRoute.value.meta.public).toBeFalsy() + expect(routeControllerId(router.currentRoute.value)).toBe('') + }) + + it('keeps an encoded request id through the login redirect', async () => { + mockApi({}) + const router = createAdminRouter(createMemoryHistory()) + await router.push({ path: '/connect', query: { request: 'a b/c' } }) + const redirect = router.currentRoute.value.query.redirect + expect(router.currentRoute.value.name).toBe('login') + expect(safeRedirect(redirect)).toBe(redirect) + expect(new URL(String(redirect), 'http://admin.invalid').searchParams.get('request')).toBe('a b/c') + }) +}) diff --git a/admin/tests/views/ConnectView.test.ts b/admin/tests/views/ConnectView.test.ts new file mode 100644 index 00000000..0c5892d5 --- /dev/null +++ b/admin/tests/views/ConnectView.test.ts @@ -0,0 +1,471 @@ +// 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. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, flushPromises, type VueWrapper } from '@vue/test-utils' +import { setBundle, t } from '../../src/app/i18n' +import type { 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 = { 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 } + +function consentView(overrides: Partial = {}): 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 { + 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 + +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 = routes()) { + const mounted = await mountApp(path, r, { attach: true }) + 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) +} + +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 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('lists the returned scopes in order 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.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 * 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]) + 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') + 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 () => { + 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-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() + 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 }]) + }) +}) + +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', 'acme'], 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', 'acme'], 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 custom = await open('/connect?request=req1', routes(consentView(), 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 agent.example.test') + }) + + 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((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,', 'vbscript:msgbox(1)', 'JavaScript:alert(1)', 'not a uri'])( + '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'))) + 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-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((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-picker]').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') + }) +}) diff --git a/admin/tests/views/LoginView.test.ts b/admin/tests/views/LoginView.test.ts index d0999c97..641761d0 100644 --- a/admin/tests/views/LoginView.test.ts +++ b/admin/tests/views/LoginView.test.ts @@ -124,4 +124,26 @@ describe('login view', () => { await flushPromises() expect(requestsTo(calls, 'POST', `${API}/auth/login`)).toHaveLength(1) }) + + it('shows the connect hint under the heading only for a /connect redirect', async () => { + for (const redirect of ['/connect?request=req1', '/connect']) { + const { wrapper } = await mountLogin({ redirect }) + const hint = wrapper.find('[data-login-hint]') + expect(hint.exists(), redirect).toBe(true) + expect(hint.text()).toBe('backend::lang.mcp_connect.login_hint') + expect(wrapper.find('h1').element.nextElementSibling).toBe(hint.element) + wrapper.unmount() + } + for (const redirect of [undefined, '/acme/demo/gadgets', '/connect/more', '/connections', '//evil.example/connect', 'https://evil.example/connect']) { + const { wrapper } = await mountLogin(redirect === undefined ? {} : { redirect }) + expect(wrapper.find('[data-login-hint]').exists(), String(redirect)).toBe(false) + wrapper.unmount() + } + }) + + it('returns to the consent request after signing in from the hint', async () => { + const { wrapper, router } = await mountLogin({ redirect: '/connect?request=req1' }) + await submit(wrapper) + expect(router.currentRoute.value.fullPath).toBe('/connect?request=req1') + }) })