Add auth API to get self subject attributes
Signed-off-by: m.nabokikh <maksim.nabokikh@flant.com>
This commit is contained in:
130
test/e2e/auth/selfsubjectreviews.go
Normal file
130
test/e2e/auth/selfsubjectreviews.go
Normal file
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
Copyright 2022 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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/onsi/ginkgo/v2"
|
||||
authenticationv1alpha1 "k8s.io/api/authentication/v1alpha1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/kubernetes/test/e2e/framework"
|
||||
admissionapi "k8s.io/pod-security-admission/api"
|
||||
)
|
||||
|
||||
var _ = SIGDescribe("SelfSubjectReview [Feature:APISelfSubjectReview]", func() {
|
||||
f := framework.NewDefaultFramework("selfsubjectreviews")
|
||||
f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged
|
||||
|
||||
/*
|
||||
Release: v1.24
|
||||
Testname: SelfSubjectReview API
|
||||
Description:
|
||||
The authentication.k8s.io API group MUST exist in the /apis discovery document.
|
||||
The authentication.k8s.io/v1alpha1 API group/version MUST exist in the /apis/mode.k8s.io discovery document.
|
||||
The selfsubjectreviews resource MUST exist in the /apis/authentication.k8s.io/v1alpha1 discovery document.
|
||||
The selfsubjectreviews resource must support create.
|
||||
*/
|
||||
ginkgo.It("should support SelfSubjectReview API operations", func() {
|
||||
// Setup
|
||||
ssarAPIVersion := "v1alpha1"
|
||||
|
||||
// Discovery
|
||||
ginkgo.By("getting /apis")
|
||||
{
|
||||
discoveryGroups, err := f.ClientSet.Discovery().ServerGroups()
|
||||
framework.ExpectNoError(err)
|
||||
found := false
|
||||
for _, group := range discoveryGroups.Groups {
|
||||
if group.Name == authenticationv1alpha1.GroupName {
|
||||
for _, version := range group.Versions {
|
||||
if version.Version == ssarAPIVersion {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
ginkgo.Skip(fmt.Sprintf("expected SelfSubjectReview API group/version, got %#v", discoveryGroups.Groups))
|
||||
}
|
||||
}
|
||||
|
||||
ginkgo.By("getting /apis/authentication.k8s.io")
|
||||
{
|
||||
group := &metav1.APIGroup{}
|
||||
err := f.ClientSet.Discovery().RESTClient().Get().AbsPath("/apis/authentication.k8s.io").Do(context.TODO()).Into(group)
|
||||
framework.ExpectNoError(err)
|
||||
found := false
|
||||
for _, version := range group.Versions {
|
||||
if version.Version == ssarAPIVersion {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
ginkgo.Skip(fmt.Sprintf("expected SelfSubjectReview API version, got %#v", group.Versions))
|
||||
}
|
||||
}
|
||||
|
||||
ginkgo.By("getting /apis/authentication.k8s.io/" + ssarAPIVersion)
|
||||
{
|
||||
resources, err := f.ClientSet.Discovery().ServerResourcesForGroupVersion(authenticationv1alpha1.SchemeGroupVersion.String())
|
||||
framework.ExpectNoError(err)
|
||||
found := false
|
||||
for _, resource := range resources.APIResources {
|
||||
switch resource.Name {
|
||||
case "selfsubjectreviews":
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
ginkgo.Skip(fmt.Sprintf("expected selfsubjectreviews, got %#v", resources.APIResources))
|
||||
}
|
||||
}
|
||||
|
||||
// Check creating
|
||||
ginkgo.By("creating")
|
||||
{
|
||||
// Use impersonate to make user attributes predictable
|
||||
config := f.ClientConfig()
|
||||
config.Impersonate.UserName = "jane-doe"
|
||||
config.Impersonate.UID = "uniq-id"
|
||||
config.Impersonate.Groups = []string{"system:authenticated", "developers"}
|
||||
config.Impersonate.Extra = map[string][]string{
|
||||
"known-languages": {"python", "javascript"},
|
||||
}
|
||||
|
||||
ssrClient := kubernetes.NewForConfigOrDie(config).AuthenticationV1alpha1().SelfSubjectReviews()
|
||||
res, err := ssrClient.Create(context.TODO(), &authenticationv1alpha1.SelfSubjectReview{}, metav1.CreateOptions{})
|
||||
framework.ExpectNoError(err)
|
||||
|
||||
framework.ExpectEqual(config.Impersonate.UserName, res.Status.UserInfo.Username)
|
||||
framework.ExpectEqual(config.Impersonate.UID, res.Status.UserInfo.UID)
|
||||
framework.ExpectEqual(config.Impersonate.Groups, res.Status.UserInfo.Groups)
|
||||
|
||||
extra := make(map[string][]string, len(res.Status.UserInfo.Extra))
|
||||
for k, v := range res.Status.UserInfo.Extra {
|
||||
extra[k] = v
|
||||
}
|
||||
|
||||
framework.ExpectEqual(config.Impersonate.Extra, extra)
|
||||
}
|
||||
})
|
||||
})
|
@@ -52,12 +52,15 @@ import (
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
|
||||
utilfeature "k8s.io/apiserver/pkg/util/feature"
|
||||
"k8s.io/client-go/dynamic"
|
||||
clientset "k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/client-go/util/retry"
|
||||
featuregatetesting "k8s.io/component-base/featuregate/testing"
|
||||
kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
|
||||
apisv1beta1 "k8s.io/kubernetes/pkg/apis/admissionregistration/v1beta1"
|
||||
"k8s.io/kubernetes/pkg/features"
|
||||
"k8s.io/kubernetes/test/integration/etcd"
|
||||
"k8s.io/kubernetes/test/integration/framework"
|
||||
)
|
||||
@@ -150,6 +153,7 @@ var (
|
||||
// Non persistent Reviews resource
|
||||
gvr("authentication.k8s.io", "v1", "tokenreviews"): `{"metadata": {"name": "tokenreview"}, "spec": {"token": "token", "audience": ["audience1","audience2"]}}`,
|
||||
gvr("authentication.k8s.io", "v1beta1", "tokenreviews"): `{"metadata": {"name": "tokenreview"}, "spec": {"token": "token", "audience": ["audience1","audience2"]}}`,
|
||||
gvr("authentication.k8s.io", "v1alpha1", "selfsubjectreviews"): `{"metadata": {"name": "SelfSubjectReview"},"status":{"userInfo":{}}}`,
|
||||
gvr("authorization.k8s.io", "v1", "localsubjectaccessreviews"): `{"metadata": {"name": "", "namespace":"` + testNamespace + `"}, "spec": {"uid": "token", "user": "user1","groups": ["group1","group2"],"resourceAttributes": {"name":"name1","namespace":"` + testNamespace + `"}}}`,
|
||||
gvr("authorization.k8s.io", "v1", "subjectaccessreviews"): `{"metadata": {"name": "", "namespace":""}, "spec": {"user":"user1","resourceAttributes": {"name":"name1", "namespace":"` + testNamespace + `"}}}`,
|
||||
gvr("authorization.k8s.io", "v1", "selfsubjectaccessreviews"): `{"metadata": {"name": "", "namespace":""}, "spec": {"resourceAttributes": {"name":"name1", "namespace":""}}}`,
|
||||
@@ -444,6 +448,8 @@ func TestWebhookAdmissionWithoutWatchCache(t *testing.T) {
|
||||
|
||||
// testWebhookAdmission tests communication between API server and webhook process.
|
||||
func testWebhookAdmission(t *testing.T, watchCache bool) {
|
||||
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.APISelfSubjectReview, true)()
|
||||
|
||||
// holder communicates expectations to webhooks, and results from webhooks
|
||||
holder := &holder{
|
||||
t: t,
|
||||
|
195
test/integration/auth/selfsubjectreview_test.go
Normal file
195
test/integration/auth/selfsubjectreview_test.go
Normal file
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
Copyright 2022 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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
authenticationv1 "k8s.io/api/authentication/v1"
|
||||
authenticationv1alpha1 "k8s.io/api/authentication/v1alpha1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apiserver/pkg/authentication/authenticator"
|
||||
"k8s.io/apiserver/pkg/authentication/user"
|
||||
"k8s.io/apiserver/pkg/authorization/authorizerfactory"
|
||||
utilfeature "k8s.io/apiserver/pkg/util/feature"
|
||||
featuregatetesting "k8s.io/component-base/featuregate/testing"
|
||||
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
|
||||
"k8s.io/kubernetes/pkg/controlplane"
|
||||
"k8s.io/kubernetes/pkg/features"
|
||||
"k8s.io/kubernetes/test/integration/framework"
|
||||
)
|
||||
|
||||
func TestGetsSelfAttributes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
userInfo *user.DefaultInfo
|
||||
expectedName string
|
||||
expectedUID string
|
||||
expectedGroups []string
|
||||
expectedExtra map[string]authenticationv1.ExtraValue
|
||||
}{
|
||||
{
|
||||
name: "Username",
|
||||
userInfo: &user.DefaultInfo{
|
||||
Name: "alice",
|
||||
},
|
||||
expectedName: "alice",
|
||||
},
|
||||
{
|
||||
name: "Username with groups and UID",
|
||||
userInfo: &user.DefaultInfo{
|
||||
Name: "alice",
|
||||
UID: "unique-id",
|
||||
Groups: []string{"devs", "admins"},
|
||||
},
|
||||
expectedName: "alice",
|
||||
expectedUID: "unique-id",
|
||||
expectedGroups: []string{"devs", "admins"},
|
||||
},
|
||||
{
|
||||
name: "Username with extra attributes",
|
||||
userInfo: &user.DefaultInfo{
|
||||
Name: "alice",
|
||||
Extra: map[string][]string{
|
||||
"nicknames": {"cutie", "bestie"},
|
||||
},
|
||||
},
|
||||
expectedName: "alice",
|
||||
expectedExtra: map[string]authenticationv1.ExtraValue{
|
||||
"nicknames": authenticationv1.ExtraValue([]string{"cutie", "bestie"}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Without username",
|
||||
userInfo: &user.DefaultInfo{
|
||||
UID: "unique-id",
|
||||
},
|
||||
expectedUID: "unique-id",
|
||||
},
|
||||
}
|
||||
|
||||
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.APISelfSubjectReview, true)()
|
||||
|
||||
var respMu sync.RWMutex
|
||||
response := &user.DefaultInfo{
|
||||
Name: "stub",
|
||||
}
|
||||
|
||||
kubeClient, _, tearDownFn := framework.StartTestServer(t, framework.TestServerSetup{
|
||||
ModifyServerConfig: func(config *controlplane.Config) {
|
||||
// Unset BearerToken to disable BearerToken authenticator.
|
||||
config.GenericConfig.LoopbackClientConfig.BearerToken = ""
|
||||
config.GenericConfig.Authentication.Authenticator = authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
|
||||
respMu.RLock()
|
||||
defer respMu.RUnlock()
|
||||
return &authenticator.Response{User: response}, true, nil
|
||||
})
|
||||
config.GenericConfig.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
|
||||
},
|
||||
ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
|
||||
opts.APIEnablement.RuntimeConfig.Set("authentication.k8s.io/v1alpha1=true")
|
||||
},
|
||||
})
|
||||
defer tearDownFn()
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
respMu.Lock()
|
||||
response = tc.userInfo
|
||||
respMu.Unlock()
|
||||
|
||||
res, err := kubeClient.AuthenticationV1alpha1().
|
||||
SelfSubjectReviews().
|
||||
Create(context.TODO(), &authenticationv1alpha1.SelfSubjectReview{}, metav1.CreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if res == nil {
|
||||
t.Fatalf("empty response")
|
||||
}
|
||||
|
||||
if res.Status.UserInfo.Username != tc.expectedName {
|
||||
t.Fatalf("unexpected username: wanted %s, got %s", tc.expectedName, res.Status.UserInfo.Username)
|
||||
}
|
||||
|
||||
if res.Status.UserInfo.UID != tc.expectedUID {
|
||||
t.Fatalf("unexpected uid: wanted %s, got %s", tc.expectedUID, res.Status.UserInfo.UID)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(res.Status.UserInfo.Groups, tc.expectedGroups) {
|
||||
t.Fatalf("unexpected groups: wanted %v, got %v", tc.expectedGroups, res.Status.UserInfo.Groups)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(res.Status.UserInfo.Extra, tc.expectedExtra) {
|
||||
t.Fatalf("unexpected extra: wanted %v, got %v", tc.expectedExtra, res.Status.UserInfo.Extra)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestGetsSelfAttributesError(t *testing.T) {
|
||||
toggle := &atomic.Value{}
|
||||
toggle.Store(true)
|
||||
|
||||
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.APISelfSubjectReview, true)()
|
||||
|
||||
kubeClient, _, tearDownFn := framework.StartTestServer(t, framework.TestServerSetup{
|
||||
ModifyServerConfig: func(config *controlplane.Config) {
|
||||
// Unset BearerToken to disable BearerToken authenticator.
|
||||
config.GenericConfig.LoopbackClientConfig.BearerToken = ""
|
||||
config.GenericConfig.Authentication.Authenticator = authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
|
||||
if toggle.Load().(bool) {
|
||||
return &authenticator.Response{
|
||||
User: &user.DefaultInfo{
|
||||
Name: "alice",
|
||||
},
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
return nil, false, fmt.Errorf("test error")
|
||||
})
|
||||
config.GenericConfig.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
|
||||
},
|
||||
ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
|
||||
opts.APIEnablement.RuntimeConfig.Set("authentication.k8s.io/v1alpha1=true")
|
||||
},
|
||||
})
|
||||
defer tearDownFn()
|
||||
|
||||
expected := fmt.Errorf("Unauthorized")
|
||||
toggle.Store(!toggle.Load().(bool))
|
||||
|
||||
_, err := kubeClient.AuthenticationV1alpha1().
|
||||
SelfSubjectReviews().
|
||||
Create(context.TODO(), &authenticationv1alpha1.SelfSubjectReview{}, metav1.CreateOptions{})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error: %v, got nil", err)
|
||||
}
|
||||
|
||||
toggle.Store(!toggle.Load().(bool))
|
||||
if expected.Error() != err.Error() {
|
||||
t.Fatalf("expected error: %v, got %v", expected, err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user