diff --git a/backend/src/modules/mcp/principal-security-source.owned.test.ts b/backend/src/modules/mcp/principal-security-source.owned.test.ts index 1e7be7c2..5cf80d55 100644 --- a/backend/src/modules/mcp/principal-security-source.owned.test.ts +++ b/backend/src/modules/mcp/principal-security-source.owned.test.ts @@ -25,7 +25,7 @@ const { applySqlMigrations } = await import("../../db/migrate.js") const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js") const { MCP_SERVICE_EXPIRATION, mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp") const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource, - updateMcpConnection, revalidateMcpOwner, rotateConnectionToken, setConnectionStatus } = await import("./store.js") + updateMcpConnection, revalidateMcpOwner, rotateConnectionToken, setConnectionStatus, intersectGrant } = await import("./store.js") const { acceptPortalRevocation } = await import("./portal-revocation.js") const { connectProbeStorage } = await import("../../services/server-probe-storage-connection.js") const { principalSourceSql, principalSourceStatementName } = await import("./principal-security-sql.js") @@ -84,6 +84,35 @@ try { assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n, MIGRATION_MANIFEST.length) priorEnabled = Boolean((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled) await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1") + await check("explicit all-server selection stores current IDs and the empty list stays empty", async () => { + const { actor, principal } = await fixture() + const input = mcpConnectionCreateSchema.parse({ name: "All server scope", expiresAt: new Date(actor.expiresAt!).toISOString(), + permissions: ["mm:servers:read"], scope: { serverIds: [], operationIds: ["servers.list"], allowGlobal: false } }) + const insertServer = async (name: string) => Number((await pool.query("INSERT INTO servers(name,host,enabled) VALUES($1,'127.0.0.1',false) RETURNING id", [name])).rows[0].id) + const serverIds: number[] = [] + try { + serverIds.push(await insertServer("Owned all-scope first")) + const current = (await pool.query("SELECT id FROM servers ORDER BY id")).rows.map(row => Number(row.id)) + assert.equal(mcpConnectionCreateSchema.safeParse({ ...input, selectAllServers: true, scope: { ...input.scope, serverIds } }).success, false) + const access = await createMcpConnection({ ...input, selectAllServers: true }, actor) + connectionIds.push(access.connection.id) + const allPrincipal = await authenticateMcpToken(access.token) + serverIds.push(await insertServer("Owned all-scope second")) + const granted = await validatePrincipal(allPrincipal) + assert.deepEqual(granted.policy.scope.serverIds, current) + assert.equal(granted.policy.scope.allowGlobal, false) + assert.equal(Object.hasOwn(granted.policy, "selectAllServers"), false) + const limited = intersectGrant(granted, { id: randomUUID(), startsAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 60000).toISOString(), + scope: { serverIds: [serverIds[0]], operationIds: ["servers.list"], allowGlobal: false } }) + assert.deepEqual(limited.policy.scope.serverIds, [serverIds[0]]) + const updated = await updateMcpConnection(principal.connectionId, { ...input, selectAllServers: true }, actor) + assert.deepEqual(updated.policy.scope.serverIds, [...current, serverIds[1]]) + const emptied = await updateMcpConnection(principal.connectionId, input, actor) + assert.deepEqual(emptied.policy.scope.serverIds, []) + } finally { + await pool.query("DELETE FROM servers WHERE id=ANY($1::bigint[])", [serverIds]) + } + }) await check("service access survives portal expiry and preserves token rotation and revocation", async () => { const { actor, principal: personal } = await fixture() const payload = { authority: "service", name: "Service access", mode: "autonomous", expiresAt: null, diff --git a/backend/src/modules/mcp/store.ts b/backend/src/modules/mcp/store.ts index 59716c08..e3ebe0dc 100644 --- a/backend/src/modules/mcp/store.ts +++ b/backend/src/modules/mcp/store.ts @@ -29,6 +29,19 @@ function connectionExpiration(input: McpConnectionCreate, actor: AuthUser) { throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400) return input.expiresAt } +async function resolveConnectionScope(scope: McpConnectionCreate["scope"], selectAllServers: boolean, client: PoolClient) { + if (selectAllServers) { + if (scope.serverIds.length) throw new McpError("INVALID_CONFIGURATION", "Выберите все серверы или укажите конкретные ID", 400) + const { rows } = await client.query<{ id: string }>("SELECT id FROM servers ORDER BY id LIMIT 1001") + if (rows.length > 1000) throw new McpError("INVALID_CONFIGURATION", "Подключению можно выдать доступ не более чем к 1000 серверам", 400) + return { ...scope, serverIds: rows.map(row => Number(row.id)) } + } + if (scope.serverIds.length) { + const { rows } = await client.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [scope.serverIds]) + if (rows.length !== scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400) + } + return scope +} export interface McpPrincipal { connectionId: string; credentialId: string; credentialExpiresAt: string } export function intersectGrant(connection: ConnectionRow, grant?: z.infer): ConnectionRow { if (!grant) return connection @@ -125,18 +138,15 @@ export function assertConnectionVisible(row: ConnectionRow, actor: AuthUser): vo export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) { const expiresAt = connectionExpiration(input, actor) if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права") - if (input.scope.serverIds.length) { - const { rows } = await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [input.scope.serverIds]) - if (rows.length !== input.scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400) - } const id = randomUUID(), generation = await accessGeneration() - const { name, ...configuration } = input - const policy = mcpConnectionPolicySchema.parse({ ...configuration, expiresAt, id, version: 1, status: "active" }) - const service = policy.authority === "service" + const { name, scope: requestedScope, selectAllServers, ...configuration } = input const token = randomToken("bearer") return connectionWrite(async client => { await lockPortalOwner(client, actor.id) await assertPortalClaimsCurrent(actor, client) + const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client) + const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: 1, status: "active" }) + const service = policy.authority === "service" const { rows: [row] } = await client.query("INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation,owner_valid_until,owner_claims_issued_at) VALUES($1,$2,$3,$4::jsonb,$5::jsonb,$6,$7,$8) RETURNING *", [id, name, actor.id, JSON.stringify(service ? policy.permissions : actor.permissions), JSON.stringify(policy), generation, service ? expiresAt : ownerValidUntil(actor), new Date(actor.issuedAt ?? 0)]) await client.query("INSERT INTO mcp_credentials(id,connection_id,digest,kind,expires_at) VALUES($1,$2,$3,'bearer',$4)", [randomUUID(), id, tokenDigest(token), expiresAt]) await audit(client, actor.id, "connection.create", id, { name, policy }) @@ -147,7 +157,6 @@ export async function updateMcpConnection(id: string, input: McpConnectionCreate const expiresAt = connectionExpiration(input, actor) const service = input.authority === "service" if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие права") - if (input.scope.serverIds.length && (await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [input.scope.serverIds])).rows.length !== input.scope.serverIds.length) throw new McpError("SERVER_DENIED", "Выбран неизвестный сервер", 400) return connectionWrite(async client => { if (service) { await lockPortalOwner(client, actor.id) @@ -158,8 +167,9 @@ export async function updateMcpConnection(id: string, input: McpConnectionCreate if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав") if (before.policy.authority !== input.authority) throw new McpError("INVALID_CONFIGURATION", "Для смены типа доступа создайте новое подключение", 400) if (Date.parse(expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400) - const { name, ...configuration } = input - const policy = mcpConnectionPolicySchema.parse({ ...configuration, expiresAt, id, version: before.policy.version + 1, status: before.policy.status }) + const { name, scope: requestedScope, selectAllServers, ...configuration } = input + const scope = await resolveConnectionScope(requestedScope, selectAllServers === true, client) + const policy = mcpConnectionPolicySchema.parse({ ...configuration, scope, expiresAt, id, version: before.policy.version + 1, status: before.policy.status }) const { rows: [row] } = await client.query("UPDATE mcp_connections SET name=$2,policy=$3::jsonb,owner_permissions=$4::jsonb,owner_valid_until=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, name, JSON.stringify(policy), JSON.stringify(service ? policy.permissions : actor.permissions), service ? before.owner_valid_until : ownerValidUntil(actor)]) await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id=$1 AND state IN ('draft','awaiting-approval','approved')", [id]) await audit(client, actor.id, "connection.policy.update", id, { before: before.policy, after: policy }) diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx index 04b198f5..cc379e03 100644 --- a/components/mcp/mcp-workspace.tsx +++ b/components/mcp/mcp-workspace.tsx @@ -157,20 +157,15 @@ function DeviceEditor({ api, connectionId, serverId, resource }: { api: McpApi; function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) { return { if (!open) close() }}>Доступ создан{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя. } -function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) { - const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("") - const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState(editing?.policy.mode ?? "observer") - const [service, setService] = useState(editing?.policy.authority === "service") - const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) - const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval") - const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? []) - const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16)) - const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 }) - const permissions = getClaims()?.permissions ?? [] - const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission))) +function OperationChoices({ operations, selected, onChange, selectAllLabel = "Выбрать все операции" }: { + operations: McpOperationDescriptor[] + selected: string[] + onChange: (ids: string[]) => void + selectAllLabel?: string +}) { const selectedIds = new Set(selected) const bySection = new Map() - for (const operation of eligible) { + for (const operation of operations) { const group = bySection.get(operation.section) if (group) group.push(operation) else bySection.set(operation.section, [operation]) @@ -179,12 +174,51 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp .sort(([left], [right]) => (operationSectionLabels[left] ?? left).localeCompare(operationSectionLabels[right] ?? right, "ru")) const selectOperations = (operations: McpOperationDescriptor[], checked: boolean) => { const groupIds = new Set(operations.map(operation => operation.id)) - setSelected(ids => checked ? [...new Set([...ids, ...groupIds])] : ids.filter(id => !groupIds.has(id))) + onChange(checked ? [...new Set([...selected, ...groupIds])] : selected.filter(id => !groupIds.has(id))) } + return <> +
+ + + Выбрано {selected.length} +
+
+ {groups.map(([section, items]) => { + const title = operationSectionLabels[section] ?? section + const count = items.filter(operation => selectedIds.has(operation.id)).length + return
+ 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} /> +
+ {title} {count} / {items.length} +
+ {items.map(operation => selectOperations([operation], checked)} />)} +
+
+
+ })} + {!operations.length &&

Нет доступных операций.

} +
+ +} +function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) { + const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("") + const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState(editing?.policy.mode ?? "observer") + const [service, setService] = useState(editing?.policy.authority === "service") + const [selectAllServers, setSelectAllServers] = useState(false) + const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) + const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval") + const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? []) + const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16)) + const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 }) + const permissions = getClaims()?.permissions ?? [] + const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission))) + const selectedIds = new Set(selected) + const dangerous = eligible.filter(operation => operation.risk === "dangerous" && selectedIds.has(operation.id)) + const autonomousDangerIds = dangerous.filter(operation => dangerIds.includes(operation.id)).map(operation => operation.id) const save = async () => { setBusy(true); setError("") try { - const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null } : { mode, expiresAt: new Date(expires + "Z").toISOString() }), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], scope: { serverIds: serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service ? [] : dangerIds.filter(id => selected.includes(id)), limits }) + const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null } : { mode, expiresAt: new Date(expires + "Z").toISOString() }), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], ...(selectAllServers && { selectAllServers: true }), scope: { serverIds: selectAllServers ? [] : serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service || danger !== "explicit-allow" ? [] : autonomousDangerIds, limits }) if (editing) { await api.update(editing.id, input); created() } else { const result = await api.create(input); created(result.token) } } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } @@ -195,33 +229,19 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp ?

Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.

: <> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}}} {step === 2 && <> - setServerText(event.target.value)} placeholder="1, 2" /> + + {selectAllServers + ?

Доступ получат все серверы, зарегистрированные на момент сохранения.

+ : <> setServerText(event.target.value)} placeholder="1, 2" />

Пустой список означает, что доступ к серверам закрыт.

} -
- - - Выбрано {selected.length} -
-
- {groups.map(([section, items]) => { - const title = operationSectionLabels[section] ?? section - const count = items.filter(operation => selectedIds.has(operation.id)).length - return
- 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} /> -
- {title} {count} / {items.length} -
- {items.map(operation => selectOperations([operation], checked)} />)} -
-
-
- })} - {!eligible.length &&

Нет доступных операций.

} -
+

Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.

} - {step === 3 && <>
{Object.entries(limits).map(([key, value]) => )[key]}> setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} />)}
{service ?

Опасные действия всегда требуют подтверждения.

: <> setDanger(value as typeof danger)}>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}}} - {step === 4 &&

{name || "Без названия"} · {service ? "Сервисное, бессрочное" : modeLabels[mode]}

Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

} + {step === 3 && <>
{Object.entries(limits).map(([key, value]) => )[key]}> setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} />)}
{service ?

Опасные действия всегда требуют подтверждения.

: <> setDanger(value as typeof danger)}>{danger === "explicit-allow" && <> +

В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.

+ + }}} + {step === 4 &&

{name || "Без названия"} · {service ? "Сервисное, бессрочное" : modeLabels[mode]}

Серверы: {selectAllServers ? "все на момент сохранения" : serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

{!service && mode === "autonomous" && danger === "explicit-allow" &&

Опасных операций выбрано для автономного выполнения: {autonomousDangerIds.length}.

}

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

}
{step < 4 ? : }
} diff --git a/docs/mcp-enable-guide.md b/docs/mcp-enable-guide.md index 146c0f36..9340f31b 100644 --- a/docs/mcp-enable-guide.md +++ b/docs/mcp-enable-guide.md @@ -65,6 +65,8 @@ - **«Срок действия (UTC)»** — не больше года. Для первого шага достаточно нескольких дней. - **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию. - **Серверы и операции** — только те, что нужны агенту. + - «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений. + - Пустой список ID при выключенной опции «Все серверы» закрывает доступ ко всем серверам. - Операция, не выданная подключению, получает `OPERATION_DENIED`. - Сервер вне списка получает `SERVER_DENIED`. - Глобальные операции работают только с «Разрешить выбранные глобальные операции». diff --git a/packages/contracts/src/mcp.ts b/packages/contracts/src/mcp.ts index 64b7aff8..f51d5a73 100644 --- a/packages/contracts/src/mcp.ts +++ b/packages/contracts/src/mcp.ts @@ -137,12 +137,14 @@ export const mcpConnectionCreateSchema = z.object({ mode: mcpModeSchema.default("observer"), permissions: uniqueStrings, scope: mcpScopeSchema, + selectAllServers: z.literal(true).optional(), dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"), autonomousDangerousOperationIds: uniqueStrings.default([]), limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})), }).strict().refine(input => input.authority === "service" ? input.expiresAt === null && input.mode === "autonomous" && input.dangerousPolicy === "approval" && !input.autonomousDangerousOperationIds.length : input.expiresAt !== null, "Для сервисного подключения выберите автономный режим с подтверждением опасных действий. Для личного подключения укажите срок действия.") + .refine(input => !input.selectAllServers || !input.scope.serverIds.length, "Выберите все серверы или укажите конкретные ID") export const mcpConnectionSchema = z.object({ id: z.string().uuid(), name: z.string(), ownerId: z.string(), policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant, diff --git a/tests/e2e/mcp-auth-context.spec.ts b/tests/e2e/mcp-auth-context.spec.ts index dbdd135a..7ee4a5c8 100644 --- a/tests/e2e/mcp-auth-context.spec.ts +++ b/tests/e2e/mcp-auth-context.spec.ts @@ -26,6 +26,10 @@ async function setup(page: Page, permissions: string[], access: { expiresAt?: st 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}` && method === 'PUT') { + const { name, selectAllServers, scope, ...policy } = request.postDataJSON() + return json({ ...connection, name, policy: { ...connection.policy, ...policy, scope: selectAllServers ? { ...scope, serverIds: [1, 2] } : scope }, ownerValidUntil }) + } 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 }) @@ -332,6 +336,52 @@ test('synthetic: issue only selected server/read permission and hide one-time to await expect(token).toHaveCount(0) }) +test('synthetic: edit autonomous dangerous operations by group or all at once', async ({ page }) => { + const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read']) + const danger = { ...read, effect: 'write', risk: 'dangerous' } + const logs = { ...danger, id: 'test.logs.change', toolName: 'mm_test_logs_change', title: 'Изменить журналы' } + const network = { ...danger, id: 'test.network.change', toolName: 'mm_test_network_change', title: 'Изменить сеть', section: 'network' } + const unchecked = { ...network, id: 'test.network.other', toolName: 'mm_test_network_other', title: 'Другая операция сети' } + await page.route('**/api/mcp/catalog', route => route.fulfill({ json: { stage: 'runtime', executionAvailable: true, operations: [read, logs, network, unchecked] } })) + await page.goto('/mcp?tab=connections') + await page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' }).getByRole('button', { name: 'Разрешения', exact: true }).click() + const dialog = page.getByRole('dialog', { name: 'Изменить разрешения' }) + const next = dialog.getByRole('button', { name: 'Далее', exact: true }) + await dialog.getByLabel('Режим управления', { exact: true }).selectOption('autonomous') + await next.click() + const allServers = dialog.getByRole('checkbox', { name: 'Все серверы', exact: true }) + const serverIds = dialog.getByLabel('ID разрешённых серверов через запятую') + await expect(allServers).not.toBeChecked() + await expect(serverIds).toHaveValue('1') + await allServers.check() + await expect(serverIds).toHaveCount(0) + await allServers.uncheck() + await expect(serverIds).toHaveValue('1') + await allServers.check() + await dialog.getByRole('button', { name: 'Выбрать все операции', exact: true }).click() + await dialog.locator('summary').filter({ hasText: 'Сеть и маршрутизация' }).click() + await dialog.getByRole('checkbox', { name: unchecked.title, exact: true }).uncheck() + await next.click() + await dialog.getByLabel('Опасные действия', { exact: true }).selectOption('explicit-allow') + const selectAll = dialog.getByRole('button', { name: 'Выбрать все опасные операции' }) + await selectAll.click() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 2') + await dialog.getByRole('button', { name: 'Снять все' }).click() + await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 1') + await selectAll.click() + await next.click() + await expect(dialog.getByText(/Серверы: все на момент сохранения/)).toBeVisible() + await expect(dialog.getByText('Опасных операций выбрано для автономного выполнения: 2.')).toBeVisible() + await dialog.getByRole('button', { name: 'Сохранить доступ' }).click() + await expect(dialog).toBeHidden() + expect(state.mutations).toEqual([expect.objectContaining({ path: `/api/mcp/connections/${id}`, body: expect.objectContaining({ + selectAllServers: true, + scope: { serverIds: [], operationIds: [read.id, logs.id, network.id], allowGlobal: false }, + autonomousDangerousOperationIds: [logs.id, network.id], + }) })]) +}) + test('synthetic: issue service access with no expiry and mandatory approval of dangerous actions', async ({ page }) => { const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read']) await page.goto('/mcp?tab=connections')