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)])
|
||||
|
||||
Reference in new issue
Block a user