1
0
mirror of https://github.com/getsops/sops.git synced 2026-02-05 12:45:21 +01:00

feat: Support more complicated path_regexp (issues/826) (#829)

* feat: Support more complicated path_regexp (https://github.com/mozilla/sops/issues/826)

* feat: Support more complicated path_regexp (https://github.com/mozilla/sops/issues/826)

* fix review: do not panic and return an error instead if the regexp is not valid.

* fix merge mess

Co-authored-by: AJ Bahnken <1144310+ajvb@users.noreply.github.com>
This commit is contained in:
Brice Colucci
2021-03-10 15:23:11 -05:00
committed by GitHub
parent fbc87aea14
commit 79d5dac9ff
3 changed files with 44 additions and 8 deletions

View File

@@ -10,7 +10,6 @@ import (
"path"
"regexp"
"gopkg.in/yaml.v3"
"github.com/sirupsen/logrus"
"go.mozilla.org/sops/v3"
"go.mozilla.org/sops/v3/age"
@@ -21,6 +20,7 @@ import (
"go.mozilla.org/sops/v3/logging"
"go.mozilla.org/sops/v3/pgp"
"go.mozilla.org/sops/v3/publish"
"gopkg.in/yaml.v3"
)
var log *logrus.Logger
@@ -326,11 +326,13 @@ func parseCreationRuleForFile(conf *configFile, filePath string, kmsEncryptionCo
rule = &r
break
}
if r.PathRegex != "" {
if match, _ := regexp.MatchString(r.PathRegex, filePath); match {
rule = &r
break
}
reg, err := regexp.Compile(r.PathRegex)
if err != nil {
return nil, fmt.Errorf("can not compile regexp: %w", err)
}
if reg.MatchString(filePath) {
rule = &r
break
}
}

View File

@@ -208,6 +208,24 @@ destination_rules:
path_regex: "vault-v1/*"
`)
var sampleConfigWithInvalidComplicatedRegexp = []byte(`
creation_rules:
- path_regex: "[ ]\\K(?<!\\d )(?="
kms: default
`)
var sampleConfigWithComplicatedRegexp = []byte(`
creation_rules:
- path_regex: "stage/dev/feature-.*"
kms: dev-feature
- path_regex: "stage/dev/.*"
kms: dev
- path_regex: "stage/staging/.*"
kms: staging
- path_regex: "stage/.*/.*"
kms: default
`)
func parseConfigFile(confBytes []byte, t *testing.T) *configFile {
conf := &configFile{}
err := conf.load(confBytes)
@@ -285,6 +303,24 @@ func TestLoadConfigFileWithNoMatchingRules(t *testing.T) {
assert.NotNil(t, err)
}
func TestLoadConfigFileWithInvalidComplicatedRegexp(t *testing.T) {
conf, err := parseCreationRuleForFile(parseConfigFile(sampleConfigWithInvalidComplicatedRegexp, t), "stage/prod/api.yml", nil)
assert.Equal(t, "can not compile regexp: error parsing regexp: invalid escape sequence: `\\K`", err.Error())
assert.Nil(t, conf)
}
func TestLoadConfigFileWithComplicatedRegexp(t *testing.T) {
for filePath, k := range map[string]string{
"stage/prod/api.yml": "default",
"stage/dev/feature-foo.yml": "dev-feature",
"stage/dev/api.yml": "dev",
} {
conf, err := parseCreationRuleForFile(parseConfigFile(sampleConfigWithComplicatedRegexp, t), filePath, nil)
assert.Nil(t, err)
assert.Equal(t, k, conf.KeyGroups[0][0].ToString())
}
}
func TestLoadEmptyConfigFile(t *testing.T) {
conf, err := parseCreationRuleForFile(parseConfigFile(sampleEmptyConfig, t), "foobar2000", nil)
assert.Nil(t, conf)