-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule.go
291 lines (246 loc) · 7.17 KB
/
module.go
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
package CADDY_FILE_SERVER
import (
"bytes"
"cmp"
"errors"
"fmt"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/h2non/bimg"
"github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/zstd"
"go.uber.org/zap"
"io"
"net/http"
"strconv"
)
func init() {
caddy.RegisterModule(&Middleware{})
httpcaddyfile.RegisterHandlerDirective("image_processor", parseCaddyfile)
httpcaddyfile.RegisterDirectiveOrder("image_processor", "before", "respond")
}
// OnFail represents the possible values for the "on_fail" directive.
type OnFail string
const (
// OnFailAbort returns a 500 Internal Server Error to the client.
OnFailAbort OnFail = "abort"
// OnFailBypass forces the response to return the initial (unprocessed) image.
OnFailBypass OnFail = "bypass"
)
// Middleware allow user to do image processing on the fly using libvips
// With simple queries parameters you can resize, convert, crop your served images
type Middleware struct {
logger *zap.Logger
OnFail OnFail `json:"on_fail,omitempty"`
Security *SecurityOptions `json:"security,omitempty"`
}
func (*Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.image_processor",
New: func() caddy.Module { return new(Middleware) },
}
}
func (m *Middleware) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger()
// Set default configuration
m.OnFail = cmp.Or(m.OnFail, OnFailBypass)
if m.Security != nil {
if err := m.Security.Provision(ctx); err != nil {
return err
}
}
return nil
}
func (m *Middleware) Validate() error {
switch m.OnFail {
case OnFailAbort, OnFailBypass:
// Valid values
default:
return fmt.Errorf("invalid value for on_fail: '%s' (expected 'abort', or 'bypass')", m.OnFail)
}
if m.Security != nil {
if err := m.Security.Validate(); err != nil {
return err
}
}
return nil
}
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
//Automatic return if not options set
if r.URL.RawQuery == "" {
return next.ServeHTTP(w, r)
}
responseRecorder := caddyhttp.NewResponseRecorder(w, &bytes.Buffer{}, func(status int, header http.Header) bool {
return true
})
if err := next.ServeHTTP(responseRecorder, r); err != nil {
return err
}
if responseRecorder.Status() != 200 || responseRecorder.Size() == 0 {
return responseRecorder.WriteResponse()
}
decoded, err := m.getDecodedBufferFromResponse(&responseRecorder)
if err != nil {
m.logger.Error("error getting initial response", zap.Error(err))
return responseRecorder.WriteResponse()
}
// Extract form request
if err := r.ParseForm(); err != nil {
return errors.Join(errors.New("failed to parse form"), err)
}
// Remove unsupported query parameters
filterForm(&r.Form)
// Return if no parameters remains
if len(r.Form) == 0 {
return responseRecorder.WriteResponse()
}
// Send to security middleware if defined
if m.Security != nil {
if err := m.Security.ProcessRequestForm(&r.Form); err != nil {
if errors.Is(err, BypassRequestError) {
return responseRecorder.WriteResponse()
}
var abortRequestError *AbortRequestError
if errors.As(err, &abortRequestError) {
http.Error(w, err.Error(), http.StatusBadRequest)
return nil
}
return err
}
// Return initial image if no parameters remains
if len(r.Form) == 0 {
return responseRecorder.WriteResponse()
}
}
// Generate specific ETag if necessary
processedEtag := getProcessedImageEtag(responseRecorder.Header().Get("ETag"), &r.Form)
if processedEtag != "" {
responseRecorder.Header().Del("ETag") // Remove initial ETag
w.Header().Set("ETag", processedEtag)
// Check If-None-Match header to avoid reprocessing
ifNoneMatchHeader := r.Header.Get("If-None-Match")
if ifNoneMatchHeader != "" && ifNoneMatchHeader == processedEtag {
w.WriteHeader(http.StatusNotModified)
return nil
}
}
// Parse options
options, err := getOptions(&r.Form)
if err != nil {
m.logger.Error("error parsing options", zap.Error(err))
return responseRecorder.WriteResponse()
}
newImage, err := bimg.NewImage(decoded).Process(options)
if err != nil {
m.logger.Error("error processing image", zap.Error(err))
if m.OnFail == OnFailBypass {
return responseRecorder.WriteResponse()
}
if m.OnFail == OnFailAbort {
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
return err
}
// Remove proxied invalid header
w.Header().Del("Content-Type")
w.Header().Del("Content-Length")
w.Header().Del("Content-Encoding")
w.Header().Del("Vary")
// Set new headers
w.Header().Set("Content-Length", strconv.Itoa(len(newImage)))
w.Header().Set("Content-Type", "image/"+bimg.DetermineImageTypeName(newImage))
if _, err = w.Write(newImage); err != nil {
m.logger.Error("error writing processed image", zap.Error(err))
if m.OnFail == OnFailBypass {
return responseRecorder.WriteResponse()
}
if m.OnFail == OnFailAbort {
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
return err
}
return nil
}
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
for d.NextBlock(0) {
switch d.Val() {
case "on_fail":
// Check if argument provided
if !d.NextArg() {
return d.ArgErr()
}
m.OnFail = OnFail(d.Val())
// Ensure there are no more arguments
if d.NextArg() {
return d.ArgErr() // More than one argument provided
}
break
case "security":
m.Security = &SecurityOptions{}
if err := m.Security.UnmarshalCaddyfile(d); err != nil {
return err
}
break
default:
return d.Errf("unexpected directive '%s' in image_processor block", d.Val())
}
}
}
return nil
}
func (m *Middleware) getDecodedBufferFromResponse(r *caddyhttp.ResponseRecorder) ([]byte, error) {
encoding := (*r).Header().Get("Content-Encoding")
if encoding == "" {
return (*r).Buffer().Bytes(), nil
}
if encoding == "gzip" {
decoder, err := gzip.NewReader((*r).Buffer())
if err != nil {
return nil, err
}
defer func(decoder *gzip.Reader) {
err := decoder.Close()
if err != nil {
return
}
}(decoder)
decodedOut := bytes.Buffer{}
_, err = io.Copy(&decodedOut, decoder)
if err != nil {
return nil, err
}
return decodedOut.Bytes(), nil
}
if encoding == "zstd" {
// Try decode zstd
var decoder, err = zstd.NewReader((*r).Buffer(), zstd.WithDecoderConcurrency(0))
if err != nil {
return nil, err
}
defer decoder.Close()
decodedOut := bytes.Buffer{}
_, err = io.Copy(&decodedOut, decoder)
if err != nil {
return nil, err
}
return decodedOut.Bytes(), nil
}
return nil, fmt.Errorf("unsupported encoding: %s", encoding)
}
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m Middleware
err := m.UnmarshalCaddyfile(h.Dispenser)
return &m, err
}
// Interface guards
var (
_ caddy.Provisioner = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
)