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')
  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. markDocAsArchived: sinon.stub().resolves(),
  133. restoreArchivedDoc: sinon.stub().resolves(),
  134. upsertIntoDocCollection: sinon.stub().resolves(),
  135. getProjectsDocs: sinon.stub().resolves(mongoDocs),
  136. getNonDeletedArchivedProjectDocs: getArchivedProjectDocs,
  137. getNonArchivedProjectDocIds,
  138. getArchivedProjectDocs,
  139. findDoc: sinon.stub().callsFake(fakeGetDoc),
  140. getDocForArchiving: sinon.stub().callsFake(fakeGetDoc),
  141. destroyProject: sinon.stub().resolves(),
  142. }
  143. // Wrap streamToBuffer so that we can pass in something that it expects (in
  144. // this case, a Promise) rather than a stubbed stream object
  145. streamToBuffer = {
  146. streamToBuffer: async () => {
  147. const inputStream = new Promise(resolve => {
  148. stream.on('data', data => resolve(data))
  149. })
  150. const value = await StreamToBuffer.streamToBuffer(
  151. 'testProjectId',
  152. 'testDocId',
  153. inputStream
  154. )
  155. return value
  156. },
  157. }
  158. DocArchiveManager = SandboxedModule.require(modulePath, {
  159. requires: {
  160. '@overleaf/settings': Settings,
  161. crypto: Crypto,
  162. '@overleaf/stream-utils': StreamUtils,
  163. './MongoManager': MongoManager,
  164. './RangeManager': RangeManager,
  165. './PersistorManager': PersistorManager,
  166. './Errors': Errors,
  167. './StreamToBuffer': streamToBuffer,
  168. },
  169. })
  170. })
  171. describe('archiveDoc', function () {
  172. it('should resolve when passed a valid document', async function () {
  173. await expect(DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)).to
  174. .eventually.be.fulfilled
  175. })
  176. it('should throw an error if the doc has no lines', async function () {
  177. const doc = mongoDocs[0]
  178. doc.lines = null
  179. await expect(
  180. DocArchiveManager.archiveDoc(projectId, doc._id)
  181. ).to.eventually.be.rejectedWith('doc has no lines')
  182. })
  183. it('should add the schema version', async function () {
  184. await DocArchiveManager.archiveDoc(projectId, mongoDocs[1]._id)
  185. expect(StreamUtils.ReadableString).to.have.been.calledWith(
  186. sinon.match(/"schema_v":1/)
  187. )
  188. })
  189. it('should calculate the hex md5 sum of the content', async function () {
  190. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  191. expect(Crypto.createHash).to.have.been.calledWith('md5')
  192. expect(HashUpdate).to.have.been.calledWith(archivedDocJson)
  193. expect(HashDigest).to.have.been.calledWith('hex')
  194. })
  195. it('should pass the md5 hash to the object persistor for verification', async function () {
  196. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  197. expect(PersistorManager.sendStream).to.have.been.calledWith(
  198. sinon.match.any,
  199. sinon.match.any,
  200. sinon.match.any,
  201. { sourceMd5: md5Sum }
  202. )
  203. })
  204. it('should pass the correct bucket and key to the persistor', async function () {
  205. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  206. expect(PersistorManager.sendStream).to.have.been.calledWith(
  207. Settings.docstore.bucket,
  208. `${projectId}/${mongoDocs[0]._id}`
  209. )
  210. })
  211. it('should create a stream from the encoded json and send it', async function () {
  212. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  213. expect(StreamUtils.ReadableString).to.have.been.calledWith(
  214. archivedDocJson
  215. )
  216. expect(PersistorManager.sendStream).to.have.been.calledWith(
  217. sinon.match.any,
  218. sinon.match.any,
  219. readStream
  220. )
  221. })
  222. it('should mark the doc as archived', async function () {
  223. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  224. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  225. projectId,
  226. mongoDocs[0]._id,
  227. mongoDocs[0].rev
  228. )
  229. })
  230. describe('when archiving is not configured', function () {
  231. beforeEach(function () {
  232. Settings.docstore.backend = undefined
  233. })
  234. it('should bail out early', async function () {
  235. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  236. expect(MongoManager.getDocForArchiving).to.not.have.been.called
  237. })
  238. })
  239. describe('with null bytes in the result', function () {
  240. const _stringify = JSON.stringify
  241. beforeEach(function () {
  242. JSON.stringify = sinon.stub().returns('{"bad": "\u0000"}')
  243. })
  244. afterEach(function () {
  245. JSON.stringify = _stringify
  246. })
  247. it('should return an error', async function () {
  248. await expect(
  249. DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  250. ).to.eventually.be.rejectedWith('null bytes detected')
  251. })
  252. })
  253. })
  254. describe('unarchiveDoc', function () {
  255. let docId, lines, rev
  256. describe('when the doc is in S3', function () {
  257. beforeEach(function () {
  258. MongoManager.findDoc = sinon.stub().resolves({ inS3: true, rev })
  259. docId = mongoDocs[0]._id
  260. lines = ['doc', 'lines']
  261. rev = 123
  262. })
  263. it('should resolve when passed a valid document', async function () {
  264. await expect(DocArchiveManager.unarchiveDoc(projectId, docId)).to
  265. .eventually.be.fulfilled
  266. })
  267. it('should test md5 validity with the raw buffer', async function () {
  268. await DocArchiveManager.unarchiveDoc(projectId, docId)
  269. expect(HashUpdate).to.have.been.calledWith(
  270. sinon.match.instanceOf(Buffer)
  271. )
  272. })
  273. it('should throw an error if the md5 does not match', async function () {
  274. PersistorManager.getObjectMd5Hash.resolves('badf00d')
  275. await expect(
  276. DocArchiveManager.unarchiveDoc(projectId, docId)
  277. ).to.eventually.be.rejected.and.be.instanceof(Errors.Md5MismatchError)
  278. })
  279. it('should restore the doc in Mongo', async function () {
  280. await DocArchiveManager.unarchiveDoc(projectId, docId)
  281. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  282. projectId,
  283. docId,
  284. archivedDoc
  285. )
  286. })
  287. describe('when archiving is not configured', function () {
  288. beforeEach(function () {
  289. Settings.docstore.backend = undefined
  290. })
  291. it('should error out on archived doc', async function () {
  292. await expect(
  293. DocArchiveManager.unarchiveDoc(projectId, docId)
  294. ).to.eventually.be.rejected.and.match(
  295. /found archived doc, but archiving backend is not configured/
  296. )
  297. })
  298. it('should return early on non-archived doc', async function () {
  299. MongoManager.findDoc = sinon.stub().resolves({ rev })
  300. await DocArchiveManager.unarchiveDoc(projectId, docId)
  301. expect(PersistorManager.getObjectMd5Hash).to.not.have.been.called
  302. })
  303. })
  304. describe('doc contents', function () {
  305. let archivedDoc
  306. describe('when the doc has the old schema', function () {
  307. beforeEach(function () {
  308. archivedDoc = lines
  309. archivedDocJson = JSON.stringify(archivedDoc)
  310. stream.on
  311. .withArgs('data')
  312. .yields(Buffer.from(archivedDocJson, 'utf8'))
  313. })
  314. it('should return the docs lines', async function () {
  315. await DocArchiveManager.unarchiveDoc(projectId, docId)
  316. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  317. projectId,
  318. docId,
  319. { lines, rev }
  320. )
  321. })
  322. })
  323. describe('with the new schema and ranges', function () {
  324. beforeEach(function () {
  325. archivedDoc = {
  326. lines,
  327. ranges: { json: 'ranges' },
  328. rev: 456,
  329. schema_v: 1,
  330. }
  331. archivedDocJson = JSON.stringify(archivedDoc)
  332. stream.on
  333. .withArgs('data')
  334. .yields(Buffer.from(archivedDocJson, 'utf8'))
  335. })
  336. it('should return the doc lines and ranges', async function () {
  337. await DocArchiveManager.unarchiveDoc(projectId, docId)
  338. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  339. projectId,
  340. docId,
  341. {
  342. lines,
  343. ranges: { mongo: 'ranges' },
  344. rev: 456,
  345. }
  346. )
  347. })
  348. })
  349. describe('with the new schema and no ranges', function () {
  350. beforeEach(function () {
  351. archivedDoc = { lines, rev: 456, schema_v: 1 }
  352. archivedDocJson = JSON.stringify(archivedDoc)
  353. stream.on
  354. .withArgs('data')
  355. .yields(Buffer.from(archivedDocJson, 'utf8'))
  356. })
  357. it('should return only the doc lines', async function () {
  358. await DocArchiveManager.unarchiveDoc(projectId, docId)
  359. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  360. projectId,
  361. docId,
  362. { lines, rev: 456 }
  363. )
  364. })
  365. })
  366. describe('with the new schema and no rev', function () {
  367. beforeEach(function () {
  368. archivedDoc = { lines, schema_v: 1 }
  369. archivedDocJson = JSON.stringify(archivedDoc)
  370. stream.on
  371. .withArgs('data')
  372. .yields(Buffer.from(archivedDocJson, 'utf8'))
  373. })
  374. it('should use the rev obtained from Mongo', async function () {
  375. await DocArchiveManager.unarchiveDoc(projectId, docId)
  376. expect(MongoManager.restoreArchivedDoc).to.have.been.calledWith(
  377. projectId,
  378. docId,
  379. { lines, rev }
  380. )
  381. })
  382. })
  383. describe('with an unrecognised schema', function () {
  384. beforeEach(function () {
  385. archivedDoc = { lines, schema_v: 2 }
  386. archivedDocJson = JSON.stringify(archivedDoc)
  387. stream.on
  388. .withArgs('data')
  389. .yields(Buffer.from(archivedDocJson, 'utf8'))
  390. })
  391. it('should throw an error', async function () {
  392. await expect(
  393. DocArchiveManager.unarchiveDoc(projectId, docId)
  394. ).to.eventually.be.rejectedWith(
  395. "I don't understand the doc format in s3"
  396. )
  397. })
  398. })
  399. })
  400. })
  401. it('should not do anything if the file is already unarchived', async function () {
  402. MongoManager.findDoc.resolves({ inS3: false })
  403. await DocArchiveManager.unarchiveDoc(projectId, docId)
  404. expect(PersistorManager.getObjectStream).not.to.have.been.called
  405. })
  406. it('should throw an error if the file is not found', async function () {
  407. PersistorManager.getObjectStream = sinon
  408. .stub()
  409. .rejects(new Errors.NotFoundError())
  410. await expect(
  411. DocArchiveManager.unarchiveDoc(projectId, docId)
  412. ).to.eventually.be.rejected.and.be.instanceof(Errors.NotFoundError)
  413. })
  414. })
  415. describe('destroyProject', function () {
  416. describe('when archiving is enabled', function () {
  417. beforeEach(async function () {
  418. await DocArchiveManager.destroyProject(projectId)
  419. })
  420. it('should delete the project in Mongo', function () {
  421. expect(MongoManager.destroyProject).to.have.been.calledWith(projectId)
  422. })
  423. it('should delete the project in the persistor', function () {
  424. expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
  425. Settings.docstore.bucket,
  426. projectId
  427. )
  428. })
  429. })
  430. describe('when archiving is disabled', function () {
  431. beforeEach(async function () {
  432. Settings.docstore.backend = ''
  433. await DocArchiveManager.destroyProject(projectId)
  434. })
  435. it('should delete the project in Mongo', function () {
  436. expect(MongoManager.destroyProject).to.have.been.calledWith(projectId)
  437. })
  438. it('should not delete the project in the persistor', function () {
  439. expect(PersistorManager.deleteDirectory).not.to.have.been.called
  440. })
  441. })
  442. })
  443. describe('archiveAllDocs', function () {
  444. it('should resolve with valid arguments', async function () {
  445. await expect(DocArchiveManager.archiveAllDocs(projectId)).to.eventually.be
  446. .fulfilled
  447. })
  448. it('should archive all project docs which are not in s3', async function () {
  449. await DocArchiveManager.archiveAllDocs(projectId)
  450. // not inS3
  451. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  452. projectId,
  453. mongoDocs[0]._id
  454. )
  455. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  456. projectId,
  457. mongoDocs[1]._id
  458. )
  459. expect(MongoManager.markDocAsArchived).to.have.been.calledWith(
  460. projectId,
  461. mongoDocs[4]._id
  462. )
  463. // inS3
  464. expect(MongoManager.markDocAsArchived).not.to.have.been.calledWith(
  465. projectId,
  466. mongoDocs[2]._id
  467. )
  468. expect(MongoManager.markDocAsArchived).not.to.have.been.calledWith(
  469. projectId,
  470. mongoDocs[3]._id
  471. )
  472. })
  473. describe('when archiving is not configured', function () {
  474. beforeEach(function () {
  475. Settings.docstore.backend = undefined
  476. })
  477. it('should bail out early', async function () {
  478. await DocArchiveManager.archiveDoc(projectId, mongoDocs[0]._id)
  479. expect(MongoManager.getNonArchivedProjectDocIds).to.not.have.been.called
  480. })
  481. })
  482. })
  483. describe('unArchiveAllDocs', function () {
  484. it('should resolve with valid arguments', async function () {
  485. await expect(DocArchiveManager.unArchiveAllDocs(projectId)).to.eventually
  486. .be.fulfilled
  487. })
  488. it('should unarchive all inS3 docs', async function () {
  489. await DocArchiveManager.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.archiveDoc(projectId, mongoDocs[0]._id)
  503. expect(MongoManager.getNonDeletedArchivedProjectDocs).to.not.have.been
  504. .called
  505. })
  506. })
  507. })
  508. })