Skip to content

Commit 764476d

Browse files
committed
return error on long-form or invalid sa name
Returns an error when the long-form name of a ServiceAccount is used with the --serviceaccount (-z) flag in `oc policy ...' commands, or if the name given is invalid.
1 parent e92d5c5 commit 764476d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

pkg/oc/admin/policy/modify_roles.go

+13
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ import (
44
"errors"
55
"fmt"
66
"io"
7+
"strings"
78

89
"github.com/spf13/cobra"
910

1011
kapierrors "k8s.io/apimachinery/pkg/api/errors"
12+
"k8s.io/apimachinery/pkg/api/validation"
1113
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1214
"k8s.io/apimachinery/pkg/runtime"
1315
kapi "k8s.io/kubernetes/pkg/api"
@@ -320,6 +322,17 @@ func (o *RoleModificationOptions) CompleteUserWithSA(f *clientcmd.Factory, cmd *
320322
return errors.New("you must specify at least one user or service account")
321323
}
322324

325+
// return an error if a fully-qualified service-account name is used
326+
for _, sa := range saNames {
327+
if strings.HasPrefix(sa, "system:serviceaccount") {
328+
return errors.New("--serviceaccount (-z) should only be used with short-form serviceaccount names (e.g. \"default\")")
329+
}
330+
331+
if len(validation.ValidateServiceAccountName(sa, false)) > 0 {
332+
return errors.New(fmt.Sprintf("%q is not a valid serviceaccount name", sa))
333+
}
334+
}
335+
323336
authorizationClient, err := f.OpenshiftInternalAuthorizationClient()
324337
if err != nil {
325338
return err

test/cmd/policy.sh

+5
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ os::cmd::expect_success "oc login -u system:admin -n '${project}'"
4040
os::cmd::expect_success 'oc delete project policy-login'
4141
os::cmd::expect_failure_and_text 'oc create policybinding default -n myproject' 'error: the server does not support legacy policy resources'
4242

43+
# validate --serviceaccount values
44+
os::cmd::expect_success_and_text 'oc policy add-role-to-user admin -z default' 'role "admin" added\: "default"'
45+
os::cmd::expect_failure_and_text 'oc policy add-role-to-user admin -z system:serviceaccount:test:default' 'should only be used with short\-form serviceaccount names'
46+
os::cmd::expect_failure_and_text 'oc policy add-role-to-user admin -z :invalid' '"\:default" is not a valid serviceaccount name'
47+
4348
# This test validates user level policy
4449
os::cmd::expect_failure_and_text 'oc policy add-role-to-user' 'you must specify a role'
4550
os::cmd::expect_failure_and_text 'oc policy add-role-to-user -z NamespaceWithoutRole' 'you must specify a role'

0 commit comments

Comments
 (0)