WebsocketControllerTests.coffee 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. chai = require('chai')
  2. should = chai.should()
  3. sinon = require("sinon")
  4. expect = chai.expect
  5. modulePath = "../../../app/js/WebsocketController.js"
  6. SandboxedModule = require('sandboxed-module')
  7. tk = require "timekeeper"
  8. describe 'WebsocketController', ->
  9. beforeEach ->
  10. tk.freeze(new Date())
  11. @project_id = "project-id-123"
  12. @user = {
  13. _id: @user_id = "user-id-123"
  14. first_name: "James"
  15. last_name: "Allen"
  16. email: "james@example.com"
  17. signUpDate: new Date("2014-01-01")
  18. loginCount: 42
  19. }
  20. @callback = sinon.stub()
  21. @client =
  22. id: @client_id = "mock-client-id-123"
  23. params: {}
  24. set: sinon.stub()
  25. get: (param, cb) -> cb null, @params[param]
  26. join: sinon.stub()
  27. leave: sinon.stub()
  28. @WebsocketController = SandboxedModule.require modulePath, requires:
  29. "./WebApiManager": @WebApiManager = {}
  30. "./AuthorizationManager": @AuthorizationManager = {}
  31. "./DocumentUpdaterManager": @DocumentUpdaterManager = {}
  32. "./ConnectedUsersManager": @ConnectedUsersManager = {}
  33. "./WebsocketLoadBalancer": @WebsocketLoadBalancer = {}
  34. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() }
  35. "metrics-sharelatex": @metrics =
  36. inc: sinon.stub()
  37. set: sinon.stub()
  38. afterEach ->
  39. tk.reset()
  40. describe "joinProject", ->
  41. describe "when authorised", ->
  42. beforeEach ->
  43. @client.id = "mock-client-id"
  44. @project = {
  45. name: "Test Project"
  46. owner: {
  47. _id: @owner_id = "mock-owner-id-123"
  48. }
  49. }
  50. @privilegeLevel = "owner"
  51. @ConnectedUsersManager.updateUserPosition = sinon.stub().callsArg(4)
  52. @WebApiManager.joinProject = sinon.stub().callsArgWith(2, null, @project, @privilegeLevel)
  53. @WebsocketController.joinProject @client, @user, @project_id, @callback
  54. it "should load the project from web", ->
  55. @WebApiManager.joinProject
  56. .calledWith(@project_id, @user._id)
  57. .should.equal true
  58. it "should join the project room", ->
  59. @client.join.calledWith(@project_id).should.equal true
  60. it "should set the privilege level on the client", ->
  61. @client.set.calledWith("privilege_level", @privilegeLevel).should.equal true
  62. it "should set the user's id on the client", ->
  63. @client.set.calledWith("user_id", @user._id).should.equal true
  64. it "should set the user's email on the client", ->
  65. @client.set.calledWith("email", @user.email).should.equal true
  66. it "should set the user's first_name on the client", ->
  67. @client.set.calledWith("first_name", @user.first_name).should.equal true
  68. it "should set the user's last_name on the client", ->
  69. @client.set.calledWith("last_name", @user.last_name).should.equal true
  70. it "should set the user's sign up date on the client", ->
  71. @client.set.calledWith("signup_date", @user.signUpDate).should.equal true
  72. it "should set the user's login_count on the client", ->
  73. @client.set.calledWith("login_count", @user.loginCount).should.equal true
  74. it "should set the connected time on the client", ->
  75. @client.set.calledWith("connected_time", new Date()).should.equal true
  76. it "should set the project_id on the client", ->
  77. @client.set.calledWith("project_id", @project_id).should.equal true
  78. it "should set the project owner id on the client", ->
  79. @client.set.calledWith("owner_id", @owner_id).should.equal true
  80. it "should call the callback with the project, privilegeLevel and protocolVersion", ->
  81. @callback
  82. .calledWith(null, @project, @privilegeLevel, @WebsocketController.PROTOCOL_VERSION)
  83. .should.equal true
  84. it "should mark the user as connected in ConnectedUsersManager", ->
  85. @ConnectedUsersManager.updateUserPosition
  86. .calledWith(@project_id, @client.id, @user, null)
  87. .should.equal true
  88. it "should increment the join-project metric", ->
  89. @metrics.inc.calledWith("editor.join-project").should.equal true
  90. describe "when not authorized", ->
  91. beforeEach ->
  92. @WebApiManager.joinProject = sinon.stub().callsArgWith(2, null, null, null)
  93. @WebsocketController.joinProject @client, @user, @project_id, @callback
  94. it "should return an error", ->
  95. @callback
  96. .calledWith(new Error("not authorized"))
  97. .should.equal true
  98. describe "leaveProject", ->
  99. beforeEach ->
  100. @DocumentUpdaterManager.flushProjectToMongoAndDelete = sinon.stub().callsArg(1)
  101. @ConnectedUsersManager.markUserAsDisconnected = sinon.stub().callsArg(2)
  102. @WebsocketLoadBalancer.emitToRoom = sinon.stub()
  103. @clientsInRoom = []
  104. @io =
  105. sockets:
  106. clients: (room_id) =>
  107. if room_id != @project_id
  108. throw "expected room_id to be project_id"
  109. return @clientsInRoom
  110. @client.params.project_id = @project_id
  111. @client.params.user_id = @user_id
  112. @WebsocketController.FLUSH_IF_EMPTY_DELAY = 0
  113. tk.reset() # Allow setTimeout to work.
  114. describe "when the project is empty", ->
  115. beforeEach (done) ->
  116. @clientsInRoom = []
  117. @WebsocketController.leaveProject @io, @client, done
  118. it "should end clientTracking.clientDisconnected to the project room", ->
  119. @WebsocketLoadBalancer.emitToRoom
  120. .calledWith(@project_id, "clientTracking.clientDisconnected", @client.id)
  121. .should.equal true
  122. it "should mark the user as disconnected", ->
  123. @ConnectedUsersManager.markUserAsDisconnected
  124. .calledWith(@project_id, @client.id)
  125. .should.equal true
  126. it "should flush the project in the document updater", ->
  127. @DocumentUpdaterManager.flushProjectToMongoAndDelete
  128. .calledWith(@project_id)
  129. .should.equal true
  130. it "should increment the leave-project metric", ->
  131. @metrics.inc.calledWith("editor.leave-project").should.equal true
  132. describe "when the project is not empty", ->
  133. beforeEach ->
  134. @clientsInRoom = ["mock-remaining-client"]
  135. @WebsocketController.leaveProject @io, @client
  136. it "should not flush the project in the document updater", ->
  137. @DocumentUpdaterManager.flushProjectToMongoAndDelete
  138. .called.should.equal false
  139. describe "when client has not authenticated", ->
  140. beforeEach (done) ->
  141. @client.params.user_id = null
  142. @client.params.project_id = null
  143. @WebsocketController.leaveProject @io, @client, done
  144. it "should not end clientTracking.clientDisconnected to the project room", ->
  145. @WebsocketLoadBalancer.emitToRoom
  146. .calledWith(@project_id, "clientTracking.clientDisconnected", @client.id)
  147. .should.equal false
  148. it "should not mark the user as disconnected", ->
  149. @ConnectedUsersManager.markUserAsDisconnected
  150. .calledWith(@project_id, @client.id)
  151. .should.equal false
  152. it "should not flush the project in the document updater", ->
  153. @DocumentUpdaterManager.flushProjectToMongoAndDelete
  154. .calledWith(@project_id)
  155. .should.equal false
  156. it "should increment the leave-project metric", ->
  157. @metrics.inc.calledWith("editor.leave-project").should.equal true
  158. describe "when client has not joined a project", ->
  159. beforeEach (done) ->
  160. @client.params.user_id = @user_id
  161. @client.params.project_id = null
  162. @WebsocketController.leaveProject @io, @client, done
  163. it "should not end clientTracking.clientDisconnected to the project room", ->
  164. @WebsocketLoadBalancer.emitToRoom
  165. .calledWith(@project_id, "clientTracking.clientDisconnected", @client.id)
  166. .should.equal false
  167. it "should not mark the user as disconnected", ->
  168. @ConnectedUsersManager.markUserAsDisconnected
  169. .calledWith(@project_id, @client.id)
  170. .should.equal false
  171. it "should not flush the project in the document updater", ->
  172. @DocumentUpdaterManager.flushProjectToMongoAndDelete
  173. .calledWith(@project_id)
  174. .should.equal false
  175. it "should increment the leave-project metric", ->
  176. @metrics.inc.calledWith("editor.leave-project").should.equal true
  177. describe "joinDoc", ->
  178. beforeEach ->
  179. @doc_id = "doc-id-123"
  180. @doc_lines = ["doc", "lines"]
  181. @version = 42
  182. @ops = ["mock", "ops"]
  183. @ranges = { "mock": "ranges" }
  184. @options = {}
  185. @client.params.project_id = @project_id
  186. @AuthorizationManager.addAccessToDoc = sinon.stub()
  187. @AuthorizationManager.assertClientCanViewProject = sinon.stub().callsArgWith(1, null)
  188. @DocumentUpdaterManager.getDocument = sinon.stub().callsArgWith(3, null, @doc_lines, @version, @ranges, @ops)
  189. describe "works", ->
  190. beforeEach ->
  191. @WebsocketController.joinDoc @client, @doc_id, -1, @options, @callback
  192. it "should check that the client is authorized to view the project", ->
  193. @AuthorizationManager.assertClientCanViewProject
  194. .calledWith(@client)
  195. .should.equal true
  196. it "should get the document from the DocumentUpdaterManager with fromVersion", ->
  197. @DocumentUpdaterManager.getDocument
  198. .calledWith(@project_id, @doc_id, -1)
  199. .should.equal true
  200. it "should add permissions for the client to access the doc", ->
  201. @AuthorizationManager.addAccessToDoc
  202. .calledWith(@client, @doc_id)
  203. .should.equal true
  204. it "should join the client to room for the doc_id", ->
  205. @client.join
  206. .calledWith(@doc_id)
  207. .should.equal true
  208. it "should call the callback with the lines, version, ranges and ops", ->
  209. @callback
  210. .calledWith(null, @doc_lines, @version, @ops, @ranges)
  211. .should.equal true
  212. it "should increment the join-doc metric", ->
  213. @metrics.inc.calledWith("editor.join-doc").should.equal true
  214. describe "with a fromVersion", ->
  215. beforeEach ->
  216. @fromVersion = 40
  217. @WebsocketController.joinDoc @client, @doc_id, @fromVersion, @options, @callback
  218. it "should get the document from the DocumentUpdaterManager with fromVersion", ->
  219. @DocumentUpdaterManager.getDocument
  220. .calledWith(@project_id, @doc_id, @fromVersion)
  221. .should.equal true
  222. describe "with doclines that need escaping", ->
  223. beforeEach ->
  224. @doc_lines.push ["räksmörgås"]
  225. @WebsocketController.joinDoc @client, @doc_id, -1, @options, @callback
  226. it "should call the callback with the escaped lines", ->
  227. escaped_lines = @callback.args[0][1]
  228. escaped_word = escaped_lines.pop()
  229. escaped_word.should.equal 'räksmörgås'
  230. # Check that unescaping works
  231. decodeURIComponent(escape(escaped_word)).should.equal "räksmörgås"
  232. describe "with comments that need encoding", ->
  233. beforeEach ->
  234. @ranges.comments = [{ op: { c: "räksmörgås" } }]
  235. @WebsocketController.joinDoc @client, @doc_id, -1, { encodeRanges: true }, @callback
  236. it "should call the callback with the encoded comment", ->
  237. encoded_comments = @callback.args[0][4]
  238. encoded_comment = encoded_comments.comments.pop()
  239. encoded_comment_text = encoded_comment.op.c
  240. encoded_comment_text.should.equal 'räksmörgås'
  241. describe "with changes that need encoding", ->
  242. it "should call the callback with the encoded insert change", ->
  243. @ranges.changes = [{ op: { i: "räksmörgås" } }]
  244. @WebsocketController.joinDoc @client, @doc_id, -1, { encodeRanges: true }, @callback
  245. encoded_changes = @callback.args[0][4]
  246. encoded_change = encoded_changes.changes.pop()
  247. encoded_change_text = encoded_change.op.i
  248. encoded_change_text.should.equal 'räksmörgås'
  249. it "should call the callback with the encoded delete change", ->
  250. @ranges.changes = [{ op: { d: "räksmörgås" } }]
  251. @WebsocketController.joinDoc @client, @doc_id, -1, { encodeRanges: true }, @callback
  252. encoded_changes = @callback.args[0][4]
  253. encoded_change = encoded_changes.changes.pop()
  254. encoded_change_text = encoded_change.op.d
  255. encoded_change_text.should.equal 'räksmörgås'
  256. describe "when not authorized", ->
  257. beforeEach ->
  258. @AuthorizationManager.assertClientCanViewProject = sinon.stub().callsArgWith(1, @err = new Error("not authorized"))
  259. @WebsocketController.joinDoc @client, @doc_id, -1, @options, @callback
  260. it "should call the callback with an error", ->
  261. @callback.calledWith(@err).should.equal true
  262. it "should not call the DocumentUpdaterManager", ->
  263. @DocumentUpdaterManager.getDocument.called.should.equal false
  264. describe "leaveDoc", ->
  265. beforeEach ->
  266. @doc_id = "doc-id-123"
  267. @client.params.project_id = @project_id
  268. @WebsocketController.leaveDoc @client, @doc_id, @callback
  269. it "should remove the client from the doc_id room", ->
  270. @client.leave
  271. .calledWith(@doc_id).should.equal true
  272. it "should call the callback", ->
  273. @callback.called.should.equal true
  274. it "should increment the leave-doc metric", ->
  275. @metrics.inc.calledWith("editor.leave-doc").should.equal true
  276. describe "getConnectedUsers", ->
  277. beforeEach ->
  278. @client.params.project_id = @project_id
  279. @users = ["mock", "users"]
  280. @ConnectedUsersManager.getConnectedUsers = sinon.stub().callsArgWith(1, null, @users)
  281. describe "when authorized", ->
  282. beforeEach ->
  283. @AuthorizationManager.assertClientCanViewProject = sinon.stub().callsArgWith(1, null)
  284. @WebsocketController.getConnectedUsers @client, @callback
  285. it "should check that the client is authorized to view the project", ->
  286. @AuthorizationManager.assertClientCanViewProject
  287. .calledWith(@client)
  288. .should.equal true
  289. it "should get the connected users for the project", ->
  290. @ConnectedUsersManager.getConnectedUsers
  291. .calledWith(@project_id)
  292. .should.equal true
  293. it "should return the users", ->
  294. @callback.calledWith(null, @users).should.equal true
  295. it "should increment the get-connected-users metric", ->
  296. @metrics.inc.calledWith("editor.get-connected-users").should.equal true
  297. describe "when not authorized", ->
  298. beforeEach ->
  299. @AuthorizationManager.assertClientCanViewProject = sinon.stub().callsArgWith(1, @err = new Error("not authorized"))
  300. @WebsocketController.getConnectedUsers @client, @callback
  301. it "should not get the connected users for the project", ->
  302. @ConnectedUsersManager.getConnectedUsers
  303. .called
  304. .should.equal false
  305. it "should return an error", ->
  306. @callback.calledWith(@err).should.equal true
  307. describe "updateClientPosition", ->
  308. beforeEach ->
  309. @WebsocketLoadBalancer.emitToRoom = sinon.stub()
  310. @ConnectedUsersManager.updateUserPosition = sinon.stub().callsArgWith(4)
  311. @AuthorizationManager.assertClientCanViewProjectAndDoc = sinon.stub().callsArgWith(2, null)
  312. @update = {
  313. doc_id: @doc_id = "doc-id-123"
  314. row: @row = 42
  315. column: @column = 37
  316. }
  317. describe "with a logged in user", ->
  318. beforeEach ->
  319. @clientParams = {
  320. project_id: @project_id
  321. first_name: @first_name = "Douglas"
  322. last_name: @last_name = "Adams"
  323. email: @email = "joe@example.com"
  324. user_id: @user_id = "user-id-123"
  325. }
  326. @client.get = (param, callback) => callback null, @clientParams[param]
  327. @WebsocketController.updateClientPosition @client, @update
  328. @populatedCursorData =
  329. doc_id: @doc_id,
  330. id: @client.id
  331. name: "#{@first_name} #{@last_name}"
  332. row: @row
  333. column: @column
  334. email: @email
  335. user_id: @user_id
  336. it "should send the update to the project room with the user's name", ->
  337. @WebsocketLoadBalancer.emitToRoom.calledWith(@project_id, "clientTracking.clientUpdated", @populatedCursorData).should.equal true
  338. it "should send the cursor data to the connected user manager", (done)->
  339. @ConnectedUsersManager.updateUserPosition.calledWith(@project_id, @client.id, {
  340. _id: @user_id,
  341. email: @email,
  342. first_name: @first_name,
  343. last_name: @last_name
  344. }, {
  345. row: @row
  346. column: @column
  347. doc_id: @doc_id
  348. }).should.equal true
  349. done()
  350. it "should increment the update-client-position metric at 0.1 frequency", ->
  351. @metrics.inc.calledWith("editor.update-client-position", 0.1).should.equal true
  352. describe "with an anonymous user", ->
  353. beforeEach ->
  354. @clientParams = {
  355. project_id: @project_id
  356. }
  357. @client.get = (param, callback) => callback null, @clientParams[param]
  358. @WebsocketController.updateClientPosition @client, @update
  359. it "should send the update to the project room with an anonymous name", ->
  360. @WebsocketLoadBalancer.emitToRoom
  361. .calledWith(@project_id, "clientTracking.clientUpdated", {
  362. doc_id: @doc_id,
  363. id: @client.id
  364. name: "Anonymous"
  365. row: @row
  366. column: @column
  367. })
  368. .should.equal true
  369. it "should not send cursor data to the connected user manager", (done)->
  370. @ConnectedUsersManager.updateUserPosition.called.should.equal false
  371. done()
  372. describe "applyOtUpdate", ->
  373. beforeEach ->
  374. @update = {op: {p: 12, t: "foo"}}
  375. @client.params.user_id = @user_id
  376. @client.params.project_id = @project_id
  377. @WebsocketController._assertClientCanApplyUpdate = sinon.stub().yields()
  378. @DocumentUpdaterManager.queueChange = sinon.stub().callsArg(3)
  379. describe "succesfully", ->
  380. beforeEach ->
  381. @WebsocketController.applyOtUpdate @client, @doc_id, @update, @callback
  382. it "should set the source of the update to the client id", ->
  383. @update.meta.source.should.equal @client.id
  384. it "should set the user_id of the update to the user id", ->
  385. @update.meta.user_id.should.equal @user_id
  386. it "should queue the update", ->
  387. @DocumentUpdaterManager.queueChange
  388. .calledWith(@project_id, @doc_id, @update)
  389. .should.equal true
  390. it "should call the callback", ->
  391. @callback.called.should.equal true
  392. it "should update the active users metric", ->
  393. @metrics.set.calledWith("editor.active-users", @user_id).should.equal true
  394. it "should update the active projects metric", ->
  395. @metrics.set.calledWith("editor.active-projects", @project_id).should.equal true
  396. it "should increment the doc updates", ->
  397. @metrics.inc.calledWith("editor.doc-update").should.equal true
  398. describe "unsuccessfully", ->
  399. beforeEach ->
  400. @client.disconnect = sinon.stub()
  401. @DocumentUpdaterManager.queueChange = sinon.stub().callsArgWith(3, @error = new Error("Something went wrong"))
  402. @WebsocketController.applyOtUpdate @client, @doc_id, @update, @callback
  403. it "should disconnect the client", ->
  404. @client.disconnect.called.should.equal true
  405. it "should log an error", ->
  406. @logger.error.called.should.equal true
  407. it "should call the callback with the error", ->
  408. @callback.calledWith(@error).should.equal true
  409. describe "when not authorized", ->
  410. beforeEach ->
  411. @client.disconnect = sinon.stub()
  412. @WebsocketController._assertClientCanApplyUpdate = sinon.stub().yields(@error = new Error("not authorized"))
  413. @WebsocketController.applyOtUpdate @client, @doc_id, @update, @callback
  414. # This happens in a setTimeout to allow the client a chance to receive the error first.
  415. # I'm not sure how to unit test, but it is acceptance tested.
  416. # it "should disconnect the client", ->
  417. # @client.disconnect.called.should.equal true
  418. it "should log an error", ->
  419. @logger.error.called.should.equal true
  420. it "should call the callback with the error", ->
  421. @callback.calledWith(@error).should.equal true
  422. describe "_assertClientCanApplyUpdate", ->
  423. beforeEach ->
  424. @edit_update = { op: [{i: "foo", p: 42}, {c: "bar", p: 132}] } # comments may still be in an edit op
  425. @comment_update = { op: [{c: "bar", p: 132}] }
  426. @AuthorizationManager.assertClientCanEditProjectAndDoc = sinon.stub()
  427. @AuthorizationManager.assertClientCanViewProjectAndDoc = sinon.stub()
  428. describe "with a read-write client", ->
  429. it "should return successfully", (done) ->
  430. @AuthorizationManager.assertClientCanEditProjectAndDoc.yields(null)
  431. @WebsocketController._assertClientCanApplyUpdate @client, @doc_id, @edit_update, (error) ->
  432. expect(error).to.be.null
  433. done()
  434. describe "with a read-only client and an edit op", ->
  435. it "should return an error", (done) ->
  436. @AuthorizationManager.assertClientCanEditProjectAndDoc.yields(new Error("not authorized"))
  437. @AuthorizationManager.assertClientCanViewProjectAndDoc.yields(null)
  438. @WebsocketController._assertClientCanApplyUpdate @client, @doc_id, @edit_update, (error) ->
  439. expect(error.message).to.equal "not authorized"
  440. done()
  441. describe "with a read-only client and a comment op", ->
  442. it "should return successfully", (done) ->
  443. @AuthorizationManager.assertClientCanEditProjectAndDoc.yields(new Error("not authorized"))
  444. @AuthorizationManager.assertClientCanViewProjectAndDoc.yields(null)
  445. @WebsocketController._assertClientCanApplyUpdate @client, @doc_id, @comment_update, (error) ->
  446. expect(error).to.be.null
  447. done()
  448. describe "with a totally unauthorized client", ->
  449. it "should return an error", (done) ->
  450. @AuthorizationManager.assertClientCanEditProjectAndDoc.yields(new Error("not authorized"))
  451. @AuthorizationManager.assertClientCanViewProjectAndDoc.yields(new Error("not authorized"))
  452. @WebsocketController._assertClientCanApplyUpdate @client, @doc_id, @comment_update, (error) ->
  453. expect(error.message).to.equal "not authorized"
  454. done()