tickets
All repositories: gitoria
15.3 KB
// Ticket #51 contract against an isolated store and a real HTTP fake HyperConductor chat push endpoint.import { spawn, spawnSync } from 'node:child_process';import { mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';import { resolve, join } from 'node:path';import http from 'node:http';import { createHmac, timingSafeEqual } from 'node:crypto';const APP = process.env.SUBSCRIPTIONS_APP || resolve(new URL('..', import.meta.url).pathname);const BIN = join(APP, 'bin/hybriel');const STORE = join(APP, '.scratch/subscriptions');const PORT=Number(process.env.SUBSCRIPTIONS_PORT || 8740);const BASE = 'http://127.0.0.1:'+PORT;const sleep = ms => new Promise(r => setTimeout(r, ms));let passed = 0, failed = 0, log = '', server;function check(label, ok, detail = '') { console.log(`${ok ? 'ok' : 'FAIL'} ${label}${ok ? '' : ': ' + JSON.stringify(detail)}`); ok ? passed++ : failed++; }rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });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' };const seed = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env, encoding: 'utf8', timeout: 120000 });const line = seed.stdout?.split('\n').find(l => l.startsWith('SEED '));if (!line) throw Error(seed.stdout + seed.stderr);const K = JSON.parse(line.slice(5));const wakes = [];let reject = false;const delivered=new Set(), lastAccepted=new Map();let fakeNow=Date.now();const fake = http.createServer(async (req, res) => {if(req.method!=='POST'||!/^\/api\/push\/[0-9-]+$/.test(req.url)){res.writeHead(404).end();return;}let raw = ''; for await (const d of req) raw += d;const expected = 'sha256=' + createHmac('sha256', 'test-secret').update(raw).digest('hex');const received=String(req.headers['x-push-signature-256']||'');const valid=received.length===expected.length && timingSafeEqual(Buffer.from(received),Buffer.from(expected));if(!valid){res.writeHead(401).end();return;}let body; try{body=JSON.parse(raw);}catch{res.writeHead(400).end();return;}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;}const subscription=body.text.match(/\/api\/subscriptions\/([^/]+)\/delta/)?.[1];const key=req.url+':'+body.delivery;let status=202;if(reject)status=503;else if(delivered.has(key))status=409;else if(lastAccepted.has(req.url)&&fakeNow-lastAccepted.get(req.url)<10000)status=429;else{delivered.add(key);lastAccepted.set(req.url,fakeNow);}wakes.push({body,valid,subscription,status,path:req.url,raw});res.writeHead(status).end();});await new Promise(r => fake.listen(PORT+1, '127.0.0.1', r));let chatCounter=100;const api = async (path, method='GET', body, token=K.aliceToken, md=false) => {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'};}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) });const text = await response.text(); let data; try { data = JSON.parse(text); } catch {}return { status: response.status, data, text, headers: response.headers };};async function start() {server = spawn(BIN, ['project.hl'], { cwd: APP, env });console.log('PROCESS tickets', server.pid); server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (const end=Date.now()+120000; Date.now()<end;) { try { if ((await api('/api/projects')).status === 200) return; } catch {} await sleep(200); }throw Error('server did not start: '+log);}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'); } }const sub = (id, suffix='delta') => '/api/subscriptions/' + id + '/' + suffix;const comment = (text, token=K.bobToken) => api('/api/projects/alpha/tickets/1/comments', 'POST', {text}, token);try {const kat = spawnSync(BIN, ['tests/subscriptions-hmac.hl'], { cwd: APP, env, encoding: 'utf8', timeout:120000 });check('HMAC known answer', kat.stdout.trim() === 'sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8', kat.stdout+kat.stderr);await start();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']){const bad=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:url,secret:'test-secret'});check('disallowed pushUrl refused without secret echo',bad.status===400 && !bad.text.includes('test-secret'),bad);}const noSecret=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:'http://127.0.0.1:'+(PORT+1)+'/api/push/1'});check('push requires secret',noSecret.status===400 && !noSecret.text.includes('test-secret'));for(const sig of ['', 'sha256='+'0'.repeat(64)]){const refused=await fetch('http://127.0.0.1:'+(PORT+1)+'/api/push/1',{method:'POST',headers:{'X-Push-Signature-256':sig},body:'{}'});check('fake HC refuses missing or wrong signature',refused.status===401);}check('no token refused', (await api('/api/subscriptions','GET',undefined,null)).status===401);check('project key refused', (await api('/api/subscriptions','GET',undefined,K.betaKey)).status===401);let r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.carol},K.bobToken);check('nonadmin for another user refused',r.status===403,r);r=await api('/api/subscriptions','POST',{projects:'all',owner:K.bob}); check('all for another user refused',r.status===403,r);r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.bob,label:'bob alpha'});check('admin subscribes another user',r.status===201,r);const other=r.data?.subscription?.id;r=await api('/api/subscriptions','POST',{projects:[K.alpha],label:'alice alpha'});check('create self baseline',r.status===201 && r.data.subscription.cursor>=2,r);const id=r.data?.subscription?.id;check('list own and administered', (await api('/api/subscriptions')).data.subscriptions.length===2);check('other cannot fetch', (await api(sub(id),'GET',undefined,K.bobToken)).status===403);check('other cannot remove', (await api(sub(id,'remove'),'POST',{},K.bobToken)).status===403);check('baseline empty', (await api(sub(id))).data.tickets.length===0);await comment('self only',K.aliceToken); await sleep(250);check('own events absent', (await api(sub(id)+'?peek=1')).data.tickets.length===0);check('own events never wake own subscription', wakes.every(w=>w.subscription!==id));check('comment write succeeds',(await comment('hello alice')).status===201);await sleep(300);const first=wakes.filter(w=>w.subscription===id);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);check('secret absent from creation and list', !r.text.includes('test-secret') && !(await api('/api/subscriptions')).text.includes('secret'));check('secret encrypted at rest',!readFileSync(join(STORE,'mpackdb/subscriptions.mpack')).includes(Buffer.from('test-secret')));await stop(); await start(); await sleep(300);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');await comment('second alice'); await sleep(300);check('no further wakes pending',wakes.filter(w=>w.subscription===id).length===2);for (const state of ['review','done']) await api('/api/projects/alpha/tickets/1/state','POST',{state},K.aliceToken);// bob has use role; temporarily promote so he can generate both state events, while self exclusion stays mandatory.await api('/api/projects/alpha/members','POST',{user:K.bob,role:'edit'});await api('/api/projects/alpha/tickets/1/state','POST',{state:'open'},K.bobToken);await api('/api/projects/alpha/tickets/1/state','POST',{state:'review'},K.bobToken);await api('/api/projects/alpha/tickets/1/state','POST',{state:'done'},K.bobToken);await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.bob},K.bobToken);await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.alice},K.bobToken);await api('/api/projects/alpha/tickets/1/edit','POST',{subject:'edited',summary:'alice summary'},K.bobToken);await api('/api/projects/alpha/tickets/1/blocked-by','POST',{add:'beta#1'},K.bobToken);r=await api(sub(id)+'?peek=1'); const t=r.data.tickets[0];check('merged per ticket',r.data.tickets.length===1 && t.changes.state.from==='done' && t.changes.state.to==='done',r.data);check('comments and full last snippet',t.changes.comments===2 && t.changes.lastComment==='second alice',t);check('all relevance markers', ['assigned','own','mention'].every(x=>t.relevance.includes(x)),t);check('edit, assignment and links', t.changes.titleEdited && t.changes.summaryEdited && t.changes.assignee.to===K.alice && t.changes.links.length===1,t);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);check('peek keeps pending',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);r=await api(sub(id),'GET',undefined,K.aliceToken,true);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);check('fetch drains', (await api(sub(id))).data.tickets.length===0);check('fetch clears wakePending',!(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);await comment('after fetch'); await sleep(300);check('new episode wakes',wakes.filter(w=>w.subscription===id).length===3);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');fakeNow+=10001;await stop(); await start(); await sleep(400);const restarted=wakes.filter(w=>w.subscription===id);check('restart rewakes same delivery',restarted.length===4 && restarted[2].body.delivery===restarted[3].body.delivery,restarted);await api(sub(id));// Lots of tickets exercise byte cap and project overflow, all from non-owner bob.for (let i=0;i<35;i++) await api('/api/projects/alpha/tickets','POST',{subject:'bulk '+i+' '+ '界'.repeat(60),summary:'bulk'},K.bobToken);r=await api(sub(id)+'?peek=1','GET',undefined,K.aliceToken,true);check('Markdown UTF-8 cap and summary',Buffer.byteLength(r.text)<=4096 && /… and \d+ more tickets in alpha \(\d+\)/.test(r.text),r.text);check('JSON retains overflow', (await api(sub(id)+'?peek=1')).data.tickets.length===35);r=await api(sub(other,'remove'),'POST',{}); check('admin removes',r.status===200,r);r=await api(sub(id,'remove'),'POST',{}); check('owner removes',r.status===200,r);check('removed route 404',(await api(sub(id))).status===404);r=await api('/api/subscriptions','POST',{projects:'all'},K.carolToken); const overview=r.data.subscription.id;await comment('overview alpha');await api('/api/projects/beta/tickets/1/comments','POST',{text:'overview beta'},K.bobToken);r=await api(sub(overview),'GET',undefined,K.carolToken);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);await api(sub(overview,'remove'),'POST',{},K.carolToken);r=await api('/api/subscriptions','POST',{projects:[K.alpha],pushUrl:''}); const deltaOnly=r.data.subscription.id;const wakeCount=wakes.length; await comment('no push destination'); await sleep(1200);check('unset pushUrl keeps delta without push',wakes.length===wakeCount && (await api(sub(deltaOnly))).data.tickets.length===1);await api(sub(deltaOnly,'remove'),'POST',{});// Main/standby overlap: only main may send; a disabled standby writes to the same numbered store.const standby = spawn(BIN, ['project.hl'], {cwd: APP, env: {...env,TICKETS_PORT:'8752',TICKETS_WAKES_DISABLED:'1'}});console.log('PROCESS standby',standby.pid);standby.stdout.on('data',d=>log+=d); standby.stderr.on('data',d=>log+=d);try {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);}r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const pending=r.data.subscription.id;const mark=wakes.length;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'})});await sleep(1600);check('standby write gets one main wake',wakes.slice(mark).filter(w=>w.subscription===pending).length===1,wakes.slice(mark));await api(sub(pending,'remove'),'POST',{});} finally { standby.kill('SIGTERM'); await Promise.race([new Promise(r=>standby.once('exit',r)),sleep(3000)]); if(standby.exitCode===null)standby.kill('SIGKILL'); }// Create one rejected episode, then exercise actual HTTP retries with test-only due-time advancement.reject=true;r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const failing=r.data.subscription.id;await comment('retry me'); await sleep(300); await stop();const retryMark=wakes.length;const retry=spawn(BIN,['tests/subscriptions-retry.hl'],{cwd:APP,env}); console.log('PROCESS retries',retry.pid);let retryLog=''; retry.stdout.on('data',d=>retryLog+=d);retry.stderr.on('data',d=>retryLog+=d);let retryTimeout;const done=await Promise.race([new Promise(r=>retry.once('exit',r)),new Promise(r=>{retryTimeout=setTimeout(()=>r('timeout'),120000);})]);clearTimeout(retryTimeout);if(done==='timeout')retry.kill('SIGKILL');check('failed wake retries then failed after five attempts',done===0 && /FAILED_AFTER 5/.test(retryLog) && wakes.length-retryMark===5,retryLog);const delays=[...retryLog.matchAll(/RETRY (\d+) DELAY ([\d.]+)/g)].map(m=>Number(m[2]));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);reject=false; await start(); await sleep(300);check('restart recovers failed undelivered subscription',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===failing).wakeStatus==='sent');await api(sub(failing,'remove'),'POST',{});check('secret absent from logs',!log.includes('test-secret') && !log.includes(env.TICKETS_PUSH_KEY));} catch(e) { check('suite completed',false,e.stack); }finally { await stop(); await new Promise(r=>fake.close(r)); writeFileSync(join(STORE,'server.log'),log); }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