Merge review fixes: DDoS (#153 fixes kept, multi-ingress model dropped), locked rules

This commit is contained in:
Frederic Jung 2026-10-29 07:49:00 +01:00
commit d2f6ac1d5b
No known key found for this signature in database
20 changed files with 343 additions and 228 deletions

155
tests/ddos-floods.test.js Normal file
View file

@ -0,0 +1,155 @@
// Where a flood goes and who pays for it: junk enters at its ingress ports and rides your backbone to the victim.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away.
const remoteTransit = (ev, flip) => {
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'ams'});ACT.launchBB({city:'fra'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1})");
if (flip) ev("const p=S.pops;S.pops={ams:p.ams,fra:p.fra}");
ev("compute()");
};
test('a flood loads the backbone and the victim as on main, whatever order the POPs were built in', () => {
const out = [];
for (const flip of [false, true]) {
const { ev, errors } = load({ seed: 5 });
remoteTransit(ev, flip);
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()");
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.ok(ev('R.nodeLoad.fra') >= 100, "and the victim's router");
assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark');
assert.equal(ev("sfOf(R,'ams')"), 1);
out.push(ev("JSON.stringify([R.load.L,Object.values(R.useT)[0],sfOf(R,'fra'),R.ddos.length])"));
assert.deepEqual(errors, []);
}
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', () => {
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("S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:0}];S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always'");
// New York is struggling on its own (a 10G port for 200G of eyeballs), and has a DDoS-protected customer.
ev("S.pops.nyc.bb.d=200;S.biz.push({id:'sc',type:'scrub',name:'Shield',city:'nyc',bw:1,rate:1000,mood:80,since:0})");
ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:20,start:S.day,until:S.day+3,entry:{k:'t',id:'tf',lab:''}};compute()");
assert.ok(ev("sfOf(R,'nyc')") < 0.85, 'New York is under water anyway');
assert.ok(ev("sfOf(R,'fra')") >= 0.97, 'the victim is fine');
assert.equal(ev('ddosSf(S.ev.ddos)'), ev("sfOf(R,'fra')"));
ev('dayTick()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ev.ddos.sla||[])')), [], 'no SLA payout for a customer in another city');
assert.equal(ev('S.stats.sla||0'), 0);
ev('S.day=S.ev.ddos.until;ddosExpire()');
assert.equal(ev('S.stats.ddosOk||0'), 1, 'held at the victim');
assert.equal(ev('S.stats.ddosLost||0'), 0);
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', () => {
const fs = require('node:fs'), path = require('node:path');
const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'));
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(fx.S || fx))}));UI.started=true;compute()`);
const before = ev('JSON.stringify(S).length');
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.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.
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()");
assert.equal(ev('S.ev.ddos.entries'), undefined);
assert.equal(ev('S.ev.ddos.entry.k'), 'edge');
assert.equal(ev('ddosAll().length'), 14);
assert.match(ev('ddosPanel()'), /Live attack/);
assert.deepEqual(errors, []);
});
test('spicy chaos stretches exactly the attack (or outage) an incident is about, and saves keep it', () => {
const { ev, errors } = load({ seed: 99 });
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.
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");
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);
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'); }
assert.equal(ev('S.links[0].cut'), 52, 'an unrelated cut ending the same day is not stretched');
// The longest spicy attack (7 days, stretched to 11) survives a reload.
ev("S.ev.ddos.until=S.day+11;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.ev.ddos.until-S.day'), 11);
ev("S.ev.ddos.until=S.day+40;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.ev.ddos.until-S.ev.ddos.start'), 11, 'but not longer');
// Outages are found by their ref: a fiber cut stretches its own link only.
ev("S.links.push({id:'M',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:S.day+4});S.links[0].cut=S.day+4;S.links[0].trench='T';addInc({type:'cut',ref:'T',until:S.day+4,msg:'x'})");
assert.equal(ev("S.links[0].cut-S.day"), 6);
assert.equal(ev("S.links.find(l=>l.id==='M').cut-S.day"), 4);
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', () => {
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)))");
assert.equal(ev('S.ev.ddos.who'), undefined, 'only names from the list survive a load');
ev('S.ev.ddos.who="<img src=x id=pwn2>";ddosDone(S.ev.ddos)');
assert.equal(dom.window.document.getElementById('pwn'), null);
assert.equal(dom.window.document.getElementById('pwn2'), null, 'and the toast escapes it anyway');
assert.deepEqual(errors, []);
});
test('the China licence arrives in a tenth of the time with quick lead times, and the button says so', () => {
for (const [preset, days] of [['oncall', 45], ['freeze', 5]]) {
const { ev, errors } = load();
ev(`beginGame('C','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9`);
assert.match(ev("tr('link_panels.apply_for_a_license_price_mo_n_days',{price:'$1',mo:'$1',n:leadDays(45)})"), new RegExp(`~${days} days`));
ev('ACT.applyCn()');
assert.equal(ev('S.cnLic.ready-S.day'), days, preset);
assert.deepEqual(errors, []);
}
});
test('Flood Season escalates from ordinary floods to monsters, and empty POPs or no customers do not hold floods for free', () => {
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()");
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.some(g => g >= 1000), 'and some terabit monsters');
// Ten empty POPs: floods still go for Amsterdam, where the customers 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(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']);
// A flood on a city with nobody to serve only holds if the tools soak it up.
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()");
assert.equal(ev("R.cityDem.lon||0"), 0);
assert.ok(ev('ddosSf(S.ev.ddos)') < 0.97, 'unmitigated: not held');
ev("S.scrubs=[{city:'lon',tier:1}];S.scrubMode='always';compute()");
assert.equal(ev('ddosSf(S.ev.ddos)'), 1, 'scrubbed: held');
assert.deepEqual(errors, []);
});

View file

@ -4,8 +4,8 @@ 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 DDoS schedule needs spicy chaos (BGP at 3 a.m.) or gaming customers.
ev("ACT.start({});S.rules=makeRules('bgp');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");
// 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');
@ -209,7 +209,7 @@ test('Flowspec is a router-model capability, and each tool answers a flood', ()
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,entries:[{k:'edge',city:'fra',share:1}]};compute()");
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/);
@ -230,29 +230,22 @@ test('a distributed SYN flood reports actual Flowspec drops and sends only the r
assert.deepEqual(errors, []);
});
test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => {
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;ACT.buildPop({city:'nyc'});S.pops.nyc.rgen=3;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0},{city:'nyc',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.5},{k:'t',id:'tn',city:'nyc',share:0.5}]};compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-12.835)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)')-17.365)<1e-9);
assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 12\.8 Gbps; some ingress routers have no TCAM/);
assert.match(ev('ddosPanel()'), /Scrubbing in Frankfurt: 15\.1 Gbps \/ 100G/);
assert.match(ev('ddosPanel()'), /Scrubbing in New York: 2\.3 Gbps \/ 100G/);
assert.equal(ev('ddosMitigation(S.ev.ddos).flowspec'), ev('ddosReport(S.ev.ddos).flowspec'), 'uncached reports also filter at the ingress instead of the target');
ev('S.transit[1].clean=true;compute()');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-16.61)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.2835)<1e-9);
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 16\.6 Gbps/);
assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 1\.3 Gbps/);
ev("S.pops.fra.rgen=3;S.ixp={fra:1,nyc:1};S.ev.ddos.ixbh=true;compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-14.1185)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-1.24575)<1e-9);
assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 14\.1 Gbps/);
assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 1\.2 Gbps/);
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()");
@ -793,8 +786,8 @@ test('DDoS frequency rises with level and signed gaming customers, with a rollin
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 (with spicy chaos on), then verify each rolling seven-day window.
ev("S.rules=makeRules('bgp');");
// 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))`);
@ -813,11 +806,7 @@ test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood
const { ev, errors } = load();
ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]');
assert.equal(ev('ddosSizeMean()'), 20000);
ev("S.scn={id:'flood',rules:{ddos:true}};S.day=365");
assert.equal(ev('ddosSizeMean()'), 400000);
ev('S.day=730');
assert.equal(ev('ddosSizeMean()'), 600000, 'Flood Season keeps growing after completion');
ev('S.scn=null;R.demand=300000');
ev('R.demand=300000');
assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks');
ev('S.lvl=1');
const early = ev('ddosSizeMax()');
@ -832,39 +821,6 @@ test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood
assert.deepEqual(errors, []);
});
test('distributed attacks follow normal transit and peering traffic across regions', () => {
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.pops[c].bb={d:c==='fra'?100:300}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];S.pni=[{id:'pf',city:'fra',net:'ggl',tier:1}];S.ixp={nyc:1};S.rs={nyc:true};compute();window.__normal=JSON.stringify(R.ingressPorts);ddosAttack()");
const normal = JSON.parse(ev('window.__normal'));
const entries = JSON.parse(ev('JSON.stringify(ddosAll()[0].entries)'));
const total = Object.values(normal).reduce((n,p)=>n+p.traffic,0);
assert.ok(entries.some(p=>p.k==='t') && entries.some(p=>p.k==='p') && entries.some(p=>p.k==='ix'));
assert.deepEqual([...new Set(entries.map(p=>p.city))].sort(), ['fra','nyc']);
for (const en of entries) assert.ok(Math.abs(en.share-normal[en.k+':'+en.id].traffic/total)<1e-9);
assert.ok(Math.abs(entries.reduce((n,en)=>n+en.share,0)-1)<1e-9);
assert.match(ev('ddosPanel()'), /Live attack:/);
assert.doesNotMatch(ev('ddosPanel()'), /ports: .*regions:/, 'keep regional detail out of the live attack card');
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev('S.ev.ddos.entries.length'), entries.length, 'distributed shares survive a save round trip');
assert.deepEqual(errors, []);
});
test('distributed ingress applies upstream scrubbing only to its own port and uses regional centers', () => {
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.pops[c].bb={d:100}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2,clean:true},{id:'tn',city:'nyc',net:'cog',tier:2}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.25},{k:'t',id:'tn',city:'nyc',share:0.75}]};compute()");
assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 775);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 750);
assert.equal(ev('R.useT.tn'), 400, 'the uncleaned flood fills its own ingress port');
assert.ok(ev('R.useT.tf') < 200, 'it cannot spill into the cleaned port');
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 775 Gbps/);
assert.match(ev('ddosPanel()'), /~ 750 Gbps is leaking through/);
ev("S.scrubs.push({city:'nyc',tier:1});compute()");
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 25\.0 Gbps \/ 100G/);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in New York: 750 Gbps \/ 1T/);
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});
@ -875,8 +831,8 @@ test('scrubbing hauls retain their real source on each link when several cities
{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:'spread',city:'ber',vec:'ack',gbps:100,start:0,until:7,
entries:[{k:'t',id:'tp',city:'prg',share:.5},{k:'t',id:'tb',city:'ber',share:.5}]};compute()`);
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');
@ -892,8 +848,8 @@ test('scrubbing hauls retain their real source on each link when several cities
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');
// Reordering ingress and adding an overlapping flood must not change the attribution.
ev("S.ev.ddos.entries.reverse();S.ev.ddosMore=[{...S.ev.ddos,id:'overlap',gbps:20,entries:S.ev.ddos.entries.slice().reverse()}];compute()");
// 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.
@ -914,29 +870,9 @@ function setupScrubLatency(ev) {
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,
entries:[{k:'t',id:'tf',city:'fra',share:0.65},{k:'t',id:'tn',city:'nyc',share:0.35}]};compute()`);
entry:{k:'edge',lab:''}};compute()`);
}
test('distributed ingress does not give a locally protected victim a remote scrubbing latency', () => {
const { ev, errors, dom } = load();
setupScrubLatency(ev);
assert.ok(ev("R.haul.some(q=>q.city==='nyc'&&q.to==='par'&&q.ms>60)"), 'the remote ingress still travels to its scrubbing center');
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'both centers clean the distributed flood');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-20.28)<1e-9);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0);
Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true });
ev("UI.left='noc';UI.leftOpen=true;renderLeft()");
const text = dom.window.document.getElementById('left').textContent;
assert.match(text, /Live attack: Paris/);
assert.match(text, /Scrubbing in Frankfurt: 8\.8 Gbps/);
assert.match(text, /Scrubbing in Paris: 4\.7 Gbps/);
assert.doesNotMatch(text, /Scrubbing traffic hauled over your backbone|\+\d+(\.\d+)? ms/);
// A local center is still nearest when it is full and other centers take overflow.
ev("S.ev.ddos.vec='ack';S.ev.ddos.gbps=300;compute()");
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
assert.deepEqual(errors, []);
});
test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => {
const { ev, errors } = load();
setupScrubLatency(ev);
@ -946,11 +882,11 @@ test('each attack shows only the nearest scrubbing detour using precise one-way
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,entries:[{k:'t',id:'tn',city:'nyc',share:1}]}];compute()");
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});S.ev.ddos.entries=[{k:'edge',city:'par',share:1}];compute()");
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/);
@ -970,17 +906,6 @@ test('a constrained remote haul leaves scrubbing capacity for the next overlappi
assert.deepEqual(errors, []);
});
test('distributed attack statistics survive an ingress outage and corrupted saved shares', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'a',city:'fra',share:0.25},{k:'t',id:'b',city:'nyc',share:0.75}]};S.pops.nyc.down=5;compute()");
assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 1000);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 1000);
ev("S.ev.ddos.entries.push({k:'t',id:'bad',city:'unknown',share:5},{k:'t',id:'bad2',city:'fra',share:-1});S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev('S.ev.ddos.entries.length'), 2);
assert.equal(ev('S.ev.ddos.entries.reduce((n,en)=>n+en.share,0)'), 1);
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()");
@ -1004,7 +929,7 @@ test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec,
assert.deepEqual(errors, []);
});
test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => {
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(`
@ -1020,9 +945,9 @@ test('normal DDoS starts average half an attack per week without gaming and neve
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));
if(row.games===0)assert.equal(row.observed,0.5);
else assert.ok(row.expected>0.5&&row.expected<=7);
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');
@ -1105,18 +1030,19 @@ test('normal attack sizes cover a broad ordinary range and a two-percent large t
assert.deepEqual(errors, []);
});
test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => {
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.demand=1850");
for (const [day,expected] of [[0,[700,1400,2099]],[365,[1400,2800,4199]],[730,[2100,4200,6299]]]) {
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,0.5,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn')})}finally{Math.random=old}JSON.stringify(sizes)"));
assert.deepEqual(actual, expected);
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 spicy chaos or gaming customers; otherwise attacks come as before', () => {
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;})()");
@ -1127,14 +1053,15 @@ test('the busier DDoS schedule needs spicy chaos or gaming customers; otherwise
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.ok(ticks() > 0, 'spicy chaos brings more attacks');
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('bgp');S.biz=[]");
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=[];}})()"), 'spicy attacks come from their own schedule only, never twice');
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=[]");

View file

@ -5,8 +5,8 @@ module.exports = `
for(f of flows){
if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue;
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
const candidates=E.filter(e=>e.used<e.cap&&(f.pin?e.ek===f.pin:e.ok(f.n))&&
(f.pin?base(e):TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity)
const candidates=E.filter(e=>e.used<e.cap&&e.ok(f.n)&&
(TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity)
.sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]);
for(let i=0;i<candidates.length&&f.rem>1e-6;){
let j=i+1;while(j<candidates.length&&(candidates[j].pref==='high')===(candidates[i].pref==='high')&&

View file

@ -38,7 +38,7 @@ test('indexed routing matches the simple allocation loop across network changes'
"S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'",
"S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3",
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
"S.ev.ddos.entries=[{k:'t',id:'transit0',city:'fra',share:.4},{k:'t',id:'transit4',city:'nyc',share:.6}]",
"S.ev.ddosMore=[{id:'x2',city:'nyc',until:S.day+3,gbps:200,vec:'http',entry:{k:'t',id:'transit4'}}]",
"S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}",
"S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2",
"S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'",

View file

@ -0,0 +1,45 @@
// The rules follow from the mode when a save loads: an edited or imported save cannot change them (2.0).
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('a loaded save gets the rules of its mode, whatever its rules say', () => {
const { ev, errors } = load();
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
const base = JSON.parse(ev('JSON.stringify(packSave(S))'));
const loadAs = (mut) => { const s = JSON.parse(JSON.stringify(base)); mut(s); ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}))`); return JSON.parse(ev('JSON.stringify(S.rules)')); };
const preset = (p, o) => JSON.parse(ev(`JSON.stringify(makeRules('${p}'${o ? ',' + JSON.stringify(o) : ''}))`));
// Normal games keep one of the three Normal presets, with nothing changed.
for (const p of ['freeze', 'oncall', 'bgp']) assert.deepEqual(loadAs(s => { s.rules = { preset: p }; }), preset(p));
assert.deepEqual(loadAs(s => { s.rules = { preset: 'oncall', money: 'infinite', gates: 'open', chaos: 'none', lead: 'quick' }; }), preset('oncall'), 'no free money or open gates in On-call');
assert.deepEqual(loadAs(s => { s.rules = { preset: 'freeze', clock: false }; }), preset('freeze'), 'the clock always runs');
assert.deepEqual(loadAs(s => { s.rules = { preset: 'puzzle' }; }), preset('oncall'), 'no puzzle rules (clock off for ever) in a Normal game');
assert.deepEqual(loadAs(s => { s.rules = { preset: 'sandbox' }; }), preset('oncall'), 'no sandbox powers without the sandbox tag');
assert.deepEqual(loadAs(s => { delete s.rules; }), preset('oncall'), 'a save from before 2.0 is On-call');
// Sandboxes keep only their chaos.
assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'sandbox', chaos: 'spicy', clock: false, money: 'normal' }; }), preset('sandbox', { chaos: 'spicy' }));
assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'bgp' }; }), preset('sandbox'));
// Scenarios and the weekly run on On-call.
const scn = { id: 'pac', rules: {}, days: 1095, name: 'x', mods: [] };
for (const r of [{ preset: 'bgp' }, { preset: 'oncall', chaos: 'none' }, { preset: 'sandbox' }, { preset: 'freeze' }])
assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = scn; s.rules = r; }), preset('oncall'), JSON.stringify(r));
assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = { ...scn, id: 'weekly', key: '2026-W44' }; s.rules = { preset: 'freeze' }; }), preset('oncall'), 'the weekly too');
assert.deepEqual(errors, []);
});
test('a save that claims to be a puzzle loads as a Normal On-call game with the clock running', () => {
const { ev, errors } = load();
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
s.mode = 'puzzle'; s.rules = { preset: 'puzzle' };
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}));UI.started=true;compute()`);
assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('pzOn()'), false);
assert.equal(ev("rule('clock')"), true);
ev('for(let i=0;i<3;i++)dayTick()');
assert.equal(ev('S.day'), 3, 'days pass');
ev(`UI.importing=JSON.parse(${JSON.stringify(JSON.stringify(s))});ACT.importGo()`);
assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('rulePreset()'), 'oncall');
assert.deepEqual(errors, []);
});