...

Source file src/edge-infra.dev/pkg/lib/gcp/iam/credentials.go

Documentation: edge-infra.dev/pkg/lib/gcp/iam

     1  package iam
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"edge-infra.dev/pkg/lib/errors"
     9  
    10  	"github.com/mitchellh/go-homedir"
    11  )
    12  
    13  const (
    14  	// GoogleAppCredsEnvVar contains the env var name used to pass creds file
    15  	// paths to google tooling
    16  	GoogleAppCredsEnvVar = "GOOGLE_APPLICATION_CREDENTIALS" // nolint:gosec
    17  )
    18  
    19  // ResolveGoogleAppCreds resolves the Google app creds file path
    20  // (https://cloud.google.com/docs/authentication/production) in this order:
    21  // - GOOGLE_APPLICATION_CREDENTIALS
    22  // - default location on disk
    23  // and will return an error if none of the three are present
    24  func ResolveGoogleAppCreds() (string, error) {
    25  	if os.Getenv(GoogleAppCredsEnvVar) != "" {
    26  		return os.Getenv(GoogleAppCredsEnvVar), nil
    27  	}
    28  
    29  	return DefaultGoogleAppCredsPath()
    30  }
    31  
    32  func DefaultGoogleAppCredsPath() (string, error) {
    33  	// resolve home dir
    34  	home, err := homedir.Dir()
    35  	if err != nil {
    36  		return "", errors.Wrap(err)
    37  	}
    38  
    39  	home, err = homedir.Expand(home)
    40  	if err != nil {
    41  		return "", errors.Wrap(err)
    42  	}
    43  
    44  	p := filepath.Join(home, ".config/gcloud/application_default_credentials.json")
    45  
    46  	if _, err := os.Stat(p); err != nil {
    47  		return "", errors.New(
    48  			fmt.Sprintf("couldnt find google default application credentials at %s", p),
    49  			err,
    50  		)
    51  	}
    52  
    53  	return p, nil
    54  }
    55  
    56  // CredentialsFile represents the JSON structure of Google creds files,
    57  // e.g., service account key files and default app creds files
    58  type CredentialsFile struct {
    59  	Type string `json:"type"` // service_account or authorized_user
    60  
    61  	// Service Account fields
    62  	ClientEmail  string `json:"client_email,omitempty"`
    63  	PrivateKeyID string `json:"private_key_id,omitempty"`
    64  	PrivateKey   string `json:"private_key,omitempty"`
    65  	TokenURL     string `json:"token_uri,omitempty"`
    66  	ProjectID    string `json:"project_id,omitempty"`
    67  
    68  	// User Credential fields
    69  	// (These typically come from gcloud auth.)
    70  	ClientSecret   string `json:"client_secret,omitempty"`
    71  	ClientID       string `json:"client_id,omitempty"`
    72  	RefreshToken   string `json:"refresh_token,omitempty"`
    73  	QuotaProjectID string `json:"quota_project_id,omitempty"`
    74  }
    75  

View as plain text