Router.js 17 KB

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