reconcile.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. Copyright 2017 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 auth
  14. import (
  15. "errors"
  16. "fmt"
  17. "github.com/spf13/cobra"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. "k8s.io/klog"
  20. rbacv1 "k8s.io/api/rbac/v1"
  21. rbacv1alpha1 "k8s.io/api/rbac/v1alpha1"
  22. rbacv1beta1 "k8s.io/api/rbac/v1beta1"
  23. "k8s.io/cli-runtime/pkg/genericclioptions"
  24. "k8s.io/cli-runtime/pkg/printers"
  25. "k8s.io/cli-runtime/pkg/resource"
  26. corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
  27. rbacv1client "k8s.io/client-go/kubernetes/typed/rbac/v1"
  28. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  29. "k8s.io/kubernetes/pkg/kubectl/scheme"
  30. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  31. "k8s.io/kubernetes/pkg/registry/rbac/reconciliation"
  32. )
  33. // ReconcileOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  34. // referencing the cmd.Flags()
  35. type ReconcileOptions struct {
  36. PrintFlags *genericclioptions.PrintFlags
  37. FilenameOptions *resource.FilenameOptions
  38. DryRun bool
  39. RemoveExtraPermissions bool
  40. RemoveExtraSubjects bool
  41. Visitor resource.Visitor
  42. RBACClient rbacv1client.RbacV1Interface
  43. NamespaceClient corev1client.CoreV1Interface
  44. PrintObject printers.ResourcePrinterFunc
  45. genericclioptions.IOStreams
  46. }
  47. var (
  48. reconcileLong = templates.LongDesc(`
  49. Reconciles rules for RBAC Role, RoleBinding, ClusterRole, and ClusterRole binding objects.
  50. Missing objects are created, and the containing namespace is created for namespaced objects, if required.
  51. Existing roles are updated to include the permissions in the input objects,
  52. and remove extra permissions if --remove-extra-permissions is specified.
  53. Existing bindings are updated to include the subjects in the input objects,
  54. and remove extra subjects if --remove-extra-subjects is specified.
  55. This is preferred to 'apply' for RBAC resources so that semantically-aware merging of rules and subjects is done.`)
  56. reconcileExample = templates.Examples(`
  57. # Reconcile rbac resources from a file
  58. kubectl auth reconcile -f my-rbac-rules.yaml`)
  59. )
  60. // NewReconcileOptions returns a new ReconcileOptions instance
  61. func NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOptions {
  62. return &ReconcileOptions{
  63. FilenameOptions: &resource.FilenameOptions{},
  64. PrintFlags: genericclioptions.NewPrintFlags("reconciled").WithTypeSetter(scheme.Scheme),
  65. IOStreams: ioStreams,
  66. }
  67. }
  68. // NewCmdReconcile holds the options for 'auth reconcile' sub command
  69. func NewCmdReconcile(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  70. o := NewReconcileOptions(streams)
  71. cmd := &cobra.Command{
  72. Use: "reconcile -f FILENAME",
  73. DisableFlagsInUseLine: true,
  74. Short: "Reconciles rules for RBAC Role, RoleBinding, ClusterRole, and ClusterRole binding objects",
  75. Long: reconcileLong,
  76. Example: reconcileExample,
  77. Run: func(cmd *cobra.Command, args []string) {
  78. cmdutil.CheckErr(o.Complete(cmd, f, args))
  79. cmdutil.CheckErr(o.Validate())
  80. cmdutil.CheckErr(o.RunReconcile())
  81. },
  82. }
  83. o.PrintFlags.AddFlags(cmd)
  84. cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, "identifying the resource to reconcile.")
  85. cmd.Flags().BoolVar(&o.DryRun, "dry-run", o.DryRun, "If true, display results but do not submit changes")
  86. cmd.Flags().BoolVar(&o.RemoveExtraPermissions, "remove-extra-permissions", o.RemoveExtraPermissions, "If true, removes extra permissions added to roles")
  87. cmd.Flags().BoolVar(&o.RemoveExtraSubjects, "remove-extra-subjects", o.RemoveExtraSubjects, "If true, removes extra subjects added to rolebindings")
  88. return cmd
  89. }
  90. // Complete completes all the required options
  91. func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error {
  92. if err := o.FilenameOptions.RequireFilenameOrKustomize(); err != nil {
  93. return err
  94. }
  95. if len(args) > 0 {
  96. return errors.New("no arguments are allowed")
  97. }
  98. namespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()
  99. if err != nil {
  100. return err
  101. }
  102. r := f.NewBuilder().
  103. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  104. ContinueOnError().
  105. NamespaceParam(namespace).DefaultNamespace().
  106. FilenameParam(enforceNamespace, o.FilenameOptions).
  107. Flatten().
  108. Do()
  109. if err := r.Err(); err != nil {
  110. return err
  111. }
  112. o.Visitor = r
  113. clientConfig, err := f.ToRESTConfig()
  114. if err != nil {
  115. return err
  116. }
  117. o.RBACClient, err = rbacv1client.NewForConfig(clientConfig)
  118. if err != nil {
  119. return err
  120. }
  121. o.NamespaceClient, err = corev1client.NewForConfig(clientConfig)
  122. if err != nil {
  123. return err
  124. }
  125. if o.DryRun {
  126. o.PrintFlags.Complete("%s (dry run)")
  127. }
  128. printer, err := o.PrintFlags.ToPrinter()
  129. if err != nil {
  130. return err
  131. }
  132. o.PrintObject = printer.PrintObj
  133. return nil
  134. }
  135. // Validate makes sure provided values for ReconcileOptions are valid
  136. func (o *ReconcileOptions) Validate() error {
  137. if o.Visitor == nil {
  138. return errors.New("ReconcileOptions.Visitor must be set")
  139. }
  140. if o.RBACClient == nil {
  141. return errors.New("ReconcileOptions.RBACClient must be set")
  142. }
  143. if o.NamespaceClient == nil {
  144. return errors.New("ReconcileOptions.NamespaceClient must be set")
  145. }
  146. if o.PrintObject == nil {
  147. return errors.New("ReconcileOptions.Print must be set")
  148. }
  149. if o.Out == nil {
  150. return errors.New("ReconcileOptions.Out must be set")
  151. }
  152. if o.ErrOut == nil {
  153. return errors.New("ReconcileOptions.Err must be set")
  154. }
  155. return nil
  156. }
  157. // RunReconcile performs the execution
  158. func (o *ReconcileOptions) RunReconcile() error {
  159. return o.Visitor.Visit(func(info *resource.Info, err error) error {
  160. if err != nil {
  161. return err
  162. }
  163. switch t := info.Object.(type) {
  164. case *rbacv1.Role:
  165. reconcileOptions := reconciliation.ReconcileRoleOptions{
  166. Confirm: !o.DryRun,
  167. RemoveExtraPermissions: o.RemoveExtraPermissions,
  168. Role: reconciliation.RoleRuleOwner{Role: t},
  169. Client: reconciliation.RoleModifier{
  170. NamespaceClient: o.NamespaceClient.Namespaces(),
  171. Client: o.RBACClient,
  172. },
  173. }
  174. result, err := reconcileOptions.Run()
  175. if err != nil {
  176. return err
  177. }
  178. o.printResults(result.Role.GetObject(), nil, nil, result.MissingRules, result.ExtraRules, result.Operation, result.Protected)
  179. case *rbacv1.ClusterRole:
  180. reconcileOptions := reconciliation.ReconcileRoleOptions{
  181. Confirm: !o.DryRun,
  182. RemoveExtraPermissions: o.RemoveExtraPermissions,
  183. Role: reconciliation.ClusterRoleRuleOwner{ClusterRole: t},
  184. Client: reconciliation.ClusterRoleModifier{
  185. Client: o.RBACClient.ClusterRoles(),
  186. },
  187. }
  188. result, err := reconcileOptions.Run()
  189. if err != nil {
  190. return err
  191. }
  192. o.printResults(result.Role.GetObject(), nil, nil, result.MissingRules, result.ExtraRules, result.Operation, result.Protected)
  193. case *rbacv1.RoleBinding:
  194. reconcileOptions := reconciliation.ReconcileRoleBindingOptions{
  195. Confirm: !o.DryRun,
  196. RemoveExtraSubjects: o.RemoveExtraSubjects,
  197. RoleBinding: reconciliation.RoleBindingAdapter{RoleBinding: t},
  198. Client: reconciliation.RoleBindingClientAdapter{
  199. Client: o.RBACClient,
  200. NamespaceClient: o.NamespaceClient.Namespaces(),
  201. },
  202. }
  203. result, err := reconcileOptions.Run()
  204. if err != nil {
  205. return err
  206. }
  207. o.printResults(result.RoleBinding.GetObject(), result.MissingSubjects, result.ExtraSubjects, nil, nil, result.Operation, result.Protected)
  208. case *rbacv1.ClusterRoleBinding:
  209. reconcileOptions := reconciliation.ReconcileRoleBindingOptions{
  210. Confirm: !o.DryRun,
  211. RemoveExtraSubjects: o.RemoveExtraSubjects,
  212. RoleBinding: reconciliation.ClusterRoleBindingAdapter{ClusterRoleBinding: t},
  213. Client: reconciliation.ClusterRoleBindingClientAdapter{
  214. Client: o.RBACClient.ClusterRoleBindings(),
  215. },
  216. }
  217. result, err := reconcileOptions.Run()
  218. if err != nil {
  219. return err
  220. }
  221. o.printResults(result.RoleBinding.GetObject(), result.MissingSubjects, result.ExtraSubjects, nil, nil, result.Operation, result.Protected)
  222. case *rbacv1beta1.Role,
  223. *rbacv1beta1.RoleBinding,
  224. *rbacv1beta1.ClusterRole,
  225. *rbacv1beta1.ClusterRoleBinding,
  226. *rbacv1alpha1.Role,
  227. *rbacv1alpha1.RoleBinding,
  228. *rbacv1alpha1.ClusterRole,
  229. *rbacv1alpha1.ClusterRoleBinding:
  230. return fmt.Errorf("only rbac.authorization.k8s.io/v1 is supported: not %T", t)
  231. default:
  232. klog.V(1).Infof("skipping %#v", info.Object.GetObjectKind())
  233. // skip ignored resources
  234. }
  235. return nil
  236. })
  237. }
  238. func (o *ReconcileOptions) printResults(object runtime.Object,
  239. missingSubjects, extraSubjects []rbacv1.Subject,
  240. missingRules, extraRules []rbacv1.PolicyRule,
  241. operation reconciliation.ReconcileOperation,
  242. protected bool) {
  243. o.PrintObject(object, o.Out)
  244. caveat := ""
  245. if protected {
  246. caveat = ", but object opted out (rbac.authorization.kubernetes.io/autoupdate: false)"
  247. }
  248. switch operation {
  249. case reconciliation.ReconcileNone:
  250. return
  251. case reconciliation.ReconcileCreate:
  252. fmt.Fprintf(o.ErrOut, "\treconciliation required create%s\n", caveat)
  253. case reconciliation.ReconcileUpdate:
  254. fmt.Fprintf(o.ErrOut, "\treconciliation required update%s\n", caveat)
  255. case reconciliation.ReconcileRecreate:
  256. fmt.Fprintf(o.ErrOut, "\treconciliation required recreate%s\n", caveat)
  257. }
  258. if len(missingSubjects) > 0 {
  259. fmt.Fprintf(o.ErrOut, "\tmissing subjects added:\n")
  260. for _, s := range missingSubjects {
  261. fmt.Fprintf(o.ErrOut, "\t\t%+v\n", s)
  262. }
  263. }
  264. if o.RemoveExtraSubjects {
  265. if len(extraSubjects) > 0 {
  266. fmt.Fprintf(o.ErrOut, "\textra subjects removed:\n")
  267. for _, s := range extraSubjects {
  268. fmt.Fprintf(o.ErrOut, "\t\t%+v\n", s)
  269. }
  270. }
  271. }
  272. if len(missingRules) > 0 {
  273. fmt.Fprintf(o.ErrOut, "\tmissing rules added:\n")
  274. for _, r := range missingRules {
  275. fmt.Fprintf(o.ErrOut, "\t\t%+v\n", r)
  276. }
  277. }
  278. if o.RemoveExtraPermissions {
  279. if len(extraRules) > 0 {
  280. fmt.Fprintf(o.ErrOut, "\textra rules removed:\n")
  281. for _, r := range extraRules {
  282. fmt.Fprintf(o.ErrOut, "\t\t%+v\n", r)
  283. }
  284. }
  285. }
  286. }