diff --git a/compatibility-tests/sdk-test-node/package.json b/compatibility-tests/sdk-test-node/package.json index abfa750b34..fd9bb1faf5 100644 --- a/compatibility-tests/sdk-test-node/package.json +++ b/compatibility-tests/sdk-test-node/package.json @@ -8,6 +8,7 @@ }, "dependencies": { "@aws-sdk/client-acm": "^3.500.0", + "@aws-sdk/client-api-gateway": "^3.500.0", "@aws-sdk/client-apigatewaymanagementapi": "^3.500.0", "@aws-sdk/client-apigatewayv2": "^3.500.0", "@aws-sdk/client-cloudformation": "^3.500.0", diff --git a/compatibility-tests/sdk-test-node/tests/apigateway.test.ts b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts new file mode 100644 index 0000000000..381f9377f1 --- /dev/null +++ b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts @@ -0,0 +1,747 @@ +/** + * API Gateway v1 (REST API) compatibility tests. + * + * Covers management-plane CRUD (RestApis, Resources, Methods, Integrations, + * Authorizers, Deployments, Stages) and execute-api data-plane behaviour, + * including the REQUEST authorizer full-event shape. + * + * Uses @aws-sdk/client-api-gateway for management-plane calls and the native + * fetch API for execute-api invocations (which are plain HTTP, not SDK calls). + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { + APIGatewayClient, + CreateRestApiCommand, + GetRestApiCommand, + GetRestApisCommand, + DeleteRestApiCommand, + GetResourcesCommand, + CreateAuthorizerCommand, + GetAuthorizerCommand, + GetAuthorizersCommand, + AuthorizerType, +} from '@aws-sdk/client-api-gateway'; +import { + LambdaClient, + CreateFunctionCommand, + DeleteFunctionCommand, +} from '@aws-sdk/client-lambda'; +import { makeClient, uniqueName, ENDPOINT, ACCOUNT, REGION, buildMinimalZip } from './setup'; + +// ──────────────────────────── helpers ──────────────────────────── + +/** POST a raw JSON body to the Floci management plane (no SDK needed for simple calls). */ +async function apigwFetch(path: string, method = 'GET', body?: unknown): Promise { + return fetch(`${ENDPOINT}${path}`, { + method, + headers: { 'Content-Type': 'application/json' }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); +} + +/** Invoke the execute-api data plane and return the raw Response. */ +async function executeApi( + apiId: string, + stage: string, + resourcePath: string, + opts: { method?: string; headers?: Record; query?: string } = {} +): Promise { + const { method = 'GET', headers = {}, query = '' } = opts; + const qs = query ? `?${query}` : ''; + return fetch(`${ENDPOINT}/execute-api/${apiId}/${stage}${resourcePath}${qs}`, { + method, + headers, + }); +} + +/** Create a Node.js Lambda function with the given inline handler source. */ +async function createLambda(lambda: LambdaClient, name: string, handlerSrc: string): Promise { + const zip = buildMinimalZip('index.js', Buffer.from(handlerSrc)); + await lambda.send(new CreateFunctionCommand({ + FunctionName: name, + Runtime: 'nodejs20.x', + Role: `arn:aws:iam::${ACCOUNT}:role/lambda-role`, + Handler: 'index.handler', + Code: { ZipFile: zip }, + Timeout: 30, + })); +} + +/** Delete a Lambda function, ignoring 404. */ +async function deleteLambda(lambda: LambdaClient, name: string): Promise { + try { await lambda.send(new DeleteFunctionCommand({ FunctionName: name })); } catch { /* ignore */ } +} + +// ──────────────────────────── Management-plane CRUD ──────────────────────────── + +describe('API Gateway v1 — management plane', () => { + let gw: APIGatewayClient; + + beforeAll(() => { + gw = makeClient(APIGatewayClient); + }); + + describe('RestApi lifecycle', () => { + let apiId: string; + + afterAll(async () => { + try { if (apiId) await gw.send(new DeleteRestApiCommand({ restApiId: apiId })); } catch { /* ignore */ } + }); + + it('should create a REST API', async () => { + const res = await gw.send(new CreateRestApiCommand({ name: uniqueName('rest-api') })); + apiId = res.id!; + expect(apiId).toBeTruthy(); + expect(res.name).toContain('rest-api'); + }); + + it('should get the REST API', async () => { + const res = await gw.send(new GetRestApiCommand({ restApiId: apiId })); + expect(res.id).toBe(apiId); + }); + + it('should list REST APIs including the created one', async () => { + const res = await gw.send(new GetRestApisCommand({})); + expect(res.items?.some(a => a.id === apiId)).toBe(true); + }); + + it('should delete the REST API', async () => { + await gw.send(new DeleteRestApiCommand({ restApiId: apiId })); + await expect(gw.send(new GetRestApiCommand({ restApiId: apiId }))).rejects.toThrow(); + apiId = ''; + }); + }); + + describe('Authorizer CRUD', () => { + let apiId: string; + let authorizerId: string; + + beforeAll(async () => { + const res = await gw.send(new CreateRestApiCommand({ name: uniqueName('auth-crud') })); + apiId = res.id!; + }); + + afterAll(async () => { + try { await gw.send(new DeleteRestApiCommand({ restApiId: apiId })); } catch { /* ignore */ } + }); + + it('should create a TOKEN authorizer', async () => { + const res = await gw.send(new CreateAuthorizerCommand({ + restApiId: apiId, + name: 'token-auth', + type: AuthorizerType.TOKEN, + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:dummy/invocations`, + identitySource: 'method.request.header.Authorization', + authorizerResultTtlInSeconds: 0, + })); + authorizerId = res.id!; + expect(authorizerId).toBeTruthy(); + expect(res.type).toBe(AuthorizerType.TOKEN); + }); + + it('should get the authorizer', async () => { + const res = await gw.send(new GetAuthorizerCommand({ restApiId: apiId, authorizerId })); + expect(res.id).toBe(authorizerId); + expect(res.type).toBe(AuthorizerType.TOKEN); + }); + + it('should list authorizers', async () => { + const res = await gw.send(new GetAuthorizersCommand({ restApiId: apiId })); + expect(res.items?.some(a => a.id === authorizerId)).toBe(true); + }); + }); +}); + +// ──────────────────────────── Execute-API data plane ──────────────────────────── + +describe('API Gateway v1 — execute-api data plane', () => { + let gw: APIGatewayClient; + let lambda: LambdaClient; + + // Shared API wired up in beforeAll + let apiId: string; + let itemResourceId: string; + let secureResourceId: string; + let openResourceId: string; + + // Lambda function names + const echoAuthFn = uniqueName('req-auth-echo'); + const tokenAuthFn = uniqueName('tok-auth-echo'); + const denyAuthFn = uniqueName('deny-auth'); + const proxyFn = uniqueName('proxy-echo'); + const simpleFn = uniqueName('simple-fn'); + + beforeAll(async () => { + gw = makeClient(APIGatewayClient); + lambda = makeClient(LambdaClient); + + // ── Lambda: REQUEST authorizer — echoes received event into policy context ── + await createLambda(lambda, echoAuthFn, ` + exports.handler = async (event) => ({ + principalId: 'user', + policyDocument: { + Version: '2012-10-17', + Statement: [{ Action: 'execute-api:Invoke', Effect: 'Allow', Resource: event.methodArn }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + `); + + // ── Lambda: TOKEN authorizer — echoes received event into policy context ── + await createLambda(lambda, tokenAuthFn, ` + exports.handler = async (event) => ({ + principalId: 'user', + policyDocument: { + Version: '2012-10-17', + Statement: [{ Action: 'execute-api:Invoke', Effect: 'Allow', Resource: event.methodArn }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + `); + + // ── Lambda: REQUEST authorizer — always Deny ── + await createLambda(lambda, denyAuthFn, ` + exports.handler = async (event) => ({ + principalId: 'user', + policyDocument: { + Version: '2012-10-17', + Statement: [{ Action: 'execute-api:Invoke', Effect: 'Deny', Resource: event.methodArn }] + } + }); + `); + + // ── Lambda: proxy integration — returns authorizer context so tests can inspect it ── + await createLambda(lambda, proxyFn, ` + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ + authorizer: event.requestContext?.authorizer ?? null + }) + }); + `); + + // ── Lambda: simple integration — returns { invoked: true } ── + await createLambda(lambda, simpleFn, ` + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ invoked: true }) + }); + `); + + // ── Build the REST API ── + const api = await gw.send(new CreateRestApiCommand({ name: uniqueName('exec-api-test') })); + apiId = api.id!; + + const resources = await gw.send(new GetResourcesCommand({ restApiId: apiId })); + const rootId = resources.items![0].id!; + + // /items + const itemsRes = await apigwFetch(`/restapis/${apiId}/resources/${rootId}`, 'POST', { pathPart: 'items' }); + const itemsId = (await itemsRes.json() as { id: string }).id; + + // /items/{id} + const itemRes = await apigwFetch(`/restapis/${apiId}/resources/${itemsId}`, 'POST', { pathPart: '{id}' }); + itemResourceId = (await itemRes.json() as { id: string }).id; + + // /secure (TOKEN authorizer) + const secureRes = await apigwFetch(`/restapis/${apiId}/resources/${rootId}`, 'POST', { pathPart: 'secure' }); + secureResourceId = (await secureRes.json() as { id: string }).id; + + // /open (NONE authorizer) + const openRes = await apigwFetch(`/restapis/${apiId}/resources/${rootId}`, 'POST', { pathPart: 'open' }); + openResourceId = (await openRes.json() as { id: string }).id; + + // ── REQUEST authorizer ── + const reqAuthRes = await apigwFetch(`/restapis/${apiId}/authorizers`, 'POST', { + name: 'req-echo-auth', + type: 'REQUEST', + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${echoAuthFn}/invocations`, + identitySource: 'method.request.header.Authorization', + authorizerResultTtlInSeconds: 0, + }); + const reqAuthId = (await reqAuthRes.json() as { id: string }).id; + + // ── TOKEN authorizer ── + const tokAuthRes = await apigwFetch(`/restapis/${apiId}/authorizers`, 'POST', { + name: 'tok-echo-auth', + type: 'TOKEN', + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${tokenAuthFn}/invocations`, + identitySource: 'method.request.header.Authorization', + authorizerResultTtlInSeconds: 0, + }); + const tokAuthId = (await tokAuthRes.json() as { id: string }).id; + + const proxyUri = `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${proxyFn}/invocations`; + const simpleUri = `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${simpleFn}/invocations`; + + // GET /items/{id} — REQUEST authorizer + proxy integration + await apigwFetch(`/restapis/${apiId}/resources/${itemResourceId}/methods/GET`, 'PUT', { + authorizationType: 'CUSTOM', + authorizerId: reqAuthId, + }); + await apigwFetch(`/restapis/${apiId}/resources/${itemResourceId}/methods/GET/integration`, 'PUT', { + type: 'AWS_PROXY', + httpMethod: 'POST', + uri: proxyUri, + }); + + // GET /secure — TOKEN authorizer + proxy integration + await apigwFetch(`/restapis/${apiId}/resources/${secureResourceId}/methods/GET`, 'PUT', { + authorizationType: 'CUSTOM', + authorizerId: tokAuthId, + }); + await apigwFetch(`/restapis/${apiId}/resources/${secureResourceId}/methods/GET/integration`, 'PUT', { + type: 'AWS_PROXY', + httpMethod: 'POST', + uri: proxyUri, + }); + + // GET /open — NONE authorizer + simple integration + await apigwFetch(`/restapis/${apiId}/resources/${openResourceId}/methods/GET`, 'PUT', { + authorizationType: 'NONE', + }); + await apigwFetch(`/restapis/${apiId}/resources/${openResourceId}/methods/GET/integration`, 'PUT', { + type: 'AWS_PROXY', + httpMethod: 'POST', + uri: simpleUri, + }); + + // ── Deploy ── + const depRes = await apigwFetch(`/restapis/${apiId}/deployments`, 'POST', { description: 'compat-test' }); + const depId = (await depRes.json() as { id: string }).id; + await apigwFetch(`/restapis/${apiId}/stages`, 'POST', { stageName: 'prod', deploymentId: depId }); + }); + + afterAll(async () => { + try { if (apiId) await gw.send(new DeleteRestApiCommand({ restApiId: apiId })); } catch { /* ignore */ } + await deleteLambda(lambda, echoAuthFn); + await deleteLambda(lambda, tokenAuthFn); + await deleteLambda(lambda, denyAuthFn); + await deleteLambda(lambda, proxyFn); + await deleteLambda(lambda, simpleFn); + }); + + // ──────────────────────────── REQUEST authorizer event shape ──────────────────────────── + + describe('REQUEST authorizer — full event shape', () => { + let receivedEvent: Record; + + beforeAll(async () => { + const res = await executeApi(apiId, 'prod', '/items/42', { + headers: { Authorization: 'Bearer test-token', 'X-Custom-Header': 'hello' }, + query: 'foo=bar&baz=qux', + }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + receivedEvent = JSON.parse(body.authorizer.receivedEvent) as Record; + }); + + it('should include type=REQUEST and methodArn', () => { + expect(receivedEvent.type).toBe('REQUEST'); + expect(typeof receivedEvent.methodArn).toBe('string'); + expect(receivedEvent.methodArn as string).toContain(apiId); + }); + + it('should include the matched resource path template', () => { + expect(receivedEvent.resource).toBe('/items/{id}'); + }); + + it('should include the actual request path', () => { + expect(receivedEvent.path).toBe('/items/42'); + }); + + it('should include the HTTP method', () => { + expect(receivedEvent.httpMethod).toBe('GET'); + }); + + it('should include a non-null headers map', () => { + expect(receivedEvent.headers).toBeTruthy(); + expect(typeof receivedEvent.headers).toBe('object'); + const headers = receivedEvent.headers as Record; + expect(headers['Authorization']).toBe('Bearer test-token'); + expect(headers['X-Custom-Header']).toBe('hello'); + }); + + it('should include a multiValueHeaders map', () => { + expect(receivedEvent.multiValueHeaders).toBeTruthy(); + const mvh = receivedEvent.multiValueHeaders as Record; + expect(Array.isArray(mvh['Authorization'])).toBe(true); + expect(mvh['Authorization'][0]).toBe('Bearer test-token'); + }); + + it('should include queryStringParameters with all query params', () => { + expect(receivedEvent.queryStringParameters).toBeTruthy(); + const qsp = receivedEvent.queryStringParameters as Record; + expect(qsp.foo).toBe('bar'); + expect(qsp.baz).toBe('qux'); + }); + + it('should include multiValueQueryStringParameters', () => { + expect(receivedEvent.multiValueQueryStringParameters).toBeTruthy(); + const mqsp = receivedEvent.multiValueQueryStringParameters as Record; + expect(Array.isArray(mqsp.foo)).toBe(true); + expect(mqsp.foo[0]).toBe('bar'); + }); + + it('should include pathParameters with the id segment', () => { + expect(receivedEvent.pathParameters).toBeTruthy(); + const pp = receivedEvent.pathParameters as Record; + expect(pp.id).toBe('42'); + }); + + it('should include stageVariables as null', () => { + expect(receivedEvent.stageVariables).toBeNull(); + }); + + it('should include a requestContext with requestId', () => { + expect(receivedEvent.requestContext).toBeTruthy(); + const ctx = receivedEvent.requestContext as Record; + expect(typeof ctx.requestId).toBe('string'); + expect((ctx.requestId as string).length).toBeGreaterThan(0); + }); + + it('should include requestContext.identity.sourceIp', () => { + const ctx = receivedEvent.requestContext as Record; + const identity = ctx.identity as Record; + expect(identity.sourceIp).toBe('127.0.0.1'); + }); + + it('should include requestContext.resourcePath', () => { + const ctx = receivedEvent.requestContext as Record; + expect(ctx.resourcePath).toBe('/items/{id}'); + }); + + it('should include requestContext.httpMethod', () => { + const ctx = receivedEvent.requestContext as Record; + expect(ctx.httpMethod).toBe('GET'); + }); + + it('should include requestContext.stage', () => { + const ctx = receivedEvent.requestContext as Record; + expect(ctx.stage).toBe('prod'); + }); + + it('should include requestContext.accountId', () => { + const ctx = receivedEvent.requestContext as Record; + expect(typeof ctx.accountId).toBe('string'); + expect((ctx.accountId as string).length).toBeGreaterThan(0); + }); + + it('should include requestContext.apiId', () => { + const ctx = receivedEvent.requestContext as Record; + expect(ctx.apiId).toBe(apiId); + }); + + it('should include requestContext.resourceId as a non-empty string', () => { + const ctx = receivedEvent.requestContext as Record; + expect(typeof ctx.resourceId).toBe('string'); + expect((ctx.resourceId as string).length).toBeGreaterThan(0); + }); + + it('should include requestContext.path equal to the actual request path', () => { + const ctx = receivedEvent.requestContext as Record; + expect(ctx.path).toBe('/items/42'); + }); + + it('should include requestContext.identity.apiKey as null when no usage plan key matches', () => { + const ctx = receivedEvent.requestContext as Record; + const identity = ctx.identity as Record; + expect(Object.prototype.hasOwnProperty.call(identity, 'apiKey')).toBe(true); + expect(identity.apiKey).toBeNull(); + }); + }); + + describe('REQUEST authorizer — no query params', () => { + it('should set queryStringParameters to null when no query string is present', async () => { + const res = await executeApi(apiId, 'prod', '/items/99', { + headers: { Authorization: 'Bearer test' }, + }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + const event = JSON.parse(body.authorizer.receivedEvent) as Record; + expect(event.queryStringParameters).toBeNull(); + expect(event.multiValueQueryStringParameters).toBeNull(); + }); + }); + + // ──────────────────────────── TOKEN authorizer preservation ──────────────────────────── + + describe('TOKEN authorizer — event shape preserved', () => { + let receivedEvent: Record; + + beforeAll(async () => { + const res = await executeApi(apiId, 'prod', '/secure', { + headers: { Authorization: 'Bearer my-secret-token' }, + }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + receivedEvent = JSON.parse(body.authorizer.receivedEvent) as Record; + }); + + it('should include type=TOKEN', () => { + expect(receivedEvent.type).toBe('TOKEN'); + }); + + it('should include methodArn', () => { + expect(typeof receivedEvent.methodArn).toBe('string'); + expect((receivedEvent.methodArn as string).length).toBeGreaterThan(0); + }); + + it('should include authorizationToken equal to the Authorization header value', () => { + expect(receivedEvent.authorizationToken).toBe('Bearer my-secret-token'); + }); + + it('should NOT include headers, queryStringParameters, or requestContext', () => { + // TOKEN authorizer event must contain exactly type, methodArn, authorizationToken + expect(receivedEvent.headers == null).toBe(true); + expect(receivedEvent.queryStringParameters == null).toBe(true); + expect(receivedEvent.requestContext == null).toBe(true); + }); + }); + + // ──────────────────────────── NONE authorizer preservation ──────────────────────────── + + describe('NONE authorizer — skips authorizer invocation', () => { + it('should invoke the integration directly without an Authorization header', async () => { + const res = await executeApi(apiId, 'prod', '/open'); + expect(res.status).toBe(200); + const body = await res.json() as { invoked: boolean }; + expect(body.invoked).toBe(true); + }); + }); + + // ──────────────────────────── Allow / Deny policy ──────────────────────────── + + describe('REQUEST authorizer — Allow policy forwards to integration', () => { + it('should return HTTP 200 when the authorizer returns Allow', async () => { + const res = await executeApi(apiId, 'prod', '/items/1', { + headers: { Authorization: 'Bearer allow-me' }, + }); + expect(res.status).toBe(200); + }); + }); + + describe('REQUEST authorizer — Deny policy returns 403', () => { + let denyApiId: string; + + beforeAll(async () => { + // Build a separate API with only the deny authorizer to avoid interfering with other tests + const api = await gw.send(new CreateRestApiCommand({ name: uniqueName('deny-api') })); + denyApiId = api.id!; + + const resources = await gw.send(new GetResourcesCommand({ restApiId: denyApiId })); + const rootId = resources.items![0].id!; + + const protectedRes = await apigwFetch(`/restapis/${denyApiId}/resources/${rootId}`, 'POST', { pathPart: 'protected' }); + const protectedId = (await protectedRes.json() as { id: string }).id; + + const denyAuthRes = await apigwFetch(`/restapis/${denyApiId}/authorizers`, 'POST', { + name: 'deny-auth', + type: 'REQUEST', + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${denyAuthFn}/invocations`, + identitySource: 'method.request.header.Authorization', + authorizerResultTtlInSeconds: 0, + }); + const denyAuthId = (await denyAuthRes.json() as { id: string }).id; + + await apigwFetch(`/restapis/${denyApiId}/resources/${protectedId}/methods/GET`, 'PUT', { + authorizationType: 'CUSTOM', + authorizerId: denyAuthId, + }); + await apigwFetch(`/restapis/${denyApiId}/resources/${protectedId}/methods/GET/integration`, 'PUT', { + type: 'MOCK', + requestTemplates: { 'application/json': '{"statusCode": 200}' }, + }); + await apigwFetch(`/restapis/${denyApiId}/resources/${protectedId}/methods/GET/responses/200`, 'PUT', { + responseParameters: {}, + }); + await apigwFetch(`/restapis/${denyApiId}/resources/${protectedId}/methods/GET/integration/responses/200`, 'PUT', { + selectionPattern: '', + responseTemplates: { 'application/json': '{"message":"ok"}' }, + }); + + const depRes = await apigwFetch(`/restapis/${denyApiId}/deployments`, 'POST', { description: 'deny-test' }); + const depId = (await depRes.json() as { id: string }).id; + await apigwFetch(`/restapis/${denyApiId}/stages`, 'POST', { stageName: 'prod', deploymentId: depId }); + }); + + afterAll(async () => { + try { if (denyApiId) await gw.send(new DeleteRestApiCommand({ restApiId: denyApiId })); } catch { /* ignore */ } + }); + + it('should return HTTP 403 when the authorizer returns Deny', async () => { + const res = await executeApi(denyApiId, 'prod', '/protected', { + headers: { Authorization: 'Bearer any-token' }, + }); + expect(res.status).toBe(403); + }); + }); + + // ──────────────────────────── Stage Variables ──────────────────────────── + + describe('Stage variables — populated in authorizer and proxy events', () => { + let svApiId: string; + + beforeAll(async () => { + const svAuthName = uniqueName('sv-auth'); + const svProxyName = uniqueName('sv-proxy'); + await createLambda(lambda, svAuthName, ` + exports.handler = async (event) => ({ + principalId: 'user', + policyDocument: { Version: '2012-10-17', Statement: [{ Action: 'execute-api:Invoke', Effect: 'Allow', Resource: event.methodArn }] }, + context: { receivedEvent: JSON.stringify(event) } + }); + `); + await createLambda(lambda, svProxyName, ` + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ stageVariables: event.stageVariables, authorizer: event.requestContext?.authorizer ?? null }) + }); + `); + + const api = await gw.send(new CreateRestApiCommand({ name: uniqueName('sv-api') })); + svApiId = api.id!; + const resources = await gw.send(new GetResourcesCommand({ restApiId: svApiId })); + const rootId = resources.items![0].id!; + const pingRes = await apigwFetch(`/restapis/${svApiId}/resources/${rootId}`, 'POST', { pathPart: 'ping' }); + const pingId = (await pingRes.json() as { id: string }).id; + + const authRes = await apigwFetch(`/restapis/${svApiId}/authorizers`, 'POST', { + name: 'sv-auth', type: 'REQUEST', + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${svAuthName}/invocations`, + identitySource: 'method.request.header.Authorization', authorizerResultTtlInSeconds: 0, + }); + const svAuthId = (await authRes.json() as { id: string }).id; + + await apigwFetch(`/restapis/${svApiId}/resources/${pingId}/methods/GET`, 'PUT', { authorizationType: 'CUSTOM', authorizerId: svAuthId }); + await apigwFetch(`/restapis/${svApiId}/resources/${pingId}/methods/GET/integration`, 'PUT', { + type: 'AWS_PROXY', httpMethod: 'POST', + uri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${svProxyName}/invocations`, + }); + + const depRes = await apigwFetch(`/restapis/${svApiId}/deployments`, 'POST', { description: 'sv-test' }); + const depId = (await depRes.json() as { id: string }).id; + // Create stage WITH variables + await apigwFetch(`/restapis/${svApiId}/stages`, 'POST', { + stageName: 'prod', deploymentId: depId, + variables: { env: 'test', version: 'v1' }, + }); + }); + + afterAll(async () => { + try { if (svApiId) await gw.send(new DeleteRestApiCommand({ restApiId: svApiId })); } catch { /* ignore */ } + }); + + it('should populate stageVariables in the proxy event from the stage configuration', async () => { + const res = await executeApi(svApiId, 'prod', '/ping', { headers: { Authorization: 'Bearer t' } }); + expect(res.status).toBe(200); + const body = await res.json() as { stageVariables: Record; authorizer: { receivedEvent: string } }; + expect(body.stageVariables).toBeTruthy(); + expect(body.stageVariables.env).toBe('test'); + expect(body.stageVariables.version).toBe('v1'); + }); + + it('should populate stageVariables in the REQUEST authorizer event', async () => { + const res = await executeApi(svApiId, 'prod', '/ping', { headers: { Authorization: 'Bearer t' } }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + const event = JSON.parse(body.authorizer.receivedEvent) as Record; + const sv = event.stageVariables as Record; + expect(sv).toBeTruthy(); + expect(sv.env).toBe('test'); + expect(sv.version).toBe('v1'); + }); + }); + + // ──────────────────────────── API Key Resolution ──────────────────────────── + + describe('API key — identity.apiKey resolved from usage plan', () => { + let akApiId: string; + const testKeyValue = uniqueName('ak'); + + beforeAll(async () => { + const akAuthName = uniqueName('ak-auth'); + const akProxyName = uniqueName('ak-proxy'); + await createLambda(lambda, akAuthName, ` + exports.handler = async (event) => ({ + principalId: 'user', + policyDocument: { Version: '2012-10-17', Statement: [{ Action: 'execute-api:Invoke', Effect: 'Allow', Resource: event.methodArn }] }, + context: { receivedEvent: JSON.stringify(event) } + }); + `); + await createLambda(lambda, akProxyName, ` + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ authorizer: event.requestContext?.authorizer ?? null }) + }); + `); + + const api = await gw.send(new CreateRestApiCommand({ name: uniqueName('ak-api') })); + akApiId = api.id!; + const resources = await gw.send(new GetResourcesCommand({ restApiId: akApiId })); + const rootId = resources.items![0].id!; + const secRes = await apigwFetch(`/restapis/${akApiId}/resources/${rootId}`, 'POST', { pathPart: 'secure' }); + const secId = (await secRes.json() as { id: string }).id; + + const authRes = await apigwFetch(`/restapis/${akApiId}/authorizers`, 'POST', { + name: 'ak-auth', type: 'REQUEST', + authorizerUri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${akAuthName}/invocations`, + identitySource: 'method.request.header.Authorization', authorizerResultTtlInSeconds: 0, + }); + const akAuthId = (await authRes.json() as { id: string }).id; + + await apigwFetch(`/restapis/${akApiId}/resources/${secId}/methods/GET`, 'PUT', { authorizationType: 'CUSTOM', authorizerId: akAuthId }); + await apigwFetch(`/restapis/${akApiId}/resources/${secId}/methods/GET/integration`, 'PUT', { + type: 'AWS_PROXY', httpMethod: 'POST', + uri: `arn:aws:apigateway:${REGION}:lambda:path/2015-03-31/functions/arn:aws:lambda:${REGION}:${ACCOUNT}:function:${akProxyName}/invocations`, + }); + + const depRes = await apigwFetch(`/restapis/${akApiId}/deployments`, 'POST', { description: 'ak-test' }); + const depId = (await depRes.json() as { id: string }).id; + await apigwFetch(`/restapis/${akApiId}/stages`, 'POST', { stageName: 'prod', deploymentId: depId }); + + // Create API key + usage plan linked to (akApiId, prod) + const keyRes = await apigwFetch('/apikeys', 'POST', { name: uniqueName('key'), value: testKeyValue, enabled: true }); + const keyId = (await keyRes.json() as { id: string }).id; + const planRes = await apigwFetch('/usageplans', 'POST', { name: uniqueName('plan'), apiStages: [{ apiId: akApiId, stage: 'prod' }] }); + const planId = (await planRes.json() as { id: string }).id; + await apigwFetch(`/usageplans/${planId}/keys`, 'POST', { keyId, keyType: 'API_KEY' }); + }); + + afterAll(async () => { + try { if (akApiId) await gw.send(new DeleteRestApiCommand({ restApiId: akApiId })); } catch { /* ignore */ } + }); + + it('should populate identity.apiKey when x-api-key header matches a usage plan key', async () => { + const res = await executeApi(akApiId, 'prod', '/secure', { + headers: { Authorization: 'Bearer t', 'x-api-key': testKeyValue }, + }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + const event = JSON.parse(body.authorizer.receivedEvent) as Record; + const identity = (event.requestContext as Record).identity as Record; + expect(identity.apiKey).toBe(testKeyValue); + }); + + it('should set identity.apiKey to null when x-api-key header is absent', async () => { + const res = await executeApi(akApiId, 'prod', '/secure', { headers: { Authorization: 'Bearer t' } }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + const event = JSON.parse(body.authorizer.receivedEvent) as Record; + const identity = (event.requestContext as Record).identity as Record; + expect(identity.apiKey).toBeNull(); + }); + + it('should set identity.apiKey to null when x-api-key does not match any plan key', async () => { + const res = await executeApi(akApiId, 'prod', '/secure', { + headers: { Authorization: 'Bearer t', 'x-api-key': 'wrong-key' }, + }); + expect(res.status).toBe(200); + const body = await res.json() as { authorizer: { receivedEvent: string } }; + const event = JSON.parse(body.authorizer.receivedEvent) as Record; + const identity = (event.requestContext as Record).identity as Record; + expect(identity.apiKey).toBeNull(); + }); + }); +}); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index 8f8bb12b61..ea2c644109 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -8,6 +8,9 @@ import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; import io.github.hectorvent.floci.services.apigateway.model.Integration; import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse; import io.github.hectorvent.floci.services.apigateway.model.MethodConfig; +import io.github.hectorvent.floci.services.apigateway.model.Stage; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlan; +import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer; import io.github.hectorvent.floci.services.apigatewayv2.model.Route; @@ -22,6 +25,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.smallrye.common.annotation.Blocking; import jakarta.enterprise.context.ApplicationScoped; @@ -237,9 +241,10 @@ public class ApiGatewayExecuteController { } // Verify API and stage exist + Stage stage; try { apiGatewayService.getRestApi(region, apiId); - apiGatewayService.getStage(region, apiId, stageName); + stage = apiGatewayService.getStage(region, apiId, stageName); } catch (AwsException e) { return Response.status(e.getHttpStatus()) .entity(jsonMessage(e.getMessage())) @@ -268,7 +273,8 @@ public class ApiGatewayExecuteController { } // 1. Authorizer - AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, method, headers, uriInfo); + String resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers); + AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey); if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse(); // 2. Request validation @@ -286,8 +292,8 @@ public class ApiGatewayExecuteController { integration.getType()); return switch (integration.getType().toUpperCase()) { - case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName, - matched, integration, headers, uriInfo, body, authorizerResult); + case "AWS_PROXY" -> invokeProxy(region, apiId, httpMethod, path, proxy, stageName, + matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey); case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName, matched, integration, headers, uriInfo, body); case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body); @@ -299,11 +305,12 @@ public class ApiGatewayExecuteController { // ──────────────────────────── AWS_PROXY ──────────────────────────── - private Response invokeProxy(String region, String httpMethod, String path, String proxy, + private Response invokeProxy(String region, String apiId, String httpMethod, String path, String proxy, String stageName, ApiGatewayResource resource, + Stage stage, Integration integration, HttpHeaders headers, UriInfo uriInfo, byte[] body, - AuthorizerResult authorizerResult) { + AuthorizerResult authorizerResult, String resolvedApiKey) { String functionName = functionNameFromUri(integration.getUri()); if (functionName == null) { return Response.status(500) @@ -312,9 +319,9 @@ public class ApiGatewayExecuteController { } String requestId = UUID.randomUUID().toString(); - String eventJson = buildProxyEvent(httpMethod, path, proxy, resource.getPath(), - stageName, headers, uriInfo, body, requestId, - authorizerResult.principalId(), authorizerResult.context()); + String eventJson = buildProxyEvent(region, apiId, httpMethod, path, proxy, resource.getPath(), + resource.getId(), stageName, stage, headers, uriInfo, body, requestId, + authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey); try { InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(), @@ -331,8 +338,11 @@ public class ApiGatewayExecuteController { } private AuthorizerResult invokeAuthorizer(String region, String apiId, String stageName, - String httpMethod, String requestPath, MethodConfig method, - HttpHeaders headers, UriInfo uriInfo) { + String httpMethod, String requestPath, String resourcePath, + String resourceId, + Stage stage, + MethodConfig method, + HttpHeaders headers, UriInfo uriInfo, String resolvedApiKey) { if ("CUSTOM".equals(method.getAuthorizationType())) { String authorizerId = method.getAuthorizerId(); if (authorizerId == null) { @@ -345,7 +355,7 @@ public class ApiGatewayExecuteController { return new AuthorizerResult(null, null, null); } - String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath); + String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath, resourcePath, resourceId, stage, uriInfo, resolvedApiKey); try { InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse); if (result.getFunctionError() != null) { @@ -471,17 +481,91 @@ public class ApiGatewayExecuteController { private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers, String region, String apiId, String stageName, - String httpMethod, String requestPath) { + String httpMethod, String requestPath, + String resourcePath, String resourceId, Stage stage, UriInfo uriInfo, + String resolvedApiKey) { ObjectNode node = objectMapper.createObjectNode(); node.put("type", auth.getType()); node.put("methodArn", buildMethodArn(region, apiId, stageName, httpMethod, requestPath)); if ("TOKEN".equals(auth.getType())) { String headerName = auth.getIdentitySource().replace("method.request.header.", ""); node.put("authorizationToken", headers.getHeaderString(headerName)); + } else if ("REQUEST".equals(auth.getType())) { + node.put("resource", resourcePath); + node.put("path", requestPath); + node.put("httpMethod", httpMethod); + putSingleValueHeaders(node, headers); + putMultiValueHeaders(node, headers); + putQueryStringParameters(node, uriInfo); + putMultiValueQueryStringParameters(node, uriInfo); + + Map pathParams = extractPathParams(resourcePath, requestPath); + ObjectNode ppNode = node.putObject("pathParameters"); + if (!pathParams.isEmpty()) { + pathParams.forEach(ppNode::put); + } + + // stageVariables: populate from the Stage object (null if no variables configured) + Map stageVars = stage != null ? stage.getVariables() : null; + if (stageVars != null && !stageVars.isEmpty()) { + ObjectNode svNode = node.putObject("stageVariables"); + stageVars.forEach(svNode::put); + } else { + node.putNull("stageVariables"); + } + + ObjectNode ctx = node.putObject("requestContext"); + ctx.put("accountId", regionResolver.getAccountId()); + ctx.put("apiId", apiId); + ctx.put("resourceId", resourceId != null ? resourceId : ""); + ctx.put("resourcePath", resourcePath); + ctx.put("path", requestPath); + ctx.put("httpMethod", httpMethod); + ctx.put("stage", stageName); + ctx.put("requestId", UUID.randomUUID().toString()); + ctx.put("requestTimeEpoch", System.currentTimeMillis()); + + // identity.apiKey: resolve from usage plans linked to this (apiId, stage) + ObjectNode identity = ctx.putObject("identity"); + identity.put("sourceIp", "127.0.0.1"); + String userAgent = headers.getHeaderString("User-Agent"); + identity.put("userAgent", userAgent != null ? userAgent : ""); + if (resolvedApiKey != null) { + identity.put("apiKey", resolvedApiKey); + } else { + identity.putNull("apiKey"); + } + identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS) } return node.toString(); } + /** + * Resolves the API key value for a request by matching the {@code x-api-key} header + * against usage plan keys linked to this (apiId, stageName) pair. + * + *

Returns the key value string if a matching enabled key is found, {@code null} otherwise. + */ + private String resolveApiKeyForRequest(String region, String apiId, String stageName, HttpHeaders headers) { + String keyHeader = headers.getHeaderString("x-api-key"); + if (keyHeader == null || keyHeader.isBlank()) { + return null; + } + // Find all usage plans that include this (apiId, stage) pair + for (UsagePlan plan : apiGatewayService.getUsagePlans(region)) { + boolean planCoversStage = plan.getApiStages().stream() + .anyMatch(s -> apiId.equals(s.apiId()) && stageName.equals(s.stage())); + if (!planCoversStage) continue; + // Check if any key in this plan matches the header value + for (UsagePlanKey planKey : apiGatewayService.getUsagePlanKeys(region, plan.getId())) { + if (keyHeader.equals(planKey.getValue())) { + return planKey.getValue(); + } + } + } + return null; + } + private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) { String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", ""); String arnRegion = region == null ? regionResolver.getDefaultRegion() : region; @@ -497,45 +581,91 @@ public class ApiGatewayExecuteController { return LambdaArnUtils.extractFunctionNameFromUri(uri); } - private String buildProxyEvent(String httpMethod, String path, String proxy, - String resourcePath, String stageName, + private String buildProxyEvent(String region, String apiId, + String httpMethod, String path, String proxy, + String resourcePath, String resourceId, + String stageName, Stage stage, HttpHeaders headers, UriInfo uriInfo, byte[] body, String requestId, - String principalId, Map authorizerContext) { + String principalId, Map authorizerContext, + String resolvedApiKey) { ObjectNode event = objectMapper.createObjectNode(); event.put("resource", resourcePath); event.put("path", path); event.put("httpMethod", httpMethod); - ObjectNode headersNode = event.putObject("headers"); - MultivaluedMap reqHeaders = headers.getRequestHeaders(); - for (Map.Entry> e : reqHeaders.entrySet()) { - if (!e.getValue().isEmpty()) headersNode.put(e.getKey(), e.getValue().get(0)); - } - - MultivaluedMap queryParams = uriInfo.getQueryParameters(); - if (!queryParams.isEmpty()) { - ObjectNode qsp = event.putObject("queryStringParameters"); - for (Map.Entry> e : queryParams.entrySet()) { - if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0)); - } - } else { - event.putNull("queryStringParameters"); - } + putSingleValueHeaders(event, headers); + putMultiValueHeaders(event, headers); + putQueryStringParameters(event, uriInfo); + putMultiValueQueryStringParameters(event, uriInfo); ObjectNode pathParams = event.putObject("pathParameters"); if (proxy != null && !proxy.isEmpty()) pathParams.put("proxy", proxy); extractPathParams(resourcePath, path).forEach(pathParams::put); - event.putNull("stageVariables"); + // stageVariables: populate from the Stage object (null if no variables configured) + Map stageVars = stage != null ? stage.getVariables() : null; + if (stageVars != null && !stageVars.isEmpty()) { + ObjectNode svNode = event.putObject("stageVariables"); + stageVars.forEach(svNode::put); + } else { + event.putNull("stageVariables"); + } + + String arnRegion = region != null ? region : regionResolver.getDefaultRegion(); + String domainName = apiId + ".execute-api." + arnRegion + ".amazonaws.com"; + long nowMillis = System.currentTimeMillis(); + String requestTime = java.time.format.DateTimeFormatter + .ofPattern("dd/MMM/yyyy:HH:mm:ss Z") + .format(java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC)); ObjectNode ctx = event.putObject("requestContext"); - ctx.put("resourcePath", resourcePath); + ctx.put("accountId", regionResolver.getAccountId()); + ctx.put("apiId", apiId); + ctx.put("domainName", domainName); + ctx.put("domainPrefix", apiId); + ctx.put("extendedRequestId", requestId); ctx.put("httpMethod", httpMethod); - ctx.put("stage", stageName); + ctx.put("path", path); + ctx.put("protocol", "HTTP/1.1"); ctx.put("requestId", requestId); - ctx.put("requestTimeEpoch", System.currentTimeMillis()); - ctx.putObject("identity").put("sourceIp", "127.0.0.1"); + ctx.put("requestTime", requestTime); + ctx.put("requestTimeEpoch", nowMillis); + ctx.put("resourceId", resourceId != null ? resourceId : ""); + ctx.put("resourcePath", resourcePath); + ctx.put("stage", stageName); + + // identity — full shape matching AWS proxy event spec. + // Fields that require auth mechanisms not implemented in v1 REST API dispatch: + // - accessKey, accountId, caller, user, userArn, principalOrgId: only set for AWS_IAM auth + // (v1 dispatch does not implement AWS_IAM — invokeAuthorizer only handles CUSTOM) + // - cognitoIdentityId, cognitoIdentityPoolId, cognitoAuthenticationType, + // cognitoAuthenticationProvider: only set for COGNITO_USER_POOLS auth (not implemented in v1) + // - clientCert: only set when mutual TLS is configured (not supported in Floci) + // AWS sends these as explicit JSON null (not absent), so we match that wire format. + ObjectNode identity = ctx.putObject("identity"); + identity.putNull("accessKey"); + identity.putNull("accountId"); + identity.putNull("caller"); + identity.putNull("cognitoAuthenticationProvider"); + identity.putNull("cognitoAuthenticationType"); + identity.putNull("cognitoIdentityId"); + identity.putNull("cognitoIdentityPoolId"); + identity.putNull("principalOrgId"); + identity.put("sourceIp", "127.0.0.1"); + identity.putNull("user"); + String userAgent = headers.getHeaderString("User-Agent"); + identity.put("userAgent", userAgent != null ? userAgent : ""); + identity.putNull("userArn"); + identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS) + // apiKey: use pre-resolved value from usage plan keys linked to this (apiId, stage) + if (resolvedApiKey != null) { + identity.put("apiKey", resolvedApiKey); + } else { + identity.putNull("apiKey"); + } + + // authorizer context (set by CUSTOM authorizer) if (principalId != null || (authorizerContext != null && !authorizerContext.isEmpty())) { ObjectNode authorizerNode = ctx.putObject("authorizer"); if (principalId != null) { @@ -565,6 +695,46 @@ public class ApiGatewayExecuteController { } } + private void putSingleValueHeaders(ObjectNode event, HttpHeaders headers) { + ObjectNode headersNode = event.putObject("headers"); + headers.getRequestHeaders().forEach((name, values) -> { + if (!values.isEmpty()) headersNode.put(name, values.get(0)); + }); + } + + private void putMultiValueHeaders(ObjectNode event, HttpHeaders headers) { + ObjectNode mvHeaders = event.putObject("multiValueHeaders"); + headers.getRequestHeaders().forEach((name, values) -> { + ArrayNode arr = mvHeaders.putArray(name); + values.forEach(arr::add); + }); + } + + private void putQueryStringParameters(ObjectNode event, UriInfo uriInfo) { + MultivaluedMap queryParams = uriInfo.getQueryParameters(); + if (!queryParams.isEmpty()) { + ObjectNode qsp = event.putObject("queryStringParameters"); + queryParams.forEach((name, values) -> { + if (!values.isEmpty()) qsp.put(name, values.get(0)); + }); + } else { + event.putNull("queryStringParameters"); + } + } + + private void putMultiValueQueryStringParameters(ObjectNode event, UriInfo uriInfo) { + MultivaluedMap queryParams = uriInfo.getQueryParameters(); + if (!queryParams.isEmpty()) { + ObjectNode mqsp = event.putObject("multiValueQueryStringParameters"); + queryParams.forEach((name, values) -> { + ArrayNode arr = mqsp.putArray(name); + values.forEach(arr::add); + }); + } else { + event.putNull("multiValueQueryStringParameters"); + } + } + private Response buildProxyResponse(InvokeResult result) { if (result.getPayload() == null || result.getPayload().length == 0) { return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build(); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestAuthorizerIntegrationTest.java new file mode 100644 index 0000000000..02d8e2071b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestAuthorizerIntegrationTest.java @@ -0,0 +1,956 @@ +package io.github.hectorvent.floci.services.apigateway; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Integration tests for REQUEST authorizer full event shape (issue #807). + * + *

Validates that {@code toAuthorizerEvent} populates the complete + * {@code APIGatewayRequestAuthorizerEvent} shape for REQUEST-type authorizers, + * and that TOKEN and NONE authorizer paths are unaffected. + * + *

All management-plane setup uses RestAssured against the local Floci endpoint. + * Execute-api invocations also use RestAssured. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayRequestAuthorizerIntegrationTest { + + private static final String LAMBDA_BASE_PATH = "/2015-03-31/functions"; + private static final String AUTHORIZER_FUNCTION = "apigw-request-auth-echo"; + private static final String PROXY_FUNCTION = "apigw-request-auth-proxy"; + private static final String TOKEN_AUTHORIZER_FUNCTION = "apigw-token-auth-echo"; + private static final String TOKEN_PROXY_FUNCTION = "apigw-token-auth-proxy"; + private static final String NONE_INTEGRATION_FUNCTION = "apigw-none-auth-integration"; + private static final String DENY_AUTHORIZER_FUNCTION = "apigw-deny-auth"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/lambda-role"; + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + // State shared across ordered tests + private static String apiId; + private static String rootId; + private static String itemResourceId; + private static String authorizerId; + + private static String tokenApiId; + private static String noneApiId; + private static String denyApiId; + + // ──────────────────────────── Lambda setup ──────────────────────────── + + @Test + @Order(1) + void createEchoAuthorizerLambda() throws Exception { + createNodeLambda(AUTHORIZER_FUNCTION, """ + exports.handler = async (event) => ({ + principalId: "test-user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ + Action: "execute-api:Invoke", + Effect: "Allow", + Resource: event.methodArn + }] + }, + context: { + receivedEvent: JSON.stringify(event) + } + }); + """); + } + + @Test + @Order(2) + void createProxyLambda() throws Exception { + createNodeLambda(PROXY_FUNCTION, """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ + authorizer: event.requestContext && event.requestContext.authorizer + ? event.requestContext.authorizer + : null + }) + }); + """); + } + + // ──────────────────────────── REQUEST authorizer API setup ──────────────────────────── + + @Test + @Order(3) + void createRestApi() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"request-authorizer-test-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + assertNotNull(apiId); + } + + @Test + @Order(4) + void getResources() { + rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + assertNotNull(rootId); + } + + @Test + @Order(5) + void createResources() { + String itemsId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"items\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201) + .extract().path("id"); + + itemResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"{id}\"}") + .when().post("/restapis/" + apiId + "/resources/" + itemsId) + .then().statusCode(201) + .extract().path("id"); + assertNotNull(itemResourceId); + } + + @Test + @Order(6) + void createRequestAuthorizer() { + String authorizerUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + AUTHORIZER_FUNCTION + "/invocations"; + authorizerId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"request-echo-authorizer","type":"REQUEST","authorizerUri":"%s","identitySource":"method.request.header.Authorization","authorizerResultTtlInSeconds":0} + """.formatted(authorizerUri)) + .when().post("/restapis/" + apiId + "/authorizers") + .then().statusCode(201) + .extract().path("id"); + assertNotNull(authorizerId); + } + + @Test + @Order(7) + void configureMethodAndIntegration() { + given() + .contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(authorizerId)) + .when().put("/restapis/" + apiId + "/resources/" + itemResourceId + "/methods/GET") + .then().statusCode(201); + + String proxyUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + PROXY_FUNCTION + "/invocations"; + given() + .contentType(ContentType.JSON) + .body(""" + {"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"} + """.formatted(proxyUri)) + .when().put("/restapis/" + apiId + "/resources/" + itemResourceId + "/methods/GET/integration") + .then().statusCode(201); + } + + @Test + @Order(8) + void deployApi() { + String depId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"request-auth-test\"}") + .when().post("/restapis/" + apiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s"} + """.formatted(depId)) + .when().post("/restapis/" + apiId + "/stages") + .then().statusCode(201); + } + + // ──────────────────────────── Core bug condition test ──────────────────────────── + + @Test + @Order(9) + void requestAuthorizerReceivesFullEvent() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .when().get("/execute-api/" + apiId + "/prod/items/42?foo=bar") + .then() + .statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + JsonNode authorizer = payload.path("authorizer"); + + assertFalse(authorizer.isNull(), "authorizer context should be present in proxy response"); + assertFalse(authorizer.isMissingNode(), "authorizer context should be present in proxy response"); + + String receivedEventStr = authorizer.path("receivedEvent").asText(null); + assertNotNull(receivedEventStr, "authorizer should have embedded receivedEvent in context"); + assertFalse(receivedEventStr.isEmpty(), "receivedEvent should not be empty"); + + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + + // type and methodArn + assertEquals("REQUEST", event.path("type").asText(null)); + assertFalse(event.path("methodArn").isMissingNode(), "methodArn must be present"); + assertTrue(event.path("methodArn").asText("").contains(apiId), "methodArn must contain apiId"); + + // resource (matched template path) and actual path + assertEquals("/items/{id}", event.path("resource").asText(null), + "resource should be the matched resource path template"); + assertEquals("/items/42", event.path("path").asText(null), + "path should be the actual request path"); + assertEquals("GET", event.path("httpMethod").asText(null)); + + // headers + assertFalse(event.path("headers").isNull(), "headers must be non-null"); + assertFalse(event.path("headers").isMissingNode(), "headers must be present"); + + // multiValueHeaders + assertFalse(event.path("multiValueHeaders").isNull(), "multiValueHeaders must be non-null"); + assertFalse(event.path("multiValueHeaders").isMissingNode(), "multiValueHeaders must be present"); + + // queryStringParameters + assertFalse(event.path("queryStringParameters").isNull(), + "queryStringParameters must be non-null when query params are present"); + assertEquals("bar", event.path("queryStringParameters").path("foo").asText(null)); + + // multiValueQueryStringParameters + assertFalse(event.path("multiValueQueryStringParameters").isNull(), + "multiValueQueryStringParameters must be non-null when query params are present"); + assertTrue(event.path("multiValueQueryStringParameters").path("foo").isArray()); + + // pathParameters + assertFalse(event.path("pathParameters").isNull(), "pathParameters must be non-null"); + assertEquals("42", event.path("pathParameters").path("id").asText(null)); + + // stageVariables must be null (no stage variables configured) + assertTrue(event.path("stageVariables").isNull(), "stageVariables must be null"); + + // requestContext + JsonNode ctx = event.path("requestContext"); + assertFalse(ctx.isNull(), "requestContext must be present"); + assertFalse(ctx.isMissingNode(), "requestContext must be present"); + + String requestId = ctx.path("requestId").asText(null); + assertNotNull(requestId, "requestContext.requestId must be non-null"); + assertFalse(requestId.isEmpty(), "requestContext.requestId must be non-empty"); + + assertEquals("127.0.0.1", ctx.path("identity").path("sourceIp").asText(null), + "requestContext.identity.sourceIp must equal '127.0.0.1'"); + assertFalse(ctx.path("identity").path("userAgent").isMissingNode(), + "requestContext.identity.userAgent must be present"); + assertTrue(ctx.path("identity").path("apiKey").isNull(), + "requestContext.identity.apiKey must be null when no matching usage plan key exists"); + assertTrue(ctx.path("identity").path("clientCert").isNull(), + "requestContext.identity.clientCert must be null (mTLS not supported)"); + assertEquals("/items/{id}", ctx.path("resourcePath").asText(null)); + assertEquals("/items/42", ctx.path("path").asText(null), + "requestContext.path must equal the actual request path"); + assertEquals("GET", ctx.path("httpMethod").asText(null)); + assertEquals("prod", ctx.path("stage").asText(null)); + assertEquals(ACCOUNT, ctx.path("accountId").asText(null), + "requestContext.accountId must be present"); + assertEquals(apiId, ctx.path("apiId").asText(null), + "requestContext.apiId must be present"); + + String resourceId = ctx.path("resourceId").asText(null); + assertNotNull(resourceId, "requestContext.resourceId must be non-null"); + assertFalse(resourceId.isEmpty(), "requestContext.resourceId must be non-empty"); + } + + @Test + @Order(10) + void requestAuthorizerNullQueryParamsWhenNonePresent() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .when().get("/execute-api/" + apiId + "/prod/items/99") + .then() + .statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr); + + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + assertTrue(event.path("queryStringParameters").isNull(), + "queryStringParameters must be null when no query string is present"); + assertTrue(event.path("multiValueQueryStringParameters").isNull(), + "multiValueQueryStringParameters must be null when no query string is present"); + } + + // ──────────────────────────── TOKEN authorizer preservation ──────────────────────────── + + @Test + @Order(20) + void preservation_createTokenLambdas() throws Exception { + createNodeLambda(TOKEN_AUTHORIZER_FUNCTION, """ + exports.handler = async (event) => ({ + principalId: "test-user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ + Action: "execute-api:Invoke", + Effect: "Allow", + Resource: event.methodArn + }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + """); + createNodeLambda(TOKEN_PROXY_FUNCTION, """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ + authorizer: event.requestContext && event.requestContext.authorizer + ? event.requestContext.authorizer : null + }) + }); + """); + } + + @Test + @Order(21) + void preservation_setupTokenAuthorizerApi() { + tokenApiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"token-authorizer-preservation-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String tokenRootId = given() + .when().get("/restapis/" + tokenApiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + + String secureResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"secure\"}") + .when().post("/restapis/" + tokenApiId + "/resources/" + tokenRootId) + .then().statusCode(201) + .extract().path("id"); + + String authUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + TOKEN_AUTHORIZER_FUNCTION + "/invocations"; + String tokenAuthId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"token-echo-authorizer","type":"TOKEN","authorizerUri":"%s","identitySource":"method.request.header.Authorization","authorizerResultTtlInSeconds":0} + """.formatted(authUri)) + .when().post("/restapis/" + tokenApiId + "/authorizers") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(tokenAuthId)) + .when().put("/restapis/" + tokenApiId + "/resources/" + secureResourceId + "/methods/GET") + .then().statusCode(201); + + String proxyUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + TOKEN_PROXY_FUNCTION + "/invocations"; + given().contentType(ContentType.JSON) + .body(""" + {"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"} + """.formatted(proxyUri)) + .when().put("/restapis/" + tokenApiId + "/resources/" + secureResourceId + "/methods/GET/integration") + .then().statusCode(201); + + String depId = given().contentType(ContentType.JSON) + .body("{\"description\":\"token-auth-preservation\"}") + .when().post("/restapis/" + tokenApiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s"} + """.formatted(depId)) + .when().post("/restapis/" + tokenApiId + "/stages") + .then().statusCode(201); + } + + @Test + @Order(22) + void preservation_tokenAuthorizerEventShapeIsExact() throws Exception { + String response = given() + .header("Authorization", "Bearer mytoken") + .when().get("/execute-api/" + tokenApiId + "/prod/secure") + .then().statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr, "TOKEN authorizer should embed receivedEvent in context"); + + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + + assertEquals("TOKEN", event.path("type").asText(null)); + assertFalse(event.path("methodArn").isMissingNode(), "methodArn must be present"); + assertEquals("Bearer mytoken", event.path("authorizationToken").asText(null)); + + // TOKEN event must NOT contain REQUEST-specific fields + assertTrue(event.path("headers").isMissingNode() || event.path("headers").isNull(), + "TOKEN event must NOT contain headers"); + assertTrue(event.path("queryStringParameters").isMissingNode() || event.path("queryStringParameters").isNull(), + "TOKEN event must NOT contain queryStringParameters"); + assertTrue(event.path("requestContext").isMissingNode() || event.path("requestContext").isNull(), + "TOKEN event must NOT contain requestContext"); + } + + // ──────────────────────────── NONE authorizer preservation ──────────────────────────── + + @Test + @Order(30) + void preservation_setupNoneAuthorizerApi() throws Exception { + createNodeLambda(NONE_INTEGRATION_FUNCTION, """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ invoked: true }) + }); + """); + + noneApiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"none-authorizer-preservation-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String noneRootId = given() + .when().get("/restapis/" + noneApiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + + String openResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"open\"}") + .when().post("/restapis/" + noneApiId + "/resources/" + noneRootId) + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + noneApiId + "/resources/" + openResourceId + "/methods/GET") + .then().statusCode(201); + + String integrationUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + NONE_INTEGRATION_FUNCTION + "/invocations"; + given().contentType(ContentType.JSON) + .body(""" + {"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"} + """.formatted(integrationUri)) + .when().put("/restapis/" + noneApiId + "/resources/" + openResourceId + "/methods/GET/integration") + .then().statusCode(201); + + String depId = given().contentType(ContentType.JSON) + .body("{\"description\":\"none-auth-preservation\"}") + .when().post("/restapis/" + noneApiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s"} + """.formatted(depId)) + .when().post("/restapis/" + noneApiId + "/stages") + .then().statusCode(201); + } + + @Test + @Order(31) + void preservation_noneAuthorizerSkipsInvocation() { + given() + .when().get("/execute-api/" + noneApiId + "/prod/open") + .then() + .statusCode(200) + .body("invoked", org.hamcrest.Matchers.equalTo(true)); + } + + // ──────────────────────────── Allow / Deny policy ──────────────────────────── + + @Test + @Order(32) + void preservation_requestAuthorizerAllowPolicyForwardsToIntegration() { + given() + .header("Authorization", "Bearer test") + .when().get("/execute-api/" + apiId + "/prod/items/42") + .then() + .statusCode(200); + } + + @Test + @Order(40) + void preservation_setupDenyAuthorizerApi() throws Exception { + createNodeLambda(DENY_AUTHORIZER_FUNCTION, """ + exports.handler = async (event) => ({ + principalId: "test-user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ + Action: "execute-api:Invoke", + Effect: "Deny", + Resource: event.methodArn + }] + } + }); + """); + + denyApiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"deny-authorizer-preservation-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String denyRootId = given() + .when().get("/restapis/" + denyApiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + + String protectedResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"protected\"}") + .when().post("/restapis/" + denyApiId + "/resources/" + denyRootId) + .then().statusCode(201) + .extract().path("id"); + + String authUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + DENY_AUTHORIZER_FUNCTION + "/invocations"; + String denyAuthId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"deny-authorizer","type":"REQUEST","authorizerUri":"%s","identitySource":"method.request.header.Authorization","authorizerResultTtlInSeconds":0} + """.formatted(authUri)) + .when().post("/restapis/" + denyApiId + "/authorizers") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(denyAuthId)) + .when().put("/restapis/" + denyApiId + "/resources/" + protectedResourceId + "/methods/GET") + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put("/restapis/" + denyApiId + "/resources/" + protectedResourceId + "/methods/GET/integration") + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{\"responseParameters\":{}}") + .when().put("/restapis/" + denyApiId + "/resources/" + protectedResourceId + "/methods/GET/responses/200") + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"message\\\":\\\"ok\\\"}\"}}") + .when().put("/restapis/" + denyApiId + "/resources/" + protectedResourceId + "/methods/GET/integration/responses/200") + .then().statusCode(201); + + String depId = given().contentType(ContentType.JSON) + .body("{\"description\":\"deny-auth-preservation\"}") + .when().post("/restapis/" + denyApiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s"} + """.formatted(depId)) + .when().post("/restapis/" + denyApiId + "/stages") + .then().statusCode(201); + } + + @Test + @Order(41) + void preservation_requestAuthorizerDenyPolicyReturns403() { + given() + .header("Authorization", "Bearer anytoken") + .when().get("/execute-api/" + denyApiId + "/prod/protected") + .then() + .statusCode(403); + } + + // ──────────────────────────── Stage Variables ──────────────────────────── + + private static String stageVarApiId; + + @Test + @Order(50) + void stageVariables_setupApiWithStageVars() throws Exception { + createNodeLambda("apigw-stagevar-auth-echo", """ + exports.handler = async (event) => ({ + principalId: "user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + """); + createNodeLambda("apigw-stagevar-proxy", """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ + stageVariables: event.stageVariables, + authorizer: event.requestContext && event.requestContext.authorizer + ? event.requestContext.authorizer : null + }) + }); + """); + + stageVarApiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"stage-var-test-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String svRootId = given() + .when().get("/restapis/" + stageVarApiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + + String resourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"ping\"}") + .when().post("/restapis/" + stageVarApiId + "/resources/" + svRootId) + .then().statusCode(201) + .extract().path("id"); + + String authUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:apigw-stagevar-auth-echo/invocations"; + String svAuthId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"sv-auth","type":"REQUEST","authorizerUri":"%s","identitySource":"method.request.header.Authorization","authorizerResultTtlInSeconds":0} + """.formatted(authUri)) + .when().post("/restapis/" + stageVarApiId + "/authorizers") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(svAuthId)) + .when().put("/restapis/" + stageVarApiId + "/resources/" + resourceId + "/methods/GET") + .then().statusCode(201); + + String proxyUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:apigw-stagevar-proxy/invocations"; + given().contentType(ContentType.JSON) + .body(""" + {"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"} + """.formatted(proxyUri)) + .when().put("/restapis/" + stageVarApiId + "/resources/" + resourceId + "/methods/GET/integration") + .then().statusCode(201); + + String depId = given().contentType(ContentType.JSON) + .body("{\"description\":\"sv-test\"}") + .when().post("/restapis/" + stageVarApiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + // Create stage WITH variables + given().contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s","variables":{"env":"test","version":"v1"}} + """.formatted(depId)) + .when().post("/restapis/" + stageVarApiId + "/stages") + .then().statusCode(201); + } + + @Test + @Order(51) + void stageVariables_authorizerEventContainsStageVars() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .when().get("/execute-api/" + stageVarApiId + "/prod/ping") + .then().statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + + // Proxy event stageVariables + JsonNode proxyStageVars = payload.path("stageVariables"); + assertFalse(proxyStageVars.isNull(), "proxy event stageVariables must be non-null"); + assertEquals("test", proxyStageVars.path("env").asText(null)); + assertEquals("v1", proxyStageVars.path("version").asText(null)); + + // Authorizer event stageVariables (embedded in context) + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr); + JsonNode authEvent = OBJECT_MAPPER.readTree(receivedEventStr); + JsonNode authStageVars = authEvent.path("stageVariables"); + assertFalse(authStageVars.isNull(), "authorizer event stageVariables must be non-null"); + assertEquals("test", authStageVars.path("env").asText(null)); + assertEquals("v1", authStageVars.path("version").asText(null)); + } + + // ──────────────────────────── API Key Resolution ──────────────────────────── + + private static String apiKeyApiId; + + @Test + @Order(60) + void apiKey_setupApiWithUsagePlan() throws Exception { + createNodeLambda("apigw-apikey-auth-echo", """ + exports.handler = async (event) => ({ + principalId: "user", + policyDocument: { + Version: "2012-10-17", + Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn }] + }, + context: { receivedEvent: JSON.stringify(event) } + }); + """); + createNodeLambda("apigw-apikey-proxy", """ + exports.handler = async (event) => ({ + statusCode: 200, + body: JSON.stringify({ + authorizer: event.requestContext && event.requestContext.authorizer + ? event.requestContext.authorizer : null + }) + }); + """); + + apiKeyApiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"apikey-test-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String akRootId = given() + .when().get("/restapis/" + apiKeyApiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + + String resourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"secure\"}") + .when().post("/restapis/" + apiKeyApiId + "/resources/" + akRootId) + .then().statusCode(201) + .extract().path("id"); + + String authUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:apigw-apikey-auth-echo/invocations"; + String akAuthId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"ak-auth","type":"REQUEST","authorizerUri":"%s","identitySource":"method.request.header.Authorization","authorizerResultTtlInSeconds":0} + """.formatted(authUri)) + .when().post("/restapis/" + apiKeyApiId + "/authorizers") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"authorizationType":"CUSTOM","authorizerId":"%s"} + """.formatted(akAuthId)) + .when().put("/restapis/" + apiKeyApiId + "/resources/" + resourceId + "/methods/GET") + .then().statusCode(201); + + String proxyUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:apigw-apikey-proxy/invocations"; + given().contentType(ContentType.JSON) + .body(""" + {"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"} + """.formatted(proxyUri)) + .when().put("/restapis/" + apiKeyApiId + "/resources/" + resourceId + "/methods/GET/integration") + .then().statusCode(201); + + String depId = given().contentType(ContentType.JSON) + .body("{\"description\":\"ak-test\"}") + .when().post("/restapis/" + apiKeyApiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"stageName":"prod","deploymentId":"%s"} + """.formatted(depId)) + .when().post("/restapis/" + apiKeyApiId + "/stages") + .then().statusCode(201); + + // Create API key + usage plan linked to this (apiId, stage) + given().contentType(ContentType.JSON) + .body("{\"name\":\"test-key\",\"value\":\"my-secret-api-key\",\"enabled\":true}") + .when().post("/apikeys") + .then().statusCode(201); + + String keyId = given() + .when().get("/apikeys") + .then().statusCode(200) + .extract().path("item.find { it.name == 'test-key' }.id"); + + String planId = given().contentType(ContentType.JSON) + .body(""" + {"name":"test-plan","apiStages":[{"apiId":"%s","stage":"prod"}]} + """.formatted(apiKeyApiId)) + .when().post("/usageplans") + .then().statusCode(201) + .extract().path("id"); + + given().contentType(ContentType.JSON) + .body(""" + {"keyId":"%s","keyType":"API_KEY"} + """.formatted(keyId)) + .when().post("/usageplans/" + planId + "/keys") + .then().statusCode(201); + } + + @Test + @Order(61) + void apiKey_identityApiKeyPopulatedWhenHeaderMatches() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .header("x-api-key", "my-secret-api-key") + .when().get("/execute-api/" + apiKeyApiId + "/prod/secure") + .then().statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr); + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + + assertEquals("my-secret-api-key", + event.path("requestContext").path("identity").path("apiKey").asText(null), + "identity.apiKey must equal the matched usage plan key value"); + } + + @Test + @Order(62) + void apiKey_identityApiKeyNullWhenNoHeaderPresent() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .when().get("/execute-api/" + apiKeyApiId + "/prod/secure") + .then().statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr); + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + + assertTrue(event.path("requestContext").path("identity").path("apiKey").isNull(), + "identity.apiKey must be null when no x-api-key header is present"); + } + + @Test + @Order(63) + void apiKey_identityApiKeyNullWhenHeaderDoesNotMatchAnyPlanKey() throws Exception { + String response = given() + .header("Authorization", "Bearer test") + .header("x-api-key", "wrong-key-value") + .when().get("/execute-api/" + apiKeyApiId + "/prod/secure") + .then().statusCode(200) + .extract().asString(); + + JsonNode payload = OBJECT_MAPPER.readTree(response); + String receivedEventStr = payload.path("authorizer").path("receivedEvent").asText(null); + assertNotNull(receivedEventStr); + JsonNode event = OBJECT_MAPPER.readTree(receivedEventStr); + + assertTrue(event.path("requestContext").path("identity").path("apiKey").isNull(), + "identity.apiKey must be null when x-api-key header does not match any plan key"); + } + + // ──────────────────────────── Cleanup ──────────────────────────── + + @Test + @Order(99) + void cleanup() { + if (apiId != null) given().when().delete("/restapis/" + apiId).then().statusCode(202); + if (tokenApiId != null) given().when().delete("/restapis/" + tokenApiId).then().statusCode(202); + if (noneApiId != null) given().when().delete("/restapis/" + noneApiId).then().statusCode(202); + if (denyApiId != null) given().when().delete("/restapis/" + denyApiId).then().statusCode(202); + if (stageVarApiId != null) given().when().delete("/restapis/" + stageVarApiId).then().statusCode(202); + if (apiKeyApiId != null) given().when().delete("/restapis/" + apiKeyApiId).then().statusCode(202); + deleteFunction(AUTHORIZER_FUNCTION); + deleteFunction(PROXY_FUNCTION); + deleteFunction(TOKEN_AUTHORIZER_FUNCTION); + deleteFunction(TOKEN_PROXY_FUNCTION); + deleteFunction(NONE_INTEGRATION_FUNCTION); + deleteFunction(DENY_AUTHORIZER_FUNCTION); + deleteFunction("apigw-stagevar-auth-echo"); + deleteFunction("apigw-stagevar-proxy"); + deleteFunction("apigw-apikey-auth-echo"); + deleteFunction("apigw-apikey-proxy"); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static void createNodeLambda(String functionName, String handlerSource) throws Exception { + String zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of( + "index.js", handlerSource + ))); + given() + .contentType(ContentType.JSON) + .body(""" + { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Role": "%s", + "Handler": "index.handler", + "Timeout": 30, + "Code": {"ZipFile": "%s"} + } + """.formatted(functionName, ROLE_ARN, zipBase64)) + .when().post(LAMBDA_BASE_PATH) + .then() + .statusCode(201); + } + + private static byte[] zipEntries(Map entries) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + for (Map.Entry entry : entries.entrySet()) { + zos.putNextEntry(new ZipEntry(entry.getKey())); + zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + } + return baos.toByteArray(); + } + + private static void deleteFunction(String functionName) { + int statusCode = given() + .when().delete(LAMBDA_BASE_PATH + "/" + functionName) + .then() + .extract().statusCode(); + assertTrue(statusCode == 204 || statusCode == 404); + } +}