return error on invalid UTF-8

Signed-off-by: Somtochi Onyekwere <somtochionyekwere@gmail.com>
This commit is contained in:
Somtochi Onyekwere 2022-04-08 15:05:13 +01:00
parent cd7ad15bda
commit 6477e1500e
2 changed files with 26 additions and 4 deletions

View File

@ -29,6 +29,7 @@ import (
"time"
"github.com/fluxcd/pkg/runtime/conditions"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
@ -264,7 +265,7 @@ func (s *EventServer) handleEvent() func(w http.ResponseWriter, r *http.Request)
go func(n notifier.Interface, e events.Event) {
if err := n.Post(e); err != nil {
err = redactTokenFromError(err, token)
err = redactTokenFromError(err, token, s.logger)
s.logger.Error(err, "failed to send notification",
"reconciler kind", event.InvolvedObject.Kind,
@ -318,12 +319,17 @@ func (s *EventServer) eventMatchesAlert(ctx context.Context, event *events.Event
return false
}
func redactTokenFromError(err error, token string) error {
func redactTokenFromError(err error, token string, log logr.Logger) error {
if token == "" {
return err
}
re := regexp.MustCompile(fmt.Sprintf("%s*", token))
re, compileErr := regexp.Compile(fmt.Sprintf("%s*", token))
if compileErr != nil {
log.Error(compileErr, "error redacting token from error message")
return err
}
redacted := re.ReplaceAllString(err.Error(), "*****")
return errors.New(redacted)

View File

@ -3,6 +3,8 @@ package server
import (
"errors"
"testing"
"github.com/fluxcd/pkg/runtime/logger"
)
func TestRedactTokenFromError(t *testing.T) {
@ -42,10 +44,23 @@ func TestRedactTokenFromError(t *testing.T) {
originalErrStr: `Cannot post to github with token metoo8h0387hdyehbwwa45\\n`,
expectedErrStr: `Cannot post to github with token metoo*****\\n`,
},
{
name: "extra text in front token",
token: "8h0387hdyehbwwa45踙",
originalErrStr: `Cannot post to github with token metoo8h0387hdyehbwwa45踙\\n`,
expectedErrStr: `Cannot post to github with token metoo*****\\n`,
},
{
name: "return error on invalid UTF-8 string",
token: "\x18\xd0\xfa\xab\xb2\x93\xbb;\xc0l\xf4\xdc",
originalErrStr: `Cannot post to github with token \x18\xd0\xfa\xab\xb2\x93\xbb;\xc0l\xf4\xdc\\n`,
expectedErrStr: `Cannot post to github with token \x18\xd0\xfa\xab\xb2\x93\xbb;\xc0l\xf4\xdc\\n`,
},
}
for _, tt := range tests {
err := redactTokenFromError(errors.New(tt.originalErrStr), tt.token)
log := logger.NewLogger(logger.Options{})
err := redactTokenFromError(errors.New(tt.originalErrStr), tt.token, log)
if err == nil {
t.Fatalf("error shouldn't be nil")
}
@ -55,4 +70,5 @@ func TestRedactTokenFromError(t *testing.T) {
tt.expectedErrStr, err)
}
}
}