-
Notifications
You must be signed in to change notification settings - Fork 21
/
utils.js
199 lines (186 loc) · 5.71 KB
/
utils.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
const axios = require('axios');
const dnsUtils = require('./dnsUtils');
const ipRangeCheck = require('ip-range-check');
const logger = require('./logger');
const net = require('net');
const uuidv4 = require('uuid').v4;
/**
* Authenticate the request, if auth configured.
*
* If UVS_AUTH_TOKEN is set, we'll require that
* in a bearer token authorization header.
*
* Updates the response and returns false on rejection.
*
* @param req Request
* @param res Response
* @return {boolean} false if auth failed
*/
function authenticateRequest(req, res) {
if (!process.env.UVS_AUTH_TOKEN) {
return true;
}
const authorization = req.header('Authorization');
if (!authorization) {
res.status(403);
res.send({});
logger.log('warn', 'No authorization header found.', {requestId: req.requestId});
return false;
}
try {
const parts = authorization.split(' ');
const result = parts[0] === 'Bearer' && parts[1] === process.env.UVS_AUTH_TOKEN;
if (result) {
return true;
}
} catch (error) {
logger.log('warn', 'Failed to parse authentication header.', {requestId: req.requestId});
res.status(403);
res.send({});
return false;
}
logger.log('warn', 'Invalid Authorization header or wrong token.', {requestId: req.requestId});
res.status(403);
res.send({});
return false;
}
function tryStringify(obj) {
try {
return JSON.stringify(obj);
} catch (error) {
return obj;
}
}
function errorLogger(error, req) {
if (error.response) {
const response = error.response;
if (response.headers.authorization) {
// Redact token from logs
response.headers.authorization = 'Bearer <redacted>';
}
logger.log(
'debug',
`Verify token failed: ${response.status}, ${tryStringify(response.headers)}, ${tryStringify(response.data)}`,
{requestId: req.requestId},
);
} else if (error.request) {
logger.log('error', `No response received: ${tryStringify(error.request)}`, {requestId: req.requestId});
} else {
logger.log('error', `Failed to make verify request: ${error.message}`, {requestId: req.requestId});
}
}
function requestLogger(req) {
if (!req.requestId) {
req.requestId = uuidv4();
}
if (req.method === 'POST') {
let loggedBody = Object.assign({}, req.body);
if (loggedBody.token) {
// Ensure we don't log the token
loggedBody.token = '<redacted>';
}
logger.log('info', `${req.method} ${req.path}: ${tryStringify(loggedBody)}`, {requestId: req.requestId});
} else {
logger.log('info', `${req.method} ${req.path}`,{requestId: req.requestId});
}
}
const ip4RangeBlacklist = [
'127.0.0.0/8',
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'100.64.0.0/10',
'192.0.0.0/24',
'169.254.0.0/16',
'198.18.0.0/15',
'192.0.2.0/24',
'198.51.100.0/24',
'203.0.113.0/24',
'224.0.0.0/4',
];
const ip6RangeBlacklist = [
'::1/128',
'fe80::/10',
'fc00::/7',
'fec0::/10',
];
const ip6FromIp4Blacklist = ip4RangeBlacklist.map(a => `::ffff:${a}`);
const ipRangeBlacklist = [
...ip4RangeBlacklist,
...ip6RangeBlacklist,
...ip6FromIp4Blacklist,
];
/**
* Check if a domain is blacklisted via IP ranges.
*
* If it's not an IP already, resolve any addresses and check them all separately.
*
* @param {string} domain Domain to check
* @returns {Promise<boolean>} true if blacklisted
*/
async function isDomainBlacklisted(domain) {
let addresses;
if (!net.isIP(domain)) {
try {
addresses = await dnsUtils.resolve(domain);
} catch (error) {
return true;
}
if (addresses.length === 0) {
return true;
}
} else {
addresses = [domain];
}
return addresses.some(a => ipRangeCheck(a, ipRangeBlacklist));
}
/**
* Wrapped Axios GET.
*
* Check all requests, including the redirects against our blacklist.
* Also implements some other sane defaults like timeouts.
*
* @param {string} url URL to call
* @param {number|null} haveRedirectedTimes Counter how many times we've redirected already
* @param {object|null} headers Extra headers to use
* @returns {Promise<object>} Response object
* @throws On non-20x response (after redirects) or a blacklisted domain
*/
async function axiosGet(url, haveRedirectedTimes = null, headers = null) {
let redirects = haveRedirectedTimes;
if (!redirects) {
redirects = 0;
}
const urlObj = new URL(url);
if (await isDomainBlacklisted(urlObj.hostname)) {
throw new Error(`Refusing to call blacklisted or unresolved hostname ${urlObj.hostname}`);
}
const response = await axios.get(
url,
{
headers,
maxRedirects: 0,
timeout: 10000,
validateStatus: function (status) {
// Include redirects as OK here, since we control that separately
return status >= 200 && status < 400;
},
},
);
if (response.status >= 300) {
if (redirects >= 4) {
// This was the fourth time following a redirect, abort
throw new Error('Maximum amount of redirects reached.');
}
return axiosGet(response.headers.location, redirects + 1, headers);
}
return response;
}
module.exports = {
authenticateRequest,
axiosGet,
errorLogger,
isDomainBlacklisted,
requestLogger,
tryStringify,
};