github.go 6.5 KB

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