Router.js 15 KB

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