processing_handler_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/imgproxy/imgproxy/v3/config"
  15. "github.com/imgproxy/imgproxy/v3/config/configurators"
  16. "github.com/imgproxy/imgproxy/v3/etag"
  17. "github.com/imgproxy/imgproxy/v3/imagedata"
  18. "github.com/imgproxy/imgproxy/v3/imagemeta"
  19. "github.com/imgproxy/imgproxy/v3/imagetype"
  20. "github.com/imgproxy/imgproxy/v3/options"
  21. "github.com/imgproxy/imgproxy/v3/router"
  22. "github.com/imgproxy/imgproxy/v3/svg"
  23. "github.com/imgproxy/imgproxy/v3/vips"
  24. "github.com/sirupsen/logrus"
  25. "github.com/stretchr/testify/require"
  26. "github.com/stretchr/testify/suite"
  27. )
  28. type ProcessingHandlerTestSuite struct {
  29. suite.Suite
  30. router *router.Router
  31. }
  32. func (s *ProcessingHandlerTestSuite) SetupSuite() {
  33. config.Reset()
  34. wd, err := os.Getwd()
  35. require.Nil(s.T(), err)
  36. config.LocalFileSystemRoot = filepath.Join(wd, "/testdata")
  37. // Disable keep-alive to test connection restrictions
  38. config.ClientKeepAliveTimeout = 0
  39. err = initialize()
  40. require.Nil(s.T(), err)
  41. logrus.SetOutput(io.Discard)
  42. s.router = buildRouter()
  43. }
  44. func (s *ProcessingHandlerTestSuite) TeardownSuite() {
  45. shutdown()
  46. logrus.SetOutput(os.Stdout)
  47. }
  48. func (s *ProcessingHandlerTestSuite) SetupTest() {
  49. // We don't need config.LocalFileSystemRoot anymore as it is used
  50. // only during initialization
  51. config.Reset()
  52. config.AllowLoopbackSourceAddresses = true
  53. }
  54. func (s *ProcessingHandlerTestSuite) send(path string, header ...http.Header) *httptest.ResponseRecorder {
  55. req := httptest.NewRequest(http.MethodGet, path, nil)
  56. rw := httptest.NewRecorder()
  57. if len(header) > 0 {
  58. req.Header = header[0]
  59. }
  60. s.router.ServeHTTP(rw, req)
  61. return rw
  62. }
  63. func (s *ProcessingHandlerTestSuite) readTestFile(name string) []byte {
  64. wd, err := os.Getwd()
  65. require.Nil(s.T(), err)
  66. data, err := os.ReadFile(filepath.Join(wd, "testdata", name))
  67. require.Nil(s.T(), err)
  68. return data
  69. }
  70. func (s *ProcessingHandlerTestSuite) readBody(res *http.Response) []byte {
  71. data, err := io.ReadAll(res.Body)
  72. require.Nil(s.T(), err)
  73. return data
  74. }
  75. func (s *ProcessingHandlerTestSuite) sampleETagData(imgETag string) (string, *imagedata.ImageData, string) {
  76. poStr := "rs:fill:4:4"
  77. po := options.NewProcessingOptions()
  78. po.ResizingType = options.ResizeFill
  79. po.Width = 4
  80. po.Height = 4
  81. imgdata := imagedata.ImageData{
  82. Type: imagetype.PNG,
  83. Data: s.readTestFile("test1.png"),
  84. }
  85. if len(imgETag) != 0 {
  86. imgdata.Headers = map[string]string{"ETag": imgETag}
  87. }
  88. var h etag.Handler
  89. h.SetActualProcessingOptions(po)
  90. h.SetActualImageData(&imgdata)
  91. return poStr, &imgdata, h.GenerateActualETag()
  92. }
  93. func (s *ProcessingHandlerTestSuite) TestRequest() {
  94. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  95. res := rw.Result()
  96. require.Equal(s.T(), 200, res.StatusCode)
  97. require.Equal(s.T(), "image/png", res.Header.Get("Content-Type"))
  98. meta, err := imagemeta.DecodeMeta(res.Body)
  99. require.Nil(s.T(), err)
  100. require.Equal(s.T(), imagetype.PNG, meta.Format())
  101. require.Equal(s.T(), 4, meta.Width())
  102. require.Equal(s.T(), 4, meta.Height())
  103. }
  104. func (s *ProcessingHandlerTestSuite) TestSignatureValidationFailure() {
  105. config.Keys = [][]byte{[]byte("test-key")}
  106. config.Salts = [][]byte{[]byte("test-salt")}
  107. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  108. res := rw.Result()
  109. require.Equal(s.T(), 403, res.StatusCode)
  110. }
  111. func (s *ProcessingHandlerTestSuite) TestSignatureValidationSuccess() {
  112. config.Keys = [][]byte{[]byte("test-key")}
  113. config.Salts = [][]byte{[]byte("test-salt")}
  114. rw := s.send("/My9d3xq_PYpVHsPrCyww0Kh1w5KZeZhIlWhsa4az1TI/rs:fill:4:4/plain/local:///test1.png")
  115. res := rw.Result()
  116. require.Equal(s.T(), 200, res.StatusCode)
  117. }
  118. func (s *ProcessingHandlerTestSuite) TestSourceValidation() {
  119. imagedata.RedirectAllRequestsTo("local:///test1.png")
  120. defer imagedata.StopRedirectingRequests()
  121. tt := []struct {
  122. name string
  123. allowedSources []string
  124. requestPath string
  125. expectedError bool
  126. }{
  127. {
  128. name: "match http URL without wildcard",
  129. allowedSources: []string{"local://", "http://images.dev/"},
  130. requestPath: "/unsafe/plain/http://images.dev/lorem/ipsum.jpg",
  131. expectedError: false,
  132. },
  133. {
  134. name: "match http URL with wildcard in hostname single level",
  135. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  136. requestPath: "/unsafe/plain/http://a-1.mycdn.dev/lorem/ipsum.jpg",
  137. expectedError: false,
  138. },
  139. {
  140. name: "match http URL with wildcard in hostname multiple levels",
  141. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  142. requestPath: "/unsafe/plain/http://a-1.b-2.mycdn.dev/lorem/ipsum.jpg",
  143. expectedError: false,
  144. },
  145. {
  146. name: "no match s3 URL with allowed local and http URLs",
  147. allowedSources: []string{"local://", "http://images.dev/"},
  148. requestPath: "/unsafe/plain/s3://images/lorem/ipsum.jpg",
  149. expectedError: true,
  150. },
  151. {
  152. name: "no match http URL with wildcard in hostname including slash",
  153. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  154. requestPath: "/unsafe/plain/http://other.dev/.mycdn.dev/lorem/ipsum.jpg",
  155. expectedError: true,
  156. },
  157. }
  158. for _, tc := range tt {
  159. s.T().Run(tc.name, func(t *testing.T) {
  160. exps := make([]*regexp.Regexp, len(tc.allowedSources))
  161. for i, pattern := range tc.allowedSources {
  162. exps[i] = configurators.RegexpFromPattern(pattern)
  163. }
  164. config.AllowedSources = exps
  165. rw := s.send(tc.requestPath)
  166. res := rw.Result()
  167. if tc.expectedError {
  168. require.Equal(s.T(), 404, res.StatusCode)
  169. } else {
  170. require.Equal(s.T(), 200, res.StatusCode)
  171. }
  172. })
  173. }
  174. }
  175. func (s *ProcessingHandlerTestSuite) TestSourceNetworkValidation() {
  176. data := s.readTestFile("test1.png")
  177. server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  178. rw.WriteHeader(200)
  179. rw.Write(data)
  180. }))
  181. defer server.Close()
  182. var rw *httptest.ResponseRecorder
  183. u := fmt.Sprintf("/unsafe/rs:fill:4:4/plain/%s/test1.png", server.URL)
  184. fmt.Println(u)
  185. rw = s.send(u)
  186. require.Equal(s.T(), 200, rw.Result().StatusCode)
  187. config.AllowLoopbackSourceAddresses = false
  188. rw = s.send(u)
  189. require.Equal(s.T(), 404, rw.Result().StatusCode)
  190. }
  191. func (s *ProcessingHandlerTestSuite) TestSourceFormatNotSupported() {
  192. vips.DisableLoadSupport(imagetype.PNG)
  193. defer vips.ResetLoadSupport()
  194. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  195. res := rw.Result()
  196. require.Equal(s.T(), 422, res.StatusCode)
  197. }
  198. func (s *ProcessingHandlerTestSuite) TestResultingFormatNotSupported() {
  199. vips.DisableSaveSupport(imagetype.PNG)
  200. defer vips.ResetSaveSupport()
  201. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@png")
  202. res := rw.Result()
  203. require.Equal(s.T(), 422, res.StatusCode)
  204. }
  205. func (s *ProcessingHandlerTestSuite) TestSkipProcessingConfig() {
  206. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  207. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  208. res := rw.Result()
  209. require.Equal(s.T(), 200, res.StatusCode)
  210. actual := s.readBody(res)
  211. expected := s.readTestFile("test1.png")
  212. require.True(s.T(), bytes.Equal(expected, actual))
  213. }
  214. func (s *ProcessingHandlerTestSuite) TestSkipProcessingPO() {
  215. rw := s.send("/unsafe/rs:fill:4:4/skp:png/plain/local:///test1.png")
  216. res := rw.Result()
  217. require.Equal(s.T(), 200, res.StatusCode)
  218. actual := s.readBody(res)
  219. expected := s.readTestFile("test1.png")
  220. require.True(s.T(), bytes.Equal(expected, actual))
  221. }
  222. func (s *ProcessingHandlerTestSuite) TestSkipProcessingSameFormat() {
  223. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  224. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@png")
  225. res := rw.Result()
  226. require.Equal(s.T(), 200, res.StatusCode)
  227. actual := s.readBody(res)
  228. expected := s.readTestFile("test1.png")
  229. require.True(s.T(), bytes.Equal(expected, actual))
  230. }
  231. func (s *ProcessingHandlerTestSuite) TestSkipProcessingDifferentFormat() {
  232. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  233. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@jpg")
  234. res := rw.Result()
  235. require.Equal(s.T(), 200, res.StatusCode)
  236. actual := s.readBody(res)
  237. expected := s.readTestFile("test1.png")
  238. require.False(s.T(), bytes.Equal(expected, actual))
  239. }
  240. func (s *ProcessingHandlerTestSuite) TestSkipProcessingSVG() {
  241. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.svg")
  242. res := rw.Result()
  243. require.Equal(s.T(), 200, res.StatusCode)
  244. actual := s.readBody(res)
  245. expected, err := svg.Sanitize(&imagedata.ImageData{Data: s.readTestFile("test1.svg")})
  246. require.Nil(s.T(), err)
  247. require.True(s.T(), bytes.Equal(expected.Data, actual))
  248. }
  249. func (s *ProcessingHandlerTestSuite) TestNotSkipProcessingSVGToJPG() {
  250. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.svg@jpg")
  251. res := rw.Result()
  252. require.Equal(s.T(), 200, res.StatusCode)
  253. actual := s.readBody(res)
  254. expected := s.readTestFile("test1.svg")
  255. require.False(s.T(), bytes.Equal(expected, actual))
  256. }
  257. func (s *ProcessingHandlerTestSuite) TestErrorSavingToSVG() {
  258. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@svg")
  259. res := rw.Result()
  260. require.Equal(s.T(), 422, res.StatusCode)
  261. }
  262. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthrough() {
  263. config.CacheControlPassthrough = true
  264. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  265. rw.Header().Set("Cache-Control", "fake-cache-control")
  266. rw.Header().Set("Expires", "fake-expires")
  267. rw.WriteHeader(200)
  268. rw.Write(s.readTestFile("test1.png"))
  269. }))
  270. defer ts.Close()
  271. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  272. res := rw.Result()
  273. require.Equal(s.T(), "fake-cache-control", res.Header.Get("Cache-Control"))
  274. require.Equal(s.T(), "fake-expires", res.Header.Get("Expires"))
  275. }
  276. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthroughDisabled() {
  277. config.CacheControlPassthrough = false
  278. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  279. rw.Header().Set("Cache-Control", "fake-cache-control")
  280. rw.Header().Set("Expires", "fake-expires")
  281. rw.WriteHeader(200)
  282. rw.Write(s.readTestFile("test1.png"))
  283. }))
  284. defer ts.Close()
  285. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  286. res := rw.Result()
  287. require.NotEqual(s.T(), "fake-cache-control", res.Header.Get("Cache-Control"))
  288. require.NotEqual(s.T(), "fake-expires", res.Header.Get("Expires"))
  289. }
  290. func (s *ProcessingHandlerTestSuite) TestETagDisabled() {
  291. config.ETagEnabled = false
  292. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  293. res := rw.Result()
  294. require.Equal(s.T(), 200, res.StatusCode)
  295. require.Empty(s.T(), res.Header.Get("ETag"))
  296. }
  297. func (s *ProcessingHandlerTestSuite) TestETagReqNoIfNotModified() {
  298. config.ETagEnabled = true
  299. poStr, imgdata, etag := s.sampleETagData("loremipsumdolor")
  300. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  301. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  302. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  303. rw.WriteHeader(200)
  304. rw.Write(s.readTestFile("test1.png"))
  305. }))
  306. defer ts.Close()
  307. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL))
  308. res := rw.Result()
  309. require.Equal(s.T(), 200, res.StatusCode)
  310. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  311. }
  312. func (s *ProcessingHandlerTestSuite) TestETagDataNoIfNotModified() {
  313. config.ETagEnabled = true
  314. poStr, imgdata, etag := s.sampleETagData("")
  315. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  316. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  317. rw.WriteHeader(200)
  318. rw.Write(imgdata.Data)
  319. }))
  320. defer ts.Close()
  321. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL))
  322. res := rw.Result()
  323. require.Equal(s.T(), 200, res.StatusCode)
  324. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  325. }
  326. func (s *ProcessingHandlerTestSuite) TestETagReqMatch() {
  327. config.ETagEnabled = true
  328. poStr, imgdata, etag := s.sampleETagData(`"loremipsumdolor"`)
  329. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  330. require.Equal(s.T(), imgdata.Headers["ETag"], r.Header.Get("If-None-Match"))
  331. rw.WriteHeader(304)
  332. }))
  333. defer ts.Close()
  334. header := make(http.Header)
  335. header.Set("If-None-Match", etag)
  336. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  337. res := rw.Result()
  338. require.Equal(s.T(), 304, res.StatusCode)
  339. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  340. }
  341. func (s *ProcessingHandlerTestSuite) TestETagDataMatch() {
  342. config.ETagEnabled = true
  343. poStr, imgdata, etag := s.sampleETagData("")
  344. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  345. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  346. rw.WriteHeader(200)
  347. rw.Write(imgdata.Data)
  348. }))
  349. defer ts.Close()
  350. header := make(http.Header)
  351. header.Set("If-None-Match", etag)
  352. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  353. res := rw.Result()
  354. require.Equal(s.T(), 304, res.StatusCode)
  355. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  356. }
  357. func (s *ProcessingHandlerTestSuite) TestETagReqNotMatch() {
  358. config.ETagEnabled = true
  359. poStr, imgdata, actualETag := s.sampleETagData(`"loremipsumdolor"`)
  360. _, _, expectedETag := s.sampleETagData(`"loremipsum"`)
  361. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  362. require.Equal(s.T(), `"loremipsum"`, r.Header.Get("If-None-Match"))
  363. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  364. rw.WriteHeader(200)
  365. rw.Write(imgdata.Data)
  366. }))
  367. defer ts.Close()
  368. header := make(http.Header)
  369. header.Set("If-None-Match", expectedETag)
  370. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  371. res := rw.Result()
  372. require.Equal(s.T(), 200, res.StatusCode)
  373. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  374. }
  375. func (s *ProcessingHandlerTestSuite) TestETagDataNotMatch() {
  376. config.ETagEnabled = true
  377. poStr, imgdata, actualETag := s.sampleETagData("")
  378. // Change the data hash
  379. expectedETag := actualETag[:strings.IndexByte(actualETag, '/')] + "/Dasdbefj"
  380. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  381. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  382. rw.WriteHeader(200)
  383. rw.Write(imgdata.Data)
  384. }))
  385. defer ts.Close()
  386. header := make(http.Header)
  387. header.Set("If-None-Match", expectedETag)
  388. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  389. res := rw.Result()
  390. require.Equal(s.T(), 200, res.StatusCode)
  391. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  392. }
  393. func (s *ProcessingHandlerTestSuite) TestETagProcessingOptionsNotMatch() {
  394. config.ETagEnabled = true
  395. poStr, imgdata, actualETag := s.sampleETagData("")
  396. // Change the processing options hash
  397. expectedETag := "abcdefj" + actualETag[strings.IndexByte(actualETag, '/'):]
  398. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  399. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  400. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  401. rw.WriteHeader(200)
  402. rw.Write(imgdata.Data)
  403. }))
  404. defer ts.Close()
  405. header := make(http.Header)
  406. header.Set("If-None-Match", expectedETag)
  407. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  408. res := rw.Result()
  409. require.Equal(s.T(), 200, res.StatusCode)
  410. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  411. }
  412. func (s *ProcessingHandlerTestSuite) TestLastModifiedEnabled() {
  413. config.LastModifiedEnabled = true
  414. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  415. rw.Header().Set("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT")
  416. rw.WriteHeader(200)
  417. rw.Write(s.readTestFile("test1.png"))
  418. }))
  419. defer ts.Close()
  420. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  421. res := rw.Result()
  422. require.Equal(s.T(), "Wed, 21 Oct 2015 07:28:00 GMT", res.Header.Get("Last-Modified"))
  423. }
  424. func (s *ProcessingHandlerTestSuite) TestLastModifiedDisabled() {
  425. config.LastModifiedEnabled = false
  426. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  427. rw.Header().Set("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT")
  428. rw.WriteHeader(200)
  429. rw.Write(s.readTestFile("test1.png"))
  430. }))
  431. defer ts.Close()
  432. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  433. res := rw.Result()
  434. require.Equal(s.T(), "", res.Header.Get("Last-Modified"))
  435. }
  436. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqExactMatchLastModifiedDisabled() {
  437. config.LastModifiedEnabled = false
  438. data := s.readTestFile("test1.png")
  439. lastModified := "Wed, 21 Oct 2015 07:28:00 GMT"
  440. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  441. modifiedSince := r.Header.Get("If-Modified-Since")
  442. require.Equal(s.T(), "", modifiedSince)
  443. rw.WriteHeader(200)
  444. rw.Write(data)
  445. }))
  446. defer ts.Close()
  447. header := make(http.Header)
  448. header.Set("If-Modified-Since", lastModified)
  449. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  450. res := rw.Result()
  451. require.Equal(s.T(), 200, res.StatusCode)
  452. }
  453. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqExactMatchLastModifiedEnabled() {
  454. config.LastModifiedEnabled = true
  455. lastModified := "Wed, 21 Oct 2015 07:28:00 GMT"
  456. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  457. modifiedSince := r.Header.Get("If-Modified-Since")
  458. require.Equal(s.T(), lastModified, modifiedSince)
  459. rw.WriteHeader(304)
  460. }))
  461. defer ts.Close()
  462. header := make(http.Header)
  463. header.Set("If-Modified-Since", lastModified)
  464. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  465. res := rw.Result()
  466. require.Equal(s.T(), 304, res.StatusCode)
  467. }
  468. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareMoreRecentLastModifiedDisabled() {
  469. data := s.readTestFile("test1.png")
  470. config.LastModifiedEnabled = false
  471. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  472. modifiedSince := r.Header.Get("If-Modified-Since")
  473. require.Equal(s.T(), modifiedSince, "")
  474. rw.WriteHeader(200)
  475. rw.Write(data)
  476. }))
  477. defer ts.Close()
  478. recentTimestamp := "Thu, 25 Feb 2021 01:45:00 GMT"
  479. header := make(http.Header)
  480. header.Set("If-Modified-Since", recentTimestamp)
  481. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  482. res := rw.Result()
  483. require.Equal(s.T(), 200, res.StatusCode)
  484. }
  485. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareMoreRecentLastModifiedEnabled() {
  486. config.LastModifiedEnabled = true
  487. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  488. fileLastModified, _ := time.Parse(http.TimeFormat, "Wed, 21 Oct 2015 07:28:00 GMT")
  489. modifiedSince := r.Header.Get("If-Modified-Since")
  490. parsedModifiedSince, err := time.Parse(http.TimeFormat, modifiedSince)
  491. require.Nil(s.T(), err)
  492. require.True(s.T(), fileLastModified.Before(parsedModifiedSince))
  493. rw.WriteHeader(304)
  494. }))
  495. defer ts.Close()
  496. recentTimestamp := "Thu, 25 Feb 2021 01:45:00 GMT"
  497. header := make(http.Header)
  498. header.Set("If-Modified-Since", recentTimestamp)
  499. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  500. res := rw.Result()
  501. require.Equal(s.T(), 304, res.StatusCode)
  502. }
  503. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareTooOldLastModifiedDisabled() {
  504. config.LastModifiedEnabled = false
  505. data := s.readTestFile("test1.png")
  506. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  507. modifiedSince := r.Header.Get("If-Modified-Since")
  508. require.Equal(s.T(), modifiedSince, "")
  509. rw.WriteHeader(200)
  510. rw.Write(data)
  511. }))
  512. defer ts.Close()
  513. oldTimestamp := "Tue, 01 Oct 2013 17:31:00 GMT"
  514. header := make(http.Header)
  515. header.Set("If-Modified-Since", oldTimestamp)
  516. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  517. res := rw.Result()
  518. require.Equal(s.T(), 200, res.StatusCode)
  519. }
  520. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareTooOldLastModifiedEnabled() {
  521. config.LastModifiedEnabled = true
  522. data := s.readTestFile("test1.png")
  523. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  524. fileLastModified, _ := time.Parse(http.TimeFormat, "Wed, 21 Oct 2015 07:28:00 GMT")
  525. modifiedSince := r.Header.Get("If-Modified-Since")
  526. parsedModifiedSince, err := time.Parse(http.TimeFormat, modifiedSince)
  527. require.Nil(s.T(), err)
  528. require.True(s.T(), fileLastModified.After(parsedModifiedSince))
  529. rw.WriteHeader(200)
  530. rw.Write(data)
  531. }))
  532. defer ts.Close()
  533. oldTimestamp := "Tue, 01 Oct 2013 17:31:00 GMT"
  534. header := make(http.Header)
  535. header.Set("If-Modified-Since", oldTimestamp)
  536. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  537. res := rw.Result()
  538. require.Equal(s.T(), 200, res.StatusCode)
  539. }
  540. func TestProcessingHandler(t *testing.T) {
  541. suite.Run(t, new(ProcessingHandlerTestSuite))
  542. }