gc_admission.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 gc
  14. import (
  15. "fmt"
  16. "io"
  17. apiequality "k8s.io/apimachinery/pkg/api/equality"
  18. "k8s.io/apimachinery/pkg/api/meta"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/runtime"
  21. "k8s.io/apimachinery/pkg/runtime/schema"
  22. "k8s.io/apimachinery/pkg/types"
  23. "k8s.io/apiserver/pkg/admission"
  24. "k8s.io/apiserver/pkg/authorization/authorizer"
  25. )
  26. // PluginName indicates name of admission plugin.
  27. const PluginName = "OwnerReferencesPermissionEnforcement"
  28. // Register registers a plugin
  29. func Register(plugins *admission.Plugins) {
  30. plugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {
  31. // the pods/status endpoint is ignored by this plugin since old kubelets
  32. // corrupt them. the pod status strategy ensures status updates cannot mutate
  33. // ownerRef.
  34. whiteList := []whiteListItem{
  35. {
  36. groupResource: schema.GroupResource{Resource: "pods"},
  37. subresource: "status",
  38. },
  39. }
  40. return &gcPermissionsEnforcement{
  41. Handler: admission.NewHandler(admission.Create, admission.Update),
  42. whiteList: whiteList,
  43. }, nil
  44. })
  45. }
  46. // gcPermissionsEnforcement is an implementation of admission.Interface.
  47. type gcPermissionsEnforcement struct {
  48. *admission.Handler
  49. authorizer authorizer.Authorizer
  50. restMapper meta.RESTMapper
  51. // items in this whitelist are ignored upon admission.
  52. // any item in this list must protect against ownerRef mutations
  53. // via strategy enforcement.
  54. whiteList []whiteListItem
  55. }
  56. var _ admission.ValidationInterface = &gcPermissionsEnforcement{}
  57. // whiteListItem describes an entry in a whitelist ignored by gc permission enforcement.
  58. type whiteListItem struct {
  59. groupResource schema.GroupResource
  60. subresource string
  61. }
  62. // isWhiteListed returns true if the specified item is in the whitelist.
  63. func (a *gcPermissionsEnforcement) isWhiteListed(groupResource schema.GroupResource, subresource string) bool {
  64. for _, item := range a.whiteList {
  65. if item.groupResource == groupResource && item.subresource == subresource {
  66. return true
  67. }
  68. }
  69. return false
  70. }
  71. func (a *gcPermissionsEnforcement) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
  72. // // if the request is in the whitelist, we skip mutation checks for this resource.
  73. if a.isWhiteListed(attributes.GetResource().GroupResource(), attributes.GetSubresource()) {
  74. return nil
  75. }
  76. // if we aren't changing owner references, then the edit is always allowed
  77. if !isChangingOwnerReference(attributes.GetObject(), attributes.GetOldObject()) {
  78. return nil
  79. }
  80. // if you are creating a thing, you should always be allowed to set an owner ref since you logically had the power
  81. // to never create it. We still need to check block owner deletion below, because the power to delete does not
  82. // imply the power to prevent deletion on other resources.
  83. if attributes.GetOperation() != admission.Create {
  84. deleteAttributes := authorizer.AttributesRecord{
  85. User: attributes.GetUserInfo(),
  86. Verb: "delete",
  87. Namespace: attributes.GetNamespace(),
  88. APIGroup: attributes.GetResource().Group,
  89. APIVersion: attributes.GetResource().Version,
  90. Resource: attributes.GetResource().Resource,
  91. Subresource: attributes.GetSubresource(),
  92. Name: attributes.GetName(),
  93. ResourceRequest: true,
  94. Path: "",
  95. }
  96. decision, reason, err := a.authorizer.Authorize(deleteAttributes)
  97. if decision != authorizer.DecisionAllow {
  98. return admission.NewForbidden(attributes, fmt.Errorf("cannot set an ownerRef on a resource you can't delete: %v, %v", reason, err))
  99. }
  100. }
  101. // Further check if the user is setting ownerReference.blockOwnerDeletion to
  102. // true. If so, only allows the change if the user has delete permission of
  103. // the _OWNER_
  104. newBlockingRefs := newBlockingOwnerDeletionRefs(attributes.GetObject(), attributes.GetOldObject())
  105. for _, ref := range newBlockingRefs {
  106. records, err := a.ownerRefToDeleteAttributeRecords(ref, attributes)
  107. if err != nil {
  108. return admission.NewForbidden(attributes, fmt.Errorf("cannot set blockOwnerDeletion in this case because cannot find RESTMapping for APIVersion %s Kind %s: %v", ref.APIVersion, ref.Kind, err))
  109. }
  110. // Multiple records are returned if ref.Kind could map to multiple
  111. // resources. User needs to have delete permission on all the
  112. // matched Resources.
  113. for _, record := range records {
  114. decision, reason, err := a.authorizer.Authorize(record)
  115. if decision != authorizer.DecisionAllow {
  116. return admission.NewForbidden(attributes, fmt.Errorf("cannot set blockOwnerDeletion if an ownerReference refers to a resource you can't set finalizers on: %v, %v", reason, err))
  117. }
  118. }
  119. }
  120. return nil
  121. }
  122. func isChangingOwnerReference(newObj, oldObj runtime.Object) bool {
  123. newMeta, err := meta.Accessor(newObj)
  124. if err != nil {
  125. // if we don't have objectmeta, we don't have the object reference
  126. return false
  127. }
  128. if oldObj == nil {
  129. return len(newMeta.GetOwnerReferences()) > 0
  130. }
  131. oldMeta, err := meta.Accessor(oldObj)
  132. if err != nil {
  133. // if we don't have objectmeta, we don't have the object reference
  134. return false
  135. }
  136. // compare the old and new. If they aren't the same, then we're trying to change an ownerRef
  137. oldOwners := oldMeta.GetOwnerReferences()
  138. newOwners := newMeta.GetOwnerReferences()
  139. if len(oldOwners) != len(newOwners) {
  140. return true
  141. }
  142. for i := range oldOwners {
  143. if !apiequality.Semantic.DeepEqual(oldOwners[i], newOwners[i]) {
  144. return true
  145. }
  146. }
  147. return false
  148. }
  149. // Translates ref to a DeleteAttribute deleting the object referred by the ref.
  150. // OwnerReference only records the object kind, which might map to multiple
  151. // resources, so multiple DeleteAttribute might be returned.
  152. func (a *gcPermissionsEnforcement) ownerRefToDeleteAttributeRecords(ref metav1.OwnerReference, attributes admission.Attributes) ([]authorizer.AttributesRecord, error) {
  153. var ret []authorizer.AttributesRecord
  154. groupVersion, err := schema.ParseGroupVersion(ref.APIVersion)
  155. if err != nil {
  156. return ret, err
  157. }
  158. mappings, err := a.restMapper.RESTMappings(schema.GroupKind{Group: groupVersion.Group, Kind: ref.Kind}, groupVersion.Version)
  159. if err != nil {
  160. return ret, err
  161. }
  162. for _, mapping := range mappings {
  163. ar := authorizer.AttributesRecord{
  164. User: attributes.GetUserInfo(),
  165. Verb: "update",
  166. APIGroup: mapping.Resource.Group,
  167. APIVersion: mapping.Resource.Version,
  168. Resource: mapping.Resource.Resource,
  169. Subresource: "finalizers",
  170. Name: ref.Name,
  171. ResourceRequest: true,
  172. Path: "",
  173. }
  174. if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
  175. // if the owner is namespaced, it must be in the same namespace as the dependent is.
  176. ar.Namespace = attributes.GetNamespace()
  177. }
  178. ret = append(ret, ar)
  179. }
  180. return ret, nil
  181. }
  182. // only keeps the blocking refs
  183. func blockingOwnerRefs(refs []metav1.OwnerReference) []metav1.OwnerReference {
  184. var ret []metav1.OwnerReference
  185. for _, ref := range refs {
  186. if ref.BlockOwnerDeletion != nil && *ref.BlockOwnerDeletion == true {
  187. ret = append(ret, ref)
  188. }
  189. }
  190. return ret
  191. }
  192. func indexByUID(refs []metav1.OwnerReference) map[types.UID]metav1.OwnerReference {
  193. ret := make(map[types.UID]metav1.OwnerReference)
  194. for _, ref := range refs {
  195. ret[ref.UID] = ref
  196. }
  197. return ret
  198. }
  199. // Returns new blocking ownerReferences, and references whose blockOwnerDeletion
  200. // field is changed from nil or false to true.
  201. func newBlockingOwnerDeletionRefs(newObj, oldObj runtime.Object) []metav1.OwnerReference {
  202. newMeta, err := meta.Accessor(newObj)
  203. if err != nil {
  204. // if we don't have objectmeta, we don't have the object reference
  205. return nil
  206. }
  207. newRefs := newMeta.GetOwnerReferences()
  208. blockingNewRefs := blockingOwnerRefs(newRefs)
  209. if len(blockingNewRefs) == 0 {
  210. return nil
  211. }
  212. if oldObj == nil {
  213. return blockingNewRefs
  214. }
  215. oldMeta, err := meta.Accessor(oldObj)
  216. if err != nil {
  217. // if we don't have objectmeta, treat it as if all the ownerReference are newly created
  218. return blockingNewRefs
  219. }
  220. var ret []metav1.OwnerReference
  221. indexedOldRefs := indexByUID(oldMeta.GetOwnerReferences())
  222. for _, ref := range blockingNewRefs {
  223. oldRef, ok := indexedOldRefs[ref.UID]
  224. if !ok {
  225. // if ref is newly added, and it's blocking, then returns it.
  226. ret = append(ret, ref)
  227. continue
  228. }
  229. wasNotBlocking := oldRef.BlockOwnerDeletion == nil || *oldRef.BlockOwnerDeletion == false
  230. if wasNotBlocking {
  231. ret = append(ret, ref)
  232. }
  233. }
  234. return ret
  235. }
  236. func (a *gcPermissionsEnforcement) SetAuthorizer(authorizer authorizer.Authorizer) {
  237. a.authorizer = authorizer
  238. }
  239. func (a *gcPermissionsEnforcement) SetRESTMapper(restMapper meta.RESTMapper) {
  240. a.restMapper = restMapper
  241. }
  242. func (a *gcPermissionsEnforcement) ValidateInitialization() error {
  243. if a.authorizer == nil {
  244. return fmt.Errorf("missing authorizer")
  245. }
  246. if a.restMapper == nil {
  247. return fmt.Errorf("missing restMapper")
  248. }
  249. return nil
  250. }