Files
MikrotikManager/tests/e2e/mcp-auth-context.spec.ts
T

340 lines
23 KiB
TypeScript

import { test, expect, type Page } from '@playwright/test'
// Synthetic JWT and routed API responses. This exercises the shipped UI only;
// it does not verify backend enforcement, Portal/Sender or a live end-user route.
const id = 'fa58fa40-4bcb-4616-9316-cb69463b3150'
const at = '2026-10-29T00:00:00Z'
const read = { id: 'logs.query', toolName: 'mm_logs_query', title: 'Поиск логов', section: 'logs', version: 1, effect: 'read', risk: 'ordinary', scope: 'servers', requiredPermissions: ['mm:servers:read'], implementation: 'available', annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } }
const forbidden = { ...read, id: 'users.delete', title: 'Запрещённая операция каталога', requiredPermissions: ['mm:users:admin'], effect: 'write' }
async function setup(page: Page, permissions: string[], access: { expiresAt?: string; ownerValidUntil?: string; status?: string; generationValid?: boolean } = {}) {
await page.addInitScript(permissions => { localStorage.setItem('mmapp_token', 'header.' + btoa(JSON.stringify({ sub: 'synthetic-owner', apps: ['mm'], permissions, exp: 4102444800 })) + '.signature') }, permissions)
const connection = { id, name: 'Синтетический AI клиент', ownerId: 'synthetic-owner', policy: { id, version: 1, status: 'active', mode: 'observer', expiresAt: '2099-01-01T00:00:00Z', permissions: ['mm:servers:read'], scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false }, dangerousPolicy: 'approval', autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }
const mutations: { path: string, body: Record<string, unknown> }[] = []
connection.policy.expiresAt = access.expiresAt ?? connection.policy.expiresAt
connection.policy.status = access.status ?? connection.policy.status
connection.generationValid = access.generationValid ?? connection.generationValid
const ownerValidUntil = access.ownerValidUntil ?? '2099-01-01T00:00:00Z'
let connectionReads = 0
let enabled = true
await page.route('**/api/**', async route => {
const request = route.request(), path = new URL(request.url()).pathname, method = request.method()
const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,PUT,DELETE,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
if (method === 'OPTIONS') return route.fulfill({ status: 204, headers })
const json = (body: unknown) => route.fulfill({ headers, json: body })
if (method !== 'GET') mutations.push({ path, body: request.postDataJSON() })
if (path === '/api/auth/config') return json({ required: true })
if (path === '/api/mcp/catalog') return json({ stage: 'runtime', executionAvailable: true, operations: [read, forbidden] })
if (path === '/api/mcp/overview') return json({ connections: 1, calls: 3, errors: 1, approvals: 0, running: 0, enabled, observedAt: at })
if (path === '/api/mcp/connections') { connectionReads++; const visible = { ...connection, ownerValidUntil }; return json(method === 'POST' ? { connection: visible, token: 'synthetic-one-time-token' } : { connections: [visible] }) }
if (path === `/api/mcp/connections/${id}/status`) { connection.policy.status = request.postDataJSON().status; return json({ ok: true }) }
if (path === '/api/mcp/stop-automation') { enabled = false; return json({ ok: true }) }
if (path === '/api/mcp/requests') return json({ items: [{ id: 'synthetic-call', tool: 'mm_logs_query', created_at: at, connection_id: id, status: connection.policy.status === 'active' ? 'completed' : 'denied', error_code: connection.policy.status === 'active' ? null : `connection_${connection.policy.status}`, detail: 'synthetic fixture outcome' }], total: 1, nextCursor: null })
if (path.endsWith('/grants')) return json({ grants: [] })
if (path === '/api/servers') return json([])
return json({ items: [], total: 0, nextCursor: null })
})
return { mutations, get connectionReads() { return connectionReads } }
}
for (const [access, label, reason] of [
[{ expiresAt: '2000-01-01T00:00:00Z' }, 'Срок доступа истёк', 'Продлите срок в разрешениях подключения'],
[{ ownerValidUntil: '2000-01-01T00:00:00Z' }, 'Права владельца истекли', 'Владельцу нужно подтвердить актуальные права'],
[{ status: 'paused' }, 'На паузе', 'Новые вызовы подключения остановлены'],
[{ status: 'revoked' }, 'Доступ отозван', 'Подключение и его токены отозваны'],
[{ generationValid: false }, 'Доступ аннулирован', 'Поколение доступа больше не действительно'],
] as const) test(`synthetic: connection state explains ${label}`, async ({ page }, testInfo) => {
await setup(page, ['mm:mcp:read'], access)
await page.goto('/mcp?tab=connections')
const row = page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' })
await expect(row.getByText(label, { exact: true })).toBeVisible()
await expect(row.getByText(reason, { exact: true })).toBeVisible()
await expect(row.getByText('Активен', { exact: true })).toHaveCount(0)
await expect(page.getByRole('columnheader', { name: 'Доступ до', exact: true })).toBeVisible()
await expect(page.getByRole('columnheader', { name: 'Права владельца до', exact: true })).toBeVisible()
if (label === 'Срок доступа истёк') {
await row.screenshot({ path: testInfo.outputPath('connection-expired-desktop.png') })
await page.setViewportSize({ width: 390, height: 844 })
await row.getByText(label, { exact: true }).scrollIntoViewIfNeeded()
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true)
await page.screenshot({ path: testInfo.outputPath('connection-expired-mobile.png') })
}
})
for (const field of ['expiresAt', 'ownerValidUntil'] as const) test(`synthetic: connection clock crosses ${field} without another API response`, async ({ page }) => {
const start = new Date('2030-01-01T00:00:00Z')
await page.clock.install({ time: start })
const state = await setup(page, ['mm:mcp:read'], { [field]: '2030-01-01T01:00:02Z' })
await page.goto('/mcp?tab=connections')
const row = page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' })
await expect(row.getByText('Активен', { exact: true })).toBeVisible()
await page.clock.pauseAt(new Date('2030-01-01T01:00:00Z'))
// Ignore any catch-up polling from pauseAt; the crossing below is <5 seconds.
await page.waitForLoadState('networkidle')
const reads = state.connectionReads
await page.clock.runFor(2100)
await expect(row.getByText(field === 'expiresAt' ? 'Срок доступа истёк' : 'Права владельца истекли', { exact: true })).toBeVisible()
await expect(row.getByText('Активен', { exact: true })).toHaveCount(0)
expect(state.connectionReads).toBe(reads)
expect(state.mutations).toEqual([])
})
test('synthetic: bind OAuth consent to the displayed request and submit only once', async ({ page }) => {
await setup(page, ['mm:mcp:read'])
const firstId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
const secondId = 'fa58fa40-4bcb-4616-9316-cb69463b3152'
const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
const first = { id: firstId, name: 'OAuth A', redirect_uri: 'https://a.example.test/callback', scope: 'mcp' }
const second = { id: secondId, name: 'OAuth B', redirect_uri: 'https://b.example.test/callback', scope: 'mcp' }
let releaseSecond!: () => void
const secondPending = new Promise<void>(resolve => { releaseSecond = resolve })
await page.route('**/api/mcp/oauth/requests/*', async route => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
const isSecond = route.request().url().endsWith(secondId)
if (isSecond) await secondPending
await route.fulfill({ headers, json: isSecond ? second : first })
})
let releasePost!: () => void
const postPending = new Promise<void>(resolve => { releasePost = resolve })
const decisions: unknown[] = []
await page.route('**/api/mcp/oauth/consent', async route => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
decisions.push(route.request().postDataJSON())
await postPending
await route.fulfill({ status: 409, headers, json: { message: 'Синтетический отказ' } })
})
await page.goto('/mcp?oauthRequest=' + firstId)
const connection = page.getByLabel('Подключение', { exact: true })
const approve = page.getByRole('button', { name: 'Разрешить', exact: true })
const deny = page.getByRole('button', { name: 'Отклонить', exact: true })
await expect(page.getByText(first.redirect_uri, { exact: false })).toBeVisible()
await connection.selectOption(id)
await expect(approve).toBeEnabled()
const secondRequest = page.waitForRequest(request => request.method() === 'GET' && request.url().endsWith('/oauth/requests/' + secondId))
await page.evaluate(id => window.history.pushState(null, '', '/mcp?oauthRequest=' + id), secondId)
await secondRequest
await expect(page.getByText(first.redirect_uri, { exact: false })).toHaveCount(0)
await expect(connection).toHaveValue('')
await expect(approve).toBeDisabled()
await expect(deny).toBeDisabled()
expect(decisions).toEqual([])
releaseSecond()
await expect(page.getByText(second.redirect_uri, { exact: false })).toBeVisible()
await connection.selectOption(id)
await expect(approve).toBeEnabled()
await approve.evaluate((button, denyLabel) => {
const approve = button as HTMLButtonElement
const deny = [...document.querySelectorAll('button')].find(node => node.textContent === denyLabel)
approve.click()
deny?.click()
}, 'Отклонить')
await expect.poll(() => decisions).toEqual([{ requestId: secondId, connectionId: id, approve: true }])
await expect(approve).toBeDisabled()
await expect(deny).toBeDisabled()
releasePost()
await expect(approve).toBeEnabled()
expect(decisions).toHaveLength(1)
})
test('synthetic: concurrent unauthorized MCP reads hand off to Portal once', async ({ page, baseURL }) => {
await setup(page, ['mm:mcp:read'])
const portal = 'http://127.0.0.1:3165'
const operationPath = `/mcp?tab=plans&operation=${id}`
await page.route('**/api/auth/config', route => route.fulfill({ json: { required: true, portal_url: portal } }))
let revoked = false, refusals = 0
let delayedRefusal: Promise<void> | undefined
const headers = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'Authorization' }
await page.route(/\/api\/mcp\/(operations|plans|drift)\?/, async route => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
const selected = new URL(route.request().url()).searchParams.get('operationId') === id
if (selected && delayedRefusal) {
const wait = delayedRefusal
delayedRefusal = undefined
await wait
return route.fulfill({ status: 401, headers, json: { error: 'Unauthorized' } })
}
if (revoked) {
refusals++
return route.fulfill({ status: 401, headers, json: { error: 'Unauthorized' } })
}
return route.fulfill({ headers, json: { items: selected ? [{ id, state: 'applied', steps: [{ step_index: 0, state: 'verified' }] }] : [], total: selected ? 1 : 0, nextCursor: null } })
})
const handoffs: URL[] = []
await page.route(url => url.origin === portal && url.pathname === '/', async route => {
handoffs.push(new URL(route.request().url()))
await expect.poll(() => refusals).toBeGreaterThan(1)
await route.fulfill({ contentType: 'text/html', body: '<h1>Portal sign-in</h1>' })
})
await page.goto(operationPath)
const step = page.getByRole('region', { name: 'Шаги выполнения' }).getByText('Результат проверен')
await expect(step).toBeVisible()
const refresh = page.getByRole('button', { name: 'Обновить выполнение' })
let releaseRefusal!: () => void
delayedRefusal = new Promise<void>(resolve => { releaseRefusal = resolve })
try {
await Promise.all([
page.waitForRequest(request => request.method() === 'GET' && new URL(request.url()).searchParams.get('operationId') === id),
refresh.click(),
])
await page.evaluate(() => {
localStorage.setItem('mmapp_token', 'header.' + btoa(JSON.stringify({ sub: 'new-session', apps: ['mm'], permissions: ['mm:mcp:read'], exp: 4102444800 })) + '.signature')
})
} finally { releaseRefusal() }
await expect(page.getByRole('alert').filter({ hasText: 'Unauthorized' })).toBeVisible()
expect(handoffs).toHaveLength(0)
revoked = true
await refresh.click()
await expect(page.getByRole('heading', { name: 'Portal sign-in' })).toBeVisible()
expect(handoffs).toHaveLength(1)
const callback = new URL(handoffs[0].searchParams.get('return_to')!)
expect(callback.origin).toBe(new URL(baseURL!).origin)
expect(callback.pathname).toBe('/auth/callback')
expect(callback.searchParams.get('next')).toBe(operationPath)
await expect(step).toHaveCount(0)
})
test('synthetic: deny OAuth consent without an available connection', async ({ page, baseURL }) => {
await setup(page, ['mm:mcp:read'])
const requestId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
const callback = new URL('/local-oauth-callback', baseURL!)
const response = { id: requestId, name: 'OAuth without connection', redirect_uri: callback.href, scope: 'mcp' }
callback.searchParams.set('error', 'access_denied')
const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
await page.route('**/api/mcp/connections', route => route.fulfill({ headers, json: { connections: [] } }))
await page.route(`**/api/mcp/oauth/requests/${requestId}`, route => route.fulfill({ headers, json: response }))
const decisions: unknown[] = []
await page.route('**/api/mcp/oauth/consent', async route => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
decisions.push(route.request().postDataJSON())
await route.fulfill({ headers, json: { redirectUrl: callback.href } })
})
await page.route(callback.href, route => route.fulfill({ body: 'OAuth request declined' }))
await page.goto('/mcp?oauthRequest=' + requestId)
await expect(page.getByText('OAuth without connection запрашивает доступ к MikrotikManager.')).toBeVisible()
await expect(page.getByLabel('Подключение', { exact: true }).locator('option')).toHaveCount(1)
await expect(page.getByRole('button', { name: 'Разрешить', exact: true })).toBeDisabled()
await page.getByRole('button', { name: 'Отклонить', exact: true }).click()
await expect(page).toHaveURL(callback.href)
expect(decisions).toEqual([{ requestId, approve: false }])
})
test('synthetic: OAuth approval becomes unavailable when the selected connection expires', async ({ page }) => {
const start = new Date('2030-01-01T00:00:00Z')
await page.clock.install({ time: start })
await page.clock.pauseAt(new Date('2030-01-01T00:00:01Z'))
const state = await setup(page, ['mm:mcp:read'], { expiresAt: '2030-01-01T00:00:03Z' })
const requestId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
await page.route(`**/api/mcp/oauth/requests/${requestId}`, route => route.request().method() === 'OPTIONS'
? route.fulfill({ status: 204, headers })
: route.fulfill({ headers, json: { id: requestId, name: 'OAuth expiry', redirect_uri: 'https://a.example.test/callback', scope: 'mcp' } }))
await page.goto('/mcp?oauthRequest=' + requestId)
const connection = page.getByLabel('Подключение', { exact: true })
const approve = page.getByRole('button', { name: 'Разрешить', exact: true })
await connection.selectOption(id)
await expect(approve).toBeEnabled()
const reads = state.connectionReads
await page.clock.runFor(2100)
await expect(approve).toBeDisabled()
await expect(connection.locator('option')).toHaveCount(1)
await expect(page.getByRole('button', { name: 'Отклонить', exact: true })).toBeEnabled()
expect(state.connectionReads).toBe(reads)
expect(state.mutations).toEqual([])
})
test('synthetic: issue only selected server/read permission and hide one-time token', async ({ page }) => {
const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
await page.goto('/mcp?tab=connections')
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
const dialog = page.getByRole('dialog')
await dialog.getByLabel('Название', { exact: true }).fill('Ограниченная диагностика')
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
await dialog.getByRole('checkbox', { name: read.title, exact: true }).check()
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
await expect(dialog).toContainText('Глобальный доступ: нет')
await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
const token = page.getByLabel('Одноразовый токен MCP')
await expect(token).toHaveValue('synthetic-one-time-token')
await expect(token).toHaveAttribute('type', 'password')
expect(state.mutations).toHaveLength(1)
expect(state.mutations[0]).toMatchObject({ path: '/api/mcp/connections', body: { permissions: ['mm:servers:read'], scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false }, mode: 'observer' } })
await page.getByRole('button', { name: 'Закрыть и скрыть токен' }).click()
await expect(token).toHaveCount(0)
await page.reload()
await expect(token).toHaveCount(0)
})
test('synthetic: pause, resume, cancelled revoke, revoke, monitor denied outcome, stop automation', async ({ page }) => {
const state = await setup(page, ['mm:mcp:admin', 'mm:mcp:pause', 'mm:servers:read'])
await page.goto('/mcp?tab=connections')
await page.getByRole('button', { name: 'Пауза', exact: true }).click()
await expect(page.getByRole('button', { name: 'Включить', exact: true })).toBeEnabled()
expect(state.mutations.at(-1)?.body).toEqual({ status: 'paused' })
await page.getByRole('tab', { name: 'Обращения', exact: true }).click()
await expect(page.getByRole('cell', { name: 'connection_paused', exact: true })).toBeVisible()
await page.getByRole('button', { name: 'Открыть', exact: true }).click()
await expect(page.getByRole('dialog')).toContainText('synthetic fixture outcome')
await page.keyboard.press('Escape')
await page.getByRole('tab', { name: 'Подключения', exact: true }).click()
await page.getByRole('button', { name: 'Включить', exact: true }).click()
await expect(page.getByRole('button', { name: 'Пауза', exact: true })).toBeEnabled()
page.once('dialog', dialog => dialog.dismiss())
await page.getByRole('button', { name: 'Отозвать', exact: true }).click()
expect(state.mutations.filter(x => x.body.status === 'revoked')).toHaveLength(0)
page.once('dialog', dialog => dialog.accept())
await page.getByRole('button', { name: 'Отозвать', exact: true }).click()
await expect(page.getByRole('button', { name: 'Отозвать', exact: true })).toBeDisabled()
await expect(page.getByRole('button', { name: 'Включить', exact: true })).toBeDisabled()
await expect(page.getByRole('button', { name: 'Новый токен', exact: true })).toBeDisabled()
await page.getByRole('tab', { name: 'Обращения', exact: true }).click()
await expect(page.getByRole('cell', { name: 'connection_revoked', exact: true })).toBeVisible()
await expect(page.getByRole('cell', { name: 'denied', exact: true })).toBeVisible()
await page.getByRole('tab', { name: 'Обзор', exact: true }).click()
page.once('dialog', dialog => dialog.accept())
await page.getByRole('button', { name: 'Остановить автоматические изменения', exact: true }).click()
await expect(page.getByText('MCP выключен', { exact: true })).toBeVisible()
expect(state.mutations.map(x => [x.path, x.body])).toEqual([
[`/api/mcp/connections/${id}/status`, { status: 'paused' }],
[`/api/mcp/connections/${id}/status`, { status: 'active' }],
[`/api/mcp/connections/${id}/status`, { status: 'revoked' }],
['/api/mcp/stop-automation', {}],
])
})
test('synthetic: read-only role cannot issue/revoke/pause or reach settings', async ({ page }) => {
const state = await setup(page, ['mm:mcp:read'])
await page.goto('/mcp?tab=connections')
await expect(page.getByText('Синтетический AI клиент', { exact: true })).toBeVisible()
await expect(page.getByRole('tab', { name: 'Настройки', exact: true })).toHaveCount(0)
for (const name of ['Выдать доступ', 'Пауза', 'Отозвать', 'Новый токен', 'Выдать временный допуск']) await expect(page.getByRole('button', { name, exact: true })).toHaveCount(0)
await page.getByRole('tab', { name: 'Обзор', exact: true }).click()
await expect(page.getByText('MCP включён', { exact: true })).toBeVisible()
await expect(page.getByRole('button', { name: 'Остановить автоматические изменения', exact: true })).toHaveCount(0)
await page.goto('/mcp?tab=settings')
await expect(page.getByRole('heading', { name: 'MCP', exact: true })).toBeVisible()
await expect(page.getByText('Настройки MCP', { exact: true })).toHaveCount(0)
expect(state.mutations).toEqual([])
})
test('synthetic: direct application URLs enforce declared route permissions', async ({ page }) => {
await setup(page, ['mm:mcp:read', 'mm:servers:read'])
await page.goto('/logs')
await expect(page.getByRole('heading', { name: 'Логи MikroTik', exact: true })).toBeVisible()
await page.goto('/mcp?tab=settings')
await expect(page.getByRole('heading', { name: 'MCP', exact: true })).toBeVisible()
for (const path of ['/settings', '/traffic']) {
await page.goto(path)
await expect(page).toHaveURL(/\/access-denied$/)
await expect(page.getByRole('heading', { name: 'Нет доступа', exact: true })).toBeVisible()
}
})