Files
mtusi2026lab6/student-tests/openobserve-gateway-boundaries.ts
T

19 lines
5.0 KiB
TypeScript

import{mkdir,readFile,writeFile}from'node:fs/promises';import{resolve}from'node:path';
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-parser-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query;const auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64'),base='http://127.0.0.1:28906',now=Date.now()*1000;
const q=(size=1)=>({query:{sql:'SELECT trace_id FROM "messenger" LIMIT 2',start_time:now-300_000_000,end_time:now,size}});const encoded=JSON.stringify(q());const cases=[
{name:"reverse duplicate values size rejected",path:"/api/default/messenger/_values?fields=service_name&start_time="+(now-300_000_000)+"&end_time="+now+"&size=1001&size=1&type=logs",expected:400},
{name:"duplicate JSON query objects rejected",path:"/api/default/_search?type=traces",body:encoded.slice(0,-1)+",\"query\":"+JSON.stringify(q(1001).query)+"}",expected:400},
{name:"fractional inverted subsecond window rejected",path:"/api/default/prometheus/api/v1/query_range?"+new URLSearchParams({query:"vector(1)",start:String(Math.floor(now/1e6)+0.9),end:String(Math.floor(now/1e6)+0.1),step:"1"}),expected:400},
{name:'duplicate values size rejected',path:'/api/default/messenger/_values?fields=service_name&start_time='+(now-300_000_000)+'&end_time='+now+'&size=1&size=1001&type=logs',expected:400},
{name:'encoded duplicate values size rejected',path:'/api/default/messenger/_values?fields=service_name&start_time='+(now-300_000_000)+'&end_time='+now+'&size=1&%73ize=1001&type=logs',expected:400},
{name:'duplicate JSON size rejected',path:'/api/default/_search?type=traces',body:encoded.replace('"size":1','"size":1,"size":1001'),expected:400},
{name:'encoded duplicate JSON size rejected',path:'/api/default/_search?type=traces',body:encoded.replace('"size":1','"size":1,"\\u0073ize":1001'),expected:400},
{name:'fractional window greater than1hour rejected',path:'/api/default/prometheus/api/v1/query_range?'+new URLSearchParams({query:'max(database_observer_up)',start:String(Math.floor(now/1e6)-3600),end:String(Math.floor(now/1e6)+0.5),step:'60'}),expected:400},
{name:'native SQL LIMIT controls row count',path:'/api/default/_search?type=traces',body:encoded,expected:200,maxRows:2}
];const results:any[]=[];
for(const c of cases){const response=await fetch(base+c.path,{method:c.body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:c.body,signal:AbortSignal.timeout(12_000)});const body=await response.text();let rows:number|undefined;try{rows=JSON.parse(body).hits?.length}catch{}results.push({name:c.name,expected:c.expected,actual:response.status,rows,maxRows:c.maxRows,pass:(c.name.includes('duplicate JSON')?[400,422].includes(response.status):response.status===c.expected)&&(c.maxRows===undefined||rows===c.maxRows)});}
async function raw(name:string,headers:string,body:string,expected:number[],tail='',delay=0){const start=performance.now();let socket:any;let tailTimer:ReturnType<typeof setTimeout>|undefined;let result:string='';await new Promise<void>((done,fail)=>{const timeout=setTimeout(()=>{socket?.terminate();fail(new Error('raw parser boundary exceeded14seconds'));},14_000);Bun.connect({hostname:'127.0.0.1',port:28906,socket:{open(s){socket=s;s.write('POST /api/default/_search?type=traces HTTP/1.1\r\nHost: own-query\r\nAuthorization: '+auth+'\r\nContent-Type: application/json\r\nConnection: close\r\n'+headers+'\r\n'+body);if(tail)tailTimer=setTimeout(()=>s.write(tail),delay);},data(s,b){result+=new TextDecoder().decode(b);if(result.length>1_048_576){clearTimeout(timeout);s.terminate();fail(new Error('raw parser response cap'));}},close(){clearTimeout(timeout);if(tailTimer)clearTimeout(tailTimer);done();},error(){clearTimeout(timeout);if(tailTimer)clearTimeout(tailTimer);fail(new Error('raw parser socket failure'));}}}).catch(()=>{clearTimeout(timeout);fail(new Error('raw parser connect failure'));});});const actual=Number(result.match(/^HTTP\/\S+ (\d{3})/)?.[1]??0);results.push({name,expected,actual,elapsedMs:Math.round(performance.now()-start),pass:expected.includes(actual)});}
const chunk=(s:string)=>Buffer.byteLength(s).toString(16)+'\r\n'+s+'\r\n';await raw('complete chunked JSON remains usable','Transfer-Encoding: chunked\r\n',chunk(encoded)+'0\r\n\r\n',[200]);await raw('oversized chunked JSON rejected','Transfer-Encoding: chunked\r\n',chunk(JSON.stringify({...q(),padding:'x'.repeat(150_000)}))+'0\r\n\r\n',[413]);await raw('incomplete body explicitly fails within transport budget','Content-Length: 500\r\n',encoded,[400,408,413,504]);
await raw("delayed chunked oversize rejects beyond inspection timeout","Transfer-Encoding: chunked\r\n",chunk(encoded),[408,413],chunk(" ".repeat(150_000))+"0\r\n\r\n",2200);
await writeFile(resolve(output,'RESULT.json'),JSON.stringify({checkedAt:new Date().toISOString(),base,results,output},null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),results}));if(results.some(r=>!r.pass))process.exitCode=1;