|
| 1 | +package controllers |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "github.com/diggerhq/digger/ee/drift/dbmodels" |
| 8 | + "github.com/diggerhq/digger/ee/drift/middleware" |
| 9 | + "github.com/diggerhq/digger/ee/drift/model" |
| 10 | + next_utils "github.com/diggerhq/digger/next/utils" |
| 11 | + "github.com/gin-gonic/gin" |
| 12 | + "github.com/google/go-github/v61/github" |
| 13 | + "golang.org/x/oauth2" |
| 14 | + "log" |
| 15 | + "net/http" |
| 16 | + "os" |
| 17 | + "strconv" |
| 18 | + "strings" |
| 19 | +) |
| 20 | + |
| 21 | +func (mc MainController) GithubAppCallbackPage(c *gin.Context) { |
| 22 | + installationId := c.Request.URL.Query()["installation_id"][0] |
| 23 | + //setupAction := c.Request.URL.Query()["setup_action"][0] |
| 24 | + code := c.Request.URL.Query()["code"][0] |
| 25 | + clientId := os.Getenv("GITHUB_APP_CLIENT_ID") |
| 26 | + clientSecret := os.Getenv("GITHUB_APP_CLIENT_SECRET") |
| 27 | + |
| 28 | + installationId64, err := strconv.ParseInt(installationId, 10, 64) |
| 29 | + if err != nil { |
| 30 | + log.Printf("err: %v", err) |
| 31 | + c.String(http.StatusInternalServerError, "Failed to parse installation_id.") |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + result, installation, err := validateGithubCallback(mc.GithubClientProvider, clientId, clientSecret, code, installationId64) |
| 36 | + if !result { |
| 37 | + log.Printf("Failed to validated installation id, %v\n", err) |
| 38 | + c.String(http.StatusInternalServerError, "Failed to validate installation_id.") |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + // retrive org for current orgID |
| 43 | + orgId, exists := c.Get(middleware.ORGANISATION_ID_KEY) |
| 44 | + if !exists { |
| 45 | + log.Printf("missing argument orgId in github callback") |
| 46 | + c.String(http.StatusBadRequest, "missing orgID in request") |
| 47 | + return |
| 48 | + } |
| 49 | + org, err := dbmodels.DB.GetOrganisationById(orgId) |
| 50 | + if err != nil { |
| 51 | + log.Printf("Error fetching organisation: %v", err) |
| 52 | + c.JSON(http.StatusInternalServerError, gin.H{"error": "Error fetching organisation"}) |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + // create a github installation link (org ID matched to installation ID) |
| 57 | + _, err = dbmodels.DB.CreateGithubInstallationLink(org.ID, installationId) |
| 58 | + if err != nil { |
| 59 | + log.Printf("Error saving GithubInstallationLink to database: %v", err) |
| 60 | + c.JSON(http.StatusInternalServerError, gin.H{"error": "Error updating GitHub installation"}) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + client, _, err := mc.GithubClientProvider.Get(*installation.AppID, installationId64) |
| 65 | + if err != nil { |
| 66 | + log.Printf("Error retriving github client: %v", err) |
| 67 | + c.JSON(http.StatusInternalServerError, gin.H{"error": "Error fetching organisation"}) |
| 68 | + return |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | + // we get repos accessible to this installation |
| 73 | + listRepos, _, err := client.Apps.ListRepos(context.Background(), nil) |
| 74 | + if err != nil { |
| 75 | + log.Printf("Failed to validated list existing repos, %v\n", err) |
| 76 | + c.String(http.StatusInternalServerError, "Failed to list existing repos: %v", err) |
| 77 | + return |
| 78 | + } |
| 79 | + repos := listRepos.Repositories |
| 80 | + |
| 81 | + // reset all existing repos (soft delete) |
| 82 | + var ExistingRepos []model.Repo |
| 83 | + err = dbmodels.DB.GormDB.Delete(ExistingRepos, "organization_id=?", orgId).Error |
| 84 | + if err != nil { |
| 85 | + log.Printf("could not delete repos: %v", err) |
| 86 | + c.String(http.StatusInternalServerError, "could not delete repos: %v", err) |
| 87 | + return |
| 88 | + } |
| 89 | + |
| 90 | + // here we mark repos that are available one by one |
| 91 | + for _, repo := range repos { |
| 92 | + repoFullName := *repo.FullName |
| 93 | + repoOwner := strings.Split(*repo.FullName, "/")[0] |
| 94 | + repoName := *repo.Name |
| 95 | + repoUrl := fmt.Sprintf("https://github.com/%v", repoFullName) |
| 96 | + |
| 97 | + _, _, err = dbmodels.CreateOrGetDiggerRepoForGithubRepo(repoFullName, repoOwner, repoName, repoUrl, installationId64, *installation.AppID, *installation.Account.ID, *installation.Account.Login) |
| 98 | + if err != nil { |
| 99 | + log.Printf("createOrGetDiggerRepoForGithubRepo error: %v", err) |
| 100 | + c.String(http.StatusInternalServerError, "createOrGetDiggerRepoForGithubRepo error: %v", err) |
| 101 | + return |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + c.HTML(http.StatusOK, "github_success.tmpl", gin.H{}) |
| 106 | +} |
| 107 | + |
| 108 | +// why this validation is needed: https://roadie.io/blog/avoid-leaking-github-org-data/ |
| 109 | +// validation based on https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app , step 3 |
| 110 | +func validateGithubCallback(githubClientProvider next_utils.GithubClientProvider, clientId string, clientSecret string, code string, installationId int64) (bool, *github.Installation, error) { |
| 111 | + ctx := context.Background() |
| 112 | + type OAuthAccessResponse struct { |
| 113 | + AccessToken string `json:"access_token"` |
| 114 | + } |
| 115 | + httpClient := http.Client{} |
| 116 | + |
| 117 | + githubHostname := "github.com" |
| 118 | + reqURL := fmt.Sprintf("https://%v/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", githubHostname, clientId, clientSecret, code) |
| 119 | + req, err := http.NewRequest(http.MethodPost, reqURL, nil) |
| 120 | + if err != nil { |
| 121 | + return false, nil, fmt.Errorf("could not create HTTP request: %v\n", err) |
| 122 | + } |
| 123 | + req.Header.Set("accept", "application/json") |
| 124 | + |
| 125 | + res, err := httpClient.Do(req) |
| 126 | + if err != nil { |
| 127 | + return false, nil, fmt.Errorf("request to login/oauth/access_token failed: %v\n", err) |
| 128 | + } |
| 129 | + |
| 130 | + if err != nil { |
| 131 | + return false, nil, fmt.Errorf("Failed to read response's body: %v\n", err) |
| 132 | + } |
| 133 | + |
| 134 | + var t OAuthAccessResponse |
| 135 | + if err := json.NewDecoder(res.Body).Decode(&t); err != nil { |
| 136 | + return false, nil, fmt.Errorf("could not parse JSON response: %v\n", err) |
| 137 | + } |
| 138 | + |
| 139 | + ts := oauth2.StaticTokenSource( |
| 140 | + &oauth2.Token{AccessToken: t.AccessToken}, |
| 141 | + ) |
| 142 | + tc := oauth2.NewClient(ctx, ts) |
| 143 | + //tc := &http.Client{ |
| 144 | + // Transport: &oauth2.Transport{ |
| 145 | + // Base: httpClient.Transport, |
| 146 | + // Source: oauth2.ReuseTokenSource(nil, ts), |
| 147 | + // }, |
| 148 | + //} |
| 149 | + |
| 150 | + client, err := githubClientProvider.NewClient(tc) |
| 151 | + if err != nil { |
| 152 | + log.Printf("could create github client: %v", err) |
| 153 | + return false, nil, fmt.Errorf("could not create github client: %v", err) |
| 154 | + } |
| 155 | + |
| 156 | + installationIdMatch := false |
| 157 | + // list all installations for the user |
| 158 | + var matchedInstallation *github.Installation |
| 159 | + installations, _, err := client.Apps.ListUserInstallations(ctx, nil) |
| 160 | + if err != nil { |
| 161 | + log.Printf("could not retrieve installations: %v", err) |
| 162 | + return false, nil, fmt.Errorf("could not retrieve installations: %v", installationId) |
| 163 | + } |
| 164 | + log.Printf("installations %v", installations) |
| 165 | + for _, v := range installations { |
| 166 | + log.Printf("installation id: %v\n", *v.ID) |
| 167 | + if *v.ID == installationId { |
| 168 | + matchedInstallation = v |
| 169 | + installationIdMatch = true |
| 170 | + } |
| 171 | + } |
| 172 | + if !installationIdMatch { |
| 173 | + return false, nil, fmt.Errorf("InstallationId %v doesn't match any id for specified user\n", installationId) |
| 174 | + } |
| 175 | + |
| 176 | + return true, matchedInstallation, nil |
| 177 | +} |
0 commit comments