Router.js 14 KB

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