Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down Expand Up @@ -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 }}
Expand Down
14 changes: 14 additions & 0 deletions packages/_infra/src/serve/lambda.tiler.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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);

/**
Expand Down
25 changes: 1 addition & 24 deletions packages/lambda-tiler/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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'];
Expand Down
19 changes: 2 additions & 17 deletions packages/lambda-tiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand All @@ -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();
Expand All @@ -65,8 +51,7 @@ handler.router.hook('request', (req) => {

req.set('name', 'LambdaTiler');

const clientIp = getClientIp(req);
if (clientIp) req.set('clientIp', clientIp);
Validate.clientIp(req);

req.log.debug({ ...req.logContext }, 'Lambda:Start');
});
Expand Down
45 changes: 44 additions & 1 deletion packages/lambda-tiler/src/util/__test__/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -24,6 +24,49 @@ describe('Validate.blockedApiKeys', () => {
});
});

describe('Validate.blockedClientIps', () => {
const viewer = (addr?: string): ReturnType<typeof mockUrlRequest> =>
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');
Expand Down
57 changes: 57 additions & 0 deletions packages/lambda-tiler/src/util/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,67 @@ 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<string>(getBlockedApiKeys()),

/** list of client IP addresses that have been disabled, normalized with {@link normalizeIp} */
blockedClientIps: new Set<string>(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;

req.set('clientIp', clientIp);

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
*
Expand Down
7 changes: 7 additions & 0 deletions packages/shared/src/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading