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

refactor: [experimental] create TLS certificate via code & save it in a PersistentVolume #421

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
works
  • Loading branch information
royhadad committed Jul 13, 2023
commit ef5643ac8ae449ca4a72c9ed4fcc836b5c5d5f13
6 changes: 0 additions & 6 deletions charts/datree-admission-webhook/templates/deployment.yaml
Original file line number Diff line number Diff line change
@@ -108,19 +108,13 @@ spec:
volumeMounts:
- mountPath: /etc/webhook-certs
name: volume
- name: webhook-tls-certs
mountPath: /run/secrets/tls
readOnly: true
- name: webhook-config
mountPath: /config
readOnly: true
volumes:
- name: volume
persistentVolumeClaim:
claimName: volume-claim
- name: webhook-tls-certs
secret:
secretName: webhook-server-tls
- name: webhook-config
projected:
sources:
2 changes: 1 addition & 1 deletion internal/startup/startup.go
Original file line number Diff line number Diff line change
@@ -98,7 +98,7 @@ func Start() {
if err != nil {
fmt.Printf("Failed to create k8s client: %s \n", err.Error())
}
err = k8sClient2Instance.ActivateValidatingWebhookConfiguration(cert_manager.CaCertPath)
err = k8sClient2Instance.ActivateValidatingWebhookConfiguration()
if err != nil {
fmt.Printf("Failed to activate validating webhook configuration: %s \n", err.Error())
}
22 changes: 12 additions & 10 deletions pkg/cert-manager/cert-manager.go
Original file line number Diff line number Diff line change
@@ -19,7 +19,6 @@ const certsFolder = "/etc/webhook-certs"
const TlsCertPath = certsFolder + "/tls.crt"
const TlsKeyPath = certsFolder + "/tls.key"
const CaCertPath = certsFolder + "/ca.crt"
const CaKeyPath = certsFolder + "/ca.key"

type AllCertificates struct {
Cert []byte
@@ -43,7 +42,7 @@ func doCertificatesExist() bool {
return true
}

return doesFileExist(TlsCertPath) && doesFileExist(TlsKeyPath) && doesFileExist(CaCertPath) && doesFileExist(CaKeyPath)
return doesFileExist(TlsCertPath) && doesFileExist(TlsKeyPath) && doesFileExist(CaCertPath)
}

func generateCertificates() {
@@ -81,20 +80,18 @@ func generateCertificates() {
Bytes: caBytes,
})

dnsNames := []string{"webhook-service",
"webhook-service.default", "webhook-service.default.svc"}
commonName := "datree-webhook-server.datree.svc" // TODO use namespace from config
webhookDNS := "datree-webhook-server.datree.svc" // TODO use namespace from config

// server cert config
cert := &x509.Certificate{
DNSNames: dnsNames,
DNSNames: []string{webhookDNS},
SerialNumber: big.NewInt(1658),
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"velotio.com"},
CommonName: fmt.Sprintf("/CN=%v", webhookDNS),
Organization: []string{"/CN=Datree Admission Controller Webhook CA"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
NotAfter: time.Now().AddDate(5, 0, 0),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
@@ -124,7 +121,12 @@ func generateCertificates() {
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(serverPrivKey),
})


err = writeFile(CaCertPath, caPEM)
if err != nil {
log.Panic(err)
}

err = writeFile(TlsCertPath, serverCertPEM)
if err != nil {
log.Panic(err)
25 changes: 6 additions & 19 deletions pkg/k8sClient2/k8sClient2.go
Original file line number Diff line number Diff line change
@@ -2,23 +2,18 @@ package k8sClient2

import (
"context"
"fmt"
cert_manager "github.com/datreeio/admission-webhook-datree/pkg/cert-manager"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"os"
)

type k8sClientInterface interface {
doesValidatingWebhookConfigurationExist() (any, error)
applyValidatingWebhookConfiguration() (any, error)
}

type k8sClient struct {
type K8sClient struct {
clientset *kubernetes.Clientset
}

func NewK8sClient() (*k8sClient, error) {
func NewK8sClient() (*K8sClient, error) {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
@@ -30,21 +25,17 @@ func NewK8sClient() (*k8sClient, error) {
return nil, err
}

return &k8sClient{
return &K8sClient{
clientset: clientsetInstance,
}, nil
}

func (kc *k8sClient) ActivateValidatingWebhookConfiguration(caCertPath string) error {
certificateContent, readFileError := os.ReadFile(caCertPath)
func (kc *K8sClient) ActivateValidatingWebhookConfiguration() error {
certificateContent, readFileError := os.ReadFile(cert_manager.CaCertPath)
if readFileError != nil {
return readFileError
}

fmt.Println("@@@@@@@@@@@@@@@@@")
fmt.Println(string(certificateContent))
fmt.Println("@@@@@@@@@@@@@@@@@")

existingValidatingWebhookConfiguration, err := kc.clientset.AdmissionregistrationV1().ValidatingWebhookConfigurations().Get(context.TODO(), "datree-webhook", metav1.GetOptions{})
if err != nil {
return err
@@ -66,7 +57,3 @@ func (kc *k8sClient) ActivateValidatingWebhookConfiguration(caCertPath string) e

return nil
}

func (kc *k8sClient) applyValidatingWebhookConfiguration() error {
return nil
}
23 changes: 0 additions & 23 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
@@ -2,12 +2,10 @@ package server

import (
"errors"
"fmt"
servicestate "github.com/datreeio/admission-webhook-datree/pkg/serviceState"
"os"
"path/filepath"

"github.com/datreeio/admission-webhook-datree/pkg/deploymentConfig"
"gopkg.in/yaml.v2"
)

@@ -71,24 +69,3 @@ func readConfigScanningFilters() (skipList []string, err error) {
}
return skipLists, nil
}

func ValidateCertificate() (certPath string, keyPath string, err error) {
tlsDir := `/run/secrets/tls`
tlsCertFile := `tls.crt`
tlsKeyFile := `tls.key`

certPath = filepath.Join(tlsDir, tlsCertFile)
keyPath = filepath.Join(tlsDir, tlsKeyFile)

if deploymentConfig.ShouldValidateCertificate {
if _, err := os.Stat(certPath); errors.Is(err, os.ErrNotExist) {
return "", "", fmt.Errorf("cert file doesn't exist")
}

if _, err := os.Stat(keyPath); errors.Is(err, os.ErrNotExist) {
return "", "", fmt.Errorf("key file doesn't exist")
}
}

return certPath, keyPath, nil
}