Router.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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.post('/drain', HttpApiController.startDrain)
  109. app.post(
  110. '/client/:client_id/disconnect',
  111. HttpApiController.disconnectClient
  112. )
  113. session.on('connection', function (error, client, session) {
  114. // init client context, we may access it in Router._handleError before
  115. // setting any values
  116. client.ol_context = {}
  117. // bail out from joinDoc when a parallel joinDoc or leaveDoc is running
  118. client.joinLeaveEpoch = 0
  119. if (client) {
  120. client.on('error', function (err) {
  121. logger.err(
  122. { clientErr: err, publicId: client.publicId, clientId: client.id },
  123. 'socket.io client error'
  124. )
  125. if (client.connected) {
  126. client.emit('reconnectGracefully')
  127. client.disconnect()
  128. }
  129. })
  130. }
  131. if (settings.shutDownInProgress) {
  132. client.emit('connectionRejected', { message: 'retry' })
  133. client.disconnect()
  134. return
  135. }
  136. if (
  137. client &&
  138. error &&
  139. error.message.match(/could not look up session by key/)
  140. ) {
  141. logger.warn(
  142. { err: error, client: !!client, session: !!session },
  143. 'invalid session'
  144. )
  145. // tell the client to reauthenticate if it has an invalid session key
  146. client.emit('connectionRejected', { message: 'invalid session' })
  147. client.disconnect()
  148. return
  149. }
  150. if (error) {
  151. logger.err(
  152. { err: error, client: !!client, session: !!session },
  153. 'error when client connected'
  154. )
  155. if (client) {
  156. client.emit('connectionRejected', { message: 'error' })
  157. }
  158. if (client) {
  159. client.disconnect()
  160. }
  161. return
  162. }
  163. const useServerPing =
  164. !!client.handshake?.query?.esh &&
  165. !!client.handshake?.query?.ssp &&
  166. // No server ping with long-polling transports.
  167. client.transport === 'websocket'
  168. const isDebugging = !!client.handshake?.query?.debugging
  169. const projectId = client.handshake?.query?.projectId
  170. if (isDebugging) {
  171. client.connectedAt = Date.now()
  172. client.isDebugging = true
  173. }
  174. if (!isDebugging) {
  175. try {
  176. Joi.assert(projectId, JOI_OBJECT_ID)
  177. } catch (error) {
  178. metrics.inc('socket-io.connection', 1, {
  179. status: client.transport,
  180. method: projectId ? 'bad-project-id' : 'missing-project-id',
  181. })
  182. client.emit('connectionRejected', {
  183. message: 'missing/bad ?projectId=... query flag on handshake',
  184. })
  185. client.disconnect()
  186. return
  187. }
  188. }
  189. // The client.id is security sensitive. Generate a publicId for sending to other clients.
  190. client.publicId = 'P.' + base64id.generateId()
  191. client.remoteIp = websocketAddressManager.getRemoteIp(client.handshake)
  192. const headers = client.handshake && client.handshake.headers
  193. client.userAgent = headers && headers['user-agent']
  194. metrics.inc('socket-io.connection', 1, {
  195. status: client.transport,
  196. method: 'auto-join-project',
  197. })
  198. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  199. const info = {
  200. session,
  201. publicId: client.publicId,
  202. clientId: client.id,
  203. isDebugging,
  204. }
  205. if (isDebugging) {
  206. logger.info(info, 'client connected')
  207. } else {
  208. logger.debug(info, 'client connected')
  209. }
  210. let user
  211. if (session && session.passport && session.passport.user) {
  212. ;({ user } = session.passport)
  213. } else if (session && session.user) {
  214. ;({ user } = session)
  215. } else {
  216. const anonymousAccessToken = session?.anonTokenAccess?.[projectId]
  217. user = { _id: 'anonymous-user', anonymousAccessToken }
  218. }
  219. const connectionDetails = {
  220. userId: user._id,
  221. projectId,
  222. remoteIp: client.remoteIp,
  223. publicId: client.publicId,
  224. clientId: client.id,
  225. }
  226. let pingTimestamp
  227. let pingId = -1
  228. let pongId = -1
  229. const pingTimer = useServerPing
  230. ? setInterval(function () {
  231. if (pongId !== pingId) {
  232. logger.warn(
  233. {
  234. ...connectionDetails,
  235. pingId,
  236. pongId,
  237. lastPingTimestamp: pingTimestamp,
  238. },
  239. 'no client response to last ping'
  240. )
  241. }
  242. pingTimestamp = Date.now()
  243. client.emit(
  244. 'serverPing',
  245. ++pingId,
  246. pingTimestamp,
  247. client.transport,
  248. client.id
  249. )
  250. }, SERVER_PING_INTERVAL)
  251. : null
  252. client.on(
  253. 'clientPong',
  254. function (
  255. receivedPingId,
  256. sentTimestamp,
  257. serverTransport,
  258. serverSessionId,
  259. clientTransport,
  260. clientSessionId
  261. ) {
  262. pongId = receivedPingId
  263. const receivedTimestamp = Date.now()
  264. if (
  265. receivedPingId !== pingId ||
  266. (serverSessionId && serverSessionId !== clientSessionId)
  267. ) {
  268. logger.warn(
  269. {
  270. ...connectionDetails,
  271. receivedPingId,
  272. pingId,
  273. sentTimestamp,
  274. receivedTimestamp,
  275. latency: receivedTimestamp - sentTimestamp,
  276. lastPingTimestamp: pingTimestamp,
  277. serverTransport,
  278. serverSessionId,
  279. clientTransport,
  280. clientSessionId,
  281. },
  282. 'received pong with wrong counter'
  283. )
  284. } else if (
  285. receivedTimestamp - sentTimestamp >
  286. SERVER_PING_LATENCY_THRESHOLD
  287. ) {
  288. logger.warn(
  289. {
  290. ...connectionDetails,
  291. receivedPingId,
  292. pingId,
  293. sentTimestamp,
  294. receivedTimestamp,
  295. latency: receivedTimestamp - sentTimestamp,
  296. lastPingTimestamp: pingTimestamp,
  297. },
  298. 'received pong with high latency'
  299. )
  300. }
  301. }
  302. )
  303. if (settings.exposeHostname) {
  304. client.on('debug.getHostname', function (callback) {
  305. if (typeof callback !== 'function') {
  306. return Router._handleInvalidArguments(
  307. client,
  308. 'debug.getHostname',
  309. arguments
  310. )
  311. }
  312. callback(HOSTNAME)
  313. })
  314. }
  315. client.on('debug', (data, callback) => {
  316. if (typeof callback !== 'function') {
  317. return Router._handleInvalidArguments(client, 'debug', arguments)
  318. }
  319. logger.info(
  320. { publicId: client.publicId, clientId: client.id },
  321. 'received debug message'
  322. )
  323. const response = {
  324. serverTime: Date.now(),
  325. data,
  326. client: {
  327. publicId: client.publicId,
  328. remoteIp: client.remoteIp,
  329. userAgent: client.userAgent,
  330. connected: !client.disconnected,
  331. connectedAt: client.connectedAt,
  332. },
  333. server: {
  334. hostname: settings.exposeHostname ? HOSTNAME : undefined,
  335. },
  336. }
  337. callback(response)
  338. })
  339. const joinProject = function (callback) {
  340. WebsocketController.joinProject(
  341. client,
  342. user,
  343. projectId,
  344. function (err, ...args) {
  345. if (err) {
  346. Router._handleError(callback, err, client, 'joinProject', {
  347. project_id: projectId,
  348. user_id: user._id,
  349. })
  350. } else {
  351. callback(null, ...args)
  352. }
  353. }
  354. )
  355. }
  356. client.on('disconnect', function () {
  357. metrics.inc('socket-io.disconnect', 1, { status: client.transport })
  358. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  359. if (client.isDebugging) {
  360. const duration = Date.now() - client.connectedAt
  361. metrics.timing('socket-io.debugging.duration', duration)
  362. logger.info(
  363. { duration, publicId: client.publicId, clientId: client.id },
  364. 'debug client disconnected'
  365. )
  366. } else {
  367. clearInterval(pingTimer)
  368. }
  369. WebsocketController.leaveProject(io, client, function (err) {
  370. if (err) {
  371. Router._handleError(function () {}, err, client, 'leaveProject')
  372. }
  373. })
  374. })
  375. // Variadic. The possible arguments:
  376. // doc_id, callback
  377. // doc_id, fromVersion, callback
  378. // doc_id, options, callback
  379. // doc_id, fromVersion, options, callback
  380. client.on('joinDoc', function (docId, fromVersion, options, callback) {
  381. if (typeof fromVersion === 'function' && !options) {
  382. callback = fromVersion
  383. fromVersion = -1
  384. options = {}
  385. } else if (
  386. typeof fromVersion === 'number' &&
  387. typeof options === 'function'
  388. ) {
  389. callback = options
  390. options = {}
  391. } else if (
  392. typeof fromVersion === 'object' &&
  393. typeof options === 'function'
  394. ) {
  395. callback = options
  396. options = fromVersion
  397. fromVersion = -1
  398. } else if (
  399. typeof fromVersion === 'number' &&
  400. typeof options === 'object' &&
  401. typeof callback === 'function'
  402. ) {
  403. // Called with 4 args, things are as expected
  404. } else {
  405. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  406. }
  407. try {
  408. Joi.assert(
  409. { doc_id: docId, fromVersion, options },
  410. Joi.object({
  411. doc_id: JOI_OBJECT_ID,
  412. fromVersion: Joi.number().integer(),
  413. options: Joi.object().required(),
  414. })
  415. )
  416. } catch (error) {
  417. return Router._handleError(callback, error, client, 'joinDoc', {
  418. disconnect: 1,
  419. })
  420. }
  421. WebsocketController.joinDoc(
  422. client,
  423. docId,
  424. fromVersion,
  425. options,
  426. function (err, ...args) {
  427. if (err) {
  428. Router._handleError(callback, err, client, 'joinDoc', {
  429. doc_id: docId,
  430. fromVersion,
  431. })
  432. } else {
  433. callback(null, ...args)
  434. }
  435. }
  436. )
  437. })
  438. client.on('leaveDoc', function (docId, callback) {
  439. if (typeof callback !== 'function') {
  440. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  441. }
  442. try {
  443. Joi.assert(docId, JOI_OBJECT_ID)
  444. } catch (error) {
  445. return Router._handleError(callback, error, client, 'joinDoc', {
  446. disconnect: 1,
  447. })
  448. }
  449. WebsocketController.leaveDoc(client, docId, function (err, ...args) {
  450. if (err) {
  451. Router._handleError(callback, err, client, 'leaveDoc', {
  452. doc_id: docId,
  453. })
  454. } else {
  455. callback(null, ...args)
  456. }
  457. })
  458. })
  459. client.on('clientTracking.getConnectedUsers', function (callback) {
  460. if (typeof callback !== 'function') {
  461. return Router._handleInvalidArguments(
  462. client,
  463. 'clientTracking.getConnectedUsers',
  464. arguments
  465. )
  466. }
  467. WebsocketController.getConnectedUsers(client, function (err, users) {
  468. if (err) {
  469. Router._handleError(
  470. callback,
  471. err,
  472. client,
  473. 'clientTracking.getConnectedUsers'
  474. )
  475. } else {
  476. callback(null, users)
  477. }
  478. })
  479. })
  480. client.on(
  481. 'clientTracking.updatePosition',
  482. function (cursorData, callback) {
  483. if (!callback) {
  484. callback = function () {
  485. // NOTE: The frontend does not pass any callback to socket.io.
  486. // Any error is already logged via Router._handleError.
  487. }
  488. }
  489. if (typeof callback !== 'function') {
  490. return Router._handleInvalidArguments(
  491. client,
  492. 'clientTracking.updatePosition',
  493. arguments
  494. )
  495. }
  496. WebsocketController.updateClientPosition(
  497. client,
  498. cursorData,
  499. function (err) {
  500. if (err) {
  501. Router._handleError(
  502. callback,
  503. err,
  504. client,
  505. 'clientTracking.updatePosition'
  506. )
  507. } else {
  508. callback()
  509. }
  510. }
  511. )
  512. }
  513. )
  514. client.on('applyOtUpdate', function (docId, update, callback) {
  515. if (typeof callback !== 'function') {
  516. return Router._handleInvalidArguments(
  517. client,
  518. 'applyOtUpdate',
  519. arguments
  520. )
  521. }
  522. try {
  523. Joi.assert(
  524. { doc_id: docId, update },
  525. Joi.object({
  526. doc_id: JOI_OBJECT_ID,
  527. update: Joi.object().required(),
  528. })
  529. )
  530. } catch (error) {
  531. return Router._handleError(callback, error, client, 'applyOtUpdate', {
  532. disconnect: 1,
  533. })
  534. }
  535. WebsocketController.applyOtUpdate(
  536. client,
  537. docId,
  538. update,
  539. function (err) {
  540. if (err) {
  541. Router._handleError(callback, err, client, 'applyOtUpdate', {
  542. doc_id: docId,
  543. update,
  544. })
  545. } else {
  546. callback()
  547. }
  548. }
  549. )
  550. })
  551. if (!isDebugging) {
  552. joinProject((err, project, permissionsLevel, protocolVersion) => {
  553. if (err) {
  554. client.emit('connectionRejected', err)
  555. client.disconnect()
  556. return
  557. }
  558. client.emit('joinProjectResponse', {
  559. publicId: client.publicId,
  560. project,
  561. permissionsLevel,
  562. protocolVersion,
  563. })
  564. })
  565. }
  566. })
  567. },
  568. }