diff --git a/backend/src/modules/mcp/principal-security-source.owned.test.ts b/backend/src/modules/mcp/principal-security-source.owned.test.ts index e4854231..1e7be7c2 100644 --- a/backend/src/modules/mcp/principal-security-source.owned.test.ts +++ b/backend/src/modules/mcp/principal-security-source.owned.test.ts @@ -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") diff --git a/backend/src/modules/mcp/store.ts b/backend/src/modules/mcp/store.ts index 11c09a43..59716c08 100644 --- a/backend/src/modules/mcp/store.ts +++ b/backend/src/modules/mcp/store.ts @@ -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): 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("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("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("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("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("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)]) diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx index 0394289b..04b198f5 100644 --- a/components/mcp/mcp-workspace.tsx +++ b/components/mcp/mcp-workspace.tsx @@ -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(editing?.policy.mode ?? "observer") + const [service, setService] = useState(editing?.policy.authority === "service") const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval") const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? []) @@ -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 { if (!open && !busy) close() }}>{editing ? "Изменить разрешения" : "Новое подключение"}Шаг {step} из 4 · доступ ограничивается правами текущего владельца. - {step === 1 && <> setName(event.target.value)} placeholder="Агент диагностики" /> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}} + {step === 1 && <> setName(event.target.value)} placeholder="Агент диагностики" />{!editing && setService(value === "service")}>} + {service + ?

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

+ : <> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}}} {step === 2 && <> setServerText(event.target.value)} placeholder="1, 2" /> @@ -216,8 +220,8 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp

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

} - {step === 3 && <>
{Object.entries(limits).map(([key, value]) => )[key]}> setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} />)}
setDanger(value as typeof danger)}>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}} - {step === 4 &&

{name || "Без названия"} · {modeLabels[mode]}

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

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

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

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

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

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

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

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

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

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

}
{step < 4 ? : }
} @@ -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 }) => }, - { 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
{date(connection.ownerValidUntil)}{connection.ownerId === getClaims()?.sub && }
} }, + { id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return connection.policy.authority === "service" ? "Сервисный доступ" :
{date(connection.ownerValidUntil)}{connection.ownerId === getClaims()?.sub && }
} }, { id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin &&
} }, ], [api, admin, act]) return <> setEditing("new")}>Выдать доступ}>

HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.

{editing && setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />} setToken("")} /> @@ -320,7 +324,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: { return <> -

Права владельца подтверждены до {date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.

+

{connection.policy.authority === "service" ? "Сервисный доступ действует до отзыва." : `Права владельца подтверждены до ${date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.`}

{result !== null && <> diff --git a/docs/mcp-enable-guide.md b/docs/mcp-enable-guide.md index c62b4a1a..146c0f36 100644 --- a/docs/mcp-enable-guide.md +++ b/docs/mcp-enable-guide.md @@ -117,6 +117,12 @@ Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками. +### Сервисное подключение + +В «Подключения» → «Выдать доступ» администратор MCP может выбрать «Сервисное — бессрочный автономный доступ». Выберите нужные серверы и операции. Доступ действует до отзыва и переживает истечение обычной сессии портала. Опасные операции всегда требуют подтверждения человеком, а лимиты и защита объектов действуют как обычно. + +Сервисный токен можно заменить, приостановить вместе с подключением или отозвать. Явный отзыв прав выдавшего доступ администратора в портале также отзывает его сервисные подключения. Чтобы сменить тип подключения, выдайте новый токен через новое подключение. + ### Что агент может на этом шаге - **Может** вызывать операции чтения: каталоги, состояние, журналы. diff --git a/packages/contracts/src/mcp.ts b/packages/contracts/src/mcp.ts index 32fdb615..64b7aff8 100644 --- a/packages/contracts/src/mcp.ts +++ b/packages/contracts/src/mcp.ts @@ -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 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, diff --git a/tests/e2e/mcp-auth-context.spec.ts b/tests/e2e/mcp-auth-context.spec.ts index 129fda80..dbdd135a 100644 --- a/tests/e2e/mcp-auth-context.spec.ts +++ b/tests/e2e/mcp-auth-context.spec.ts @@ -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')