DocArchiveManagerTests.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. const sinon = require('sinon')
  2. const { expect } = require('chai')
  3. const modulePath = '../../../app/js/DocArchiveManager.js'
  4. const SandboxedModule = require('sandboxed-module')
  5. const { ObjectId } = require('mongodb-legacy')
  6. const Errors = require('../../../app/js/Errors')
  7. const StreamToBuffer = require('../../../app/js/StreamToBuffer')
  8. describe('DocArchiveManager', function () {
  9. let DocArchiveManager,
  10. PersistorManager,
  11. MongoManager,
  12. RangeManager,
  13. Settings,
  14. Crypto,
  15. StreamUtils,
  16. HashDigest,
  17. HashUpdate,
  18. archivedDocs,
  19. mongoDocs,
  20. archivedDoc,
  21. archivedDocJson,
  22. md5Sum,
  23. projectId,
  24. readStream,
  25. stream,
  26. streamToBuffer
  27. beforeEach(function () {
  28. md5Sum = 'decafbad'
  29. RangeManager = {
  30. jsonRangesToMongo: sinon.stub().returns({ mongo: 'ranges' }),
  31. fixCommentIds: sinon.stub(),
  32. }
  33. Settings = {
  34. docstore: {
  35. backend: 'gcs',
  36. bucket: 'wombat',
  37. },
  38. parallelArchiveJobs: 3,
  39. }
  40. HashDigest = sinon.stub().returns(md5Sum)
  41. HashUpdate = sinon.stub().returns({ digest: HashDigest })
  42. Crypto = {
  43. createHash: sinon.stub().returns({ update: HashUpdate }),
  44. }
  45. StreamUtils = {
  46. ReadableString: sinon.stub().returns({ stream: 'readStream' }),
  47. }
  48. projectId = new ObjectId()
  49. archivedDocs = [
  50. {
  51. _id: new ObjectId(),
  52. inS3: true,
  53. rev: 2,
  54. },
  55. {
  56. _id: new ObjectId(),
  57. inS3: true,
  58. rev: 4,
  59. },
  60. {
  61. _id: new ObjectId(),
  62. inS3: true,
  63. rev: 6,
  64. },
  65. ]
  66. mongoDocs = [
  67. {
  68. _id: new ObjectId(),
  69. lines: ['one', 'two', 'three'],
  70. rev: 2,
  71. },
  72. {
  73. _id: new ObjectId(),
  74. lines: ['aaa', 'bbb', 'ccc'],
  75. rev: 4,
  76. },
  77. {
  78. _id: new ObjectId(),
  79. inS3: true,
  80. rev: 6,
  81. },
  82. {
  83. _id: new ObjectId(),
  84. inS3: true,
  85. rev: 6,
  86. },
  87. {
  88. _id: new ObjectId(),
  89. lines: ['111', '222', '333'],
  90. rev: 6,
  91. },
  92. ]
  93. archivedDoc = {
  94. lines: mongoDocs[0].lines,
  95. rev: mongoDocs[0].rev,
  96. }
  97. archivedDocJson = JSON.stringify({ ...archivedDoc, schema_v: 1 })
  98. stream = {
  99. on: sinon.stub(),
  100. resume: sinon.stub(),
  101. }
  102. stream.on.withArgs('data').yields(Buffer.from(archivedDocJson, 'utf8'))
  103. stream.on.withArgs('end').yields()
  104. readStream = {
  105. stream: 'readStream',
  106. }
  107. PersistorManager = {
  108. getObjectStream: sinon.stub().resolves(stream),
  109. sendStream: sinon.stub().resolves(),
  110. getObjectMd5Hash: sinon.stub().resolves(md5Sum),
  111. deleteObject: sinon.stub().resolves(),
  112. deleteDirectory: sinon.stub().resolves(),
  113. }
  114. const getNonArchivedProjectDocIds = sinon.stub()
  115. getNonArchivedProjectDocIds
  116. .onCall(0)
  117. .resolves(mongoDocs.filter(doc => !doc.inS3).map(doc => doc._id))
  118. getNonArchivedProjectDocIds.onCall(1).resolves([])
  119. const getArchivedProjectDocs = sinon.stub()
  120. getArchivedProjectDocs.onCall(0).resolves(archivedDocs)
  121. getArchivedProjectDocs.onCall(1).resolves([])
  122. const fakeGetDoc = async (_projectId, _docId) => {
  123. if (_projectId.equals(projectId)) {
  124. for (const mongoDoc of mongoDocs.concat(archivedDocs)) {
  125. if (mongoDoc._id.equals(_docId)) {
  126. return mongoDoc
  127. }
  128. }
  129. }
  130. throw new Errors.NotFoundError()
  131. }
  132. MongoManager = {
  133. markDocAsArchived: sinon.stub().resolves(),
  134. restoreArchivedDoc: sinon.stub().resolves(),
  135. upsertIntoDocCollection: sinon.stub().resolves(),
  136. getProjectsDocs: sinon.stub().resolves(mongoDocs),
  137. getNonDeletedArchivedProjectDocs: getArchivedProjectDocs,
  138. getNonArchivedProjectDocIds,
  139. getArchivedProjectDocs,
  140. findDoc: sinon.stub().callsFake(fakeGetDoc),
  141. getDocForArchiving: sinon.stub().callsFake(fakeGetDoc),
  142. destroyProject: sinon.stub().resolves(),
  143. }
  144. // Wrap streamToBuffer so that we can pass in something that it expects (in
  145. // this case, a Promise) rather than a stubbed stream object
  146. streamToBuffer = {
  147. streamToBuffer: async () => {
  148. const inputStream = new Promise(resolve => {
  149. stream.on('data', data => resolve(data))
  150. })
  151. const value = await StreamToBuffer.streamToBuffer(
  152. 'testProjectId',
  153. 'testDocId',
  154. inputStream
  155. )
  156. return value
  157. },
  158. }
  159. DocArchiveManager = SandboxedModule.require(modulePath, {
  160. requires: {
  161. '@overleaf/settings': Settings,
  162. crypto: Crypto,
  163. '@overleaf/stream-utils': StreamUtils,
  164. './MongoManager': MongoManager,
  165. './RangeManager': RangeManager,
  166. './PersistorManager': PersistorManager,
  167. './Errors': Errors,
  168. './StreamToBuffer': streamToBuffer,
  169. },
  170. })
  171. })
  172. describe('archiveDoc', function () {
  173. it('should resolve when passed a valid document', async function () {
  174. await expect(DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)).to
  175. .eventually.be.fulfilled
  176. })
  177. it('should fix comment ids', async function () {
  178. await DocArchiveManager.archiveDoc(projectId, mongoDocs[1]._id)
  179. expect(RangeManager.fixCommentIds).to.have.been.called
  180. })
  181. it('should throw an error if the doc has no lines', async function () {
  182. const doc = mongoDocs[0]
  183. doc.lines = null
  184. await expect(
  185. DocArchiveManager.archiveDoc(projectId, doc._id)
  186. ).to.eventually.be.rejectedWith('doc has no lines')
  187. })
  188. it('should add the schema version', async function () {
  189. await DocArchiveManager.archiveDoc(projectId, mongoDocs[1]._id)
  190. expect(StreamUtils.ReadableString).to.have.been.calledWith(
  191. sinon.match(/"schema_v":1/)
  192. )
  193. })
  194. it('should calculate the hex md5 sum of the content', async function () {
  195. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  196. expect(Crypto.createHash).to.have.been.calledWith('md5')
  197. expect(HashUpdate).to.have.been.calledWith(archivedDocJson)
  198. expect(HashDigest).to.have.been.calledWith('hex')
  199. })
  200. it('should pass the md5 hash to the object persistor for verification', async function () {
  201. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  202. expect(PersistorManager.sendStream).to.have.been.calledWith(
  203. sinon.match.any,
  204. sinon.match.any,
  205. sinon.match.any,
  206. { sourceMd5: md5Sum }
  207. )
  208. })
  209. it('should pass the correct bucket and key to the persistor', async function () {
  210. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  211. expect(PersistorManager.sendStream).to.have.been.calledWith(
  212. Settings.docstore.bucket,
  213. `${projectId}/${mongoDocs[0]._id}`
  214. )
  215. })
  216. it('should create a stream from the encoded json and send it', async function () {
  217. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  218. expect(StreamUtils.ReadableString).to.have.been.calledWith(
  219. archivedDocJson
  220. )
  221. expect(PersistorManager.sendStream).to.have.been.calledWith(
  222. sinon.match.any,
  223. sinon.match.any,
  224. readStream
  225. )
  226. })
  227. it('should mark the doc as archived', async function () {
  228. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  229. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  230. projectId,
  231. mongoDocs[0]._id,
  232. mongoDocs[0].rev
  233. )
  234. })
  235. describe('when archiving is not configured', function () {
  236. beforeEach(function () {
  237. Settings.docstore.backend = undefined
  238. })
  239. it('should bail out early', async function () {
  240. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  241. expect(MongoManager.getDocForArchiving).to.not.have.been.called
  242. })
  243. })
  244. describe('with null bytes in the result', function () {
  245. const _stringify = JSON.stringify
  246. beforeEach(function () {
  247. JSON.stringify = sinon.stub().returns('{"bad": "\u0000"}')
  248. })
  249. afterEach(function () {
  250. JSON.stringify = _stringify
  251. })
  252. it('should return an error', async function () {
  253. await expect(
  254. DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  255. ).to.eventually.be.rejectedWith('null bytes detected')
  256. })
  257. })
  258. })
  259. describe('unarchiveDoc', function () {
  260. let docId, lines, rev
  261. describe('when the doc is in S3', function () {
  262. beforeEach(function () {
  263. MongoManager.findDoc = sinon.stub().resolves({ inS3: true, rev })
  264. docId = mongoDocs[0]._id
  265. lines = ['doc', 'lines']
  266. rev = 123
  267. })
  268. it('should resolve when passed a valid document', async function () {
  269. await expect(DocArchiveManager.unarchiveDoc(projectId, docId)).to
  270. .eventually.be.fulfilled
  271. })
  272. it('should test md5 validity with the raw buffer', async function () {
  273. await DocArchiveManager.unarchiveDoc(projectId, docId)
  274. expect(HashUpdate).to.have.been.calledWith(
  275. sinon.match.instanceOf(Buffer)
  276. )
  277. })
  278. it('should throw an error if the md5 does not match', async function () {
  279. PersistorManager.getObjectMd5Hash.resolves('badf00d')
  280. await expect(
  281. DocArchiveManager.unarchiveDoc(projectId, docId)
  282. ).to.eventually.be.rejected.and.be.instanceof(Errors.Md5MismatchError)
  283. })
  284. it('should restore the doc in Mongo', async function () {
  285. await DocArchiveManager.unarchiveDoc(projectId, docId)
  286. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  287. projectId,
  288. docId,
  289. archivedDoc
  290. )
  291. })
  292. describe('when archiving is not configured', function () {
  293. beforeEach(function () {
  294. Settings.docstore.backend = undefined
  295. })
  296. it('should error out on archived doc', async function () {
  297. await expect(
  298. DocArchiveManager.unarchiveDoc(projectId, docId)
  299. ).to.eventually.be.rejected.and.match(
  300. /found archived doc, but archiving backend is not configured/
  301. )
  302. })
  303. it('should return early on non-archived doc', async function () {
  304. MongoManager.findDoc = sinon.stub().resolves({ rev })
  305. await DocArchiveManager.unarchiveDoc(projectId, docId)
  306. expect(PersistorManager.getObjectMd5Hash).to.not.have.been.called
  307. })
  308. })
  309. describe('doc contents', function () {
  310. let archivedDoc
  311. describe('when the doc has the old schema', function () {
  312. beforeEach(function () {
  313. archivedDoc = lines
  314. archivedDocJson = JSON.stringify(archivedDoc)
  315. stream.on
  316. .withArgs('data')
  317. .yields(Buffer.from(archivedDocJson, 'utf8'))
  318. })
  319. it('should return the docs lines', async function () {
  320. await DocArchiveManager.unarchiveDoc(projectId, docId)
  321. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  322. projectId,
  323. docId,
  324. { lines, rev }
  325. )
  326. })
  327. })
  328. describe('with the new schema and ranges', function () {
  329. beforeEach(function () {
  330. archivedDoc = {
  331. lines,
  332. ranges: { json: 'ranges' },
  333. rev: 456,
  334. schema_v: 1,
  335. }
  336. archivedDocJson = JSON.stringify(archivedDoc)
  337. stream.on
  338. .withArgs('data')
  339. .yields(Buffer.from(archivedDocJson, 'utf8'))
  340. })
  341. it('should return the doc lines and ranges', async function () {
  342. await DocArchiveManager.unarchiveDoc(projectId, docId)
  343. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  344. projectId,
  345. docId,
  346. {
  347. lines,
  348. ranges: { mongo: 'ranges' },
  349. rev: 456,
  350. }
  351. )
  352. })
  353. })
  354. describe('with the new schema and no ranges', function () {
  355. beforeEach(function () {
  356. archivedDoc = { lines, rev: 456, schema_v: 1 }
  357. archivedDocJson = JSON.stringify(archivedDoc)
  358. stream.on
  359. .withArgs('data')
  360. .yields(Buffer.from(archivedDocJson, 'utf8'))
  361. })
  362. it('should return only the doc lines', async function () {
  363. await DocArchiveManager.unarchiveDoc(projectId, docId)
  364. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  365. projectId,
  366. docId,
  367. { lines, rev: 456 }
  368. )
  369. })
  370. })
  371. describe('with the new schema and no rev', function () {
  372. beforeEach(function () {
  373. archivedDoc = { lines, schema_v: 1 }
  374. archivedDocJson = JSON.stringify(archivedDoc)
  375. stream.on
  376. .withArgs('data')
  377. .yields(Buffer.from(archivedDocJson, 'utf8'))
  378. })
  379. it('should use the rev obtained from Mongo', async function () {
  380. await DocArchiveManager.unarchiveDoc(projectId, docId)
  381. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  382. projectId,
  383. docId,
  384. { lines, rev }
  385. )
  386. })
  387. })
  388. describe('with an unrecognised schema', function () {
  389. beforeEach(function () {
  390. archivedDoc = { lines, schema_v: 2 }
  391. archivedDocJson = JSON.stringify(archivedDoc)
  392. stream.on
  393. .withArgs('data')
  394. .yields(Buffer.from(archivedDocJson, 'utf8'))
  395. })
  396. it('should throw an error', async function () {
  397. await expect(
  398. DocArchiveManager.unarchiveDoc(projectId, docId)
  399. ).to.eventually.be.rejectedWith(
  400. "I don't understand the doc format in s3"
  401. )
  402. })
  403. })
  404. })
  405. })
  406. it('should not do anything if the file is already unarchived', async function () {
  407. MongoManager.findDoc.resolves({ inS3: false })
  408. await DocArchiveManager.unarchiveDoc(projectId, docId)
  409. expect(PersistorManager.getObjectStream).not.to.have.been.called
  410. })
  411. it('should throw an error if the file is not found', async function () {
  412. PersistorManager.getObjectStream = sinon
  413. .stub()
  414. .rejects(new Errors.NotFoundError())
  415. await expect(
  416. DocArchiveManager.unarchiveDoc(projectId, docId)
  417. ).to.eventually.be.rejected.and.be.instanceof(Errors.NotFoundError)
  418. })
  419. })
  420. describe('destroyProject', function () {
  421. describe('when archiving is enabled', function () {
  422. beforeEach(async function () {
  423. await DocArchiveManager.destroyProject(projectId)
  424. })
  425. it('should delete the project in Mongo', function () {
  426. expect(MongoManager.destroyProject).to.have.been.calledWith(projectId)
  427. })
  428. it('should delete the project in the persistor', function () {
  429. expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
  430. Settings.docstore.bucket,
  431. projectId
  432. )
  433. })
  434. })
  435. describe('when archiving is disabled', function () {
  436. beforeEach(async function () {
  437. Settings.docstore.backend = ''
  438. await DocArchiveManager.destroyProject(projectId)
  439. })
  440. it('should delete the project in Mongo', function () {
  441. expect(MongoManager.destroyProject).to.have.been.calledWith(projectId)
  442. })
  443. it('should not delete the project in the persistor', function () {
  444. expect(PersistorManager.deleteDirectory).not.to.have.been.called
  445. })
  446. })
  447. })
  448. describe('archiveAllDocs', function () {
  449. it('should resolve with valid arguments', async function () {
  450. await expect(DocArchiveManager.archiveAllDocs(projectId)).to.eventually.be
  451. .fulfilled
  452. })
  453. it('should archive all project docs which are not in s3', async function () {
  454. await DocArchiveManager.archiveAllDocs(projectId)
  455. // not inS3
  456. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  457. projectId,
  458. mongoDocs[0]._id
  459. )
  460. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  461. projectId,
  462. mongoDocs[1]._id
  463. )
  464. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  465. projectId,
  466. mongoDocs[4]._id
  467. )
  468. // inS3
  469. expect(MongoManager.markDocAsArchived).not.to.have.been.calledWith(
  470. projectId,
  471. mongoDocs[2]._id
  472. )
  473. expect(MongoManager.markDocAsArchived).not.to.have.been.calledWith(
  474. projectId,
  475. mongoDocs[3]._id
  476. )
  477. })
  478. describe('when archiving is not configured', function () {
  479. beforeEach(function () {
  480. Settings.docstore.backend = undefined
  481. })
  482. it('should bail out early', async function () {
  483. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  484. expect(MongoManager.getNonArchivedProjectDocIds).to.not.have.been.called
  485. })
  486. })
  487. })
  488. describe('unArchiveAllDocs', function () {
  489. it('should resolve with valid arguments', async function () {
  490. await expect(DocArchiveManager.unArchiveAllDocs(projectId)).to.eventually
  491. .be.fulfilled
  492. })
  493. it('should unarchive all inS3 docs', async function () {
  494. await DocArchiveManager.unArchiveAllDocs(projectId)
  495. for (const doc of archivedDocs) {
  496. expect(PersistorManager.getObjectStream).to.have.been.calledWith(
  497. Settings.docstore.bucket,
  498. `${projectId}/${doc._id}`
  499. )
  500. }
  501. })
  502. describe('when archiving is not configured', function () {
  503. beforeEach(function () {
  504. Settings.docstore.backend = undefined
  505. })
  506. it('should bail out early', async function () {
  507. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  508. expect(MongoManager.getNonDeletedArchivedProjectDocs).to.not.have.been
  509. .called
  510. })
  511. })
  512. })
  513. })