feat(mcp): добавить выбор всех серверов и группы опасных операций
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Canceled after 1m59s
Docker images / backend-image (push) Canceled after 0s
Docker images / frontend-image (push) Canceled after 0s
Docker images / updater-image (push) Canceled after 0s
Docker images / netflow-agent-image (push) Canceled after 0s
Docker images / publish-release (push) Canceled after 0s
Docker images / notify-webhook (push) Canceled after 0s

This commit is contained in:
Denozordec committed 2026-11-22 02:32:54 +07:00
1 parent 776dea6a77
commit 04c3b1e482
6 files changed
+162 -49

No files matched your search

@@ -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,
+20 -10
View File
@@ -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<typeof mcpTemporaryGrantSchema>): 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<ConnectionRow>("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<ConnectionRow>("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 })
+58 -38
View File
@@ -157,20 +157,15 @@ function DeviceEditor({ api, connectionId, serverId, resource }: { api: McpApi;
function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) {
return <Dialog open={!!token} onOpenChange={open => { if (!open) close() }}><DialogContent className="sm:max-w-xl"><DialogHeader><DialogTitle>Доступ создан</DialogTitle><DialogDescription>{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя.</DialogDescription></DialogHeader><Input aria-label="Одноразовый токен MCP" readOnly type="password" value={token} /><Button onClick={() => { void navigator.clipboard.writeText(token).then(() => toast.success("Токен скопирован"), () => toast.error("Не удалось скопировать токен")) }}><CopyIcon />Копировать</Button><Button variant="outline" onClick={close}>Закрыть и скрыть токен</Button></DialogContent></Dialog>
}
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<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
const [service, setService] = useState(editing?.policy.authority === "service")
const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState<string[]>(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<string, McpOperationDescriptor[]>()
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 <>
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" disabled={!operations.length} onClick={() => onChange(operations.map(operation => operation.id))}>{selectAllLabel}</Button>
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => onChange([])}>Снять все</Button>
<span className="text-sm text-muted-foreground" role="status">Выбрано {selected.length}</span>
</div>
<div className="max-h-80 space-y-2 overflow-y-auto">
{groups.map(([section, items]) => {
const title = operationSectionLabels[section] ?? section
const count = items.filter(operation => selectedIds.has(operation.id)).length
return <div key={section} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3 rounded-md border p-3">
<Checkbox aria-label={`Все операции группы «${title}»`} className="mt-0.5" checked={count === items.length} indeterminate={count > 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} />
<details>
<summary className="cursor-pointer text-sm font-medium">{title} <span className="ms-1 font-normal text-muted-foreground">{count} / {items.length}</span></summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
{items.map(operation => <Choice key={operation.id} label={operation.title} checked={selectedIds.has(operation.id)} onChange={checked => selectOperations([operation], checked)} />)}
</div>
</details>
</div>
})}
{!operations.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
</div>
</>
}
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<McpConnection["policy"]["mode"]>(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<string[]>(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
? <p className="text-sm text-muted-foreground">Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.</p>
: <><Field label="Срок действия (UTC)"><Input type="datetime-local" value={expires} onChange={event => setExpires(event.target.value)} /></Field><NativeSelect label="Режим управления" value={mode} onChange={value => setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => <option key={value} value={value}>{title}</option>)}</NativeSelect></>}</>}
{step === 2 && <>
<Field label="ID разрешённых серверов через запятую"><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="1, 2" /></Field>
<Choice label="Все серверы" checked={selectAllServers} onChange={setSelectAllServers} />
{selectAllServers
? <p className="text-sm text-muted-foreground">Доступ получат все серверы, зарегистрированные на момент сохранения.</p>
: <><Field label="ID разрешённых серверов через запятую"><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="1, 2" /></Field><p className="text-sm text-muted-foreground">Пустой список означает, что доступ к серверам закрыт.</p></>}
<Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} />
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" disabled={!eligible.length} onClick={() => setSelected(eligible.map(operation => operation.id))}>Выбрать все операции</Button>
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => setSelected([])}>Снять все</Button>
<span className="text-sm text-muted-foreground" role="status">Выбрано {selected.length}</span>
</div>
<div className="max-h-80 space-y-2 overflow-y-auto">
{groups.map(([section, items]) => {
const title = operationSectionLabels[section] ?? section
const count = items.filter(operation => selectedIds.has(operation.id)).length
return <div key={section} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3 rounded-md border p-3">
<Checkbox aria-label={`Все операции группы «${title}»`} className="mt-0.5" checked={count === items.length} indeterminate={count > 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} />
<details>
<summary className="cursor-pointer text-sm font-medium">{title} <span className="ms-1 font-normal text-muted-foreground">{count} / {items.length}</span></summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
{items.map(operation => <Choice key={operation.id} label={operation.title} checked={selectedIds.has(operation.id)} onChange={checked => selectOperations([operation], checked)} />)}
</div>
</details>
</div>
})}
{!eligible.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
</div>
<OperationChoices operations={eligible} selected={selected} onChange={setSelected} />
<p className="text-xs text-muted-foreground">Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.</p>
</>}
{step === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div>{service ? <p className="text-sm text-muted-foreground">Опасные действия всегда требуют подтверждения.</p> : <><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => <Choice key={operation.id} label={operation.title} checked={dangerIds.includes(operation.id)} onChange={checked => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}</>}</>}
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {service ? "Сервисное, бессрочное" : modeLabels[mode]}</p><p>Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p><p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
{step === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div>{service ? <p className="text-sm text-muted-foreground">Опасные действия всегда требуют подтверждения.</p> : <><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && <>
<p className="text-sm text-muted-foreground">В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.</p>
<OperationChoices operations={dangerous} selected={autonomousDangerIds} onChange={setDangerIds} selectAllLabel="Выбрать все опасные операции" />
</>}</>}</>}
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {service ? "Сервисное, бессрочное" : modeLabels[mode]}</p><p>Серверы: {selectAllServers ? "все на момент сохранения" : serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p>{!service && mode === "autonomous" && danger === "explicit-allow" && <p>Опасных операций выбрано для автономного выполнения: {autonomousDangerIds.length}.</p>}<p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
<div className="flex flex-wrap justify-between gap-2"><Button variant="outline" disabled={busy} onClick={() => step > 1 ? setStep(step - 1) : close()}>{step > 1 ? "Назад" : "Отмена"}</Button>{step < 4 ? <Button onClick={() => setStep(step + 1)}>Далее</Button> : <Button disabled={busy} onClick={() => { void save() }}>{busy ? "Сохранение…" : "Сохранить доступ"}</Button>}</div>
</DialogContent></Dialog>
}
+2
View File
@@ -65,6 +65,8 @@
- **«Срок действия (UTC)»** — не больше года. Для первого шага достаточно нескольких дней.
- **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию.
- **Серверы и операции** — только те, что нужны агенту.
- «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений.
- Пустой список ID при выключенной опции «Все серверы» закрывает доступ ко всем серверам.
- Операция, не выданная подключению, получает `OPERATION_DENIED`.
- Сервер вне списка получает `SERVER_DENIED`.
- Глобальные операции работают только с «Разрешить выбранные глобальные операции».
+2
View File
@@ -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,
+50
View File
@@ -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')