Router.js 18 KB

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