Skip to content

Commit

Permalink
generate gitea password (#195)
Browse files Browse the repository at this point in the history
Signed-off-by: Manabu McCloskey <[email protected]>
  • Loading branch information
nabuskey authored Apr 18, 2024
1 parent bfd3cd6 commit a822dbd
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 19 deletions.
1 change: 0 additions & 1 deletion hack/gitea/generate-manifests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,3 @@ sed -i '3d' ${INSTALL_YAML}
sed -i 's/namespace: default/namespace: gitea/g' ${INSTALL_YAML}

cat ${GITEA_DIR}/ingress.yaml.tmpl >> ${INSTALL_YAML}
cat ${GITEA_DIR}/gitea-creds.yaml >> ${INSTALL_YAML}
9 changes: 0 additions & 9 deletions hack/gitea/gitea-creds.yaml

This file was deleted.

32 changes: 32 additions & 0 deletions pkg/controllers/localbuild/gitea.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import (

"github.com/cnoe-io/idpbuilder/api/v1alpha1"
"github.com/cnoe-io/idpbuilder/pkg/k8s"
"github.com/cnoe-io/idpbuilder/pkg/util"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
Expand All @@ -30,6 +34,27 @@ func RawGiteaInstallResources(templateData any, config v1alpha1.PackageCustomiza
return k8s.BuildCustomizedManifests(config.FilePath, "resources/gitea/k8s", installGiteaFS, scheme, templateData)
}

func newGiteAdminSecret() (corev1.Secret, error) {
pass, err := util.GeneratePassword()
if err != nil {
return corev1.Secret{}, err
}
return corev1.Secret{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: giteaAdminSecret,
Namespace: giteaNamespace,
},
StringData: map[string]string{
"username": "giteaAdmin",
"password": pass,
},
}, nil
}

func (r *LocalbuildReconciler) ReconcileGitea(ctx context.Context, req ctrl.Request, resource *v1alpha1.Localbuild) (ctrl.Result, error) {
gitea := EmbeddedInstallation{
name: "Gitea",
Expand All @@ -45,6 +70,13 @@ func (r *LocalbuildReconciler) ReconcileGitea(ctx context.Context, req ctrl.Requ
},
}

giteCreds, err := newGiteAdminSecret()
if err != nil {
return ctrl.Result{}, fmt.Errorf("generating gitea admin secret: %w", err)
}

gitea.unmanagedResources = []client.Object{&giteCreds}

if result, err := gitea.Install(ctx, req, resource, r.Client, r.Scheme, r.Config); err != nil {
return result, err
}
Expand Down
10 changes: 10 additions & 0 deletions pkg/controllers/localbuild/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ type EmbeddedInstallation struct {
monitoredResources map[string]schema.GroupVersionKind
customization v1alpha1.PackageCustomization
resourceFS embed.FS

// resources that need to be created without using static manifests or gitops
unmanagedResources []client.Object
}

func (e *EmbeddedInstallation) installResources(scheme *runtime.Scheme, templateData any) ([]client.Object, error) {
Expand Down Expand Up @@ -69,6 +72,13 @@ func (e *EmbeddedInstallation) Install(ctx context.Context, req ctrl.Request, re
}
}

for i := range e.unmanagedResources {
err = k8s.EnsureObject(ctx, nsClient, e.unmanagedResources[i], e.namespace)
if err != nil {
return ctrl.Result{}, err
}
}

logger.V(1).Info(fmt.Sprintf("Installing/Reconciling %s resources", e.name))
for _, obj := range installObjs {
if gvk, ok := e.monitoredResources[obj.GetName()]; ok {
Expand Down
9 changes: 0 additions & 9 deletions pkg/controllers/localbuild/resources/gitea/k8s/install.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -646,12 +646,3 @@ spec:
name: my-gitea-http
port:
number: 3000
---
apiVersion: v1
kind: Secret
metadata:
name: gitea-admin-secret
type: Opaque
stringData:
username: giteaAdmin
password: giteaPassword
64 changes: 64 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,27 @@ package util

import (
"context"
"crypto/rand"
"fmt"
"math"
"math/big"
mathrand "math/rand"
"strings"

"github.com/cnoe-io/idpbuilder/api/v1alpha1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
specialChars = `!"#$%&'()*+,-./:;<=>?@[\\]^_{|}~`
passwordLength = 40
numSpecialChars = 3
numDigits = 3
)

func GetCLIStartTimeAnnotationValue(annotations map[string]string) (string, error) {
if annotations == nil {
return "", fmt.Errorf("this object's annotation is nil")
Expand Down Expand Up @@ -59,3 +73,53 @@ func UpdateSyncAnnotation(ctx context.Context, kubeClient client.Client, obj cli

return kubeClient.Patch(ctx, &u, client.Apply, client.ForceOwnership, client.FieldOwner(v1alpha1.FieldManager))
}

func GeneratePassword() (string, error) {
passChars := make([]string, passwordLength)
validChars := fmt.Sprintf("%s%s%s", chars, digits, specialChars)

for i := 0; i < numSpecialChars; i++ {
c, err := getRandElement(specialChars)
if err != nil {
return "", err
}
passChars = append(passChars, c)
}

for i := 0; i < numDigits; i++ {
c, err := getRandElement(digits)
if err != nil {
return "", err
}
passChars = append(passChars, c)
}

for i := 0; i < passwordLength-numDigits-numSpecialChars; i++ {
c, err := getRandElement(validChars)
if err != nil {
return "", err
}
passChars = append(passChars, c)
}

seed, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
return "", err
}

r := mathrand.New(mathrand.NewSource(seed.Int64()))
r.Shuffle(len(passChars), func(i, j int) {
passChars[i], passChars[j] = passChars[j], passChars[i]
})

return strings.Join(passChars, ""), nil
}

func getRandElement(input string) (string, error) {
position, err := rand.Int(rand.Reader, big.NewInt(int64(len(input))))
if err != nil {
return "", err
}

return string(input[position.Int64()]), nil
}
45 changes: 45 additions & 0 deletions pkg/util/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package util

import (
"strconv"
"testing"
)

var specialCharMap = make(map[string]struct{})

func TestGeneratePassword(t *testing.T) {

for i := range specialChars {
specialCharMap[string(specialChars[i])] = struct{}{}
}

for i := 0; i < 1000; i++ {
p, err := GeneratePassword()
if err != nil {
t.Fatalf("error generating password: %v", err)
}
counts := make([]int, 3)
for j := range p {
counts[0] += 1
c := string(p[j])
_, ok := specialCharMap[c]
if ok {
counts[1] += 1
continue
}
_, err := strconv.Atoi(c)
if err == nil {
counts[2] += 1
}
}
if counts[0] != passwordLength {
t.Fatalf("password legnth incorrect")
}
if counts[1] < numSpecialChars {
t.Fatalf("min number of special chars not generated")
}
if counts[2] < numDigits {
t.Fatalf("min number of digits not generated")
}
}
}

0 comments on commit a822dbd

Please sign in to comment.