From 2e2f7564680d142f3c9701cd0077b3ccc62b089b Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Wed, 4 Nov 2026 22:13:01 -0500 Subject: [PATCH 1/4] fix(places): don't let the browser cache a refused Google answer The Places and Geocoding proxies sent Cache-Control: private, max-age=300 whatever Google answered. A 403 from a key without the Places API, or a geocode REQUEST_DENIED / OVER_QUERY_LIMIT (which Google sends as HTTP 200), was then replayed from the browser cache for five minutes after the key was fixed. Refusals are now no-store. --- docs/CURRENT-STATE.md | 1 + server/providers/places/google.js | 26 +++++++++++++++++--- src/tooling/placeProviders.test.mjs | 38 +++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f1244947d4..ece994cab5 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5996,6 +5996,7 @@ apply to `public/` assets or built-preview serving. - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache. - `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context. - `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution. +- The two Places routes and both geocode routes let the browser keep an answer for five minutes (`private, max-age=300`), but a refusal is `no-store`: a Places error status, or a Geocoding status other than `OK` or `ZERO_RESULTS` (Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200). A denied or exhausted key is not replayed from the browser cache after it is fixed. - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded. - `/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. diff --git a/server/providers/places/google.js b/server/providers/places/google.js index 1ddaa95939..e20efa899d 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -71,6 +71,9 @@ const GEOCODE_UPSTREAM_TIMEOUT_MS = 10_000; const GEOCODE_MAX_RESPONSE_BYTES = 256 * 1024; +/** Geocoding statuses that answer the query; the rest report a failure. */ +const GEOCODE_ANSWER_STATUSES = new Set(['OK', 'ZERO_RESULTS']); + /** Validate a free-text geocoder query before consuming request quota. */ export function validateGeocodeAddress(searchParams) { const address = String(searchParams.get('address') || '').trim(); @@ -199,7 +202,12 @@ export function googlePlacesContextProxy({ res.statusCode = response.ok ? 200 : response.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); - res.setHeader('Cache-Control', 'private, max-age=300'); + // A refusal (bad key, API not enabled, quota) is not kept: the browser + // would replay it for five minutes after the key is fixed. + res.setHeader( + 'Cache-Control', + response.ok ? 'private, max-age=300' : 'no-store', + ); res.end( JSON.stringify({ places, @@ -320,7 +328,12 @@ export function googlePlacesContextProxy({ res.statusCode = response.ok ? 200 : response.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); - res.setHeader('Cache-Control', 'private, max-age=300'); + // A refusal (bad key, API not enabled, quota) is not kept: the browser + // would replay it for five minutes after the key is fixed. + res.setHeader( + 'Cache-Control', + response.ok ? 'private, max-age=300' : 'no-store', + ); res.end( JSON.stringify({ places, @@ -446,7 +459,14 @@ export function googlePlacesContextProxy({ res.statusCode = response.ok ? 200 : response.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); - res.setHeader('Cache-Control', 'private, max-age=300'); + // Geocoding reports a denied key or spent quota as HTTP 200 with a + // status of its own; only an answer is worth keeping. + res.setHeader( + 'Cache-Control', + response.ok && GEOCODE_ANSWER_STATUSES.has(data.status) + ? 'private, max-age=300' + : 'no-store', + ); res.end(JSON.stringify(data)); } catch { // Fixed public text: a transport, URL or runtime message would diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index d533b7fb9a..a6a3457536 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -185,6 +185,44 @@ for (const preview of [false, true]) { }); } +test('a refused Places or Geocoding answer is not kept by the browser', async (t) => { + const plugin = googlePlacesContextProxy({ + resolveApiKey: () => 'fixture-server-key', + }); + const request = install((middlewares) => + plugin.configureServer({ middlewares }), + ); + t.mock.method(globalThis, 'fetch', async () => + Response.json({ error: { message: 'API key not valid' } }, { status: 403 }), + ); + for (const url of [ + ['/api/google/nearby-places', '?lat=30&lon=-97'], + ['/api/google/text-search', '?q=museum&lat=30&lon=-97'], + ]) { + const refused = await request(...url); + assert.equal(refused.statusCode, 403); + assert.equal(refused.headers['cache-control'], 'no-store'); + } + + // Geocoding reports a denied key as HTTP 200 with a status of its own. + let status = 'REQUEST_DENIED'; + t.mock.method(globalThis, 'fetch', async () => + Response.json({ status, results: [] }), + ); + for (const denied of ['REQUEST_DENIED', 'OVER_QUERY_LIMIT']) { + status = denied; + const answer = await request('/api/google/geocode', '?address=Austin'); + assert.equal(answer.statusCode, 200); + assert.equal(answer.body.status, denied); + assert.equal(answer.headers['cache-control'], 'no-store', denied); + } + for (const answered of ['OK', 'ZERO_RESULTS']) { + status = answered; + const answer = await request('/api/google/geocode', '?address=Austin'); + assert.equal(answer.headers['cache-control'], 'private, max-age=300'); + } +}); + test('OSRM routing preserves aliases, cache, span guards and upstream failure behavior', async (t) => { const request = install(installRouteMiddleware); let calls = 0; From f22701ae7064392ace46afd8f5188531bf4c79ee Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Wed, 4 Nov 2026 22:25:40 -0500 Subject: [PATCH 2/4] docs(changelog): add the fragment for #1570 --- changelog.d/1570-places-no-store-on-errors.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1570-places-no-store-on-errors.md diff --git a/changelog.d/1570-places-no-store-on-errors.md b/changelog.d/1570-places-no-store-on-errors.md new file mode 100644 index 0000000000..459258ad0b --- /dev/null +++ b/changelog.d/1570-places-no-store-on-errors.md @@ -0,0 +1,4 @@ +- Stop the browser caching a refused Google Places or Geocoding answer. The + proxies sent `private, max-age=300` on a 403 and on a geocode + `REQUEST_DENIED` or `OVER_QUERY_LIMIT`, so a fixed key kept failing for five + minutes; refusals are now `no-store` (Rudy Celekli, @rudycelekli, #1570). From 31b6b25d8bb16f0b1b42c8f1bde8e190578cc3a3 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:29:24 +0400 Subject: [PATCH 3/4] fix(places): make no-store the default and refuse an unreadable Places 200 Every Google route now sets no-store right after the same-site gate and switches to private, max-age=300 only on a confirmed answer, so the proxy's own 400, 405, 429 and 502 replies are no longer left without a header. Both Places routes answer an unreadable 200 body with 502 instead of caching an empty result, as the geocode routes already did. The test pins the allowlist with OVER_DAILY_LIMIT and UNKNOWN_ERROR and covers the unreadable and empty Places bodies; the changelog fragment is shorter. --- changelog.d/1570-places-no-store-on-errors.md | 6 +- docs/CURRENT-STATE.md | 2 +- server/providers/places/google.js | 71 +++++++++++-------- src/tooling/placeProviders.test.mjs | 59 ++++++++++++++- 4 files changed, 103 insertions(+), 35 deletions(-) diff --git a/changelog.d/1570-places-no-store-on-errors.md b/changelog.d/1570-places-no-store-on-errors.md index 459258ad0b..4753638588 100644 --- a/changelog.d/1570-places-no-store-on-errors.md +++ b/changelog.d/1570-places-no-store-on-errors.md @@ -1,4 +1,2 @@ -- Stop the browser caching a refused Google Places or Geocoding answer. The - proxies sent `private, max-age=300` on a 403 and on a geocode - `REQUEST_DENIED` or `OVER_QUERY_LIMIT`, so a fixed key kept failing for five - minutes; refusals are now `no-store` (Rudy Celekli, @rudycelekli, #1570). +- Stop the browser caching a refused Google Places or Geocoding answer, so a + fixed key works at once (Rudy Celekli, @rudycelekli, #1570). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ece994cab5..42ff3ff9c2 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5996,7 +5996,7 @@ apply to `public/` assets or built-preview serving. - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache. - `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context. - `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution. -- The two Places routes and both geocode routes let the browser keep an answer for five minutes (`private, max-age=300`), but a refusal is `no-store`: a Places error status, or a Geocoding status other than `OK` or `ZERO_RESULTS` (Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200). A denied or exhausted key is not replayed from the browser cache after it is fixed. +- The two Places routes and both geocode routes let the browser keep an answer for five minutes (`private, max-age=300`), and everything else is `no-store`: a Places error status or unreadable body, a Geocoding status other than `OK` or `ZERO_RESULTS` (Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200), and the proxy's own 400, 405, 429 and 502 replies. A denied or exhausted key is not replayed from the browser cache after it is fixed. - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded. - `/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. diff --git a/server/providers/places/google.js b/server/providers/places/google.js index e20efa899d..c321dc0c4b 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -71,7 +71,6 @@ const GEOCODE_UPSTREAM_TIMEOUT_MS = 10_000; const GEOCODE_MAX_RESPONSE_BYTES = 256 * 1024; -/** Geocoding statuses that answer the query; the rest report a failure. */ const GEOCODE_ANSWER_STATUSES = new Set(['OK', 'ZERO_RESULTS']); /** Validate a free-text geocoder query before consuming request quota. */ @@ -117,6 +116,9 @@ export function googlePlacesContextProxy({ // Gate first, like the OpenAI routes: a cross-site caller learns nothing // about this endpoint's method surface. if (admitSameSite(req, res)) return; + // Nothing but a confirmed answer is kept: a refusal (bad key, API not + // enabled, quota) would be replayed for five minutes after the key is fixed. + res.setHeader('Cache-Control', 'no-store'); if (req.method !== 'GET') { res.statusCode = 405; res.setHeader('Content-Type', 'application/json'); @@ -132,7 +134,6 @@ export function googlePlacesContextProxy({ if (keyless) { res.statusCode = keyless.statusCode; res.setHeader('Content-Type', 'application/json'); - res.setHeader('Cache-Control', 'no-store'); res.end(JSON.stringify(keyless.payload)); return; } @@ -197,23 +198,30 @@ export function googlePlacesContextProxy({ }), }, ); - const data = await response.json().catch(() => ({})); - const places = projectNearbyPlaces(data, latitude, longitude); + const data = await response.json().catch(() => null); + // A 200 we could not read is an upstream failure, not an empty answer. + if (response.ok && !data) { + res.statusCode = 502; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end( + JSON.stringify({ + error: 'Google Places request failed', + places: [], + }), + ); + return; + } + const places = projectNearbyPlaces(data || {}, latitude, longitude); res.statusCode = response.ok ? 200 : response.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); - // A refusal (bad key, API not enabled, quota) is not kept: the browser - // would replay it for five minutes after the key is fixed. - res.setHeader( - 'Cache-Control', - response.ok ? 'private, max-age=300' : 'no-store', - ); + if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300'); res.end( JSON.stringify({ places, error: response.ok ? null - : data.error?.message || 'Google Places request failed', + : data?.error?.message || 'Google Places request failed', }), ); } catch (error) { @@ -231,10 +239,12 @@ export function googlePlacesContextProxy({ // Text Search: resolve a named landmark/POI to a real coordinate, biased to // the view. Geocoding scatters obscure monument/POI names across the city; // a view-biased Text Search lands on the actual feature. Same key, field - // mask, throttle, and `places: []` error contract as nearby-places above. + // mask, throttle, cache rule, and `places: []` error contract as + // nearby-places above. middlewares.use('/api/google/text-search', async (req, res) => { // Paid like nearby-places, so gated the same way, first. if (admitSameSite(req, res)) return; + res.setHeader('Cache-Control', 'no-store'); if (req.method !== 'GET') { res.statusCode = 405; res.setHeader('Content-Type', 'application/json'); @@ -250,7 +260,6 @@ export function googlePlacesContextProxy({ if (keyless) { res.statusCode = keyless.statusCode; res.setHeader('Content-Type', 'application/json'); - res.setHeader('Cache-Control', 'no-store'); res.end(JSON.stringify(keyless.payload)); return; } @@ -323,23 +332,30 @@ export function googlePlacesContextProxy({ }), }, ); - const data = await response.json().catch(() => ({})); - const places = projectTextSearchPlaces(data, latitude, longitude); + const data = await response.json().catch(() => null); + // A 200 we could not read is an upstream failure, not an empty answer. + if (response.ok && !data) { + res.statusCode = 502; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end( + JSON.stringify({ + error: 'Google Places request failed', + places: [], + }), + ); + return; + } + const places = projectTextSearchPlaces(data || {}, latitude, longitude); res.statusCode = response.ok ? 200 : response.status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); - // A refusal (bad key, API not enabled, quota) is not kept: the browser - // would replay it for five minutes after the key is fixed. - res.setHeader( - 'Cache-Control', - response.ok ? 'private, max-age=300' : 'no-store', - ); + if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300'); res.end( JSON.stringify({ places, error: response.ok ? null - : data.error?.message || 'Google Places request failed', + : data?.error?.message || 'Google Places request failed', }), ); } catch (error) { @@ -379,6 +395,8 @@ export function googlePlacesContextProxy({ // Gate first, like the Places routes above: a cross-site caller learns // nothing about this endpoint's method surface. if (admitSameSite(req, res)) return; + // As in the Places routes, only the confirmed answer below is kept. + res.setHeader('Cache-Control', 'no-store'); if (req.method !== 'GET') { refuse(405, 'Method not allowed'); return; @@ -392,7 +410,6 @@ export function googlePlacesContextProxy({ if (keyless) { res.statusCode = keyless.statusCode; res.setHeader('Content-Type', 'application/json'); - res.setHeader('Cache-Control', 'no-store'); res.end(JSON.stringify(keyless.payload)); return; } @@ -461,12 +478,8 @@ export function googlePlacesContextProxy({ res.setHeader('Content-Type', 'application/json; charset=utf-8'); // Geocoding reports a denied key or spent quota as HTTP 200 with a // status of its own; only an answer is worth keeping. - res.setHeader( - 'Cache-Control', - response.ok && GEOCODE_ANSWER_STATUSES.has(data.status) - ? 'private, max-age=300' - : 'no-store', - ); + if (response.ok && GEOCODE_ANSWER_STATUSES.has(data.status)) + res.setHeader('Cache-Control', 'private, max-age=300'); res.end(JSON.stringify(data)); } catch { // Fixed public text: a transport, URL or runtime message would diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index a6a3457536..2a9cf16daa 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -209,7 +209,12 @@ test('a refused Places or Geocoding answer is not kept by the browser', async (t t.mock.method(globalThis, 'fetch', async () => Response.json({ status, results: [] }), ); - for (const denied of ['REQUEST_DENIED', 'OVER_QUERY_LIMIT']) { + for (const denied of [ + 'REQUEST_DENIED', + 'OVER_QUERY_LIMIT', + 'OVER_DAILY_LIMIT', + 'UNKNOWN_ERROR', + ]) { status = denied; const answer = await request('/api/google/geocode', '?address=Austin'); assert.equal(answer.statusCode, 200); @@ -223,6 +228,58 @@ test('a refused Places or Geocoding answer is not kept by the browser', async (t } }); +const ROUTES = [ + ['/api/google/nearby-places', '?lat=30&lon=-97'], + ['/api/google/text-search', '?q=museum&lat=30&lon=-97'], +]; + +const truncated = () => + new Response( + new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode('{"places":[{"displayName"')); + c.error(new TypeError('terminated')); + }, + }), + { status: 200 }, + ); + +for (const [name, body] of [ + ['non-JSON', () => new Response('not json', { status: 200 })], + ['cut mid-body', truncated], +]) { + test(`an unreadable Places 200 (${name}) is a failure, not a cached empty answer`, async () => { + const request = install((middlewares) => + googlePlacesContextProxy({ + resolveApiKey: () => 'fixture-server-key', + fetchImpl: async () => body(), + }).configureServer({ middlewares }), + ); + for (const [route, query] of ROUTES) { + const res = await request(route, query); + assert.equal(res.statusCode, 502, route); + assert.equal(res.headers['cache-control'], 'no-store', route); + assert.deepEqual(res.body.places, [], route); + assert.ok(res.body.error, route); + } + }); +} + +test('a real empty Places answer ({}) stays cacheable', async () => { + const request = install((middlewares) => + googlePlacesContextProxy({ + resolveApiKey: () => 'fixture-server-key', + fetchImpl: async () => Response.json({}), + }).configureServer({ middlewares }), + ); + for (const [route, query] of ROUTES) { + const res = await request(route, query); + assert.equal(res.statusCode, 200, route); + assert.equal(res.headers['cache-control'], 'private, max-age=300', route); + assert.equal(res.body.error, null, route); + } +}); + test('OSRM routing preserves aliases, cache, span guards and upstream failure behavior', async (t) => { const request = install(installRouteMiddleware); let calls = 0; From 67bead9eb931d835416e8b30d73a2cd35ea20779 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 03:36:48 +0400 Subject: [PATCH 4/4] test(places): pin no-store on every refusal path and reuse the catch Tests now check Cache-Control on the proxy's own 400, 405, 429 and transport 502, a geocode 503 with ZERO_RESULTS on both geocode routes, and an upstream 429 with an HTML body on both Places routes; the geocode status cases move to the geocode suite and cover reverse-geocode too. An unreadable Places 200 now throws into the existing catch instead of repeating its 502 reply. Comments and the CURRENT-STATE rule are shorter and match the code. --- docs/CURRENT-STATE.md | 5 +- server/providers/places/google.js | 38 ++----- src/costEndpointThrottle.test.mjs | 1 + src/googleGeocodeProxy.test.mjs | 30 ++++++ src/tooling/placeProviders.test.mjs | 162 +++++++++++----------------- 5 files changed, 106 insertions(+), 130 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 068e615e4d..caf2cfb5e0 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8332,7 +8332,8 @@ Providers normalize coordinates, canonical name, label, place types and optional bounds. Camera framing, nearby landmark recovery and footprint selection remain in their consumers, including the Capitol identity/containment safeguards. Radio keeps localized country names in labels rather than station filters. -Nearby/text-search endpoints retain their existing behavior. +Nearby/text-search cache and error rules are listed under Proxy/Security +Baseline below. **Google geocoding is a server route, not a browser call** (#363). Forward and reverse lookups go to `/api/google/geocode` and `/api/google/reverse-geocode`, @@ -8652,7 +8653,7 @@ apply to `public/` assets or built-preview serving. - `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache. - `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context. - `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution. -- The two Places routes and both geocode routes let the browser keep an answer for five minutes (`private, max-age=300`), and everything else is `no-store`: a Places error status or unreadable body, a Geocoding status other than `OK` or `ZERO_RESULTS` (Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200), and the proxy's own 400, 405, 429 and 502 replies. A denied or exhausted key is not replayed from the browser cache after it is fixed. +- The Places and geocode routes cache only an answer (`private, max-age=300`). For geocode, that means an HTTP success with `OK` or `ZERO_RESULTS`, because Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200. Every other reply, including an unreadable Places 200 (now a 502), is `no-store`. - `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded. - `/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; routing outages return 502. diff --git a/server/providers/places/google.js b/server/providers/places/google.js index c321dc0c4b..d81d8eef1d 100644 --- a/server/providers/places/google.js +++ b/server/providers/places/google.js @@ -116,8 +116,9 @@ export function googlePlacesContextProxy({ // Gate first, like the OpenAI routes: a cross-site caller learns nothing // about this endpoint's method surface. if (admitSameSite(req, res)) return; - // Nothing but a confirmed answer is kept: a refusal (bad key, API not - // enabled, quota) would be replayed for five minutes after the key is fixed. + // Default to no-store. The browser caches only the 200 answer below. + // A cached refusal (bad key, API off, quota) would outlive the key fix + // by five minutes. res.setHeader('Cache-Control', 'no-store'); if (req.method !== 'GET') { res.statusCode = 405; @@ -200,17 +201,8 @@ export function googlePlacesContextProxy({ ); const data = await response.json().catch(() => null); // A 200 we could not read is an upstream failure, not an empty answer. - if (response.ok && !data) { - res.statusCode = 502; - res.setHeader('Content-Type', 'application/json; charset=utf-8'); - res.end( - JSON.stringify({ - error: 'Google Places request failed', - places: [], - }), - ); - return; - } + if (response.ok && !data) + throw new Error('Google Places request failed'); const places = projectNearbyPlaces(data || {}, latitude, longitude); res.statusCode = response.ok ? 200 : response.status; @@ -238,9 +230,8 @@ export function googlePlacesContextProxy({ // Text Search: resolve a named landmark/POI to a real coordinate, biased to // the view. Geocoding scatters obscure monument/POI names across the city; - // a view-biased Text Search lands on the actual feature. Same key, field - // mask, throttle, cache rule, and `places: []` error contract as - // nearby-places above. + // a view-biased Text Search lands on the actual feature. Same key, throttle, + // cache rule, and `places: []` error contract as nearby-places above. middlewares.use('/api/google/text-search', async (req, res) => { // Paid like nearby-places, so gated the same way, first. if (admitSameSite(req, res)) return; @@ -333,18 +324,8 @@ export function googlePlacesContextProxy({ }, ); const data = await response.json().catch(() => null); - // A 200 we could not read is an upstream failure, not an empty answer. - if (response.ok && !data) { - res.statusCode = 502; - res.setHeader('Content-Type', 'application/json; charset=utf-8'); - res.end( - JSON.stringify({ - error: 'Google Places request failed', - places: [], - }), - ); - return; - } + if (response.ok && !data) + throw new Error('Google Places request failed'); const places = projectTextSearchPlaces(data || {}, latitude, longitude); res.statusCode = response.ok ? 200 : response.status; @@ -395,7 +376,6 @@ export function googlePlacesContextProxy({ // Gate first, like the Places routes above: a cross-site caller learns // nothing about this endpoint's method surface. if (admitSameSite(req, res)) return; - // As in the Places routes, only the confirmed answer below is kept. res.setHeader('Cache-Control', 'no-store'); if (req.method !== 'GET') { refuse(405, 'Method not allowed'); diff --git a/src/costEndpointThrottle.test.mjs b/src/costEndpointThrottle.test.mjs index 8a4e5bc55c..9aa2ef45d8 100644 --- a/src/costEndpointThrottle.test.mjs +++ b/src/costEndpointThrottle.test.mjs @@ -335,6 +335,7 @@ test('the Google places route throttles by default and keeps its places[] contra const overLimit = await request(handler, { url, method: 'GET' }); assert.equal(overLimit.status, 429); assert.equal(overLimit.headers['retry-after'], '5'); + assert.equal(overLimit.headers['cache-control'], 'no-store'); // Every error response on this route carries places[]; the client reads it // unconditionally, so a throttled reply must not be the one shape that omits it. assert.deepEqual(JSON.parse(overLimit.body).places, []); diff --git a/src/googleGeocodeProxy.test.mjs b/src/googleGeocodeProxy.test.mjs index 98ffd876e3..4675999a79 100644 --- a/src/googleGeocodeProxy.test.mjs +++ b/src/googleGeocodeProxy.test.mjs @@ -134,6 +134,7 @@ test('a bad or keyless geocode request never reaches Google', async () => { ]) { const response = await invokeRoute(routes.get(path), { url }); assert.equal(response.statusCode, 400); + assert.equal(response.headers['cache-control'], 'no-store'); assert.deepEqual(response.body.results, []); assert.equal(response.body.status, 'REQUEST_DENIED'); } @@ -144,6 +145,7 @@ test('a bad or keyless geocode request never reaches Google', async () => { url: '/?address=Austin&lat=30&lon=-97', }); assert.equal(rejected.statusCode, 405); + assert.equal(rejected.headers['cache-control'], 'no-store'); } // Keyless is an empty capability, not an outage: a 200 the browser adapters @@ -167,6 +169,33 @@ test('a bad or keyless geocode request never reaches Google', async () => { assert.deepEqual(upstream, []); }); +test('only a Geocoding answer is kept by the browser', async () => { + // Google can report a denied key or exhausted quota with HTTP 200. + for (const [httpStatus, status, cacheControl] of [ + [200, 'OK', 'private, max-age=300'], + [200, 'ZERO_RESULTS', 'private, max-age=300'], + [200, 'REQUEST_DENIED', 'no-store'], + [200, 'OVER_QUERY_LIMIT', 'no-store'], + [200, 'OVER_DAILY_LIMIT', 'no-store'], + [200, 'UNKNOWN_ERROR', 'no-store'], + [503, 'ZERO_RESULTS', 'no-store'], + ]) { + const routes = installRoutes({ + fetchImpl: async () => + Response.json({ status, results: [] }, { status: httpStatus }), + }); + for (const path of ['/api/google/geocode', '/api/google/reverse-geocode']) { + const label = `${path} ${httpStatus} ${status}`; + const response = await invokeRoute(routes.get(path), { + url: '/?address=Austin&lat=30&lon=-97', + }); + assert.equal(response.statusCode, httpStatus, label); + assert.equal(response.body.status, status, label); + assert.equal(response.headers['cache-control'], cacheControl, label); + } + } +}); + test('an upstream failure reaches the browser as fixed public text', async () => { const routes = installRoutes({ fetchImpl: async () => { @@ -178,6 +207,7 @@ test('an upstream failure reaches the browser as fixed public text', async () => url: '/?address=Austin&lat=30&lon=-97', }); assert.equal(response.statusCode, 502); + assert.equal(response.headers['cache-control'], 'no-store'); assert.deepEqual(response.body, { status: 'UNKNOWN_ERROR', results: [], diff --git a/src/tooling/placeProviders.test.mjs b/src/tooling/placeProviders.test.mjs index edcf7143d8..600f4d05cd 100644 --- a/src/tooling/placeProviders.test.mjs +++ b/src/tooling/placeProviders.test.mjs @@ -52,6 +52,11 @@ function install(register) { }; } +const ROUTES = [ + ['/api/google/nearby-places', '?lat=30&lon=-97'], + ['/api/google/text-search', '?q=museum&lat=30&lon=-97'], +]; + test('nearby labels rank landmarks, deduplicate names/addresses and bound the projection', () => { const place = (name, types, longitude = 0) => ({ displayName: { text: name }, @@ -176,113 +181,72 @@ for (const preview of [false, true]) { JSON.parse(calls[1].options.body).locationBias.circle.radius, 50, ); - assert.equal((await request(search, '?lat=30&lon=-97')).statusCode, 400); - assert.equal((await request(nearby, '?lat=bad&lon=-97')).statusCode, 400); - assert.equal((await request(nearby, '', 'POST')).statusCode, 405); + for (const [route, query, method, statusCode] of [ + [search, '?lat=30&lon=-97', 'GET', 400], + [nearby, '?lat=bad&lon=-97', 'GET', 400], + [nearby, '', 'POST', 405], + ]) { + const refused = await request(route, query, method); + assert.equal(refused.statusCode, statusCode, `${method} ${route}`); + assert.equal( + refused.headers['cache-control'], + 'no-store', + `${method} ${route}`, + ); + } t.mock.method(globalThis, 'fetch', async () => Response.json({ error: { message: 'Denied' } }, { status: 403 }), ); - assert.deepEqual((await request(search, '?q=museum&lat=30&lon=-97')).body, { - places: [], - error: 'Denied', - }); - }); -} - -test('a refused Places or Geocoding answer is not kept by the browser', async (t) => { - const plugin = googlePlacesContextProxy({ - resolveApiKey: () => 'fixture-server-key', - }); - const request = install((middlewares) => - plugin.configureServer({ middlewares }), - ); - t.mock.method(globalThis, 'fetch', async () => - Response.json({ error: { message: 'API key not valid' } }, { status: 403 }), - ); - for (const url of [ - ['/api/google/nearby-places', '?lat=30&lon=-97'], - ['/api/google/text-search', '?q=museum&lat=30&lon=-97'], - ]) { - const refused = await request(...url); - assert.equal(refused.statusCode, 403); - assert.equal(refused.headers['cache-control'], 'no-store'); - } - - // Geocoding reports a denied key as HTTP 200 with a status of its own. - let status = 'REQUEST_DENIED'; - t.mock.method(globalThis, 'fetch', async () => - Response.json({ status, results: [] }), - ); - for (const denied of [ - 'REQUEST_DENIED', - 'OVER_QUERY_LIMIT', - 'OVER_DAILY_LIMIT', - 'UNKNOWN_ERROR', - ]) { - status = denied; - const answer = await request('/api/google/geocode', '?address=Austin'); - assert.equal(answer.statusCode, 200); - assert.equal(answer.body.status, denied); - assert.equal(answer.headers['cache-control'], 'no-store', denied); - } - for (const answered of ['OK', 'ZERO_RESULTS']) { - status = answered; - const answer = await request('/api/google/geocode', '?address=Austin'); - assert.equal(answer.headers['cache-control'], 'private, max-age=300'); - } -}); - -const ROUTES = [ - ['/api/google/nearby-places', '?lat=30&lon=-97'], - ['/api/google/text-search', '?q=museum&lat=30&lon=-97'], -]; - -const truncated = () => - new Response( - new ReadableStream({ - start(c) { - c.enqueue(new TextEncoder().encode('{"places":[{"displayName"')); - c.error(new TypeError('terminated')); - }, - }), - { status: 200 }, - ); - -for (const [name, body] of [ - ['non-JSON', () => new Response('not json', { status: 200 })], - ['cut mid-body', truncated], -]) { - test(`an unreadable Places 200 (${name}) is a failure, not a cached empty answer`, async () => { - const request = install((middlewares) => - googlePlacesContextProxy({ - resolveApiKey: () => 'fixture-server-key', - fetchImpl: async () => body(), - }).configureServer({ middlewares }), - ); for (const [route, query] of ROUTES) { - const res = await request(route, query); - assert.equal(res.statusCode, 502, route); - assert.equal(res.headers['cache-control'], 'no-store', route); - assert.deepEqual(res.body.places, [], route); - assert.ok(res.body.error, route); + const refused = await request(route, query); + assert.equal(refused.statusCode, 403, route); + assert.equal(refused.headers['cache-control'], 'no-store', route); + assert.deepEqual(refused.body, { places: [], error: 'Denied' }, route); } }); } -test('a real empty Places answer ({}) stays cacheable', async () => { - const request = install((middlewares) => - googlePlacesContextProxy({ - resolveApiKey: () => 'fixture-server-key', - fetchImpl: async () => Response.json({}), - }).configureServer({ middlewares }), - ); - for (const [route, query] of ROUTES) { - const res = await request(route, query); - assert.equal(res.statusCode, 200, route); - assert.equal(res.headers['cache-control'], 'private, max-age=300', route); - assert.equal(res.body.error, null, route); - } -}); +for (const [name, upstream, statusCode, cacheControl] of [ + [ + 'unreadable 200', + () => new Response('not json', { status: 200 }), + 502, + 'no-store', + ], + [ + 'unreadable 429', + () => new Response('Too Many Requests', { status: 429 }), + 429, + 'no-store', + ], + [ + 'transport failure', + () => { + throw new TypeError('fetch failed'); + }, + 502, + 'no-store', + ], + // Google returns {} for a successful search with no places. + ['empty answer ({})', () => Response.json({}), 200, 'private, max-age=300'], +]) { + test(`a Places ${name} is a ${statusCode} with Cache-Control ${cacheControl}`, async () => { + const request = install((middlewares) => + googlePlacesContextProxy({ + resolveApiKey: () => 'fixture-server-key', + fetchImpl: async () => upstream(), + }).configureServer({ middlewares }), + ); + for (const [route, query] of ROUTES) { + const res = await request(route, query); + assert.equal(res.statusCode, statusCode, route); + assert.equal(res.headers['cache-control'], cacheControl, route); + assert.deepEqual(res.body.places, [], route); + if (statusCode === 200) assert.equal(res.body.error, null, route); + else assert.ok(res.body.error, route); + } + }); +} test('OSRM routing preserves aliases, cache, span guards and upstream failure behavior', async (t) => { const request = install(installRouteMiddleware);