github.com/google/cloudprober@v0.11.3/common/oauth/oauth.go (about) 1 // Copyright 2019 The Cloudprober Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 /* 16 Package oauth implements OAuth related utilities for Cloudprober. 17 */ 18 package oauth 19 20 import ( 21 "context" 22 "fmt" 23 24 "github.com/google/cloudprober/common/file" 25 configpb "github.com/google/cloudprober/common/oauth/proto" 26 "github.com/google/cloudprober/logger" 27 "golang.org/x/oauth2" 28 "golang.org/x/oauth2/google" 29 ) 30 31 // TokenSourceFromConfig builds a oauth2.TokenSource from the provided config. 32 func TokenSourceFromConfig(c *configpb.Config, l *logger.Logger) (oauth2.TokenSource, error) { 33 switch c.Type.(type) { 34 35 case *configpb.Config_BearerToken: 36 return newBearerTokenSource(c.GetBearerToken(), l) 37 38 case *configpb.Config_GoogleCredentials: 39 f := c.GetGoogleCredentials().GetJsonFile() 40 41 // If JSON file is not provided, try default credentials. 42 if f == "" { 43 creds, err := google.FindDefaultCredentials(context.Background(), c.GetGoogleCredentials().GetScope()...) 44 if err != nil { 45 return nil, err 46 } 47 return creds.TokenSource, nil 48 } 49 50 jsonKey, err := file.ReadFile(f) 51 if err != nil { 52 return nil, fmt.Errorf("error reading Google Credentials file (%s): %v", f, err) 53 } 54 55 aud := c.GetGoogleCredentials().GetAudience() 56 if aud != "" || c.GetGoogleCredentials().GetJwtAsAccessToken() { 57 if !c.GetGoogleCredentials().GetJwtAsAccessToken() { 58 return nil, fmt.Errorf("oauth: audience (%s) should only be set if jwt_as_access_token is set to true", aud) 59 } 60 return google.JWTAccessTokenSourceFromJSON(jsonKey, aud) 61 } 62 63 creds, err := google.CredentialsFromJSON(context.Background(), jsonKey, c.GetGoogleCredentials().GetScope()...) 64 if err != nil { 65 return nil, fmt.Errorf("error parsing Google Credentials file (%s): %v", f, err) 66 } 67 return creds.TokenSource, nil 68 } 69 70 return nil, fmt.Errorf("unknown oauth credentials type: %v", c.Type) 71 }