59 lines
6.6 KiB
TypeScript
59 lines
6.6 KiB
TypeScript
import assert from 'node:assert/strict'
|
|
import {createServer} from 'node:http'
|
|
import {MikrotikClient} from './mikrotik.js'
|
|
import {pool,closePool} from '../db/index.js'
|
|
import {configurationAuditTransactionFixture,emptyActiveRoutingProfilesSqlFixture} from '../test/fixtures/managed-mutation-sql.js'
|
|
const originalQuery=pool.query,originalConnect=pool.connect
|
|
pool.connect=(async()=>({async query(text:string,values?:unknown[]){
|
|
const admission=configurationAuditTransactionFixture(text,values)
|
|
if(admission)return admission
|
|
if(text.startsWith('INSERT INTO mcp_audit('))return pool.query(text,values)
|
|
assert(['SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired','SELECT pg_advisory_unlock(hashtextextended($1,0))'].includes(text));assert.deepEqual(values,['mm-config:71']);return{rows:[{acquired:true}]}
|
|
},release(){}})) as typeof pool.connect
|
|
pool.query=(async(text:string,values?:unknown[])=>{const routing=emptyActiveRoutingProfilesSqlFixture(text,values,71);if(routing)return routing;if(text.startsWith('SELECT object_ref FROM mcp_protections WHERE')){assert.deepEqual(values,['71']);return{rows:[]}}assert.equal(text,'INSERT INTO mcp_audit(actor_id,action,connection_id,payload) VALUES($1,$2,$3,$4::jsonb)');assert.equal(JSON.parse(String(values?.[3])).serverId,71);return{rows:[]}}) as typeof pool.query
|
|
const good='# oct/14/2026 by RouterOS 7.24.5\n/system identity\nset name=export-test\n'
|
|
try{
|
|
for(const mode of ['success','malformed-list','export-error','truncated','section-error','oversize','cleanup-error','foreign-id','short-chunk','missing-data','changed-file','utf8-boundary','max-size']){
|
|
let ownName='',exportCalls=0,readCalls=0,deletes=0
|
|
const original={'.id':'*ORIG',name:'important.rsc',size:'2'}
|
|
let own:Record<string,string>|null=null
|
|
const content=mode==='utf8-boundary'?good+'#'.repeat(32767-Buffer.byteLength(good))+'я'.repeat(20000):mode==='section-error'?good+'#error exporting /routing (timeout)\n':['oversize','short-chunk','missing-data','changed-file'].includes(mode)?good+'#'.repeat(70000):good
|
|
const fixture=createServer(async(req,res)=>{let input='';for await(const b of req)input+=b;const body=input?JSON.parse(input):{};const reply=(status:number,value:unknown)=>{res.statusCode=status;res.setHeader('content-type','application/json');res.end(JSON.stringify(value))}
|
|
if(req.method==='GET'&&req.url==='/rest/file')return reply(200,mode==='malformed-list'?{}:[original,...(own?[own]:[])])
|
|
if(req.method==='POST'&&req.url==='/rest/export'){exportCalls++;ownName=body.file;assert(/^mmapp-export-[a-f0-9-]{36}\.rsc$/.test(ownName));assert.deepEqual(Object.keys(body),['file']);own={'.id':mode==='foreign-id'?'*ORIG':'*TEMP',name:ownName,size:String(mode==='max-size'?8*1024*1024+1:Buffer.byteLength(content))};return reply(mode==='export-error'?500:200,mode==='export-error'?{error:'export failed'}:[])}
|
|
if(req.method==='POST'&&req.url==='/rest/file/read'){readCalls++;const offset=Number(body.offset),length=Number(body['chunk-size']);assert.equal(body.file,ownName);assert(length>0&&length<=32768);const bytes=Buffer.from(content).subarray(offset,offset+length);const data=bytes.toString('utf8');if(mode==='utf8-boundary'){const encoded=[];for(const byte of bytes){if(byte===34||byte===92)encoded.push(92,byte);else if(byte===10)encoded.push(92,110);else if(byte===13)encoded.push(92,114);else encoded.push(byte)}res.setHeader('content-type','application/json');res.end(Buffer.concat([Buffer.from('[{"data":"'),Buffer.from(encoded),Buffer.from('"}]')]));return}if(mode==='changed-file'&&own)own['last-modified']='changed';return reply(200,mode==='missing-data'?[{ret:data}]:[{data:['short-chunk','truncated'].includes(mode)?data.slice(0,-1):data}])}
|
|
if(req.method==='POST'&&req.url==='/rest/file/get'){readCalls++;return reply(200,[{ret:mode==='truncated'?content.slice(0,20):content}])}
|
|
if(req.method==='DELETE'&&req.url==='/rest/file/*TEMP'){deletes++;if(mode==='cleanup-error')return reply(500,{error:'cleanup denied'});own=null;return reply(200,{})}
|
|
assert.fail('Unexpected request '+req.method+' '+req.url)
|
|
});await new Promise<void>(r=>fixture.listen(0,'127.0.0.1',r));const address=fixture.address();assert(address&&typeof address!=='string');const c=new MikrotikClient({host:'127.0.0.1',port:address.port,useSsl:false,verifySsl:false,username:'fixture',password:'fixture'}, 71);
|
|
try{if(['success','oversize','utf8-boundary'].includes(mode)){assert.equal(await c.exportConfigScript(),content);assert.equal(readCalls,mode==='success'?1:3)}else await assert.rejects(c.exportConfigScript(), mode);assert.equal(original.name,'important.rsc');if(mode==='malformed-list')assert.equal(exportCalls,0);else assert.equal(exportCalls,1);if(!['malformed-list','foreign-id'].includes(mode))assert.equal(deletes,1);if(!['cleanup-error','foreign-id'].includes(mode))assert.equal(own,null);if(mode==='max-size')assert.equal(readCalls,0);if(['short-chunk','missing-data'].includes(mode))assert.equal(readCalls,1)}finally{await new Promise<void>(r=>fixture.close(()=>r()))}
|
|
}
|
|
console.log('native configuration export: 13 HTTP scenarios passed; original file never deleted')
|
|
for (const mode of ['unsupported-put', 'lost-put-response', 'missing-readback'] as const) {
|
|
const methods: string[] = []
|
|
const fixture = createServer(async (request, response) => {
|
|
methods.push(`${request.method} ${request.url}`)
|
|
for await (const _chunk of request) { /* Drain the request. */ }
|
|
if (mode === 'lost-put-response' && request.method === 'PUT') {
|
|
request.socket.destroy()
|
|
return
|
|
}
|
|
if (mode === 'unsupported-put' && request.method === 'PUT') response.statusCode = 405
|
|
response.setHeader('content-type', 'application/json')
|
|
response.end(JSON.stringify(request.method === 'GET' ? (mode === 'unsupported-put'
|
|
? [{'.id':'*NEW', name:'flash/test.rsc', size:'5'}] : []) : {}))
|
|
})
|
|
await new Promise<void>(resolve => fixture.listen(0, '127.0.0.1', resolve))
|
|
const address = fixture.address()
|
|
assert(address && typeof address !== 'string')
|
|
const router = new MikrotikClient({ host:'127.0.0.1', port:address.port, useSsl:false, verifySsl:false, username:'fixture', password:'fixture' }, 71)
|
|
try {
|
|
if (mode === 'unsupported-put') assert.equal(await router.uploadTextFile('test.rsc', 'test'), 'flash/test.rsc')
|
|
else await assert.rejects(router.uploadTextFile('test.rsc', 'test'))
|
|
assert.deepEqual(methods, mode === 'unsupported-put' ? ['PUT /rest/file', 'POST /rest/file/add', 'GET /rest/file']
|
|
: mode === 'missing-readback' ? ['PUT /rest/file', 'GET /rest/file'] : ['PUT /rest/file'])
|
|
} finally { await new Promise<void>(resolve => fixture.close(() => resolve())) }
|
|
}
|
|
}finally{pool.query=originalQuery;pool.connect=originalConnect;await closePool()}
|
|
|