29 lines
15 KiB
JavaScript
29 lines
15 KiB
JavaScript
'use strict';
|
|||
|
|
const {app,BrowserWindow,session,safeStorage}=require('electron'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'),{X509Certificate}=require('node:crypto');
|
||
|
|
app.setPath('userData',process.env.SAFETYNET_SMOKE_USERDATA);app.disableHardwareAcceleration();require('../apps/browser/main.cjs');
|
||
|
|
const wait=ms=>new Promise(r=>setTimeout(r,ms)),base=process.env.SAFETYNET_SMOKE_SERVER,origin=process.env.SAFETYNET_SMOKE_ORIGIN,headers={authorization:`Bearer ${process.env.SAFETYNET_SMOKE_ADMIN}`,'content-type':'application/json'};
|
||
|
|
async function until(fn){for(let i=0;i<200;i++){const r=await fn();if(r)return r;await wait(100);}throw Error('Vault native fixture timed out');}
|
||
|
|
const overview=async()=> (await fetch(base+'/api/admin/overview',{headers})).json();
|
||
|
|
app.whenReady().then(async()=>{const pages=[];let stage='startup';try{
|
||
|
|
const win=await until(()=>{const w=BrowserWindow.getAllWindows()[0];return w&&!w.webContents.isLoading()&&w.webContents.getURL().endsWith('index.html')&&w;});
|
||
|
|
const fingerprint=new X509Certificate(fs.readFileSync(path.join(__dirname,'../tests/fixtures/icap/cert.pem'))).fingerprint256;
|
||
|
|
// Only the exact synthetic certificate on loopback is trusted, in this isolated fixture partition.
|
||
|
|
session.fromPartition('persist:safetynet-managed').setCertificateVerifyProc((req,callback)=>callback(req.hostname==='127.0.0.1'&&new X509Certificate(req.certificate.data).fingerprint256===fingerprint?0:-2));
|
||
|
|
const ui=async(method,value)=>{const result=await win.webContents.executeJavaScript(`window.safetynet.${method}(${value===undefined?'':JSON.stringify(value)})`);assert.equal(result.ok,true,method);return result.data;};
|
||
|
|
stage='enrollment';if(process.env.SAFETYNET_SMOKE_PHASE==='save')await ui('enroll',{server:base,code:process.env.SAFETYNET_SMOKE_CODE});else await until(async()=> (await ui('state')).ready);const page=win.contentView.children.find(v=>v.webContents!==win.webContents).webContents;pages.push(page);await until(()=>!page.isLoading()&&page.getURL().startsWith(origin));
|
||
|
|
const a=await ui('agentConnection','session-a'),b=await ui('agentConnection','session-b'),requestFile=path.join(app.getPath('userData'),'session-request.json');
|
||
|
|
async function call(connection,action,args={}){fs.writeFileSync(requestFile,JSON.stringify({action,args}));const child=require('node:child_process').spawn(process.execPath,['scripts/agent-client.cjs','--connection',connection.credentialPath,'--request',requestFile],{windowsHide:true,stdio:['ignore','pipe','pipe']});let output='';child.stdout.on('data',v=>output+=v);child.stderr.on('data',()=>{});const exit=await new Promise(r=>{child.once('exit',r);child.once('error',()=>r(1));});return {exit,result:exit===0?JSON.parse(output).result:undefined};}
|
||
|
|
const inventory=async()=>{const r=await call(a,'sessions');assert.equal(r.exit,0);return r.result;};
|
||
|
|
if(process.env.SAFETYNET_SMOKE_PHASE==='save'){
|
||
|
|
stage='save tabs';const first=(await inventory())[0].id;await ui('groupTab',{id:first,group:'Research'});await ui('createTab',{url:origin+'/reference?view=public#details',group:'Research'});await until(()=>win.contentView.children.filter(v=>v.webContents!==win.webContents).every(v=>!v.webContents.isLoading()));for(const v of win.contentView.children.filter(v=>v.webContents!==win.webContents))await v.webContents.executeJavaScript("document.querySelector('input[name=private]').value='PRIVATE_EDITED_FORM';document.querySelector('input[type=password]').value='PRIVATE_EDITED_PASSWORD';history.replaceState({pageState:'PRIVATE_PAGESTATE'},'')");const ids=(await inventory()).map(row=>row.id);assert.equal(ids.length,2);const saved=await call(a,'sessions:save',{name:'Research collection',sessionIds:ids});assert.equal(saved.exit,0);const listed=await call(a,'sessions:list');assert.equal(listed.exit,0);assert.equal(listed.result.collections[0].tabs.length,2);assert.ok(listed.result.collections[0].tabs.every(t=>t.group==='Research'));assert.ok(listed.result.collections[0].tabs.some(t=>t.url.includes('?q=public#section')));const raw=fs.readFileSync(path.join(app.getPath('userData'),'managed-sessions.bin'));for(const text of ['Research collection',origin,'PRIVATE_FORM_SENTINEL','PRIVATE_PASSWORD_SENTINEL','pageState'])assert.equal(raw.includes(Buffer.from(text)),false);const plain=Buffer.from(safeStorage.decryptString(raw),'base64');try{const parsed=JSON.parse(plain.toString());for(const row of parsed.collections)for(const tab of row.collection.tabs){assert.deepEqual(Object.keys(tab).sort(),['group','title','url']);for(const text of ['PRIVATE_EDITED_FORM','PRIVATE_EDITED_PASSWORD','PRIVATE_PAGESTATE'])assert.ok(!plain.includes(Buffer.from(text)));}}finally{plain.fill(0);}await wait(1500);fs.writeFileSync(path.join(app.getPath('userData'),'session-fixture-id.json'),JSON.stringify({id:saved.result.id}));for(const p of pages)require('../apps/browser/page-clipboard-guard.cjs').disposePageClipboardGuard(p);app.exit(0);return;}
|
||
|
|
stage='restart inventory';const id=JSON.parse(fs.readFileSync(path.join(app.getPath('userData'),'session-fixture-id.json'))).id;let listed=await call(a,'sessions:list');assert.equal(listed.exit,0);assert.equal(listed.result.collections[0].id,id);for(const text of ['PRIVATE_FORM_SENTINEL','PRIVATE_PASSWORD_SENTINEL','pageState'])assert.ok(!JSON.stringify(listed.result).includes(text));assert.equal((await call(b,'sessions:list')).result.collections.length,0);
|
||
|
|
stage='cross actor';let plan=await call(a,'sessions:restore',{id});assert.equal(plan.exit,0);assert.equal((await call(b,'sessions:restore',{planId:plan.result.planId})).exit,1); // attempted consumption is scoped to the authenticated actor
|
||
|
|
plan=await call(a,'sessions:restore',{id});assert.equal(plan.exit,0);const originals=await inventory();stage='restore actual tabs';const restored=await call(a,'sessions:restore',{planId:plan.result.planId});assert.equal(restored.exit,0);assert.equal(restored.result.sessionIds.length,2);await until(()=>win.contentView.children.filter(v=>v.webContents!==win.webContents).every(v=>!v.webContents.isLoading()));let now=await inventory();assert.equal(now.length,originals.length+2);for(const row of originals)assert.ok(now.some(x=>x.id===row.id));assert.ok((await ui('state')).tabs.filter(t=>restored.result.sessionIds.includes(t.id)).every(t=>t.group==='Research'));for(const tab of win.contentView.children.filter(v=>v.webContents!==win.webContents).slice(-2)){assert.equal(await tab.webContents.executeJavaScript('document.querySelector("input[name=private]").value'), 'PRIVATE_FORM_SENTINEL');assert.equal(await tab.webContents.executeJavaScript('document.querySelector("input[type=password]").value'), 'PRIVATE_PASSWORD_SENTINEL');}assert.equal((await call(a,'sessions:restore',{planId:plan.result.planId})).exit,1);
|
||
|
|
stage='stale revision';plan=await call(a,'sessions:restore',{id});await call(a,'sessions:save',{name:'Another collection',sessionIds:[now[0].id]});assert.equal((await call(a,'sessions:restore',{planId:plan.result.planId})).exit,1);
|
||
|
|
stage='activation race source';const baseIds=(await inventory()).map(r=>r.id);await ui('createTab',{url:origin+'/delayed?delay=public',group:'Race'});await until(()=>win.contentView.children.filter(v=>v.webContents!==win.webContents).every(v=>!v.webContents.isLoading()));const delayedId=(await inventory()).find(r=>!baseIds.includes(r.id)).id;await ui('createTab',{url:origin+'/second-race',group:'Race'});await until(()=>win.contentView.children.filter(v=>v.webContents!==win.webContents).every(v=>!v.webContents.isLoading()));const secondId=(await inventory()).find(r=>!baseIds.includes(r.id)&&r.id!==delayedId).id;const raceSaved=await call(a,'sessions:save',{name:'Race collection',sessionIds:[delayedId,secondId]});assert.equal(raceSaved.exit,0);await ui('closeTab',secondId);await ui('closeTab',delayedId);await ui('activateTab',baseIds[0]);const raceOriginals=await inventory(),raceContents=win.contentView.children.filter(v=>v.webContents!==win.webContents).map(v=>v.webContents);const raceCounts=async()=> (await page.executeJavaScript("fetch('/count').then(r=>r.json())")).paths;const raceBefore=await raceCounts();const racePlan=await call(a,'sessions:restore',{id:raceSaved.result.id});assert.equal(racePlan.exit,0);stage='activation away and back';const raceCommit=call(a,'sessions:restore',{planId:racePlan.result.planId});await until(()=>win.contentView.children.some(v=>v.webContents!==win.webContents&&!raceContents.includes(v.webContents)&&v.webContents.isLoading()));await until(async()=>((await raceCounts())['/delayed']||0)===(raceBefore['/delayed']||0)+1);const raceState=await ui('state'),newId=raceState.tabs.find(t=>!raceOriginals.some(r=>r.id===t.id)).id;await ui('activateTab',baseIds[0]);await ui('activateTab',newId);assert.equal((await raceCommit).exit,1);await until(async()=> (await inventory()).length===raceOriginals.length);const raceAfter=await inventory();for(const old of raceOriginals)assert.ok(raceAfter.some(r=>r.id===old.id));const raceAfterCounts=await raceCounts();assert.equal(raceAfterCounts['/delayed'],(raceBefore['/delayed']||0)+1);assert.equal(raceAfterCounts['/second-race']||0,raceBefore['/second-race']||0);
|
||
|
|
const change=async modify=>{const p=(await overview()).policy;modify(p);p.version++;const proposed=await fetch(base+'/api/admin/policy',{method:'PUT',headers,body:JSON.stringify(p)});assert.equal(proposed.status,202);const review=await proposed.json();const approval=await fetch(base+`/api/admin/policy-reviews/${review.reviewId}/approve`,{method:'POST',headers:{cookie:`sn_session=${process.env.SAFETYNET_SMOKE_REVIEWER}`,origin:base,'content-type':'application/json'},body:JSON.stringify({payloadHash:review.payloadHash,expectedVersion:review.expectedVersion,approve:true})});assert.equal(approval.status,200);await until(async()=>{const s=await ui('state');return s.ready&&s.policyVersion===p.version;});};
|
||
|
|
stage='central disable';plan=await call(a,'sessions:restore',{id});const count=async()=> (await page.executeJavaScript("fetch('/count').then(r=>r.json())")).requested;let before;await change(p=>{p.agents.scopes=p.agents.scopes.filter(s=>s!=='sessions:restore');});await wait(500);before=await count();assert.equal((await call(a,'sessions:restore',{planId:plan.result.planId})).exit,1);assert.equal(await count(),before);await change(p=>{p.agents.scopes.push('sessions:restore');});
|
||
|
|
stage='host restriction';plan=await call(a,'sessions:restore',{id});await change(p=>{p.agents.grants.find(g=>g.id==='session-a').allowedHosts=['127.0.0.2'];});await wait(500);before=await count();assert.equal((await call(a,'sessions:restore',{planId:plan.result.planId})).exit,1);assert.equal(await count(),before);await change(p=>{p.agents.grants.find(g=>g.id==='session-a').allowedHosts=['127.0.0.1'];});
|
||
|
|
stage='target revoke';plan=await call(a,'sessions:restore',{id});await change(p=>{p.agents.grants.find(g=>g.id==='session-a').enabled=false;});await wait(500);before=await count();assert.equal((await call(a,'sessions:restore',{planId:plan.result.planId})).exit,1);assert.equal(await count(),before);
|
||
|
|
stage='audit trace';const events=await until(async()=>{const e=(await overview()).events;return e.some(e=>e.metadata.agent?.action==='sessions:restore'&&e.metadata.agent.outcome==='completed')&&e;});for(const e of events)for(const text of ['PRIVATE_FORM_SENTINEL','PRIVATE_PASSWORD_SENTINEL','Research collection'])assert.ok(!JSON.stringify(e).includes(text));await wait(1500);const proofs=[];for(const action of ['sessions:save','sessions:list','sessions:restore']){let proof;for(const event of events.filter(e=>e.metadata.agent?.action===action&&e.metadata.agent.outcome==='completed'&&e.metadata.traceId)){const trace=await(await fetch('http://127.0.0.1:4318/api/trace/'+event.metadata.traceId)).json(),spans=trace.spans||[];if(action==='sessions:restore'&&!spans.some(s=>s.operation==='sessions.native'))continue;const request=spans.find(s=>s.operation==='agent.request'),dispatch=spans.find(s=>s.operation==='agent.dispatch'&&s.parentSpanId===request?.spanId),agent=spans.find(s=>s.name==='browser.agent'&&s.operation===action&&s.parentSpanId===dispatch?.spanId);assert.ok(agent);for(const op of ['audit.serialize','audit.encrypt','audit.write','audit.fsync','audit.commit'])assert.ok(spans.some(s=>s.operation===op&&spans.some(p=>p.operation==='agent.audit'&&p.spanId===s.parentSpanId)),op);for(const op of action==='sessions:save'?['sessions.inspect','sessions.save']:action==='sessions:list'?['sessions.list','sessions.inspect']:['sessions.load','sessions.inspect','sessions.restore','sessions.preflight','sessions.native'])assert.ok(spans.some(s=>s.name==='browser.session'&&s.operation===op&&spans.some(p=>p.spanId===s.parentSpanId)),op);proof={action,traceId:event.metadata.traceId,stages:spans.map(({name,operation,parentSpanId,spanId,durationMs})=>({name,operation,parentSpanId,spanId,durationMs}))};break;}assert.ok(proof,action);proofs.push(proof);}let raceProof;for(const event of events.filter(e=>e.metadata.agent?.action==='sessions:restore'&&e.metadata.agent.outcome!=='completed'&&e.metadata.traceId)){const t=await(await fetch('http://127.0.0.1:4318/api/trace/'+event.metadata.traceId)).json();if(t.spans?.some(s=>s.operation==='sessions.rollback')){raceProof={traceId:event.metadata.traceId,stages:t.spans.map(({name,operation,parentSpanId,spanId,durationMs})=>({name,operation,parentSpanId,spanId,durationMs}))};break;}}assert.ok(raceProof,'Actual race rollback trace required');const health=await(await fetch('http://127.0.0.1:4318/health')).json();assert.equal(health.rejectedWrites,0);fs.writeFileSync(path.join(process.env.SAFETYNET_SMOKE_ARTIFACTS,'session-agent-controls-native-proof.json'),JSON.stringify({actualElectron:true,encryptedRestart:true,sameDevicePrincipal:true,benignQueryHashPreserved:true,groupsPreserved:true,existingTabsPreserved:true,noPageStateOrSecretsSaved:true,twoStage:true,crossActorDenied:true,replayDenied:true,staleRevisionDenied:true,activationAwayAndBackDenied:true,raceOwnedTabsCleaned:true,raceExistingTabsPreserved:true,raceSecondDestinationNotReleased:true,raceProof,centralDisableBeforeRelease:true,hostRestrictionBeforeRelease:true,targetedRevocationBeforeRelease:true,health:{storedBytes:health.storedBytes,rejectedWrites:health.rejectedWrites},proofs},null,2));console.log('Session agent controls native proof passed');for(const p of win.contentView.children.filter(v=>v.webContents!==win.webContents))require('../apps/browser/page-clipboard-guard.cjs').disposePageClipboardGuard(p.webContents);app.exit(0);
|
||
|
|
}catch(error){fs.writeFileSync(path.resolve('artifacts/session-agent-controls-native-error.json'),JSON.stringify({stage,name:error.name,message:error.message},null,2));console.error(`Session fixture failed at ${stage}: ${error.name}`);for(const p of pages)if(!p.isDestroyed())require('../apps/browser/page-clipboard-guard.cjs').disposePageClipboardGuard(p);app.exit(1);}});
|