-
Notifications
You must be signed in to change notification settings - Fork 737
feat(github): add support for refresh tokens and token management #8667
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
Changes from 1 commit
dff9b6a
8f68983
9deb463
cb79908
fa99f08
ef6b168
b304afa
7552742
e1d9d1e
ee306d7
8a8b678
eca3279
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -56,6 +56,21 @@ type GithubConn struct { | |
| helper.MultiAuth `mapstructure:",squash"` | ||
| GithubAccessToken `mapstructure:",squash" authMethod:"AccessToken"` | ||
| GithubAppKey `mapstructure:",squash" authMethod:"AppKey"` | ||
| RefreshToken string `mapstructure:"refreshToken" json:"refreshToken" gorm:"type:text;serializer:encdec"` | ||
| TokenExpiresAt time.Time `mapstructure:"tokenExpiresAt" json:"tokenExpiresAt"` | ||
| RefreshTokenExpiresAt time.Time `mapstructure:"refreshTokenExpiresAt" json:"refreshTokenExpiresAt"` | ||
| } | ||
|
|
||
| // UpdateToken updates the token and refresh token information | ||
| func (conn *GithubConn) UpdateToken(newToken, newRefreshToken string, expiry, refreshExpiry time.Time) { | ||
| conn.Token = newToken | ||
| conn.RefreshToken = newRefreshToken | ||
| conn.TokenExpiresAt = expiry | ||
| conn.RefreshTokenExpiresAt = refreshExpiry | ||
|
|
||
| // Update the internal tokens slice used by SetupAuthentication | ||
| conn.tokens = []string{newToken} | ||
| conn.tokenIndex = 0 | ||
|
Comment on lines
+71
to
+73
|
||
| } | ||
|
Comment on lines
+65
to
74
|
||
|
|
||
| // PrepareApiClient splits Token to tokens for SetupAuthentication to utilize | ||
|
|
@@ -249,7 +264,7 @@ func (conn *GithubConn) typeIs(token string) string { | |
| // total len is 40, {prefix}{showPrefix}{secret}{showSuffix} | ||
| // fine-grained tokens | ||
| // github_pat_{82_characters} | ||
| classicalTokenClassicalPrefixes := []string{"ghp_", "gho_", "ghs_", "ghr_"} | ||
| classicalTokenClassicalPrefixes := []string{"ghp_", "gho_", "ghs_", "ghr_", "ghu_"} | ||
| classicalTokenFindGrainedPrefixes := []string{"github_pat_"} | ||
| for _, prefix := range classicalTokenClassicalPrefixes { | ||
| if strings.HasPrefix(token, prefix) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| /* | ||
| Licensed to the Apache Software Foundation (ASF) under one or more | ||
| contributor license agreements. See the NOTICE file distributed with | ||
| this work for additional information regarding copyright ownership. | ||
| The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| (the "License"); you may not use this file except in compliance with | ||
| the License. You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package migrationscripts | ||
|
|
||
| import ( | ||
| "github.com/apache/incubator-devlake/core/context" | ||
| "github.com/apache/incubator-devlake/core/errors" | ||
| "github.com/apache/incubator-devlake/helpers/migrationhelper" | ||
| "github.com/apache/incubator-devlake/plugins/github/models" | ||
| ) | ||
|
|
||
| type addRefreshTokenFields struct{} | ||
|
|
||
| func (*addRefreshTokenFields) Up(basicRes context.BasicRes) errors.Error { | ||
| return migrationhelper.AutoMigrateTables( | ||
| basicRes, | ||
| &models.GithubConnection{}, | ||
| ) | ||
| } | ||
|
|
||
| func (*addRefreshTokenFields) Version() uint64 { | ||
| return 20241120000001 | ||
| } | ||
|
|
||
| func (*addRefreshTokenFields) Name() string { | ||
| return "add refresh token fields to github_connections" | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ import ( | |
| "github.com/apache/incubator-devlake/core/plugin" | ||
| "github.com/apache/incubator-devlake/helpers/pluginhelper/api" | ||
| "github.com/apache/incubator-devlake/plugins/github/models" | ||
| "github.com/apache/incubator-devlake/plugins/github/token" | ||
| ) | ||
|
|
||
| func CreateApiClient(taskCtx plugin.TaskContext, connection *models.GithubConnection) (*api.ApiAsyncClient, errors.Error) { | ||
|
|
@@ -34,6 +35,24 @@ func CreateApiClient(taskCtx plugin.TaskContext, connection *models.GithubConnec | |
| return nil, err | ||
| } | ||
|
|
||
| // Inject TokenProvider if refresh token is present | ||
| if connection.RefreshToken != "" { | ||
| logger := taskCtx.GetLogger() | ||
| db := taskCtx.GetDal() | ||
|
|
||
| // Create TokenProvider | ||
| tp := token.NewTokenProvider(connection, db, apiClient.GetClient(), logger) | ||
|
|
||
| // Wrap the transport | ||
| baseTransport := apiClient.GetClient().Transport | ||
| if baseTransport == nil { | ||
| baseTransport = http.DefaultTransport | ||
| } | ||
|
|
||
| rt := token.NewRefreshRoundTripper(baseTransport, tp) | ||
| apiClient.GetClient().Transport = rt | ||
| } | ||
|
Comment on lines
+38
to
+54
|
||
|
|
||
| // create rate limit calculator | ||
| rateLimiter := &api.ApiRateLimitCalculator{ | ||
| UserRateLimitPerHour: connection.RateLimitPerHour, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /* | ||
| Licensed to the Apache Software Foundation (ASF) under one or more | ||
| contributor license agreements. See the NOTICE file distributed with | ||
| this work for additional information regarding copyright ownership. | ||
| The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| (the "License"); you may not use this file except in compliance with | ||
| the License. You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package token | ||
|
|
||
| import ( | ||
| "net/http" | ||
| ) | ||
|
|
||
| type RefreshRoundTripper struct { | ||
| base http.RoundTripper | ||
| tokenProvider *TokenProvider | ||
| } | ||
|
|
||
|
ysinghc marked this conversation as resolved.
|
||
| func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshRoundTripper { | ||
| return &RefreshRoundTripper{ | ||
| base: base, | ||
| tokenProvider: tp, | ||
| } | ||
| } | ||
|
Comment on lines
+29
to
+39
|
||
|
|
||
| func (rt *RefreshRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { | ||
| // Get token | ||
| token, err := rt.tokenProvider.GetToken() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Clone request before modifying | ||
| reqClone := req.Clone(req.Context()) | ||
|
||
| reqClone.Header.Set("Authorization", "Bearer "+token) | ||
|
|
||
| // Execute request | ||
| resp, reqErr := rt.base.RoundTrip(reqClone) | ||
| if reqErr != nil { | ||
| return nil, reqErr | ||
| } | ||
|
|
||
| // Reactive refresh on 401 | ||
| if resp.StatusCode == http.StatusUnauthorized { | ||
| // Close previous response body | ||
| resp.Body.Close() | ||
|
|
||
| // Force refresh | ||
| if err := rt.tokenProvider.ForceRefresh(token); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Get new token | ||
| newToken, err := rt.tokenProvider.GetToken() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Retry request with new token | ||
| reqRetry := req.Clone(req.Context()) | ||
|
||
| reqRetry.Header.Set("Authorization", "Bearer "+newToken) | ||
| return rt.base.RoundTrip(reqRetry) | ||
|
ysinghc marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| return resp, nil | ||
| } | ||
|
ysinghc marked this conversation as resolved.
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,171 @@ | ||||||||||||
| /* | ||||||||||||
| Licensed to the Apache Software Foundation (ASF) under one or more | ||||||||||||
| contributor license agreements. See the NOTICE file distributed with | ||||||||||||
| this work for additional information regarding copyright ownership. | ||||||||||||
| The ASF licenses this file to You under the Apache License, Version 2.0 | ||||||||||||
| (the "License"); you may not use this file except in compliance with | ||||||||||||
| the License. You may obtain a copy of the License at | ||||||||||||
|
|
||||||||||||
| http://www.apache.org/licenses/LICENSE-2.0 | ||||||||||||
|
|
||||||||||||
| Unless required by applicable law or agreed to in writing, software | ||||||||||||
| distributed under the License is distributed on an "AS IS" BASIS, | ||||||||||||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||||||||
| See the License for the specific language governing permissions and | ||||||||||||
| limitations under the License. | ||||||||||||
| */ | ||||||||||||
|
|
||||||||||||
| package token | ||||||||||||
|
|
||||||||||||
| import ( | ||||||||||||
| "bytes" | ||||||||||||
| "context" | ||||||||||||
| "encoding/json" | ||||||||||||
| "fmt" | ||||||||||||
| "io" | ||||||||||||
| "net/http" | ||||||||||||
| "os" | ||||||||||||
| "strconv" | ||||||||||||
| "sync" | ||||||||||||
| "time" | ||||||||||||
|
|
||||||||||||
| "github.com/apache/incubator-devlake/core/dal" | ||||||||||||
| "github.com/apache/incubator-devlake/core/errors" | ||||||||||||
| "github.com/apache/incubator-devlake/core/log" | ||||||||||||
| "github.com/apache/incubator-devlake/plugins/github/models" | ||||||||||||
| ) | ||||||||||||
|
|
||||||||||||
| const ( | ||||||||||||
| DefaultRefreshBuffer = 5 * time.Minute | ||||||||||||
| ) | ||||||||||||
|
|
||||||||||||
|
ysinghc marked this conversation as resolved.
|
||||||||||||
| type TokenProvider struct { | ||||||||||||
| conn *models.GithubConnection | ||||||||||||
| dal dal.Dal | ||||||||||||
| httpClient *http.Client | ||||||||||||
| logger log.Logger | ||||||||||||
| mu sync.Mutex | ||||||||||||
| refreshURL string | ||||||||||||
| } | ||||||||||||
|
ysinghc marked this conversation as resolved.
|
||||||||||||
|
|
||||||||||||
|
ysinghc marked this conversation as resolved.
|
||||||||||||
| func NewTokenProvider(conn *models.GithubConnection, d dal.Dal, client *http.Client, logger log.Logger) *TokenProvider { | ||||||||||||
| return &TokenProvider{ | ||||||||||||
| conn: conn, | ||||||||||||
| dal: d, | ||||||||||||
| httpClient: client, | ||||||||||||
| logger: logger, | ||||||||||||
| refreshURL: "https://github.com/login/oauth/access_token", | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
|
ysinghc marked this conversation as resolved.
|
||||||||||||
| func (tp *TokenProvider) GetToken() (string, errors.Error) { | ||||||||||||
| tp.mu.Lock() | ||||||||||||
| defer tp.mu.Unlock() | ||||||||||||
|
|
||||||||||||
| if tp.needsRefresh() { | ||||||||||||
| if err := tp.refreshToken(); err != nil { | ||||||||||||
| return "", err | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
| return tp.conn.Token, nil | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| func (tp *TokenProvider) needsRefresh() bool { | ||||||||||||
| if tp.conn.RefreshToken == "" { | ||||||||||||
| return false | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| buffer := DefaultRefreshBuffer | ||||||||||||
| if envBuffer := os.Getenv("GITHUB_TOKEN_REFRESH_BUFFER_MINUTES"); envBuffer != "" { | ||||||||||||
| if val, err := strconv.Atoi(envBuffer); err == nil { | ||||||||||||
| buffer = time.Duration(val) * time.Minute | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
|
Comment on lines
+80
to
+85
|
||||||||||||
|
|
||||||||||||
| return time.Now().Add(buffer).After(tp.conn.TokenExpiresAt) | ||||||||||||
| } | ||||||||||||
|
Comment on lines
+75
to
+88
|
||||||||||||
|
|
||||||||||||
| func (tp *TokenProvider) refreshToken() errors.Error { | ||||||||||||
| tp.logger.Info("Refreshing GitHub token for connection %d", tp.conn.ID) | ||||||||||||
|
|
||||||||||||
| data := map[string]string{ | ||||||||||||
| "refresh_token": tp.conn.RefreshToken, | ||||||||||||
| "grant_type": "refresh_token", | ||||||||||||
| "client_id": tp.conn.AppId, | ||||||||||||
| "client_secret": tp.conn.SecretKey, | ||||||||||||
| } | ||||||||||||
|
Comment on lines
+93
to
+98
|
||||||||||||
| jsonData, _ := json.Marshal(data) | ||||||||||||
|
||||||||||||
| jsonData, _ := json.Marshal(data) | |
| jsonData, err := json.Marshal(data) | |
| if err != nil { | |
| return errors.Convert(err) | |
| } |
Uh oh!
There was an error while loading. Please reload this page.