]> cat aescling's git repositories - mastodon.git/blob - streaming/index.js
Improve streaming server security (#10818)
[mastodon.git] / streaming / index.js
1 const os = require('os');
2 const throng = require('throng');
3 const dotenv = require('dotenv');
4 const express = require('express');
5 const http = require('http');
6 const redis = require('redis');
7 const pg = require('pg');
8 const log = require('npmlog');
9 const url = require('url');
10 const { WebSocketServer } = require('@clusterws/cws');
11 const uuid = require('uuid');
12 const fs = require('fs');
13
14 const env = process.env.NODE_ENV || 'development';
15
16 dotenv.config({
17 path: env === 'production' ? '.env.production' : '.env',
18 });
19
20 log.level = process.env.LOG_LEVEL || 'verbose';
21
22 const dbUrlToConfig = (dbUrl) => {
23 if (!dbUrl) {
24 return {};
25 }
26
27 const params = url.parse(dbUrl, true);
28 const config = {};
29
30 if (params.auth) {
31 [config.user, config.password] = params.auth.split(':');
32 }
33
34 if (params.hostname) {
35 config.host = params.hostname;
36 }
37
38 if (params.port) {
39 config.port = params.port;
40 }
41
42 if (params.pathname) {
43 config.database = params.pathname.split('/')[1];
44 }
45
46 const ssl = params.query && params.query.ssl;
47
48 if (ssl && ssl === 'true' || ssl === '1') {
49 config.ssl = true;
50 }
51
52 return config;
53 };
54
55 const redisUrlToClient = (defaultConfig, redisUrl) => {
56 const config = defaultConfig;
57
58 if (!redisUrl) {
59 return redis.createClient(config);
60 }
61
62 if (redisUrl.startsWith('unix://')) {
63 return redis.createClient(redisUrl.slice(7), config);
64 }
65
66 return redis.createClient(Object.assign(config, {
67 url: redisUrl,
68 }));
69 };
70
71 const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
72
73 const startMaster = () => {
74 if (!process.env.SOCKET && process.env.PORT && isNaN(+process.env.PORT)) {
75 log.warn('UNIX domain socket is now supported by using SOCKET. Please migrate from PORT hack.');
76 }
77
78 log.info(`Starting streaming API server master with ${numWorkers} workers`);
79 };
80
81 const startWorker = (workerId) => {
82 log.info(`Starting worker ${workerId}`);
83
84 const pgConfigs = {
85 development: {
86 user: process.env.DB_USER || pg.defaults.user,
87 password: process.env.DB_PASS || pg.defaults.password,
88 database: process.env.DB_NAME || 'mastodon_development',
89 host: process.env.DB_HOST || pg.defaults.host,
90 port: process.env.DB_PORT || pg.defaults.port,
91 max: 10,
92 },
93
94 production: {
95 user: process.env.DB_USER || 'mastodon',
96 password: process.env.DB_PASS || '',
97 database: process.env.DB_NAME || 'mastodon_production',
98 host: process.env.DB_HOST || 'localhost',
99 port: process.env.DB_PORT || 5432,
100 max: 10,
101 },
102 };
103
104 if (!!process.env.DB_SSLMODE && process.env.DB_SSLMODE !== 'disable') {
105 pgConfigs.development.ssl = true;
106 pgConfigs.production.ssl = true;
107 }
108
109 const app = express();
110 app.set('trusted proxy', process.env.TRUSTED_PROXY_IP || 'loopback,uniquelocal');
111
112 const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
113 const server = http.createServer(app);
114 const redisNamespace = process.env.REDIS_NAMESPACE || null;
115
116 const redisParams = {
117 host: process.env.REDIS_HOST || '127.0.0.1',
118 port: process.env.REDIS_PORT || 6379,
119 db: process.env.REDIS_DB || 0,
120 password: process.env.REDIS_PASSWORD,
121 };
122
123 if (redisNamespace) {
124 redisParams.namespace = redisNamespace;
125 }
126
127 const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
128
129 const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
130 const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
131
132 const subs = {};
133
134 redisSubscribeClient.on('message', (channel, message) => {
135 const callbacks = subs[channel];
136
137 log.silly(`New message on channel ${channel}`);
138
139 if (!callbacks) {
140 return;
141 }
142
143 callbacks.forEach(callback => callback(message));
144 });
145
146 const subscriptionHeartbeat = (channel) => {
147 const interval = 6*60;
148 const tellSubscribed = () => {
149 redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval*3);
150 };
151 tellSubscribed();
152 const heartbeat = setInterval(tellSubscribed, interval*1000);
153 return () => {
154 clearInterval(heartbeat);
155 };
156 };
157
158 const subscribe = (channel, callback) => {
159 log.silly(`Adding listener for ${channel}`);
160 subs[channel] = subs[channel] || [];
161 if (subs[channel].length === 0) {
162 log.verbose(`Subscribe ${channel}`);
163 redisSubscribeClient.subscribe(channel);
164 }
165 subs[channel].push(callback);
166 };
167
168 const unsubscribe = (channel, callback) => {
169 log.silly(`Removing listener for ${channel}`);
170 subs[channel] = subs[channel].filter(item => item !== callback);
171 if (subs[channel].length === 0) {
172 log.verbose(`Unsubscribe ${channel}`);
173 redisSubscribeClient.unsubscribe(channel);
174 }
175 };
176
177 const allowCrossDomain = (req, res, next) => {
178 res.header('Access-Control-Allow-Origin', '*');
179 res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
180 res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
181
182 next();
183 };
184
185 const setRequestId = (req, res, next) => {
186 req.requestId = uuid.v4();
187 res.header('X-Request-Id', req.requestId);
188
189 next();
190 };
191
192 const setRemoteAddress = (req, res, next) => {
193 req.remoteAddress = req.connection.remoteAddress;
194
195 next();
196 };
197
198 const accountFromToken = (token, allowedScopes, req, next) => {
199 pgPool.connect((err, client, done) => {
200 if (err) {
201 next(err);
202 return;
203 }
204
205 client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.chosen_languages, oauth_access_tokens.scopes FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 AND oauth_access_tokens.revoked_at IS NULL LIMIT 1', [token], (err, result) => {
206 done();
207
208 if (err) {
209 next(err);
210 return;
211 }
212
213 if (result.rows.length === 0) {
214 err = new Error('Invalid access token');
215 err.statusCode = 401;
216
217 next(err);
218 return;
219 }
220
221 const scopes = result.rows[0].scopes.split(' ');
222
223 if (allowedScopes.size > 0 && !scopes.some(scope => allowedScopes.includes(scope))) {
224 err = new Error('Access token does not cover required scopes');
225 err.statusCode = 401;
226
227 next(err);
228 return;
229 }
230
231 req.accountId = result.rows[0].account_id;
232 req.chosenLanguages = result.rows[0].chosen_languages;
233 req.allowNotifications = scopes.some(scope => ['read', 'read:notifications'].includes(scope));
234
235 next();
236 });
237 });
238 };
239
240 const accountFromRequest = (req, next, required = true, allowedScopes = ['read']) => {
241 const authorization = req.headers.authorization;
242 const location = url.parse(req.url, true);
243 const accessToken = location.query.access_token || req.headers['sec-websocket-protocol'];
244
245 if (!authorization && !accessToken) {
246 if (required) {
247 const err = new Error('Missing access token');
248 err.statusCode = 401;
249
250 next(err);
251 return;
252 } else {
253 next();
254 return;
255 }
256 }
257
258 const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
259
260 accountFromToken(token, allowedScopes, req, next);
261 };
262
263 const PUBLIC_STREAMS = [
264 'public',
265 'public:media',
266 'public:local',
267 'public:local:media',
268 'hashtag',
269 'hashtag:local',
270 ];
271
272 const wsVerifyClient = (info, cb) => {
273 const location = url.parse(info.req.url, true);
274 const authRequired = !PUBLIC_STREAMS.some(stream => stream === location.query.stream);
275 const allowedScopes = [];
276
277 if (authRequired) {
278 allowedScopes.push('read');
279 if (location.query.stream === 'user:notification') {
280 allowedScopes.push('read:notifications');
281 } else {
282 allowedScopes.push('read:statuses');
283 }
284 }
285
286 accountFromRequest(info.req, err => {
287 if (!err) {
288 cb(true, undefined, undefined);
289 } else {
290 log.error(info.req.requestId, err.toString());
291 cb(false, 401, 'Unauthorized');
292 }
293 }, authRequired, allowedScopes);
294 };
295
296 const PUBLIC_ENDPOINTS = [
297 '/api/v1/streaming/public',
298 '/api/v1/streaming/public/local',
299 '/api/v1/streaming/hashtag',
300 '/api/v1/streaming/hashtag/local',
301 ];
302
303 const authenticationMiddleware = (req, res, next) => {
304 if (req.method === 'OPTIONS') {
305 next();
306 return;
307 }
308
309 const authRequired = !PUBLIC_ENDPOINTS.some(endpoint => endpoint === req.path);
310 const allowedScopes = [];
311
312 if (authRequired) {
313 allowedScopes.push('read');
314 if (req.path === '/api/v1/streaming/user/notification') {
315 allowedScopes.push('read:notifications');
316 } else {
317 allowedScopes.push('read:statuses');
318 }
319 }
320
321 accountFromRequest(req, next, authRequired, allowedScopes);
322 };
323
324 const errorMiddleware = (err, req, res, {}) => {
325 log.error(req.requestId, err.toString());
326 res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
327 res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
328 };
329
330 const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
331
332 const authorizeListAccess = (id, req, next) => {
333 pgPool.connect((err, client, done) => {
334 if (err) {
335 next(false);
336 return;
337 }
338
339 client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [id], (err, result) => {
340 done();
341
342 if (err || result.rows.length === 0 || result.rows[0].account_id !== req.accountId) {
343 next(false);
344 return;
345 }
346
347 next(true);
348 });
349 });
350 };
351
352 const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
353 const accountId = req.accountId || req.remoteAddress;
354
355 const streamType = notificationOnly ? ' (notification)' : '';
356 log.verbose(req.requestId, `Starting stream from ${id} for ${accountId}${streamType}`);
357
358 const listener = message => {
359 const { event, payload, queued_at } = JSON.parse(message);
360
361 const transmit = () => {
362 const now = new Date().getTime();
363 const delta = now - queued_at;
364 const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
365
366 log.silly(req.requestId, `Transmitting for ${accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
367 output(event, encodedPayload);
368 };
369
370 if (notificationOnly && event !== 'notification') {
371 return;
372 }
373
374 if (event === 'notification' && !req.allowNotifications) {
375 return;
376 }
377
378 // Only messages that may require filtering are statuses, since notifications
379 // are already personalized and deletes do not matter
380 if (!needsFiltering || event !== 'update') {
381 transmit();
382 return;
383 }
384
385 const unpackedPayload = payload;
386 const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
387 const accountDomain = unpackedPayload.account.acct.split('@')[1];
388
389 if (Array.isArray(req.chosenLanguages) && unpackedPayload.language !== null && req.chosenLanguages.indexOf(unpackedPayload.language) === -1) {
390 log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
391 return;
392 }
393
394 // When the account is not logged in, it is not necessary to confirm the block or mute
395 if (!req.accountId) {
396 transmit();
397 return;
398 }
399
400 pgPool.connect((err, client, done) => {
401 if (err) {
402 log.error(err);
403 return;
404 }
405
406 const queries = [
407 client.query(`SELECT 1 FROM blocks WHERE (account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})) OR (account_id = $2 AND target_account_id = $1) UNION SELECT 1 FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})`, [req.accountId, unpackedPayload.account.id].concat(targetAccountIds)),
408 ];
409
410 if (accountDomain) {
411 queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
412 }
413
414 Promise.all(queries).then(values => {
415 done();
416
417 if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
418 return;
419 }
420
421 transmit();
422 }).catch(err => {
423 done();
424 log.error(err);
425 });
426 });
427 };
428
429 subscribe(`${redisPrefix}${id}`, listener);
430 attachCloseHandler(`${redisPrefix}${id}`, listener);
431 };
432
433 // Setup stream output to HTTP
434 const streamToHttp = (req, res) => {
435 const accountId = req.accountId || req.remoteAddress;
436
437 res.setHeader('Content-Type', 'text/event-stream');
438 res.setHeader('Transfer-Encoding', 'chunked');
439
440 const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
441
442 req.on('close', () => {
443 log.verbose(req.requestId, `Ending stream for ${accountId}`);
444 clearInterval(heartbeat);
445 });
446
447 return (event, payload) => {
448 res.write(`event: ${event}\n`);
449 res.write(`data: ${payload}\n\n`);
450 };
451 };
452
453 // Setup stream end for HTTP
454 const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
455 req.on('close', () => {
456 unsubscribe(id, listener);
457 if (closeHandler) {
458 closeHandler();
459 }
460 });
461 };
462
463 // Setup stream output to WebSockets
464 const streamToWs = (req, ws) => (event, payload) => {
465 if (ws.readyState !== ws.OPEN) {
466 log.error(req.requestId, 'Tried writing to closed socket');
467 return;
468 }
469
470 ws.send(JSON.stringify({ event, payload }));
471 };
472
473 // Setup stream end for WebSockets
474 const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
475 const accountId = req.accountId || req.remoteAddress;
476
477 ws.on('close', () => {
478 log.verbose(req.requestId, `Ending stream for ${accountId}`);
479 unsubscribe(id, listener);
480 if (closeHandler) {
481 closeHandler();
482 }
483 });
484
485 ws.on('error', () => {
486 log.verbose(req.requestId, `Ending stream for ${accountId}`);
487 unsubscribe(id, listener);
488 if (closeHandler) {
489 closeHandler();
490 }
491 });
492 };
493
494 const httpNotFound = res => {
495 res.writeHead(404, { 'Content-Type': 'application/json' });
496 res.end(JSON.stringify({ error: 'Not found' }));
497 };
498
499 app.use(setRequestId);
500 app.use(setRemoteAddress);
501 app.use(allowCrossDomain);
502
503 app.get('/api/v1/streaming/health', (req, res) => {
504 res.writeHead(200, { 'Content-Type': 'text/plain' });
505 res.end('OK');
506 });
507
508 app.use(authenticationMiddleware);
509 app.use(errorMiddleware);
510
511 app.get('/api/v1/streaming/user', (req, res) => {
512 const channel = `timeline:${req.accountId}`;
513 streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
514 });
515
516 app.get('/api/v1/streaming/user/notification', (req, res) => {
517 streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
518 });
519
520 app.get('/api/v1/streaming/public', (req, res) => {
521 const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
522 const channel = onlyMedia ? 'timeline:public:media' : 'timeline:public';
523
524 streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
525 });
526
527 app.get('/api/v1/streaming/public/local', (req, res) => {
528 const onlyMedia = req.query.only_media === '1' || req.query.only_media === 'true';
529 const channel = onlyMedia ? 'timeline:public:local:media' : 'timeline:public:local';
530
531 streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req), true);
532 });
533
534 app.get('/api/v1/streaming/direct', (req, res) => {
535 const channel = `timeline:direct:${req.accountId}`;
536 streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)), true);
537 });
538
539 app.get('/api/v1/streaming/hashtag', (req, res) => {
540 const { tag } = req.query;
541
542 if (!tag || tag.length === 0) {
543 httpNotFound(res);
544 return;
545 }
546
547 streamFrom(`timeline:hashtag:${tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
548 });
549
550 app.get('/api/v1/streaming/hashtag/local', (req, res) => {
551 const { tag } = req.query;
552
553 if (!tag || tag.length === 0) {
554 httpNotFound(res);
555 return;
556 }
557
558 streamFrom(`timeline:hashtag:${tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
559 });
560
561 app.get('/api/v1/streaming/list', (req, res) => {
562 const listId = req.query.list;
563
564 authorizeListAccess(listId, req, authorized => {
565 if (!authorized) {
566 httpNotFound(res);
567 return;
568 }
569
570 const channel = `timeline:list:${listId}`;
571 streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
572 });
573 });
574
575 const wss = new WebSocketServer({ server, verifyClient: wsVerifyClient });
576
577 wss.on('connection', (ws, req) => {
578 const location = url.parse(req.url, true);
579 req.requestId = uuid.v4();
580 req.remoteAddress = ws._socket.remoteAddress;
581
582 let channel;
583
584 switch(location.query.stream) {
585 case 'user':
586 channel = `timeline:${req.accountId}`;
587 streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
588 break;
589 case 'user:notification':
590 streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
591 break;
592 case 'public':
593 streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
594 break;
595 case 'public:local':
596 streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
597 break;
598 case 'public:media':
599 streamFrom('timeline:public:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
600 break;
601 case 'public:local:media':
602 streamFrom('timeline:public:local:media', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
603 break;
604 case 'direct':
605 channel = `timeline:direct:${req.accountId}`;
606 streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)), true);
607 break;
608 case 'hashtag':
609 if (!location.query.tag || location.query.tag.length === 0) {
610 ws.close();
611 return;
612 }
613
614 streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
615 break;
616 case 'hashtag:local':
617 if (!location.query.tag || location.query.tag.length === 0) {
618 ws.close();
619 return;
620 }
621
622 streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
623 break;
624 case 'list':
625 const listId = location.query.list;
626
627 authorizeListAccess(listId, req, authorized => {
628 if (!authorized) {
629 ws.close();
630 return;
631 }
632
633 channel = `timeline:list:${listId}`;
634 streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
635 });
636 break;
637 default:
638 ws.close();
639 }
640 });
641
642 wss.startAutoPing(30000);
643
644 attachServerWithConfig(server, address => {
645 log.info(`Worker ${workerId} now listening on ${address}`);
646 });
647
648 const onExit = () => {
649 log.info(`Worker ${workerId} exiting, bye bye`);
650 server.close();
651 process.exit(0);
652 };
653
654 const onError = (err) => {
655 log.error(err);
656 server.close();
657 process.exit(0);
658 };
659
660 process.on('SIGINT', onExit);
661 process.on('SIGTERM', onExit);
662 process.on('exit', onExit);
663 process.on('uncaughtException', onError);
664 };
665
666 const attachServerWithConfig = (server, onSuccess) => {
667 if (process.env.SOCKET || process.env.PORT && isNaN(+process.env.PORT)) {
668 server.listen(process.env.SOCKET || process.env.PORT, () => {
669 if (onSuccess) {
670 fs.chmodSync(server.address(), 0o666);
671 onSuccess(server.address());
672 }
673 });
674 } else {
675 server.listen(+process.env.PORT || 4000, process.env.BIND || '0.0.0.0', () => {
676 if (onSuccess) {
677 onSuccess(`${server.address().address}:${server.address().port}`);
678 }
679 });
680 }
681 };
682
683 const onPortAvailable = onSuccess => {
684 const testServer = http.createServer();
685
686 testServer.once('error', err => {
687 onSuccess(err);
688 });
689
690 testServer.once('listening', () => {
691 testServer.once('close', () => onSuccess());
692 testServer.close();
693 });
694
695 attachServerWithConfig(testServer);
696 };
697
698 onPortAvailable(err => {
699 if (err) {
700 log.error('Could not start server, the port or socket is in use');
701 return;
702 }
703
704 throng({
705 workers: numWorkers,
706 lifetime: Infinity,
707 start: startWorker,
708 master: startMaster,
709 });
710 });
This page took 0.263325 seconds and 4 git commands to generate.