Skip to content

Commit

Permalink
fix: avoid panic from tracing on bad request (#2871)
Browse files Browse the repository at this point in the history
This fixes a panic which arises from the tracing components when a request has some defect which results in an error when creating the operation context. The transports consistently handle this by calling `DispatchError(graphql.WithOperationContext(ctx, rc), err)` where `rc` is the OperationContext which was not correctly constructed. This seems dangerous, because middleware may assume that if there in an `OperationContext` in the `context.Context` than they are being invoked on a normal codepath and can assume their other interceptors have been invoked in the normal order. Also, using a value returned by a function which also returned a non-nil error is very unusual. However, I have no idea what the impact of changing that dangerous behavior in the transports would be, so I opted to make the tracing component more resilient instead.
  • Loading branch information
SteveRuble committed Dec 29, 2023
1 parent 13bb415 commit c811d47
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions graphql/handler/apollofederatedtracingv1/tracing.go
Expand Up @@ -85,10 +85,12 @@ func (t *Tracer) InterceptResponse(ctx context.Context, next graphql.ResponseHan
return next(ctx)
}
tb := t.getTreeBuilder(ctx)
if tb != nil {
tb.StartTimer(ctx)
if tb == nil {
return next(ctx)
}

tb.StartTimer(ctx)

val := new(string)
graphql.RegisterExtension(ctx, "ftv1", val)

Expand Down
23 changes: 23 additions & 0 deletions graphql/handler/apollofederatedtracingv1/tracing_test.go
Expand Up @@ -110,6 +110,29 @@ func TestApolloTracing_withFail(t *testing.T) {
require.Equal(t, "PersistedQueryNotFound", respData.Errors[0].Message)
}

// This tests that the tracing extension does not panic when the request
// can't be processed for some reason. The specific cause is not
// important, the scenario being tested is the response interceptor
// being run to process the error response when no other interceptor
// has been run, due to (for example) a problem creating the OperationContext.
func TestApolloTracing_withMissingOp(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.POST{})
h.Use(extension.AutomaticPersistedQuery{Cache: lru.New(100)})
h.Use(&apollofederatedtracingv1.Tracer{})

resp := doRequest(h, http.MethodPost, "/graphql", `{}`)
assert.Equal(t, http.StatusUnprocessableEntity, resp.Code, resp.Body.String())
b := resp.Body.Bytes()
t.Log(string(b))
var respData struct {
Errors gqlerror.List
}
require.NoError(t, json.Unmarshal(b, &respData))
require.Len(t, respData.Errors, 1)
require.Equal(t, "no operation provided", respData.Errors[0].Message)
}

func TestApolloTracing_withUnexpectedEOF(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.POST{})
Expand Down

0 comments on commit c811d47

Please sign in to comment.