generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
transport.go
226 lines (194 loc) · 5.95 KB
/
transport.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
// SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package ancla
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/spf13/cast"
"github.com/xmidt-org/bascule/basculechecks"
"github.com/xmidt-org/httpaux/erraux"
"go.uber.org/zap"
"github.com/xmidt-org/bascule"
)
var (
errFailedWebhookUnmarshal = errors.New("failed to JSON unmarshal webhook")
errAuthIsNotOfTypeBasicOrJWT = errors.New("auth is not of type Basic of JWT")
errGettingPartnerIDs = errors.New("unable to retrieve PartnerIDs")
errAuthNotPresent = errors.New("auth not present")
errAuthTokenIsNil = errors.New("auth token is nil")
errPartnerIDsDoNotExist = errors.New("partnerIDs do not exist")
DefaultBasicPartnerIDsHeader = "X-Xmidt-Partner-Ids"
jwtstr = "jwt"
basicstr = "basic"
)
const (
contentTypeHeader string = "Content-Type"
jsonContentType string = "application/json"
)
type transportConfig struct {
now func() time.Time
v Validator
basicPartnerIDsHeader string
disablePartnerIDs bool
}
type addWebhookRequest struct {
owner string
internalWebook InternalWebhook
}
func encodeGetAllWebhooksResponse(ctx context.Context, rw http.ResponseWriter, response interface{}) error {
iws := response.([]InternalWebhook)
webhooks := InternalWebhooksToWebhooks(iws)
if webhooks == nil {
// prefer JSON output to be "[]" instead of "<nil>"
webhooks = []Webhook{}
}
obfuscateSecrets(webhooks)
encodedWebhooks, err := json.Marshal(&webhooks)
if err != nil {
return err
}
rw.Header().Set(contentTypeHeader, jsonContentType)
_, err = rw.Write(encodedWebhooks)
return err
}
func addWebhookRequestDecoder(config transportConfig) kithttp.DecodeRequestFunc {
wv := webhookValidator{
now: config.now,
}
if config.basicPartnerIDsHeader == "" {
config.basicPartnerIDsHeader = DefaultBasicPartnerIDsHeader
}
// if no validators are given, we accept anything.
if config.v == nil {
config.v = AlwaysValid()
}
return func(c context.Context, r *http.Request) (request interface{}, err error) {
requestPayload, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var wr WebhookRegistration
err = json.Unmarshal(requestPayload, &wr)
if err != nil {
var e *json.UnmarshalTypeError
if errors.As(err, &e) {
return nil, &erraux.Error{Err: fmt.Errorf("%w: %v must be of type %v", errFailedWebhookUnmarshal, e.Field, e.Type), Code: http.StatusBadRequest}
}
return nil, &erraux.Error{Err: fmt.Errorf("%w: %v", errFailedWebhookUnmarshal, err), Code: http.StatusBadRequest}
}
webhook := wr.ToWebhook()
err = config.v.Validate(webhook)
if err != nil {
return nil, &erraux.Error{Err: err, Message: "failed webhook validation", Code: http.StatusBadRequest}
}
wv.setWebhookDefaults(&webhook, r.RemoteAddr)
var partners []string
partners, err = extractPartnerIDs(config, c, r)
if err != nil && !config.disablePartnerIDs {
return nil, &erraux.Error{Err: err, Message: "failed getting partnerIDs", Code: http.StatusBadRequest}
}
return &addWebhookRequest{
owner: getOwner(r.Context()),
internalWebook: InternalWebhook{
Webhook: webhook,
PartnerIDs: partners,
},
}, nil
}
}
func extractPartnerIDs(config transportConfig, c context.Context, r *http.Request) ([]string, error) {
auth, present := bascule.FromContext(c)
if !present {
return nil, errAuthNotPresent
}
if auth.Token == nil {
return nil, errAuthTokenIsNil
}
var partners []string
switch auth.Token.Type() {
case basicstr:
authHeader := r.Header[config.basicPartnerIDsHeader]
for _, value := range authHeader {
fields := strings.Split(value, ",")
for i := 0; i < len(fields); i++ {
fields[i] = strings.TrimSpace(fields[i])
}
partners = append(partners, fields...)
}
return partners, nil
case jwtstr:
authToken := auth.Token
partnersInterface, attrExist := bascule.GetNestedAttribute(authToken.Attributes(), basculechecks.PartnerKeys()...)
if !attrExist {
return nil, errPartnerIDsDoNotExist
}
vals, err := cast.ToStringSliceE(partnersInterface)
if err != nil {
return nil, fmt.Errorf("%w: %v", errGettingPartnerIDs, err)
}
partners = vals
return partners, nil
}
return nil, errAuthIsNotOfTypeBasicOrJWT
}
func encodeAddWebhookResponse(ctx context.Context, rw http.ResponseWriter, _ interface{}) error {
rw.Header().Set(contentTypeHeader, jsonContentType)
rw.Write([]byte(`{"message": "Success"}`))
return nil
}
func getOwner(ctx context.Context) string {
auth, ok := bascule.FromContext(ctx)
if !ok {
return ""
}
switch auth.Token.Type() {
case jwtstr, basicstr:
return auth.Token.Principal()
}
return ""
}
func obfuscateSecrets(webhooks []Webhook) {
for i := range webhooks {
webhooks[i].Config.Secret = "<obfuscated>"
}
}
type webhookValidator struct {
now func() time.Time
}
func (wv webhookValidator) setWebhookDefaults(webhook *Webhook, requestOriginHost string) {
if len(webhook.Matcher.DeviceID) == 0 {
webhook.Matcher.DeviceID = []string{".*"} // match anything
}
if webhook.Until.IsZero() {
webhook.Until = wv.now().Add(webhook.Duration)
}
if requestOriginHost != "" {
webhook.Address = requestOriginHost
}
}
func errorEncoder(getLogger func(context.Context) *zap.Logger) kithttp.ErrorEncoder {
return func(ctx context.Context, err error, w http.ResponseWriter) {
w.Header().Set(contentTypeHeader, jsonContentType)
code := http.StatusInternalServerError
var sc kithttp.StatusCoder
if errors.As(err, &sc) {
code = sc.StatusCode()
}
logger := getLogger(ctx)
if logger != nil && code != http.StatusNotFound {
logger.Error("sending non-200, non-404 response", zap.Int("code", code), zap.Error(err))
}
w.WriteHeader(code)
json.NewEncoder(w).Encode(
map[string]interface{}{
"message": err.Error(),
})
}
}