Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/vault-node-async-gateway-handler.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chainlink": patch
---

#bugfix Vault nodes serve each gateway request in its own goroutine instead of inline in the gateway connection's read loop, so a request waiting on authorization no longer delays every later request from that gateway
14 changes: 14 additions & 0 deletions core/capabilities/vault/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package vault

import (
"context"
"encoding/json"

jsonrpc "github.com/smartcontractkit/chainlink-common/pkg/jsonrpc2"
)

// ServeGatewayMessage runs the request synchronously, as the goroutine that
// HandleGatewayMessage starts does, so tests can assert on the result directly.
func (h *GatewayHandler) ServeGatewayMessage(ctx context.Context, gatewayID string, req *jsonrpc.Request[json.RawMessage]) error {
return h.serveGatewayMessage(ctx, gatewayID, req)
}
23 changes: 22 additions & 1 deletion core/capabilities/vault/gw_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"sync"
"time"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
Expand All @@ -31,6 +32,11 @@ var (
HandlerName = "VaultHandler"
)

// gatewayRequestServeTimeout bounds how long one gateway request may be served for. It stays
// above the allowlist retry window (allowListBasedAuthRetryCount * allowListBasedAuthRetryInterval)
// so a request whose allowlist entry is still reaching this node is not cut short.
const gatewayRequestServeTimeout = 60 * time.Second

type metrics struct {
// Given that all requests are coming from the gateway, we can assume that all errors are internal errors
requestInternalError metric.Int64Counter
Expand Down Expand Up @@ -177,7 +183,22 @@ func (h *GatewayHandler) requestLogger(req *jsonrpc.Request[json.RawMessage], ga
return logger.With(h.lggr, "requestID", req.ID, "method", req.Method, "gatewayID", gatewayID)
}

func (h *GatewayHandler) HandleGatewayMessage(ctx context.Context, gatewayID string, req *jsonrpc.Request[json.RawMessage]) (err error) {
// HandleGatewayMessage serves the request in its own goroutine and returns immediately. The
// connector calls it from the single read loop for the gateway, so serving the request inline
// would hold every later message from that gateway behind it, for example while authorization
// waits out the allowlist retry window.
func (h *GatewayHandler) HandleGatewayMessage(ctx context.Context, gatewayID string, req *jsonrpc.Request[json.RawMessage]) error {
return h.eng.IfStarted(func() error {
h.eng.GoCtx(ctx, func(ctx context.Context) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure that you want GoCtx here? I think you need to shed the cancellation either with:

Suggested change
h.eng.GoCtx(ctx, func(ctx context.Context) {
h.eng.Go(func(ctx context.Context) {

Or if there are other relevant context values, then:

Suggested change
h.eng.GoCtx(ctx, func(ctx context.Context) {
h.eng.GoCtx(context.WithoutCancel(ctx), func(ctx context.Context) {

ctx, cancel := context.WithTimeout(ctx, gatewayRequestServeTimeout)
defer cancel()
_ = h.serveGatewayMessage(ctx, gatewayID, req)
})
return nil
})
}

func (h *GatewayHandler) serveGatewayMessage(ctx context.Context, gatewayID string, req *jsonrpc.Request[json.RawMessage]) (err error) {
reqLggr := h.requestLogger(req, gatewayID)
reqLggr.Debugw("received message from gateway", "req", req)

Expand Down
111 changes: 108 additions & 3 deletions core/capabilities/vault/gw_handler_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package vault_test

import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -679,7 +681,7 @@ func TestGatewayHandler_HandleGatewayMessage(t *testing.T) {
)
require.NoError(t, err)

err = handler.HandleGatewayMessage(ctx, "gateway-1", request)
err = handler.ServeGatewayMessage(ctx, "gateway-1", request)

if tt.expectedError {
assert.Error(t, err)
Expand Down Expand Up @@ -776,7 +778,7 @@ func TestGatewayHandler_DeleteListWithoutPublicKeyFetch(t *testing.T) {
ID: "1",
Params: &raw,
}
require.NoError(t, handler.HandleGatewayMessage(ctx, "gateway-1", req))
require.NoError(t, handler.ServeGatewayMessage(ctx, "gateway-1", req))
})
}
}
Expand Down Expand Up @@ -833,7 +835,7 @@ func TestGatewayHandler_CreateUpdateReusesCachedPublicKey(t *testing.T) {
return resp.Error == nil
})).Return(nil).Once()

require.NoError(t, handler.HandleGatewayMessage(ctx, "gateway-1", makeCreateRequest(id)), "request %d", i+1)
require.NoError(t, handler.ServeGatewayMessage(ctx, "gateway-1", makeCreateRequest(id)), "request %d", i+1)
}
}

Expand Down Expand Up @@ -899,3 +901,106 @@ func TestGatewayHandler_Lifecycle_DefaultAuthorizer_NoJWTConfig(t *testing.T) {
gwConnector.On("RemoveHandler", mock.Anything, vaulttypes.Methods).Return(nil).Once()
require.NoError(t, handler.Close())
}

// blockingAuthorizer holds the request with ID blockedID in authorization until release is closed,
// the way allowlist auth holds a request while it retries a digest that has not reached this node.
type blockingAuthorizer struct {
owner string
blockedID string
blocked chan struct{}
release chan struct{}
}

func (a *blockingAuthorizer) AuthorizeRequest(ctx context.Context, req jsonrpc.Request[json.RawMessage]) (*vaultcap.AuthResult, error) {
if req.ID == a.blockedID {
close(a.blocked)
select {
case <-a.release:
case <-ctx.Done():
return nil, ctx.Err()
}
}
return vaultcap.NewAuthResult("", a.owner, "digest-"+req.ID, 0), nil
}

func TestGatewayHandler_HandleGatewayMessageDoesNotBlockOtherRequests(t *testing.T) {
t.Parallel()

lggr := logger.TestLogger(t)
ctx := t.Context()
owner := "0xabc"

secretsService := vaulttypesmocks.NewSecretsService(t)
secretsService.EXPECT().ListSecretIdentifiers(mock.Anything, mock.Anything).
Return(&vaulttypes.Response{ID: "test_secret"}, nil)

sent := make(chan string, 2)
gwConnector := connector_mocks.NewGatewayConnector(t)
gwConnector.On("SendToGateway", mock.Anything, "gateway-1", mock.Anything).Run(func(args mock.Arguments) {
sent <- args.Get(2).(*jsonrpc.Response[json.RawMessage]).ID
}).Return(nil)

authorizer := &blockingAuthorizer{owner: owner, blockedID: "slow", blocked: make(chan struct{}), release: make(chan struct{})}
releaseSlow := sync.OnceFunc(func() { close(authorizer.release) })
t.Cleanup(releaseSlow)

handler, err := vaultcap.NewGatewayHandler(
secretsService,
gwConnector,
nil,
lggr,
limits.Factory{Settings: cresettings.DefaultGetter},
authorizer,
nil,
)
require.NoError(t, err)

listRequest := func(id string) *jsonrpc.Request[json.RawMessage] {
params, err := json.Marshal(vaultcommon.ListSecretIdentifiersRequest{RequestId: id, Owner: owner, Namespace: vaulttypes.DefaultNamespace})
require.NoError(t, err)
raw := json.RawMessage(params)
return &jsonrpc.Request[json.RawMessage]{ID: id, Method: vaulttypes.MethodSecretsList, Params: &raw}
}
waitFor := func(ch <-chan struct{}, failure string) {
t.Helper()
select {
case <-ch:
case <-time.After(5 * time.Second):
t.Fatal(failure)
}
}

require.ErrorContains(t, handler.HandleGatewayMessage(ctx, "gateway-1", listRequest("early")), "not started")

gwConnector.On("AddHandler", mock.Anything, vaulttypes.Methods, handler).Return(nil).Once()
require.NoError(t, handler.Start(ctx))

// The connector calls HandleGatewayMessage from its single read loop for the gateway, so the call
// must return while the request is still being served.
returned := make(chan struct{})
go func() {
assert.NoError(t, handler.HandleGatewayMessage(ctx, "gateway-1", listRequest("slow")))
close(returned)
}()
waitFor(authorizer.blocked, "slow request never reached authorization")
waitFor(returned, "HandleGatewayMessage blocked the read loop until the request was served")

require.NoError(t, handler.HandleGatewayMessage(ctx, "gateway-1", listRequest("fast")))
select {
case id := <-sent:
require.Equal(t, owner+vaulttypes.RequestIDSeparator+"fast", id)
case <-time.After(5 * time.Second):
t.Fatal("fast request was not served while the slow one was held in authorization")
}

releaseSlow()
select {
case id := <-sent:
require.Equal(t, owner+vaulttypes.RequestIDSeparator+"slow", id)
case <-time.After(5 * time.Second):
t.Fatal("slow request was not served after authorization was released")
}

gwConnector.On("RemoveHandler", mock.Anything, vaulttypes.Methods).Return(nil).Once()
require.NoError(t, handler.Close())
}
Loading