/
handler.go
188 lines (158 loc) · 4.54 KB
/
handler.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
package http
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-logr/logr"
"github.com/google/wire"
"github.com/tommy351/pullup/internal/httputil"
"github.com/tommy351/pullup/internal/webhook/hookutil"
"github.com/tommy351/pullup/pkg/apis/pullup/v1beta1"
corev1 "k8s.io/api/core/v1"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/validation"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// +kubebuilder:rbac:groups=pullup.dev,resources=httpwebhooks,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
// HandlerSet provides a handler.
// nolint: gochecknoglobals
var HandlerSet = wire.NewSet(
wire.Struct(new(Handler), "*"),
)
type Body struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Action string `json:"action"`
Data extv1.JSON `json:"data"`
}
type Handler struct {
Client client.Client
TriggerHandler hookutil.TriggerHandler
}
func (h *Handler) parseBody(r *http.Request) (*Body, error) {
logger := logr.FromContextOrDiscard(r.Context())
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
return nil, httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: []httputil.Error{
{Description: `Content type must be "application/json"`},
},
}
}
var body Body
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
logger.Error(err, "invalid json")
return nil, httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: []httputil.Error{
{Description: "Invalid JSON"},
},
}
}
if e := validation.ValidateNamespaceName(body.Namespace, false); len(e) > 0 {
return nil, httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: httputil.NewValidationErrors("namespace", e),
}
}
if e := validation.NameIsDNSSubdomain(body.Name, false); len(e) > 0 {
return nil, httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: httputil.NewValidationErrors("name", e),
}
}
if !v1beta1.IsActionValid(body.Action) {
return nil, httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: []httputil.Error{
{Description: "Invalid action", Field: "action"},
},
}
}
return &body, nil
}
func (h *Handler) validateSecretToken(r *http.Request, hook *v1beta1.HTTPWebhook) error {
if hook.Spec.SecretToken == nil || hook.Spec.SecretToken.SecretKeyRef == nil {
return nil
}
header := r.Header.Get("Pullup-Webhook-Secret")
ref := hook.Spec.SecretToken.SecretKeyRef
secret := new(corev1.Secret)
secretName := types.NamespacedName{
Namespace: hook.Namespace,
Name: ref.Name,
}
if err := h.Client.Get(r.Context(), secretName, secret); err != nil {
if kerrors.IsNotFound(err) {
return httputil.Response{
StatusCode: http.StatusForbidden,
Errors: []httputil.Error{
{Description: "Secret not found"},
},
}
}
return fmt.Errorf("failed to get secret: %w", err)
}
value, ok := secret.Data[ref.Key]
if !ok {
return httputil.Response{
StatusCode: http.StatusForbidden,
Errors: []httputil.Error{
{Description: "Key does not contain in the secret"},
},
}
}
if header != string(value) {
return httputil.Response{
StatusCode: http.StatusForbidden,
Errors: []httputil.Error{
{Description: "Secret mismatch"},
},
}
}
return nil
}
func (h *Handler) Handle(w http.ResponseWriter, r *http.Request) error {
body, err := h.parseBody(r)
if err != nil {
return err
}
hook := new(v1beta1.HTTPWebhook)
err = h.Client.Get(r.Context(), types.NamespacedName{
Namespace: body.Namespace,
Name: body.Name,
}, hook)
if err != nil {
if kerrors.IsNotFound(err) {
return httputil.Response{
StatusCode: http.StatusBadRequest,
Errors: []httputil.Error{
{Description: "HTTPWebhook not found"},
},
}
}
return fmt.Errorf("failed to get HTTPWebhook: %w", err)
}
if err := h.validateSecretToken(r, hook); err != nil {
return err
}
data, err := hookutil.ValidateJSONSchema(hook.Spec.Schema, &body.Data)
if err != nil {
return fmt.Errorf("validate failed: %w", err)
}
options := &hookutil.TriggerOptions{
Source: hook,
Triggers: hook.Spec.Triggers,
DefaultAction: body.Action,
Action: hook.Spec.Action,
Event: data,
}
if err := h.TriggerHandler.Handle(r.Context(), options); err != nil {
return fmt.Errorf("trigger failed: %w", err)
}
return httputil.JSON(w, http.StatusOK, &httputil.Response{})
}