Skip to content
File

Blob: cmd/server/server.go

go316 lines
1package server
2 
3import (
4 "context"
5 "fmt"
6 
7 serverruntime "go.miragespace.co/specter/internal/server"
8 acmeSpec "go.miragespace.co/specter/spec/acme"
9 "go.miragespace.co/specter/spec/cipher"
10 "go.miragespace.co/specter/util"
11 
12 "github.com/urfave/cli/v3"
13 "go.uber.org/zap"
14)
15 
16func Generate() *cli.Command {
17 ip := util.GetOutboundIP()
18 return &cli.Command{
19 Name: "server",
20 Usage: "start an specter server on the edge",
21 Description: `Start a Specter server that joins a Chord DHT ring, routes all tunnels over QUIC, issues/renews TLS certificates via ACME DNS-01, and persists state for high availability.
22
23 Specter server provides an internal endpoint on /_internal under apex domain. To enable internal endpoint, provide username and password
24 under environment variables INTERNAL_USER and INTERNAL_PASS. Absent of them will disable the internal endpoint entirely.
25
26 Warning: do not use certificates issued by public CA for inter-node certificates, otherwise anyone can join your specter network`,
27 ArgsUsage: " ",
28 Flags: []cli.Flag{
29 &cli.StringFlag{
30 Name: "advertise-addr",
31 Aliases: []string{"advertise"},
32 Sources: cli.EnvVars("ADVERTISE_ADDR"),
33 DefaultText: "same as listen-addr",
34 Value: fmt.Sprintf("%s:443", ip.String()),
35 Usage: `Address and port to advertise to specter servers and clients to connect to.
36 Note that specter will use advertised address to derive its Identity hash.`,
37 Category: "Network Options",
38 },
39 &cli.StringSliceFlag{
40 Name: "listen-addr",
41 Aliases: []string{"listen"},
42 Value: []string{fmt.Sprintf("%s:443", ip.String())},
43 Usage: `Repeatable address:port to listen for specter server, specter client and gateway connections. Each entry serves both TCP and UDP unless overridden.
44 Note that if specter is listening on port 443, it will also listen on port 80 to handle http connect proxy, and redirect other http requests to https`,
45 Category: "Network Options",
46 Sources: cli.EnvVars("LISTEN_ADDR"),
47 },
48 &cli.StringSliceFlag{
49 Name: "listen-tcp",
50 DefaultText: "same as listen-addr",
51 Usage: "Override the listen address and port for TCP (repeatable)",
52 Category: "Network Options",
53 Sources: cli.EnvVars("LISTEN_TCP"),
54 },
55 &cli.StringSliceFlag{
56 Name: "listen-udp",
57 DefaultText: "same as listen-addr",
58 Usage: "Override the listen address and port for UDP (repeatable). Required if environment needs a specific address, such as on fly.io",
59 Category: "Network Options",
60 Sources: cli.EnvVars("LISTEN_UDP"),
61 },
62 &cli.BoolFlag{
63 Name: "proxy-protocol",
64 Value: false,
65 Usage: "Parse client IP via PROXY protocol (v1 or v2) when handling TCP connections. Required if environment is behind a TCP Load Balancer, such as on fly.io",
66 Category: "Network Options",
67 },
68 
69 &cli.StringFlag{
70 Name: "listen-rpc",
71 Value: "tcp://127.0.0.1:11180",
72 Usage: `Expose chord's VNode/KV RPC and read-only shared configuration snapshots to an external program. This is required to use with specter's acme dns.
73 NOTE: The listener is exposed without any authentication or authorization. You should only expose it to localhost or unix socket`,
74 Category: "Server Options",
75 },
76 &cli.StringFlag{
77 Name: "data-dir",
78 Aliases: []string{"data"},
79 Usage: "Path to directory that will be used for persisting KV data and shared configuration",
80 Required: true,
81 Category: "Server Options",
82 },
83 &cli.StringFlag{
84 Name: "cert-dir",
85 Aliases: []string{"cert"},
86 Usage: `Path to directory containing ca.crt, client-ca.crt, client-ca.key, node.crt, and node.key for mutual TLS between specter server nodes`,
87 Category: "Server Options",
88 },
89 &cli.BoolFlag{
90 Name: "cert-env",
91 Usage: `Load ca.crt (CERT_CA), client-ca.crt (CERT_CLIENT_CA), client-ca.key (CERT_CLIENT_CA_KEY), node.crt (CERT_NODE), and node.key (CERT_NODE_KEY) from environment variables encoded as base64.
92 This can be set instead of loading from cert-dir. Required if environment prefers loading secrets from ENV, such as on fly.io`,
93 Category: "Server Options",
94 },
95 &cli.StringFlag{
96 Name: "sentry",
97 DefaultText: "https://public@sentry.example.com/1",
98 Usage: "Sentry DSN for error monitoring. Alternatively, you can set the DSN via the environment variable SENTRY_DSN",
99 Sources: cli.EnvVars("SENTRY_DSN"),
100 Category: "Server Options",
101 },
102 
103 &cli.IntFlag{
104 Name: "virtual",
105 Usage: "Number of virtual nodes to be started as part of the chord ring",
106 Value: 5,
107 Category: "Chord Options",
108 },
109 &cli.StringFlag{
110 Name: "join",
111 Sources: cli.EnvVars("CHORD_JOIN"),
112 Usage: `A known specter server's advertise address.
113 Absent of this flag will bootstrap a new cluster with current node as the seed node`,
114 Category: "Chord Options",
115 },
116 &cli.StringFlag{
117 Name: "kv-provider",
118 Usage: "Backend storage provider for KV. Valid options are memory, aof, and sqlite",
119 Value: "aof",
120 Sources: cli.EnvVars("KV_PROVIDER"),
121 Category: "Chord Options",
122 },
123 
124 &cli.StringFlag{
125 Name: "acme",
126 DefaultText: "acme://{ACME_EMAIL}:@acmehostedzone.com",
127 Sources: cli.EnvVars("ACME_URI"),
128 Usage: `To enable acme, provide an email for the issuer, and the delegated zone for hosting challenges.
129 Absent of this flag will serve self-signed certificate.
130 Alternatively, you can set the URI via the environment variable ACME_URI.`,
131 Category: "Gateway Options",
132 },
133 &cli.IntFlag{
134 Name: "listen-http",
135 Value: 80,
136 Usage: `Override the listening port of the http handler, which handles http connect proxy, and redirects other http requests to https.
137 Note by default the http handler will not be started unless the node is advertising on port 443. Using this option will force the http handler to start.`,
138 Category: "Gateway Options",
139 },
140 &cli.StringSliceFlag{
141 Name: "apex",
142 Sources: cli.EnvVars("APEX"),
143 Usage: "Canonical domain to be used as tunnel root domain. Tunnels will be given names under *.`APEX`. Additional canonical domains can be specified.",
144 Required: true,
145 Category: "Gateway Options",
146 },
147 &cli.StringFlag{
148 Name: "transport-buffer",
149 Value: "16KiB",
150 Usage: "Buffer size when making HTTP request to client",
151 Category: "Gateway Options",
152 },
153 &cli.StringFlag{
154 Name: "proxy-buffer",
155 Value: "16KiB",
156 Usage: "Buffer size when copying response from client",
157 Category: "Gateway Options",
158 },
159 
160 &cli.BoolFlag{
161 Name: "print-acme",
162 Value: false,
163 Usage: "Print acme setup instructions for apex domains based on current configuration.",
164 Category: "Miscellaneous",
165 },
166 
167 &cli.StringFlag{
168 Name: "acme_ca",
169 Hidden: true,
170 Value: cipher.CertCA,
171 Sources: cli.EnvVars("ACME_CA"),
172 },
173 
174 // used for acme setup internally
175 &cli.StringFlag{
176 Name: "acme_email",
177 Hidden: true,
178 },
179 &cli.StringFlag{
180 Name: "acme_zone",
181 Hidden: true,
182 },
183 &cli.StringFlag{
184 Name: "auth_user",
185 Hidden: true,
186 Sources: cli.EnvVars("INTERNAL_USER"),
187 },
188 &cli.StringFlag{
189 Name: "auth_pass",
190 Hidden: true,
191 Sources: cli.EnvVars("INTERNAL_PASS"),
192 },
193 &cli.StringFlag{
194 Name: "env_ca",
195 Hidden: true,
196 Sources: cli.EnvVars("CERT_CA"),
197 },
198 &cli.StringFlag{
199 Name: "env_node",
200 Hidden: true,
201 Sources: cli.EnvVars("CERT_NODE"),
202 },
203 &cli.StringFlag{
204 Name: "env_node_key",
205 Hidden: true,
206 Sources: cli.EnvVars("CERT_NODE_KEY"),
207 },
208 &cli.StringFlag{
209 Name: "env_client_ca",
210 Hidden: true,
211 Sources: cli.EnvVars("CERT_CLIENT_CA"),
212 },
213 &cli.StringFlag{
214 Name: "env_client_ca_key",
215 Hidden: true,
216 Sources: cli.EnvVars("CERT_CLIENT_CA_KEY"),
217 },
218 },
219 Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
220 if !cmd.IsSet("cert-dir") && !cmd.IsSet("cert-env") {
221 return ctx, fmt.Errorf("no certificate loader is specified")
222 }
223 if cmd.Int("virtual") < 1 {
224 return ctx, fmt.Errorf("minimum of 1 virtual node is required")
225 }
226 if cmd.IsSet("acme") {
227 email, zone, err := acmeSpec.ParseAcmeURI(cmd.String("acme"))
228 if err != nil {
229 return ctx, err
230 }
231 cmd.Set("acme_email", email)
232 cmd.Set("acme_zone", zone)
233 }
234 return ctx, nil
235 },
236 Action: cmdServer,
237 }
238}
239 
240func cmdServer(ctx context.Context, cmd *cli.Command) error {
241 logger, ok := cmd.Root().Metadata["logger"].(*zap.Logger)
242 if !ok || logger == nil {
243 return fmt.Errorf("unable to obtain logger from app context")
244 }
245 
246 rootDomains := cmd.StringSlice("apex")
247 managedDomains := rootDomains
248 
249 if cmd.Bool("print-acme") {
250 if !cmd.IsSet("acme") {
251 return fmt.Errorf("acme is not configured")
252 }
253 for _, d := range managedDomains {
254 hostname, err := acmeSpec.Normalize(d)
255 if err != nil {
256 return fmt.Errorf("error normalizing domain for %s: %w", d, err)
257 }
258 name, content := acmeSpec.GenerateManagedRecord(hostname, cmd.String("acme_zone"))
259 logger.Info("ACME DNS Record", zap.String("name", name), zap.String("content", content), zap.String("type", "CNAME"))
260 }
261 return nil
262 }
263 
264 return serverruntime.Run(ctx, serverOptions(cmd, logger))
265}
266 
267func serverOptions(cmd *cli.Command, logger *zap.Logger) serverruntime.Options {
268 options := serverruntime.Options{
269 Logger: logger,
270 Version: cmd.Root().Version,
271 DataDir: cmd.String("data-dir"),
272 KVProvider: cmd.String("kv-provider"),
273 ListenAddresses: cmd.StringSlice("listen-addr"),
274 ListenTCP: cmd.StringSlice("listen-tcp"),
275 ListenUDP: cmd.StringSlice("listen-udp"),
276 AdvertiseAddress: optionalString(cmd, "advertise-addr"),
277 RPCListen: optionalString(cmd, "listen-rpc"),
278 ProxyProtocol: cmd.Bool("proxy-protocol"),
279 CertDirectory: optionalString(cmd, "cert-dir"),
280 VirtualNodes: cmd.Int("virtual"),
281 JoinAddress: optionalString(cmd, "join"),
282 SentryDSN: optionalString(cmd, "sentry"),
283 Apex: cmd.StringSlice("apex"),
284 ACMEEnabled: cmd.IsSet("acme"),
285 ACMECA: cmd.String("acme_ca"),
286 ACMEEmail: cmd.String("acme_email"),
287 ACMEZone: cmd.String("acme_zone"),
288 ProxyBuffer: cmd.String("proxy-buffer"),
289 TransportBuffer: cmd.String("transport-buffer"),
290 AdminUser: cmd.String("auth_user"),
291 AdminPass: cmd.String("auth_pass"),
292 }
293 if cmd.IsSet("listen-http") {
294 port := cmd.Int("listen-http")
295 options.HTTPPort = &port
296 }
297 if cmd.IsSet("cert-env") {
298 options.CertEnvironment = &serverruntime.CertificateEnvironment{
299 CA: cmd.String("env_ca"),
300 Node: cmd.String("env_node"),
301 NodeKey: cmd.String("env_node_key"),
302 ClientCA: cmd.String("env_client_ca"),
303 ClientCAKey: cmd.String("env_client_ca_key"),
304 }
305 }
306 return options
307}
308 
309func optionalString(cmd *cli.Command, name string) *string {
310 if !cmd.IsSet(name) {
311 return nil
312 }
313 value := cmd.String(name)
314 return &value
315}