-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
82 lines (67 loc) · 2 KB
/
client.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
package csbouncer
import (
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
)
func getAPIClient(urlstr string, userAgent string, apiKey string, caPath string, certPath string, keyPath string, skipVerify *bool, logger logrus.FieldLogger) (*apiclient.ApiClient, error) {
var client *http.Client
if apiKey == "" && certPath == "" && keyPath == "" {
return nil, errors.New("no API key nor certificate provided")
}
if apiKey != "" && (certPath != "" || keyPath != "") {
return nil, fmt.Errorf("cannot use both API key and certificate auth")
}
insecureSkipVerify := false
apiURL, err := url.Parse(urlstr)
if err != nil {
return nil, fmt.Errorf("local API Url '%s': %w", urlstr, err)
}
if skipVerify != nil && *skipVerify {
insecureSkipVerify = true
}
caCertPool, err := getCertPool(caPath, logger)
if err != nil {
return nil, err
}
if apiKey != "" {
var transport *apiclient.APIKeyTransport
logger.Infof("Using API key auth")
if apiURL.Scheme == "https" {
transport = &apiclient.APIKeyTransport{
APIKey: apiKey,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
InsecureSkipVerify: insecureSkipVerify,
},
},
}
} else {
transport = &apiclient.APIKeyTransport{
APIKey: apiKey,
}
}
client = transport.Client()
}
if certPath != "" && keyPath != "" {
logger.Infof("Using cert auth with cert '%s' and key '%s'", certPath, keyPath)
certificate, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, fmt.Errorf("unable to load certificate '%s' and key '%s': %w", certPath, keyPath, err)
}
client = &http.Client{}
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{certificate},
InsecureSkipVerify: insecureSkipVerify,
},
}
}
return apiclient.NewDefaultClient(apiURL, "v1", userAgent, client)
}