-
Notifications
You must be signed in to change notification settings - Fork 19
/
primaryHandler.go
260 lines (229 loc) · 8.54 KB
/
primaryHandler.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
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"regexp"
"syscall"
"emperror.dev/emperror"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/viper"
"github.com/xmidt-org/ancla"
"github.com/xmidt-org/bascule"
"github.com/xmidt-org/bascule/basculechecks"
"github.com/xmidt-org/bascule/basculehelper"
"github.com/xmidt-org/bascule/basculehttp"
"github.com/xmidt-org/clortho"
"github.com/xmidt-org/clortho/clorthometrics"
"github.com/xmidt-org/clortho/clorthozap"
"github.com/xmidt-org/sallust"
"github.com/xmidt-org/touchstone"
// nolint:staticcheck
"github.com/xmidt-org/webpa-common/v2/xmetrics"
"go.uber.org/zap"
)
const (
apiVersion = "v4"
prevAPIVersion = "v3"
apiBase = "api/" + apiVersion
apiBaseDualVersion = "api/{version:" + apiVersion + "|" + prevAPIVersion + "}"
)
type CapabilityConfig struct {
Type string
Prefix string
AcceptAllMethod string
EndpointBuckets []string
}
// JWTValidator provides a convenient way to define jwt validator through config files
type JWTValidator struct {
// Config is used to create the clortho Resolver & Refresher for JWT verification keys
Config clortho.Config `json:"config"`
// Leeway is used to set the amount of time buffer should be given to JWT
// time values, such as nbf
Leeway bascule.Leeway
}
func NewPrimaryHandler(l *zap.Logger, v *viper.Viper, registry xmetrics.Registry, sw *ServerHandler, webhookSvc ancla.Service, router *mux.Router, prevVersionSupport bool) (*mux.Router, error) {
auth, err := authenticationMiddleware(v, l, registry)
if err != nil {
// nolint:errorlint
return nil, fmt.Errorf("unable to build authentication middleware: %v", err)
}
// if we want to support the previous API version, then include it in the
// api base.
urlPrefix := fmt.Sprintf("/%s", apiBase)
if prevVersionSupport {
urlPrefix = fmt.Sprintf("/%s", apiBaseDualVersion)
}
router.Handle(urlPrefix+"/notify", auth.Then(sw)).Methods("POST")
return router, nil
}
// authenticationMiddleware configures the authorization requirements for requests to reach the main handler
func authenticationMiddleware(v *viper.Viper, logger *zap.Logger, registry xmetrics.Registry) (*alice.Chain, error) {
if registry == nil {
return nil, errors.New("nil registry")
}
basculeMeasures := basculehelper.NewAuthValidationMeasures(registry)
capabilityCheckMeasures := basculehelper.NewAuthCapabilityCheckMeasures(registry)
listener := basculehelper.NewMetricListener(basculeMeasures)
basicAllowed := make(map[string]string)
basicAuth := v.GetStringSlice("authHeader")
for _, a := range basicAuth {
decoded, err := base64.StdEncoding.DecodeString(a)
if err != nil {
logger.Info("failed to decode auth header", zap.String("authHeader", a), zap.Error(err))
continue
}
i := bytes.IndexByte(decoded, ':')
logger.Debug("decoded string", zap.ByteString("string", decoded), zap.Int("i", i))
if i > 0 {
basicAllowed[string(decoded[:i])] = string(decoded[i+1:])
}
}
logger.Debug("Created list of allowed basic auths", zap.Any("allowed", basicAllowed), zap.Any("config", basicAuth))
options := []basculehttp.COption{
basculehttp.WithCLogger(getLogger),
basculehttp.WithCErrorResponseFunc(listener.OnErrorResponse),
}
if len(basicAllowed) > 0 {
options = append(options, basculehttp.WithTokenFactory("Basic", basculehttp.BasicTokenFactory(basicAllowed)))
}
var jwtVal JWTValidator
// Get jwt configuration, including clortho's configuration
v.UnmarshalKey("jwtValidator", &jwtVal)
kr := clortho.NewKeyRing()
// Instantiate a fetcher for refresher and resolver to share
f, err := clortho.NewFetcher()
if err != nil {
return &alice.Chain{}, emperror.With(err, "failed to create clortho fetcher")
}
ref, err := clortho.NewRefresher(
clortho.WithConfig(jwtVal.Config),
clortho.WithFetcher(f),
)
if err != nil {
return &alice.Chain{}, emperror.With(err, "failed to create clortho refresher")
}
resolver, err := clortho.NewResolver(
clortho.WithConfig(jwtVal.Config),
clortho.WithKeyRing(kr),
clortho.WithFetcher(f),
)
if err != nil {
return &alice.Chain{}, emperror.With(err, "failed to create clortho resolver")
}
promReg, ok := registry.(prometheus.Registerer)
if !ok {
return &alice.Chain{}, errors.New("failed to get prometheus registerer")
}
var (
tsConfig touchstone.Config
zConfig sallust.Config
)
// Get touchstone & zap configurations
v.UnmarshalKey("touchstone", &tsConfig)
v.UnmarshalKey("zap", &zConfig)
zlogger := zap.Must(zConfig.Build())
tf := touchstone.NewFactory(tsConfig, zlogger, promReg)
// Instantiate a metric listener for refresher and resolver to share
cml, err := clorthometrics.NewListener(clorthometrics.WithFactory(tf))
if err != nil {
return &alice.Chain{}, emperror.With(err, "failed to create clortho metrics listener")
}
// Instantiate a logging listener for refresher and resolver to share
czl, err := clorthozap.NewListener(
clorthozap.WithLogger(zlogger),
)
if err != nil {
return &alice.Chain{}, emperror.With(err, "failed to create clortho zap logger listener")
}
resolver.AddListener(cml)
resolver.AddListener(czl)
ref.AddListener(cml)
ref.AddListener(czl)
ref.AddListener(kr)
// context.Background() is for the unused `context.Context` argument in refresher.Start
ref.Start(context.Background())
// Shutdown refresher's goroutines when SIGTERM
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM)
go func() {
<-sigs
// context.Background() is for the unused `context.Context` argument in refresher.Stop
ref.Stop(context.Background())
}()
options = append(options, basculehttp.WithTokenFactory("Bearer", basculehttp.BearerTokenFactory{
DefaultKeyID: defaultKeyID,
Resolver: resolver,
Parser: bascule.DefaultJWTParser,
Leeway: jwtVal.Leeway,
}))
authConstructor := basculehttp.NewConstructor(append([]basculehttp.COption{
basculehttp.WithParseURLFunc(basculehttp.CreateRemovePrefixURLFunc("/"+apiBase+"/", basculehttp.DefaultParseURLFunc)),
}, options...)...)
authConstructorLegacy := basculehttp.NewConstructor(append([]basculehttp.COption{
basculehttp.WithParseURLFunc(basculehttp.CreateRemovePrefixURLFunc("/api/"+prevAPIVersion+"/", basculehttp.DefaultParseURLFunc)),
basculehttp.WithCErrorHTTPResponseFunc(basculehttp.LegacyOnErrorHTTPResponse),
}, options...)...)
bearerRules := bascule.Validators{
basculechecks.NonEmptyPrincipal(),
basculechecks.NonEmptyType(),
basculechecks.ValidType([]string{"jwt"}),
}
// only add capability check if the configuration is set
var capabilityCheck CapabilityConfig
v.UnmarshalKey("capabilityCheck", &capabilityCheck)
if capabilityCheck.Type == "enforce" || capabilityCheck.Type == "monitor" {
var endpoints []*regexp.Regexp
c, err := basculehelper.NewEndpointRegexCheck(capabilityCheck.Prefix, capabilityCheck.AcceptAllMethod)
if err != nil {
// nolint:errorlint
return nil, fmt.Errorf("failed to create capability check: %v", err)
}
for _, e := range capabilityCheck.EndpointBuckets {
r, err := regexp.Compile(e)
if err != nil {
logger.Error("failed to compile regular expression", zap.Any("regex", e), zap.Error(err))
continue
}
endpoints = append(endpoints, r)
}
m := basculehelper.MetricValidator{
C: basculehelper.CapabilitiesValidator{Checker: c},
Measures: capabilityCheckMeasures,
Endpoints: endpoints,
}
bearerRules = append(bearerRules, m.CreateValidator(capabilityCheck.Type == "enforce"))
}
authEnforcer := basculehttp.NewEnforcer(
basculehttp.WithELogger(getLogger),
basculehttp.WithRules("Basic", bascule.Validators{
basculechecks.AllowAll(),
}),
basculehttp.WithRules("Bearer", bearerRules),
basculehttp.WithEErrorResponseFunc(listener.OnErrorResponse),
)
authChain := alice.New(setLogger(logger), authConstructor, authEnforcer, basculehttp.NewListenerDecorator(listener))
authChainLegacy := alice.New(setLogger(logger), authConstructorLegacy, authEnforcer, basculehttp.NewListenerDecorator(listener))
versionCompatibleAuth := alice.New(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(r http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if vars != nil {
if vars["version"] == prevAPIVersion {
authChainLegacy.Then(next).ServeHTTP(r, req)
return
}
}
authChain.Then(next).ServeHTTP(r, req)
})
})
return &versionCompatibleAuth, nil
}