-
Notifications
You must be signed in to change notification settings - Fork 1
[BB-508] baton-github: use github app to sync #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,16 +2,24 @@ package connector | |
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rsa" | ||
| "crypto/x509" | ||
| "encoding/json" | ||
| "encoding/pem" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "time" | ||
|
|
||
| cfg "github.com/conductorone/baton-github/pkg/config" | ||
| v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" | ||
| "github.com/conductorone/baton-sdk/pkg/annotations" | ||
| "github.com/conductorone/baton-sdk/pkg/connectorbuilder" | ||
| "github.com/conductorone/baton-sdk/pkg/uhttp" | ||
| jwtv5 "github.com/golang-jwt/jwt/v5" | ||
| "github.com/google/go-github/v63/github" | ||
| "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap" | ||
| "github.com/shurcooL/githubv4" | ||
|
|
@@ -58,14 +66,24 @@ type GitHub struct { | |
| graphqlClient *githubv4.Client | ||
| hasSAMLEnabled *bool | ||
| orgCache *orgNameCache | ||
| app gitHubApp | ||
| } | ||
|
|
||
| // gitHubApp has app clients that are used by the GitHub App. | ||
| // Each app has a single JWT token shared across all organizations. | ||
| // However, each organization has its own unique installation token. | ||
| type gitHubApp struct { | ||
| appJWTClient *github.Client | ||
| appInstallationClient map[int64]*github.Client | ||
| graphqlClient map[int64]*githubv4.Client | ||
| } | ||
|
|
||
| func (gh *GitHub) ResourceSyncers(ctx context.Context) []connectorbuilder.ResourceSyncer { | ||
| return []connectorbuilder.ResourceSyncer{ | ||
| orgBuilder(gh.client, gh.orgCache, gh.orgs), | ||
| teamBuilder(gh.client, gh.orgCache), | ||
| userBuilder(gh.client, gh.hasSAMLEnabled, gh.graphqlClient, gh.orgCache), | ||
| repositoryBuilder(gh.client, gh.orgCache), | ||
| orgBuilder(gh.client, gh.app, gh.orgCache, gh.orgs), | ||
| teamBuilder(gh.client, gh.app, gh.orgCache), | ||
| userBuilder(gh.client, gh.app, gh.hasSAMLEnabled, gh.graphqlClient, gh.orgCache), | ||
| repositoryBuilder(gh.client, gh.app, gh.orgCache), | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -78,6 +96,10 @@ func (gh *GitHub) Metadata(ctx context.Context) (*v2.ConnectorMetadata, error) { | |
|
|
||
| // Validate hits the GitHub API to validate that the configured credentials are still valid. | ||
| func (gh *GitHub) Validate(ctx context.Context) (annotations.Annotations, error) { | ||
| if gh.app.appJWTClient != nil { | ||
| return gh.validateAppCredentials(ctx) | ||
| } | ||
|
|
||
| page := 0 | ||
| orgLogins := gh.orgs | ||
| filterOrgs := true | ||
|
|
@@ -99,7 +121,6 @@ func (gh *GitHub) Validate(ctx context.Context) (annotations.Annotations, error) | |
| if resp.NextPage == 0 { | ||
| break | ||
| } | ||
|
|
||
| page = resp.NextPage | ||
| } | ||
| } | ||
|
|
@@ -132,6 +153,62 @@ func (gh *GitHub) Validate(ctx context.Context) (annotations.Annotations, error) | |
| return nil, nil | ||
| } | ||
|
|
||
| func (gh *GitHub) validateAppCredentials(ctx context.Context) (annotations.Annotations, error) { | ||
| iResp, err := getAllInstallations(ctx, gh.app.appJWTClient) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| for _, o := range gh.orgs { | ||
| if _, ok := iResp.accountNames[o]; !ok { | ||
| return nil, fmt.Errorf("access token must be an admin on the %s organization", o) | ||
| } | ||
| } | ||
| return nil, nil | ||
| } | ||
|
|
||
| type getAllInstallationsResp struct { | ||
| installationIDs map[int64]*github.Installation | ||
| accountIDs map[int64]struct{} | ||
| accountNames map[string]struct{} | ||
| } | ||
|
|
||
| func getAllInstallations(ctx context.Context, c *github.Client) (getAllInstallationsResp, error) { | ||
| var ( | ||
| AccountIDMap = make(map[int64]struct{}) | ||
| installationsIDToInstallation = make(map[int64]*github.Installation) | ||
| AccountNameMap = make(map[string]struct{}) | ||
| page = 0 | ||
| ) | ||
| for { | ||
| installations, resp, err := c.Apps.ListInstallations(ctx, &github.ListOptions{Page: page}) | ||
| if err != nil { | ||
| return getAllInstallationsResp{}, fmt.Errorf("github-connector: failed to retrieve org: %w", err) | ||
| } | ||
| if resp.StatusCode == http.StatusUnauthorized { | ||
| return getAllInstallationsResp{}, status.Error(codes.Unauthenticated, "github token is not authorized") | ||
| } | ||
| for _, installation := range installations { | ||
| if installation.GetAccount().GetType() != "Organization" { | ||
| continue | ||
| } | ||
| installationsIDToInstallation[installation.GetID()] = installation | ||
| AccountIDMap[installation.GetAccount().GetID()] = struct{}{} | ||
| AccountNameMap[installation.GetAccount().GetLogin()] = struct{}{} | ||
| } | ||
|
|
||
| if resp.NextPage == 0 { | ||
| break | ||
| } | ||
| page = resp.NextPage | ||
| } | ||
| return getAllInstallationsResp{ | ||
| installationIDs: installationsIDToInstallation, | ||
| accountIDs: AccountIDMap, | ||
| accountNames: AccountNameMap, | ||
| }, nil | ||
| } | ||
|
|
||
| // newGitHubClient returns a new GitHub API client authenticated with an access token via oauth2. | ||
| func newGitHubClient(ctx context.Context, instanceURL string, accessToken string) (*github.Client, error) { | ||
| httpClient, err := uhttp.NewClient(ctx, uhttp.WithLogger(true, ctxzap.Extract(ctx))) | ||
|
|
@@ -157,6 +234,19 @@ func newGitHubClient(ctx context.Context, instanceURL string, accessToken string | |
|
|
||
| // New returns the GitHub connector configured to sync against the instance URL. | ||
| func New(ctx context.Context, ghc *cfg.Github) (*GitHub, error) { | ||
| if ghc.Token == "" { | ||
| app, err := newAppClient(ctx, ghc) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &GitHub{ | ||
| instanceURL: ghc.InstanceUrl, | ||
| orgs: ghc.Orgs, | ||
| app: app, | ||
| orgCache: newOrgNameCache(nil, app.appInstallationClient), | ||
| }, nil | ||
| } | ||
|
|
||
| client, err := newGitHubClient(ctx, ghc.InstanceUrl, ghc.Token) | ||
| if err != nil { | ||
| return nil, err | ||
|
|
@@ -170,12 +260,56 @@ func New(ctx context.Context, ghc *cfg.Github) (*GitHub, error) { | |
| instanceURL: ghc.InstanceUrl, | ||
| orgs: ghc.Orgs, | ||
| graphqlClient: graphqlClient, | ||
| orgCache: newOrgNameCache(client), | ||
| orgCache: newOrgNameCache(client, nil), | ||
| } | ||
|
|
||
| return gh, nil | ||
| } | ||
|
|
||
| func newAppClient(ctx context.Context, ghc *cfg.Github) (gitHubApp, error) { | ||
| key, err := loadPrivateKeyFromString(ghc.AppPrivatekey) | ||
| if err != nil { | ||
| return gitHubApp{}, err | ||
| } | ||
| now := time.Now() | ||
| token, err := jwtv5.NewWithClaims(jwtv5.SigningMethodRS256, jwtv5.MapClaims{ | ||
| "iat": now.Unix() - 60, // issued at | ||
| "exp": now.Add(time.Minute * 10).Unix(), // expires | ||
| "iss": ghc.AppId, // GitHub App ID | ||
| }).SignedString(key) | ||
| if err != nil { | ||
| return gitHubApp{}, err | ||
| } | ||
|
|
||
| client, err := newGitHubClient(ctx, ghc.InstanceUrl, token) | ||
| if err != nil { | ||
| return gitHubApp{}, err | ||
| } | ||
|
|
||
| iResp, err := getAllInstallations(ctx, client) | ||
| if err != nil { | ||
| return gitHubApp{}, err | ||
| } | ||
|
|
||
| var ( | ||
| installationsClient = make(map[int64]*github.Client, len(iResp.installationIDs)) | ||
| installationsGLClient = make(map[int64]*githubv4.Client, len(iResp.accountIDs)) | ||
| ) | ||
| for id, installation := range iResp.installationIDs { | ||
| c, glc, err := getInstallationClient(ctx, ghc.InstanceUrl, id, token) | ||
| if err != nil { | ||
| return gitHubApp{}, err | ||
| } | ||
| installationsClient[installation.GetAccount().GetID()] = c | ||
| installationsGLClient[installation.GetAccount().GetID()] = glc | ||
| } | ||
| return gitHubApp{ | ||
| appJWTClient: client, | ||
| appInstallationClient: installationsClient, | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if many organizations are using the same app, they should have different tokens and clients. |
||
| graphqlClient: installationsGLClient, | ||
| }, nil | ||
| } | ||
|
|
||
| func newGitHubGraphqlClient(ctx context.Context, instanceURL string, accessToken string) (*githubv4.Client, error) { | ||
| httpClient, err := uhttp.NewClient(ctx, uhttp.WithLogger(true, ctxzap.Extract(ctx))) | ||
| if err != nil { | ||
|
|
@@ -203,3 +337,62 @@ func newGitHubGraphqlClient(ctx context.Context, instanceURL string, accessToken | |
|
|
||
| return githubv4.NewClient(tc), nil | ||
| } | ||
|
|
||
| func loadPrivateKeyFromString(p string) (*rsa.PrivateKey, error) { | ||
| block, _ := pem.Decode([]byte(p)) | ||
| if block == nil || (block.Type != "PRIVATE KEY" && block.Type != "RSA PRIVATE KEY") { | ||
| return nil, errors.New("invalid private key PEM format") | ||
| } | ||
|
|
||
| // PKCS8 format | ||
| if block.Type == "PRIVATE KEY" { | ||
| key, err := x509.ParsePKCS8PrivateKey(block.Bytes) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| rsaKey, ok := key.(*rsa.PrivateKey) | ||
| if !ok { | ||
| return nil, errors.New("not an RSA private key") | ||
| } | ||
| return rsaKey, nil | ||
| } | ||
|
|
||
| // PKCS1 format | ||
| return x509.ParsePKCS1PrivateKey(block.Bytes) | ||
| } | ||
|
|
||
| func getInstallationClient(ctx context.Context, instanceURL string, orgId int64, jwtToken string) (*github.Client, *githubv4.Client, error) { | ||
| url := fmt.Sprintf("https://api.github.com/app/installations/%d/access_tokens", orgId) | ||
| req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) | ||
| req.Header.Set("Authorization", "Bearer "+jwtToken) | ||
| req.Header.Set("Accept", "application/vnd.github+json") | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusCreated { | ||
| body, _ := io.ReadAll(resp.Body) | ||
| return nil, nil, fmt.Errorf("GitHub API error: %s", body) | ||
| } | ||
|
|
||
| var result struct { | ||
| Token string `json:"token"` | ||
| } | ||
| err = json.NewDecoder(resp.Body).Decode(&result) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
|
|
||
| client, err := newGitHubClient(ctx, instanceURL, result.Token) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| gcclient, err := newGitHubGraphqlClient(ctx, instanceURL, result.Token) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| return client, gcclient, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we might want to have it use the file instead of taking it as a string