Skip to content

Commit 6ad2935

Browse files
committed
use oauth client instead of registry
1 parent 021c3b4 commit 6ad2935

File tree

20 files changed

+251
-589
lines changed

20 files changed

+251
-589
lines changed

pkg/auth/oauth/registry/grantchecker.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,25 @@ import (
55

66
"k8s.io/apimachinery/pkg/api/errors"
77
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
8-
apirequest "k8s.io/apiserver/pkg/endpoints/request"
8+
"k8s.io/apiserver/pkg/authentication/user"
99

1010
"github.com/openshift/origin/pkg/auth/api"
11+
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset/typed/oauth/internalversion"
1112
"github.com/openshift/origin/pkg/oauth/registry/oauthclientauthorization"
1213
"github.com/openshift/origin/pkg/oauth/scope"
13-
"k8s.io/apiserver/pkg/authentication/user"
1414
)
1515

1616
type ClientAuthorizationGrantChecker struct {
17-
registry oauthclientauthorization.Registry
17+
client oauthclient.OAuthClientAuthorizationInterface
1818
}
1919

20-
func NewClientAuthorizationGrantChecker(registry oauthclientauthorization.Registry) *ClientAuthorizationGrantChecker {
21-
return &ClientAuthorizationGrantChecker{registry}
20+
func NewClientAuthorizationGrantChecker(client oauthclient.OAuthClientAuthorizationInterface) *ClientAuthorizationGrantChecker {
21+
return &ClientAuthorizationGrantChecker{client}
2222
}
2323

2424
func (c *ClientAuthorizationGrantChecker) HasAuthorizedClient(user user.Info, grant *api.Grant) (approved bool, err error) {
25-
id := c.registry.ClientAuthorizationName(user.GetName(), grant.Client.GetId())
26-
authorization, err := c.registry.GetClientAuthorization(apirequest.NewContext(), id, &metav1.GetOptions{})
25+
id := oauthclientauthorization.ClientAuthorizationName(user.GetName(), grant.Client.GetId())
26+
authorization, err := c.client.Get(id, metav1.GetOptions{})
2727
if errors.IsNotFound(err) {
2828
return false, nil
2929
}

pkg/auth/oauth/registry/tokenauthenticator.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,24 @@ import (
55
"fmt"
66
"time"
77

8+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
9+
kuser "k8s.io/apiserver/pkg/authentication/user"
10+
811
"github.com/openshift/origin/pkg/auth/userregistry/identitymapper"
912
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
10-
"github.com/openshift/origin/pkg/oauth/registry/oauthaccesstoken"
13+
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset/typed/oauth/internalversion"
1114
userclient "github.com/openshift/origin/pkg/user/generated/internalclientset/typed/user/internalversion"
12-
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
13-
kuser "k8s.io/apiserver/pkg/authentication/user"
14-
kapirequest "k8s.io/apiserver/pkg/endpoints/request"
1515
)
1616

1717
type TokenAuthenticator struct {
18-
tokens oauthaccesstoken.Registry
18+
tokens oauthclient.OAuthAccessTokenInterface
1919
users userclient.UserResourceInterface
2020
groupMapper identitymapper.UserToGroupMapper
2121
}
2222

2323
var ErrExpired = errors.New("Token is expired")
2424

25-
func NewTokenAuthenticator(tokens oauthaccesstoken.Registry, users userclient.UserResourceInterface, groupMapper identitymapper.UserToGroupMapper) *TokenAuthenticator {
25+
func NewTokenAuthenticator(tokens oauthclient.OAuthAccessTokenInterface, users userclient.UserResourceInterface, groupMapper identitymapper.UserToGroupMapper) *TokenAuthenticator {
2626
return &TokenAuthenticator{
2727
tokens: tokens,
2828
users: users,
@@ -31,9 +31,7 @@ func NewTokenAuthenticator(tokens oauthaccesstoken.Registry, users userclient.Us
3131
}
3232

3333
func (a *TokenAuthenticator) AuthenticateToken(value string) (kuser.Info, bool, error) {
34-
ctx := kapirequest.NewContext()
35-
36-
token, err := a.tokens.GetAccessToken(ctx, value, &metav1.GetOptions{})
34+
token, err := a.tokens.Get(value, metav1.GetOptions{})
3735
if err != nil {
3836
return nil, false, err
3937
}

pkg/auth/server/grant/grant.go

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ import (
1111
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
1212
"k8s.io/apiserver/pkg/authentication/serviceaccount"
1313
"k8s.io/apiserver/pkg/authentication/user"
14-
apirequest "k8s.io/apiserver/pkg/endpoints/request"
1514

1615
"github.com/golang/glog"
1716
"github.com/openshift/origin/pkg/auth/authenticator"
1817
"github.com/openshift/origin/pkg/auth/server/csrf"
1918
scopeauthorizer "github.com/openshift/origin/pkg/authorization/authorizer/scope"
2019
oapi "github.com/openshift/origin/pkg/oauth/apis/oauth"
21-
"github.com/openshift/origin/pkg/oauth/registry/oauthclient"
20+
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset/typed/oauth/internalversion"
21+
oauthclientregistry "github.com/openshift/origin/pkg/oauth/registry/oauthclient"
2222
"github.com/openshift/origin/pkg/oauth/registry/oauthclientauthorization"
2323
"github.com/openshift/origin/pkg/oauth/scope"
2424
)
@@ -82,11 +82,11 @@ type Grant struct {
8282
auth authenticator.Request
8383
csrf csrf.CSRF
8484
render FormRenderer
85-
clientregistry oauthclient.Getter
86-
authregistry oauthclientauthorization.Registry
85+
clientregistry oauthclientregistry.Getter
86+
authregistry oauthclient.OAuthClientAuthorizationInterface
8787
}
8888

89-
func NewGrant(csrf csrf.CSRF, auth authenticator.Request, render FormRenderer, clientregistry oauthclient.Getter, authregistry oauthclientauthorization.Registry) *Grant {
89+
func NewGrant(csrf csrf.CSRF, auth authenticator.Request, render FormRenderer, clientregistry oauthclientregistry.Getter, authregistry oauthclient.OAuthClientAuthorizationInterface) *Grant {
9090
return &Grant{
9191
auth: auth,
9292
csrf: csrf,
@@ -129,7 +129,7 @@ func (l *Grant) handleForm(user user.Info, w http.ResponseWriter, req *http.Requ
129129
scopes := scope.Split(q.Get(scopeParam))
130130
redirectURI := q.Get(redirectURIParam)
131131

132-
client, err := l.clientregistry.GetClient(apirequest.NewContext(), clientID, &metav1.GetOptions{})
132+
client, err := l.clientregistry.Get(clientID, metav1.GetOptions{})
133133
if err != nil || client == nil {
134134
l.failed("Could not find client for client_id", w, req)
135135
return
@@ -152,8 +152,8 @@ func (l *Grant) handleForm(user user.Info, w http.ResponseWriter, req *http.Requ
152152
grantedScopes := []Scope{}
153153
requestedScopes := []Scope{}
154154

155-
clientAuthID := l.authregistry.ClientAuthorizationName(user.GetName(), client.Name)
156-
if clientAuth, err := l.authregistry.GetClientAuthorization(apirequest.NewContext(), clientAuthID, &metav1.GetOptions{}); err == nil {
155+
clientAuthID := oauthclientauthorization.ClientAuthorizationName(user.GetName(), client.Name)
156+
if clientAuth, err := l.authregistry.Get(clientAuthID, metav1.GetOptions{}); err == nil {
157157
grantedScopeNames = clientAuth.Scopes
158158
}
159159

@@ -233,7 +233,7 @@ func (l *Grant) handleGrant(user user.Info, w http.ResponseWriter, req *http.Req
233233
}
234234

235235
clientID := req.PostFormValue(clientIDParam)
236-
client, err := l.clientregistry.GetClient(apirequest.NewContext(), clientID, &metav1.GetOptions{})
236+
client, err := l.clientregistry.Get(clientID, metav1.GetOptions{})
237237
if err != nil || client == nil {
238238
l.failed("Could not find client for client_id", w, req)
239239
return
@@ -244,14 +244,13 @@ func (l *Grant) handleGrant(user user.Info, w http.ResponseWriter, req *http.Req
244244
return
245245
}
246246

247-
clientAuthID := l.authregistry.ClientAuthorizationName(user.GetName(), client.Name)
247+
clientAuthID := oauthclientauthorization.ClientAuthorizationName(user.GetName(), client.Name)
248248

249-
ctx := apirequest.NewContext()
250-
clientAuth, err := l.authregistry.GetClientAuthorization(ctx, clientAuthID, &metav1.GetOptions{})
249+
clientAuth, err := l.authregistry.Get(clientAuthID, metav1.GetOptions{})
251250
if err == nil && clientAuth != nil {
252251
// Add new scopes and update
253252
clientAuth.Scopes = scope.Add(clientAuth.Scopes, scope.Split(scopes))
254-
if _, err = l.authregistry.UpdateClientAuthorization(ctx, clientAuth); err != nil {
253+
if _, err = l.authregistry.Update(clientAuth); err != nil {
255254
glog.Errorf("Unable to update authorization: %v", err)
256255
l.failed("Could not update client authorization", w, req)
257256
return
@@ -266,7 +265,7 @@ func (l *Grant) handleGrant(user user.Info, w http.ResponseWriter, req *http.Req
266265
}
267266
clientAuth.Name = clientAuthID
268267

269-
if _, err = l.authregistry.CreateClientAuthorization(ctx, clientAuth); err != nil {
268+
if _, err = l.authregistry.Create(clientAuth); err != nil {
270269
glog.Errorf("Unable to create authorization: %v", err)
271270
l.failed("Could not create client authorization", w, req)
272271
return

pkg/cmd/server/origin/master.go

Lines changed: 73 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,24 @@ func (c *MasterConfig) newAssetServerHandler() (http.Handler, error) {
180180
return assetServer.GenericAPIServer.PrepareRun().GenericAPIServer.Handler.FullHandlerChain, nil
181181
}
182182

183-
func (c *MasterConfig) newOAuthServerHandler() (http.Handler, error) {
183+
func (c *MasterConfig) newOAuthServerHandler() (http.Handler, map[string]apiserver.PostStartHookFunc, error) {
184184
if c.Options.OAuthConfig == nil {
185-
return http.NotFoundHandler(), nil
185+
return http.NotFoundHandler(), nil, nil
186186
}
187187

188188
config, err := NewOAuthServerConfigFromMasterConfig(c)
189189
if err != nil {
190-
return nil, err
190+
return nil, nil, err
191191
}
192192
oauthServer, err := config.Complete().New(apiserver.EmptyDelegate)
193193
if err != nil {
194-
return nil, err
194+
return nil, nil, err
195195
}
196-
return oauthServer.GenericAPIServer.PrepareRun().GenericAPIServer.Handler.FullHandlerChain, nil
196+
return oauthServer.GenericAPIServer.PrepareRun().GenericAPIServer.Handler.FullHandlerChain,
197+
map[string]apiserver.PostStartHookFunc{
198+
"oauth.openshift.io-RegisterTokenRequestEndpoint": config.EnsureBootstrapOAuthClients,
199+
},
200+
nil
197201
}
198202

199203
func (c *MasterConfig) withAggregator(delegateAPIServer apiserver.DelegationTarget, kubeAPIServerConfig apiserver.Config, apiExtensionsInformers apiextensionsinformers.SharedInformerFactory) (*aggregatorapiserver.APIAggregator, error) {
@@ -216,8 +220,9 @@ func (c *MasterConfig) Run(kubeAPIServerConfig *kubeapiserver.Config, controller
216220
var err error
217221
var apiExtensionsInformers apiextensionsinformers.SharedInformerFactory
218222
var delegateAPIServer apiserver.DelegationTarget
223+
var extraPostStartHooks map[string]apiserver.PostStartHookFunc
219224

220-
kubeAPIServerConfig.GenericConfig.BuildHandlerChainFunc, err = c.buildHandlerChain()
225+
kubeAPIServerConfig.GenericConfig.BuildHandlerChainFunc, extraPostStartHooks, err = c.buildHandlerChain()
221226
if err != nil {
222227
return err
223228
}
@@ -255,79 +260,84 @@ func (c *MasterConfig) Run(kubeAPIServerConfig *kubeapiserver.Config, controller
255260
// add post-start hooks
256261
aggregatedAPIServer.GenericAPIServer.AddPostStartHookOrDie("template.openshift.io-sharednamespace", c.ensureOpenShiftSharedResourcesNamespace)
257262
aggregatedAPIServer.GenericAPIServer.AddPostStartHookOrDie("authorization.openshift.io-bootstrapclusterroles", bootstrappolicy.Policy().EnsureRBACPolicy())
263+
for name, fn := range extraPostStartHooks {
264+
aggregatedAPIServer.GenericAPIServer.AddPostStartHookOrDie(name, fn)
265+
}
258266

259267
go aggregatedAPIServer.GenericAPIServer.PrepareRun().Run(stopCh)
260268

261269
// Attempt to verify the server came up for 20 seconds (100 tries * 100ms, 100ms timeout per try)
262270
return cmdutil.WaitForSuccessfulDial(true, aggregatedAPIServer.GenericAPIServer.SecureServingInfo.BindNetwork, aggregatedAPIServer.GenericAPIServer.SecureServingInfo.BindAddress, 100*time.Millisecond, 100*time.Millisecond, 100)
263271
}
264272

265-
func (c *MasterConfig) buildHandlerChain() (func(apiHandler http.Handler, kc *apiserver.Config) http.Handler, error) {
273+
func (c *MasterConfig) buildHandlerChain() (func(apiHandler http.Handler, kc *apiserver.Config) http.Handler, map[string]apiserver.PostStartHookFunc, error) {
266274
assetServerHandler, err := c.newAssetServerHandler()
267275
if err != nil {
268-
return nil, err
276+
return nil, nil, err
269277
}
270-
oauthServerHandler, err := c.newOAuthServerHandler()
278+
oauthServerHandler, extraPostStartHooks, err := c.newOAuthServerHandler()
271279
if err != nil {
272-
return nil, err
280+
return nil, nil, err
273281
}
274282

275283
return func(apiHandler http.Handler, genericConfig *apiserver.Config) http.Handler {
276-
// these are after the kube handler
277-
handler := c.versionSkewFilter(apiHandler, genericConfig.RequestContextMapper)
278-
handler = namespacingFilter(handler, genericConfig.RequestContextMapper)
279-
280-
// these are all equivalent to the kube handler chain
281-
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
282-
handler = serverhandlers.AuthorizationFilter(handler, c.Authorizer, c.AuthorizationAttributeBuilder, genericConfig.RequestContextMapper)
283-
handler = serverhandlers.ImpersonationFilter(handler, c.Authorizer, cache.NewGroupCache(c.UserInformers.User().InternalVersion().Groups()), genericConfig.RequestContextMapper)
284-
// audit handler must comes before the impersonationFilter to read the original user
285-
if c.Options.AuditConfig.Enabled {
286-
var writer io.Writer
287-
if len(c.Options.AuditConfig.AuditFilePath) > 0 {
288-
writer = &lumberjack.Logger{
289-
Filename: c.Options.AuditConfig.AuditFilePath,
290-
MaxAge: c.Options.AuditConfig.MaximumFileRetentionDays,
291-
MaxBackups: c.Options.AuditConfig.MaximumRetainedFiles,
292-
MaxSize: c.Options.AuditConfig.MaximumFileSizeMegabytes,
284+
// these are after the kube handler
285+
handler := c.versionSkewFilter(apiHandler, genericConfig.RequestContextMapper)
286+
handler = namespacingFilter(handler, genericConfig.RequestContextMapper)
287+
288+
// these are all equivalent to the kube handler chain
289+
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
290+
handler = serverhandlers.AuthorizationFilter(handler, c.Authorizer, c.AuthorizationAttributeBuilder, genericConfig.RequestContextMapper)
291+
handler = serverhandlers.ImpersonationFilter(handler, c.Authorizer, cache.NewGroupCache(c.UserInformers.User().InternalVersion().Groups()), genericConfig.RequestContextMapper)
292+
// audit handler must comes before the impersonationFilter to read the original user
293+
if c.Options.AuditConfig.Enabled {
294+
var writer io.Writer
295+
if len(c.Options.AuditConfig.AuditFilePath) > 0 {
296+
writer = &lumberjack.Logger{
297+
Filename: c.Options.AuditConfig.AuditFilePath,
298+
MaxAge: c.Options.AuditConfig.MaximumFileRetentionDays,
299+
MaxBackups: c.Options.AuditConfig.MaximumRetainedFiles,
300+
MaxSize: c.Options.AuditConfig.MaximumFileSizeMegabytes,
301+
}
302+
} else {
303+
// backwards compatible writer to regular log
304+
writer = cmdutil.NewGLogWriterV(0)
293305
}
294-
} else {
295-
// backwards compatible writer to regular log
296-
writer = cmdutil.NewGLogWriterV(0)
306+
c.AuditBackend = auditlog.NewBackend(writer)
307+
auditPolicyChecker := auditpolicy.NewChecker(&auditinternal.Policy{
308+
// This is for backwards compatibility maintaining the old visibility, ie. just
309+
// raw overview of the requests comming in.
310+
Rules: []auditinternal.PolicyRule{{Level: auditinternal.LevelMetadata}},
311+
})
312+
handler = apifilters.WithAudit(handler, genericConfig.RequestContextMapper, c.AuditBackend, auditPolicyChecker, genericConfig.LongRunningFunc)
297313
}
298-
c.AuditBackend = auditlog.NewBackend(writer)
299-
auditPolicyChecker := auditpolicy.NewChecker(&auditinternal.Policy{
300-
// This is for backwards compatibility maintaining the old visibility, ie. just
301-
// raw overview of the requests comming in.
302-
Rules: []auditinternal.PolicyRule{{Level: auditinternal.LevelMetadata}},
303-
})
304-
handler = apifilters.WithAudit(handler, genericConfig.RequestContextMapper, c.AuditBackend, auditPolicyChecker, genericConfig.LongRunningFunc)
305-
}
306-
handler = serverhandlers.AuthenticationHandlerFilter(handler, c.Authenticator, genericConfig.RequestContextMapper)
307-
handler = apiserverfilters.WithCORS(handler, c.Options.CORSAllowedOrigins, nil, nil, nil, "true")
308-
handler = apiserverfilters.WithTimeoutForNonLongRunningRequests(handler, genericConfig.RequestContextMapper, genericConfig.LongRunningFunc)
309-
// TODO: MaxRequestsInFlight should be subdivided by intent, type of behavior, and speed of
310-
// execution - updates vs reads, long reads vs short reads, fat reads vs skinny reads.
311-
// NOTE: read vs. write is implemented in Kube 1.6+
312-
handler = apiserverfilters.WithMaxInFlightLimit(handler, genericConfig.MaxRequestsInFlight, genericConfig.MaxMutatingRequestsInFlight, genericConfig.RequestContextMapper, genericConfig.LongRunningFunc)
313-
handler = apifilters.WithRequestInfo(handler, apiserver.NewRequestInfoResolver(genericConfig), genericConfig.RequestContextMapper)
314-
handler = apirequest.WithRequestContext(handler, genericConfig.RequestContextMapper)
315-
handler = apiserverfilters.WithPanicRecovery(handler)
316-
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
317-
318-
// these handlers are all before the normal kube chain
319-
handler = cacheControlFilter(handler, "no-store") // protected endpoints should not be cached
320-
321-
if c.WebConsoleEnabled() {
322-
handler = assetapiserver.WithAssetServerRedirect(handler, c.Options.AssetConfig.PublicURL)
323-
}
324-
// these handlers are actually separate API servers which have their own handler chains.
325-
// our server embeds these
326-
handler = c.withConsoleRedirection(handler, assetServerHandler, c.Options.AssetConfig)
327-
handler = c.withOAuthRedirection(handler, oauthServerHandler)
328-
329-
return handler
330-
}, nil
314+
handler = serverhandlers.AuthenticationHandlerFilter(handler, c.Authenticator, genericConfig.RequestContextMapper)
315+
handler = apiserverfilters.WithCORS(handler, c.Options.CORSAllowedOrigins, nil, nil, nil, "true")
316+
handler = apiserverfilters.WithTimeoutForNonLongRunningRequests(handler, genericConfig.RequestContextMapper, genericConfig.LongRunningFunc)
317+
// TODO: MaxRequestsInFlight should be subdivided by intent, type of behavior, and speed of
318+
// execution - updates vs reads, long reads vs short reads, fat reads vs skinny reads.
319+
// NOTE: read vs. write is implemented in Kube 1.6+
320+
handler = apiserverfilters.WithMaxInFlightLimit(handler, genericConfig.MaxRequestsInFlight, genericConfig.MaxMutatingRequestsInFlight, genericConfig.RequestContextMapper, genericConfig.LongRunningFunc)
321+
handler = apifilters.WithRequestInfo(handler, apiserver.NewRequestInfoResolver(genericConfig), genericConfig.RequestContextMapper)
322+
handler = apirequest.WithRequestContext(handler, genericConfig.RequestContextMapper)
323+
handler = apiserverfilters.WithPanicRecovery(handler)
324+
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
325+
326+
// these handlers are all before the normal kube chain
327+
handler = cacheControlFilter(handler, "no-store") // protected endpoints should not be cached
328+
329+
if c.WebConsoleEnabled() {
330+
handler = assetapiserver.WithAssetServerRedirect(handler, c.Options.AssetConfig.PublicURL)
331+
}
332+
// these handlers are actually separate API servers which have their own handler chains.
333+
// our server embeds these
334+
handler = c.withConsoleRedirection(handler, assetServerHandler, c.Options.AssetConfig)
335+
handler = c.withOAuthRedirection(handler, oauthServerHandler)
336+
337+
return handler
338+
},
339+
extraPostStartHooks,
340+
nil
331341
}
332342

333343
func (c *MasterConfig) withConsoleRedirection(handler, assetServerHandler http.Handler, assetConfig *configapi.AssetConfig) http.Handler {

0 commit comments

Comments
 (0)