Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix-cert-and-token #109

Merged
merged 1 commit into from
Jan 16, 2023
Merged
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
5 changes: 4 additions & 1 deletion internal/resources/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)


func (r *Manager) SecretGet(namespace, name string) (*v1.Secret, error) {
return r.kubeclient.CoreV1().Secrets(namespace).Get(r.context, name, metav1.GetOptions{})
}

func (r *Manager) SecretCreate(namespace string, secret *v1.Secret) (*v1.Secret, error) {
return r.kubeclient.CoreV1().Secrets(namespace).Create(r.context, secret, metav1.CreateOptions{})
}
184 changes: 119 additions & 65 deletions internal/resources/serviceaccount.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
package resources

import (
b64 "encoding/base64"
"fmt"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"log"
"sighupio/permission-manager/internal/config"
"strings"
"time"
)

v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func (r *Manager) ServiceAccountGet(namespace, name string) (*v1.ServiceAccount, error) {
return r.kubeclient.CoreV1().ServiceAccounts(namespace).Get(r.context, name, metav1.GetOptions{})
}

// func (r *Manager) ServiceAccountCreateToken(namespace string, tokenRequest *v1.TokenRequest, name string) (*v1.TokenRequest, error) {
// return r.kubeclient.CoreV1().ServiceAccounts(namespace).CreateToken(r.context, name, tokenRequest, metav1.CreateOptions{})
// }

func (r *Manager) ServiceAccountCreate(namespace, name string) (*v1.ServiceAccount, error) {
return r.kubeclient.CoreV1().ServiceAccounts(namespace).Create(r.context, &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Expand All @@ -29,19 +33,74 @@ func (r *Manager) ServiceAccountCreateKubeConfigForUser(cluster config.ClusterCo

serviceAccountNamespace := "permission-manager" // TODO: must be received externally to this func?

// Create service account
_, err := r.ServiceAccountCreate(serviceAccountNamespace, username)
var serviceAccount *v1.ServiceAccount = nil
var accountSecret *v1.Secret = nil
var err error

/**** handle service account start ****/
serviceAccount, err = r.ServiceAccountGet(serviceAccountNamespace, username)
if err != nil {
log.Printf("Service Account not created: %v", err)
if strings.Contains(err.Error(), "not found") {
serviceAccount = nil
} else {
log.Printf("Inital get secret failed: %v", err)
}
}

// get service account token
_, token, err := r.serviceAccountGetToken(serviceAccountNamespace, username, true)
if serviceAccount == nil {
serviceAccount, err = r.ServiceAccountCreate(serviceAccountNamespace, username)
time.Sleep(2 * time.Second)
if err != nil {
log.Printf("Service Account not created: %v", err)
}
}
/**** handle service account end ****/

/**** handle service account's secret ****/
accountSecret, err = r.SecretGet(serviceAccountNamespace, username)
if err != nil {
log.Fatal(err)
if strings.Contains(err.Error(), "not found") {
accountSecret = nil
} else {
log.Printf("Inital get secret failed: %v", err)
}
}

// if user delete the secret of the account this will allow generate a new one as well)
if accountSecret == nil {
// create secrete for the service account
var secret = new(v1.Secret)
secret.SetName(username)
// ensure the name and the uid match to the account name and account uid, which will be used for authentication by the k8s
secret.SetAnnotations(map[string]string{
"kubernetes.io/service-account.name": username,
"kubernetes.io/service-account.uid": string(serviceAccount.GetUID()),
})

// type kubernetes.io/service-account-token will automatically map the root.ca and create a token to the Data of service account
secret.Type = "kubernetes.io/service-account-token"
// create secreat
_, err = r.SecretCreate(serviceAccountNamespace, secret)

if err != nil {
log.Printf("Account Secret not created: %v", err)
}

// try 10 times with 0.5 second interval (to wait for k8s fill the data to the newly created Secret)
for i := 1; i <= 10; i++ {
accountSecret, err = r.SecretGet(serviceAccountNamespace, username)
if err != nil {
log.Printf("Get Secret for account %v failed, : %v", username, err)
break
}

if accountSecret.Data["ca.crt"] != nil {
break
}
time.Sleep(500 * time.Millisecond)
}
}
/**** handle service account's end ****/

certificateTpl := `---
apiVersion: v1
Expand All @@ -66,7 +125,7 @@ users:
return fmt.Sprintf(certificateTpl,
username,
cluster.Name,
getCaBase64(),
b64.StdEncoding.EncodeToString(accountSecret.Data["ca.crt"]),
cluster.ControlPlaneAddress,
cluster.Name,
cluster.Name,
Expand All @@ -75,76 +134,71 @@ users:
username,
cluster.Name,
username,
token,
accountSecret.Data["token"],
)
}



//todo refactor
func (r *Manager) serviceAccountGetToken(ns string, name string, shouldWaitServiceAccountCreation bool) (tokenName string, token string, err error) {

findToken := func() (bool, error) {
user, err := r.ServiceAccountGet(ns, name)
// func (r *Manager) serviceAccountGetToken(ns string, name string, shouldWaitServiceAccountCreation bool) (tokenName string, token string, err error) {

if apierrors.IsNotFound(err) {
return false, nil
}
// findToken := func() (bool, error) {
// user, err := r.ServiceAccountGet(ns, name)

if err != nil {
return false, err
}
// if apierrors.IsNotFound(err) {
// return false, nil
// }

for _, ref := range user.Secrets {
// if err != nil {
// return false, err
// }

secret, err := r.SecretGet(ns, ref.Name)

if apierrors.IsNotFound(err) {
continue
}

if err != nil {
return false, err
}
// for _, ref := range user.Secrets {

if secret.Type != v1.SecretTypeServiceAccountToken {
continue
}
// secret, err := r.SecretGet(ns, ref.Name)

name := secret.Annotations[v1.ServiceAccountNameKey]
uid := secret.Annotations[v1.ServiceAccountUIDKey]
tokenData := secret.Data[v1.ServiceAccountTokenKey]
// if apierrors.IsNotFound(err) {
// continue
// }

if name == user.Name && uid == string(user.UID) && len(tokenData) > 0 {
tokenName = secret.Name
token = string(tokenData)
// if err != nil {
// return false, err
// }

return true, nil
}
}
// if secret.Type != v1.SecretTypeServiceAccountToken {
// continue
// }

return false, nil
}
// name := secret.Annotations[v1.ServiceAccountNameKey]
// uid := secret.Annotations[v1.ServiceAccountUIDKey]
// tokenData := secret.Data[v1.ServiceAccountTokenKey]

if shouldWaitServiceAccountCreation {
err := wait.Poll(time.Second, 10*time.Second, findToken)
// if name == user.Name && uid == string(user.UID) && len(tokenData) > 0 {
// tokenName = secret.Name
// token = string(tokenData)

if err != nil {
return "", "", err
}
} else {
ok, err := findToken()
if err != nil {
return "", "", err
}
// return true, nil
// }
// }

if !ok {
return "", "", fmt.Errorf("No token found for %s/%s", ns, name)
}
}
// return false, nil
// }

return tokenName, token, nil
}
// if shouldWaitServiceAccountCreation {
// err := wait.Poll(time.Second, 10*time.Second, findToken)

// if err != nil {
// return "", "", err
// }
// } else {
// ok, err := findToken()
// if err != nil {
// return "", "", err
// }

// if !ok {
// return "", "", fmt.Errorf("No token found for %s/%s", ns, name)
// }
// }

// return tokenName, token, nil
// }