-
Notifications
You must be signed in to change notification settings - Fork 218
/
authn.go
309 lines (252 loc) · 10.3 KB
/
authn.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package cmd
import (
"context"
"crypto"
"fmt"
"net/http"
"os"
"regexp"
"github.com/go-chi/chi/v5"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/selector"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/hashicorp/cap/jwt"
"go.flipt.io/flipt/internal/cleanup"
"go.flipt.io/flipt/internal/config"
"go.flipt.io/flipt/internal/containers"
"go.flipt.io/flipt/internal/gateway"
"go.flipt.io/flipt/internal/server/authn"
"go.flipt.io/flipt/internal/server/authn/method"
authgithub "go.flipt.io/flipt/internal/server/authn/method/github"
authkubernetes "go.flipt.io/flipt/internal/server/authn/method/kubernetes"
authoidc "go.flipt.io/flipt/internal/server/authn/method/oidc"
authtoken "go.flipt.io/flipt/internal/server/authn/method/token"
authmiddlewaregrpc "go.flipt.io/flipt/internal/server/authn/middleware/grpc"
authmiddlewarehttp "go.flipt.io/flipt/internal/server/authn/middleware/http"
"go.flipt.io/flipt/internal/server/authn/public"
storageauth "go.flipt.io/flipt/internal/storage/authn"
storageauthcache "go.flipt.io/flipt/internal/storage/authn/cache"
storageauthmemory "go.flipt.io/flipt/internal/storage/authn/memory"
authsql "go.flipt.io/flipt/internal/storage/authn/sql"
oplocksql "go.flipt.io/flipt/internal/storage/oplock/sql"
rpcauth "go.flipt.io/flipt/rpc/flipt/auth"
"go.uber.org/zap"
"google.golang.org/grpc"
)
func authenticationGRPC(
ctx context.Context,
logger *zap.Logger,
cfg *config.Config,
forceMigrate bool,
tokenDeletedEnabled bool,
authOpts ...containers.Option[authmiddlewaregrpc.InterceptorOptions],
) (grpcRegisterers, []grpc.UnaryServerInterceptor, func(context.Context) error, error) {
shutdown := func(ctx context.Context) error {
return nil
}
// NOTE: we skip attempting to connect to any database in the situation that either the git, local, or object
// FS backends are configured.
// All that is required to establish a connection for authentication is to either make auth required
// or configure at-least one authentication method (e.g. enable token method).
if !cfg.Authentication.Enabled() && (cfg.Storage.Type != config.DatabaseStorageType) {
return grpcRegisterers{
public.NewServer(logger, cfg.Authentication),
authn.NewServer(logger, storageauthmemory.NewStore()),
}, nil, shutdown, nil
}
_, builder, driver, dbShutdown, err := getDB(ctx, logger, cfg, forceMigrate)
if err != nil {
return nil, nil, nil, err
}
var (
authCfg = cfg.Authentication
store storageauth.Store = authsql.NewStore(driver, builder, logger)
oplock = oplocksql.New(logger, driver, builder)
publicServer = public.NewServer(logger, authCfg)
)
if cfg.Cache.Enabled {
cacher, _, err := getCache(ctx, cfg)
if err != nil {
return nil, nil, nil, err
}
store = storageauthcache.NewStore(store, cacher, logger)
}
authServer := authn.NewServer(logger, store, authn.WithAuditLoggingEnabled(tokenDeletedEnabled))
var (
register = grpcRegisterers{
publicServer,
authServer,
}
interceptors []grpc.UnaryServerInterceptor
)
// register auth method token service
if authCfg.Methods.Token.Enabled {
opts := []storageauth.BootstrapOption{}
// if a bootstrap token is provided, use it
if authCfg.Methods.Token.Method.Bootstrap.Token != "" {
opts = append(opts, storageauth.WithToken(authCfg.Methods.Token.Method.Bootstrap.Token))
}
// if a bootstrap expiration is provided, use it
if authCfg.Methods.Token.Method.Bootstrap.Expiration != 0 {
opts = append(opts, storageauth.WithExpiration(authCfg.Methods.Token.Method.Bootstrap.Expiration))
}
// attempt to bootstrap authentication store
clientToken, err := storageauth.Bootstrap(ctx, store, opts...)
if err != nil {
return nil, nil, nil, fmt.Errorf("configuring token authentication: %w", err)
}
if clientToken != "" {
logger.Info("access token created", zap.String("client_token", clientToken))
}
register.Add(authtoken.NewServer(logger, store))
logger.Debug("authentication method \"token\" server registered")
}
// register auth method oidc service
if authCfg.Methods.OIDC.Enabled {
oidcServer := authoidc.NewServer(logger, store, authCfg)
register.Add(oidcServer)
logger.Debug("authentication method \"oidc\" server registered")
}
if authCfg.Methods.Github.Enabled {
githubServer := authgithub.NewServer(logger, store, authCfg)
register.Add(githubServer)
logger.Debug("authentication method \"github\" registered")
}
if authCfg.Methods.Kubernetes.Enabled {
kubernetesServer, err := authkubernetes.New(logger, store, authCfg)
if err != nil {
return nil, nil, nil, fmt.Errorf("configuring kubernetes authentication: %w", err)
}
register.Add(kubernetesServer)
logger.Debug("authentication method \"kubernetes\" server registered")
}
// only enable enforcement middleware if authentication required
if authCfg.Required {
if authCfg.Methods.JWT.Enabled {
authJWT := authCfg.Methods.JWT
var ks jwt.KeySet
if authJWT.Method.JWKSURL != "" {
ks, err = jwt.NewJSONWebKeySet(ctx, authJWT.Method.JWKSURL, "")
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to create JSON web key set: %w", err)
}
} else if authJWT.Method.PublicKeyFile != "" {
keyPEMBlock, err := os.ReadFile(authJWT.Method.PublicKeyFile)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to read key file: %w", err)
}
publicKey, err := jwt.ParsePublicKeyPEM(keyPEMBlock)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to parse public key PEM block: %w", err)
}
ks, err = jwt.NewStaticKeySet([]crypto.PublicKey{publicKey})
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to create static key set: %w", err)
}
}
validator, err := jwt.NewValidator(ks)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to create JWT validator: %w", err)
}
// intentionally restricted to a set of common asymmetric algorithms
// if we want to support symmetric algorithms, we need to add support for
// private keys in the configuration
exp := jwt.Expected{
SigningAlgorithms: []jwt.Alg{jwt.RS256, jwt.RS512, jwt.ES256, jwt.ES512, jwt.EdDSA},
}
if authJWT.Method.ValidateClaims.Issuer != "" {
exp.Issuer = authJWT.Method.ValidateClaims.Issuer
}
if len(authJWT.Method.ValidateClaims.Audiences) != 0 {
exp.Audiences = authJWT.Method.ValidateClaims.Audiences
}
interceptors = append(interceptors, selector.UnaryServerInterceptor(authmiddlewaregrpc.JWTAuthenticationInterceptor(logger, *validator, exp, authOpts...), authmiddlewaregrpc.JWTInterceptorSelector()))
}
interceptors = append(interceptors, selector.UnaryServerInterceptor(authmiddlewaregrpc.ClientTokenAuthenticationInterceptor(
logger,
store,
authOpts...,
), authmiddlewaregrpc.ClientTokenInterceptorSelector()))
if authCfg.Methods.OIDC.Enabled && len(authCfg.Methods.OIDC.Method.EmailMatches) != 0 {
rgxs := make([]*regexp.Regexp, 0, len(authCfg.Methods.OIDC.Method.EmailMatches))
for _, em := range authCfg.Methods.OIDC.Method.EmailMatches {
rgx, err := regexp.Compile(em)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed compiling string for pattern: %s: %w", em, err)
}
rgxs = append(rgxs, rgx)
}
interceptors = append(interceptors, selector.UnaryServerInterceptor(authmiddlewaregrpc.EmailMatchingInterceptor(logger, rgxs, authOpts...), authmiddlewaregrpc.ClientTokenInterceptorSelector()))
}
if authCfg.Methods.Token.Enabled {
interceptors = append(interceptors, selector.UnaryServerInterceptor(authmiddlewaregrpc.NamespaceMatchingInterceptor(logger, authOpts...), authmiddlewaregrpc.ClientTokenInterceptorSelector()))
}
// at this point, we have already registered all authentication methods that are enabled
// so atleast one authentication method should pass if authentication is required
interceptors = append(interceptors, authmiddlewaregrpc.AuthenticationRequiredInterceptor(logger, authOpts...))
logger.Info("authentication middleware enabled")
}
if authCfg.ShouldRunCleanup() {
cleanupAuthService := cleanup.NewAuthenticationService(
logger,
oplock,
store,
authCfg,
)
cleanupAuthService.Run(ctx)
shutdown = func(ctx context.Context) error {
logger.Info("shutting down authentication cleanup service...")
if err := cleanupAuthService.Shutdown(ctx); err != nil {
_ = dbShutdown(ctx)
return err
}
return dbShutdown(ctx)
}
}
return register, interceptors, shutdown, nil
}
func registerFunc(ctx context.Context, conn *grpc.ClientConn, fn func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error) runtime.ServeMuxOption {
return func(mux *runtime.ServeMux) {
if err := fn(ctx, mux, conn); err != nil {
panic(err)
}
}
}
func authenticationHTTPMount(
ctx context.Context,
logger *zap.Logger,
cfg config.AuthenticationConfig,
r chi.Router,
conn *grpc.ClientConn,
) {
var (
authmiddleware = authmiddlewarehttp.NewHTTPMiddleware(cfg.Session)
middleware = []func(next http.Handler) http.Handler{authmiddleware.Handler}
muxOpts = []runtime.ServeMuxOption{
registerFunc(ctx, conn, rpcauth.RegisterPublicAuthenticationServiceHandler),
registerFunc(ctx, conn, rpcauth.RegisterAuthenticationServiceHandler),
runtime.WithErrorHandler(authmiddleware.ErrorHandler),
}
)
if cfg.Methods.Token.Enabled {
muxOpts = append(muxOpts, registerFunc(ctx, conn, rpcauth.RegisterAuthenticationMethodTokenServiceHandler))
}
if cfg.SessionEnabled() {
muxOpts = append(muxOpts, runtime.WithMetadata(method.ForwardCookies))
methodMiddleware := method.NewHTTPMiddleware(cfg.Session)
muxOpts = append(muxOpts, runtime.WithForwardResponseOption(methodMiddleware.ForwardResponseOption))
if cfg.Methods.OIDC.Enabled {
muxOpts = append(muxOpts, registerFunc(ctx, conn, rpcauth.RegisterAuthenticationMethodOIDCServiceHandler))
}
if cfg.Methods.Github.Enabled {
muxOpts = append(muxOpts, registerFunc(ctx, conn, rpcauth.RegisterAuthenticationMethodGithubServiceHandler))
}
middleware = append(middleware, methodMiddleware.Handler)
}
if cfg.Methods.Kubernetes.Enabled {
muxOpts = append(muxOpts, registerFunc(ctx, conn, rpcauth.RegisterAuthenticationMethodKubernetesServiceHandler))
}
r.Group(func(r chi.Router) {
r.Use(middleware...)
r.Mount("/auth/v1", gateway.NewGatewayServeMux(logger, muxOpts...))
})
}