github.go 4.7 KB

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