Compare commits

...
5 Commits
Author SHA1 Message Date
Denozordec e9639313c6 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
2026-11-22 02:41:58 +07:00
Denozordec 04c3b1e482 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
2026-11-22 02:32:54 +07:00
Denozordec 776dea6a77 feat(mcp): добавить бессрочные сервисные подключения
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 13m33s
Docker images / backend-image (push) Canceled after 0s
Docker images / frontend-image (push) Canceled after 3s
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
2026-11-22 02:18:33 +07:00
Denozordec f27fd035bc fix(mcp): упростить выбор разрешений и ускорить сборку фронтенда
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m30s
Docker images / frontend-image (push) Successful in 4m16s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 4m5s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-22 01:51:25 +07:00
Denozordec cad54635a8 fix(mcp): восстановить прокрутку раздела
Docker images / prepare-release (push) Successful in 14s
Docker images / backend-test (push) Successful in 12m5s
Docker images / frontend-image (push) Successful in 3m59s
Docker images / updater-image (push) Successful in 2m43s
Docker images / netflow-agent-image (push) Successful in 41s
Docker images / backend-image (push) Successful in 3m48s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-22 01:23:34 +07:00
13 changed files with 472 additions and 45 deletions

No files matched your search

+48 -1
View File
@@ -19,12 +19,39 @@ jobs:
tag: ${{ steps.release.outputs.tag }}
bump: ${{ steps.release.outputs.bump }}
release_url: ${{ steps.release.outputs.release_url }}
backend_reuse_version: ${{ steps.changes.outputs.backend_reuse_version }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check if the released backend can be reused
id: changes
shell: bash
env:
EVENT_NAME: ${{ gitea.event_name }}
BEFORE_SHA: ${{ gitea.event.before }}
run: |
set -euo pipefail
if [[ "$EVENT_NAME" != push || ! "$BEFORE_SHA" =~ ^[0-9a-f]{40}$ ]] ||
! git merge-base --is-ancestor "$BEFORE_SHA" HEAD 2>/dev/null; then
exit 0
fi
# Compare with a published release, including changes from any failed earlier run.
BASE_TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' "$BEFORE_SHA" 2>/dev/null || true)
if [[ ! "$BASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || git diff --quiet "$BASE_TAG" HEAD --; then
exit 0
fi
if git diff --quiet --no-renames "$BASE_TAG" HEAD -- . \
':(exclude)app/**' ':(exclude)components/**' ':(exclude)lib/**' ':(exclude)shared/**' \
':(exclude)entities/**' ':(exclude)public/**' ':(exclude)hooks/**' ':(exclude)tests/e2e/**' \
':(exclude)Dockerfile.frontend' ':(exclude)next.config.ts' ':(exclude)tsconfig.json' \
':(exclude)postcss.config.mjs' ':(exclude)eslint.config.mjs' ':(exclude)components.json' \
':(exclude,top,glob)playwright*.config.ts'; then
echo "backend_reuse_version=${BASE_TAG#v}" >> "$GITHUB_OUTPUT"
fi
- name: Test release version calculation
run: node --test .ci/scripts/compute-release.test.mjs
@@ -42,17 +69,21 @@ jobs:
test -f .ci/release/release-manifest.json
backend-test:
needs: prepare-release
runs-on: ubuntu-latest
steps:
- name: Checkout
if: needs.prepare-release.outputs.backend_reuse_version == ''
uses: actions/checkout@v4
- name: Setup Node 22
if: needs.prepare-release.outputs.backend_reuse_version == ''
uses: actions/setup-node@v4
with:
node-version: 22
- name: Start PostgreSQL 18
if: needs.prepare-release.outputs.backend_reuse_version == ''
shell: bash
run: |
set -euo pipefail
@@ -93,6 +124,7 @@ jobs:
exit 1
- name: Install and test backend
if: needs.prepare-release.outputs.backend_reuse_version == ''
shell: bash
env:
REQUIRE_TEST_POSTGRES: "1"
@@ -112,7 +144,7 @@ jobs:
npm run test --prefix backend
- name: Stop PostgreSQL
if: always()
if: always() && needs.prepare-release.outputs.backend_reuse_version == ''
shell: bash
run: docker rm -f "${PG_CONTAINER:-}" 2>/dev/null || true
@@ -123,6 +155,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
if: needs.prepare-release.outputs.backend_reuse_version == ''
uses: actions/checkout@v4
- name: Configure backend image name
@@ -135,6 +168,7 @@ jobs:
echo "IMAGE_NAME=${{ env.REGISTRY }}/${owner}/${stem}-backend" >> "${GITHUB_ENV}"
- name: Prepare backend build context
if: needs.prepare-release.outputs.backend_reuse_version == ''
shell: bash
run: |
set -euo pipefail
@@ -174,6 +208,7 @@ jobs:
password: ${{ secrets.ACTIONS_PAT }}
- name: Build and push backend image
if: needs.prepare-release.outputs.backend_reuse_version == ''
uses: docker/build-push-action@v5
with:
context: .ci/docker/backend
@@ -195,6 +230,18 @@ jobs:
org.opencontainers.image.revision=${{ gitea.sha }}
org.opencontainers.image.created=${{ gitea.event.head_commit.timestamp }}
- name: Tag the existing backend image for this release
if: needs.prepare-release.outputs.backend_reuse_version != ''
shell: bash
env:
BACKEND_VERSION: ${{ needs.prepare-release.outputs.backend_reuse_version }}
RELEASE_VERSION: ${{ needs.prepare-release.outputs.version }}
run: |
set -euo pipefail
docker buildx imagetools create --prefer-index=false \
--tag "$IMAGE_NAME:$GITHUB_SHA" --tag "$IMAGE_NAME:$RELEASE_VERSION" \
"$IMAGE_NAME:$BACKEND_VERSION"
frontend-image:
needs: prepare-release
runs-on: ubuntu-latest
+7
View File
@@ -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",
+1
View File
@@ -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" },
@@ -23,8 +23,9 @@ assert.match(basename(dirname(resolve(process.env.MCP_STATE_DIR))), /^mm-mcp-tes
const { pool, closePool } = await import("../../db/index.js")
const { applySqlMigrations } = await import("../../db/migrate.js")
const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js")
const { mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource } = await import("./store.js")
const { MCP_SERVICE_EXPIRATION, mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource,
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")
@@ -83,6 +84,67 @@ 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,
permissions: ["mm:servers:read"], scope: { serverIds: [], operationIds: ["capabilities.read"], allowGlobal: false } }
const policy = mcpConnectionCreateSchema.parse(payload)
assert.equal(mcpConnectionCreateSchema.safeParse({ ...payload, dangerousPolicy: "explicit-allow" }).success, false)
assert.equal(mcpConnectionCreateSchema.safeParse({ ...payload, authority: undefined }).success, false)
await assert.rejects(createMcpConnection(policy, { ...actor, permissions: policy.permissions }), { code: "PERMISSION_DENIED" })
await assert.rejects(updateMcpConnection(personal.connectionId, policy, actor), { code: "INVALID_CONFIGURATION" })
const shortSession = { ...actor, expiresAt: Date.now() + 250 }
const { connection, token } = await createMcpConnection(policy, shortSession)
connectionIds.push(connection.id)
await new Promise(resolve => setTimeout(resolve, Math.max(0, shortSession.expiresAt - Date.now() + 1)))
const principal = await authenticateMcpToken(token)
const current = await validatePrincipal(principal)
assert.equal(current.policy.authority, "service")
assert.equal(current.owner_valid_until.toISOString(), MCP_SERVICE_EXPIRATION)
assert.equal(principal.credentialExpiresAt, MCP_SERVICE_EXPIRATION)
assert.deepEqual(current.owner_permissions, policy.permissions)
await assert.rejects(revalidateMcpOwner(connection.id, actor), { code: "INVALID_CONFIGURATION" })
const edited = await updateMcpConnection(connection.id, { ...policy, name: "Edited service access" }, actor)
assert.equal(edited.ownerValidUntil, MCP_SERVICE_EXPIRATION)
const rotated = await rotateConnectionToken(connection.id, actor)
await assert.rejects(authenticateMcpToken(token), { code: "UNAUTHORIZED" })
const replacement = await authenticateMcpToken(rotated.token)
await setConnectionStatus(connection.id, "paused", actor)
await assert.rejects(validatePrincipal(replacement), { code: "UNAUTHORIZED" })
await setConnectionStatus(connection.id, "active", actor)
await validatePrincipal(replacement)
await setConnectionStatus(connection.id, "revoked", actor)
await assert.rejects(authenticateMcpToken(rotated.token), { code: "UNAUTHORIZED" })
})
await check("poll current policy tuple: real SQL bounds, clock, backend, scopes and fresh committed updates", async () => {
const f = await fixture()
console.log("Owned poll policy tuple SQL:", JSON.stringify(await checkOwnedPollPolicySource(pool, f.principal.connectionId, f.principal.credentialId)))
@@ -132,12 +194,17 @@ try {
})
await check("actual HMAC portal revoke and private external cutoff interrupt source capture", async () => {
const f = await fixture(), secret = randomBytes(32).toString("hex")
const service = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Revocable service", authority: "service", expiresAt: null,
mode: "autonomous", permissions: [], scope: { serverIds: [], operationIds: ["capabilities.read"] } }), f.actor)
connectionIds.push(service.connection.id)
await validatePrincipal(await authenticateMcpToken(service.token))
await refusalBetween(f, async () => {
const timestamp = String(Math.floor(Date.now() / 1000)), raw = Buffer.from(JSON.stringify({ eventId: randomUUID(), userId: f.actor.id, type: "sessions.revoked" }))
const signature = "sha256=" + createHmac("sha256", secret).update(timestamp + ".").update(raw).digest("hex")
assert.deepEqual(await acceptPortalRevocation(raw, timestamp, signature, secret), { ok: true, duplicate: false })
}, "OWNER_CLAIMS_REVOKED")
await assert.rejects(validatePrincipal(f.principal), { code: "OWNER_CLAIMS_REVOKED" })
await assert.rejects(authenticateMcpToken(service.token), { code: "UNAUTHORIZED" })
})
await check("duplicate signed revocation repairs the external cutoff without moving recorded authority", async () => {
const f = await fixture(), secret = randomBytes(32).toString("hex")
+44 -17
View File
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"
import type { PoolClient, QueryResultRow } from "pg"
import { z } from "zod"
import {
mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
MCP_SERVICE_EXPIRATION, mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
type McpConnection, type McpConnectionCreate, type McpConnectionPolicy,
} from "@mmapp/contracts/mcp"
import { pool } from "../../db/index.js"
@@ -19,6 +19,29 @@ export interface ConnectionRow extends QueryResultRow {
owner_claims_issued_at: Date
}
function ownerValidUntil(actor: AuthUser) { return new Date(Math.min(actor.expiresAt ?? Date.now() + 900000, Date.now() + 86400000)) }
function connectionExpiration(input: McpConnectionCreate, actor: AuthUser) {
if (input.authority === "service" && input.expiresAt === null) {
if (!hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("PERMISSION_DENIED", "Сервисный доступ выдаёт администратор MCP", 403)
return MCP_SERVICE_EXPIRATION
}
const expires = Date.parse(input.expiresAt ?? ""), now = Date.now()
if (!input.expiresAt || !Number.isFinite(expires) || expires <= now || expires > now + 366 * 86400000)
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
@@ -113,38 +136,41 @@ export function assertConnectionVisible(row: ConnectionRow, actor: AuthUser): vo
if (row.owner_id !== actor.id && !hasPermission(actor.permissions, "mm:mcp:admin")) throw new McpError("NOT_FOUND", "Подключение не найдено", 404)
}
export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) {
const expires = Date.parse(input.expiresAt)
if (expires <= Date.now() || expires > Date.now() + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400)
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, id, version: 1, status: "active" })
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 { 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(actor.permissions), JSON.stringify(policy), generation, 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), input.expiresAt])
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 })
return { connection: publicConnection(row, generation), token }
})
}
export async function updateMcpConnection(id: string, input: McpConnectionCreate, actor: AuthUser) {
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 (Date.parse(input.expiresAt) > Date.now() + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа не может превышать год", 400)
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)
await assertPortalClaimsCurrent(actor, client)
}
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
const before = await getConnection(id, client)
if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав")
if (Date.parse(input.expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400)
const { name, ...configuration } = input
const policy = mcpConnectionPolicySchema.parse({ ...configuration, 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(actor.permissions), ownerValidUntil(actor)])
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, 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 })
return publicConnection(row, await accessGeneration())
@@ -169,6 +195,7 @@ export async function revalidateMcpOwner(id: string, actor: AuthUser) {
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
const connection = await getConnection(id, client)
if (connection.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Права подтверждает владелец подключения")
if (connection.policy.authority === "service") throw new McpError("INVALID_CONFIGURATION", "Сервисное подключение не требует подтверждения прав владельца", 400)
const policy = { ...connection.policy, version: connection.policy.version + 1 }
const until = ownerValidUntil(actor)
const { rows: [row] } = await client.query<ConnectionRow>("UPDATE mcp_connections SET owner_permissions=$2::jsonb,owner_valid_until=$3,policy=$4::jsonb,owner_claims_issued_at=$5,updated_at=now() WHERE id=$1 RETURNING *", [id, JSON.stringify(actor.permissions), until, JSON.stringify(policy), new Date(actor.issuedAt ?? 0)])
+24
View File
@@ -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`
+15
View File
@@ -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))
+118 -19
View File
@@ -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,12 +25,18 @@ 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"
const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос"
const modeLabels = { observer: "Наблюдатель", approval: "С подтверждением", autonomous: "Автономный" }
const operationSectionLabels: Record<string, string> = {
backups: "Резервные копии", certificates: "Сертификаты", filters: "Фильтры маршрутизации", firewall: "Межсетевой экран",
ipsec: "IPsec", logs: "Журналы", mcp: "Управление MCP", network: "Сеть и маршрутизация", "recursive-routes": "Рекурсивные маршруты",
servers: "Серверы", settings: "Настройки", traffic: "Трафик", uptime: "Доступность", users: "Пользователи", wireguard: "WireGuard",
}
const tabs = { overview: "Обзор", connections: "Подключения", permissions: "Разрешения", devices: "Интерфейсы", requests: "Обращения", plans: "Планы и операции", routing: "Route AI", settings: "Настройки" }
type Tab = keyof typeof tabs
type RecordRow = Record<string, unknown>
@@ -152,30 +158,122 @@ 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 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 operations) {
const group = bySection.get(operation.section)
if (group) group.push(operation)
else bySection.set(operation.section, [operation])
}
const groups = [...bySection]
.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))
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 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 [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
const [service, setService] = useState(editing?.policy.authority === "service")
const [selectAllServers, setSelectAllServers] = useState(false)
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))
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 toggle = (id: string) => setSelected(ids => ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id])
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, 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: danger, autonomousDangerousOperationIds: 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 ? [] : 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) }
}
return <Dialog open onOpenChange={open => { if (!open && !busy) close() }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl"><DialogHeader><DialogTitle>{editing ? "Изменить разрешения" : "Новое подключение"}</DialogTitle><DialogDescription>Шаг {step} из 4 · доступ ограничивается правами текущего владельца.</DialogDescription></DialogHeader><ErrorMessage message={error} />
{step === 1 && <><Field label="Название"><Input value={name} onChange={event => setName(event.target.value)} placeholder="Агент диагностики" /></Field><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={global} onChange={setGlobal} /><div className="grid max-h-80 gap-2 overflow-y-auto sm:grid-cols-2">{eligible.map(operation => <Choice key={operation.id} label={operation.title} checked={selected.includes(operation.id)} onChange={() => toggle(operation.id)} />)}</div><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><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> · {modeLabels[mode]}</p><p>Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p><p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
{step === 1 && <><Field label="Название"><Input value={name} onChange={event => setName(event.target.value)} placeholder="Агент диагностики" /></Field>{!editing && <NativeSelect label="Тип подключения" value={service ? "service" : "personal"} onChange={value => setService(value === "service")}><option value="personal">Личное</option><option value="service">Сервисное — бессрочный автономный доступ</option></NativeSelect>}
{service
? <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 && <>
<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>
</>}
{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 ? "все на момент сохранения" : 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>
}
@@ -196,9 +294,9 @@ function Connections({ api, operations }: { api: McpApi; operations: McpOperatio
} },
{ id: "mode", header: "Режим", cell: ({ row }) => modeLabels[(row.original.policy as McpConnection["policy"]).mode] },
{ id: "status", header: "Состояние доступа", size: 260, cell: ({ row }) => <ConnectionAccessStatus connection={row.original as unknown as McpConnection} /> },
{ id: "expiresAt", header: "Доступ до", size: 170, cell: ({ row }) => date((row.original.policy as McpConnection["policy"]).expiresAt) },
{ id: "expiresAt", header: "Доступ до", size: 170, cell: ({ row }) => { const policy = row.original.policy as McpConnection["policy"]; return policy.authority === "service" ? "Бессрочно" : date(policy.expiresAt) } },
{ accessorKey: "lastUsedAt", header: "Последний вызов", cell: ({ row }) => date(row.original.lastUsedAt) },
{ id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return <div className="flex flex-col gap-1"><span className="text-xs">{date(connection.ownerValidUntil)}</span>{connection.ownerId === getClaims()?.sub && <Button size="sm" variant="outline" disabled={!connection.generationValid || connection.policy.status === "revoked"} onClick={() => { void act(() => api.revalidate(connection.id)) }}>Обновить мои права</Button>}</div> } },
{ id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return connection.policy.authority === "service" ? "Сервисный доступ" : <div className="flex flex-col gap-1"><span className="text-xs">{date(connection.ownerValidUntil)}</span>{connection.ownerId === getClaims()?.sub && <Button size="sm" variant="outline" disabled={!connection.generationValid || connection.policy.status === "revoked"} onClick={() => { void act(() => api.revalidate(connection.id)) }}>Обновить мои права</Button>}</div> } },
{ id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin && <div className="flex flex-wrap gap-1"><Button size="sm" variant="outline" onClick={() => setEditing(connection)}>Разрешения</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { void act(() => api.status(connection.id, connection.policy.status === "active" ? "paused" : "active")) }}>{connection.policy.status === "active" ? "Пауза" : "Включить"}</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Отозвать доступ подключения и все его токены?")) void act(() => api.status(connection.id, "revoked")) }}>Отозвать</Button><Button size="sm" variant="ghost" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Заменить токен? Старый токен перестанет работать.")) void act(async () => setToken((await api.rotate(connection.id)).token)) }}>Новый токен</Button></div> } },
], [api, admin, act])
return <><Panel title="Подключения" description="Токены, сроки и разрешения AI-клиентов" actions={admin && <Button onClick={() => setEditing("new")}><PlusIcon />Выдать доступ</Button>}><ErrorMessage message={query.error} /><Grid items={(query.data?.connections ?? []) as unknown as RecordRow[]} columns={columns} loading={!query.data && !query.error} /><p className="text-sm text-muted-foreground">HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.</p></Panel>{editing && <ConnectionForm api={api} operations={operations} editing={editing === "new" ? undefined : editing} close={() => setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />}<TokenDialog token={token} close={() => setToken("")} /></>
@@ -247,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++ }, [])
@@ -269,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))
@@ -278,7 +379,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
return <>
<ErrorMessage message={grants.error} />
<p className="text-sm text-muted-foreground">Права владельца подтверждены до {date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.</p>
<p className="text-sm text-muted-foreground">{connection.policy.authority === "service" ? "Сервисный доступ действует до отзыва." : `Права владельца подтверждены до ${date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.`}</p>
<Button variant="outline" className="self-start" disabled={connection.ownerId !== getClaims()?.sub} onClick={() => { void api.revalidate(connectionId).then(() => { grants.refresh(); toast.success("Права владельца обновлены") }, error => toast.error(errorText(error))) }}>Подтвердить текущие права владельца</Button>
<Button variant="outline" className="self-start" onClick={() => { void check() }}>Проверить готовность доступа</Button>
{result !== null && <>
@@ -287,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>
@@ -798,5 +897,5 @@ function McpWorkspaceContent({ backendUrl, live }: { backendUrl: string; live: b
const [operations, setOperations] = useState<McpOperationDescriptor[]>([]), [error, setError] = useState("")
useEffect(() => { if (!live) return; const controller = new AbortController(); void api.catalog(controller.signal).then(catalog => setOperations(catalog.operations), failure => { if (!controller.signal.aborted) setError(errorText(failure)) }); return () => controller.abort() }, [api, live])
const changeTab = (value: unknown) => { const next = String(value); const url = new URL(window.location.href); url.searchParams.set("tab", next); window.history.replaceState(null, "", url.pathname + url.search) }
return <><PageHeader crumbs={[{ label: "MCP" }]} /><main className="flex min-w-0 flex-1 flex-col gap-5 p-4 md:p-6"><div className="flex items-center gap-3"><BotIcon className="size-7 text-muted-foreground" /><div><h1 className="text-xl font-semibold">MCP</h1><p className="text-sm text-muted-foreground">Доступ нейросетей, разрешения и контроль изменений</p></div></div>{!live ? <Panel title="Подключите backend"><p>Для выдачи реального AI-доступа выберите режим «Живые» и настройте авторизацию портала.</p></Panel> : <><ErrorMessage message={error} />{oauthRequestId && <Consent key={oauthRequestId} api={api} id={oauthRequestId} />}<Tabs value={tab} onValueChange={changeTab}><div className="overflow-x-auto pb-1"><TabsList variant="line">{Object.entries(tabs).filter(([key]) => key !== "settings" || can("mm:mcp:admin")).map(([key, title]) => <TabsTrigger key={key} value={key}>{title}</TabsTrigger>)}</TabsList></div><TabsContent value="overview"><Overview api={api} /></TabsContent><TabsContent value="connections"><div className="flex flex-col gap-4"><Connections api={api} operations={operations} />{can("mm:mcp:admin") && <AccessTools api={api} />}</div></TabsContent><TabsContent value="permissions"><Permissions api={api} operations={operations} /></TabsContent><TabsContent value="devices"><DeviceManagement api={api} /></TabsContent><TabsContent value="routing"><div className="flex flex-col gap-4"><RoutingProfiles api={api} /><RoutePathVerification api={api} /></div></TabsContent><TabsContent value="requests"><Records api={api} kind="requests" /></TabsContent><TabsContent value="plans"><div className="flex flex-col gap-4"><Records api={api} kind="plans" /><Records api={api} kind="operations" />{admin && <OperationRecovery key={recoveryId} api={api} operationId={recoveryId} />}<Records api={api} kind="drift" /></div></TabsContent>{can("mm:mcp:admin") && <TabsContent value="settings"><div className="flex flex-col gap-4"><Settings api={api} /><RestCoverage api={api} /><ManagementChannels api={api} />{can("mm:settings:admin") && <DatabaseRestore api={api} />}</div></TabsContent>}</Tabs></>}</main></>
return <><PageHeader crumbs={[{ label: "MCP" }]} /><div className="flex min-h-0 min-w-0 flex-1 flex-col gap-5 overflow-y-auto p-4 md:p-6"><div className="flex items-center gap-3"><BotIcon className="size-7 text-muted-foreground" /><div><h1 className="text-xl font-semibold">MCP</h1><p className="text-sm text-muted-foreground">Доступ нейросетей, разрешения и контроль изменений</p></div></div>{!live ? <Panel title="Подключите backend"><p>Для выдачи реального AI-доступа выберите режим «Живые» и настройте авторизацию портала.</p></Panel> : <><ErrorMessage message={error} />{oauthRequestId && <Consent key={oauthRequestId} api={api} id={oauthRequestId} />}<Tabs value={tab} onValueChange={changeTab}><div className="overflow-x-auto pb-1"><TabsList variant="line">{Object.entries(tabs).filter(([key]) => key !== "settings" || can("mm:mcp:admin")).map(([key, title]) => <TabsTrigger key={key} value={key}>{title}</TabsTrigger>)}</TabsList></div><TabsContent value="overview"><Overview api={api} /></TabsContent><TabsContent value="connections"><div className="flex flex-col gap-4"><Connections api={api} operations={operations} />{can("mm:mcp:admin") && <AccessTools api={api} />}</div></TabsContent><TabsContent value="permissions"><Permissions api={api} operations={operations} /></TabsContent><TabsContent value="devices"><DeviceManagement api={api} /></TabsContent><TabsContent value="routing"><div className="flex flex-col gap-4"><RoutingProfiles api={api} /><RoutePathVerification api={api} /></div></TabsContent><TabsContent value="requests"><Records api={api} kind="requests" /></TabsContent><TabsContent value="plans"><div className="flex flex-col gap-4"><Records api={api} kind="plans" /><Records api={api} kind="operations" />{admin && <OperationRecovery key={recoveryId} api={api} operationId={recoveryId} />}<Records api={api} kind="drift" /></div></TabsContent>{can("mm:mcp:admin") && <TabsContent value="settings"><div className="flex flex-col gap-4"><Settings api={api} /><RestCoverage api={api} /><ManagementChannels api={api} />{can("mm:settings:admin") && <DatabaseRestore api={api} />}</div></TabsContent>}</Tabs></>}</div></>
}
+8
View File
@@ -65,6 +65,8 @@
- **«Срок действия (UTC)»** — не больше года. Для первого шага достаточно нескольких дней.
- **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию.
- **Серверы и операции** — только те, что нужны агенту.
- «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений.
- Для выборочного доступа отметьте карточки нужных серверов. Если «Все серверы» выключено и ни одна карточка не отмечена, доступ к серверам закрыт.
- Операция, не выданная подключению, получает `OPERATION_DENIED`.
- Сервер вне списка получает `SERVER_DENIED`.
- Глобальные операции работают только с «Разрешить выбранные глобальные операции».
@@ -117,6 +119,12 @@
Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками.
### Сервисное подключение
В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. Опасные операции всегда требуют подтверждения человеком, а лимиты и защита объектов действуют как обычно.
Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение.
### Что агент может на этом шаге
- **Может** вызывать операции чтения: каталоги, состояние, журналы.
+13 -3
View File
@@ -5,6 +5,8 @@ const serverId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const instant = z.string().datetime({ offset: true })
const uniqueStrings = z.array(identifier).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся значения")
const serverIds = z.array(serverId).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся серверы")
// Keep the existing finite timestamp contract for policy, credential and SQL proofs.
export const MCP_SERVICE_EXPIRATION = "9999-12-31T23:59:59.000Z"
export const mcpModeSchema = z.enum(["observer", "approval", "autonomous"])
export const mcpLimitsSchema = z.object({
@@ -32,6 +34,7 @@ export const mcpConnectionPolicySchema = z.object({
id: identifier,
version: z.number().int().positive(),
status: z.enum(["active", "paused", "revoked"]),
authority: z.literal("service").optional(),
expiresAt: instant,
mode: mcpModeSchema,
permissions: uniqueStrings,
@@ -39,7 +42,9 @@ export const mcpConnectionPolicySchema = z.object({
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
autonomousDangerousOperationIds: uniqueStrings.default([]),
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
}).strict()
}).strict().refine(policy => policy.authority !== "service" ||
policy.expiresAt === MCP_SERVICE_EXPIRATION && policy.mode === "autonomous" && policy.dangerousPolicy === "approval" && !policy.autonomousDangerousOperationIds.length,
"Некорректная политика сервисного подключения")
export const mcpTargetSchema = z.discriminatedUnion("scope", [
z.object({ scope: z.literal("servers"), serverIds: serverIds.refine(ids => ids.length > 0, "Выберите серверы") }).strict(),
@@ -127,14 +132,19 @@ export type McpPolicyReasonCode = z.infer<typeof mcpPolicyReasonCodeSchema>
export const mcpConnectionCreateSchema = z.object({
name: z.string().trim().min(1).max(100),
expiresAt: instant,
authority: z.literal("service").optional(),
expiresAt: instant.nullable(),
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()
}).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,
+2
View File
@@ -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 })),
+99 -1
View File
@@ -24,8 +24,16 @@ 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') {
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 })
@@ -292,13 +300,33 @@ test('synthetic: OAuth approval becomes unavailable when the selected connection
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'])
const logStatus = { ...read, id: 'logs.status', toolName: 'mm_logs_status', title: 'Статус журналов' }
const capabilities = { ...read, id: 'capabilities.read', toolName: 'mm_capabilities_get', title: 'Доступные возможности', section: 'mcp', requiredPermissions: [] }
await page.route('**/api/mcp/catalog', route => route.fulfill({ json: { stage: 'runtime', executionAvailable: true, operations: [read, logStatus, capabilities, forbidden] } }))
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')
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()
await expect(dialog.getByRole('status')).toHaveText('Выбрано 0')
const logsGroup = dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' })
await logsGroup.check()
await expect(dialog.getByRole('status')).toHaveText('Выбрано 2')
await dialog.locator('summary').filter({ hasText: 'Журналы' }).click()
await expect(dialog.getByRole('checkbox', { name: read.title, exact: true })).toBeChecked()
await dialog.getByRole('checkbox', { name: logStatus.title, exact: true }).uncheck()
await expect(logsGroup).toHaveAttribute('aria-checked', 'mixed')
await logsGroup.check()
await logsGroup.uncheck()
await expect(dialog.getByRole('status')).toHaveText('Выбрано 0')
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()
@@ -315,6 +343,76 @@ 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 wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true })
await expect(allServers).not.toBeChecked()
await expect(wan).toHaveAttribute('aria-pressed', 'true')
await allServers.check()
await expect(wan).toHaveCount(0)
await allServers.uncheck()
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()
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')
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
const dialog = page.getByRole('dialog')
const next = dialog.getByRole('button', { name: 'Далее', exact: true })
await dialog.getByLabel('Название', { exact: true }).fill('Служебный мониторинг')
await dialog.getByLabel('Тип подключения', { exact: true }).selectOption('service')
await expect(dialog.getByLabel('Срок действия (UTC)', { exact: true })).toHaveCount(0)
await next.click()
await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click()
await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check()
await next.click()
await expect(dialog.getByText('Опасные действия всегда требуют подтверждения.')).toBeVisible()
await next.click()
await expect(dialog.getByText('Сервисное, бессрочное', { exact: false })).toBeVisible()
await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
await expect(page.getByLabel('Одноразовый токен MCP')).toHaveValue('synthetic-one-time-token')
expect(state.mutations).toEqual([expect.objectContaining({ path: '/api/mcp/connections', body: expect.objectContaining({
authority: 'service', expiresAt: null, mode: 'autonomous', dangerousPolicy: 'approval', autonomousDangerousOperationIds: [],
scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false },
}) })])
})
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')
+24 -2
View File
@@ -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] })
@@ -40,6 +41,20 @@ async function setup(page: Page, fail = false) {
return calls
}
test("MCP: настройки прокручиваются до восстановления базы", async ({ page }) => {
await page.setViewportSize({ width: 1100, height: 640 })
await setup(page)
await page.goto("/mcp?tab=settings")
const restoreHeading = page.getByRole("heading", { name: "Восстановление БД через MCP" })
await expect(restoreHeading).toBeAttached()
await expect(restoreHeading).not.toBeInViewport()
await page.mouse.move(700, 400)
await page.mouse.wheel(0, 3000)
await expect(restoreHeading).toBeInViewport()
await expect(page.getByRole("navigation", { name: "Путь страницы" })).toBeInViewport()
})
test("MCP приостанавливает опрос по сигналу скрытия документа и возобновляет при показе", async ({ page }) => {
const calls = await setup(page)
const overviewCalls = () => calls.filter(call => call === "GET /api/mcp/overview").length
@@ -400,7 +415,8 @@ 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()
await page.getByRole("button", { name: "Далее", exact: true }).click()
@@ -463,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()