92 lines
5.5 KiB
TypeScript
92 lines
5.5 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createServer } from "node:http"
|
|
import { test } from "node:test"
|
|
import { MikrotikClient, MikrotikError } from "./mikrotik.js"
|
|
import { assertRestorableBackupScript, BackupRestoreUnknownError, importBackupOnce } from "./backup-restore.js"
|
|
import { installManagedMutationSqlFixture } from "../test/fixtures/managed-mutation-sql.js"
|
|
const makeClient = () => new MikrotikClient({ host: "router.invalid", port: 80, useSsl: false, verifySsl: false, username: "test", password: "test" })
|
|
|
|
test("restore imports only the exact verified upload, even if a similar file has the same size", async t => {
|
|
const routerId = 71
|
|
const sql = installManagedMutationSqlFixture(routerId)
|
|
t.after(() => sql.restore())
|
|
const script = "# копия\n/system identity\nset name=valid"
|
|
for (const mode of ["verified", "wrong-bytes", "wrong-directory", "duplicate-name"] as const) {
|
|
let stored = Buffer.alloc(0), writes = 0, reads = 0, imports = 0
|
|
const name = "flash/restore.rsc"
|
|
const server = createServer(async (req, res) => {
|
|
const chunks: Buffer[] = []
|
|
for await (const chunk of req) chunks.push(chunk)
|
|
const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {}
|
|
const reply = (output: unknown) => {
|
|
res.setHeader("Content-Type", "application/json")
|
|
res.end(JSON.stringify(output))
|
|
}
|
|
if (req.method === "PUT" && req.url === "/rest/file") {
|
|
writes++
|
|
assert.equal(body.name, name)
|
|
assert.equal(body.contents, script + "\n")
|
|
stored = Buffer.from(mode === "wrong-bytes" ? body.contents.replace("valid", "other") : body.contents)
|
|
return reply({})
|
|
}
|
|
if (req.method === "GET" && req.url === "/rest/file") {
|
|
const entry = { ".id": "*FILE", name: mode === "wrong-directory" ? "disk/restore.rsc" : name, size: String(stored.length) }
|
|
return reply(mode === "duplicate-name" ? [entry, { ...entry, ".id": "*OTHER" }] : [entry])
|
|
}
|
|
if (req.method === "POST" && req.url === "/rest/file/read") {
|
|
reads++
|
|
assert.deepEqual(body, { file: name, offset: "0", "chunk-size": String(stored.length) })
|
|
return reply([{ data: stored.toString("utf8") }])
|
|
}
|
|
if (req.method === "POST" && req.url === "/rest/import") {
|
|
imports++
|
|
assert.deepEqual(body, { "file-name": name })
|
|
return reply({})
|
|
}
|
|
res.statusCode = 500
|
|
return reply({ error: "unexpected request" })
|
|
})
|
|
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve) })
|
|
try {
|
|
const address = server.address()
|
|
assert(address && typeof address === "object")
|
|
const router = new MikrotikClient({ host: "127.0.0.1", port: address.port, useSsl: false, verifySsl: false, username: "test", password: "test" }, routerId)
|
|
const restore = async () => {
|
|
const uploaded = await router.uploadConfigurationScript("restore.rsc", script)
|
|
await importBackupOnce(uploaded, file => router.importUploadedFile(file))
|
|
}
|
|
if (mode === "verified") await restore()
|
|
else await assert.rejects(restore(), mode === "wrong-bytes" ? /отличается от резервной копии/ : /не подтвердил имя, ID или размер/)
|
|
assert.equal(writes, 1)
|
|
assert.equal(reads, mode === "verified" || mode === "wrong-bytes" ? 1 : 0)
|
|
assert.equal(imports, mode === "verified" ? 1 : 0)
|
|
} finally {
|
|
await new Promise<void>(resolve => server.close(() => resolve()))
|
|
}
|
|
}
|
|
})
|
|
|
|
test("legacy partial exports are rejected while native and limited scripts remain usable", () => {
|
|
for (const prefix of ["", "\uFEFF\r\n "]) assert.throws(() => assertRestorableBackupScript(prefix + "# synthetic export generated by MikrotikManager\n/system identity\nset name=legacy"), /частичным экспортом/)
|
|
for (const script of ["# oct/14/2026 by RouterOS 7.24.5\n/system identity\nset name=native", "/interface bridge\nadd name=owned-probe", "# harmless fixture\n"]) assert.doesNotThrow(() => assertRestorableBackupScript(script))
|
|
})
|
|
test("import does not fallback after ambiguous failure or command rejection", async () => {
|
|
for (const error of [new Error("connection lost after apply"), new Error("Invalid JSON"), new MikrotikError(500, "/import", "error"), new MikrotikError(400, "/import", "script failed"), new MikrotikError(401, "/import", "unauthorized")]) {
|
|
const client = makeClient(), calls: string[] = []
|
|
client.post = async <T>(endpoint: string): Promise<T> => { calls.push(endpoint); throw error }
|
|
await assert.rejects(client.importUploadedFile("config.rsc"), error); assert.deepEqual(calls, ["/import"])
|
|
}
|
|
})
|
|
test("unsupported endpoint retains one fallback and successful import is not repeated", async () => {
|
|
for (const status of [200, 404, 405]) {
|
|
const client = makeClient(), calls: string[] = []
|
|
client.post = async <T>(endpoint: string): Promise<T> => { calls.push(endpoint); if (endpoint === "/import" && status !== 200) throw new MikrotikError(status, endpoint, "unsupported"); return { ok: true } as T }
|
|
await client.importUploadedFile("config.rsc"); assert.deepEqual(calls, status === 200 ? ["/import"] : ["/import", "/execute"])
|
|
}
|
|
})
|
|
test("failed import has unknown outcome and no application retry", async () => {
|
|
let calls = 0
|
|
await assert.rejects(importBackupOnce("config.rsc", async () => { calls++; throw new Error("lost response") }), BackupRestoreUnknownError)
|
|
assert.equal(calls, 1); await importBackupOnce("config.rsc", async () => ({}))
|
|
})
|