-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gcpauth.go
78 lines (65 loc) 路 2.29 KB
/
gcpauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package filestate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"golang.org/x/oauth2/google"
"gocloud.dev/blob/gcsblob"
"cloud.google.com/go/storage"
"gocloud.dev/blob"
"gocloud.dev/gcp"
)
type GoogleCredentials struct {
PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
}
func googleCredentials(ctx context.Context) (*google.Credentials, error) {
// GOOGLE_CREDENTIALS aren't part of the gcloud standard authorization variables
// but the GCP terraform provider uses this variable to allow users to authenticate
// with the contents of a credentials.json file instead of just a file path.
// https://www.terraform.io/docs/backends/types/gcs.html
if creds := os.Getenv("GOOGLE_CREDENTIALS"); creds != "" {
// We try $GOOGLE_CREDENTIALS before gcp.DefaultCredentials
// so that users can override the default creds
credentials, err := google.CredentialsFromJSON(ctx, []byte(creds), storage.ScopeReadWrite)
if err != nil {
return nil, fmt.Errorf("unable to parse credentials from $GOOGLE_CREDENTIALS: %w", err)
}
return credentials, nil
}
// DefaultCredentials will attempt to load creds in the following order:
// 1. a file located at $GOOGLE_APPLICATION_CREDENTIALS
// 2. application_default_credentials.json file in ~/.config/gcloud or $APPDATA\gcloud
credentials, err := gcp.DefaultCredentials(ctx)
if err != nil {
return nil, fmt.Errorf("unable to find gcp credentials: %w", err)
}
return credentials, nil
}
func GoogleCredentialsMux(ctx context.Context) (*blob.URLMux, error) {
credentials, err := googleCredentials(ctx)
if err != nil {
return nil, errors.New("missing google credentials")
}
client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), credentials.TokenSource)
if err != nil {
return nil, err
}
options := gcsblob.Options{}
account := GoogleCredentials{}
err = json.Unmarshal(credentials.JSON, &account)
if err == nil && account.ClientEmail != "" && account.PrivateKey != "" {
options.GoogleAccessID = account.ClientEmail
options.PrivateKey = []byte(account.PrivateKey)
}
blobmux := &blob.URLMux{}
blobmux.RegisterBucket(gcsblob.Scheme, &gcsblob.URLOpener{
Client: client,
Options: options,
})
return blobmux, nil
}