actions.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package actions
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/google/go-github/v33/github"
  7. "github.com/porter-dev/porter/internal/models"
  8. "github.com/porter-dev/porter/internal/repository"
  9. "golang.org/x/crypto/nacl/box"
  10. "golang.org/x/oauth2"
  11. "strings"
  12. "gopkg.in/yaml.v2"
  13. )
  14. type GithubActions struct {
  15. GitIntegration *models.GitRepo
  16. GitRepoName string
  17. GitRepoOwner string
  18. Repo repository.Repository
  19. GithubConf *oauth2.Config
  20. WebhookToken string
  21. PorterToken string
  22. ProjectID uint
  23. ReleaseName string
  24. DockerFilePath string
  25. ImageRepoURL string
  26. defaultBranch string
  27. }
  28. func (g *GithubActions) Setup() (string, error) {
  29. client, err := g.getClient()
  30. if err != nil {
  31. return "", err
  32. }
  33. // get the repository to find the default branch
  34. repo, _, err := client.Repositories.Get(
  35. context.TODO(),
  36. g.GitRepoOwner,
  37. g.GitRepoName,
  38. )
  39. if err != nil {
  40. return "", err
  41. }
  42. g.defaultBranch = repo.GetDefaultBranch()
  43. // create a new secret with a webhook token
  44. err = g.createGithubSecret(client, g.getWebhookSecretName(), g.WebhookToken)
  45. if err != nil {
  46. return "", err
  47. }
  48. // create a new secret with a porter token
  49. err = g.createGithubSecret(client, g.getPorterTokenSecretName(), g.PorterToken)
  50. if err != nil {
  51. return "", err
  52. }
  53. fileBytes, err := g.GetGithubActionYAML()
  54. if err != nil {
  55. return "", err
  56. }
  57. return g.commitGithubFile(client, g.getPorterYMLFileName(), fileBytes)
  58. }
  59. type GithubActionYAMLStep struct {
  60. Name string `yaml:"name,omitempty"`
  61. ID string `yaml:"id,omitempty"`
  62. Uses string `yaml:"uses,omitempty"`
  63. Run string `yaml:"run,omitempty"`
  64. }
  65. type GithubActionYAMLOnPushBranches struct {
  66. Branches []string `yaml:"branches,omitempty"`
  67. }
  68. type GithubActionYAMLOnPush struct {
  69. Push GithubActionYAMLOnPushBranches `yaml:"push,omitempty"`
  70. }
  71. type GithubActionYAMLJob struct {
  72. RunsOn string `yaml:"runs-on,omitempty"`
  73. Steps []GithubActionYAMLStep `yaml:"steps,omitempty"`
  74. }
  75. type GithubActionYAML struct {
  76. On GithubActionYAMLOnPush `yaml:"on,omitempty"`
  77. Name string `yaml:"name,omitempty"`
  78. Jobs map[string]GithubActionYAMLJob `yaml:"jobs,omitempty"`
  79. }
  80. func (g *GithubActions) GetGithubActionYAML() ([]byte, error) {
  81. actionYAML := &GithubActionYAML{
  82. On: GithubActionYAMLOnPush{
  83. Push: GithubActionYAMLOnPushBranches{
  84. Branches: []string{
  85. g.defaultBranch,
  86. },
  87. },
  88. },
  89. Name: "Deploy to Porter",
  90. Jobs: map[string]GithubActionYAMLJob{
  91. "porter-deploy": GithubActionYAMLJob{
  92. RunsOn: "ubuntu-latest",
  93. Steps: []GithubActionYAMLStep{
  94. getCheckoutCodeStep(),
  95. getDownloadPorterStep(),
  96. getConfigurePorterStep(g.getPorterTokenSecretName()),
  97. getDockerBuildPushStep(g.DockerFilePath, g.ImageRepoURL),
  98. deployPorterWebhookStep(g.getWebhookSecretName(), g.ImageRepoURL),
  99. },
  100. },
  101. },
  102. }
  103. return yaml.Marshal(actionYAML)
  104. }
  105. func (g *GithubActions) getClient() (*github.Client, error) {
  106. // get the oauth integration
  107. oauthInt, err := g.Repo.OAuthIntegration.ReadOAuthIntegration(g.GitIntegration.OAuthIntegrationID)
  108. if err != nil {
  109. return nil, err
  110. }
  111. tok := &oauth2.Token{
  112. AccessToken: string(oauthInt.AccessToken),
  113. RefreshToken: string(oauthInt.RefreshToken),
  114. TokenType: "Bearer",
  115. }
  116. client := github.NewClient(g.GithubConf.Client(oauth2.NoContext, tok))
  117. return client, nil
  118. }
  119. func (g *GithubActions) createGithubSecret(
  120. client *github.Client,
  121. secretName,
  122. secretValue string,
  123. ) error {
  124. // get the public key for the repo
  125. key, _, err := client.Actions.GetRepoPublicKey(context.TODO(), g.GitRepoOwner, g.GitRepoName)
  126. if err != nil {
  127. return err
  128. }
  129. // encrypt the secret with the public key
  130. keyBytes := [32]byte{}
  131. keyDecoded, err := base64.StdEncoding.DecodeString(*key.Key)
  132. if err != nil {
  133. return err
  134. }
  135. copy(keyBytes[:], keyDecoded[:])
  136. secretEncoded, err := box.SealAnonymous(nil, []byte(secretValue), &keyBytes, nil)
  137. if err != nil {
  138. return err
  139. }
  140. encrypted := base64.StdEncoding.EncodeToString(secretEncoded)
  141. encryptedSecret := &github.EncryptedSecret{
  142. Name: secretName,
  143. KeyID: *key.KeyID,
  144. EncryptedValue: encrypted,
  145. }
  146. // write the secret to the repo
  147. _, err = client.Actions.CreateOrUpdateRepoSecret(context.TODO(), g.GitRepoOwner, g.GitRepoName, encryptedSecret)
  148. return nil
  149. }
  150. func (g *GithubActions) getWebhookSecretName() string {
  151. return fmt.Sprintf("WEBHOOK_%s", strings.Replace(
  152. strings.ToUpper(g.ReleaseName), "-", "_", -1),
  153. )
  154. }
  155. func (g *GithubActions) getPorterYMLFileName() string {
  156. return fmt.Sprintf("porter_%s.yml", strings.Replace(
  157. strings.ToLower(g.ReleaseName), "-", "_", -1),
  158. )
  159. }
  160. func (g *GithubActions) getPorterTokenSecretName() string {
  161. return fmt.Sprintf("PORTER_TOKEN_%d", g.ProjectID)
  162. }
  163. func (g *GithubActions) commitGithubFile(
  164. client *github.Client,
  165. filename string,
  166. contents []byte,
  167. ) (string, error) {
  168. filepath := ".github/workflows/" + filename
  169. opts := &github.RepositoryContentFileOptions{
  170. Message: github.String(fmt.Sprintf("Create %s file", filename)),
  171. Content: contents,
  172. Branch: github.String(g.defaultBranch),
  173. Committer: &github.CommitAuthor{
  174. Name: github.String("Porter Bot"),
  175. Email: github.String("contact@getporter.dev"),
  176. },
  177. }
  178. resp, _, err := client.Repositories.UpdateFile(
  179. context.TODO(),
  180. g.GitRepoOwner,
  181. g.GitRepoName,
  182. filepath,
  183. opts,
  184. )
  185. if err != nil {
  186. return "", err
  187. }
  188. return *resp.Commit.SHA, nil
  189. }