-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestcert.go
71 lines (63 loc) · 1.78 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package bifrost
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io"
"net/http"
"github.com/google/uuid"
)
// RequestCertificate sends a certificate request to url and returns the signed certificate.
func RequestCertificate(
ctx context.Context,
url string,
ns uuid.UUID,
key *ecdsa.PrivateKey,
) (*x509.Certificate, error) {
template := x509.CertificateRequest{
Subject: pkix.Name{
CommonName: UUID(ns, &key.PublicKey).String(),
Organization: []string{ns.String()},
},
SignatureAlgorithm: SignatureAlgorithm,
}
csr, err := x509.CreateCertificateRequest(rand.Reader, &template, key)
if err != nil {
return nil, fmt.Errorf("error creating certificate request: %w", err)
}
resp, err := http.Post(url+"/issue", "application/octet-stream", bytes.NewReader(csr))
if err != nil {
return nil, fmt.Errorf("error creating certificate request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unexpected error reading response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected response status: %s, body: %s", resp.Status, body)
}
cert, err := x509.ParseCertificate(body)
if err != nil {
return nil, err
}
return cert, nil
}
// X509ToTLSCertificate puts an x509.Certificate inside a tls.Certificate.
func X509ToTLSCertificate(crt *x509.Certificate, key *ecdsa.PrivateKey) *tls.Certificate {
return &tls.Certificate{
Certificate: [][]byte{
crt.Raw,
},
PrivateKey: key,
Leaf: crt,
}
}