From e600bb96ee9cbfb9d19d30bfbf6aa442b920ed7b Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Mon, 30 Jan 2023 12:28:21 +0800 Subject: [PATCH 01/15] update go.mod&sum --- go.mod | 11 +++++------ go.sum | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index acaefdf0..19a671f1 100644 --- a/go.mod +++ b/go.mod @@ -3,10 +3,9 @@ module github.com/h2non/imaginary go 1.12 require ( - github.com/garyburd/redigo v1.6.0 // indirect - github.com/h2non/bimg v1.1.7 - github.com/h2non/filetype v1.1.0 - github.com/hashicorp/golang-lru v0.0.0-20160813221303-0a025b7e63ad // indirect - github.com/rs/cors v0.0.0-20170727213201-7af7a1e09ba3 - gopkg.in/throttled/throttled.v2 v2.0.3 + github.com/h2non/bimg v1.1.9 + github.com/h2non/filetype v1.1.3 + github.com/rs/cors v1.8.3 + gopkg.in/throttled/throttled.v2 v2.9.1 ) +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 9ef6d1c1..3dda5c20 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,71 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 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/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= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +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.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.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/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +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/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.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/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +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/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-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.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +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= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +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/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.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= From 05a8c197f70567c76dc3e22b73d2d48e3314f387 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Mon, 30 Jan 2023 18:06:03 +0800 Subject: [PATCH 02/15] add referer policy --- Dockerfile | 2 +- imaginary.go | 3 ++ server.go | 1 + source.go | 2 + source_http.go | 21 +++++++++ source_http_test.go | 107 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 135 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 67c699be..c7ba5de4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,7 +28,7 @@ RUN DEBIAN_FRONTEND=noninteractive \ --enable-gtk-doc-html=no \ --enable-gtk-doc=no \ --enable-pyvips8=no && \ - make && \ + make -j 4 && \ make install && \ ldconfig diff --git a/imaginary.go b/imaginary.go index b46f86d9..c55cc0e0 100644 --- a/imaginary.go +++ b/imaginary.go @@ -52,6 +52,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") ) const usage = `imaginary %s @@ -110,6 +111,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. [default: no]. ` type URLSignature struct { @@ -163,6 +165,7 @@ func main() { MaxAllowedPixels: *aMaxAllowedPixels, LogLevel: getLogLevel(*aLogLevel), ReturnSize: *aReturnSize, + ReferrerPolicy: *aReferrerPolicy, } // Show warning if gzip flag is passed diff --git a/server.go b/server.go index f3a17d73..62635d5b 100644 --- a/server.go +++ b/server.go @@ -45,6 +45,7 @@ type ServerOptions struct { AllowedOrigins []*url.URL LogLevel string ReturnSize bool + ReferrerPolicy string } // Endpoints represents a list of endpoint names to disable. diff --git a/source.go b/source.go index 572e6aaf..73fb95cd 100644 --- a/source.go +++ b/source.go @@ -16,6 +16,7 @@ type SourceConfig struct { ForwardHeaders []string AllowedOrigins []*url.URL MaxAllowedSize int + ReferrerPolicy string } 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..5db1a8a2 100644 --- a/source_http.go +++ b/source_http.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "net/http" "net/url" + "path" "strconv" "strings" ) @@ -95,6 +96,22 @@ func (s *HTTPImageSource) setForwardHeaders(req *http.Request, ireq *http.Reques } } +func (s *HTTPImageSource) setRefererHeader(req *http.Request, ireq *http.Request, url *url.URL) { + referrerPolicy := s.Config.ReferrerPolicy + switch referrerPolicy { + case "url-host": + req.Header.Set("Referer", url.Scheme+"://"+url.Host) + case "url-dir": + req.Header.Set("Referer", url.Scheme+"://"+url.Host+path.Dir(url.Path)) + case "origin": + req.Header.Set("Referer", ireq.URL.Scheme+"://"+ireq.Host) + case "unsafe": + req.Header.Set("Referer", ireq.Referer()) + default: + break + } +} + func parseURL(request *http.Request) (*url.URL, error) { return url.Parse(request.URL.Query().Get(URLQueryKey)) } @@ -113,6 +130,10 @@ func newHTTPRequest(s *HTTPImageSource, ireq *http.Request, method string, url * s.setAuthorizationHeader(req, ireq) } + if s.Config.ReferrerPolicy != "" { + s.setRefererHeader(req, ireq, url) + } + return req } diff --git a/source_http_test.go b/source_http_test.go index aa542726..5daf64b0 100755 --- a/source_http_test.go +++ b/source_http_test.go @@ -241,6 +241,113 @@ func TestHttpImageSourceEmptyForwardedHeaders(t *testing.T) { } } +func TestHttpImageSourceNoReferrerHeader(t *testing.T) { + policy := "no" + + 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 := "unsafe" + + 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 := "origin" + 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 := "url-host" + 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 := "url-dir" + 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 TestHttpImageSourceError(t *testing.T) { var err error From 439ae57fa112418bbe2bc2578ef239a52fada373 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Mon, 6 Feb 2023 14:31:52 +0800 Subject: [PATCH 03/15] first prop file --- testdata/policy.properties | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 testdata/policy.properties diff --git a/testdata/policy.properties b/testdata/policy.properties new file mode 100644 index 00000000..954ba515 --- /dev/null +++ b/testdata/policy.properties @@ -0,0 +1,2 @@ +default=url-host +sites=[{url=tva1.moyu.im, refer=i.jandan.net}] From 3672016db139600fa47c9773305a5ad24645ae3c Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 7 Feb 2023 04:00:43 +0800 Subject: [PATCH 04/15] gotest ok --- go.mod | 4 ++- go.sum | 2 ++ imaginary.go | 60 ++++++++++++++++++++++++++++++++++++-- server.go | 22 +++++++++++++- source.go | 2 +- source_http.go | 29 ++++++++++++------ source_http_test.go | 25 ++++++++++++---- testdata/policy.properties | 2 -- testdata/policy.yml | 4 +++ 9 files changed, 128 insertions(+), 22 deletions(-) delete mode 100644 testdata/policy.properties create mode 100644 testdata/policy.yml diff --git a/go.mod b/go.mod index 19a671f1..35fea3e5 100644 --- a/go.mod +++ b/go.mod @@ -7,5 +7,7 @@ require ( github.com/h2non/filetype v1.1.3 github.com/rs/cors v1.8.3 gopkg.in/throttled/throttled.v2 v2.9.1 + gopkg.in/yaml.v2 v2.4.0 // indirect ) -replace gopkg.in/throttled/throttled.v2 v2.9.1 => github.com/throttled/throttled/v2 v2.9.1 + +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 3dda5c20..785bb527 100644 --- a/go.sum +++ b/go.sum @@ -69,3 +69,5 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD 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 c55cc0e0..73e75852 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,7 +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") + 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 @@ -111,7 +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. [default: no]. + -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 { @@ -165,7 +167,7 @@ func main() { MaxAllowedPixels: *aMaxAllowedPixels, LogLevel: getLogLevel(*aLogLevel), ReturnSize: *aReturnSize, - ReferrerPolicy: *aReferrerPolicy, + ReferrerPolicy: parseReferrerPolicy(*aReferrerPolicy), } // Show warning if gzip flag is passed @@ -256,6 +258,58 @@ func getLogLevel(logLevel string) string { return logLevel } +var ( + // DefaultConfigFiles is the file names from which we attempt to read configuration. + DefaultConfigFiles = []string{"config.yml", "config.yaml"} + + // DefaultUnixConfigLocation is the primary location to find a config file + DefaultUnixConfigLocation = "/usr/local/etc/imaginary" + + // Launchd doesn't set root env variables, so there is default + // Windows default config dir was ~/cloudflare-warp in documentation; let's keep it compatible + defaultNixConfigDirs = []string{"/etc/imaginary", DefaultUnixConfigLocation} + + ErrNoConfigFile = fmt.Errorf("Cannot determine default configuration path. No file %v in %v", DefaultConfigFiles, defaultNixConfigDirs) +) + +func parseReferrerPolicy(s string) ReferrerPolicy { + 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) { + err = ErrNoConfigFile + } + log.Fatalf("Configuration file %s was not existed", s) + } + defer file.Close() + if err := yaml.NewDecoder(file).Decode(&policy); err != nil { + if err == io.EOF { + log.Fatalf("Configuration file %s was empty", s) + return policy + } + log.Fatalf("error parsing YAML in config file at "+s+"with error: %s", err) + } + } + return policy +} + func showUsage() { flag.Usage() os.Exit(1) diff --git a/server.go b/server.go index 62635d5b..ffc25ea2 100644 --- a/server.go +++ b/server.go @@ -45,12 +45,32 @@ type ServerOptions struct { AllowedOrigins []*url.URL LogLevel string ReturnSize bool - ReferrerPolicy string + 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" + SiteReferrer = "site" +) + +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, "/") diff --git a/source.go b/source.go index 73fb95cd..69aa9766 100644 --- a/source.go +++ b/source.go @@ -16,7 +16,7 @@ type SourceConfig struct { ForwardHeaders []string AllowedOrigins []*url.URL MaxAllowedSize int - ReferrerPolicy string + ReferrerPolicy ReferrerPolicy } var imageSourceMap = make(map[ImageSourceType]ImageSource) diff --git a/source_http.go b/source_http.go index 5db1a8a2..688cc443 100644 --- a/source_http.go +++ b/source_http.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "path" + "path/filepath" "strconv" "strings" ) @@ -97,18 +98,28 @@ func (s *HTTPImageSource) setForwardHeaders(req *http.Request, ireq *http.Reques } func (s *HTTPImageSource) setRefererHeader(req *http.Request, ireq *http.Request, url *url.URL) { - referrerPolicy := s.Config.ReferrerPolicy - switch referrerPolicy { - case "url-host": + policy := s.Config.ReferrerPolicy + if len(policy.Sites) != 0 { + for _, site := range policy.Sites { + match, err := filepath.Match(url.String(), site.URL) + if err != nil { + return + } + if match { + req.Header.Set("Referer", site.Refer) + return + } + } + } + switch policy.Default { + case UrlHostReferrer: req.Header.Set("Referer", url.Scheme+"://"+url.Host) - case "url-dir": + case UrlDirReferrer: req.Header.Set("Referer", url.Scheme+"://"+url.Host+path.Dir(url.Path)) - case "origin": + case OriginReferrer: req.Header.Set("Referer", ireq.URL.Scheme+"://"+ireq.Host) - case "unsafe": + case UnsafeReferrer: req.Header.Set("Referer", ireq.Referer()) - default: - break } } @@ -130,7 +141,7 @@ func newHTTPRequest(s *HTTPImageSource, ireq *http.Request, method string, url * s.setAuthorizationHeader(req, ireq) } - if s.Config.ReferrerPolicy != "" { + if s.Config.ReferrerPolicy.Default != "" { s.setRefererHeader(req, ireq, url) } diff --git a/source_http_test.go b/source_http_test.go index 5daf64b0..76df46c9 100755 --- a/source_http_test.go +++ b/source_http_test.go @@ -10,6 +10,7 @@ import ( const fixtureImage = "testdata/large.jpg" const fixture1024Bytes = "testdata/1024bytes" +const fixturePolicyFile = "testdata/policy.yaml" func TestHttpImageSource(t *testing.T) { var body []byte @@ -242,7 +243,9 @@ func TestHttpImageSourceEmptyForwardedHeaders(t *testing.T) { } func TestHttpImageSourceNoReferrerHeader(t *testing.T) { - policy := "no" + policy := ReferrerPolicy{ + Default: NoReferrer, + } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -264,7 +267,9 @@ func TestHttpImageSourceNoReferrerHeader(t *testing.T) { } func TestHttpImageSourceUnsafeReferrerHeader(t *testing.T) { - policy := "unsafe" + policy := ReferrerPolicy{ + Default: UnsafeReferrer, + } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -286,7 +291,9 @@ func TestHttpImageSourceUnsafeReferrerHeader(t *testing.T) { } func TestHttpImageSourceOriginReferrerHeader(t *testing.T) { - policy := "origin" + policy := ReferrerPolicy{ + Default: OriginReferrer, + } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -307,7 +314,9 @@ func TestHttpImageSourceOriginReferrerHeader(t *testing.T) { } func TestHttpImageSourceUrlHostReferrerHeader(t *testing.T) { - policy := "url-host" + policy := ReferrerPolicy{ + Default: UrlHostReferrer, + } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -328,7 +337,9 @@ func TestHttpImageSourceUrlHostReferrerHeader(t *testing.T) { } func TestHttpImageSourceUrlDirReferrerHeader(t *testing.T) { - policy := "url-dir" + policy := ReferrerPolicy{ + Default: UrlDirReferrer, + } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -348,6 +359,10 @@ func TestHttpImageSourceUrlDirReferrerHeader(t *testing.T) { } } +//func TestHttpImageSourceSiteFileReferrerHeader(t *testing.T) { +// +//} + func TestHttpImageSourceError(t *testing.T) { var err error diff --git a/testdata/policy.properties b/testdata/policy.properties deleted file mode 100644 index 954ba515..00000000 --- a/testdata/policy.properties +++ /dev/null @@ -1,2 +0,0 @@ -default=url-host -sites=[{url=tva1.moyu.im, refer=i.jandan.net}] diff --git a/testdata/policy.yml b/testdata/policy.yml new file mode 100644 index 00000000..15aeebe1 --- /dev/null +++ b/testdata/policy.yml @@ -0,0 +1,4 @@ +default: url-host +sites: + - url: tva1.moyu.im + refer: i.jandan.net From ee20b4ea74db92701f3174f77ec63826519cd857 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 7 Feb 2023 15:28:19 +0800 Subject: [PATCH 05/15] fix --- .gitignore | 1 + imaginary.go | 27 +++++++++----------- source_http.go | 6 ++--- source_http_test.go | 61 ++++++++++++++++++++++++++++++++++++++++++--- testdata/policy.yml | 2 ++ 5 files changed, 75 insertions(+), 22 deletions(-) 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/imaginary.go b/imaginary.go index 73e75852..c6563b7f 100644 --- a/imaginary.go +++ b/imaginary.go @@ -139,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, @@ -167,7 +172,7 @@ func main() { MaxAllowedPixels: *aMaxAllowedPixels, LogLevel: getLogLevel(*aLogLevel), ReturnSize: *aReturnSize, - ReferrerPolicy: parseReferrerPolicy(*aReferrerPolicy), + ReferrerPolicy: referrerPolicy, } // Show warning if gzip flag is passed @@ -262,17 +267,10 @@ var ( // DefaultConfigFiles is the file names from which we attempt to read configuration. DefaultConfigFiles = []string{"config.yml", "config.yaml"} - // DefaultUnixConfigLocation is the primary location to find a config file - DefaultUnixConfigLocation = "/usr/local/etc/imaginary" - - // Launchd doesn't set root env variables, so there is default - // Windows default config dir was ~/cloudflare-warp in documentation; let's keep it compatible - defaultNixConfigDirs = []string{"/etc/imaginary", DefaultUnixConfigLocation} - - ErrNoConfigFile = fmt.Errorf("Cannot determine default configuration path. No file %v in %v", DefaultConfigFiles, defaultNixConfigDirs) + ErrNoConfigFile = fmt.Errorf("Cannot determine default configuration path. No file %v ", DefaultConfigFiles) ) -func parseReferrerPolicy(s string) ReferrerPolicy { +func parseReferrerPolicy(s string) (ReferrerPolicy, error) { defaultPolicy := NoReferrer policy := ReferrerPolicy{ Default: defaultPolicy, @@ -296,18 +294,17 @@ func parseReferrerPolicy(s string) ReferrerPolicy { if os.IsNotExist(err) { err = ErrNoConfigFile } - log.Fatalf("Configuration file %s was not existed", s) + return policy, fmt.Errorf("referrer policy file %s was not existed", s) } defer file.Close() if err := yaml.NewDecoder(file).Decode(&policy); err != nil { if err == io.EOF { - log.Fatalf("Configuration file %s was empty", s) - return policy + return policy, fmt.Errorf("referrer policy file %s was empty", s) } - log.Fatalf("error parsing YAML in config file at "+s+"with error: %s", err) + return policy, fmt.Errorf("error parsing YAML in referrer policy file at "+s+"with error: %s", err) } } - return policy + return policy, nil } func showUsage() { diff --git a/source_http.go b/source_http.go index 688cc443..91516e0d 100644 --- a/source_http.go +++ b/source_http.go @@ -101,12 +101,12 @@ func (s *HTTPImageSource) setRefererHeader(req *http.Request, ireq *http.Request policy := s.Config.ReferrerPolicy if len(policy.Sites) != 0 { for _, site := range policy.Sites { - match, err := filepath.Match(url.String(), site.URL) + match, err := filepath.Match(site.URL, url.Host) if err != nil { return } if match { - req.Header.Set("Referer", site.Refer) + req.Header.Set("Referer", url.Scheme+"://"+site.Refer) return } } @@ -141,7 +141,7 @@ func newHTTPRequest(s *HTTPImageSource, ireq *http.Request, method string, url * s.setAuthorizationHeader(req, ireq) } - if s.Config.ReferrerPolicy.Default != "" { + if s.Config.ReferrerPolicy.Default != NoReferrer { s.setRefererHeader(req, ireq, url) } diff --git a/source_http_test.go b/source_http_test.go index 76df46c9..9cf07350 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,7 +11,7 @@ import ( const fixtureImage = "testdata/large.jpg" const fixture1024Bytes = "testdata/1024bytes" -const fixturePolicyFile = "testdata/policy.yaml" +const fixturePolicyFile = "testdata/policy.yml" func TestHttpImageSource(t *testing.T) { var body []byte @@ -359,9 +360,61 @@ func TestHttpImageSourceUrlDirReferrerHeader(t *testing.T) { } } -//func TestHttpImageSourceSiteFileReferrerHeader(t *testing.T) { -// -//} +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 index 15aeebe1..0e38bf33 100644 --- a/testdata/policy.yml +++ b/testdata/policy.yml @@ -2,3 +2,5 @@ default: url-host sites: - url: tva1.moyu.im refer: i.jandan.net + - url: "*.moyu.im" + refer: jandan.net \ No newline at end of file From dd589c29c09b3981477b09bf10bbdf18f29f59e4 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 7 Feb 2023 16:51:11 +0800 Subject: [PATCH 06/15] golint fix --- imaginary.go | 19 ++++++------------- server.go | 6 ++---- source_http.go | 4 ++-- source_http_test.go | 4 ++-- 4 files changed, 12 insertions(+), 21 deletions(-) diff --git a/imaginary.go b/imaginary.go index c6563b7f..25c79447 100644 --- a/imaginary.go +++ b/imaginary.go @@ -263,13 +263,6 @@ func getLogLevel(logLevel string) string { return logLevel } -var ( - // DefaultConfigFiles is the file names from which we attempt to read configuration. - DefaultConfigFiles = []string{"config.yml", "config.yaml"} - - ErrNoConfigFile = fmt.Errorf("Cannot determine default configuration path. No file %v ", DefaultConfigFiles) -) - func parseReferrerPolicy(s string) (ReferrerPolicy, error) { defaultPolicy := NoReferrer policy := ReferrerPolicy{ @@ -277,10 +270,10 @@ func parseReferrerPolicy(s string) (ReferrerPolicy, error) { } switch s { - case UrlHostReferrer: - policy.Default = UrlHostReferrer - case UrlDirReferrer: - policy.Default = UrlDirReferrer + case URLHostReferrer: + policy.Default = URLHostReferrer + case URLDirReferrer: + policy.Default = URLDirReferrer case OriginReferrer: policy.Default = OriginReferrer case UnsafeReferrer: @@ -292,9 +285,9 @@ func parseReferrerPolicy(s string) (ReferrerPolicy, error) { if err != nil { // If does not exist and config file was not specificly specified then return ErrNoConfigFile found. if os.IsNotExist(err) { - err = ErrNoConfigFile + return policy, fmt.Errorf("referrer policy file %s is not existed", s) } - return policy, fmt.Errorf("referrer policy file %s was 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 { diff --git a/server.go b/server.go index ffc25ea2..eae32837 100644 --- a/server.go +++ b/server.go @@ -55,9 +55,8 @@ const ( NoReferrer = "no" OriginReferrer = "origin" UnsafeReferrer = "unsafe" - UrlHostReferrer = "url-host" - UrlDirReferrer = "url-dir" - SiteReferrer = "site" + URLHostReferrer = "url-host" + URLDirReferrer = "url-dir" ) type ReferrerSite struct { @@ -70,7 +69,6 @@ type ReferrerPolicy struct { 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, "/") diff --git a/source_http.go b/source_http.go index 91516e0d..35bd2d4f 100644 --- a/source_http.go +++ b/source_http.go @@ -112,9 +112,9 @@ func (s *HTTPImageSource) setRefererHeader(req *http.Request, ireq *http.Request } } switch policy.Default { - case UrlHostReferrer: + case URLHostReferrer: req.Header.Set("Referer", url.Scheme+"://"+url.Host) - case UrlDirReferrer: + 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) diff --git a/source_http_test.go b/source_http_test.go index 9cf07350..ee353434 100755 --- a/source_http_test.go +++ b/source_http_test.go @@ -316,7 +316,7 @@ func TestHttpImageSourceOriginReferrerHeader(t *testing.T) { func TestHttpImageSourceUrlHostReferrerHeader(t *testing.T) { policy := ReferrerPolicy{ - Default: UrlHostReferrer, + Default: URLHostReferrer, } u := "http://bar.com/a/img" u1, _ := url.Parse(u) @@ -339,7 +339,7 @@ func TestHttpImageSourceUrlHostReferrerHeader(t *testing.T) { func TestHttpImageSourceUrlDirReferrerHeader(t *testing.T) { policy := ReferrerPolicy{ - Default: UrlDirReferrer, + Default: URLDirReferrer, } u := "http://bar.com/a/img" u1, _ := url.Parse(u) From ecbed3c44ee63f580e9cde7daf9592041d9bb761 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 7 Feb 2023 17:21:16 +0800 Subject: [PATCH 07/15] fix bad cond --- source_http.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source_http.go b/source_http.go index 35bd2d4f..254b7b5f 100644 --- a/source_http.go +++ b/source_http.go @@ -46,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) } From 126893a38661cb072cf9dca5ee44132035de3c5c Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 7 Feb 2023 17:22:44 +0800 Subject: [PATCH 08/15] VOL add --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index c7ba5de4..1ee098c6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -95,6 +95,8 @@ ENV PORT 9000 # Drop privileges for non-UID mapped environments USER nobody +VOLUME /config + # Run the entrypoint command by default when the container starts. ENTRYPOINT ["/usr/local/bin/imaginary"] From 1d0fd9e451b3cfc8e507a35987ec281edb9be29e Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Sun, 12 Feb 2023 00:27:52 +0800 Subject: [PATCH 09/15] ok for imaginary --- Dockerfile | 65 +++++++++++++++++++++++++++++++++++---------------- error.go | 2 +- middleware.go | 2 +- server.go | 2 +- 4 files changed, 48 insertions(+), 23 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1ee098c6..bf599497 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,35 +1,59 @@ -ARG GOLANG_VERSION=1.17 +# syntax=docker/dockerfile:1.4 + +ARG GOLANG_VERSION=1.19 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 < Date: Sun, 12 Feb 2023 12:27:06 +0800 Subject: [PATCH 10/15] add avif support --- README.md | 1 + controllers.go | 2 ++ options.go | 5 +++++ type.go | 4 ++++ type_test.go | 3 +++ 5 files changed, 15 insertions(+) diff --git a/README.md b/README.md index 3aa65d15..d3400647 100644 --- a/README.md +++ b/README.md @@ -569,6 +569,7 @@ Image measures are always in pixels, unless otherwise indicated. - **areawidth** `int` - Height area to extract. Example: `300` - **areaheight** `int` - Width area to extract. Example: `300` - **quality** `int` - JPEG image quality between 1-100. Defaults to `80` +- **speed** `int` - Defines the AVIF encoders CPU effort. Valid values are 0-8. Default `0` - **compression** `int` - PNG compression level. Default: `6` - **palette** `bool` - Enable 8-bit quantisation. Works with only PNG images. Default: `false` - **rotate** `int` - Image rotation angle. Must be multiple of `90`. Example: `180` diff --git a/controllers.go b/controllers.go index 1de48b55..2f2b7417 100644 --- a/controllers.go +++ b/controllers.go @@ -70,6 +70,8 @@ func determineAcceptMimeType(accept string) string { switch mediaType { case "image/webp": return "webp" + case "image/avif": + return "avif" case "image/png": return "png" case "image/jpeg": diff --git a/options.go b/options.go index bc639c59..b56446d9 100644 --- a/options.go +++ b/options.go @@ -168,5 +168,10 @@ func BimgOptions(o ImageOptions) bimg.Options { } } + if opts.Type == bimg.AVIF { + opts.Speed = 6 + opts.Quality = 60 + } + return opts } 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"}, From 38b390d71fde1ec8628dec934db0a2e94ffa7529 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Sun, 12 Feb 2023 17:13:15 +0800 Subject: [PATCH 11/15] update some --- controllers.go | 4 ++-- options.go | 5 ----- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/controllers.go b/controllers.go index 2f2b7417..1da8d032 100644 --- a/controllers.go +++ b/controllers.go @@ -70,8 +70,8 @@ func determineAcceptMimeType(accept string) string { switch mediaType { case "image/webp": return "webp" - case "image/avif": - return "avif" + //case "image/avif": + // return "avif" case "image/png": return "png" case "image/jpeg": diff --git a/options.go b/options.go index b56446d9..bc639c59 100644 --- a/options.go +++ b/options.go @@ -168,10 +168,5 @@ func BimgOptions(o ImageOptions) bimg.Options { } } - if opts.Type == bimg.AVIF { - opts.Speed = 6 - opts.Quality = 60 - } - return opts } From 3abf02f9a21c6c25c861570ea2ff98af63a63793 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Sun, 12 Feb 2023 17:20:05 +0800 Subject: [PATCH 12/15] update some --- controllers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers.go b/controllers.go index 1da8d032..e7ec39e8 100644 --- a/controllers.go +++ b/controllers.go @@ -70,7 +70,7 @@ func determineAcceptMimeType(accept string) string { switch mediaType { case "image/webp": return "webp" - //case "image/avif": + // case "image/avif": // return "avif" case "image/png": return "png" From 5ced92895319c55d29d46905b7920e1fd27e24be Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Mon, 20 Mar 2023 17:46:37 +0800 Subject: [PATCH 13/15] add COmpress-Rate --- controllers.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/controllers.go b/controllers.go index e7ec39e8..ae013336 100644 --- a/controllers.go +++ b/controllers.go @@ -94,6 +94,11 @@ func imageHandler(w http.ResponseWriter, r *http.Request, buf []byte, operation } } + // Use magick to process bmp image + if mimeType == "image/bmp" { + mimeType = "image/magick" + } + // Infer text/plain responses as potential SVG image if strings.Contains(mimeType, "text/plain") && len(buf) > 8 { if bimg.IsSVGImage(buf) { @@ -150,11 +155,14 @@ 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 != "" { From 0d0c3848dee4221a4f0ba262a6db5404e04783e7 Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Mon, 20 Mar 2023 19:33:32 +0800 Subject: [PATCH 14/15] controller ok --- controllers.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/controllers.go b/controllers.go index ae013336..2358da5d 100644 --- a/controllers.go +++ b/controllers.go @@ -143,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 } @@ -162,12 +164,9 @@ func imageHandler(w http.ResponseWriter, r *http.Request, buf []byte, operation 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) } From 7458a6b0a061dad4e903841e7094a610ada3441b Mon Sep 17 00:00:00 2001 From: Felix Xu Date: Tue, 21 Mar 2023 11:01:20 +0800 Subject: [PATCH 15/15] ok for compression rate --- controllers.go | 1 + 1 file changed, 1 insertion(+) diff --git a/controllers.go b/controllers.go index 2358da5d..6260d0c2 100644 --- a/controllers.go +++ b/controllers.go @@ -165,6 +165,7 @@ func imageHandler(w http.ResponseWriter, r *http.Request, buf []byte, operation 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)))) } _, _ = w.Write(image.Body)