/
firefly.go
239 lines (209 loc) · 6.93 KB
/
firefly.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*
* Copyright 2023 Venafi, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package firefly
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/go-http-utils/headers"
"github.com/Venafi/vcert/v5/pkg/certificate"
"github.com/Venafi/vcert/v5/pkg/endpoint"
"github.com/Venafi/vcert/v5/pkg/verror"
)
type urlResource string
const (
urlResourceCertificateRequest urlResource = "v1/certificaterequest"
urlResourceCertificateRequestCSR urlResource = "v1/certificatesigningrequest"
scopesSeparator = " "
)
var (
rsaSizes = map[int]bool{certificate.DefaultRSAlength: true, 3072: true, 4096: true}
)
type certificateRequest struct {
CSR string `json:"request,omitempty"`
Subject Subject `json:"subject,omitempty"`
AlternativeName *AlternativeNames `json:"altNames,omitempty"`
ValidityPeriod *string `json:"validityPeriod,omitempty"`
PolicyName string `json:"policyName,omitempty"`
KeyAlgorithm string `json:"keyType,omitempty"`
}
type Subject struct {
CommonName string `json:"commonName,omitempty"`
Organization string `json:"organization,omitempty"`
OrgUnits []string `json:"orgUnits,omitempty"`
Locality string `json:"locality,omitempty"`
State string `json:"state,omitempty"`
Country string `json:"country,omitempty"`
}
type AlternativeNames struct {
DnsNames []string `json:"dnsNames,omitempty"`
IpAddresses []string `json:"ipAddresses,omitempty"`
EmailAddresses []string `json:"emailAddresses,omitempty"`
Uris []string `json:"uris,omitempty"`
}
type certificateRequestResponse struct {
CertificateChain string `json:"certificateChain,omitempty"`
PrivateKey string `json:"privateKey"`
}
// GenerateRequest should generate a CertificateRequest based on the zone configuration when the csrOrigin was
// set to LocalGeneratedCSR but given that is not supported by Firefly yet, then it's only validating if the CSR
// was provided when the csrOrigin was set to UserProvidedCSR
func (c *Connector) GenerateRequest(_ *endpoint.ZoneConfiguration, req *certificate.Request) (err error) {
switch req.CsrOrigin {
case certificate.LocalGeneratedCSR:
return fmt.Errorf("local generated CSR it's not supported by Firefly yet")
case certificate.UserProvidedCSR:
if len(req.GetCSR()) == 0 {
return fmt.Errorf("%w: CSR was supposed to be provided by user, but it's empty", verror.UserDataError)
}
return nil
case certificate.ServiceGeneratedCSR:
return nil
default:
return fmt.Errorf("%w: unrecognised req.CsrOrigin %v", verror.UserDataError, req.CsrOrigin)
}
}
func (c *Connector) request(method string, resource urlResource, data interface{}) (statusCode int, statusText string, body []byte, err error) {
resourceUrl := string(resource)
//validating if the resource is already a full url
reg := regexp.MustCompile("^http(|s)://")
//if the resourceUrl is not a full Url then prefixing it with the baseUrl
if reg.FindStringIndex(strings.ToLower(string(resource))) == nil {
resourceUrl = c.baseURL + resourceUrl
}
var payload io.Reader
var b []byte
var values url.Values
contentType := "application/json"
if method == "POST" || method == "PUT" {
//determining if the data is type of url.Values
v, ok := data.(url.Values)
//if the data is type of url.Values then commonly they are passed to the request as form
if ok {
payload = strings.NewReader(v.Encode())
values = v
contentType = "application/x-www-form-urlencoded"
} else {
b, _ = json.Marshal(data)
payload = bytes.NewReader(b)
}
}
r, _ := http.NewRequest(method, resourceUrl, payload)
r.Close = true
r.Header.Set(headers.UserAgent, c.userAgent)
if c.accessToken != "" {
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
}
r.Header.Add("content-type", contentType)
r.Header.Add("cache-control", "no-cache")
res, err := c.getHTTPClient().Do(r)
if err != nil {
return
}
if res != nil {
statusCode = res.StatusCode
statusText = res.Status
}
defer res.Body.Close()
body, err = io.ReadAll(res.Body)
// Do not enable trace in production
trace := false // IMPORTANT: sensitive information can be diclosured
// I hope you know what are you doing
if trace {
log.Println("#################")
log.Printf("Headers are:\n%s", r.Header)
if method == "POST" || method == "PUT" {
if len(values) > 0 {
log.Printf("Values sent for %s\n%s\n", resourceUrl, values.Encode())
} else {
log.Printf("JSON sent for %s\n%s\n", resourceUrl, string(b))
}
} else {
log.Printf("%s request sent to %s\n", method, resourceUrl)
}
log.Printf("Response:\n%s\n", string(body))
} else if c.verbose {
log.Printf("Got %s status for %s %s\n", statusText, method, resourceUrl)
}
return
}
func (c *Connector) getHTTPClient() *http.Client {
if c.client != nil {
return c.client
}
var netTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
tlsConfig := http.DefaultTransport.(*http.Transport).TLSClientConfig
/* #nosec */
if c.trust != nil {
if tlsConfig == nil {
tlsConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
}
} else {
tlsConfig = tlsConfig.Clone()
}
tlsConfig.RootCAs = c.trust
}
netTransport.TLSClientConfig = tlsConfig
c.client = &http.Client{
Timeout: time.Second * 30,
Transport: netTransport,
}
return c.client
}
func parseCertificateRequestResult(httpStatusCode int, httpStatus string, body []byte) (*certificateRequestResponse, error) {
switch httpStatusCode {
case http.StatusOK:
return parseCertificateRequestData(body)
default:
respError, err := NewResponseError(body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("unexpected status code on Venafi Firefly. Status: %s: %w", httpStatus, respError)
}
}
func parseCertificateRequestData(b []byte) (*certificateRequestResponse, error) {
var data certificateRequestResponse
err := json.Unmarshal(b, &data)
if err != nil {
return nil, fmt.Errorf("%w: %v", verror.ServerError, err)
}
return &data, nil
}
func (c *Connector) getURL(resource urlResource) string {
return fmt.Sprintf("%s%s", c.baseURL, resource)
}