forked from aws/aws-js-sns-message-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
217 lines (188 loc) · 5.7 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"use strict";
var url = require('url'),
https = require('https'),
crypto = require('crypto'),
defaultEncoding = 'utf8',
defaultHostPattern = /^sns\.[a-zA-Z0-9\-]{3,}\.amazonaws\.com(\.cn)?$/,
certCache = {},
subscriptionControlKeys = ['SubscribeURL', 'Token'],
subscriptionControlMessageTypes = [
'SubscriptionConfirmation',
'UnsubscribeConfirmation'
],
requiredKeys = [
'Message',
'MessageId',
'Timestamp',
'TopicArn',
'Type',
'Signature',
'SigningCertURL',
'SignatureVersion'
],
signableKeysForNotification = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'TopicArn',
'Type'
],
signableKeysForSubscription = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type'
],
lambdaMessageKeys = {
'SigningCertUrl': 'SigningCertURL',
'UnsubscribeUrl': 'UnsubscribeURL'
};
var hashHasKeys = function (hash, keys) {
for (var i = 0; i < keys.length; i++) {
if (!(keys[i] in hash)) {
return false;
}
}
return true;
};
var indexOf = function (array, value) {
for (var i = 0; i < array.length; i++) {
if (value === array[i]) {
return i;
}
}
return -1;
};
function convertLambdaMessage(message) {
for (var key in lambdaMessageKeys) {
if (key in message) {
message[lambdaMessageKeys[key]] = message[key];
}
}
if ('Subject' in message && message.Subject === null) {
delete message.Subject;
}
return message;
}
var validateMessageStructure = function (message) {
var valid = hashHasKeys(message, requiredKeys);
if (indexOf(subscriptionControlMessageTypes, message['Type']) > -1) {
valid = valid && hashHasKeys(message, subscriptionControlKeys);
}
return valid;
};
var validateUrl = function (urlToValidate, hostPattern) {
var parsed = url.parse(urlToValidate);
return parsed.protocol === 'https:'
&& parsed.path.substr(-4) === '.pem'
&& hostPattern.test(parsed.host);
};
var getCertificate = function (certUrl, cb) {
if (certCache.hasOwnProperty(certUrl)) {
cb(null, certCache[certUrl]);
return;
}
https.get(certUrl, function (res) {
var chunks = [];
if(res.statusCode !== 200){
return cb(new Error('Certificate could not be retrieved'));
}
res
.on('data', function (data) {
chunks.push(data.toString());
})
.on('end', function () {
certCache[certUrl] = chunks.join('');
cb(null, certCache[certUrl]);
});
}).on('error', cb)
};
var validateSignature = function (message, cb, encoding) {
var signatureVersion = message['SignatureVersion'];
if (signatureVersion !== '1' && signatureVersion !== '2') {
cb(new Error('The signature version '
+ signatureVersion + ' is not supported.'));
return;
}
var signableKeys = [];
if (message.Type === 'SubscriptionConfirmation') {
signableKeys = signableKeysForSubscription.slice(0);
} else {
signableKeys = signableKeysForNotification.slice(0);
}
var verifier = (signatureVersion === '1') ? crypto.createVerify('RSA-SHA1') : crypto.createVerify('RSA-SHA256');
for (var i = 0; i < signableKeys.length; i++) {
if (signableKeys[i] in message) {
verifier.update(signableKeys[i] + "\n"
+ message[signableKeys[i]] + "\n", encoding);
}
}
getCertificate(message['SigningCertURL'], function (err, certificate) {
if (err) {
cb(err);
return;
}
try {
if (verifier.verify(certificate, message['Signature'], 'base64')) {
cb(null, message);
} else {
cb(new Error('The message signature is invalid.'));
}
} catch (e) {
cb(e);
}
});
};
/**
* A validator for inbound HTTP(S) SNS messages.
*
* @constructor
* @param {RegExp} [hostPattern=/^sns\.[a-zA-Z0-9\-]{3,}\.amazonaws\.com(\.cn)?$/] - A pattern used to validate that a message's certificate originates from a trusted domain.
* @param {String} [encoding='utf8'] - The encoding of the messages being signed.
*/
function MessageValidator(hostPattern, encoding) {
this.hostPattern = hostPattern || defaultHostPattern;
this.encoding = encoding || defaultEncoding;
}
/**
* A callback to be called by the validator once it has verified a message's
* signature.
*
* @callback validationCallback
* @param {Error} error - Any error encountered attempting to validate a
* message's signature.
* @param {Object} message - The validated inbound SNS message.
*/
/**
* Validates a message's signature and passes it to the provided callback.
*
* @param {Object} hash
* @param {validationCallback} cb
*/
MessageValidator.prototype.validate = function (hash, cb) {
if (typeof hash === 'string') {
try {
hash = JSON.parse(hash);
} catch (err) {
cb(err);
return;
}
}
hash = convertLambdaMessage(hash);
if (!validateMessageStructure(hash)) {
cb(new Error('Message missing required keys.'));
return;
}
if (!validateUrl(hash['SigningCertURL'], this.hostPattern)) {
cb(new Error('The certificate is located on an invalid domain.'));
return;
}
validateSignature(hash, cb, this.encoding);
};
module.exports = MessageValidator;