Router.js 18 KB

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