Repository navigation
Validate pr template regexes up front, and stop recursive matches panicking #855
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package pr | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // Apply rejects invalid regexes before it gets here (validateRegexes), so this exercises recursiveReplace directly: | ||
| // a nested regex that doesn't compile used to panic out of ReplaceAllFunc. | ||
| func TestRecursiveReplaceReturnsNestedErrors(t *testing.T) { | ||
| data := []byte("image: nginx:v1\n") | ||
|
|
||
| var ( | ||
| res []byte | ||
| err error | ||
| ) | ||
| require.NotPanics(t, func() { | ||
| // the first regex matches, so the invalid second one is only compiled while recursing | ||
| res, err = recursiveReplace(data, []string{`image: (.*)`, `(v[0-9]`}, []byte("v2")) | ||
| }) | ||
|
|
||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), "missing closing )") | ||
| assert.Equal(t, data, res, "the input comes back unchanged") | ||
| } | ||
|
|
||
| func TestRecursiveReplaceReplacesNestedMatches(t *testing.T) { | ||
| res, err := recursiveReplace([]byte("image: nginx:v1\n"), []string{`image: .*`, `v[0-9]+`}, []byte("v2")) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, "image: nginx:v2\n", string(res)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| package pr | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "regexp" | ||
| "regexp/syntax" | ||
| ) | ||
|
|
||
| // validateRegexes compiles every regular expression the updates will use, rendered the way applying them renders | ||
| // them, so an invalid one fails the template before any file is written, with an error naming the field and the | ||
| // pattern. Compiling them lazily, per file, let an invalid one fail halfway through, after earlier files had changed. | ||
| func validateRegexes(updates *UpdateSpec, ctx map[string]interface{}) error { | ||
| if updates == nil { | ||
| return nil | ||
| } | ||
|
|
||
| var errs []error | ||
| check := func(field, rx string) { | ||
| if _, err := regexp.Compile(rx); err != nil { | ||
| errs = append(errs, regexError(field, rx, err)) | ||
| } | ||
| } | ||
| for i, replacement := range updates.RegexReplacements { | ||
| check(fmt.Sprintf("updates.regexReplacements[%d].regex", i), renderRegex(replacement.Regex, ctx)) | ||
| } | ||
| for i, file := range updates.Files { | ||
| check(fmt.Sprintf("updates.files[%d]", i), renderRegex(file, ctx)) | ||
| } | ||
| for i, rx := range updates.Regexes { | ||
| check(fmt.Sprintf("updates.regexes[%d]", i), rx) | ||
| } | ||
| return errors.Join(errs...) | ||
| } | ||
|
|
||
| // renderRegex templates a regular expression the way applying it does: one whose template doesn't render is used as | ||
| // written. | ||
| func renderRegex(rx string, ctx map[string]interface{}) string { | ||
| res, err := templateReplacement([]byte(rx), ctx) | ||
| if err != nil { | ||
| return rx | ||
| } | ||
| return string(res) | ||
| } | ||
|
|
||
| func regexError(field, rx string, err error) error { | ||
| var se *syntax.Error | ||
| if errors.As(err, &se) { | ||
| return fmt.Errorf("%s %q isn't a valid regular expression: %s", field, rx, se.Code) | ||
| } | ||
| return fmt.Errorf("%s %q isn't a valid regular expression: %w", field, rx, err) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| package pr_test | ||
|
|
||
| import ( | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/pluralsh/plural-cli/pkg/pr" | ||
| ) | ||
|
|
||
| func TestApplyRejectsInvalidRegexes(t *testing.T) { | ||
| cases := []struct { | ||
| name string | ||
| updates *pr.UpdateSpec | ||
| ctx map[string]interface{} | ||
| err string | ||
| }{ | ||
| { | ||
| // the pattern a user's pull request automation failed on, as "unknown error" in console | ||
| name: "an unbalanced regex replacement", | ||
| updates: &pr.UpdateSpec{RegexReplacements: []pr.RegexReplacement{ | ||
| {Regex: `tag: (.*)`, Replacement: "tag: v2", File: "values.yaml"}, | ||
| {Regex: `(image: (.*)`, Replacement: "x", File: "values.yaml"}, | ||
| }}, | ||
| err: `updates.regexReplacements[1].regex "(image: (.*)" isn't a valid regular expression: missing closing )`, | ||
| }, | ||
| { | ||
| name: "a templated regex replacement is checked as rendered", | ||
| updates: &pr.UpdateSpec{RegexReplacements: []pr.RegexReplacement{{Regex: `{{ context.key }}: (.*`, Replacement: "x", File: "values.yaml"}}}, | ||
| ctx: map[string]interface{}{"key": "image"}, | ||
| err: `updates.regexReplacements[0].regex "image: (.*" isn't a valid regular expression: missing closing )`, | ||
| }, | ||
| { | ||
| name: "file patterns", | ||
| updates: &pr.UpdateSpec{Files: []string{`values[.yaml`}, MatchStrategy: "any", Regexes: []string{"a"}}, | ||
| err: `updates.files[0] "values[.yaml" isn't a valid regular expression: missing closing ]`, | ||
| }, | ||
| { | ||
| name: "PCRE-only syntax RE2 doesn't support", | ||
| updates: &pr.UpdateSpec{Files: []string{`.*`}, MatchStrategy: "any", Regexes: []string{`image: (?=v)(.*)`}}, | ||
| err: `updates.regexes[0] "image: (?=v)(.*)" isn't a valid regular expression: invalid or unsupported Perl syntax`, | ||
| }, | ||
| { | ||
| // it used to panic out of ReplaceAllFunc while recursing; it's caught up front now | ||
| name: "an invalid regex after the first in a recursive match", | ||
| updates: &pr.UpdateSpec{Files: []string{`.*`}, MatchStrategy: "recursive", Regexes: []string{`image: (.*)`, `(v[0-9]`}}, | ||
| err: `updates.regexes[1] "(v[0-9]" isn't a valid regular expression: missing closing )`, | ||
| }, | ||
| } | ||
|
|
||
| for _, tc := range cases { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| dir := t.TempDir() | ||
| wd, err := os.Getwd() | ||
| require.NoError(t, err) | ||
| require.NoError(t, os.Chdir(dir)) | ||
| t.Cleanup(func() { _ = os.Chdir(wd) }) | ||
| const values = "image: nginx\ntag: v1\n" | ||
| require.NoError(t, os.WriteFile(filepath.Join(dir, "values.yaml"), []byte(values), 0o644)) | ||
|
|
||
| err = pr.Apply(&pr.PrTemplate{Context: tc.ctx, Spec: pr.PrTemplateSpec{Updates: tc.updates}}) | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), tc.err) | ||
|
|
||
| // nothing is written when any regex is invalid, even one that would have been applied first | ||
| data, err := os.ReadFile(filepath.Join(dir, "values.yaml")) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, values, string(data)) | ||
| }) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.