-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathca.go
More file actions
236 lines (205 loc) · 6.14 KB
/
ca.go
File metadata and controls
236 lines (205 loc) · 6.14 KB
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
package main
import (
"context"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"time"
"github.com/RealImage/bifrost"
"github.com/RealImage/bifrost/cafiles"
"github.com/RealImage/bifrost/internal/webapp"
"github.com/RealImage/bifrost/tinyca"
"github.com/urfave/cli/v3"
)
const (
defaultCaHost = "localhost"
defaultCaPort = 8008
serverShutdownTimeout = 1 * time.Second
)
// caServeCmd flags
var (
caHost string
caPort int64
enableCORS bool
exposeMetrics bool
gauntletPlugin string
)
var caServeCmd = &cli.Command{
Name: "serve",
Aliases: []string{"ca"},
Usage: "Starts the Certificate Authority server",
Flags: []cli.Flag{
caCertFlag,
caPrivKeyFlag,
&cli.StringFlag{
Name: "host",
Usage: "listen on `HOST`",
Aliases: []string{"H"},
Sources: cli.EnvVars("HOST"),
Value: defaultCaHost,
Destination: &caHost,
},
&cli.IntFlag{
Name: "port",
Usage: "listen on `PORT`",
Aliases: []string{"p"},
Sources: cli.EnvVars("PORT"),
Value: defaultCaPort,
Destination: &caPort,
Action: func(_ context.Context, _ *cli.Command, p int64) error {
if p < 1 || p > 65535 {
return errors.New("port must be between 1 and 65535")
}
return nil
},
},
&cli.BoolFlag{
Name: "cors",
Usage: "enable CORS from all origins",
Sources: cli.EnvVars("CORS"),
Value: false,
Destination: &enableCORS,
},
&cli.BoolFlag{
Name: "metrics",
Usage: "expose Prometheus metrics",
Sources: cli.EnvVars("METRICS"),
Value: false,
Destination: &exposeMetrics,
},
},
Action: func(ctx context.Context, _ *cli.Command) error {
cert, key, err := cafiles.GetCertKey(ctx, caCertUri, caPrivKeyUri)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error reading cert/key", "error", err)
return cli.Exit("Error reading cert/key", 1)
}
bifrost.Logger().DebugContext(
ctx, "loaded CA certificate and private key",
"subject", cert.Subject,
"notBefore", cert.NotBefore,
"notAfter", cert.NotAfter,
)
gauntlet, err := tinyca.LoadGauntlet(gauntletPlugin)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error loading interceptor plugin", "error", err)
return cli.Exit("Error loading interceptor plugin", 1)
}
ca, err := tinyca.New(cert, key, gauntlet)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error creating CA", "error", err)
return cli.Exit("Error creating CA", 1)
}
defer ca.Close()
mux := http.NewServeMux()
ca.AddRoutes(mux, exposeMetrics)
hdlr := webapp.RequestLogger(mux)
if enableCORS {
hdlr = corsMiddleware(hdlr)
}
addr := fmt.Sprintf("%s:%d", caHost, caPort)
bifrost.Logger().
InfoContext(ctx, "starting server", "address", addr, "namespace", cert.Namespace)
server := http.Server{Addr: addr, Handler: hdlr}
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
bifrost.Logger().ErrorContext(ctx, "error starting server", "error", err)
os.Exit(1)
}
}()
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
<-ctx.Done()
ctx, cancel = context.WithTimeout(context.Background(), serverShutdownTimeout)
defer cancel()
bifrost.Logger().DebugContext(ctx, "shutting down server")
if err := server.Shutdown(ctx); err != nil {
return err
}
bifrost.Logger().InfoContext(ctx, "server shut down")
return nil
},
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding")
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
var caIssueCmd = &cli.Command{
Name: "issue",
Usage: "Issues a certificate from the Certificate Authority key",
Flags: []cli.Flag{
caCertFlag,
caPrivKeyFlag,
clientPrivKeyFlag,
notBeforeFlag,
notAfterFlag,
outputFlag,
},
Action: func(ctx context.Context, _ *cli.Command) error {
caCert, caKey, err := cafiles.GetCertKey(ctx, caCertUri, caPrivKeyUri)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error reading cert/key", "error", err)
return cli.Exit("Error reading cert/key", 1)
}
ca, err := tinyca.New(caCert, caKey, nil)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error creating CA", "error", err)
return cli.Exit("Error creating CA", 1)
}
defer ca.Close()
clientKey, err := cafiles.GetPrivateKey(ctx, clientPrivKeyUri)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error reading client key", "error", err)
return cli.Exit("Error reading client key", 1)
}
csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
Subject: pkix.Name{
Organization: []string{caCert.Namespace.String()},
CommonName: clientKey.UUID(caCert.Namespace).String(),
},
}, clientKey)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error creating certificate request", "error", err)
return cli.Exit("Error creating certificate request", 1)
}
notBefore, notAfter, err := tinyca.ParseValidity(notBeforeTime, notAfterTime)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error parsing validity", "error", err)
return cli.Exit("Error parsing validity", 1)
}
cert, err := ca.IssueCertificate(csr, notBefore, notAfter)
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error issuing certificate", "error", err)
return cli.Exit("Error issuing certificate", 1)
}
out, cls, err := getOutputWriter()
if err != nil {
bifrost.Logger().ErrorContext(ctx, "error getting output writer", "error", err)
return cli.Exit("Error getting output writer", 1)
}
defer func() {
if err := cls(); err != nil {
bifrost.Logger().ErrorContext(ctx, "error closing output writer", "error", err)
}
}()
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
}
return pem.Encode(out, block)
},
}