helpers.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 rbac
  14. import (
  15. "fmt"
  16. "strings"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/util/sets"
  19. )
  20. func ResourceMatches(rule *PolicyRule, combinedRequestedResource, requestedSubresource string) bool {
  21. for _, ruleResource := range rule.Resources {
  22. // if everything is allowed, we match
  23. if ruleResource == ResourceAll {
  24. return true
  25. }
  26. // if we have an exact match, we match
  27. if ruleResource == combinedRequestedResource {
  28. return true
  29. }
  30. // We can also match a */subresource.
  31. // if there isn't a subresource, then continue
  32. if len(requestedSubresource) == 0 {
  33. continue
  34. }
  35. // if the rule isn't in the format */subresource, then we don't match, continue
  36. if len(ruleResource) == len(requestedSubresource)+2 &&
  37. strings.HasPrefix(ruleResource, "*/") &&
  38. strings.HasSuffix(ruleResource, requestedSubresource) {
  39. return true
  40. }
  41. }
  42. return false
  43. }
  44. // subjectsStrings returns users, groups, serviceaccounts, unknown for display purposes.
  45. func SubjectsStrings(subjects []Subject) ([]string, []string, []string, []string) {
  46. users := []string{}
  47. groups := []string{}
  48. sas := []string{}
  49. others := []string{}
  50. for _, subject := range subjects {
  51. switch subject.Kind {
  52. case ServiceAccountKind:
  53. sas = append(sas, fmt.Sprintf("%s/%s", subject.Namespace, subject.Name))
  54. case UserKind:
  55. users = append(users, subject.Name)
  56. case GroupKind:
  57. groups = append(groups, subject.Name)
  58. default:
  59. others = append(others, fmt.Sprintf("%s/%s/%s", subject.Kind, subject.Namespace, subject.Name))
  60. }
  61. }
  62. return users, groups, sas, others
  63. }
  64. func (r PolicyRule) String() string {
  65. return "PolicyRule" + r.CompactString()
  66. }
  67. // CompactString exposes a compact string representation for use in escalation error messages
  68. func (r PolicyRule) CompactString() string {
  69. formatStringParts := []string{}
  70. formatArgs := []interface{}{}
  71. if len(r.APIGroups) > 0 {
  72. formatStringParts = append(formatStringParts, "APIGroups:%q")
  73. formatArgs = append(formatArgs, r.APIGroups)
  74. }
  75. if len(r.Resources) > 0 {
  76. formatStringParts = append(formatStringParts, "Resources:%q")
  77. formatArgs = append(formatArgs, r.Resources)
  78. }
  79. if len(r.NonResourceURLs) > 0 {
  80. formatStringParts = append(formatStringParts, "NonResourceURLs:%q")
  81. formatArgs = append(formatArgs, r.NonResourceURLs)
  82. }
  83. if len(r.ResourceNames) > 0 {
  84. formatStringParts = append(formatStringParts, "ResourceNames:%q")
  85. formatArgs = append(formatArgs, r.ResourceNames)
  86. }
  87. if len(r.Verbs) > 0 {
  88. formatStringParts = append(formatStringParts, "Verbs:%q")
  89. formatArgs = append(formatArgs, r.Verbs)
  90. }
  91. formatString := "{" + strings.Join(formatStringParts, ", ") + "}"
  92. return fmt.Sprintf(formatString, formatArgs...)
  93. }
  94. // +k8s:deepcopy-gen=false
  95. // PolicyRuleBuilder let's us attach methods. A no-no for API types.
  96. // We use it to construct rules in code. It's more compact than trying to write them
  97. // out in a literal and allows us to perform some basic checking during construction
  98. type PolicyRuleBuilder struct {
  99. PolicyRule PolicyRule
  100. }
  101. func NewRule(verbs ...string) *PolicyRuleBuilder {
  102. return &PolicyRuleBuilder{
  103. PolicyRule: PolicyRule{Verbs: sets.NewString(verbs...).List()},
  104. }
  105. }
  106. func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder {
  107. r.PolicyRule.APIGroups = combine(r.PolicyRule.APIGroups, groups)
  108. return r
  109. }
  110. func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder {
  111. r.PolicyRule.Resources = combine(r.PolicyRule.Resources, resources)
  112. return r
  113. }
  114. func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder {
  115. r.PolicyRule.ResourceNames = combine(r.PolicyRule.ResourceNames, names)
  116. return r
  117. }
  118. func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder {
  119. r.PolicyRule.NonResourceURLs = combine(r.PolicyRule.NonResourceURLs, urls)
  120. return r
  121. }
  122. func (r *PolicyRuleBuilder) RuleOrDie() PolicyRule {
  123. ret, err := r.Rule()
  124. if err != nil {
  125. panic(err)
  126. }
  127. return ret
  128. }
  129. func combine(s1, s2 []string) []string {
  130. s := sets.NewString(s1...)
  131. s.Insert(s2...)
  132. return s.List()
  133. }
  134. func (r *PolicyRuleBuilder) Rule() (PolicyRule, error) {
  135. if len(r.PolicyRule.Verbs) == 0 {
  136. return PolicyRule{}, fmt.Errorf("verbs are required: %#v", r.PolicyRule)
  137. }
  138. switch {
  139. case len(r.PolicyRule.NonResourceURLs) > 0:
  140. if len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 {
  141. return PolicyRule{}, fmt.Errorf("non-resource rule may not have apiGroups, resources, or resourceNames: %#v", r.PolicyRule)
  142. }
  143. case len(r.PolicyRule.Resources) > 0:
  144. // resource rule may not have nonResourceURLs
  145. if len(r.PolicyRule.APIGroups) == 0 {
  146. // this a common bug
  147. return PolicyRule{}, fmt.Errorf("resource rule must have apiGroups: %#v", r.PolicyRule)
  148. }
  149. // if resource names are set, then the verb must not be list, watch, create, or deletecollection
  150. // since verbs are largely opaque, we don't want to accidentally prevent things like "impersonate", so
  151. // we will backlist common mistakes, not whitelist acceptable options.
  152. if len(r.PolicyRule.ResourceNames) != 0 {
  153. illegalVerbs := []string{}
  154. for _, verb := range r.PolicyRule.Verbs {
  155. switch verb {
  156. case "list", "watch", "create", "deletecollection":
  157. illegalVerbs = append(illegalVerbs, verb)
  158. }
  159. }
  160. if len(illegalVerbs) > 0 {
  161. return PolicyRule{}, fmt.Errorf("verbs %v do not have names available: %#v", illegalVerbs, r.PolicyRule)
  162. }
  163. }
  164. default:
  165. return PolicyRule{}, fmt.Errorf("a rule must have either nonResourceURLs or resources: %#v", r.PolicyRule)
  166. }
  167. return r.PolicyRule, nil
  168. }
  169. // +k8s:deepcopy-gen=false
  170. // ClusterRoleBindingBuilder let's us attach methods. A no-no for API types.
  171. // We use it to construct bindings in code. It's more compact than trying to write them
  172. // out in a literal.
  173. type ClusterRoleBindingBuilder struct {
  174. ClusterRoleBinding ClusterRoleBinding
  175. }
  176. func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder {
  177. return &ClusterRoleBindingBuilder{
  178. ClusterRoleBinding: ClusterRoleBinding{
  179. ObjectMeta: metav1.ObjectMeta{Name: clusterRoleName},
  180. RoleRef: RoleRef{
  181. APIGroup: GroupName,
  182. Kind: "ClusterRole",
  183. Name: clusterRoleName,
  184. },
  185. },
  186. }
  187. }
  188. func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder {
  189. for _, group := range groups {
  190. r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: GroupKind, APIGroup: GroupName, Name: group})
  191. }
  192. return r
  193. }
  194. func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder {
  195. for _, user := range users {
  196. r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: UserKind, APIGroup: GroupName, Name: user})
  197. }
  198. return r
  199. }
  200. func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder {
  201. for _, saName := range serviceAccountNames {
  202. r.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: ServiceAccountKind, Namespace: namespace, Name: saName})
  203. }
  204. return r
  205. }
  206. func (r *ClusterRoleBindingBuilder) BindingOrDie() ClusterRoleBinding {
  207. ret, err := r.Binding()
  208. if err != nil {
  209. panic(err)
  210. }
  211. return ret
  212. }
  213. func (r *ClusterRoleBindingBuilder) Binding() (ClusterRoleBinding, error) {
  214. if len(r.ClusterRoleBinding.Subjects) == 0 {
  215. return ClusterRoleBinding{}, fmt.Errorf("subjects are required: %#v", r.ClusterRoleBinding)
  216. }
  217. return r.ClusterRoleBinding, nil
  218. }
  219. // +k8s:deepcopy-gen=false
  220. // RoleBindingBuilder let's us attach methods. It is similar to
  221. // ClusterRoleBindingBuilder above.
  222. type RoleBindingBuilder struct {
  223. RoleBinding RoleBinding
  224. }
  225. // NewRoleBinding creates a RoleBinding builder that can be used
  226. // to define the subjects of a role binding. At least one of
  227. // the `Groups`, `Users` or `SAs` method must be called before
  228. // calling the `Binding*` methods.
  229. func NewRoleBinding(roleName, namespace string) *RoleBindingBuilder {
  230. return &RoleBindingBuilder{
  231. RoleBinding: RoleBinding{
  232. ObjectMeta: metav1.ObjectMeta{
  233. Name: roleName,
  234. Namespace: namespace,
  235. },
  236. RoleRef: RoleRef{
  237. APIGroup: GroupName,
  238. Kind: "Role",
  239. Name: roleName,
  240. },
  241. },
  242. }
  243. }
  244. func NewRoleBindingForClusterRole(roleName, namespace string) *RoleBindingBuilder {
  245. return &RoleBindingBuilder{
  246. RoleBinding: RoleBinding{
  247. ObjectMeta: metav1.ObjectMeta{
  248. Name: roleName,
  249. Namespace: namespace,
  250. },
  251. RoleRef: RoleRef{
  252. APIGroup: GroupName,
  253. Kind: "ClusterRole",
  254. Name: roleName,
  255. },
  256. },
  257. }
  258. }
  259. // Groups adds the specified groups as the subjects of the RoleBinding.
  260. func (r *RoleBindingBuilder) Groups(groups ...string) *RoleBindingBuilder {
  261. for _, group := range groups {
  262. r.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: GroupKind, APIGroup: GroupName, Name: group})
  263. }
  264. return r
  265. }
  266. // Users adds the specified users as the subjects of the RoleBinding.
  267. func (r *RoleBindingBuilder) Users(users ...string) *RoleBindingBuilder {
  268. for _, user := range users {
  269. r.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: UserKind, APIGroup: GroupName, Name: user})
  270. }
  271. return r
  272. }
  273. // SAs adds the specified service accounts as the subjects of the
  274. // RoleBinding.
  275. func (r *RoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *RoleBindingBuilder {
  276. for _, saName := range serviceAccountNames {
  277. r.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: ServiceAccountKind, Namespace: namespace, Name: saName})
  278. }
  279. return r
  280. }
  281. // BindingOrDie calls the binding method and panics if there is an error.
  282. func (r *RoleBindingBuilder) BindingOrDie() RoleBinding {
  283. ret, err := r.Binding()
  284. if err != nil {
  285. panic(err)
  286. }
  287. return ret
  288. }
  289. // Binding builds and returns the RoleBinding API object from the builder
  290. // object.
  291. func (r *RoleBindingBuilder) Binding() (RoleBinding, error) {
  292. if len(r.RoleBinding.Subjects) == 0 {
  293. return RoleBinding{}, fmt.Errorf("subjects are required: %#v", r.RoleBinding)
  294. }
  295. return r.RoleBinding, nil
  296. }
  297. type SortableRuleSlice []PolicyRule
  298. func (s SortableRuleSlice) Len() int { return len(s) }
  299. func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  300. func (s SortableRuleSlice) Less(i, j int) bool {
  301. return strings.Compare(s[i].String(), s[j].String()) < 0
  302. }