From 36e96b89c8a32757c6a8d33972a0414d5d6c3346 Mon Sep 17 00:00:00 2001 From: Blayne Chard Date: Tue, 27 Oct 2026 13:14:13 +1300 Subject: [PATCH 1/2] feat(lambda-tiler): allow blocking viewer ip addresses Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/push.yml | 2 + packages/_infra/src/serve/lambda.tiler.ts | 14 +++++ .../lambda-tiler/src/__tests__/index.test.ts | 25 +-------- packages/lambda-tiler/src/index.ts | 18 +----- .../src/util/__test__/validate.test.ts | 45 ++++++++++++++- packages/lambda-tiler/src/util/validate.ts | 55 +++++++++++++++++++ packages/shared/src/const.ts | 7 +++ 7 files changed, 125 insertions(+), 41 deletions(-) diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index 35868498ac..962242b0dc 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -133,6 +133,7 @@ jobs: npx lerna run deploy:deploy --stream env: BASEMAPS_API_KEY_BLOCKS: ${{ secrets.BASEMAPS_API_KEY_BLOCKS }} + BASEMAPS_VIEWER_IP_BLOCKS: ${{ secrets.BASEMAPS_VIEWER_IP_BLOCKS }} GOOGLE_ANALYTICS: ${{ secrets.GOOGLE_ANALYTICS }} ELASTIC_ID: ${{ secrets.ELASTIC_ID }} ELASTIC_API_KEY: ${{ secrets.ELASTIC_API_KEY }} @@ -202,6 +203,7 @@ jobs: npx lerna run deploy:deploy --stream env: BASEMAPS_API_KEY_BLOCKS: ${{ secrets.BASEMAPS_API_KEY_BLOCKS }} + BASEMAPS_VIEWER_IP_BLOCKS: ${{ secrets.BASEMAPS_VIEWER_IP_BLOCKS }} GOOGLE_ANALYTICS: ${{ secrets.GOOGLE_ANALYTICS }} ELASTIC_ID: ${{ secrets.ELASTIC_ID }} ELASTIC_API_KEY: ${{ secrets.ELASTIC_API_KEY }} diff --git a/packages/_infra/src/serve/lambda.tiler.ts b/packages/_infra/src/serve/lambda.tiler.ts index 13b80b635f..c3876b6c7a 100644 --- a/packages/_infra/src/serve/lambda.tiler.ts +++ b/packages/_infra/src/serve/lambda.tiler.ts @@ -1,4 +1,5 @@ import assert from 'node:assert'; +import { isIP } from 'node:net'; import { Env, isValidApiKey } from '@basemaps/shared'; import type * as cdk from 'aws-cdk-lib'; @@ -51,6 +52,19 @@ export class LambdaTiler extends Construct { environment[Env.BlockedApiKeys] = blockedKeys; } + // Set blocked client ips if some are present + const blockedIps = Env.get(Env.BlockedClientIps) ?? ''; + if (blockedIps.length > 0) { + const listOfIps = JSON.parse(blockedIps) as string[]; + if (!Array.isArray(listOfIps)) throw new Error(` ${Env.BlockedClientIps} is not valid`); + for (const ip of listOfIps) { + // IPv6 addresses can be wrapped in "[]" to match the CloudFront-Viewer-Address header + const bareIp = typeof ip === 'string' ? ip.replace(/^\[(.*)\]$/, '$1') : ''; + assert.ok(isIP(bareIp) !== 0, `${ip} is not a valid ip address to block ${Env.BlockedClientIps}`); + } + environment[Env.BlockedClientIps] = blockedIps; + } + const code = lambda.Code.fromAsset(CODE_PATH); /** diff --git a/packages/lambda-tiler/src/__tests__/index.test.ts b/packages/lambda-tiler/src/__tests__/index.test.ts index 617a6dc804..a61268a606 100644 --- a/packages/lambda-tiler/src/__tests__/index.test.ts +++ b/packages/lambda-tiler/src/__tests__/index.test.ts @@ -3,7 +3,7 @@ import { afterEach, describe, it } from 'node:test'; import { ConfigProviderMemory } from '@basemaps/config'; -import { getClientIp, handler } from '../index.js'; +import { handler } from '../index.js'; import { ConfigLoader } from '../util/config.loader.js'; import { mockRequest } from './xyz.util.js'; @@ -13,29 +13,6 @@ describe('LambdaXyz index', () => { assert.equal(typeof foo.handler, 'function'); }); - describe('getClientIp', () => { - const ip = (addr?: string): string | undefined => { - return getClientIp(mockRequest('/v1/version', 'get', addr ? { 'cloudfront-viewer-address': addr } : {})); - }; - - it('should strip the port from ipv4', () => { - assert.equal(ip('203.0.113.10:46532'), '203.0.113.10'); - }); - - it('should strip the port from ipv6 and keep brackets', () => { - assert.equal(ip('[2001:db8::1]:46532'), '[2001:db8::1]'); - }); - - it('should handle missing ports', () => { - assert.equal(ip('203.0.113.10'), '203.0.113.10'); - assert.equal(ip('[2001:db8::1]'), '[2001:db8::1]'); - }); - - it('should return undefined when header is missing', () => { - assert.equal(ip(), undefined); - }); - }); - describe('version', () => { afterEach(() => { delete process.env['GIT_VERSION']; diff --git a/packages/lambda-tiler/src/index.ts b/packages/lambda-tiler/src/index.ts index 8fd37303d2..78803784a0 100644 --- a/packages/lambda-tiler/src/index.ts +++ b/packages/lambda-tiler/src/index.ts @@ -19,6 +19,7 @@ import { wmtsCapabilitiesGet } from './routes/tile.wmts.js'; import { tileXyzGet } from './routes/tile.xyz.js'; import { versionGet } from './routes/version.js'; import { NotFound } from './util/response.js'; +import { Validate } from './util/validate.js'; export const handler = lf.http(LogConfig.get()); @@ -42,21 +43,6 @@ function randomTrace(req: LambdaHttpRequest): void { else req.log.level = 'info'; } -/** - * Get the viewer's IP address from the CloudFront-Viewer-Address header, removing the port - * - * @example - * "203.0.113.10:46532" => "203.0.113.10" - * "[2001:db8::1]:46532" => "[2001:db8::1]" - */ -export function getClientIp(req: LambdaHttpRequest): string | undefined { - const addr = req.header('cloudfront-viewer-address'); - if (addr == null) return undefined; - const portIndex = addr.lastIndexOf(':'); - if (portIndex === -1 || addr.endsWith(']')) return addr; - return addr.slice(0, portIndex); -} - handler.router.hook('request', (req) => { LogStorage.enterWith({ log: req.log }); FsaLog.reset(); @@ -65,7 +51,7 @@ handler.router.hook('request', (req) => { req.set('name', 'LambdaTiler'); - const clientIp = getClientIp(req); + const clientIp = Validate.clientIp(req); if (clientIp) req.set('clientIp', clientIp); req.log.debug({ ...req.logContext }, 'Lambda:Start'); diff --git a/packages/lambda-tiler/src/util/__test__/validate.test.ts b/packages/lambda-tiler/src/util/__test__/validate.test.ts index 6615baf667..2e54100b0e 100644 --- a/packages/lambda-tiler/src/util/__test__/validate.test.ts +++ b/packages/lambda-tiler/src/util/__test__/validate.test.ts @@ -4,7 +4,7 @@ import { describe, it } from 'node:test'; import { GoogleTms, Nztm2000QuadTms, Nztm2000Tms } from '@basemaps/geo'; import { mockUrlRequest } from '../../__tests__/xyz.util.js'; -import { Validate } from '../validate.js'; +import { getClientIp, normalizeIp, Validate } from '../validate.js'; describe('Validate.blockedApiKeys', () => { const validApiKey = 'c01jswmpe1yn3mwne7e0ggtp8vg'; @@ -24,6 +24,49 @@ describe('Validate.blockedApiKeys', () => { }); }); +describe('Validate.blockedClientIps', () => { + const viewer = (addr?: string): ReturnType => + mockUrlRequest('/v1/blank', '', addr ? { 'cloudfront-viewer-address': addr } : {}); + + it('should get client ip without port', () => { + assert.equal(getClientIp(viewer('203.0.113.10:46532')), '203.0.113.10'); + assert.equal(getClientIp(viewer('[2001:db8::1]:46532')), '[2001:db8::1]'); + assert.equal(getClientIp(viewer('203.0.113.10')), '203.0.113.10'); + assert.equal(getClientIp(viewer('[2001:db8::1]')), '[2001:db8::1]'); + assert.equal(getClientIp(viewer()), undefined); + }); + + it('should normalize ips', () => { + assert.equal(normalizeIp(' 203.0.113.10 '), '203.0.113.10'); + assert.equal(normalizeIp('2001:DB8::1'), '[2001:db8::1]'); + assert.equal(normalizeIp('[2001:db8::1]'), '[2001:db8::1]'); + }); + + it('should block ipv4 clients', () => { + const req = viewer('203.0.113.10:46532'); + assert.equal(Validate.clientIp(req), '203.0.113.10'); + + Validate.blockedClientIps.add(normalizeIp('203.0.113.10')); + assert.throws(() => Validate.clientIp(req)); + assert.equal(Validate.clientIp(viewer('203.0.113.11:46532')), '203.0.113.11'); + + Validate.blockedClientIps.delete(normalizeIp('203.0.113.10')); + assert.equal(Validate.clientIp(req), '203.0.113.10'); + }); + + it('should block ipv6 clients', () => { + const req = viewer('[2001:db8::1]:46532'); + Validate.blockedClientIps.add(normalizeIp('2001:DB8::1')); + assert.throws(() => Validate.clientIp(req)); + Validate.blockedClientIps.delete(normalizeIp('2001:DB8::1')); + assert.equal(Validate.clientIp(req), '[2001:db8::1]'); + }); + + it('should allow requests without a client address', () => { + assert.equal(Validate.clientIp(viewer()), undefined); + }); +}); + describe('GetImageFormats', () => { it('should parse all formats', () => { const req = mockUrlRequest('/v1/blank', 'format=png&format=jpeg'); diff --git a/packages/lambda-tiler/src/util/validate.ts b/packages/lambda-tiler/src/util/validate.ts index dcd9e38775..22caadb13e 100644 --- a/packages/lambda-tiler/src/util/validate.ts +++ b/packages/lambda-tiler/src/util/validate.ts @@ -34,10 +34,65 @@ function getBlockedApiKeys(): string[] { } } +/** + * Normalize an IP address so it can be compared against the CloudFront-Viewer-Address header, + * IPv6 addresses are lowercased and wrapped in "[]" + */ +export function normalizeIp(ip: string): string { + const trimmed = ip.trim().toLowerCase(); + if (trimmed.includes(':') && !trimmed.startsWith('[')) return `[${trimmed}]`; + return trimmed; +} + +function getBlockedClientIps(): string[] { + try { + const ips = JSON.parse(Env.get(Env.BlockedClientIps) ?? '[]') as string[]; + return ips.map(normalizeIp); + } catch (e) { + LogConfig.get().error(`"$${Env.BlockedClientIps}" is invalid`); + return []; + } +} + +/** + * Get the client's IP address from the CloudFront-Viewer-Address header, removing the port + * + * @example + * "203.0.113.10:46532" => "203.0.113.10" + * "[2001:db8::1]:46532" => "[2001:db8::1]" + */ +export function getClientIp(req: LambdaHttpRequest): string | undefined { + const addr = req.header('cloudfront-viewer-address'); + if (addr == null) return undefined; + const portIndex = addr.lastIndexOf(':'); + if (portIndex === -1 || addr.endsWith(']')) return addr; + return addr.slice(0, portIndex); +} + export const Validate = { /** list of API Keys that have been disabled */ blockedApiKeys: new Set(getBlockedApiKeys()), + /** list of client IP addresses that have been disabled, normalized with {@link normalizeIp} */ + blockedClientIps: new Set(getBlockedClientIps()), + + /** + * Validate that the client's IP address has not been blocked + * + * @throws if the client IP is blocked + */ + clientIp(req: LambdaHttpRequest): string | undefined { + const clientIp = getClientIp(req); + if (clientIp == null) return undefined; + + if (this.blockedClientIps.has(normalizeIp(clientIp))) { + req.set('clientIpBlocked', true); + throw new LambdaHttpResponse(429, 'Too many requests! Please contact basemaps@linz.govt.nz'); + } + + return clientIp; + }, + /** * Validate that the api key exists and is valid * diff --git a/packages/shared/src/const.ts b/packages/shared/src/const.ts index 3d3997b3ed..4048c86fb7 100644 --- a/packages/shared/src/const.ts +++ b/packages/shared/src/const.ts @@ -49,6 +49,13 @@ export const Env = { */ BlockedApiKeys: 'BASEMAPS_API_KEY_BLOCKS', + /** + * JSON encoded array of client IP addresses to block, IPv6 addresses can be with or without "[]" + * + * @example '["203.0.113.10","[2001:db8::1]"]' + */ + BlockedClientIps: 'BASEMAPS_CLIENT_IP_BLOCKS', + Gdal: { /** Should the gdal docker container be used? */ UseDocker: 'GDAL_DOCKER', From 8469b1fa0e5daca3d00bbf04e7dd648477f3d867 Mon Sep 17 00:00:00 2001 From: Blayne Chard Date: Tue, 27 Oct 2026 13:56:34 +1300 Subject: [PATCH 2/2] refactor: include ip in logs when blocked --- packages/lambda-tiler/src/index.ts | 3 +-- packages/lambda-tiler/src/util/validate.ts | 4 +++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/lambda-tiler/src/index.ts b/packages/lambda-tiler/src/index.ts index 78803784a0..092fbb89f6 100644 --- a/packages/lambda-tiler/src/index.ts +++ b/packages/lambda-tiler/src/index.ts @@ -51,8 +51,7 @@ handler.router.hook('request', (req) => { req.set('name', 'LambdaTiler'); - const clientIp = Validate.clientIp(req); - if (clientIp) req.set('clientIp', clientIp); + Validate.clientIp(req); req.log.debug({ ...req.logContext }, 'Lambda:Start'); }); diff --git a/packages/lambda-tiler/src/util/validate.ts b/packages/lambda-tiler/src/util/validate.ts index 22caadb13e..2858004d82 100644 --- a/packages/lambda-tiler/src/util/validate.ts +++ b/packages/lambda-tiler/src/util/validate.ts @@ -83,7 +83,9 @@ export const Validate = { */ clientIp(req: LambdaHttpRequest): string | undefined { const clientIp = getClientIp(req); - if (clientIp == null) return undefined; + if (clientIp == null) return; + + req.set('clientIp', clientIp); if (this.blockedClientIps.has(normalizeIp(clientIp))) { req.set('clientIpBlocked', true);