1// Copyright 2014 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package google
6
7import (
8	"encoding/json"
9	"errors"
10	"fmt"
11	"strings"
12	"time"
13
14	"cloud.google.com/go/compute/metadata"
15	"golang.org/x/net/context"
16	"golang.org/x/oauth2"
17	"golang.org/x/oauth2/jwt"
18)
19
20// Endpoint is Google's OAuth 2.0 endpoint.
21var Endpoint = oauth2.Endpoint{
22	AuthURL:  "https://accounts.google.com/o/oauth2/auth",
23	TokenURL: "https://accounts.google.com/o/oauth2/token",
24}
25
26// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow.
27const JWTTokenURL = "https://accounts.google.com/o/oauth2/token"
28
29// ConfigFromJSON uses a Google Developers Console client_credentials.json
30// file to construct a config.
31// client_credentials.json can be downloaded from
32// https://console.developers.google.com, under "Credentials". Download the Web
33// application credentials in the JSON format and provide the contents of the
34// file as jsonKey.
35func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) {
36	type cred struct {
37		ClientID     string   `json:"client_id"`
38		ClientSecret string   `json:"client_secret"`
39		RedirectURIs []string `json:"redirect_uris"`
40		AuthURI      string   `json:"auth_uri"`
41		TokenURI     string   `json:"token_uri"`
42	}
43	var j struct {
44		Web       *cred `json:"web"`
45		Installed *cred `json:"installed"`
46	}
47	if err := json.Unmarshal(jsonKey, &j); err != nil {
48		return nil, err
49	}
50	var c *cred
51	switch {
52	case j.Web != nil:
53		c = j.Web
54	case j.Installed != nil:
55		c = j.Installed
56	default:
57		return nil, fmt.Errorf("oauth2/google: no credentials found")
58	}
59	if len(c.RedirectURIs) < 1 {
60		return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json")
61	}
62	return &oauth2.Config{
63		ClientID:     c.ClientID,
64		ClientSecret: c.ClientSecret,
65		RedirectURL:  c.RedirectURIs[0],
66		Scopes:       scope,
67		Endpoint: oauth2.Endpoint{
68			AuthURL:  c.AuthURI,
69			TokenURL: c.TokenURI,
70		},
71	}, nil
72}
73
74// JWTConfigFromJSON uses a Google Developers service account JSON key file to read
75// the credentials that authorize and authenticate the requests.
76// Create a service account on "Credentials" for your project at
77// https://console.developers.google.com to download a JSON key file.
78func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
79	var f credentialsFile
80	if err := json.Unmarshal(jsonKey, &f); err != nil {
81		return nil, err
82	}
83	if f.Type != serviceAccountKey {
84		return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey)
85	}
86	scope = append([]string(nil), scope...) // copy
87	return f.jwtConfig(scope), nil
88}
89
90// JSON key file types.
91const (
92	serviceAccountKey  = "service_account"
93	userCredentialsKey = "authorized_user"
94)
95
96// credentialsFile is the unmarshalled representation of a credentials file.
97type credentialsFile struct {
98	Type string `json:"type"` // serviceAccountKey or userCredentialsKey
99
100	// Service Account fields
101	ClientEmail  string `json:"client_email"`
102	PrivateKeyID string `json:"private_key_id"`
103	PrivateKey   string `json:"private_key"`
104	TokenURL     string `json:"token_uri"`
105	ProjectID    string `json:"project_id"`
106
107	// User Credential fields
108	// (These typically come from gcloud auth.)
109	ClientSecret string `json:"client_secret"`
110	ClientID     string `json:"client_id"`
111	RefreshToken string `json:"refresh_token"`
112}
113
114func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config {
115	cfg := &jwt.Config{
116		Email:        f.ClientEmail,
117		PrivateKey:   []byte(f.PrivateKey),
118		PrivateKeyID: f.PrivateKeyID,
119		Scopes:       scopes,
120		TokenURL:     f.TokenURL,
121	}
122	if cfg.TokenURL == "" {
123		cfg.TokenURL = JWTTokenURL
124	}
125	return cfg
126}
127
128func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oauth2.TokenSource, error) {
129	switch f.Type {
130	case serviceAccountKey:
131		cfg := f.jwtConfig(scopes)
132		return cfg.TokenSource(ctx), nil
133	case userCredentialsKey:
134		cfg := &oauth2.Config{
135			ClientID:     f.ClientID,
136			ClientSecret: f.ClientSecret,
137			Scopes:       scopes,
138			Endpoint:     Endpoint,
139		}
140		tok := &oauth2.Token{RefreshToken: f.RefreshToken}
141		return cfg.TokenSource(ctx, tok), nil
142	case "":
143		return nil, errors.New("missing 'type' field in credentials")
144	default:
145		return nil, fmt.Errorf("unknown credential type: %q", f.Type)
146	}
147}
148
149// ComputeTokenSource returns a token source that fetches access tokens
150// from Google Compute Engine (GCE)'s metadata server. It's only valid to use
151// this token source if your program is running on a GCE instance.
152// If no account is specified, "default" is used.
153// Further information about retrieving access tokens from the GCE metadata
154// server can be found at https://cloud.google.com/compute/docs/authentication.
155func ComputeTokenSource(account string) oauth2.TokenSource {
156	return oauth2.ReuseTokenSource(nil, computeSource{account: account})
157}
158
159type computeSource struct {
160	account string
161}
162
163func (cs computeSource) Token() (*oauth2.Token, error) {
164	if !metadata.OnGCE() {
165		return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE")
166	}
167	acct := cs.account
168	if acct == "" {
169		acct = "default"
170	}
171	tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token")
172	if err != nil {
173		return nil, err
174	}
175	var res struct {
176		AccessToken  string `json:"access_token"`
177		ExpiresInSec int    `json:"expires_in"`
178		TokenType    string `json:"token_type"`
179	}
180	err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
181	if err != nil {
182		return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err)
183	}
184	if res.ExpiresInSec == 0 || res.AccessToken == "" {
185		return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata")
186	}
187	return &oauth2.Token{
188		AccessToken: res.AccessToken,
189		TokenType:   res.TokenType,
190		Expiry:      time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
191	}, nil
192}
193