From 65018015a0526fd2c9b9adc4244e8c349dcdd39c Mon Sep 17 00:00:00 2001 From: daikaginza Date: Mon, 21 Sep 2026 09:43:39 +0700 Subject: [PATCH 1/5] fix(server): stop track backfill from spending the OpenSky credit budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `/api/opensky-track` costs 4 OpenSky credits per call against the same ~4000/day account as `/api/opensky`, but participated in none of that proxy's credit governor. Its 60-second per-icao cache bounds memory, not spend: `icao24` is six hex digits, so a caller that varies it produces a fresh key and a fresh upstream call every time. Both track-backfill routes now carry an always-on 30/min per-client limiter (90 global) — the band `/api/geocode` and `/api/regional-brief` already use, and far above the real demand, which is one backfill per aircraft the operator selects. `/api/opensky-track` additionally reads the 429 cooldown `/api/opensky` already maintains. While the account is out of budget it serves any cached track and otherwise answers 429 with the remaining cooldown, instead of minting a token and spending four more credits. adsb.lol is free and unmetered, so only the limiter applies there. --- CHANGELOG.md | 11 ++ docs/CURRENT-STATE.md | 1 + scripts/format-scope.json | 3 +- scripts/package-boundaries.json | 2 + server/providers/aircraft/opensky.js | 15 ++ server/providers/aircraft/tracks.js | 69 ++++++++- src/openSkyTrackGovernor.test.mjs | 218 +++++++++++++++++++++++++++ 7 files changed, 313 insertions(+), 6 deletions(-) create mode 100644 src/openSkyTrackGovernor.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 29dbedfaa8..ad4710d1c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +- Stop the track-backfill proxies from spending the OpenSky credit budget the + main flights proxy is protecting. `/api/opensky-track` and + `/api/adsblol/trace` now carry an always-on 30-per-minute per-client limiter + (90 global), and `/api/opensky-track` honours the 429 cooldown that + `/api/opensky` already sets: while the account is out of budget it serves any + cached track and otherwise answers `429` with the remaining cooldown rather + than spending 4 more credits. The existing 60-second per-key cache bounds + memory, not spend — a caller varying `icao24` produced a fresh upstream call + every time. Single-aircraft backfill, which is issued once per selected + contact, is unaffected. + - CCTV cameras whose bearing is a guess now say so. Packs mark bearings derived from a hash of the camera id as `headingConfidence: 'low'`, but nothing read the flag, so roughly 70% of a default catalog rendered like surveyed facings. The HUD diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index fdb42fc0c2..d145cb918e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3843,6 +3843,7 @@ are omitted rather than framing the wrong part of the globe. - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation/traffic capacity. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. - Track endpoints: `/api/ais-live/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/opensky-track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/adsblol/trace?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). +- Both track-backfill routes carry an always-on per-client limiter of 30 requests/minute (90 global), because their 60s per-key cache bounds memory rather than spend: a caller varying `icao24`/`hex` produces a fresh key and a fresh upstream call each time. `/api/opensky-track` additionally reads `/api/opensky`'s 429 credit cooldown and, while it is active, serves any cached track and otherwise answers `429` with the remaining cooldown instead of spending 4 more credits against an account that is already out of budget. - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. - `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index eee546dd54..69248a6927 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -839,5 +839,6 @@ "src/ui/imageryBoxTool.test.mjs", "src/ui/recentImagery.test.mjs", "src/layers/recentImagery/testDoubles.mjs", - "scripts/qa-recent-imagery.mjs" + "scripts/qa-recent-imagery.mjs", + "src/openSkyTrackGovernor.test.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 189192f10e..1681eeb765 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -36,6 +36,8 @@ "server/providers/live.js", "server/providers/common/http.js", "server/providers/common/query.js", + "server/providers/common/rate-limit.js", + "src/sources/rateLimit.js", "server/providers/aircraft/opensky.js", "server/providers/aircraft/adsb-lol.js", "server/providers/aircraft/enrichment.js", diff --git a/server/providers/aircraft/opensky.js b/server/providers/aircraft/opensky.js index 612d01e11a..a71ec28653 100644 --- a/server/providers/aircraft/opensky.js +++ b/server/providers/aircraft/opensky.js @@ -41,6 +41,21 @@ const OPENSKY_CACHE_MS = 9000; let _openskyTtlMs = OPENSKY_CACHE_MS; /** @type {number} Epoch-ms before which no upstream fetch is attempted. */ let _openskyCooldownUntil = 0; +/** + * Milliseconds left on the 429 cooldown, or 0 when upstream may be called. + * + * Read-only view of lever 2 above, exported so the OTHER routes that spend the + * same daily credit budget can honor it. `/api/opensky-track` costs 4 credits + * per call against this account just as `/states/all` does, so minting one + * while this proxy is cooling would spend budget the account has already been + * told it does not have. Only this module writes the cooldown. + * + * @param {number} [now] - Epoch-ms; injectable so tests need no clock control. + * @returns {number} Remaining cooldown in ms (0 when clear). + */ +export function openSkyCooldownRemainingMs(now = Date.now()) { + return Math.max(0, _openskyCooldownUntil - now); +} /** * Picks the cache TTL from the remaining daily credit budget. * Client polls every 30 s, so tiers ≤30 s cost the same 480 credits/h; the diff --git a/server/providers/aircraft/tracks.js b/server/providers/aircraft/tracks.js index 2c7b78a789..05a5fc826a 100644 --- a/server/providers/aircraft/tracks.js +++ b/server/providers/aircraft/tracks.js @@ -1,12 +1,16 @@ -import { getOpenSkyToken } from './opensky.js'; +import { getOpenSkyToken, openSkyCooldownRemainingMs } from './opensky.js'; import { readCappedResponseText } from '../common/http.js'; +import { makeRateLimiter, clientKey } from '../common/rate-limit.js'; /** * Vite plugin: aircraft track-history backfill proxies (PRD WS-F F1/F2). * * /api/opensky-track?icao24= — OpenSky GET /tracks/all (experimental; * own credit bucket, 4 credits per call on the free tier). OAuth via the * shared coalesced token. 60s per-icao cache; 404/429 forwarded so the - * client can fall back to its accumulated trail silently. + * client can fall back to its accumulated trail silently. Both routes are + * rate-limited per IP, and the OpenSky one additionally stands down while + * `/api/opensky` is in its 429 credit cooldown — the per-icao cache bounds + * memory, not spend, since a different `icao24` is simply a different key. * /api/adsblol/trace?hex= — adsb.lol tar1090 readsb trace * (undocumented but live; no browser CORS, hence this proxy). Up to ~24h * of real history per aircraft. Treat as best-effort; data is ODbL — @@ -16,9 +20,36 @@ export function trackBackfillProxies() { const TRACK_CACHE_MS = 60000; const TRACK_CACHE_MAX = 200; const RESPONSE_CAP_BYTES = 5 * 1024 * 1024; + /** + * Requests/min/IP. The per-icao cache below bounds MEMORY, not request + * volume: every distinct `icao24` is a fresh key, and `icao24` is 6 hex + * digits, so varying it walks straight past the cache into a live call. + * + * Sized against demand, not guessed: a backfill is issued once per aircraft + * the operator SELECTS (`_backfillTrail`, fired from the tracked-contact + * path in the flights, military and vessels layers), and re-selecting the + * same aircraft inside a minute is served from cache. 30/min is a target + * switch every two seconds, sustained — well clear of any human, and the + * same band `/api/geocode` and `/api/regional-brief` already use. + */ + const TRACK_RATE_PER_MIN = 30; + const allow = makeRateLimiter({ + windowMs: 60_000, + max: TRACK_RATE_PER_MIN, + globalMax: TRACK_RATE_PER_MIN * 3, + }); /** @type {Map} */ const cache = new Map(); + /** Shared refusal shape, matching the other rate-limited proxies. */ + function refuse(res, retryAfterSeconds) { + res.writeHead(429, { + 'Content-Type': 'application/json', + 'Retry-After': String(Math.max(1, Math.ceil(retryAfterSeconds))), + }); + res.end(JSON.stringify({ error: 'Rate limit exceeded' })); + } + function cachePut(key, entry) { cache.set(key, entry); if (cache.size > TRACK_CACHE_MAX) { @@ -27,15 +58,27 @@ export function trackBackfillProxies() { } } - async function proxyJson(res, key, upstreamUrl, headers = {}) { + /** + * @param {number} [blockedMs] - When > 0 the upstream must not be called; + * an already-fetched body may still be served (it costs nothing further). + */ + async function proxyJson(res, key, upstreamUrl, headers = {}, blockedMs = 0) { const cached = cache.get(key); - if (cached && Date.now() - cached.at < TRACK_CACHE_MS) { + const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS; + // Serve-stale while the account is cooling, the way `/api/opensky` does: + // a stale trail beats no trail, and replaying a cached body spends no + // credits. + if (cached && (fresh || blockedMs > 0)) { res.statusCode = cached.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.setHeader('Cache-Control', 'no-store'); res.end(cached.body); return; } + if (blockedMs > 0) { + refuse(res, blockedMs / 1000); + return; + } const upstream = await fetch(upstreamUrl, { headers, signal: AbortSignal.timeout(12000), @@ -67,6 +110,10 @@ export function trackBackfillProxies() { function install(middlewares) { middlewares.use('/api/opensky-track', async (req, res) => { try { + if (!allow(clientKey(req))) { + refuse(res, 10); + return; + } const incoming = new URL(req.url || '', 'http://localhost'); const icao24 = String(incoming.searchParams.get('icao24') || '') .trim() @@ -79,12 +126,17 @@ export function trackBackfillProxies() { ); return; } - const token = await getOpenSkyToken(); + // This route spends the SAME daily credit budget as `/api/opensky` + // (4 credits per call), so it honors that proxy's 429 cooldown. While + // the account is cooling, do not mint a token and do not call upstream. + const coolingMs = openSkyCooldownRemainingMs(); + const token = coolingMs > 0 ? null : await getOpenSkyToken(); await proxyJson( res, `osky:${icao24}`, `https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`, token ? { Authorization: `Bearer ${token}` } : {}, + coolingMs, ); } catch (error) { res.statusCode = 502; @@ -95,6 +147,13 @@ export function trackBackfillProxies() { middlewares.use('/api/adsblol/trace', async (req, res) => { try { + // adsb.lol is free and unmetered, so no credit governor applies here — + // the limiter is for the operator's own IP reputation with a community + // service, the same reason `/api/overpass` carries one. + if (!allow(clientKey(req))) { + refuse(res, 10); + return; + } const incoming = new URL(req.url || '', 'http://localhost'); const hex = String(incoming.searchParams.get('hex') || '') .trim() diff --git a/src/openSkyTrackGovernor.test.mjs b/src/openSkyTrackGovernor.test.mjs new file mode 100644 index 0000000000..1852e2d74d --- /dev/null +++ b/src/openSkyTrackGovernor.test.mjs @@ -0,0 +1,218 @@ +// OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard. +// +// `/api/opensky-track` spends 4 OpenSky credits per call against the same +// ~4000/day account as `/api/opensky`. Its 60s per-icao cache bounds MEMORY, +// not spend: `icao24` is six hex digits, so a caller that varies it walks past +// the cache into a live, credit-consuming call every time. +// +// These cases drive the real exported route handlers. No network: `fetch` is +// stubbed per test and restored afterwards, so a case that reaches upstream +// fails loudly rather than making a request. +// +// NOTE: the 429 cooldown is module-scoped state in `opensky.js` and, once set, +// stays set for the life of the process (bounded 30s…30min). The case that +// arms it therefore runs LAST, and nothing after it may assume a clear +// governor. Node runs each test file in its own process, so this is contained. +// +// Run with: npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js'; +import { + openSkyProxy, + openSkyCooldownRemainingMs, +} from '../server/providers/aircraft/opensky.js'; + +/** Collect a plugin's routes into a path → handler map. */ +function install(plugin) { + const routes = new Map(); + const server = { + middlewares: { + use(path, handler) { + routes.set(path, handler); + }, + }, + }; + plugin.configureServer(server); + return routes; +} + +function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) { + return new Promise((resolve, reject) => { + const headers = new Map(); + const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } }; + const res = { + statusCode: 200, + setHeader(name, value) { + headers.set(String(name).toLowerCase(), String(value)); + }, + writeHead(status, hdrs = {}) { + this.statusCode = status; + for (const [name, value] of Object.entries(hdrs)) + headers.set(String(name).toLowerCase(), String(value)); + }, + end(body = '') { + let parsed = null; + try { + parsed = body ? JSON.parse(String(body)) : null; + } catch { + parsed = String(body); + } + resolve({ + statusCode: this.statusCode, + headers: Object.fromEntries(headers), + body: parsed, + }); + }, + }; + Promise.resolve(handler(req, res)).catch(reject); + }); +} + +/** Replace global fetch for one test, restoring it afterwards. */ +function stubFetch(t, impl) { + const original = globalThis.fetch; + globalThis.fetch = impl; + t.after(() => { + globalThis.fetch = original; + }); +} + +/** An OpenSky /tracks/all answer, shaped like the real one. */ +const trackOk = () => + new Response(JSON.stringify({ path: [] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + +test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', async (t) => { + let upstreamCalls = 0; + stubFetch(t, async () => { + upstreamCalls += 1; + return trackOk(); + }); + const track = install(trackBackfillProxies()).get('/api/opensky-track'); + + const allowed = []; + for (let i = 0; i < 30; i += 1) { + // A DIFFERENT icao24 every time: each one is a fresh cache key, which is + // exactly the path the 60s cache cannot see. + const icao24 = (0x400000 + i).toString(16).padStart(6, '0'); + allowed.push(await request(track, { url: `/?icao24=${icao24}` })); + } + assert.equal( + allowed.filter((r) => r.statusCode === 429).length, + 0, + 'the first 30 distinct lookups in a minute are ordinary use', + ); + + const refused = await request(track, { url: '/?icao24=4affff' }); + assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused'); + assert.deepEqual(refused.body, { error: 'Rate limit exceeded' }); + assert.ok( + Number(refused.headers['retry-after']) >= 1, + 'a refusal tells the caller when to come back', + ); + assert.equal( + upstreamCalls, + 30, + 'the refused request never reached OpenSky — the point is the credits', + ); +}); + +test('each client gets its own quota rather than sharing one bucket', async (t) => { + stubFetch(t, async () => trackOk()); + const track = install(trackBackfillProxies()).get('/api/opensky-track'); + + for (let i = 0; i < 30; i += 1) + await request(track, { + url: `/?icao24=${(0x500000 + i).toString(16)}`, + remoteAddress: '198.51.100.7', + }); + const exhausted = await request(track, { + url: '/?icao24=5affff', + remoteAddress: '198.51.100.7', + }); + assert.equal(exhausted.statusCode, 429); + + const neighbour = await request(track, { + url: '/?icao24=5abbbb', + remoteAddress: '198.51.100.8', + }); + assert.notEqual( + neighbour.statusCode, + 429, + 'one noisy host must not take the layer away from everyone else', + ); +}); + +test('adsb.lol traces are metered too, for the operator IP reputation', async (t) => { + stubFetch(t, async () => new Response('{"trace":[]}', { status: 200 })); + const trace = install(trackBackfillProxies()).get('/api/adsblol/trace'); + + for (let i = 0; i < 30; i += 1) + await request(trace, { url: `/?hex=${(0x600000 + i).toString(16)}` }); + const refused = await request(trace, { url: '/?hex=6affff' }); + assert.equal(refused.statusCode, 429); +}); + +test('a malformed icao24 is still rejected before any upstream call', async (t) => { + let upstreamCalls = 0; + stubFetch(t, async () => { + upstreamCalls += 1; + return trackOk(); + }); + const track = install(trackBackfillProxies()).get('/api/opensky-track'); + const bad = await request(track, { url: '/?icao24=nothex' }); + assert.equal(bad.statusCode, 400); + assert.equal(upstreamCalls, 0); +}); + +test('the governor is clear until OpenSky says otherwise', () => { + assert.equal(openSkyCooldownRemainingMs(), 0); + // Injectable clock: a cooldown in the past never reads as active. + assert.equal(openSkyCooldownRemainingMs(Date.now() + 60_000), 0); +}); + +// --- LAST: arming the cooldown is one-way for this process (see file header). +test('while /api/opensky is in its credit cooldown, track backfill stands down', async (t) => { + let trackUpstreamCalls = 0; + stubFetch(t, async (url) => { + if ( + String(url).includes('/api/states/all') || + String(url).includes('states/all') + ) { + // OpenSky refusing for budget: this is what arms the shared governor. + return new Response('{}', { + status: 429, + headers: { 'x-rate-limit-retry-after-seconds': '120' }, + }); + } + trackUpstreamCalls += 1; + return trackOk(); + }); + + const states = install(openSkyProxy()).get('/api/opensky'); + await request(states, { url: '/' }); + assert.ok( + openSkyCooldownRemainingMs() > 0, + 'the 429 from OpenSky arms the shared cooldown', + ); + + const track = install(trackBackfillProxies()).get('/api/opensky-track'); + const refused = await request(track, { url: '/?icao24=7a1b2c' }); + assert.equal( + refused.statusCode, + 429, + 'a cold backfill during the cooldown is refused, not minted', + ); + assert.ok( + Number(refused.headers['retry-after']) > 1, + 'the refusal carries the remaining cooldown, not a fixed guess', + ); + assert.equal( + trackUpstreamCalls, + 0, + 'no credits are spent while the account is already out of budget', + ); +}); From 5668c0c08bcfa8da6e6ec9fc3b056208ba731cf5 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sun, 18 Oct 2026 13:35:24 +0700 Subject: [PATCH 2/5] docs(changelog): move the entry into a changelog.d fragment Main now takes pending entries as changelog.d/-.md files (#787), so the entry leaves CHANGELOG.md for changelog.d/685-opensky-track-credit-governor.md. --- changelog.d/685-opensky-track-credit-governor.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 changelog.d/685-opensky-track-credit-governor.md diff --git a/changelog.d/685-opensky-track-credit-governor.md b/changelog.d/685-opensky-track-credit-governor.md new file mode 100644 index 0000000000..2d0e202554 --- /dev/null +++ b/changelog.d/685-opensky-track-credit-governor.md @@ -0,0 +1,10 @@ +- Stop the track-backfill proxies from spending the OpenSky credit budget the + main flights proxy is protecting. `/api/flights/track` and + `/api/military/track` now carry an always-on 30-per-minute per-client limiter + (90 global), and `/api/flights/track` honours the 429 cooldown that + `/api/flights` already sets: while the account is out of budget it serves any + cached track and otherwise answers `429` with the remaining cooldown rather + than spending 4 more credits. The existing 60-second per-key cache bounds + memory, not spend — a caller varying `icao24` produced a fresh upstream call + every time. Single-aircraft backfill, which is issued once per selected + contact, is unaffected (daikaginza, #685). From a073e6e658aa1753a626befbefb9e422a5b9e387 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Fri, 23 Oct 2026 12:34:46 +0700 Subject: [PATCH 3/5] test(server): pin the /tracks credit bucket the way OpenSky meters it OpenSky keeps /states/*, /tracks/* and /flights/* as three independent credit buckets. The cases pin that a 429 from /tracks/all stands every other icao24 down (review on #685), that a /states/all 429 does not, that the two backfill routes meter separately, and that a limiter refusal names its 60 s window. Four of them fail on the branch as it stands. --- src/openSkyTrackGovernor.test.mjs | 151 +++++++++++++++++++++--------- 1 file changed, 106 insertions(+), 45 deletions(-) diff --git a/src/openSkyTrackGovernor.test.mjs b/src/openSkyTrackGovernor.test.mjs index 29c23bf973..f08f2f8bcb 100644 --- a/src/openSkyTrackGovernor.test.mjs +++ b/src/openSkyTrackGovernor.test.mjs @@ -1,27 +1,26 @@ // OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard. // -// `/api/flights/track` spends 4 OpenSky credits per call against the same -// ~4000/day account as `/api/flights`. Its 60s per-icao cache bounds MEMORY, -// not spend: `icao24` is six hex digits, so a caller that varies it walks past -// the cache into a live, credit-consuming call every time. +// `/api/flights/track` spends 4 OpenSky credits per call from the `/tracks/*` +// bucket. OpenSky keeps three independent daily buckets (`/states/*`, +// `/tracks/*`, `/flights/*`), so this route neither spends nor is blocked by +// the `/states/all` budget `/api/flights` governs. Its 60s per-icao cache +// bounds MEMORY, not spend: `icao24` is six hex digits, so a caller that varies +// it walks past the cache into a live, credit-consuming call every time. // // These cases drive the real exported route handlers. No network: `fetch` is // stubbed per test and restored afterwards, so a case that reaches upstream // fails loudly rather than making a request. // -// NOTE: the 429 cooldown is module-scoped state in `opensky.js` and, once set, -// stays set for the life of the process (bounded 30s…30min). The case that -// arms it therefore runs LAST, and nothing after it may assume a clear -// governor. Node runs each test file in its own process, so this is contained. +// NOTE: the `/states/all` cooldown is module-scoped state in `opensky.js` and, +// once set, stays set for the life of the process (bounded 30s…30min). The case +// that arms it therefore runs LAST. The tracks cooldown lives in each +// `trackBackfillProxies()` instance, so every test gets a clear one. // // Run with: npm test import { test } from 'node:test'; import assert from 'node:assert/strict'; import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js'; -import { - openSkyProxy, - openSkyCooldownRemainingMs, -} from '../server/providers/aircraft/opensky.js'; +import { openSkyProxy } from '../server/providers/aircraft/opensky.js'; /** Collect a plugin's routes into a path → handler map. */ function install(plugin) { @@ -109,9 +108,10 @@ test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', const refused = await request(track, { url: '/?icao24=4affff' }); assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused'); assert.deepEqual(refused.body, { error: 'Rate limit exceeded' }); - assert.ok( - Number(refused.headers['retry-after']) >= 1, - 'a refusal tells the caller when to come back', + assert.equal( + refused.headers['retry-after'], + '60', + 'a refusal names the limiter window, not a shorter guess', ); assert.equal( upstreamCalls, @@ -156,6 +156,89 @@ test('adsb.lol traces are metered too, for the operator IP reputation', async (t assert.equal(refused.statusCode, 429); }); +test('the two routes meter separately, since they spend different upstreams', async (t) => { + stubFetch(t, async (url) => + String(url).includes('adsb.lol') + ? new Response('{"trace":[]}', { status: 200 }) + : trackOk(), + ); + const routes = install(trackBackfillProxies()); + const track = routes.get('/api/flights/track'); + const trace = routes.get('/api/military/track'); + + for (let i = 0; i < 30; i += 1) + await request(track, { url: `/?icao24=${(0x610000 + i).toString(16)}` }); + assert.equal( + (await request(track, { url: '/?icao24=61ffff' })).statusCode, + 429, + ); + const military = await request(trace, { url: '/?hex=62aaaa' }); + assert.equal( + military.statusCode, + 200, + 'spending the OpenSky quota leaves the adsb.lol one untouched', + ); +}); + +test('a 429 from /tracks stands every other icao24 down until it clears', async (t) => { + let upstreamCalls = 0; + stubFetch(t, async () => { + upstreamCalls += 1; + return new Response('{}', { + status: 429, + headers: { 'x-rate-limit-retry-after-seconds': '120' }, + }); + }); + const track = install(trackBackfillProxies()).get('/api/flights/track'); + + const first = await request(track, { url: '/?icao24=71a001' }); + assert.equal(first.statusCode, 429); + assert.equal(upstreamCalls, 1); + + // A DIFFERENT key: the per-icao cache cannot see it, only the cooldown can. + const second = await request(track, { url: '/?icao24=71a002' }); + assert.equal(second.statusCode, 429, 'refused locally'); + assert.equal( + upstreamCalls, + 1, + 'the /tracks bucket is empty, so no further credits are asked for', + ); + const retryAfter = Number(second.headers['retry-after']); + assert.ok( + retryAfter > 60 && retryAfter <= 120, + `the refusal carries OpenSky's remaining cooldown (got ${retryAfter})`, + ); +}); + +test('a cached track is still served while /tracks is cooling', async (t) => { + let cooling = false; + stubFetch(t, async () => + cooling + ? new Response('{}', { + status: 429, + headers: { 'x-rate-limit-retry-after-seconds': '120' }, + }) + : trackOk(), + ); + const track = install(trackBackfillProxies()).get('/api/flights/track'); + + assert.equal( + (await request(track, { url: '/?icao24=72b001' })).statusCode, + 200, + ); + cooling = true; + assert.equal( + (await request(track, { url: '/?icao24=72b002' })).statusCode, + 429, + ); + const replay = await request(track, { url: '/?icao24=72b001' }); + assert.equal( + replay.statusCode, + 200, + 'replaying a fetched body costs nothing', + ); +}); + test('a malformed icao24 is still rejected before any upstream call', async (t) => { let upstreamCalls = 0; stubFetch(t, async () => { @@ -168,21 +251,11 @@ test('a malformed icao24 is still rejected before any upstream call', async (t) assert.equal(upstreamCalls, 0); }); -test('the governor is clear until OpenSky says otherwise', () => { - assert.equal(openSkyCooldownRemainingMs(), 0); - // Injectable clock: a cooldown in the past never reads as active. - assert.equal(openSkyCooldownRemainingMs(Date.now() + 60_000), 0); -}); - -// --- LAST: arming the cooldown is one-way for this process (see file header). -test('while /api/flights is in its credit cooldown, track backfill stands down', async (t) => { +// --- LAST: arming the /states/all cooldown is one-way for this process. +test('a /states/all 429 does not block track backfill: separate OpenSky buckets', async (t) => { let trackUpstreamCalls = 0; stubFetch(t, async (url) => { - if ( - String(url).includes('/api/states/all') || - String(url).includes('states/all') - ) { - // OpenSky refusing for budget: this is what arms the shared governor. + if (String(url).includes('states/all')) { return new Response('{}', { status: 429, headers: { 'x-rate-limit-retry-after-seconds': '120' }, @@ -194,25 +267,13 @@ test('while /api/flights is in its credit cooldown, track backfill stands down', const states = install(openSkyProxy()).get('/api/flights'); await request(states, { url: '/' }); - assert.ok( - openSkyCooldownRemainingMs() > 0, - 'the 429 from OpenSky arms the shared cooldown', - ); const track = install(trackBackfillProxies()).get('/api/flights/track'); - const refused = await request(track, { url: '/?icao24=7a1b2c' }); + const backfill = await request(track, { url: '/?icao24=7a1b2c' }); assert.equal( - refused.statusCode, - 429, - 'a cold backfill during the cooldown is refused, not minted', - ); - assert.ok( - Number(refused.headers['retry-after']) > 1, - 'the refusal carries the remaining cooldown, not a fixed guess', - ); - assert.equal( - trackUpstreamCalls, - 0, - 'no credits are spent while the account is already out of budget', + backfill.statusCode, + 200, + 'the /tracks bucket still has credits, so the trail is fetched', ); + assert.equal(trackUpstreamCalls, 1); }); From bfcf12af49f6469f496d8e3669cd01911a953b32 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Fri, 23 Oct 2026 12:34:46 +0700 Subject: [PATCH 4/5] fix(server): give /tracks its own credit cooldown, armed by its own 429 The branch read the /states/all cooldown from /api/flights and never set one from /tracks/all, which is backwards for an API that meters the two separately: a flights cooldown blocked backfill that still had credits, and a /tracks 429 left every other icao24 free to ask again. tracks.js now keeps a cooldown for the /tracks bucket, armed by a 429 from /tracks/all with OpenSky's retry-after (opensky.js exports its existing parser so both buckets read the header the same way). The two routes get separate limiters, and a limiter refusal sends Retry-After 60, the window, rather than 10. --- .../685-opensky-track-credit-governor.md | 20 ++--- docs/CURRENT-STATE.md | 2 +- server/providers/aircraft/opensky.js | 21 +---- server/providers/aircraft/tracks.js | 79 ++++++++++++------- 4 files changed, 67 insertions(+), 55 deletions(-) diff --git a/changelog.d/685-opensky-track-credit-governor.md b/changelog.d/685-opensky-track-credit-governor.md index 2d0e202554..c40cf1b630 100644 --- a/changelog.d/685-opensky-track-credit-governor.md +++ b/changelog.d/685-opensky-track-credit-governor.md @@ -1,10 +1,10 @@ -- Stop the track-backfill proxies from spending the OpenSky credit budget the - main flights proxy is protecting. `/api/flights/track` and - `/api/military/track` now carry an always-on 30-per-minute per-client limiter - (90 global), and `/api/flights/track` honours the 429 cooldown that - `/api/flights` already sets: while the account is out of budget it serves any - cached track and otherwise answers `429` with the remaining cooldown rather - than spending 4 more credits. The existing 60-second per-key cache bounds - memory, not spend — a caller varying `icao24` produced a fresh upstream call - every time. Single-aircraft backfill, which is issued once per selected - contact, is unaffected (daikaginza, #685). +- Stop the track-backfill proxies from turning a varied `icao24`/`hex` into + unbounded upstream spend. `/api/flights/track` and `/api/military/track` + each carry an always-on 30-per-minute per-client limiter (90 global), and a + `429` from OpenSky `/tracks/all` now starts a cooldown for that credit + bucket: until OpenSky's retry-after passes, any cached track is served and + other lookups are answered `429` locally instead of asking for 4 more + credits. The `/tracks/*` bucket is separate from the `/states/*` one + `/api/flights` spends, so a flights cooldown does not block backfill. The + existing 60-second per-key cache bounds memory, not spend. Single-aircraft + backfill, issued once per selected contact, is unaffected (daikaginza, #685). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ef1a866425..bcfba11acb 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5276,7 +5276,7 @@ pins and share links already supply complete boxes. - `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity. - `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors. - Track endpoints: `/api/vessels/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/flights/track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/military/track?hex=` (60s cache, 5MB cap, ODbL attribution required in UI). -- Both track-backfill routes carry an always-on per-client limiter of 30 requests/minute (90 global), because their 60s per-key cache bounds memory rather than spend: a caller varying `icao24`/`hex` produces a fresh key and a fresh upstream call each time. `/api/flights/track` additionally reads `/api/flights`'s 429 credit cooldown and, while it is active, serves any cached track and otherwise answers `429` with the remaining cooldown instead of spending 4 more credits against an account that is already out of budget. +- Each track-backfill route carries its own always-on per-client limiter of 30 requests/minute (90 global; refusals send `Retry-After: 60`), because their 60s per-key cache bounds memory rather than spend: a caller varying `icao24`/`hex` produces a fresh key and a fresh upstream call each time. A `429` from OpenSky `/tracks/all` starts a cooldown for the `/tracks/*` credit bucket (OpenSky's retry-after, bounded 30 s–30 min): while it runs, `/api/flights/track` serves any cached track and otherwise answers `429` with the remaining cooldown instead of spending 4 more credits. It does not read `/api/flights`'s `/states/*` cooldown, since OpenSky meters the two buckets independently. - Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped. - `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message. diff --git a/server/providers/aircraft/opensky.js b/server/providers/aircraft/opensky.js index 1a8a5cf71b..5e662370ce 100644 --- a/server/providers/aircraft/opensky.js +++ b/server/providers/aircraft/opensky.js @@ -35,11 +35,13 @@ const OPENSKY_STATES_MAX_RESPONSE_BYTES = 8 * 1024 * 1024; /** * Credit-governor cooldown for a 429: OpenSky's retry-after bounded to - * 30 s … 30 min, or 2 min when the header is absent. + * 30 s … 30 min, or 2 min when the header is absent. Exported for the + * `/tracks/*` governor in tracks.js, which reads the same header for its own + * bucket. * @param {Response} upstream Rate-limited response. * @returns {number} Cooldown (ms). */ -function openSkyRateLimitCooldownMs(upstream) { +export function openSkyRateLimitCooldownMs(upstream) { // headers.get() gives null when absent, and Number(null) is 0, not NaN. const header = upstream.headers.get('x-rate-limit-retry-after-seconds'); const retryAfterSec = @@ -120,21 +122,6 @@ let _openskyTtlMs = OPENSKY_CACHE_MS; let _openskyCooldownUntil = 0; let _openskyCooldownStatus = 429; const _openskySnapshotInFlight = new Map(); -/** - * Milliseconds left on the 429 cooldown, or 0 when upstream may be called. - * - * Read-only view of lever 2 above, exported so the OTHER routes that spend the - * same daily credit budget can honor it. `/api/flights/track` costs 4 credits - * per call against this account just as `/states/all` does, so minting one - * while this proxy is cooling would spend budget the account has already been - * told it does not have. Only this module writes the cooldown. - * - * @param {number} [now] - Epoch-ms; injectable so tests need no clock control. - * @returns {number} Remaining cooldown in ms (0 when clear). - */ -export function openSkyCooldownRemainingMs(now = Date.now()) { - return Math.max(0, _openskyCooldownUntil - now); -} /** * Picks the cache TTL from the remaining daily credit budget. * Client polls every 30 s, so tiers ≤30 s cost the same 480 credits/h; the diff --git a/server/providers/aircraft/tracks.js b/server/providers/aircraft/tracks.js index 2c64a00f52..36cfdc92fc 100644 --- a/server/providers/aircraft/tracks.js +++ b/server/providers/aircraft/tracks.js @@ -1,16 +1,17 @@ -import { getOpenSkyToken, openSkyCooldownRemainingMs } from './opensky.js'; +import { getOpenSkyToken, openSkyRateLimitCooldownMs } from './opensky.js'; import { readCappedResponseText } from '../common/http.js'; import { makeRateLimiter, clientKey } from '../common/rate-limit.js'; /** * Vite plugin: aircraft track-history backfill proxies (PRD WS-F F1/F2). * * /api/flights/track?icao24= — OpenSky GET /tracks/all (experimental; - * own credit bucket, 4 credits per call on the free tier). OAuth via the + * 4 credits per call from the `/tracks/*` bucket, which OpenSky keeps + * separate from the `/states/*` one `/api/flights` spends). OAuth via the * shared coalesced token. 60s per-icao cache; 404/429 forwarded so the - * client can fall back to its accumulated trail silently. Both routes are - * rate-limited per IP, and the OpenSky one additionally stands down while - * `/api/flights` is in its 429 credit cooldown — the per-icao cache bounds - * memory, not spend, since a different `icao24` is simply a different key. + * client can fall back to its accumulated trail silently. Each route has + * its own per-IP limiter, and a 429 from /tracks starts a cooldown for that + * bucket — the per-icao cache bounds memory, not spend, since a different + * `icao24` is simply a different key. * /api/military/track?hex= — adsb.lol tar1090 readsb trace * (undocumented but live; no browser CORS, hence this proxy). Up to ~24h * of real history per aircraft. Treat as best-effort; data is ODbL — @@ -28,16 +29,36 @@ export function trackBackfillProxies() { * Sized against demand, not guessed: a backfill is issued once per aircraft * the operator SELECTS (`_backfillTrail`, fired from the tracked-contact * path in the flights, military and vessels layers), and re-selecting the - * same aircraft inside a minute is served from cache. 30/min is a target - * switch every two seconds, sustained — well clear of any human, and the - * same band `/api/geocode` and `/api/regional-brief` already use. + * same aircraft inside a minute is served from cache. The assistant's + * `get_aircraft_track` tool asks once per call, a handful per turn. 30/min + * is a target switch every two seconds, sustained — well clear of either, + * and the same band `/api/geocode` and `/api/regional-brief` already use. + * Each route gets its own limiter: they spend different upstreams. */ const TRACK_RATE_PER_MIN = 30; - const allow = makeRateLimiter({ - windowMs: 60_000, - max: TRACK_RATE_PER_MIN, - globalMax: TRACK_RATE_PER_MIN * 3, - }); + const TRACK_RATE_WINDOW_MS = 60_000; + const trackLimiter = () => + makeRateLimiter({ + windowMs: TRACK_RATE_WINDOW_MS, + max: TRACK_RATE_PER_MIN, + globalMax: TRACK_RATE_PER_MIN * 3, + }); + const allowOpenSky = trackLimiter(); + const allowAdsbLol = trackLimiter(); + /** + * `/tracks/*` credit governor: a 429 from /tracks/all means that bucket is + * empty for every `icao24`, so no upstream call is made until OpenSky's + * retry-after passes. The `/states/*` cooldown in opensky.js is a different + * bucket and does not apply here. + */ + let openSkyTracksCooldownUntil = 0; + const openSkyTracksGovernor = { + remainingMs: () => Math.max(0, openSkyTracksCooldownUntil - Date.now()), + arm(upstream) { + openSkyTracksCooldownUntil = + Date.now() + openSkyRateLimitCooldownMs(upstream); + }, + }; /** @type {Map} */ const cache = new Map(); @@ -59,10 +80,13 @@ export function trackBackfillProxies() { } /** - * @param {number} [blockedMs] - When > 0 the upstream must not be called; - * an already-fetched body may still be served (it costs nothing further). + * @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [governor] + * Credit cooldown for a metered upstream. While it is cooling the upstream + * is not called, though an already-fetched body may still be served (it + * costs nothing further); an upstream 429 arms it. */ - async function proxyJson(res, key, upstreamUrl, headers = {}, blockedMs = 0) { + async function proxyJson(res, key, upstreamUrl, headers = {}, governor) { + const blockedMs = governor?.remainingMs() ?? 0; const cached = cache.get(key); const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS; // Serve-stale while the account is cooling, the way `/api/flights` does: @@ -83,6 +107,7 @@ export function trackBackfillProxies() { headers, signal: AbortSignal.timeout(12000), }); + if (upstream.status === 429) governor?.arm(upstream); const { tooLarge, text } = await readCappedResponseText( upstream, RESPONSE_CAP_BYTES, @@ -110,8 +135,8 @@ export function trackBackfillProxies() { function install(middlewares) { middlewares.use('/api/flights/track', async (req, res) => { try { - if (!allow(clientKey(req))) { - refuse(res, 10); + if (!allowOpenSky(clientKey(req))) { + refuse(res, TRACK_RATE_WINDOW_MS / 1000); return; } const incoming = new URL(req.url || '', 'http://localhost'); @@ -126,17 +151,17 @@ export function trackBackfillProxies() { ); return; } - // This route spends the SAME daily credit budget as `/api/flights` - // (4 credits per call), so it honors that proxy's 429 cooldown. While - // the account is cooling, do not mint a token and do not call upstream. - const coolingMs = openSkyCooldownRemainingMs(); - const token = coolingMs > 0 ? null : await getOpenSkyToken(); + // While the /tracks bucket is cooling, do not mint a token either. + const token = + openSkyTracksGovernor.remainingMs() > 0 + ? null + : await getOpenSkyToken(); await proxyJson( res, `osky:${icao24}`, `https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`, token ? { Authorization: `Bearer ${token}` } : {}, - coolingMs, + openSkyTracksGovernor, ); } catch (error) { res.statusCode = 502; @@ -150,8 +175,8 @@ export function trackBackfillProxies() { // adsb.lol is free and unmetered, so no credit governor applies here — // the limiter is for the operator's own IP reputation with a community // service, the same reason `/api/overpass` carries one. - if (!allow(clientKey(req))) { - refuse(res, 10); + if (!allowAdsbLol(clientKey(req))) { + refuse(res, TRACK_RATE_WINDOW_MS / 1000); return; } const incoming = new URL(req.url || '', 'http://localhost'); From d8a8f1b9176d5bf52947573565e1073d53402bc6 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sat, 24 Oct 2026 13:38:30 +0700 Subject: [PATCH 5/5] test(opensky): fail the retired-route case if it reaches any upstream The stub answered every URL, so the case still passed had the military route started fetching again while still answering 503. It now counts non-OpenSky calls and requires zero. --- src/openSkyTrackGovernor.test.mjs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/openSkyTrackGovernor.test.mjs b/src/openSkyTrackGovernor.test.mjs index 4ced3e33da..41e86c7524 100644 --- a/src/openSkyTrackGovernor.test.mjs +++ b/src/openSkyTrackGovernor.test.mjs @@ -147,7 +147,12 @@ test('each client gets its own quota rather than sharing one bucket', async (t) }); test('the retired military route is not metered, so the OpenSky limiter never reaches it', async (t) => { - stubFetch(t, async () => trackOk()); + let militaryUpstreamCalls = 0; + stubFetch(t, async (url) => { + if (String(url).includes('/tracks/all')) return trackOk(); + militaryUpstreamCalls += 1; + return new Response('{"trace":[]}', { status: 200 }); + }); const routes = install(trackBackfillProxies()); const track = routes.get('/api/flights/track'); const trace = routes.get('/api/military/track'); @@ -166,6 +171,7 @@ test('the retired military route is not metered, so the OpenSky limiter never re }); assert.equal(military.statusCode, 503); } + assert.equal(militaryUpstreamCalls, 0, 'the refusal makes no upstream call'); }); test('a 429 from /tracks stands every other icao24 down until it clears', async (t) => {