DDoS rework: tests for the new model, Flood Season and its weekly at level 4, routing reference fix

This commit is contained in:
Frederic Jung 2026-10-31 12:51:15 +01:00
parent 72fb233af7
commit 3e7bbdffad
No known key found for this signature in database
9 changed files with 131 additions and 665 deletions

View file

@ -30,7 +30,7 @@ const TEMPLATES = {
spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] }, spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] },
region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 }, region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 },
event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] }, event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] },
flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 3, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 1 }, flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 4, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 2 },
island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 }, island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 },
cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 }, cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 },
latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 }, latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 },

View file

@ -1 +1 @@
{"v":1,"key":"2026-W44","theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":3,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":24,"big":1}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":169,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":1}} {"v":1,"key":"2026-W44","rev":2,"theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":4,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":32,"big":5}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":198,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":2}}

View file

@ -248,10 +248,10 @@ function compute(){
} }
} }
} }
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
if(DD){let rem=0,jf=0;for(const f of flows)if(f.rem>1e-6)rem+=f.rem;if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} if(DD){let rem=0,jf=0;for(const f of flows)if(f.rem>1e-6)rem+=f.rem;if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;}
ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf), ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf),
lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});} lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});}
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i]; for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i];
if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);} if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);}
// Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did. // Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did.

View file

@ -16,8 +16,7 @@ test('a flood loads the backbone and the victim as on main, whatever order the P
const { ev, errors } = load({ seed: 5 }); const { ev, errors } = load({ seed: 5 });
remoteTransit(ev, flip); remoteTransit(ev, flip);
assert.ok(ev("sfOf(R,'fra')") > 0.95, 'fine before the attack'); assert.ok(ev("sfOf(R,'fra')") > 0.95, 'fine before the attack');
ev("S.day=60;ddosAttack();Object.assign(S.ev.ddos,{city:'fra',vec:'http',gbps:300});compute()"); ev("S.day=60;ddosAttack();Object.assign(S.ev.ddos,{city:'fra',tgt:'bb:fra',vec:'http',gbps:300});compute()");
assert.equal(ev('S.ev.ddos.entries'), undefined, 'no per-port shares');
assert.equal(ev('R.load.L'), 100, 'the junk fills the wave between the transit and the victim'); assert.equal(ev('R.load.L'), 100, 'the junk fills the wave between the transit and the victim');
assert.ok(ev('R.nodeLoad.fra') >= 100, "and the victim's router"); assert.ok(ev('R.nodeLoad.fra') >= 100, "and the victim's router");
assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark'); assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark');
@ -28,16 +27,6 @@ test('a flood loads the backbone and the victim as on main, whatever order the P
assert.equal(out[0], out[1], 'POP build order does not change the outcome'); assert.equal(out[0], out[1], 'POP build order does not change the outcome');
}); });
test('the same flood lands exactly as it does on main (one entry port, the victim\'s router filters it)', () => {
const { ev, errors } = load({ seed: 5 });
remoteTransit(ev, false);
ev("S.pops.fra.rgen=RG.findIndex(r=>r.fs===2);S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'dns',gbps:200,start:S.day,until:S.day+3,entry:{k:'t',id:S.transit[0].id,lab:''},bh:false};compute()");
// Full Flowspec leaves 15%: 30G of junk on the 100G wave, next to Frankfurt's own traffic.
assert.ok(Math.abs(ev('R.ddos[0].leak') - 30) < 1e-9);
assert.ok(Math.abs(ev("R.ef[edgeKey(S.links[0])].net.junk") - 30) < 1e-6);
assert.deepEqual(errors, []);
});
test('an attack is held or lost at its victim; other POPs and their DDoS-protected customers are not charged', () => { test('an attack is held or lost at its victim; other POPs and their DDoS-protected customers are not charged', () => {
const { ev, errors } = load({ seed: 5 }); const { ev, errors } = load({ seed: 5 });
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].bb={d:50};S.pops[c].rgen=3}"); ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].bb={d:50};S.pops[c].rgen=3}");
@ -57,7 +46,7 @@ test('an attack is held or lost at its victim; other POPs and their DDoS-protect
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('fourteen attacks on a big network keep the save small, and 2.0 beta saves with per-port shares still load', () => { test('fourteen attacks on a big network keep the save small, and 2.0 saves with entry ports still load', () => {
const fs = require('node:fs'), path = require('node:path'); const fs = require('node:fs'), path = require('node:path');
const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8')); const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'));
const { ev, errors } = load({ seed: 3 }); const { ev, errors } = load({ seed: 3 });
@ -66,12 +55,12 @@ test('fourteen attacks on a big network keep the save small, and 2.0 beta saves
ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()"); ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()");
assert.equal(ev('ddosAll().length'), 14); assert.equal(ev('ddosAll().length'), 14);
assert.ok(ev('JSON.stringify(S).length') - before < 10000, 'a few hundred bytes per attack'); assert.ok(ev('JSON.stringify(S).length') - before < 10000, 'a few hundred bytes per attack');
// A beta save spread each attack over every port: the shares are dropped and the attack carries on. // Saves from 2.0 and 2.1 brought each attack in on one port: that is dropped, and the attack spreads (#242).
ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:S.ev.ddos.city,lab:'',share:1}));S.ev.ddos.entry={k:'distributed',lab:'Distributed ingress'};S=migrate(JSON.parse(JSON.stringify(S)));compute()"); ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:S.ev.ddos.city,lab:'',share:1}));S.ev.ddos.entry={k:'t',lab:'Distributed ingress'};S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev('S.ev.ddos.entries'), undefined); assert.equal(ev('S.ev.ddos.entries'), undefined);
assert.equal(ev('S.ev.ddos.entry.k'), 'edge'); assert.equal(ev('S.ev.ddos.entry'), undefined);
assert.equal(ev('ddosAll().length'), 14); assert.equal(ev('ddosAll().length'), 14);
assert.match(ev('ddosPanel()'), /Live attack/); assert.match(ev('ddosPanel()'), /🚨/);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
@ -80,7 +69,8 @@ test('spicy chaos stretches exactly the attack (or outage) an incident is about,
ev("beginGame('R','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});S.day=50"); ev("beginGame('R','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});S.day=50");
// A link that happens to be cut until the same day as the next attacks must stay as it is. // A link that happens to be cut until the same day as the next attacks must stay as it is.
ev("S.links[0].cut=S.day+2"); ev("S.links[0].cut=S.day+2");
for (let k = 0; k < 4; k++) ev("const old=Math.random;let n=0;Math.random=()=>n++===3?0:old();ddosAttack();Math.random=old"); // The third draw of an attack is its length: 0 makes it one day.
for (let k = 0; k < 4; k++) ev("const old=Math.random;let n=0;Math.random=()=>n++===2?0:old();ddosAttack();Math.random=old");
const rows = JSON.parse(ev("JSON.stringify(S.inc.filter(i=>i.type==='ddos').map(i=>[i.until,ddosAll(S,false).find(a=>a.id===i.atk).until]))")); const rows = JSON.parse(ev("JSON.stringify(S.inc.filter(i=>i.type==='ddos').map(i=>[i.until,ddosAll(S,false).find(a=>a.id===i.atk).until]))"));
assert.equal(rows.length, 4); assert.equal(rows.length, 4);
for (const [inc, atk] of rows) { assert.equal(atk, inc, 'the attack lasts as long as its incident'); assert.equal(inc, 52, 'one day, stretched by half'); } for (const [inc, atk] of rows) { assert.equal(atk, inc, 'the attack lasts as long as its incident'); assert.equal(inc, 52, 'one day, stretched by half'); }
@ -97,23 +87,6 @@ test('spicy chaos stretches exactly the attack (or outage) an incident is about,
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('BGP at 3 a.m. brings about twice On-call\'s DDoS; gaming customers bring their own, busier schedule', () => {
const picks = {};
for (const preset of ['oncall', 'bgp']) {
const { ev, errors } = load({ seed: 7 });
ev(`beginGame('R','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.day=100;compute()`);
// No daily attacks without gamers, spicy or not.
ev("window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();window.__tick=window.__n;window.__n=0;for(let i=0;i<4000;i++)fireFailure();ddosAttack=real");
assert.equal(ev('window.__tick'), 0, `${preset}: no daily DDoS schedule without gaming customers`);
picks[preset] = ev('window.__n') * ev('chaosMul()');
ev("S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:1,rate:1,mood:80,since:0});window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();ddosAttack=real");
assert.ok(ev('window.__n') > 5, `${preset}: gamers attract attacks on their own schedule`);
assert.deepEqual(errors, []);
}
const ratio = picks.bgp / picks.oncall;
assert.ok(ratio > 1.7 && ratio < 2.3, `about twice the DDoS (${ratio.toFixed(2)}x)`);
});
test('an imported save cannot put HTML in a Flood Season attacker\'s name', () => { test('an imported save cannot put HTML in a Flood Season attacker\'s name', () => {
const { ev, dom, errors } = load({ seed: 5 }); const { ev, dom, errors } = load({ seed: 5 });
ev("ACT.startScn({id:'flood',sure:1});S.day=10;ddosAttack();S.ev.ddos.who='<img src=x id=pwn>';S=migrate(JSON.parse(JSON.stringify(S)))"); ev("ACT.startScn({id:'flood',sure:1});S.day=10;ddosAttack();S.ev.ddos.who='<img src=x id=pwn>';S=migrate(JSON.parse(JSON.stringify(S)))");
@ -135,21 +108,27 @@ test('the China licence arrives in a tenth of the time with quick lead times, an
} }
}); });
test('Flood Season escalates from ordinary floods to monsters, and empty POPs or no customers do not hold floods for free', () => { test('Flood Season escalates from ordinary floods to monsters, and goes for the people you serve', () => {
const { ev, errors } = load({ seed: 5 }); const { ev, errors } = load({ seed: 5 });
ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1});compute()"); ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1});compute()");
const sizes = JSON.parse(ev("const o=[];for(let i=0;i<60;i++){dayTick();for(const a of ddosAll())if(a.start===S.day)o.push(a.gbps);}JSON.stringify(o)")); const sizes = JSON.parse(ev("const o=[];for(let i=0;i<60;i++){dayTick();for(const a of ddosAll())if(a.start===S.day)o.push(a.gbps);}JSON.stringify(o)"));
assert.ok(sizes.some(g => g < 100), `some ordinary floods early on (${sizes.join(' ')})`); assert.ok(sizes.length >= 8 && sizes.some(g => g < 100), `a flood every few days, ordinary ones among them (${sizes.join(' ')})`);
assert.ok(sizes.some(g => g >= 1000), 'and some terabit monsters'); // A third are monsters, and they grow through the year.
// Ten empty POPs: floods still go for Amsterdam, where the customers are. const mix = (day) => JSON.parse(ev(`S.day=${day};__reseed(77);JSON.stringify(Array.from({length:300},()=>ddosSize({tgt:'bb:ams'})))`));
const early = mix(60), late = mix(360), big = (xs) => xs.filter((g) => g >= 800);
assert.ok(big(early).length > 70 && big(early).length < 130, `${big(early).length} of 300 are monsters`);
const med = (xs) => xs.slice().sort((a, b) => a - b)[xs.length >> 1];
assert.ok(med(big(late)) > med(big(early)) * 1.4, 'and they grow');
// Ten empty POPs: floods still go for Amsterdam, where the subscribers are.
ev("for(const c of ['lon','par','fra','mad','mil','vie','waw','sto','osl','hel'])ACT.buildPop({city:c});compute();S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[]"); ev("for(const c of ['lon','par','fra','mad','mil','vie','waw','sto','osl','hel'])ACT.buildPop({city:c});compute();S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[]");
ev("for(let i=0;i<10;i++){S.ddosStarts=[];ddosAttack(false);}"); ev("for(let i=0;i<10;i++){S.ddosStarts=[];ddosAttack(false);}");
assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(ddosAll().map(a=>a.city))])')), ['ams']); assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(ddosAll().map(a=>a.city))])')), ['ams']);
// A flood on a city with nobody to serve only holds if the tools soak it up. // A terabit flood on Amsterdam's subscribers: lost without scrubbing, held with a 10T center.
ev("S.ev.ddosMore=[];S.ev.ddos={id:'e',city:'lon',vec:'http',gbps:500,start:S.day,until:S.day+2,entry:{k:'edge',lab:''}};compute()"); ev("S.ev.ddosMore=[];S.ev.ddos={id:'e',city:'ams',tgt:'bb:ams',vec:'http',gbps:1500,start:S.day,until:S.day+2};compute()");
assert.equal(ev("R.cityDem.lon||0"), 0);
assert.ok(ev('ddosSf(S.ev.ddos)') < 0.97, 'unmitigated: not held'); assert.ok(ev('ddosSf(S.ev.ddos)') < 0.97, 'unmitigated: not held');
ev("S.scrubs=[{city:'lon',tier:1}];S.scrubMode='always';compute()"); ev("S.scrubs=[{city:'ams',tier:2}];S.scrubMode='always';compute()");
assert.equal(ev('ddosSf(S.ev.ddos)'), 1, 'scrubbed: held'); assert.ok(ev('ddosSf(S.ev.ddos)') >= 0.97, 'scrubbed: held');
assert.ok(ev('ddosCol(S.ev.ddos)') < 0.01);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -181,3 +181,97 @@ test('the NOC card fits a phone and the sandbox can send a test flood', () => {
assert.ok(card.querySelectorAll('.btns').length <= 2, 'one suggestion, the rest behind More'); assert.ok(card.querySelectorAll('.btns').length <= 2, 'one suggestion, the rest behind More');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('a DDoS-protection customer under attack who goes down, or is blackholed, is paid out once per attack', () => {
const { ev, errors } = load();
fra(ev);
ev("S.biz.push({id:'p',type:'scrub',name:'Shield',city:'fra',bw:5,rate:900,mood:80,since:0,reqs:[]});compute()");
flood(ev, { tgt: 'p', vec: 'http', gbps: 60, until: ev('S.day') + 3 });
ev('dayTick();dayTick()');
assert.equal(ev('S.stats.sla'), 1, 'once, not every day');
assert.ok(ev("S.biz.find(b=>b.id==='p').mood") < 80, 'and it remembers');
// A second attack on the same customer bills again; one on someone else does not bill it.
flood(ev, { tgt: 'p', vec: 'http', gbps: 60, until: ev('S.day') + 2 });
flood(ev, { tgt: 'g', vec: 'http', gbps: 1, until: ev('S.day') + 2 });
ev('dayTick()');
assert.equal(ev('S.stats.sla'), 2);
assert.deepEqual(errors, []);
});
test('overlapping attacks have their own cards and buttons and end on their own', () => {
const { ev, errors } = load();
fra(ev);
const a = flood(ev, { gbps: 3, until: ev('S.day') + 1 }), b = flood(ev, { tgt: 'd', gbps: 300, until: ev('S.day') + 3 });
ev("UI.left='noc';renderLeft()");
assert.equal(ev("document.querySelectorAll('#left .inc.ddos').length"), 2);
ev(`ACT.rtbh({id:'${b}'})`);
assert.equal(ev(`ddosAll().find(x=>x.id==='${a}').bh`), false, 'blackholing one leaves the other alone');
ev('dayTick()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(ddosAll().map(x=>x.id))')), [b]);
assert.deepEqual(errors, []);
});
test('Hackback 3000 is still a gamble', () => {
const { ev, errors } = load();
fra(ev);
const id = flood(ev, { gbps: 3 });
ev(`const r=Math.random;Math.random=()=>0.1;ACT.hackback({id:'${id}'});Math.random=r`);
assert.equal(ev('ddosAll().length'), 0, 'a lucky strike ends it');
assert.equal(ev('S.stats.hackback'), 1, 'paid for');
const id2 = flood(ev, { gbps: 3 });
ev(`const r=Math.random;Math.random=()=>0.9;ACT.hackback({id:'${id2}'});Math.random=r`);
assert.equal(ev('ddosAll().length'), 1, 'an unlucky one hits someone else');
assert.ok(ev('S.stats.vigilante') >= 1);
assert.deepEqual(errors, []);
});
test('a sacrificial PNI takes all of its peer\'s junk, and a clean pipe scrubs a transit upstream', () => {
const { ev, errors } = load();
fra(ev);
ev("ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.transit[0].clean=true;compute()");
const id = flood(ev, { gbps: 150 });
const ports = JSON.parse(rep(ev, id, 'JSON.stringify(m.portList.map(p=>[p.lab,Math.round(p.off)]))'));
assert.equal(ports.length, 2);
assert.ok(ports.find((p) => /Cogentle/.test(p[0]))[1] < ports.find((p) => !/Cogentle/.test(p[0]))[1] / 5, `the clean pipe took most of its share: ${JSON.stringify(ports)}`);
// A PNI with a network that also comes in over transit: once sacrificial, that network's junk goes only there.
ev("S.pni.push({id:'px',city:'fra',net:'ggl',tier:1,ready:0,sacrif:true});S.ev.ddos=null;S.ev.ddosMore=[];compute()");
const id2 = flood(ev, { gbps: 150 });
assert.ok(rep(ev, id2, "m.portList.some(p=>p.k==='p')"), 'junk arrives on the sacrificial PNI');
assert.deepEqual(errors, []);
});
test('several scrubbing centers share a flood by size, and a far one costs the target latency', () => {
const { ev, errors } = load();
fra(ev);
ev("for(const c of ['ams','nyc'])ACT.buildPop({city:c});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.pending={a:'ams',b:'nyc'};ACT.buildLink({tier:1});closeModal();S.scrubs=[{city:'ams',tier:1},{city:'nyc',tier:0}];S.scrubMode='always';compute()");
const id = flood(ev, { gbps: 550 });
const parts = JSON.parse(rep(ev, id, 'JSON.stringify(m.parts.map(p=>[p.city,Math.round(p.a)]))'));
assert.deepEqual(parts, [['ams', 500], ['nyc', 50]]);
assert.ok(ev("R.haul.find(q=>q.to==='nyc').ms") > ev("R.haul.find(q=>q.to==='ams').ms"), 'across the Atlantic and back');
assert.match(ev("ddosOne(ddosAll()[0])"), /detour via New York/);
assert.deepEqual(errors, []);
});
test('RackNet and TeamSpooked need gaming customers and slip past Flowspec; amplification floods do not', () => {
const { ev, errors } = load();
fra(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(ddosVectors(false).filter(v=>DDOS_VEC[v].gaming))")), []);
assert.ok(ev("ddosVectors(true).includes('racknet')&&ddosVectors(true).includes('teamspooked')"));
assert.equal(ev("DDOS_VEC.racknet.fs||DDOS_VEC.teamspooked.fs||DDOS_VEC.ack.fs"), false);
assert.ok(ev("DDOS_VEC.memcached.fs&&DDOS_VEC.dns.fs"));
// A gaming target draws gaming vectors; a DIA customer never does.
const vecs = JSON.parse(ev("__reseed(4);ddosPickTgt=()=>['d','fra'];const o=[];for(let i=0;i<60;i++){S.ddosStarts=[];const a=ddosAttack(false);if(a)o.push(a.vec);}JSON.stringify(o)"));
assert.ok(vecs.every((v) => !['racknet', 'teamspooked'].includes(v)));
assert.deepEqual(errors, []);
});
test('an attack started during the day is announced and scored after the day\'s routing', () => {
const { ev, errors } = load();
fra(ev);
ev("S.day=60;window.__t=[];const t=toast;toast=(m,k)=>{window.__t.push(m);return t(m,k)};const a=ddosAttack(false);a.until=S.inc.at(-1).until=S.day+3;dayTick()");
assert.equal(ev('ddosAll().length'), 1);
assert.ok(ev('ddosAll()[0].worst') !== undefined, 'scored on its first day');
assert.equal(ev('ddosAll()[0].fresh'), undefined, 'and announced');
assert.ok(ev("window.__t.some(m=>/attack is hitting/.test(m))"));
assert.deepEqual(errors, []);
});

View file

@ -2,16 +2,6 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load, seed } = require('./harness'); const { load, seed } = require('./harness');
test('daily DDoS spawns share one routing calculation and score their first active day', () => {
const { ev, errors } = load();
// The busier daily DDoS schedule comes with gaming customers.
ev("ACT.start({});S.biz=[{type:'game',id:'g',name:'G',city:'fra',bw:1,rate:1,reqs:[]}];S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random");
assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used');
assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually');
assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing');
assert.deepEqual(errors, []);
});
test('page boots to the title screen without errors', () => { test('page boots to the title screen without errors', () => {
const { ev, errors } = load(); const { ev, errors } = load();
assert.equal(ev("document.getElementById('modal').hidden"), false); assert.equal(ev("document.getElementById('modal').hidden"), false);
@ -181,87 +171,6 @@ test('bank: the venture vultures take a share of revenue instead of payments', (
assert.ok(Math.abs(ev('R.cost.revshare') - ev('R.revMo') * 0.1) < 1); assert.ok(Math.abs(ev('R.cost.revshare') - ev('R.revMo') * 0.1) < 1);
}); });
test('Flowspec is a router-model capability, and each tool answers a flood', () => {
const { ev, errors } = load();
// The capability table: full TCAM leaves least junk, basic more, none lets it all through.
assert.ok(ev("FS_RES[2] < FS_RES[1] && FS_RES[1] < FS_RES[0] && FS_RES[0] === 1"), 'full trims more than basic, basic more than none');
assert.ok(ev("RG.some(r=>r.fs===0) && RG.some(r=>r.fs===1) && RG.some(r=>r.fs===2)"), 'models span none/basic/full TCAM');
// Start on the used Rusty Router (rgen 0), which has no Flowspec TCAM.
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()");
assert.equal(ev("fsAt('fra')"), 0, 'the Rusty POP cannot do Flowspec');
const clean = ev('R.served');
assert.ok(clean > 20, 'traffic flows before the attack');
// A 300 Gbps DNS flood on fra: with no TCAM here the junk starves the exit and node.
ev("S.ev.ddos={city:'fra',vec:'dns',gbps:300,until:S.day+3,entry:{k:'t',lab:'x'},bh:false,start:S.day};compute()");
const none = ev('R.served');
assert.ok(none < clean, 'an unfiltered flood displaces real traffic');
// Give this same router Flowspec TCAM (holding its forwarding capacity fixed): the DNS flood is filtered.
const full = ev("RG[0].fs=2;compute();R.served"); ev("RG[0].fs=0");
assert.ok(full > none, 'a Flowspec-capable router recovers a known flood');
// It cannot touch an application-layer HTTP flood, however big the TCAM.
const http = ev("RG[0].fs=2;S.ev.ddos.vec='http';compute();const s=R.served;RG[0].fs=0;s");
assert.ok(Math.abs(http - none) < 1, 'Flowspec is useless against HTTP');
// Scrubbing cleans any vector, regardless of router. A 1T center swallows this 300 Gbps flood whole.
ev("S.ev.ddos.vec='dns';S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always';compute()");
assert.ok(ev('R.served') > none, 'scrubbing recovers real traffic');
assert.deepEqual(errors, []);
});
test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entry:{k:'edge',lab:''}};compute()");
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/);
assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/);
for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) {
ev(`S.pops.fra.rgen=${router};compute()`);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9);
assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps'));
assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G'));
assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/);
}
ev("S.ev.ddos.vec='ack';compute()");
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/);
assert.deepEqual(errors, []);
});
test('Flowspec, upstream cleaning and other edge filters are each accounted for separately', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.pops.fra.rgen=1;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entry:{k:'t',id:'tf'}};compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-18.12)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-12.08)<1e-9);
assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 18\.1 Gbps/);
ev('S.transit[0].clean=true;compute()');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-3.02)<1e-9, 'clean pipe leaves a tenth');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.812)<1e-9);
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 3\.0 Gbps/);
ev("S.ixp={fra:1};S.ev.ddos.ixbh=true;compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-0.604)<1e-9);
assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 0\.6 Gbps/);
assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9'));
assert.deepEqual(errors, []);
});
test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => {
const { ev } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()");
ev("S.ev.ddos={city:'fra',vec:'syn',gbps:200,until:S.day+3,entry:{k:'edge',lab:''},bh:false,start:S.day};ACT.rtbh();compute()");
assert.equal(ev('S.ev.ddos.bh'), true);
assert.equal(ev('S.stats.rtbh'), 1);
assert.ok(ev("R.citySrv.fra") < 1, 'the blackholed city serves nothing');
// HackBack: a forced win ends the attack early.
ev("S.ev.ddos.bh=false;S.ev.ddos.until=S.day+3;const _r=Math.random;Math.random=()=>0.1;ACT.hackback();Math.random=_r");
assert.ok(ev('S.ev.ddos.until') <= ev('S.day'), 'a lucky hack-back ends it');
// A forced miss fines you and marks you a vigilante.
ev("S.ev.ddos={city:'fra',vec:'dns',gbps:50,until:S.day+3,entry:{k:'edge',lab:''},bh:false,start:S.day};const c=S.cash;const _r=Math.random;Math.random=()=>0.9;ACT.hackback();Math.random=_r;window.__fined=c-S.cash");
assert.ok(ev('window.__fined') > 20000, 'a bad hack-back costs the fee plus a fine');
assert.equal(ev('S.stats.vigilante'), 1);
});
test('old saves load, and a stale flat DDoS object is repaired away', () => { test('old saves load, and a stale flat DDoS object is repaired away', () => {
const { ev } = load(); const { ev } = load();
ev("ACT.start({})"); ev("ACT.start({})");
@ -273,57 +182,6 @@ test('old saves load, and a stale flat DDoS object is repaired away', () => {
assert.deepEqual(JSON.parse(kept), ['dns', 80], 'a shaped attack is kept, numbers coerced'); assert.deepEqual(JSON.parse(kept), ['dns', 80], 'a shaped attack is kept, numbers coerced');
}); });
test('scrubbing tiers: capacity caps what a center can clean, and on-demand lags', () => {
const { ev } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.ev.ddos={city:'fra',vec:'dns',gbps:300,until:S.day+3,entry:{k:'t',lab:'x'},bh:false,start:S.day};compute()");
const none = ev('R.served');
// A 100G center cannot swallow a 300 Gbps flood; a 10T center can.
const small = ev("S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';compute();R.served");
const big = ev("S.scrubs[0].tier=2;compute();R.served");
assert.ok(big > small, 'a bigger scrubbing tier cleans more');
assert.ok(big > none, 'the 10T center recovers the flood');
// On-demand does nothing until it engages (SCRUB_DELAY days in).
const notYet = ev("S.scrubMode='ondemand';S.ev.ddos.start=S.day;compute();R.served");
const engaged = ev("S.ev.ddos.start=S.day-SCRUB_DELAY;compute();R.served");
assert.ok(engaged > notYet, 'on-demand scrubbing kicks in only after the delay');
});
test('clean-pipe on the entry transit, a sacrificial PNI, and an IX blackhole each blunt a flood', () => {
const { ev } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1})");
const tid = ev("S.transit[0].id");
ev(`S.ev.ddos={city:'fra',vec:'dns',gbps:400,until:S.day+3,entry:{k:'t',id:'${tid}'},bh:false,start:S.day};compute()`);
const raw = ev('R.served');
// Clean-pipe on the transit the attack enters: the provider scrubs it upstream.
const clean = ev(`S.transit[0].clean=true;compute();const s=R.served;S.transit[0].clean=false;s`);
assert.ok(clean > raw, 'clean-pipe on the entry transit recovers traffic');
// A sacrificial CN PNI contains a flood entering over it (capped at the small port).
ev("S.pni.push({id:'pn1',city:'fra',net:'ctc',tier:1,n:1,site:'a',sacrif:true});S.ev.ddos.entry={k:'p',id:'pn1'}");
const contained = ev("compute();R.served");
const uncontained = ev("S.pni[0].sacrif=false;compute();const s=R.served;S.pni[0].sacrif=true;s");
assert.ok(contained > uncontained, 'a sacrificial PNI contains the flood');
// IX blackhole: ~half the junk gone, victim stays up. Shrink the flood so the drop shows in served.
ev("ACT.buyIx({city:'fra',tier:1,signed:true});S.ev.ddos.entry={k:'t',id:S.transit[0].id};S.ev.ddos.gbps=180");
const before = ev("compute();R.served");
ev("ACT.ixbh()");
assert.equal(ev('S.ev.ddos.ixbh'), true, 'blackhole announced');
assert.equal(ev('S.ev.ddos.bh'), false, 'the customer is not taken dark');
assert.ok(ev("compute();R.served") > before, 'the IX blackhole drops some junk');
});
test('SLA: a protected customer that still goes down costs an SLA credit, once', () => {
const { ev } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.nextFail=1e9;S.nextEvent=1e9");
// A DDoS protection customer, an overwhelming flood, a 100G center that can't cope.
ev("S.scrubs=[{city:'fra',tier:0}];S.biz.push({id:'b1',city:'fra',type:'scrub',bw:5,rate:900,mood:80,since:0,reqs:[]});S.ev.ddos={city:'fra',vec:'dns',gbps:6000,until:S.day+5,entry:{k:'t',lab:'x'},bh:false,start:S.day}");
ev("dayTick()");
assert.equal(ev('S.stats.sla'), 1, 'one SLA breach recorded');
assert.ok(ev('S.biz[0].mood') < 70, 'the SLA breach dented their mood');
// The same attack does not bill twice.
ev("dayTick()");
assert.equal(ev('S.stats.sla'), 1, 'the same attack is only billed once');
});
test('DDoS goal and badges unlock from the right state', () => { test('DDoS goal and badges unlock from the right state', () => {
const { ev } = load(); const { ev } = load();
ev("ACT.start({});S.cash=1e8"); ev("ACT.start({});S.cash=1e8");
@ -404,57 +262,6 @@ test('loans: good terms need good credit, big loans want revenue, and the weird
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('#117 several scrubbing centers: nearest first, spill to the next, and far ones haul the flood over the backbone', () => {
const { ev, errors, dom } = load();
// an old save with one center carries it over
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9");
ev("const o=JSON.parse(JSON.stringify(S));o.scrubAt='fra';o.scrubTier=1;delete o.scrubs;migrate(o);window.__o=o");
assert.deepEqual(JSON.parse(ev("JSON.stringify(window.__o.scrubs)")), [{ city: 'fra', tier: 1 }]);
assert.equal(ev("'scrubAt' in window.__o||'scrubTier' in window.__o"), false);
// New York and London over one transatlantic wave
ev("for(const c of ['nyc','lon']){ACT.buildPop({city:c});}for(const c of ['fra','nyc','lon'])S.pops[c].rgen=3;ACT.launchBB({city:'nyc'});S.pops.nyc.bb.d=150");
ev("ACT.buyTransit({city:'nyc',net:'cog',tier:2});ACT.buyTransit({city:'lon',net:'cog',tier:3});UI.via='grace';UI.route='same';openLinkModal('nyc','lon');ACT.buildLink({tier:3});closeModal()");
const tl = "S.links.find(l=>[l.a,l.b].includes('nyc')).id";
const atk = g => ev(`S.ev.ddos={city:'nyc',vec:'http',gbps:${g},until:S.day+3,entry:{k:'t',lab:'x'},bh:false,start:S.day-5};compute()`);
// build in two cities, one each; the bill adds up
ev("ACT.buildScrub({city:'fra',tier:1});ACT.buildScrub({city:'lon',tier:1});ACT.buildScrub({city:'lon',tier:2})");
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.scrubs.map(x=>x.city+':'+x.tier))")), ['fra:1', 'lon:1'], 'one center per city');
assert.equal(ev('scrubMo()'), 2 * ev('SCRUB_TIERS[1].mo'));
// Frankfurt has no backbone path from New York, so the flood goes to London, across the Atlantic
atk(0); const quiet = ev(`R.load[${tl}]||0`);
atk(600);
assert.deepEqual(JSON.parse(ev("JSON.stringify(R.haul.map(q=>q.to))")), ['lon']);
assert.ok(ev('R.haul[0].h') > 590, 'all of it fits on the 800G wave');
assert.ok(ev('R.haul[0].ms') > 30 && ev('R.haul[0].ms') < 120, `a transatlantic detour (${ev('R.haul[0].ms').toFixed(0)} ms)`);
assert.ok(ev(`R.load[${tl}]`) > quiet + 500, 'the flood fills the transatlantic link');
assert.match(ev('ddosPanel()'), /hauled over your backbone/);
// a protected customer in New York minds the detour
ev("S.biz.push({id:'bs',city:'nyc',type:'scrub',bw:5,rate:900,mood:80,since:0,reqs:['scrubnear']})");
assert.match(ev("bizWhy(S.biz.find(b=>b.id==='bs')).join(' ')"), /hauled to London/);
assert.equal(ev("REQS.scrubnear.ok(S.biz.find(b=>b.id==='bs'))"), false, 'no center in the Americas yet');
// a center in New York cleans it on the spot: nothing crosses the ocean
ev("ACT.buildScrub({city:'nyc',tier:0})");atk(600);
assert.equal(ev("R.haul.filter(q=>q.to==='lon').length"), 1, '100G local, the rest spills to London');
assert.equal(ev("R.haul.some(q=>q.to==='nyc')"), false);
assert.ok(ev("REQS.scrubnear.ok(S.biz.find(b=>b.id==='bs'))"));
ev("S.scrubs.find(x=>x.city==='nyc').tier=1");atk(600);
assert.equal(ev('R.haul.length'), 0, 'a 1T center at home takes it all');
assert.ok(ev(`R.load[${tl}]||0`) < quiet + 50);
// over a thin link only part of it can be hauled; the rest is not scrubbed
ev("ACT.rmScrub({city:'nyc'});ACT.rmScrub({city:'nyc'})");
assert.equal(ev("S.scrubs.some(x=>x.city==='nyc')"), false, 'shut down after confirming');
ev(`S.links.find(l=>l.id===${tl}).tier=1`);atk(600);
assert.ok(ev('R.haul[0].h') < 120 && ev('R.haul[0].h') > 0, `the 100G wave caps the haul (${ev('R.haul[0].h').toFixed(0)})`);
assert.match(ev('ddosPanel()'), /can only haul/);
// the Infra tab says where attacks go from here
ev("ACT.selCity&&ACT.selCity({id:'nyc'});UI.sel={type:'city',id:'nyc'};UI.tab='infra';renderPanel()");
assert.match(dom.window.document.getElementById('panelBody').textContent, /nearest scrubbing center\. From here that is London/);
// closing a POP closes its center
ev("ACT.decomOpen({});ACT.decomToggle({city:'lon'});ACT.decomGo()");
assert.equal(ev("S.scrubs.some(x=>x.city==='lon')"), false);
assert.deepEqual(errors, []);
});
test('notifications: the NOC keeps the last ten minutes, folds repeats and opens what each is about', () => { test('notifications: the NOC keeps the last ten minutes, folds repeats and opens what each is about', () => {
const { ev, errors, dom } = load(); const { ev, errors, dom } = load();
const doc = dom.window.document; const doc = dom.window.document;
@ -642,107 +449,6 @@ test('a custom metric belongs to the city pair, like the presets, and a standby
}); });
test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2");
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('DDOS_VEC.memcached.fs'), true);
assert.equal(ev('DDOS_VEC.ack.fs'), false);
ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()");
const ack = ev('R.served');
assert.match(ev('ddosPanel()'), /ACK flood/);
assert.doesNotMatch(ev('ddosPanel()'), /application layer/);
ev("S.ev.ddos.vec='memcached';compute()");
assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK');
for (const vec of ['memcached', 'ack']) {
ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`);
assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector');
}
assert.deepEqual(errors, []);
});
test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()");
assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9);
assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching'));
assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder');
assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/);
ev('S.transit[0].clean=false;compute()');
assert.equal(ev('R.ddos[0].reaching'), 1842);
assert.equal(ev('R.ddos[0].leak'), 842);
for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) {
ev(setup+';compute()');
assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9'));
assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching'));
}
// On-demand diversion must also work for an attack which began on day zero.
ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()");
assert.equal(ev('R.ddos[0].leak'), 0);
assert.deepEqual(errors, []);
});
test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => {
const { ev, errors, dom } = load();
ev('ACT.start({})');
Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true });
ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc');
const text = () => card().textContent;
assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/);
assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card');
assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/);
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once');
assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/);
assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once');
assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/);
assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/);
assert.match(text(), /✓ Attack fully mitigated/);
ev('S.transit[0].clean=false;compute();renderLeft()');
assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/);
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size');
assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/);
assert.match(text(), /~ 2\.84 Tbps is leaking through/);
assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once');
assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/);
ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()");
assert.match(text(), /✓ Flowspec dropping: 326 Gbps/);
assert.doesNotMatch(text(), /Edge filters dropping/);
assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/);
assert.match(text(), /✓ Attack fully mitigated/);
ev('ACT.rtbh();renderLeft()');
assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/);
assert.equal(text().match(/Blackholed:/g).length, 1);
assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i);
assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card');
assert.deepEqual(errors, []);
});
test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => {
const { ev, errors, dom } = load();
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
assert.equal(ev('R.ddos.length'), 2);
assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000);
assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice');
const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc'));
assert.equal(cards.length, 2);
assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/);
ev("ACT.rtbh({id:'two'})");
assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control');
assert.equal(ev('S.ev.ddosMore[0].bh'), true);
assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it');
ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old");
assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack');
ev('S.day=3;ddosExpire();compute()');
assert.equal(ev('ddosAll().length'), 0);
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once');
ev('ddosExpire()');
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2);
assert.deepEqual(errors, []);
});
test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => { test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))"); ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))");
@ -759,315 +465,3 @@ test('overlapping DDoS saves round trip and legacy attacks migrate safely', () =
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('simultaneous attacks each bill their protected customer only once', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()");
assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities');
ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()');
assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice');
assert.deepEqual(errors, []);
});
test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => {
const { ev, errors } = load();
ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]");
const base = ev('ddosRate()');
assert.equal(base, 0.5);
ev('S.lvl=13');
assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate');
ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1");
const early = ev('ddosRate()');
ev('S.lvl=13');
const level = ev('ddosRate()');
ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))");
const gaming = ev('ddosRate()');
assert.ok(base < early && early < level && level < gaming && gaming <= 7);
ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1");
assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks');
// Force every random spawn opportunity (gamers on board), then verify each rolling seven-day window.
ev("S.biz=[{type:'game',city:'fra'}];");
ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0');
for (let day = 50; day < 66; day++) {
ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`);
assert.ok(ev('S.ddosStarts.length') <= 14);
}
ev('Math.random=window.__oldRandom');
const starts = JSON.parse(ev('JSON.stringify(window.__starts)'));
for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14);
assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window');
ev('for(let i=0;i<30;i++)ddosAttack()');
assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap');
assert.deepEqual(errors, []);
});
test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => {
const { ev, errors } = load();
ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]');
assert.equal(ev('ddosSizeMean()'), 20000);
ev('R.demand=300000');
assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks');
ev('S.lvl=1');
const early = ev('ddosSizeMax()');
ev('S.lvl=13');
const late = ev('ddosSizeMax()');
ev("S.biz=[{type:'game',city:'fra'}]");
assert.ok(early < late && late < ev('ddosSizeMax()'));
// Fixed quantiles show longer durations as both level and gaming exposure rise.
ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom');
assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur'));
assert.equal(ev('ddosAll().at(-1).until-S.day'), 7);
assert.deepEqual(errors, []);
});
test('scrubbing hauls retain their real source on each link when several cities use one center', () => {
const { ev, errors, dom } = load();
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c});
for(const c in S.pops)S.pops[c].rgen=3;
S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
{id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
{id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100},
{id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}];
S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}];
S.scrubs=[{city:'fra',tier:1}];
S.ev.ddos={id:'b',city:'ber',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tb'}};
S.ev.ddosMore=[{id:'p',city:'prg',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tp'}}];compute()`);
const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg)
.filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`));
assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link');
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0);
assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly');
ev("selectLink('fp1');draw(0)");
const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt');
assert.ok(row);
assert.match(row.querySelector('.meta').textContent, /^Prague · /);
assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg');
assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link');
row.querySelector('[data-act="goEgress"]').click();
assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city');
// Swapping the attacks' order and adding an overlapping flood must not change the attribution.
ev("S.ev.ddosMore.push(S.ev.ddos,{...S.ev.ddos,id:'overlap',gbps:20});S.ev.ddos=S.ev.ddosMore.shift();compute()");
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
// When Berlin's direct link fails, its haul really does join Prague's route.
ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()');
assert.ok(ev('R.load.pb')>0);
assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']);
assert.deepEqual(sources('pb').map(x=>x.city), ['ber']);
assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load');
assert.deepEqual(errors, []);
});
function setupScrubLatency(ev) {
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c});
for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1);
S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100},
{id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100},
{id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}];
S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];
S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}];
S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7,
entry:{k:'edge',lab:''}};compute()`);
}
test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => {
const { ev, errors } = load();
setupScrubLatency(ev);
ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()");
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers');
const card = ev('ddosOne(S.ev.ddos)');
assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1);
assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/);
// An overlapping attack has its own victim and nearest center.
ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entry:{k:'edge',lab:''}}];compute()");
assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/);
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/);
// Ignore a failed nearby center and use the live path to Amsterdam.
ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});compute()");
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/);
ev('S.ev.ddos.bh=true;compute()');
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()');
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
assert.deepEqual(errors, []);
});
test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()");
const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))'));
assert.equal(clean.find(m=>m.id==='near').clean, 900);
assert.ok(clean.find(m=>m.id==='far').clean <= 100);
assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000);
for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600);
assert.deepEqual(errors, []);
});
test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()");
assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false);
ev("S.offers=[{type:'game'}]");
assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks');
ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()");
for (const vec of ['racknet','teamspooked']) {
assert.equal(ev(`DDOS_VEC.${vec}.fs`), false);
const sizeMax = ev('ddosSizeMax()/3');
ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`);
assert.equal(ev('ddosAll().at(-1).vec'), vec);
assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax);
assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes');
}
ev("S.biz[0].type='cgame'");
assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors');
ev('S.biz=[]');
assert.equal(ev("ddosVectors().includes('teamspooked')"), false);
assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves');
assert.deepEqual(errors, []);
});
test('gamers\' DDoS starts rise gradually from half an attack per week and never exceed a seven-per-week expected rate', () => {
const { ev, errors } = load();
ev("ACT.start({});S.rules=makeRules('bgp');S.day=50");
const checks = JSON.parse(ev(`
const oldAttack=ddosAttack,oldRandom=Math.random,out=[];
try {
for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){
S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'}));
let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000;
for(let day=0;day<7000;day++)ddosTick();
out.push({level,games,expected:ddosRate(),observed:starts/1000});
}
} finally {ddosAttack=oldAttack;Math.random=oldRandom;}
JSON.stringify(out)
`));
for(const row of checks){
if(row.games===0){assert.equal(row.observed,0,'without gamers attacks stay on the failure schedule');continue;}
assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row));
assert.ok(row.expected>0.5&&row.expected<=7);
}
assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency');
assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency');
assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level');
assert.deepEqual(errors, []);
});
test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => {
const { ev, errors } = load();
ev('ACT.start({})');
const samples = JSON.parse(ev(`
const oldRandom=Math.random,out=[];
try {
for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){
const counts=[];
for(const games of [0,1,2,5,10,20,50,100,1000]){
S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0}));
const vectors=ddosVectors();let sum=0;
for(let i=0;i<vectors.length;i++)for(const [roll,weight] of [[0.49,0.98],[0.99,0.02]]){
S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=demand;
let draw=0;Math.random=()=>draw++===1?(i+0.5)/vectors.length:roll;
ddosAttack(false);sum+=weight*S.ev.ddos.gbps;
}
counts.push({games,mean:sum/vectors.length,rate:ddosRate()});
}
out.push({level,demand,counts});
}
} finally {Math.random=oldRandom;}
JSON.stringify(out)
`));
for(const row of samples){
const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1);
assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row));
assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding');
assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers');
assert.ok(hundred.mean>plain.mean*10 && hundred.mean<plain.mean*11, 'a hundred gamers bring roughly tenfold sizes');
assert.ok(many.mean<=plain.mean*12+0.01, 'high-exposure sizes approach the existing upper balance');
assert.equal(plain.rate,0.5);
assert.ok(first.rate<0.8);
assert.ok(hundred.rate>6 && many.rate<=7);
for(let i=1;i<row.counts.length;i++){
assert.ok(row.counts[i].mean>row.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes');
assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency');
}
}
assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks');
assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average');
assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001);
assert.deepEqual(errors, []);
});
test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => {
const { ev, errors } = load();
ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850');
const distribution = JSON.parse(ev(`
const oldRandom=Math.random,ordinary=[],large=[];let sum=0;
try {
for(let i=0;i<10000;i++){
Math.random=()=>(i+0.5)/10000;
const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g);
}
} finally {Math.random=oldRandom;}
JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)},
large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000})
`));
assert.equal(distribution.ordinary.n, 9800);
assert.equal(distribution.large.n, 200);
assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10);
assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1);
assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9);
assert.ok(distribution.large.min>=356 && distribution.large.max<=535);
assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood');
assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average');
// Verify that real spawns use both bands, not just the standalone sampler.
for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) {
ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`);
assert.equal(ev('S.ev.ddos.vec'), 'syn');
assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum);
}
assert.deepEqual(errors, []);
});
test('Flood Season mixes terabit monsters with ordinary floods, and all of it grows through the year and after', () => {
const { ev, errors } = load();
ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.cityDem={fra:100}");
// One draw: below a third a monster (800 to 3,400G), above it an ordinary flood up to 90% of the city's traffic.
for (const [day,expected] of [[0,[800,3399,2,91]],[365,[1600,6799,4,183]],[730,[2400,10199,6,275]]]) {
ev(`S.day=${day}`);
const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,1/3-1e-9,1/3,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn','fra')})}finally{Math.random=old}JSON.stringify(sizes)"));
assert.deepEqual(actual, expected, `day ${day}`);
}
assert.deepEqual(errors, []);
});
test('the busier DDoS schedule needs gaming customers; otherwise attacks come with the other incidents', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.day=50;S.lvl=13;S.biz=[];S.nextFail=1e9;S.nextEvent=1e9");
const ticks = () => ev("(()=>{const old=Math.random,oa=ddosAttack;let n=0;ddosAttack=()=>{n++};Math.random=()=>0;try{for(let i=0;i<30;i++)ddosTick();}finally{Math.random=old;ddosAttack=oa;}return n;})()");
assert.equal(ticks(), 0, 'no spicy chaos, no gamers: no extra schedule');
// DDoS stays one of the regular incidents instead: some roll of fireFailure() still starts one.
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return true;}return false;}finally{Math.random=old;}})()"), 'fireFailure can start an attack');
ev("S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];S.inc=[]");
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
assert.ok(ticks() > 0, 'gaming customers bring their own attacks');
ev("S.biz=[];S.rules=makeRules('bgp')");
assert.equal(ticks(), 0, 'spicy chaos alone has no daily schedule: it doubles the incident one');
ev("S.rules=makeRules('freeze')");
assert.equal(ticks(), 0, 'Change Freeze has no attacks on either schedule');
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
assert.equal(ticks(), 0, 'not even with gamers');
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'and fireFailure never rolls one');
ev("S.rules=makeRules('oncall');S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'gamers\' attacks come from their own schedule only, never twice');
ev("S.biz=[]");
ev("S.rules=makeRules('oncall')");
// Flood Season, not spicy: one flood at a time, 3 to 7 days apart, however old the scenario is.
ev("ACT.startScn({id:'flood',sure:1});S.biz=[]");
const gaps = JSON.parse(ev("(()=>{const o=[];for(const d of [0,1000])for(const r of [0,0.999]){S.day=d;const old=Math.random;Math.random=()=>r;o.push(floodGap());Math.random=old;}return JSON.stringify(o);})()"));
assert.deepEqual(gaps, [3, 7, 3, 7]);
ev("S.scn.nextDdos=S.day;ddosTick()");
assert.equal(ev('ddosAll().length'), 1);
ev("S.scn.nextDdos=S.day;ddosTick()");
assert.equal(ev('ddosAll().length'), 1, 'the next flood waits for the last one to end');
assert.deepEqual(errors, []);
});

View file

@ -1349,7 +1349,7 @@ test('link redundancy trials distinguish a bridge, a full fallback and a healthy
test('#219 splitting a one-member PNI across both sites splits it when the augment lands', () => { test('#219 splitting a one-member PNI across both sites splits it when the augment lands', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;Object.assign(S.pops.fra,{site2:true,routers:4});S.pni.push({id:'x',net:'nfx',city:'fra',tier:1,ready:0});compute()"); ev("ACT.start({});S.cash=1e8;UI.speed=0;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;Object.assign(S.pops.fra,{site2:true,routers:4});S.pni.push({id:'x',net:'nfx',city:'fra',tier:1,ready:0});compute()");
const cash = ev('S.cash'); const cash = ev('S.cash');
ev("ACT.siteSet({k:'p',id:'x',s:'ab'})"); ev("ACT.siteSet({k:'p',id:'x',s:'ab'})");
assert.equal(ev('S.pni[0].up.n'), 2, 'second member ordered'); assert.equal(ev('S.pni[0].up.n'), 2, 'second member ordered');

View file

@ -355,19 +355,18 @@ test('Flood Season: attacks keep coming, grow, and only count when service held'
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.startScn({id:'flood',sure:1})"); ev("ACT.startScn({id:'flood',sure:1})");
assert.equal(ev("S.scn.id"), 'flood'); assert.equal(ev("S.scn.id"), 'flood');
assert.ok(ev('S.lvl') >= 3, 'starts with bigger gear unlocked'); assert.ok(ev('S.lvl') >= 4, 'starts with bigger gear unlocked: a 10T scrubbing center');
// a few weeks in: several attacks start on their own schedule // a few weeks in: several attacks start on their own schedule
let n = 0; let n = 0;
for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; } for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; }
assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`); assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`);
assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored'); assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored');
// scoring: held only if service stayed at 97%+, and a terabit one only with scrubbing or Flowspec // Scoring: held only if the target got 97% and nobody else lost 1%; a flood you blackhole is sacrificed, not held.
ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,vec:'http',worst:0.99})"); ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;S.stats.ddosSac=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'ams',gbps:30,worst:1,colMax:0.05});ddosDone({city:'ams',gbps:40,worst:0,sac:1})");
assert.equal(ev('S.stats.ddosOk+S.stats.ddosOkBig'), 1, 'held, but no terabit credit without mitigation'); assert.equal(ev('S.stats.ddosOk'), 1);
ev("S.scrubs.push({city:'ams',tier:1});S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})"); assert.equal(ev('S.stats.ddosOkBig'), 1, 'a terabit flood held counts as terabit');
assert.equal(ev('S.stats.ddosOk'), 2); assert.equal(ev('S.stats.ddosLost'), 2, 'the target down, or everyone else hurt');
assert.equal(ev('S.stats.ddosOkBig'), 1); assert.equal(ev('S.stats.ddosSac'), 1);
assert.equal(ev('S.stats.ddosLost'), 1);
const P = JSON.parse(ev('JSON.stringify(scnProg())')); const P = JSON.parse(ev('JSON.stringify(scnProg())'));
assert.match(P.items.map((x) => x.l).join(' '), /Floods held.*Terabit floods held/); assert.match(P.items.map((x) => x.l).join(' '), /Floods held.*Terabit floods held/);
ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;scnTick(S.day)'); ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;scnTick(S.day)');
@ -490,7 +489,7 @@ test('Flood Season keeps attacking and escalating after both success and timeout
ev("S.rules.chaos='spicy'"); ev("S.rules.chaos='spicy'");
const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])')); const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])'));
assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age'); assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age');
const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])')); const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.2;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])'));
assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age'); assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
dom.window.close(); dom.window.close();

View file

@ -88,12 +88,12 @@ test('--check: a week the reference no longer wins is regenerated as a new revis
const now = g.ev(`pzWeekStart('${j.key}')`); const now = g.ev(`pzWeekStart('${j.key}')`);
let r = G.refresh(g, dir, now); let r = G.refresh(g, dir, now);
assert.ok(r.fixed.includes(`${j.key}: new par ${j.par}`), r.fixed.join('; ')); assert.ok(r.fixed.includes(`${j.key}: new par ${j.par}`), r.fixed.join('; '));
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')).rev, undefined, 'a new par keeps the revision'); assert.equal(JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')).rev, j.rev, 'a new par keeps the revision');
// A goal its reference plan never reaches: as if a release changed the world under the week. // A goal its reference plan never reaches: as if a release changed the world under the week.
fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'pops', p: { cs: ['scl'] } }, ref: { ...j.ref, steps: [] } }) + '\n'); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'pops', p: { cs: ['scl'] } }, ref: { ...j.ref, steps: [] } }) + '\n');
r = G.refresh(g, dir, now); r = G.refresh(g, dir, now);
const n = JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')); const n = JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8'));
assert.equal(n.rev, 2, r.fixed.join('; ') + r.bad.join('; ')); assert.equal(n.rev, (j.rev || 1) + 1, r.fixed.join('; ') + r.bad.join('; '));
assert.ok(G.verify(g, n).ok); assert.ok(G.verify(g, n).ok);
// Past weeks keep their files. // Past weeks keep their files.
assert.deepEqual(G.refresh(g, dir, now + 30 * 864e5).fixed, []); assert.deepEqual(G.refresh(g, dir, now + 30 * 864e5).fixed, []);