File size: 9,723 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package graphqlapp

import (
	context "context"
	"database/sql"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/99designs/gqlgen/graphql"
	"github.com/99designs/gqlgen/graphql/errcode"
	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/handler/apollotracing"
	"github.com/99designs/gqlgen/graphql/handler/extension"
	"github.com/99designs/gqlgen/graphql/handler/lru"
	"github.com/99designs/gqlgen/graphql/handler/transport"
	"github.com/pkg/errors"
	"github.com/target/goalert/alert"
	"github.com/target/goalert/alert/alertlog"
	"github.com/target/goalert/alert/alertmetrics"
	"github.com/target/goalert/apikey"
	"github.com/target/goalert/auth"
	"github.com/target/goalert/auth/authlink"
	"github.com/target/goalert/auth/basic"
	"github.com/target/goalert/calsub"
	"github.com/target/goalert/config"
	"github.com/target/goalert/escalation"
	"github.com/target/goalert/event"
	"github.com/target/goalert/graphql2"
	"github.com/target/goalert/heartbeat"
	"github.com/target/goalert/integrationkey"
	"github.com/target/goalert/keyring"
	"github.com/target/goalert/label"
	"github.com/target/goalert/limit"
	"github.com/target/goalert/notice"
	"github.com/target/goalert/notification"
	"github.com/target/goalert/notification/nfydest"
	"github.com/target/goalert/notification/slack"
	"github.com/target/goalert/notification/twilio"
	"github.com/target/goalert/notificationchannel"
	"github.com/target/goalert/oncall"
	"github.com/target/goalert/override"
	"github.com/target/goalert/permission"
	"github.com/target/goalert/schedule"
	"github.com/target/goalert/schedule/rotation"
	"github.com/target/goalert/schedule/rule"
	"github.com/target/goalert/service"
	"github.com/target/goalert/swo"
	"github.com/target/goalert/timezone"
	"github.com/target/goalert/user"
	"github.com/target/goalert/user/contactmethod"
	"github.com/target/goalert/user/favorite"
	"github.com/target/goalert/user/notificationrule"
	"github.com/target/goalert/util/errutil"
	"github.com/target/goalert/util/log"
	"github.com/target/goalert/validation"
	"github.com/vektah/gqlparser/v2/ast"
	"github.com/vektah/gqlparser/v2/gqlerror"
)

type App struct {
	DB                *sql.DB
	AuthBasicStore    *basic.Store
	UserStore         *user.Store
	CMStore           *contactmethod.Store
	NRStore           *notificationrule.Store
	NCStore           *notificationchannel.Store
	AlertStore        *alert.Store
	AlertMetricsStore *alertmetrics.Store
	AlertLogStore     *alertlog.Store
	ServiceStore      *service.Store
	FavoriteStore     *favorite.Store
	PolicyStore       *escalation.Store
	ScheduleStore     *schedule.Store
	CalSubStore       *calsub.Store
	RotationStore     *rotation.Store
	OnCallStore       *oncall.Store
	IntKeyStore       *integrationkey.Store
	LabelStore        *label.Store
	RuleStore         *rule.Store
	OverrideStore     *override.Store
	ConfigStore       *config.Store
	LimitStore        *limit.Store
	SlackStore        *slack.ChannelSender
	HeartbeatStore    *heartbeat.Store
	NoticeStore       *notice.Store
	APIKeyStore       *apikey.Store

	AuthLinkStore *authlink.Store

	NotificationManager *notification.Manager

	AuthHandler *auth.Handler

	NotificationStore *notification.Store
	Twilio            *twilio.Config

	TimeZoneStore *timezone.Store

	EncryptionKeys keyring.Keys

	SWO *swo.Manager

	DestReg  *nfydest.Registry
	EventBus *event.Bus
}

type fieldErr struct {
	FieldName string `json:"fieldName"`
	Message   string `json:"message"`
}

type apolloTracer struct {
	apollotracing.Tracer
	shouldTrace func(context.Context) bool
}

func (a apolloTracer) InterceptField(ctx context.Context, next graphql.Resolver) (res interface{}, err error) {
	if !a.shouldTrace(ctx) {
		return next(ctx)
	}

	return a.Tracer.InterceptField(ctx, next)
}

func (a apolloTracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
	if !a.shouldTrace(ctx) {
		return next(ctx)
	}

	return a.Tracer.InterceptResponse(ctx, next)
}

func isGQLValidation(gqlErr *gqlerror.Error) bool {
	if gqlErr == nil {
		return false
	}

	var numErr *strconv.NumError
	if errors.As(gqlErr, &numErr) {
		return true
	}

	if strings.HasPrefix(gqlErr.Message, "json request body") || strings.HasPrefix(gqlErr.Message, "could not get json request body:") || strings.HasPrefix(gqlErr.Message, "could not read request body:") {
		var body string
		gqlErr.Message, body, _ = strings.Cut(gqlErr.Message, " body:") // remove body
		if !strings.HasPrefix(strings.TrimSpace(body), "{") {
			// Make the error more readable for common JSON errors.
			gqlErr.Message = "json request body could not be decoded: body must be an object, missing '{'"
		}

		return true
	}

	if gqlErr.Extensions == nil {
		return false
	}

	_, ok := gqlErr.Extensions["code"].(graphql2.ErrorCode)
	if ok {
		return true
	}

	code, ok := gqlErr.Extensions["code"].(string)
	if !ok {
		return false
	}

	switch code {
	case errcode.ValidationFailed, errcode.ParseFailed:
		// These are gqlgen validation errors.
		return true
	}

	return false
}

func (a *App) Handler() http.Handler {
	h := handler.New(
		graphql2.NewExecutableSchema(graphql2.Config{
			Resolvers: a,
			Directives: graphql2.DirectiveRoot{
				Experimental: Experimental,
			},
		}),
	)

	h.AddTransport(transport.Websocket{
		KeepAlivePingInterval: 10 * time.Second,
	})
	h.AddTransport(transport.Options{})
	h.AddTransport(transport.GET{})
	h.AddTransport(transport.POST{})
	h.AddTransport(transport.MultipartForm{})
	h.SetQueryCache(lru.New[*ast.QueryDocument](1000))
	h.Use(extension.Introspection{})
	h.Use(extension.AutomaticPersistedQuery{
		Cache: lru.New[string](100),
	})

	type hasTraceKey int
	h.Use(apolloTracer{Tracer: apollotracing.Tracer{}, shouldTrace: func(ctx context.Context) bool {
		enabled, ok := ctx.Value(hasTraceKey(1)).(bool)
		return ok && enabled
	}})

	h.Use(apikey.Middleware{})

	h.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) {
		defer func() {
			err := recover()
			if err != nil {
				panic(err)
			}
		}()
		fieldCtx := graphql.GetFieldContext(ctx)

		start := time.Now()
		res, err = next(ctx)
		errVal := "0"
		if err != nil {
			errVal = "1"
		}
		if fieldCtx.IsMethod {
			metricResolverHist.
				WithLabelValues(fmt.Sprintf("%s.%s", fieldCtx.Object, fieldCtx.Field.Name), errVal).
				Observe(time.Since(start).Seconds())
		}
		if err == nil && fieldCtx.Object == "Mutation" {
			ctx = log.WithFields(ctx, log.Fields{
				"MutationName": fieldCtx.Field.Name,
			})
			log.Logf(ctx, "Mutation.")
		}

		return res, err
	})

	h.Use(&errSkipHandler{})

	h.SetErrorPresenter(func(ctx context.Context, err error) *gqlerror.Error {
		if errors.Is(err, errAlreadySet) {
			// This error just indicates that a field error has already been set on the context
			// it should not be returned to the client.
			return &gqlerror.Error{
				Extensions: map[string]interface{}{
					"skip": true,
				},
			}
		}

		if errors.Is(err, context.Canceled) {
			return &gqlerror.Error{
				Message: "Request canceled.",
			}
		}

		var argErr *nfydest.DestArgError
		if errors.As(err, &argErr) {
			return &gqlerror.Error{
				Message: argErr.Err.Error(),
				Path:    graphql.GetPath(ctx),
				Extensions: map[string]interface{}{
					"code":    graphql2.ErrorCodeInvalidDestFieldValue,
					"fieldID": argErr.FieldID,
				},
			}
		}

		var paramErr *nfydest.ActionParamError
		if errors.As(err, &paramErr) {
			return &gqlerror.Error{
				Message: paramErr.Err.Error(),
				Path:    graphql.GetPath(ctx),
				Extensions: map[string]interface{}{
					"code": graphql2.ErrorCodeInvalidMapFieldValue,
					"key":  paramErr.ParamID,
				},
			}
		}

		err = errutil.MapDBError(err)
		var gqlErr *gqlerror.Error

		isUnsafe, safeErr := errutil.ScrubError(err)
		if !errors.As(err, &gqlErr) {
			gqlErr = &gqlerror.Error{
				Message: safeErr.Error(),
			}
		}

		if isUnsafe && !isGQLValidation(gqlErr) {
			// context.Canceled is caused by normal things like closing a browser tab.
			if !errors.Is(err, context.Canceled) {
				log.Log(ctx, err)
			}
			gqlErr.Message = safeErr.Error()
		}

		var multiFieldErr validation.MultiFieldError
		var singleFieldErr validation.FieldError
		if errors.As(err, &multiFieldErr) {
			errs := make([]fieldErr, len(multiFieldErr.FieldErrors()))
			for i, err := range multiFieldErr.FieldErrors() {
				errs[i].FieldName = err.Field()
				errs[i].Message = err.Reason()
			}
			gqlErr.Message = "Multiple fields failed validation."
			gqlErr.Extensions = map[string]interface{}{
				"isMultiFieldError": true,
				"fieldErrors":       errs,
			}
		} else if errors.As(err, &singleFieldErr) {
			type reasonable interface {
				Reason() string
			}
			msg := singleFieldErr.Error()
			if rs, ok := singleFieldErr.(reasonable); ok {
				msg = rs.Reason()
			}
			gqlErr.Message = msg
			gqlErr.Extensions = map[string]interface{}{
				"fieldName":    singleFieldErr.Field(),
				"isFieldError": true,
			}
		}

		var mapErr graphql2.MapValueError
		if errors.As(err, &mapErr) {
			gqlErr.Message = mapErr.Err.Error()
			gqlErr.Extensions = map[string]interface{}{
				"code": "INVALID_MAP_FIELD_VALUE",
				"key":  mapErr.Key,
			}
		}

		return gqlErr
	})

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()

		// ensure some sort of auth before continuing
		err := permission.LimitCheckAny(ctx)
		if errutil.HTTPError(ctx, w, err) {
			return
		}

		ctx = a.registerLoaders(ctx)
		defer a.closeLoaders(ctx)

		if req.URL.Query().Get("trace") == "1" && permission.Admin(ctx) {
			ctx = context.WithValue(ctx, hasTraceKey(1), true)
		}

		h.ServeHTTP(w, req.WithContext(ctx))
	})
}