mustrunas.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 user
  14. import (
  15. "fmt"
  16. policy "k8s.io/api/policy/v1beta1"
  17. "k8s.io/apimachinery/pkg/util/validation/field"
  18. api "k8s.io/kubernetes/pkg/apis/core"
  19. psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util"
  20. )
  21. // mustRunAs implements the RunAsUserStrategy interface
  22. type mustRunAs struct {
  23. opts *policy.RunAsUserStrategyOptions
  24. }
  25. // NewMustRunAs provides a strategy that requires the container to run as a specific UID in a range.
  26. func NewMustRunAs(options *policy.RunAsUserStrategyOptions) (RunAsUserStrategy, error) {
  27. if options == nil {
  28. return nil, fmt.Errorf("MustRunAs requires run as user options")
  29. }
  30. if len(options.Ranges) == 0 {
  31. return nil, fmt.Errorf("MustRunAs requires at least one range")
  32. }
  33. return &mustRunAs{
  34. opts: options,
  35. }, nil
  36. }
  37. // Generate creates the uid based on policy rules. MustRunAs returns the first range's Min.
  38. func (s *mustRunAs) Generate(pod *api.Pod, container *api.Container) (*int64, error) {
  39. return &s.opts.Ranges[0].Min, nil
  40. }
  41. // Validate ensures that the specified values fall within the range of the strategy.
  42. func (s *mustRunAs) Validate(scPath *field.Path, _ *api.Pod, _ *api.Container, runAsNonRoot *bool, runAsUser *int64) field.ErrorList {
  43. allErrs := field.ErrorList{}
  44. if runAsUser == nil {
  45. allErrs = append(allErrs, field.Required(scPath.Child("runAsUser"), ""))
  46. return allErrs
  47. }
  48. if !s.isValidUID(*runAsUser) {
  49. detail := fmt.Sprintf("must be in the ranges: %v", s.opts.Ranges)
  50. allErrs = append(allErrs, field.Invalid(scPath.Child("runAsUser"), *runAsUser, detail))
  51. }
  52. return allErrs
  53. }
  54. func (s *mustRunAs) isValidUID(id int64) bool {
  55. for _, rng := range s.opts.Ranges {
  56. if psputil.UserFallsInRange(id, rng) {
  57. return true
  58. }
  59. }
  60. return false
  61. }