package events import ( "encoding/json" "strings" "testing" "unicode/utf8" ) const ping = `{"schema_version":1,"device_id":"sim-001","request_id":"req-001","issued_at":"2026-10-06T10:00:00Z","expires_at":"2026-10-06T10:00:15Z","command":"ping"}` func TestSafePreviews(t *testing.T) { p := SafePreview("commands", "sim-001", []byte(ping), 4096) if p.Omitted || !strings.Contains(p.Text, `"command":"ping"`) || p.Bytes != len(ping) { t.Fatal("lost useful preview") } for _, raw := range []string{`{"password":"SECRET"}`, `{"x":"SECRET`, string([]byte{255, 0}), strings.Replace(ping, `"command":"ping"`, `"command":"ping","token":"SECRET"`, 1)} { preview := SafePreview("commands", "sim-001", []byte(raw), 4096) encoded, _ := json.Marshal(preview) if !preview.Omitted || preview.Text != "" || strings.Contains(string(encoded), "SECRET") { t.Fatal("unsafe payload exposed") } } ack := `{"schema_version":1,"device_id":"sim-001","request_id":"req-001","timestamp":"2026-10-06T10:00:00Z","stage":"failed","ok":false,"error":{"code":"error","message":"password=SECRET"}}` p = SafePreview("acks", "sim-001", []byte(ack), 4096) if p.Omitted || strings.Contains(p.Text, "SECRET") || !strings.Contains(p.Text, "[redacted]") { t.Fatal("free-form error not redacted") } } func TestPreviewBounds(t *testing.T) { for _, n := range []int{-1, 0, 1, 64, 100, 4096, 99999} { p := SafePreview("commands", "sim-001", []byte(ping), n) if n <= 0 { if !p.Omitted { t.Fatal("disabled preview not omitted") } continue } if len(p.Text) > n || !utf8.ValidString(p.Text) { t.Fatal("invalid preview bounds") } if n < len(ping) && !p.Truncated { t.Fatal("truncation not labeled") } } } func TestRawPreviewIsBounded(t *testing.T) { for _, data := range [][]byte{[]byte("hello"), []byte("éééé"), {0xff, 0x00}} { preview := RawPreview(data, 5) if preview.Omitted || len(preview.Text) > 5 || preview.Bytes != len(data) { t.Fatal("invalid bounded raw preview") } } }