github.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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. "bytes"
  16. "context"
  17. "crypto/rsa"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "net/http"
  23. "time"
  24. "github.com/golang-jwt/jwt/v5"
  25. corev1 "k8s.io/api/core/v1"
  26. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  27. "sigs.k8s.io/controller-runtime/pkg/client"
  28. "sigs.k8s.io/yaml"
  29. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  30. )
  31. type Generator struct {
  32. httpClient *http.Client
  33. }
  34. type Github struct {
  35. HTTP *http.Client
  36. Kube client.Client
  37. Namespace string
  38. URL string
  39. InstallTkn string
  40. Repositories []string
  41. Permissions map[string]string
  42. }
  43. const (
  44. defaultLoginUsername = "token"
  45. defaultGithubAPI = "https://api.github.com"
  46. errNoSpec = "no config spec provided"
  47. errParseSpec = "unable to parse spec: %w"
  48. errGetToken = "unable to get authorization token: %w"
  49. contextTimeout = 30 * time.Second
  50. httpClientTimeout = 5 * time.Second
  51. )
  52. func (g *Generator) Generate(ctx context.Context, jsonSpec *apiextensions.JSON, kube client.Client, namespace string) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  53. return g.generate(
  54. ctx,
  55. jsonSpec,
  56. kube,
  57. namespace,
  58. )
  59. }
  60. func (g *Generator) Cleanup(ctx context.Context, jsonSpec *apiextensions.JSON, _ genv1alpha1.GeneratorProviderState, crClient client.Client, namespace string) error {
  61. return nil
  62. }
  63. func (g *Generator) generate(
  64. ctx context.Context,
  65. jsonSpec *apiextensions.JSON,
  66. kube client.Client,
  67. namespace string) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  68. if jsonSpec == nil {
  69. return nil, nil, errors.New(errNoSpec)
  70. }
  71. ctx, cancel := context.WithTimeout(ctx, contextTimeout)
  72. defer cancel()
  73. gh, err := newGHClient(ctx, kube, namespace, g.httpClient, jsonSpec)
  74. if err != nil {
  75. return nil, nil, fmt.Errorf("error creating request: %w", err)
  76. }
  77. payload := make(map[string]interface{})
  78. if gh.Permissions != nil {
  79. payload["permissions"] = gh.Permissions
  80. }
  81. if len(gh.Repositories) > 0 {
  82. payload["repositories"] = gh.Repositories
  83. }
  84. var body io.Reader = http.NoBody
  85. if len(payload) > 0 {
  86. bodyBytes, err := json.Marshal(payload)
  87. if err != nil {
  88. return nil, nil, fmt.Errorf("error marshaling payload: %w", err)
  89. }
  90. body = bytes.NewReader(bodyBytes)
  91. }
  92. // Github api expects POST request
  93. req, err := http.NewRequestWithContext(ctx, http.MethodPost, gh.URL, body)
  94. if err != nil {
  95. return nil, nil, fmt.Errorf("error creating request: %w", err)
  96. }
  97. req.Header.Add("Authorization", "Bearer "+gh.InstallTkn)
  98. req.Header.Add("Accept", "application/vnd.github.v3+json")
  99. resp, err := gh.HTTP.Do(req)
  100. if err != nil {
  101. return nil, nil, fmt.Errorf("error performing request: %w", err)
  102. }
  103. defer func() {
  104. _ = resp.Body.Close()
  105. }()
  106. // git access token
  107. var gat map[string]any
  108. if err := json.NewDecoder(resp.Body).Decode(&gat); err != nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
  109. return nil, nil, fmt.Errorf("error decoding response: %w", err)
  110. }
  111. if resp.StatusCode >= 300 {
  112. if message, ok := gat["message"]; ok {
  113. return nil, nil, fmt.Errorf("error generating token: response code: %d, response: %v", resp.StatusCode, message)
  114. }
  115. return nil, nil, fmt.Errorf("error generating token, failed to extract error message from github request: response code: %d", resp.StatusCode)
  116. }
  117. accessToken, ok := gat["token"].(string)
  118. if !ok {
  119. return nil, nil, errors.New("token isn't a string or token key doesn't exist")
  120. }
  121. return map[string][]byte{
  122. defaultLoginUsername: []byte(accessToken),
  123. }, nil, nil
  124. }
  125. func newGHClient(ctx context.Context, k client.Client, n string, hc *http.Client,
  126. js *apiextensions.JSON) (*Github, error) {
  127. if hc == nil {
  128. hc = &http.Client{
  129. Timeout: httpClientTimeout,
  130. }
  131. }
  132. res, err := parseSpec(js.Raw)
  133. if err != nil {
  134. return nil, fmt.Errorf(errParseSpec, err)
  135. }
  136. gh := &Github{
  137. Kube: k,
  138. Namespace: n,
  139. HTTP: hc,
  140. Repositories: res.Spec.Repositories,
  141. Permissions: res.Spec.Permissions,
  142. }
  143. ghPath := fmt.Sprintf("/app/installations/%s/access_tokens", res.Spec.InstallID)
  144. gh.URL = defaultGithubAPI + ghPath
  145. if res.Spec.URL != "" {
  146. gh.URL = res.Spec.URL + ghPath
  147. }
  148. secret := &corev1.Secret{}
  149. if err := gh.Kube.Get(ctx, client.ObjectKey{Name: res.Spec.Auth.PrivateKey.SecretRef.Name, Namespace: n}, secret); err != nil {
  150. return nil, fmt.Errorf("error getting GH pem from secret:%w", err)
  151. }
  152. pk, err := jwt.ParseRSAPrivateKeyFromPEM(secret.Data[res.Spec.Auth.PrivateKey.SecretRef.Key])
  153. if err != nil {
  154. return nil, fmt.Errorf("error parsing RSA private key: %w", err)
  155. }
  156. if gh.InstallTkn, err = GetInstallationToken(pk, res.Spec.AppID); err != nil {
  157. return nil, fmt.Errorf("can't get InstallationToken: %w", err)
  158. }
  159. return gh, nil
  160. }
  161. // Get github installation token.
  162. func GetInstallationToken(key *rsa.PrivateKey, aid string) (string, error) {
  163. claims := jwt.RegisteredClaims{
  164. Issuer: aid,
  165. IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Second * 10)),
  166. ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * 300)),
  167. }
  168. token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
  169. signedToken, err := token.SignedString(key)
  170. if err != nil {
  171. return "", fmt.Errorf("error signing token: %w", err)
  172. }
  173. return signedToken, nil
  174. }
  175. func parseSpec(data []byte) (*genv1alpha1.GithubAccessToken, error) {
  176. var spec genv1alpha1.GithubAccessToken
  177. err := yaml.Unmarshal(data, &spec)
  178. return &spec, err
  179. }
  180. func init() {
  181. genv1alpha1.Register(genv1alpha1.GithubAccessTokenKind, &Generator{})
  182. }