Router.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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(
  120. { clientErr: err, publicId: client.publicId, clientId: client.id },
  121. 'socket.io client error'
  122. )
  123. if (client.connected) {
  124. client.emit('reconnectGracefully')
  125. client.disconnect()
  126. }
  127. })
  128. }
  129. if (settings.shutDownInProgress) {
  130. client.emit('connectionRejected', { message: 'retry' })
  131. client.disconnect()
  132. return
  133. }
  134. if (
  135. client &&
  136. error &&
  137. error.message.match(/could not look up session by key/)
  138. ) {
  139. logger.warn(
  140. { err: error, client: !!client, session: !!session },
  141. 'invalid session'
  142. )
  143. // tell the client to reauthenticate if it has an invalid session key
  144. client.emit('connectionRejected', { message: 'invalid session' })
  145. client.disconnect()
  146. return
  147. }
  148. if (error) {
  149. logger.err(
  150. { err: error, client: !!client, session: !!session },
  151. 'error when client connected'
  152. )
  153. if (client) {
  154. client.emit('connectionRejected', { message: 'error' })
  155. }
  156. if (client) {
  157. client.disconnect()
  158. }
  159. return
  160. }
  161. const isDebugging = !!client.handshake?.query?.debugging
  162. const projectId = client.handshake?.query?.projectId
  163. if (isDebugging) {
  164. client.connectedAt = Date.now()
  165. client.isDebugging = true
  166. }
  167. if (!isDebugging) {
  168. try {
  169. Joi.assert(projectId, JOI_OBJECT_ID)
  170. } catch (error) {
  171. metrics.inc('socket-io.connection', 1, {
  172. status: client.transport,
  173. method: projectId ? 'bad-project-id' : 'missing-project-id',
  174. })
  175. client.emit('connectionRejected', {
  176. message: 'missing/bad ?projectId=... query flag on handshake',
  177. })
  178. client.disconnect()
  179. return
  180. }
  181. }
  182. // The client.id is security sensitive. Generate a publicId for sending to other clients.
  183. client.publicId = 'P.' + base64id.generateId()
  184. client.remoteIp = websocketAddressManager.getRemoteIp(client.handshake)
  185. const headers = client.handshake && client.handshake.headers
  186. client.userAgent = headers && headers['user-agent']
  187. metrics.inc('socket-io.connection', 1, {
  188. status: client.transport,
  189. method: 'auto-join-project',
  190. })
  191. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  192. const info = {
  193. session,
  194. publicId: client.publicId,
  195. clientId: client.id,
  196. isDebugging,
  197. }
  198. if (isDebugging) {
  199. logger.info(info, 'client connected')
  200. } else {
  201. logger.debug(info, 'client connected')
  202. }
  203. let user
  204. if (session && session.passport && session.passport.user) {
  205. ;({ user } = session.passport)
  206. } else if (session && session.user) {
  207. ;({ user } = session)
  208. } else {
  209. const anonymousAccessToken = session?.anonTokenAccess?.[projectId]
  210. user = { _id: 'anonymous-user', anonymousAccessToken }
  211. }
  212. if (settings.exposeHostname) {
  213. client.on('debug.getHostname', function (callback) {
  214. if (typeof callback !== 'function') {
  215. return Router._handleInvalidArguments(
  216. client,
  217. 'debug.getHostname',
  218. arguments
  219. )
  220. }
  221. callback(HOSTNAME)
  222. })
  223. }
  224. client.on('debug', (data, callback) => {
  225. if (typeof callback !== 'function') {
  226. return Router._handleInvalidArguments(client, 'debug', arguments)
  227. }
  228. logger.info(
  229. { publicId: client.publicId, clientId: client.id },
  230. 'received debug message'
  231. )
  232. const response = {
  233. serverTime: Date.now(),
  234. data,
  235. client: {
  236. publicId: client.publicId,
  237. remoteIp: client.remoteIp,
  238. userAgent: client.userAgent,
  239. connected: !client.disconnected,
  240. connectedAt: client.connectedAt,
  241. },
  242. server: {
  243. hostname: settings.exposeHostname ? HOSTNAME : undefined,
  244. },
  245. }
  246. callback(response)
  247. })
  248. const joinProject = function (callback) {
  249. WebsocketController.joinProject(
  250. client,
  251. user,
  252. projectId,
  253. function (err, ...args) {
  254. if (err) {
  255. Router._handleError(callback, err, client, 'joinProject', {
  256. project_id: projectId,
  257. user_id: user._id,
  258. })
  259. } else {
  260. callback(null, ...args)
  261. }
  262. }
  263. )
  264. }
  265. client.on('disconnect', function () {
  266. metrics.inc('socket-io.disconnect', 1, { status: client.transport })
  267. metrics.gauge('socket-io.clients', io.sockets.clients().length)
  268. if (client.isDebugging) {
  269. const duration = Date.now() - client.connectedAt
  270. metrics.timing('socket-io.debugging.duration', duration)
  271. logger.info(
  272. { duration, publicId: client.publicId, clientId: client.id },
  273. 'debug client disconnected'
  274. )
  275. }
  276. WebsocketController.leaveProject(io, client, function (err) {
  277. if (err) {
  278. Router._handleError(function () {}, err, client, 'leaveProject')
  279. }
  280. })
  281. })
  282. // Variadic. The possible arguments:
  283. // doc_id, callback
  284. // doc_id, fromVersion, callback
  285. // doc_id, options, callback
  286. // doc_id, fromVersion, options, callback
  287. client.on('joinDoc', function (docId, fromVersion, options, callback) {
  288. if (typeof fromVersion === 'function' && !options) {
  289. callback = fromVersion
  290. fromVersion = -1
  291. options = {}
  292. } else if (
  293. typeof fromVersion === 'number' &&
  294. typeof options === 'function'
  295. ) {
  296. callback = options
  297. options = {}
  298. } else if (
  299. typeof fromVersion === 'object' &&
  300. typeof options === 'function'
  301. ) {
  302. callback = options
  303. options = fromVersion
  304. fromVersion = -1
  305. } else if (
  306. typeof fromVersion === 'number' &&
  307. typeof options === 'object' &&
  308. typeof callback === 'function'
  309. ) {
  310. // Called with 4 args, things are as expected
  311. } else {
  312. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  313. }
  314. try {
  315. Joi.assert(
  316. { doc_id: docId, fromVersion, options },
  317. Joi.object({
  318. doc_id: JOI_OBJECT_ID,
  319. fromVersion: Joi.number().integer(),
  320. options: Joi.object().required(),
  321. })
  322. )
  323. } catch (error) {
  324. return Router._handleError(callback, error, client, 'joinDoc', {
  325. disconnect: 1,
  326. })
  327. }
  328. WebsocketController.joinDoc(
  329. client,
  330. docId,
  331. fromVersion,
  332. options,
  333. function (err, ...args) {
  334. if (err) {
  335. Router._handleError(callback, err, client, 'joinDoc', {
  336. doc_id: docId,
  337. fromVersion,
  338. })
  339. } else {
  340. callback(null, ...args)
  341. }
  342. }
  343. )
  344. })
  345. client.on('leaveDoc', function (docId, callback) {
  346. if (typeof callback !== 'function') {
  347. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  348. }
  349. try {
  350. Joi.assert(docId, JOI_OBJECT_ID)
  351. } catch (error) {
  352. return Router._handleError(callback, error, client, 'joinDoc', {
  353. disconnect: 1,
  354. })
  355. }
  356. WebsocketController.leaveDoc(client, docId, function (err, ...args) {
  357. if (err) {
  358. Router._handleError(callback, err, client, 'leaveDoc', {
  359. doc_id: docId,
  360. })
  361. } else {
  362. callback(null, ...args)
  363. }
  364. })
  365. })
  366. client.on('clientTracking.getConnectedUsers', function (callback) {
  367. if (typeof callback !== 'function') {
  368. return Router._handleInvalidArguments(
  369. client,
  370. 'clientTracking.getConnectedUsers',
  371. arguments
  372. )
  373. }
  374. WebsocketController.getConnectedUsers(client, function (err, users) {
  375. if (err) {
  376. Router._handleError(
  377. callback,
  378. err,
  379. client,
  380. 'clientTracking.getConnectedUsers'
  381. )
  382. } else {
  383. callback(null, users)
  384. }
  385. })
  386. })
  387. client.on(
  388. 'clientTracking.updatePosition',
  389. function (cursorData, callback) {
  390. if (!callback) {
  391. callback = function () {
  392. // NOTE: The frontend does not pass any callback to socket.io.
  393. // Any error is already logged via Router._handleError.
  394. }
  395. }
  396. if (typeof callback !== 'function') {
  397. return Router._handleInvalidArguments(
  398. client,
  399. 'clientTracking.updatePosition',
  400. arguments
  401. )
  402. }
  403. WebsocketController.updateClientPosition(
  404. client,
  405. cursorData,
  406. function (err) {
  407. if (err) {
  408. Router._handleError(
  409. callback,
  410. err,
  411. client,
  412. 'clientTracking.updatePosition'
  413. )
  414. } else {
  415. callback()
  416. }
  417. }
  418. )
  419. }
  420. )
  421. client.on('applyOtUpdate', function (docId, update, callback) {
  422. if (typeof callback !== 'function') {
  423. return Router._handleInvalidArguments(
  424. client,
  425. 'applyOtUpdate',
  426. arguments
  427. )
  428. }
  429. try {
  430. Joi.assert(
  431. { doc_id: docId, update },
  432. Joi.object({
  433. doc_id: JOI_OBJECT_ID,
  434. update: Joi.object().required(),
  435. })
  436. )
  437. } catch (error) {
  438. return Router._handleError(callback, error, client, 'applyOtUpdate', {
  439. disconnect: 1,
  440. })
  441. }
  442. WebsocketController.applyOtUpdate(
  443. client,
  444. docId,
  445. update,
  446. function (err) {
  447. if (err) {
  448. Router._handleError(callback, err, client, 'applyOtUpdate', {
  449. doc_id: docId,
  450. update,
  451. })
  452. } else {
  453. callback()
  454. }
  455. }
  456. )
  457. })
  458. if (!isDebugging) {
  459. joinProject((err, project, permissionsLevel, protocolVersion) => {
  460. if (err) {
  461. client.emit('connectionRejected', err)
  462. client.disconnect()
  463. return
  464. }
  465. client.emit('joinProjectResponse', {
  466. publicId: client.publicId,
  467. project,
  468. permissionsLevel,
  469. protocolVersion,
  470. })
  471. })
  472. }
  473. })
  474. },
  475. }