Commit 528b7b9e authored by Darren Shepherd's avatar Darren Shepherd

Remove client-go auth plugins

parent 4ebd95be
...@@ -28,9 +28,6 @@ import ( ...@@ -28,9 +28,6 @@ import (
cliflag "k8s.io/component-base/cli/flag" cliflag "k8s.io/component-base/cli/flag"
"k8s.io/kubernetes/pkg/kubectl/cmd" "k8s.io/kubernetes/pkg/kubectl/cmd"
"k8s.io/kubernetes/pkg/kubectl/util/logs" "k8s.io/kubernetes/pkg/kubectl/util/logs"
// Import to initialize client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth"
) )
func main() { func main() {
......
...@@ -36,7 +36,6 @@ import ( ...@@ -36,7 +36,6 @@ import (
"k8s.io/apiserver/plugin/pkg/authenticator/token/webhook" "k8s.io/apiserver/plugin/pkg/authenticator/token/webhook"
// Initialize all known client auth plugins. // Initialize all known client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth"
certutil "k8s.io/client-go/util/cert" certutil "k8s.io/client-go/util/cert"
"k8s.io/client-go/util/keyutil" "k8s.io/client-go/util/keyutil"
"k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/pkg/features"
......
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["plugins.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth",
importpath = "k8s.io/client-go/plugin/pkg/client/auth",
deps = [
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure:go_default_library",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/gcp:go_default_library",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc:go_default_library",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/openstack:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure:all-srcs",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec:all-srcs",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/gcp:all-srcs",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc:all-srcs",
"//staging/src/k8s.io/client-go/plugin/pkg/client/auth/openstack:all-srcs",
],
tags = ["automanaged"],
)
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- sig-auth-authenticators-approvers
reviewers:
- sig-auth-authenticators-reviewers
labels:
- sig/auth
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["azure_test.go"],
embed = [":go_default_library"],
deps = ["//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["azure.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth/azure",
importpath = "k8s.io/client-go/plugin/pkg/client/auth/azure",
deps = [
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/client-go/rest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
# Azure Active Directory plugin for client authentication
This plugin provides an integration with Azure Active Directory device flow. If no tokens are present in the kubectl configuration, it will prompt a device code which can be used to login in a browser. After login it will automatically fetch the tokens and store them in the kubectl configuration. In addition it will refresh and update the tokens in the configuration when expired.
## Usage
1. Create an Azure Active Directory *Web App / API* application for `apiserver` following these [instructions](https://docs.microsoft.com/en-us/azure/active-directory/active-directory-app-registration). The callback URL does not matter (just cannot be empty).
2. Create a second Azure Active Directory native application for `kubectl`. The callback URL does not matter (just cannot be empty).
3. On `kubectl` application's configuration page in Azure portal grant permissions to `apiserver` application by clicking on *Required Permissions*, click the *Add* button and search for the apiserver application created in step 1. Select "Access apiserver" under the *DELEGATED PERMISSIONS*. Once added click the *Grant Permissions* button to apply the changes.
4. Configure the `apiserver` to use the Azure Active Directory as an OIDC provider with following options
```
--oidc-client-id="spn:APISERVER_APPLICATION_ID" \
--oidc-issuer-url="https://sts.windows.net/TENANT_ID/"
--oidc-username-claim="sub"
```
* Replace the `APISERVER_APPLICATION_ID` with the application ID of `apiserver` application
* Replace `TENANT_ID` with your tenant ID.
  * For a list of alternative username claims that are supported by the OIDC issuer check the JSON response at `https://sts.windows.net/TENANT_ID/.well-known/openid-configuration`.
5. Configure `kubectl` to use the `azure` authentication provider
```
kubectl config set-credentials "USER_NAME" --auth-provider=azure \
--auth-provider-arg=environment=AzurePublicCloud \
--auth-provider-arg=client-id=APPLICATION_ID \
--auth-provider-arg=tenant-id=TENANT_ID \
--auth-provider-arg=apiserver-id=APISERVER_APPLICATION_ID
```
* Supported environments: `AzurePublicCloud`, `AzureUSGovernmentCloud`, `AzureChinaCloud`, `AzureGermanCloud`
* Replace `USER_NAME` and `TENANT_ID` with your user name and tenant ID
* Replace `APPLICATION_ID` with the application ID of your`kubectl` application ID
* Replace `APISERVER_APPLICATION_ID` with the application ID of your `apiserver` application ID
* Be sure to also (create and) select a context that uses above user
6. The access token is acquired when first `kubectl` command is executed
```
kubectl get pods
To sign in, use a web browser to open the page https://aka.ms/devicelogin and enter the code DEC7D48GA to authenticate.
```
* After signing in a web browser, the token is stored in the configuration, and it will be reused when executing further commands.
* The resulting username in Kubernetes depends on your [configuration of the `--oidc-username-claim` and `--oidc-username-prefix` flags on the API server](https://kubernetes.io/docs/admin/authentication/#configuring-the-api-server). If you are using any authorization method you need to give permissions to that user, e.g. by binding the user to a role in the case of RBAC.
/*
Copyright 2017 The Kubernetes 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 azure
import (
"encoding/json"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/Azure/go-autorest/autorest/adal"
)
func TestAzureTokenSource(t *testing.T) {
fakeAccessToken := "fake token 1"
fakeSource := fakeTokenSource{
accessToken: fakeAccessToken,
expiresOn: strconv.FormatInt(time.Now().Add(3600*time.Second).Unix(), 10),
}
cfg := make(map[string]string)
persiter := &fakePersister{cache: make(map[string]string)}
tokenCache := newAzureTokenCache()
tokenSource := newAzureTokenSource(&fakeSource, tokenCache, cfg, persiter)
token, err := tokenSource.Token()
if err != nil {
t.Errorf("failed to retrieve the token form cache: %v", err)
}
wantCacheLen := 1
if len(tokenCache.cache) != wantCacheLen {
t.Errorf("Token() cache length error: got %v, want %v", len(tokenCache.cache), wantCacheLen)
}
if token != tokenCache.cache[azureTokenKey] {
t.Error("Token() returned token != cached token")
}
wantCfg := token2Cfg(token)
persistedCfg := persiter.Cache()
wantCfgLen := len(wantCfg)
persistedCfgLen := len(persistedCfg)
if wantCfgLen != persistedCfgLen {
t.Errorf("wantCfgLen and persistedCfgLen do not match, wantCfgLen=%v, persistedCfgLen=%v", wantCfgLen, persistedCfgLen)
}
for k, v := range persistedCfg {
if strings.Compare(v, wantCfg[k]) != 0 {
t.Errorf("Token() persisted cfg %s: got %v, want %v", k, v, wantCfg[k])
}
}
fakeSource.accessToken = "fake token 2"
token, err = tokenSource.Token()
if err != nil {
t.Errorf("failed to retrieve the cached token: %v", err)
}
if token.token.AccessToken != fakeAccessToken {
t.Errorf("Token() didn't return the cached token")
}
}
type fakePersister struct {
lock sync.Mutex
cache map[string]string
}
func (p *fakePersister) Persist(cache map[string]string) error {
p.lock.Lock()
defer p.lock.Unlock()
p.cache = map[string]string{}
for k, v := range cache {
p.cache[k] = v
}
return nil
}
func (p *fakePersister) Cache() map[string]string {
ret := map[string]string{}
p.lock.Lock()
defer p.lock.Unlock()
for k, v := range p.cache {
ret[k] = v
}
return ret
}
type fakeTokenSource struct {
expiresOn string
accessToken string
}
func (ts *fakeTokenSource) Token() (*azureToken, error) {
return &azureToken{
token: newFackeAzureToken(ts.accessToken, ts.expiresOn),
environment: "testenv",
clientID: "fake",
tenantID: "fake",
apiserverID: "fake",
}, nil
}
func token2Cfg(token *azureToken) map[string]string {
cfg := make(map[string]string)
cfg[cfgAccessToken] = token.token.AccessToken
cfg[cfgRefreshToken] = token.token.RefreshToken
cfg[cfgEnvironment] = token.environment
cfg[cfgClientID] = token.clientID
cfg[cfgTenantID] = token.tenantID
cfg[cfgApiserverID] = token.apiserverID
cfg[cfgExpiresIn] = string(token.token.ExpiresIn)
cfg[cfgExpiresOn] = string(token.token.ExpiresOn)
return cfg
}
func newFackeAzureToken(accessToken string, expiresOn string) adal.Token {
return adal.Token{
AccessToken: accessToken,
RefreshToken: "fake",
ExpiresIn: "3600",
ExpiresOn: json.Number(expiresOn),
NotBefore: json.Number(expiresOn),
Resource: "fake",
Type: "fake",
}
}
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = ["exec.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec",
importpath = "k8s.io/client-go/plugin/pkg/client/auth/exec",
visibility = ["//visibility:public"],
deps = [
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/runtime:go_default_library",
"//staging/src/k8s.io/client-go/pkg/apis/clientauthentication:go_default_library",
"//staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1:go_default_library",
"//staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1:go_default_library",
"//staging/src/k8s.io/client-go/tools/clientcmd/api:go_default_library",
"//staging/src/k8s.io/client-go/transport:go_default_library",
"//staging/src/k8s.io/client-go/util/connrotation:go_default_library",
"//vendor/github.com/davecgh/go-spew/spew:go_default_library",
"//vendor/golang.org/x/crypto/ssh/terminal:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["exec_test.go"],
data = glob(["testdata/**"]),
embed = [":go_default_library"],
deps = [
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/client-go/pkg/apis/clientauthentication:go_default_library",
"//staging/src/k8s.io/client-go/tools/clientcmd/api:go_default_library",
"//staging/src/k8s.io/client-go/transport:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
#!/bin/bash -e
# Copyright 2018 The Kubernetes 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.
>&2 echo "$KUBERNETES_EXEC_INFO"
echo "$TEST_OUTPUT"
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["gcp_test.go"],
embed = [":go_default_library"],
deps = ["//vendor/golang.org/x/oauth2:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["gcp.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth/gcp",
importpath = "k8s.io/client-go/plugin/pkg/client/auth/gcp",
deps = [
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/yaml:go_default_library",
"//staging/src/k8s.io/client-go/rest:go_default_library",
"//staging/src/k8s.io/client-go/util/jsonpath:go_default_library",
"//vendor/golang.org/x/oauth2:go_default_library",
"//vendor/golang.org/x/oauth2/google:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- cjcullen
- jlowdermilk
reviewers:
- cjcullen
- jlowdermilk
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["oidc_test.go"],
embed = [":go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["oidc.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth/oidc",
importpath = "k8s.io/client-go/plugin/pkg/client/auth/oidc",
deps = [
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/client-go/rest:go_default_library",
"//vendor/golang.org/x/oauth2:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- ericchiang
reviewers:
- ericchiang
- rithujohn191
/*
Copyright 2016 The Kubernetes 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 oidc
import (
"encoding/base64"
"encoding/json"
"fmt"
"testing"
"time"
)
func TestJSONTime(t *testing.T) {
data := `{
"t1": 1493851263,
"t2": 1.493851263e9
}`
var v struct {
T1 jsonTime `json:"t1"`
T2 jsonTime `json:"t2"`
}
if err := json.Unmarshal([]byte(data), &v); err != nil {
t.Fatal(err)
}
wantT1 := time.Unix(1493851263, 0)
wantT2 := time.Unix(1493851263, 0)
gotT1 := time.Time(v.T1)
gotT2 := time.Time(v.T2)
if !wantT1.Equal(gotT1) {
t.Errorf("t1 value: wanted %s got %s", wantT1, gotT1)
}
if !wantT2.Equal(gotT2) {
t.Errorf("t2 value: wanted %s got %s", wantT2, gotT2)
}
}
func encodeJWT(header, payload, sig string) string {
e := func(s string) string {
return base64.RawURLEncoding.EncodeToString([]byte(s))
}
return e(header) + "." + e(payload) + "." + e(sig)
}
func TestExpired(t *testing.T) {
now := time.Now()
nowFunc := func() time.Time { return now }
tests := []struct {
name string
idToken string
wantErr bool
wantExpired bool
}{
{
name: "valid",
idToken: encodeJWT(
"{}",
fmt.Sprintf(`{"exp":%d}`, now.Add(time.Hour).Unix()),
"blah", // signature isn't veified.
),
},
{
name: "expired",
idToken: encodeJWT(
"{}",
fmt.Sprintf(`{"exp":%d}`, now.Add(-time.Hour).Unix()),
"blah", // signature isn't veified.
),
wantExpired: true,
},
{
name: "bad exp claim",
idToken: encodeJWT(
"{}",
`{"exp":"foobar"}`,
"blah", // signature isn't veified.
),
wantErr: true,
},
{
name: "not an id token",
idToken: "notanidtoken",
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
valid, err := idTokenExpired(nowFunc, test.idToken)
if err != nil {
if !test.wantErr {
t.Errorf("parse error: %v", err)
}
return
}
if test.wantExpired == valid {
t.Errorf("wanted expired %t, got %t", test.wantExpired, !valid)
}
})
}
}
func TestClientCache(t *testing.T) {
cache := newClientCache()
if _, ok := cache.getClient("issuer1", "id1"); ok {
t.Fatalf("got client before putting one in the cache")
}
cli1 := new(oidcAuthProvider)
cli2 := new(oidcAuthProvider)
gotcli := cache.setClient("issuer1", "id1", cli1)
if cli1 != gotcli {
t.Fatalf("set first client and got a different one")
}
gotcli = cache.setClient("issuer1", "id1", cli2)
if cli1 != gotcli {
t.Fatalf("set a second client and didn't get the first")
}
}
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["openstack_test.go"],
embed = [":go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["openstack.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/plugin/pkg/client/auth/openstack",
importpath = "k8s.io/client-go/plugin/pkg/client/auth/openstack",
deps = [
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/client-go/rest:go_default_library",
"//vendor/github.com/gophercloud/gophercloud:go_default_library",
"//vendor/github.com/gophercloud/gophercloud/openstack:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
/*
Copyright 2017 The Kubernetes 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 openstack
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/util/net"
restclient "k8s.io/client-go/rest"
)
func init() {
if err := restclient.RegisterAuthProviderPlugin("openstack", newOpenstackAuthProvider); err != nil {
klog.Fatalf("Failed to register openstack auth plugin: %s", err)
}
}
// DefaultTTLDuration is the time before a token gets expired.
const DefaultTTLDuration = 10 * time.Minute
// openstackAuthProvider is an authprovider for openstack. this provider reads
// the environment variables to determine the client identity, and generates a
// token which will be inserted into the request header later.
type openstackAuthProvider struct {
ttl time.Duration
tokenGetter TokenGetter
}
// TokenGetter returns a bearer token that can be inserted into request.
type TokenGetter interface {
Token() (string, error)
}
type tokenGetter struct {
authOpt *gophercloud.AuthOptions
}
// Token creates a token by authenticate with keystone.
func (t *tokenGetter) Token() (string, error) {
var options gophercloud.AuthOptions
var err error
if t.authOpt == nil {
// reads the config from the environment
klog.V(4).Info("reading openstack config from the environment variables")
options, err = openstack.AuthOptionsFromEnv()
if err != nil {
return "", fmt.Errorf("failed to read openstack env vars: %s", err)
}
} else {
options = *t.authOpt
}
client, err := openstack.AuthenticatedClient(options)
if err != nil {
return "", fmt.Errorf("authentication failed: %s", err)
}
return client.TokenID, nil
}
// cachedGetter caches a token until it gets expired, after the expiration, it will
// generate another token and cache it.
type cachedGetter struct {
mutex sync.Mutex
tokenGetter TokenGetter
token string
born time.Time
ttl time.Duration
}
// Token returns the current available token, create a new one if expired.
func (c *cachedGetter) Token() (string, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
var err error
// no token or exceeds the TTL
if c.token == "" || time.Since(c.born) > c.ttl {
c.token, err = c.tokenGetter.Token()
if err != nil {
return "", fmt.Errorf("failed to get token: %s", err)
}
c.born = time.Now()
}
return c.token, nil
}
// tokenRoundTripper implements the RoundTripper interface: adding the bearer token
// into the request header.
type tokenRoundTripper struct {
http.RoundTripper
tokenGetter TokenGetter
}
var _ net.RoundTripperWrapper = &tokenRoundTripper{}
// RoundTrip adds the bearer token into the request.
func (t *tokenRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// if the authorization header already present, use it.
if req.Header.Get("Authorization") != "" {
return t.RoundTripper.RoundTrip(req)
}
token, err := t.tokenGetter.Token()
if err == nil {
req.Header.Set("Authorization", "Bearer "+token)
} else {
klog.V(4).Infof("failed to get token: %s", err)
}
return t.RoundTripper.RoundTrip(req)
}
func (t *tokenRoundTripper) WrappedRoundTripper() http.RoundTripper { return t.RoundTripper }
// newOpenstackAuthProvider creates an auth provider which works with openstack
// environment.
func newOpenstackAuthProvider(_ string, config map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
var ttlDuration time.Duration
var err error
klog.Warningf("WARNING: in-tree openstack auth plugin is now deprecated. please use the \"client-keystone-auth\" kubectl/client-go credential plugin instead")
ttl, found := config["ttl"]
if !found {
ttlDuration = DefaultTTLDuration
// persist to config
config["ttl"] = ttlDuration.String()
if err = persister.Persist(config); err != nil {
return nil, fmt.Errorf("failed to persist config: %s", err)
}
} else {
ttlDuration, err = time.ParseDuration(ttl)
if err != nil {
return nil, fmt.Errorf("failed to parse ttl config: %s", err)
}
}
authOpt := gophercloud.AuthOptions{
IdentityEndpoint: config["identityEndpoint"],
Username: config["username"],
Password: config["password"],
DomainName: config["name"],
TenantID: config["tenantId"],
TenantName: config["tenantName"],
}
getter := tokenGetter{}
// not empty
if (authOpt != gophercloud.AuthOptions{}) {
if len(authOpt.IdentityEndpoint) == 0 {
return nil, fmt.Errorf("empty %q in the config for openstack auth provider", "identityEndpoint")
}
getter.authOpt = &authOpt
}
return &openstackAuthProvider{
ttl: ttlDuration,
tokenGetter: &getter,
}, nil
}
func (oap *openstackAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {
return &tokenRoundTripper{
RoundTripper: rt,
tokenGetter: &cachedGetter{
tokenGetter: oap.tokenGetter,
ttl: oap.ttl,
},
}
}
func (oap *openstackAuthProvider) Login() error { return nil }
/*
Copyright 2017 The Kubernetes 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 openstack
import (
"math/rand"
"net/http"
"testing"
"time"
)
// testTokenGetter is a simple random token getter.
type testTokenGetter struct{}
const LetterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = LetterBytes[rand.Intn(len(LetterBytes))]
}
return string(b)
}
func (*testTokenGetter) Token() (string, error) {
return RandStringBytes(32), nil
}
// testRoundTripper is mocked roundtripper which responds with unauthorized when
// there is no authorization header, otherwise returns status ok.
type testRoundTripper struct{}
func (trt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
authHeader := req.Header.Get("Authorization")
if authHeader == "" || authHeader == "Bearer " {
return &http.Response{
StatusCode: http.StatusUnauthorized,
}, nil
}
return &http.Response{StatusCode: http.StatusOK}, nil
}
func TestOpenstackAuthProvider(t *testing.T) {
trt := &tokenRoundTripper{
RoundTripper: &testRoundTripper{},
}
tests := []struct {
name string
ttl time.Duration
interval time.Duration
same bool
}{
{
name: "normal",
ttl: 2 * time.Second,
interval: 1 * time.Second,
same: true,
},
{
name: "expire",
ttl: 1 * time.Second,
interval: 2 * time.Second,
same: false,
},
}
for _, test := range tests {
trt.tokenGetter = &cachedGetter{
tokenGetter: &testTokenGetter{},
ttl: test.ttl,
}
req, err := http.NewRequest(http.MethodPost, "https://test-api-server.com", nil)
if err != nil {
t.Errorf("failed to new request: %s", err)
}
trt.RoundTrip(req)
header := req.Header.Get("Authorization")
if header == "" {
t.Errorf("expect to see token in header, but is absent")
}
time.Sleep(test.interval)
req, err = http.NewRequest(http.MethodPost, "https://test-api-server.com", nil)
if err != nil {
t.Errorf("failed to new request: %s", err)
}
trt.RoundTrip(req)
newHeader := req.Header.Get("Authorization")
if newHeader == "" {
t.Errorf("expect to see token in header, but is absent")
}
same := newHeader == header
if same != test.same {
t.Errorf("expect to get %t when compare header, but saw %t", test.same, same)
}
}
}
type fakePersister struct{}
func (i *fakePersister) Persist(map[string]string) error {
return nil
}
func TestNewOpenstackAuthProvider(t *testing.T) {
tests := []struct {
name string
config map[string]string
expectError bool
}{
{
name: "normal config without openstack configurations",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
},
},
{
name: "openstack auth provider: missing identityEndpoint",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
"username": "xyz",
"password": "123",
"tenantName": "admin",
},
expectError: true,
},
{
name: "openstack auth provider",
config: map[string]string{
"ttl": "1s",
"foo": "bar",
"identityEndpoint": "http://controller:35357/v3",
"username": "xyz",
"password": "123",
"tenantName": "admin",
},
},
}
for _, test := range tests {
_, err := newOpenstackAuthProvider("test", test.config, &fakePersister{})
if err != nil {
if !test.expectError {
t.Errorf("unexpected error: %v", err)
}
} else {
if test.expectError {
t.Error("expect error, but nil")
}
}
}
}
/*
Copyright 2016 The Kubernetes 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 (
// Initialize all known client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth/azure"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
_ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)
...@@ -21,7 +21,6 @@ import ( ...@@ -21,7 +21,6 @@ import (
"errors" "errors"
"net/http" "net/http"
"k8s.io/client-go/plugin/pkg/client/auth/exec"
"k8s.io/client-go/transport" "k8s.io/client-go/transport"
) )
...@@ -89,15 +88,6 @@ func (c *Config) TransportConfig() (*transport.Config, error) { ...@@ -89,15 +88,6 @@ func (c *Config) TransportConfig() (*transport.Config, error) {
return nil, errors.New("execProvider and authProvider cannot be used in combination") return nil, errors.New("execProvider and authProvider cannot be used in combination")
} }
if c.ExecProvider != nil {
provider, err := exec.GetAuthenticator(c.ExecProvider)
if err != nil {
return nil, err
}
if err := provider.UpdateTransportConfig(conf); err != nil {
return nil, err
}
}
if c.AuthProvider != nil { if c.AuthProvider != nil {
provider, err := GetAuthProvider(c.Host, c.AuthProvider, c.AuthConfigPersister) provider, err := GetAuthProvider(c.Host, c.AuthProvider, c.AuthConfigPersister)
if err != nil { if err != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment