DocArchiveManagerTests.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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').promises
  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. }
  32. Settings = {
  33. docstore: {
  34. backend: 'gcs',
  35. bucket: 'wombat',
  36. },
  37. parallelArchiveJobs: 3,
  38. }
  39. HashDigest = sinon.stub().returns(md5Sum)
  40. HashUpdate = sinon.stub().returns({ digest: HashDigest })
  41. Crypto = {
  42. createHash: sinon.stub().returns({ update: HashUpdate }),
  43. }
  44. StreamUtils = {
  45. ReadableString: sinon.stub().returns({ stream: 'readStream' }),
  46. }
  47. projectId = new ObjectId()
  48. archivedDocs = [
  49. {
  50. _id: new ObjectId(),
  51. inS3: true,
  52. rev: 2,
  53. },
  54. {
  55. _id: new ObjectId(),
  56. inS3: true,
  57. rev: 4,
  58. },
  59. {
  60. _id: new ObjectId(),
  61. inS3: true,
  62. rev: 6,
  63. },
  64. ]
  65. mongoDocs = [
  66. {
  67. _id: new ObjectId(),
  68. lines: ['one', 'two', 'three'],
  69. rev: 2,
  70. },
  71. {
  72. _id: new ObjectId(),
  73. lines: ['aaa', 'bbb', 'ccc'],
  74. rev: 4,
  75. },
  76. {
  77. _id: new ObjectId(),
  78. inS3: true,
  79. rev: 6,
  80. },
  81. {
  82. _id: new ObjectId(),
  83. inS3: true,
  84. rev: 6,
  85. },
  86. {
  87. _id: new ObjectId(),
  88. lines: ['111', '222', '333'],
  89. rev: 6,
  90. },
  91. ]
  92. archivedDoc = {
  93. lines: mongoDocs[0].lines,
  94. rev: mongoDocs[0].rev,
  95. }
  96. archivedDocJson = JSON.stringify({ ...archivedDoc, schema_v: 1 })
  97. stream = {
  98. on: sinon.stub(),
  99. resume: sinon.stub(),
  100. }
  101. stream.on.withArgs('data').yields(Buffer.from(archivedDocJson, 'utf8'))
  102. stream.on.withArgs('end').yields()
  103. readStream = {
  104. stream: 'readStream',
  105. }
  106. PersistorManager = {
  107. getObjectStream: sinon.stub().resolves(stream),
  108. sendStream: sinon.stub().resolves(),
  109. getObjectMd5Hash: sinon.stub().resolves(md5Sum),
  110. deleteObject: sinon.stub().resolves(),
  111. deleteDirectory: sinon.stub().resolves(),
  112. }
  113. const getNonArchivedProjectDocIds = sinon.stub()
  114. getNonArchivedProjectDocIds
  115. .onCall(0)
  116. .resolves(mongoDocs.filter(doc => !doc.inS3).map(doc => doc._id))
  117. getNonArchivedProjectDocIds.onCall(1).resolves([])
  118. const getArchivedProjectDocs = sinon.stub()
  119. getArchivedProjectDocs.onCall(0).resolves(archivedDocs)
  120. getArchivedProjectDocs.onCall(1).resolves([])
  121. const fakeGetDoc = async (_projectId, _docId) => {
  122. if (_projectId.equals(projectId)) {
  123. for (const mongoDoc of mongoDocs.concat(archivedDocs)) {
  124. if (mongoDoc._id.equals(_docId)) {
  125. return mongoDoc
  126. }
  127. }
  128. }
  129. throw new Errors.NotFoundError()
  130. }
  131. MongoManager = {
  132. promises: {
  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. }
  145. // Wrap streamToBuffer so that we can pass in something that it expects (in
  146. // this case, a Promise) rather than a stubbed stream object
  147. streamToBuffer = {
  148. promises: {
  149. streamToBuffer: async () => {
  150. const inputStream = new Promise(resolve => {
  151. stream.on('data', data => resolve(data))
  152. })
  153. const value = await StreamToBuffer.streamToBuffer(
  154. 'testProjectId',
  155. 'testDocId',
  156. inputStream
  157. )
  158. return value
  159. },
  160. },
  161. }
  162. DocArchiveManager = SandboxedModule.require(modulePath, {
  163. requires: {
  164. '@overleaf/settings': Settings,
  165. crypto: Crypto,
  166. '@overleaf/stream-utils': StreamUtils,
  167. './MongoManager': MongoManager,
  168. './RangeManager': RangeManager,
  169. './PersistorManager': PersistorManager,
  170. './Errors': Errors,
  171. './StreamToBuffer': streamToBuffer,
  172. },
  173. })
  174. })
  175. describe('archiveDoc', function () {
  176. it('should resolve when passed a valid document', async function () {
  177. await expect(
  178. DocArchiveManager.promises.archiveDoc(projectId, mongoDocs[0]._id)
  179. ).to.eventually.be.fulfilled
  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.promises.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.promises.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.promises.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.promises.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.promises.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.promises.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.promises.archiveDoc(projectId, mongoDocs[0]._id)
  229. expect(MongoManager.promises.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.promises.archiveDoc(projectId, mongoDocs[0]._id)
  241. expect(MongoManager.promises.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.promises.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.promises.findDoc = sinon
  264. .stub()
  265. .resolves({ inS3: true, rev })
  266. docId = mongoDocs[0]._id
  267. lines = ['doc', 'lines']
  268. rev = 123
  269. })
  270. it('should resolve when passed a valid document', async function () {
  271. await expect(DocArchiveManager.promises.unarchiveDoc(projectId, docId))
  272. .to.eventually.be.fulfilled
  273. })
  274. it('should test md5 validity with the raw buffer', async function () {
  275. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  276. expect(HashUpdate).to.have.been.calledWith(
  277. sinon.match.instanceOf(Buffer)
  278. )
  279. })
  280. it('should throw an error if the md5 does not match', async function () {
  281. PersistorManager.getObjectMd5Hash.resolves('badf00d')
  282. await expect(
  283. DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  284. ).to.eventually.be.rejected.and.be.instanceof(Errors.Md5MismatchError)
  285. })
  286. it('should restore the doc in Mongo', async function () {
  287. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  288. expect(
  289. MongoManager.promises.restoreArchivedDoc
  290. ).to.have.been.calledWith(projectId, docId, archivedDoc)
  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.promises.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.promises.findDoc = sinon.stub().resolves({ rev })
  305. await DocArchiveManager.promises.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.promises.unarchiveDoc(projectId, docId)
  321. expect(
  322. MongoManager.promises.restoreArchivedDoc
  323. ).to.have.been.calledWith(projectId, docId, { lines, rev })
  324. })
  325. })
  326. describe('with the new schema and ranges', function () {
  327. beforeEach(function () {
  328. archivedDoc = {
  329. lines,
  330. ranges: { json: 'ranges' },
  331. rev: 456,
  332. schema_v: 1,
  333. }
  334. archivedDocJson = JSON.stringify(archivedDoc)
  335. stream.on
  336. .withArgs('data')
  337. .yields(Buffer.from(archivedDocJson, 'utf8'))
  338. })
  339. it('should return the doc lines and ranges', async function () {
  340. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  341. expect(
  342. MongoManager.promises.restoreArchivedDoc
  343. ).to.have.been.calledWith(projectId, docId, {
  344. lines,
  345. ranges: { mongo: 'ranges' },
  346. rev: 456,
  347. })
  348. })
  349. })
  350. describe('with the new schema and no ranges', function () {
  351. beforeEach(function () {
  352. archivedDoc = { lines, rev: 456, schema_v: 1 }
  353. archivedDocJson = JSON.stringify(archivedDoc)
  354. stream.on
  355. .withArgs('data')
  356. .yields(Buffer.from(archivedDocJson, 'utf8'))
  357. })
  358. it('should return only the doc lines', async function () {
  359. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  360. expect(
  361. MongoManager.promises.restoreArchivedDoc
  362. ).to.have.been.calledWith(projectId, docId, { lines, rev: 456 })
  363. })
  364. })
  365. describe('with the new schema and no rev', function () {
  366. beforeEach(function () {
  367. archivedDoc = { lines, schema_v: 1 }
  368. archivedDocJson = JSON.stringify(archivedDoc)
  369. stream.on
  370. .withArgs('data')
  371. .yields(Buffer.from(archivedDocJson, 'utf8'))
  372. })
  373. it('should use the rev obtained from Mongo', async function () {
  374. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  375. expect(
  376. MongoManager.promises.restoreArchivedDoc
  377. ).to.have.been.calledWith(projectId, docId, { lines, rev })
  378. })
  379. })
  380. describe('with an unrecognised schema', function () {
  381. beforeEach(function () {
  382. archivedDoc = { lines, schema_v: 2 }
  383. archivedDocJson = JSON.stringify(archivedDoc)
  384. stream.on
  385. .withArgs('data')
  386. .yields(Buffer.from(archivedDocJson, 'utf8'))
  387. })
  388. it('should throw an error', async function () {
  389. await expect(
  390. DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  391. ).to.eventually.be.rejectedWith(
  392. "I don't understand the doc format in s3"
  393. )
  394. })
  395. })
  396. })
  397. })
  398. it('should not do anything if the file is already unarchived', async function () {
  399. MongoManager.promises.findDoc.resolves({ inS3: false })
  400. await DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  401. expect(PersistorManager.getObjectStream).not.to.have.been.called
  402. })
  403. it('should throw an error if the file is not found', async function () {
  404. PersistorManager.getObjectStream = sinon
  405. .stub()
  406. .rejects(new Errors.NotFoundError())
  407. await expect(
  408. DocArchiveManager.promises.unarchiveDoc(projectId, docId)
  409. ).to.eventually.be.rejected.and.be.instanceof(Errors.NotFoundError)
  410. })
  411. })
  412. describe('destroyProject', function () {
  413. describe('when archiving is enabled', function () {
  414. beforeEach(async function () {
  415. await DocArchiveManager.promises.destroyProject(projectId)
  416. })
  417. it('should delete the project in Mongo', function () {
  418. expect(MongoManager.promises.destroyProject).to.have.been.calledWith(
  419. projectId
  420. )
  421. })
  422. it('should delete the project in the persistor', function () {
  423. expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
  424. Settings.docstore.bucket,
  425. projectId
  426. )
  427. })
  428. })
  429. describe('when archiving is disabled', function () {
  430. beforeEach(async function () {
  431. Settings.docstore.backend = ''
  432. await DocArchiveManager.promises.destroyProject(projectId)
  433. })
  434. it('should delete the project in Mongo', function () {
  435. expect(MongoManager.promises.destroyProject).to.have.been.calledWith(
  436. projectId
  437. )
  438. })
  439. it('should not delete the project in the persistor', function () {
  440. expect(PersistorManager.deleteDirectory).not.to.have.been.called
  441. })
  442. })
  443. })
  444. describe('archiveAllDocs', function () {
  445. it('should resolve with valid arguments', async function () {
  446. await expect(DocArchiveManager.promises.archiveAllDocs(projectId)).to
  447. .eventually.be.fulfilled
  448. })
  449. it('should archive all project docs which are not in s3', async function () {
  450. await DocArchiveManager.promises.archiveAllDocs(projectId)
  451. // not inS3
  452. expect(MongoManager.promises.markDocAsArchived).to.have.been.calledWith(
  453. projectId,
  454. mongoDocs[0]._id
  455. )
  456. expect(MongoManager.promises.markDocAsArchived).to.have.been.calledWith(
  457. projectId,
  458. mongoDocs[1]._id
  459. )
  460. expect(MongoManager.promises.markDocAsArchived).to.have.been.calledWith(
  461. projectId,
  462. mongoDocs[4]._id
  463. )
  464. // inS3
  465. expect(
  466. MongoManager.promises.markDocAsArchived
  467. ).not.to.have.been.calledWith(projectId, mongoDocs[2]._id)
  468. expect(
  469. MongoManager.promises.markDocAsArchived
  470. ).not.to.have.been.calledWith(projectId, mongoDocs[3]._id)
  471. })
  472. describe('when archiving is not configured', function () {
  473. beforeEach(function () {
  474. Settings.docstore.backend = undefined
  475. })
  476. it('should bail out early', async function () {
  477. await DocArchiveManager.promises.archiveDoc(projectId, mongoDocs[0]._id)
  478. expect(MongoManager.promises.getNonArchivedProjectDocIds).to.not.have
  479. .been.called
  480. })
  481. })
  482. })
  483. describe('unArchiveAllDocs', function () {
  484. it('should resolve with valid arguments', async function () {
  485. await expect(DocArchiveManager.promises.unArchiveAllDocs(projectId)).to
  486. .eventually.be.fulfilled
  487. })
  488. it('should unarchive all inS3 docs', async function () {
  489. await DocArchiveManager.promises.unArchiveAllDocs(projectId)
  490. for (const doc of archivedDocs) {
  491. expect(PersistorManager.getObjectStream).to.have.been.calledWith(
  492. Settings.docstore.bucket,
  493. `${projectId}/${doc._id}`
  494. )
  495. }
  496. })
  497. describe('when archiving is not configured', function () {
  498. beforeEach(function () {
  499. Settings.docstore.backend = undefined
  500. })
  501. it('should bail out early', async function () {
  502. await DocArchiveManager.promises.archiveDoc(projectId, mongoDocs[0]._id)
  503. expect(MongoManager.promises.getNonDeletedArchivedProjectDocs).to.not
  504. .have.been.called
  505. })
  506. })
  507. })
  508. })