-
Notifications
You must be signed in to change notification settings - Fork 153
/
apihandler.go
2299 lines (2013 loc) · 70.2 KB
/
apihandler.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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package apihandler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/buger/jsonparser"
"github.com/dgraph-io/ristretto"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/hashicorp/go-uuid"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/wI2L/jsondiff"
"go.uber.org/zap"
"github.com/wundergraph/graphql-go-tools/pkg/ast"
"github.com/wundergraph/graphql-go-tools/pkg/astparser"
"github.com/wundergraph/graphql-go-tools/pkg/asttransform"
"github.com/wundergraph/graphql-go-tools/pkg/astvalidation"
"github.com/wundergraph/graphql-go-tools/pkg/astvisitor"
"github.com/wundergraph/graphql-go-tools/pkg/engine/datasource/introspection_datasource"
"github.com/wundergraph/graphql-go-tools/pkg/engine/plan"
"github.com/wundergraph/graphql-go-tools/pkg/engine/resolve"
"github.com/wundergraph/graphql-go-tools/pkg/graphql"
"github.com/wundergraph/graphql-go-tools/pkg/lexer/literal"
"github.com/wundergraph/wundergraph/internal/unsafebytes"
"github.com/wundergraph/wundergraph/pkg/authentication"
"github.com/wundergraph/wundergraph/pkg/cacheheaders"
"github.com/wundergraph/wundergraph/pkg/engineconfigloader"
"github.com/wundergraph/wundergraph/pkg/hooks"
"github.com/wundergraph/wundergraph/pkg/inputvariables"
"github.com/wundergraph/wundergraph/pkg/interpolate"
"github.com/wundergraph/wundergraph/pkg/jsonpath"
"github.com/wundergraph/wundergraph/pkg/loadvariable"
"github.com/wundergraph/wundergraph/pkg/logging"
"github.com/wundergraph/wundergraph/pkg/metrics"
"github.com/wundergraph/wundergraph/pkg/operation"
"github.com/wundergraph/wundergraph/pkg/pool"
"github.com/wundergraph/wundergraph/pkg/postresolvetransform"
"github.com/wundergraph/wundergraph/pkg/querystring"
"github.com/wundergraph/wundergraph/pkg/s3uploadclient"
"github.com/wundergraph/wundergraph/pkg/trace"
"github.com/wundergraph/wundergraph/pkg/webhookhandler"
"github.com/wundergraph/wundergraph/pkg/wgpb"
)
const (
WgInternalApiCallHeader = "X-WG-Internal-GraphQL-API"
WgPrefix = "wg_"
WgVariables = WgPrefix + "variables"
WgLiveParam = WgPrefix + "live"
WgJSONPatchParam = WgPrefix + "json_patch"
WgSSEParam = WgPrefix + "sse"
WgSubscribeOnceParam = WgPrefix + "subscribe_once"
WgDeduplicateParam = WgPrefix + "deduplicate"
defaultAuthTimeoutSeconds = 600 // 10 minutes
)
type JSONPatchConfiguration int
const (
JSONPatchConfigurationDisabled = JSONPatchConfiguration(0)
JSONPatchConfigurationEnabled = JSONPatchConfiguration(1)
JSONPatchConfigurationForced = JSONPatchConfiguration(2)
)
func (c JSONPatchConfiguration) IsEnabled() bool {
return c > JSONPatchConfigurationDisabled
}
type WgRequestParams struct {
JSONPatch JSONPatchConfiguration
SSE bool
SubscribeOnce bool
Deduplicate bool
}
func NewWgRequestParams(r *http.Request) WgRequestParams {
q := r.URL.Query()
var JSONPatch JSONPatchConfiguration
if q.Has(WgJSONPatchParam) {
if q.Get(WgJSONPatchParam) == "force" {
JSONPatch = JSONPatchConfigurationForced
} else {
JSONPatch = JSONPatchConfigurationForced
}
}
return WgRequestParams{
JSONPatch: JSONPatch,
SSE: q.Has(WgSSEParam),
SubscribeOnce: q.Has(WgSubscribeOnceParam),
Deduplicate: q.Has(WgDeduplicateParam),
}
}
type Builder struct {
router *mux.Router
loader *engineconfigloader.EngineConfigLoader
api *Api
resolver *resolve.Resolver
pool *pool.Pool
middlewareClient *hooks.Client
definition *ast.Document
log *zap.Logger
planConfig plan.Configuration
insecureCookies bool
forceHttpsRedirects bool
enableIntrospection bool
devMode bool
renameTypeNames []resolve.RenameTypeName
githubAuthDemoClientID string
githubAuthDemoClientSecret string
metrics metrics.Metrics
}
type BuilderConfig struct {
InsecureCookies bool
ForceHttpsRedirects bool
EnableRequestLogging bool
EnableIntrospection bool
GitHubAuthDemoClientID string
GitHubAuthDemoClientSecret string
DevMode bool
Metrics metrics.Metrics
}
func NewBuilder(pool *pool.Pool,
log *zap.Logger,
loader *engineconfigloader.EngineConfigLoader,
hooksClient *hooks.Client,
config BuilderConfig,
) *Builder {
return &Builder{
loader: loader,
log: log,
pool: pool,
insecureCookies: config.InsecureCookies,
middlewareClient: hooksClient,
forceHttpsRedirects: config.ForceHttpsRedirects,
enableIntrospection: config.EnableIntrospection,
githubAuthDemoClientID: config.GitHubAuthDemoClientID,
githubAuthDemoClientSecret: config.GitHubAuthDemoClientSecret,
devMode: config.DevMode,
metrics: config.Metrics,
}
}
func (r *Builder) BuildAndMountApiHandler(ctx context.Context, router *mux.Router, api *Api, planCache *ristretto.Cache) (streamClosers []chan struct{}, err error) {
r.api = api
r.router = r.createSubRouter(router)
for _, webhook := range api.Webhooks {
err = r.registerWebhook(webhook)
if err != nil {
r.log.Error("register webhook", zap.Error(err))
}
}
if api.EngineConfiguration == nil {
// no engine config, skipping configuration
return streamClosers, nil
}
if api.AuthenticationConfig == nil ||
api.AuthenticationConfig.Hooks == nil {
return streamClosers, fmt.Errorf("authentication config missing")
}
planConfig, err := r.loader.Load(api.EngineConfiguration, api.Options.ServerUrl)
if err != nil {
return streamClosers, err
}
r.planConfig = *planConfig
r.resolver = resolve.New(ctx, resolve.NewFetcher(true), true)
definition, report := astparser.ParseGraphqlDocumentString(api.EngineConfiguration.GraphqlSchema)
if report.HasErrors() {
return streamClosers, report
}
r.definition = &definition
err = asttransform.MergeDefinitionWithBaseSchema(r.definition)
if err != nil {
return streamClosers, err
}
if r.enableIntrospection {
introspectionFactory, err := introspection_datasource.NewIntrospectionConfigFactory(r.definition)
if err != nil {
return streamClosers, err
}
fieldConfigs := introspectionFactory.BuildFieldConfigurations()
r.planConfig.Fields = append(r.planConfig.Fields, fieldConfigs...)
dataSource := introspectionFactory.BuildDataSourceConfiguration()
r.planConfig.DataSources = append(r.planConfig.DataSources, dataSource)
}
r.log.Debug("configuring API",
zap.Int("numOfOperations", len(api.Operations)),
)
r.router.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requestID := request.Header.Get(logging.RequestIDHeader)
if requestID == "" {
id, _ := uuid.GenerateUUID()
requestID = id
}
request = request.WithContext(context.WithValue(request.Context(), logging.RequestIDKey{}, requestID))
if len(api.Hosts) > 0 {
for i := range api.Hosts {
if request.Host == api.Hosts[i] {
handler.ServeHTTP(w, request)
return
}
}
http.Error(w, fmt.Sprintf("Host not found: %s", request.Host), http.StatusNotFound)
return
}
handler.ServeHTTP(w, request)
})
})
if err := r.registerAuth(); err != nil {
if !r.devMode {
// If authentication fails in production, consider this a fatal error
return streamClosers, err
}
r.log.Error("configuring auth", zap.Error(err))
}
for _, s3Provider := range api.S3UploadConfiguration {
profiles := make(map[string]*s3uploadclient.UploadProfile, len(s3Provider.UploadProfiles))
for name, profile := range s3Provider.UploadProfiles {
profiles[name] = &s3uploadclient.UploadProfile{
RequireAuthentication: profile.RequireAuthentication,
MaxFileSizeBytes: int(profile.MaxAllowedUploadSizeBytes),
MaxAllowedFiles: int(profile.MaxAllowedFiles),
AllowedMimeTypes: append([]string(nil), profile.AllowedMimeTypes...),
AllowedFileExtensions: append([]string(nil), profile.AllowedFileExtensions...),
MetadataJSONSchema: profile.MetadataJSONSchema,
UsePreUploadHook: profile.Hooks.PreUpload,
UsePostUploadHook: profile.Hooks.PostUpload,
}
}
s3, err := s3uploadclient.NewS3UploadClient(loadvariable.String(s3Provider.Endpoint),
s3uploadclient.Options{
Logger: r.log,
BucketName: loadvariable.String(s3Provider.BucketName),
BucketLocation: loadvariable.String(s3Provider.BucketLocation),
AccessKeyID: loadvariable.String(s3Provider.AccessKeyID),
SecretAccessKey: loadvariable.String(s3Provider.SecretAccessKey),
UseSSL: s3Provider.UseSSL,
Profiles: profiles,
HooksClient: r.middlewareClient,
Name: s3Provider.Name,
},
)
if err != nil {
r.log.Error("unable to register S3 provider",
zap.Error(err),
zap.String("provider", s3Provider.Name),
zap.String("endpoint", loadvariable.String(s3Provider.Endpoint)),
)
} else {
s3Path := fmt.Sprintf("/s3/%s/upload", s3Provider.Name)
r.router.Handle(s3Path, http.HandlerFunc(s3.UploadFile))
r.log.Debug("register S3 provider", zap.String("provider", s3Provider.Name))
r.log.Debug("register S3 endpoint", zap.String("path", s3Path))
}
}
// RenameTo is the correct name for the origin
// for the downstream (client), we have to reverse the __typename fields
// this is why Types.RenameTo is assigned to rename.From
for _, configuration := range planConfig.Types {
r.renameTypeNames = append(r.renameTypeNames, resolve.RenameTypeName{
From: []byte(configuration.RenameTo),
To: []byte(configuration.TypeName),
})
}
for _, operation := range api.Operations {
err = r.registerOperation(operation)
if err != nil {
r.log.Error("registerOperation", zap.Error(err))
return streamClosers, err
}
}
for _, operationName := range api.InvalidOperationNames {
r.registerInvalidOperation(operationName)
}
if api.EnableGraphqlEndpoint {
mountGraphQLHandler(r.router, GraphQLHandlerOptions{
GraphQLBaseURL: api.Options.PublicNodeUrl,
Internal: false,
PlanConfig: r.planConfig,
Definition: r.definition,
Resolver: r.resolver,
RenameTypeNames: r.renameTypeNames,
Pool: r.pool,
Cache: planCache,
Log: r.log,
})
}
return streamClosers, err
}
func mergeRequiredFields(fields plan.FieldConfigurations, fieldsRequired plan.FieldConfigurations) plan.FieldConfigurations {
WithNext:
for _, required := range fieldsRequired {
for i := range fields {
if required.TypeName == fields[i].TypeName && required.FieldName == fields[i].FieldName {
NextRequired:
for _, add := range required.RequiresFields {
for _, ex := range fields[i].RequiresFields {
if ex == add {
continue NextRequired
}
}
fields[i].RequiresFields = append(fields[i].RequiresFields, add)
}
continue WithNext
}
}
fields = append(fields, required)
}
return fields
}
func (r *Builder) createSubRouter(router *mux.Router) *mux.Router {
route := router.NewRoute()
r.log.Debug("create sub router")
return route.Subrouter()
}
func (r *Builder) registerWebhook(config *wgpb.WebhookConfiguration) error {
handler, err := webhookhandler.New(config, r.api.Options.ServerUrl, r.log)
if err != nil {
return err
}
webhookPath := fmt.Sprintf("/webhooks/%s", config.Name)
r.router.
Methods(http.MethodPost, http.MethodGet).
Path(webhookPath).
Handler(handler)
return nil
}
func operationApiPath(name string) string {
return fmt.Sprintf("/operations/%s", name)
}
func (r *Builder) registerInvalidOperation(name string) {
apiPath := operationApiPath(name)
route := r.router.Methods(http.MethodGet, http.MethodPost, http.MethodOptions).Path(apiPath)
route.Handler(&EndpointUnavailableHandler{
OperationName: name,
Logger: r.log,
})
r.log.Warn("EndpointUnavailableHandler",
zap.String("Operation", name),
zap.String("Endpoint", apiPath),
zap.String("Help", "This operation is invalid. Please, check the logs"),
)
}
func (r *Builder) registerOperation(operation *wgpb.Operation) error {
if operation.Internal {
return nil
}
apiPath := operationApiPath(operation.Path)
if operation.Engine == wgpb.OperationExecutionEngine_ENGINE_NODEJS {
return r.registerNodejsOperation(operation, apiPath)
}
shared := r.pool.GetShared(context.Background(), r.planConfig, pool.Config{})
shared.Doc.Input.ResetInputString(operation.Content)
shared.Parser.Parse(shared.Doc, shared.Report)
if shared.Report.HasErrors() {
return fmt.Errorf(ErrMsgOperationParseFailed, shared.Report)
}
shared.Normalizer.NormalizeNamedOperation(shared.Doc, r.definition, []byte(operation.Name), shared.Report)
if shared.Report.HasErrors() {
return fmt.Errorf(ErrMsgOperationNormalizationFailed, shared.Report)
}
state := shared.Validation.Validate(shared.Doc, r.definition, shared.Report)
if state != astvalidation.Valid {
return fmt.Errorf(ErrMsgOperationValidationFailed, shared.Report)
}
preparedPlan := shared.Planner.Plan(shared.Doc, r.definition, operation.Name, shared.Report)
if shared.Report.HasErrors() {
return fmt.Errorf(ErrMsgOperationPlanningFailed, shared.Report)
}
shared.Postprocess.Process(preparedPlan)
variablesValidator, err := inputvariables.NewValidator(cleanupJsonSchema(operation.VariablesSchema), false)
if err != nil {
return err
}
queryParamsAllowList := generateQueryArgumentsAllowList(operation.VariablesSchema)
stringInterpolator, err := interpolate.NewStringInterpolator(cleanupJsonSchema(operation.VariablesSchema))
if err != nil {
return err
}
jsonStringInterpolator, err := interpolate.NewStringInterpolatorJSONOnly(cleanupJsonSchema(operation.InterpolationVariablesSchema))
if err != nil {
return err
}
postResolveTransformer := postresolvetransform.NewTransformer(operation.PostResolveTransformations)
hooksPipelineCommonConfig := hooks.PipelineConfig{
Client: r.middlewareClient,
Operation: operation,
Transformer: postResolveTransformer,
Logger: r.log,
}
var operationHandler http.Handler
var route *mux.Route
switch operation.OperationType {
case wgpb.OperationType_QUERY:
synchronousPlan, ok := preparedPlan.(*plan.SynchronousResponsePlan)
if !ok {
break
}
hooksPipelineConfig := hooks.SynchronousOperationPipelineConfig{
PipelineConfig: hooksPipelineCommonConfig,
Resolver: r.resolver,
Plan: synchronousPlan,
}
hooksPipeline := hooks.NewSynchronousOperationPipeline(hooksPipelineConfig)
handler := &QueryHandler{
resolver: r.resolver,
log: r.log,
preparedPlan: synchronousPlan,
pool: r.pool,
extractedVariables: make([]byte, len(shared.Doc.Input.Variables)),
cacheHeaders: cacheheaders.New(newCacheControl(operation.CacheConfig), r.api.ApiConfigHash),
operation: operation,
variablesValidator: variablesValidator,
rbacEnforcer: authentication.NewRBACEnforcer(operation),
stringInterpolator: stringInterpolator,
jsonStringInterpolator: jsonStringInterpolator,
postResolveTransformer: postResolveTransformer,
renameTypeNames: r.renameTypeNames,
queryParamsAllowList: queryParamsAllowList,
hooksPipeline: hooksPipeline,
errorHandler: newErrorHandler(operation, r.devMode),
}
if operation.LiveQueryConfig != nil && operation.LiveQueryConfig.Enable {
handler.liveQuery = liveQueryConfig{
enabled: true,
pollingIntervalSeconds: operation.LiveQueryConfig.PollingIntervalSeconds,
}
}
copy(handler.extractedVariables, shared.Doc.Input.Variables)
route = r.router.Methods(http.MethodGet, http.MethodOptions).Path(apiPath)
operationHandler = handler
r.log.Debug("registered QueryHandler",
zap.String("method", http.MethodGet),
zap.String("path", apiPath),
zap.Bool("mock", operation.HooksConfiguration.MockResolve.Enable),
zap.String("cache", handler.cacheHeaders.String()),
zap.Bool("authRequired", operation.AuthenticationConfig != nil && operation.AuthenticationConfig.AuthRequired),
)
case wgpb.OperationType_MUTATION:
synchronousPlan, ok := preparedPlan.(*plan.SynchronousResponsePlan)
if !ok {
break
}
hooksPipelineConfig := hooks.SynchronousOperationPipelineConfig{
PipelineConfig: hooksPipelineCommonConfig,
Resolver: r.resolver,
Plan: synchronousPlan,
}
hooksPipeline := hooks.NewSynchronousOperationPipeline(hooksPipelineConfig)
handler := &MutationHandler{
resolver: r.resolver,
log: r.log,
preparedPlan: synchronousPlan,
pool: r.pool,
extractedVariables: make([]byte, len(shared.Doc.Input.Variables)),
cacheHeaders: cacheheaders.New(newCacheControl(operation.CacheConfig), r.api.ApiConfigHash),
operation: operation,
variablesValidator: variablesValidator,
rbacEnforcer: authentication.NewRBACEnforcer(operation),
stringInterpolator: stringInterpolator,
jsonStringInterpolator: jsonStringInterpolator,
postResolveTransformer: postResolveTransformer,
renameTypeNames: r.renameTypeNames,
hooksPipeline: hooksPipeline,
errorHandler: newErrorHandler(operation, r.devMode),
}
copy(handler.extractedVariables, shared.Doc.Input.Variables)
route = r.router.Methods(http.MethodPost, http.MethodOptions).Path(apiPath)
operationHandler = handler
r.log.Debug("registered MutationHandler",
zap.String("method", http.MethodPost),
zap.String("path", apiPath),
zap.Bool("mock", operation.HooksConfiguration.MockResolve.Enable),
zap.Bool("authRequired", operation.AuthenticationConfig != nil && operation.AuthenticationConfig.AuthRequired),
)
case wgpb.OperationType_SUBSCRIPTION:
subscriptionPlan, ok := preparedPlan.(*plan.SubscriptionResponsePlan)
if !ok {
break
}
hooksPipelineConfig := hooks.SubscriptionOperationPipelineConfig{
PipelineConfig: hooksPipelineCommonConfig,
Resolver: r.resolver,
Plan: subscriptionPlan,
}
hooksPipeline := hooks.NewSubscriptionOperationPipeline(hooksPipelineConfig)
handler := &SubscriptionHandler{
resolver: r.resolver,
log: r.log,
preparedPlan: subscriptionPlan,
pool: r.pool,
extractedVariables: make([]byte, len(shared.Doc.Input.Variables)),
cacheHeaders: cacheheaders.New(newCacheControl(operation.CacheConfig), r.api.ApiConfigHash),
operation: operation,
variablesValidator: variablesValidator,
rbacEnforcer: authentication.NewRBACEnforcer(operation),
stringInterpolator: stringInterpolator,
jsonStringInterpolator: jsonStringInterpolator,
postResolveTransformer: postResolveTransformer,
renameTypeNames: r.renameTypeNames,
queryParamsAllowList: queryParamsAllowList,
hooksPipeline: hooksPipeline,
pingInterval: r.api.Options.Subscriptions.ServerPingInterval,
errorHandler: newErrorHandler(operation, r.devMode),
}
copy(handler.extractedVariables, shared.Doc.Input.Variables)
route = r.router.Methods(http.MethodGet, http.MethodOptions).Path(apiPath)
operationHandler = handler
r.log.Debug("registered SubscriptionHandler",
zap.String("method", http.MethodGet),
zap.String("path", apiPath),
zap.Bool("mock", operation.HooksConfiguration.MockResolve.Enable),
zap.Bool("authRequired", operation.AuthenticationConfig != nil && operation.AuthenticationConfig.AuthRequired),
)
default:
r.log.Debug("operation type unknown",
zap.String("name", operation.Name),
zap.String("content", operation.Content),
)
}
if route != nil && operationHandler != nil {
if operation.AuthenticationConfig != nil && operation.AuthenticationConfig.AuthRequired {
operationHandler = authentication.RequiresAuthentication(operationHandler)
route.Handler(authentication.RequiresAuthentication(operationHandler))
}
metrics := newOperationMetrics(r.metrics, operation.Name)
route.Handler(metrics.Handler(operationHandler))
} else {
r.registerInvalidOperation(operation.Name)
}
return nil
}
func generateQueryArgumentsAllowList(schema string) []string {
var allowList []string
schema = cleanupJsonSchema(schema)
_ = jsonparser.ObjectEach([]byte(schema), func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
allowList = append(allowList, string(key))
return nil
}, "properties")
return allowList
}
func cleanupJsonSchema(schema string) string {
schema = strings.Replace(schema, "/definitions/", "/$defs/", -1)
schema = strings.Replace(schema, "\"definitions\"", "\"$defs\"", -1)
return schema
}
func (r *Builder) Close() error {
return nil
}
type planWithExtractedVariables struct {
preparedPlan plan.Plan
variables []byte
}
var (
errInvalid = errors.New("invalid")
)
func postProcessVariables(operation *wgpb.Operation, r *http.Request, variables []byte) ([]byte, error) {
var err error
variables, err = injectClaims(operation, r, variables)
if err != nil {
return nil, err
}
variables = injectVariables(operation, r, variables)
return variables, nil
}
func injectWellKnownClaim(claim *wgpb.ClaimConfig, user *authentication.User, variables []byte) ([]byte, error) {
var err error
var replacement string
switch claim.ClaimType {
case wgpb.ClaimType_ISSUER:
replacement = user.ProviderID
case wgpb.ClaimType_SUBJECT: // handles wgpb.ClaimType_USERID too
replacement = user.UserID
case wgpb.ClaimType_NAME:
replacement = user.Name
case wgpb.ClaimType_GIVEN_NAME:
replacement = user.FirstName
case wgpb.ClaimType_FAMILY_NAME:
replacement = user.LastName
case wgpb.ClaimType_MIDDLE_NAME:
replacement = user.MiddleName
case wgpb.ClaimType_NICKNAME:
replacement = user.NickName
case wgpb.ClaimType_PREFERRED_USERNAME:
replacement = user.PreferredUsername
case wgpb.ClaimType_PROFILE:
replacement = user.Profile
case wgpb.ClaimType_PICTURE:
replacement = user.Picture
case wgpb.ClaimType_WEBSITE:
replacement = user.Website
case wgpb.ClaimType_EMAIL:
replacement = user.Email
case wgpb.ClaimType_EMAIL_VERIFIED:
var boolValue string
if user.EmailVerified {
boolValue = "true"
} else {
boolValue = "false"
}
variables, err = jsonparser.Set(variables, []byte(boolValue), claim.VariablePathComponents...)
if err != nil {
return nil, fmt.Errorf("error replacing variable for claim %s: %w", claim.ClaimType, err)
}
// Don't go into the block after the switch that sets the variable as a string
return variables, nil
case wgpb.ClaimType_GENDER:
replacement = user.Gender
case wgpb.ClaimType_BIRTH_DATE:
replacement = user.BirthDate
case wgpb.ClaimType_ZONE_INFO:
replacement = user.ZoneInfo
case wgpb.ClaimType_LOCALE:
replacement = user.Locale
case wgpb.ClaimType_LOCATION:
replacement = user.Location
default:
return nil, fmt.Errorf("unhandled well known claim %s", claim.ClaimType)
}
variables, err = jsonparser.Set(variables, []byte("\""+replacement+"\""), claim.VariablePathComponents...)
if err != nil {
return nil, fmt.Errorf("error replacing variable for well known claim %s: %w", claim.ClaimType, err)
}
return variables, nil
}
func injectCustomClaim(claim *wgpb.ClaimConfig, user *authentication.User, variables []byte) ([]byte, error) {
custom := claim.GetCustom()
value := jsonpath.GetKeys(user.CustomClaims, custom.JsonPathComponents...)
var replacement []byte
switch x := value.(type) {
case nil:
if custom.Required {
return nil, inputvariables.NewValidationError(fmt.Sprintf("required customClaim %s not found", custom.Name), nil, nil)
}
return variables, nil
case string:
if custom.Type != wgpb.ValueType_STRING && custom.Type != wgpb.ValueType_ANY {
return nil, inputvariables.NewValidationError(
fmt.Sprintf("customClaim %s expected to be of type %s, found %T instead", custom.Name, custom.Type, x),
nil,
nil,
)
}
replacement = []byte("\"" + string(x) + "\"")
case bool:
if custom.Type != wgpb.ValueType_BOOLEAN && custom.Type != wgpb.ValueType_ANY {
return nil, inputvariables.NewValidationError(
fmt.Sprintf("customClaim %s expected to be of type %s, found %T instead", custom.Name, custom.Type, x),
nil,
nil,
)
}
if x {
replacement = []byte("true")
} else {
replacement = []byte("false")
}
case float64:
switch custom.Type {
case wgpb.ValueType_INT:
if x != float64(int(x)) {
// Value is not integral
return nil, inputvariables.NewValidationError(
fmt.Sprintf("customClaim %s expected to be of type %s, found %s instead", custom.Name, custom.Type, "float"),
nil,
nil,
)
}
replacement = []byte(strconv.FormatInt(int64(x), 10))
case wgpb.ValueType_FLOAT, wgpb.ValueType_ANY:
// JSON number is always a valid float
replacement = []byte(strconv.FormatFloat(x, 'f', -1, 64))
default:
return nil, inputvariables.NewValidationError(
fmt.Sprintf("customClaim %s expected to be of type %s, found %T instead", custom.Name, custom.Type, x),
nil,
nil,
)
}
default:
if custom.Type != wgpb.ValueType_ANY {
return nil, inputvariables.NewValidationError(
fmt.Sprintf("customClaim %s expected to be of type %s, found %T instead", custom.Name, custom.Type, x),
nil,
nil,
)
}
var err error
replacement, err = json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("error serializing data %v for custom claim %s: %w", value, custom.Name, err)
}
}
var err error
variables, err = jsonparser.Set(variables, replacement, claim.VariablePathComponents...)
if err != nil {
return nil, fmt.Errorf("error replacing variable for customClaim %s: %w", custom.Name, err)
}
return variables, nil
}
func injectClaims(operation *wgpb.Operation, r *http.Request, variables []byte) ([]byte, error) {
authorizationConfig := operation.GetAuthorizationConfig()
claims := authorizationConfig.GetClaims()
if len(claims) == 0 {
return variables, nil
}
user := authentication.UserFromContext(r.Context())
if user == nil {
return variables, nil
}
var err error
for _, claim := range claims {
if claim.GetClaimType() == wgpb.ClaimType_CUSTOM {
variables, err = injectCustomClaim(claim, user, variables)
} else {
variables, err = injectWellKnownClaim(claim, user, variables)
}
}
if err != nil {
return nil, err
}
return variables, nil
}
func injectVariables(operation *wgpb.Operation, _ *http.Request, variables []byte) []byte {
if operation.VariablesConfiguration == nil || operation.VariablesConfiguration.InjectVariables == nil {
return variables
}
for i := range operation.VariablesConfiguration.InjectVariables {
keys := operation.VariablesConfiguration.InjectVariables[i].VariablePathComponents
kind := operation.VariablesConfiguration.InjectVariables[i].VariableKind
switch kind {
case wgpb.InjectVariableKind_UUID:
id, _ := uuid.GenerateUUID()
variables, _ = jsonparser.Set(variables, []byte("\""+id+"\""), keys...)
case wgpb.InjectVariableKind_DATE_TIME:
format := operation.VariablesConfiguration.InjectVariables[i].DateFormat
now := time.Now()
dateTime := now.Format(format)
variables, _ = jsonparser.Set(variables, []byte("\""+dateTime+"\""), keys...)
case wgpb.InjectVariableKind_ENVIRONMENT_VARIABLE:
value := os.Getenv(operation.VariablesConfiguration.InjectVariables[i].EnvironmentVariableName)
if value == "" {
continue
}
variables, _ = jsonparser.Set(variables, []byte("\""+value+"\""), keys...)
}
}
return variables
}
type QueryResolver interface {
ResolveGraphQLResponse(ctx *resolve.Context, response *resolve.GraphQLResponse, data []byte, writer io.Writer) (err error)
}
type SubscriptionResolver interface {
ResolveGraphQLSubscription(ctx *resolve.Context, subscription *resolve.GraphQLSubscription, writer resolve.FlushWriter) (err error)
}
type GraphQLResolver interface {
QueryResolver
SubscriptionResolver
}
type liveQueryConfig struct {
enabled bool
pollingIntervalSeconds int64
}
type QueryHandler struct {
resolver QueryResolver
log *zap.Logger
preparedPlan *plan.SynchronousResponsePlan
extractedVariables []byte
pool *pool.Pool
cacheHeaders *cacheheaders.Headers
liveQuery liveQueryConfig
operation *wgpb.Operation
variablesValidator *inputvariables.Validator
rbacEnforcer *authentication.RBACEnforcer
stringInterpolator *interpolate.StringInterpolator
jsonStringInterpolator *interpolate.StringInterpolator
postResolveTransformer *postresolvetransform.Transformer
renameTypeNames []resolve.RenameTypeName
queryParamsAllowList []string
hooksPipeline *hooks.SynchronousOperationPipeline
errorHandler *errorHandler
}
func (h *QueryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestLogger := h.log.With(logging.WithRequestIDFromContext(r.Context()))
r = operation.RequestWithMetadata(r, operation.NewMetadata(h.operation))
// Set trace attributes based on the current operation
trace.SetOperationAttributes(r.Context())
if proceed := h.rbacEnforcer.Enforce(r); !proceed {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
isLive := h.liveQuery.enabled && r.URL.Query().Has(WgLiveParam)
buf := pool.GetBytesBuffer()
defer pool.PutBytesBuffer(buf)
resolveCtx := pool.GetCtx(r, r, pool.Config{
RenameTypeNames: h.renameTypeNames,
})
defer pool.PutCtx(resolveCtx)
var err error
resolveCtx.Variables, err = querystring.ToJSON(r.URL.RawQuery, h.queryParamsAllowList)
if err != nil {
requestLogger.Error("Could not parse query string", zap.Error(err))
w.WriteHeader(http.StatusBadRequest)
return
}
resolveCtx.Variables = h.stringInterpolator.Interpolate(resolveCtx.Variables)
if !validateInputVariables(resolveCtx.Context(), requestLogger, resolveCtx.Variables, h.variablesValidator, w) {
return
}
compactBuf := pool.GetBytesBuffer()
defer pool.PutBytesBuffer(compactBuf)
err = json.Compact(compactBuf, resolveCtx.Variables)
if err != nil {
requestLogger.Error("Could not compact variables in query handler", zap.Bool("isLive", isLive), zap.Error(err))
w.WriteHeader(http.StatusBadRequest)
return
}
resolveCtx.Variables = compactBuf.Bytes()
resolveCtx.Variables = h.jsonStringInterpolator.Interpolate(resolveCtx.Variables)
if len(h.extractedVariables) != 0 {
// we make a copy of the extracted variables to not override h.extractedVariables
resolveCtx.Variables = MergeJsonRightIntoLeft(h.extractedVariables, resolveCtx.Variables)
}
resolveCtx.Variables, err = postProcessVariables(h.operation, r, resolveCtx.Variables)
if h.errorHandler.Done(w, err, "postProcessVariables failed", requestLogger) {
return
}
flusher, flusherOk := w.(http.Flusher)
if isLive {
if !flusherOk {
requestLogger.Error("Could not flush in query handler", zap.Bool("isLive", isLive))
http.Error(w, "requires flushing", http.StatusBadRequest)
return
}
setSubscriptionHeaders(w)
flusher.Flush()
} else {
w.Header().Set("Content-Type", "application/json")
}
if isLive {
h.handleLiveQuery(r, w, resolveCtx, buf, flusher, requestLogger)
return
}
resp, err := h.hooksPipeline.Run(resolveCtx, w, r, buf)
if h.errorHandler.Done(w, err, "hooks pipeline failed", requestLogger) {
return
}
if resp.Done {
return
}
if h.cacheHeaders != nil {
h.cacheHeaders.Set(r, w, resp.Data)
if h.cacheHeaders.NotModified(r, w) {
return
}
}
_, err = w.Write(resp.Data)
if h.errorHandler.Done(w, err, "writing response failed", requestLogger) {
return
}
}
func (h *QueryHandler) handleLiveQueryEvent(ctx *resolve.Context, w http.ResponseWriter, r *http.Request, requestBuf *bytes.Buffer, hookBuf *bytes.Buffer) ([]byte, error) {
requestBuf.Reset()
hooksResponse, err := h.hooksPipeline.Run(ctx, w, r, requestBuf)
if err != nil {
return nil, fmt.Errorf("handleLiveQueryEvent: %w", err)
}
if hooksResponse.Done {
// Response is already written by hooks pipeline, tell
// caller to stop
return nil, context.Canceled
}
return hooksResponse.Data, nil
}
func (h *QueryHandler) handleLiveQuery(r *http.Request, w http.ResponseWriter, ctx *resolve.Context, requestBuf *bytes.Buffer, flusher http.Flusher, requestLogger *zap.Logger) {
wgParams := NewWgRequestParams(r)
done := ctx.Context().Done()
hookBuf := pool.GetBytesBuffer()