Commit 0ced76aa authored by michaelguarino's avatar michaelguarino
Browse files

Implement plural cert manager webhook

parent 9440683e
Pipeline #632 passed with stage
in 3 minutes and 27 seconds
Showing with 219 additions and 134 deletions
+219 -134
default:
image: gcr.io/google.com/cloudsdktool/cloud-sdk:latest
services:
- name: gcr.io/pluralsh/docker:19.03.13-dind
alias: docker
before_script:
- until docker info; do sleep 1; done
- gcloud auth activate-service-account --key-file=$GOOGLE_APPLICATION_CREDENTIALS
- gcloud auth configure-docker -q
- docker login -u mguarino46@gmail.com -p $PLURAL_ACCESS_TOKEN dkr.plural.sh
retry:
max: 2
when:
- runner_system_failure
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: 1
DOCKER_CERT_PATH: "$DOCKER_TLS_CERTDIR/client"
stages:
- push
push-certmanager-webhook:
stage: push
script:
- make build
- make push
OS ?= $(shell go env GOOS)
ARCH ?= $(shell go env GOARCH)
IMAGE_NAME := "webhook"
IMAGE_TAG := "latest"
GCP_PROJECT ?= pluralsh
IMAGE_NAME := "plural-certmanager-webhook"
IMAGE_TAG := "0.1.0"
DKR_HOST ?= dkr.plural.sh
OUT := $(shell pwd)/_out
......@@ -27,7 +29,12 @@ clean-kubebuilder:
rm -Rf _test/kubebuilder
build:
docker build -t "$(IMAGE_NAME):$(IMAGE_TAG)" .
docker build -t gcr.io/$(GCP_PROJECT)/$(IMAGE_NAME):$(IMAGE_TAG) \
-t $(DKR_HOST)/bootstrap/$(IMAGE_NAME):$(IMAGE_TAG) .
push:
docker push gcr.io/$(GCP_PROJECT)/$(IMAGE_NAME):$(IMAGE_TAG)
docker push $(DKR_HOST)/bootstrap/$(IMAGE_NAME):$(IMAGE_TAG)
.PHONY: rendered-manifest.yaml
rendered-manifest.yaml:
......
This diff is collapsed.
......@@ -11,6 +11,7 @@ import (
"github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/jetstack/cert-manager/pkg/acme/webhook/cmd"
"github.com/pluralsh/plural-certmanager-webhook/plural"
)
var GroupName = os.Getenv("GROUP_NAME")
......@@ -26,56 +27,25 @@ func main() {
// webhook, where the Name() method will be used to disambiguate between
// the different implementations.
cmd.RunWebhookServer(GroupName,
&customDNSProviderSolver{},
&pluralDnsProviderSolver{
Token: os.Getenv("PLURAL_ACCESS_TOKEN"),
Endpoint: os.Getenv("PlURAL_ENDPOINT"),
},
)
}
// customDNSProviderSolver implements the provider-specific logic needed to
// 'present' an ACME challenge TXT record for your own DNS provider.
// To do so, it must implement the `github.com/jetstack/cert-manager/pkg/acme/webhook.Solver`
// interface.
type customDNSProviderSolver struct {
// If a Kubernetes 'clientset' is needed, you must:
// 1. uncomment the additional `client` field in this structure below
// 2. uncomment the "k8s.io/client-go/kubernetes" import at the top of the file
// 3. uncomment the relevant code in the Initialize method below
// 4. ensure your webhook's service account has the required RBAC role
// assigned to it for interacting with the Kubernetes APIs you need.
//client kubernetes.Clientset
type pluralDnsProviderSolver struct {
Token string
Endpoint string
}
// customDNSProviderConfig is a structure that is used to decode into when
// solving a DNS01 challenge.
// This information is provided by cert-manager, and may be a reference to
// additional configuration that's needed to solve the challenge for this
// particular certificate or issuer.
// This typically includes references to Secret resources containing DNS
// provider credentials, in cases where a 'multi-tenant' DNS solver is being
// created.
// If you do *not* require per-issuer or per-certificate configuration to be
// provided to your webhook, you can skip decoding altogether in favour of
// using CLI flags or similar to provide configuration.
// You should not include sensitive information here. If credentials need to
// be used by your provider here, you should reference a Kubernetes Secret
// resource and fetch these credentials using a Kubernetes clientset.
type customDNSProviderConfig struct {
// Change the two fields below according to the format of the configuration
// to be decoded.
// These fields will be set by users in the
// `issuer.spec.acme.dns01.providers.webhook.config` field.
//Email string `json:"email"`
//APIKeySecretRef v1alpha1.SecretKeySelector `json:"apiKeySecretRef"`
type pluralDNSProviderConfig struct {
Cluster string `json:"cluster"`
Provider string `json:"provider"`
}
// Name is used as the name for this DNS solver when referencing it on the ACME
// Issuer resource.
// This should be unique **within the group name**, i.e. you can have two
// solvers configured with the same Name() **so long as they do not co-exist
// within a single webhook deployment**.
// For example, `cloudflare` may be used as the name of a solver.
func (c *customDNSProviderSolver) Name() string {
return "my-custom-solver"
func (c *pluralDnsProviderSolver) Name() string {
return "plural-solver"
}
// Present is responsible for actually presenting the DNS record with the
......@@ -83,17 +53,23 @@ func (c *customDNSProviderSolver) Name() string {
// 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 (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
func (c *pluralDnsProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
cfg, err := loadConfig(ch.Config)
if err != nil {
return err
}
// TODO: do something more useful with the decoded configuration
fmt.Printf("Decoded configuration %v", cfg)
conf := plural.NewConfig(c.Token, c.Endpoint, cfg.Cluster, cfg.Provider)
client := plural.NewClient(conf)
// TODO: add code that sets a record in the DNS provider's console
return nil
_, err = client.CreateRecord(&plural.DnsRecord{
Type: "TXT",
Name: ch.ResolvedFQDN,
Records: []string{ ch.Key },
})
fmt.Printf("attempted to create record for %s", ch.ResolvedFQDN)
return err
}
// CleanUp should delete the relevant TXT record from the DNS provider console.
......@@ -102,9 +78,15 @@ func (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error {
// value provided on the ChallengeRequest should be cleaned up.
// This is in order to facilitate multiple DNS validations for the same domain
// concurrently.
func (c *customDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
// TODO: add code that deletes a record from the DNS provider's console
return nil
func (c *pluralDnsProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
cfg, err := loadConfig(ch.Config)
if err != nil {
return err
}
conf := plural.NewConfig(c.Token, c.Endpoint, cfg.Cluster, cfg.Provider)
client := plural.NewClient(conf)
return client.DeleteRecord(ch.ResolvedFQDN, "TXT")
}
// Initialize will be called when the webhook first starts.
......@@ -116,7 +98,7 @@ func (c *customDNSProviderSolver) CleanUp(ch *v1alpha1.ChallengeRequest) error {
// 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 (c *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
func (c *pluralDnsProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {
///// UNCOMMENT THE BELOW CODE TO MAKE A KUBERNETES CLIENTSET AVAILABLE TO
///// YOUR CUSTOM DNS PROVIDER
......@@ -133,9 +115,9 @@ func (c *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stop
// loadConfig is a small helper function that decodes JSON configuration into
// the typed config struct.
func loadConfig(cfgJSON *extapi.JSON) (customDNSProviderConfig, error) {
cfg := customDNSProviderConfig{}
// handle the 'base case' where no configuration has been provided
func loadConfig(cfgJSON *extapi.JSON) (pluralDNSProviderConfig, error) {
cfg := pluralDNSProviderConfig{}
if cfgJSON == nil {
return cfg, nil
}
......
package plural
import (
"context"
"fmt"
"strings"
"github.com/michaeljguarino/graphql"
)
type Config struct {
Token string
Endpoint string
Cluster string
Provider string
}
type Client struct {
gqlClient *graphql.Client
config *Config
}
type DnsRecord struct {
Type string
Name string
Records []string
}
const DnsRecordFragment = `
fragment DnsRecord on DnsRecord {
type
name
records
}
`
var createDnsRecord = fmt.Sprintf(`
mutation Create($cluster: String!, $provider: Provider!, $attributes: DnsRecordAttributes!) {
createDnsRecord(cluster: $cluster, provider: $provider, attributes: $attributes) {
...DnsRecord
}
}
%s
`, DnsRecordFragment)
var deleteDnsRecord = fmt.Sprintf(`
mutation Delete($name: String!, $type: DnsRecordType!) {
deleteDnsRecord(name: $name, type: $type) {
...DnsRecord
}
}
%s
`, DnsRecordFragment)
func NewConfig(token, endpoint, cluster, provider string) *Config {
return &Config{
Token: token,
Endpoint: endpoint,
Cluster: cluster,
Provider: provider,
}
}
func NewClient(conf *Config) *Client {
base := conf.BaseUrl()
return &Client{graphql.NewClient(base + "/gql"), conf}
}
func (c *Config) BaseUrl() string {
host := "https://app.plural.sh"
if (c.Endpoint != "") {
host = fmt.Sprintf("https://%s", c.Endpoint)
}
return host
}
func (client *Client) Build(doc string) *graphql.Request {
req := graphql.NewRequest(doc)
req.Header.Set("Authorization", "Bearer "+client.config.Token)
return req
}
func (client *Client) Run(req *graphql.Request, resp interface{}) error {
return client.gqlClient.Run(context.Background(), req, &resp)
}
func (client *Client) CreateRecord(record *DnsRecord) (result *DnsRecord, err error) {
var resp struct {
CreateDnsRecord *DnsRecord
}
req := client.Build(createDnsRecord)
req.Var("cluster", client.config.Cluster)
req.Var("provider", strings.ToUpper(client.config.Provider))
req.Var("attributes", record)
err = client.Run(req, &resp)
result = resp.CreateDnsRecord
return
}
func (client *Client) DeleteRecord(name, ttype string) error {
var resp struct {
DeleteDnsRecord *DnsRecord
}
req := client.Build(deleteDnsRecord)
req.Var("type", ttype)
req.Var("name", name)
return client.Run(req, &resp)
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment