Router.js 15 KB

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