Skip to content
Open
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
76 changes: 45 additions & 31 deletions lambdas/authorizer/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,30 @@
Callback,
Context,
} from "aws-lambda";
import { metricScope } from "aws-embedded-metrics";

Check failure on line 7 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

'aws-embedded-metrics' should be listed in the project's dependencies. Run 'npm i aws-embedded-metrics' to add it
import pino from "pino";
import { Deps } from "../deps";
import { EnvVars } from "../env";
import createAuthorizerHandler from "../authorizer";

jest.mock("aws-embedded-metrics", () => {
const metricsMock = {
setNamespace: jest.fn(),
putMetric: jest.fn(),
};

return {
metricScope: jest.fn((handler: (metrics: typeof metricsMock) => unknown) => {

Check failure on line 20 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `⏎······`
const wrapped = handler(metricsMock);

Check failure on line 21 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `··`
if (typeof wrapped === "function") {

Check failure on line 22 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `··`
return wrapped();

Check failure on line 23 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `··`
}

Check failure on line 24 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `··`
return undefined;

Check failure on line 25 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Do not use useless `undefined`

Check failure on line 25 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Insert `··`
}),

Check failure on line 26 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Replace `}` with `··},⏎····`
__metricsMock: metricsMock,
};
});

const mockedDeps: jest.Mocked<Deps> = {
logger: {
info: jest.fn(),
Expand Down Expand Up @@ -60,6 +79,17 @@
jest
.useFakeTimers({ doNotFake: ["nextTick"] })
.setSystemTime(new Date("2025-11-03T14:19:00Z"));
(metricScope as jest.Mock).mockClear();
const metricsMock = (jest.requireMock(

Check failure on line 83 in lambdas/authorizer/src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Test stage / Linting

Replace `jest.requireMock(⏎········"aws-embedded-metrics",⏎······` with `⏎········jest.requireMock("aws-embedded-metrics"`
"aws-embedded-metrics",
) as {
__metricsMock: {
setNamespace: jest.Mock;
putMetric: jest.Mock;
};
}).__metricsMock;
metricsMock.setNamespace.mockClear();
metricsMock.putMetric.mockClear();
});

afterEach(() => {
Expand All @@ -73,10 +103,7 @@
handler(mockEvent, mockContext, mockCallback);
await new Promise(process.nextTick);

const mockedInfo = mockedDeps.logger.info as jest.Mock;
expect(mockedInfo.mock.calls).not.toContainEqual(
expect.stringContaining("CloudWatchMetrics"),
);
expect(metricScope).not.toHaveBeenCalled();
});

it("Should log CloudWatch metric when the certificate expiry threshold is reached", async () => {
Expand All @@ -88,29 +115,19 @@
handler(mockEvent, mockContext, mockCallback);
await new Promise(process.nextTick);

const mockedInfo = mockedDeps.logger.info as jest.Mock;
expect(mockedInfo.mock.calls.map((call) => call[0])).toContain(
JSON.stringify({
_aws: {
Timestamp: 1_762_179_540_000,
CloudWatchMetrics: [
{
Namespace: "cloudwatch-namespace",
Dimensions: ["SUBJECT_DN", "NOT_AFTER"],
Metrics: [
{
Name: "apim-client-certificate-near-expiry",
Unit: "Count",
Value: 1,
},
],
},
],
},
SUBJECT_DN: "CN=test-subject",
NOT_AFTER: "2025-11-17T14:19:00Z",
"apim-client-certificate-near-expiry": 1,
}),
const metricsMock = (jest.requireMock("aws-embedded-metrics") as {
__metricsMock: {
setNamespace: jest.Mock;
putMetric: jest.Mock;
};
}).__metricsMock;

expect(metricScope).toHaveBeenCalledTimes(1);
expect(metricsMock.setNamespace).toHaveBeenCalledWith("authorizer");
expect(metricsMock.putMetric).toHaveBeenCalledWith(
"apim-client-certificate-near-expiry",
14,
"Count",
);
});

Expand All @@ -123,10 +140,7 @@
handler(mockEvent, mockContext, mockCallback);
await new Promise(process.nextTick);

const mockedInfo = mockedDeps.logger.info as jest.Mock;
expect(mockedInfo.mock.calls).not.toContainEqual(
expect.stringContaining("CloudWatchMetrics"),
);
expect(metricScope).not.toHaveBeenCalled();
});
});

Expand Down
43 changes: 9 additions & 34 deletions lambdas/authorizer/src/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
APIGatewayRequestAuthorizerHandler,
Callback,
Context,
} from "aws-lambda";
} from "aws-lambda"
import { MetricsLogger, metricScope } from "aws-embedded-metrics";
import { Supplier } from "@internal/datastore";
import { Deps } from "./deps";

Expand Down Expand Up @@ -100,33 +101,6 @@ function getCertificateExpiryInDays(
return (expiry - now) / (1000 * 60 * 60 * 24);
}

function buildCloudWatchMetric(
namespace: string,
certificate: APIGatewayEventClientCertificate,
) {
return {
_aws: {
Timestamp: Date.now(),
CloudWatchMetrics: [
{
Namespace: namespace,
Dimensions: ["SUBJECT_DN", "NOT_AFTER"],
Metrics: [
{
Name: "apim-client-certificate-near-expiry",
Unit: "Count",
Value: 1,
},
],
},
],
},
SUBJECT_DN: certificate.subjectDN,
NOT_AFTER: certificate.validity.notAfter,
"apim-client-certificate-near-expiry": 1,
};
}

async function checkCertificateExpiry(
certificate: APIGatewayEventClientCertificate | null,
deps: Deps,
Expand All @@ -146,10 +120,11 @@ async function checkCertificateExpiry(
const expiry = getCertificateExpiryInDays(certificate);

if (expiry <= deps.env.CLIENT_CERTIFICATE_EXPIRATION_ALERT_DAYS) {
deps.logger.info(
JSON.stringify(
buildCloudWatchMetric(deps.env.CLOUDWATCH_NAMESPACE, certificate),
),
);
}
metricScope(
(metrics: MetricsLogger) => async () => {
deps.logger.warn(`APIM Certificated expiry in ${expiry} days`);
metrics.setNamespace(process.env.AWS_LAMBDA_FUNCTION_NAME || 'authorizer');
metrics.putMetric("apim-client-certificate-near-expiry", expiry, "Count");
});
};
}
Loading