當前位置: 首頁>>代碼示例>>Golang>>正文


Golang serviceaccount.MakeUsername函數代碼示例

本文整理匯總了Golang中k8s/io/kubernetes/pkg/serviceaccount.MakeUsername函數的典型用法代碼示例。如果您正苦於以下問題:Golang MakeUsername函數的具體用法?Golang MakeUsername怎麽用?Golang MakeUsername使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了MakeUsername函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: GetBootstrapServiceAccountProjectRoleBindings

func GetBootstrapServiceAccountProjectRoleBindings(namespace string) []authorizationapi.RoleBinding {
    return []authorizationapi.RoleBinding{
        {
            ObjectMeta: kapi.ObjectMeta{
                Name:      ImagePullerRoleBindingName,
                Namespace: namespace,
            },
            RoleRef: kapi.ObjectReference{
                Name: ImagePullerRoleName,
            },
            Groups: util.NewStringSet(serviceaccount.MakeNamespaceGroupName(namespace)),
        },
        {
            ObjectMeta: kapi.ObjectMeta{
                Name:      ImageBuilderRoleBindingName,
                Namespace: namespace,
            },
            RoleRef: kapi.ObjectReference{
                Name: ImageBuilderRoleName,
            },
            Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, BuilderServiceAccountName)),
        },
        {
            ObjectMeta: kapi.ObjectMeta{
                Name:      DeployerRoleBindingName,
                Namespace: namespace,
            },
            RoleRef: kapi.ObjectReference{
                Name: DeployerRoleName,
            },
            Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, DeployerServiceAccountName)),
        },
    }
}
開發者ID:Tlacenka,項目名稱:origin,代碼行數:34,代碼來源:project_policy.go

示例2: getExpectedAccess

func getExpectedAccess() (map[string][]string, map[string][]string) {
    groups := map[string][]string{
        SecurityContextConstraintPrivileged: {ClusterAdminGroup, NodesGroup},
        SecurityContextConstraintsAnyUID:    {ClusterAdminGroup},
        SecurityContextConstraintRestricted: {AuthenticatedGroup},
    }

    buildControllerUsername := serviceaccount.MakeUsername(DefaultOpenShiftInfraNamespace, InfraBuildControllerServiceAccountName)
    pvControllerUsername := serviceaccount.MakeUsername(DefaultOpenShiftInfraNamespace, InfraPersistentVolumeBinderControllerServiceAccountName)
    users := map[string][]string{
        SecurityContextConstraintPrivileged:         {buildControllerUsername},
        SecurityContextConstraintHostMountAndAnyUID: {pvControllerUsername},
    }
    return groups, users
}
開發者ID:rrati,項目名稱:origin,代碼行數:15,代碼來源:securitycontextconstraints_test.go

示例3: GetBoostrapSCCAccess

// GetBoostrapSCCAccess provides the default set of access that should be passed to GetBootstrapSecurityContextConstraints.
func GetBoostrapSCCAccess(infraNamespace string) (map[string][]string, map[string][]string) {
    groups := map[string][]string{
        SecurityContextConstraintPrivileged: {ClusterAdminGroup, NodesGroup},
        SecurityContextConstraintsAnyUID:    {ClusterAdminGroup},
        SecurityContextConstraintRestricted: {AuthenticatedGroup},
    }

    buildControllerUsername := serviceaccount.MakeUsername(infraNamespace, InfraBuildControllerServiceAccountName)
    pvRecyclerControllerUsername := serviceaccount.MakeUsername(infraNamespace, InfraPersistentVolumeRecyclerControllerServiceAccountName)
    users := map[string][]string{
        SecurityContextConstraintPrivileged:         {buildControllerUsername},
        SecurityContextConstraintHostMountAndAnyUID: {pvRecyclerControllerUsername},
    }
    return groups, users
}
開發者ID:enoodle,項目名稱:origin,代碼行數:16,代碼來源:securitycontextconstraints.go

示例4: CompleteUserWithSA

func (o *RoleModificationOptions) CompleteUserWithSA(f *clientcmd.Factory, args []string, saNames util.StringList) error {
    if (len(args) < 2) && (len(saNames) == 0) {
        return errors.New("You must specify at least two arguments: <role> <user> [user]...")
    }

    o.RoleName = args[0]
    if len(args) > 1 {
        o.Users = append(o.Users, args[1:]...)
    }

    osClient, _, err := f.Clients()
    if err != nil {
        return err
    }

    roleBindingNamespace, _, err := f.DefaultNamespace()
    if err != nil {
        return err
    }
    o.RoleBindingAccessor = NewLocalRoleBindingAccessor(roleBindingNamespace, osClient)

    for _, sa := range saNames {
        o.Users = append(o.Users, serviceaccount.MakeUsername(roleBindingNamespace, sa))
    }

    return nil
}
開發者ID:Tlacenka,項目名稱:origin,代碼行數:27,代碼來源:modify_roles.go

示例5: StringSubjectsFor

// StringSubjectsFor returns users and groups for comparison against user.Info.  currentNamespace is used to
// to create usernames for service accounts where namespace=="".
func StringSubjectsFor(currentNamespace string, subjects []kapi.ObjectReference) ([]string, []string) {
    // these MUST be nil to indicate empty
    var users, groups []string

    for _, subject := range subjects {
        switch subject.Kind {
        case ServiceAccountKind:
            namespace := currentNamespace
            if len(subject.Namespace) > 0 {
                namespace = subject.Namespace
            }
            if len(namespace) > 0 {
                users = append(users, serviceaccount.MakeUsername(namespace, subject.Name))
            }

        case UserKind, SystemUserKind:
            users = append(users, subject.Name)

        case GroupKind, SystemGroupKind:
            groups = append(groups, subject.Name)
        }
    }

    return users, groups
}
開發者ID:Xmagicer,項目名稱:origin,代碼行數:27,代碼來源:helpers.go

示例6: SubjectsContainUser

// SubjectsContainUser returns true if the provided subjects contain the named user. currentNamespace
// is used to identify service accounts that are defined in a relative fashion.
func SubjectsContainUser(subjects []kapi.ObjectReference, currentNamespace string, user string) bool {
    if !strings.HasPrefix(user, serviceaccount.ServiceAccountUsernamePrefix) {
        for _, subject := range subjects {
            switch subject.Kind {
            case UserKind, SystemUserKind:
                if user == subject.Name {
                    return true
                }
            }
        }
        return false
    }

    for _, subject := range subjects {
        switch subject.Kind {
        case ServiceAccountKind:
            namespace := currentNamespace
            if len(subject.Namespace) > 0 {
                namespace = subject.Namespace
            }
            if len(namespace) == 0 {
                continue
            }
            if user == serviceaccount.MakeUsername(namespace, subject.Name) {
                return true
            }

        case UserKind, SystemUserKind:
            if user == subject.Name {
                return true
            }
        }
    }
    return false
}
開發者ID:Xmagicer,項目名稱:origin,代碼行數:37,代碼來源:helpers.go

示例7: ensureOpenShiftInfraNamespace

// ensureOpenShiftInfraNamespace is called as part of global policy initialization to ensure infra namespace exists
func (c *MasterConfig) ensureOpenShiftInfraNamespace() {
    ns := c.Options.PolicyConfig.OpenShiftInfrastructureNamespace

    // Ensure namespace exists
    _, err := c.KubeClient().Namespaces().Create(&kapi.Namespace{ObjectMeta: kapi.ObjectMeta{Name: ns}})
    if err != nil && !kapierror.IsAlreadyExists(err) {
        glog.Errorf("Error creating namespace %s: %v", ns, err)
    }

    // Ensure service accounts exist
    serviceAccounts := []string{c.BuildControllerServiceAccount, c.DeploymentControllerServiceAccount, c.ReplicationControllerServiceAccount}
    for _, serviceAccountName := range serviceAccounts {
        _, err := c.KubeClient().ServiceAccounts(ns).Create(&kapi.ServiceAccount{ObjectMeta: kapi.ObjectMeta{Name: serviceAccountName}})
        if err != nil && !kapierror.IsAlreadyExists(err) {
            glog.Errorf("Error creating service account %s/%s: %v", ns, serviceAccountName, err)
        }
    }

    // Ensure service account cluster role bindings exist
    clusterRolesToUsernames := map[string][]string{
        bootstrappolicy.BuildControllerRoleName:       {serviceaccount.MakeUsername(ns, c.BuildControllerServiceAccount)},
        bootstrappolicy.DeploymentControllerRoleName:  {serviceaccount.MakeUsername(ns, c.DeploymentControllerServiceAccount)},
        bootstrappolicy.ReplicationControllerRoleName: {serviceaccount.MakeUsername(ns, c.ReplicationControllerServiceAccount)},
    }
    roleAccessor := policy.NewClusterRoleBindingAccessor(c.ServiceAccountRoleBindingClient())
    for clusterRole, usernames := range clusterRolesToUsernames {
        addRole := &policy.RoleModificationOptions{
            RoleName:            clusterRole,
            RoleBindingAccessor: roleAccessor,
            Users:               usernames,
        }
        if err := addRole.AddRole(); err != nil {
            glog.Errorf("Could not add %v users to the %v cluster role: %v\n", ns, usernames, clusterRole, err)
        } else {
            glog.V(2).Infof("Added %v users to the %v cluster role: %v\n", usernames, clusterRole, err)
        }
    }
}
開發者ID:Tlacenka,項目名稱:origin,代碼行數:39,代碼來源:ensure.go

示例8: appliesToUser

func appliesToUser(user user.Info, subject rbac.Subject) (bool, error) {
    switch subject.Kind {
    case rbac.UserKind:
        return subject.Name == rbac.UserAll || user.GetName() == subject.Name, nil
    case rbac.GroupKind:
        return has(user.GetGroups(), subject.Name), nil
    case rbac.ServiceAccountKind:
        if subject.Namespace == "" {
            return false, fmt.Errorf("subject of kind service account without specified namespace")
        }
        return serviceaccount.MakeUsername(subject.Namespace, subject.Name) == user.GetName(), nil
    default:
        return false, fmt.Errorf("unknown subject kind: %s", subject.Kind)
    }
}
開發者ID:CodeJuan,項目名稱:kubernetes,代碼行數:15,代碼來源:rulevalidation.go

示例9: TestMakeSplitUsername

func TestMakeSplitUsername(t *testing.T) {
    username := serviceaccount.MakeUsername("ns", "name")
    ns, name, err := serviceaccount.SplitUsername(username)
    if err != nil {
        t.Errorf("Unexpected error %v", err)
    }
    if ns != "ns" || name != "name" {
        t.Errorf("Expected ns/name, got %s/%s", ns, name)
    }

    invalid := []string{"test", "system:serviceaccount", "system:serviceaccount:", "system:serviceaccount:ns", "system:serviceaccount:ns:name:extra"}
    for _, n := range invalid {
        _, _, err := serviceaccount.SplitUsername("test")
        if err == nil {
            t.Errorf("Expected error for %s", n)
        }
    }
}
開發者ID:ncdc,項目名稱:kubernetes,代碼行數:18,代碼來源:jwt_test.go

示例10: ensureDefaultSecurityContextConstraints

func (c *MasterConfig) ensureDefaultSecurityContextConstraints() {
    sccList, err := c.KubeClient().SecurityContextConstraints().List(labels.Everything(), fields.Everything())
    if err != nil {
        glog.Errorf("Unable to initialize security context constraints: %v.  This may prevent the creation of pods", err)
        return
    }
    if len(sccList.Items) > 0 {
        return
    }

    glog.Infof("No security context constraints detected, adding defaults")
    ns := c.Options.PolicyConfig.OpenShiftInfrastructureNamespace
    buildControllerUsername := serviceaccount.MakeUsername(ns, c.BuildControllerServiceAccount)
    for _, scc := range bootstrappolicy.GetBootstrapSecurityContextConstraints(buildControllerUsername) {
        _, err = c.KubeClient().SecurityContextConstraints().Create(&scc)
        if err != nil {
            glog.Errorf("Unable to create default security context constraint %s.  Got error: %v", scc.Name, err)
        }
    }
}
開發者ID:Tlacenka,項目名稱:origin,代碼行數:20,代碼來源:ensure.go

示例11: appliesToUser

func appliesToUser(user user.Info, subject rbac.Subject, namespace string) bool {
    switch subject.Kind {
    case rbac.UserKind:
        return subject.Name == rbac.UserAll || user.GetName() == subject.Name

    case rbac.GroupKind:
        return has(user.GetGroups(), subject.Name)

    case rbac.ServiceAccountKind:
        // default the namespace to namespace we're working in if its available.  This allows rolebindings that reference
        // SAs in th local namespace to avoid having to qualify them.
        saNamespace := namespace
        if len(subject.Namespace) > 0 {
            saNamespace = subject.Namespace
        }
        if len(saNamespace) == 0 {
            return false
        }
        return serviceaccount.MakeUsername(saNamespace, subject.Name) == user.GetName()
    default:
        return false
    }
}
開發者ID:Q-Lee,項目名稱:kubernetes,代碼行數:23,代碼來源:rulevalidation.go

示例12: TestSAAsOAuthClient

func TestSAAsOAuthClient(t *testing.T) {
    testutil.RequireEtcd(t)
    _, clusterAdminKubeConfig, err := testserver.StartTestMaster()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    authorizationCodes := make(chan string, 1)
    authorizationErrors := make(chan string, 1)
    oauthServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        t.Logf("fake pod server got %v", req.URL)

        if code := req.URL.Query().Get("code"); len(code) > 0 {
            authorizationCodes <- code
        }
        if err := req.URL.Query().Get("error"); len(err) > 0 {
            authorizationErrors <- err
        }
    }))
    defer oauthServer.Close()

    clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    clusterAdminKubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    projectName := "hammer-project"
    if _, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projectName, "harold"); err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if err := testserver.WaitForServiceAccounts(clusterAdminKubeClient, projectName, []string{"default"}); err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    // get the SA ready with redirect URIs and secret annotations
    var defaultSA *kapi.ServiceAccount

    // retry this a couple times.  We seem to be flaking on update conflicts and missing secrets all together
    err = kclient.RetryOnConflict(kclient.DefaultRetry, func() error {
        defaultSA, err = clusterAdminKubeClient.ServiceAccounts(projectName).Get("default")
        if err != nil {
            return err
        }
        if defaultSA.Annotations == nil {
            defaultSA.Annotations = map[string]string{}
        }
        defaultSA.Annotations[saoauth.OAuthRedirectURISecretAnnotationPrefix+"one"] = oauthServer.URL
        defaultSA.Annotations[saoauth.OAuthWantChallengesAnnotationPrefix] = "true"
        defaultSA, err = clusterAdminKubeClient.ServiceAccounts(projectName).Update(defaultSA)
        return err
    })
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    var oauthSecret *kapi.Secret
    // retry this a couple times.  We seem to be flaking on update conflicts and missing secrets all together
    err = wait.PollImmediate(30*time.Millisecond, 10*time.Second, func() (done bool, err error) {
        allSecrets, err := clusterAdminKubeClient.Secrets(projectName).List(kapi.ListOptions{})
        if err != nil {
            return false, err
        }
        for i := range allSecrets.Items {
            secret := allSecrets.Items[i]
            if serviceaccount.IsServiceAccountToken(&secret, defaultSA) {
                oauthSecret = &secret
                return true, nil
            }
        }

        return false, nil
    })
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    oauthClientConfig := &osincli.ClientConfig{
        ClientId:     serviceaccount.MakeUsername(defaultSA.Namespace, defaultSA.Name),
        ClientSecret: string(oauthSecret.Data[kapi.ServiceAccountTokenKey]),
        AuthorizeUrl: clusterAdminClientConfig.Host + "/oauth/authorize",
        TokenUrl:     clusterAdminClientConfig.Host + "/oauth/token",
        RedirectUrl:  oauthServer.URL,
        Scope:        scope.Join([]string{"user:info", "role:edit:" + projectName}),
        SendClientSecretInParams: true,
    }
    runOAuthFlow(t, clusterAdminClientConfig, projectName, oauthClientConfig, authorizationCodes, authorizationErrors, true, true)
    clusterAdminClient.OAuthClientAuthorizations().Delete("harold:" + oauthClientConfig.ClientId)

    oauthClientConfig = &osincli.ClientConfig{
        ClientId:     serviceaccount.MakeUsername(defaultSA.Namespace, defaultSA.Name),
        ClientSecret: string(oauthSecret.Data[kapi.ServiceAccountTokenKey]),
        AuthorizeUrl: clusterAdminClientConfig.Host + "/oauth/authorize",
//.........這裏部分代碼省略.........
開發者ID:bmeng,項目名稱:origin,代碼行數:101,代碼來源:sa_oauthclient_test.go

示例13: TestImpersonateIsForbidden


//.........這裏部分代碼省略.........
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all of bob's actions to return Forbidden
            if resp.StatusCode != http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected not status Forbidden, but got %s", resp.Status)
            }
        }()
    }

    // bob can impersonate alice to do other things
    for _, r := range getTestRequests() {
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", "alice")
        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all the requests to be allowed, don't care what they actually do
            if resp.StatusCode == http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected status not %v, but got %v", http.StatusForbidden, resp.StatusCode)
            }
        }()
    }

    // alice can't impersonate bob
    for _, r := range getTestRequests() {
        token := AliceToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", "bob")

        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all of bob's actions to return Forbidden
            if resp.StatusCode != http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected not status Forbidden, but got %s", resp.Status)
            }
        }()
    }

    // alice can impersonate a service account
    for _, r := range getTestRequests() {
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", serviceaccount.MakeUsername("default", "default"))
        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all the requests to be allowed, don't care what they actually do
            if resp.StatusCode == http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected status not %v, but got %v", http.StatusForbidden, resp.StatusCode)
            }
        }()
    }

}
開發者ID:Xmagicer,項目名稱:origin,代碼行數:101,代碼來源:auth_test.go

示例14: TestScopedTokens

func TestScopedTokens(t *testing.T) {
    testutil.RequireEtcd(t)
    defer testutil.DumpEtcdOnFailure(t)
    _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    projectName := "hammer-project"
    userName := "harold"
    haroldClient, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projectName, userName)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    if _, err := haroldClient.Builds(projectName).List(kapi.ListOptions{}); err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    haroldUser, err := haroldClient.Users().Get("~")
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    whoamiOnlyToken := &oauthapi.OAuthAccessToken{
        ObjectMeta: kapi.ObjectMeta{Name: "whoami-token-plus-some-padding-here-to-make-the-limit"},
        ClientName: origin.OpenShiftCLIClientID,
        ExpiresIn:  200,
        Scopes:     []string{scope.UserInfo},
        UserName:   userName,
        UserUID:    string(haroldUser.UID),
    }
    if _, err := clusterAdminClient.OAuthAccessTokens().Create(whoamiOnlyToken); err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    whoamiConfig := clientcmd.AnonymousClientConfig(clusterAdminClientConfig)
    whoamiConfig.BearerToken = whoamiOnlyToken.Name
    whoamiClient, err := client.New(&whoamiConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    if _, err := whoamiClient.Builds(projectName).List(kapi.ListOptions{}); !kapierrors.IsForbidden(err) {
        t.Fatalf("unexpected error: %v", err)
    }

    user, err := whoamiClient.Users().Get("~")
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if user.Name != userName {
        t.Fatalf("expected %v, got %v", userName, user.Name)
    }

    // try to impersonate a service account using this token
    whoamiConfig.Impersonate = serviceaccount.MakeUsername(projectName, "default")
    impersonatingClient, err := client.New(&whoamiConfig)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    impersonatedUser, err := impersonatingClient.Users().Get("~")
    if !kapierrors.IsForbidden(err) {
        t.Fatalf("missing error: %v got user %#v", err, impersonatedUser)
    }
}
開發者ID:xgwang-zte,項目名稱:origin,代碼行數:76,代碼來源:scopes_test.go

示例15: TestImpersonateIsForbidden

func TestImpersonateIsForbidden(t *testing.T) {
    // Set up a master
    masterConfig := framework.NewIntegrationTestMasterConfig()
    masterConfig.Authenticator = getTestTokenAuth()
    masterConfig.Authorizer = impersonateAuthorizer{}
    _, s := framework.RunAMaster(masterConfig)
    defer s.Close()

    ns := framework.CreateTestingNamespace("auth-impersonate-forbidden", s, t)
    defer framework.DeleteTestingNamespace(ns, s, t)

    transport := http.DefaultTransport

    // bob can't perform actions himself
    for _, r := range getTestRequests(ns.Name) {
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all of bob's actions to return Forbidden
            if resp.StatusCode != http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected not status Forbidden, but got %s", resp.Status)
            }
        }()
    }

    // bob can impersonate alice to do other things
    for _, r := range getTestRequests(ns.Name) {
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", "alice")
        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all the requests to be allowed, don't care what they actually do
            if resp.StatusCode == http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected status not %v, but got %v", http.StatusForbidden, resp.StatusCode)
            }
        }()
    }

    // alice can't impersonate bob
    for _, r := range getTestRequests(ns.Name) {
        token := AliceToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", "bob")

        func() {
            resp, err := transport.RoundTrip(req)
            defer resp.Body.Close()
            if err != nil {
                t.Logf("case %v", r)
                t.Fatalf("unexpected error: %v", err)
            }
            // Expect all of bob's actions to return Forbidden
            if resp.StatusCode != http.StatusForbidden {
                t.Logf("case %v", r)
                t.Errorf("Expected not status Forbidden, but got %s", resp.Status)
            }
        }()
    }

    // alice can impersonate a service account
    for _, r := range getTestRequests(ns.Name) {
        token := BobToken
        bodyBytes := bytes.NewReader([]byte(r.body))
        req, err := http.NewRequest(r.verb, s.URL+r.URL, bodyBytes)
        if err != nil {
            t.Fatalf("unexpected error: %v", err)
        }
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
        req.Header.Set("Impersonate-User", serviceaccount.MakeUsername("default", "default"))
        func() {
//.........這裏部分代碼省略.........
開發者ID:RyanBinfeng,項目名稱:kubernetes,代碼行數:101,代碼來源:auth_test.go


注:本文中的k8s/io/kubernetes/pkg/serviceaccount.MakeUsername函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。