@@ -17,13 +17,16 @@ limitations under the License.
17
17
package gcp
18
18
19
19
import (
20
+ "bytes"
20
21
"context"
21
22
"encoding/json"
22
23
"fmt"
23
24
"os/exec"
24
25
"sync"
26
+ "time"
25
27
26
28
"github.com/docker/cli/cli/config/configfile"
29
+ "golang.org/x/oauth2"
27
30
"golang.org/x/oauth2/google"
28
31
29
32
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output/log"
@@ -59,33 +62,41 @@ func AutoConfigureGCRCredentialHelper(cf *configfile.ConfigFile) {
59
62
}
60
63
}
61
64
65
+ type token struct {
66
+ AccessToken string `json:"access_token"`
67
+ TokenExpiry time.Time `json:"token_expiry"`
68
+ }
69
+
70
+ type tokenSource struct {
71
+ }
72
+
73
+ func (ts tokenSource ) Token () (* oauth2.Token , error ) {
74
+ cmd := exec .Command ("gcloud" , "auth" , "print-identity-token" , "--format=json" )
75
+ var body bytes.Buffer
76
+ cmd .Stdout = & body
77
+ err := util .RunCmd (context .TODO (), cmd )
78
+ if err != nil {
79
+ return nil , fmt .Errorf ("failed to get access token %v" , err )
80
+ }
81
+ var t token
82
+ if err := json .Unmarshal (body .Bytes (), & t ); err != nil {
83
+ return nil , fmt .Errorf ("failed to get access token %v" , err )
84
+ }
85
+ return & oauth2.Token {AccessToken : t .AccessToken , Expiry : t .TokenExpiry }, nil
86
+ }
87
+
62
88
func activeUserCredentials (ctx context.Context ) (* google.Credentials , error ) {
63
89
credsOnce .Do (func () {
64
- cmd := exec . Command ( "gcloud" , "auth" , "print-access-token" , "--format=json" )
65
- body , err := util . RunCmdOut ( ctx , cmd )
90
+ var ts tokenSource
91
+ t , err := ts . Token ( )
66
92
if err != nil {
67
93
log .Entry (context .TODO ()).Infof ("unable to retrieve gcloud access token: %v" , err )
68
94
log .Entry (context .TODO ()).Info ("falling back to application default credentials" )
69
95
credsErr = fmt .Errorf ("retrieving gcloud access token: %w" , err )
70
96
return
71
97
}
72
- jsonCreds := make (map [string ]interface {})
73
- json .Unmarshal (body , & jsonCreds )
74
- jsonCreds ["type" ] = "authorized_user"
75
- body , _ = json .Marshal (jsonCreds )
76
98
77
- c , err := google .CredentialsFromJSON (context .Background (), body )
78
- if err != nil {
79
- log .Entry (context .TODO ()).Infof ("unable to retrieve google creds: %v" , err )
80
- log .Entry (context .TODO ()).Info ("falling back to application default credentials" )
81
- return
82
- }
83
- _ , err = c .TokenSource .Token ()
84
- if err != nil {
85
- log .Entry (context .TODO ()).Infof ("unable to retrieve token: %v" , err )
86
- log .Entry (context .TODO ()).Info ("falling back to application default credentials" )
87
- return
88
- }
99
+ c := & google.Credentials {TokenSource : oauth2 .ReuseTokenSource (t , ts )}
89
100
creds = c
90
101
})
91
102
0 commit comments