vendor update for CSI 0.3.0

This commit is contained in:
gman
2018-07-18 16:47:22 +02:00
parent 6f484f92fc
commit 8ea659f0d5
6810 changed files with 438061 additions and 193861 deletions

View File

@ -59,6 +59,7 @@ type AuthenticatorConfig struct {
OIDCGroupsClaim string
OIDCGroupsPrefix string
OIDCSigningAlgs []string
OIDCRequiredClaims map[string]string
ServiceAccountKeyFiles []string
ServiceAccountLookup bool
ServiceAccountIssuer string
@ -82,7 +83,6 @@ func (config AuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDe
var authenticators []authenticator.Request
var tokenAuthenticators []authenticator.Token
securityDefinitions := spec.SecurityDefinitions{}
hasBasicAuth := false
// front-proxy, BasicAuth methods, local first, then remote
// Add the front proxy authenticator if requested
@ -100,13 +100,20 @@ func (config AuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDe
authenticators = append(authenticators, requestHeaderAuthenticator)
}
// basic auth
if len(config.BasicAuthFile) > 0 {
basicAuth, err := newAuthenticatorFromBasicAuthFile(config.BasicAuthFile)
if err != nil {
return nil, nil, err
}
authenticators = append(authenticators, basicAuth)
hasBasicAuth = true
securityDefinitions["HTTPBasic"] = &spec.SecurityScheme{
SecuritySchemeProps: spec.SecuritySchemeProps{
Type: "basic",
Description: "HTTP Basic authentication",
},
}
}
// X509 methods
@ -153,7 +160,7 @@ func (config AuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDe
// simply returns an error, the OpenID Connect plugin may query the provider to
// update the keys, causing performance hits.
if len(config.OIDCIssuerURL) > 0 && len(config.OIDCClientID) > 0 {
oidcAuth, err := newAuthenticatorFromOIDCIssuerURL(config.OIDCIssuerURL, config.OIDCClientID, config.OIDCCAFile, config.OIDCUsernameClaim, config.OIDCUsernamePrefix, config.OIDCGroupsClaim, config.OIDCGroupsPrefix, config.OIDCSigningAlgs)
oidcAuth, err := newAuthenticatorFromOIDCIssuerURL(config.OIDCIssuerURL, config.OIDCClientID, config.OIDCCAFile, config.OIDCUsernameClaim, config.OIDCUsernamePrefix, config.OIDCGroupsClaim, config.OIDCGroupsPrefix, config.OIDCSigningAlgs, config.OIDCRequiredClaims)
if err != nil {
return nil, nil, err
}
@ -167,15 +174,6 @@ func (config AuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDe
tokenAuthenticators = append(tokenAuthenticators, webhookTokenAuth)
}
if hasBasicAuth {
securityDefinitions["HTTPBasic"] = &spec.SecurityScheme{
SecuritySchemeProps: spec.SecuritySchemeProps{
Type: "basic",
Description: "HTTP Basic authentication",
},
}
}
if len(tokenAuthenticators) > 0 {
// Union the token authenticators
tokenAuth := tokenunion.New(tokenAuthenticators...)
@ -198,10 +196,6 @@ func (config AuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDe
if config.Anonymous {
return anonymous.NewAuthenticator(), &securityDefinitions, nil
}
}
switch len(authenticators) {
case 0:
return nil, &securityDefinitions, nil
}
@ -245,7 +239,7 @@ func newAuthenticatorFromTokenFile(tokenAuthFile string) (authenticator.Token, e
}
// newAuthenticatorFromOIDCIssuerURL returns an authenticator.Token or an error.
func newAuthenticatorFromOIDCIssuerURL(issuerURL, clientID, caFile, usernameClaim, usernamePrefix, groupsClaim, groupsPrefix string, signingAlgs []string) (authenticator.Token, error) {
func newAuthenticatorFromOIDCIssuerURL(issuerURL, clientID, caFile, usernameClaim, usernamePrefix, groupsClaim, groupsPrefix string, signingAlgs []string, requiredClaims map[string]string) (authenticator.Token, error) {
const noUsernamePrefix = "-"
if usernamePrefix == "" && usernameClaim != "email" {
@ -270,6 +264,7 @@ func newAuthenticatorFromOIDCIssuerURL(issuerURL, clientID, caFile, usernameClai
GroupsClaim: groupsClaim,
GroupsPrefix: groupsPrefix,
SupportedSigningAlgs: signingAlgs,
RequiredClaims: requiredClaims,
})
if err != nil {
return nil, err

View File

@ -3,17 +3,6 @@ package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_test(
name = "go_default_test",
srcs = ["config_test.go"],
data = [
"//pkg/auth/authorizer/abac:example_policy",
],
embed = [":go_default_library"],
deps = ["//pkg/kubeapiserver/authorizer/modes:go_default_library"],
)
go_library(

View File

@ -17,7 +17,6 @@ limitations under the License.
package authorizer
import (
"errors"
"fmt"
"time"
@ -60,26 +59,22 @@ type AuthorizationConfig struct {
// based on the authorizationMode or an error.
func (config AuthorizationConfig) New() (authorizer.Authorizer, authorizer.RuleResolver, error) {
if len(config.AuthorizationModes) == 0 {
return nil, nil, errors.New("At least one authorization mode should be passed")
return nil, nil, fmt.Errorf("at least one authorization mode must be passed")
}
var (
authorizers []authorizer.Authorizer
ruleResolvers []authorizer.RuleResolver
)
authorizerMap := make(map[string]bool)
for _, authorizationMode := range config.AuthorizationModes {
if authorizerMap[authorizationMode] {
return nil, nil, fmt.Errorf("Authorization mode %s specified more than once", authorizationMode)
}
// Keep cases in sync with constant list above.
// Keep cases in sync with constant list in k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes/modes.go.
switch authorizationMode {
case modes.ModeNode:
graph := node.NewGraph()
node.AddGraphEventHandlers(
graph,
config.InformerFactory.Core().InternalVersion().Nodes(),
config.InformerFactory.Core().InternalVersion().Pods(),
config.InformerFactory.Core().InternalVersion().PersistentVolumes(),
config.VersionedInformerFactory.Storage().V1beta1().VolumeAttachments(),
@ -96,9 +91,6 @@ func (config AuthorizationConfig) New() (authorizer.Authorizer, authorizer.RuleR
authorizers = append(authorizers, alwaysDenyAuthorizer)
ruleResolvers = append(ruleResolvers, alwaysDenyAuthorizer)
case modes.ModeABAC:
if config.PolicyFile == "" {
return nil, nil, errors.New("ABAC's authorization policy file not passed")
}
abacAuthorizer, err := abac.NewFromFile(config.PolicyFile)
if err != nil {
return nil, nil, err
@ -106,9 +98,6 @@ func (config AuthorizationConfig) New() (authorizer.Authorizer, authorizer.RuleR
authorizers = append(authorizers, abacAuthorizer)
ruleResolvers = append(ruleResolvers, abacAuthorizer)
case modes.ModeWebhook:
if config.WebhookConfigFile == "" {
return nil, nil, errors.New("Webhook's configuration file not passed")
}
webhookAuthorizer, err := webhook.New(config.WebhookConfigFile,
config.WebhookCacheAuthorizedTTL,
config.WebhookCacheUnauthorizedTTL)
@ -119,24 +108,16 @@ func (config AuthorizationConfig) New() (authorizer.Authorizer, authorizer.RuleR
ruleResolvers = append(ruleResolvers, webhookAuthorizer)
case modes.ModeRBAC:
rbacAuthorizer := rbac.New(
&rbac.RoleGetter{Lister: config.InformerFactory.Rbac().InternalVersion().Roles().Lister()},
&rbac.RoleBindingLister{Lister: config.InformerFactory.Rbac().InternalVersion().RoleBindings().Lister()},
&rbac.ClusterRoleGetter{Lister: config.InformerFactory.Rbac().InternalVersion().ClusterRoles().Lister()},
&rbac.ClusterRoleBindingLister{Lister: config.InformerFactory.Rbac().InternalVersion().ClusterRoleBindings().Lister()},
&rbac.RoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().Roles().Lister()},
&rbac.RoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().RoleBindings().Lister()},
&rbac.ClusterRoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoles().Lister()},
&rbac.ClusterRoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoleBindings().Lister()},
)
authorizers = append(authorizers, rbacAuthorizer)
ruleResolvers = append(ruleResolvers, rbacAuthorizer)
default:
return nil, nil, fmt.Errorf("Unknown authorization mode %s specified", authorizationMode)
return nil, nil, fmt.Errorf("unknown authorization mode %s specified", authorizationMode)
}
authorizerMap[authorizationMode] = true
}
if !authorizerMap[modes.ModeABAC] && config.PolicyFile != "" {
return nil, nil, errors.New("Cannot specify --authorization-policy-file without mode ABAC")
}
if !authorizerMap[modes.ModeWebhook] && config.WebhookConfigFile != "" {
return nil, nil, errors.New("Cannot specify --authorization-webhook-config-file without mode Webhook")
}
return union.New(authorizers...), union.NewRuleResolvers(ruleResolvers...), nil

View File

@ -1,101 +0,0 @@
/*
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 authorizer
import (
"k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes"
"testing"
)
// New has multiple return possibilities. This test
// validates that errors are returned only when proper.
func TestNew(t *testing.T) {
examplePolicyFile := "../../auth/authorizer/abac/example_policy_file.jsonl"
tests := []struct {
config AuthorizationConfig
wantErr bool
msg string
}{
{
// Unknown modes should return errors
config: AuthorizationConfig{AuthorizationModes: []string{"DoesNotExist"}},
wantErr: true,
msg: "using a fake mode should have returned an error",
},
{
// ModeAlwaysAllow and ModeAlwaysDeny should return without authorizationPolicyFile
// but error if one is given
config: AuthorizationConfig{AuthorizationModes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny}},
msg: "returned an error for valid config",
},
{
// ModeABAC requires a policy file
config: AuthorizationConfig{AuthorizationModes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny, modes.ModeABAC}},
wantErr: true,
msg: "specifying ABAC with no policy file should return an error",
},
{
// ModeABAC should not error if a valid policy path is provided
config: AuthorizationConfig{
AuthorizationModes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny, modes.ModeABAC},
PolicyFile: examplePolicyFile,
},
msg: "errored while using a valid policy file",
},
{
// Authorization Policy file cannot be used without ModeABAC
config: AuthorizationConfig{
AuthorizationModes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny},
PolicyFile: examplePolicyFile,
},
wantErr: true,
msg: "should have errored when Authorization Policy File is used without ModeABAC",
},
{
// At least one authorizationMode is necessary
config: AuthorizationConfig{PolicyFile: examplePolicyFile},
wantErr: true,
msg: "should have errored when no authorization modes are passed",
},
{
// ModeWebhook requires at minimum a target.
config: AuthorizationConfig{AuthorizationModes: []string{modes.ModeWebhook}},
wantErr: true,
msg: "should have errored when config was empty with ModeWebhook",
},
{
// Cannot provide webhook flags without ModeWebhook
config: AuthorizationConfig{
AuthorizationModes: []string{modes.ModeAlwaysAllow},
WebhookConfigFile: "authz_webhook_config.yml",
},
wantErr: true,
msg: "should have errored when Webhook config file is used without ModeWebhook",
},
}
for _, tt := range tests {
_, _, err := tt.config.New()
if tt.wantErr && (err == nil) {
t.Errorf("New %s", tt.msg)
} else if !tt.wantErr && (err != nil) {
t.Errorf("New %s: %v", tt.msg, err)
}
}
}

View File

@ -26,7 +26,6 @@ import (
// SpecialDefaultResourcePrefixes are prefixes compiled into Kubernetes.
var SpecialDefaultResourcePrefixes = map[schema.GroupResource]string{
{Group: "", Resource: "replicationControllers"}: "controllers",
{Group: "", Resource: "replicationcontrollers"}: "controllers",
{Group: "", Resource: "endpoints"}: "services/endpoints",
{Group: "", Resource: "nodes"}: "minions",

View File

@ -23,6 +23,7 @@ go_library(
"//pkg/api/legacyscheme:go_default_library",
"//pkg/client/informers/informers_generated/internalversion:go_default_library",
"//pkg/cloudprovider/providers:go_default_library",
"//pkg/features:go_default_library",
"//pkg/kubeapiserver/authenticator:go_default_library",
"//pkg/kubeapiserver/authorizer:go_default_library",
"//pkg/kubeapiserver/authorizer/modes:go_default_library",
@ -37,13 +38,10 @@ go_library(
"//plugin/pkg/admission/extendedresourcetoleration:go_default_library",
"//plugin/pkg/admission/gc:go_default_library",
"//plugin/pkg/admission/imagepolicy:go_default_library",
"//plugin/pkg/admission/initialresources:go_default_library",
"//plugin/pkg/admission/limitranger:go_default_library",
"//plugin/pkg/admission/namespace/autoprovision:go_default_library",
"//plugin/pkg/admission/namespace/exists:go_default_library",
"//plugin/pkg/admission/noderestriction:go_default_library",
"//plugin/pkg/admission/persistentvolume/label:go_default_library",
"//plugin/pkg/admission/persistentvolume/resize:go_default_library",
"//plugin/pkg/admission/podnodeselector:go_default_library",
"//plugin/pkg/admission/podpreset:go_default_library",
"//plugin/pkg/admission/podtolerationrestriction:go_default_library",
@ -52,6 +50,8 @@ go_library(
"//plugin/pkg/admission/security/podsecuritypolicy:go_default_library",
"//plugin/pkg/admission/securitycontext/scdeny:go_default_library",
"//plugin/pkg/admission/serviceaccount:go_default_library",
"//plugin/pkg/admission/storage/persistentvolume/label:go_default_library",
"//plugin/pkg/admission/storage/persistentvolume/resize:go_default_library",
"//plugin/pkg/admission/storage/storageclass/setdefault:go_default_library",
"//plugin/pkg/admission/storage/storageobjectinuseprotection:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
@ -68,6 +68,8 @@ go_library(
"//vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/options:go_default_library",
"//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library",
"//vendor/k8s.io/apiserver/pkg/util/flag:go_default_library",
"//vendor/k8s.io/client-go/informers:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
],
@ -90,8 +92,12 @@ go_test(
name = "go_default_test",
srcs = [
"admission_test.go",
"authorization_test.go",
"storage_versions_test.go",
],
embed = [":go_default_library"],
deps = ["//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library"],
deps = [
"//pkg/kubeapiserver/authorizer/modes:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
],
)

View File

@ -73,6 +73,7 @@ func (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet) {
"The order of plugins in which they are passed to this flag does not matter. "+
"Comma-delimited list of: "+strings.Join(a.GenericAdmission.Plugins.Registered(), ", ")+".")
fs.MarkDeprecated("admission-control", "Use --enable-admission-plugins or --disable-admission-plugins instead. Will be removed in a future version.")
fs.Lookup("admission-control").Hidden = false
a.GenericAdmission.AddFlags(fs)
}

View File

@ -25,8 +25,10 @@ import (
"github.com/golang/glog"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/util/sets"
genericapiserver "k8s.io/apiserver/pkg/server"
genericoptions "k8s.io/apiserver/pkg/server/options"
"k8s.io/apiserver/pkg/util/flag"
"k8s.io/kubernetes/pkg/kubeapiserver/authenticator"
authzmodes "k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes"
)
@ -63,6 +65,7 @@ type OIDCAuthenticationOptions struct {
GroupsClaim string
GroupsPrefix string
SigningAlgs []string
RequiredClaims map[string]string
}
type PasswordFileAuthenticationOptions struct {
@ -222,6 +225,11 @@ func (s *BuiltInAuthenticationOptions) AddFlags(fs *pflag.FlagSet) {
"Comma-separated list of allowed JOSE asymmetric signing algorithms. JWTs with a "+
"'alg' header value not in this list will be rejected. "+
"Values are defined by RFC 7518 https://tools.ietf.org/html/rfc7518#section-3.1.")
fs.Var(flag.NewMapStringStringNoSplit(&s.OIDC.RequiredClaims), "oidc-required-claim", ""+
"A key=value pair that describes a required claim in the ID Token. "+
"If set, the claim is verified to be present in the ID Token with a matching value. "+
"Repeat this flag to specify multiple claims.")
}
if s.PasswordFile != nil {
@ -297,6 +305,7 @@ func (s *BuiltInAuthenticationOptions) ToAuthenticationConfig() authenticator.Au
ret.OIDCUsernameClaim = s.OIDC.UsernameClaim
ret.OIDCUsernamePrefix = s.OIDC.UsernamePrefix
ret.OIDCSigningAlgs = s.OIDC.SigningAlgs
ret.OIDCRequiredClaims = s.OIDC.RequiredClaims
}
if s.PasswordFile != nil {
@ -365,17 +374,8 @@ func (o *BuiltInAuthenticationOptions) ApplyAuthorization(authorization *BuiltIn
// authorization ModeAlwaysAllow cannot be combined with AnonymousAuth.
// in such a case the AnonymousAuth is stomped to false and you get a message
if o.Anonymous.Allow {
found := false
for _, mode := range strings.Split(authorization.Mode, ",") {
if mode == authzmodes.ModeAlwaysAllow {
found = true
break
}
}
if found {
glog.Warningf("AnonymousAuth is not allowed with the AllowAll authorizer. Resetting AnonymousAuth to false. You should use a different authorizer")
o.Anonymous.Allow = false
}
if o.Anonymous.Allow && sets.NewString(authorization.Modes...).Has(authzmodes.ModeAlwaysAllow) {
glog.Warningf("AnonymousAuth is not allowed with the AlwaysAllow authorizer. Resetting AnonymousAuth to false. You should use a different authorizer")
o.Anonymous.Allow = false
}
}

View File

@ -17,11 +17,13 @@ limitations under the License.
package options
import (
"fmt"
"strings"
"time"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/util/sets"
versionedinformers "k8s.io/client-go/informers"
informers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"
"k8s.io/kubernetes/pkg/kubeapiserver/authorizer"
@ -29,7 +31,7 @@ import (
)
type BuiltInAuthorizationOptions struct {
Mode string
Modes []string
PolicyFile string
WebhookConfigFile string
WebhookCacheAuthorizedTTL time.Duration
@ -38,19 +40,57 @@ type BuiltInAuthorizationOptions struct {
func NewBuiltInAuthorizationOptions() *BuiltInAuthorizationOptions {
return &BuiltInAuthorizationOptions{
Mode: authzmodes.ModeAlwaysAllow,
Modes: []string{authzmodes.ModeAlwaysAllow},
WebhookCacheAuthorizedTTL: 5 * time.Minute,
WebhookCacheUnauthorizedTTL: 30 * time.Second,
}
}
func (s *BuiltInAuthorizationOptions) Validate() []error {
if s == nil {
return nil
}
allErrors := []error{}
if len(s.Modes) == 0 {
allErrors = append(allErrors, fmt.Errorf("at least one authorization-mode must be passed"))
}
allowedModes := sets.NewString(authzmodes.AuthorizationModeChoices...)
modes := sets.NewString(s.Modes...)
for _, mode := range s.Modes {
if !allowedModes.Has(mode) {
allErrors = append(allErrors, fmt.Errorf("authorization-mode %q is not a valid mode", mode))
}
if mode == authzmodes.ModeABAC {
if s.PolicyFile == "" {
allErrors = append(allErrors, fmt.Errorf("authorization-mode ABAC's authorization policy file not passed"))
}
}
if mode == authzmodes.ModeWebhook {
if s.WebhookConfigFile == "" {
allErrors = append(allErrors, fmt.Errorf("authorization-mode Webhook's authorization config file not passed"))
}
}
}
if s.PolicyFile != "" && !modes.Has(authzmodes.ModeABAC) {
allErrors = append(allErrors, fmt.Errorf("cannot specify --authorization-policy-file without mode ABAC"))
}
if s.WebhookConfigFile != "" && !modes.Has(authzmodes.ModeWebhook) {
allErrors = append(allErrors, fmt.Errorf("cannot specify --authorization-webhook-config-file without mode Webhook"))
}
if len(s.Modes) != len(modes.List()) {
allErrors = append(allErrors, fmt.Errorf("authorization-mode %q has mode specified more than once", s.Modes))
}
return allErrors
}
func (s *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&s.Mode, "authorization-mode", s.Mode, ""+
fs.StringSliceVar(&s.Modes, "authorization-mode", s.Modes, ""+
"Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: "+
strings.Join(authzmodes.AuthorizationModeChoices, ",")+".")
@ -68,25 +108,11 @@ func (s *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {
fs.DurationVar(&s.WebhookCacheUnauthorizedTTL,
"authorization-webhook-cache-unauthorized-ttl", s.WebhookCacheUnauthorizedTTL,
"The duration to cache 'unauthorized' responses from the webhook authorizer.")
fs.String("authorization-rbac-super-user", "", ""+
"If specified, a username which avoids RBAC authorization checks and role binding "+
"privilege escalation checks, to be used with --authorization-mode=RBAC.")
fs.MarkDeprecated("authorization-rbac-super-user", "Removed during alpha to beta. The 'system:masters' group has privileged access.")
}
func (s *BuiltInAuthorizationOptions) Modes() []string {
modes := []string{}
if len(s.Mode) > 0 {
modes = strings.Split(s.Mode, ",")
}
return modes
}
func (s *BuiltInAuthorizationOptions) ToAuthorizationConfig(informerFactory informers.SharedInformerFactory, versionedInformerFactory versionedinformers.SharedInformerFactory) authorizer.AuthorizationConfig {
return authorizer.AuthorizationConfig{
AuthorizationModes: s.Modes(),
AuthorizationModes: s.Modes,
PolicyFile: s.PolicyFile,
WebhookConfigFile: s.WebhookConfigFile,
WebhookCacheAuthorizedTTL: s.WebhookCacheAuthorizedTTL,

View File

@ -0,0 +1,104 @@
/*
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.
*/
package options
import (
"testing"
"k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes"
)
func TestAuthzValidate(t *testing.T) {
examplePolicyFile := "../../auth/authorizer/abac/example_policy_file.jsonl"
testCases := []struct {
name string
modes []string
policyFile string
webhookConfigFile string
expectErr bool
}{
{
name: "Unknown modes should return errors",
modes: []string{"DoesNotExist"},
expectErr: true,
},
{
name: "At least one authorizationMode is necessary",
modes: []string{},
expectErr: true,
},
{
name: "ModeAlwaysAllow and ModeAlwaysDeny should return without authorizationPolicyFile",
modes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny},
expectErr: false,
},
{
name: "ModeABAC requires a policy file",
modes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny, modes.ModeABAC},
expectErr: true,
},
{
name: "Authorization Policy file cannot be used without ModeABAC",
modes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny},
policyFile: examplePolicyFile,
webhookConfigFile: "",
expectErr: true,
},
{
name: "ModeABAC should not error if a valid policy path is provided",
modes: []string{modes.ModeAlwaysAllow, modes.ModeAlwaysDeny, modes.ModeABAC},
policyFile: examplePolicyFile,
webhookConfigFile: "",
expectErr: false,
},
{
name: "ModeWebhook requires a config file",
modes: []string{modes.ModeWebhook},
expectErr: true,
},
{
name: "Cannot provide webhook config file without ModeWebhook",
modes: []string{modes.ModeAlwaysAllow},
webhookConfigFile: "authz_webhook_config.yaml",
expectErr: true,
},
{
name: "ModeWebhook should not error if a valid config file is provided",
modes: []string{modes.ModeWebhook},
webhookConfigFile: "authz_webhook_config.yaml",
expectErr: false,
},
}
for _, testcase := range testCases {
t.Run(testcase.name, func(t *testing.T) {
options := NewBuiltInAuthorizationOptions()
options.Modes = testcase.modes
options.WebhookConfigFile = testcase.webhookConfigFile
options.PolicyFile = testcase.policyFile
errs := options.Validate()
if len(errs) > 0 && !testcase.expectErr {
t.Errorf("got unexpected err %v", errs)
}
if testcase.expectErr && len(errs) == 0 {
t.Errorf("should return an error")
}
})
}
}

View File

@ -34,13 +34,10 @@ import (
"k8s.io/kubernetes/plugin/pkg/admission/extendedresourcetoleration"
"k8s.io/kubernetes/plugin/pkg/admission/gc"
"k8s.io/kubernetes/plugin/pkg/admission/imagepolicy"
"k8s.io/kubernetes/plugin/pkg/admission/initialresources"
"k8s.io/kubernetes/plugin/pkg/admission/limitranger"
"k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision"
"k8s.io/kubernetes/plugin/pkg/admission/namespace/exists"
"k8s.io/kubernetes/plugin/pkg/admission/noderestriction"
"k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label"
"k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/resize"
"k8s.io/kubernetes/plugin/pkg/admission/podnodeselector"
"k8s.io/kubernetes/plugin/pkg/admission/podpreset"
"k8s.io/kubernetes/plugin/pkg/admission/podtolerationrestriction"
@ -49,6 +46,8 @@ import (
"k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy"
"k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny"
"k8s.io/kubernetes/plugin/pkg/admission/serviceaccount"
"k8s.io/kubernetes/plugin/pkg/admission/storage/persistentvolume/label"
"k8s.io/kubernetes/plugin/pkg/admission/storage/persistentvolume/resize"
"k8s.io/kubernetes/plugin/pkg/admission/storage/storageclass/setdefault"
"k8s.io/kubernetes/plugin/pkg/admission/storage/storageobjectinuseprotection"
@ -58,6 +57,8 @@ import (
"k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle"
mutatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/mutating"
validatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/validating"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/kubernetes/pkg/features"
)
// AllOrderedPlugins is the list of all the plugins in order.
@ -68,7 +69,6 @@ var AllOrderedPlugins = []string{
exists.PluginName, // NamespaceExists
scdeny.PluginName, // SecurityContextDeny
antiaffinity.PluginName, // LimitPodHardAntiAffinityTopology
initialresources.PluginName, // InitialResources
podpreset.PluginName, // PodPreset
limitranger.PluginName, // LimitRanger
serviceaccount.PluginName, // ServiceAccount
@ -109,7 +109,6 @@ func RegisterAllAdmissionPlugins(plugins *admission.Plugins) {
extendedresourcetoleration.Register(plugins)
gc.Register(plugins)
imagepolicy.Register(plugins)
initialresources.Register(plugins)
limitranger.Register(plugins)
autoprovision.Register(plugins)
exists.Register(plugins)
@ -134,13 +133,17 @@ func DefaultOffAdmissionPlugins() sets.String {
lifecycle.PluginName, //NamespaceLifecycle
limitranger.PluginName, //LimitRanger
serviceaccount.PluginName, //ServiceAccount
label.PluginName, //PersistentVolumeLabel
setdefault.PluginName, //DefaultStorageClass
resize.PluginName, //PersistentVolumeClaimResize
defaulttolerationseconds.PluginName, //DefaultTolerationSeconds
mutatingwebhook.PluginName, //MutatingAdmissionWebhook
validatingwebhook.PluginName, //ValidatingAdmissionWebhook
resourcequota.PluginName, //ResourceQuota
)
if utilfeature.DefaultFeatureGate.Enabled(features.PodPriority) {
defaultOnPlugins.Insert(podpriority.PluginName) //PodPriority
}
return sets.NewString(AllOrderedPlugins...).Difference(defaultOnPlugins)
}

View File

@ -81,7 +81,7 @@ func NewInsecureServingOptions() *InsecureServingOptions {
}
}
func (s InsecureServingOptions) Validate(portArg string) []error {
func (s InsecureServingOptions) Validate() []error {
errors := []error{}
if s.BindPort < 0 || s.BindPort > 65535 {
@ -99,6 +99,7 @@ func (s *InsecureServingOptions) AddFlags(fs *pflag.FlagSet) {
fs.IPVar(&s.BindAddress, "insecure-bind-address", s.BindAddress, ""+
"The IP address on which to serve the --insecure-port (set to 0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces).")
fs.MarkDeprecated("insecure-bind-address", "This flag will be removed in a future version.")
fs.Lookup("insecure-bind-address").Hidden = false
fs.IntVar(&s.BindPort, "insecure-port", s.BindPort, ""+
"The port on which to serve unsecured, unauthenticated access. It is assumed "+
@ -106,6 +107,7 @@ func (s *InsecureServingOptions) AddFlags(fs *pflag.FlagSet) {
"the cluster and that port 443 on the cluster's public address is proxied to this "+
"port. This is performed by nginx in the default setup. Set to zero to disable.")
fs.MarkDeprecated("insecure-port", "This flag will be removed in a future version.")
fs.Lookup("insecure-port").Hidden = false
}
// TODO: remove it until kops stop using `--address`

View File

@ -22,6 +22,8 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"sort"
"github.com/spf13/pflag"
)
@ -40,8 +42,8 @@ type StorageSerializationOptions struct {
func NewStorageSerializationOptions() *StorageSerializationOptions {
return &StorageSerializationOptions{
DefaultStorageVersions: legacyscheme.Registry.AllPreferredGroupVersions(),
StorageVersions: legacyscheme.Registry.AllPreferredGroupVersions(),
DefaultStorageVersions: ToPreferredVersionString(legacyscheme.Scheme.PreferredVersionAllGroups()),
StorageVersions: ToPreferredVersionString(legacyscheme.Scheme.PreferredVersionAllGroups()),
}
}
@ -95,20 +97,25 @@ func mergeGroupVersionIntoMap(gvList string, dest map[string]schema.GroupVersion
func (s *StorageSerializationOptions) AddFlags(fs *pflag.FlagSet) {
// Note: the weird ""+ in below lines seems to be the only way to get gofmt to
// arrange these text blocks sensibly. Grrr.
deprecatedStorageVersion := ""
fs.StringVar(&deprecatedStorageVersion, "storage-version", deprecatedStorageVersion,
"DEPRECATED: the version to store the legacy v1 resources with. Defaults to server preferred.")
fs.MarkDeprecated("storage-version", "--storage-version is deprecated and will be removed when the v1 API "+
"is retired. Setting this has no effect. See --storage-versions instead.")
fs.StringVar(&s.StorageVersions, "storage-versions", s.StorageVersions, ""+
"The per-group version to store resources in. "+
"Specified in the format \"group1/version1,group2/version2,...\". "+
"In the case where objects are moved from one group to the other, "+
"you may specify the format \"group1=group2/v1beta1,group3/v1beta1,...\". "+
"You only need to pass the groups you wish to change from the defaults. "+
"It defaults to a list of preferred versions of all registered groups, "+
"which is derived from the KUBE_API_VERSIONS environment variable.")
"It defaults to a list of preferred versions of all known groups.")
}
// ToPreferredVersionString returns the preferred versions of all registered
// groups in the form of "group1/version1,group2/version2,...". This is compatible
// with the flag format
func ToPreferredVersionString(versions []schema.GroupVersion) string {
var defaults []string
for _, version := range versions {
defaults = append(defaults, version.String())
}
// sorting provides stable output for help.
sort.Strings(defaults)
return strings.Join(defaults, ",")
}

View File

@ -13,7 +13,6 @@ go_library(
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/filters:go_default_library",
"//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library",
"//vendor/k8s.io/apiserver/pkg/features:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server:go_default_library",
"//vendor/k8s.io/apiserver/pkg/server/filters:go_default_library",

View File

@ -25,7 +25,6 @@ import (
"k8s.io/apiserver/pkg/authentication/user"
genericapifilters "k8s.io/apiserver/pkg/endpoints/filters"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/server"
genericfilters "k8s.io/apiserver/pkg/server/filters"
@ -41,17 +40,16 @@ import (
func BuildInsecureHandlerChain(apiHandler http.Handler, c *server.Config) http.Handler {
handler := apiHandler
if utilfeature.DefaultFeatureGate.Enabled(features.AdvancedAuditing) {
handler = genericapifilters.WithAudit(handler, c.RequestContextMapper, c.AuditBackend, c.AuditPolicyChecker, c.LongRunningFunc)
handler = genericapifilters.WithAudit(handler, c.AuditBackend, c.AuditPolicyChecker, c.LongRunningFunc)
} else {
handler = genericapifilters.WithLegacyAudit(handler, c.RequestContextMapper, c.LegacyAuditWriter)
handler = genericapifilters.WithLegacyAudit(handler, c.LegacyAuditWriter)
}
handler = genericapifilters.WithAuthentication(handler, c.RequestContextMapper, insecureSuperuser{}, nil)
handler = genericapifilters.WithAuthentication(handler, insecureSuperuser{}, nil)
handler = genericfilters.WithCORS(handler, c.CorsAllowedOriginList, nil, nil, nil, "true")
handler = genericfilters.WithTimeoutForNonLongRunningRequests(handler, c.RequestContextMapper, c.LongRunningFunc, c.RequestTimeout)
handler = genericfilters.WithMaxInFlightLimit(handler, c.MaxRequestsInFlight, c.MaxMutatingRequestsInFlight, c.RequestContextMapper, c.LongRunningFunc)
handler = genericfilters.WithWaitGroup(handler, c.RequestContextMapper, c.LongRunningFunc, c.HandlerChainWaitGroup)
handler = genericapifilters.WithRequestInfo(handler, server.NewRequestInfoResolver(c), c.RequestContextMapper)
handler = apirequest.WithRequestContext(handler, c.RequestContextMapper)
handler = genericfilters.WithTimeoutForNonLongRunningRequests(handler, c.LongRunningFunc, c.RequestTimeout)
handler = genericfilters.WithMaxInFlightLimit(handler, c.MaxRequestsInFlight, c.MaxMutatingRequestsInFlight, c.LongRunningFunc)
handler = genericfilters.WithWaitGroup(handler, c.LongRunningFunc, c.HandlerChainWaitGroup)
handler = genericapifilters.WithRequestInfo(handler, server.NewRequestInfoResolver(c))
handler = genericfilters.WithPanicRecovery(handler)
return handler