fix(mcp): заменить ввод ID выбором карточек серверов
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m19s
Docker images / frontend-image (push) Successful in 3m44s
Docker images / updater-image (push) Successful in 1m58s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-image (push) Successful in 4m0s
Docker images / publish-release (push) Failing after 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m19s
Docker images / frontend-image (push) Successful in 3m44s
Docker images / updater-image (push) Successful in 1m58s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-image (push) Successful in 4m0s
Docker images / publish-release (push) Failing after 12s
Docker images / notify-webhook (push) Successful in 2s
This commit is contained in:
1 parent
04c3b1e482
commit
e9639313c6
9 files changed
+120
-24
No files matched your search
@@ -555,6 +555,13 @@
|
||||
"operations": [],
|
||||
"reason": "Управление самим MCP, транспорт или машинная авторизация: отдельного AI-инструмента нет."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/mcp/server-choices",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Каталог выбора серверов для выдачи доступа в панели MCP."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/mcp/connections/:id/grants",
|
||||
|
||||
@@ -48,6 +48,7 @@ const RULES: Rule[] = [
|
||||
{ methods: ["POST"], match: p => p === "/api/mcp/oauth/consent", permission: "mm:mcp:read" },
|
||||
{ methods: ["POST"], match: p => /^\/api\/mcp\/connections\/[^/]+\/revalidate$/.test(p), permission: "mm:mcp:read" },
|
||||
{ methods: ["GET"], match: p => p === "/api/mcp/catalog", permission: "mm:mcp:read" },
|
||||
{ methods: ["GET"], match: p => p === "/api/mcp/server-choices", permission: "mm:mcp:read" },
|
||||
{ methods: ["GET"], match: p => p.startsWith("/api/mcp/devices/"), permission: "mm:mcp:read" },
|
||||
{ methods: ["GET"], match: p => /^\/api\/mcp\/(?:overview|connections|requests|plans|operations|protections|drift|audit|artifacts|routing-profiles)(?:\/|$)/.test(p), permission: "mm:mcp:read" },
|
||||
{ methods: ["POST"], match: p => /^\/api\/mcp\/plans\/(?:[^/]+)\/decision$/.test(p), permission: "mm:mcp:approve" },
|
||||
|
||||
@@ -111,6 +111,30 @@ try {
|
||||
} finally { pool.query = originalQuery; pool.connect = originalConnect }
|
||||
// Human JWT authentication stays outside the delegated MCP credential failure.
|
||||
const connectionSql = "SELECT * FROM mcp_connections WHERE id=$1"
|
||||
const serverChoicesUrl = "/api/mcp/server-choices"
|
||||
const scopedChoicesUrl = `${serverChoicesUrl}?connectionId=${createBody.connectionId}`
|
||||
const readMcp = { authorization: "Bearer " + await token(["mm:mcp:read"]) }
|
||||
let catalogOwnerId = "human-admin"
|
||||
const serverScopeQueries: unknown[] = []
|
||||
pool.query = (async (sql: string, values?: unknown[]) => {
|
||||
if (sql === connectionSql) return { rows: [{ id: createBody.connectionId, owner_id: catalogOwnerId, policy: payload.policy }] }
|
||||
assert.match(sql, /^SELECT id,name,host,enabled FROM servers/)
|
||||
serverScopeQueries.push(values?.[0])
|
||||
return { rows: [{ id: "1", name: "CHR test", host: "router.example.test", enabled: true, password: "synthetic-hidden" }] }
|
||||
}) as typeof pool.query
|
||||
try {
|
||||
assert.equal((await app.inject({ url: serverChoicesUrl })).statusCode, 401)
|
||||
assert.equal((await app.inject({ url: serverChoicesUrl, headers: readMcp })).statusCode, 403)
|
||||
const full = await app.inject({ url: serverChoicesUrl, headers: admin })
|
||||
const scoped = await app.inject({ url: scopedChoicesUrl, headers: readMcp })
|
||||
for (const response of [full, scoped]) {
|
||||
assert.equal(response.statusCode, 200)
|
||||
assert.deepEqual(response.json(), { servers: [{ id: 1, name: "CHR test", host: "router.example.test", enabled: true }] })
|
||||
}
|
||||
catalogOwnerId = "another-owner"
|
||||
assert.equal((await app.inject({ url: scopedChoicesUrl, headers: readMcp })).statusCode, 404)
|
||||
assert.deepEqual(serverScopeQueries, [null, [1]])
|
||||
} finally { pool.query = originalQuery }
|
||||
const credentialSql = `SELECT c.id,c.expires_at FROM mcp_credentials c WHERE c.connection_id=$1 AND c.kind='bearer'
|
||||
AND c.revoked_at IS NULL AND c.expires_at>now() AND NOT EXISTS(SELECT 1 FROM mcp_grants g WHERE g.payload->>'credentialId'=c.id::text)
|
||||
ORDER BY c.created_at DESC LIMIT 1`
|
||||
|
||||
@@ -160,6 +160,21 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
|
||||
})
|
||||
|
||||
app.get("/mcp/connections", async request => ({ connections: await listMcpConnections(actorOf(request.authUser)) }))
|
||||
app.get("/mcp/server-choices", async request => {
|
||||
const { connectionId } = z.object({ connectionId: uuid.optional() }).strict().parse(request.query)
|
||||
const actor = actorOf(request.authUser)
|
||||
let serverIds: number[] | null = null
|
||||
if (connectionId) {
|
||||
const connection = await getConnection(connectionId)
|
||||
assertConnectionVisible(connection, actor)
|
||||
serverIds = connection.policy.scope.serverIds
|
||||
} else if (!hasPermission(actor.permissions, "mm:mcp:admin")) {
|
||||
throw new McpError("PERMISSION_DENIED", "Полный каталог доступен администратору MCP", 403)
|
||||
}
|
||||
const { rows } = await pool.query<{ id: string; name: string; host: string; enabled: boolean }>(
|
||||
"SELECT id,name,host,enabled FROM servers WHERE $1::bigint[] IS NULL OR id=ANY($1::bigint[]) ORDER BY name,id", [serverIds])
|
||||
return { servers: rows.map(row => ({ id: Number(row.id), name: row.name, host: row.host, enabled: row.enabled })) }
|
||||
})
|
||||
app.post("/mcp/connections", async request => {
|
||||
const input = mcpConnectionCreateSchema.parse(request.body)
|
||||
const available = new Set(listActions().map(action => action.operation.id))
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { useTable, type ColumnDef } from "@tanstack/react-table"
|
||||
import { BotIcon, CopyIcon, PlusIcon, RefreshCwIcon, ShieldIcon, StopCircleIcon } from "lucide-react"
|
||||
import { BotIcon, CheckIcon, CopyIcon, PlusIcon, RefreshCwIcon, ServerIcon, ShieldIcon, StopCircleIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { mcpConnectionCreateSchema, mcpPageQuerySchema, mcpTargetSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp"
|
||||
import { routeAiControllerBlockReason, routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
@@ -25,6 +25,7 @@ import { Badge } from "@/components/reui/badge"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
|
||||
@@ -200,12 +201,46 @@ function OperationChoices({ operations, selected, onChange, selectAllLabel = "В
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
function ServerChoices({ catalog, selected, onChange, all, onAllChange, forGrant = false }: {
|
||||
catalog: { data: Awaited<ReturnType<McpApi["serverChoices"]>> | null; error: string; refresh: () => void }
|
||||
selected: number[]
|
||||
onChange: (ids: number[]) => void
|
||||
all: boolean
|
||||
onAllChange: (value: boolean) => void
|
||||
forGrant?: boolean
|
||||
}) {
|
||||
const servers = catalog.data?.servers ?? []
|
||||
const unknown = catalog.data ? selected.filter(id => !servers.some(server => server.id === id)) : []
|
||||
return <fieldset className="min-w-0 space-y-2">
|
||||
<legend className="mb-2 text-sm font-medium">{forGrant ? "Серверы временного допуска" : "Разрешённые серверы"}</legend>
|
||||
<Choice label={forGrant ? "Все серверы подключения" : "Все серверы"} checked={all} onChange={onAllChange} />
|
||||
{all ? <><p className="text-sm text-muted-foreground">{forGrant ? "Выбраны серверы, разрешённые основному подключению." : "Доступ получат все серверы, зарегистрированные на момент сохранения."}</p>{forGrant && <ErrorMessage message={catalog.error} />}</> : <>
|
||||
<div className="grid max-h-60 gap-2 overflow-y-auto p-1 sm:grid-cols-2" aria-label="Карточки серверов" role="group">
|
||||
{servers.map(server => {
|
||||
const active = selected.includes(server.id), title = server.name || server.host
|
||||
return <Item key={server.id} variant="outline" size="sm" className="cursor-pointer text-left hover:bg-muted aria-pressed:border-primary aria-pressed:bg-accent"
|
||||
render={<button type="button" aria-label={title} aria-pressed={active} />}
|
||||
onClick={() => onChange(active ? selected.filter(id => id !== server.id) : [...selected, server.id])}>
|
||||
<ItemMedia variant="icon"><ServerIcon /></ItemMedia>
|
||||
<ItemContent className="min-w-0"><ItemTitle className="block max-w-full truncate">{title}</ItemTitle><ItemDescription className="break-all">{server.host !== title ? `${server.host} · ` : ""}ID {server.id}{!server.enabled && " · отключён"}</ItemDescription></ItemContent>
|
||||
{active && <CheckIcon className="size-4 shrink-0" aria-hidden="true" />}
|
||||
</Item>
|
||||
})}
|
||||
{unknown.map(id => <Button key={id} variant="outline" onClick={() => onChange(selected.filter(value => value !== id))}>Убрать отсутствующий сервер №{id}</Button>)}
|
||||
</div>
|
||||
{catalog.error && <><ErrorMessage message={catalog.error} /><Button variant="outline" size="sm" onClick={catalog.refresh}>Обновить список серверов</Button></>}
|
||||
{!catalog.data && !catalog.error && <p role="status" className="text-sm text-muted-foreground">Загрузка серверов…</p>}
|
||||
{catalog.data && <p className="text-sm text-muted-foreground">{selected.length ? `Выбрано серверов: ${selected.length}` : "Серверы не выбраны. Доступ к ним закрыт."}</p>}
|
||||
</>}
|
||||
</fieldset>
|
||||
}
|
||||
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 [serverIds, setServerIds] = useState(editing?.policy.scope.serverIds ?? []), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
|
||||
const serverCatalog = useQuery(useCallback(signal => api.serverChoices(undefined, signal), [api]))
|
||||
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))
|
||||
@@ -218,7 +253,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
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))], ...(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 })
|
||||
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 ? [] : serverIds, 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) }
|
||||
@@ -229,10 +264,7 @@ 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 && <>
|
||||
<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></>}
|
||||
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} />
|
||||
<Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} />
|
||||
<OperationChoices operations={eligible} selected={selected} onChange={setSelected} />
|
||||
<p className="text-xs text-muted-foreground">Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.</p>
|
||||
@@ -241,7 +273,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
<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>}
|
||||
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {service ? "Сервисное, бессрочное" : modeLabels[mode]}</p><p>Серверы: {selectAllServers ? "все на момент сохранения" : serverIds.join(", ") || "не выбраны"}. Операций: {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>
|
||||
}
|
||||
@@ -313,8 +345,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
||||
grantBusy: boolean
|
||||
}) {
|
||||
const [result, setResult] = useState<Awaited<ReturnType<McpApi["check"]>> | null>(null)
|
||||
const [operations, setOperations] = useState<string[]>([]), [serverText, setServerText] = useState(""), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false)
|
||||
const [serverIds, setServerIds] = useState<number[]>([]), [selectAllServers, setSelectAllServers] = useState(false)
|
||||
const [operations, setOperations] = useState<string[]>([]), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false)
|
||||
const connectionId = connection.id
|
||||
const serverCatalog = useQuery(useCallback(signal => api.serverChoices(connectionId, signal), [api, connectionId]), connectionId)
|
||||
const grantServers = selectAllServers ? serverCatalog.data?.servers.map(server => server.id) ?? [] : serverIds
|
||||
const grants = useQuery(useCallback(signal => api.grants(connectionId, signal), [api, connectionId]))
|
||||
const checkRevision = useRef(0)
|
||||
useEffect(() => () => { checkRevision.current++ }, [])
|
||||
@@ -335,7 +370,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
||||
try {
|
||||
void issue({
|
||||
id: crypto.randomUUID(), startsAt: now.toISOString(), expiresAt: expires.toISOString(),
|
||||
scope: { serverIds: serverText.split(",").map(value => value.trim()).filter(Boolean).map(Number), operationIds: operations, allowGlobal: global },
|
||||
scope: { serverIds: grantServers, operationIds: operations, allowGlobal: global },
|
||||
})
|
||||
} catch (error) {
|
||||
toast.error(errorText(error))
|
||||
@@ -353,13 +388,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
||||
</p>}
|
||||
<pre className="overflow-auto rounded bg-muted p-3 text-xs">{pretty(result)}</pre>
|
||||
</>}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label={`Серверы допуска (доступны: ${connection.policy.scope.serverIds.join(", ")})`}><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="ID через запятую" /></Field>
|
||||
<Field label="Срок допуска, минут"><Input type="number" min={1} max={1440} value={minutes} onChange={event => setMinutes(Number(event.target.value))} /></Field>
|
||||
</div>
|
||||
<ServerChoices catalog={serverCatalog} selected={serverIds} onChange={setServerIds} all={selectAllServers} onAllChange={setSelectAllServers} forGrant />
|
||||
<Field label="Срок допуска, минут"><Input type="number" min={1} max={1440} value={minutes} onChange={event => setMinutes(Number(event.target.value))} /></Field>
|
||||
{connection.policy.scope.allowGlobal && <Choice label="Разрешить глобальные действия в допуске" checked={global} onChange={setGlobal} />}
|
||||
<div className="grid max-h-60 gap-2 overflow-y-auto sm:grid-cols-2">{connection.policy.scope.operationIds.map(id => <Choice key={id} label={id} checked={operations.includes(id)} onChange={checked => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}</div>
|
||||
<Button className="self-start" disabled={grantBusy || !operations.length || connection.policy.status !== "active"} onClick={create}>Выдать временный допуск</Button>
|
||||
<Button className="self-start" disabled={grantBusy || !operations.length || connection.policy.status !== "active" || (selectAllServers && !serverCatalog.data)} onClick={create}>Выдать временный допуск</Button>
|
||||
{grants.data?.grants.map(grant => <div key={grant.id} className="flex flex-wrap items-center justify-between gap-2 rounded border p-3 text-sm">
|
||||
<span>До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"}</span>
|
||||
<Button size="sm" variant="outline" disabled={!!grant.revoked_at} onClick={() => { void api.revokeGrant(grant.id).then(grants.refresh, error => toast.error(errorText(error))) }}>Отозвать допуск</Button>
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
- **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию.
|
||||
- **Серверы и операции** — только те, что нужны агенту.
|
||||
- «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений.
|
||||
- Пустой список ID при выключенной опции «Все серверы» закрывает доступ ко всем серверам.
|
||||
- Для выборочного доступа отметьте карточки нужных серверов. Если «Все серверы» выключено и ни одна карточка не отмечена, доступ к серверам закрыт.
|
||||
- Операция, не выданная подключению, получает `OPERATION_DENIED`.
|
||||
- Сервер вне списка получает `SERVER_DENIED`.
|
||||
- Глобальные операции работают только с «Разрешить выбранные глобальные операции».
|
||||
|
||||
@@ -13,6 +13,8 @@ export function mcpApi(base: string) {
|
||||
const get = async <T>(path: string, schema: z.ZodType<T>, signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { signal }))
|
||||
const send = async <T>(path: string, body: unknown, schema: z.ZodType<T>, method = "POST", signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { method, body: JSON.stringify(body), signal }))
|
||||
return {
|
||||
serverChoices: (connectionId?: string, signal?: AbortSignal) => get(connectionId ? "/server-choices?" + new URLSearchParams({ connectionId }) : "/server-choices",
|
||||
deviceCatalogSchema.pick({ servers: true }), signal),
|
||||
downloadArtifact: (receipt: unknown, signal?: AbortSignal) => downloadHumanArtifact(base, receipt, signal),
|
||||
coverage: (signal?: AbortSignal) => get("/coverage", z.object({ version: z.literal(1), routes: z.array(z.object({ method: z.string(), path: z.string(), status: z.enum(["mediated", "excluded", "pending"]), operations: z.array(z.string()), reason: z.string() })) }), signal),
|
||||
uploadRestoreArchive: async (file: File, signal?: AbortSignal) => restoreArchiveSchema.parse(await requestJson(base, "/api/mcp/database/archives", { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file, signal })),
|
||||
|
||||
@@ -24,6 +24,10 @@ async function setup(page: Page, permissions: string[], access: { expiresAt?: st
|
||||
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/server-choices') return json({ servers: [
|
||||
{ id: 1, name: 'CHR WAN', host: 'wan.example.test', enabled: true },
|
||||
{ id: 2, name: 'CHR LAN', host: 'lan.example.test', enabled: true },
|
||||
] })
|
||||
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') {
|
||||
@@ -305,7 +309,10 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
||||
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')
|
||||
const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true })
|
||||
await wan.click()
|
||||
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||
await expect(dialog.getByRole('button', { name: 'CHR LAN', exact: true })).toHaveAttribute('aria-pressed', 'false')
|
||||
await dialog.getByRole('button', { name: 'Выбрать все операции' }).click()
|
||||
await expect(dialog.getByRole('status')).toHaveText('Выбрано 3')
|
||||
await dialog.getByRole('button', { name: 'Снять все' }).click()
|
||||
@@ -350,13 +357,13 @@ test('synthetic: edit autonomous dangerous operations by group or all at once',
|
||||
await dialog.getByLabel('Режим управления', { exact: true }).selectOption('autonomous')
|
||||
await next.click()
|
||||
const allServers = dialog.getByRole('checkbox', { name: 'Все серверы', exact: true })
|
||||
const serverIds = dialog.getByLabel('ID разрешённых серверов через запятую')
|
||||
const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true })
|
||||
await expect(allServers).not.toBeChecked()
|
||||
await expect(serverIds).toHaveValue('1')
|
||||
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||
await allServers.check()
|
||||
await expect(serverIds).toHaveCount(0)
|
||||
await expect(wan).toHaveCount(0)
|
||||
await allServers.uncheck()
|
||||
await expect(serverIds).toHaveValue('1')
|
||||
await expect(wan).toHaveAttribute('aria-pressed', 'true')
|
||||
await allServers.check()
|
||||
await dialog.getByRole('button', { name: 'Выбрать все операции', exact: true }).click()
|
||||
await dialog.locator('summary').filter({ hasText: 'Сеть и маршрутизация' }).click()
|
||||
@@ -392,7 +399,7 @@ test('synthetic: issue service access with no expiry and mandatory approval of d
|
||||
await dialog.getByLabel('Тип подключения', { exact: true }).selectOption('service')
|
||||
await expect(dialog.getByLabel('Срок действия (UTC)', { exact: true })).toHaveCount(0)
|
||||
await next.click()
|
||||
await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
|
||||
await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click()
|
||||
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
|
||||
await next.click()
|
||||
await expect(dialog.getByText('Опасные действия всегда требуют подтверждения.')).toBeVisible()
|
||||
|
||||
@@ -17,6 +17,7 @@ async function setup(page: Page, fail = false) {
|
||||
const json = (body: unknown) => route.fulfill({ headers, json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] })
|
||||
if (path === "/api/mcp/server-choices") return json({ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }] })
|
||||
if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] })
|
||||
if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at })
|
||||
if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] })
|
||||
@@ -414,7 +415,7 @@ test("MCP: доступ, проверка подключения, выдача
|
||||
await page.getByRole("button", { name: "Выдать доступ", exact: true }).click()
|
||||
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||
await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
|
||||
await page.getByRole("button", { name: "CHR lab", exact: true }).click()
|
||||
await page.locator("summary").filter({ hasText: "Журналы" }).click()
|
||||
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
|
||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||
@@ -478,13 +479,19 @@ test("MCP: временные допуски и результаты прове
|
||||
await expect(revoke).toBeVisible()
|
||||
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()])
|
||||
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
||||
await Promise.all([
|
||||
const serverCard = page.getByRole("button", { name: "CHR lab", exact: true })
|
||||
await serverCard.click()
|
||||
await expect(serverCard).toHaveAttribute("aria-pressed", "true")
|
||||
await page.getByRole("checkbox", { name: "Все серверы подключения", exact: true }).check()
|
||||
const [issuedRequest] = await Promise.all([
|
||||
page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)),
|
||||
create.click(),
|
||||
])
|
||||
expect(issuedRequest.postDataJSON().scope.serverIds).toEqual([1])
|
||||
|
||||
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)])
|
||||
await expect(revoke).toHaveCount(0)
|
||||
await expect(serverCard).toHaveAttribute("aria-pressed", "false")
|
||||
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
|
||||
await expect(create).toBeDisabled()
|
||||
releaseOtherGrants()
|
||||
|
||||
Reference in new issue
Block a user