Skip to content

Commit 91375c7

Browse files
committed
feat: inject bundle data into configmap
Signed-off-by: Erik Godding Boye <[email protected]>
1 parent 12e7368 commit 91375c7

File tree

3 files changed

+291
-0
lines changed

3 files changed

+291
-0
lines changed

pkg/bundle/inject/controller.go

+111
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
Copyright 2021 The cert-manager Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package inject
18+
19+
import (
20+
"context"
21+
"crypto/sha256"
22+
"fmt"
23+
24+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25+
v1 "k8s.io/client-go/applyconfigurations/core/v1"
26+
ctrl "sigs.k8s.io/controller-runtime"
27+
"sigs.k8s.io/controller-runtime/pkg/builder"
28+
"sigs.k8s.io/controller-runtime/pkg/client"
29+
"sigs.k8s.io/controller-runtime/pkg/predicate"
30+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
31+
32+
"github.com/cert-manager/trust-manager/pkg/apis/trust/v1alpha1"
33+
"github.com/cert-manager/trust-manager/pkg/bundle/internal/ssa_client"
34+
)
35+
36+
const (
37+
BundleInjectLabelKey = "trust-manager.io/inject-bundle"
38+
39+
fieldManager = "trust-manager-injector"
40+
)
41+
42+
var configMap = &metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ConfigMap"}}
43+
44+
type Injector struct {
45+
client.Client
46+
}
47+
48+
func (i *Injector) SetupWithManager(mgr ctrl.Manager) error {
49+
return ctrl.NewControllerManagedBy(mgr).
50+
Named("configmap-injector").
51+
For(configMap,
52+
builder.WithPredicates(
53+
hasLabel(BundleInjectLabelKey),
54+
)).
55+
Complete(i)
56+
}
57+
58+
func (i *Injector) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
59+
data := map[string]string{"ca.crt": "bundle data"}
60+
dataHash := fmt.Sprintf("%x", sha256.Sum256([]byte("bundle data hash")))
61+
62+
applyConfig := v1.ConfigMap(request.Name, request.Namespace).
63+
WithAnnotations(map[string]string{v1alpha1.BundleHashAnnotationKey: dataHash}).
64+
WithData(data)
65+
66+
return reconcile.Result{}, patchConfigMap(ctx, i.Client, applyConfig)
67+
}
68+
69+
type Cleaner struct {
70+
client.Client
71+
}
72+
73+
func (c *Cleaner) SetupWithManager(mgr ctrl.Manager) error {
74+
return ctrl.NewControllerManagedBy(mgr).
75+
Named("configmap-injector-cleaner").
76+
For(configMap,
77+
builder.WithPredicates(
78+
hasAnnotation(v1alpha1.BundleHashAnnotationKey),
79+
predicate.Not(hasLabel(BundleInjectLabelKey)),
80+
)).
81+
Complete(c)
82+
}
83+
84+
func (c *Cleaner) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
85+
applyConfig := v1.ConfigMap(request.Name, request.Namespace)
86+
87+
return reconcile.Result{}, patchConfigMap(ctx, c.Client, applyConfig)
88+
}
89+
90+
func patchConfigMap(ctx context.Context, c client.Client, applyConfig *v1.ConfigMapApplyConfiguration) error {
91+
configMap, patch, err := ssa_client.GenerateConfigMapPatch(applyConfig)
92+
if err != nil {
93+
return err
94+
}
95+
96+
return c.Patch(ctx, configMap, patch, client.FieldOwner(fieldManager), client.ForceOwnership)
97+
}
98+
99+
func hasLabel(key string) predicate.Predicate {
100+
return predicate.NewPredicateFuncs(func(obj client.Object) bool {
101+
_, ok := obj.GetLabels()[key]
102+
return ok
103+
})
104+
}
105+
106+
func hasAnnotation(key string) predicate.Predicate {
107+
return predicate.NewPredicateFuncs(func(obj client.Object) bool {
108+
_, ok := obj.GetAnnotations()[key]
109+
return ok
110+
})
111+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
Copyright 2021 The cert-manager Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package inject
18+
19+
import (
20+
"context"
21+
22+
corev1 "k8s.io/api/core/v1"
23+
"sigs.k8s.io/controller-runtime/pkg/envtest/komega"
24+
25+
"github.com/cert-manager/trust-manager/pkg/bundle/inject"
26+
27+
. "github.com/onsi/ginkgo/v2"
28+
. "github.com/onsi/gomega"
29+
)
30+
31+
var _ = Describe("Injector", func() {
32+
var namespace string
33+
34+
BeforeEach(func() {
35+
ctx = context.Background()
36+
37+
ns := &corev1.Namespace{}
38+
ns.GenerateName = "inject-"
39+
Expect(k8sClient.Create(ctx, ns)).To(Succeed())
40+
namespace = ns.Name
41+
})
42+
43+
It("should inject bundle data when ConfigMap labeled", func() {
44+
cm := &corev1.ConfigMap{}
45+
cm.GenerateName = "cm-"
46+
cm.Namespace = namespace
47+
cm.Labels = map[string]string{
48+
inject.BundleInjectLabelKey: "foo-bundle",
49+
"app": "my-app",
50+
}
51+
cm.Data = map[string]string{
52+
"tls.crt": "bar",
53+
"tls.key": "baz",
54+
}
55+
Expect(k8sClient.Create(ctx, cm)).To(Succeed())
56+
57+
// Wait for ConfigMap to be processed by controller
58+
Eventually(komega.Object(cm)).Should(HaveField("Data", HaveKeyWithValue("ca.crt", "bundle data")))
59+
Expect(cm.Labels).To(HaveKeyWithValue("app", "my-app"))
60+
61+
By("removing label from ConfigMap, it should remove bundle data", func() {
62+
Expect(komega.Update(cm, func() {
63+
delete(cm.Labels, inject.BundleInjectLabelKey)
64+
})()).To(Succeed())
65+
66+
// Wait for ConfigMap to be processed by controller
67+
Eventually(komega.Object(cm)).Should(HaveField("Data", Not(HaveKey("ca.crt"))))
68+
Expect(cm.Labels).To(HaveKeyWithValue("app", "my-app"))
69+
Expect(cm.Data).To(Equal(map[string]string{
70+
"tls.crt": "bar",
71+
"tls.key": "baz",
72+
}))
73+
})
74+
})
75+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
Copyright 2021 The cert-manager Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package inject
18+
19+
import (
20+
"context"
21+
"testing"
22+
23+
"k8s.io/client-go/kubernetes/scheme"
24+
"k8s.io/client-go/rest"
25+
ctrl "sigs.k8s.io/controller-runtime"
26+
"sigs.k8s.io/controller-runtime/pkg/client"
27+
"sigs.k8s.io/controller-runtime/pkg/envtest"
28+
"sigs.k8s.io/controller-runtime/pkg/envtest/komega"
29+
logf "sigs.k8s.io/controller-runtime/pkg/log"
30+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
31+
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
32+
33+
"github.com/cert-manager/trust-manager/pkg/bundle/inject"
34+
35+
. "github.com/onsi/ginkgo/v2"
36+
. "github.com/onsi/gomega"
37+
)
38+
39+
var (
40+
cfg *rest.Config
41+
k8sClient client.Client
42+
testEnv *envtest.Environment
43+
ctx context.Context
44+
cancel context.CancelFunc
45+
)
46+
47+
func TestAPIs(t *testing.T) {
48+
RegisterFailHandler(Fail)
49+
50+
RunSpecs(t, "Controller Suite")
51+
}
52+
53+
var _ = BeforeSuite(func() {
54+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
55+
56+
ctx, cancel = context.WithCancel(context.TODO())
57+
58+
By("bootstrapping test environment")
59+
testEnv = &envtest.Environment{}
60+
61+
var err error
62+
// cfg is defined in this file globally.
63+
cfg, err = testEnv.Start()
64+
Expect(err).NotTo(HaveOccurred())
65+
Expect(cfg).NotTo(BeNil())
66+
67+
k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
68+
Expect(err).NotTo(HaveOccurred())
69+
Expect(k8sClient).NotTo(BeNil())
70+
komega.SetClient(k8sClient)
71+
72+
k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{
73+
Client: client.Options{Cache: &client.CacheOptions{Unstructured: true}},
74+
Scheme: scheme.Scheme,
75+
Metrics: server.Options{
76+
// Disable metrics server to avoid port conflict
77+
BindAddress: "0",
78+
},
79+
})
80+
Expect(err).NotTo(HaveOccurred())
81+
82+
injector := &inject.Injector{
83+
Client: k8sManager.GetClient(),
84+
}
85+
Expect(injector.SetupWithManager(k8sManager)).To(Succeed())
86+
cleaner := &inject.Cleaner{
87+
Client: k8sManager.GetClient(),
88+
}
89+
Expect(cleaner.SetupWithManager(k8sManager)).To(Succeed())
90+
91+
go func() {
92+
defer GinkgoRecover()
93+
var ctrlCtx context.Context
94+
ctrlCtx, cancel = context.WithCancel(ctrl.SetupSignalHandler())
95+
Expect(k8sManager.Start(ctrlCtx)).To(Succeed())
96+
}()
97+
})
98+
99+
var _ = AfterSuite(func() {
100+
cancel()
101+
102+
By("tearing down the test environment")
103+
err := testEnv.Stop()
104+
Expect(err).NotTo(HaveOccurred())
105+
})

0 commit comments

Comments
 (0)