Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
776dea6a77 | ||
|
|
f27fd035bc |
No files matched your search
@@ -19,12 +19,39 @@ jobs:
|
|||||||
tag: ${{ steps.release.outputs.tag }}
|
tag: ${{ steps.release.outputs.tag }}
|
||||||
bump: ${{ steps.release.outputs.bump }}
|
bump: ${{ steps.release.outputs.bump }}
|
||||||
release_url: ${{ steps.release.outputs.release_url }}
|
release_url: ${{ steps.release.outputs.release_url }}
|
||||||
|
backend_reuse_version: ${{ steps.changes.outputs.backend_reuse_version }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
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
|
- name: Test release version calculation
|
||||||
run: node --test .ci/scripts/compute-release.test.mjs
|
run: node --test .ci/scripts/compute-release.test.mjs
|
||||||
|
|
||||||
@@ -42,17 +69,21 @@ jobs:
|
|||||||
test -f .ci/release/release-manifest.json
|
test -f .ci/release/release-manifest.json
|
||||||
|
|
||||||
backend-test:
|
backend-test:
|
||||||
|
needs: prepare-release
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Node 22
|
- name: Setup Node 22
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
|
|
||||||
- name: Start PostgreSQL 18
|
- name: Start PostgreSQL 18
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -93,6 +124,7 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Install and test backend
|
- name: Install and test backend
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
REQUIRE_TEST_POSTGRES: "1"
|
REQUIRE_TEST_POSTGRES: "1"
|
||||||
@@ -112,7 +144,7 @@ jobs:
|
|||||||
npm run test --prefix backend
|
npm run test --prefix backend
|
||||||
|
|
||||||
- name: Stop PostgreSQL
|
- name: Stop PostgreSQL
|
||||||
if: always()
|
if: always() && needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
shell: bash
|
shell: bash
|
||||||
run: docker rm -f "${PG_CONTAINER:-}" 2>/dev/null || true
|
run: docker rm -f "${PG_CONTAINER:-}" 2>/dev/null || true
|
||||||
|
|
||||||
@@ -123,6 +155,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Configure backend image name
|
- name: Configure backend image name
|
||||||
@@ -135,6 +168,7 @@ jobs:
|
|||||||
echo "IMAGE_NAME=${{ env.REGISTRY }}/${owner}/${stem}-backend" >> "${GITHUB_ENV}"
|
echo "IMAGE_NAME=${{ env.REGISTRY }}/${owner}/${stem}-backend" >> "${GITHUB_ENV}"
|
||||||
|
|
||||||
- name: Prepare backend build context
|
- name: Prepare backend build context
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -174,6 +208,7 @@ jobs:
|
|||||||
password: ${{ secrets.ACTIONS_PAT }}
|
password: ${{ secrets.ACTIONS_PAT }}
|
||||||
|
|
||||||
- name: Build and push backend image
|
- name: Build and push backend image
|
||||||
|
if: needs.prepare-release.outputs.backend_reuse_version == ''
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: .ci/docker/backend
|
context: .ci/docker/backend
|
||||||
@@ -195,6 +230,18 @@ jobs:
|
|||||||
org.opencontainers.image.revision=${{ gitea.sha }}
|
org.opencontainers.image.revision=${{ gitea.sha }}
|
||||||
org.opencontainers.image.created=${{ gitea.event.head_commit.timestamp }}
|
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:
|
frontend-image:
|
||||||
needs: prepare-release
|
needs: prepare-release
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -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 { pool, closePool } = await import("../../db/index.js")
|
||||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||||
const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js")
|
const { MIGRATION_MANIFEST } = await import("../../db/migration-manifest.js")
|
||||||
const { mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
|
const { MCP_SERVICE_EXPIRATION, mcpConnectionCreateSchema, mcpTemporaryGrantSchema } = await import("@mmapp/contracts/mcp")
|
||||||
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource } = await import("./store.js")
|
const { createMcpConnection, authenticateMcpToken, getConnection, validatePrincipal, effectiveMcpConnectionSource,
|
||||||
|
updateMcpConnection, revalidateMcpOwner, rotateConnectionToken, setConnectionStatus } = await import("./store.js")
|
||||||
const { acceptPortalRevocation } = await import("./portal-revocation.js")
|
const { acceptPortalRevocation } = await import("./portal-revocation.js")
|
||||||
const { connectProbeStorage } = await import("../../services/server-probe-storage-connection.js")
|
const { connectProbeStorage } = await import("../../services/server-probe-storage-connection.js")
|
||||||
const { principalSourceSql, principalSourceStatementName } = await import("./principal-security-sql.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)
|
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)
|
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 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 () => {
|
await check("poll current policy tuple: real SQL bounds, clock, backend, scopes and fresh committed updates", async () => {
|
||||||
const f = await fixture()
|
const f = await fixture()
|
||||||
console.log("Owned poll policy tuple SQL:", JSON.stringify(await checkOwnedPollPolicySource(pool, f.principal.connectionId, f.principal.credentialId)))
|
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 () => {
|
await check("actual HMAC portal revoke and private external cutoff interrupt source capture", async () => {
|
||||||
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
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 () => {
|
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 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")
|
const signature = "sha256=" + createHmac("sha256", secret).update(timestamp + ".").update(raw).digest("hex")
|
||||||
assert.deepEqual(await acceptPortalRevocation(raw, timestamp, signature, secret), { ok: true, duplicate: false })
|
assert.deepEqual(await acceptPortalRevocation(raw, timestamp, signature, secret), { ok: true, duplicate: false })
|
||||||
}, "OWNER_CLAIMS_REVOKED")
|
}, "OWNER_CLAIMS_REVOKED")
|
||||||
await assert.rejects(validatePrincipal(f.principal), { code: "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 () => {
|
await check("duplicate signed revocation repairs the external cutoff without moving recorded authority", async () => {
|
||||||
const f = await fixture(), secret = randomBytes(32).toString("hex")
|
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 type { PoolClient, QueryResultRow } from "pg"
|
||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import {
|
import {
|
||||||
mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
|
MCP_SERVICE_EXPIRATION, mcpConnectionPolicySchema, mcpConnectionSchema, mcpSettingsSchema, mcpTemporaryGrantSchema,
|
||||||
type McpConnection, type McpConnectionCreate, type McpConnectionPolicy,
|
type McpConnection, type McpConnectionCreate, type McpConnectionPolicy,
|
||||||
} from "@mmapp/contracts/mcp"
|
} from "@mmapp/contracts/mcp"
|
||||||
import { pool } from "../../db/index.js"
|
import { pool } from "../../db/index.js"
|
||||||
@@ -19,6 +19,16 @@ export interface ConnectionRow extends QueryResultRow {
|
|||||||
owner_claims_issued_at: Date
|
owner_claims_issued_at: Date
|
||||||
}
|
}
|
||||||
function ownerValidUntil(actor: AuthUser) { return new Date(Math.min(actor.expiresAt ?? Date.now() + 900000, Date.now() + 86400000)) }
|
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 interface McpPrincipal { connectionId: string; credentialId: string; credentialExpiresAt: string }
|
||||||
export function intersectGrant(connection: ConnectionRow, grant?: z.infer<typeof mcpTemporaryGrantSchema>): ConnectionRow {
|
export function intersectGrant(connection: ConnectionRow, grant?: z.infer<typeof mcpTemporaryGrantSchema>): ConnectionRow {
|
||||||
if (!grant) return connection
|
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)
|
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) {
|
export async function createMcpConnection(input: McpConnectionCreate, actor: AuthUser) {
|
||||||
const expires = Date.parse(input.expiresAt)
|
const expiresAt = connectionExpiration(input, actor)
|
||||||
if (expires <= Date.now() || expires > Date.now() + 366 * 86400000) throw new McpError("INVALID_EXPIRATION", "Срок доступа должен быть от текущего времени до одного года", 400)
|
|
||||||
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права")
|
if (input.permissions.some(permission => !hasPermission(actor.permissions, permission))) throw new McpError("PERMISSION_DENIED", "Нельзя делегировать отсутствующие у владельца права")
|
||||||
if (input.scope.serverIds.length) {
|
if (input.scope.serverIds.length) {
|
||||||
const { rows } = await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [input.scope.serverIds])
|
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 id = randomUUID(), generation = await accessGeneration()
|
||||||
const { name, ...configuration } = input
|
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")
|
const token = randomToken("bearer")
|
||||||
return connectionWrite(async client => {
|
return connectionWrite(async client => {
|
||||||
await lockPortalOwner(client, actor.id)
|
await lockPortalOwner(client, actor.id)
|
||||||
await assertPortalClaimsCurrent(actor, client)
|
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)])
|
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), input.expiresAt])
|
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 })
|
await audit(client, actor.id, "connection.create", id, { name, policy })
|
||||||
return { connection: publicConnection(row, generation), token }
|
return { connection: publicConnection(row, generation), token }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
export async function updateMcpConnection(id: string, input: McpConnectionCreate, actor: AuthUser) {
|
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 (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)
|
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 => {
|
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])
|
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
||||||
const before = await getConnection(id, client)
|
const before = await getConnection(id, client)
|
||||||
if (before.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Политику обновляет её владелец после подтверждения своих прав")
|
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 { name, ...configuration } = input
|
||||||
const policy = mcpConnectionPolicySchema.parse({ ...configuration, id, version: before.policy.version + 1, status: before.policy.status })
|
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(actor.permissions), ownerValidUntil(actor)])
|
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 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 })
|
await audit(client, actor.id, "connection.policy.update", id, { before: before.policy, after: policy })
|
||||||
return publicConnection(row, await accessGeneration())
|
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])
|
await client.query("SELECT id FROM mcp_connections WHERE id=$1 FOR UPDATE", [id])
|
||||||
const connection = await getConnection(id, client)
|
const connection = await getConnection(id, client)
|
||||||
if (connection.owner_id !== actor.id) throw new McpError("PERMISSION_DENIED", "Права подтверждает владелец подключения")
|
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 policy = { ...connection.policy, version: connection.policy.version + 1 }
|
||||||
const until = ownerValidUntil(actor)
|
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)])
|
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)])
|
||||||
|
|||||||
@@ -31,6 +31,11 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } f
|
|||||||
|
|
||||||
const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос"
|
const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос"
|
||||||
const modeLabels = { observer: "Наблюдатель", approval: "С подтверждением", autonomous: "Автономный" }
|
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: "Настройки" }
|
const tabs = { overview: "Обзор", connections: "Подключения", permissions: "Разрешения", devices: "Интерфейсы", requests: "Обращения", plans: "Планы и операции", routing: "Route AI", settings: "Настройки" }
|
||||||
type Tab = keyof typeof tabs
|
type Tab = keyof typeof tabs
|
||||||
type RecordRow = Record<string, unknown>
|
type RecordRow = Record<string, unknown>
|
||||||
@@ -155,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 }) {
|
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 [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 [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 [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 [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval")
|
||||||
const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? [])
|
const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? [])
|
||||||
@@ -162,20 +168,60 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
|||||||
const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 })
|
const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 })
|
||||||
const permissions = getClaims()?.permissions ?? []
|
const permissions = getClaims()?.permissions ?? []
|
||||||
const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission)))
|
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 bySection = new Map<string, McpOperationDescriptor[]>()
|
||||||
|
for (const operation of eligible) {
|
||||||
|
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))
|
||||||
|
setSelected(ids => checked ? [...new Set([...ids, ...groupIds])] : ids.filter(id => !groupIds.has(id)))
|
||||||
|
}
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
setBusy(true); setError("")
|
setBusy(true); setError("")
|
||||||
try {
|
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() }
|
if (editing) { await api.update(editing.id, input); created() }
|
||||||
else { const result = await api.create(input); created(result.token) }
|
else { const result = await api.create(input); created(result.token) }
|
||||||
} catch (failure) { setError(errorText(failure)) } finally { setBusy(false) }
|
} 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} />
|
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>}
|
||||||
{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></>}
|
{service
|
||||||
{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))} />)}</>}
|
? <p className="text-sm text-muted-foreground">Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.</p>
|
||||||
{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>}
|
: <><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="flex flex-wrap items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={!eligible.length} onClick={() => setSelected(eligible.map(operation => operation.id))}>Выбрать все операции</Button>
|
||||||
|
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => setSelected([])}>Снять все</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>
|
||||||
|
})}
|
||||||
|
{!eligible.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
|
||||||
|
</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>{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>
|
<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>
|
</DialogContent></Dialog>
|
||||||
}
|
}
|
||||||
@@ -196,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: "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: "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) },
|
{ 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> } },
|
{ 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])
|
], [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("")} /></>
|
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("")} /></>
|
||||||
@@ -278,7 +324,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
|
|||||||
|
|
||||||
return <>
|
return <>
|
||||||
<ErrorMessage message={grants.error} />
|
<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" 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>
|
<Button variant="outline" className="self-start" onClick={() => { void check() }}>Проверить готовность доступа</Button>
|
||||||
{result !== null && <>
|
{result !== null && <>
|
||||||
|
|||||||
@@ -117,6 +117,12 @@
|
|||||||
|
|
||||||
Если в портале отозвать сессии пользователя, Manager отзывает и его подключения MCP вместе с токенами и временными допусками.
|
Если в портале отозвать сессии пользователя, 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 instant = z.string().datetime({ offset: true })
|
||||||
const uniqueStrings = z.array(identifier).max(1000).refine(values => new Set(values).size === values.length, "Повторяющиеся значения")
|
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, "Повторяющиеся серверы")
|
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 mcpModeSchema = z.enum(["observer", "approval", "autonomous"])
|
||||||
export const mcpLimitsSchema = z.object({
|
export const mcpLimitsSchema = z.object({
|
||||||
@@ -32,6 +34,7 @@ export const mcpConnectionPolicySchema = z.object({
|
|||||||
id: identifier,
|
id: identifier,
|
||||||
version: z.number().int().positive(),
|
version: z.number().int().positive(),
|
||||||
status: z.enum(["active", "paused", "revoked"]),
|
status: z.enum(["active", "paused", "revoked"]),
|
||||||
|
authority: z.literal("service").optional(),
|
||||||
expiresAt: instant,
|
expiresAt: instant,
|
||||||
mode: mcpModeSchema,
|
mode: mcpModeSchema,
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
@@ -39,7 +42,9 @@ export const mcpConnectionPolicySchema = z.object({
|
|||||||
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
||||||
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
||||||
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
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", [
|
export const mcpTargetSchema = z.discriminatedUnion("scope", [
|
||||||
z.object({ scope: z.literal("servers"), serverIds: serverIds.refine(ids => ids.length > 0, "Выберите серверы") }).strict(),
|
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({
|
export const mcpConnectionCreateSchema = z.object({
|
||||||
name: z.string().trim().min(1).max(100),
|
name: z.string().trim().min(1).max(100),
|
||||||
expiresAt: instant,
|
authority: z.literal("service").optional(),
|
||||||
|
expiresAt: instant.nullable(),
|
||||||
mode: mcpModeSchema.default("observer"),
|
mode: mcpModeSchema.default("observer"),
|
||||||
permissions: uniqueStrings,
|
permissions: uniqueStrings,
|
||||||
scope: mcpScopeSchema,
|
scope: mcpScopeSchema,
|
||||||
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
dangerousPolicy: z.enum(["approval", "explicit-allow"]).default("approval"),
|
||||||
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
autonomousDangerousOperationIds: uniqueStrings.default([]),
|
||||||
limits: mcpLimitsSchema.default(() => mcpLimitsSchema.parse({})),
|
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({
|
export const mcpConnectionSchema = z.object({
|
||||||
id: z.string().uuid(), name: z.string(), ownerId: z.string(),
|
id: z.string().uuid(), name: z.string(), ownerId: z.string(),
|
||||||
policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant,
|
policy: mcpConnectionPolicySchema, createdAt: instant, updatedAt: instant,
|
||||||
|
|||||||
@@ -292,6 +292,9 @@ 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 }) => {
|
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 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.goto('/mcp?tab=connections')
|
||||||
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
|
await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
|
||||||
const dialog = page.getByRole('dialog')
|
const dialog = page.getByRole('dialog')
|
||||||
@@ -299,6 +302,20 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
|||||||
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
||||||
await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
|
await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
|
||||||
await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
|
await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
|
||||||
|
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('checkbox', { name: read.title, exact: true }).check()
|
||||||
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
||||||
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
|
||||||
@@ -315,6 +332,30 @@ test('synthetic: issue only selected server/read permission and hide one-time to
|
|||||||
await expect(token).toHaveCount(0)
|
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 }) => {
|
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'])
|
const state = await setup(page, ['mm:mcp:admin', 'mm:mcp:pause', 'mm:servers:read'])
|
||||||
await page.goto('/mcp?tab=connections')
|
await page.goto('/mcp?tab=connections')
|
||||||
|
|||||||
@@ -415,6 +415,7 @@ test("MCP: доступ, проверка подключения, выдача
|
|||||||
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
|
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
|
||||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||||
await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
|
await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
|
||||||
|
await page.locator("summary").filter({ hasText: "Журналы" }).click()
|
||||||
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
|
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
|
||||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||||
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
await page.getByRole("button", { name: "Далее", exact: true }).click()
|
||||||
|
|||||||
Reference in new issue
Block a user