Skip to content
Merged
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
34 changes: 32 additions & 2 deletions cmd/internal/migrations/v3/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,40 @@ func MigrateCORSConfig(cmd *cobra.Command, cwd string, _, _ *semver.Version) err
// MigrateCSRFConfig updates csrf middleware configuration fields
func MigrateCSRFConfig(cmd *cobra.Command, cwd string, _, _ *semver.Version) error {
replacer := strings.NewReplacer("Expiration:", "IdleTimeout:")
re := regexp.MustCompile(`\s*SessionKey:\s*[^,]+,?\n`)
reSession := regexp.MustCompile(`\s*SessionKey:\s*[^,]+,?\n`)
reKeyLookup := regexp.MustCompile(`(\s*)KeyLookup:\s*([^,\n]+)(,?)(\n?)`)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current regular expression for reKeyLookup is too greedy and can cause issues when a KeyLookup line contains a comment. This could lead to the migration tool incorrectly removing the entire line.

For example, with a line like KeyLookup: "header:X-CSRF-Token" // my token, the ([^,\n]+) part of the regex will match the entire value including the comment ("header:X-CSRF-Token" // my token). This combined string will then fail to be unquoted by strconv.Unquote, causing the migration to fall into the default case which removes the line.

A safer regex would be more specific, for instance, by only matching quoted string literals. This would correctly parse the value and leave the comment untouched.

Suggested change
reKeyLookup := regexp.MustCompile(`(\s*)KeyLookup:\s*([^,\n]+)(,?)(\n?)`)
reKeyLookup := regexp.MustCompile(`(\s*)KeyLookup:\s*("[^"]*")\s*(,?)(\n?)`)

err := internal.ChangeFileContent(cwd, func(content string) string {
content = replacer.Replace(content)
return re.ReplaceAllString(content, "")
content = reSession.ReplaceAllString(content, "")

content = reKeyLookup.ReplaceAllStringFunc(content, func(s string) string {
sub := reKeyLookup.FindStringSubmatch(s)
indent := sub[1]
val := strings.TrimSpace(sub[2])
comma := sub[3]
newline := sub[4]

if uq, err := strconv.Unquote(val); err == nil {
val = uq
}

var extractor string
switch {
case strings.HasPrefix(val, "header:"):
extractor = fmt.Sprintf("Extractor: csrf.FromHeader(%q)", strings.TrimPrefix(val, "header:"))
case strings.HasPrefix(val, "form:"):
extractor = fmt.Sprintf("Extractor: csrf.FromForm(%q)", strings.TrimPrefix(val, "form:"))
case strings.HasPrefix(val, "query:"):
extractor = fmt.Sprintf("Extractor: csrf.FromQuery(%q)", strings.TrimPrefix(val, "query:"))
default:
// Unsupported or insecure value (e.g. cookie) - remove
return ""
}

return fmt.Sprintf("%s%s%s%s", indent, extractor, comma, newline)
})

return content
})
if err != nil {
return fmt.Errorf("failed to migrate CSRF configs: %w", err)
Expand Down
25 changes: 25 additions & 0 deletions cmd/internal/migrations/v3/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,31 @@ var _ = csrf.New(csrf.Config{
assert.Contains(t, buf.String(), "Migrating CSRF middleware configs")
}

func Test_MigrateCSRFConfig_KeyLookup(t *testing.T) {
t.Parallel()

dir, err := os.MkdirTemp("", "mcsrfkl")
require.NoError(t, err)
defer func() { require.NoError(t, os.RemoveAll(dir)) }()

file := writeTempFile(t, dir, `package main
import (
"github.com/gofiber/fiber/v2/middleware/csrf"
)
var _ = csrf.New(csrf.Config{
KeyLookup: "header:X-CSRF-Token",
})`)

var buf bytes.Buffer
cmd := newCmd(&buf)
require.NoError(t, v3.MigrateCSRFConfig(cmd, dir, nil, nil))

content := readFile(t, file)
assert.NotContains(t, content, "KeyLookup")
assert.Contains(t, content, `Extractor: csrf.FromHeader("X-CSRF-Token")`)
assert.Contains(t, buf.String(), "Migrating CSRF middleware configs")
}

func Test_MigrateMonitorImport(t *testing.T) {
t.Parallel()

Expand Down
Loading