1 // Copyright 2023 Google LLC
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 // Package credsfile is meant to hide implementation details from the pubic
16 // surface of the detect package. It should not import any other packages in
17 // this module. It is located under the main internal package so other
18 // sub-packages can use these parsed types as well.
19 package credsfile
20 21 import (
22 "os"
23 "os/user"
24 "path/filepath"
25 "runtime"
26 )
27 28 const (
29 // GoogleAppCredsEnvVar is the environment variable for setting the
30 // application default credentials.
31 GoogleAppCredsEnvVar = "GOOGLE_APPLICATION_CREDENTIALS"
32 userCredsFilename = "application_default_credentials.json"
33 )
34 35 // GetFileNameFromEnv returns the override if provided or detects a filename
36 // from the environment.
37 func GetFileNameFromEnv(override string) string {
38 if override != "" {
39 return override
40 }
41 return os.Getenv(GoogleAppCredsEnvVar)
42 }
43 44 // GetWellKnownFileName tries to locate the filepath for the user credential
45 // file based on the environment.
46 func GetWellKnownFileName() string {
47 if runtime.GOOS == "windows" {
48 return filepath.Join(os.Getenv("APPDATA"), "gcloud", userCredsFilename)
49 }
50 return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", userCredsFilename)
51 }
52 53 // guessUnixHomeDir default to checking for HOME, but not all unix systems have
54 // this set, do have a fallback.
55 func guessUnixHomeDir() string {
56 if v := os.Getenv("HOME"); v != "" {
57 return v
58 }
59 if u, err := user.Current(); err == nil {
60 return u.HomeDir
61 }
62 return ""
63 }
64