Add kubernetes client back

This commit is contained in:
Chris Stuurman 2024-04-06 12:39:47 +02:00
parent 712c49164a
commit a5f92861e7
11 changed files with 152 additions and 68 deletions

View File

@ -27,7 +27,7 @@ type LocalDNSProviderSolver struct {
// within a single webhook deployment**. // within a single webhook deployment**.
// For example, `cloudflare` may be used as the name of a solver. // For example, `cloudflare` may be used as the name of a solver.
func (p *LocalDNSProviderSolver) Name() string { func (p *LocalDNSProviderSolver) Name() string {
return providerName return ProviderName
} }
// Present is responsible for actually presenting the DNS record with the // Present is responsible for actually presenting the DNS record with the

View File

@ -10,7 +10,6 @@ import (
) )
const ( const (
version = "0.0.4-alpha"
chartfile = "./deploy/sthome-webhook/Chart.yaml" chartfile = "./deploy/sthome-webhook/Chart.yaml"
valuesfile = "./deploy/sthome-webhook/values.yaml" valuesfile = "./deploy/sthome-webhook/values.yaml"
tagprefix = " tag: " tagprefix = " tag: "
@ -38,9 +37,11 @@ func main() {
// Generate a timestamp. // Generate a timestamp.
buildTime = time.Now().Format("20060102-1504") buildTime = time.Now().Format("20060102-1504")
// Load the count from the 3rd line of the file // deconstruct version line and remove build increment part
// It's a string so we need to convert to integer verparts := strings.Split(vLines[0], "-")
// Then increment it by 1 versionmins := strings.Split(verparts[1], ".")
version := verparts[0] + "-" + versionmins[0]
bNum, _ := strconv.Atoi(vLines[2]) bNum, _ := strconv.Atoi(vLines[2])
bNum++ bNum++
longversion = version + "." + fmt.Sprint(bNum) longversion = version + "." + fmt.Sprint(bNum)

View File

@ -1,5 +1,5 @@
apiVersion: v1 apiVersion: v1
appVersion: v0.0.4-alpha.112 appVersion: v0.0.5-alpha.1
description: Cert-Manager webhook for sthome description: Cert-Manager webhook for sthome
name: sthome-webhook name: sthome-webhook
version: 0.0.4-alpha.112 version: 0.0.5-alpha.1

View File

@ -31,7 +31,7 @@ clusterIssuer:
image: image:
repository: stuurmcp/cert-manager-webhook-sthome repository: stuurmcp/cert-manager-webhook-sthome
#repository: wstat.sthome.net:5000/cert-manager-webhook-sthome #repository: wstat.sthome.net:5000/cert-manager-webhook-sthome
tag: 0.0.4-alpha.112 tag: 0.0.5-alpha.1
#pullPolicy should be IfNotPresent. Set to Always for testing purposes #pullPolicy should be IfNotPresent. Set to Always for testing purposes
pullPolicy: IfNotPresent pullPolicy: IfNotPresent

10
go.mod
View File

@ -12,12 +12,12 @@ require (
k8s.io/client-go v0.29.0 k8s.io/client-go v0.29.0
) )
require ( require k8s.io/klog/v2 v2.110.1
k8s.io/apimachinery v0.29.0
k8s.io/klog/v2 v2.110.1
)
require github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect require (
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
k8s.io/apimachinery v0.29.0 // indirect
)
require ( require (
github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect

88
main.go
View File

@ -2,11 +2,17 @@ package main
import ( import (
_ "embed" _ "embed"
"fmt"
"os"
"strings" "strings"
"os" "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd" "github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd"
"github.com/cert-manager/cert-manager/pkg/issuer/acme/dns/util"
dns "github.com/stuurmcp/cert-manager-webhook-sthome/pkg/dns" dns "github.com/stuurmcp/cert-manager-webhook-sthome/pkg/dns"
) )
@ -28,3 +34,83 @@ func main() {
&dns.SthomeSolver{}, &dns.SthomeSolver{},
) )
} }
type LocalDNSProviderSolver struct {
client kubernetes.Interface
}
func (p *LocalDNSProviderSolver) Name() string {
return dns.ProviderName
}
func (loc *LocalDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
cfg, err := dns.LoadConfig(ch.Config)
if err != nil {
return err
}
klog.Infof("CZ: Presenting record for %s, type: %s, uid: %s, key: %s, ns: %s, fqdn: %s, zone: %s, allowambcred: %t, cfg.secret: %s, cfg.email: %s, cfg.allowz: %s",
ch.DNSName,
ch.UID,
ch.Type,
ch.Key,
ch.ResourceNamespace,
ch.ResolvedFQDN,
ch.ResolvedZone,
ch.AllowAmbientCredentials,
cfg.APIKeySecretRef.Name,
cfg.Email,
strings.Join(cfg.AllowedZones, ","),
)
// TODO: convert shell script to golang
localip := dns.GetOutboundIP(dns.Dnsserver_net)
success, _ := dns.Execute(
dns.Shell,
dns.AcmeAuthCmd,
"set",
ch.DNSName,
ch.ResolvedFQDN,
ch.Key,
"-l",
localip,
"-v",
)
klog.Infof("Execute set TXT returned success: %t", success)
return nil
}
func (loc *LocalDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
//domainName := extractDomainName(ch.ResolvedZone)
// TODO: add code that deletes a record from the DNS provider's console
localip := dns.GetOutboundIP(dns.Dnsserver_net)
success, _ := dns.Execute(
dns.Shell,
dns.AcmeAuthCmd,
"unset",
ch.DNSName,
ch.ResolvedFQDN,
ch.Key,
"-l",
localip,
"-v",
)
klog.Infof("Execute unset TXT returned success: %t", success)
return nil
}
func (loc *LocalDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
cl, err := kubernetes.NewForConfig(kubeClientConfig)
if err != nil {
return fmt.Errorf("failed to get kubernetes client: %w", err)
}
loc.client = cl
klog.InfoS("CZ: Successfully initialised kubernetes client!")
return nil
}
func extractDomainName(zone string) string {
authZone, err := util.FindZoneByFqdn(zone, util.RecursiveNameservers)
if err != nil {
klog.Errorf("could not get zone by fqdn %v", err)
return zone
}
return util.UnFqdn(authZone)
}

View File

@ -12,14 +12,14 @@ const (
SthomeAccessKeyEnv = "STHOME_ACCESS_KEY" SthomeAccessKeyEnv = "STHOME_ACCESS_KEY"
SthomeSecretKeyEnv = "STHOME_SECRET_KEY" SthomeSecretKeyEnv = "STHOME_SECRET_KEY"
providerName = "sthome" ProviderName = "sthome"
shell = "/bin/bash" Shell = "/bin/bash"
acmeAuthCmd = "/acme/acmeauth.sh" AcmeAuthCmd = "/acme/acmeauth.sh"
dnsserver_net = "10.0.0.15" Dnsserver_net = "10.0.0.15"
dnsserver_lan = "192.168.2.1" Dnsserver_lan = "192.168.2.1"
hostserver_net = "truenas.sthome.net" Hostserver_net = "truenas.sthome.net"
hostserver_lan = "truenas.sthome.lan" Hostserver_lan = "truenas.sthome.lan"
) )
// localDNSProviderConfig is a structure that is used to decode into when // localDNSProviderConfig is a structure that is used to decode into when
@ -111,7 +111,7 @@ func (cfg LocalDNSProviderConfig) IsAllowedZone(zone string) bool {
} }
// Get preferred outbound ip of this machine // Get preferred outbound ip of this machine
func getOutboundIP(dest string) string { func GetOutboundIP(dest string) string {
conn, err := net.Dial("udp", dest+":80") conn, err := net.Dial("udp", dest+":80")
if err != nil { if err != nil {
klog.Errorf("net.Dial error: %s", err) klog.Errorf("net.Dial error: %s", err)

View File

@ -29,7 +29,7 @@ func (e *SthomeSolver) Present(ch *acme.ChallengeRequest) error {
e.Lock() e.Lock()
e.txtRecords[ch.ResolvedFQDN] = ch.Key e.txtRecords[ch.ResolvedFQDN] = ch.Key
e.Unlock() e.Unlock()
cfg, err := loadConfig(ch.Config) cfg, err := LoadConfig(ch.Config)
if err != nil { if err != nil {
return err return err
} }
@ -47,10 +47,10 @@ func (e *SthomeSolver) Present(ch *acme.ChallengeRequest) error {
strings.Join(cfg.AllowedZones, ","), strings.Join(cfg.AllowedZones, ","),
) )
// TODO: convert shell script to golang // TODO: convert shell script to golang
localip := getOutboundIP(dnsserver_net) localip := GetOutboundIP(Dnsserver_net)
success, _ := Execute( success, _ := Execute(
shell, Shell,
acmeAuthCmd, AcmeAuthCmd,
"set", "set",
ch.DNSName, ch.DNSName,
ch.ResolvedFQDN, ch.ResolvedFQDN,
@ -67,10 +67,10 @@ func (e *SthomeSolver) CleanUp(ch *acme.ChallengeRequest) error {
e.Lock() e.Lock()
delete(e.txtRecords, ch.ResolvedFQDN) delete(e.txtRecords, ch.ResolvedFQDN)
e.Unlock() e.Unlock()
localip := getOutboundIP(dnsserver_net) localip := GetOutboundIP(Dnsserver_net)
success, _ := Execute( success, _ := Execute(
shell, Shell,
acmeAuthCmd, AcmeAuthCmd,
"unset", "unset",
ch.DNSName, ch.DNSName,
ch.ResolvedFQDN, ch.ResolvedFQDN,
@ -101,7 +101,7 @@ func (e *SthomeSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan s
func New(port string) webhook.Solver { func New(port string) webhook.Solver {
e := &SthomeSolver{ e := &SthomeSolver{
name: "sthome", name: ProviderName,
txtRecords: make(map[string]string), txtRecords: make(map[string]string),
} }
e.server = &dns.Server{ e.server = &dns.Server{

View File

@ -12,7 +12,7 @@ import (
// loadConfig is a small helper function that decodes JSON configuration into // loadConfig is a small helper function that decodes JSON configuration into
// the typed config struct. // the typed config struct.
func loadConfig(cfgJSON *extapi.JSON) (LocalDNSProviderConfig, error) { func LoadConfig(cfgJSON *extapi.JSON) (LocalDNSProviderConfig, error) {
cfg := LocalDNSProviderConfig{} cfg := LocalDNSProviderConfig{}
// handle the 'base case' where no configuration has been provided // handle the 'base case' where no configuration has been provided
if cfgJSON == nil { if cfgJSON == nil {

View File

@ -1,9 +1,7 @@
package dns package dns
import ( import (
"context"
"fmt" "fmt"
"os"
"reflect" "reflect"
"testing" "testing"
@ -11,8 +9,6 @@ import (
//client "github.com/kubernetes-sdk-for-go-101/pkg/client" //client "github.com/kubernetes-sdk-for-go-101/pkg/client"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
testclient "k8s.io/client-go/kubernetes/fake"
) )
func Test_loadConfig(t *testing.T) { func Test_loadConfig(t *testing.T) {
@ -67,7 +63,7 @@ func Test_loadConfig(t *testing.T) {
if test.json == "" { if test.json == "" {
json = nil json = nil
} }
config, err := loadConfig(json) config, err := LoadConfig(json)
if err != nil { if err != nil {
if !test.shouldErr { if !test.shouldErr {
t.Errorf("got error %v where no error was expected", err) t.Errorf("got error %v where no error was expected", err)
@ -81,6 +77,7 @@ func Test_loadConfig(t *testing.T) {
} }
} }
/*
func Test_getDomainAPI(t *testing.T) { func Test_getDomainAPI(t *testing.T) {
jsonBothKey := &extapi.JSON{ jsonBothKey := &extapi.JSON{
Raw: []byte(`{ Raw: []byte(`{
@ -158,42 +155,42 @@ func Test_getDomainAPI(t *testing.T) {
shouldErr: false, shouldErr: false,
}, },
} }
for _, test := range testCases {
fakeKubernetesClient := testclient.NewSimpleClientset()
pSolver := &main.LocalDNSProviderSolver{
client: fakeKubernetesClient,
}
for _, test := range testCases { if test.secret != nil {
fakeKubernetesClient := testclient.NewSimpleClientset() _, err := pSolver.client.CoreV1().Secrets(test.ch.ResourceNamespace).Create(context.Background(), test.secret, metav1.CreateOptions{})
pSolver := &LocalDNSProviderSolver{ if err != nil {
client: fakeKubernetesClient, t.Errorf("failed to create kubernetes secret")
} }
}
if test.secret != nil { for k, v := range test.env {
_, err := pSolver.client.CoreV1().Secrets(test.ch.ResourceNamespace).Create(context.Background(), test.secret, metav1.CreateOptions{}) os.Setenv(k, v)
}
_, err := getDomainAPI(test.ch)
if err != nil { if err != nil {
t.Errorf("failed to create kubernetes secret") if !test.shouldErr {
t.Errorf("got error %v where no error was expected", err)
}
if err.Error() != test.errMessage {
t.Errorf("expected error %s, got %s", test.errMessage, err.Error())
}
} else if test.shouldErr {
t.Errorf("didn't get an error where an error was expected with message %s", test.errMessage)
}
for k := range test.env {
os.Unsetenv(k)
} }
} }
for k, v := range test.env {
os.Setenv(k, v)
}
_, err := getDomainAPI(test.ch)
if err != nil {
if !test.shouldErr {
t.Errorf("got error %v where no error was expected", err)
}
if err.Error() != test.errMessage {
t.Errorf("expected error %s, got %s", test.errMessage, err.Error())
}
} else if test.shouldErr {
t.Errorf("didn't get an error where an error was expected with message %s", test.errMessage)
}
for k := range test.env {
os.Unsetenv(k)
}
}
}
}
*/
// dummy, should actually return the API, but here we just return the config // dummy, should actually return the API, but here we just return the config
func getDomainAPI(ch *v1alpha1.ChallengeRequest) (*LocalDNSProviderConfig, error) { func getDomainAPI(ch *v1alpha1.ChallengeRequest) (*LocalDNSProviderConfig, error) {
config, err := loadConfig(ch.Config) config, err := LoadConfig(ch.Config)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err) return nil, fmt.Errorf("failed to load config: %w", err)
} }

View File

@ -1,3 +1,3 @@
0.0.4-alpha.112 0.0.5-alpha.1
20240406-0925 20240406-1230
112 1