gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain5d144817Merge branch 'records-t40' into mainTicketsmain/tests/subscriptions.mjs

15.3 KB

  1. // Ticket #51 contract against an isolated store and a real HTTP fake HyperConductor chat push endpoint.
  2. import { spawn, spawnSync } from 'node:child_process';
  3. import { mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
  4. import { resolve, join } from 'node:path';
  5. import http from 'node:http';
  6. import { createHmac, timingSafeEqual } from 'node:crypto';
  7. const APP = process.env.SUBSCRIPTIONS_APP || resolve(new URL('..', import.meta.url).pathname);
  8. const BIN = join(APP, 'bin/hybriel');
  9. const STORE = join(APP, '.scratch/subscriptions');
  10. const PORT=Number(process.env.SUBSCRIPTIONS_PORT || 8740);
  11. const BASE = 'http://127.0.0.1:'+PORT;
  12. const sleep = ms => new Promise(r => setTimeout(r, ms));
  13. let passed = 0, failed = 0, log = '', server;
  14. function check(label, ok, detail = '') { console.log(`${ok ? 'ok' : 'FAIL'} ${label}${ok ? '' : ': ' + JSON.stringify(detail)}`); ok ? passed++ : failed++; }
  15. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  16. const env = { ...process.env, HL_HOST: '127.0.0.1', HL_PORT_BASE: '8742', TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'), TICKETS_PORT: String(PORT), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE, TICKETS_PUSH_ALLOWED: 'http://127.0.0.1:'+(PORT+1), TICKETS_PUSH_KEY: 'test-only-32-character-storage-key' };
  17. const seed = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env, encoding: 'utf8', timeout: 120000 });
  18. const line = seed.stdout?.split('\n').find(l => l.startsWith('SEED '));
  19. if (!line) throw Error(seed.stdout + seed.stderr);
  20. const K = JSON.parse(line.slice(5));
  21. const wakes = [];
  22. let reject = false;
  23. const delivered=new Set(), lastAccepted=new Map();
  24. let fakeNow=Date.now();
  25. const fake = http.createServer(async (req, res) => {
  26. if(req.method!=='POST'||!/^\/api\/push\/[0-9-]+$/.test(req.url)){res.writeHead(404).end();return;}
  27. let raw = ''; for await (const d of req) raw += d;
  28. const expected = 'sha256=' + createHmac('sha256', 'test-secret').update(raw).digest('hex');
  29. const received=String(req.headers['x-push-signature-256']||'');
  30. const valid=received.length===expected.length && timingSafeEqual(Buffer.from(received),Buffer.from(expected));
  31. if(!valid){res.writeHead(401).end();return;}
  32. let body; try{body=JSON.parse(raw);}catch{res.writeHead(400).end();return;}
  33. if(Object.keys(body).sort().join()!=='delivery,source,text'||body.source!=='tickets'||typeof body.text!=='string'||body.text.length>500||req.headers['x-push-delivery']!==body.delivery){res.writeHead(400).end();return;}
  34. const subscription=body.text.match(/\/api\/subscriptions\/([^/]+)\/delta/)?.[1];
  35. const key=req.url+':'+body.delivery;
  36. let status=202;
  37. if(reject)status=503;
  38. else if(delivered.has(key))status=409;
  39. else if(lastAccepted.has(req.url)&&fakeNow-lastAccepted.get(req.url)<10000)status=429;
  40. else{delivered.add(key);lastAccepted.set(req.url,fakeNow);}
  41. wakes.push({body,valid,subscription,status,path:req.url,raw});res.writeHead(status).end();
  42. });
  43. await new Promise(r => fake.listen(PORT+1, '127.0.0.1', r));
  44. let chatCounter=100;
  45. const api = async (path, method='GET', body, token=K.aliceToken, md=false) => {
  46. if(path==='/api/subscriptions' && method==='POST' && body && body.pushUrl===undefined){body={...body,pushUrl:'http://127.0.0.1:'+(PORT+1)+'/api/push/'+(++chatCounter),secret:'test-secret'};}
  47. const response = await fetch(BASE + path, { method, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json', ...(md ? { accept: 'text/markdown' } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
  48. const text = await response.text(); let data; try { data = JSON.parse(text); } catch {}
  49. return { status: response.status, data, text, headers: response.headers };
  50. };
  51. async function start() {
  52. server = spawn(BIN, ['project.hl'], { cwd: APP, env });
  53. console.log('PROCESS tickets', server.pid); server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  54. for (const end=Date.now()+120000; Date.now()<end;) { try { if ((await api('/api/projects')).status === 200) return; } catch {} await sleep(200); }
  55. throw Error('server did not start: '+log);
  56. }
  57. async function stop() { if (server && server.exitCode === null) { server.kill('SIGTERM'); await Promise.race([new Promise(r=>server.once('exit',r)), sleep(3000)]); if (server.exitCode === null) server.kill('SIGKILL'); } }
  58. const sub = (id, suffix='delta') => '/api/subscriptions/' + id + '/' + suffix;
  59. const comment = (text, token=K.bobToken) => api('/api/projects/alpha/tickets/1/comments', 'POST', {text}, token);
  60. try {
  61. const kat = spawnSync(BIN, ['tests/subscriptions-hmac.hl'], { cwd: APP, env, encoding: 'utf8', timeout:120000 });
  62. check('HMAC known answer', kat.stdout.trim() === 'sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8', kat.stdout+kat.stderr);
  63. await start();
  64. for(const url of ['http://evil.test/api/push/123','http://127.0.0.1:'+(PORT+1)+'.evil/api/push/123','http://127.0.0.1:'+(PORT+1)+'/api/push/12?x=1','http://127.0.0.1:'+(PORT+1)+'/api/push/abc','http://127.0.0.1:'+(PORT+1)+'/api/push/123/other']){
  65. const bad=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:url,secret:'test-secret'});
  66. check('disallowed pushUrl refused without secret echo',bad.status===400 && !bad.text.includes('test-secret'),bad);
  67. }
  68. const noSecret=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:'http://127.0.0.1:'+(PORT+1)+'/api/push/1'});
  69. check('push requires secret',noSecret.status===400 && !noSecret.text.includes('test-secret'));
  70. for(const sig of ['', 'sha256='+'0'.repeat(64)]){
  71. const refused=await fetch('http://127.0.0.1:'+(PORT+1)+'/api/push/1',{method:'POST',headers:{'X-Push-Signature-256':sig},body:'{}'});
  72. check('fake HC refuses missing or wrong signature',refused.status===401);
  73. }
  74. check('no token refused', (await api('/api/subscriptions','GET',undefined,null)).status===401);
  75. check('project key refused', (await api('/api/subscriptions','GET',undefined,K.betaKey)).status===401);
  76. let r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.carol},K.bobToken);
  77. check('nonadmin for another user refused',r.status===403,r);
  78. r=await api('/api/subscriptions','POST',{projects:'all',owner:K.bob}); check('all for another user refused',r.status===403,r);
  79. r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.bob,label:'bob alpha'});
  80. check('admin subscribes another user',r.status===201,r);
  81. const other=r.data?.subscription?.id;
  82. r=await api('/api/subscriptions','POST',{projects:[K.alpha],label:'alice alpha'});
  83. check('create self baseline',r.status===201 && r.data.subscription.cursor>=2,r);
  84. const id=r.data?.subscription?.id;
  85. check('list own and administered', (await api('/api/subscriptions')).data.subscriptions.length===2);
  86. check('other cannot fetch', (await api(sub(id),'GET',undefined,K.bobToken)).status===403);
  87. check('other cannot remove', (await api(sub(id,'remove'),'POST',{},K.bobToken)).status===403);
  88. check('baseline empty', (await api(sub(id))).data.tickets.length===0);
  89. await comment('self only',K.aliceToken); await sleep(250);
  90. check('own events absent', (await api(sub(id)+'?peek=1')).data.tickets.length===0);
  91. check('own events never wake own subscription', wakes.every(w=>w.subscription!==id));
  92. check('comment write succeeds',(await comment('hello alice')).status===201);
  93. await sleep(300);
  94. const first=wakes.filter(w=>w.subscription===id);
  95. check('one signed HC push with fetch command', first.length===1 && first[0].valid && Object.keys(first[0].body).sort().join() === 'delivery,source,text' && first[0].body.source==='tickets' && first[0].body.text.length<=500,first);
  96. check('secret absent from creation and list', !r.text.includes('test-secret') && !(await api('/api/subscriptions')).text.includes('secret'));
  97. check('secret encrypted at rest',!readFileSync(join(STORE,'mpackdb/subscriptions.mpack')).includes(Buffer.from('test-secret')));
  98. await stop(); await start(); await sleep(300);
  99. check('409 duplicate is delivered',wakes.some(w=>w.subscription===id && w.status===409) && (await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakeStatus==='sent');
  100. await comment('second alice'); await sleep(300);
  101. check('no further wakes pending',wakes.filter(w=>w.subscription===id).length===2);
  102. for (const state of ['review','done']) await api('/api/projects/alpha/tickets/1/state','POST',{state},K.aliceToken);
  103. // bob has use role; temporarily promote so he can generate both state events, while self exclusion stays mandatory.
  104. await api('/api/projects/alpha/members','POST',{user:K.bob,role:'edit'});
  105. await api('/api/projects/alpha/tickets/1/state','POST',{state:'open'},K.bobToken);
  106. await api('/api/projects/alpha/tickets/1/state','POST',{state:'review'},K.bobToken);
  107. await api('/api/projects/alpha/tickets/1/state','POST',{state:'done'},K.bobToken);
  108. await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.bob},K.bobToken);
  109. await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.alice},K.bobToken);
  110. await api('/api/projects/alpha/tickets/1/edit','POST',{subject:'edited',summary:'alice summary'},K.bobToken);
  111. await api('/api/projects/alpha/tickets/1/blocked-by','POST',{add:'beta#1'},K.bobToken);
  112. r=await api(sub(id)+'?peek=1'); const t=r.data.tickets[0];
  113. check('merged per ticket',r.data.tickets.length===1 && t.changes.state.from==='done' && t.changes.state.to==='done',r.data);
  114. check('comments and full last snippet',t.changes.comments===2 && t.changes.lastComment==='second alice',t);
  115. check('all relevance markers', ['assigned','own','mention'].every(x=>t.relevance.includes(x)),t);
  116. check('edit, assignment and links', t.changes.titleEdited && t.changes.summaryEdited && t.changes.assignee.to===K.alice && t.changes.links.length===1,t);
  117. check('JSON shape', ['subscription','from','upTo','tickets','more'].every(k=>k in r.data) && t.href===BASE+'/alpha/1' && t.actors.includes(K.bob),r.data);
  118. check('peek keeps pending',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);
  119. r=await api(sub(id),'GET',undefined,K.aliceToken,true);
  120. check('Markdown shape',!r.text.includes('test-secret') && !r.text.includes('secret') && r.status===200 && r.headers.get('content-type').startsWith('text/markdown') && r.text.includes('alpha#1') && r.text.includes('2 comments'),r);
  121. check('fetch drains', (await api(sub(id))).data.tickets.length===0);
  122. check('fetch clears wakePending',!(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);
  123. await comment('after fetch'); await sleep(300);
  124. check('new episode wakes',wakes.filter(w=>w.subscription===id).length===3);
  125. check('429 schedules retry',wakes.some(w=>w.subscription===id&&w.status===429) && (await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakeStatus==='retry');
  126. fakeNow+=10001;
  127. await stop(); await start(); await sleep(400);
  128. const restarted=wakes.filter(w=>w.subscription===id);
  129. check('restart rewakes same delivery',restarted.length===4 && restarted[2].body.delivery===restarted[3].body.delivery,restarted);
  130. await api(sub(id));
  131. // Lots of tickets exercise byte cap and project overflow, all from non-owner bob.
  132. for (let i=0;i<35;i++) await api('/api/projects/alpha/tickets','POST',{subject:'bulk '+i+' '+ '界'.repeat(60),summary:'bulk'},K.bobToken);
  133. r=await api(sub(id)+'?peek=1','GET',undefined,K.aliceToken,true);
  134. check('Markdown UTF-8 cap and summary',Buffer.byteLength(r.text)<=4096 && /… and \d+ more tickets in alpha \(\d+\)/.test(r.text),r.text);
  135. check('JSON retains overflow', (await api(sub(id)+'?peek=1')).data.tickets.length===35);
  136. r=await api(sub(other,'remove'),'POST',{}); check('admin removes',r.status===200,r);
  137. r=await api(sub(id,'remove'),'POST',{}); check('owner removes',r.status===200,r);
  138. check('removed route 404',(await api(sub(id))).status===404);
  139. r=await api('/api/subscriptions','POST',{projects:'all'},K.carolToken); const overview=r.data.subscription.id;
  140. await comment('overview alpha');
  141. await api('/api/projects/beta/tickets/1/comments','POST',{text:'overview beta'},K.bobToken);
  142. r=await api(sub(overview),'GET',undefined,K.carolToken);
  143. check('all-project self overview coalesces both projects',r.data.tickets.length===2 && r.data.tickets.some(t=>t.project==='alpha') && r.data.tickets.some(t=>t.project==='beta'),r.data);
  144. await api(sub(overview,'remove'),'POST',{},K.carolToken);
  145. r=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:''}); const deltaOnly=r.data.subscription.id;
  146. const wakeCount=wakes.length; await comment('no push destination'); await sleep(1200);
  147. check('unset pushUrl keeps delta without push',wakes.length===wakeCount && (await api(sub(deltaOnly))).data.tickets.length===1);
  148. await api(sub(deltaOnly,'remove'),'POST',{});
  149. // Main/standby overlap: only main may send; a disabled standby writes to the same numbered store.
  150. const standby = spawn(BIN, ['project.hl'], {cwd: APP, env: {...env,TICKETS_PORT:'8752',TICKETS_WAKES_DISABLED:'1'}});
  151. console.log('PROCESS standby',standby.pid);
  152. standby.stdout.on('data',d=>log+=d); standby.stderr.on('data',d=>log+=d);
  153. try {
  154. for(const end=Date.now()+120000;Date.now()<end;){try{if((await fetch('http://127.0.0.1:8752/api/projects')).ok)break;}catch{} await sleep(200);}
  155. r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const pending=r.data.subscription.id;
  156. const mark=wakes.length;
  157. await fetch('http://127.0.0.1:8752/api/projects/alpha/tickets/1/comments',{method:'POST',headers:{authorization:'Bearer '+K.bobToken,'content-type':'application/json'},body:JSON.stringify({text:'from standby'})});
  158. await sleep(1600);
  159. check('standby write gets one main wake',wakes.slice(mark).filter(w=>w.subscription===pending).length===1,wakes.slice(mark));
  160. await api(sub(pending,'remove'),'POST',{});
  161. } finally { standby.kill('SIGTERM'); await Promise.race([new Promise(r=>standby.once('exit',r)),sleep(3000)]); if(standby.exitCode===null)standby.kill('SIGKILL'); }
  162. // Create one rejected episode, then exercise actual HTTP retries with test-only due-time advancement.
  163. reject=true;
  164. r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const failing=r.data.subscription.id;
  165. await comment('retry me'); await sleep(300); await stop();
  166. const retryMark=wakes.length;
  167. const retry=spawn(BIN,['tests/subscriptions-retry.hl'],{cwd:APP,env}); console.log('PROCESS retries',retry.pid);
  168. let retryLog=''; retry.stdout.on('data',d=>retryLog+=d);retry.stderr.on('data',d=>retryLog+=d);
  169. let retryTimeout;
  170. const done=await Promise.race([new Promise(r=>retry.once('exit',r)),new Promise(r=>{retryTimeout=setTimeout(()=>r('timeout'),120000);})]);
  171. clearTimeout(retryTimeout);
  172. if(done==='timeout')retry.kill('SIGKILL');
  173. check('failed wake retries then failed after five attempts',done===0 && /FAILED_AFTER 5/.test(retryLog) && wakes.length-retryMark===5,retryLog);
  174. const delays=[...retryLog.matchAll(/RETRY (\d+) DELAY ([\d.]+)/g)].map(m=>Number(m[2]));
  175. check('retry delays 1, 5, 30, 120 minutes',delays.length===4 && delays.every((v,i)=>Math.abs(v-[1,5,30,120][i])<0.02),retryLog);
  176. reject=false; await start(); await sleep(300);
  177. check('restart recovers failed undelivered subscription',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===failing).wakeStatus==='sent');
  178. await api(sub(failing,'remove'),'POST',{});
  179. check('secret absent from logs',!log.includes('test-secret') && !log.includes(env.TICKETS_PUSH_KEY));
  180. } catch(e) { check('suite completed',false,e.stack); }
  181. finally { await stop(); await new Promise(r=>fake.close(r)); writeFileSync(join(STORE,'server.log'),log); }
  182. console.log(`${passed} passed, ${failed} failed`); process.exitCode=failed?1:0;

Branches

Latest commits

  • 5d144817Merge branch 'records-t40' into mainTickets
  • 44ee6f06|||PR records: #43 #45 livemre
  • b8fdeee9Merge branch 'p39-routes' into mainTickets
  • a0187a0a|||PR Remove redundant route-order loopmre
  • 369e4b9cMerge branch 'k40-lists' into mainTickets
  • 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
  • 610d8e8aMerge branch 'records-t39' into mainTickets
  • 32bcdf24|||PR records: GO P39 K40mre
  • 4123c6d1Merge branch 'records-t38' into mainTickets
  • cd3641a1|||PR records: day72 deploy live, tickets closedmre
  • 7d44d852Merge branch 'records-t37' into mainTickets
  • 926f7061|||PR records: merges, D36 deploymre
  • bf58534eMerge branch 'l33-final' into mainTickets
  • 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
  • 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
  • 5822cb3aMerge branch 'o34-clean' into mainTickets
  • 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
  • 14cf96b4Merge branch 'records-t36' into mainTickets
  • 07749fa1|||PR records: day72 + #40 mergedmre
  • ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre