forked from mtusi2026/mtusi2026lab6
14 lines
7.9 KiB
TypeScript
14 lines
7.9 KiB
TypeScript
import{createServer}from'node:net';import{gzipSync}from'node:zlib';import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
|
|
if(process.platform!=='linux'||!process.argv.includes('--run-native'))throw new Error('Explicit native Linux fixture invocation required; no live command executed');
|
|
const root=resolve(import.meta.dir,'..'),out=resolve(root,'.local/response-boundary-'+crypto.randomUUID()),claim=crypto.randomUUID();await mkdir(out,{mode:0o700});await writeFile(resolve(out,'CLAIM.json'),JSON.stringify({claim,kind:'temporary native HAProxy response framing test; synthetic upstream only'})+'\n',{flag:'wx',mode:0o600});
|
|
const run=(args:string[])=>Bun.spawnSync(args,{stdout:'pipe',stderr:'pipe'}),own=run(['docker','inspect','mtuci-vp6-medvedev-observe-query-1']);if(own.exitCode!==0)throw new Error('Own gateway missing');const gateway=JSON.parse(new TextDecoder().decode(own.stdout))[0];if(gateway.Config.Labels['com.docker.compose.project']!=='mtuci-vp6-medvedev')throw new Error('Own gateway identity mismatch');const image=gateway.Image,source=await readFile(resolve(root,'config/openobserve-query.cfg'),'utf8');let cfg=source.replace('bind :5082','bind 127.0.0.1:29506').replace(/ server own openobserve:5080[^\n]*/,' server synthetic 127.0.0.1:29606');if(cfg===source||cfg.includes('server own openobserve:5080'))throw new Error('Fixture must not address real upstream');
|
|
cfg=cfg.replace(' http-response return',' http-response set-header X-VP6-Observed-Length %[res.fhdr(Content-Length)]\n http-response set-header X-VP6-Observed-Length-Count %[res.fhdr_cnt(Content-Length)]\n http-response return');
|
|
const configPath=resolve(out,'fixture.cfg'),usersPath=resolve(out,'users.cfg');await writeFile(configPath,cfg,{flag:'wx',mode:0o644});await writeFile(usersPath,'userlist query_users\n user fixture insecure-password fixture-only\n',{flag:'wx',mode:0o644});
|
|
const small=Buffer.from('{"ok":true}'),sized=(n:number)=>Buffer.from('{"v":"'+'x'.repeat(n-8)+'"}');if(sized(1048576).length!==1048576)throw new Error('Fixture byte oracle invalid');
|
|
const cases=[{id:'small',body:small,headers:['Content-Length: '+small.length],expected:[200]}, {id:'exact-cap',body:sized(1048576),headers:['Content-Length: 1048576'],expected:[200]}, {id:'cap-plus-one',body:sized(1048577),headers:['Content-Length: 1048577'],expected:[502]}, {id:'gzip',body:gzipSync(small),headers:['Content-Length: '+gzipSync(small).length,'Content-Encoding: gzip'],expected:[502]}, {id:'encoding-identity',body:small,headers:['Content-Length: '+small.length,'Content-Encoding: identity'],expected:[502]}, {id:'empty-encoding',body:small,headers:['Content-Length: '+small.length,'Content-Encoding:'],expected:[502]}, {id:'chunked',body:Buffer.from(small.length.toString(16)+'\r\n'+small+'\r\n0\r\n\r\n'),headers:['Transfer-Encoding: chunked'],expected:[502]}, {id:'eof-delimited',body:small,headers:[],expected:[502]}, {id:'duplicate-equal',body:small,headers:['Content-Length: '+small.length,'Content-Length: '+small.length],expected:[200,502],normalizationInformational:true}, {id:'duplicate-conflicting',body:small,headers:['Content-Length: '+small.length,'Content-Length: '+(small.length+1)],expected:[502]}, {id:'leading-zero',body:small,headers:['Content-Length: 000'+small.length],expected:[200,502],normalizationInformational:true}, {id:'invalid-length',body:small,headers:['Content-Length: abc'],expected:[502]}, {id:'length-overflow',body:small,headers:['Content-Length: 999999999999999999999999999999999999'],expected:[502]}, {id:'negative-length',body:small,headers:['Content-Length: -1'],expected:[502]}];
|
|
const originRequests:any[]=[];const server=createServer(socket=>{let request='';socket.on('data',chunk=>{request+=chunk.toString();if(!request.includes('\r\n\r\n'))return;socket.removeAllListeners('data');const id=/fixture=([a-z0-9-]+)/.exec(request)?.[1],c=cases.find(c=>c.id===id)??cases[0];originRequests.push({id:c.id,acceptEncodingIdentity:/\r\naccept-encoding:\s*identity\r\n/i.test(request)});socket.end(Buffer.concat([Buffer.from('HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/json\r\n'+c.headers.join('\r\n')+'\r\n\r\n'),c.body]));});socket.on('error',()=>{});});await new Promise<void>((ok,fail)=>{server.once('error',fail);server.listen(29606,'127.0.0.1',ok);});let id='',primaryFailure:string|undefined,cleanup='not-started';const results:any[]=[];
|
|
try{const launched=run(['docker','run','--detach','--rm','--pull=never','--network','host','--read-only','--cap-drop','ALL','--user','10001:10001','--label','mtuci.task=vp6-response-boundary','--label','mtuci.claim='+claim,'-v',configPath+':/fixture.cfg:ro','-v',usersPath+':/users.cfg:ro','--entrypoint','haproxy',image,'-W','-db','-f','/fixture.cfg','-f','/users.cfg']);await writeFile(resolve(out,'launch-stderr.private'),launched.stderr,{flag:'wx',mode:0o600});if(launched.exitCode!==0)throw new Error('Fixture container launch failed');id=new TextDecoder().decode(launched.stdout).trim();if(!/^[a-f0-9]{64}$/.test(id))throw new Error('Owned fixture launch identity absent');for(let attempt=0;attempt<50;attempt++){try{const r=await fetch('http://127.0.0.1:29506/api/default/streams?fixture=small',{headers:{Authorization:'Basic Zml4dHVyZTpmaXh0dXJlLW9ubHk='},signal:AbortSignal.timeout(1000)});await r.arrayBuffer();if(r.status===200)break;}catch{}if(attempt===49)throw new Error('Fixture readiness failed');await Bun.sleep(100);}
|
|
for(const c of cases){const response=await fetch('http://127.0.0.1:29506/api/default/streams?fixture='+c.id,{headers:{Authorization:'Basic Zml4dHVyZTpmaXh0dXJlLW9ubHk=','Accept-Encoding':'gzip'},signal:AbortSignal.timeout(5000)});const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.length>1048576)throw new Error('Fixture forwarded bytes exceed boundary');let body:any;try{body=JSON.parse(new TextDecoder().decode(bytes))}catch{}const marker=body?.error==='query_response_boundary';const observedLength=response.headers.get('x-vp6-observed-length'),observedCount=response.headers.get('x-vp6-observed-length-count');const pass=(response.status!==200||observedLength===String(c.body.length)&&observedCount==='1')&&c.expected.includes(response.status)&&(response.status!==200||bytes.length===c.body.length)&&originRequests.filter(o=>o.id===c.id).every(o=>o.acceptEncodingIdentity);results.push({id:c.id,status:response.status,bytes:bytes.length,observedLength,observedCount,rawContentLengthFields:c.headers.filter(h=>h.toLowerCase().startsWith('content-length:')),expected:c.expected,aclMarker:marker,classification:response.status===200?(c.normalizationInformational?'accepted-native-normalized-bounded':'accepted-bounded'):marker?'response-acl':'native-http-rejected-without-acl-marker',normalizationInformational:c.normalizationInformational??false,pass});}}
|
|
catch(error){primaryFailure=error instanceof Error?error.message:'fixture failed';}finally{if(id){const check=run(['docker','inspect',id]);if(check.exitCode===0){const c=JSON.parse(new TextDecoder().decode(check.stdout))[0];if(c.Id!==id||c.Image!==image||c.Config.Labels['mtuci.claim']!==claim)cleanup='ownership-mismatch';else{const log=run(['docker','logs',id]);await writeFile(resolve(out,'haproxy.private.log'),Buffer.concat([log.stdout,log.stderr]),{flag:'wx',mode:0o600});const stop=run(['docker','stop','--time','3',id]);cleanup=stop.exitCode===0?'stopped':'stop-failed';}}else cleanup='already-absent';}server.close();}
|
|
const receipt={checkedAt:new Date().toISOString(),configSHA256:new Bun.CryptoHasher('sha256').update(source).digest('hex'),scope:'native HAProxy recognized Content-Length boundary; temporary synthetic raw HTTP upstream, no application mutation',image,results,originRequests,primaryFailure,cleanup,passed:!primaryFailure&&results.length===cases.length&&results.every(r=>r.pass)&&cleanup==='stopped'};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(out,'RESULT.json'),...receipt}));if(!receipt.passed)process.exitCode=1;
|