Skip to content

Commit

Permalink
fix: b64-encode geo location in local dev (#5873)
Browse files Browse the repository at this point in the history
* fix: b64-encode geo location in local dev

* fix: update test

* fix: another test
  • Loading branch information
Skn0tt authored Jul 20, 2023
1 parent f38514a commit faa6ad2
Show file tree
Hide file tree
Showing 10 changed files with 730 additions and 92 deletions.
778 changes: 696 additions & 82 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"@netlify/framework-info": "9.8.10",
"@netlify/local-functions-proxy": "1.1.1",
"@netlify/serverless-functions-api": "1.5.1",
"@netlify/zip-it-and-ship-it": "9.13.0",
"@netlify/zip-it-and-ship-it": "9.13.1",
"@octokit/rest": "19.0.13",
"@skn0tt/lambda-local": "2.0.3",
"ansi-escapes": "6.2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/edge-functions/bootstrap.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { env } from 'process'

const latestBootstrapURL = 'https://6494585a67d46e0008867e60--edge.netlify.com/bootstrap/index-combined.ts'
const latestBootstrapURL = 'https://64ae60d920fd0f000865bcfc--edge.netlify.com/bootstrap/index-combined.ts'

export const getBootstrapURL = () => env.NETLIFY_EDGE_BOOTSTRAP || latestBootstrapURL
2 changes: 1 addition & 1 deletion src/lib/edge-functions/proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export const initializeProxy = async ({
if (!registry) return

// Setting header with geolocation and site info.
req.headers[headers.Geo] = JSON.stringify(geoLocation)
req.headers[headers.Geo] = Buffer.from(JSON.stringify(geoLocation)).toString('base64')
req.headers[headers.Site] = createSiteInfoHeader(siteInfo)
req.headers[headers.Account] = createAccountInfoHeader({ id: accountId })

Expand Down
5 changes: 3 additions & 2 deletions src/lib/functions/server.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// @ts-check
import { Buffer } from 'buffer'

import express from 'express'
import expressLogging from 'express-logging'
import jwtDecode from 'jwt-decode'
Expand Down Expand Up @@ -47,7 +49,6 @@ const hasBody = (req) =>
// eslint-disable-next-line unicorn/prefer-number-properties
(req.header('transfer-encoding') !== undefined || !isNaN(req.header('content-length'))) &&
// we expect a string or a buffer, because we use the two bodyParsers(text, raw) from express
// eslint-disable-next-line n/prefer-global/buffer
(typeof req.body === 'string' || Buffer.isBuffer(req.body))

export const createHandler = function (options) {
Expand Down Expand Up @@ -114,7 +115,7 @@ export const createHandler = function (options) {
'client-ip': [remoteAddress],
'x-nf-client-connection-ip': [remoteAddress],
'x-nf-account-id': [options.accountId],
[efHeaders.Geo]: JSON.stringify(geoLocation),
[efHeaders.Geo]: Buffer.from(JSON.stringify(geoLocation)).toString('base64'),
}).reduce((prev, [key, value]) => ({ ...prev, [key]: Array.isArray(value) ? value : [value] }), {})
const rawQuery = new URLSearchParams(requestQuery).toString()
const protocol = options.config?.dev?.https ? 'https' : 'http'
Expand Down
10 changes: 7 additions & 3 deletions tests/integration/130.eleventy.test.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { Buffer } = require('buffer')
const path = require('path')

const test = require('ava')
Expand Down Expand Up @@ -69,8 +70,9 @@ test('functions rewrite echo without body', async (t) => {
'x-forwarded-for': originalIP,
'x-nf-account-id': '',
'x-nf-client-connection-ip': clientIP,
'x-nf-geo':
'x-nf-geo': Buffer.from(
'{"city":"San Francisco","country":{"code":"US","name":"United States"},"subdivision":{"code":"CA","name":"California"},"longitude":0,"latitude":0,"timezone":"UTC"}',
).toString('base64'),
})
t.is(requestID.length, 26)
t.is(response.httpMethod, 'GET')
Expand Down Expand Up @@ -104,8 +106,9 @@ test('functions rewrite echo with body', async (t) => {
'x-forwarded-for': originalIP,
'x-nf-account-id': '',
'x-nf-client-connection-ip': clientIP,
'x-nf-geo':
'x-nf-geo': Buffer.from(
'{"city":"San Francisco","country":{"code":"US","name":"United States"},"subdivision":{"code":"CA","name":"California"},"longitude":0,"latitude":0,"timezone":"UTC"}',
).toString('base64'),
})
t.is(requestID.length, 26)
t.is(response.httpMethod, 'POST')
Expand All @@ -129,8 +132,9 @@ test('functions echo with multiple query params', async (t) => {
'x-forwarded-for': originalIP,
'x-nf-account-id': '',
'x-nf-client-connection-ip': clientIP,
'x-nf-geo':
'x-nf-geo': Buffer.from(
'{"city":"San Francisco","country":{"code":"US","name":"United States"},"subdivision":{"code":"CA","name":"California"},"longitude":0,"latitude":0,"timezone":"UTC"}',
).toString('base64'),
})
t.is(requestID.length, 26)
t.is(response.httpMethod, 'GET')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Config, Context } from 'https://edge.netlify.com'

export default (_, context: Context) => Response.json(context)

export const config: Config = {
path: '/context',
}
11 changes: 11 additions & 0 deletions tests/integration/commands/dev/edge-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ describe('edge functions', () => {
expect(response.statusCode).toBe(200)
expect(response.body).toMatchSnapshot()
})

test<FixtureTestContext>('should provide geo location', async ({ devServer }) => {
const response = await got(`http://localhost:${devServer.port}/context`, {
throwHttpErrors: false,
retry: { limit: 0 },
})

const { geo } = JSON.parse(response.body)
expect(geo.city).toEqual('Mock City')
expect(geo.country.code).toEqual('DE')
})
})

setupFixtureTests('dev-server-with-edge-functions', { devServer: true }, () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/commands/dev/v2-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe.runIf(gte(version, '18.13.0'))('v2 api', () => {
expect(context.site.url).toEqual(`http://localhost:${devServer.port}`)
expect(context.server.region).toEqual('dev')
expect(context.ip).toEqual('::1')
expect(context.geo.city).toEqual('San Francisco')
expect(context.geo.city).toEqual('Mock City')

expect(context.cookies).toEqual({ foo: 'bar' })
})
Expand Down
3 changes: 2 additions & 1 deletion tests/integration/utils/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ export async function setupFixtureTests(
if (options.mockApi) mockApi = await startMockApi(options.mockApi)
fixture = await Fixture.create(fixturePath, { apiUrl: mockApi?.apiUrl })

if (options.devServer) devServer = await startDevServer({ cwd: fixture.directory, args: ['--offline'] })
if (options.devServer)
devServer = await startDevServer({ cwd: fixture.directory, args: ['--offline', '--country', 'DE'] })

await options.setup?.({ devServer, fixture, mockApi })
}, HOOK_TIMEOUT)
Expand Down

1 comment on commit faa6ad2

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📊 Benchmark results

  • Dependency count: 1,320
  • Package size: 275 MB

Please sign in to comment.