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
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
This commit is contained in:
1 parent
f27fd035bc
commit
776dea6a77
6 files changed
+119
-22
No files matched your search
@@ -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 } = 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,38 @@ 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("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 +165,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")
|
||||
|
||||
@@ -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,16 @@ 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
|
||||
}
|
||||
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,8 +123,7 @@ 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])
|
||||
@@ -122,29 +131,36 @@ export async function createMcpConnection(input: McpConnectionCreate, actor: Aut
|
||||
}
|
||||
const id = randomUUID(), generation = await accessGeneration()
|
||||
const { name, ...configuration } = input
|
||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, id, version: 1, status: "active" })
|
||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, expiresAt, id, version: 1, status: "active" })
|
||||
const service = policy.authority === "service"
|
||||
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 { 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)
|
||||
if (before.policy.authority !== input.authority) throw new McpError("INVALID_CONFIGURATION", "Для смены типа доступа создайте новое подключение", 400)
|
||||
if (Date.parse(expiresAt) <= Date.now()) throw new McpError("INVALID_EXPIRATION", "Истёк срок доступа", 400)
|
||||
const { name, ...configuration } = input
|
||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, 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)])
|
||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, 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 +185,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)])
|
||||
|
||||
@@ -160,6 +160,7 @@ function TokenDialog({ token, close, connectionName }: { token: string; close: (
|
||||
function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) {
|
||||
const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("")
|
||||
const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
|
||||
const [service, setService] = useState(editing?.policy.authority === "service")
|
||||
const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState<string[]>(editing?.policy.scope.operationIds ?? [])
|
||||
const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval")
|
||||
const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? [])
|
||||
@@ -183,13 +184,16 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
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))], scope: { serverIds: serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service ? [] : dangerIds.filter(id => selected.includes(id)), limits })
|
||||
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 === 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 && <>
|
||||
<Field label="ID разрешённых серверов через запятую"><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="1, 2" /></Field>
|
||||
<Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} />
|
||||
@@ -216,8 +220,8 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
</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 === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div>{service ? <p className="text-sm text-muted-foreground">Опасные действия всегда требуют подтверждения.</p> : <><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => <Choice key={operation.id} label={operation.title} checked={dangerIds.includes(operation.id)} onChange={checked => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}</>}</>}
|
||||
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {service ? "Сервисное, бессрочное" : modeLabels[mode]}</p><p>Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p><p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
|
||||
<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>
|
||||
}
|
||||
@@ -238,9 +242,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("")} /></>
|
||||
@@ -320,7 +324,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 && <>
|
||||
|
||||
@@ -117,6 +117,12 @@
|
||||
|
||||
Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками.
|
||||
|
||||
### Сервисное подключение
|
||||
|
||||
В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. Опасные операции всегда требуют подтверждения человеком, а лимиты и защита объектов действуют как обычно.
|
||||
|
||||
Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение.
|
||||
|
||||
### Что агент может на этом шаге
|
||||
|
||||
- **Может** вызывать операции чтения: каталоги, состояние, журналы.
|
||||
|
||||
@@ -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,17 @@ 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,
|
||||
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, "Для сервисного подключения выберите автономный режим с подтверждением опасных действий. Для личного подключения укажите срок действия.")
|
||||
export const mcpConnectionSchema = z.object({
|
||||
id: z.string().uuid(), name: z.string(), ownerId: z.string(),
|
||||
policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant,
|
||||
|
||||
@@ -332,6 +332,30 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
||||
await expect(token).toHaveCount(0)
|
||||
})
|
||||
|
||||
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.getByLabel('ID разрешённых серверов через запятую').fill('1')
|
||||
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')
|
||||
|
||||
Reference in new issue
Block a user