This repository has been archived by the owner on Oct 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
common.go
260 lines (221 loc) · 10.2 KB
/
common.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
// Copyright (c) 2021 Red Hat, Inc.
// 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 controllers
import (
"context"
"errors"
"fmt"
"html/template"
"net/http"
"strings"
"time"
"github.com/kcp-dev/logicalcluster/v2"
"github.com/redhat-appstudio/service-provider-integration-operator/pkg/logs"
v1 "k8s.io/api/authorization/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
"github.com/redhat-appstudio/service-provider-integration-operator/api/v1beta1"
"github.com/redhat-appstudio/service-provider-integration-operator/pkg/spi-shared/config"
"github.com/redhat-appstudio/service-provider-integration-operator/pkg/spi-shared/oauthstate"
"github.com/redhat-appstudio/service-provider-integration-operator/pkg/spi-shared/tokenstorage"
"golang.org/x/oauth2"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var (
noActiveSessionError = errors.New("no active oauth session found")
)
// commonController is the implementation of the Controller interface that assumes typical OAuth flow.
type commonController struct {
Config config.ServiceProviderConfiguration
K8sClient AuthenticatingClient
TokenStorage tokenstorage.TokenStorage
Endpoint oauth2.Endpoint
BaseUrl string
RedirectTemplate *template.Template
Authenticator *Authenticator
StateStorage *StateStorage
}
// exchangeState is the state that we're sending out to the SP after checking the anonymous oauth state produced by
// the operator as the initial OAuth URL. Notice that the state doesn't contain any sensitive information.
type exchangeState struct {
oauthstate.OAuthInfo
}
// exchangeResult this the result of the OAuth exchange with all the data necessary to store the token into the storage
type exchangeResult struct {
exchangeState
result oauthFinishResult
token *oauth2.Token
authorizationHeader string
}
// newOAuth2Config returns a new instance of the oauth2.Config struct with the clientId, clientSecret and redirect URL
// specific to this controller.
func (c *commonController) newOAuth2Config() oauth2.Config {
return oauth2.Config{
ClientID: c.Config.ClientId,
ClientSecret: c.Config.ClientSecret,
RedirectURL: c.redirectUrl(),
}
}
// redirectUrl constructs the URL to the callback endpoint so that it can be handled by this controller.
func (c *commonController) redirectUrl() string {
return strings.TrimSuffix(c.BaseUrl, "/") + "/" + strings.ToLower(string(c.Config.ServiceProviderType)) + "/callback"
}
func (c commonController) Authenticate(w http.ResponseWriter, r *http.Request) {
log := log.FromContext(r.Context())
defer logs.TimeTrack(log, time.Now(), "/authenticate")
stateString := r.FormValue("state")
state, err := oauthstate.ParseOAuthInfo(stateString)
if err != nil {
LogErrorAndWriteResponse(r.Context(), w, http.StatusBadRequest, "failed to decode the OAuth state", err)
return
}
token, err := c.Authenticator.GetToken(r)
if err != nil {
LogErrorAndWriteResponse(r.Context(), w, http.StatusUnauthorized, "No active session was found. Please use `/login` method to authorize your request and try again. Or provide the token as a `k8s_token` query parameter.", err)
return
}
hasAccess, err := c.checkIdentityHasAccess(token, r, state)
if err != nil {
LogErrorAndWriteResponse(r.Context(), w, http.StatusInternalServerError, "failed to determine if the authenticated user has access", err)
log.Error(err, "The token is incorrect or the SPI OAuth service is not configured properly "+
"and the API_SERVER environment variable points it to the incorrect Kubernetes API server. "+
"If SPI is running with Devsandbox Proxy or KCP, make sure this env var points to the Kubernetes API proxy,"+
" otherwise unset this variable. See more https://github.com/redhat-appstudio/infra-deployments/pull/264")
return
}
if !hasAccess {
LogDebugAndWriteResponse(r.Context(), w, http.StatusUnauthorized, "authenticating the request in Kubernetes unsuccessful")
return
}
AuditLogWithTokenInfo(r.Context(), "OAuth authentication flow started", state.TokenNamespace, state.TokenName, "scopes", state.Scopes, "providerType", string(state.ServiceProviderType), "providerUrl", state.ServiceProviderUrl, "kcpWorkspace", state.TokenKcpWorkspace)
newStateString, err := c.StateStorage.VeilRealState(r)
if err != nil {
LogErrorAndWriteResponse(r.Context(), w, http.StatusBadRequest, err.Error(), err)
return
}
keyedState := exchangeState{
OAuthInfo: state,
}
oauthCfg := c.newOAuth2Config()
oauthCfg.Endpoint = c.Endpoint
oauthCfg.Scopes = keyedState.Scopes
templateData := struct {
Url string
}{
Url: oauthCfg.AuthCodeURL(newStateString),
}
log.V(logs.DebugLevel).Info("Redirecting ", "url", templateData.Url)
err = c.RedirectTemplate.Execute(w, templateData)
if err != nil {
LogErrorAndWriteResponse(r.Context(), w, http.StatusInternalServerError, "failed to return redirect notice HTML page", err)
return
}
}
func (c commonController) Callback(ctx context.Context, w http.ResponseWriter, r *http.Request) {
lg := log.FromContext(ctx)
defer logs.TimeTrack(lg, time.Now(), "/callback")
exchange, err := c.finishOAuthExchange(ctx, r, c.Endpoint)
if err != nil {
LogErrorAndWriteResponse(ctx, w, http.StatusBadRequest, "error in Service Provider token exchange", err)
return
}
ctx = logicalcluster.WithCluster(ctx, logicalcluster.New(exchange.TokenKcpWorkspace))
if exchange.result == oauthFinishK8sAuthRequired {
LogErrorAndWriteResponse(ctx, w, http.StatusUnauthorized, "could not authenticate to Kubernetes", err)
return
}
err = c.syncTokenData(ctx, &exchange)
if err != nil {
LogErrorAndWriteResponse(ctx, w, http.StatusInternalServerError, "failed to store token data to cluster", err)
return
}
AuditLogWithTokenInfo(ctx, "OAuth authentication completed successfully", exchange.TokenNamespace, exchange.TokenName, "scopes", exchange.Scopes, "providerType", string(exchange.ServiceProviderType), "providerUrl", exchange.ServiceProviderUrl, "kcpWorkspace", exchange.TokenKcpWorkspace)
redirectLocation := r.FormValue("redirect_after_login")
if redirectLocation == "" {
redirectLocation = strings.TrimSuffix(c.BaseUrl, "/") + "/" + "callback_success"
}
http.Redirect(w, r, redirectLocation, http.StatusFound)
}
// finishOAuthExchange implements the bulk of the Callback function. It returns the token, if obtained, the decoded
// state from the oauth flow, if available, and the result of the authentication.
func (c commonController) finishOAuthExchange(ctx context.Context, r *http.Request, endpoint oauth2.Endpoint) (exchangeResult, error) {
// TODO support the implicit flow here, too?
// check that the state is correct
stateString, err := c.StateStorage.UnveilState(ctx, r)
if err != nil {
return exchangeResult{result: oauthFinishError}, fmt.Errorf("failed to unveil token state: %w", err)
}
state := &exchangeState{}
err = oauthstate.ParseInto(stateString, state)
if err != nil {
return exchangeResult{result: oauthFinishError}, fmt.Errorf("failed to parse JWT state string: %w", err)
}
k8sToken, err := c.Authenticator.GetToken(r) //nolint:contextCheck // no idea why contextCheck is complaining here - we're not doing any HTTP requests with this call
if err != nil {
return exchangeResult{result: oauthFinishK8sAuthRequired}, noActiveSessionError
}
// the state is ok, let's retrieve the token from the service provider
oauthCfg := c.newOAuth2Config()
oauthCfg.Endpoint = endpoint
code := r.FormValue("code")
// adding scopes to code exchange request is little out of spec, but quay wants them,
// while other providers will just ignore this parameter
scopeOption := oauth2.SetAuthURLParam("scope", r.FormValue("scope"))
token, err := oauthCfg.Exchange(ctx, code, scopeOption)
if err != nil {
return exchangeResult{result: oauthFinishError}, fmt.Errorf("failed to finish the OAuth exchange: %w", err)
}
return exchangeResult{
exchangeState: *state,
result: oauthFinishAuthenticated,
token: token,
authorizationHeader: k8sToken,
}, nil
}
// syncTokenData stores the data of the token to the configured TokenStorage.
func (c commonController) syncTokenData(ctx context.Context, exchange *exchangeResult) error {
ctx = WithAuthIntoContext(exchange.authorizationHeader, ctx)
accessToken := &v1beta1.SPIAccessToken{}
if err := c.K8sClient.Get(ctx, client.ObjectKey{Name: exchange.TokenName, Namespace: exchange.TokenNamespace}, accessToken); err != nil {
return fmt.Errorf("failed to get the SPIAccessToken object %s/%s: %w", exchange.TokenNamespace, exchange.TokenName, err)
}
apiToken := v1beta1.Token{
AccessToken: exchange.token.AccessToken,
TokenType: exchange.token.TokenType,
RefreshToken: exchange.token.RefreshToken,
Expiry: uint64(exchange.token.Expiry.Unix()),
}
if err := c.TokenStorage.Store(ctx, accessToken, &apiToken); err != nil {
return fmt.Errorf("failed to persist the token to storage: %w", err)
}
return nil
}
func (c *commonController) checkIdentityHasAccess(token string, req *http.Request, state oauthstate.OAuthInfo) (bool, error) {
review := v1.SelfSubjectAccessReview{
Spec: v1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &v1.ResourceAttributes{
Namespace: state.TokenNamespace,
Verb: "create",
Group: v1beta1.GroupVersion.Group,
Version: v1beta1.GroupVersion.Version,
Resource: "spiaccesstokendataupdates",
},
},
}
ctx := WithAuthIntoContext(token, req.Context())
ctx = logicalcluster.WithCluster(ctx, logicalcluster.New(state.TokenKcpWorkspace))
if err := c.K8sClient.Create(ctx, &review); err != nil {
return false, fmt.Errorf("failed to create SelfSubjectAccessReview: %w", err)
}
log.FromContext(req.Context()).V(logs.DebugLevel).Info("self subject review result", "review", &review)
return review.Status.Allowed, nil
}