forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory_config.go
111 lines (85 loc) · 2.05 KB
/
factory_config.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
package uaa
import (
"crypto/x509"
"encoding/pem"
gonet "net"
gourl "net/url"
"strconv"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
type Config struct {
Host string
Port int
Path string
Client string
ClientSecret string
CACert string
}
func NewConfigFromURL(url string) (Config, error) {
if len(url) == 0 {
return Config{}, bosherr.Error("Expected non-empty UAA URL")
}
parsedURL, err := gourl.Parse(url)
if err != nil {
return Config{}, bosherr.WrapErrorf(err, "Parsing UAA URL '%s'", url)
}
host := parsedURL.Host
port := 443
path := parsedURL.Path
if len(host) == 0 {
host = url
path = ""
}
if strings.Contains(host, ":") {
var portStr string
host, portStr, err = gonet.SplitHostPort(host)
if err != nil {
return Config{}, bosherr.WrapErrorf(
err, "Extracting host/port from URL '%s'", url)
}
port, err = strconv.Atoi(portStr)
if err != nil {
return Config{}, bosherr.WrapErrorf(
err, "Extracting port from URL '%s'", url)
}
}
if len(host) == 0 {
return Config{}, bosherr.Errorf("Expected to extract host from URL '%s'", url)
}
return Config{Host: host, Port: port, Path: path}, nil
}
func (c Config) Validate() error {
if len(c.Host) == 0 {
return bosherr.Error("Missing 'Host'")
}
if c.Port == 0 {
return bosherr.Error("Missing 'Port'")
}
if len(c.Client) == 0 {
return bosherr.Error("Missing 'Client'")
}
if _, err := c.CACertPool(); err != nil {
return err
}
return nil
}
func (c Config) CACertPool() (*x509.CertPool, error) {
if len(c.CACert) == 0 {
return nil, nil
}
certPool := x509.NewCertPool()
block, _ := pem.Decode([]byte(c.CACert))
if block == nil {
return nil, bosherr.Error("Parsing CA certificate: Missing PEM block")
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
return nil, bosherr.Error("Parsing CA certificate: Not a certificate")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, bosherr.WrapError(err, "Parsing CA certificate")
}
certPool.AddCert(cert)
return certPool, nil
}