-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestcert.go
81 lines (70 loc) · 1.95 KB
/
requestcert.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
package bifrost
import (
"bytes"
"context"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io"
"net/http"
"sync"
"github.com/VictoriaMetrics/metrics"
"github.com/google/uuid"
)
var nsMetricsMap = sync.Map{}
func getNsMetrics(namespace uuid.UUID) *metrics.Counter {
m, ok := nsMetricsMap.Load(namespace)
if !ok {
m = metrics.NewCounter(
fmt.Sprintf(`bifrost_certificate_requests_total{namespace="%s"}`, namespace),
)
nsMetricsMap.Store(namespace, m)
}
return m.(*metrics.Counter)
}
// Template returns a bifrost certificate template for the given namespace and public key.
func Template(ns uuid.UUID, key *PublicKey) *x509.CertificateRequest {
return &x509.CertificateRequest{
Subject: pkix.Name{
CommonName: key.UUID(ns).String(),
Organization: []string{ns.String()},
},
SignatureAlgorithm: SignatureAlgorithm,
}
}
// RequestCertificate sends a certificate request to url and returns the signed certificate.
func RequestCertificate(
ctx context.Context,
url string,
ns uuid.UUID,
key *PrivateKey,
) (*Certificate, error) {
template := Template(ns, key.PublicKey())
csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
if err != nil {
return nil, fmt.Errorf("bifrost: error creating certificate request: %w", err)
}
resp, err := http.Post(url+"/issue", "application/octet-stream", bytes.NewReader(csr))
if err != nil || resp == nil {
return nil, fmt.Errorf("bifrost: error creating certificate request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("bifrost: unexpected error reading response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"bifrost: unexpected response status: %s, body: %s",
resp.Status,
body,
)
}
cert, err := ParseCertificate(body)
if err != nil {
return nil, fmt.Errorf("bifrost: error parsing certificate: %w", err)
}
getNsMetrics(ns).Inc()
return cert, nil
}