91 lines
7.0 KiB
TypeScript
91 lines
7.0 KiB
TypeScript
import { z } from "zod"
|
|
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
|
import { getServerRowById } from "../modules/servers/repository/servers-repository.js"
|
|
import { MikrotikClient, firewallRestPath, encodeRosId } from "./mikrotik.js"
|
|
import { observedBoolean } from "./ospf-observed-values.js"
|
|
import { fingerprint } from "../modules/mcp/security.js"
|
|
import { RuleWriteSchema, ruleToRos } from "./firewall-rule-input.js"
|
|
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
|
import { captureAndAppendRevision } from "./config-revisions.js"
|
|
import { fetchFirewallState } from "./firewall-live.js"
|
|
|
|
const key = { family: z.enum(["ip", "ip6"]), table: z.enum(["filter", "nat", "mangle", "raw"]) }
|
|
const nativeId = z.string().regex(/^\*[A-Za-z0-9]+$/).max(100)
|
|
export const firewallRuleFieldsSchema = RuleWriteSchema.omit({ serverId: true, family: true, table: true, rosId: true }).strict()
|
|
export const firewallRuleMutationSchema = z.discriminatedUnion("operation", [
|
|
z.object({ ...key, operation: z.literal("create"), fields: firewallRuleFieldsSchema }).strict(),
|
|
z.object({ ...key, operation: z.literal("update"), rosId: nativeId, fields: firewallRuleFieldsSchema }).strict(),
|
|
z.object({ ...key, operation: z.literal("toggle"), rosId: nativeId, disabled: z.boolean() }).strict(),
|
|
z.object({ ...key, operation: z.literal("delete"), rosId: nativeId }).strict(),
|
|
])
|
|
export type FirewallRuleMutation = z.infer<typeof firewallRuleMutationSchema>
|
|
export type FirewallRuleState = { serverConfiguration: string; rows: Record<string, string>[] }
|
|
const conflict = (message: string) => Object.assign(new Error(message), { statusCode: 409 })
|
|
const bodyFor = (input: FirewallRuleMutation): Record<string, string> => input.operation === "delete" ? {} : input.operation === "toggle" ? { disabled: input.disabled ? "yes" : "no" } : ruleToRos({ ...input.fields, serverId: "", family: input.family, table: input.table })
|
|
const same = (a: unknown, b: unknown) => fingerprint(a) === fingerprint(b)
|
|
const normalized = (value: string | undefined, key: string) => ["disabled", "log", "dynamic", "invalid"].includes(key) ? observedBoolean(value) : value
|
|
|
|
export async function readFirewallRuleState(server: ServerRow, input: FirewallRuleMutation): Promise<FirewallRuleState> {
|
|
if (!server.enabled) throw conflict("Сервер отключён")
|
|
const client = MikrotikClient.fromServer(server), path = firewallRestPath(input.family, input.table)
|
|
const raw = await client.get<unknown>(path)
|
|
if (!Array.isArray(raw) || raw.length > 1000 || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || Object.values(row).some(value => typeof value !== "string") || [".id", "chain", "action"].some(key => typeof row[key] !== "string" || !row[key].trim()))) throw conflict("Недостоверная таблица Firewall")
|
|
if (new Set(raw.map(row => row[".id"])).size !== raw.length) throw conflict("Повторяющиеся ID Firewall")
|
|
const rows = (raw as Record<string, string>[]).map(row => Object.fromEntries(Object.entries(row).filter(([key]) => !["bytes", "packets"].includes(key))))
|
|
const target = input.operation === "create" ? undefined : rows.find(row => row[".id"] === input.rosId)
|
|
if (target && target.dynamic === undefined) {
|
|
const result = await client.post<{ ret?: string }>(`${path}/get`, { ".id": target[".id"], "value-name": "dynamic" })
|
|
if (typeof result?.ret === "string") target.dynamic = result.ret
|
|
}
|
|
return { serverConfiguration: fingerprint(server), rows }
|
|
}
|
|
|
|
export function assertFirewallRuleTarget(input: FirewallRuleMutation, before: FirewallRuleState) {
|
|
if (input.operation === "create") return
|
|
const row = before.rows.find(row => row[".id"] === input.rosId)
|
|
if (!row || observedBoolean(row.dynamic) !== false) throw conflict("Требуется существующее подтверждённо статическое правило")
|
|
}
|
|
|
|
/** Verify only the requested mutation while preserving every opaque matcher and order. */
|
|
export function verifyFirewallRuleMutation(input: FirewallRuleMutation, before: FirewallRuleState, next: FirewallRuleState) {
|
|
if (before.serverConfiguration !== next.serverConfiguration) return false
|
|
const body = bodyFor(input)
|
|
if (input.operation === "create") {
|
|
const added = next.rows.filter(row => !before.rows.some(previous => previous[".id"] === row[".id"]))
|
|
return added.length === 1 && next.rows.at(-1) === added[0] && same(next.rows.slice(0, -1), before.rows)
|
|
&& Object.entries(body).every(([key, value]) => normalized(added[0][key], key) === normalized(value, key))
|
|
}
|
|
const expected = before.rows.filter(row => input.operation !== "delete" || row[".id"] !== input.rosId).map(row => row[".id"] === input.rosId ? { ...row, ...body } : row)
|
|
const canonical = (rows: Record<string, string>[]) => rows.map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, normalized(value, key)])))
|
|
return same(canonical(next.rows), canonical(expected))
|
|
}
|
|
|
|
export async function executeFirewallRuleMutation(input: FirewallRuleMutation, expectedFingerprint: string | undefined, deps: {
|
|
read: () => Promise<FirewallRuleState>; command: (body: Record<string, string>) => Promise<unknown>; recordRevision: () => Promise<boolean>;
|
|
}) {
|
|
const before = await deps.read()
|
|
if (expectedFingerprint && fingerprint(before) !== expectedFingerprint) throw conflict("Конфигурация Firewall изменилась после подготовки")
|
|
assertFirewallRuleTarget(input, before)
|
|
await deps.command(bodyFor(input))
|
|
const next = await deps.read(), verified = verifyFirewallRuleMutation(input, before, next)
|
|
return { acknowledged: true, verified, afterFingerprint: fingerprint(next), revisionRecorded: verified ? await deps.recordRevision() : false }
|
|
}
|
|
|
|
export async function writeFirewallRule(server: ServerRow, raw: FirewallRuleMutation, expectedFingerprint?: string) {
|
|
const input = firewallRuleMutationSchema.parse(raw)
|
|
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => {
|
|
const fresh = await getServerRowById(server.id)
|
|
if (!fresh?.enabled || !same(fresh, server)) throw conflict("Источник Firewall изменился")
|
|
const client = MikrotikClient.fromServer(fresh), path = firewallRestPath(input.family, input.table)
|
|
return executeFirewallRuleMutation(input, expectedFingerprint, {
|
|
read: () => readFirewallRuleState(fresh, input),
|
|
command: body => input.operation === "create" ? client.put(path, body) : input.operation === "delete" ? client.delete(`${path}/${encodeRosId(input.rosId)}`) : client.patch(`${path}/${encodeRosId(input.rosId)}`, body),
|
|
recordRevision: async () => (await captureAndAppendRevision({ serverId: fresh.id, section: "firewall", source: "apply", capture: async () => {
|
|
const state = await fetchFirewallState(fresh)
|
|
if (!state.snapshotFlagsVerified) throw conflict("Flags ревизии Firewall не подтверждены")
|
|
return state.snapshot
|
|
} })) !== null,
|
|
})
|
|
}))
|
|
}
|