-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjsonconf.go
More file actions
329 lines (283 loc) · 10.8 KB
/
jsonconf.go
File metadata and controls
329 lines (283 loc) · 10.8 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
package caddyconsul
import (
"encoding/json"
"fmt"
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
"github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
"github.com/caddyserver/caddy/v2/modules/caddytls"
"github.com/greenpau/caddy-auth-jwt/pkg/acl"
"github.com/greenpau/caddy-auth-jwt/pkg/authz"
portal "github.com/greenpau/caddy-auth-portal"
caddyrequestid "github.com/lolPants/caddy-requestid"
)
// generateConfAsJSON is an easy accessor that calls generateConf,
// but returns its result as JSON
func (cc *App) generateConfAsJSON() (confJson []byte, err error) {
conf, err := cc.generateConf()
if err != nil {
return
}
return caddyconfig.JSON(conf, nil), nil
}
// generateConf generates the Caddy configuration from the global K/V store
// and the services in Consul
func (cc *App) generateConf() (conf *caddy.Config, err error) {
if globalConfig == nil {
return conf, fmt.Errorf("globalConfig not initialized yet!")
}
conf = &*globalConfig
err = cc.generateHTTPAndTLSAppConfFromConsulServices(conf)
if err != nil {
return
}
return
}
// generateHTTPAndTLSAppConfFromConsulServices handles the generation
// of the TLS and HTTP Caddy apps
func (cc *App) generateHTTPAndTLSAppConfFromConsulServices(conf *caddy.Config) (err error) {
if len(globalServices) == 0 {
return
}
services := globalServices
if conf.AppsRaw == nil {
conf.AppsRaw = make(caddy.ModuleMap)
}
// We create two servers while generating the HTTP app config:
// - http handles the HTTP only websites
// - https handles the HTTPS websites
httpConf := &caddyhttp.App{
Servers: map[string]*caddyhttp.Server{
"http": {
Listen: []string{
fmt.Sprintf(":%d", cc.AutoReverseProxy.DefaultHTTPServerOptions.HTTPPort),
},
Routes: caddyhttp.RouteList{},
},
"https": {
Listen: []string{
fmt.Sprintf(":%d", cc.AutoReverseProxy.DefaultHTTPServerOptions.HTTPSPort),
},
Routes: caddyhttp.RouteList{cc.getAuthRoute()},
AllowH2C: true,
},
},
}
// We also generate the TLS app config
tlsConf := &caddytls.TLS{
Automation: &caddytls.AutomationConfig{
Policies: []*caddytls.AutomationPolicy{},
},
}
// If the authentication is enabled, we need to handle the certificates for the authentication domain too
if cc.AutoReverseProxy.AuthenticationConfiguration.Enabled {
tlsConf.Automation.Policies = append(tlsConf.Automation.Policies, &caddytls.AutomationPolicy{
Subjects: []string{cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain},
IssuersRaw: cc.AutoReverseProxy.TLSIssuers,
})
}
// We iterate on every Consul service
for _, instances := range services {
// If no instance (AKA upstream) was returned, let's continue
if len(instances) == 0 {
continue
}
// We compute the upstreams and options requested from the service's instances
upstreams, options := parseConsulService(instances)
// Let's start by instantiating the reverse-proxy handler
reverseProxyHandler := &reverseproxy.Handler{
Upstreams: upstreams,
FlushInterval: caddy.Duration(options.FlushInterval),
BufferRequests: options.BufferRequests,
BufferResponses: options.BufferResponses,
MaxBufferSize: int64(options.MaxBufferSize),
Headers: &headers.Handler{
Request: &headers.HeaderOps{Add: http.Header{}},
Response: &headers.RespHeaderOps{
Deferred: true,
HeaderOps: &headers.HeaderOps{Add: http.Header{}},
},
},
}
// If Upstream is HTTPS, then we use HTTPTransport and add the TLS tag (insecure)
if options.UpstreamsScheme == "https" {
transport := reverseproxy.HTTPTransport{
TLS: &reverseproxy.TLSConfig{
InsecureSkipVerify: options.InsecureTLSUpstreams,
},
}
reverseProxyHandler.TransportRaw = caddyconfig.JSONModuleObject(transport, "protocol", "http", nil)
} else if options.UpstreamsScheme == "grpc" {
transport := reverseproxy.HTTPTransport{
Versions: []string{"h2c", "2"},
}
reverseProxyHandler.TransportRaw = caddyconfig.JSONModuleObject(transport, "protocol", "http", nil)
}
// Do we propagate upstream headers?
if options.UpstreamHeaders {
reverseProxyHandler.Headers.Response.Add = http.Header{
"X-PROXY-UPSTREAM-ADDRESS": []string{"{http.reverse_proxy.upstream.address}"},
"X-PROXY-UPSTREAM-LATENCY": []string{"{http.reverse_proxy.upstream.latency}"},
"X-PROXY-UPSTREAM-DURATION": []string{"{http.reverse_proxy.upstream.duration}"},
"X-PROXY-DURATION": []string{"{http.reverse_proxy.duration}"},
}
}
// If authentication is enabled, let's remap the JWT claims
if cc.AutoReverseProxy.AuthenticationConfiguration.Enabled && options.Authentication {
for header, customHeader := range cc.AutoReverseProxy.AuthenticationConfiguration.CustomClaimsHeaders {
if _, ok := reverseProxyHandler.Headers.Request.Add[customHeader]; !ok {
reverseProxyHandler.Headers.Request.Add[customHeader] = []string{}
}
reverseProxyHandler.Headers.Request.Add[customHeader] = append(
reverseProxyHandler.Headers.Request.Add[customHeader],
fmt.Sprintf("{http.request.header.%s}", header),
)
if _, ok := reverseProxyHandler.Headers.Response.Add[customHeader]; !ok {
reverseProxyHandler.Headers.Response.Add[customHeader] = []string{}
}
reverseProxyHandler.Headers.Response.Add[customHeader] = append(
reverseProxyHandler.Headers.Response.Add[customHeader],
fmt.Sprintf("{http.request.header.%s}", header),
)
}
}
// Do we want to use the request-id module?
if cc.AutoReverseProxy.UseRequestID {
reverseProxyHandler.Headers.Request.Add["X-REQUEST-ID"] = []string{"{http.request_id}"}
reverseProxyHandler.Headers.Response.Add["X-REQUEST-ID"] = []string{"{http.request_id}"}
}
// Do we have a specific load-balancing policy attached?
if options.LoadBalancingPolicy != "" {
reverseProxyHandler.LoadBalancing = &reverseproxy.LoadBalancing{
SelectionPolicyRaw: caddyconfig.JSON(map[string]string{"policy": options.LoadBalancingPolicy}, nil),
}
}
// Is our service HTTP only?
servers := []string{"https"}
if options.NoHTTPS {
servers = []string{"http"}
} else if options.NoAutoHTTPSRedirect {
servers = append(servers, "http")
}
// Let's define the host name for the service
name := instances[0].Service.Service
zone := cc.AutoReverseProxy.DefaultHTTPServerOptions.Zone
if options.ServiceNameOverride != "" {
name = options.ServiceNameOverride
}
if options.ZoneOverride != "" {
zone = options.ZoneOverride
}
// We now have the hostname we want to use
hostnames := []string{fmt.Sprintf("%s.%s", name, zone)}
// Let's prepare the TLS app part for this website
tlsConf.Automation.Policies = append(tlsConf.Automation.Policies, &caddytls.AutomationPolicy{
Subjects: hostnames,
IssuersRaw: cc.AutoReverseProxy.TLSIssuers,
})
// And now, let's build the handlers!
handlersRaw := []json.RawMessage{}
// If we have authentication, we need to add the caddy-auth-jwt handler
if options.Authentication {
authURLPath := fmt.Sprintf(
"https://%s/auth",
cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain,
)
if options.AuthenticationProvider != "" {
authURLPath = fmt.Sprintf(
"https://%s/auth/%s",
cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain,
options.AuthenticationProvider,
)
}
handlersRaw = append(handlersRaw, caddyconfig.JSON(NewAuthenticationHandler(authURLPath), nil))
}
// If we generate (or propagate) the X-Request-ID header, we need to add the request_id handler
if cc.AutoReverseProxy.UseRequestID {
handlersRaw = append(handlersRaw, caddyconfig.JSONModuleObject(caddyrequestid.RequestID{}, "handler", "request_id", nil))
}
// And finally, we add the reverse_proxy handler!
handlersRaw = append(handlersRaw, caddyconfig.JSONModuleObject(reverseProxyHandler, "handler", "reverse_proxy", nil))
// Now that we have everything, we add the route to our host on the relevant server (HTTP or HTTPS)
for _, server := range servers {
httpConf.Servers[server].Routes = append(httpConf.Servers[server].Routes,
caddyhttp.Route{
HandlersRaw: handlersRaw,
MatcherSetsRaw: caddyhttp.RawMatcherSets{
caddy.ModuleMap{
"host": caddyconfig.JSON(hostnames, nil),
},
},
Terminal: true,
},
)
}
}
// As we finished iterating on all Consul services, we generated both HTTP and TLS apps config,
// so we just need to push them to our config, and we're done!
conf.AppsRaw["http"] = caddyconfig.JSON(httpConf, nil)
conf.AppsRaw["tls"] = caddyconfig.JSON(tlsConf, nil)
return
}
// getAuthRoute generates the HTTPS entry for the caddy-auth-portal plugin.
// It uses the value `AuthenticationConfiguration.AuthenticationDomain`
// to expose the auth portal on https://[AuthenticationConfiguration.AuthenticationDomain]/auth.
// It also setups a catch-all authenticated route to instantiate the primary caddy-auth-jwt
// plugin.
func (cc *App) getAuthRoute() (route caddyhttp.Route) {
if !cc.AutoReverseProxy.AuthenticationConfiguration.Enabled {
return
}
authMiddleware := &portal.AuthMiddleware{
Portal: &cc.AutoReverseProxy.AuthenticationConfiguration.AuthPortalConfiguration,
}
defaultAuthHandler := NewAuthenticationHandler(fmt.Sprintf(
"https://%s/auth",
cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain,
))
defaultAuthHandler.Providers.JWT.Authorizer = authz.Authorizer{
AuthURLPath: fmt.Sprintf(
"https://%s/auth",
cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain,
),
PrimaryInstance: true,
PassClaimsWithHeaders: true,
CryptoKeyConfigs: cc.AutoReverseProxy.AuthenticationConfiguration.AuthPortalConfiguration.CryptoKeyConfigs,
AccessListRules: []*acl.RuleConfiguration{
{
Conditions: []string{"always match roles any"},
Action: "allow",
},
},
}
subRouteHandler := &caddyhttp.Subroute{
Routes: caddyhttp.RouteList{
caddyhttp.Route{
Terminal: true,
MatcherSetsRaw: caddyhttp.RawMatcherSets{
caddy.ModuleMap{
"path_regexp": caddyconfig.JSON(caddyhttp.MatchPathRE{MatchRegexp: caddyhttp.MatchRegexp{Pattern: fmt.Sprintf("/auth*")}}, nil),
},
},
HandlersRaw: []json.RawMessage{
caddyconfig.JSONModuleObject(authMiddleware, "handler", "authp", nil),
},
},
caddyhttp.Route{
HandlersRaw: []json.RawMessage{caddyconfig.JSON(defaultAuthHandler, nil)},
},
},
}
route = caddyhttp.Route{
MatcherSetsRaw: caddyhttp.RawMatcherSets{
caddy.ModuleMap{
"host": caddyconfig.JSON([]string{cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain}, nil),
},
},
HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subRouteHandler, "handler", "subroute", nil)},
}
return
}