actions.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. BuildEnv map[string]string
  23. ProjectID uint
  24. ReleaseName string
  25. DockerFilePath string
  26. FolderPath string
  27. ImageRepoURL string
  28. defaultBranch string
  29. }
  30. func (g *GithubActions) Setup() (string, error) {
  31. client, err := g.getClient()
  32. if err != nil {
  33. return "", err
  34. }
  35. // get the repository to find the default branch
  36. repo, _, err := client.Repositories.Get(
  37. context.TODO(),
  38. g.GitRepoOwner,
  39. g.GitRepoName,
  40. )
  41. if err != nil {
  42. return "", err
  43. }
  44. g.defaultBranch = repo.GetDefaultBranch()
  45. // create a new secret with a webhook token
  46. err = g.createGithubSecret(client, g.getWebhookSecretName(), g.WebhookToken)
  47. if err != nil {
  48. return "", err
  49. }
  50. // create a new secret with a porter token
  51. err = g.createGithubSecret(client, g.getPorterTokenSecretName(), g.PorterToken)
  52. if err != nil {
  53. return "", err
  54. }
  55. // create a new secret with the build variables
  56. err = g.createEnvSecret(client)
  57. if err != nil {
  58. return "", err
  59. }
  60. fileBytes, err := g.GetGithubActionYAML()
  61. if err != nil {
  62. return "", err
  63. }
  64. return g.commitGithubFile(client, g.getPorterYMLFileName(), fileBytes)
  65. }
  66. type GithubActionYAMLStep struct {
  67. Name string `yaml:"name,omitempty"`
  68. ID string `yaml:"id,omitempty"`
  69. Uses string `yaml:"uses,omitempty"`
  70. Run string `yaml:"run,omitempty"`
  71. }
  72. type GithubActionYAMLOnPushBranches struct {
  73. Branches []string `yaml:"branches,omitempty"`
  74. }
  75. type GithubActionYAMLOnPush struct {
  76. Push GithubActionYAMLOnPushBranches `yaml:"push,omitempty"`
  77. }
  78. type GithubActionYAMLJob struct {
  79. RunsOn string `yaml:"runs-on,omitempty"`
  80. Steps []GithubActionYAMLStep `yaml:"steps,omitempty"`
  81. }
  82. type GithubActionYAML struct {
  83. On GithubActionYAMLOnPush `yaml:"on,omitempty"`
  84. Name string `yaml:"name,omitempty"`
  85. Jobs map[string]GithubActionYAMLJob `yaml:"jobs,omitempty"`
  86. }
  87. func (g *GithubActions) GetGithubActionYAML() ([]byte, error) {
  88. gaSteps := []GithubActionYAMLStep{
  89. getCheckoutCodeStep(),
  90. getDownloadPorterStep(),
  91. getConfigurePorterStep(g.getPorterTokenSecretName()),
  92. }
  93. if g.DockerFilePath == "" {
  94. gaSteps = append(gaSteps, getBuildPackPushStep(g.getBuildEnvSecretName(), g.FolderPath, g.ImageRepoURL))
  95. } else {
  96. gaSteps = append(gaSteps, getDockerBuildPushStep(g.getBuildEnvSecretName(), g.DockerFilePath, g.ImageRepoURL))
  97. }
  98. gaSteps = append(gaSteps, deployPorterWebhookStep(g.getWebhookSecretName(), g.ImageRepoURL))
  99. actionYAML := &GithubActionYAML{
  100. On: GithubActionYAMLOnPush{
  101. Push: GithubActionYAMLOnPushBranches{
  102. Branches: []string{
  103. g.defaultBranch,
  104. },
  105. },
  106. },
  107. Name: "Deploy to Porter",
  108. Jobs: map[string]GithubActionYAMLJob{
  109. "porter-deploy": {
  110. RunsOn: "ubuntu-latest",
  111. Steps: gaSteps,
  112. },
  113. },
  114. }
  115. return yaml.Marshal(actionYAML)
  116. }
  117. func (g *GithubActions) getClient() (*github.Client, error) {
  118. // get the oauth integration
  119. oauthInt, err := g.Repo.OAuthIntegration.ReadOAuthIntegration(g.GitIntegration.OAuthIntegrationID)
  120. if err != nil {
  121. return nil, err
  122. }
  123. tok := &oauth2.Token{
  124. AccessToken: string(oauthInt.AccessToken),
  125. RefreshToken: string(oauthInt.RefreshToken),
  126. TokenType: "Bearer",
  127. }
  128. client := github.NewClient(g.GithubConf.Client(oauth2.NoContext, tok))
  129. return client, nil
  130. }
  131. func (g *GithubActions) createGithubSecret(
  132. client *github.Client,
  133. secretName,
  134. secretValue string,
  135. ) error {
  136. // get the public key for the repo
  137. key, _, err := client.Actions.GetRepoPublicKey(context.TODO(), g.GitRepoOwner, g.GitRepoName)
  138. if err != nil {
  139. return err
  140. }
  141. // encrypt the secret with the public key
  142. keyBytes := [32]byte{}
  143. keyDecoded, err := base64.StdEncoding.DecodeString(*key.Key)
  144. if err != nil {
  145. return err
  146. }
  147. copy(keyBytes[:], keyDecoded[:])
  148. secretEncoded, err := box.SealAnonymous(nil, []byte(secretValue), &keyBytes, nil)
  149. if err != nil {
  150. return err
  151. }
  152. encrypted := base64.StdEncoding.EncodeToString(secretEncoded)
  153. encryptedSecret := &github.EncryptedSecret{
  154. Name: secretName,
  155. KeyID: *key.KeyID,
  156. EncryptedValue: encrypted,
  157. }
  158. // write the secret to the repo
  159. _, err = client.Actions.CreateOrUpdateRepoSecret(context.TODO(), g.GitRepoOwner, g.GitRepoName, encryptedSecret)
  160. return nil
  161. }
  162. func (g *GithubActions) createEnvSecret(client *github.Client) error {
  163. // convert the env object to a string
  164. lines := make([]string, 0)
  165. for key, val := range g.BuildEnv {
  166. lines = append(lines, fmt.Sprintf(`%s=%s`, key, val))
  167. }
  168. secretName := g.getBuildEnvSecretName()
  169. return g.createGithubSecret(client, secretName, strings.Join(lines, "\n"))
  170. }
  171. func (g *GithubActions) getWebhookSecretName() string {
  172. return fmt.Sprintf("WEBHOOK_%s", strings.Replace(
  173. strings.ToUpper(g.ReleaseName), "-", "_", -1),
  174. )
  175. }
  176. func (g *GithubActions) getBuildEnvSecretName() string {
  177. return fmt.Sprintf("ENV_%s", strings.Replace(
  178. strings.ToUpper(g.ReleaseName), "-", "_", -1),
  179. )
  180. }
  181. func (g *GithubActions) getPorterYMLFileName() string {
  182. return fmt.Sprintf("porter_%s.yml", strings.Replace(
  183. strings.ToLower(g.ReleaseName), "-", "_", -1),
  184. )
  185. }
  186. func (g *GithubActions) getPorterTokenSecretName() string {
  187. return fmt.Sprintf("PORTER_TOKEN_%d", g.ProjectID)
  188. }
  189. func (g *GithubActions) commitGithubFile(
  190. client *github.Client,
  191. filename string,
  192. contents []byte,
  193. ) (string, error) {
  194. filepath := ".github/workflows/" + filename
  195. opts := &github.RepositoryContentFileOptions{
  196. Message: github.String(fmt.Sprintf("Create %s file", filename)),
  197. Content: contents,
  198. Branch: github.String(g.defaultBranch),
  199. Committer: &github.CommitAuthor{
  200. Name: github.String("Porter Bot"),
  201. Email: github.String("contact@getporter.dev"),
  202. },
  203. }
  204. resp, _, err := client.Repositories.UpdateFile(
  205. context.TODO(),
  206. g.GitRepoOwner,
  207. g.GitRepoName,
  208. filepath,
  209. opts,
  210. )
  211. if err != nil {
  212. return "", err
  213. }
  214. return *resp.Commit.SHA, nil
  215. }