client.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*
  2. Copyright © The ESO 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. https://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 github
  14. import (
  15. "context"
  16. crypto_rand "crypto/rand"
  17. "encoding/base64"
  18. "encoding/json"
  19. "fmt"
  20. "time"
  21. github "github.com/google/go-github/v56/github"
  22. "golang.org/x/crypto/nacl/box"
  23. corev1 "k8s.io/api/core/v1"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  26. )
  27. const errWriteOnlyProvider = "not implemented - this provider supports write-only operations"
  28. // orgSecretVisibilitySelected is the GitHub org-secret visibility value that
  29. // restricts the secret to an explicit list of repositories.
  30. const orgSecretVisibilitySelected = "selected"
  31. // https://github.com/external-secrets/external-secrets/issues/644
  32. var _ esv1.SecretsClient = &Client{}
  33. // ActionsServiceClient defines the interface for interacting with GitHub Actions secrets.
  34. type ActionsServiceClient interface {
  35. // CreateOrUpdateOrgSecret creates or updates an organization secret.
  36. CreateOrUpdateOrgSecret(ctx context.Context, org string, eSecret *github.EncryptedSecret) (response *github.Response, err error)
  37. // GetOrgSecret retrieves an organization secret.
  38. GetOrgSecret(ctx context.Context, org string, name string) (*github.Secret, *github.Response, error)
  39. // ListOrgSecrets lists all organization secrets.
  40. ListOrgSecrets(ctx context.Context, org string, opts *github.ListOptions) (*github.Secrets, *github.Response, error)
  41. }
  42. // Client implements the External Secrets Kubernetes provider for GitHub Actions or Dependabot secrets.
  43. type Client struct {
  44. crClient client.Client
  45. store esv1.GenericStore
  46. provider *esv1.GithubProvider
  47. baseClient github.ActionsService
  48. dependabotClient github.DependabotService
  49. namespace string
  50. storeKind string
  51. repoID int64
  52. getSecretFn func(ctx context.Context, ref esv1.PushSecretRemoteRef) (*github.Secret, *github.Response, error)
  53. getPublicKeyFn func(ctx context.Context) (*github.PublicKey, *github.Response, error)
  54. createOrUpdateFn func(ctx context.Context, eSecret *github.EncryptedSecret) (*github.Response, error)
  55. listSecretsFn func(ctx context.Context) (*github.Secrets, *github.Response, error)
  56. deleteSecretFn func(ctx context.Context, ref esv1.PushSecretRemoteRef) (*github.Response, error)
  57. // listSelectedReposFn lists the repo IDs currently granted access to a
  58. // "selected"-visibility org secret; nil for repo/env scopes.
  59. listSelectedReposFn func(ctx context.Context, name string) (github.SelectedRepoIDs, error)
  60. }
  61. // DeleteSecret deletes a secret from the configured GitHub secrets service.
  62. func (g *Client) DeleteSecret(ctx context.Context, remoteRef esv1.PushSecretRemoteRef) error {
  63. _, err := g.deleteSecretFn(ctx, remoteRef)
  64. if err != nil {
  65. return fmt.Errorf("failed to delete secret: %w", err)
  66. }
  67. return nil
  68. }
  69. // SecretExists checks if a secret exists in the configured GitHub secrets service.
  70. func (g *Client) SecretExists(ctx context.Context, ref esv1.PushSecretRemoteRef) (bool, error) {
  71. githubSecret, _, err := g.getSecretFn(ctx, ref)
  72. if err != nil {
  73. return false, fmt.Errorf("error fetching secret: %w", err)
  74. }
  75. if githubSecret != nil {
  76. return true, nil
  77. }
  78. return false, nil
  79. }
  80. // PushSecret pushes a new secret to the configured GitHub secrets service.
  81. func (g *Client) PushSecret(ctx context.Context, secret *corev1.Secret, remoteRef esv1.PushSecretData) error {
  82. githubSecret, response, err := g.getSecretFn(ctx, remoteRef)
  83. if err != nil && (response == nil || response.StatusCode != 404) {
  84. return fmt.Errorf("error fetching secret: %w", err)
  85. }
  86. // First at all, we need the organization public key to encrypt the secret.
  87. publicKey, _, err := g.getPublicKeyFn(ctx)
  88. if err != nil {
  89. return fmt.Errorf("error fetching public key: %w", err)
  90. }
  91. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey.GetKey())
  92. if err != nil {
  93. return fmt.Errorf("unable to decode public key: %w", err)
  94. }
  95. var boxKey [32]byte
  96. copy(boxKey[:], decodedPublicKey)
  97. var ok bool
  98. // default to full secret.
  99. value, err := json.Marshal(secret.Data)
  100. if err != nil {
  101. return fmt.Errorf("json.Marshal failed with error %w", err)
  102. }
  103. // if key is specified, overwrite to key only
  104. if remoteRef.GetSecretKey() != "" {
  105. value, ok = secret.Data[remoteRef.GetSecretKey()]
  106. if !ok {
  107. return fmt.Errorf("key %s not found in secret", remoteRef.GetSecretKey())
  108. }
  109. }
  110. encryptedBytes, err := box.SealAnonymous([]byte{}, value, &boxKey, crypto_rand.Reader)
  111. if err != nil {
  112. return fmt.Errorf("box.SealAnonymous failed with error %w", err)
  113. }
  114. name := remoteRef.GetRemoteKey()
  115. visibility := g.resolveOrgSecretVisibility(githubSecret)
  116. if githubSecret != nil {
  117. name = githubSecret.Name
  118. }
  119. encryptedString := base64.StdEncoding.EncodeToString(encryptedBytes)
  120. keyID := publicKey.GetKeyID()
  121. encryptedSecret := &github.EncryptedSecret{
  122. Name: name,
  123. KeyID: keyID,
  124. EncryptedValue: encryptedString,
  125. Visibility: visibility,
  126. }
  127. // A "selected"-visibility org secret restricts access to an explicit list
  128. // of repositories. GitHub treats an update that omits
  129. // selected_repository_ids as "clear all repositories", so without re-sending
  130. // the current list an update silently revokes access for every previously
  131. // selected repository. Preserve the existing associations on update.
  132. if visibility == orgSecretVisibilitySelected && githubSecret != nil && g.listSelectedReposFn != nil {
  133. repoIDs, err := g.listSelectedReposFn(ctx, name)
  134. if err != nil {
  135. return fmt.Errorf("failed to list selected repositories for org secret %q: %w", name, err)
  136. }
  137. encryptedSecret.SelectedRepositoryIDs = repoIDs
  138. }
  139. if _, err := g.createOrUpdateFn(ctx, encryptedSecret); err != nil {
  140. return fmt.Errorf("failed to create secret: %w", err)
  141. }
  142. return nil
  143. }
  144. // resolveOrgSecretVisibility returns the visibility to use when creating or updating an org secret.
  145. //
  146. // Rules:
  147. // - If OrgSecretVisibility is set on the provider, that value is always used.
  148. // - Otherwise, if the secret already exists in GitHub, its current visibility is preserved.
  149. // - Otherwise (new secret, no provider override), visibility defaults to "all".
  150. func (g *Client) resolveOrgSecretVisibility(existing *github.Secret) string {
  151. if g.provider != nil && g.provider.OrgSecretVisibility != "" {
  152. return g.provider.OrgSecretVisibility
  153. }
  154. if existing != nil && existing.Visibility != "" {
  155. return existing.Visibility
  156. }
  157. return "all"
  158. }
  159. // GetAllSecrets is not implemented as this provider is write-only.
  160. func (g *Client) GetAllSecrets(_ context.Context, _ esv1.ExternalSecretFind) (map[string][]byte, error) {
  161. return nil, fmt.Errorf(errWriteOnlyProvider)
  162. }
  163. // GetSecret is not implemented as this provider is write-only.
  164. func (g *Client) GetSecret(_ context.Context, _ esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  165. return nil, fmt.Errorf(errWriteOnlyProvider)
  166. }
  167. // GetSecretMap is not implemented as this provider is write-only.
  168. func (g *Client) GetSecretMap(_ context.Context, _ esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  169. return nil, fmt.Errorf(errWriteOnlyProvider)
  170. }
  171. // Close cleans up any resources held by the client. No-op for this provider.
  172. func (g *Client) Close(_ context.Context) error {
  173. return nil
  174. }
  175. // Validate checks if the client is properly configured and has access to the configured GitHub secrets API.
  176. func (g *Client) Validate() (esv1.ValidationResult, error) {
  177. if g.store.GetKind() == esv1.ClusterSecretStoreKind {
  178. return esv1.ValidationResultUnknown, nil
  179. }
  180. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  181. defer cancel()
  182. _, _, err := g.listSecretsFn(ctx)
  183. if err != nil {
  184. return esv1.ValidationResultError, fmt.Errorf("store is not allowed to list secrets: %w", err)
  185. }
  186. return esv1.ValidationResultReady, nil
  187. }