-
Notifications
You must be signed in to change notification settings - Fork 66
/
main.go
250 lines (218 loc) · 7.24 KB
/
main.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
// Copyright © 2019 Arrikto Inc. All Rights Reserved.
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"path"
"time"
oidc "github.com/coreos/go-oidc"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"github.com/tevino/abool"
"github.com/yosssi/boltstore/shared"
"golang.org/x/oauth2"
"k8s.io/apiserver/pkg/authentication/authenticator"
clientconfig "sigs.k8s.io/controller-runtime/pkg/client/config"
)
// Issue: https://github.com/gorilla/sessions/issues/200
const secureCookieKeyPair = "notNeededBecauseCookieValueIsRandom"
const CacheCleanupInterval = 10
func main() {
c, err := parseConfig()
if err != nil {
log.Fatalf("Failed to parse configuration: %+v", err)
}
log.Infof("Config: %+v", c)
// Start readiness probe immediately
log.Infof("Starting readiness probe at %v", c.ReadinessProbePort)
isReady := abool.New()
go func() {
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", c.ReadinessProbePort), readiness(isReady)))
}()
/////////////////////////////////////////////////////
// Start server immediately for whitelisted routes //
/////////////////////////////////////////////////////
s := &server{}
// Register handlers for routes
router := mux.NewRouter()
router.HandleFunc(path.Join(c.AuthserviceURLPrefix.Path, OIDCCallbackPath), s.callback).Methods(http.MethodGet)
router.HandleFunc(path.Join(c.AuthserviceURLPrefix.Path, SessionLogoutPath), s.logout).Methods(http.MethodPost)
router.PathPrefix("/").Handler(whitelistMiddleware(c.SkipAuthURLs, isReady)(http.HandlerFunc(s.authenticate)))
// Start server
log.Infof("Starting server at %v:%v", c.Hostname, c.Port)
stopCh := make(chan struct{})
go func(stopCh chan struct{}) {
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", c.Hostname, c.Port), handlers.CORS()(router)))
close(stopCh)
}(stopCh)
// Start web server
webServer := WebServer{
TemplatePaths: c.TemplatePath,
ProviderURL: c.ProviderURL.String(),
ClientName: c.ClientName,
ThemeURL: resolvePathReference(c.ThemesURL, c.Theme).String(),
Frontend: c.UserTemplateContext,
}
log.Infof("Starting web server at %v:%v", c.Hostname, c.WebServerPort)
go func() {
log.Fatal(webServer.Start(fmt.Sprintf("%s:%d", c.Hostname, c.WebServerPort)))
}()
/////////////////////////////////
// Resume setup asynchronously //
/////////////////////////////////
// Read custom CA bundle
var caBundle []byte
if c.CABundlePath != "" {
caBundle, err = ioutil.ReadFile(c.CABundlePath)
if err != nil {
log.Fatalf("Could not read CA bundle path %s: %v", c.CABundlePath, err)
}
}
// OIDC Discovery
var provider *oidc.Provider
ctx := setTLSContext(context.Background(), caBundle)
for {
provider, err = oidc.NewProvider(ctx, c.ProviderURL.String())
if err == nil {
break
}
log.Errorf("OIDC provider setup failed, retrying in 10 seconds: %v", err)
time.Sleep(10 * time.Second)
}
endpoint := provider.Endpoint()
if len(c.OIDCAuthURL.String()) > 0 {
endpoint.AuthURL = c.OIDCAuthURL.String()
}
// Setup session store
// Using BoltDB by default
store, err := newBoltDBSessionStore(c.SessionStorePath,
shared.DefaultBucketName, false)
if err != nil {
log.Fatalf("Error creating session store: %v", err)
}
defer store.Close()
// Setup state store
// Using BoltDB by default
oidcStateStore, err := newBoltDBSessionStore(c.OIDCStateStorePath,
"oidc_state", true)
if err != nil {
log.Fatalf("Error creating oidc state store: %v", err)
}
defer oidcStateStore.Close()
// Get Kubernetes authenticator
restConfig, err := clientconfig.GetConfig()
if err != nil {
log.Fatalf("Error getting K8s config: %v", err)
}
k8sAuthenticator, err := newKubernetesAuthenticator(restConfig, c.Audiences)
if err != nil {
log.Fatalf("Error creating K8s authenticator: %v", err)
}
// Get OIDC Session Authenticator
oauth2Config := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
Endpoint: endpoint,
RedirectURL: c.RedirectURL.String(),
Scopes: c.OIDCScopes,
}
sessionAuthenticator := &sessionAuthenticator{
store: store,
cookie: userSessionCookie,
header: c.AuthHeader,
strictSessionValidation: c.StrictSessionValidation,
caBundle: caBundle,
provider: provider,
oauth2Config: oauth2Config,
}
groupsAuthorizer := newGroupsAuthorizer(c.GroupsAllowlist)
idTokenAuthenticator := &idTokenAuthenticator{
header: c.IDTokenHeader,
caBundle: caBundle,
provider: provider,
clientID: c.ClientID,
userIDClaim: c.UserIDClaim,
groupsClaim: c.GroupsClaim,
}
jwtTokenAuthenticator := &jwtTokenAuthenticator{
header: c.IDTokenHeader,
caBundle: caBundle,
provider: provider,
audiences: c.Audiences,
issuer: c.ProviderURL.String(),
userIDClaim: c.UserIDClaim,
groupsClaim: c.GroupsClaim,
}
opaqueTokenAuthenticator := &opaqueTokenAuthenticator{
header: c.IDTokenHeader,
caBundle: caBundle,
provider: provider,
oauth2Config: oauth2Config,
userIDClaim: c.UserIDClaim,
groupsClaim: c.GroupsClaim,
}
// Set the bearerUserInfoCache cache to store
// the (Bearer Token, UserInfo) pairs.
bearerUserInfoCache := cache.New(time.Duration(c.CacheExpirationMinutes)*time.Minute, time.Duration(CacheCleanupInterval)*time.Minute)
// Set the server values.
// The isReady atomic variable should protect it from concurrency issues.
*s = server{
provider: provider,
oauth2Config: oauth2Config,
// TODO: Add support for Redis
store: store,
oidcStateStore: oidcStateStore,
bearerUserInfoCache: bearerUserInfoCache,
afterLoginRedirectURL: c.AfterLoginURL.String(),
homepageURL: c.HomepageURL.String(),
afterLogoutRedirectURL: c.AfterLogoutURL.String(),
idTokenOpts: jwtClaimOpts{
userIDClaim: c.UserIDClaim,
groupsClaim: c.GroupsClaim,
},
upstreamHTTPHeaderOpts: httpHeaderOpts{
userIDHeader: c.UserIDHeader,
userIDPrefix: c.UserIDPrefix,
groupsHeader: c.GroupsHeader,
authMethodHeader: c.AuthMethodHeader,
},
userIdTransformer: c.UserIDTransformer,
sessionMaxAgeSeconds: c.SessionMaxAge,
strictSessionValidation: c.StrictSessionValidation,
cacheEnabled: c.CacheEnabled,
cacheExpirationMinutes: c.CacheExpirationMinutes,
IDTokenAuthnEnabled: c.IDTokenAuthnEnabled,
KubernetesAuthnEnabled: c.KubernetesAuthnEnabled,
AccessTokenAuthnEnabled: c.AccessTokenAuthnEnabled,
AccessTokenAuthn: c.AccessTokenAuthn,
authHeader: c.AuthHeader,
caBundle: caBundle,
authenticators: []authenticator.Request{
k8sAuthenticator,
opaqueTokenAuthenticator,
jwtTokenAuthenticator,
sessionAuthenticator,
idTokenAuthenticator,
},
authorizers: []Authorizer{groupsAuthorizer},
}
switch c.SessionSameSite {
case "None":
s.sessionSameSite = http.SameSiteNoneMode
case "Strict":
s.sessionSameSite = http.SameSiteStrictMode
default:
// Use Lax mode as the default
s.sessionSameSite = http.SameSiteLaxMode
}
// Print server configuration info
log.Infof("Cache enabled: %t", s.cacheEnabled)
// Setup complete, mark server ready
isReady.Set()
// Block until server exits
<-stopCh
}