Skip to content
File

Blob: tun/client/server.go

go371 lines
1package client
2 
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "net/url"
12 "os"
13 "time"
14 
15 "go.miragespace.co/specter/spec/acme"
16 "go.miragespace.co/specter/spec/protocol"
17 "go.miragespace.co/specter/spec/rpc"
18 "go.miragespace.co/specter/spec/transport"
19 "go.miragespace.co/specter/ui"
20 "go.miragespace.co/specter/util"
21 
22 "github.com/go-chi/chi/v5"
23 "github.com/go-chi/chi/v5/middleware"
24 "github.com/twitchtv/twirp"
25 "go.uber.org/zap"
26)
27 
28var _ protocol.ClientQueryService = (*Client)(nil)
29 
30func (c *Client) attachRPC(ctx context.Context, router *transport.StreamRouter) {
31 queryTwirp := protocol.NewClientQueryServiceServer(c)
32 
33 rpcHandler := chi.NewRouter()
34 rpcHandler.Use(middleware.Recoverer)
35 rpcHandler.Use(util.LimitBody(1 << 10)) // 1KB
36 rpcHandler.Mount(queryTwirp.PathPrefix(), queryTwirp)
37 
38 srv := &http.Server{
39 BaseContext: func(l net.Listener) context.Context {
40 return ctx
41 },
42 ConnContext: func(ctx context.Context, c net.Conn) context.Context {
43 return rpc.WithDelegation(ctx, c.(*transport.StreamDelegate))
44 },
45 MaxHeaderBytes: 1 << 10, // 1KB
46 ReadHeaderTimeout: time.Second * 3,
47 Handler: rpcHandler,
48 ErrorLog: util.GetStdLogger(c.Logger, "queryServer"),
49 }
50 
51 go srv.Serve(c.rpcAcceptor)
52 
53 router.HandleTunnel(protocol.Stream_RPC, func(delegate *transport.StreamDelegate) {
54 c.rpcAcceptor.Handle(delegate)
55 })
56}
57 
58func (c *Client) ListTunnels(ctx context.Context, _ *protocol.ListTunnelsRequest) (*protocol.ListTunnelsResponse, error) {
59 c.configMu.RLock()
60 cfg := c.Configuration.clone()
61 c.configMu.RUnlock()
62 
63 tunnels := make([]*protocol.ClientTunnel, 0)
64 for _, tunnel := range cfg.Tunnels {
65 tunnels = append(tunnels, &protocol.ClientTunnel{
66 Hostname: tunnel.Hostname,
67 Target: tunnel.Target,
68 })
69 }
70 
71 return &protocol.ListTunnelsResponse{
72 Tunnels: tunnels,
73 }, nil
74}
75 
76type ClientStatus struct {
77 Apex string `json:"apex"`
78 ConnectedNodes []*protocol.Node `json:"connectedNodes"`
79 Synchronization SyncResult `json:"synchronization"`
80 Pending bool `json:"pending"`
81 RetryAt *time.Time `json:"retryAt,omitempty"`
82}
83 
84func (c *Client) getStatus() ClientStatus {
85 c.configMu.RLock()
86 defer c.configMu.RUnlock()
87 c.syncStateMu.RLock()
88 defer c.syncStateMu.RUnlock()
89 
90 result := c.lastSync
91 result.Tunnels = make([]TunnelSyncResult, 0, len(c.Configuration.Tunnels))
92 for _, tunnel := range c.Configuration.Tunnels {
93 outcome := TunnelSyncResult{Hostname: tunnel.Hostname, Target: tunnel.Target}
94 for _, previous := range c.lastSync.Tunnels {
95 if previous.Hostname == tunnel.Hostname && previous.Target == tunnel.Target {
96 outcome = previous
97 break
98 }
99 }
100 result.Tunnels = append(result.Tunnels, outcome)
101 }
102 status := ClientStatus{
103 Apex: c.Configuration.Apex, ConnectedNodes: c.getConnectedNodes(),
104 Synchronization: result, Pending: result.pendingPublication(),
105 }
106 if status.ConnectedNodes == nil {
107 status.ConnectedNodes = []*protocol.Node{}
108 }
109 if status.Pending {
110 next := c.nextSync
111 status.RetryAt = &next
112 }
113 return status
114}
115 
116func writeJSONResult(w http.ResponseWriter, status int, result any) {
117 w.Header().Set("Content-Type", "application/json")
118 w.WriteHeader(status)
119 json.NewEncoder(w).Encode(result)
120}
121 
122func writeActionError(w http.ResponseWriter, err error) {
123 var saveError *ConfigSaveError
124 writeJSONResult(w, http.StatusInternalServerError, SyncResult{
125 Applied: errors.As(err, &saveError), Error: err.Error(), Tunnels: []TunnelSyncResult{},
126 })
127}
128 
129func (c *Client) localHandler() http.Handler {
130 r := chi.NewRouter()
131 
132 r.Use(middleware.Heartbeat("/healthz"))
133 
134 api := chi.NewRouter()
135 api.With(middleware.SetHeader("Cache-Control", "no-store")).Get("/waf", c.getHostWAFHandler)
136 api.With(middleware.SetHeader("Cache-Control", "no-store"), http.NewCrossOriginProtection().Handler, util.LimitBody(maxHostWAFRequestBytes)).Put("/waf", c.setHostWAFHandler)
137 
138 api.Route("/tokens", func(tokens chi.Router) {
139 tokens.Use(func(next http.Handler) http.Handler {
140 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
141 w.Header().Set("Cache-Control", "no-store")
142 w.Header().Set("Content-Type", "application/json")
143 next.ServeHTTP(w, r)
144 })
145 })
146 tokens.Get("/", func(w http.ResponseWriter, r *http.Request) {
147 resp, err := c.ListDelegations(r.Context())
148 if err != nil {
149 writeDelegationError(w, err)
150 return
151 }
152 c.FormatDelegations(resp, w)
153 })
154 tokens.With(util.LimitBody(1<<10)).Post("/", func(w http.ResponseWriter, r *http.Request) {
155 var body struct {
156 Hostname string `json:"hostname"`
157 ExpiresAt string `json:"expiresAt"`
158 }
159 decoder := json.NewDecoder(r.Body)
160 if err := decoder.Decode(&body); err != nil {
161 writeDelegationError(w, twirp.InvalidArgument.Error("invalid token request body"))
162 return
163 }
164 if err := decoder.Decode(new(any)); err != io.EOF {
165 writeDelegationError(w, twirp.InvalidArgument.Error("invalid token request body"))
166 return
167 }
168 var expiry time.Time
169 if body.ExpiresAt != "" {
170 parsed, err := time.Parse(time.RFC3339, body.ExpiresAt)
171 if err != nil {
172 writeDelegationError(w, twirp.InvalidArgument.Error("expiresAt must be RFC3339"))
173 return
174 }
175 expiry = parsed
176 }
177 resp, err := c.MintDelegation(r.Context(), body.Hostname, expiry)
178 if err != nil {
179 writeDelegationError(w, err)
180 return
181 }
182 w.WriteHeader(http.StatusCreated)
183 c.FormatMintedDelegation(resp, w)
184 })
185 tokens.Post("/{id}/revoke", func(w http.ResponseWriter, r *http.Request) {
186 resp, err := c.RevokeDelegation(r.Context(), chi.URLParam(r, "id"))
187 if err != nil {
188 writeDelegationError(w, err)
189 return
190 }
191 c.FormatRevokedDelegation(resp, w)
192 })
193 })
194 
195 api.Post("/reload", func(w http.ResponseWriter, r *http.Request) {
196 c.Logger.Info("Received request from API, reloading config")
197 result := c.doReload(r.Context())
198 if result.Error == "" {
199 w.WriteHeader(http.StatusNoContent)
200 return
201 }
202 status := http.StatusInternalServerError
203 if !result.Applied {
204 status = http.StatusBadRequest
205 }
206 writeJSONResult(w, status, result)
207 })
208 
209 api.Get("/status", func(w http.ResponseWriter, r *http.Request) {
210 w.Header().Set("Cache-Control", "no-store")
211 writeJSONResult(w, http.StatusOK, c.getStatus())
212 })
213 
214 api.Get("/config", func(w http.ResponseWriter, r *http.Request) {
215 cfg := c.GetCurrentConfig()
216 f, err := os.Open(cfg.path)
217 if err != nil {
218 http.Error(w, err.Error(), 500)
219 return
220 }
221 defer f.Close()
222 io.Copy(w, f)
223 })
224 
225 api.Post("/unpublish/{hostname}", func(w http.ResponseWriter, r *http.Request) {
226 hostname := chi.URLParam(r, "hostname")
227 hostname, err := url.PathUnescape(hostname)
228 if err != nil {
229 http.Error(w, err.Error(), http.StatusBadRequest)
230 return
231 }
232 hostname, err = acme.Normalize(hostname)
233 if err != nil {
234 http.Error(w, err.Error(), http.StatusBadRequest)
235 return
236 }
237 
238 err = c.UnpublishTunnel(r.Context(), Tunnel{
239 Hostname: hostname,
240 })
241 if err != nil {
242 writeActionError(w, err)
243 return
244 }
245 
246 fmt.Fprintf(w, "Tunnel %s unpublished from network\n", hostname)
247 })
248 
249 api.Post("/release/{hostname}", func(w http.ResponseWriter, r *http.Request) {
250 hostname := chi.URLParam(r, "hostname")
251 hostname, err := url.PathUnescape(hostname)
252 if err != nil {
253 http.Error(w, err.Error(), http.StatusBadRequest)
254 return
255 }
256 hostname, err = acme.Normalize(hostname)
257 if err != nil {
258 http.Error(w, err.Error(), http.StatusBadRequest)
259 return
260 }
261 
262 err = c.ReleaseTunnel(r.Context(), Tunnel{
263 Hostname: hostname,
264 })
265 if err != nil {
266 writeActionError(w, err)
267 return
268 }
269 
270 fmt.Fprintf(w, "Tunnel %s released from network\n", hostname)
271 })
272 
273 api.Get("/acme/{hostname}", func(w http.ResponseWriter, r *http.Request) {
274 hostname := chi.URLParam(r, "hostname")
275 hostname, err := url.PathUnescape(hostname)
276 if err != nil {
277 http.Error(w, err.Error(), http.StatusBadRequest)
278 return
279 }
280 hostname, err = acme.Normalize(hostname)
281 if err != nil {
282 http.Error(w, err.Error(), http.StatusBadRequest)
283 return
284 }
285 resp, err := c.GetAcmeInstruction(r.Context(), hostname)
286 if err != nil {
287 http.Error(w, err.Error(), http.StatusInternalServerError)
288 return
289 }
290 c.FormatAcme(resp, w)
291 })
292 
293 api.Get("/validate/{hostname}", func(w http.ResponseWriter, r *http.Request) {
294 hostname := chi.URLParam(r, "hostname")
295 hostname, err := url.PathUnescape(hostname)
296 if err != nil {
297 http.Error(w, err.Error(), http.StatusBadRequest)
298 return
299 }
300 hostname, err = acme.Normalize(hostname)
301 if err != nil {
302 http.Error(w, err.Error(), http.StatusBadRequest)
303 return
304 }
305 resp, err := c.RequestAcmeValidation(r.Context(), hostname)
306 if err != nil {
307 http.Error(w, err.Error(), http.StatusInternalServerError)
308 return
309 }
310 c.FormatValidate(hostname, resp, w)
311 })
312 
313 api.Get("/ls", func(w http.ResponseWriter, r *http.Request) {
314 hostnames, err := c.GetRegisteredHostnames(r.Context())
315 if err != nil {
316 http.Error(w, err.Error(), http.StatusInternalServerError)
317 return
318 }
319 c.FormatList(hostnames, w)
320 })
321 
322 r.Mount("/api", api)
323 r.Handle("/ui/*", http.StripPrefix("/ui", ui.Assets()))
324 r.Handle("/", ui.ClientPage())
325 
326 return r
327}
328 
329func (c *Client) startLocalServer(ctx context.Context) {
330 if c.ServerListener == nil {
331 return
332 }
333 
334 srv := &http.Server{
335 Handler: c.localHandler(),
336 ReadHeaderTimeout: connectTimeout,
337 ErrorLog: util.GetStdLogger(c.Logger, "localServer"),
338 BaseContext: func(l net.Listener) context.Context {
339 return ctx
340 },
341 }
342 
343 c.Logger.Info("Local server started", zap.String("listen", c.ServerListener.Addr().String()))
344 
345 go srv.Serve(c.ServerListener)
346}
347 
348func writeDelegationError(w http.ResponseWriter, err error) {
349 status := http.StatusInternalServerError
350 var te twirp.Error
351 if errors.Is(err, ErrDelegationUnsupported) {
352 status = http.StatusNotImplemented
353 } else if errors.As(err, &te) {
354 switch te.Code() {
355 case twirp.InvalidArgument:
356 status = http.StatusBadRequest
357 case twirp.PermissionDenied:
358 status = http.StatusForbidden
359 case twirp.Unauthenticated:
360 status = http.StatusUnauthorized
361 case twirp.NotFound:
362 status = http.StatusNotFound
363 case twirp.ResourceExhausted:
364 status = http.StatusTooManyRequests
365 }
366 }
367 writeJSONResult(w, status, struct {
368 Error string `json:"error"`
369 }{err.Error()})
370}