http.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // HTTP POST handler for ingestd. Implements the seven protection
  2. // layers from SPEC §22 in order:
  3. //
  4. // 1. payload-size cap
  5. // 2. (per-IP) — M1: deferred to M5 with the WS path
  6. // 3. per-source token bucket
  7. // 4. per-company token bucket
  8. // 5. schema validate
  9. // 6. (broker CB) — M9
  10. // 7. (quarantine) — M9
  11. //
  12. // Auth: Stripe-style HMAC-SHA256 in header `X-BA-Signature: t=<ts>,v1=<hex>`.
  13. // The source's secret is keyed by (company_id, source_id) — for M0
  14. // the secret is fetched from the source table; for M0 the simplest
  15. // impl is a single env var per source, but we go straight to the
  16. // DB lookup so M2 doesn't have to change this path.
  17. package main
  18. import (
  19. "crypto/hmac"
  20. "crypto/sha256"
  21. "crypto/subtle"
  22. "encoding/hex"
  23. "encoding/json"
  24. "errors"
  25. "io"
  26. "log/slog"
  27. "net/http"
  28. "os"
  29. "strconv"
  30. "strings"
  31. "time"
  32. "git3.techno-world.net/lrosales/broad-announce/internal/config"
  33. )
  34. // httpDeps is the HTTP-handler-scoped wrapper. It embeds
  35. // processDeps (the shared pipeline used by both HTTP and MQTT)
  36. // and adds the HTTP-only fields (MaxBytes, raw request/response
  37. // types). The body of the handler is a single ProcessAlert call.
  38. type httpDeps struct {
  39. processDeps
  40. MaxBytes int
  41. }
  42. // AcceptResponse is the JSON body returned on 202.
  43. type AcceptResponse struct {
  44. AlertID string `json:"alert_id"`
  45. DedupeCount uint32 `json:"dedupe_count"`
  46. ReceivedAt string `json:"received_at"`
  47. }
  48. // RegisterRoutes wires the ingestd HTTP routes onto the given mux.
  49. func RegisterRoutes(mux *http.ServeMux, d *httpDeps) {
  50. mux.HandleFunc("POST /v1/ingest", d.handleIngest)
  51. }
  52. // handleIngest is the M0 HTTP POST endpoint. The body of the
  53. // pipeline is the shared processDeps.ProcessAlert; this handler
  54. // only adds the HTTP-specific bits (MaxBytesReader, header
  55. // signature, response shape).
  56. func (d *httpDeps) handleIngest(w http.ResponseWriter, r *http.Request) {
  57. // 1. Payload-size cap. We use MaxBytesReader so a streaming
  58. // client can't lie about Content-Length and try to OOM us.
  59. r.Body = http.MaxBytesReader(w, r.Body, int64(d.MaxBytes))
  60. body, err := io.ReadAll(r.Body)
  61. if err != nil {
  62. var maxErr *http.MaxBytesError
  63. if errors.As(err, &maxErr) {
  64. d.Metrics.AlertsReceived.WithLabelValues("payload_too_large").Inc()
  65. writeErr(w, http.StatusRequestEntityTooLarge, "payload_too_large", "")
  66. return
  67. }
  68. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  69. writeErr(w, http.StatusBadRequest, "bad_request", err.Error())
  70. return
  71. }
  72. _ = r.Body.Close()
  73. res := d.ProcessAlert(r.Context(), body, r.Header.Get("X-BA-Signature"))
  74. if !res.Accepted {
  75. // Rate-limit rejections get a Retry-After header.
  76. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  77. if n, err := strconv.Atoi(res.Detail); err == nil {
  78. w.Header().Set("Retry-After", strconv.Itoa(n))
  79. }
  80. }
  81. writeErr(w, res.HTTPStatus, res.RejectReason, res.Detail)
  82. return
  83. }
  84. w.Header().Set("Content-Type", "application/json")
  85. w.WriteHeader(http.StatusAccepted)
  86. _ = json.NewEncoder(w).Encode(AcceptResponse{
  87. AlertID: res.AlertID,
  88. DedupeCount: res.DedupeCount,
  89. ReceivedAt: time.Now().UTC().Format(time.RFC3339Nano),
  90. })
  91. }
  92. // now is a thin alias for processDeps.now (kept here so the
  93. // existing tests that call d.now() on httpDeps still work).
  94. func (d *httpDeps) now() time.Time { return d.processDeps.Now() }
  95. // verifyHMAC parses `X-BA-Signature: t=<unix>,v1=<hex>` and checks
  96. // HMAC-SHA256(secret, "<unix>.<body>") == hex. Replay window: 5 min.
  97. func verifyHMAC(header string, secret, body []byte, now time.Time) bool {
  98. if header == "" || len(secret) == 0 {
  99. return false
  100. }
  101. var tsStr, sigHex string
  102. for _, part := range strings.Split(header, ",") {
  103. kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
  104. if len(kv) != 2 {
  105. continue
  106. }
  107. switch kv[0] {
  108. case "t":
  109. tsStr = kv[1]
  110. case "v1":
  111. sigHex = kv[1]
  112. }
  113. }
  114. if tsStr == "" || sigHex == "" {
  115. return false
  116. }
  117. tsInt, err := strconv.ParseInt(tsStr, 10, 64)
  118. if err != nil {
  119. return false
  120. }
  121. ts := time.Unix(tsInt, 0)
  122. if abs(now.Sub(ts)) > 5*time.Minute {
  123. return false
  124. }
  125. mac := hmac.New(sha256.New, secret)
  126. mac.Write([]byte(tsStr))
  127. mac.Write([]byte("."))
  128. mac.Write(body)
  129. expected := mac.Sum(nil)
  130. got, err := hex.DecodeString(sigHex)
  131. if err != nil {
  132. return false
  133. }
  134. return subtle.ConstantTimeCompare(expected, got) == 1
  135. }
  136. func abs(d time.Duration) time.Duration {
  137. if d < 0 {
  138. return -d
  139. }
  140. return d
  141. }
  142. func writeErr(w http.ResponseWriter, code int, reason, detail string) {
  143. w.Header().Set("Content-Type", "application/json")
  144. w.WriteHeader(code)
  145. body := map[string]string{"error": reason}
  146. if detail != "" {
  147. body["detail"] = detail
  148. }
  149. _ = json.NewEncoder(w).Encode(body)
  150. }
  151. // loadSourcesFromEnv parses BA_INGESTD_SOURCES as a comma-separated
  152. // list of company_id:source_id:secret triples. M0 dev-mode only;
  153. // M2 swaps this for a Postgres lookup.
  154. func loadSourcesFromEnv(logger *slog.Logger) map[string]SourceConfig {
  155. out := map[string]SourceConfig{}
  156. raw := os.Getenv("BA_INGESTD_SOURCES")
  157. if raw == "" {
  158. logger.Warn("no BA_INGESTD_SOURCES configured; ingestd will reject all sources")
  159. return out
  160. }
  161. for _, triple := range strings.Split(raw, ",") {
  162. parts := strings.SplitN(triple, ":", 3)
  163. if len(parts) != 3 {
  164. logger.Warn("bad BA_INGESTD_SOURCES entry, expected company:source:secret", "entry", triple)
  165. continue
  166. }
  167. key := parts[0] + ":" + parts[1]
  168. out[key] = SourceConfig{
  169. CompanyID: parts[0],
  170. HMACSecret: []byte(parts[2]),
  171. RateLimitPerSec: config.GetInt("BA_INGESTD_RATE_LIMIT_PER_SOURCE", 100),
  172. }
  173. }
  174. logger.Info("loaded sources from env", "count", len(out))
  175. return out
  176. }