Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#2287 from jingyih/validate_gsa…
Browse files Browse the repository at this point in the history
…_format

Validate format of GoogleServiceAccount in CCC
  • Loading branch information
google-oss-prow[bot] authored Nov 13, 2024
2 parents e3b7c21 + fa4d2d0 commit 863ba97
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions operator/pkg/preflight/configconnectorcontextchecker.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package preflight
import (
"context"
"fmt"
"regexp"

corev1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/operator/pkg/apis/core/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/operator/pkg/k8s"
Expand Down Expand Up @@ -52,5 +53,21 @@ func (c *ConfigConnectorContextChecker) Preflight(_ context.Context, o declarati
return fmt.Errorf("spec.billingProject must be set if spec.requestProjectPolicy is set to %v", k8s.BillingProjectPolicy)
}

if err := validateGSAFormat(ccc.Spec.GoogleServiceAccount); err != nil {
return err
}

return nil
}

func validateGSAFormat(gsa string) error {
if gsa == "" { // GoogleServiceAccount is a required field. We do not need to fail here.
return nil
}
validGSAPattern := `^[A-Za-z0-9._%+\-]+@[a-z0-9.\-]+\.gserviceaccount.com$`
emailRegex := regexp.MustCompile(validGSAPattern)
if !emailRegex.MatchString(gsa) {
return fmt.Errorf("invalid GoogleServiceAccount format for %q", gsa)
}
return nil
}
46 changes: 46 additions & 0 deletions operator/pkg/preflight/configconnectorcontextchecker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,49 @@ func TestConfigConnectorContextChecker(t *testing.T) {
})
}
}

func TestValidateGSAFormat(t *testing.T) {
tests := []struct {
name string
gsa string
err error
}{
{
name: "empty",
gsa: "",
err: nil,
},
{
name: "valid GSA format",
gsa: "[email protected]",
err: nil,
},
{
name: "valid GSA format",
gsa: "[email protected]",
err: nil,
},
{
name: "valid GSA format",
gsa: "[email protected]",
err: nil,
},
{
name: "invalid GSA format",
gsa: "abc",
err: fmt.Errorf("invalid GoogleServiceAccount format for %q", "abc"),
},
{
name: "invalid GSA format",
gsa: "[email protected]",
err: fmt.Errorf("invalid GoogleServiceAccount format for %q", "[email protected]"),
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := validateGSAFormat(tc.gsa)
asserts.AssertErrorIsExpected(t, err, tc.err)
})
}
}

0 comments on commit 863ba97

Please sign in to comment.