diff --git a/.gitignore b/.gitignore index 87f61275..4ccd7589 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ bin/ imaginary bin/imaginary +coverage.out \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 8dcabd13..2a17162e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,35 +1,60 @@ -ARG GOLANG_VERSION=1.17 -FROM golang:${GOLANG_VERSION}-bullseye AS builder +# syntax=docker/dockerfile:1.4 + +ARG GOLANG_VERSION=1.25 +FROM golang:${GOLANG_VERSION}-bullseye as builder + ARG IMAGINARY_VERSION=dev -ARG LIBVIPS_VERSION=8.12.2 -ARG GOLANGCILINT_VERSION=1.29.0 +ARG LIBVIPS_VERSION=8.14.1 +ARG GOLANGCILINT_VERSION=1.51.1 + +ENV LIBSPNG_VERSION="0.7.3" +ENV LIBSPNG_URL="https://github.com/randy408/libspng/archive/refs/tags/v${LIBSPNG_VERSION}.tar.gz" + +#ENV PDFIUM_VERSION="5579" +#ENV PDFIUM_URL="https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/${PDFIUM_VERSION}/pdfium-linux-arm64.tgz" +# +## Installs libvips + required libraries +#COPY < 8 { if bimg.IsSVGImage(buf) { @@ -136,11 +143,13 @@ func imageHandler(w http.ResponseWriter, r *http.Request, buf []byte, operation } image, err := operation.Run(buf, opts) + + // Ensure the Vary header is set when an error occurs + if vary != "" { + w.Header().Set("Vary", vary) + } + if err != nil { - // Ensure the Vary header is set when an error occurs - if vary != "" { - w.Header().Set("Vary", vary) - } ErrorReply(r, w, NewError("Error while processing the image: "+err.Error(), http.StatusBadRequest), o) return } @@ -148,16 +157,17 @@ func imageHandler(w http.ResponseWriter, r *http.Request, buf []byte, operation // Expose Content-Length response header w.Header().Set("Content-Length", strconv.Itoa(len(image.Body))) w.Header().Set("Content-Type", image.Mime) - if image.Mime != "application/json" && o.ReturnSize { - meta, err := bimg.Metadata(image.Body) - if err == nil { - w.Header().Set("Image-Width", strconv.Itoa(meta.Size.Width)) - w.Header().Set("Image-Height", strconv.Itoa(meta.Size.Height)) + if image.Mime != "application/json" { + if o.ReturnSize { + meta, err := bimg.Metadata(image.Body) + if err == nil { + w.Header().Set("Image-Width", strconv.Itoa(meta.Size.Width)) + w.Header().Set("Image-Height", strconv.Itoa(meta.Size.Height)) + } } + w.Header().Set("X-Compression-Rate", fmt.Sprintf(`%.2f`, float64(len(image.Body))/float64(len(buf)))) } - if vary != "" { - w.Header().Set("Vary", vary) - } + _, _ = w.Write(image.Body) } diff --git a/error.go b/error.go index 8d01660a..3288af53 100644 --- a/error.go +++ b/error.go @@ -49,7 +49,7 @@ func (e Error) HTTPCode() int { } func NewError(err string, code int) Error { - err = strings.Replace(err, "\n", "", -1) + err = strings.ReplaceAll(err, "\n", "") return Error{Message: err, Code: code} } diff --git a/go.mod b/go.mod index aaa451f1..c341dd9d 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,10 @@ module github.com/h2non/imaginary go 1.12 require ( - github.com/h2non/bimg v1.1.7 - github.com/h2non/filetype v1.1.0 - github.com/rs/cors v0.0.0-20170727213201-7af7a1e09ba3 - github.com/throttled/throttled/v2 v2.15.0 + github.com/h2non/bimg v1.1.9 + github.com/h2non/filetype v1.1.3 + github.com/rs/cors v1.11.1 + gopkg.in/throttled/throttled.v2 v2.15.0 ) + +replace gopkg.in/throttled/throttled.v2 v2.9.1 => github.com/throttled/throttled/v2 v2.9.1 diff --git a/go.sum b/go.sum index e246f500..785bb527 100644 --- a/go.sum +++ b/go.sum @@ -1,14 +1,8 @@ -github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w= -github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/garyburd/redigo v1.6.0 h1:0VruCpn7yAIIu7pWVClQC8wxCJEcG3nyzpMSHKi1PQc= +github.com/garyburd/redigo v1.6.0/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= -github.com/go-redis/redis/v8 v8.4.2/go.mod h1:A1tbYoHSa1fXwN+//ljcCYYJeLmVrwL9hbQN45Jdy0M= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= @@ -16,82 +10,49 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= -github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= +github.com/gomodule/redigo v1.8.4/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/h2non/bimg v1.1.7 h1:JKJe70nDNMWp2wFnTLMGB8qJWQQMaKRn56uHmC/4+34= github.com/h2non/bimg v1.1.7/go.mod h1:R3+UiYwkK4rQl6KVFTOFJHitgLbZXBZNFh2cv3AEbp8= +github.com/h2non/bimg v1.1.9 h1:WH20Nxko9l/HFm4kZCA3Phbgu2cbHvYzxwxn9YROEGg= +github.com/h2non/bimg v1.1.9/go.mod h1:R3+UiYwkK4rQl6KVFTOFJHitgLbZXBZNFh2cv3AEbp8= github.com/h2non/filetype v1.1.0 h1:Or/gjocJrJRNK/Cri/TDEKFjAR+cfG6eK65NGYB6gBA= github.com/h2non/filetype v1.1.0/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= +github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad h1:eMxs9EL0PvIGS9TTtxg4R+JxuPGav82J8rA+GFnY7po= +github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk= github.com/rs/cors v0.0.0-20170727213201-7af7a1e09ba3 h1:86ukAHRTa2CXdBnWJHcjjPPGTyLGEF488OFRsbBAuFs= github.com/rs/cors v0.0.0-20170727213201-7af7a1e09ba3/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= +github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/throttled/throttled/v2 v2.15.0 h1:7XLCECtmEx+Yz/e5opBNff9cPGpH0ia0xEj5kyDPotI= -github.com/throttled/throttled/v2 v2.15.0/go.mod h1:JlfSSSYoM/bjFoW2sCATGxJJXggjO67DFQu9xduGAWE= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.opentelemetry.io/otel v0.14.0/go.mod h1:vH5xEuwy7Rts0GNtsCW3HYQoZDY+OmBJ6t1bFGGlxgw= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/throttled/throttled/v2 v2.9.1 h1:Es7fBRL04IUOvs4RwbieshgyccyztfaAjzQdKbrpqyo= +github.com/throttled/throttled/v2 v2.9.1/go.mod h1:SxVlv4wUgeS/hWOSMDeb9Ez+stPqP7tWY5wI5BUiGqs= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= @@ -100,12 +61,13 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/throttled/throttled.v2 v2.0.3 h1:PGm7nfjjexecEyI2knw1akeLcrjzqxuYSU9a04R8rfU= +gopkg.in/throttled/throttled.v2 v2.0.3/go.mod h1:L4cTNZO77XKEXtn8HNFRCMNGZPtRRKAhyuJBSvK/T90= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/imaginary.go b/imaginary.go index b46f86d9..25c79447 100644 --- a/imaginary.go +++ b/imaginary.go @@ -3,6 +3,8 @@ package main import ( "flag" "fmt" + "gopkg.in/yaml.v2" + "io" "io/ioutil" "log" "net/url" @@ -52,6 +54,7 @@ var ( aCpus = flag.Int("cpus", runtime.GOMAXPROCS(-1), "Number of cpu cores to use") aLogLevel = flag.String("log-level", "info", "Define log level for http-server. E.g: info,warning,error") aReturnSize = flag.Bool("return-size", false, "Return the image size in the HTTP headers") + aReferrerPolicy = flag.String("referrer-policy", "no", "How to set the HTTP Referer header when requesting image from HTTP. E.g: no, origin, unsafe, url-host, url-dir, site-file(a YAML config file)") ) const usage = `imaginary %s @@ -110,6 +113,7 @@ Options: -log-level Set log level for http-server. E.g: info,warning,error [default: info]. Or can use the environment variable GOLANG_LOG=info. -return-size Return the image size with X-Width and X-Height HTTP header. [default: disabled]. + -referrer-policy How to set the HTTP Referer header when requesting image from HTTP. E.g: no, origin, unsafe, url-host, url-dir, site-file(a YAML config file). [default: no]. ` type URLSignature struct { @@ -135,6 +139,11 @@ func main() { port := getPort(*aPort) urlSignature := getURLSignature(*aURLSignatureKey) + referrerPolicy, err := parseReferrerPolicy(*aReferrerPolicy) + if err != nil { + log.Printf("ReferrerPolicy Config errors: %s", err) + } + opts := ServerOptions{ Port: port, Address: *aAddr, @@ -163,6 +172,7 @@ func main() { MaxAllowedPixels: *aMaxAllowedPixels, LogLevel: getLogLevel(*aLogLevel), ReturnSize: *aReturnSize, + ReferrerPolicy: referrerPolicy, } // Show warning if gzip flag is passed @@ -253,6 +263,43 @@ func getLogLevel(logLevel string) string { return logLevel } +func parseReferrerPolicy(s string) (ReferrerPolicy, error) { + defaultPolicy := NoReferrer + policy := ReferrerPolicy{ + Default: defaultPolicy, + } + + switch s { + case URLHostReferrer: + policy.Default = URLHostReferrer + case URLDirReferrer: + policy.Default = URLDirReferrer + case OriginReferrer: + policy.Default = OriginReferrer + case UnsafeReferrer: + policy.Default = UnsafeReferrer + case NoReferrer: + policy.Default = NoReferrer + default: + file, err := os.Open(s) + if err != nil { + // If does not exist and config file was not specificly specified then return ErrNoConfigFile found. + if os.IsNotExist(err) { + return policy, fmt.Errorf("referrer policy file %s is not existed", s) + } + return policy, fmt.Errorf("referrer policy file %s cannot be opened because %s ", s, err) + } + defer file.Close() + if err := yaml.NewDecoder(file).Decode(&policy); err != nil { + if err == io.EOF { + return policy, fmt.Errorf("referrer policy file %s was empty", s) + } + return policy, fmt.Errorf("error parsing YAML in referrer policy file at "+s+"with error: %s", err) + } + } + return policy, nil +} + func showUsage() { flag.Usage() os.Exit(1) diff --git a/middleware.go b/middleware.go index 2898b22c..d9856ef9 100644 --- a/middleware.go +++ b/middleware.go @@ -148,7 +148,7 @@ func setCacheHeaders(next http.Handler, ttl int) http.Handler { ttlDiff := time.Duration(ttl) * time.Second expires := time.Now().Add(ttlDiff) - w.Header().Add("Expires", strings.Replace(expires.Format(time.RFC1123), "UTC", "GMT", -1)) + w.Header().Add("Expires", strings.ReplaceAll(expires.Format(time.RFC1123), "UTC", "GMT")) w.Header().Add("Cache-Control", getCacheControl(ttl)) }) } diff --git a/server.go b/server.go index f3a17d73..8323454a 100644 --- a/server.go +++ b/server.go @@ -45,11 +45,30 @@ type ServerOptions struct { AllowedOrigins []*url.URL LogLevel string ReturnSize bool + ReferrerPolicy ReferrerPolicy } // Endpoints represents a list of endpoint names to disable. type Endpoints []string +const ( + NoReferrer = "no" + OriginReferrer = "origin" + UnsafeReferrer = "unsafe" + URLHostReferrer = "url-host" + URLDirReferrer = "url-dir" +) + +type ReferrerSite struct { + URL string `yaml:"url"` + Refer string `yaml:"refer"` +} + +type ReferrerPolicy struct { + Default string `yaml:"default"` + Sites []ReferrerSite `yaml:"sites"` +} + // IsValid validates if a given HTTP request endpoint is valid or not. func (e Endpoints) IsValid(r *http.Request) bool { parts := strings.Split(r.URL.Path, "/") @@ -93,7 +112,7 @@ func Server(o ServerOptions) { }() if err := server.Shutdown(ctx); err != nil { - log.Fatalf("Server Shutdown Failed:%+v", err) + log.Printf("Server Shutdown Failed:%+v", err) } } diff --git a/source.go b/source.go index 572e6aaf..69aa9766 100644 --- a/source.go +++ b/source.go @@ -16,6 +16,7 @@ type SourceConfig struct { ForwardHeaders []string AllowedOrigins []*url.URL MaxAllowedSize int + ReferrerPolicy ReferrerPolicy } var imageSourceMap = make(map[ImageSourceType]ImageSource) @@ -40,6 +41,7 @@ func LoadSources(o ServerOptions) { AllowedOrigins: o.AllowedOrigins, MaxAllowedSize: o.MaxAllowedSize, ForwardHeaders: o.ForwardHeaders, + ReferrerPolicy: o.ReferrerPolicy, }) } } diff --git a/source_http.go b/source_http.go index 5bfeeaa3..254b7b5f 100644 --- a/source_http.go +++ b/source_http.go @@ -5,6 +5,8 @@ import ( "io/ioutil" "net/http" "net/url" + "path" + "path/filepath" "strconv" "strings" ) @@ -44,7 +46,7 @@ func (s *HTTPImageSource) fetchImage(url *url.URL, ireq *http.Request) ([]byte, return nil, fmt.Errorf("error fetching remote http image headers: %v", err) } _ = res.Body.Close() - if res.StatusCode < 200 && res.StatusCode > 206 { + if res.StatusCode < 200 || res.StatusCode > 206 { return nil, NewError(fmt.Sprintf("error fetching remote http image headers: (status=%d) (url=%s)", res.StatusCode, req.URL.String()), res.StatusCode) } @@ -95,6 +97,32 @@ func (s *HTTPImageSource) setForwardHeaders(req *http.Request, ireq *http.Reques } } +func (s *HTTPImageSource) setRefererHeader(req *http.Request, ireq *http.Request, url *url.URL) { + policy := s.Config.ReferrerPolicy + if len(policy.Sites) != 0 { + for _, site := range policy.Sites { + match, err := filepath.Match(site.URL, url.Host) + if err != nil { + return + } + if match { + req.Header.Set("Referer", url.Scheme+"://"+site.Refer) + return + } + } + } + switch policy.Default { + case URLHostReferrer: + req.Header.Set("Referer", url.Scheme+"://"+url.Host) + case URLDirReferrer: + req.Header.Set("Referer", url.Scheme+"://"+url.Host+path.Dir(url.Path)) + case OriginReferrer: + req.Header.Set("Referer", ireq.URL.Scheme+"://"+ireq.Host) + case UnsafeReferrer: + req.Header.Set("Referer", ireq.Referer()) + } +} + func parseURL(request *http.Request) (*url.URL, error) { return url.Parse(request.URL.Query().Get(URLQueryKey)) } @@ -113,6 +141,10 @@ func newHTTPRequest(s *HTTPImageSource, ireq *http.Request, method string, url * s.setAuthorizationHeader(req, ireq) } + if s.Config.ReferrerPolicy.Default != NoReferrer { + s.setRefererHeader(req, ireq, url) + } + return req } diff --git a/source_http_test.go b/source_http_test.go index aa542726..ee353434 100755 --- a/source_http_test.go +++ b/source_http_test.go @@ -1,6 +1,7 @@ package main import ( + "gopkg.in/yaml.v2" "io/ioutil" "net/http" "net/http/httptest" @@ -10,6 +11,7 @@ import ( const fixtureImage = "testdata/large.jpg" const fixture1024Bytes = "testdata/1024bytes" +const fixturePolicyFile = "testdata/policy.yml" func TestHttpImageSource(t *testing.T) { var body []byte @@ -241,6 +243,179 @@ func TestHttpImageSourceEmptyForwardedHeaders(t *testing.T) { } } +func TestHttpImageSourceNoReferrerHeader(t *testing.T) { + policy := ReferrerPolicy{ + Default: NoReferrer, + } + + u := "http://bar.com/a/img" + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != "" { + t.Fatal("Mismatch Referer header, should be empty") + } +} + +func TestHttpImageSourceUnsafeReferrerHeader(t *testing.T) { + policy := ReferrerPolicy{ + Default: UnsafeReferrer, + } + + u := "http://bar.com/a/img" + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != "http://foo" { + t.Fatalf("Mismatch Referer header, should be %s", "http://foo") + } +} + +func TestHttpImageSourceOriginReferrerHeader(t *testing.T) { + policy := ReferrerPolicy{ + Default: OriginReferrer, + } + u := "http://bar.com/a/img" + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != "http://foo.com" { + t.Fatalf("Mismatch Referer header, should be %s", "http://foo.com") + } +} + +func TestHttpImageSourceUrlHostReferrerHeader(t *testing.T) { + policy := ReferrerPolicy{ + Default: URLHostReferrer, + } + u := "http://bar.com/a/img" + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != "http://bar.com" { + t.Fatalf("Mismatch Referer header, should be %s", "http://bar.com") + } +} + +func TestHttpImageSourceUrlDirReferrerHeader(t *testing.T) { + policy := ReferrerPolicy{ + Default: URLDirReferrer, + } + u := "http://bar.com/a/img" + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != "http://bar.com/a" { + t.Fatalf("Mismatch Referer header, should be %s", "http://bar.com/a") + } +} + +func TestHttpImageSourceSiteFileReferrerHeaderReadFromYamlFile(t *testing.T) { + // Read the YAML file into memory + data, err := ioutil.ReadFile(fixturePolicyFile) + if err != nil { + t.Errorf("Error reading YAML file: %v", err) + } + + // Parse the YAML data into a ReferrerPolicy struct + var policy ReferrerPolicy + err = yaml.Unmarshal(data, &policy) + if err != nil { + t.Errorf("Error parsing YAML data: %v", err) + } + + tests := []struct { + name string + url string + expectedRefer string + }{ + { + name: "single match", + url: "http://tva1.moyu.im/a/img", + expectedRefer: "http://i.jandan.net", + }, + { + name: "wildcard match", + url: "http://tva2.moyu.im/a/img", + expectedRefer: "http://jandan.net", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + u := tt.url + u1, _ := url.Parse(u) + + r, _ := http.NewRequest(http.MethodGet, "http://foo.com/bar?url="+u, nil) + r.Header.Set("Referer", "http://foo") + + source := &HTTPImageSource{&SourceConfig{ReferrerPolicy: policy}} + if !source.Matches(r) { + t.Fatal("Cannot match the request") + } + + oreq := &http.Request{Header: make(http.Header)} + source.setRefererHeader(oreq, r, u1) + + if oreq.Header.Get("Referer") != tt.expectedRefer { + t.Fatalf("Mismatch Referer header, should be %s, but %s", tt.expectedRefer, oreq.Header.Get("Referer")) + } + + }) + } + +} + func TestHttpImageSourceError(t *testing.T) { var err error diff --git a/testdata/policy.yml b/testdata/policy.yml new file mode 100644 index 00000000..0e38bf33 --- /dev/null +++ b/testdata/policy.yml @@ -0,0 +1,6 @@ +default: url-host +sites: + - url: tva1.moyu.im + refer: i.jandan.net + - url: "*.moyu.im" + refer: jandan.net \ No newline at end of file diff --git a/type.go b/type.go index 6230ca8a..858eab3e 100644 --- a/type.go +++ b/type.go @@ -39,6 +39,8 @@ func ImageType(name string) bimg.ImageType { return bimg.PNG case "webp": return bimg.WEBP + case "avif": + return bimg.AVIF case "tiff": return bimg.TIFF case "gif": @@ -59,6 +61,8 @@ func GetImageMimeType(code bimg.ImageType) string { return "image/png" case bimg.WEBP: return "image/webp" + case bimg.AVIF: + return "image/avif" case bimg.TIFF: return "image/tiff" case bimg.GIF: diff --git a/type_test.go b/type_test.go index 494f6a0a..449f6d84 100644 --- a/type_test.go +++ b/type_test.go @@ -37,6 +37,7 @@ func TestIsImageTypeSupported(t *testing.T) { {"png", false}, {"multipart/form-data; encoding=utf-8", false}, {"application/json", false}, + {"image/avif", bimg.IsImageTypeSupportedByVips(bimg.AVIF).Load}, {"image/gif", bimg.IsImageTypeSupportedByVips(bimg.GIF).Load}, {"image/svg+xml", bimg.IsImageTypeSupportedByVips(bimg.SVG).Load}, {"image/svg", bimg.IsImageTypeSupportedByVips(bimg.SVG).Load}, @@ -62,6 +63,7 @@ func TestImageType(t *testing.T) { {"jpeg", bimg.JPEG}, {"png", bimg.PNG}, {"webp", bimg.WEBP}, + {"avif", bimg.AVIF}, {"tiff", bimg.TIFF}, {"gif", bimg.GIF}, {"svg", bimg.SVG}, @@ -89,6 +91,7 @@ func TestGetImageMimeType(t *testing.T) { {bimg.PNG, "image/png"}, {bimg.WEBP, "image/webp"}, {bimg.TIFF, "image/tiff"}, + {bimg.AVIF, "image/avif"}, {bimg.GIF, "image/gif"}, {bimg.PDF, "application/pdf"}, {bimg.SVG, "image/svg+xml"},