-
Notifications
You must be signed in to change notification settings - Fork 855
node: Add ability to pass custom headers to Sui gRPC #4890
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
djb15
wants to merge
1
commit into
wormhole-foundation:main
Choose a base branch
from
djb15:node/sui-grpc-headers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| package suiclient | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/metadata" | ||
| ) | ||
|
|
||
| // GrpcHeaderDialOptions converts key=value header specs from command line args | ||
| // into gRPC client interceptors that attach the headers as outgoing metadata | ||
| func GrpcHeaderDialOptions(headerSpecs []string) ([]grpc.DialOption, error) { | ||
| headers, err := parseGrpcHeaderSpecs(headerSpecs) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if len(headers) == 0 { | ||
| return nil, nil | ||
| } | ||
|
|
||
| headers = headers.Copy() | ||
| return []grpc.DialOption{ | ||
| grpc.WithChainUnaryInterceptor(grpcHeaderUnaryInterceptor(headers)), | ||
| grpc.WithChainStreamInterceptor(grpcHeaderStreamInterceptor(headers)), | ||
| }, nil | ||
| } | ||
|
|
||
| func parseGrpcHeaderSpecs(headerSpecs []string) (metadata.MD, error) { | ||
| headers := metadata.MD{} | ||
|
|
||
| for _, spec := range headerSpecs { | ||
| spec = strings.TrimSpace(spec) | ||
| if spec == "" { | ||
| continue | ||
| } | ||
|
|
||
| key, value, ok := strings.Cut(spec, "=") | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid gRPC header: expected key=value") | ||
| } | ||
|
|
||
| key = strings.ToLower(strings.TrimSpace(key)) | ||
| value = strings.TrimSpace(value) | ||
|
|
||
| if err := validateGrpcMetadataKey(key); err != nil { | ||
| return nil, err | ||
| } | ||
| if value == "" { | ||
| return nil, fmt.Errorf("invalid gRPC header %q: value must not be empty", key) | ||
| } | ||
| if _, exists := headers[key]; exists { | ||
| return nil, fmt.Errorf("duplicate gRPC header key %q", key) | ||
| } | ||
|
|
||
| headers.Append(key, value) | ||
| } | ||
|
|
||
| return headers, nil | ||
| } | ||
|
|
||
| func validateGrpcMetadataKey(key string) error { | ||
| if key == "" { | ||
| return fmt.Errorf("invalid gRPC header: key must not be empty") | ||
| } | ||
|
|
||
| for _, r := range key { | ||
| switch { | ||
| case r >= 'a' && r <= 'z': | ||
| case r >= '0' && r <= '9': | ||
| case r == '-' || r == '_' || r == '.': | ||
| default: | ||
| return fmt.Errorf("invalid gRPC header key %q: keys may only contain letters, digits, '-', '_' or '.'", key) | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func grpcHeaderUnaryInterceptor(headers metadata.MD) grpc.UnaryClientInterceptor { | ||
| return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { | ||
| return invoker(appendGrpcHeadersToContext(ctx, headers), method, req, reply, cc, opts...) | ||
| } | ||
| } | ||
|
|
||
| func grpcHeaderStreamInterceptor(headers metadata.MD) grpc.StreamClientInterceptor { | ||
| return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { | ||
| return streamer(appendGrpcHeadersToContext(ctx, headers), desc, cc, method, opts...) | ||
| } | ||
| } | ||
|
|
||
| func appendGrpcHeadersToContext(ctx context.Context, headers metadata.MD) context.Context { | ||
| if len(headers) == 0 { | ||
| return ctx | ||
| } | ||
|
|
||
| existing, _ := metadata.FromOutgoingContext(ctx) | ||
| return metadata.NewOutgoingContext(ctx, metadata.Join(existing, headers)) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| package suiclient | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/metadata" | ||
| ) | ||
|
|
||
| func TestParseGrpcHeaderSpecs(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| specs []string | ||
| want metadata.MD | ||
| wantErr bool | ||
| }{ | ||
| { | ||
| name: "empty", | ||
| specs: nil, | ||
| want: metadata.MD{}, | ||
| }, | ||
| { | ||
| name: "valid headers", | ||
| specs: []string{"X-API-Key=secret", "chain-route=sui-mainnet"}, | ||
| want: metadata.MD{ | ||
| "x-api-key": []string{"secret"}, | ||
| "chain-route": []string{"sui-mainnet"}, | ||
| }, | ||
| }, | ||
| { | ||
| name: "duplicate key", | ||
| specs: []string{"X-API-Key=secret", "x-api-key=second"}, | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "trims whitespace", | ||
| specs: []string{" x-api-key = secret "}, | ||
| want: metadata.MD{ | ||
| "x-api-key": []string{"secret"}, | ||
| }, | ||
| }, | ||
| { | ||
| name: "missing separator", | ||
| specs: []string{"x-api-key"}, | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "empty key", | ||
| specs: []string{"=secret"}, | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "empty value", | ||
| specs: []string{"x-api-key="}, | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "invalid key", | ||
| specs: []string{"x api key=secret"}, | ||
| wantErr: true, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got, err := parseGrpcHeaderSpecs(tt.specs) | ||
| if tt.wantErr { | ||
| require.Error(t, err) | ||
| return | ||
| } | ||
|
|
||
| require.NoError(t, err) | ||
| require.Equal(t, tt.want, got) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestGrpcHeaderInterceptorsAppendMetadata(t *testing.T) { | ||
| headers := metadata.MD{ | ||
| "x-api-key": []string{"secret"}, | ||
| "chain-route": []string{"sui-mainnet"}, | ||
| } | ||
|
|
||
| ctx := metadata.AppendToOutgoingContext(context.Background(), "existing-header", "existing-value") | ||
|
|
||
| var unaryMetadata metadata.MD | ||
| unaryInvoker := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, opts ...grpc.CallOption) error { | ||
| var ok bool | ||
| unaryMetadata, ok = metadata.FromOutgoingContext(ctx) | ||
| require.True(t, ok) | ||
| return nil | ||
| } | ||
|
|
||
| err := grpcHeaderUnaryInterceptor(headers)(ctx, "/sui.rpc.v2.LedgerService/GetCheckpoint", nil, nil, nil, unaryInvoker) | ||
| require.NoError(t, err) | ||
| require.Equal(t, []string{"existing-value"}, unaryMetadata.Get("existing-header")) | ||
| require.Equal(t, []string{"secret"}, unaryMetadata.Get("x-api-key")) | ||
| require.Equal(t, []string{"sui-mainnet"}, unaryMetadata.Get("chain-route")) | ||
|
|
||
| var streamMetadata metadata.MD | ||
| streamer := func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) { | ||
| var ok bool | ||
| streamMetadata, ok = metadata.FromOutgoingContext(ctx) | ||
| require.True(t, ok) | ||
| return nil, nil | ||
| } | ||
|
|
||
| _, err = grpcHeaderStreamInterceptor(headers)(ctx, &grpc.StreamDesc{}, nil, "/sui.rpc.v2.SubscriptionService/SubscribeCheckpoints", streamer) | ||
| require.NoError(t, err) | ||
| require.Equal(t, []string{"existing-value"}, streamMetadata.Get("existing-header")) | ||
| require.Equal(t, []string{"secret"}, streamMetadata.Get("x-api-key")) | ||
| require.Equal(t, []string{"sui-mainnet"}, streamMetadata.Get("chain-route")) | ||
| } | ||
|
|
||
| func TestGrpcHeaderDialOptions(t *testing.T) { | ||
| opts, err := GrpcHeaderDialOptions([]string{"x-api-key=secret"}) | ||
| require.NoError(t, err) | ||
| require.Len(t, opts, 2) | ||
|
|
||
| opts, err = GrpcHeaderDialOptions(nil) | ||
| require.NoError(t, err) | ||
| require.Empty(t, opts) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: I think some of this logic could be replaced by using cobra's built-in parsing.
This is an example that parses key-value pairs:
It might make more sense to put this in a the
cmd/code as well since this is related to CLI input parsing rather than Sui client code.