本文整理汇总了Golang中k8s/io/kubernetes/pkg/api/errors.IsForbidden函数的典型用法代码示例。如果您正苦于以下问题:Golang IsForbidden函数的具体用法?Golang IsForbidden怎么用?Golang IsForbidden使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsForbidden函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServerGroups
// ServerGroups returns the supported groups, with information like supported versions and the
// preferred version.
func (d *DiscoveryClient) ServerGroups() (apiGroupList *unversioned.APIGroupList, err error) {
// Get the groupVersions exposed at /api
v := &unversioned.APIVersions{}
err = d.restClient.Get().AbsPath(d.LegacyPrefix).Do().Into(v)
apiGroup := unversioned.APIGroup{}
if err == nil {
apiGroup = apiVersionsToAPIGroup(v)
}
if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
return nil, err
}
// Get the groupVersions exposed at /apis
apiGroupList = &unversioned.APIGroupList{}
err = d.restClient.Get().AbsPath("/apis").Do().Into(apiGroupList)
if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
return nil, err
}
// to be compatible with a v1.0 server, if it's a 403 or 404, ignore and return whatever we got from /api
if err != nil && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
apiGroupList = &unversioned.APIGroupList{}
}
// append the group retrieved from /api to the list
apiGroupList.Groups = append(apiGroupList.Groups, apiGroup)
return apiGroupList, nil
}
示例2: doServiceAccountAPIRequests
func doServiceAccountAPIRequests(t *testing.T, c *clientset.Clientset, ns string, authenticated bool, canRead bool, canWrite bool) {
testSecret := &api.Secret{
ObjectMeta: api.ObjectMeta{Name: "testSecret"},
Data: map[string][]byte{"test": []byte("data")},
}
readOps := []testOperation{
func() error {
_, err := c.Core().Secrets(ns).List(api.ListOptions{})
return err
},
func() error {
_, err := c.Core().Pods(ns).List(api.ListOptions{})
return err
},
}
writeOps := []testOperation{
func() error { _, err := c.Core().Secrets(ns).Create(testSecret); return err },
func() error { return c.Core().Secrets(ns).Delete(testSecret.Name, nil) },
}
for _, op := range readOps {
err := op()
unauthorizedError := errors.IsUnauthorized(err)
forbiddenError := errors.IsForbidden(err)
switch {
case !authenticated && !unauthorizedError:
t.Fatalf("expected unauthorized error, got %v", err)
case authenticated && unauthorizedError:
t.Fatalf("unexpected unauthorized error: %v", err)
case authenticated && canRead && forbiddenError:
t.Fatalf("unexpected forbidden error: %v", err)
case authenticated && !canRead && !forbiddenError:
t.Fatalf("expected forbidden error, got: %v", err)
}
}
for _, op := range writeOps {
err := op()
unauthorizedError := errors.IsUnauthorized(err)
forbiddenError := errors.IsForbidden(err)
switch {
case !authenticated && !unauthorizedError:
t.Fatalf("expected unauthorized error, got %v", err)
case authenticated && unauthorizedError:
t.Fatalf("unexpected unauthorized error: %v", err)
case authenticated && canWrite && forbiddenError:
t.Fatalf("unexpected forbidden error: %v", err)
case authenticated && !canWrite && !forbiddenError:
t.Fatalf("expected forbidden error, got: %v", err)
}
}
}
示例3: TestAuthorizationRestrictedAccessForProjectAdmins
func TestAuthorizationRestrictedAccessForProjectAdmins(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)
}
haroldClient, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, "hammer-project", "harold")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
markClient, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, "mallet-project", "mark")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = haroldClient.DeploymentConfigs("hammer-project").List(kapi.ListOptions{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = markClient.DeploymentConfigs("hammer-project").List(kapi.ListOptions{})
if (err == nil) || !kapierror.IsForbidden(err) {
t.Fatalf("unexpected error: %v", err)
}
// projects are a special case where a get of a project actually sets a namespace. Make sure that
// the namespace is properly special cased and set for authorization rules
_, err = haroldClient.Projects().Get("hammer-project")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = markClient.Projects().Get("hammer-project")
if (err == nil) || !kapierror.IsForbidden(err) {
t.Fatalf("unexpected error: %v", err)
}
// wait for the project authorization cache to catch the change. It is on a one second period
waitForProject(t, haroldClient, "hammer-project", 1*time.Second, 10)
waitForProject(t, markClient, "mallet-project", 1*time.Second, 10)
}
示例4: Authorize
func (c *CacheAuthorizer) Authorize(ctx kapi.Context, a authorizer.Action) (allowed bool, reason string, err error) {
key, err := cacheKey(ctx, a)
if err != nil {
glog.V(5).Infof("could not build cache key for %#v: %v", a, err)
return c.authorizer.Authorize(ctx, a)
}
if value, hit := c.authorizeCache.Get(key); hit {
switch record := value.(type) {
case *authorizeCacheRecord:
if record.created.Add(c.ttl).After(c.now()) {
return record.allowed, record.reason, record.err
} else {
glog.V(5).Infof("cache record expired for %s", key)
c.authorizeCache.Remove(key)
}
default:
utilruntime.HandleError(fmt.Errorf("invalid cache record type for key %s: %#v", key, record))
}
}
allowed, reason, err = c.authorizer.Authorize(ctx, a)
// Don't cache results if there was an error unrelated to authorization
// TODO: figure out a better way to determine this
if err == nil || kerrs.IsForbidden(err) {
c.authorizeCache.Add(key, &authorizeCacheRecord{created: c.now(), allowed: allowed, reason: reason, err: err})
}
return allowed, reason, err
}
示例5: MakeGraph
func (d *ProjectStatusDescriber) MakeGraph(namespace string) (osgraph.Graph, sets.String, error) {
g := osgraph.New()
loaders := []GraphLoader{
&serviceLoader{namespace: namespace, lister: d.K},
&serviceAccountLoader{namespace: namespace, lister: d.K},
&secretLoader{namespace: namespace, lister: d.K},
&rcLoader{namespace: namespace, lister: d.K},
&podLoader{namespace: namespace, lister: d.K},
// TODO check swagger for feature enablement and selectively add bcLoader and buildLoader
// then remove errors.TolerateNotFoundError method.
&bcLoader{namespace: namespace, lister: d.C},
&buildLoader{namespace: namespace, lister: d.C},
&isLoader{namespace: namespace, lister: d.C},
&dcLoader{namespace: namespace, lister: d.C},
&routeLoader{namespace: namespace, lister: d.C},
}
loadingFuncs := []func() error{}
for _, loader := range loaders {
loadingFuncs = append(loadingFuncs, loader.Load)
}
forbiddenResources := sets.String{}
if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
actualErrors := []error{}
for _, err := range errs {
if kapierrors.IsForbidden(err) {
forbiddenErr := err.(*kapierrors.StatusError)
if (forbiddenErr.Status().Details != nil) && (len(forbiddenErr.Status().Details.Kind) > 0) {
forbiddenResources.Insert(forbiddenErr.Status().Details.Kind)
}
continue
}
actualErrors = append(actualErrors, err)
}
if len(actualErrors) > 0 {
return g, forbiddenResources, utilerrors.NewAggregate(actualErrors)
}
}
for _, loader := range loaders {
loader.AddToGraph(g)
}
kubeedges.AddAllExposedPodTemplateSpecEdges(g)
kubeedges.AddAllExposedPodEdges(g)
kubeedges.AddAllManagedByRCPodEdges(g)
kubeedges.AddAllRequestedServiceAccountEdges(g)
kubeedges.AddAllMountableSecretEdges(g)
kubeedges.AddAllMountedSecretEdges(g)
buildedges.AddAllInputOutputEdges(g)
buildedges.AddAllBuildEdges(g)
deployedges.AddAllTriggerEdges(g)
deployedges.AddAllDeploymentEdges(g)
imageedges.AddAllImageStreamRefEdges(g)
routeedges.AddAllRouteEdges(g)
return g, forbiddenResources, nil
}
示例6: SetupProject
// SetupProject creates a new project and assign a random user to the project.
// All resources will be then created within this project and Kubernetes E2E
// suite will destroy the project after test case finish.
func (c *CLI) SetupProject(name string, kubeClient *kclient.Client, _ map[string]string) (*kapi.Namespace, error) {
newNamespace := kapi.SimpleNameGenerator.GenerateName(fmt.Sprintf("extended-test-%s-", name))
c.SetNamespace(newNamespace).ChangeUser(fmt.Sprintf("%s-user", c.Namespace()))
e2e.Logf("The user is now %q", c.Username())
e2e.Logf("Creating project %q", c.Namespace())
_, err := c.REST().ProjectRequests().Create(&projectapi.ProjectRequest{
ObjectMeta: kapi.ObjectMeta{Name: c.Namespace()},
})
if err != nil {
e2e.Logf("Failed to create a project and namespace %q: %v", c.Namespace(), err)
return nil, err
}
if err := wait.ExponentialBackoff(kclient.DefaultBackoff, func() (bool, error) {
if _, err := c.KubeREST().Pods(c.Namespace()).List(kapi.ListOptions{}); err != nil {
if apierrs.IsForbidden(err) {
e2e.Logf("Waiting for user to have access to the namespace")
return false, nil
}
}
return true, nil
}); err != nil {
return nil, err
}
return &kapi.Namespace{ObjectMeta: kapi.ObjectMeta{Name: c.Namespace()}}, err
}
示例7: verifyImageStreamAccess
func verifyImageStreamAccess(ctx context.Context, namespace, imageRepo, verb string, client client.LocalSubjectAccessReviewsNamespacer) error {
sar := authorizationapi.LocalSubjectAccessReview{
Action: authorizationapi.Action{
Verb: verb,
Group: imageapi.GroupName,
Resource: "imagestreams/layers",
ResourceName: imageRepo,
},
}
response, err := client.LocalSubjectAccessReviews(namespace).Create(&sar)
if err != nil {
context.GetLogger(ctx).Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
context.GetLogger(ctx).Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
示例8: Create
func (c *subjectAccessReviews) Create(sar *authorizationapi.SubjectAccessReview) (result *authorizationapi.SubjectAccessReviewResponse, err error) {
result = &authorizationapi.SubjectAccessReviewResponse{}
// if this a cluster SAR, then no special handling
if len(sar.Action.Namespace) == 0 {
err = overrideAuth(c.token, c.r.Post().Resource("subjectAccessReviews")).Body(sar).Do().Into(result)
return
}
err = c.r.Post().Resource("subjectAccessReviews").Body(sar).Do().Into(result)
// if the namespace values don't match then we definitely hit an old server. If we got a forbidden, then we might have hit an old server
// and should try the old endpoint
if (sar.Action.Namespace != result.Namespace) || kapierrors.IsForbidden(err) {
deprecatedResponse := &authorizationapi.SubjectAccessReviewResponse{}
deprecatedAttemptErr := overrideAuth(c.token, c.r.Post().Namespace(sar.Action.Namespace).Resource("subjectAccessReviews")).Body(sar).Do().Into(deprecatedResponse)
// if we definitely hit an old server, then return the error and result you get from the older server.
if sar.Action.Namespace != result.Namespace {
return deprecatedResponse, deprecatedAttemptErr
}
// if we're not certain it was an old server, success overwrites the previous error, but failure doesn't overwrite the previous error
if deprecatedAttemptErr == nil {
err = nil
result = deprecatedResponse
}
}
return
}
示例9: verifyImageStreamAccess
func verifyImageStreamAccess(namespace, imageRepo, verb string, client *client.Client) error {
sar := authorizationapi.LocalSubjectAccessReview{
Action: authorizationapi.AuthorizationAttributes{
Verb: verb,
Resource: "imagestreams/layers",
ResourceName: imageRepo,
},
}
response, err := client.LocalSubjectAccessReviews(namespace).Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
示例10: ensureComponentAuthorizationRules
// ensureComponentAuthorizationRules initializes the cluster policies
func (c *MasterConfig) ensureComponentAuthorizationRules() {
clusterPolicyRegistry := clusterpolicyregistry.NewRegistry(clusterpolicystorage.NewStorage(c.EtcdHelper))
ctx := kapi.WithNamespace(kapi.NewContext(), "")
if _, err := clusterPolicyRegistry.GetClusterPolicy(ctx, authorizationapi.PolicyName); kapierror.IsNotFound(err) {
glog.Infof("No cluster policy found. Creating bootstrap policy based on: %v", c.Options.PolicyConfig.BootstrapPolicyFile)
if err := admin.OverwriteBootstrapPolicy(c.EtcdHelper, c.Options.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil {
glog.Errorf("Error creating bootstrap policy: %v", err)
}
} else {
glog.V(2).Infof("Ignoring bootstrap policy file because cluster policy found")
}
// Wait until the policy cache has caught up before continuing
review := &authorizationapi.SubjectAccessReview{Action: authorizationapi.AuthorizationAttributes{Verb: "get", Resource: "clusterpolicies"}}
err := wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (done bool, err error) {
result, err := c.PolicyClient().SubjectAccessReviews().Create(review)
if err == nil && result.Allowed {
return true, nil
}
if kapierror.IsForbidden(err) || (err == nil && !result.Allowed) {
glog.V(2).Infof("waiting for policy cache to initialize")
return false, nil
}
return false, err
})
if err != nil {
glog.Errorf("error waiting for policy cache to initialize: %v", err)
}
}
示例11: whoAmI
func whoAmI(clientConfig *restclient.Config) (*api.User, error) {
client, err := client.New(clientConfig)
me, err := client.Users().Get("~")
// if we're talking to kube (or likely talking to kube),
if kerrors.IsNotFound(err) || kerrors.IsForbidden(err) {
switch {
case len(clientConfig.BearerToken) > 0:
// the user has already been willing to provide the token on the CLI, so they probably
// don't mind using it again if they switch to and from this user
return &api.User{ObjectMeta: kapi.ObjectMeta{Name: clientConfig.BearerToken}}, nil
case len(clientConfig.Username) > 0:
return &api.User{ObjectMeta: kapi.ObjectMeta{Name: clientConfig.Username}}, nil
}
}
if err != nil {
return nil, err
}
return me, nil
}
示例12: Create
func (c *localSubjectAccessReviews) Create(sar *authorizationapi.LocalSubjectAccessReview) (*authorizationapi.SubjectAccessReviewResponse, error) {
result := &authorizationapi.SubjectAccessReviewResponse{}
req, err := overrideAuth(c.token, c.r.Post().Namespace(c.ns).Resource("localSubjectAccessReviews"))
if err != nil {
return &authorizationapi.SubjectAccessReviewResponse{}, err
}
err = req.Body(sar).Do().Into(result)
// if we get one of these failures, we may be talking to an older openshift. In that case, we need to try hitting ns/namespace-name/subjectaccessreview
if kapierrors.IsForbidden(err) || kapierrors.IsNotFound(err) {
deprecatedSAR := &authorizationapi.SubjectAccessReview{
Action: sar.Action,
User: sar.User,
Groups: sar.Groups,
}
deprecatedResponse := &authorizationapi.SubjectAccessReviewResponse{}
req, err := overrideAuth(c.token, c.r.Post().Namespace(c.ns).Resource("subjectAccessReviews"))
if err != nil {
return &authorizationapi.SubjectAccessReviewResponse{}, err
}
deprecatedAttemptErr := req.Body(deprecatedSAR).Do().Into(deprecatedResponse)
if deprecatedAttemptErr == nil {
err = nil
result = deprecatedResponse
}
}
return result, err
}
示例13: ServerResourcesForGroupVersion
// ServerResourcesForGroupVersion returns the supported resources for a group and version.
func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *unversioned.APIResourceList, err error) {
// we don't expose this version
if groupVersion == "v1beta3" {
return &unversioned.APIResourceList{}, nil
}
parentList, err := d.DiscoveryClient.ServerResourcesForGroupVersion(groupVersion)
if err != nil {
return parentList, err
}
if groupVersion != "v1" {
return parentList, nil
}
// we request v1, we must combine the parent list with the list from /oapi
url := url.URL{}
url.Path = "/oapi/" + groupVersion
originResources := &unversioned.APIResourceList{}
err = d.Get().AbsPath(url.String()).Do().Into(originResources)
if err != nil {
// ignore 403 or 404 error to be compatible with an v1.0 server.
if groupVersion == "v1" && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
return parentList, nil
}
return nil, err
}
parentList.APIResources = append(parentList.APIResources, originResources.APIResources...)
return parentList, nil
}
示例14: RunRolloutLatest
func (o RolloutLatestOptions) RunRolloutLatest() error {
info := o.infos[0]
config, ok := info.Object.(*deployapi.DeploymentConfig)
if !ok {
return fmt.Errorf("%s is not a deployment config", info.Name)
}
// TODO: Consider allowing one-off deployments for paused configs
// See https://github.com/openshift/origin/issues/9903
if config.Spec.Paused {
return fmt.Errorf("cannot deploy a paused deployment config")
}
deploymentName := deployutil.LatestDeploymentNameForConfig(config)
deployment, err := o.kc.ReplicationControllers(config.Namespace).Get(deploymentName)
switch {
case err == nil:
// Reject attempts to start a concurrent deployment.
if !deployutil.IsTerminatedDeployment(deployment) {
status := deployutil.DeploymentStatusFor(deployment)
return fmt.Errorf("#%d is already in progress (%s).", config.Status.LatestVersion, status)
}
case !kerrors.IsNotFound(err):
return err
}
dc := config
if !o.DryRun {
request := &deployapi.DeploymentRequest{
Name: config.Name,
Latest: !o.again,
Force: true,
}
dc, err = o.oc.DeploymentConfigs(config.Namespace).Instantiate(request)
// Pre 1.4 servers don't support the instantiate endpoint. Fallback to incrementing
// latestVersion on them.
if kerrors.IsNotFound(err) || kerrors.IsForbidden(err) {
config.Status.LatestVersion++
dc, err = o.oc.DeploymentConfigs(config.Namespace).Update(config)
}
if err != nil {
return err
}
info.Refresh(dc, true)
}
if o.output == "revision" {
fmt.Fprintf(o.out, fmt.Sprintf("%d", dc.Status.LatestVersion))
return nil
}
kcmdutil.PrintSuccess(o.mapper, o.output == "name", o.out, info.Mapping.Resource, info.Name, o.DryRun, "rolled out")
return nil
}
示例15: ensureComponentAuthorizationRules
// ensureComponentAuthorizationRules initializes the cluster policies
func (c *MasterConfig) ensureComponentAuthorizationRules() {
clusterPolicyRegistry := clusterpolicyregistry.NewRegistry(clusterpolicystorage.NewStorage(c.EtcdHelper))
ctx := kapi.WithNamespace(kapi.NewContext(), "")
if _, err := clusterPolicyRegistry.GetClusterPolicy(ctx, authorizationapi.PolicyName); kapierror.IsNotFound(err) {
glog.Infof("No cluster policy found. Creating bootstrap policy based on: %v", c.Options.PolicyConfig.BootstrapPolicyFile)
if err := admin.OverwriteBootstrapPolicy(c.EtcdHelper, c.Options.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil {
glog.Errorf("Error creating bootstrap policy: %v", err)
}
} else {
glog.V(2).Infof("Ignoring bootstrap policy file because cluster policy found")
}
// Wait until the policy cache has caught up before continuing
review := &authorizationapi.SubjectAccessReview{Action: authorizationapi.AuthorizationAttributes{Verb: "get", Group: authorizationapi.GroupName, Resource: "clusterpolicies"}}
err := wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (done bool, err error) {
result, err := c.PolicyClient().SubjectAccessReviews().Create(review)
if err == nil && result.Allowed {
return true, nil
}
if kapierror.IsForbidden(err) || (err == nil && !result.Allowed) {
glog.V(2).Infof("waiting for policy cache to initialize")
return false, nil
}
return false, err
})
if err != nil {
glog.Errorf("error waiting for policy cache to initialize: %v", err)
}
// Reconcile roles that must exist for the cluster to function
// Be very judicious about what is placed in this list, since it will be enforced on every server start
reconcileRoles := &policy.ReconcileClusterRolesOptions{
RolesToReconcile: []string{bootstrappolicy.DiscoveryRoleName},
Confirmed: true,
Union: true,
Out: ioutil.Discard,
RoleClient: c.PrivilegedLoopbackOpenShiftClient.ClusterRoles(),
}
if err := reconcileRoles.RunReconcileClusterRoles(nil, nil); err != nil {
glog.Errorf("Could not auto reconcile roles: %v\n", err)
}
// Reconcile rolebindings that must exist for the cluster to function
// Be very judicious about what is placed in this list, since it will be enforced on every server start
reconcileRoleBindings := &policy.ReconcileClusterRoleBindingsOptions{
RolesToReconcile: []string{bootstrappolicy.DiscoveryRoleName},
Confirmed: true,
Union: true,
Out: ioutil.Discard,
RoleBindingClient: c.PrivilegedLoopbackOpenShiftClient.ClusterRoleBindings(),
}
if err := reconcileRoleBindings.RunReconcileClusterRoleBindings(nil, nil); err != nil {
glog.Errorf("Could not auto reconcile role bindings: %v\n", err)
}
}