Skip to content

Commit

Permalink
fix: k8s escape resource filename on windows os (aquasecurity#4693)
Browse files Browse the repository at this point in the history
Signed-off-by: chenk <hen.keinan@gmail.com>
  • Loading branch information
chen-keinan committed Jun 22, 2023
1 parent a21acc7 commit c6741bd
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/k8s/scanner/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package scanner
import (
"fmt"
"os"
"regexp"
"runtime"

"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
Expand All @@ -15,6 +17,10 @@ import (
func createTempFile(artifact *artifacts.Artifact) (string, error) {
filename := fmt.Sprintf("%s-%s-%s-*.yaml", artifact.Namespace, artifact.Kind, artifact.Name)

if runtime.GOOS == "windows" {
//removes characters not permitted in file/directory names on Windows
filename = filenameWindowsFriendly(filename)
}
file, err := os.CreateTemp("", filename)
if err != nil {
return "", xerrors.Errorf("creating tmp file error: %w", err)
Expand All @@ -38,3 +44,9 @@ func removeFile(filename string) {
log.Logger.Errorf("failed to remove temp file %s: %s:", filename, err)
}
}

var r, _ = regexp.Compile("\\\\|/|:|\\*|\\?|<|>")

func filenameWindowsFriendly(name string) string {
return r.ReplaceAllString(name, "_")
}
34 changes: 34 additions & 0 deletions pkg/k8s/scanner/io_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package scanner

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test_FilenameWindowsFriendly(t *testing.T) {

tests := []struct {
name string
fileName string
want string
}{
{
name: "name with invalid char - colon",
fileName: `kube-system-Role-system:controller:bootstrap-signer-2934213283.yaml`,
want: `kube-system-Role-system_controller_bootstrap-signer-2934213283.yaml`,
},
{
name: "name with no invalid chars",
fileName: `kube-system-Role-system-controller-bootstrap-signer-2934213283.yaml`,
want: `kube-system-Role-system-controller-bootstrap-signer-2934213283.yaml`,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := filenameWindowsFriendly(test.fileName)
assert.Equal(t, test.want, got)
})
}
}

0 comments on commit c6741bd

Please sign in to comment.