certificates.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 certificates
  14. import (
  15. "fmt"
  16. "io"
  17. "github.com/spf13/cobra"
  18. certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
  19. "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/cli-runtime/pkg/genericclioptions"
  23. "k8s.io/cli-runtime/pkg/printers"
  24. "k8s.io/cli-runtime/pkg/resource"
  25. certificatesv1beta1client "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
  26. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  27. "k8s.io/kubernetes/pkg/kubectl/scheme"
  28. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  29. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  30. )
  31. func NewCmdCertificate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  32. cmd := &cobra.Command{
  33. Use: "certificate SUBCOMMAND",
  34. DisableFlagsInUseLine: true,
  35. Short: i18n.T("Modify certificate resources."),
  36. Long: "Modify certificate resources.",
  37. Run: func(cmd *cobra.Command, args []string) {
  38. cmd.Help()
  39. },
  40. }
  41. cmd.AddCommand(NewCmdCertificateApprove(f, ioStreams))
  42. cmd.AddCommand(NewCmdCertificateDeny(f, ioStreams))
  43. return cmd
  44. }
  45. type CertificateOptions struct {
  46. resource.FilenameOptions
  47. PrintFlags *genericclioptions.PrintFlags
  48. PrintObj printers.ResourcePrinterFunc
  49. csrNames []string
  50. outputStyle string
  51. clientSet certificatesv1beta1client.CertificatesV1beta1Interface
  52. builder *resource.Builder
  53. genericclioptions.IOStreams
  54. }
  55. // NewCertificateOptions creates the options for certificate
  56. func NewCertificateOptions(ioStreams genericclioptions.IOStreams) *CertificateOptions {
  57. return &CertificateOptions{
  58. PrintFlags: genericclioptions.NewPrintFlags("approved").WithTypeSetter(scheme.Scheme),
  59. IOStreams: ioStreams,
  60. }
  61. }
  62. func (o *CertificateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  63. o.csrNames = args
  64. o.outputStyle = cmdutil.GetFlagString(cmd, "output")
  65. printer, err := o.PrintFlags.ToPrinter()
  66. if err != nil {
  67. return err
  68. }
  69. o.PrintObj = func(obj runtime.Object, out io.Writer) error {
  70. return printer.PrintObj(obj, out)
  71. }
  72. o.builder = f.NewBuilder()
  73. clientConfig, err := f.ToRESTConfig()
  74. if err != nil {
  75. return err
  76. }
  77. o.clientSet, err = certificatesv1beta1client.NewForConfig(clientConfig)
  78. if err != nil {
  79. return err
  80. }
  81. return nil
  82. }
  83. func (o *CertificateOptions) Validate() error {
  84. if len(o.csrNames) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {
  85. return fmt.Errorf("one or more CSRs must be specified as <name> or -f <filename>")
  86. }
  87. return nil
  88. }
  89. func NewCmdCertificateApprove(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  90. o := NewCertificateOptions(ioStreams)
  91. cmd := &cobra.Command{
  92. Use: "approve (-f FILENAME | NAME)",
  93. DisableFlagsInUseLine: true,
  94. Short: i18n.T("Approve a certificate signing request"),
  95. Long: templates.LongDesc(`
  96. Approve a certificate signing request.
  97. kubectl certificate approve allows a cluster admin to approve a certificate
  98. signing request (CSR). This action tells a certificate signing controller to
  99. issue a certificate to the requestor with the attributes requested in the CSR.
  100. SECURITY NOTICE: Depending on the requested attributes, the issued certificate
  101. can potentially grant a requester access to cluster resources or to authenticate
  102. as a requested identity. Before approving a CSR, ensure you understand what the
  103. signed certificate can do.
  104. `),
  105. Run: func(cmd *cobra.Command, args []string) {
  106. cmdutil.CheckErr(o.Complete(f, cmd, args))
  107. cmdutil.CheckErr(o.Validate())
  108. cmdutil.CheckErr(o.RunCertificateApprove(cmdutil.GetFlagBool(cmd, "force")))
  109. },
  110. }
  111. o.PrintFlags.AddFlags(cmd)
  112. cmd.Flags().Bool("force", false, "Update the CSR even if it is already approved.")
  113. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")
  114. return cmd
  115. }
  116. func (o *CertificateOptions) RunCertificateApprove(force bool) error {
  117. return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
  118. var alreadyApproved bool
  119. for _, c := range csr.Status.Conditions {
  120. if c.Type == certificatesv1beta1.CertificateApproved {
  121. alreadyApproved = true
  122. }
  123. }
  124. if alreadyApproved {
  125. return csr, true
  126. }
  127. csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
  128. Type: certificatesv1beta1.CertificateApproved,
  129. Reason: "KubectlApprove",
  130. Message: "This CSR was approved by kubectl certificate approve.",
  131. LastUpdateTime: metav1.Now(),
  132. })
  133. return csr, false
  134. })
  135. }
  136. func NewCmdCertificateDeny(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  137. o := NewCertificateOptions(ioStreams)
  138. cmd := &cobra.Command{
  139. Use: "deny (-f FILENAME | NAME)",
  140. DisableFlagsInUseLine: true,
  141. Short: i18n.T("Deny a certificate signing request"),
  142. Long: templates.LongDesc(`
  143. Deny a certificate signing request.
  144. kubectl certificate deny allows a cluster admin to deny a certificate
  145. signing request (CSR). This action tells a certificate signing controller to
  146. not to issue a certificate to the requestor.
  147. `),
  148. Run: func(cmd *cobra.Command, args []string) {
  149. cmdutil.CheckErr(o.Complete(f, cmd, args))
  150. cmdutil.CheckErr(o.Validate())
  151. cmdutil.CheckErr(o.RunCertificateDeny(cmdutil.GetFlagBool(cmd, "force")))
  152. },
  153. }
  154. o.PrintFlags.AddFlags(cmd)
  155. cmd.Flags().Bool("force", false, "Update the CSR even if it is already denied.")
  156. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")
  157. return cmd
  158. }
  159. func (o *CertificateOptions) RunCertificateDeny(force bool) error {
  160. return o.modifyCertificateCondition(o.builder, o.clientSet, force, func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool) {
  161. var alreadyDenied bool
  162. for _, c := range csr.Status.Conditions {
  163. if c.Type == certificatesv1beta1.CertificateDenied {
  164. alreadyDenied = true
  165. }
  166. }
  167. if alreadyDenied {
  168. return csr, true
  169. }
  170. csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
  171. Type: certificatesv1beta1.CertificateDenied,
  172. Reason: "KubectlDeny",
  173. Message: "This CSR was denied by kubectl certificate deny.",
  174. LastUpdateTime: metav1.Now(),
  175. })
  176. return csr, false
  177. })
  178. }
  179. func (o *CertificateOptions) modifyCertificateCondition(builder *resource.Builder, clientSet certificatesv1beta1client.CertificatesV1beta1Interface, force bool, modify func(csr *certificatesv1beta1.CertificateSigningRequest) (*certificatesv1beta1.CertificateSigningRequest, bool)) error {
  180. var found int
  181. r := builder.
  182. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  183. ContinueOnError().
  184. FilenameParam(false, &o.FilenameOptions).
  185. ResourceNames("certificatesigningrequest", o.csrNames...).
  186. RequireObject(true).
  187. Flatten().
  188. Latest().
  189. Do()
  190. err := r.Visit(func(info *resource.Info, err error) error {
  191. if err != nil {
  192. return err
  193. }
  194. for i := 0; ; i++ {
  195. csr := info.Object.(*certificatesv1beta1.CertificateSigningRequest)
  196. csr, hasCondition := modify(csr)
  197. if !hasCondition || force {
  198. csr, err = clientSet.CertificateSigningRequests().UpdateApproval(csr)
  199. if errors.IsConflict(err) && i < 10 {
  200. if err := info.Get(); err != nil {
  201. return err
  202. }
  203. continue
  204. }
  205. if err != nil {
  206. return err
  207. }
  208. }
  209. break
  210. }
  211. found++
  212. return o.PrintObj(info.Object, o.Out)
  213. })
  214. if found == 0 {
  215. fmt.Fprintf(o.Out, "No resources found\n")
  216. }
  217. return err
  218. }