Debian Codegraph @

modules/caddyhttp/reverseproxy/forwardauth/caddyfile.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 forwardauth
16
17 import (
18 "encoding/json"
19 "net/http"
20 "sort"
21 "strings"
22
23 "github.com/caddyserver/caddy/v2"
24 "github.com/caddyserver/caddy/v2/caddyconfig"
25 "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
26 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
27 "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
29 "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
30 )
31
32 func init() {
33 httpcaddyfile.RegisterDirective("forward_auth", parseCaddyfile)
34 }
35
36 // parseCaddyfile parses the forward_auth directive, which has the same syntax
37 // as the reverse_proxy directive (in fact, the reverse_proxy's directive
38 // Unmarshaler is invoked by this function) but the resulting proxy is specially
39 // configured for most™️ auth gateways that support forward auth. The typical
40 // config which looks something like this:
41 //
42 // forward_auth auth-gateway:9091 {
43 // uri /authenticate?redirect=https://auth.example.com
44 // copy_headers Remote-User Remote-Email
45 // }
46 //
47 // is equivalent to a reverse_proxy directive like this:
48 //
49 // reverse_proxy auth-gateway:9091 {
50 // method GET
51 // rewrite /authenticate?redirect=https://auth.example.com
52 //
53 // header_up X-Forwarded-Method {method}
54 // header_up X-Forwarded-Uri {uri}
55 //
56 // @good status 2xx
57 // handle_response @good {
58 // request_header {
59 // Remote-User {http.reverse_proxy.header.Remote-User}
60 // Remote-Email {http.reverse_proxy.header.Remote-Email}
61 // }
62 // }
63 // }
64 func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) {
65 if !h.Next() {
66 return nil, h.ArgErr()
67 }
68
69 // if the user specified a matcher token, use that
70 // matcher in a route that wraps both of our routes;
71 // either way, strip the matcher token and pass
72 // the remaining tokens to the unmarshaler so that
73 // we can gain the rest of the reverse_proxy syntax
74 userMatcherSet, err := h.ExtractMatcherSet()
75 if err != nil {
76 return nil, err
77 }
78
79 // make a new dispenser from the remaining tokens so that we
80 // can reset the dispenser back to this point for the
81 // reverse_proxy unmarshaler to read from it as well
82 dispenser := h.NewFromNextSegment()
83
84 // create the reverse proxy handler
85 rpHandler := &reverseproxy.Handler{
86 // set up defaults for header_up; reverse_proxy already deals with
87 // adding the other three X-Forwarded-* headers, but for this flow,
88 // we want to also send along the incoming method and URI since this
89 // request will have a rewritten URI and method.
90 Headers: &headers.Handler{
91 Request: &headers.HeaderOps{
92 Set: http.Header{
93 "X-Forwarded-Method": []string{"{http.request.method}"},
94 "X-Forwarded-Uri": []string{"{http.request.uri}"},
95 },
96 },
97 },
98
99 // we always rewrite the method to GET, which implicitly
100 // turns off sending the incoming request's body, which
101 // allows later middleware handlers to consume it
102 Rewrite: &rewrite.Rewrite{
103 Method: "GET",
104 },
105
106 HandleResponse: []caddyhttp.ResponseHandler{},
107 }
108
109 // collect the headers to copy from the auth response
110 // onto the original request, so they can get passed
111 // through to a backend app
112 headersToCopy := make(map[string]string)
113
114 // read the subdirectives for configuring the forward_auth shortcut
115 // NOTE: we delete the tokens as we go so that the reverse_proxy
116 // unmarshal doesn't see these subdirectives which it cannot handle
117 for dispenser.Next() {
118 for dispenser.NextBlock(0) {
119 // ignore any sub-subdirectives that might
120 // have the same name somewhere within
121 // the reverse_proxy passthrough tokens
122 if dispenser.Nesting() != 1 {
123 continue
124 }
125
126 // parse the forward_auth subdirectives
127 switch dispenser.Val() {
128 case "uri":
129 if !dispenser.NextArg() {
130 return nil, dispenser.ArgErr()
131 }
132 rpHandler.Rewrite.URI = dispenser.Val()
133 dispenser.DeleteN(2)
134
135 case "copy_headers":
136 args := dispenser.RemainingArgs()
137 hadBlock := false
138 for nesting := dispenser.Nesting(); dispenser.NextBlock(nesting); {
139 hadBlock = true
140 args = append(args, dispenser.Val())
141 }
142
143 // directive name + args
144 dispenser.DeleteN(len(args) + 1)
145 if hadBlock {
146 // opening & closing brace
147 dispenser.DeleteN(2)
148 }
149
150 for _, headerField := range args {
151 if strings.Contains(headerField, ">") {
152 parts := strings.Split(headerField, ">")
153 headersToCopy[parts[0]] = parts[1]
154 } else {
155 headersToCopy[headerField] = headerField
156 }
157 }
158 if len(headersToCopy) == 0 {
159 return nil, dispenser.ArgErr()
160 }
161 }
162 }
163 }
164
165 // reset the dispenser after we're done so that the reverse_proxy
166 // unmarshaler can read it from the start
167 dispenser.Reset()
168
169 // the auth target URI must not be empty
170 if rpHandler.Rewrite.URI == "" {
171 return nil, dispenser.Errf("the 'uri' subdirective is required")
172 }
173
174 // Set up handler for good responses; when a response has 2xx status,
175 // then we will copy some headers from the response onto the original
176 // request, and allow handling to continue down the middleware chain,
177 // by _not_ executing a terminal handler. We must have at least one
178 // route in the response handler, even if it's no-op, so that the
179 // response handling logic in reverse_proxy doesn't skip this entry.
180 goodResponseHandler := caddyhttp.ResponseHandler{
181 Match: &caddyhttp.ResponseMatcher{
182 StatusCode: []int{2},
183 },
184 Routes: []caddyhttp.Route{
185 {
186 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(
187 &caddyhttp.VarsMiddleware{},
188 "handler",
189 "vars",
190 nil,
191 )},
192 },
193 },
194 }
195
196 // Sort the headers so that the order in the JSON output is deterministic.
197 sortedHeadersToCopy := make([]string, 0, len(headersToCopy))
198 for k := range headersToCopy {
199 sortedHeadersToCopy = append(sortedHeadersToCopy, k)
200 }
201 sort.Strings(sortedHeadersToCopy)
202
203 // Set up handlers to copy headers from the auth response onto the
204 // original request. We use vars matchers to test that the placeholder
205 // values aren't empty, because the header handler would not replace
206 // placeholders which have no value.
207 copyHeaderRoutes := []caddyhttp.Route{}
208 for _, from := range sortedHeadersToCopy {
209 to := http.CanonicalHeaderKey(headersToCopy[from])
210 placeholderName := "http.reverse_proxy.header." + http.CanonicalHeaderKey(from)
211
212 // Always delete the client-supplied header before conditionally setting
213 // it from the auth response. Without this, a client that pre-supplies a
214 // header listed in copy_headers can inject arbitrary values when the auth
215 // service does not return that header: the MatchNot guard below would
216 // skip the Set entirely, leaving the original client-controlled value
217 // intact and forwarding it to the backend.
218 copyHeaderRoutes = append(copyHeaderRoutes, caddyhttp.Route{
219 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(
220 &headers.Handler{
221 Request: &headers.HeaderOps{
222 Delete: []string{to},
223 },
224 },
225 "handler", "headers", nil,
226 )},
227 })
228
229 handler := &headers.Handler{
230 Request: &headers.HeaderOps{
231 Set: http.Header{
232 to: []string{"{" + placeholderName + "}"},
233 },
234 },
235 }
236 copyHeaderRoutes = append(copyHeaderRoutes, caddyhttp.Route{
237 MatcherSetsRaw: []caddy.ModuleMap{{
238 "not": h.JSON(caddyhttp.MatchNot{MatcherSetsRaw: []caddy.ModuleMap{{
239 "vars": h.JSON(caddyhttp.VarsMatcher{"{" + placeholderName + "}": []string{""}}),
240 }}}),
241 }},
242 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(
243 handler,
244 "handler",
245 "headers",
246 nil,
247 )},
248 })
249 }
250
251 goodResponseHandler.Routes = append(goodResponseHandler.Routes, copyHeaderRoutes...)
252
253 // note that when a response has any other status than 2xx, then we
254 // use the reverse proxy's default behaviour of copying the response
255 // back to the client, so we don't need to explicitly add a response
256 // handler specifically for that behaviour; we do need the 2xx handler
257 // though, to make handling fall through to handlers deeper in the chain.
258 rpHandler.HandleResponse = append(rpHandler.HandleResponse, goodResponseHandler)
259
260 // the rest of the config is specified by the user
261 // using the reverse_proxy directive syntax
262 dispenser.Next() // consume the directive name
263 err = rpHandler.UnmarshalCaddyfile(dispenser)
264 if err != nil {
265 return nil, err
266 }
267 err = rpHandler.FinalizeUnmarshalCaddyfile(h)
268 if err != nil {
269 return nil, err
270 }
271
272 // create the final reverse proxy route
273 rpRoute := caddyhttp.Route{
274 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(
275 rpHandler,
276 "handler",
277 "reverse_proxy",
278 nil,
279 )},
280 }
281
282 // apply the user's matcher if any
283 if userMatcherSet != nil {
284 rpRoute.MatcherSetsRaw = []caddy.ModuleMap{userMatcherSet}
285 }
286
287 return []httpcaddyfile.ConfigValue{
288 {
289 Class: "route",
290 Value: rpRoute,
291 },
292 }, nil
293 }