package events import ( json "encoding/json/v2" "strings" "testing" "github.com/samcharles93/archie-core/modules/events/internal/store" ) // TestRedactLinkCode guards the credential in an account.link event: once the // event is handled, whether the code linked the account, expired or was // refused, neither the parsed fields nor the stored body may hold it, and the // event must still say which channel account sent it. func TestRedactLinkCode(t *testing.T) { const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" //nolint:gosec // plainly fake link code the redaction must remove tests := []struct { name string fields string body string }{ { name: "webhook body", fields: `{"by":"telegram:1001","code":"` + code + `","name":"Jo","chat_id":"55"}`, body: `{"message":{"from":{"id":1001},"text":"/link ` + code + `"}}`, }, { name: "streamed batch", fields: `{"by":"telegram:1001","code":"` + code + `","name":"Jo","chat_id":"55"}`, body: `[{"type":"account.link","fields":{"by":"telegram:1001","code":"` + code + `"}}]`, }, { name: "no stored body", fields: `{"by":"telegram:1001","code":"` + code + `"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { e := store.Event{Type: linkType, Fields: []byte(tt.fields)} if tt.body != "" { e.Body = []byte(tt.body) } got, err := redactLinkCode(e) if err != nil { t.Fatalf("redactLinkCode: %v", err) } if strings.Contains(string(got.Fields), code) || strings.Contains(string(got.Body), code) { t.Fatalf("code still stored: fields %s body %s", got.Fields, got.Body) } var f struct { By string `json:"by"` Code string `json:"code"` } if err := json.Unmarshal(got.Fields, &f); err != nil { t.Fatalf("fields are not valid JSON: %v", err) } if f.By != "telegram:1001" || f.Code != redactedCode { t.Fatalf("fields = %s, want the sender and a marker in place of the code", got.Fields) } if tt.body != "" && !strings.Contains(string(got.Body), redactedCode) { t.Fatalf("body = %s, want the marker in place of the code", got.Body) } }) } }