forked from fydrah/loginapp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
370 lines (343 loc) · 11.1 KB
/
main.go
File metadata and controls
370 lines (343 loc) · 11.1 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright 2018 fydrah
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Some code comes from @ericchiang (Dex - CoreOS)
// Loginapp is an OIDC authentication web interface.
// It is mainly designed to render the token issued by an IdP (like Dex) in
// a kubernetes kubeconfig format.
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/coreos/go-oidc"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
var (
logger = logrus.New()
)
// Server is the description
// of loginapp web server
type Server struct {
client *http.Client
config AppConfig
provider *oidc.Provider
router *httprouter.Router
verifier *oidc.IDTokenVerifier
context context.Context
idpCA string
clusterCA string
}
// KubeUserInfo contains all values
// needed by a user for OIDC authentication
type KubeUserInfo struct {
ClientID string
IDToken string
RefreshToken string
RedirectURL string
Claims interface{}
ClientSecret string
UsernameClaim string
Name string
IDPCA string
ClusterServer string
ClusterCA string
ClusterName string
ContextName string
}
// OAuth2Config generate oauth config
// based on scopes and yaml configuration file
func (s *Server) OAuth2Config(scopes []string) *oauth2.Config {
return &oauth2.Config{
ClientID: s.config.OIDC.Client.ID,
ClientSecret: s.config.OIDC.Client.Secret,
RedirectURL: s.config.OIDC.Client.RedirectURL,
Endpoint: s.provider.Endpoint(),
Scopes: scopes,
}
}
// PrepareCallbackURL build and return
// an authCodeURL based on scopes provided
func (s *Server) PrepareCallbackURL() string {
// Prepare scopes
var (
scopes []string
authCodeURL string
)
scopes = append(scopes, s.config.OIDC.ExtraScopes...)
// Prepare cross client auth
// see https://github.com/coreos/dex/blob/master/Documentation/custom-scopes-claims-clients.md
for _, crossClient := range s.config.OIDC.CrossClients {
scopes = append(scopes, "audience:server:client_id:"+crossClient)
}
scopes = append(scopes, "openid", "profile", "email", "groups")
if *s.config.OIDC.OfflineAsScope {
scopes = append(scopes, "offline_access")
authCodeURL = s.OAuth2Config(scopes).AuthCodeURL(s.config.Name)
} else {
authCodeURL = s.OAuth2Config(scopes).AuthCodeURL(s.config.Name)
}
logger.Debugf("Request token with the following scopes: %v", scopes)
return authCodeURL
}
// HandleGetIndex serves
// requests to index.html page
func (s *Server) HandleGetIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
renderTemplate(w, indexTmpl, s.config)
}
// HandleGetHealthz serves
// healthchecks requests (mainly
// used by kubernetes healthchecks)
// 200: OK, 500 otherwise
func (s *Server) HandleGetHealthz(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Check if provider is setup
if s.provider == nil {
logger.Debug("Provider is not yet setup or unavailable")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
// Check if our application can still contact the provider
wellKnown := strings.TrimSuffix(s.config.OIDC.Issuer.URL, "/") + "/.well-known/openid-configuration"
_, err := s.client.Head(wellKnown)
if err != nil {
logger.Debugf("Error while checking provider access: %v", err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
// Should we add more checks ?
w.WriteHeader(http.StatusOK)
}
// HandleLogin redirect to
// our IdP
func (s *Server) HandleLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
http.Redirect(w, r, s.PrepareCallbackURL(), http.StatusSeeOther)
}
// HandleGetCallback serves
// callback requests (from our IdP)
func (s *Server) HandleGetCallback(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
kc, err := s.ProcessCallback(w, r)
if err != nil {
logger.Errorf("error handling cli callback: %v", err)
return
}
renderTemplate(w, tokenTmpl, kc)
}
// ProcessCallback check callback
// from our IdP after a successful user
// login.
func (s *Server) ProcessCallback(w http.ResponseWriter, r *http.Request) (KubeUserInfo, error) {
var (
err error
token *oauth2.Token
jsonClaims map[string]interface{}
)
oauth2Config := s.OAuth2Config(nil)
// Authorization redirect callback from OAuth2 auth flow.
if errMsg := r.FormValue("error"); errMsg != "" {
msg := fmt.Sprintf("%v: %v", errMsg, r.FormValue("error_description"))
http.Error(w, msg, http.StatusBadRequest)
return KubeUserInfo{}, fmt.Errorf(msg)
}
code := r.FormValue("code")
if code == "" {
msg := fmt.Sprintf("no code in request: %q", r.Form)
http.Error(w, msg, http.StatusBadRequest)
return KubeUserInfo{}, fmt.Errorf(msg)
}
if state := r.FormValue("state"); state != s.config.Name {
msg := fmt.Sprintf("expected state %q got %q", s.config.Name, state)
http.Error(w, msg, http.StatusBadRequest)
return KubeUserInfo{}, fmt.Errorf(msg)
}
token, err = oauth2Config.Exchange(s.context, code)
if err != nil {
msg := fmt.Sprintf("failed to get token: %v", err)
http.Error(w, msg, http.StatusInternalServerError)
return KubeUserInfo{}, fmt.Errorf(msg)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
msg := "no id_token in token response"
http.Error(w, msg, http.StatusInternalServerError)
return KubeUserInfo{}, fmt.Errorf(msg)
}
idToken, err := s.verifier.Verify(r.Context(), rawIDToken)
if err != nil {
msg := fmt.Sprintf("Failed to verify ID token: %v", err)
http.Error(w, msg, http.StatusInternalServerError)
return KubeUserInfo{}, fmt.Errorf(msg)
}
var claims json.RawMessage
if err := idToken.Claims(&claims); err != nil {
return KubeUserInfo{}, fmt.Errorf("Failed to unmarshal claims from idToken: %v", err)
}
buff := new(bytes.Buffer)
if err := json.Indent(buff, []byte(claims), "", " "); err != nil {
return KubeUserInfo{}, fmt.Errorf("Failed to format claims output: %v", err)
}
if err := json.Unmarshal(claims, &jsonClaims); err != nil {
panic(err)
}
var usernameClaim interface{}
if usernameClaim = jsonClaims[s.config.WebOutput.MainUsernameClaim]; usernameClaim == nil {
msg := fmt.Sprintf("Failed to find a claim matching the main_username_claim '%v'", s.config.WebOutput.MainUsernameClaim)
http.Error(w, msg, http.StatusInternalServerError)
return KubeUserInfo{}, fmt.Errorf(msg)
}
logger.Debugf("Token issued with claims: %v", jsonClaims)
return KubeUserInfo{
IDToken: rawIDToken,
RefreshToken: token.RefreshToken,
RedirectURL: oauth2Config.RedirectURL,
Claims: jsonClaims,
ClientSecret: s.config.OIDC.Client.Secret,
ClientID: s.config.WebOutput.MainClientID,
UsernameClaim: usernameClaim.(string),
Name: s.config.Name,
IDPCA: s.idpCA,
ClusterServer: s.config.Template.ClusterServer,
ClusterCA: s.clusterCA,
ClusterName: s.config.Template.ClusterName,
ContextName: s.config.Template.ContextName,
}, nil
}
// loggingHandler catch requests,
// add metadata and log user requests
func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
logger.WithFields(logrus.Fields{
"method": r.Method,
"path": r.URL.String(),
"request_duration": t2.Sub(t1).String(),
"protocol": r.Proto,
"remote_address": r.RemoteAddr,
}).Info()
}
return http.HandlerFunc(fn)
}
// Run launch app
func (s *Server) Run() error {
var (
provider *oidc.Provider
backoffErr error
)
// router setup
s.router = httprouter.New()
if s.config.WebOutput.SkipMainPage {
s.router.GET("/", s.HandleLogin)
logger.Debug("routes loaded, skipping main page")
} else {
s.router.GET("/", s.HandleGetIndex)
s.router.POST("/login", s.HandleLogin)
logger.Debug("routes loaded, using main page")
}
s.router.GET("/callback", s.HandleGetCallback)
s.router.GET("/healthz", s.HandleGetHealthz)
s.router.ServeFiles("/assets/*filepath", http.Dir(s.config.WebOutput.AssetsDir))
s.router.Handler(http.MethodGet, "/metrics", promhttp.Handler())
// client setup
if s.client == nil {
client, err := httpClientForRootCAs(s.config.OIDC.Issuer.RootCA)
if err != nil {
return err
}
s.client = client
}
// OIDC setup
// Retry with backoff
s.context = oidc.ClientContext(context.Background(), s.client)
setupProvider := func() error {
if provider, backoffErr = oidc.NewProvider(s.context, s.config.OIDC.Issuer.URL); backoffErr != nil {
logger.Errorf("Failed to query provider %q: %v", s.config.OIDC.Issuer.URL, backoffErr)
return backoffErr
}
return nil
}
if err := backoff.Retry(setupProvider, backoff.NewExponentialBackOff()); err != nil {
return err
}
var ss struct {
// What scopes does a provider support?
//
// See: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
ScopesSupported []string `json:"scopes_supported"`
}
if err := provider.Claims(&ss); err != nil {
return fmt.Errorf("Failed to parse provider scopes_supported: %v", err)
}
if s.config.OIDC.OfflineAsScope == nil {
if len(ss.ScopesSupported) > 0 {
// See if scopes_supported has the "offline_access" scope.
s.config.OIDC.OfflineAsScope = func() *bool {
b := new(bool)
for _, scope := range ss.ScopesSupported {
if scope == oidc.ScopeOfflineAccess {
*b = true
return b
}
}
*b = false
return b
}()
}
}
s.provider = provider
s.verifier = provider.Verifier(&oidc.Config{ClientID: s.config.OIDC.Client.ID})
if s.config.OIDC.Issuer.RootCA != "" {
rootCABytes, err := ioutil.ReadFile(s.config.OIDC.Issuer.RootCA)
if err != nil {
return fmt.Errorf("failed to read root-ca: %v", err)
}
s.idpCA = base64.StdEncoding.EncodeToString(rootCABytes)
}
if s.config.Template.ClusterCA != "" {
clusterCABytes, err := ioutil.ReadFile(s.config.Template.ClusterCA)
if err != nil {
return fmt.Errorf("failed to read cluster-ca: %v", err)
}
s.clusterCA = base64.StdEncoding.EncodeToString(clusterCABytes)
}
// Run
if s.config.TLS.Enabled {
logger.Infof("listening on https://%s", s.config.Listen)
if err := fmt.Errorf("%v", http.ListenAndServeTLS(s.config.Listen, s.config.TLS.Cert, s.config.TLS.Key, loggingHandler(s.router))); err != nil {
return err
}
} else {
logger.Infof("listening on http://%s", s.config.Listen)
if err := fmt.Errorf("%v", http.ListenAndServe(s.config.Listen, loggingHandler(s.router))); err != nil {
return err
}
}
return nil
}
func main() {
app := NewCli()
if err := app.Run(os.Args); err != nil {
logger.Fatal(err)
}
}