A tiny, self-hosted notification inbox for developers. Something happened in one of your apps; Boop tells you on your phone.
HTML
fix: address Sentry compat PR review feedback
Ashwin M067d22919526
diff --git a/README.md b/README.mdindex e806e39..71dede8 100644--- a/README.md+++ b/README.md@@ -173,7 +173,7 @@ TypeScript, ESM + CJS, zero runtime dependencies, Node 18+.### Sentry SDKs — drop-in DSN-Boop speaks the Sentry ingest protocol, so any existing Sentry SDK (Python, Node, Go, Ruby, PHP, browser, …) can report to Boop with no code changes — just point the DSN at your Boop host and use a project API key as the public key:+Boop speaks the Sentry ingest protocol, so any existing server-side Sentry SDK (Python, Node, Go, Ruby, PHP, …) can report to Boop with no code changes — just point the DSN at your Boop host and use a project API key as the public key:```SENTRY_DSN=https://[email protected]/1@@ -181,6 +181,8 @@ SENTRY_DSN=https://[email protected]/1The part before `@` is a Boop project's API key; the host is your Boop server; the trailing project id is required by the DSN format but ignored (the key selects the project). Boop implements the SDK envelope endpoint (`/api/{id}/envelope/`) that every current Sentry SDK uses, including gzipped bodies.+> **Keep the DSN server-side.** A real Sentry DSN's public key is safe to ship in frontend bundles, but Boop's is a write-capable project API key — treat it like any other secret and don't embed it in browser or other client-side code.+Each Sentry event becomes a Boop event: the exception `Type: value` (or the message) is the title; the body carries the culprit, top stack frame and `env`/`release`; levels map `fatal→critical`, `error`, `warning`, `info`/`debug→info`; `source` is `sentry`; and Sentry's grouping fingerprint is preserved so [silence rules](#api) work per error group. Full event context (platform, tags, top frames) is kept in the event's `data` and redacted like any other event. Transactions, sessions and other non-error items are accepted and ignored.### Anything elsediff --git a/server/internal/api/api.go b/server/internal/api/api.goindex 7fdcfd4..d75c398 100644--- a/server/internal/api/api.go+++ b/server/internal/api/api.go@@ -66,7 +66,7 @@ func (s *Server) Handler() http.Handler {// Sentry SDK compatibility: point a Sentry DSN at Boop and existing Sentry// clients report here. The DSN public key is a Boop project API key; the// numeric project id in the path is ignored.- mux.HandleFunc("POST /api/{project_id}/envelope/", s.sentryEnvelope)+ mux.HandleFunc("POST /api/{project_id}/envelope/{$}", s.sentryEnvelope)// Reading events: device credential or the (unauthenticated) web UI.mux.Handle("GET /api/v1/events", s.readerAuth(s.listEvents))diff --git a/server/internal/api/sentry.go b/server/internal/api/sentry.goindex 8bb11be..2b5a58b 100644--- a/server/internal/api/sentry.go+++ b/server/internal/api/sentry.go@@ -16,8 +16,10 @@ import ("compress/zlib""context""encoding/json"+ "errors""io""net/http"+ "sort""strconv""strings""time"@@ -36,6 +38,15 @@ const (sentryMaxDecompressed = 16 << 20 // 16 MiB expanded)+// Bounds on the tag set copied into an event's data. A pathological tag set+// (many tags, or a single huge value) would otherwise push data past+// events.MaxDataSize, which Create rejects — silently dropping an event the SDK+// was told (200) it delivered.+const (+ maxSentryTags = 50+ maxSentryTagBytes = 1024+)+// sentryEnvelope accepts a Sentry SDK envelope: POST /api/{project_id}/envelope/.func (s *Server) sentryEnvelope(w http.ResponseWriter, r *http.Request) {p, ok := s.sentryAuth(w, r)@@ -101,9 +112,23 @@ func (s *Server) sentryBody(w http.ResponseWriter, r *http.Request) ([]byte, boo}defer zr.Close()reader = zr+ case "", "identity":+ // No encoding; read the body as-is.+ default:+ // Reject an encoding we can't decode rather than parsing the still-+ // compressed bytes as a plaintext envelope and silently storing nothing.+ writeError(w, http.StatusUnsupportedMediaType, "unsupported", "unsupported Content-Encoding")+ return nil, false}body, err := io.ReadAll(io.LimitReader(reader, sentryMaxDecompressed))if err != nil {+ // MaxBytesReader tripped: 413 so the SDK treats it as "too large, drop"+ // rather than retrying, matching readJSON on the native endpoint.+ var mbe *http.MaxBytesError+ if errors.As(err, &mbe) {+ writeError(w, http.StatusRequestEntityTooLarge, "too_large", "request body too large")+ return nil, false+ }writeError(w, http.StatusBadRequest, "invalid", "could not read request body")return nil, false}@@ -122,26 +147,29 @@ func (s *Server) ingestEnvelope(ctx context.Context, p projects.Project, body []if !ok {continue}- s.ingestOne(ctx, p, in)- if firstID == "" {- firstID = evID+ if s.ingestOne(ctx, p, in) {+ if firstID == "" {+ firstID = evID // echo only an id we actually stored+ }+ count++}- count++}return firstID, count}-// ingestOne stores one mapped event and pushes it unless a silence rule matches.-func (s *Server) ingestOne(ctx context.Context, p projects.Project, in events.Input) {+// ingestOne stores one mapped event and pushes it unless a silence rule matches,+// reporting whether it was actually stored.+func (s *Server) ingestOne(ctx context.Context, p projects.Project, in events.Input) bool {e, err := s.Events.Create(ctx, p.ID, in, s.redactor(ctx))if err != nil {s.Log.Warn("sentry.event_rejected", "project_id", p.ID, "error", err.Error())- return+ return false}s.Log.Info("event.created", "event_id", e.ID, "project_id", p.ID, "event_level", e.Level, "via", "sentry")if silenced := s.applySilence(ctx, &e); !silenced {s.Dispatcher.Enqueue(e, p)}+ return true}// ---- envelope parsing ----@@ -270,7 +298,7 @@ func (s *Server) mapSentryEvent(raw []byte) (events.Input, string, bool) {in.Title = firstLine(msg)}in.Body = sentryExceptionBody(ex, ev)- in.Fingerprint = sentryFingerprint(ev, "sentry:"+firstNonEmpty(ex.Type, ex.Module))+ in.Fingerprint = sentryFingerprint(ev, exceptionFingerprint(ex))if in.Level == "" {in.Level = levels.Error}@@ -278,7 +306,9 @@ func (s *Server) mapSentryEvent(raw []byte) (events.Input, string, bool) {in.Type = "message"in.Title = firstLine(msg)in.Body = sentryContextLine(ev)- in.Fingerprint = sentryFingerprint(ev, "sentry:msg:"+firstLine(msg))+ // Group on the unformatted template so interpolated messages ("user 1+ // failed", "user 2 failed") share a fingerprint, as they do in Sentry.+ in.Fingerprint = sentryFingerprint(ev, "sentry:msg:"+firstLine(sentryMessageTemplate(ev)))if in.Level == "" {in.Level = levels.Info}@@ -315,30 +345,64 @@ func sentryLevel(l string) string {}}-// sentryMessage returns the human message from a logentry or the message field,-// which may be a plain string or a {message, formatted} object.-func sentryMessage(ev sentryEvent) string {- if ev.Logentry.Formatted != "" {- return ev.Logentry.Formatted- }- if ev.Logentry.Message != "" {- return ev.Logentry.Message+// messageParts pulls the message template and its formatted rendering from a+// logentry or the message field (a plain string, or a {message, formatted}+// object). The title uses the formatted text (sentryMessage); grouping uses the+// unformatted template (sentryMessageTemplate).+func messageParts(ev sentryEvent) (template, formatted string) {+ if ev.Logentry.Message != "" || ev.Logentry.Formatted != "" {+ return ev.Logentry.Message, ev.Logentry.Formatted}if len(ev.Message) == 0 {- return ""+ return "", ""}var str stringif json.Unmarshal(ev.Message, &str) == nil && str != "" {- return str+ return str, str}var m struct {Message string `json:"message"`Formatted string `json:"formatted"`}if json.Unmarshal(ev.Message, &m) == nil {- return firstNonEmpty(m.Formatted, m.Message)+ return m.Message, m.Formatted}- return ""+ return "", ""+}++// sentryMessage returns the human-readable message, preferring the formatted+// (interpolated) text — this is what the title shows.+func sentryMessage(ev sentryEvent) string {+ t, f := messageParts(ev)+ return firstNonEmpty(f, t)+}++// sentryMessageTemplate returns the message used for grouping. Sentry groups+// message events on the unformatted template, not the interpolated result, so+// interpolated variants share a fingerprint.+func sentryMessageTemplate(ev sentryEvent) string {+ t, f := messageParts(ev)+ return firstNonEmpty(t, f)+}++// exceptionFingerprint derives a grouping key from the exception type plus the+// top in-app frame (module/function), approximating Sentry's stacktrace-based+// grouping so a silence rule can target one call site rather than every+// occurrence of an exception type across the project.+func exceptionFingerprint(ex sentryException) string {+ parts := []string{"sentry"}+ if t := firstNonEmpty(ex.Type, ex.Module); t != "" {+ parts = append(parts, t)+ }+ if fr, ok := topFrame(ex.Stacktrace.Frames); ok {+ if loc := firstNonEmpty(fr.Module, fr.Filename); loc != "" {+ parts = append(parts, loc)+ }+ if fr.Function != "" {+ parts = append(parts, fr.Function)+ }+ }+ return strings.Join(parts, ":")}// sentryExceptionBody builds a compact, phone-readable body: where it happened,@@ -446,14 +510,14 @@ func sentryData(ev sentryEvent) json.RawMessage {"culprit": ev.Culprit,} {if v != "" {- m[k] = v+ m[k] = clip(v, events.MaxBody) // bound each field so data can't exceed MaxDataSize}}if ev.Sdk.Name != "" {m["sdk"] = strings.TrimSuffix(ev.Sdk.Name+"/"+ev.Sdk.Version, "/")}- if len(ev.Tags) > 0 && string(ev.Tags) != "null" {- m["tags"] = json.RawMessage(ev.Tags)+ if tags := cappedTags(ev.Tags); len(tags) > 0 {+ m["tags"] = tags}if n := len(ev.Exception.Values); n > 0 {ex := ev.Exception.Values[n-1]@@ -462,7 +526,7 @@ func sentryData(ev sentryEvent) json.RawMessage {e["type"] = ex.Type}if ex.Value != "" {- e["value"] = ex.Value+ e["value"] = clip(ex.Value, events.MaxBody)}frames := ex.Stacktrace.Framesif start := len(frames) - 10; start > 0 { // keep at most the last 10 frames@@ -470,7 +534,7 @@ func sentryData(ev sentryEvent) json.RawMessage {}var out []map[string]anyfor _, fr := range frames {- out = append(out, map[string]any{"file": fr.Filename, "func": fr.Function, "line": fr.Lineno, "in_app": fr.InApp})+ out = append(out, map[string]any{"file": clip(fr.Filename, maxSentryTagBytes), "func": clip(fr.Function, maxSentryTagBytes), "line": fr.Lineno, "in_app": fr.InApp})}if len(out) > 0 {e["frames"] = out@@ -483,9 +547,67 @@ func sentryData(ev sentryEvent) json.RawMessage {if err != nil {return nil}+ if len(b) > events.MaxDataSize {+ // Last resort: shed the largest optional pieces so Create still accepts+ // the event rather than rejecting the whole thing for size.+ delete(m, "tags")+ delete(m, "exception")+ if b, err = json.Marshal(m); err != nil {+ return nil+ }+ }return json.RawMessage(b)}+// cappedTags copies Sentry tags into a bounded map, keeping the event's data+// under events.MaxDataSize. Tags arrive as an object {k: v} or, from older SDKs,+// an array of [k, v] pairs; values are rendered as display strings.+func cappedTags(raw json.RawMessage) map[string]string {+ if len(raw) == 0 || string(raw) == "null" {+ return nil+ }+ out := map[string]string{}+ add := func(k, v string) {+ if k == "" || len(out) >= maxSentryTags {+ return+ }+ out[clip(k, maxSentryTagBytes)] = clip(v, maxSentryTagBytes)+ }+ var obj map[string]json.RawMessage+ if json.Unmarshal(raw, &obj) == nil {+ // Sort so which tags survive the cap is deterministic, not dependent on+ // Go's randomized map iteration order.+ keys := make([]string, 0, len(obj))+ for k := range obj {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ add(k, tagValue(obj[k]))+ }+ return out+ }+ var pairs [][]json.RawMessage+ if json.Unmarshal(raw, &pairs) == nil {+ for _, p := range pairs {+ if len(p) == 2 {+ add(tagValue(p[0]), tagValue(p[1]))+ }+ }+ }+ return out+}++// tagValue renders a raw tag key or value as a display string, unquoting plain+// strings and passing other JSON through verbatim.+func tagValue(raw json.RawMessage) string {+ var s string+ if json.Unmarshal(raw, &s) == nil {+ return s+ }+ return string(raw)+}+// ---- small helpers ----func joinTypeValue(typ, val string) string {diff --git a/server/internal/api/sentry_test.go b/server/internal/api/sentry_test.goindex 9d939de..6f2508d 100644--- a/server/internal/api/sentry_test.go+++ b/server/internal/api/sentry_test.go@@ -48,7 +48,7 @@ func envelope(eventID string, event any) []byte {return b.Bytes()}-func (e *env) latestEvent(key string) events0 {+func (e *env) latestEvent() events0 {e.t.Helper()r := e.do("GET", "/api/v1/events?limit=1", "", nil)if r.status != 200 {@@ -107,7 +107,7 @@ func TestSentryExceptionEnvelope(t *testing.T) {t.Fatalf("echoed id = %q", id)}- got := e.latestEvent(key)+ got := e.latestEvent()if got.Level != "error" {t.Errorf("level = %q, want error", got.Level)}@@ -117,7 +117,9 @@ func TestSentryExceptionEnvelope(t *testing.T) {if got.Source != "sentry" || got.Type != "exception" {t.Errorf("source/type = %q/%q", got.Source, got.Type)}- if got.Fingerprint != "sentry:ValueError" {+ // Grouping folds in the top in-app frame, so two call sites raising the same+ // exception type get distinct fingerprints (closer to Sentry's grouping).+ if got.Fingerprint != "sentry:ValueError:app/views.py:charge" {t.Errorf("fingerprint = %q", got.Fingerprint)}if !strings.Contains(got.Body, "app/views.py:42 in charge") {@@ -142,7 +144,7 @@ func TestSentryMultilineExceptionTitle(t *testing.T) {if r := e.postSentry("/api/1/envelope/", key, nil, envelope("0", event)); r.status != 200 {t.Fatalf("status = %d", r.status)}- if got := e.latestEvent(key).Title; got != "ArgumentError: bad billing period" {+ if got := e.latestEvent().Title; got != "ArgumentError: bad billing period" {t.Errorf("title = %q, want clean single line", got)}}@@ -158,7 +160,7 @@ func TestSentryLevelMapping(t *testing.T) {if r.status != http.StatusOK {t.Fatalf("status = %d", r.status)}- got := e.latestEvent(key)+ got := e.latestEvent()if got.Level != want {t.Errorf("level %q mapped to %q, want %q", in, got.Level, want)}@@ -180,7 +182,7 @@ func TestSentryExplicitFingerprint(t *testing.T) {if r := e.postSentry("/api/1/envelope/", key, nil, envelope("0", event)); r.status != 200 {t.Fatalf("status = %d", r.status)}- if got := e.latestEvent(key).Fingerprint; got != "my-group:v2" {+ if got := e.latestEvent().Fingerprint; got != "my-group:v2" {t.Errorf("fingerprint = %q, want my-group:v2", got)}}@@ -202,7 +204,7 @@ func TestSentryGzipEnvelope(t *testing.T) {if r.status != http.StatusOK {t.Fatalf("status = %d (%s)", r.status, r.raw)}- got := e.latestEvent(key)+ got := e.latestEvent()if got.Level != "critical" || got.Title != "PanicError: kaboom" {t.Errorf("got level=%q title=%q", got.Level, got.Title)}@@ -253,3 +255,100 @@ func TestSentryTransactionItemsIgnored(t *testing.T) {}}}++// A single oversized tag value must not push data past events.MaxDataSize and+// silently drop the event: the tag is capped and the event is still stored.+func TestSentryOversizedTagStillStored(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ event := map[string]any{+ "event_id": "0",+ "message": "boom",+ "tags": map[string]any{"huge": strings.Repeat("x", 300*1024)},+ }+ if r := e.postSentry("/api/1/envelope/", key, nil, envelope("0", event)); r.status != http.StatusOK {+ t.Fatalf("status = %d", r.status)+ }+ got := e.latestEvent() // fatals if nothing was stored+ if got.Title != "boom" {+ t.Errorf("title = %q", got.Title)+ }+ if len(got.Data) > 256*1024 {+ t.Errorf("data not capped: %d bytes", len(got.Data))+ }+}++// A huge base field (culprit) is bounded too, so it can't push data past+// MaxDataSize and silently drop the event.+func TestSentryOversizedCulpritStillStored(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ event := map[string]any{+ "event_id": "0",+ "culprit": strings.Repeat("y", 300*1024),+ "exception": map[string]any{"values": []map[string]any{{+ "type": "ValueError", "value": "x",+ }}},+ }+ if r := e.postSentry("/api/1/envelope/", key, nil, envelope("0", event)); r.status != http.StatusOK {+ t.Fatalf("status = %d", r.status)+ }+ got := e.latestEvent() // fatals if nothing was stored+ if len(got.Data) > 256*1024 {+ t.Errorf("data not capped: %d bytes", len(got.Data))+ }+}++// An encoding Boop can't decode is rejected (415) rather than parsed as a+// plaintext envelope and silently storing nothing.+func TestSentryUnsupportedEncodingRejected(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ body := envelope("0", map[string]any{"message": "x"})+ r := e.postSentry("/api/1/envelope/", key, map[string]string{"Content-Encoding": "br"}, body)+ if r.status != http.StatusUnsupportedMediaType {+ t.Fatalf("status = %d, want 415", r.status)+ }+}++// Interpolated messages share a fingerprint because grouping uses the unformatted+// logentry template, not the formatted result.+func TestSentryMessageTemplateFingerprint(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ fp := func(formatted string) string {+ event := map[string]any{+ "event_id": "0",+ "logentry": map[string]any{"message": "user %s failed", "formatted": formatted},+ }+ if r := e.postSentry("/api/1/envelope/", key, nil, envelope("0", event)); r.status != 200 {+ t.Fatalf("status = %d", r.status)+ }+ return e.latestEvent().Fingerprint+ }+ if a, b := fp("user 1 failed"), fp("user 2 failed"); a != b || a != "sentry:msg:user %s failed" {+ t.Errorf("fingerprints = %q / %q, want equal sentry:msg:user %%s failed", a, b)+ }+}++// The envelope route matches only the exact path, not a subtree, so a trailing+// segment is a 404 rather than silently accepted.+func TestSentryEnvelopeSubpathNotMatched(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ r := e.postSentry("/api/1/envelope/anything/else", key, nil, envelope("0", map[string]any{"message": "x"}))+ if r.status != http.StatusNotFound {+ t.Fatalf("status = %d, want 404", r.status)+ }+}++// An over-large body answers 413 (payload too large) so SDKs drop it, matching+// the native endpoint, rather than 400.+func TestSentryOversizedBody(t *testing.T) {+ e := newEnv(t)+ _, key := e.createProject("app")+ big := bytes.Repeat([]byte("a"), 3<<20) // above sentryMaxCompressed+ if r := e.postSentry("/api/1/envelope/", key, nil, big); r.status != http.StatusRequestEntityTooLarge {+ t.Fatalf("status = %d, want 413", r.status)+ }+}