http.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. // SourceConfig is what we need to know about a source to authenticate
  43. // + rate-limit it. The full Sources row has more fields; this is the
  44. // hot-path subset.
  45. type SourceConfig struct {
  46. CompanyID string
  47. HMACSecret []byte
  48. RateLimitPerSec int
  49. AllowedTargets []string // M2
  50. }
  51. // AcceptResponse is the JSON body returned on 202.
  52. type AcceptResponse struct {
  53. AlertID string `json:"alert_id"`
  54. DedupeCount uint32 `json:"dedupe_count"`
  55. ReceivedAt string `json:"received_at"`
  56. }
  57. // RegisterRoutes wires the ingestd HTTP routes onto the given mux.
  58. func RegisterRoutes(mux *http.ServeMux, d *httpDeps) {
  59. mux.HandleFunc("POST /v1/ingest", d.handleIngest)
  60. }
  61. // handleIngest is the M0 HTTP POST endpoint. The body of the
  62. // pipeline is the shared processDeps.ProcessAlert; this handler
  63. // only adds the HTTP-specific bits (MaxBytesReader, header
  64. // signature, response shape).
  65. func (d *httpDeps) handleIngest(w http.ResponseWriter, r *http.Request) {
  66. // 1. Payload-size cap. We use MaxBytesReader so a streaming
  67. // client can't lie about Content-Length and try to OOM us.
  68. r.Body = http.MaxBytesReader(w, r.Body, int64(d.MaxBytes))
  69. body, err := io.ReadAll(r.Body)
  70. if err != nil {
  71. var maxErr *http.MaxBytesError
  72. if errors.As(err, &maxErr) {
  73. d.Metrics.AlertsReceived.WithLabelValues("payload_too_large").Inc()
  74. writeErr(w, http.StatusRequestEntityTooLarge, "payload_too_large", "")
  75. return
  76. }
  77. d.Metrics.AlertsReceived.WithLabelValues("invalid").Inc()
  78. writeErr(w, http.StatusBadRequest, "bad_request", err.Error())
  79. return
  80. }
  81. _ = r.Body.Close()
  82. res := d.ProcessAlert(r.Context(), body, r.Header.Get("X-BA-Signature"))
  83. if !res.Accepted {
  84. // Rate-limit rejections get a Retry-After header.
  85. if res.RejectReason == "rate_limited_source" || res.RejectReason == "rate_limited_company" {
  86. if n, err := strconv.Atoi(res.Detail); err == nil {
  87. w.Header().Set("Retry-After", strconv.Itoa(n))
  88. }
  89. }
  90. writeErr(w, res.HTTPStatus, res.RejectReason, res.Detail)
  91. return
  92. }
  93. w.Header().Set("Content-Type", "application/json")
  94. w.WriteHeader(http.StatusAccepted)
  95. _ = json.NewEncoder(w).Encode(AcceptResponse{
  96. AlertID: res.AlertID,
  97. DedupeCount: res.DedupeCount,
  98. ReceivedAt: time.Now().UTC().Format(time.RFC3339Nano),
  99. })
  100. }
  101. // now is a thin alias for processDeps.now (kept here so the
  102. // existing tests that call d.now() on httpDeps still work).
  103. func (d *httpDeps) now() time.Time { return d.processDeps.now() }
  104. // verifyHMAC parses `X-BA-Signature: t=<unix>,v1=<hex>` and checks
  105. // HMAC-SHA256(secret, "<unix>.<body>") == hex. Replay window: 5 min.
  106. func verifyHMAC(header string, secret, body []byte, now time.Time) bool {
  107. if header == "" || len(secret) == 0 {
  108. return false
  109. }
  110. var tsStr, sigHex string
  111. for _, part := range strings.Split(header, ",") {
  112. kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
  113. if len(kv) != 2 {
  114. continue
  115. }
  116. switch kv[0] {
  117. case "t":
  118. tsStr = kv[1]
  119. case "v1":
  120. sigHex = kv[1]
  121. }
  122. }
  123. if tsStr == "" || sigHex == "" {
  124. return false
  125. }
  126. tsInt, err := strconv.ParseInt(tsStr, 10, 64)
  127. if err != nil {
  128. return false
  129. }
  130. ts := time.Unix(tsInt, 0)
  131. if abs(now.Sub(ts)) > 5*time.Minute {
  132. return false
  133. }
  134. mac := hmac.New(sha256.New, secret)
  135. mac.Write([]byte(tsStr))
  136. mac.Write([]byte("."))
  137. mac.Write(body)
  138. expected := mac.Sum(nil)
  139. got, err := hex.DecodeString(sigHex)
  140. if err != nil {
  141. return false
  142. }
  143. return subtle.ConstantTimeCompare(expected, got) == 1
  144. }
  145. func abs(d time.Duration) time.Duration {
  146. if d < 0 {
  147. return -d
  148. }
  149. return d
  150. }
  151. func writeErr(w http.ResponseWriter, code int, reason, detail string) {
  152. w.Header().Set("Content-Type", "application/json")
  153. w.WriteHeader(code)
  154. body := map[string]string{"error": reason}
  155. if detail != "" {
  156. body["detail"] = detail
  157. }
  158. _ = json.NewEncoder(w).Encode(body)
  159. }
  160. // loadSourcesFromEnv parses BA_INGESTD_SOURCES as a comma-separated
  161. // list of company_id:source_id:secret triples. M0 dev-mode only;
  162. // M2 swaps this for a Postgres lookup.
  163. func loadSourcesFromEnv(logger *slog.Logger) map[string]SourceConfig {
  164. out := map[string]SourceConfig{}
  165. raw := os.Getenv("BA_INGESTD_SOURCES")
  166. if raw == "" {
  167. logger.Warn("no BA_INGESTD_SOURCES configured; ingestd will reject all sources")
  168. return out
  169. }
  170. for _, triple := range strings.Split(raw, ",") {
  171. parts := strings.SplitN(triple, ":", 3)
  172. if len(parts) != 3 {
  173. logger.Warn("bad BA_INGESTD_SOURCES entry, expected company:source:secret", "entry", triple)
  174. continue
  175. }
  176. key := parts[0] + ":" + parts[1]
  177. out[key] = SourceConfig{
  178. CompanyID: parts[0],
  179. HMACSecret: []byte(parts[2]),
  180. RateLimitPerSec: config.GetInt("BA_INGESTD_RATE_LIMIT_PER_SOURCE", 100),
  181. }
  182. }
  183. logger.Info("loaded sources from env", "count", len(out))
  184. return out
  185. }