2015-08-27 03:42:02 +03:00
|
|
|
// Copyright 2014 The Go Authors. All rights reserved.
|
2014-05-17 19:26:57 +04:00
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2014-05-13 22:06:46 +04:00
|
|
|
|
2018-03-09 16:25:59 +03:00
|
|
|
package google
|
2014-05-06 01:54:23 +04:00
|
|
|
|
|
|
|
import (
|
2018-11-01 18:53:36 +03:00
|
|
|
"context"
|
2014-05-11 19:06:03 +04:00
|
|
|
"encoding/json"
|
2015-01-06 22:34:34 +03:00
|
|
|
"errors"
|
2014-10-23 21:06:00 +04:00
|
|
|
"fmt"
|
2019-03-30 01:47:46 +03:00
|
|
|
"net/url"
|
2015-01-06 22:34:34 +03:00
|
|
|
"strings"
|
2014-05-11 19:06:03 +04:00
|
|
|
"time"
|
|
|
|
|
2016-07-31 01:43:56 +03:00
|
|
|
"cloud.google.com/go/compute/metadata"
|
2014-11-26 22:44:45 +03:00
|
|
|
"golang.org/x/oauth2"
|
2021-01-12 22:45:47 +03:00
|
|
|
"golang.org/x/oauth2/google/internal/externalaccount"
|
2023-09-29 01:05:58 +03:00
|
|
|
"golang.org/x/oauth2/google/internal/externalaccountauthorizeduser"
|
2014-12-31 02:11:02 +03:00
|
|
|
"golang.org/x/oauth2/jwt"
|
2014-05-06 01:54:23 +04:00
|
|
|
)
|
|
|
|
|
2021-04-27 18:31:33 +03:00
|
|
|
// Endpoint is Google's OAuth 2.0 default endpoint.
|
2014-12-11 10:30:13 +03:00
|
|
|
var Endpoint = oauth2.Endpoint{
|
2023-09-28 21:46:05 +03:00
|
|
|
AuthURL: "https://accounts.google.com/o/oauth2/auth",
|
|
|
|
TokenURL: "https://oauth2.googleapis.com/token",
|
2023-09-06 09:37:54 +03:00
|
|
|
DeviceAuthURL: "https://oauth2.googleapis.com/device/code",
|
2023-09-28 21:46:05 +03:00
|
|
|
AuthStyle: oauth2.AuthStyleInParams,
|
2014-12-11 10:30:13 +03:00
|
|
|
}
|
|
|
|
|
2023-03-02 20:40:29 +03:00
|
|
|
// MTLSTokenURL is Google's OAuth 2.0 default mTLS endpoint.
|
|
|
|
const MTLSTokenURL = "https://oauth2.mtls.googleapis.com/token"
|
|
|
|
|
2014-12-11 10:30:13 +03:00
|
|
|
// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow.
|
2018-09-19 21:11:46 +03:00
|
|
|
const JWTTokenURL = "https://oauth2.googleapis.com/token"
|
2014-12-11 10:30:13 +03:00
|
|
|
|
2015-02-26 08:39:41 +03:00
|
|
|
// ConfigFromJSON uses a Google Developers Console client_credentials.json
|
2015-02-17 23:48:56 +03:00
|
|
|
// file to construct a config.
|
2016-05-02 21:01:36 +03:00
|
|
|
// client_credentials.json can be downloaded from
|
|
|
|
// https://console.developers.google.com, under "Credentials". Download the Web
|
|
|
|
// application credentials in the JSON format and provide the contents of the
|
|
|
|
// file as jsonKey.
|
2015-02-17 23:48:56 +03:00
|
|
|
func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) {
|
2015-03-10 02:33:51 +03:00
|
|
|
type cred struct {
|
|
|
|
ClientID string `json:"client_id"`
|
|
|
|
ClientSecret string `json:"client_secret"`
|
|
|
|
RedirectURIs []string `json:"redirect_uris"`
|
|
|
|
AuthURI string `json:"auth_uri"`
|
|
|
|
TokenURI string `json:"token_uri"`
|
|
|
|
}
|
2015-02-17 23:48:56 +03:00
|
|
|
var j struct {
|
2015-03-10 02:33:51 +03:00
|
|
|
Web *cred `json:"web"`
|
|
|
|
Installed *cred `json:"installed"`
|
2015-02-17 23:48:56 +03:00
|
|
|
}
|
|
|
|
if err := json.Unmarshal(jsonKey, &j); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-03-10 02:33:51 +03:00
|
|
|
var c *cred
|
|
|
|
switch {
|
|
|
|
case j.Web != nil:
|
|
|
|
c = j.Web
|
|
|
|
case j.Installed != nil:
|
|
|
|
c = j.Installed
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("oauth2/google: no credentials found")
|
|
|
|
}
|
|
|
|
if len(c.RedirectURIs) < 1 {
|
2015-02-17 23:48:56 +03:00
|
|
|
return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json")
|
|
|
|
}
|
|
|
|
return &oauth2.Config{
|
2015-03-10 02:33:51 +03:00
|
|
|
ClientID: c.ClientID,
|
|
|
|
ClientSecret: c.ClientSecret,
|
|
|
|
RedirectURL: c.RedirectURIs[0],
|
2015-02-17 23:48:56 +03:00
|
|
|
Scopes: scope,
|
|
|
|
Endpoint: oauth2.Endpoint{
|
2015-03-10 02:33:51 +03:00
|
|
|
AuthURL: c.AuthURI,
|
|
|
|
TokenURL: c.TokenURI,
|
2015-02-17 23:48:56 +03:00
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2014-12-11 10:30:13 +03:00
|
|
|
// JWTConfigFromJSON uses a Google Developers service account JSON key file to read
|
|
|
|
// the credentials that authorize and authenticate the requests.
|
2016-05-02 21:01:36 +03:00
|
|
|
// Create a service account on "Credentials" for your project at
|
|
|
|
// https://console.developers.google.com to download a JSON key file.
|
2015-01-14 02:27:09 +03:00
|
|
|
func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
|
2016-11-04 01:50:36 +03:00
|
|
|
var f credentialsFile
|
|
|
|
if err := json.Unmarshal(jsonKey, &f); err != nil {
|
2014-12-11 10:30:13 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
2016-11-04 01:50:36 +03:00
|
|
|
if f.Type != serviceAccountKey {
|
|
|
|
return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey)
|
2016-09-02 07:31:05 +03:00
|
|
|
}
|
2016-11-04 01:50:36 +03:00
|
|
|
scope = append([]string(nil), scope...) // copy
|
2021-04-27 18:31:33 +03:00
|
|
|
return f.jwtConfig(scope, ""), nil
|
2016-11-04 01:50:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// JSON key file types.
|
|
|
|
const (
|
2023-09-29 01:05:58 +03:00
|
|
|
serviceAccountKey = "service_account"
|
|
|
|
userCredentialsKey = "authorized_user"
|
|
|
|
externalAccountKey = "external_account"
|
|
|
|
externalAccountAuthorizedUserKey = "external_account_authorized_user"
|
|
|
|
impersonatedServiceAccount = "impersonated_service_account"
|
2016-11-04 01:50:36 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// credentialsFile is the unmarshalled representation of a credentials file.
|
|
|
|
type credentialsFile struct {
|
2021-04-27 18:31:33 +03:00
|
|
|
Type string `json:"type"`
|
2016-11-04 01:50:36 +03:00
|
|
|
|
|
|
|
// Service Account fields
|
2023-09-28 21:46:05 +03:00
|
|
|
ClientEmail string `json:"client_email"`
|
|
|
|
PrivateKeyID string `json:"private_key_id"`
|
|
|
|
PrivateKey string `json:"private_key"`
|
|
|
|
AuthURL string `json:"auth_uri"`
|
|
|
|
TokenURL string `json:"token_uri"`
|
|
|
|
ProjectID string `json:"project_id"`
|
|
|
|
UniverseDomain string `json:"universe_domain"`
|
2016-11-04 01:50:36 +03:00
|
|
|
|
|
|
|
// User Credential fields
|
|
|
|
// (These typically come from gcloud auth.)
|
|
|
|
ClientSecret string `json:"client_secret"`
|
|
|
|
ClientID string `json:"client_id"`
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
2021-01-12 22:45:47 +03:00
|
|
|
|
|
|
|
// External Account fields
|
2021-01-13 23:38:24 +03:00
|
|
|
Audience string `json:"audience"`
|
|
|
|
SubjectTokenType string `json:"subject_token_type"`
|
|
|
|
TokenURLExternal string `json:"token_url"`
|
|
|
|
TokenInfoURL string `json:"token_info_url"`
|
|
|
|
ServiceAccountImpersonationURL string `json:"service_account_impersonation_url"`
|
2022-07-12 01:16:42 +03:00
|
|
|
ServiceAccountImpersonation serviceAccountImpersonationInfo `json:"service_account_impersonation"`
|
2021-10-28 20:47:33 +03:00
|
|
|
Delegates []string `json:"delegates"`
|
2021-01-13 23:38:24 +03:00
|
|
|
CredentialSource externalaccount.CredentialSource `json:"credential_source"`
|
|
|
|
QuotaProjectID string `json:"quota_project_id"`
|
2021-10-05 17:39:06 +03:00
|
|
|
WorkforcePoolUserProject string `json:"workforce_pool_user_project"`
|
2021-10-28 20:47:33 +03:00
|
|
|
|
2023-09-29 01:05:58 +03:00
|
|
|
// External Account Authorized User fields
|
|
|
|
RevokeURL string `json:"revoke_url"`
|
|
|
|
|
2021-10-28 20:47:33 +03:00
|
|
|
// Service account impersonation
|
|
|
|
SourceCredentials *credentialsFile `json:"source_credentials"`
|
2016-11-04 01:50:36 +03:00
|
|
|
}
|
|
|
|
|
2022-07-12 01:16:42 +03:00
|
|
|
type serviceAccountImpersonationInfo struct {
|
|
|
|
TokenLifetimeSeconds int `json:"token_lifetime_seconds"`
|
|
|
|
}
|
|
|
|
|
2021-04-27 18:31:33 +03:00
|
|
|
func (f *credentialsFile) jwtConfig(scopes []string, subject string) *jwt.Config {
|
2016-11-04 01:50:36 +03:00
|
|
|
cfg := &jwt.Config{
|
|
|
|
Email: f.ClientEmail,
|
|
|
|
PrivateKey: []byte(f.PrivateKey),
|
|
|
|
PrivateKeyID: f.PrivateKeyID,
|
|
|
|
Scopes: scopes,
|
|
|
|
TokenURL: f.TokenURL,
|
2021-04-27 18:31:33 +03:00
|
|
|
Subject: subject, // This is the user email to impersonate
|
2022-05-17 20:13:16 +03:00
|
|
|
Audience: f.Audience,
|
2016-11-04 01:50:36 +03:00
|
|
|
}
|
|
|
|
if cfg.TokenURL == "" {
|
|
|
|
cfg.TokenURL = JWTTokenURL
|
|
|
|
}
|
|
|
|
return cfg
|
|
|
|
}
|
|
|
|
|
2021-04-27 18:31:33 +03:00
|
|
|
func (f *credentialsFile) tokenSource(ctx context.Context, params CredentialsParams) (oauth2.TokenSource, error) {
|
2016-11-04 01:50:36 +03:00
|
|
|
switch f.Type {
|
|
|
|
case serviceAccountKey:
|
2021-04-27 18:31:33 +03:00
|
|
|
cfg := f.jwtConfig(params.Scopes, params.Subject)
|
2016-11-04 01:50:36 +03:00
|
|
|
return cfg.TokenSource(ctx), nil
|
|
|
|
case userCredentialsKey:
|
|
|
|
cfg := &oauth2.Config{
|
|
|
|
ClientID: f.ClientID,
|
|
|
|
ClientSecret: f.ClientSecret,
|
2021-04-27 18:31:33 +03:00
|
|
|
Scopes: params.Scopes,
|
|
|
|
Endpoint: oauth2.Endpoint{
|
|
|
|
AuthURL: f.AuthURL,
|
|
|
|
TokenURL: f.TokenURL,
|
|
|
|
AuthStyle: oauth2.AuthStyleInParams,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
if cfg.Endpoint.AuthURL == "" {
|
|
|
|
cfg.Endpoint.AuthURL = Endpoint.AuthURL
|
|
|
|
}
|
|
|
|
if cfg.Endpoint.TokenURL == "" {
|
2023-03-02 20:40:29 +03:00
|
|
|
if params.TokenURL != "" {
|
|
|
|
cfg.Endpoint.TokenURL = params.TokenURL
|
|
|
|
} else {
|
|
|
|
cfg.Endpoint.TokenURL = Endpoint.TokenURL
|
|
|
|
}
|
2016-11-04 01:50:36 +03:00
|
|
|
}
|
|
|
|
tok := &oauth2.Token{RefreshToken: f.RefreshToken}
|
|
|
|
return cfg.TokenSource(ctx, tok), nil
|
2021-01-12 22:45:47 +03:00
|
|
|
case externalAccountKey:
|
|
|
|
cfg := &externalaccount.Config{
|
2021-01-13 23:38:24 +03:00
|
|
|
Audience: f.Audience,
|
|
|
|
SubjectTokenType: f.SubjectTokenType,
|
|
|
|
TokenURL: f.TokenURLExternal,
|
|
|
|
TokenInfoURL: f.TokenInfoURL,
|
2021-01-12 22:45:47 +03:00
|
|
|
ServiceAccountImpersonationURL: f.ServiceAccountImpersonationURL,
|
2022-07-12 01:16:42 +03:00
|
|
|
ServiceAccountImpersonationLifetimeSeconds: f.ServiceAccountImpersonation.TokenLifetimeSeconds,
|
|
|
|
ClientSecret: f.ClientSecret,
|
|
|
|
ClientID: f.ClientID,
|
|
|
|
CredentialSource: f.CredentialSource,
|
|
|
|
QuotaProjectID: f.QuotaProjectID,
|
|
|
|
Scopes: params.Scopes,
|
|
|
|
WorkforcePoolUserProject: f.WorkforcePoolUserProject,
|
2021-01-12 22:45:47 +03:00
|
|
|
}
|
2021-08-13 01:59:38 +03:00
|
|
|
return cfg.TokenSource(ctx)
|
2023-09-29 01:05:58 +03:00
|
|
|
case externalAccountAuthorizedUserKey:
|
|
|
|
cfg := &externalaccountauthorizeduser.Config{
|
|
|
|
Audience: f.Audience,
|
|
|
|
RefreshToken: f.RefreshToken,
|
|
|
|
TokenURL: f.TokenURLExternal,
|
|
|
|
TokenInfoURL: f.TokenInfoURL,
|
|
|
|
ClientID: f.ClientID,
|
|
|
|
ClientSecret: f.ClientSecret,
|
|
|
|
RevokeURL: f.RevokeURL,
|
|
|
|
QuotaProjectID: f.QuotaProjectID,
|
|
|
|
Scopes: params.Scopes,
|
|
|
|
}
|
|
|
|
return cfg.TokenSource(ctx)
|
2021-10-28 20:47:33 +03:00
|
|
|
case impersonatedServiceAccount:
|
|
|
|
if f.ServiceAccountImpersonationURL == "" || f.SourceCredentials == nil {
|
|
|
|
return nil, errors.New("missing 'source_credentials' field or 'service_account_impersonation_url' in credentials")
|
|
|
|
}
|
|
|
|
|
|
|
|
ts, err := f.SourceCredentials.tokenSource(ctx, params)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
imp := externalaccount.ImpersonateTokenSource{
|
|
|
|
Ctx: ctx,
|
|
|
|
URL: f.ServiceAccountImpersonationURL,
|
|
|
|
Scopes: params.Scopes,
|
|
|
|
Ts: ts,
|
|
|
|
Delegates: f.Delegates,
|
|
|
|
}
|
|
|
|
return oauth2.ReuseTokenSource(nil, imp), nil
|
2016-11-04 01:50:36 +03:00
|
|
|
case "":
|
|
|
|
return nil, errors.New("missing 'type' field in credentials")
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unknown credential type: %q", f.Type)
|
2016-06-24 07:20:43 +03:00
|
|
|
}
|
2014-12-11 10:30:13 +03:00
|
|
|
}
|
2014-05-06 01:54:23 +04:00
|
|
|
|
2014-12-11 10:30:13 +03:00
|
|
|
// ComputeTokenSource returns a token source that fetches access tokens
|
|
|
|
// from Google Compute Engine (GCE)'s metadata server. It's only valid to use
|
|
|
|
// this token source if your program is running on a GCE instance.
|
|
|
|
// If no account is specified, "default" is used.
|
2019-03-30 01:47:46 +03:00
|
|
|
// If no scopes are specified, a set of default scopes are automatically granted.
|
2014-12-11 10:30:13 +03:00
|
|
|
// Further information about retrieving access tokens from the GCE metadata
|
|
|
|
// server can be found at https://cloud.google.com/compute/docs/authentication.
|
2019-03-30 01:47:46 +03:00
|
|
|
func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource {
|
2023-03-28 23:45:12 +03:00
|
|
|
return computeTokenSource(account, 0, scope...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func computeTokenSource(account string, earlyExpiry time.Duration, scope ...string) oauth2.TokenSource {
|
|
|
|
return oauth2.ReuseTokenSourceWithExpiry(nil, computeSource{account: account, scopes: scope}, earlyExpiry)
|
2014-09-03 22:40:47 +04:00
|
|
|
}
|
|
|
|
|
2014-12-11 10:30:13 +03:00
|
|
|
type computeSource struct {
|
|
|
|
account string
|
2019-03-30 01:47:46 +03:00
|
|
|
scopes []string
|
2014-05-10 11:41:39 +04:00
|
|
|
}
|
|
|
|
|
2015-01-06 22:34:34 +03:00
|
|
|
func (cs computeSource) Token() (*oauth2.Token, error) {
|
|
|
|
if !metadata.OnGCE() {
|
|
|
|
return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE")
|
|
|
|
}
|
2014-12-11 10:30:13 +03:00
|
|
|
acct := cs.account
|
|
|
|
if acct == "" {
|
|
|
|
acct = "default"
|
2014-09-03 01:06:51 +04:00
|
|
|
}
|
2019-03-30 01:47:46 +03:00
|
|
|
tokenURI := "instance/service-accounts/" + acct + "/token"
|
|
|
|
if len(cs.scopes) > 0 {
|
|
|
|
v := url.Values{}
|
|
|
|
v.Set("scopes", strings.Join(cs.scopes, ","))
|
|
|
|
tokenURI = tokenURI + "?" + v.Encode()
|
|
|
|
}
|
|
|
|
tokenJSON, err := metadata.Get(tokenURI)
|
2014-12-11 10:30:13 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-01-06 22:34:34 +03:00
|
|
|
var res struct {
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
ExpiresInSec int `json:"expires_in"`
|
|
|
|
TokenType string `json:"token_type"`
|
2014-12-11 10:30:13 +03:00
|
|
|
}
|
2015-01-06 22:34:34 +03:00
|
|
|
err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
|
2014-12-11 10:30:13 +03:00
|
|
|
if err != nil {
|
2015-01-06 22:34:34 +03:00
|
|
|
return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err)
|
|
|
|
}
|
|
|
|
if res.ExpiresInSec == 0 || res.AccessToken == "" {
|
|
|
|
return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata")
|
2014-09-03 01:06:51 +04:00
|
|
|
}
|
2019-05-08 02:52:07 +03:00
|
|
|
tok := &oauth2.Token{
|
2015-01-06 22:34:34 +03:00
|
|
|
AccessToken: res.AccessToken,
|
|
|
|
TokenType: res.TokenType,
|
|
|
|
Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
|
2019-05-08 02:52:07 +03:00
|
|
|
}
|
|
|
|
// NOTE(cbro): add hidden metadata about where the token is from.
|
|
|
|
// This is needed for detection by client libraries to know that credentials come from the metadata server.
|
|
|
|
// This may be removed in a future version of this library.
|
|
|
|
return tok.WithExtra(map[string]interface{}{
|
|
|
|
"oauth2.google.tokenSource": "compute-metadata",
|
|
|
|
"oauth2.google.serviceAccount": acct,
|
|
|
|
}), nil
|
2014-09-03 01:06:51 +04:00
|
|
|
}
|