本文整理汇总了Golang中k8s/io/kubernetes/pkg/api/errors.NewForbidden函数的典型用法代码示例。如果您正苦于以下问题:Golang NewForbidden函数的具体用法?Golang NewForbidden怎么用?Golang NewForbidden使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewForbidden函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Admit
// Admit will deny any pod that defines SELinuxOptions or RunAsUser.
func (p *plugin) Admit(a admission.Attributes) (err error) {
if a.GetResource() != string(api.ResourcePods) {
return nil
}
pod, ok := a.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.SupplementalGroups != nil {
return apierrors.NewForbidden(a.GetResource(), pod.Name, fmt.Errorf("SecurityContext.SupplementalGroups is forbidden"))
}
if pod.Spec.SecurityContext != nil {
if pod.Spec.SecurityContext.SELinuxOptions != nil {
return apierrors.NewForbidden(a.GetResource(), pod.Name, fmt.Errorf("pod.Spec.SecurityContext.SELinuxOptions is forbidden"))
}
if pod.Spec.SecurityContext.RunAsUser != nil {
return apierrors.NewForbidden(a.GetResource(), pod.Name, fmt.Errorf("pod.Spec.SecurityContext.RunAsUser is forbidden"))
}
}
for _, v := range pod.Spec.Containers {
if v.SecurityContext != nil {
if v.SecurityContext.SELinuxOptions != nil {
return apierrors.NewForbidden(a.GetResource(), pod.Name, fmt.Errorf("SecurityContext.SELinuxOptions is forbidden"))
}
if v.SecurityContext.RunAsUser != nil {
return apierrors.NewForbidden(a.GetResource(), pod.Name, fmt.Errorf("SecurityContext.RunAsUser is forbidden"))
}
}
}
return nil
}
示例2: checkAndDecrement
// checkAndDecrement checks if the provided PodDisruptionBudget allows any disruption.
func (r *EvictionREST) checkAndDecrement(namespace string, podName string, pdb policy.PodDisruptionBudget) (ok bool, err error) {
if pdb.Status.ObservedGeneration < pdb.Generation {
return false, nil
}
if pdb.Status.PodDisruptionsAllowed < 0 {
return false, errors.NewForbidden(policy.Resource("poddisruptionbudget"), pdb.Name, fmt.Errorf("pdb disruptions allowed is negative"))
}
if len(pdb.Status.DisruptedPods) > MaxDisruptedPodSize {
return false, errors.NewForbidden(policy.Resource("poddisruptionbudget"), pdb.Name, fmt.Errorf("DisrputedPods map too big - too many evictions not confirmed by PDB controller"))
}
if pdb.Status.PodDisruptionsAllowed == 0 {
return false, nil
}
pdb.Status.PodDisruptionsAllowed--
if pdb.Status.DisruptedPods == nil {
pdb.Status.DisruptedPods = make(map[string]metav1.Time)
}
// Eviction handler needs to inform the PDB controller that it is about to delete a pod
// so it should not consider it as available in calculations when updating PodDisruptions allowed.
// If the pod is not deleted within a reasonable time limit PDB controller will assume that it won't
// be deleted at all and remove it from DisruptedPod map.
pdb.Status.DisruptedPods[podName] = metav1.Time{Time: time.Now()}
if _, err := r.podDisruptionBudgetClient.PodDisruptionBudgets(namespace).UpdateStatus(&pdb); err != nil {
return false, err
}
return true, nil
}
示例3: ConfirmNoEscalation
func ConfirmNoEscalation(ctx kapi.Context, resource unversioned.GroupResource, name string, ruleResolver, cachedRuleResolver AuthorizationRuleResolver, role authorizationinterfaces.Role) error {
var ruleResolutionErrors []error
user, ok := kapi.UserFrom(ctx)
if !ok {
return kapierrors.NewForbidden(resource, name, fmt.Errorf("no user provided in context"))
}
namespace, _ := kapi.NamespaceFrom(ctx)
// if a cached resolver is provided, attempt to verify coverage against the cache, then fall back to the normal
// path otherwise
if cachedRuleResolver != nil {
if ownerRules, err := cachedRuleResolver.RulesFor(user, namespace); err == nil {
if ownerRightsCover, _ := Covers(ownerRules, role.Rules()); ownerRightsCover {
return nil
}
}
}
ownerRules, err := ruleResolver.RulesFor(user, namespace)
if err != nil {
// do not fail in this case. Rules are purely additive, so we can continue with a coverage check based on the rules we have
glog.V(1).Infof("non-fatal error getting rules for %v: %v", user, err)
ruleResolutionErrors = append(ruleResolutionErrors, err)
}
ownerRightsCover, missingRights := Covers(ownerRules, role.Rules())
if ownerRightsCover {
return nil
}
// determine what resources the user is missing
if compactedMissingRights, err := CompactRules(missingRights); err == nil {
missingRights = compactedMissingRights
}
missingRightsStrings := make([]string, 0, len(missingRights))
for _, missingRight := range missingRights {
missingRightsStrings = append(missingRightsStrings, missingRight.CompactString())
}
sort.Strings(missingRightsStrings)
var internalErr error
if len(ruleResolutionErrors) > 0 {
internalErr = fmt.Errorf("user %q cannot grant extra privileges:\n%v\nrule resolution errors: %v)", user.GetName(), strings.Join(missingRightsStrings, "\n"), ruleResolutionErrors)
} else {
internalErr = fmt.Errorf("user %q cannot grant extra privileges:\n%v", user.GetName(), strings.Join(missingRightsStrings, "\n"))
}
return kapierrors.NewForbidden(resource, name, internalErr)
}
示例4: TestStatusAdmitsRouteOnForbidden
func TestStatusAdmitsRouteOnForbidden(t *testing.T) {
now := nowFn()
nowFn = func() unversioned.Time { return now }
touched := unversioned.Time{Time: now.Add(-time.Minute)}
p := &fakePlugin{}
c := testclient.NewSimpleFake(&(errors.NewForbidden(kapi.Resource("Route"), "route1", nil).ErrStatus))
admitter := NewStatusAdmitter(p, c, "test")
err := admitter.HandleRoute(watch.Added, &routeapi.Route{
ObjectMeta: kapi.ObjectMeta{Name: "route1", Namespace: "default", UID: types.UID("uid1")},
Spec: routeapi.RouteSpec{Host: "route1.test.local"},
Status: routeapi.RouteStatus{
Ingress: []routeapi.RouteIngress{
{
Host: "route2.test.local",
RouterName: "test",
Conditions: []routeapi.RouteIngressCondition{
{
Type: routeapi.RouteAdmitted,
Status: kapi.ConditionTrue,
LastTransitionTime: &touched,
},
},
},
},
},
})
checkResult(t, err, c, admitter, "route1.test.local", now, &touched.Time, 0, 0)
}
示例5: Admit
// Admit will deny any pod that defines AntiAffinity topology key other than unversioned.LabelHostname i.e. "kubernetes.io/hostname"
// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.
func (p *plugin) Admit(attributes admission.Attributes) (err error) {
if attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil
}
pod, ok := attributes.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations)
if err != nil {
// this is validated later
return nil
}
if affinity.PodAntiAffinity != nil {
var podAntiAffinityTerms []api.PodAffinityTerm
if len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {
podAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution
}
// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.
//if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {
// podAntiAffinityTerms = append(podAntiAffinityTerms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)
//}
for _, v := range podAntiAffinityTerms {
if v.TopologyKey != unversioned.LabelHostname {
return apierrors.NewForbidden(attributes.GetResource().GroupResource(), pod.Name, fmt.Errorf("affinity.PodAntiAffinity.RequiredDuringScheduling has TopologyKey %v but only key %v is allowed", v.TopologyKey, unversioned.LabelHostname))
}
}
}
return nil
}
示例6: TestStatusAdmitsRouteOnForbidden
func TestStatusAdmitsRouteOnForbidden(t *testing.T) {
now := nowFn()
nowFn = func() unversioned.Time { return now }
touched := unversioned.Time{Time: now.Add(-time.Minute)}
p := &fakePlugin{}
c := testclient.NewSimpleFake(&routeapi.Route{ObjectMeta: kapi.ObjectMeta{Name: "route1", Namespace: "default", UID: types.UID("uid1")}})
c.PrependReactor("update", "routes", func(action core.Action) (handled bool, ret runtime.Object, err error) {
if action.GetSubresource() != "status" {
return false, nil, nil
}
return true, nil, errors.NewForbidden(kapi.Resource("Route"), "route1", nil)
})
admitter := NewStatusAdmitter(p, c, "test")
err := admitter.HandleRoute(watch.Added, &routeapi.Route{
ObjectMeta: kapi.ObjectMeta{Name: "route1", Namespace: "default", UID: types.UID("uid1")},
Spec: routeapi.RouteSpec{Host: "route1.test.local"},
Status: routeapi.RouteStatus{
Ingress: []routeapi.RouteIngress{
{
Host: "route2.test.local",
RouterName: "test",
Conditions: []routeapi.RouteIngressCondition{
{
Type: routeapi.RouteAdmitted,
Status: kapi.ConditionTrue,
LastTransitionTime: &touched,
},
},
},
},
},
})
checkResult(t, err, c, admitter, "route1.test.local", now, &touched.Time, 0, 0)
}
示例7: Create
func (s *Storage) Create(ctx api.Context, obj runtime.Object) (runtime.Object, error) {
if u, ok := api.UserFrom(ctx); ok {
if s.superUser != "" && u.GetName() == s.superUser {
return s.StandardStorage.Create(ctx, obj)
}
// system:masters is special because the API server uses it for privileged loopback connections
// therefore we know that a member of system:masters can always do anything
for _, group := range u.GetGroups() {
if group == user.SystemPrivilegedGroup {
return s.StandardStorage.Create(ctx, obj)
}
}
}
clusterRoleBinding := obj.(*rbac.ClusterRoleBinding)
rules, err := s.ruleResolver.GetRoleReferenceRules(ctx, clusterRoleBinding.RoleRef, clusterRoleBinding.Namespace)
if err != nil {
return nil, err
}
if err := validation.ConfirmNoEscalation(ctx, s.ruleResolver, rules); err != nil {
return nil, errors.NewForbidden(groupResource, clusterRoleBinding.Name, err)
}
return s.StandardStorage.Create(ctx, obj)
}
示例8: Admit
func (l *lifecycle) Admit(a admission.Attributes) (err error) {
// prevent deletion of immortal namespaces
if a.GetOperation() == admission.Delete && a.GetKind().GroupKind() == api.Kind("Namespace") && l.immortalNamespaces.Has(a.GetName()) {
return errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this namespace may not be deleted"))
}
// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do
// if we're here, then the API server has found a route, which means that if we have a non-empty namespace
// its a namespaced resource.
if len(a.GetNamespace()) == 0 || a.GetKind().GroupKind() == api.Kind("Namespace") {
// if a namespace is deleted, we want to prevent all further creates into it
// while it is undergoing termination. to reduce incidences where the cache
// is slow to update, we forcefully remove the namespace from our local cache.
// this will cause a live lookup of the namespace to get its latest state even
// before the watch notification is received.
if a.GetOperation() == admission.Delete {
l.store.Delete(&api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetName(),
},
})
}
return nil
}
namespaceObj, exists, err := l.store.Get(&api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetNamespace(),
Namespace: "",
},
})
if err != nil {
return errors.NewInternalError(err)
}
// refuse to operate on non-existent namespaces
if !exists {
// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not
namespaceObj, err = l.client.Core().Namespaces().Get(a.GetNamespace())
if err != nil {
if errors.IsNotFound(err) {
return err
}
return errors.NewInternalError(err)
}
}
// ensure that we're not trying to create objects in terminating namespaces
if a.GetOperation() == admission.Create {
namespace := namespaceObj.(*api.Namespace)
if namespace.Status.Phase != api.NamespaceTerminating {
return nil
}
// TODO: This should probably not be a 403
return admission.NewForbidden(a, fmt.Errorf("Unable to create new content in namespace %s because it is being terminated.", a.GetNamespace()))
}
return nil
}
示例9: forbidden
// forbidden renders a simple forbidden error
func forbidden(reason string, attributes authorizer.AuthorizationAttributes, w http.ResponseWriter, req *http.Request) {
kind := ""
name := ""
// the attributes can be empty for two basic reasons:
// 1. malformed API request
// 2. not an API request at all
// In these cases, just assume default that will work better than nothing
if attributes != nil {
kind = attributes.GetResource()
if len(attributes.GetAPIGroup()) > 0 {
kind = attributes.GetAPIGroup() + "." + kind
}
name = attributes.GetResourceName()
}
// Reason is an opaque string that describes why access is allowed or forbidden (forbidden by the time we reach here).
// We don't have direct access to kind or name (not that those apply either in the general case)
// We create a NewForbidden to stay close the API, but then we override the message to get a serialization
// that makes sense when a human reads it.
forbiddenError, _ := kapierrors.NewForbidden(unversioned.GroupResource{Group: attributes.GetAPIGroup(), Resource: attributes.GetResource()}, name, errors.New("") /*discarded*/).(*kapierrors.StatusError)
forbiddenError.ErrStatus.Message = reason
formatted := &bytes.Buffer{}
output, err := runtime.Encode(kapi.Codecs.LegacyCodec(kapi.SchemeGroupVersion), &forbiddenError.ErrStatus)
if err != nil {
fmt.Fprintf(formatted, "%s", forbiddenError.Error())
} else {
json.Indent(formatted, output, "", " ")
}
w.Header().Set("Content-Type", restful.MIME_JSON)
w.WriteHeader(http.StatusForbidden)
w.Write(formatted.Bytes())
}
示例10: Admit
// Admit will deny any pod that defines AntiAffinity topology key other than metav1.LabelHostname i.e. "kubernetes.io/hostname"
// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.
func (p *plugin) Admit(attributes admission.Attributes) (err error) {
// Ignore all calls to subresources or resources other than pods.
if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil
}
pod, ok := attributes.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations)
if err != nil {
glog.V(5).Infof("Invalid Affinity detected, but we will leave handling of this to validation phase")
return nil
}
if affinity != nil && affinity.PodAntiAffinity != nil {
var podAntiAffinityTerms []api.PodAffinityTerm
if len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {
podAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution
}
// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.
//if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {
// podAntiAffinityTerms = append(podAntiAffinityTerms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)
//}
for _, v := range podAntiAffinityTerms {
if v.TopologyKey != metav1.LabelHostname {
return apierrors.NewForbidden(attributes.GetResource().GroupResource(), pod.Name, fmt.Errorf("affinity.PodAntiAffinity.RequiredDuringScheduling has TopologyKey %v but only key %v is allowed", v.TopologyKey, metav1.LabelHostname))
}
}
}
return nil
}
示例11: isAllowed
// isAllowed checks to see if the current user has rights to issue a LocalSubjectAccessReview on the namespace they're attempting to access
func (r *REST) isAllowed(ctx kapi.Context, rar *authorizationapi.ResourceAccessReview) error {
localRARAttributes := authorizer.DefaultAuthorizationAttributes{
Verb: "create",
Resource: "localresourceaccessreviews",
}
allowed, reason, err := r.authorizer.Authorize(kapi.WithNamespace(ctx, rar.Action.Namespace), localRARAttributes)
if err != nil {
return kapierrors.NewForbidden(authorizationapi.Resource(localRARAttributes.GetResource()), localRARAttributes.GetResourceName(), err)
}
if !allowed {
forbiddenError := kapierrors.NewForbidden(authorizationapi.Resource(localRARAttributes.GetResource()), localRARAttributes.GetResourceName(), errors.New("") /*discarded*/)
forbiddenError.ErrStatus.Message = reason
return forbiddenError
}
return nil
}
示例12: List
// List retrieves a list of Projects that match label.
func (s *REST) List(ctx kapi.Context, label labels.Selector, field fields.Selector) (runtime.Object, error) {
user, ok := kapi.UserFrom(ctx)
if !ok {
return nil, kerrors.NewForbidden("Project", "", fmt.Errorf("unable to list projects without a user on the context"))
}
namespaceList, err := s.lister.List(user)
if err != nil {
return nil, err
}
return convertNamespaceList(namespaceList), nil
}
示例13: Validate
// Validate validates a new image stream.
func (s Strategy) Validate(ctx kapi.Context, obj runtime.Object) fielderrors.ValidationErrorList {
stream := obj.(*api.ImageStream)
user, ok := kapi.UserFrom(ctx)
if !ok {
return fielderrors.ValidationErrorList{kerrors.NewForbidden("imageStream", stream.Name, fmt.Errorf("unable to update an ImageStream without a user on the context"))}
}
errs := s.tagVerifier.Verify(nil, stream, user)
errs = append(errs, s.tagsChanged(nil, stream)...)
errs = append(errs, validation.ValidateImageStream(stream)...)
return errs
}
示例14: NewForbidden
// NewForbidden is a utility function to return a well-formatted admission control error response
func NewForbidden(a Attributes, internalError error) error {
// do not double wrap an error of same type
if apierrors.IsForbidden(internalError) {
return internalError
}
name, kind, err := extractKindName(a)
if err != nil {
return apierrors.NewInternalError(utilerrors.NewAggregate([]error{internalError, err}))
}
return apierrors.NewForbidden(kind.Kind, name, internalError)
}
示例15: VerifyLimits
func (v *limitVerifier) VerifyLimits(namespace string, is *imageapi.ImageStream) error {
limits, err := v.limiter.LimitsForNamespace(namespace)
if err != nil || len(limits) == 0 {
return err
}
usage := GetImageStreamUsage(is)
if err := verifyImageStreamUsage(usage, limits); err != nil {
return kapierrors.NewForbidden(imageapi.Resource("ImageStream"), is.Name, err)
}
return nil
}