processing_handler_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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) TestCacheControlPassthroughCacheControl() {
  263. config.CacheControlPassthrough = true
  264. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  265. rw.Header().Set("Cache-Control", "max-age=1234, public")
  266. rw.Header().Set("Expires", time.Now().Add(time.Hour).UTC().Format(http.TimeFormat))
  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(), "max-age=1234, public", res.Header.Get("Cache-Control"))
  274. require.Empty(s.T(), res.Header.Get("Expires"))
  275. }
  276. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthroughExpires() {
  277. config.CacheControlPassthrough = true
  278. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  279. rw.Header().Set("Expires", time.Now().Add(1239*time.Second).UTC().Format(http.TimeFormat))
  280. rw.WriteHeader(200)
  281. rw.Write(s.readTestFile("test1.png"))
  282. }))
  283. defer ts.Close()
  284. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  285. res := rw.Result()
  286. // Use regex to allow some delay
  287. require.Regexp(s.T(), regexp.MustCompile("max-age=123[0-9], public"), res.Header.Get("Cache-Control"))
  288. require.Empty(s.T(), res.Header.Get("Expires"))
  289. }
  290. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthroughDisabled() {
  291. config.CacheControlPassthrough = false
  292. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  293. rw.Header().Set("Cache-Control", "max-age=1234, public")
  294. rw.Header().Set("Expires", time.Now().Add(time.Hour).UTC().Format(http.TimeFormat))
  295. rw.WriteHeader(200)
  296. rw.Write(s.readTestFile("test1.png"))
  297. }))
  298. defer ts.Close()
  299. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  300. res := rw.Result()
  301. require.NotEqual(s.T(), "max-age=1234, public", res.Header.Get("Cache-Control"))
  302. require.Empty(s.T(), res.Header.Get("Expires"))
  303. }
  304. func (s *ProcessingHandlerTestSuite) TestETagDisabled() {
  305. config.ETagEnabled = false
  306. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  307. res := rw.Result()
  308. require.Equal(s.T(), 200, res.StatusCode)
  309. require.Empty(s.T(), res.Header.Get("ETag"))
  310. }
  311. func (s *ProcessingHandlerTestSuite) TestETagReqNoIfNotModified() {
  312. config.ETagEnabled = true
  313. poStr, imgdata, etag := s.sampleETagData("loremipsumdolor")
  314. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  315. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  316. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  317. rw.WriteHeader(200)
  318. rw.Write(s.readTestFile("test1.png"))
  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) TestETagDataNoIfNotModified() {
  327. config.ETagEnabled = true
  328. poStr, imgdata, etag := s.sampleETagData("")
  329. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  330. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  331. rw.WriteHeader(200)
  332. rw.Write(imgdata.Data)
  333. }))
  334. defer ts.Close()
  335. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL))
  336. res := rw.Result()
  337. require.Equal(s.T(), 200, res.StatusCode)
  338. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  339. }
  340. func (s *ProcessingHandlerTestSuite) TestETagReqMatch() {
  341. config.ETagEnabled = true
  342. poStr, imgdata, etag := s.sampleETagData(`"loremipsumdolor"`)
  343. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  344. require.Equal(s.T(), imgdata.Headers["ETag"], r.Header.Get("If-None-Match"))
  345. rw.WriteHeader(304)
  346. }))
  347. defer ts.Close()
  348. header := make(http.Header)
  349. header.Set("If-None-Match", etag)
  350. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  351. res := rw.Result()
  352. require.Equal(s.T(), 304, res.StatusCode)
  353. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  354. }
  355. func (s *ProcessingHandlerTestSuite) TestETagDataMatch() {
  356. config.ETagEnabled = true
  357. poStr, imgdata, etag := s.sampleETagData("")
  358. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  359. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  360. rw.WriteHeader(200)
  361. rw.Write(imgdata.Data)
  362. }))
  363. defer ts.Close()
  364. header := make(http.Header)
  365. header.Set("If-None-Match", etag)
  366. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  367. res := rw.Result()
  368. require.Equal(s.T(), 304, res.StatusCode)
  369. require.Equal(s.T(), etag, res.Header.Get("ETag"))
  370. }
  371. func (s *ProcessingHandlerTestSuite) TestETagReqNotMatch() {
  372. config.ETagEnabled = true
  373. poStr, imgdata, actualETag := s.sampleETagData(`"loremipsumdolor"`)
  374. _, _, expectedETag := s.sampleETagData(`"loremipsum"`)
  375. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  376. require.Equal(s.T(), `"loremipsum"`, r.Header.Get("If-None-Match"))
  377. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  378. rw.WriteHeader(200)
  379. rw.Write(imgdata.Data)
  380. }))
  381. defer ts.Close()
  382. header := make(http.Header)
  383. header.Set("If-None-Match", expectedETag)
  384. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  385. res := rw.Result()
  386. require.Equal(s.T(), 200, res.StatusCode)
  387. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  388. }
  389. func (s *ProcessingHandlerTestSuite) TestETagDataNotMatch() {
  390. config.ETagEnabled = true
  391. poStr, imgdata, actualETag := s.sampleETagData("")
  392. // Change the data hash
  393. expectedETag := actualETag[:strings.IndexByte(actualETag, '/')] + "/Dasdbefj"
  394. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  395. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  396. rw.WriteHeader(200)
  397. rw.Write(imgdata.Data)
  398. }))
  399. defer ts.Close()
  400. header := make(http.Header)
  401. header.Set("If-None-Match", expectedETag)
  402. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  403. res := rw.Result()
  404. require.Equal(s.T(), 200, res.StatusCode)
  405. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  406. }
  407. func (s *ProcessingHandlerTestSuite) TestETagProcessingOptionsNotMatch() {
  408. config.ETagEnabled = true
  409. poStr, imgdata, actualETag := s.sampleETagData("")
  410. // Change the processing options hash
  411. expectedETag := "abcdefj" + actualETag[strings.IndexByte(actualETag, '/'):]
  412. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  413. require.Empty(s.T(), r.Header.Get("If-None-Match"))
  414. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  415. rw.WriteHeader(200)
  416. rw.Write(imgdata.Data)
  417. }))
  418. defer ts.Close()
  419. header := make(http.Header)
  420. header.Set("If-None-Match", expectedETag)
  421. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  422. res := rw.Result()
  423. require.Equal(s.T(), 200, res.StatusCode)
  424. require.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  425. }
  426. func (s *ProcessingHandlerTestSuite) TestLastModifiedEnabled() {
  427. config.LastModifiedEnabled = true
  428. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  429. rw.Header().Set("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT")
  430. rw.WriteHeader(200)
  431. rw.Write(s.readTestFile("test1.png"))
  432. }))
  433. defer ts.Close()
  434. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  435. res := rw.Result()
  436. require.Equal(s.T(), "Wed, 21 Oct 2015 07:28:00 GMT", res.Header.Get("Last-Modified"))
  437. }
  438. func (s *ProcessingHandlerTestSuite) TestLastModifiedDisabled() {
  439. config.LastModifiedEnabled = false
  440. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  441. rw.Header().Set("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT")
  442. rw.WriteHeader(200)
  443. rw.Write(s.readTestFile("test1.png"))
  444. }))
  445. defer ts.Close()
  446. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  447. res := rw.Result()
  448. require.Equal(s.T(), "", res.Header.Get("Last-Modified"))
  449. }
  450. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqExactMatchLastModifiedDisabled() {
  451. config.LastModifiedEnabled = false
  452. data := s.readTestFile("test1.png")
  453. lastModified := "Wed, 21 Oct 2015 07:28:00 GMT"
  454. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  455. modifiedSince := r.Header.Get("If-Modified-Since")
  456. require.Equal(s.T(), "", modifiedSince)
  457. rw.WriteHeader(200)
  458. rw.Write(data)
  459. }))
  460. defer ts.Close()
  461. header := make(http.Header)
  462. header.Set("If-Modified-Since", lastModified)
  463. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  464. res := rw.Result()
  465. require.Equal(s.T(), 200, res.StatusCode)
  466. }
  467. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqExactMatchLastModifiedEnabled() {
  468. config.LastModifiedEnabled = true
  469. lastModified := "Wed, 21 Oct 2015 07:28:00 GMT"
  470. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  471. modifiedSince := r.Header.Get("If-Modified-Since")
  472. require.Equal(s.T(), lastModified, modifiedSince)
  473. rw.WriteHeader(304)
  474. }))
  475. defer ts.Close()
  476. header := make(http.Header)
  477. header.Set("If-Modified-Since", lastModified)
  478. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  479. res := rw.Result()
  480. require.Equal(s.T(), 304, res.StatusCode)
  481. }
  482. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareMoreRecentLastModifiedDisabled() {
  483. data := s.readTestFile("test1.png")
  484. config.LastModifiedEnabled = false
  485. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  486. modifiedSince := r.Header.Get("If-Modified-Since")
  487. require.Equal(s.T(), modifiedSince, "")
  488. rw.WriteHeader(200)
  489. rw.Write(data)
  490. }))
  491. defer ts.Close()
  492. recentTimestamp := "Thu, 25 Feb 2021 01:45:00 GMT"
  493. header := make(http.Header)
  494. header.Set("If-Modified-Since", recentTimestamp)
  495. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  496. res := rw.Result()
  497. require.Equal(s.T(), 200, res.StatusCode)
  498. }
  499. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareMoreRecentLastModifiedEnabled() {
  500. config.LastModifiedEnabled = true
  501. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  502. fileLastModified, _ := time.Parse(http.TimeFormat, "Wed, 21 Oct 2015 07:28:00 GMT")
  503. modifiedSince := r.Header.Get("If-Modified-Since")
  504. parsedModifiedSince, err := time.Parse(http.TimeFormat, modifiedSince)
  505. require.Nil(s.T(), err)
  506. require.True(s.T(), fileLastModified.Before(parsedModifiedSince))
  507. rw.WriteHeader(304)
  508. }))
  509. defer ts.Close()
  510. recentTimestamp := "Thu, 25 Feb 2021 01:45:00 GMT"
  511. header := make(http.Header)
  512. header.Set("If-Modified-Since", recentTimestamp)
  513. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  514. res := rw.Result()
  515. require.Equal(s.T(), 304, res.StatusCode)
  516. }
  517. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareTooOldLastModifiedDisabled() {
  518. config.LastModifiedEnabled = false
  519. data := s.readTestFile("test1.png")
  520. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  521. modifiedSince := r.Header.Get("If-Modified-Since")
  522. require.Equal(s.T(), modifiedSince, "")
  523. rw.WriteHeader(200)
  524. rw.Write(data)
  525. }))
  526. defer ts.Close()
  527. oldTimestamp := "Tue, 01 Oct 2013 17:31:00 GMT"
  528. header := make(http.Header)
  529. header.Set("If-Modified-Since", oldTimestamp)
  530. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  531. res := rw.Result()
  532. require.Equal(s.T(), 200, res.StatusCode)
  533. }
  534. func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareTooOldLastModifiedEnabled() {
  535. config.LastModifiedEnabled = true
  536. data := s.readTestFile("test1.png")
  537. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  538. fileLastModified, _ := time.Parse(http.TimeFormat, "Wed, 21 Oct 2015 07:28:00 GMT")
  539. modifiedSince := r.Header.Get("If-Modified-Since")
  540. parsedModifiedSince, err := time.Parse(http.TimeFormat, modifiedSince)
  541. require.Nil(s.T(), err)
  542. require.True(s.T(), fileLastModified.After(parsedModifiedSince))
  543. rw.WriteHeader(200)
  544. rw.Write(data)
  545. }))
  546. defer ts.Close()
  547. oldTimestamp := "Tue, 01 Oct 2013 17:31:00 GMT"
  548. header := make(http.Header)
  549. header.Set("If-Modified-Since", oldTimestamp)
  550. rw := s.send(fmt.Sprintf("/unsafe/plain/%s", ts.URL), header)
  551. res := rw.Result()
  552. require.Equal(s.T(), 200, res.StatusCode)
  553. }
  554. func TestProcessingHandler(t *testing.T) {
  555. suite.Run(t, new(ProcessingHandlerTestSuite))
  556. }