Router.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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('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 projectId = client.handshake?.query?.projectId
  159. try {
  160. Joi.assert(projectId, JOI_OBJECT_ID)
  161. } catch (error) {
  162. metrics.inc('socket-io.connection', 1, {
  163. status: client.transport,
  164. method: projectId ? 'bad-project-id' : 'missing-project-id',
  165. })
  166. client.emit('connectionRejected', {
  167. message: 'missing/bad ?projectId=... query flag on handshake',
  168. })
  169. client.disconnect()
  170. return
  171. }
  172. // The client.id is security sensitive. Generate a publicId for sending to other clients.
  173. client.publicId = 'P.' + base64id.generateId()
  174. client.remoteIp = websocketAddressManager.getRemoteIp(client.handshake)
  175. const headers = client.handshake && client.handshake.headers
  176. client.userAgent = headers && headers['user-agent']
  177. metrics.inc('socket-io.connection', 1, {
  178. status: client.transport,
  179. method: 'auto-join-project',
  180. })
  181. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  182. logger.debug({ session, clientId: client.id }, 'client connected')
  183. let user
  184. if (session && session.passport && session.passport.user) {
  185. ;({ user } = session.passport)
  186. } else if (session && session.user) {
  187. ;({ user } = session)
  188. } else {
  189. const anonymousAccessToken = session?.anonTokenAccess?.[projectId]
  190. user = { _id: 'anonymous-user', anonymousAccessToken }
  191. }
  192. if (settings.exposeHostname) {
  193. client.on('debug.getHostname', function (callback) {
  194. if (typeof callback !== 'function') {
  195. return Router._handleInvalidArguments(
  196. client,
  197. 'debug.getHostname',
  198. arguments
  199. )
  200. }
  201. callback(HOSTNAME)
  202. })
  203. }
  204. const joinProject = function (callback) {
  205. WebsocketController.joinProject(
  206. client,
  207. user,
  208. projectId,
  209. function (err, ...args) {
  210. if (err) {
  211. Router._handleError(callback, err, client, 'joinProject', {
  212. project_id: projectId,
  213. user_id: user._id,
  214. })
  215. } else {
  216. callback(null, ...args)
  217. }
  218. }
  219. )
  220. }
  221. client.on('disconnect', function () {
  222. metrics.inc('socket-io.disconnect', 1, { status: client.transport })
  223. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  224. WebsocketController.leaveProject(io, client, function (err) {
  225. if (err) {
  226. Router._handleError(function () {}, err, client, 'leaveProject')
  227. }
  228. })
  229. })
  230. // Variadic. The possible arguments:
  231. // doc_id, callback
  232. // doc_id, fromVersion, callback
  233. // doc_id, options, callback
  234. // doc_id, fromVersion, options, callback
  235. client.on('joinDoc', function (docId, fromVersion, options, callback) {
  236. if (typeof fromVersion === 'function' && !options) {
  237. callback = fromVersion
  238. fromVersion = -1
  239. options = {}
  240. } else if (
  241. typeof fromVersion === 'number' &&
  242. typeof options === 'function'
  243. ) {
  244. callback = options
  245. options = {}
  246. } else if (
  247. typeof fromVersion === 'object' &&
  248. typeof options === 'function'
  249. ) {
  250. callback = options
  251. options = fromVersion
  252. fromVersion = -1
  253. } else if (
  254. typeof fromVersion === 'number' &&
  255. typeof options === 'object' &&
  256. typeof callback === 'function'
  257. ) {
  258. // Called with 4 args, things are as expected
  259. } else {
  260. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  261. }
  262. try {
  263. Joi.assert(
  264. { doc_id: docId, fromVersion, options },
  265. Joi.object({
  266. doc_id: JOI_OBJECT_ID,
  267. fromVersion: Joi.number().integer(),
  268. options: Joi.object().required(),
  269. })
  270. )
  271. } catch (error) {
  272. return Router._handleError(callback, error, client, 'joinDoc', {
  273. disconnect: 1,
  274. })
  275. }
  276. WebsocketController.joinDoc(
  277. client,
  278. docId,
  279. fromVersion,
  280. options,
  281. function (err, ...args) {
  282. if (err) {
  283. Router._handleError(callback, err, client, 'joinDoc', {
  284. doc_id: docId,
  285. fromVersion,
  286. })
  287. } else {
  288. callback(null, ...args)
  289. }
  290. }
  291. )
  292. })
  293. client.on('leaveDoc', function (docId, callback) {
  294. if (typeof callback !== 'function') {
  295. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  296. }
  297. try {
  298. Joi.assert(docId, JOI_OBJECT_ID)
  299. } catch (error) {
  300. return Router._handleError(callback, error, client, 'joinDoc', {
  301. disconnect: 1,
  302. })
  303. }
  304. WebsocketController.leaveDoc(client, docId, function (err, ...args) {
  305. if (err) {
  306. Router._handleError(callback, err, client, 'leaveDoc', {
  307. doc_id: docId,
  308. })
  309. } else {
  310. callback(null, ...args)
  311. }
  312. })
  313. })
  314. client.on('clientTracking.getConnectedUsers', function (callback) {
  315. if (typeof callback !== 'function') {
  316. return Router._handleInvalidArguments(
  317. client,
  318. 'clientTracking.getConnectedUsers',
  319. arguments
  320. )
  321. }
  322. WebsocketController.getConnectedUsers(client, function (err, users) {
  323. if (err) {
  324. Router._handleError(
  325. callback,
  326. err,
  327. client,
  328. 'clientTracking.getConnectedUsers'
  329. )
  330. } else {
  331. callback(null, users)
  332. }
  333. })
  334. })
  335. client.on(
  336. 'clientTracking.updatePosition',
  337. function (cursorData, callback) {
  338. if (!callback) {
  339. callback = function () {
  340. // NOTE: The frontend does not pass any callback to socket.io.
  341. // Any error is already logged via Router._handleError.
  342. }
  343. }
  344. if (typeof callback !== 'function') {
  345. return Router._handleInvalidArguments(
  346. client,
  347. 'clientTracking.updatePosition',
  348. arguments
  349. )
  350. }
  351. WebsocketController.updateClientPosition(
  352. client,
  353. cursorData,
  354. function (err) {
  355. if (err) {
  356. Router._handleError(
  357. callback,
  358. err,
  359. client,
  360. 'clientTracking.updatePosition'
  361. )
  362. } else {
  363. callback()
  364. }
  365. }
  366. )
  367. }
  368. )
  369. client.on('applyOtUpdate', function (docId, update, callback) {
  370. if (typeof callback !== 'function') {
  371. return Router._handleInvalidArguments(
  372. client,
  373. 'applyOtUpdate',
  374. arguments
  375. )
  376. }
  377. try {
  378. Joi.assert(
  379. { doc_id: docId, update },
  380. Joi.object({
  381. doc_id: JOI_OBJECT_ID,
  382. update: Joi.object().required(),
  383. })
  384. )
  385. } catch (error) {
  386. return Router._handleError(callback, error, client, 'applyOtUpdate', {
  387. disconnect: 1,
  388. })
  389. }
  390. WebsocketController.applyOtUpdate(
  391. client,
  392. docId,
  393. update,
  394. function (err) {
  395. if (err) {
  396. Router._handleError(callback, err, client, 'applyOtUpdate', {
  397. doc_id: docId,
  398. update,
  399. })
  400. } else {
  401. callback()
  402. }
  403. }
  404. )
  405. })
  406. joinProject((err, project, permissionsLevel, protocolVersion) => {
  407. if (err) {
  408. client.emit('connectionRejected', err)
  409. client.disconnect()
  410. return
  411. }
  412. client.emit('joinProjectResponse', {
  413. publicId: client.publicId,
  414. project,
  415. permissionsLevel,
  416. protocolVersion,
  417. })
  418. })
  419. })
  420. },
  421. }