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
25 changes: 24 additions & 1 deletion 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 { handler } from '../index.js';
import { getClientIp, handler } from '../index.js';
import { ConfigLoader } from '../util/config.loader.js';
import { mockRequest } from './xyz.util.js';

Expand All @@ -13,6 +13,29 @@ 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
18 changes: 18 additions & 0 deletions packages/lambda-tiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ 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 @@ -50,6 +65,9 @@ handler.router.hook('request', (req) => {

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

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

req.log.debug({ ...req.logContext }, 'Lambda:Start');
});

Expand Down
Loading