fix: escape the event data for slack webhook payload (#18424)

Escape the event data of slack webhook as original payload is invalid
when send to slack.

Fixes: #18423

Signed-off-by: chlins <chenyuzh@vmware.com>
This commit is contained in:
Chlins Zhang 2023-03-31 17:05:10 +08:00 committed by GitHub
parent 95972ba693
commit 5d953b48b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 4 deletions

View File

@ -121,7 +121,7 @@ func (s *SlackHandler) convert(payLoad *model.Payload) (string, error) {
if err != nil { if err != nil {
return "", fmt.Errorf("marshal from eventData %v failed: %v", payLoad.EventData, err) return "", fmt.Errorf("marshal from eventData %v failed: %v", payLoad.EventData, err)
} }
data["EventData"] = "```" + strings.Replace(string(eventData), `"`, `\"`, -1) + "```" data["EventData"] = "```" + escapeEventData(string(eventData)) + "```"
st, _ := template.New("slack").Parse(SlackBodyTemplate) st, _ := template.New("slack").Parse(SlackBodyTemplate)
var slackBuf bytes.Buffer var slackBuf bytes.Buffer
@ -130,3 +130,11 @@ func (s *SlackHandler) convert(payLoad *model.Payload) (string, error) {
} }
return slackBuf.String(), nil return slackBuf.String(), nil
} }
func escapeEventData(str string) string {
// escape " to \"
str = strings.Replace(str, `"`, `\"`, -1)
// escape \\" to \\\"
str = strings.Replace(str, `\\"`, `\\\"`, -1)
return str
}

View File

@ -5,13 +5,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/goharbor/harbor/src/pkg/notification" "github.com/goharbor/harbor/src/pkg/notification"
policy_model "github.com/goharbor/harbor/src/pkg/notification/policy/model" policy_model "github.com/goharbor/harbor/src/pkg/notification/policy/model"
"github.com/goharbor/harbor/src/pkg/notifier/event" "github.com/goharbor/harbor/src/pkg/notifier/event"
"github.com/goharbor/harbor/src/pkg/notifier/model" "github.com/goharbor/harbor/src/pkg/notifier/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestSlackHandler_Handle(t *testing.T) { func TestSlackHandler_Handle(t *testing.T) {
@ -105,3 +104,32 @@ func TestSlackHandler_Name(t *testing.T) {
handler := &SlackHandler{} handler := &SlackHandler{}
assert.Equal(t, "Slack", handler.Name()) assert.Equal(t, "Slack", handler.Name())
} }
func Test_escapeEventData(t *testing.T) {
type args struct {
str string
}
tests := []struct {
name string
args args
want string
}{
{
name: `escape "`,
args: args{str: `{"foo":"bar"}`},
want: `{\"foo\":\"bar\"}`,
},
{
name: `escape \\"`,
args: args{str: `{\"foo\":\"bar\"}`},
want: `{\\\"foo\\\":\\\"bar\\\"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := escapeEventData(tt.args.str); got != tt.want {
t.Errorf("escapeEventData() = %v, want %v", got, tt.want)
}
})
}
}