Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmd/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ Examples:
RunE: func(cmd *cobra.Command, args []string) error {
format, _ := cmd.Flags().GetString("format")
savePath, _ := cmd.Flags().GetString("save")
if savePath != "" {
if err := validateCompareSavePath(savePath); err != nil {
return err
}
}
format = strings.ToLower(strings.TrimSpace(format))
if format == "" {
format = "terminal"
Expand Down Expand Up @@ -179,6 +184,14 @@ func saveCompareOutput(path string, data []byte) error {
return os.WriteFile(path, data, 0644)
}

func validateCompareSavePath(path string) error {
cleanPath := filepath.Clean(path)
if filepath.IsAbs(path) || cleanPath == ".." || strings.HasPrefix(cleanPath, ".."+string(filepath.Separator)) {
return fmt.Errorf("save path must stay within the current directory: %q", path)
}
return nil
}

func init() {
rootCmd.AddCommand(compareCmd)
compareCmd.Flags().String("format", "terminal", "Output format: terminal, html, json, markdown")
Expand Down
26 changes: 26 additions & 0 deletions cmd/compare_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package cmd

import "testing"

func TestValidateCompareSavePath(t *testing.T) {
tests := []struct {
name string
path string
valid bool
}{
{name: "filename", path: "report.html", valid: true},
{name: "nested relative path", path: "reports/compare.json", valid: true},
{name: "parent traversal", path: "../report.html", valid: false},
{name: "nested parent traversal", path: "reports/../../report.html", valid: false},
{name: "absolute path", path: "/tmp/report.html", valid: false},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := validateCompareSavePath(test.path) == nil
if got != test.valid {
t.Fatalf("validateCompareSavePath(%q) valid = %v, want %v", test.path, got, test.valid)
}
})
}
}
Loading