fix: allowed regexp prefixes for exact matches (#1962)

* test: adds failing test case

* fix: return project if there's an exact match, even if the prefix is not on the allowed list
This commit is contained in:
Bruno Ferreira
2022-01-05 16:16:28 +00:00
committed by GitHub
parent 1a342eda4d
commit cc513d4ef1
2 changed files with 53 additions and 7 deletions

View File

@@ -4,6 +4,7 @@ package valid
import (
"fmt"
"log"
"regexp"
"strings"
@@ -58,16 +59,19 @@ func (r RepoCfg) FindProjectByName(name string) *Project {
// FindProjectsByName returns all projects that match with name.
func (r RepoCfg) FindProjectsByName(name string) []Project {
var ps []Project
if isRegexAllowed(name, r.AllowedRegexpPrefixes) {
sanitizedName := "^" + name + "$"
for _, p := range r.Projects {
if p.Name != nil {
if match, _ := regexp.MatchString(sanitizedName, *p.Name); match {
ps = append(ps, p)
}
sanitizedName := "^" + name + "$"
for _, p := range r.Projects {
if p.Name != nil {
if match, _ := regexp.MatchString(sanitizedName, *p.Name); match {
ps = append(ps, p)
}
}
}
// If we found more than one project then we need to make sure that the regex is allowed.
if len(ps) > 1 && !isRegexAllowed(name, r.AllowedRegexpPrefixes) {
log.Printf("Found more than one project for regex %q. This regex is not on the allow list.", name)
return nil
}
return ps
}

View File

@@ -164,6 +164,48 @@ func TestConfig_FindProjectsByDir(t *testing.T) {
},
},
},
{
description: "Always find exact matches even if the prefix is not allowed",
nameRegex: ".*",
input: valid.RepoCfg{
Version: 3,
Projects: []valid.Project{
{
Dir: ".",
Name: String("prod_terragrunt_myproject"),
Workspace: "myworkspace",
TerraformVersion: tfVersion,
Autoplan: valid.Autoplan{
WhenModified: []string{"**/*.tf*", "**/terragrunt.hcl"},
Enabled: false,
},
ApplyRequirements: []string{"approved"},
},
},
Workflows: map[string]valid.Workflow{
"myworkflow": {
Name: "myworkflow",
Apply: valid.DefaultApplyStage,
Plan: valid.DefaultPlanStage,
PolicyCheck: valid.DefaultPolicyCheckStage,
},
},
AllowedRegexpPrefixes: []string{"dev", "staging"},
},
expProjects: []valid.Project{
{
Dir: ".",
Name: String("prod_terragrunt_myproject"),
Workspace: "myworkspace",
TerraformVersion: tfVersion,
Autoplan: valid.Autoplan{
WhenModified: []string{"**/*.tf*", "**/terragrunt.hcl"},
Enabled: false,
},
ApplyRequirements: []string{"approved"},
},
},
},
}
validation.ErrorTag = "yaml"
for _, c := range cases {