github.go 4.7 KB

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