Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JASPER-289: Lambda Function Integration #176

Merged
merged 1 commit into from
Feb 14, 2025
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
34 changes: 28 additions & 6 deletions aws/services/apiService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { APIGatewayEvent, APIGatewayProxyResult } from "aws-lambda";
import { AxiosRequestConfig, AxiosResponse } from "axios";
import { sanitizeHeaders, sanitizeQueryStringParams } from "../util";
import { HttpService, IHttpService } from "./httpService";
import { SecretsManagerService } from "./secretsManagerService";
Expand Down Expand Up @@ -39,21 +40,35 @@ export class ApiService {

const url = `${event.path}?${queryString}`;

console.log(`Sending ${method} request to ${url}`);
console.log(`Headers: ${JSON.stringify(headers, null, 2)}`);

console.log(`Body: ${JSON.stringify(body, null, 2)}`);

let data;
// Determine if request expects a binary response
const isBinary =
headers && headers["Accept"]?.startsWith("application/octet-stream");

const axiosConfig: AxiosRequestConfig = {
headers: {
...headers,
"Content-Type": isBinary
? "application/octet-stream"
: "application/json",
},
responseType: isBinary ? "arraybuffer" : "json",
};

let response: AxiosResponse<unknown>;

switch (method) {
case "GET":
data = await this.httpService.get(url, headers);
response = await this.httpService.get(url, axiosConfig);
break;
case "POST":
data = await this.httpService.post(url, body, headers);
response = await this.httpService.post(url, body, axiosConfig);
break;
case "PUT":
data = await this.httpService.put(url, body, headers);
response = await this.httpService.put(url, body, axiosConfig);
break;
default:
return {
Expand All @@ -62,9 +77,16 @@ export class ApiService {
};
}

console.log("Response:", response);

return {
statusCode: 200,
body: JSON.stringify(data),
body: isBinary
? Buffer.from(new Uint8Array(response.data as ArrayBuffer)).toString(
"base64"
)
: JSON.stringify(response.data),
isBase64Encoded: !!isBinary,
};
} catch (error) {
console.error("Error:", error);
Expand Down
57 changes: 32 additions & 25 deletions aws/services/httpService.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import axios, { AxiosInstance, AxiosResponse } from "axios";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import * as https from "https";

export interface IHttpService {
init(credentialsSecret: string, mtlsSecret: string): Promise<void>;
get<T>(url: string, headers?: Record<string, string>): Promise<T>;
get<T>(url: string, config: AxiosRequestConfig): Promise<AxiosResponse<T>>;
post<T>(
url: string,
data?: Record<string, unknown>,
headers?: Record<string, string>
): Promise<T>;
data: Record<string, unknown>,
config: AxiosRequestConfig
): Promise<AxiosResponse<T>>;
put<T>(
url: string,
data?: Record<string, unknown>,
headers?: Record<string, string>
): Promise<T>;
data: Record<string, unknown>,
config: AxiosRequestConfig
): Promise<AxiosResponse<T>>;
}

export class HttpService implements IHttpService {
Expand Down Expand Up @@ -41,40 +41,47 @@ export class HttpService implements IHttpService {
});
}

async get<T>(url: string, headers?: Record<string, string>): Promise<T> {
async get<T>(
url: string,
config: AxiosRequestConfig
): Promise<AxiosResponse<T>> {
try {
const response: AxiosResponse<T> = await this.axios.get(url, { headers });
return response.data;
const response: AxiosResponse<T> = await this.axios.get(url, config);
return response;
} catch (error) {
this.handleError(error);
}
}

async post<T>(
url: string,
data?: Record<string, unknown>,
headers?: Record<string, string>
): Promise<T> {
data: Record<string, unknown>,
config: AxiosRequestConfig
): Promise<AxiosResponse<T>> {
try {
const response: AxiosResponse<T> = await this.axios.post(url, data, {
headers,
});
return response.data;
const response: AxiosResponse<T> = await this.axios.post(
url,
data,
config
);
return response;
} catch (error) {
this.handleError(error);
}
}

async put<T>(
url: string,
data?: Record<string, unknown>,
headers?: Record<string, string>
): Promise<T> {
data: Record<string, unknown>,
config: AxiosRequestConfig
): Promise<AxiosResponse<T>> {
try {
const response: AxiosResponse<T> = await this.axios.put(url, data, {
headers,
});
return response.data;
const response: AxiosResponse<T> = await this.axios.put(
url,
data,
config
);
return response;
} catch (error) {
this.handleError(error);
}
Expand Down
41 changes: 37 additions & 4 deletions aws/tests/services/apiService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,16 @@ describe("ApiService", () => {
const response = await apiService.handleRequest(event as APIGatewayEvent);

expect(mockHttpService.get).toHaveBeenCalledWith("/test?key=value", {
Authorization: "Bearer token",
headers: {
Authorization: "Bearer token",
"Content-Type": "application/json",
},
responseType: "json",
});
expect(response).toEqual({
statusCode: 200,
body: JSON.stringify({ data: "get response" }),
body: JSON.stringify("get response"),
isBase64Encoded: false,
});
});

Expand All @@ -90,11 +95,12 @@ describe("ApiService", () => {
expect(mockHttpService.post).toHaveBeenCalledWith(
"/test?",
{ name: "test" },
{ "Content-Type": "application/json" }
{ headers: { "Content-Type": "application/json" }, responseType: "json" }
);
expect(response).toEqual({
statusCode: 200,
body: JSON.stringify({ data: "post response" }),
body: JSON.stringify("post response"),
isBase64Encoded: false,
});
});

Expand Down Expand Up @@ -122,4 +128,31 @@ describe("ApiService", () => {
body: JSON.stringify({ message: "Internal Server Error" }),
});
});

it("should handle a GET binary request", async () => {
const event: Partial<APIGatewayEvent> = {
httpMethod: "GET",
path: "/test",
queryStringParameters: { key: "value" },
headers: { Accept: "application/octet-stream" },
body: null,
};

const response = await apiService.handleRequest(event as APIGatewayEvent);

expect(mockHttpService.get).toHaveBeenCalledWith("/test?key=value", {
headers: {
Accept: "application/octet-stream",
"Content-Type": "application/octet-stream",
},
responseType: "arraybuffer",
});
expect(response).toEqual({
statusCode: 200,
body: Buffer.from(
new Uint8Array("get response" as unknown as ArrayBuffer)
).toString("base64"),
isBase64Encoded: true,
});
});
});
39 changes: 27 additions & 12 deletions aws/tests/services/httpService.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AxiosRequestConfig } from "axios";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { default as axiosMock } from "../../mocks/axios";
import HttpService from "../../services/httpService";
Expand All @@ -15,6 +16,12 @@ describe("HttpService", () => {
const cert = "mock-cert";
const key = "mock-key";

const mockAxiosConfig: AxiosRequestConfig = {
headers: {
"Content-Type": "application/json",
},
};

beforeEach(() => {
httpService = new HttpService();
credentialsSecret = JSON.stringify({
Expand Down Expand Up @@ -47,37 +54,45 @@ describe("HttpService", () => {
axiosMock.get.mockResolvedValue({ data: { message: "success" } });

await httpService.init(credentialsSecret, mtlsSecret);
const result = await httpService.get("/test");
const response = await httpService.get("/test", mockAxiosConfig);

expect(result).toEqual({ message: "success" });
expect(axiosMock.get).toHaveBeenCalledWith("/test", { headers: undefined });
expect(response.data).toEqual({ message: "success" });
expect(axiosMock.get).toHaveBeenCalledWith("/test", mockAxiosConfig);
});

it("should perform POST request", async () => {
axiosMock.post.mockResolvedValue({ data: { id: 1 } });

await httpService.init(credentialsSecret, mtlsSecret);
const result = await httpService.post("/test", { name: "example" });
const response = await httpService.post(
"/test",
{ name: "example" },
mockAxiosConfig
);

expect(result).toEqual({ id: 1 });
expect(response.data).toEqual({ id: 1 });
expect(axiosMock.post).toHaveBeenCalledWith(
"/test",
{ name: "example" },
{ headers: undefined }
mockAxiosConfig
);
});

it("should perform PUT request", async () => {
axiosMock.put.mockResolvedValue({ data: { updated: true } });

await httpService.init(credentialsSecret, mtlsSecret);
const result = await httpService.put("/test", { name: "updated" });
const response = await httpService.put(
"/test",
{ name: "updated" },
mockAxiosConfig
);

expect(result).toEqual({ updated: true });
expect(response.data).toEqual({ updated: true });
expect(axiosMock.put).toHaveBeenCalledWith(
"/test",
{ name: "updated" },
{ headers: undefined }
mockAxiosConfig
);
});

Expand All @@ -86,8 +101,8 @@ describe("HttpService", () => {
axiosMock.isAxiosError.mockReturnValue(true);

await httpService.init(credentialsSecret, mtlsSecret);
await expect(httpService.get("/not-found")).rejects.toThrow(
"HTTP Error: 404"
);
await expect(
httpService.get("/not-found", mockAxiosConfig)
).rejects.toThrow("HTTP Error: 404");
});
});
10 changes: 6 additions & 4 deletions aws/tests/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ describe("sanitizeHeaders", () => {
applicationCd: "app123",
correlationId: "12345",
Accept: "application/octet-stream",
"Content-Type": "application/octet-stream",
});
});

it("should return an empty object if no allowed headers are present", () => {
const headers = { unauthorizedHeader: "shouldBeRemoved" };
expect(sanitizeHeaders(headers)).toEqual({
"Content-Type": "application/json",
});
expect(sanitizeHeaders(headers)).toEqual({});
});

it("should return an empty object when Authorization header is present", () => {
const headers = { Authorization: "Bearer 123" };
expect(sanitizeHeaders(headers)).toEqual({});
});
});

Expand Down
6 changes: 0 additions & 6 deletions aws/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,6 @@ export const sanitizeHeaders = (
}
}

// Specify Content-Type as application/json unless specified in Accept
filteredHeaders["Content-Type"] =
filteredHeaders["Accept"] === "application/octet-stream"
? "application/octet-stream"
: "application/json";

return filteredHeaders;
};

Expand Down
7 changes: 5 additions & 2 deletions infrastructure/cloud/modules/APIGateway/main.tf
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
resource "aws_api_gateway_rest_api" "apigw" {
name = "${var.app_name}-api-gateway-${var.environment}"

binary_media_types = ["application/octet-stream"]
}

resource "aws_api_gateway_deployment" "apigw_deployment" {
Expand All @@ -10,9 +11,11 @@ resource "aws_api_gateway_deployment" "apigw_deployment" {
rest_api_id = aws_api_gateway_rest_api.apigw.id

triggers = {
redeployment = sha1(jsonencode(aws_api_gateway_rest_api.apigw))
redeployment = sha1(jsonencode({
binary_media_types = aws_api_gateway_rest_api.apigw.binary_media_types
body = aws_api_gateway_rest_api.apigw.body
}))
}

lifecycle {
create_before_destroy = true
}
Expand Down
Loading