|
| 1 | +// Copyright Jetstack Ltd. See LICENSE for details. |
| 2 | +package context |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "k8s.io/apiserver/pkg/endpoints/request" |
| 9 | + "k8s.io/client-go/transport" |
| 10 | +) |
| 11 | + |
| 12 | +type key int |
| 13 | + |
| 14 | +const ( |
| 15 | + // noImpersonationKey is the context key for whether to use impersonation. |
| 16 | + noImpersonationKey key = iota |
| 17 | + |
| 18 | + // impersonationConfigKey is the context key for the impersonation config. |
| 19 | + impersonationConfigKey |
| 20 | + |
| 21 | + // bearerTokenKey is the context key for the bearer token. |
| 22 | + bearerTokenKey |
| 23 | +) |
| 24 | + |
| 25 | +// WithNoImpersonation returns a copy of parent in which the noImpersonation value is set. |
| 26 | +func WithNoImpersonation(parent context.Context) context.Context { |
| 27 | + return request.WithValue(parent, noImpersonationKey, true) |
| 28 | +} |
| 29 | + |
| 30 | +// NoImpersonation returns whether the noImpersonation key has been set |
| 31 | +func NoImpersonation(ctx context.Context) bool { |
| 32 | + noImp, _ := ctx.Value(noImpersonationKey).(bool) |
| 33 | + return noImp |
| 34 | +} |
| 35 | + |
| 36 | +// WithImpersonationConfig returns a copy of parent in which contains the impersonation configuration. |
| 37 | +func WithImpersonationConfig(parent context.Context, conf *transport.ImpersonationConfig) context.Context { |
| 38 | + return request.WithValue(parent, impersonationConfigKey, conf) |
| 39 | +} |
| 40 | + |
| 41 | +// ImpersonationConfig returns the impersonation configuration held in the context if existing. |
| 42 | +func ImpersonationConfig(ctx context.Context) *transport.ImpersonationConfig { |
| 43 | + conf, _ := ctx.Value(impersonationConfigKey).(*transport.ImpersonationConfig) |
| 44 | + return conf |
| 45 | +} |
| 46 | + |
| 47 | +// WithBearerToken will add the bearer token from an http.Header to the context. |
| 48 | +func WithBearerToken(parent context.Context, header http.Header) context.Context { |
| 49 | + return request.WithValue(parent, bearerTokenKey, header.Get("Authorization")) |
| 50 | +} |
| 51 | + |
| 52 | +// BearerToken will return the bearer token stored in the context. |
| 53 | +func BearerToken(ctx context.Context) string { |
| 54 | + token, _ := ctx.Value(bearerTokenKey).(string) |
| 55 | + return token |
| 56 | +} |
0 commit comments