forked from nmasse-itix/gitea-tekton-interceptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
295 lines (253 loc) · 8.41 KB
/
main.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
Copyright 2020 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"encoding/json"
"log"
"net"
"net/http"
"time"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"hash"
"google.golang.org/grpc/codes"
"go.uber.org/zap"
"k8s.io/client-go/rest"
secretInformer "knative.dev/pkg/client/injection/kube/informers/core/v1/secret"
"knative.dev/pkg/injection"
"knative.dev/pkg/logging"
"knative.dev/pkg/signals"
triggersv1 "github.com/tektoncd/triggers/pkg/apis/triggers/v1beta1"
corev1lister "k8s.io/client-go/listers/core/v1"
"github.com/tektoncd/triggers/pkg/interceptors"
)
const (
// Port is the port that the port that interceptor service listens on
Port = 8080
readTimeout = 5 * time.Second
writeTimeout = 20 * time.Second
idleTimeout = 60 * time.Second
)
func main() {
// set up signals so we handle the first shutdown signal gracefully
ctx := signals.NewContext()
clusterConfig, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("Failed to build config: %v", err)
}
ctx, startInformer := injection.EnableInjectionOrDie(ctx, clusterConfig)
zap, err := zap.NewProduction()
if err != nil {
log.Fatalf("failed to initialize logger: %s", err)
}
logger := zap.Sugar()
ctx = logging.WithLogger(ctx, logger)
defer func() {
if err := logger.Sync(); err != nil {
log.Fatalf("failed to sync the logger: %s", err)
}
}()
secretLister := secretInformer.Get(ctx).Lister()
service := NewGiteaInterceptor(secretLister, logger)
startInformer()
mux := http.NewServeMux()
mux.Handle("/", service)
mux.HandleFunc("/ready", readinessHandler)
srv := &http.Server{
Addr: fmt.Sprintf(":%d", Port),
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
Handler: mux,
}
logger.Infof("Listen and serve on port %d", Port)
if err := srv.ListenAndServe(); err != nil {
logger.Fatalf("failed to start interceptors service: %v", err)
}
}
func readinessHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (gi *GiteaInterceptor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, err := gi.executeInterceptor(r)
if err != nil {
switch e := err.(type) {
case Error:
gi.Logger.Infof("HTTP %d - %s", e.Status(), e)
http.Error(w, e.Error(), e.Status())
default:
gi.Logger.Errorf("Non Status Error: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
w.Header().Add("Content-Type", "application/json")
if _, err := w.Write(b); err != nil {
gi.Logger.Errorf("failed to write response: %s", err)
}
}
// Error represents a handler error. It provides methods for a HTTP status
// code and embeds the built-in error interface.
type Error interface {
error
Status() int
}
// HTTPError represents an error with an associated HTTP status code.
type HTTPError struct {
Code int
Err error
}
// Allows HTTPError to satisfy the error interface.
func (se HTTPError) Error() string {
return se.Err.Error()
}
// Returns our HTTP status code.
func (se HTTPError) Status() int {
return se.Code
}
func badRequest(err error) HTTPError {
return HTTPError{Code: http.StatusBadRequest, Err: err}
}
func internal(err error) HTTPError {
return HTTPError{Code: http.StatusInternalServerError, Err: err}
}
func (gi *GiteaInterceptor) executeInterceptor(r *http.Request) ([]byte, error) {
// Create a context
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
var body bytes.Buffer
defer r.Body.Close()
if _, err := io.Copy(&body, r.Body); err != nil {
return nil, internal(fmt.Errorf("failed to read body: %w", err))
}
var ireq triggersv1.InterceptorRequest
if err := json.Unmarshal(body.Bytes(), &ireq); err != nil {
return nil, badRequest(fmt.Errorf("failed to parse body as InterceptorRequest: %w", err))
}
gi.Logger.Debugf("Interceptor Request is: %+v", ireq)
iresp := gi.Process(ctx, &ireq)
gi.Logger.Infof("Interceptor response is: %+v", iresp)
respBytes, err := json.Marshal(iresp)
if err != nil {
return nil, internal(err)
}
return respBytes, nil
}
// ErrInvalidContentType is returned when the content-type is not a JSON body.
var ErrInvalidContentType = errors.New("form parameter encoding not supported, please change the hook to send JSON payloads")
type GiteaInterceptor struct {
SecretLister corev1lister.SecretLister
Logger *zap.SugaredLogger
}
func NewGiteaInterceptor(s corev1lister.SecretLister, l *zap.SugaredLogger) *GiteaInterceptor {
return &GiteaInterceptor{
SecretLister: s,
Logger: l,
}
}
func (w *GiteaInterceptor) Process(ctx context.Context, r *triggersv1.InterceptorRequest) *triggersv1.InterceptorResponse {
headers := interceptors.Canonical(r.Header)
if v := headers.Get("Content-Type"); v == "application/x-www-form-urlencoded" {
return interceptors.Fail(codes.InvalidArgument, ErrInvalidContentType.Error())
}
p := triggersv1.GitHubInterceptor{}
if err := interceptors.UnmarshalParams(r.InterceptorParams, &p); err != nil {
return interceptors.Failf(codes.InvalidArgument, "failed to parse interceptor params: %v", err)
}
// Check if the event type is in the allow-list
if p.EventTypes != nil {
actualEvent := headers.Get("X-Gitea-Event")
isAllowed := false
for _, allowedEvent := range p.EventTypes {
if actualEvent == allowedEvent {
isAllowed = true
break
}
}
if !isAllowed {
return interceptors.Failf(codes.FailedPrecondition, "event type %s is not allowed", actualEvent)
}
}
// Next validate secrets
if p.SecretRef != nil {
// Check the secret to see if it is empty
if p.SecretRef.SecretKey == "" {
return interceptors.Fail(codes.FailedPrecondition, "gitea interceptor secretRef.secretKey is empty")
}
header := headers.Get("X-Gitea-Signature")
if header == "" {
return interceptors.Fail(codes.FailedPrecondition, "no X-Gitea-Signature header set")
}
ns, _ := triggersv1.ParseTriggerID(r.Context.TriggerID)
secret, err := w.SecretLister.Secrets(ns).Get(p.SecretRef.SecretName)
if err != nil {
return interceptors.Failf(codes.FailedPrecondition, "error getting secret: %v", err)
}
secretToken := secret.Data[p.SecretRef.SecretKey]
if err := validateSignature(header, []byte(r.Body), secretToken); err != nil {
return interceptors.Fail(codes.FailedPrecondition, err.Error())
}
}
return &triggersv1.InterceptorResponse{
Continue: true,
}
}
// genMAC generates the HMAC signature for a message provided the secret key
// and hashFunc.
func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte {
mac := hmac.New(hashFunc, key)
mac.Write(message)
return mac.Sum(nil)
}
// checkMAC reports whether messageMAC is a valid HMAC tag for message.
func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool {
expectedMAC := genMAC(message, key, hashFunc)
return hmac.Equal(messageMAC, expectedMAC)
}
// messageMAC returns the hex-decoded HMAC tag from the signature and its
// corresponding hash function.
func messageMAC(signature string) ([]byte, func() hash.Hash, error) {
if signature == "" {
return nil, nil, errors.New("missing signature")
}
var hashFunc func() hash.Hash
hashFunc = sha256.New
buf, err := hex.DecodeString(signature)
if err != nil {
return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err)
}
return buf, hashFunc, nil
}
// validateSignature validates the signature for the given payload.
// signature is the gitea hash signature delivered in the X-Gitea-Signature header.
// payload is the JSON payload sent by gitea Webhooks.
// secretToken is the gitea Webhook secret token.
//
func validateSignature(signature string, payload, secretToken []byte) error {
messageMAC, hashFunc, err := messageMAC(signature)
if err != nil {
return err
}
if !checkMAC(payload, messageMAC, secretToken, hashFunc) {
return errors.New("payload signature check failed")
}
return nil
}