Files
order-notification-automation/tests/backup/backup.test.cjs
T

49 lines
13 KiB
JavaScript

'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto');
const {spawnSync}=require('node:child_process'),{DatabaseSync}=require('node:sqlite');
const {acquireInstanceLock}=require('../../src/platform/service/instance-lock.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
const cli=path.resolve(__dirname,'../../scripts/backup.cjs');
function fixture(t){const root=fs.mkdtempSync(path.join(os.tmpdir(),'order-backup-test-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));const state=path.join(root,'state'),output=path.join(root,'pdf'),backup=path.join(root,'backup'),restored=path.join(root,'restored'),local=path.join(root,'local');for(const p of [state,output,local])fs.mkdirSync(p);fs.writeFileSync(path.join(state,'ordinary.json'),'{"retained":true}');fs.writeFileSync(path.join(output,'order.pdf'),'%PDF-1.4 synthetic');return {root,state,output,backup,restored,local};}
function run(f,...args){return spawnSync(process.execPath,[cli,...args],{encoding:'utf8',env:{...process.env,LOCALAPPDATA:f.local,NODE_NO_WARNINGS:'1'},windowsHide:true,timeout:60000});}
function create(f){const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.equal(r.status,0,r.stderr);return JSON.parse(fs.readFileSync(path.join(f.backup,'manifest.json'),'utf8'));}
function hashes(root){const out={};function visit(dir){for(const name of fs.readdirSync(dir)){const p=path.join(dir,name),s=fs.lstatSync(p);if(s.isDirectory())visit(p);else out[path.relative(root,p)]=crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');}}visit(root);return out;}
function changeManifest(f,change){const p=path.join(f.backup,'manifest.json'),m=JSON.parse(fs.readFileSync(p));change(m);const bytes=Buffer.from(JSON.stringify(m,null,2)+'\n');fs.writeFileSync(p,bytes);fs.writeFileSync(path.join(f.backup,'manifest.sha256'),crypto.createHash('sha256').update(bytes).digest('hex')+'\n');}
test('create, verify and restore preserve complete offline state and relocate PDF history',t=>{
const f=fixture(t);fs.mkdirSync(path.join(f.state,'dashboard'));fs.mkdirSync(path.join(f.state,'empty-vault'));fs.mkdirSync(path.join(f.state,'supervisor'));
fs.writeFileSync(path.join(f.state,'supervisor','control.key'),'stale-control-token');
const db=new DatabaseSync(path.join(f.state,'dashboard','state.sqlite'));db.exec('CREATE TABLE pdf_jobs(job_id TEXT PRIMARY KEY,value TEXT NOT NULL)');db.prepare('INSERT INTO pdf_jobs VALUES(?,?)').run('j',JSON.stringify({jobId:'j',status:'success',path:path.join(f.output,'order.pdf')}));db.close();const before=hashes(f.state);
const manifest=create(f);assert.equal(manifest.appVersion,require('../../package.json').version);assert.equal(manifest.source.stateDir,f.state);assert.ok(manifest.files.every(v=>Number.isSafeInteger(v.size)&&/^[a-f0-9]{64}$/.test(v.sha256)));
assert.equal(run(f,'verify','--source',f.backup).status,0);
const restored=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(restored.status,0,restored.stderr);
assert.ok(fs.statSync(path.join(f.restored,'empty-vault')).isDirectory());assert.ok(!fs.existsSync(path.join(f.restored,'supervisor','control.key')));
assert.equal(fs.readFileSync(path.join(f.restored,'restored-pdf','order.pdf'),'utf8'),'%PDF-1.4 synthetic');assert.equal(JSON.parse(fs.readFileSync(path.join(f.restored,'restore-config.json'))).outputDir,'restored-pdf');
const target=new DatabaseSync(path.join(f.restored,'dashboard','state.sqlite'),{readOnly:true});assert.equal(JSON.parse(target.prepare('SELECT value FROM pdf_jobs').get().value).path,path.join(f.restored,'restored-pdf','order.pdf'));target.close();assert.deepEqual(hashes(f.state),before);
});
for(const attack of ['tamper','missing','unexpected','traversal','absolute','case-collision','link'])test('verify and restore reject '+attack+' without publishing state',t=>{
const f=fixture(t);create(f);const file=path.join(f.backup,'state','ordinary.json');
if(attack==='tamper')fs.appendFileSync(file,'bad');if(attack==='missing')fs.unlinkSync(file);if(attack==='unexpected')fs.writeFileSync(path.join(f.backup,'extra'),'bad');
if(attack==='traversal')changeManifest(f,m=>m.files[0].path='../outside');if(attack==='absolute')changeManifest(f,m=>m.files[0].path='C:/outside');if(attack==='case-collision')changeManifest(f,m=>m.files.push({...m.files[0],path:m.files[0].path.toUpperCase()}));
if(attack==='link'){fs.mkdirSync(path.join(f.root,'outside'));fs.symlinkSync(path.join(f.root,'outside'),path.join(f.backup,'linked'),'junction');}
assert.notEqual(run(f,'verify','--source',f.backup).status,0);assert.notEqual(run(f,'restore','--source',f.backup,'--destination',f.restored).status,0);assert.ok(!fs.existsSync(f.restored));
});
test('source links and overlapping backup destinations are refused',t=>{const f=fixture(t);fs.symlinkSync(f.output,path.join(f.state,'linked'),'junction');const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.ok(!fs.existsSync(path.join(f.backup,'manifest.json')));fs.unlinkSync(path.join(f.state,'linked'));assert.notEqual(run(f,'create','--state',f.state,'--output',f.output,'--destination',path.join(f.state,'backup')).status,0);});
test('existing backup and occupied restore destinations remain untouched',t=>{const f=fixture(t);create(f);const before=hashes(f.backup);assert.notEqual(run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup).status,0);assert.deepEqual(hashes(f.backup),before);fs.mkdirSync(f.restored);fs.writeFileSync(path.join(f.restored,'keep'),'untouched');assert.notEqual(run(f,'restore','--source',f.backup,'--destination',f.restored).status,0);assert.equal(fs.readFileSync(path.join(f.restored,'keep'),'utf8'),'untouched');});
test('active source writer blocks backup',async t=>{const f=fixture(t),lock=await acquireInstanceLock(f.state);try{const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.match(r.stderr,/ORDER_INSTANCE_OWNED/);assert.ok(!fs.existsSync(f.backup));}finally{await lock.release();}});
test('a restored state can be backed up and restored again with its contained PDF output',t=>{const f=fixture(t);create(f);let r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);const second=path.join(f.root,'backup2'),third=path.join(f.root,'restored2');r=run(f,'create','--state',f.restored,'--output',path.join(f.restored,'restored-pdf'),'--destination',second);assert.equal(r.status,0,r.stderr);r=run(f,'restore','--source',second,'--destination',third);assert.equal(r.status,0,r.stderr);assert.equal(fs.readFileSync(path.join(third,'restored-pdf/order.pdf'),'utf8'),'%PDF-1.4 synthetic');});
test('live supervisor alone blocks offline backup',async t=>{const f=fixture(t),net=require('node:net'),{controlAddress}=require('../../src/platform/service/control.cjs');if(process.platform!=='win32')return;const server=net.createServer();await new Promise(r=>server.listen(controlAddress(f.state),r));try{const r=run(f,'create','--state',f.state,'--output',f.output,'--destination',f.backup);assert.notEqual(r.status,0);assert.match(r.stderr,/ORDER_INSTANCE_OWNED/);assert.ok(!fs.existsSync(f.backup));}finally{await new Promise(r=>server.close(r));}});
test('empty notification and scan vault directories retain external keys and readable encrypted history',{skip:process.platform!=='win32'},t=>{const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});for(const [folder,vaultDir,file,table,idColumn,aad]of [['notifications','secrets','notifications.sqlite','items','id','historic'],['bpm-scan','delivery-secrets','scan.sqlite','execution_deliveries','run_id','execution-delivery:historic']]){const v=new BpmVault({stateDir:path.join(f.state,folder,vaultDir)}),db=new DatabaseSync(path.join(f.state,folder,file));db.exec('CREATE TABLE '+table+'('+idColumn+' TEXT,payload BLOB)');db.prepare('INSERT INTO '+table+' VALUES(?,?)').run('historic',v.encode(aad,{localPath:path.join(f.output,'order.pdf'),evidence:'synthetic-history'}));db.close();v.destroy();assert.deepEqual(fs.readdirSync(path.join(f.state,folder,vaultDir)),[]);}create(f);const r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);for(const [folder,vaultDir,file,table,aad]of [['notifications','secrets','notifications.sqlite','items','historic'],['bpm-scan','delivery-secrets','scan.sqlite','execution_deliveries','execution-delivery:historic']]){const v=new BpmVault({stateDir:path.join(f.restored,folder,vaultDir)}),db=new DatabaseSync(path.join(f.restored,folder,file));assert.deepEqual(v.decode(aad,db.prepare('SELECT payload FROM '+table).get().payload),{localPath:path.join(f.restored,'restored-pdf/order.pdf'),evidence:'synthetic-history'});db.close();v.destroy();}});
test('invalid DPAPI key and existing differing target key never publish restored state',{skip:process.platform!=='win32'},async t=>{const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});const v=new BpmVault({stateDir:path.join(f.state,'bpm-sessions')});await v.write('fixture',{password:'synthetic-only'});v.destroy();const m=create(f),keyRoot=path.join(f.local,'OrderNotificationAutomation/bpm-keys'),target=path.join(keyRoot,crypto.createHash('sha256').update(path.join(f.restored,'bpm-sessions').toLowerCase()).digest('hex')+'.key');fs.writeFileSync(target,'do not overwrite');let r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_COLLISION/);assert.equal(fs.readFileSync(target,'utf8'),'do not overwrite');assert.ok(!fs.existsSync(f.restored));fs.unlinkSync(target);const key=m.vaults[0].keyFile;fs.writeFileSync(path.join(f.backup,key),'invalid DPAPI blob');changeManifest(f,m=>{const item=m.files.find(f=>f.path===key);item.size=18;item.sha256=crypto.createHash('sha256').update('invalid DPAPI blob').digest('hex');});r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_IDENTITY/);assert.ok(!fs.existsSync(f.restored));fs.unlinkSync(path.join(keyRoot,path.basename(key)));const b2=path.join(f.root,'no-key');r=run(f,'create','--state',f.state,'--output',f.output,'--destination',b2);assert.notEqual(r.status,0);assert.match(r.stderr,/BACKUP_KEY_MISSING/);assert.ok(!fs.existsSync(b2));});
test('relocated DPAPI vaults decrypt synthetic records while source and key bytes remain identical',{skip:process.platform!=='win32'},async t=>{
const f=fixture(t),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=f.local;t.after(()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;});
for(const rel of ['bpm-sessions','mail/secrets','storage/secrets','order-rules/secrets','assistant','bpm-scan/delivery-secrets']){const v=new BpmVault({stateDir:path.join(f.state,rel)});await v.write('fixture',{secret:'synthetic-only-'+rel});v.destroy();}
const ruleVault=new BpmVault({stateDir:path.join(f.state,'order-rules/secrets')}),ruleDb=new DatabaseSync(path.join(f.state,'order-rules/rules.sqlite'));ruleDb.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id))');ruleDb.prepare('INSERT INTO records VALUES(?,?,?)').run('archive-intents','intent',ruleVault.encode('archive-intents:intent',{id:'intent',localPath:path.join(f.output,'order.pdf')}));ruleDb.close();ruleVault.destroy();
const original=hashes(f.state),keyRoot=path.join(f.local,'OrderNotificationAutomation','bpm-keys'),keys=hashes(keyRoot);create(f);const backupHashes=hashes(f.backup);const r=run(f,'restore','--source',f.backup,'--destination',f.restored);assert.equal(r.status,0,r.stderr);
for(const rel of ['bpm-sessions','mail/secrets','storage/secrets','order-rules/secrets','assistant','bpm-scan/delivery-secrets']){const v=new BpmVault({stateDir:path.join(f.restored,rel)});assert.deepEqual(await v.read('fixture'),{secret:'synthetic-only-'+rel});v.destroy();}
const rv=new BpmVault({stateDir:path.join(f.restored,'order-rules/secrets')}),rd=new DatabaseSync(path.join(f.restored,'order-rules/rules.sqlite'));assert.equal(rv.decode('archive-intents:intent',rd.prepare('SELECT payload FROM records').get().payload).localPath,path.join(f.restored,'restored-pdf/order.pdf'));rd.close();rv.destroy();
assert.deepEqual(hashes(f.state),original);for(const [name,hash]of Object.entries(keys))assert.equal(hashes(keyRoot)[name],hash);assert.deepEqual(hashes(f.backup),backupHashes);
assert.ok(!fs.readFileSync(path.join(f.backup,'manifest.json'),'utf8').includes('synthetic-only'));
});