152 lines
14 KiB
TypeScript
152 lines
14 KiB
TypeScript
import { createHash, createHmac, timingSafeEqual } from "node:crypto"
|
|
import { randomUUID } from "node:crypto"
|
|
import { mkdir, open, readFile, rename } from "node:fs/promises"
|
|
import path from "node:path"
|
|
import type { PoolClient } from "pg"
|
|
import { principalBytes, sourceAliases, principalSourceSql } from "./principal-security-sql.js"
|
|
import { z } from "zod"
|
|
import { isDeepStrictEqual } from "node:util"
|
|
import { portalRevocationEvent } from "./portal-revocation-event.js"
|
|
import { mcpConnectionPolicySchema } from "@mmapp/contracts/mcp"
|
|
import { pool } from "../../db/index.js"
|
|
import type { AuthUser } from "../../lib/permissions.js"
|
|
import { McpError, mcpStateDirectory } from "./security.js"
|
|
import { audit, transaction } from "./store.js"
|
|
import type { ConnectionRow, McpPrincipal } from "./store.js"
|
|
|
|
const ownerFile = (ownerId: string) => path.join(mcpStateDirectory(), "owner-revocations", createHash("sha256").update(ownerId).digest("hex") + ".json")
|
|
async function externalCutoff(ownerId: string): Promise<number> {
|
|
try { return z.object({ invalidBefore: z.number().int().nonnegative() }).parse(JSON.parse(await readFile(ownerFile(ownerId), "utf8"))).invalidBefore }
|
|
catch (error) {
|
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return 0
|
|
throw new McpError("STATE_UNAVAILABLE", "Внешнее состояние отзыва недоступно", 503)
|
|
}
|
|
}
|
|
async function persistCutoff(ownerId: string, at: number) {
|
|
const target = ownerFile(ownerId), value = Math.max(at, await externalCutoff(ownerId))
|
|
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 })
|
|
const temporary = target + "." + randomUUID() + ".tmp", handle = await open(temporary, "wx", 0o600)
|
|
try { await handle.writeFile(JSON.stringify({ invalidBefore: value })); await handle.sync() } finally { await handle.close() }
|
|
await rename(temporary, target)
|
|
}
|
|
export async function lockPortalOwner(client: Pick<PoolClient, "query">, ownerId: string) {
|
|
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", ["mcp-owner:" + ownerId])
|
|
}
|
|
export async function assertPortalClaimsCurrent(actor: Pick<AuthUser, "id" | "issuedAt">, client: Pick<PoolClient, "query"> = pool) {
|
|
const { rows: [row] } = await client.query<{ invalid_before: Date }>("SELECT invalid_before FROM mcp_owner_revocations WHERE owner_id=$1", [actor.id])
|
|
const cutoff = Math.max(row?.invalid_before.getTime() ?? 0, await externalCutoff(actor.id))
|
|
if (cutoff && (!actor.issuedAt || actor.issuedAt <= cutoff)) throw new McpError("OWNER_CLAIMS_REVOKED", "Права портала изменены; войдите заново с актуальным JWT", 401)
|
|
}
|
|
|
|
// Internal fixed SQL source only. These limits refuse a PRESENT oversized row;
|
|
// they never turn a narrower grant or a connection into an absent source.
|
|
// Identifier arrays at their contract maxima fit these generous envelopes.
|
|
// Unbounded future/opaque SQL fields still require explicit bounded refusal.
|
|
|
|
const sourceUnavailable = (): never => { throw new McpError("STATE_UNAVAILABLE", "Текущий источник прав недоступен", 503) }
|
|
const utcTimestamp = (value: unknown, nullable = false) => {
|
|
if (nullable && value === null) return
|
|
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(value) || !Number.isFinite(Date.parse(value))) sourceUnavailable()
|
|
if (new Date(value as string).toISOString() !== (value as string).slice(0, 23) + "Z") sourceUnavailable()
|
|
}
|
|
|
|
/** Private data reader, not an authority/capability constructor. BOTH SQL reads
|
|
* and the restore-resilient owner file check are owned here. No supplied JSON,
|
|
* cutoff, source rows or fallback can replace either current read. */
|
|
export async function readCurrentPrincipalSecuritySource(principal: McpPrincipal, client: Pick<PoolClient, "query">, includeGrants: boolean) {
|
|
const capture = async () => {
|
|
const { rows } = await client.query<ConnectionRow>(principalSourceSql, [principal.credentialId, principal.connectionId, includeGrants])
|
|
if (!Array.isArray(rows) || rows.length < 1 || rows.length > 2) sourceUnavailable()
|
|
const row = rows[0]
|
|
if (row.__ps_isolation !== "read committed" || row.__ps_exists !== true && row.__ps_exists !== false || row.__ps_oversize !== true && row.__ps_oversize !== false) sourceUnavailable()
|
|
if (row.__ps_oversize) sourceUnavailable()
|
|
if (!row.__ps_exists) throw new McpError("NOT_FOUND", "Подключение не найдено", 404)
|
|
if (row.__ps_guard !== true || !Number.isSafeInteger(row.__ps_bytes) || row.__ps_bytes <= 0 || row.__ps_bytes > principalBytes
|
|
|| row.id !== principal.connectionId || typeof row.__ps_credential_current !== "boolean"
|
|
|| typeof row.__ps_policy_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(row.__ps_policy_sha256)) sourceUnavailable()
|
|
for (const field of ["__ps_owner_until", "__ps_owner_issued"]) utcTimestamp(row[field])
|
|
for (const field of ["__ps_credential_expires", "__ps_credential_revoked", "__ps_cutoff_text"]) utcTimestamp(row[field], true)
|
|
if (row.__ps_credential !== null && row.__ps_credential !== principal.credentialId
|
|
|| row.__ps_credential === null && (row.__ps_credential_current || row.__ps_credential_expires !== null || row.__ps_credential_revoked !== null)
|
|
|| row.__ps_credential !== null && row.__ps_credential_expires === null
|
|
|| row.__ps_credential_current && row.__ps_credential_revoked !== null) sourceUnavailable()
|
|
if (row.__ps_settings !== null && row.__ps_settings !== 1 || row.__ps_enabled !== null && typeof row.__ps_enabled !== "boolean") sourceUnavailable()
|
|
if (row.__ps_settings === null && row.__ps_enabled !== null) sourceUnavailable()
|
|
const connection = { ...row }
|
|
for (const key of sourceAliases) delete connection[key]
|
|
const rawPolicy = structuredClone(connection.policy)
|
|
connection.policy = mcpConnectionPolicySchema.parse(connection.policy)
|
|
if (!(connection.owner_valid_until instanceof Date) || !Number.isFinite(connection.owner_valid_until.getTime())
|
|
|| !(connection.owner_claims_issued_at instanceof Date) || !Number.isFinite(connection.owner_claims_issued_at.getTime())) sourceUnavailable()
|
|
const cutoff = row.__ps_cutoff
|
|
if (row.__ps_cutoff_owner === null ? cutoff !== null || row.__ps_cutoff_text !== null
|
|
: row.__ps_cutoff_owner !== connection.owner_id || !(cutoff instanceof Date) || !Number.isFinite(cutoff.getTime())) sourceUnavailable()
|
|
const common = (value: ConnectionRow) => {
|
|
const result = { ...value }
|
|
delete result.__ps_grant_id; delete result.__ps_grant_payload; delete result.__ps_grant_oversize; delete result.__ps_grant_sha256
|
|
return result
|
|
}
|
|
for (const other of rows) if (!isDeepStrictEqual(common(other), common(row))) sourceUnavailable()
|
|
const grants: { payload: unknown }[] = [], grantIdentities: unknown[] = [], grantHashes: unknown[] = [], grantOversizes: boolean[] = []
|
|
for (const item of rows) {
|
|
if (item.__ps_grant_id === null) {
|
|
if (rows.length !== 1 || item.__ps_grant_payload !== null || item.__ps_grant_oversize !== null || item.__ps_grant_sha256 !== null) sourceUnavailable()
|
|
} else {
|
|
if (!includeGrants || typeof item.__ps_grant_id !== "string" || typeof item.__ps_grant_oversize !== "boolean") sourceUnavailable()
|
|
if (item.__ps_grant_oversize ? item.__ps_grant_payload !== null || item.__ps_grant_sha256 !== null
|
|
: typeof item.__ps_grant_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.__ps_grant_sha256)) sourceUnavailable()
|
|
grants.push({ payload: item.__ps_grant_payload }); grantIdentities.push(item.__ps_grant_id)
|
|
grantHashes.push(item.__ps_grant_sha256); grantOversizes.push(item.__ps_grant_oversize)
|
|
}
|
|
}
|
|
if (new Set(grantIdentities).size !== grantIdentities.length) sourceUnavailable()
|
|
const security = { id: connection.id, owner: connection.owner_id, permissions: structuredClone(connection.owner_permissions), rawPolicy, policyHash: row.__ps_policy_sha256,
|
|
generation: connection.generation, ownerUntil: row.__ps_owner_until, ownerIssued: row.__ps_owner_issued,
|
|
credential: row.__ps_credential, credentialCurrent: row.__ps_credential_current, credentialExpires: row.__ps_credential_expires, credentialRevoked: row.__ps_credential_revoked,
|
|
cutoffOwner: row.__ps_cutoff_owner, cutoff: row.__ps_cutoff_text, settings: row.__ps_settings, enabled: row.__ps_enabled,
|
|
grants: structuredClone(grants), grantIdentities, grantHashes, grantOversizes }
|
|
return { connection, grants, security, grantOversized: grantOversizes.includes(true), credentialCurrent: row.__ps_credential_current, enabled: row.__ps_enabled, cutoff: cutoff?.getTime() ?? 0 }
|
|
}
|
|
const before = await capture(), fileCutoff = await externalCutoff(before.connection.owner_id)
|
|
const portalCurrent = (value: typeof before) => {
|
|
const cutoff = Math.max(value.cutoff, fileCutoff)
|
|
if (cutoff && (!value.connection.owner_claims_issued_at.getTime() || value.connection.owner_claims_issued_at.getTime() <= cutoff))
|
|
throw new McpError("OWNER_CLAIMS_REVOKED", "Права портала изменены; войдите заново с актуальным JWT", 401)
|
|
}
|
|
portalCurrent(before)
|
|
const after = await capture()
|
|
if (after.connection.owner_id !== before.connection.owner_id) throw new McpError("STATE_CONFLICT", "Текущий источник прав изменился", 409)
|
|
portalCurrent(after)
|
|
if (!isDeepStrictEqual(before.security, after.security)) throw new McpError("STATE_CONFLICT", "Текущий источник прав изменился", 409)
|
|
return { connection: after.connection, grantRows: after.grants, grantOversized: after.grantOversized, credentialCurrent: after.credentialCurrent, enabled: after.enabled, credentialExpiresAt: after.security.credentialExpires }
|
|
}
|
|
export async function acceptPortalRevocation(raw: Buffer, timestamp: unknown, signature: unknown, secret: string) {
|
|
if (secret.length < 32) throw new McpError("WEBHOOK_DISABLED", "Webhook портала не настроен", 503)
|
|
if (!Buffer.isBuffer(raw) || raw.length > 4096 || typeof timestamp !== "string" || !/^\d{10}$/.test(timestamp) || Math.abs(Date.now() - Number(timestamp) * 1000) > 300000 || typeof signature !== "string" || !/^sha256=[a-f0-9]{64}$/.test(signature)) throw new McpError("UNAUTHORIZED", "Подпись события недействительна", 401)
|
|
const expected = createHmac("sha256", secret).update(timestamp + ".").update(raw).digest()
|
|
if (!timingSafeEqual(expected, Buffer.from(signature.slice(7), "hex"))) throw new McpError("UNAUTHORIZED", "Подпись события недействительна", 401)
|
|
const { event, cutoff } = portalRevocationEvent(raw, timestamp)
|
|
const hash = createHash("sha256").update(raw).digest("hex")
|
|
return transaction(async client => {
|
|
await lockPortalOwner(client, event.userId)
|
|
const inserted = await client.query("INSERT INTO mcp_portal_events(id,owner_id,payload_hash) VALUES($1,$2,$3) ON CONFLICT DO NOTHING RETURNING id", [event.eventId, event.userId, hash])
|
|
if (!inserted.rowCount) {
|
|
const { rows: [prior] } = await client.query("SELECT owner_id,payload_hash FROM mcp_portal_events WHERE id=$1", [event.eventId])
|
|
if (prior.owner_id !== event.userId || prior.payload_hash !== hash) throw new McpError("STATE_CONFLICT", "ID события уже использован", 409)
|
|
return { ok: true, duplicate: true }
|
|
}
|
|
await client.query("INSERT INTO mcp_owner_revocations(owner_id,invalid_before) VALUES($1,to_timestamp($2::double precision/1000)) ON CONFLICT(owner_id) DO UPDATE SET invalid_before=GREATEST(mcp_owner_revocations.invalid_before,EXCLUDED.invalid_before),updated_at=now()", [event.userId, cutoff])
|
|
await client.query("SELECT id FROM mcp_connections WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000) ORDER BY id FOR UPDATE", [event.userId, cutoff])
|
|
await client.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"revoked\"'),owner_valid_until=now(),updated_at=now() WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000)", [event.userId, cutoff])
|
|
await client.query("UPDATE mcp_credentials SET revoked_at=now() WHERE connection_id IN (SELECT id FROM mcp_connections WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000)) AND revoked_at IS NULL", [event.userId, cutoff])
|
|
await client.query("UPDATE mcp_grants SET revoked_at=now() WHERE connection_id IN (SELECT id FROM mcp_connections WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000)) AND revoked_at IS NULL", [event.userId, cutoff])
|
|
await client.query("UPDATE mcp_plans SET state='invalidated' WHERE connection_id IN (SELECT id FROM mcp_connections WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000)) AND state IN ('draft','approved','awaiting-approval')", [event.userId, cutoff])
|
|
await client.query("UPDATE mcp_routing_profiles SET enabled=false,state=state || '{\"pausedReason\":\"Права владельца отозваны порталом\"}'::jsonb WHERE connection_id IN (SELECT id FROM mcp_connections WHERE owner_id=$1 AND owner_claims_issued_at<=to_timestamp($2::double precision/1000))", [event.userId, cutoff])
|
|
await audit(client, "auth-portal", "owner.revoke", null, { eventId: event.eventId, ownerId: event.userId, type: event.type, eventOccurredAt: cutoff })
|
|
// The cutoff survives a later database restore and closes stale JWT regrant.
|
|
// If commit is lost after this write, access stays revoked and delivery retries.
|
|
await persistCutoff(event.userId, cutoff)
|
|
return { ok: true, duplicate: false }
|
|
})
|
|
}
|