-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathauthorizer.ts
More file actions
134 lines (122 loc) · 3.68 KB
/
Copy pathauthorizer.ts
File metadata and controls
134 lines (122 loc) · 3.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import {
APIGatewayAuthorizerResult,
APIGatewayEventClientCertificate,
APIGatewayRequestAuthorizerEvent,
APIGatewayRequestAuthorizerEventHeaders,
APIGatewayRequestAuthorizerHandler,
Callback,
Context,
} from "aws-lambda";
import { MetricsLogger, metricScope } from "aws-embedded-metrics";
import { Supplier } from "@internal/datastore";
import { Deps } from "./deps";
export default function createAuthorizerHandler(
deps: Deps,
): APIGatewayRequestAuthorizerHandler {
return (
event: APIGatewayRequestAuthorizerEvent,
context: Context,
callback: Callback<APIGatewayAuthorizerResult>,
): void => {
checkCertificateExpiry(event.requestContext.identity.clientCert, deps);
getSupplier(event.headers, deps)
.then((supplier: Supplier) => {
deps.logger.info({
description: "Allowed event",
methodArn: event.methodArn,
supplierId: supplier.id,
});
callback(null, generateAllow(event.methodArn, supplier.id));
})
.catch((error) => {
deps.logger.warn({
description: "Denied event",
err: error,
methodArn: event.methodArn,
});
callback(null, generateDeny(event.methodArn));
});
};
}
async function getSupplier(
headers: APIGatewayRequestAuthorizerEventHeaders | null,
deps: Deps,
): Promise<Supplier> {
const apimId = Object.entries(headers || {}).find(
([headerName, _]) =>
headerName.toLowerCase() ===
deps.env.APIM_SUPPLIER_ID_HEADER.toLowerCase(),
)?.[1] as string;
if (!apimId) {
throw new Error("No APIM application ID found in header");
}
const supplier = await deps.supplierRepo.getSupplierByApimId(apimId);
if (supplier.status === "DISABLED") {
throw new Error(`Supplier ${supplier.id} is disabled`);
}
return supplier;
}
function generatePolicy(
principalId: string,
effect: "Allow" | "Deny",
resource: string,
): APIGatewayAuthorizerResult {
const authResponse: APIGatewayAuthorizerResult = {
principalId,
policyDocument: {
Version: "2012-10-17",
Statement: [
{
Action: "execute-api:Invoke",
Effect: effect,
Resource: resource,
},
],
},
};
return authResponse;
}
function generateAllow(
resource: string,
supplierId: string,
): APIGatewayAuthorizerResult {
return generatePolicy(supplierId, "Allow", resource);
}
function generateDeny(resource: string): APIGatewayAuthorizerResult {
return generatePolicy("invalid-user", "Deny", resource);
}
function getCertificateExpiryInDays(
certificate: APIGatewayEventClientCertificate,
): number {
const now = Date.now();
const expiry = new Date(certificate.validity.notAfter).getTime();
return (expiry - now) / (1000 * 60 * 60 * 24);
}
async function checkCertificateExpiry(
certificate: APIGatewayEventClientCertificate | null,
deps: Deps,
): Promise<void> {
deps.logger.info({
description: "Client certificate details",
issuerDN: certificate?.issuerDN || "-",
subjectDN: certificate?.subjectDN || "-",
validity: certificate?.validity || "-",
});
if (!certificate) {
// In a real production environment, we won't have got this far if there wasn't a cert
return;
}
const expiry = getCertificateExpiryInDays(certificate);
if (expiry <= deps.env.CLIENT_CERTIFICATE_EXPIRATION_ALERT_DAYS) {
await metricScope((metrics: MetricsLogger) => async () => {
deps.logger.warn({
description: "APIM Certificate expiry",
days: expiry,
});
metrics.setNamespace(
process.env.AWS_LAMBDA_FUNCTION_NAME || "authorizer",
);
metrics.putMetric("apim-client-certificate-near-expiry", expiry, "Count");
})();
}
}