This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
webhook.go
193 lines (161 loc) · 5.32 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package webhook
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/sirupsen/logrus"
kwhhttp "github.com/slok/kubewebhook/v2/pkg/http"
kwhlog "github.com/slok/kubewebhook/v2/pkg/log"
kwhlogrus "github.com/slok/kubewebhook/v2/pkg/log/logrus"
kwhmodel "github.com/slok/kubewebhook/v2/pkg/model"
kwhmutating "github.com/slok/kubewebhook/v2/pkg/webhook/mutating"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// binVolumeName is the name of the volume where the SecretHub CLI binary is stored.
binVolumeName = "secrethub-bin"
// binVolumeMountPath is the mount path where the SecretHub CLI binary can be found.
binVolumeMountPath = "/secrethub/bin/"
)
// binVolume is the shared, in-memory volume where the SecretHub CLI binary lives.
var binVolume = corev1.Volume{
Name: binVolumeName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{
Medium: corev1.StorageMediumMemory,
},
},
}
// binVolumeMount is the shared volume mount where the SecretHub CLI binary lives.
var binVolumeMount = corev1.VolumeMount{
Name: binVolumeName,
MountPath: binVolumeMountPath,
ReadOnly: true,
}
// SecretHubMutator is a mutator.
type SecretHubMutator struct {
logger kwhlog.Logger
}
// Mutate implements MutateFunc and provides the top-level entrypoint for object
// mutation.
func (m *SecretHubMutator) Mutate(ctx context.Context, _ *kwhmodel.AdmissionReview, obj metav1.Object) (*kwhmutating.MutatorResult, error) {
m.logger.Infof("calling mutate")
pod, ok := obj.(*corev1.Pod)
if !ok {
return &kwhmutating.MutatorResult{}, nil
}
containersStr, enabled := pod.Annotations["secrethub.io/mutate"]
if !enabled {
m.logger.Debugf("Skipping pod %s because it is not annotated with secrethub", pod.Name)
return &kwhmutating.MutatorResult{}, nil
}
containers := map[string]struct{}{}
for _, container := range strings.Split(containersStr, ",") {
containers[container] = struct{}{}
}
version, ok := pod.Annotations["secrethub.io/version"]
if !ok {
version = "latest"
}
mutated := false
for i, c := range pod.Spec.InitContainers {
_, mutate := containers[c.Name]
if !mutate {
continue
}
c, didMutate, err := m.mutateContainer(ctx, &c)
if err != nil {
return &kwhmutating.MutatorResult{}, err
}
if didMutate {
mutated = true
pod.Spec.InitContainers[i] = *c
}
}
for i, c := range pod.Spec.Containers {
_, mutate := containers[c.Name]
if !mutate {
continue
}
c, didMutate, err := m.mutateContainer(ctx, &c)
if err != nil {
return &kwhmutating.MutatorResult{}, err
}
if didMutate {
mutated = true
pod.Spec.Containers[i] = *c
}
}
// binInitContainer is the container that pulls the SecretHub CLI
// into a shared volume mount.
var binInitContainer = corev1.Container{
Name: "copy-secrethub-bin",
Image: "secrethub/cli" + ":" + version,
ImagePullPolicy: corev1.PullIfNotPresent,
Command: []string{"sh", "-c",
fmt.Sprintf("cp /usr/bin/secrethub %s", binVolumeMountPath)},
VolumeMounts: []corev1.VolumeMount{
{
Name: binVolumeName,
MountPath: binVolumeMountPath,
},
},
}
// If any of the containers requested SecretHub secrets, mount the shared volume
// and ensure the SecretHub CLI is available via an init container.
if mutated {
pod.Spec.Volumes = append(pod.Spec.Volumes, binVolume)
pod.Spec.InitContainers = append([]corev1.Container{binInitContainer},
pod.Spec.InitContainers...)
}
return &kwhmutating.MutatorResult{MutatedObject: obj}, nil
}
// mutateContainer mutates the given container, updating the volume mounts and
// command if it contains SecretHub references.
func (m *SecretHubMutator) mutateContainer(_ context.Context, c *corev1.Container) (*corev1.Container, bool, error) {
// This webhook only attaches SecretHub when a command is specified in the podspec.
//
// Note that the command should be defined in the podspec. The ENTRYPOINT or
// CMD in the Dockerfile does not suffice as this is not visible to the webhook.
if len(c.Command) == 0 {
return c, false, fmt.Errorf("not attaching SecretHub to the container %s: the podspec does not define a command", c.Name)
}
// Prepend the command with secrethub run --
c.Command = append([]string{binVolumeMountPath + "secrethub", "run", "--"}, c.Command...)
// Add the shared volume mount
c.VolumeMounts = append(c.VolumeMounts, binVolumeMount)
// Set app info
c.Env = append(c.Env, appInfo...)
return c, true, nil
}
// Handler is the http.Handler that responds to webhooks
func Handler() http.Handler {
logrusLogEntry := logrus.NewEntry(logrus.New())
logrusLogEntry.Logger.SetLevel(logrus.DebugLevel)
logger := kwhlogrus.NewLogrus(logrusLogEntry)
mutator := &SecretHubMutator{logger: logger}
mcfg := kwhmutating.WebhookConfig{
ID: "SecretHubMutator",
Obj: &corev1.Pod{},
Mutator: mutator,
Logger: logger,
}
// Create the wrapping webhook
wh, err := kwhmutating.NewWebhook(mcfg)
if err != nil {
logger.Errorf("error creating webhook: %s", err)
os.Exit(1)
}
// Get the handler for our webhook.
whhandler, err := kwhhttp.HandlerFor(kwhhttp.HandlerConfig{Webhook: wh, Logger: logger})
if err != nil {
logger.Errorf("error creating webhook handler: %s", err)
os.Exit(1)
}
return whhandler
}
// F is the exported webhook for the function to bind.
var F = Handler().ServeHTTP