/
oidc_connect.go
315 lines (257 loc) · 8.94 KB
/
oidc_connect.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
310
311
312
313
314
315
// Copyright Project Contour Authors
// 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.
package auth
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"github.com/allegro/bigcache"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-logr/logr"
"github.com/snapp-incubator/contour-auth-multi-tenant/pkg/config"
"github.com/snapp-incubator/contour-auth-multi-tenant/pkg/store"
"golang.org/x/oauth2"
)
const (
stateQueryParamName = "conauth"
oauthTokenName = "contourtoken"
)
// OIDCConnect defines parameters for an OIDC auth provider.
type OIDCConnect struct {
Log logr.Logger
OidcConfig *config.OIDCConfig
Cache *bigcache.BigCache
HTTPClient *http.Client
provider *oidc.Provider
}
// Implement interface.
var _ Checker = &OIDCConnect{}
// Check entry point for authentication. it accepts incoming request and redirects un-authenticated requests to
// IDP. Otherwise, it will route user to the intended url.
func (o *OIDCConnect) Check(ctx context.Context, req *Request) (*Response, error) {
o.Log.Info("checking request",
"host", req.Request.Host,
"path", req.Request.URL.Path,
"id", req.ID,
)
if o.provider == nil {
o.provider, _ = o.initProvider(ctx)
}
url := parseURL(req)
// Check if the current request matches the callback path.
if url.Path == o.OidcConfig.RedirectPath {
resp, err := o.callbackHandler(ctx, url)
return &resp, err
}
// Validate the state.
resp, valid, err := o.isValidState(ctx, req, url)
if err != nil {
return &resp, err
}
// If state is invalid, redirect to login handler.
if !valid {
resp = o.loginHandler(url)
return &resp, nil
}
return &resp, nil
}
// isValidState checks the user token and state validity for subsequent calls.
func (o *OIDCConnect) isValidState(ctx context.Context, req *Request, url *url.URL) (Response, bool, error) {
// Do we have stateid stored in querystring
var state *store.OIDCState
stateToken := url.Query().Get(stateQueryParamName)
stateByte, err := o.Cache.Get(stateToken)
if err == nil {
state = store.ConvertToType(stateByte)
}
// State not found, try to retrieve from cookies.
if state == nil {
state, _ = o.getStateFromCookie(req)
}
// State exists, proceed with token validation.
if state != nil {
// Re-initialize provider to refresh the context, this seems like bugs with coreos go-oidc module.
provider, err := o.initProvider(ctx)
if err != nil {
o.Log.Error(err, "fail to initialize provider")
return createResponse(http.StatusInternalServerError), false, err
}
if o.isValidStateToken(ctx, state, provider) {
stateJSON, _ := json.Marshal(state)
// Restore cookies.
resp := createResponse(http.StatusOK)
resp.Response.Header.Add(oauthTokenName, string(stateJSON))
if err := o.Cache.Delete(state.OAuthState); err != nil {
o.Log.Error(err, "error deleting state")
}
return resp, true, nil
}
}
// return empty response, will direct to loginHandler
return Response{}, false, nil
}
// loginHandler takes a url returning a Response with a new state that is required by oauth during initial user login.
func (o *OIDCConnect) loginHandler(u *url.URL) Response {
state := store.NewState()
state.GenerateOauthState()
state.RequestPath = path.Join(u.Host, u.Path)
state.Scheme = u.Scheme
authCodeURL := o.oauth2Config().AuthCodeURL(state.OAuthState)
byteState := store.ConvertToByte(state)
if err := o.Cache.Set(state.OAuthState, byteState); err != nil {
o.Log.Error(err, "error setting cache state")
}
resp := createResponse(http.StatusFound)
resp.Response.Header.Add(oauthTokenName, "")
resp.Response.Header.Add("Location", authCodeURL)
return resp
}
// callbackHandler takes an url validating the state, code and token validity. Returns a response redirect
// to their intended destination.
func (o *OIDCConnect) callbackHandler(ctx context.Context, u *url.URL) (Response, error) {
// 1. Get all variable needed.
oauthState := u.Query().Get("state")
code := u.Query().Get("code")
// 2 Check state and code validity.
if code == "" || oauthState == "" {
// 2.1 Code and State is empty, return Bad Request
err := fmt.Errorf("Code and State is not available")
return createResponse(http.StatusBadRequest), err
}
stateByte, err := o.Cache.Get(oauthState)
if err != nil {
// 2.2 State invalid , return Bad Request
o.Log.Error(err, "Invalid state, expected oAuthState not found", "oauthState", oauthState)
return createResponse(http.StatusBadRequest), err
}
// Retrieve token. and check token validity
context := oidc.ClientContext(ctx, o.HTTPClient)
token, err := o.oauth2Config().Exchange(context, code)
if err != nil {
// 2.3.1 Token invalid, return Internal Server Error
o.Log.Error(err, "Token exchange error")
return createResponse(http.StatusInternalServerError), err
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
// 2.3.2 Token invalid, return Internal Server Error
return createResponse(http.StatusInternalServerError), fmt.Errorf("Invalid token id")
}
//Store token.
state := store.ConvertToType(stateByte)
state.IDToken = rawIDToken
state.AccessToken = token.AccessToken
state.RefreshToken = token.RefreshToken
stateByte = store.ConvertToByte(state)
if err := o.Cache.Set(state.OAuthState, stateByte); err != nil {
o.Log.Error(err, "error setting cache state")
}
// Set redirection.
resp := createResponse(http.StatusTemporaryRedirect)
resp.Response.Header.Add(stateQueryParamName, state.OAuthState)
// TODO(robinfoe) #18 : OIDC support should propagate any claims back to the request
resp.Response.Header.Add("Location",
fmt.Sprintf("%s://%s?%s=%s", state.Scheme, state.RequestPath, stateQueryParamName, state.OAuthState))
return resp, nil
}
// isValidStateToken verify token and signature.
func (o *OIDCConnect) isValidStateToken(ctx context.Context, state *store.OIDCState, provider *oidc.Provider) bool {
if state == nil {
return false
}
verifier := provider.Verifier(&oidc.Config{
ClientID: o.OidcConfig.ClientID,
SkipIssuerCheck: o.OidcConfig.SkipIssuerCheck,
})
// Verify token and signature.
idToken, err := verifier.Verify(ctx, state.IDToken)
if err != nil {
o.Log.Info(fmt.Sprintf("failed to verify ID token: %v", err))
return false
}
// TODO(robinfoe) #18 : OIDC support should propagate any claims back to the request
// Try to claim.
var claims json.RawMessage
if err := idToken.Claims(&claims); err != nil {
o.Log.Error(err, "error decoding ID token")
return false
}
return true
}
// getStateFromCookie retrieve state token from cookie header and return the value as OIDCState.
func (o *OIDCConnect) getStateFromCookie(req *Request) (*store.OIDCState, error) {
var state *store.OIDCState
cookieVal := req.Request.Header.Get("cookie")
// Check through and get the right cookies
if len(cookieVal) > 0 {
cookies := strings.Split(cookieVal, ";")
for _, c := range cookies {
c = strings.TrimSpace(c)
if strings.HasPrefix(c, oauthTokenName) {
cookieJSON := c[len(oauthTokenName)+1:]
if len(cookieJSON) > 0 {
state = store.ConvertToType([]byte(cookieJSON))
return state, nil
}
}
}
}
return nil, fmt.Errorf("no %q cookie", oauthTokenName)
}
// initProvider initialize oidc provide with ths given issuer URL. return oidc.Provider.
func (o *OIDCConnect) initProvider(ctx context.Context) (*oidc.Provider, error) {
provider, err := oidc.NewProvider(ctx, o.OidcConfig.IssuerURL)
if err != nil {
o.Log.Error(err, "Unable to initialize provider", "issuerUrl", o.OidcConfig.IssuerURL)
return nil, err
}
return provider, nil
}
// oauth2Config factory method to oauth2Config.
func (o *OIDCConnect) oauth2Config() *oauth2.Config {
return &oauth2.Config{
ClientID: o.OidcConfig.ClientID,
ClientSecret: o.OidcConfig.ClientSecret,
Endpoint: o.provider.Endpoint(),
Scopes: o.OidcConfig.Scopes,
RedirectURL: o.OidcConfig.RedirectURL + o.OidcConfig.RedirectPath,
}
}
// createResponse helper class to create response. Accept status code and return Response.
func createResponse(status int) Response {
allow := status == http.StatusOK
return Response{
Response: http.Response{
StatusCode: status, // defaulted to unauthorized
Header: http.Header{},
},
Allow: allow,
}
}
func parseURL(req *Request) *url.URL {
plainURL, _ := url.QueryUnescape(req.Request.URL.String())
u, err := url.Parse(plainURL)
if err != nil {
return nil
}
if s, ok := req.Request.Header["X-Forwarded-Proto"]; ok {
u.Scheme = s[0]
} else {
u.Scheme = "http"
}
return u
}