FileStoreController.test.mjs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import { expect, vi } from 'vitest'
  2. import sinon from 'sinon'
  3. import Errors from '../../../../app/src/Features/Errors/Errors.js'
  4. import MockResponse from '../helpers/MockResponse.mjs'
  5. const MODULE_PATH =
  6. '../../../../app/src/Features/FileStore/FileStoreController.mjs'
  7. const expectedFileHeaders = {
  8. 'Cache-Control': 'private, max-age=3600',
  9. }
  10. vi.mock('../../../../app/src/Features/Errors/Errors.js', () =>
  11. vi.importActual('../../../../app/src/Features/Errors/Errors.js')
  12. )
  13. describe('FileStoreController', function () {
  14. beforeEach(async function (ctx) {
  15. ctx.ProjectLocator = { promises: { findElement: sinon.stub() } }
  16. ctx.Stream = { pipeline: sinon.stub().resolves() }
  17. ctx.HistoryManager = {
  18. promises: { requestBlobWithProjectId: sinon.stub() },
  19. }
  20. ctx.Metrics = {
  21. inc: sinon.stub(),
  22. }
  23. vi.doMock('node:stream/promises', () => ctx.Stream)
  24. vi.doMock('@overleaf/settings', () => ({
  25. default: ctx.settings,
  26. }))
  27. vi.doMock('../../../../app/src/Features/Project/ProjectLocator', () => ({
  28. default: ctx.ProjectLocator,
  29. }))
  30. vi.doMock('../../../../app/src/Features/History/HistoryManager', () => ({
  31. default: ctx.HistoryManager,
  32. }))
  33. vi.doMock('@overleaf/metrics', () => ({ default: ctx.Metrics }))
  34. ctx.controller = (await import(MODULE_PATH)).default
  35. ctx.stream = {}
  36. ctx.projectId = '2k3j1lk3j21lk3j'
  37. ctx.fileId = '12321kklj1lk3jk12'
  38. ctx.req = {
  39. params: {
  40. Project_id: ctx.projectId,
  41. File_id: ctx.fileId,
  42. },
  43. query: 'query string here',
  44. get(key) {
  45. return undefined
  46. },
  47. logger: {
  48. addFields: sinon.stub(),
  49. },
  50. }
  51. ctx.res = new MockResponse(vi)
  52. ctx.next = sinon.stub()
  53. ctx.hash = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  54. ctx.file = { name: 'myfile.png', hash: ctx.hash }
  55. })
  56. describe('getFile', function () {
  57. beforeEach(function (ctx) {
  58. ctx.HistoryManager.promises.requestBlobWithProjectId.resolves({
  59. stream: ctx.stream,
  60. })
  61. ctx.ProjectLocator.promises.findElement.resolves({ element: ctx.file })
  62. })
  63. it('should call the history manager with the project_id hash', async function (ctx) {
  64. await ctx.controller.getFile(ctx.req, ctx.res)
  65. ctx.HistoryManager.promises.requestBlobWithProjectId.should.have.been.calledWith(
  66. ctx.req.params.Project_id,
  67. ctx.hash,
  68. 'GET'
  69. )
  70. })
  71. it('should pipe to res', async function (ctx) {
  72. await ctx.controller.getFile(ctx.req, ctx.res)
  73. ctx.Stream.pipeline.should.have.been.calledWith(ctx.stream, ctx.res)
  74. })
  75. it('should get the file from the db', async function (ctx) {
  76. await ctx.controller.getFile(ctx.req, ctx.res)
  77. ctx.ProjectLocator.promises.findElement.should.have.been.calledWith({
  78. project_id: ctx.projectId,
  79. element_id: ctx.fileId,
  80. type: 'file',
  81. })
  82. })
  83. it('should set the Content-Disposition header', async function (ctx) {
  84. await ctx.controller.getFile(ctx.req, ctx.res)
  85. expect(ctx.res.setContentDisposition).toBeCalledWith('attachment', {
  86. filename: ctx.file.name,
  87. })
  88. })
  89. it('should return a 404 when not found', async function (ctx) {
  90. ctx.ProjectLocator.promises.findElement.rejects(
  91. new Errors.NotFoundError()
  92. )
  93. await ctx.controller.getFile(ctx.req, ctx.res)
  94. expect(ctx.res.statusCode).to.equal(404)
  95. })
  96. // Test behaviour around handling html files
  97. ;['.html', '.htm', '.xhtml'].forEach(extension => {
  98. describe(`with a '${extension}' file extension`, function () {
  99. beforeEach(function (ctx) {
  100. ctx.file.name = `bad${extension}`
  101. ctx.req.get = key => {
  102. if (key === 'User-Agent') {
  103. return 'A generic browser'
  104. }
  105. }
  106. })
  107. describe('from a non-ios browser', function () {
  108. it('should not set Content-Type', async function (ctx) {
  109. await ctx.controller.getFile(ctx.req, ctx.res)
  110. ctx.res.headers.should.deep.equal({
  111. ...expectedFileHeaders,
  112. })
  113. })
  114. })
  115. describe('from an iPhone', function () {
  116. beforeEach(function (ctx) {
  117. ctx.req.get = key => {
  118. if (key === 'User-Agent') {
  119. return 'An iPhone browser'
  120. }
  121. }
  122. })
  123. it("should set Content-Type to 'text/plain'", async function (ctx) {
  124. await ctx.controller.getFile(ctx.req, ctx.res)
  125. ctx.res.headers.should.deep.equal({
  126. ...expectedFileHeaders,
  127. 'Content-Type': 'text/plain; charset=utf-8',
  128. 'X-Content-Type-Options': 'nosniff',
  129. })
  130. })
  131. })
  132. describe('from an iPad', function () {
  133. beforeEach(function (ctx) {
  134. ctx.req.get = key => {
  135. if (key === 'User-Agent') {
  136. return 'An iPad browser'
  137. }
  138. }
  139. })
  140. it("should set Content-Type to 'text/plain'", async function (ctx) {
  141. await ctx.controller.getFile(ctx.req, ctx.res)
  142. ctx.res.headers.should.deep.equal({
  143. ...expectedFileHeaders,
  144. 'Content-Type': 'text/plain; charset=utf-8',
  145. 'X-Content-Type-Options': 'nosniff',
  146. })
  147. })
  148. })
  149. })
  150. })
  151. ;[
  152. // None of these should trigger the iOS/html logic
  153. 'x.html-is-rad',
  154. 'html.pdf',
  155. '.html-is-good-for-hidden-files',
  156. 'somefile',
  157. ].forEach(filename => {
  158. describe(`with filename as '${filename}'`, function () {
  159. beforeEach(function (ctx) {
  160. ctx.user_agent = 'A generic browser'
  161. ctx.file.name = filename
  162. ctx.req.get = key => {
  163. if (key === 'User-Agent') {
  164. return ctx.user_agent
  165. }
  166. }
  167. })
  168. ;['iPhone', 'iPad', 'Firefox', 'Chrome'].forEach(browser => {
  169. describe(`downloaded from ${browser}`, function () {
  170. beforeEach(function (ctx) {
  171. ctx.user_agent = `Some ${browser} thing`
  172. })
  173. it('Should not set the Content-type', async function (ctx) {
  174. await ctx.controller.getFile(ctx.req, ctx.res)
  175. ctx.res.headers.should.deep.equal({
  176. ...expectedFileHeaders,
  177. })
  178. })
  179. })
  180. })
  181. })
  182. })
  183. })
  184. describe('getFileHead', function () {
  185. beforeEach(function (ctx) {
  186. ctx.ProjectLocator.promises.findElement.resolves({ element: ctx.file })
  187. })
  188. it('reports the file size', async function (ctx) {
  189. await new Promise(resolve => {
  190. const expectedFileSize = 99393
  191. ctx.HistoryManager.promises.requestBlobWithProjectId.rejects(
  192. new Error('getFileSize: unexpected arguments')
  193. )
  194. ctx.HistoryManager.promises.requestBlobWithProjectId
  195. .withArgs(ctx.projectId, ctx.hash)
  196. .resolves({ contentLength: expectedFileSize })
  197. ctx.res.end = () => {
  198. expect(ctx.res.status.mock.lastCall).to.deep.equal([200])
  199. expect(ctx.res.header.mock.lastCall).to.deep.equal([
  200. 'Content-Length',
  201. expectedFileSize,
  202. ])
  203. resolve()
  204. }
  205. ctx.controller.getFileHead(ctx.req, ctx.res)
  206. })
  207. })
  208. it('returns 404 on NotFoundError', async function (ctx) {
  209. await new Promise(resolve => {
  210. ctx.HistoryManager.promises.requestBlobWithProjectId.rejects(
  211. new Errors.NotFoundError()
  212. )
  213. ctx.res.end = () => {
  214. expect(ctx.res.status.mock.lastCall).to.deep.equal([404])
  215. resolve()
  216. }
  217. ctx.controller.getFileHead(ctx.req, ctx.res)
  218. })
  219. })
  220. })
  221. })