-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdevice-proxy.ts
287 lines (267 loc) · 8.08 KB
/
device-proxy.ts
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import * as _ from 'lodash';
import * as Promise from 'bluebird';
import { NoDevicesFoundError } from '../lib/errors';
import {
captureException,
translateError,
handleHttpErrors,
} from '../platform/errors';
import { checkInt } from './utils';
import { sbvrUtils } from '../platform';
import { Request, Response } from 'express';
import { PinejsClientCoreFactory } from 'pinejs-client-core';
import { resinApi, root } from '../platform';
import { RequestResponse, requestAsync } from './request';
import { API_VPN_SERVICE_API_KEY } from './config';
// Degraded network, slow devices, compressed docker binaries and any combination of these factors
// can cause proxied device requests to surpass the default timeout.
const DEVICE_REQUEST_TIMEOUT = 50000;
const DELAY_BETWEEN_DEVICE_REQUEST = 50;
const { BadRequestError } = sbvrUtils;
const badSupervisorResponse = (
req: Request,
res: Response,
filter: PinejsClientCoreFactory.Filter,
reason: string,
) => {
// Log incident!
const err = new Error(
`${reason} (device: ${JSON.stringify(filter)}) (url: ${req.originalUrl})`,
);
captureException(err, 'Received invalid supervisor response', { req });
res.status(500).json({ error: 'Bad API response from supervisor' });
};
const validateSupervisorResponse = (
response: RequestResponse,
req: Request,
res: Response,
filter: PinejsClientCoreFactory.Filter,
) => {
const [{ statusCode, headers }, body] = response;
const contentType = headers != null ? headers['content-type'] : undefined;
if (contentType != null) {
if (/^application\/json/i.test(contentType)) {
let jsonBody;
if (_.isObject(body)) {
jsonBody = body;
} else {
try {
jsonBody = JSON.parse(body);
} catch (e) {
return badSupervisorResponse(req, res, filter, 'Invalid JSON data');
}
}
res.status(statusCode).json(jsonBody);
} else if (/^text\/(plain|html)/.test(contentType)) {
if (/^([A-Za-z0-9\s:'\.\?!,\/-])*$/g.test(body)) {
res
.status(statusCode)
.set('Content-Type', 'text/plain')
.send(body);
} else {
badSupervisorResponse(req, res, filter, 'Invalid TEXT data');
}
} else {
badSupervisorResponse(
req,
res,
filter,
'Invalid content-type: ' + contentType,
);
}
} else {
res.status(statusCode).end();
}
};
const multiResponse = (responses: RequestResponse[]) =>
_.map(responses, ([response]) => _.pick(response, 'statusCode', 'body'));
export const proxy = (req: Request, res: Response) => {
const filter: PinejsClientCoreFactory.Filter = {};
return Promise.try(() => {
const url = req.params[0];
if (url == null) {
throw new BadRequestError('Supervisor API url must be specified');
}
const { appId, deviceId, uuid, data, method } = req.body;
// Only check the validity of ids if they exist.
if (appId != null) {
filter.belongs_to__application = checkInt(appId);
if (filter.belongs_to__application === false) {
throw new BadRequestError(
'App ID must be a valid integer if specified',
);
}
}
if (deviceId != null) {
filter.id = checkInt(deviceId);
if (filter.id === false) {
throw new BadRequestError(
'Device ID must be a valid integer if specified',
);
}
}
if (uuid != null) {
if (!_.isString(uuid)) {
throw new BadRequestError('UUID must be a valid string if specified');
}
filter.uuid = uuid;
}
// Make sure at least one id has been set (filter isn't empty), and that the values for it are valid
if (_.isEmpty(filter)) {
throw new BadRequestError('At least one filter must be specified');
}
return requestDevices({ url, req, filter, data, method });
})
.then(responses => {
if (responses.length === 1) {
return validateSupervisorResponse(responses[0], req, res, filter);
}
res.status(207).json(multiResponse(responses));
})
.catch(err => {
if (handleHttpErrors(req, res, err)) {
return;
}
if (err != null && err.body != null) {
err = err.body;
}
res.status(502).send(translateError(err));
});
};
interface FixedMethodRequestDevicesOpts {
url: string;
filter: PinejsClientCoreFactory.Filter;
data?: AnyObject;
req?: sbvrUtils.Passthrough['req'];
wait?: boolean;
}
interface RequestDevicesOpts extends FixedMethodRequestDevicesOpts {
method: string;
}
// - req is the express req object, if passed then(the permissions of the user making
// the request will be used to get devices,
// if it is not passed then("guest" permissions will be used to get the devices.
// - method is the HTTP method for the request, defaults to 'POST'
export function requestDevices(
opts: RequestDevicesOpts & {
wait?: true;
},
): Promise<RequestResponse[]>;
export function requestDevices(
opts: RequestDevicesOpts & {
wait: false;
},
): Promise<void>;
// This override is identical to the main form in order for `postDevices` to be able to call it with the generic form
export function requestDevices(
opts: RequestDevicesOpts,
): Promise<void | RequestResponse[]>;
export function requestDevices({
url,
filter,
data,
req,
wait = true,
method = 'POST',
}: RequestDevicesOpts): Promise<void | RequestResponse[]> {
if (url == null) {
return Promise.reject(
new BadRequestError('You must specify a url to request!'),
);
}
method = method.toUpperCase();
if (!_.includes(['PUT', 'PATCH', 'POST', 'HEAD', 'DELETE', 'GET'], method)) {
return Promise.reject(new BadRequestError(`Invalid method '${method}'`));
}
return resinApi
.get({
resource: 'device',
options: {
$select: 'id',
$filter: {
$and: [
{
is_connected_to_vpn: true,
vpn_address: { $ne: null },
},
filter,
],
},
},
passthrough: { req },
})
.then((devices: AnyObject[]) => {
if (devices.length === 0) {
if (!wait) {
// Don't throw an error if it's a fire/forget
return;
}
throw new NoDevicesFoundError('No online device(s) found');
}
// And now fetch device data with full privs
return resinApi
.get({
resource: 'device',
passthrough: { req: root },
options: {
$select: ['api_port', 'api_secret', 'uuid'],
$expand: {
is_managed_by__service_instance: { $select: 'ip_address' },
},
$filter: {
id: { $in: _.map(devices, 'id') },
is_managed_by__service_instance: {
$any: {
$alias: 'si',
$expr: { si: { ip_address: { $ne: null } } },
},
},
},
},
})
.then<void | RequestResponse[]>((devices: AnyObject[]) => {
const promises: Array<ReturnType<typeof requestAsync>> = [];
const waitPromise = Promise.each(devices, device => {
const vpnIp = device.is_managed_by__service_instance[0].ip_address;
const deviceUrl = `http://${device.uuid}.resin:${device.api_port ||
80}${url}?apikey=${device.api_secret}`;
promises.push(
requestAsync({
uri: deviceUrl,
json: data,
proxy: `http://resin_api:${API_VPN_SERVICE_API_KEY}@${vpnIp}:3128`,
tunnel: true,
method: method,
timeout: DEVICE_REQUEST_TIMEOUT,
}),
);
// We add a delay between each notification so that we do not in essence trigger a DDOS from resin
// devices against us, but we do not wait for completion of individual requests because doing so
// could cause a terrible UX if we have a device time out, as that would block all the subsequent
// notifications
return Promise.delay(DELAY_BETWEEN_DEVICE_REQUEST);
}).then(() => Promise.all(promises));
if (!wait) {
// We return null if not waiting in order to stop bluebird warnings, and we cast as void to keep the
// void typing (ie that the result should not be used for this case)
return (null as any) as void;
}
return waitPromise;
});
});
}
export function postDevices(
opts: FixedMethodRequestDevicesOpts & {
wait?: true;
},
): Promise<RequestResponse[]>;
export function postDevices(
opts: FixedMethodRequestDevicesOpts & {
wait: false;
},
): Promise<void>;
export function postDevices(
opts: FixedMethodRequestDevicesOpts,
): Promise<void | RequestResponse[]> {
return requestDevices(_.defaults({ method: 'POST' }, opts));
}