/
configuration.go
191 lines (159 loc) · 5.19 KB
/
configuration.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package ovh
import (
"context"
"errors"
"fmt"
"os"
"os/user"
"strings"
"golang.org/x/oauth2/clientcredentials"
"gopkg.in/ini.v1"
)
var configPaths = []string{
// System wide configuration
"/etc/ovh.conf",
// Configuration in user's home
"~/.ovh.conf",
// Configuration in local folder
"./ovh.conf",
}
// currentUserHome attempts to get current user's home directory.
func currentUserHome() (string, error) {
usr, err := user.Current()
if err != nil {
// Fallback by trying to read $HOME
if userHome := os.Getenv("HOME"); userHome != "" {
return userHome, nil
}
return "", err
}
return usr.HomeDir, nil
}
// configPaths returns configPaths, with ~/ prefix expanded.
func expandConfigPaths() []interface{} {
paths := []interface{}{}
// Will be initialized on first use
var home string
var homeErr error
for _, path := range configPaths {
if strings.HasPrefix(path, "~/") {
// Find home if needed
if home == "" && homeErr == nil {
home, homeErr = currentUserHome()
}
// Ignore file in HOME if we cannot find it
if homeErr != nil {
continue
}
path = home + path[1:]
}
paths = append(paths, path)
}
return paths
}
// loadINI builds a ini.File from the configuration paths provided in configPaths.
// It's a helper for loadConfig.
func loadINI() (*ini.File, error) {
paths := expandConfigPaths()
if len(paths) == 0 {
return ini.Empty(), nil
}
return ini.LooseLoad(paths[0], paths[1:]...)
}
// loadConfig loads client configuration from params, environments or configuration
// files (by order of decreasing precedence).
//
// loadConfig will check OVH_CONSUMER_KEY, OVH_APPLICATION_KEY, OVH_APPLICATION_SECRET
// and OVH_ENDPOINT environment variables. If any is present, it will take precedence
// over any configuration from file.
//
// Configuration files are ini files. They share the same format as python-ovh,
// node-ovh, php-ovh and all other wrappers. If any wrapper is configured, all
// can re-use the same configuration. loadConfig will check for configuration in:
//
// - ./ovh.conf
// - $HOME/.ovh.conf
// - /etc/ovh.conf
func (c *Client) loadConfig(endpointName string) error {
if strings.HasSuffix(endpointName, "/") {
return fmt.Errorf("endpoint name cannot have a tailing slash")
}
// Load configuration files by order of increasing priority. All configuration
// files are optional. Only load file from user home if home could be resolve
cfg, err := loadINI()
if err != nil {
return fmt.Errorf("cannot load configuration: %w", err)
}
// Canonicalize configuration
if endpointName == "" {
endpointName = getConfigValue(cfg, "default", "endpoint", "ovh-eu")
}
if c.AppKey == "" {
c.AppKey = getConfigValue(cfg, endpointName, "application_key", "")
}
if c.AppSecret == "" {
c.AppSecret = getConfigValue(cfg, endpointName, "application_secret", "")
}
if c.ConsumerKey == "" {
c.ConsumerKey = getConfigValue(cfg, endpointName, "consumer_key", "")
}
if c.ClientID == "" {
c.ClientID = getConfigValue(cfg, endpointName, "client_id", "")
}
if c.ClientSecret == "" {
c.ClientSecret = getConfigValue(cfg, endpointName, "client_secret", "")
}
if (c.ClientID != "") != (c.ClientSecret != "") {
return errors.New("invalid oauth2 config, both client_id and client_secret must be given")
}
if (c.AppKey != "") != (c.AppSecret != "") {
return errors.New("invalid authentication config, both application_key and application_secret must be given")
}
if c.ClientID != "" && c.AppKey != "" {
return errors.New("can't use both application_key/application_secret and OAuth2 client_id/client_secret")
} else if c.ClientID == "" && c.AppKey == "" {
return errors.New("missing authentication information, you need to provide at least an application_key/application_secret or a client_id/client_secret")
}
// Load real endpoint URL by name. If endpoint contains a '/', consider it as a URL
if strings.Contains(endpointName, "/") {
c.endpoint = endpointName
} else {
c.endpoint = Endpoints[endpointName]
}
// If we still have no valid endpoint, AppKey or AppSecret, return an error
if c.endpoint == "" {
return fmt.Errorf("unknown endpoint '%s', consider checking 'Endpoints' list or using an URL", endpointName)
}
if c.ClientID != "" {
if _, ok := tokensURLs[c.endpoint]; !ok {
return fmt.Errorf("oauth2 authentication is not compatible with endpoint %q", c.endpoint)
}
conf := &clientcredentials.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
TokenURL: tokensURLs[c.endpoint],
Scopes: []string{"all"},
}
c.oauth2TokenSource = conf.TokenSource(context.Background())
}
return nil
}
// getConfigValue returns the value of OVH_<NAME> or "name" value from "section". If
// the value could not be read from either env or any configuration files, return 'def'
func getConfigValue(cfg *ini.File, section, name, def string) string {
// Attempt to load from environment
fromEnv := os.Getenv("OVH_" + strings.ToUpper(name))
if len(fromEnv) > 0 {
return fromEnv
}
// Attempt to load from configuration
fromSection := cfg.Section(section)
if fromSection == nil {
return def
}
fromSectionKey := fromSection.Key(name)
if fromSectionKey == nil {
return def
}
return fromSectionKey.String()
}