-
Notifications
You must be signed in to change notification settings - Fork 240
/
auth.go
96 lines (82 loc) · 2.12 KB
/
auth.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
package clients
import (
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
// AuthType is the method of authenticating requests to the server.
type AuthType string
const (
// NoAuth uses no authentication.
NoAuth AuthType = "noauth"
// HTTPBasicAuth uses HTTP Basic Authentication.
HTTPBasicAuth AuthType = "http_basic"
)
// AuthConfig contains data needed to configure authentication in the client.
type AuthConfig struct {
Type AuthType
Username string
Password string
}
func authRoot() string {
env := os.Getenv("METAL3_AUTH_ROOT_DIR")
if env != "" {
return filepath.Clean(env)
}
return "/opt/metal3/auth"
}
func readAuthFile(filename string) (string, error) {
content, err := os.ReadFile(filepath.Clean(filename))
return strings.TrimSpace(string(content)), err
}
// LoadAuth loads the Ironic configuration from the environment.
func LoadAuth() (auth AuthConfig, err error) {
authPath := path.Join(authRoot(), "ironic")
if _, err := os.Stat(authPath); err != nil {
if os.IsNotExist(err) {
auth.Type = NoAuth
return auth, nil
}
return auth, err
}
auth.Type = HTTPBasicAuth
auth.Username, err = readAuthFile(path.Join(authPath, "username"))
if err != nil {
return
}
auth.Password, err = readAuthFile(path.Join(authPath, "password"))
if err != nil {
return
}
if auth.Username == "" {
err = fmt.Errorf("empty HTTP Basic Auth username")
} else if auth.Password == "" {
err = fmt.Errorf("empty HTTP Basic Auth password")
}
return
}
// ConfigFromEndpointURL returns an endpoint and an auth config from an
// endpoint URL that may contain HTTP basic auth credentials.
func ConfigFromEndpointURL(endpointURL string) (endpoint string, auth AuthConfig, err error) {
parsedURL, err := url.Parse(endpointURL)
if err != nil {
return
}
if parsedURL.User != nil {
var hasPasswd bool
auth.Type = HTTPBasicAuth
auth.Username = parsedURL.User.Username()
auth.Password, hasPasswd = parsedURL.User.Password()
if !hasPasswd {
err = fmt.Errorf("no password supplied for HTTP Basic Auth")
}
parsedURL.User = nil
} else {
auth.Type = NoAuth
}
endpoint = parsedURL.String()
return
}