forked from willnorris/imageproxy
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimageproxy.go
More file actions
432 lines (355 loc) · 11.3 KB
/
imageproxy.go
File metadata and controls
432 lines (355 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Package imageproxy provides an image proxy server. For typical use of
// creating and using a Proxy, see cmd/imageproxy/main.go.
package imageproxy
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/gregjones/httpcache"
"go.uber.org/zap"
tphttp "github.com/richiefi/imageproxy/third_party/http"
)
const cacheTags = "imageproxy,imageproxy-1"
// Overridden in prod by linker
var buildVersion = "dev"
// Proxy serves image requests.
type Proxy struct {
logger *zap.SugaredLogger
Client *http.Client // client used to fetch remote URLs
Cache Cache // cache used to cache responses
// Whitelist specifies a list of remote hosts that images can be
// proxied from. An empty list means all hosts are allowed.
Whitelist []string
// Referrers, when given, requires that requests to the image
// proxy come from a referring host. An empty list means all
// hosts are allowed.
Referrers []string
PrefixesToConfigs map[string]*SourceConfiguration
// SignatureKey is the HMAC key used to verify signed requests.
SignatureKey []byte
// Allow images to scale beyond their original dimensions.
ScaleUp bool
// Timeout specifies a time limit for requests served by this Proxy.
// If a call runs for longer than its time limit, a 504 Gateway Timeout
// response is returned. A Timeout of zero means no timeout.
Timeout time.Duration
}
// NewProxy constructs a new proxy. The provided http RoundTripper will be
// used to fetch remote URLs. If nil is provided, http.DefaultTransport will
// be used.
func NewProxy(transport http.RoundTripper, cache Cache, maxConcurrency int, logger *zap.SugaredLogger) *Proxy {
logger.Infow("Initializing imageproxy",
"buildVersion", buildVersion,
)
if transport == nil {
transport = http.DefaultTransport
}
if cache == nil {
cache = NopCache
}
proxy := &Proxy{
Cache: cache,
logger: logger,
}
pool := make(chan bool, maxConcurrency)
client := new(http.Client)
client.Transport = &httpcache.Transport{
Transport: &TransformingTransport{
Transport: transport,
CachingClient: client,
logger: logger,
pool: pool,
},
Cache: cache,
MarkCachedResponses: true,
}
proxy.Client = client
proxy.Client.Timeout = 10 * time.Second
return proxy
}
// ServeHTTP handles incoming requests.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Respond to health checks
if r.URL.Path == "/" || r.URL.Path == "/health-check" {
fmt.Fprint(w, "OK")
return
}
// Ignore certain urls without actually parsing them
if r.URL.Path == "/favicon.ico" || r.URL.Path == "/apple-touch-icon.png" || r.URL.Path == "/apple-touch-icon-precomposed.png" {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Not found")
return
}
var h http.Handler = http.HandlerFunc(p.serveImage)
if p.Timeout > 0 {
h = tphttp.TimeoutHandler(h, p.Timeout, "Gateway timeout waiting for remote resource.")
}
h = WithLogging(h, p.logger)
h.ServeHTTP(w, r)
}
// serveImage handles incoming requests for proxied images.
func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
req, err := NewRequest(r, p.PrefixesToConfigs)
if err != nil {
p.logger.Infow("invalid request URL",
"error", err.Error(),
)
msg := fmt.Sprintf("invalid request URL: %s", err.Error())
http.Error(w, msg, http.StatusBadRequest)
return
}
// assign static settings from proxy to req.Options
req.Options.ScaleUp = p.ScaleUp
if err := p.allowed(req); err != nil {
p.logger.Infow("Generated request did not pass validation",
"error", err.Error(),
"req.URL", req.URL,
)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
resp, err := p.Client.Get(req.String())
if err != nil {
p.logger.Infow("Error fetching a remote image",
"error", err.Error(),
"req.String()", req.String(),
)
msg := fmt.Sprintf("error fetching remote image: %s", err.Error())
http.Error(w, msg, http.StatusInternalServerError)
return
}
defer resp.Body.Close()
cached := resp.Header.Get(httpcache.XFromCache)
p.logger.Debugw("About to respond",
"req.String()", req.String(),
"from cache", cached == "1",
)
copyHeader(w.Header(), resp.Header, "Cache-Control", "Last-Modified", "Expires", "Link")
// Set Cache-Tag values to make it possible to detect and purge responses created by this app
resp.Header.Set("Cache-Tag", cacheTags)
// Enable CORS for 3rd party applications
w.Header().Set("Access-Control-Allow-Origin", "*")
// Etag business
remoteEtag := resp.Header.Get("Etag")
if remoteEtag != "" {
responseEtag := semanticEtag(remoteEtag, req.Options)
etagHeader := fmt.Sprintf(`W/"%s"`, responseEtag)
w.Header().Set("ETag", etagHeader)
if should304(r, responseEtag) {
w.WriteHeader(http.StatusNotModified)
return
}
}
// Move on with other-than-304 response
copyHeader(w.Header(), resp.Header, "Content-Length", "Content-Type")
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
// copyHeader copies header values from src to dst, adding to any existing
// values with the same header name. If keys is not empty, only those header
// keys will be copied.
func copyHeader(dst, src http.Header, keys ...string) {
if len(keys) == 0 {
for k, _ := range src {
keys = append(keys, k)
}
}
for _, key := range keys {
k := http.CanonicalHeaderKey(key)
for _, v := range src[k] {
dst.Add(k, v)
}
}
}
func semanticEtag(remoteEtag string, options Options) string {
h := md5.New()
fmt.Fprintf(h, "%s%s%s", remoteEtag, options.String(), buildVersion)
return fmt.Sprintf("%x", h.Sum(nil))
}
// allowed determines whether the specified request contains an allowed
// referrer, host, and signature. It returns an error if the request is not
// allowed.
func (p *Proxy) allowed(r *Request) error {
if len(p.Referrers) > 0 && !validReferrer(p.Referrers, r.Original) {
return fmt.Errorf("request does not contain an allowed referrer: %v", r)
}
if len(p.Whitelist) == 0 && len(p.SignatureKey) == 0 {
return nil // no whitelist or signature key, all requests accepted
}
if len(p.Whitelist) > 0 && validHost(p.Whitelist, r.URL) {
return nil
}
if len(p.SignatureKey) > 0 && validSignature(p.SignatureKey, r) {
return nil
}
return fmt.Errorf("request does not contain an allowed host or valid signature: %v", r)
}
// validHost returns whether the host in u matches one of hosts.
func validHost(hosts []string, u *url.URL) bool {
for _, host := range hosts {
if u.Host == host {
return true
}
if strings.HasPrefix(host, "*.") && strings.HasSuffix(u.Host, host[2:]) {
return true
}
}
return false
}
// returns whether the referrer from the request is in the host list.
func validReferrer(hosts []string, r *http.Request) bool {
u, err := url.Parse(r.Header.Get("Referer"))
if err != nil { // malformed or blank header, just deny
return false
}
return validHost(hosts, u)
}
// validSignature returns whether the request signature is valid.
func validSignature(key []byte, r *Request) bool {
sig := r.Options.Signature
if m := len(sig) % 4; m != 0 { // add padding if missing
sig += strings.Repeat("=", 4-m)
}
got, err := base64.URLEncoding.DecodeString(sig)
if err != nil {
return false
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(r.URL.String()))
want := mac.Sum(nil)
return hmac.Equal(got, want)
}
func should304(req *http.Request, responseEtag string) bool {
if responseEtag == "" {
return false
}
ifNoneMatch := req.Header.Get("If-None-Match")
if ifNoneMatch == "" {
return false
}
candidates := strings.Split(ifNoneMatch, ",")
for _, candidate := range candidates {
stripped := strings.TrimSpace(candidate)
stripped = strings.TrimPrefix(stripped, "W/")
if stripped == responseEtag {
return true
}
}
return false
}
// TransformingTransport is an implementation of http.RoundTripper that
// optionally transforms images using the options specified in the request URL
// fragment.
type TransformingTransport struct {
// Transport is the underlying http.RoundTripper used to satisfy
// non-transform requests (those that do not include a URL fragment).
Transport http.RoundTripper
// CachingClient is used to fetch images to be resized. This client is
// used rather than Transport directly in order to ensure that
// responses are properly cached.
CachingClient *http.Client
logger *zap.SugaredLogger
pool chan bool
}
// RoundTrip implements the http.RoundTripper interface.
func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var err error
if req.URL.Fragment == "" {
// normal requests pass through, image transformations are signaled in Fragment at this point
t.logger.Debugw("Fetching remote URL",
"req.URL", req.URL,
)
return t.Transport.RoundTrip(req)
}
u := *req.URL
u.Fragment = ""
// Drop recognized options at this point, so they are not sent upstream
u.RawQuery, err = StripOurOptions(u.RawQuery)
if err != nil {
t.logger.Warnw("Unable to re-parse url query",
"u.RawQuery", u.RawQuery,
"error", err.Error(),
)
}
resp, err := t.CachingClient.Get(u.String())
if err != nil {
t.logger.Warnw("CachingClient returned an error",
"u", u,
"error", err.Error(),
)
return nil, err
}
defer resp.Body.Close()
// This should have the side effect of not caching errors
if resp.StatusCode >= 400 {
t.logger.Warnw("Erroneous status code, bail out asap",
"resp.StatusCode", resp.StatusCode,
)
return nil, fmt.Errorf("unexpected status code %d from upstream", resp.StatusCode)
}
responseEtag := resp.Header.Get("ETag")
if should304(req, responseEtag) {
// bare 304 response, full response will be used from cache
return &http.Response{StatusCode: http.StatusNotModified}, nil
}
/*
Limit concurrency of memory-intensive operations. Writing to a channel with a full buffer blocks...
so the following will limit the concurrency based on the buffer pool size.
Note that if the channel is nil this will deadlock, so the nil check is absolutely mandatory.
*/
if t.pool != nil {
t.pool <- true
defer func() { <-t.pool }() // unblock one writer eventually
} else {
t.logger.Infow("t.pool is nil, bad initialization?")
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.logger.Warnw("Error reading a response",
"u", u,
"error", err.Error(),
)
return nil, err
}
err = req.ParseForm()
if err != nil {
t.logger.Warnw("Error parsing query string",
"u", u,
"error", err.Error(),
)
return nil, err
}
opt := ParseOptions(req.URL.Fragment)
t.logger.Infow("Calling Transform",
"options fragment", req.URL.Fragment,
)
img, err := Transform(b, opt)
if err != nil {
t.logger.Warnw("Error transforming image",
"error", err.Error(),
"opt", opt,
)
img = b
}
// replay response with transformed image and updated content length
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s %s\n", resp.Proto, resp.Status)
resp.Header.WriteSubset(buf, map[string]bool{
"Content-Length": true,
// exclude Content-Type header if the format may have changed during transformation
"Content-Type": opt.Format != "" || resp.Header.Get("Content-Type") == "image/webp" || resp.Header.Get("Content-Type") == "image/tiff",
})
fmt.Fprintf(buf, "Content-Length: %d\n\n", len(img))
buf.Write(img)
return http.ReadResponse(bufio.NewReader(buf), req)
}