Skip to content
File

Blob: waf/handler.go

go136 lines
1package waf
2 
3import (
4 "encoding/json"
5 "errors"
6 "mime"
7 "net/http"
8 "strconv"
9 "time"
10 
11 "go.miragespace.co/specter/config"
12 "go.miragespace.co/specter/spec/protocol"
13 "go.miragespace.co/specter/util"
14 
15 "github.com/go-chi/chi/v5"
16 "github.com/go-chi/chi/v5/middleware"
17 "go.uber.org/zap"
18)
19 
20type settingsResponse struct {
21 Version string `json:"version"`
22 Config json.RawMessage `json:"config"`
23 Server settingsServer `json:"server"`
24 ObservedAt time.Time `json:"observed_at"`
25 Status Status `json:"status"`
26 Error string `json:"error,omitempty"`
27}
28 
29type settingsServer struct {
30 ID string `json:"id"`
31 Address string `json:"address"`
32}
33 
34// SettingsHandler must be mounted behind the existing operator authentication.
35func SettingsHandler(store *config.Store, identity *protocol.Node, status func() Status, wake func(), logger *zap.Logger) http.Handler {
36 respond := func(w http.ResponseWriter, record config.Record, found bool) {
37 s := DefaultSettings()
38 response := settingsResponse{Version: record.Token(),
39 Server: settingsServer{ID: strconv.FormatUint(identity.GetId(), 10), Address: identity.GetAddress()},
40 ObservedAt: time.Now().UTC(), Status: status(),
41 }
42 if found {
43 decoded, err := DecodeSettings(record)
44 if err != nil {
45 s = nil
46 response.Error = err.Error()
47 } else {
48 s = decoded
49 }
50 }
51 if s != nil {
52 data, err := MarshalJSON(s)
53 if err != nil {
54 config.WriteJSON(w, http.StatusInternalServerError, config.HTTPErrorResponse{Code: "read_failed", Message: "Could not encode settings."})
55 return
56 }
57 response.Config = data
58 }
59 config.WriteJSON(w, http.StatusOK, response)
60 }
61 failure := func(w http.ResponseWriter, code int, name, message string) {
62 config.WriteJSON(w, code, config.HTTPErrorResponse{Code: name, Message: message})
63 }
64 router := chi.NewRouter()
65 router.Use(middleware.SetHeader("Cache-Control", "no-store"))
66 router.Get("/waf", func(w http.ResponseWriter, r *http.Request) {
67 record, found, err := store.Get(ConfigName)
68 if err != nil {
69 logger.Error("Could not read WAF settings", zap.Error(err))
70 failure(w, http.StatusServiceUnavailable, "not_ready", "Could not read settings on this server. Try refreshing shortly.")
71 return
72 }
73 if after := r.URL.Query().Get("after"); after != "" {
74 candidate := record
75 if !found {
76 candidate.Name = ConfigName
77 }
78 comparison, err := candidate.CompareVersion(after)
79 if err != nil {
80 failure(w, http.StatusBadRequest, "invalid_version", "The configuration version is invalid.")
81 return
82 }
83 if !found || comparison < 0 {
84 failure(w, http.StatusServiceUnavailable, "not_ready", "This server has not caught up with the settings you last viewed. Try again shortly.")
85 return
86 }
87 }
88 respond(w, record, found)
89 })
90 router.With(util.LimitBody(8<<10)).Put("/waf", func(w http.ResponseWriter, r *http.Request) {
91 mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
92 if err != nil || mediaType != "application/json" {
93 failure(w, http.StatusUnsupportedMediaType, "validation_failed", "Send settings as application/json.")
94 return
95 }
96 input := new(protocol.SetWAFSettingsRequest)
97 if err := DecodeJSON(r.Body, input); err != nil {
98 failure(w, http.StatusBadRequest, "validation_failed", "Invalid settings JSON.")
99 return
100 }
101 current, found, err := store.Get(ConfigName)
102 if err != nil {
103 failure(w, http.StatusServiceUnavailable, "not_ready", "Could not read settings on this server.")
104 return
105 }
106 if current.Token() != input.ExpectedVersion {
107 failure(w, http.StatusConflict, "version_conflict", "Settings changed. Load the latest settings before saving again.")
108 return
109 }
110 if found {
111 if _, err := DecodeSettings(current); err != nil {
112 failure(w, http.StatusConflict, "unsupported_configuration", "Use a compatible Specter version to edit the stored WAF settings.")
113 return
114 }
115 }
116 s, err := ValidateSettings(input.Config)
117 if err != nil {
118 failure(w, http.StatusBadRequest, "validation_failed", err.Error())
119 return
120 }
121 payload, err := MarshalJSON(s)
122 if err != nil {
123 failure(w, http.StatusInternalServerError, "save_failed", "Could not encode settings.")
124 return
125 }
126 record, err := store.Put(ConfigName, ConfigSchema, payload, input.ExpectedVersion)
127 if wake != nil && (err == nil || errors.Is(err, config.ErrDurabilityUncertain)) {
128 wake()
129 }
130 if !config.WriteSaveError(w, ConfigName, logger, err) {
131 respond(w, record, true)
132 }
133 })
134 return router
135}