Debian Codegraph @

modules/caddyhttp/intercept/intercept.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package intercept
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "net/http"
22 "strconv"
23 "strings"
24 "sync"
25
26 "go.uber.org/zap"
27 "go.uber.org/zap/zapcore"
28
29 "github.com/caddyserver/caddy/v2"
30 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
31 "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
32 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
33 )
34
35 func init() {
36 caddy.RegisterModule(Intercept{})
37 httpcaddyfile.RegisterHandlerDirective("intercept", parseCaddyfile)
38 }
39
40 // Intercept is a middleware that intercepts then replaces or modifies the original response.
41 // It can, for instance, be used to implement X-Sendfile/X-Accel-Redirect-like features
42 // when using modules like FrankenPHP or Caddy Snake.
43 //
44 // EXPERIMENTAL: Subject to change or removal.
45 type Intercept struct {
46 // List of handlers and their associated matchers to evaluate
47 // after successful response generation.
48 // The first handler that matches the original response will
49 // be invoked. The original response body will not be
50 // written to the client;
51 // it is up to the handler to finish handling the response.
52 //
53 // Three new placeholders are available in this handler chain:
54 // - `{http.intercept.status_code}` The status code from the response
55 // - `{http.intercept.header.*}` The headers from the response
56 HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"`
57
58 // Holds the named response matchers from the Caddyfile while adapting
59 responseMatchers map[string]caddyhttp.ResponseMatcher
60
61 // Holds the handle_response Caddyfile tokens while adapting
62 handleResponseSegments []*caddyfile.Dispenser
63
64 logger *zap.Logger
65 }
66
67 // CaddyModule returns the Caddy module information.
68 //
69 // EXPERIMENTAL: Subject to change or removal.
70 func (Intercept) CaddyModule() caddy.ModuleInfo {
71 return caddy.ModuleInfo{
72 ID: "http.handlers.intercept",
73 New: func() caddy.Module { return new(Intercept) },
74 }
75 }
76
77 // Provision ensures that i is set up properly before use.
78 //
79 // EXPERIMENTAL: Subject to change or removal.
80 func (irh *Intercept) Provision(ctx caddy.Context) error {
81 // set up any response routes
82 for i, rh := range irh.HandleResponse {
83 err := rh.Provision(ctx)
84 if err != nil {
85 return fmt.Errorf("provisioning response handler %d: %w", i, err)
86 }
87 }
88
89 irh.logger = ctx.Logger()
90
91 return nil
92 }
93
94 var bufPool = sync.Pool{
95 New: func() any {
96 return new(bytes.Buffer)
97 },
98 }
99
100 // TODO: handle status code replacement
101 //
102 // EXPERIMENTAL: Subject to change or removal.
103 type interceptedResponseHandler struct {
104 caddyhttp.ResponseRecorder
105 replacer *caddy.Replacer
106 handler caddyhttp.ResponseHandler
107 handlerIndex int
108 statusCode int
109 }
110
111 // EXPERIMENTAL: Subject to change or removal.
112 func (irh interceptedResponseHandler) WriteHeader(statusCode int) {
113 if irh.statusCode != 0 && (statusCode < 100 || statusCode >= 200) {
114 irh.ResponseRecorder.WriteHeader(irh.statusCode)
115
116 return
117 }
118
119 irh.ResponseRecorder.WriteHeader(statusCode)
120 }
121
122 // EXPERIMENTAL: Subject to change or removal.
123 func (irh interceptedResponseHandler) Unwrap() http.ResponseWriter {
124 return irh.ResponseRecorder
125 }
126
127 // EXPERIMENTAL: Subject to change or removal.
128 func (ir Intercept) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
129 buf := bufPool.Get().(*bytes.Buffer)
130 buf.Reset()
131 defer bufPool.Put(buf)
132
133 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
134 rec := interceptedResponseHandler{replacer: repl}
135 rec.ResponseRecorder = caddyhttp.NewResponseRecorder(w, buf, func(status int, header http.Header) bool {
136 // see if any response handler is configured for this original response
137 for i, rh := range ir.HandleResponse {
138 if rh.Match != nil && !rh.Match.Match(status, header) {
139 continue
140 }
141 rec.handler = rh
142 rec.handlerIndex = i
143
144 // if configured to only change the status code,
145 // do that then stream
146 if statusCodeStr := rh.StatusCode.String(); statusCodeStr != "" {
147 sc, err := strconv.Atoi(repl.ReplaceAll(statusCodeStr, ""))
148 if err != nil {
149 rec.statusCode = http.StatusInternalServerError
150 } else {
151 rec.statusCode = sc
152 }
153 }
154
155 return rec.statusCode == 0
156 }
157
158 return false
159 })
160
161 if err := next.ServeHTTP(rec, r); err != nil {
162 return err
163 }
164 if !rec.Buffered() {
165 return nil
166 }
167
168 // set up the replacer so that parts of the original response can be
169 // used for routing decisions
170 for field, value := range rec.Header() {
171 repl.Set("http.intercept.header."+field, strings.Join(value, ","))
172 }
173 repl.Set("http.intercept.status_code", rec.Status())
174
175 if c := ir.logger.Check(zapcore.DebugLevel, "handling response"); c != nil {
176 c.Write(zap.Int("handler", rec.handlerIndex))
177 }
178
179 // response recorder doesn't create a new copy of the original headers, they're
180 // present in the original response writer
181 // create a new recorder to see if any response body from the new handler is present,
182 // if not, use the already buffered response body
183 recorder := caddyhttp.NewResponseRecorder(w, nil, nil)
184 if err := rec.handler.Routes.Compile(emptyHandler).ServeHTTP(recorder, r); err != nil {
185 return err
186 }
187
188 // no new response status and the status is not 0
189 if recorder.Status() == 0 && rec.Status() != 0 {
190 w.WriteHeader(rec.Status())
191 }
192
193 // no new response body and there is some in the original response
194 // TODO: what if the new response doesn't have a body by design?
195 // see: https://github.com/caddyserver/caddy/pull/6232#issue-2235224400
196 if recorder.Size() == 0 && buf.Len() > 0 {
197 _, err := io.Copy(w, buf)
198 return err
199 }
200 return nil
201 }
202
203 // this handler does nothing because everything we need is already buffered
204 var emptyHandler caddyhttp.Handler = caddyhttp.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) error {
205 return nil
206 })
207
208 // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax:
209 //
210 // intercept [<matcher>] {
211 // # intercept original responses
212 // @name {
213 // status <code...>
214 // header <field> [<value>]
215 // }
216 // replace_status [<matcher>] <status_code>
217 // handle_response [<matcher>] {
218 // <directives...>
219 // }
220 // }
221 //
222 // The FinalizeUnmarshalCaddyfile method should be called after this
223 // to finalize parsing of "handle_response" blocks, if possible.
224 //
225 // EXPERIMENTAL: Subject to change or removal.
226 func (i *Intercept) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
227 // collect the response matchers defined as subdirectives
228 // prefixed with "@" for use with "handle_response" blocks
229 i.responseMatchers = make(map[string]caddyhttp.ResponseMatcher)
230
231 d.Next() // consume the directive name
232 for d.NextBlock(0) {
233 // if the subdirective has an "@" prefix then we
234 // parse it as a response matcher for use with "handle_response"
235 if strings.HasPrefix(d.Val(), matcherPrefix) {
236 err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), i.responseMatchers)
237 if err != nil {
238 return err
239 }
240 continue
241 }
242
243 switch d.Val() {
244 case "handle_response":
245 // delegate the parsing of handle_response to the caller,
246 // since we need the httpcaddyfile.Helper to parse subroutes.
247 // See h.FinalizeUnmarshalCaddyfile
248 i.handleResponseSegments = append(i.handleResponseSegments, d.NewFromNextSegment())
249
250 case "replace_status":
251 args := d.RemainingArgs()
252 if len(args) != 1 && len(args) != 2 {
253 return d.Errf("must have one or two arguments: an optional response matcher, and a status code")
254 }
255
256 responseHandler := caddyhttp.ResponseHandler{}
257
258 if len(args) == 2 {
259 if !strings.HasPrefix(args[0], matcherPrefix) {
260 return d.Errf("must use a named response matcher, starting with '@'")
261 }
262 foundMatcher, ok := i.responseMatchers[args[0]]
263 if !ok {
264 return d.Errf("no named response matcher defined with name '%s'", args[0][1:])
265 }
266 responseHandler.Match = &foundMatcher
267 responseHandler.StatusCode = caddyhttp.WeakString(args[1])
268 } else if len(args) == 1 {
269 responseHandler.StatusCode = caddyhttp.WeakString(args[0])
270 }
271
272 // make sure there's no block, cause it doesn't make sense
273 if nesting := d.Nesting(); d.NextBlock(nesting) {
274 return d.Errf("cannot define routes for 'replace_status', use 'handle_response' instead.")
275 }
276
277 i.HandleResponse = append(
278 i.HandleResponse,
279 responseHandler,
280 )
281
282 default:
283 return d.Errf("unrecognized subdirective %s", d.Val())
284 }
285 }
286
287 return nil
288 }
289
290 // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which
291 // requires having an httpcaddyfile.Helper to function, to parse subroutes.
292 //
293 // EXPERIMENTAL: Subject to change or removal.
294 func (i *Intercept) FinalizeUnmarshalCaddyfile(helper httpcaddyfile.Helper) error {
295 for _, d := range i.handleResponseSegments {
296 // consume the "handle_response" token
297 d.Next()
298 args := d.RemainingArgs()
299
300 // TODO: Remove this check at some point in the future
301 if len(args) == 2 {
302 return d.Errf("configuring 'handle_response' for status code replacement is no longer supported. Use 'replace_status' instead.")
303 }
304
305 if len(args) > 1 {
306 return d.Errf("too many arguments for 'handle_response': %s", args)
307 }
308
309 var matcher *caddyhttp.ResponseMatcher
310 if len(args) == 1 {
311 // the first arg should always be a matcher.
312 if !strings.HasPrefix(args[0], matcherPrefix) {
313 return d.Errf("must use a named response matcher, starting with '@'")
314 }
315
316 foundMatcher, ok := i.responseMatchers[args[0]]
317 if !ok {
318 return d.Errf("no named response matcher defined with name '%s'", args[0][1:])
319 }
320 matcher = &foundMatcher
321 }
322
323 // parse the block as routes
324 handler, err := httpcaddyfile.ParseSegmentAsSubroute(helper.WithDispenser(d.NewFromNextSegment()))
325 if err != nil {
326 return err
327 }
328 subroute, ok := handler.(*caddyhttp.Subroute)
329 if !ok {
330 return helper.Errf("segment was not parsed as a subroute")
331 }
332 i.HandleResponse = append(
333 i.HandleResponse,
334 caddyhttp.ResponseHandler{
335 Match: matcher,
336 Routes: subroute.Routes,
337 },
338 )
339 }
340
341 // move the handle_response entries without a matcher to the end.
342 // we can't use sort.SliceStable because it will reorder the rest of the
343 // entries which may be undesirable because we don't have a good
344 // heuristic to use for sorting.
345 withoutMatchers := []caddyhttp.ResponseHandler{}
346 withMatchers := []caddyhttp.ResponseHandler{}
347 for _, hr := range i.HandleResponse {
348 if hr.Match == nil {
349 withoutMatchers = append(withoutMatchers, hr)
350 } else {
351 withMatchers = append(withMatchers, hr)
352 }
353 }
354 i.HandleResponse = append(withMatchers, withoutMatchers...)
355
356 // clean up the bits we only needed for adapting
357 i.handleResponseSegments = nil
358 i.responseMatchers = nil
359
360 return nil
361 }
362
363 const matcherPrefix = "@"
364
365 func parseCaddyfile(helper httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
366 var ir Intercept
367 if err := ir.UnmarshalCaddyfile(helper.Dispenser); err != nil {
368 return nil, err
369 }
370
371 if err := ir.FinalizeUnmarshalCaddyfile(helper); err != nil {
372 return nil, err
373 }
374
375 return ir, nil
376 }
377
378 // Interface guards
379 var (
380 _ caddy.Provisioner = (*Intercept)(nil)
381 _ caddyfile.Unmarshaler = (*Intercept)(nil)
382 _ caddyhttp.MiddlewareHandler = (*Intercept)(nil)
383 )