From 0fc2bb13a789df338845ea3beefb287e624c1a1a Mon Sep 17 00:00:00 2001 From: groselt Date: Sat, 30 May 2020 17:04:36 +0100 Subject: [PATCH] Sanitize log filename before saving Remove invalid path characters --- internal/view/log.go | 13 ++++++++++++- internal/view/log_test.go | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/internal/view/log.go b/internal/view/log.go index a06e040c..07f43029 100644 --- a/internal/view/log.go +++ b/internal/view/log.go @@ -7,6 +7,7 @@ import ( "io" "os" "path/filepath" + "regexp" "strings" "time" @@ -29,6 +30,9 @@ const ( flushTimeout = 50 * time.Millisecond ) +// InvalidCharsRX contains invalid filename characters. +var invalidPathCharsRX = regexp.MustCompile(`[:/\\]+`) + // Log represents a generic log viewer. type Log struct { *tview.Flex @@ -284,12 +288,19 @@ func (l *Log) SaveCmd(evt *tcell.EventKey) *tcell.EventKey { return nil } +// SanitizeFilename removes characters not allowed by OS +func SanitizeFilename(name string) string { + processedString := invalidPathCharsRX.ReplaceAllString(name, "-") + + return processedString +} + func ensureDir(dir string) error { return os.MkdirAll(dir, 0744) } func saveData(cluster, name, data string) (string, error) { - dir := filepath.Join(config.K9sDumpDir, cluster) + dir := filepath.Join(config.K9sDumpDir, SanitizeFilename(cluster)) if err := ensureDir(dir); err != nil { return "", err } diff --git a/internal/view/log_test.go b/internal/view/log_test.go index 049636a3..dd47b30e 100644 --- a/internal/view/log_test.go +++ b/internal/view/log_test.go @@ -43,6 +43,23 @@ func TestLogViewSave(t *testing.T) { assert.Equal(t, len(c2), len(c1)+1) } +func TestSanitizedFilename(t *testing.T) { + uu := []struct { + name string + expected string + }{ + {"alpha", "alpha"}, + {"123", "123"}, + {"with/slash", "with-slash"}, + {"with:colon", "with-colon"}, + {":many:invalid\\characters\\", "-many-invalid-characters-"}, + } + + for _, u := range uu { + assert.Equal(t, u.expected, view.SanitizeFilename(u.name)) + } +} + // ---------------------------------------------------------------------------- // Helpers...