processing_handler_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/http/httptest"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "testing"
  13. "github.com/imgproxy/imgproxy/v3/config"
  14. "github.com/imgproxy/imgproxy/v3/config/configurators"
  15. "github.com/imgproxy/imgproxy/v3/etag"
  16. "github.com/imgproxy/imgproxy/v3/imagedata"
  17. "github.com/imgproxy/imgproxy/v3/imagemeta"
  18. "github.com/imgproxy/imgproxy/v3/imagetype"
  19. "github.com/imgproxy/imgproxy/v3/options"
  20. "github.com/imgproxy/imgproxy/v3/router"
  21. "github.com/imgproxy/imgproxy/v3/vips"
  22. "github.com/sirupsen/logrus"
  23. "github.com/stretchr/testify/assert"
  24. "github.com/stretchr/testify/suite"
  25. )
  26. type ProcessingHandlerTestSuite struct {
  27. suite.Suite
  28. router *router.Router
  29. }
  30. func (s *ProcessingHandlerTestSuite) SetupSuite() {
  31. config.Reset()
  32. wd, err := os.Getwd()
  33. assert.Nil(s.T(), err)
  34. config.LocalFileSystemRoot = filepath.Join(wd, "/testdata")
  35. logrus.SetOutput(ioutil.Discard)
  36. initialize()
  37. s.router = buildRouter()
  38. }
  39. func (s *ProcessingHandlerTestSuite) TeardownSuite() {
  40. shutdown()
  41. logrus.SetOutput(os.Stdout)
  42. }
  43. func (s *ProcessingHandlerTestSuite) SetupTest() {
  44. // We don't need config.LocalFileSystemRoot anymore as it is used
  45. // only during initialization
  46. config.Reset()
  47. }
  48. func (s *ProcessingHandlerTestSuite) send(path string, header ...http.Header) *httptest.ResponseRecorder {
  49. req := httptest.NewRequest(http.MethodGet, path, nil)
  50. rw := httptest.NewRecorder()
  51. if len(header) > 0 {
  52. req.Header = header[0]
  53. }
  54. s.router.ServeHTTP(rw, req)
  55. return rw
  56. }
  57. func (s *ProcessingHandlerTestSuite) readTestFile(name string) []byte {
  58. wd, err := os.Getwd()
  59. assert.Nil(s.T(), err)
  60. data, err := ioutil.ReadFile(filepath.Join(wd, "testdata", name))
  61. assert.Nil(s.T(), err)
  62. return data
  63. }
  64. func (s *ProcessingHandlerTestSuite) readBody(res *http.Response) []byte {
  65. data, err := ioutil.ReadAll(res.Body)
  66. assert.Nil(s.T(), err)
  67. return data
  68. }
  69. func (s *ProcessingHandlerTestSuite) sampleETagData(imgETag string) (string, *imagedata.ImageData, string) {
  70. poStr := "rs:fill:4:4"
  71. po := options.NewProcessingOptions()
  72. po.ResizingType = options.ResizeFill
  73. po.Width = 4
  74. po.Height = 4
  75. imgdata := imagedata.ImageData{
  76. Type: imagetype.PNG,
  77. Data: s.readTestFile("test1.png"),
  78. }
  79. if len(imgETag) != 0 {
  80. imgdata.Headers = map[string]string{"ETag": imgETag}
  81. }
  82. var h etag.Handler
  83. h.SetActualProcessingOptions(po)
  84. h.SetActualImageData(&imgdata)
  85. return poStr, &imgdata, h.GenerateActualETag()
  86. }
  87. func (s *ProcessingHandlerTestSuite) TestRequest() {
  88. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  89. res := rw.Result()
  90. assert.Equal(s.T(), 200, res.StatusCode)
  91. assert.Equal(s.T(), "image/png", res.Header.Get("Content-Type"))
  92. meta, err := imagemeta.DecodeMeta(res.Body)
  93. assert.Nil(s.T(), err)
  94. assert.Equal(s.T(), imagetype.PNG, meta.Format())
  95. assert.Equal(s.T(), 4, meta.Width())
  96. assert.Equal(s.T(), 4, meta.Height())
  97. }
  98. func (s *ProcessingHandlerTestSuite) TestSignatureValidationFailure() {
  99. config.Keys = [][]byte{[]byte("test-key")}
  100. config.Salts = [][]byte{[]byte("test-salt")}
  101. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  102. res := rw.Result()
  103. assert.Equal(s.T(), 403, res.StatusCode)
  104. }
  105. func (s *ProcessingHandlerTestSuite) TestSignatureValidationSuccess() {
  106. config.Keys = [][]byte{[]byte("test-key")}
  107. config.Salts = [][]byte{[]byte("test-salt")}
  108. rw := s.send("/My9d3xq_PYpVHsPrCyww0Kh1w5KZeZhIlWhsa4az1TI/rs:fill:4:4/plain/local:///test1.png")
  109. res := rw.Result()
  110. assert.Equal(s.T(), 200, res.StatusCode)
  111. }
  112. func (s *ProcessingHandlerTestSuite) TestSourceValidation() {
  113. imagedata.RedirectAllRequestsTo("local:///test1.png")
  114. defer imagedata.StopRedirectingRequests()
  115. tt := []struct {
  116. name string
  117. allowedSources []string
  118. requestPath string
  119. expectedError bool
  120. }{
  121. {
  122. name: "match http URL without wildcard",
  123. allowedSources: []string{"local://", "http://images.dev/"},
  124. requestPath: "/unsafe/plain/http://images.dev/lorem/ipsum.jpg",
  125. expectedError: false,
  126. },
  127. {
  128. name: "match http URL with wildcard in hostname single level",
  129. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  130. requestPath: "/unsafe/plain/http://a-1.mycdn.dev/lorem/ipsum.jpg",
  131. expectedError: false,
  132. },
  133. {
  134. name: "match http URL with wildcard in hostname multiple levels",
  135. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  136. requestPath: "/unsafe/plain/http://a-1.b-2.mycdn.dev/lorem/ipsum.jpg",
  137. expectedError: false,
  138. },
  139. {
  140. name: "no match s3 URL with allowed local and http URLs",
  141. allowedSources: []string{"local://", "http://images.dev/"},
  142. requestPath: "/unsafe/plain/s3://images/lorem/ipsum.jpg",
  143. expectedError: true,
  144. },
  145. {
  146. name: "no match http URL with wildcard in hostname including slash",
  147. allowedSources: []string{"local://", "http://*.mycdn.dev/"},
  148. requestPath: "/unsafe/plain/http://other.dev/.mycdn.dev/lorem/ipsum.jpg",
  149. expectedError: true,
  150. },
  151. }
  152. for _, tc := range tt {
  153. s.T().Run(tc.name, func(t *testing.T) {
  154. exps := make([]*regexp.Regexp, len(tc.allowedSources))
  155. for i, pattern := range tc.allowedSources {
  156. exps[i] = configurators.RegexpFromPattern(pattern)
  157. }
  158. config.AllowedSources = exps
  159. rw := s.send(tc.requestPath)
  160. res := rw.Result()
  161. if tc.expectedError {
  162. assert.Equal(s.T(), 404, res.StatusCode)
  163. } else {
  164. assert.Equal(s.T(), 200, res.StatusCode)
  165. }
  166. })
  167. }
  168. }
  169. func (s *ProcessingHandlerTestSuite) TestSourceFormatNotSupported() {
  170. vips.DisableLoadSupport(imagetype.PNG)
  171. defer vips.ResetLoadSupport()
  172. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  173. res := rw.Result()
  174. assert.Equal(s.T(), 422, res.StatusCode)
  175. }
  176. func (s *ProcessingHandlerTestSuite) TestResultingFormatNotSupported() {
  177. vips.DisableSaveSupport(imagetype.PNG)
  178. defer vips.ResetSaveSupport()
  179. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@png")
  180. res := rw.Result()
  181. assert.Equal(s.T(), 422, res.StatusCode)
  182. }
  183. func (s *ProcessingHandlerTestSuite) TestSkipProcessingConfig() {
  184. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  185. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  186. res := rw.Result()
  187. assert.Equal(s.T(), 200, res.StatusCode)
  188. actual := s.readBody(res)
  189. expected := s.readTestFile("test1.png")
  190. assert.True(s.T(), bytes.Equal(expected, actual))
  191. }
  192. func (s *ProcessingHandlerTestSuite) TestSkipProcessingPO() {
  193. rw := s.send("/unsafe/rs:fill:4:4/skp:png/plain/local:///test1.png")
  194. res := rw.Result()
  195. assert.Equal(s.T(), 200, res.StatusCode)
  196. actual := s.readBody(res)
  197. expected := s.readTestFile("test1.png")
  198. assert.True(s.T(), bytes.Equal(expected, actual))
  199. }
  200. func (s *ProcessingHandlerTestSuite) TestSkipProcessingSameFormat() {
  201. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  202. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@png")
  203. res := rw.Result()
  204. assert.Equal(s.T(), 200, res.StatusCode)
  205. actual := s.readBody(res)
  206. expected := s.readTestFile("test1.png")
  207. assert.True(s.T(), bytes.Equal(expected, actual))
  208. }
  209. func (s *ProcessingHandlerTestSuite) TestSkipProcessingDifferentFormat() {
  210. config.SkipProcessingFormats = []imagetype.Type{imagetype.PNG}
  211. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@jpg")
  212. res := rw.Result()
  213. assert.Equal(s.T(), 200, res.StatusCode)
  214. actual := s.readBody(res)
  215. expected := s.readTestFile("test1.png")
  216. assert.False(s.T(), bytes.Equal(expected, actual))
  217. }
  218. func (s *ProcessingHandlerTestSuite) TestSkipProcessingSVG() {
  219. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.svg")
  220. res := rw.Result()
  221. assert.Equal(s.T(), 200, res.StatusCode)
  222. actual := s.readBody(res)
  223. expected := s.readTestFile("test1.svg")
  224. assert.True(s.T(), bytes.Equal(expected, actual))
  225. }
  226. func (s *ProcessingHandlerTestSuite) TestNotSkipProcessingSVGToJPG() {
  227. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.svg@jpg")
  228. res := rw.Result()
  229. assert.Equal(s.T(), 200, res.StatusCode)
  230. actual := s.readBody(res)
  231. expected := s.readTestFile("test1.svg")
  232. assert.False(s.T(), bytes.Equal(expected, actual))
  233. }
  234. func (s *ProcessingHandlerTestSuite) TestErrorSavingToSVG() {
  235. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png@svg")
  236. res := rw.Result()
  237. assert.Equal(s.T(), 422, res.StatusCode)
  238. }
  239. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthrough() {
  240. config.CacheControlPassthrough = true
  241. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  242. rw.Header().Set("Cache-Control", "fake-cache-control")
  243. rw.Header().Set("Expires", "fake-expires")
  244. rw.WriteHeader(200)
  245. rw.Write(s.readTestFile("test1.png"))
  246. }))
  247. defer ts.Close()
  248. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  249. res := rw.Result()
  250. assert.Equal(s.T(), "fake-cache-control", res.Header.Get("Cache-Control"))
  251. assert.Equal(s.T(), "fake-expires", res.Header.Get("Expires"))
  252. }
  253. func (s *ProcessingHandlerTestSuite) TestCacheControlPassthroughDisabled() {
  254. config.CacheControlPassthrough = false
  255. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  256. rw.Header().Set("Cache-Control", "fake-cache-control")
  257. rw.Header().Set("Expires", "fake-expires")
  258. rw.WriteHeader(200)
  259. rw.Write(s.readTestFile("test1.png"))
  260. }))
  261. defer ts.Close()
  262. rw := s.send("/unsafe/rs:fill:4:4/plain/" + ts.URL)
  263. res := rw.Result()
  264. assert.NotEqual(s.T(), "fake-cache-control", res.Header.Get("Cache-Control"))
  265. assert.NotEqual(s.T(), "fake-expires", res.Header.Get("Expires"))
  266. }
  267. func (s *ProcessingHandlerTestSuite) TestETagDisabled() {
  268. config.ETagEnabled = false
  269. rw := s.send("/unsafe/rs:fill:4:4/plain/local:///test1.png")
  270. res := rw.Result()
  271. assert.Equal(s.T(), 200, res.StatusCode)
  272. assert.Empty(s.T(), res.Header.Get("ETag"))
  273. }
  274. func (s *ProcessingHandlerTestSuite) TestETagReqNoIfNotModified() {
  275. config.ETagEnabled = true
  276. poStr, imgdata, etag := s.sampleETagData("loremipsumdolor")
  277. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  278. assert.Empty(s.T(), r.Header.Get("If-None-Match"))
  279. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  280. rw.WriteHeader(200)
  281. rw.Write(s.readTestFile("test1.png"))
  282. }))
  283. defer ts.Close()
  284. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL))
  285. res := rw.Result()
  286. assert.Equal(s.T(), 200, res.StatusCode)
  287. assert.Equal(s.T(), etag, res.Header.Get("ETag"))
  288. }
  289. func (s *ProcessingHandlerTestSuite) TestETagDataNoIfNotModified() {
  290. config.ETagEnabled = true
  291. poStr, imgdata, etag := s.sampleETagData("")
  292. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  293. assert.Empty(s.T(), r.Header.Get("If-None-Match"))
  294. rw.WriteHeader(200)
  295. rw.Write(imgdata.Data)
  296. }))
  297. defer ts.Close()
  298. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL))
  299. res := rw.Result()
  300. assert.Equal(s.T(), 200, res.StatusCode)
  301. assert.Equal(s.T(), etag, res.Header.Get("ETag"))
  302. }
  303. func (s *ProcessingHandlerTestSuite) TestETagReqMatch() {
  304. config.ETagEnabled = true
  305. poStr, imgdata, etag := s.sampleETagData(`"loremipsumdolor"`)
  306. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  307. assert.Equal(s.T(), imgdata.Headers["ETag"], r.Header.Get("If-None-Match"))
  308. rw.WriteHeader(304)
  309. }))
  310. defer ts.Close()
  311. header := make(http.Header)
  312. header.Set("If-None-Match", etag)
  313. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  314. res := rw.Result()
  315. assert.Equal(s.T(), 304, res.StatusCode)
  316. assert.Equal(s.T(), etag, res.Header.Get("ETag"))
  317. }
  318. func (s *ProcessingHandlerTestSuite) TestETagDataMatch() {
  319. config.ETagEnabled = true
  320. poStr, imgdata, etag := s.sampleETagData("")
  321. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  322. assert.Empty(s.T(), r.Header.Get("If-None-Match"))
  323. rw.WriteHeader(200)
  324. rw.Write(imgdata.Data)
  325. }))
  326. defer ts.Close()
  327. header := make(http.Header)
  328. header.Set("If-None-Match", etag)
  329. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  330. res := rw.Result()
  331. assert.Equal(s.T(), 304, res.StatusCode)
  332. assert.Equal(s.T(), etag, res.Header.Get("ETag"))
  333. }
  334. func (s *ProcessingHandlerTestSuite) TestETagReqNotMatch() {
  335. config.ETagEnabled = true
  336. poStr, imgdata, actualETag := s.sampleETagData(`"loremipsumdolor"`)
  337. _, _, expectedETag := s.sampleETagData(`"loremipsum"`)
  338. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  339. assert.Equal(s.T(), `"loremipsum"`, r.Header.Get("If-None-Match"))
  340. rw.Header().Set("ETag", imgdata.Headers["ETag"])
  341. rw.WriteHeader(200)
  342. rw.Write(imgdata.Data)
  343. }))
  344. defer ts.Close()
  345. header := make(http.Header)
  346. header.Set("If-None-Match", expectedETag)
  347. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  348. res := rw.Result()
  349. assert.Equal(s.T(), 200, res.StatusCode)
  350. assert.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  351. }
  352. func (s *ProcessingHandlerTestSuite) TestETagDataNotMatch() {
  353. config.ETagEnabled = true
  354. poStr, imgdata, actualETag := s.sampleETagData("")
  355. // Change the data hash
  356. expectedETag := actualETag[:strings.IndexByte(actualETag, '/')] + "/Dasdbefj"
  357. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  358. assert.Empty(s.T(), 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", expectedETag)
  365. rw := s.send(fmt.Sprintf("/unsafe/%s/plain/%s", poStr, ts.URL), header)
  366. res := rw.Result()
  367. assert.Equal(s.T(), 200, res.StatusCode)
  368. assert.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  369. }
  370. func (s *ProcessingHandlerTestSuite) TestETagProcessingOptionsNotMatch() {
  371. config.ETagEnabled = true
  372. poStr, imgdata, actualETag := s.sampleETagData("")
  373. // Change the processing options hash
  374. expectedETag := "abcdefj" + actualETag[strings.IndexByte(actualETag, '/'):]
  375. ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  376. assert.Empty(s.T(), 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. assert.Equal(s.T(), 200, res.StatusCode)
  387. assert.Equal(s.T(), actualETag, res.Header.Get("ETag"))
  388. }
  389. func TestProcessingHandler(t *testing.T) {
  390. suite.Run(t, new(ProcessingHandlerTestSuite))
  391. }