Skip to content
This repository has been archived by the owner on Dec 19, 2023. It is now read-only.

add checkPostPassword PreHook #35

Closed
wants to merge 1 commit into from
Closed
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
7 changes: 7 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ func main() {
Client: cl,
}

randomString := &hooks.DefaultRandomStringGenerator{}
checkPostPassword := &hooks.CheckPostPassword{
Client: cl,
Generator: randomString,
}

r, err := reconciler.New(
reconciler.WithChart(*w.Chart),
reconciler.WithGroupVersionKind(w.GroupVersionKind),
Expand All @@ -142,6 +148,7 @@ func main() {
reconciler.WithUpgradeAnnotations(annotation.DefaultUpgradeAnnotations...),
reconciler.WithUninstallAnnotations(annotation.DefaultUninstallAnnotations...),
reconciler.WithPreHook(setClusterRouterBaseHook),
reconciler.WithPreHook(checkPostPassword),
)

if err != nil {
Expand Down
90 changes: 90 additions & 0 deletions pkg/hooks/secret-prehook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package hooks

import (
"math/rand"
"time"

"github.com/go-logr/logr"
"helm.sh/helm/v3/pkg/chartutil"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
)

type RandomStringGenerator interface {
GenerateRandomString() (string, error)
}

type DefaultRandomStringGenerator struct{}

type CheckPostPassword struct {
Client client.Client
Generator RandomStringGenerator
}

// PreHook function to determine if upstream.postgresql.auth.password and upstream.postgresql.auth.postgresPassword has been set.
// Sets those parameters to the secret that has been created after the chart has been installed
func (h *CheckPostPassword) Exec(obj *unstructured.Unstructured, vals chartutil.Values, log logr.Logger) error {

if h.shouldSkipSettingPassword(vals) {
log.V(1).Info("PreHook: skipping setting upstream.posgresql.auth.password and upstream.postgresql.auth.postgresPassword")
return nil
}

pass, err := h.Generator.GenerateRandomString()
if err != nil {
return err
}
postPass, err := h.Generator.GenerateRandomString()
if err != nil {
return err
}

h.setAuthPasswords(vals, pass, postPass)

log.V(1).Info("PreHook: setting upstream.postgresql.auth.password and upstream.postgresql.auth.postgresPassword")

return nil
}

func (g *DefaultRandomStringGenerator) GenerateRandomString() (string, error) {
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
charSet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var SecretLength = 16
token := make([]byte, SecretLength)

for i := range token {
token[i] = charSet[seededRand.Intn(len(charSet))]
}

return string(token), nil
}

func (h *CheckPostPassword) shouldSkipSettingPassword(vals chartutil.Values) bool {

_, passFound, _ := unstructured.NestedString(vals, "upstream", "postgresql", "auth", "password")
_, postFound, _ := unstructured.NestedString(vals, "upstream", "postgresql", "auth", "postgresPassword")

return passFound && postFound
}

func (h *CheckPostPassword) setAuthPasswords(vals chartutil.Values, pass interface{}, postPass interface{}) {
ensureNestedMap(vals, "upstream", "postgresql", "auth")
ensureNestedMap(vals, "backstage", "postgresql", "auth")

vals["upstream"].(map[string]interface{})["postgresql"].(map[string]interface{})["auth"].(map[string]interface{})["password"] = pass
vals["upstream"].(map[string]interface{})["postgresql"].(map[string]interface{})["auth"].(map[string]interface{})["postgresPassword"] = postPass

vals["backstage"].(map[string]interface{})["postgresql"].(map[string]interface{})["auth"].(map[string]interface{})["password"] = pass
vals["backstage"].(map[string]interface{})["postgresql"].(map[string]interface{})["auth"].(map[string]interface{})["postgresPassword"] = postPass
}

// Helper function to ensure that the nested map, upstream.posgresql.auth, is there
func ensureNestedMap(m map[string]interface{}, keys ...string) {
for _, key := range keys {
_, ok := m[key].(map[string]interface{})
if !ok {
m[key] = map[string]interface{}{}
}
m = m[key].(map[string]interface{})
}
}
161 changes: 161 additions & 0 deletions pkg/hooks/secret-prehook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package hooks_test

import (
"testing"

"github.com/go-logr/logr"
"github.com/janus-idp/backstage-operator/pkg/hooks"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v3/pkg/chartutil"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

// Test cases that need to be covered
// - Not set
// - - It will set the fields
// - Is set
// - - It will skip setting the fields

type MockRandomStringGenerator struct{}

func (g *MockRandomStringGenerator) GenerateRandomString() (string, error) {
return "test", nil
}

func TestCheckPostPassword(t *testing.T) {
type args struct {
obj *unstructured.Unstructured
vals chartutil.Values
log logr.Logger
}

tests := []struct {
name string
client client.Client
args args
wantErr bool
wantVals chartutil.Values
}{
{
name: "password and postgresPassword not set, empty chart values",
client: fake.NewClientBuilder().Build(),
args: args{
obj: &unstructured.Unstructured{},
vals: chartutil.Values{},
log: logr.Discard(),
},
wantErr: false,
wantVals: chartutil.Values{
"backstage": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test",
"postgresPassword": "test",
},
},
},
"upstream": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test",
"postgresPassword": "test",
},
},
},
},
},
{
name: "password and postgresPassword not set, existing chart values, but no auth section",
client: fake.NewClientBuilder().Build(),
args: args{
obj: &unstructured.Unstructured{},
vals: chartutil.Values{"foo": "baz"},
log: logr.Discard(),
},
wantErr: false,
wantVals: chartutil.Values{
"backstage": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test",
"postgresPassword": "test",
},
},
},
"foo": "baz",
"upstream": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test",
"postgresPassword": "test",
},
},
},
},
},
{
name: "password and postgresPassword are set",
client: fake.NewClientBuilder().Build(),
args: args{
obj: &unstructured.Unstructured{},
vals: chartutil.Values{
"backstage": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test2",
"postgresPassword": "test2",
},
},
},
"upstream": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test2",
"postgresPassword": "test2",
},
},
},
},
log: logr.Discard(),
},
wantErr: false,
wantVals: chartutil.Values{
"backstage": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test2",
"postgresPassword": "test2",
},
},
},
"upstream": map[string]interface{}{
"postgresql": map[string]interface{}{
"auth": map[string]interface{}{
"password": "test2",
"postgresPassword": "test2",
},
},
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockGenerator := &MockRandomStringGenerator{}
hook := &hooks.CheckPostPassword{
Client: tt.client,
Generator: mockGenerator,
}
err := hook.Exec(tt.args.obj, tt.args.vals, tt.args.log)

if (err != nil) != tt.wantErr {
t.Errorf("CheckPostPassword.Exec() error = %v, wantErr %v", err, tt.wantErr)
}

assert.EqualValues(t, tt.wantVals, tt.args.vals)
})
}
}