Skip to content

Commit 1eb44c7

Browse files
author
OpenShift Bot
authored
Merge pull request #13356 from dmage/noglobals
Merged by openshift-bot
2 parents 0009bfa + a7ca6e1 commit 1eb44c7

18 files changed

+200
-269
lines changed

pkg/cmd/dockerregistry/dockerregistry.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import (
3939
"strings"
4040

4141
"github.com/openshift/origin/pkg/cmd/server/crypto"
42+
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
4243
"github.com/openshift/origin/pkg/dockerregistry/server"
4344
"github.com/openshift/origin/pkg/dockerregistry/server/audit"
4445
)
@@ -57,11 +58,26 @@ func Execute(configFile io.Reader) {
5758
if err != nil {
5859
log.Fatalf("error configuring logger: %v", err)
5960
}
61+
62+
registryClient := server.NewRegistryClient(clientcmd.NewConfig().BindToFile())
63+
ctx = server.WithRegistryClient(ctx, registryClient)
64+
6065
log.Infof("version=%s", version.Version)
6166
// inject a logger into the uuid library. warns us if there is a problem
6267
// with uuid generation under low entropy.
6368
uuid.Loggerf = context.GetLogger(ctx).Warnf
6469

70+
// add parameters for the auth middleware
71+
if config.Auth.Type() == server.OpenShiftAuth {
72+
if config.Auth[server.OpenShiftAuth] == nil {
73+
config.Auth[server.OpenShiftAuth] = make(configuration.Parameters)
74+
}
75+
config.Auth[server.OpenShiftAuth][server.AccessControllerOptionParams] = server.AccessControllerParams{
76+
Logger: context.GetLogger(ctx),
77+
SafeClientConfig: registryClient.SafeClientConfig(),
78+
}
79+
}
80+
6581
app := handlers.NewApp(ctx, config)
6682

6783
// Add a token handling endpoint
@@ -70,7 +86,7 @@ func Execute(configFile io.Reader) {
7086
if err != nil {
7187
log.Fatalf("error setting up token auth: %s", err)
7288
}
73-
err = app.NewRoute().Methods("GET").PathPrefix(tokenRealm.Path).Handler(server.NewTokenHandler(ctx, server.DefaultRegistryClient)).GetError()
89+
err = app.NewRoute().Methods("GET").PathPrefix(tokenRealm.Path).Handler(server.NewTokenHandler(ctx, registryClient)).GetError()
7490
if err != nil {
7591
log.Fatalf("error setting up token endpoint at %q: %v", tokenRealm.Path, err)
7692
}

pkg/dockerregistry/server/auth.go

Lines changed: 20 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"net/url"
88
"strings"
99

10-
log "github.com/Sirupsen/logrus"
1110
context "github.com/docker/distribution/context"
1211
registryauth "github.com/docker/distribution/registry/auth"
1312

@@ -45,6 +44,10 @@ const (
4544

4645
RealmKey = "realm"
4746
TokenRealmKey = "tokenrealm"
47+
48+
// AccessControllerOptionParams is an option name for passing
49+
// AccessControllerParams to AccessController.
50+
AccessControllerOptionParams = "_params"
4851
)
4952

5053
// RegistryClient encapsulates getting access to the OpenShift API.
@@ -55,9 +58,6 @@ type RegistryClient interface {
5558
SafeClientConfig() restclient.Config
5659
}
5760

58-
// DefaultRegistryClient is exposed for testing the registry with fake client.
59-
var DefaultRegistryClient = NewRegistryClient(clientcmd.NewConfig().BindToFile())
60-
6161
// registryClient implements RegistryClient
6262
type registryClient struct {
6363
config *clientcmd.Config
@@ -85,19 +85,6 @@ func init() {
8585
registryauth.Register(OpenShiftAuth, registryauth.InitFunc(newAccessController))
8686
}
8787

88-
type contextKey int
89-
90-
var userClientKey contextKey = 0
91-
92-
func WithUserClient(parent context.Context, userClient client.Interface) context.Context {
93-
return context.WithValue(parent, userClientKey, userClient)
94-
}
95-
96-
func UserClientFrom(ctx context.Context) (client.Interface, bool) {
97-
userClient, ok := ctx.Value(userClientKey).(client.Interface)
98-
return userClient, ok
99-
}
100-
10188
// WithUserInfoLogger creates a new context with provided user infomation.
10289
func WithUserInfoLogger(ctx context.Context, username, userid string) context.Context {
10390
ctx = context.WithValue(ctx, audit.AuditUserEntry, username)
@@ -110,27 +97,6 @@ func WithUserInfoLogger(ctx context.Context, username, userid string) context.Co
11097
))
11198
}
11299

113-
const authPerformedKey = "openshift.auth.performed"
114-
115-
func WithAuthPerformed(parent context.Context) context.Context {
116-
return context.WithValue(parent, authPerformedKey, true)
117-
}
118-
119-
func AuthPerformed(ctx context.Context) bool {
120-
authPerformed, ok := ctx.Value(authPerformedKey).(bool)
121-
return ok && authPerformed
122-
}
123-
124-
const deferredErrorsKey = "openshift.auth.deferredErrors"
125-
126-
func WithDeferredErrors(parent context.Context, errs deferredErrors) context.Context {
127-
return context.WithValue(parent, deferredErrorsKey, errs)
128-
}
129-
func DeferredErrorsFrom(ctx context.Context) (deferredErrors, bool) {
130-
errs, ok := ctx.Value(deferredErrorsKey).(deferredErrors)
131-
return errs, ok
132-
}
133-
134100
type AccessController struct {
135101
realm string
136102
tokenRealm *url.URL
@@ -198,8 +164,19 @@ func TokenRealm(options map[string]interface{}) (*url.URL, error) {
198164
return tokenRealm, nil
199165
}
200166

167+
// AccessControllerParams is the parameters for newAccessController
168+
type AccessControllerParams struct {
169+
Logger context.Logger
170+
SafeClientConfig restclient.Config
171+
}
172+
201173
func newAccessController(options map[string]interface{}) (registryauth.AccessController, error) {
202-
log.Info("Using Origin Auth handler")
174+
params, ok := options[AccessControllerOptionParams].(AccessControllerParams)
175+
if !ok {
176+
return nil, fmt.Errorf("no parameters provided to Origin Auth handler")
177+
}
178+
179+
params.Logger.Info("Using Origin Auth handler")
203180

204181
realm, err := getStringOption("", RealmKey, "origin", options)
205182
if err != nil {
@@ -214,7 +191,7 @@ func newAccessController(options map[string]interface{}) (registryauth.AccessCon
214191
ac := &AccessController{
215192
realm: realm,
216193
tokenRealm: tokenRealm,
217-
config: DefaultRegistryClient.SafeClientConfig(),
194+
config: params.SafeClientConfig,
218195
}
219196

220197
if audit, ok := options["audit"]; ok {
@@ -446,12 +423,12 @@ func (ac *AccessController) Authorized(ctx context.Context, accessRecords ...reg
446423
// Conditionally add auth errors we want to handle later to the context
447424
if !possibleCrossMountErrors.Empty() {
448425
context.GetLogger(ctx).Debugf("Origin auth: deferring errors: %#v", possibleCrossMountErrors)
449-
ctx = WithDeferredErrors(ctx, possibleCrossMountErrors)
426+
ctx = withDeferredErrors(ctx, possibleCrossMountErrors)
450427
}
451428
// Always add a marker to the context so we know auth was run
452-
ctx = WithAuthPerformed(ctx)
429+
ctx = withAuthPerformed(ctx)
453430

454-
return WithUserClient(ctx, osClient), nil
431+
return withUserClient(ctx, osClient), nil
455432
}
456433

457434
func getOpenShiftAPIToken(ctx context.Context, req *http.Request) (string, error) {

pkg/dockerregistry/server/auth_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"github.com/docker/distribution/context"
2121
"github.com/openshift/origin/pkg/api/latest"
2222
"github.com/openshift/origin/pkg/authorization/api"
23-
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
2423
userapi "github.com/openshift/origin/pkg/user/api"
2524

2625
// install all APIs
@@ -391,20 +390,21 @@ func TestAccessController(t *testing.T) {
391390
if len(test.bearerToken) > 0 {
392391
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", test.bearerToken))
393392
}
394-
ctx := context.WithValue(context.Background(), "http.request", req)
395393

396394
server, actions := simulateOpenShiftMaster(test.openshiftResponses)
397-
DefaultRegistryClient = NewRegistryClient(&clientcmd.Config{
398-
CommonConfig: restclient.Config{
395+
options[AccessControllerOptionParams] = AccessControllerParams{
396+
Logger: context.GetLogger(context.Background()),
397+
SafeClientConfig: restclient.Config{
399398
Host: server.URL,
400399
Insecure: true,
401400
},
402-
SkipEnv: true,
403-
})
401+
}
404402
accessController, err := newAccessController(options)
405403
if err != nil {
406404
t.Fatal(err)
407405
}
406+
ctx := context.Background()
407+
ctx = context.WithRequest(ctx, req)
408408
authCtx, err := accessController.Authorized(ctx, test.access...)
409409
server.Close()
410410

@@ -426,11 +426,11 @@ func TestAccessController(t *testing.T) {
426426
t.Errorf("%s: expected auth context but got nil", k)
427427
continue
428428
}
429-
if !AuthPerformed(authCtx) {
429+
if !authPerformed(authCtx) {
430430
t.Errorf("%s: expected AuthPerformed to be true", k)
431431
continue
432432
}
433-
deferredErrors, hasDeferred := DeferredErrorsFrom(authCtx)
433+
deferredErrors, hasDeferred := deferredErrorsFrom(authCtx)
434434
if len(test.expectedRepoErr) > 0 {
435435
if !hasDeferred || deferredErrors[test.expectedRepoErr] == nil {
436436
t.Errorf("%s: expected deferred error for repo %s, got none", k, test.expectedRepoErr)

pkg/dockerregistry/server/blobdescriptorservice.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ type blobDescriptorService struct {
5454
// a proper repository object to be set on given context by upper openshift middleware wrappers.
5555
func (bs *blobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
5656
context.GetLogger(ctx).Debugf("(*blobDescriptorService).Stat: starting with digest=%s", dgst.String())
57-
repo, found := RepositoryFrom(ctx)
57+
repo, found := repositoryFrom(ctx)
5858
if !found || repo == nil {
5959
err := fmt.Errorf("failed to retrieve repository from context")
6060
context.GetLogger(ctx).Error(err)
@@ -90,7 +90,7 @@ func (bs *blobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (
9090
return desc, nil
9191
}
9292

93-
if err == distribution.ErrBlobUnknown && RemoteBlobAccessCheckEnabledFrom(ctx) {
93+
if err == distribution.ErrBlobUnknown && remoteBlobAccessCheckEnabledFrom(ctx) {
9494
// Second attempt: looking for the blob on a remote server
9595
desc, err = repo.remoteBlobGetter.Stat(ctx, dgst)
9696
}
@@ -99,7 +99,7 @@ func (bs *blobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (
9999
}
100100

101101
func (bs *blobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
102-
repo, found := RepositoryFrom(ctx)
102+
repo, found := repositoryFrom(ctx)
103103
if !found || repo == nil {
104104
err := fmt.Errorf("failed to retrieve repository from context")
105105
context.GetLogger(ctx).Error(err)

pkg/dockerregistry/server/blobdescriptorservice_test.go

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@ func GetTestPassThroughToUpstream(ctx context.Context) bool {
4747
// It relies on the fact that blobDescriptorService requires higher levels to set repository object on given
4848
// context. If the object isn't given, its method will err out.
4949
func TestBlobDescriptorServiceIsApplied(t *testing.T) {
50-
ctx := context.Background()
51-
5250
// don't do any authorization check
5351
installFakeAccessController(t)
5452
m := fakeBlobDescriptorService(t)
@@ -64,14 +62,8 @@ func TestBlobDescriptorServiceIsApplied(t *testing.T) {
6462
client.AddReactor("get", "imagestreams", imagetest.GetFakeImageStreamGetHandler(t, *testImageStream))
6563
client.AddReactor("get", "images", registrytest.GetFakeImageGetHandler(t, *testImage))
6664

67-
// TODO: get rid of those nasty global vars
68-
backupRegistryClient := DefaultRegistryClient
69-
DefaultRegistryClient = makeFakeRegistryClient(client, fake.NewSimpleClientset())
70-
defer func() {
71-
// set it back once this test finishes to make other unit tests working
72-
DefaultRegistryClient = backupRegistryClient
73-
}()
74-
65+
ctx := context.Background()
66+
ctx = WithRegistryClient(ctx, makeFakeRegistryClient(client, fake.NewSimpleClientset()))
7567
app := handlers.NewApp(ctx, &configuration.Configuration{
7668
Loglevel: "debug",
7769
Auth: map[string]configuration.Parameters{
@@ -463,7 +455,7 @@ func (bs *testBlobDescriptorService) Stat(ctx context.Context, dgst digest.Diges
463455
bs.m.methodInvoked("Stat")
464456
if bs.m.getUnsetRepository() {
465457
bs.t.Logf("unsetting repository from the context")
466-
ctx = WithRepository(ctx, nil)
458+
ctx = withRepository(ctx, nil)
467459
}
468460

469461
return bs.BlobDescriptorService.Stat(ctx, dgst)
@@ -472,7 +464,7 @@ func (bs *testBlobDescriptorService) Clear(ctx context.Context, dgst digest.Dige
472464
bs.m.methodInvoked("Clear")
473465
if bs.m.getUnsetRepository() {
474466
bs.t.Logf("unsetting repository from the context")
475-
ctx = WithRepository(ctx, nil)
467+
ctx = withRepository(ctx, nil)
476468
}
477469
return bs.BlobDescriptorService.Clear(ctx, dgst)
478470
}
@@ -499,7 +491,7 @@ func (f *fakeAccessController) Authorized(ctx context.Context, access ...registr
499491
f.t.Logf("fake authorizer: authorizing access to %s:%s:%s", access.Resource.Type, access.Resource.Name, access.Action)
500492
}
501493

502-
ctx = WithAuthPerformed(ctx)
494+
ctx = withAuthPerformed(ctx)
503495
return ctx, nil
504496
}
505497

0 commit comments

Comments
 (0)