rest.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package subjectaccessreview
  14. import (
  15. "context"
  16. "fmt"
  17. kapierrors "k8s.io/apimachinery/pkg/api/errors"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/apiserver/pkg/authorization/authorizer"
  21. "k8s.io/apiserver/pkg/registry/rest"
  22. authorizationapi "k8s.io/kubernetes/pkg/apis/authorization"
  23. authorizationvalidation "k8s.io/kubernetes/pkg/apis/authorization/validation"
  24. authorizationutil "k8s.io/kubernetes/pkg/registry/authorization/util"
  25. )
  26. type REST struct {
  27. authorizer authorizer.Authorizer
  28. }
  29. func NewREST(authorizer authorizer.Authorizer) *REST {
  30. return &REST{authorizer}
  31. }
  32. func (r *REST) NamespaceScoped() bool {
  33. return false
  34. }
  35. func (r *REST) New() runtime.Object {
  36. return &authorizationapi.SubjectAccessReview{}
  37. }
  38. func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
  39. subjectAccessReview, ok := obj.(*authorizationapi.SubjectAccessReview)
  40. if !ok {
  41. return nil, kapierrors.NewBadRequest(fmt.Sprintf("not a SubjectAccessReview: %#v", obj))
  42. }
  43. if errs := authorizationvalidation.ValidateSubjectAccessReview(subjectAccessReview); len(errs) > 0 {
  44. return nil, kapierrors.NewInvalid(authorizationapi.Kind(subjectAccessReview.Kind), "", errs)
  45. }
  46. if createValidation != nil {
  47. if err := createValidation(obj.DeepCopyObject()); err != nil {
  48. return nil, err
  49. }
  50. }
  51. authorizationAttributes := authorizationutil.AuthorizationAttributesFrom(subjectAccessReview.Spec)
  52. decision, reason, evaluationErr := r.authorizer.Authorize(authorizationAttributes)
  53. subjectAccessReview.Status = authorizationapi.SubjectAccessReviewStatus{
  54. Allowed: (decision == authorizer.DecisionAllow),
  55. Denied: (decision == authorizer.DecisionDeny),
  56. Reason: reason,
  57. }
  58. if evaluationErr != nil {
  59. subjectAccessReview.Status.EvaluationError = evaluationErr.Error()
  60. }
  61. return subjectAccessReview, nil
  62. }