Exemple #1
0
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")
	}
	acct := cs.account
	if acct == "" {
		acct = "default"
	}
	tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token")
	if err != nil {
		return nil, err
	}
	var res struct {
		AccessToken  string `json:"access_token"`
		ExpiresInSec int    `json:"expires_in"`
		TokenType    string `json:"token_type"`
	}
	err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
	if err != nil {
		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")
	}
	return &oauth2.Token{
		AccessToken: res.AccessToken,
		TokenType:   res.TokenType,
		Expiry:      time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
	}, nil
}
Exemple #2
0
func getGceInstanceType() info.InstanceType {
	machineType, err := metadata.Get("instance/machine-type")
	if err != nil {
		return info.UnknownInstance
	}

	responseParts := strings.Split(machineType, "/") // Extract the instance name from the machine type.
	return info.InstanceType(responseParts[len(responseParts)-1])
}
Exemple #3
0
// Get a token for performing GCM requests.
func getToken() (authToken, error) {
	rawToken, err := metadata.Get("instance/service-accounts/default/token")
	if err != nil {
		return authToken{}, err
	}

	var token authToken
	err = json.Unmarshal([]byte(rawToken), &token)
	if err != nil {
		return authToken{}, fmt.Errorf("failed to unmarshal service account token with output %q: %v", rawToken, err)
	}

	return token, err
}
Exemple #4
0
// Checks that the required auth scope is present.
func VerifyAuthScope(expectedScope string) error {
	scopes, err := metadata.Get("instance/service-accounts/default/scopes")
	if err != nil {
		return err
	}

	for _, scope := range strings.Fields(scopes) {
		if scope == expectedScope {
			return nil
		}
	}

	return fmt.Errorf("Current instance does not have the expected scope (%q). Actual scopes: %v", expectedScope, scopes)
}
Exemple #5
0
// Checks that we have the required service scopes.
func checkServiceAccounts() error {
	scopes, err := metadata.Get("instance/service-accounts/default/scopes")
	if err != nil {
		return err
	}

	// Ensure it has the monitoring R/W scope.
	for _, scope := range strings.Fields(scopes) {
		if scope == "https://www.googleapis.com/auth/monitoring" {
			return nil
		}
	}

	return fmt.Errorf("current instance does not have the monitoring read-write scope")
}