Reverted to example webhook

This commit is contained in:
Chris Stuurman 2024-03-21 14:10:54 +02:00
parent b77c32f34d
commit 835d1ef135
11 changed files with 731 additions and 5043 deletions

110
go.mod
View File

@ -5,114 +5,8 @@ go 1.21
toolchain go1.22.1
require (
github.com/jetstack/cert-manager v1.7.3
github.com/cert-manager/cert-manager v1.14.4
github.com/miekg/dns v1.1.58
github.com/stretchr/testify v1.9.0
k8s.io/apiextensions-apiserver v0.29.0
k8s.io/client-go v0.29.3
)
require (
github.com/NYTimes/gziphandler v1.1.1 // indirect
github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/blang/semver/v4 v4.0.0 // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/cert-manager/cert-manager v1.14.4
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/evanphx/json-patch v5.7.0+incompatible // indirect
github.com/evanphx/json-patch/v5 v5.7.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-logr/zapr v1.3.0 // indirect
github.com/go-openapi/jsonpointer v0.20.2 // indirect
github.com/go-openapi/jsonreference v0.20.4 // indirect
github.com/go-openapi/swag v0.22.7 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/cel-go v0.17.7 // indirect
github.com/google/gnostic v0.6.9 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.18.0 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.45.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stoewer/go-strcase v1.3.0 // indirect
go.etcd.io/etcd/api/v3 v3.5.11 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.11 // indirect
go.etcd.io/etcd/client/v3 v3.5.11 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 // indirect
go.opentelemetry.io/otel v1.21.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.21.0 // indirect
go.opentelemetry.io/otel/metric v1.21.0 // indirect
go.opentelemetry.io/otel/sdk v1.21.0 // indirect
go.opentelemetry.io/otel/trace v1.21.0 // indirect
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/crypto v0.18.0 // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/oauth2 v0.15.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/term v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.17.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240102182953-50ed04b92917 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240102182953-50ed04b92917 // indirect
google.golang.org/grpc v1.60.1 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/api v0.29.3 // indirect
k8s.io/apimachinery v0.29.3 // indirect
k8s.io/apiserver v0.29.0 // indirect
k8s.io/component-base v0.29.0 // indirect
k8s.io/klog/v2 v2.110.1 // indirect
k8s.io/kms v0.29.0 // indirect
k8s.io/kube-aggregator v0.29.0 // indirect
k8s.io/kube-openapi v0.0.0-20240103051144-eec4567ac022 // indirect
k8s.io/utils v0.0.0-20240102154912-e7106e64919e // indirect
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.29.0 // indirect
sigs.k8s.io/controller-runtime v0.16.3 // indirect
sigs.k8s.io/gateway-api v1.0.0 // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)

846
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -3,8 +3,7 @@ package main
import (
"os"
"github.com/jetstack/cert-manager/pkg/acme/webhook/cmd"
"github.com/stuurmcp/cert-manager-webhook-sthome/pkg/dns"
"github.com/cert-manager/cert-manager/pkg/acme/webhook/cmd"
)
// GroupName is the name under which the webhook will be available

View File

@ -1,131 +0,0 @@
package dns
import (
"fmt"
"strconv"
"strings"
v1alpha1 "github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/stuurmcp/cert-manager-webhook-sthome/pkg/domain"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
providerName = "sthome"
)
// ProviderSolver is the struct implementing the webhook.Solver interface
// for sthome DNS
type ProviderSolver struct {
client kubernetes.Interface
}
// Name is used as the name for this DNS solver when referencing it on the ACME
// Issuer resource
func (p *ProviderSolver) Name() string {
return providerName
}
// Present is responsible for actually presenting the DNS record with the
// DNS provider.
// This method should tolerate being called multiple times with the same value.
// cert-manager itself will later perform a self check to ensure that the
// solver has correctly configured the DNS provider.
func (p *ProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
domainAPI, err := p.getDomainAPI(ch)
if err != nil {
return err
}
request := &domain.UpdateDNSZoneRecordsRequest{
DNSZone: strings.TrimSuffix(ch.ResolvedZone, "."),
Changes: []*domain.RecordChange{
{
Set: &domain.RecordChangeSet{
IDFields: &domain.RecordIdentifier{
Name: strings.TrimSuffix(strings.TrimSuffix(ch.ResolvedFQDN, ch.ResolvedZone), "."),
Type: domain.RecordTypeTXT,
Data: StringPtr(strconv.Quote(ch.Key)),
},
Records: []*domain.Record{
{
Name: strings.TrimSuffix(strings.TrimSuffix(ch.ResolvedFQDN, ch.ResolvedZone), "."),
Data: strconv.Quote(ch.Key),
Type: domain.RecordTypeTXT,
TTL: 60,
},
},
},
},
},
}
_, err = domainAPI.UpdateDNSZoneRecords(request)
if err != nil {
return fmt.Errorf("failed to update DNS zone records: %w", err)
}
return nil
}
// CleanUp should delete the relevant TXT record from the DNS provider console.
// If multiple TXT records exist with the same record name (e.g.
// _acme-challenge.example.com) then **only** the record with the same `key`
// value provided on the ChallengeRequest should be cleaned up.
// This is in order to facilitate multiple DNS validations for the same domain
// concurrently.
func (p *ProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
domainAPI, err := p.getDomainAPI(ch)
if err != nil {
return err
}
request := &domain.UpdateDNSZoneRecordsRequest{
DNSZone: strings.TrimSuffix(ch.ResolvedZone, "."),
Changes: []*domain.RecordChange{
{
Delete: &domain.RecordChangeDelete{
IDFields: &domain.RecordIdentifier{
Name: strings.TrimSuffix(strings.TrimSuffix(ch.ResolvedFQDN, ch.ResolvedZone), "."),
Data: StringPtr(strconv.Quote(ch.Key)),
Type: domain.RecordTypeTXT,
},
},
},
},
}
_, err = domainAPI.UpdateDNSZoneRecords(request)
if err != nil {
return fmt.Errorf("failed to update DNS zone records: %w", err)
}
return nil
}
// Initialize will be called when the webhook first starts.
// This method can be used to instantiate the webhook, i.e. initialising
// connections or warming up caches.
// Typically, the kubeClientConfig parameter is used to build a Kubernetes
// client that can be used to fetch resources from the Kubernetes API, e.g.
// Secret resources containing credentials used to authenticate with DNS
// provider accounts.
// The stopCh can be used to handle early termination of the webhook, in cases
// where a SIGTERM or similar signal is sent to the webhook process.
func (p *ProviderSolver) 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)
}
p.client = cl
return nil
}
// StringPtr returns a pointer to the string value provided
func StringPtr(v string) *string {
return &v
}

View File

@ -1,80 +0,0 @@
package dns
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/scaleway/cert-manager-webhook-scaleway/pkg/util"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/stuurmcp/cert-manager-webhook-sthome/pkg/domain"
//domain "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1"
//"github.com/scaleway/scaleway-sdk-go/scw"
extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// loadConfig is a small helper function that decodes JSON configuration into
// the typed config struct.
func loadConfig(cfgJSON *extapi.JSON) (ProviderConfig, error) {
cfg := ProviderConfig{}
// handle the 'base case' where no configuration has been provided
if cfgJSON == nil {
return cfg, nil
}
if err := json.Unmarshal(cfgJSON.Raw, &cfg); err != nil {
return cfg, fmt.Errorf("error decoding solver config: %v", err)
}
return cfg, nil
}
func (p *ProviderSolver) getDomainAPI(ch *v1alpha1.ChallengeRequest) (*domain.API, error) {
config, err := loadConfig(ch.Config)
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
accessKey := os.Getenv(scw.ScwAccessKeyEnv)
secretKey := os.Getenv(scw.ScwSecretKeyEnv)
if config.AccessKey != nil && config.SecretKey != nil {
accessKeySecret, err := p.client.CoreV1().Secrets(ch.ResourceNamespace).Get(context.Background(), config.AccessKey.Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("could not get secret %s: %w", config.AccessKey.Name, err)
}
secretKeySecret, err := p.client.CoreV1().Secrets(ch.ResourceNamespace).Get(context.Background(), config.SecretKey.Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("could not get secret %s: %w", config.SecretKey.Name, err)
}
accessKeyData, ok := accessKeySecret.Data[config.AccessKey.Key]
if !ok {
return nil, fmt.Errorf("could not get key %s in secret %s", config.AccessKey.Key, config.AccessKey.Name)
}
secretKeyData, ok := secretKeySecret.Data[config.SecretKey.Key]
if !ok {
return nil, fmt.Errorf("could not get key %s in secret %s", config.SecretKey.Key, config.SecretKey.Name)
}
accessKey = string(accessKeyData)
secretKey = string(secretKeyData)
}
scwClient, err := scw.NewClient(
scw.WithEnv(),
scw.WithAuth(accessKey, secretKey),
scw.WithUserAgent("cert-manager-webhook-scaleway/"+util.GetVersion().Version),
)
if err != nil {
return nil, fmt.Errorf("failed to initialize scaleway client: %w", err)
}
domainAPI := domain.NewAPI(scwClient)
return domainAPI, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,143 +0,0 @@
package domain
import (
"fmt"
"time"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/internal/errors"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
defaultRetryInterval = 15 * time.Second
defaultTimeout = 5 * time.Minute
)
const (
// ErrCodeNoSuchDNSZone for service response error code
//
// The specified dns zone does not exist.
ErrCodeNoSuchDNSZone = "NoSuchDNSZone"
ErrCodeNoSuchDNSRecord = "NoSuchDNSRecord"
)
// WaitForDNSZoneRequest is used by WaitForDNSZone method.
type WaitForDNSZoneRequest struct {
DNSZone string
DNSZones []string
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForDNSZone(
req *WaitForDNSZoneRequest,
opts ...scw.RequestOption,
) (*DNSZone, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[DNSZoneStatus]struct{}{
DNSZoneStatusActive: {},
DNSZoneStatusLocked: {},
DNSZoneStatusError: {},
}
dns, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
listReq := &ListDNSZonesRequest{
DNSZones: req.DNSZones,
}
if req.DNSZone != "" {
listReq.DNSZone = &req.DNSZone
}
// listing dns zones and take the first one
DNSZones, err := s.ListDNSZones(listReq, opts...)
if err != nil {
return nil, false, err
}
if len(DNSZones.DNSZones) == 0 {
return nil, true, fmt.Errorf(ErrCodeNoSuchDNSZone)
}
Dns := DNSZones.DNSZones[0]
_, isTerminal := terminalStatus[Dns.Status]
return Dns, isTerminal, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for DNS failed")
}
return dns.(*DNSZone), nil
}
// WaitForDNSRecordExistRequest is used by WaitForDNSRecordExist method.
type WaitForDNSRecordExistRequest struct {
DNSZone string
RecordName string
RecordType RecordType
Timeout *time.Duration
RetryInterval *time.Duration
}
func (s *API) WaitForDNSRecordExist(
req *WaitForDNSRecordExistRequest,
opts ...scw.RequestOption,
) (*Record, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
dns, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
// listing dns zone records and take the first one
DNSRecords, err := s.ListDNSZoneRecords(&ListDNSZoneRecordsRequest{
Name: req.RecordName,
Type: req.RecordType,
DNSZone: req.DNSZone,
}, opts...)
if err != nil {
return nil, false, err
}
if DNSRecords.TotalCount == 0 {
return nil, false, fmt.Errorf(ErrCodeNoSuchDNSRecord)
}
record := DNSRecords.Records[0]
return record, true, nil
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "check for DNS Record exist failed")
}
return dns.(*Record), nil
}

View File

@ -1,35 +0,0 @@
package util
import (
"fmt"
"runtime"
)
// These are set during build time via -ldflags
var (
version = "0.0.1+dev"
gitCommit string
buildDate string
)
// VersionInfo represents the current running version
type VersionInfo struct {
Version string `json:"version"`
GitCommit string `json:"gitCommit"`
BuildDate string `json:"buildDate"`
GoVersion string `json:"goVersion"`
Compiler string `json:"compiler"`
Platform string `json:"platform"`
}
// GetVersion returns the current running version
func GetVersion() VersionInfo {
return VersionInfo{
Version: version,
GitCommit: gitCommit,
BuildDate: buildDate,
GoVersion: runtime.Version(),
Compiler: runtime.Compiler,
Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
}
}

View File

@ -1,4 +1,4 @@
package dns
package sthome
import (
"fmt"
@ -50,14 +50,14 @@ func (e *sthomeSolver) addDNSAnswer(q dns.Question, msg *dns.Msg, req *dns.Msg)
// NS and SOA are for authoritative lookups, return obviously invalid data
case dns.TypeNS:
rr, err := dns.NewRR(fmt.Sprintf("%s 5 IN NS ns.example-acme-webook.invalid.", q.Name))
rr, err := dns.NewRR(fmt.Sprintf("%s 5 IN NS ns.sthome-acme-webook.invalid.", q.Name))
if err != nil {
return err
}
msg.Answer = append(msg.Answer, rr)
return nil
case dns.TypeSOA:
rr, err := dns.NewRR(fmt.Sprintf("%s 5 IN SOA %s 20 5 5 5 5", "ns.example-acme-webook.invalid.", "ns.example-acme-webook.invalid."))
rr, err := dns.NewRR(fmt.Sprintf("%s 5 IN SOA %s 20 5 5 5 5", "ns.sthome-acme-webook.invalid.", "ns.sthome-acme-webook.invalid."))
if err != nil {
return err
}

View File

@ -1,15 +1,14 @@
// package example contains a self-contained example of a webhook that passes the cert-manager
// package sthome contains a self-contained sthome of a webhook that passes the cert-manager
// DNS conformance tests
package dns
package sthome
import (
"fmt"
"os"
"sync"
//"github.com/jetstack/cert-manager/pkg/acme/webhook"
"github.com/jetstack/cert-manager/pkg/acme/webhook"
acme "github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/cert-manager/cert-manager/pkg/acme/webhook"
acme "github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/miekg/dns"
"k8s.io/client-go/rest"
)
@ -57,7 +56,7 @@ func (e *sthomeSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan s
func New(port string) webhook.Solver {
e := &sthomeSolver{
name: "example",
name: "sthome",
txtRecords: make(map[string]string),
}
e.server = &dns.Server{

View File

@ -1,23 +1,23 @@
package dns
package sthome
import (
"crypto/rand"
"math/big"
"testing"
acme "github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
acme "github.com/cert-manager/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
)
func TestSthomeSolver_Name(t *testing.T) {
func TeststhomeSolver_Name(t *testing.T) {
port, _ := rand.Int(rand.Reader, big.NewInt(50000))
port = port.Add(port, big.NewInt(15534))
solver := New(port.String())
assert.Equal(t, "sthome", solver.Name())
}
func TestSthomeSolver_Initialize(t *testing.T) {
func TeststhomeSolver_Initialize(t *testing.T) {
port, _ := rand.Int(rand.Reader, big.NewInt(50000))
port = port.Add(port, big.NewInt(15534))
solver := New(port.String())
@ -27,7 +27,7 @@ func TestSthomeSolver_Initialize(t *testing.T) {
close(done)
}
func TestSthomeSolver_Present_Cleanup(t *testing.T) {
func TeststhomeSolver_Present_Cleanup(t *testing.T) {
port, _ := rand.Int(rand.Reader, big.NewInt(50000))
port = port.Add(port, big.NewInt(15534))
solver := New(port.String())
@ -39,9 +39,9 @@ func TestSthomeSolver_Present_Cleanup(t *testing.T) {
hostname string
record string
}{
{"test1.sthome.net.", "testkey1"},
{"test2.sthome.net.", "testkey2"},
{"test3.sthome.net.", "testkey3"},
{"test1.sthome.com.", "testkey1"},
{"test2.sthome.com.", "testkey2"},
{"test3.sthome.com.", "testkey3"},
}
for _, test := range validTestData {
err := solver.Present(&acme.ChallengeRequest{