refactor: make impersonateTokenSource struct public

to impersonate the service account from the JSON config file, the existing impersonation mechanism can be reused.

Updates #515
This commit is contained in:
guillaume blaquiere 2021-08-23 10:52:40 +02:00
parent a3dd13af1f
commit 121de73b38
2 changed files with 15 additions and 15 deletions

View File

@ -124,11 +124,11 @@ func (c *Config) tokenSource(ctx context.Context, tokenURLValidPats []*regexp.Re
} }
scopes := c.Scopes scopes := c.Scopes
ts.conf.Scopes = []string{"https://www.googleapis.com/auth/cloud-platform"} ts.conf.Scopes = []string{"https://www.googleapis.com/auth/cloud-platform"}
imp := impersonateTokenSource{ imp := ImpersonateTokenSource{
ctx: ctx, Ctx: ctx,
url: c.ServiceAccountImpersonationURL, Url: c.ServiceAccountImpersonationURL,
scopes: scopes, Scopes: scopes,
ts: oauth2.ReuseTokenSource(nil, ts), Ts: oauth2.ReuseTokenSource(nil, ts),
} }
return oauth2.ReuseTokenSource(nil, imp), nil return oauth2.ReuseTokenSource(nil, imp), nil
} }

View File

@ -29,30 +29,30 @@ type impersonateTokenResponse struct {
ExpireTime string `json:"expireTime"` ExpireTime string `json:"expireTime"`
} }
type impersonateTokenSource struct { type ImpersonateTokenSource struct {
ctx context.Context Ctx context.Context
ts oauth2.TokenSource Ts oauth2.TokenSource
url string Url string
scopes []string Scopes []string
} }
// Token performs the exchange to get a temporary service account token to allow access to GCP. // Token performs the exchange to get a temporary service account token to allow access to GCP.
func (its impersonateTokenSource) Token() (*oauth2.Token, error) { func (its ImpersonateTokenSource) Token() (*oauth2.Token, error) {
reqBody := generateAccessTokenReq{ reqBody := generateAccessTokenReq{
Lifetime: "3600s", Lifetime: "3600s",
Scope: its.scopes, Scope: its.Scopes,
} }
b, err := json.Marshal(reqBody) b, err := json.Marshal(reqBody)
if err != nil { if err != nil {
return nil, fmt.Errorf("oauth2/google: unable to marshal request: %v", err) return nil, fmt.Errorf("oauth2/google: unable to marshal request: %v", err)
} }
client := oauth2.NewClient(its.ctx, its.ts) client := oauth2.NewClient(its.Ctx, its.Ts)
req, err := http.NewRequest("POST", its.url, bytes.NewReader(b)) req, err := http.NewRequest("POST", its.Url, bytes.NewReader(b))
if err != nil { if err != nil {
return nil, fmt.Errorf("oauth2/google: unable to create impersonation request: %v", err) return nil, fmt.Errorf("oauth2/google: unable to create impersonation request: %v", err)
} }
req = req.WithContext(its.ctx) req = req.WithContext(its.Ctx)
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req) resp, err := client.Do(req)