File
Blob: acme/dns_config_handler.go
| 1 | package acme |
| 2 | |
| 3 | import ( |
| 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 | |
| 20 | type dnsConfigHandler struct { |
| 21 | store *config.Store |
| 22 | identity *protocol.Node |
| 23 | zone string |
| 24 | logger *zap.Logger |
| 25 | wake func() |
| 26 | } |
| 27 | |
| 28 | type configServerIdentity struct { |
| 29 | ID string `json:"id"` |
| 30 | Address string `json:"address"` |
| 31 | } |
| 32 | |
| 33 | type dnsConfigResponse struct { |
| 34 | Version string `json:"version"` |
| 35 | Config *DNSConfig `json:"config"` |
| 36 | Server configServerIdentity `json:"server"` |
| 37 | ObservedAt time.Time `json:"observed_at"` |
| 38 | Error string `json:"error,omitempty"` |
| 39 | } |
| 40 | |
| 41 | // DNSConfigHandler serves the DNS document editor API. Mount it behind operator authentication. |
| 42 | func DNSConfigHandler(store *config.Store, identity *protocol.Node, zone string, logger *zap.Logger, wake func()) http.Handler { |
| 43 | h := &dnsConfigHandler{store: store, identity: identity, zone: zone, logger: logger, wake: wake} |
| 44 | router := chi.NewRouter() |
| 45 | router.Use(middleware.SetHeader("Cache-Control", "no-store")) |
| 46 | router.Get("/dns", h.get) |
| 47 | router.With(util.LimitBody(config.MaxValueBytes+4096)).Put("/dns", h.put) |
| 48 | return router |
| 49 | } |
| 50 | |
| 51 | func (h *dnsConfigHandler) response(record config.Record, found bool) dnsConfigResponse { |
| 52 | response := dnsConfigResponse{ |
| 53 | Server: configServerIdentity{ID: strconv.FormatUint(h.identity.GetId(), 10), Address: h.identity.GetAddress()}, |
| 54 | ObservedAt: time.Now().UTC(), |
| 55 | } |
| 56 | if found { |
| 57 | response.Version = record.Token() |
| 58 | dnsConfig, err := DecodeDNSConfig(record, h.zone) |
| 59 | if err != nil { |
| 60 | response.Error = err.Error() |
| 61 | } else { |
| 62 | response.Config = &dnsConfig |
| 63 | } |
| 64 | } |
| 65 | return response |
| 66 | } |
| 67 | |
| 68 | func (h *dnsConfigHandler) get(w http.ResponseWriter, r *http.Request) { |
| 69 | record, found, err := h.store.Get(DNSConfigName) |
| 70 | if err != nil { |
| 71 | h.logger.Error("Could not read shared DNS configuration", zap.Error(err)) |
| 72 | config.WriteJSON(w, http.StatusServiceUnavailable, config.HTTPErrorResponse{Code: "not_ready", Message: "Could not read the configuration on this server. Try refreshing again shortly."}) |
| 73 | return |
| 74 | } |
| 75 | // Keep this editor's reads from moving backward without waiting for peers. |
| 76 | if after := r.URL.Query().Get("after"); after != "" { |
| 77 | if !found { |
| 78 | // Validate the token's scope even before this replica has a document. |
| 79 | record.Name = DNSConfigName |
| 80 | } |
| 81 | comparison, err := record.CompareVersion(after) |
| 82 | if err != nil { |
| 83 | config.WriteJSON(w, http.StatusBadRequest, config.HTTPErrorResponse{Code: "invalid_version", Message: "The configuration version is invalid."}) |
| 84 | return |
| 85 | } |
| 86 | if !found || comparison < 0 { |
| 87 | config.WriteJSON(w, http.StatusServiceUnavailable, config.HTTPErrorResponse{Code: "not_ready", Message: "This server has not caught up with the configuration you last viewed. Try again shortly."}) |
| 88 | return |
| 89 | } |
| 90 | } |
| 91 | config.WriteJSON(w, http.StatusOK, h.response(record, found)) |
| 92 | } |
| 93 | |
| 94 | func (h *dnsConfigHandler) put(w http.ResponseWriter, r *http.Request) { |
| 95 | mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 96 | if err != nil || mediaType != "application/json" { |
| 97 | config.WriteJSON(w, http.StatusUnsupportedMediaType, config.HTTPErrorResponse{Code: "validation_failed", Message: "Send configuration as application/json."}) |
| 98 | return |
| 99 | } |
| 100 | var input struct { |
| 101 | ExpectedVersion string `json:"expected_version"` |
| 102 | Config DNSConfig `json:"config"` |
| 103 | } |
| 104 | if err := util.DecodeJSON(r.Body, &input); err != nil { |
| 105 | config.WriteJSON(w, http.StatusBadRequest, config.HTTPErrorResponse{Code: "validation_failed", Message: "Invalid configuration JSON."}) |
| 106 | return |
| 107 | } |
| 108 | current, found, err := h.store.Get(DNSConfigName) |
| 109 | if err != nil { |
| 110 | h.logger.Error("Could not read shared DNS configuration", zap.Error(err)) |
| 111 | config.WriteJSON(w, http.StatusServiceUnavailable, config.HTTPErrorResponse{Code: "not_ready", Message: "Could not read the configuration on this server. Try again shortly."}) |
| 112 | return |
| 113 | } |
| 114 | if current.Token() != input.ExpectedVersion { |
| 115 | h.conflict(w) |
| 116 | return |
| 117 | } |
| 118 | zone := h.zone |
| 119 | if found { |
| 120 | previous, err := DecodeDNSConfig(current, h.zone) |
| 121 | if err != nil { |
| 122 | config.WriteJSON(w, http.StatusConflict, config.HTTPErrorResponse{Code: "unsupported_configuration", Message: "This server cannot edit the stored DNS configuration. Use a compatible Specter version."}) |
| 123 | return |
| 124 | } |
| 125 | // Changing the hosted zone also changes deployment and certificate |
| 126 | // settings; the DNS records editor does not perform that migration. |
| 127 | zone = previous.Zone |
| 128 | } |
| 129 | dnsConfig, err := ValidateDNSConfig(input.Config, zone) |
| 130 | if err != nil { |
| 131 | response := config.HTTPErrorResponse{Code: "validation_failed", Message: err.Error()} |
| 132 | var field *DNSConfigError |
| 133 | if errors.As(err, &field) { |
| 134 | response.Fields = map[string]string{field.Field: field.Message} |
| 135 | } |
| 136 | config.WriteJSON(w, http.StatusBadRequest, response) |
| 137 | return |
| 138 | } |
| 139 | payload, err := json.Marshal(dnsConfig) |
| 140 | if err != nil { |
| 141 | config.WriteJSON(w, http.StatusInternalServerError, config.HTTPErrorResponse{Code: "save_failed", Message: "Could not encode the configuration."}) |
| 142 | return |
| 143 | } |
| 144 | record, err := h.store.Put(DNSConfigName, DNSConfigSchema, payload, input.ExpectedVersion) |
| 145 | if h.wake != nil && (err == nil || errors.Is(err, config.ErrDurabilityUncertain)) { |
| 146 | h.wake() |
| 147 | } |
| 148 | if !config.WriteSaveError(w, DNSConfigName, h.logger, err) { |
| 149 | config.WriteJSON(w, http.StatusOK, h.response(record, true)) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | func (h *dnsConfigHandler) conflict(w http.ResponseWriter) { |
| 154 | config.WriteJSON(w, http.StatusConflict, config.HTTPErrorResponse{Code: "version_conflict", Message: "The stored configuration changed. Load the latest settings before saving again."}) |
| 155 | } |