-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
189 lines (155 loc) · 5.4 KB
/
index.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
* Copyright 2021 Curity AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Used to read values from .env */
require('dotenv').config();
/* Default deny all policy */
const defaultDenyAllPolicy = {
"principalId":"user",
"policyDocument":{
"Version":"2012-10-17",
"Statement":[
{
"Action":"execute-api:Invoke",
"Effect":"Deny",
"Resource":"*"
}
]
}
};
/* Generate an IAM policy statement */
function generatePolicyStatement(methodArn, action) {
const statement = {};
statement.Action = 'execute-api:Invoke';
statement.Effect = action;
statement.Resource = methodArn;
return statement;
}
function generatePolicy(principalId, policyStatements) {
const authResponse = {};
authResponse.principalId = principalId;
const policyDocument = {};
policyDocument.Version = '2012-10-17';
policyDocument.Statement = policyStatements;
authResponse.policyDocument = policyDocument;
return authResponse;
}
/* Generate an IAM policy */
function generateIAMPolicy(providedScope, user, methodArn) {
const policyStatements = [];
/* Check if token scopes exist in API Permission */
let hasScopes = verifyScope(providedScope, process.env.SCOPE);
if ( hasScopes ) {
policyStatements.push(generatePolicyStatement(getServiceArn(methodArn), "Allow")); //Wildcard path generated. Needed if IAM policies are cached and multipe API paths are using the Authorizer
// policyStatements.push(generatePolicyStatement(methodArn, "Allow")); //Used for a more strict approach with no caching of IAM policies.
}
/* Check if no policy statement is generated, if so, return default deny all policy statement */
if (policyStatements.length === 0) {
return defaultDenyAllPolicy;
} else {
return generatePolicy(user, policyStatements);
}
}
/* Verify provded scope against configured required scope */
function verifyScope(providedScope, requiredScope) {
let returnValue = true;
if(!requiredScope) {
return returnValue;
}
let providedSplitScope = providedScope.split(' ');
let requiredSplitScope = requiredScope.split(' ');
for(var i = 0; i < requiredSplitScope.length; i++) {
if(!providedSplitScope.includes(requiredSplitScope[i])) {
returnValue = false;
break;
}
}
return returnValue;
}
/* Introspect access token */
function introspect(options, data) {
return new Promise((resolve, reject) => {
var https = require('https');
const req = https.request(options, (res) => {
res.setEncoding("utf8");
let responseBody = "";
res.on("data", (chunk) => {
responseBody += chunk;
});
res.on("end", () => {
resolve(responseBody);
});
});
req.on("error", (err) => {
reject(err);
});
req.write(data);
req.end();
});
}
function getServiceArn(methodArn) {
// Get the last part, such as cqo3riplm6/default/GET/products
const parts = methodArn.split(':');
if (parts.length === 6) {
// Split the path into parts
const pathParts = parts[5].split('/');
if (pathParts.length >= 4) {
// Update the final part to a wildcard value such as cqo3riplm6/mystage/*, to apply to all lambdas in the API
parts[5] = `${pathParts[0]}/${pathParts[1]}/*`;
const result = parts.join(':');
return result;
}
}
// Sanity check
throw new Error(`Unexpected method ARN received: ${methodArn}`);
}
exports.handler = async function(event, context) {
if(!event.authorizationToken) {
context.fail("Unauthorized");
return;
}
const token = event.authorizationToken.replace("Bearer ", "");
const data = new URLSearchParams();
data.append('token', token);
//Base64 encode client_id and client_secret to authenticate Introspection endpoint
const introspectCredentials = Buffer.from(process.env.CLIENT_ID + ":" + process.env.CLIENT_SECRET, 'utf-8').toString('base64');
const options = {
host: process.env.HOST,
path: process.env.INTROSPECTION_PATH,
method: 'POST',
port: process.env.PORT,
headers: {
'Authorization': 'Basic ' + introspectCredentials,
'Accept': 'application/jwt', //Get Phantom Token directly in Introspection response
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.toString().length
}
};
const jwt = await introspect(options, data.toString());
if(jwt.length > 0 ) {
const base64String = jwt.toString().split('.')[1];
const decodedValue = JSON.parse(Buffer.from(base64String,'base64').toString('ascii'));
let iamPolicy = generateIAMPolicy(decodedValue.scope, decodedValue.sub, event.methodArn);
//Add Phantom Token (jwt) to context making it available to API GW to add to upstream Authorization header
iamPolicy.context = {
"Authorization": jwt
};
return iamPolicy;
}
else {
context.fail("Unauthorized");
return;
}
};