client.go 8.1 KB

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