github.go 5.9 KB

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