1
0

processing_handler_test.go 22 KB

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