Router.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. const metrics = require('@overleaf/metrics')
  2. const logger = require('@overleaf/logger')
  3. const settings = require('@overleaf/settings')
  4. const WebsocketController = require('./WebsocketController')
  5. const HttpController = require('./HttpController')
  6. const HttpApiController = require('./HttpApiController')
  7. const WebsocketAddressManager = require('./WebsocketAddressManager')
  8. const bodyParser = require('body-parser')
  9. const base64id = require('base64id')
  10. const { UnexpectedArgumentsError } = require('./Errors')
  11. const Joi = require('joi')
  12. const HOSTNAME = require('node:os').hostname()
  13. const SERVER_PING_INTERVAL = 15000
  14. const SERVER_PING_LATENCY_THRESHOLD = 5000
  15. const JOI_OBJECT_ID = Joi.string()
  16. .required()
  17. .regex(/^[0-9a-f]{24}$/)
  18. .message('invalid id')
  19. let Router
  20. module.exports = Router = {
  21. _handleError(callback, error, client, method, attrs) {
  22. attrs = attrs || {}
  23. for (const key of ['project_id', 'user_id']) {
  24. attrs[key] = attrs[key] || client.ol_context[key]
  25. }
  26. attrs.client_id = client.id
  27. attrs.err = error
  28. attrs.method = method
  29. if (Joi.isError(error)) {
  30. logger.info(attrs, 'validation error')
  31. let message = 'invalid'
  32. try {
  33. message = error.details[0].message
  34. } catch (e) {
  35. // ignore unexpected errors
  36. logger.warn({ error, e }, 'unexpected validation error')
  37. }
  38. const serializedError = { message }
  39. metrics.inc('validation-error', 1, {
  40. status: method,
  41. })
  42. callback(serializedError)
  43. } else if (error.name === 'CodedError') {
  44. logger.warn(attrs, error.message)
  45. const serializedError = { message: error.message, code: error.info.code }
  46. callback(serializedError)
  47. } else if (error.message === 'unexpected arguments') {
  48. // the payload might be very large; put it on level debug
  49. logger.debug(attrs, 'unexpected arguments')
  50. metrics.inc('unexpected-arguments', 1, { status: method })
  51. const serializedError = { message: error.message }
  52. callback(serializedError)
  53. } else if (error.message === 'no project_id found on client') {
  54. logger.debug(attrs, error.message)
  55. const serializedError = { message: error.message }
  56. callback(serializedError)
  57. } else if (
  58. [
  59. 'not authorized',
  60. 'joinLeaveEpoch mismatch',
  61. 'doc updater could not load requested ops',
  62. 'no project_id found on client',
  63. 'cannot join multiple projects',
  64. ].includes(error.message)
  65. ) {
  66. logger.warn(attrs, error.message)
  67. const serializedError = { message: error.message }
  68. callback(serializedError)
  69. } else {
  70. logger.error(attrs, `server side error in ${method}`)
  71. // Don't return raw error to prevent leaking server side info
  72. const serializedError = {
  73. message: 'Something went wrong in real-time service',
  74. }
  75. callback(serializedError)
  76. }
  77. if (attrs.disconnect) {
  78. setTimeout(function () {
  79. client.disconnect()
  80. }, 100)
  81. }
  82. },
  83. _handleInvalidArguments(client, method, args) {
  84. const error = new UnexpectedArgumentsError()
  85. let callback = args[args.length - 1]
  86. if (typeof callback !== 'function') {
  87. callback = function () {}
  88. }
  89. const attrs = { arguments: args }
  90. Router._handleError(callback, error, client, method, attrs)
  91. },
  92. configure(app, io, session) {
  93. app.set('io', io)
  94. if (settings.behindProxy) {
  95. app.set('trust proxy', settings.trustedProxyIps)
  96. }
  97. const websocketAddressManager = new WebsocketAddressManager(
  98. settings.behindProxy,
  99. settings.trustedProxyIps
  100. )
  101. app.get('/clients', HttpController.getConnectedClients)
  102. app.get('/clients/:client_id', HttpController.getConnectedClient)
  103. app.post(
  104. '/project/:project_id/message/:message',
  105. bodyParser.json({ limit: '5mb' }),
  106. HttpApiController.sendMessage
  107. )
  108. app.get(
  109. '/project/:projectId/count-connected-clients',
  110. HttpApiController.countConnectedClients
  111. )
  112. app.post('/drain', HttpApiController.startDrain)
  113. app.post(
  114. '/client/:client_id/disconnect',
  115. HttpApiController.disconnectClient
  116. )
  117. session.on('connection', function (error, client, session) {
  118. // init client context, we may access it in Router._handleError before
  119. // setting any values
  120. client.ol_context = {}
  121. // bail out from joinDoc when a parallel joinDoc or leaveDoc is running
  122. client.joinLeaveEpoch = 0
  123. if (client) {
  124. client.on('error', function (err) {
  125. logger.err(
  126. { clientErr: err, publicId: client.publicId, clientId: client.id },
  127. 'socket.io client error'
  128. )
  129. if (client.connected) {
  130. client.emit('reconnectGracefully')
  131. client.disconnect()
  132. }
  133. })
  134. }
  135. if (settings.shutDownInProgress) {
  136. client.emit('connectionRejected', { message: 'retry' })
  137. client.disconnect()
  138. return
  139. }
  140. if (
  141. client &&
  142. error &&
  143. error.message.match(/could not look up session by key/)
  144. ) {
  145. logger.warn(
  146. { err: error, client: !!client, session: !!session },
  147. 'invalid session'
  148. )
  149. // tell the client to reauthenticate if it has an invalid session key
  150. client.emit('connectionRejected', { message: 'invalid session' })
  151. client.disconnect()
  152. return
  153. }
  154. if (error) {
  155. logger.err(
  156. { err: error, client: !!client, session: !!session },
  157. 'error when client connected'
  158. )
  159. if (client) {
  160. client.emit('connectionRejected', { message: 'error' })
  161. }
  162. if (client) {
  163. client.disconnect()
  164. }
  165. return
  166. }
  167. const useServerPing =
  168. !!client.handshake?.query?.esh &&
  169. !!client.handshake?.query?.ssp &&
  170. // No server ping with long-polling transports.
  171. client.transport === 'websocket'
  172. const isDebugging = !!client.handshake?.query?.debugging
  173. const projectId = client.handshake?.query?.projectId
  174. if (isDebugging) {
  175. client.connectedAt = Date.now()
  176. client.isDebugging = true
  177. }
  178. if (!isDebugging) {
  179. try {
  180. Joi.assert(projectId, JOI_OBJECT_ID)
  181. } catch (error) {
  182. metrics.inc('socket-io.connection', 1, {
  183. status: client.transport,
  184. method: projectId ? 'bad-project-id' : 'missing-project-id',
  185. })
  186. client.emit('connectionRejected', {
  187. message: 'missing/bad ?projectId=... query flag on handshake',
  188. })
  189. client.disconnect()
  190. return
  191. }
  192. }
  193. // The client.id is security sensitive. Generate a publicId for sending to other clients.
  194. client.publicId = 'P.' + base64id.generateId()
  195. client.remoteIp = websocketAddressManager.getRemoteIp(client.handshake)
  196. const headers = client.handshake && client.handshake.headers
  197. client.userAgent = headers && headers['user-agent']
  198. metrics.inc('socket-io.connection', 1, {
  199. status: client.transport,
  200. method: 'auto-join-project',
  201. })
  202. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  203. let user
  204. if (session && session.passport && session.passport.user) {
  205. ;({ user } = session.passport)
  206. } else if (session && session.user) {
  207. ;({ user } = session)
  208. } else {
  209. const anonymousAccessToken = session?.anonTokenAccess?.[projectId]
  210. user = { _id: 'anonymous-user', anonymousAccessToken }
  211. }
  212. const info = {
  213. userId: user._id,
  214. projectId,
  215. transport: client.transport,
  216. publicId: client.publicId,
  217. clientId: client.id,
  218. isDebugging,
  219. }
  220. if (isDebugging) {
  221. logger.info(info, 'client connected')
  222. } else {
  223. logger.debug(info, 'client connected')
  224. }
  225. const connectionDetails = {
  226. userId: user._id,
  227. projectId,
  228. remoteIp: client.remoteIp,
  229. publicId: client.publicId,
  230. clientId: client.id,
  231. }
  232. let pingTimestamp
  233. let pingId = -1
  234. let pongId = -1
  235. const pingTimer = useServerPing
  236. ? setInterval(function () {
  237. if (pongId !== pingId) {
  238. logger.warn(
  239. {
  240. ...connectionDetails,
  241. pingId,
  242. pongId,
  243. lastPingTimestamp: pingTimestamp,
  244. },
  245. 'no client response to last ping'
  246. )
  247. }
  248. pingTimestamp = Date.now()
  249. client.emit(
  250. 'serverPing',
  251. ++pingId,
  252. pingTimestamp,
  253. client.transport,
  254. client.id
  255. )
  256. }, SERVER_PING_INTERVAL)
  257. : null
  258. client.on(
  259. 'clientPong',
  260. function (
  261. receivedPingId,
  262. sentTimestamp,
  263. serverTransport,
  264. serverSessionId,
  265. clientTransport,
  266. clientSessionId
  267. ) {
  268. pongId = receivedPingId
  269. const receivedTimestamp = Date.now()
  270. if (
  271. receivedPingId !== pingId ||
  272. (serverSessionId && serverSessionId !== clientSessionId)
  273. ) {
  274. logger.warn(
  275. {
  276. ...connectionDetails,
  277. receivedPingId,
  278. pingId,
  279. sentTimestamp,
  280. receivedTimestamp,
  281. latency: receivedTimestamp - sentTimestamp,
  282. lastPingTimestamp: pingTimestamp,
  283. serverTransport,
  284. serverSessionId,
  285. clientTransport,
  286. clientSessionId,
  287. },
  288. 'received pong with wrong counter'
  289. )
  290. } else if (
  291. receivedTimestamp - sentTimestamp >
  292. SERVER_PING_LATENCY_THRESHOLD
  293. ) {
  294. logger.warn(
  295. {
  296. ...connectionDetails,
  297. receivedPingId,
  298. pingId,
  299. sentTimestamp,
  300. receivedTimestamp,
  301. latency: receivedTimestamp - sentTimestamp,
  302. lastPingTimestamp: pingTimestamp,
  303. },
  304. 'received pong with high latency'
  305. )
  306. }
  307. }
  308. )
  309. if (settings.exposeHostname) {
  310. client.on('debug.getHostname', function (callback) {
  311. if (typeof callback !== 'function') {
  312. return Router._handleInvalidArguments(
  313. client,
  314. 'debug.getHostname',
  315. arguments
  316. )
  317. }
  318. callback(HOSTNAME)
  319. })
  320. }
  321. client.on('debug', (data, callback) => {
  322. if (typeof callback !== 'function') {
  323. return Router._handleInvalidArguments(client, 'debug', arguments)
  324. }
  325. logger.info(
  326. { publicId: client.publicId, clientId: client.id },
  327. 'received debug message'
  328. )
  329. const response = {
  330. serverTime: Date.now(),
  331. data,
  332. client: {
  333. publicId: client.publicId,
  334. remoteIp: client.remoteIp,
  335. userAgent: client.userAgent,
  336. connected: !client.disconnected,
  337. connectedAt: client.connectedAt,
  338. },
  339. server: {
  340. hostname: settings.exposeHostname ? HOSTNAME : undefined,
  341. },
  342. }
  343. callback(response)
  344. })
  345. const joinProject = function (callback) {
  346. WebsocketController.joinProject(
  347. client,
  348. user,
  349. projectId,
  350. function (err, ...args) {
  351. if (err) {
  352. Router._handleError(callback, err, client, 'joinProject', {
  353. project_id: projectId,
  354. user_id: user._id,
  355. })
  356. } else {
  357. callback(null, ...args)
  358. }
  359. }
  360. )
  361. }
  362. client.on('disconnect', function () {
  363. metrics.inc('socket-io.disconnect', 1, { status: client.transport })
  364. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  365. if (client.isDebugging) {
  366. const duration = Date.now() - client.connectedAt
  367. metrics.timing('socket-io.debugging.duration', duration)
  368. logger.info(
  369. { duration, publicId: client.publicId, clientId: client.id },
  370. 'debug client disconnected'
  371. )
  372. } else {
  373. clearInterval(pingTimer)
  374. }
  375. WebsocketController.leaveProject(io, client, function (err) {
  376. if (err) {
  377. Router._handleError(function () {}, err, client, 'leaveProject')
  378. }
  379. })
  380. })
  381. // Variadic. The possible arguments:
  382. // doc_id, callback
  383. // doc_id, fromVersion, callback
  384. // doc_id, options, callback
  385. // doc_id, fromVersion, options, callback
  386. client.on('joinDoc', function (docId, fromVersion, options, callback) {
  387. if (typeof fromVersion === 'function' && !options) {
  388. callback = fromVersion
  389. fromVersion = -1
  390. options = {}
  391. } else if (
  392. typeof fromVersion === 'number' &&
  393. typeof options === 'function'
  394. ) {
  395. callback = options
  396. options = {}
  397. } else if (
  398. typeof fromVersion === 'object' &&
  399. typeof options === 'function'
  400. ) {
  401. callback = options
  402. options = fromVersion
  403. fromVersion = -1
  404. } else if (
  405. typeof fromVersion === 'number' &&
  406. typeof options === 'object' &&
  407. typeof callback === 'function'
  408. ) {
  409. // Called with 4 args, things are as expected
  410. } else {
  411. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  412. }
  413. try {
  414. Joi.assert(
  415. { doc_id: docId, fromVersion, options },
  416. Joi.object({
  417. doc_id: JOI_OBJECT_ID,
  418. fromVersion: Joi.number().integer(),
  419. options: Joi.object().required(),
  420. })
  421. )
  422. } catch (error) {
  423. return Router._handleError(callback, error, client, 'joinDoc', {
  424. disconnect: 1,
  425. })
  426. }
  427. WebsocketController.joinDoc(
  428. client,
  429. docId,
  430. fromVersion,
  431. options,
  432. function (err, ...args) {
  433. if (err) {
  434. Router._handleError(callback, err, client, 'joinDoc', {
  435. doc_id: docId,
  436. fromVersion,
  437. })
  438. } else {
  439. callback(null, ...args)
  440. }
  441. }
  442. )
  443. })
  444. client.on('leaveDoc', function (docId, callback) {
  445. if (typeof callback !== 'function') {
  446. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  447. }
  448. try {
  449. Joi.assert(docId, JOI_OBJECT_ID)
  450. } catch (error) {
  451. return Router._handleError(callback, error, client, 'joinDoc', {
  452. disconnect: 1,
  453. })
  454. }
  455. WebsocketController.leaveDoc(client, docId, function (err, ...args) {
  456. if (err) {
  457. Router._handleError(callback, err, client, 'leaveDoc', {
  458. doc_id: docId,
  459. })
  460. } else {
  461. callback(null, ...args)
  462. }
  463. })
  464. })
  465. client.on('clientTracking.getConnectedUsers', function (callback) {
  466. if (typeof callback !== 'function') {
  467. return Router._handleInvalidArguments(
  468. client,
  469. 'clientTracking.getConnectedUsers',
  470. arguments
  471. )
  472. }
  473. WebsocketController.getConnectedUsers(client, function (err, users) {
  474. if (err) {
  475. Router._handleError(
  476. callback,
  477. err,
  478. client,
  479. 'clientTracking.getConnectedUsers'
  480. )
  481. } else {
  482. callback(null, users)
  483. }
  484. })
  485. })
  486. client.on(
  487. 'clientTracking.updatePosition',
  488. function (cursorData, callback) {
  489. if (!callback) {
  490. callback = function () {
  491. // NOTE: The frontend does not pass any callback to socket.io.
  492. // Any error is already logged via Router._handleError.
  493. }
  494. }
  495. if (typeof callback !== 'function') {
  496. return Router._handleInvalidArguments(
  497. client,
  498. 'clientTracking.updatePosition',
  499. arguments
  500. )
  501. }
  502. WebsocketController.updateClientPosition(
  503. client,
  504. cursorData,
  505. function (err) {
  506. if (err) {
  507. Router._handleError(
  508. callback,
  509. err,
  510. client,
  511. 'clientTracking.updatePosition'
  512. )
  513. } else {
  514. callback()
  515. }
  516. }
  517. )
  518. }
  519. )
  520. client.on('applyOtUpdate', function (docId, update, callback) {
  521. if (typeof callback !== 'function') {
  522. return Router._handleInvalidArguments(
  523. client,
  524. 'applyOtUpdate',
  525. arguments
  526. )
  527. }
  528. try {
  529. Joi.assert(
  530. { doc_id: docId, update },
  531. Joi.object({
  532. doc_id: JOI_OBJECT_ID,
  533. update: Joi.object().required(),
  534. })
  535. )
  536. } catch (error) {
  537. return Router._handleError(callback, error, client, 'applyOtUpdate', {
  538. disconnect: 1,
  539. })
  540. }
  541. WebsocketController.applyOtUpdate(
  542. client,
  543. docId,
  544. update,
  545. function (err) {
  546. if (err) {
  547. Router._handleError(callback, err, client, 'applyOtUpdate', {
  548. doc_id: docId,
  549. })
  550. } else {
  551. callback()
  552. }
  553. }
  554. )
  555. })
  556. if (!isDebugging) {
  557. joinProject((err, project, permissionsLevel, protocolVersion) => {
  558. if (err) {
  559. client.emit('connectionRejected', err)
  560. client.disconnect()
  561. return
  562. }
  563. client.emit('joinProjectResponse', {
  564. publicId: client.publicId,
  565. project,
  566. permissionsLevel,
  567. protocolVersion,
  568. })
  569. })
  570. }
  571. })
  572. },
  573. }