Skip to content
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

metadata: validate metadata keys and values #4886

Merged
merged 26 commits into from Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions internal/metadata/metadata.go
Expand Up @@ -22,6 +22,9 @@
package metadata

import (
"errors"
"strings"

"google.golang.org/grpc/metadata"
"google.golang.org/grpc/resolver"
)
Expand Down Expand Up @@ -72,3 +75,46 @@ func Set(addr resolver.Address, md metadata.MD) resolver.Address {
addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md))
return addr
}

// Validate returns an error if the input md contains invalid keys or values.
//
// if the header is not pseudo-header, there are check items:
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
// - header names contain one or more characters from this set [0-9 a-z _ - .]
menghanl marked this conversation as resolved.
Show resolved Hide resolved
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
// - if the header-name ends with a "-bin" suffix, the header-value could contain an arbitrary octet sequence. So no real validation required here.
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
// - if header-name does not end with a "-bin" suffix, header-value should only contain one or more characters from the set ( %x20-%x7E ) which includes space and printable ASCII.
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
func Validate(md metadata.MD) error {
for k, vals := range md {
// pseudo-header will be ignored
if k[0] == ':' {
continue
}
// check key, for i that saving a conversion if not using for range
Copy link
Member

Choose a reason for hiding this comment

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

I don't understand this. Why would for _, r := range(k) { be worse?

Copy link
Contributor

@menghanl menghanl Jan 14, 2022

Choose a reason for hiding this comment

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

Range is different for strings (runes vs bytes etc): http://go.dev/play/p/2B-0HiWektw
#4886 (comment)

Copy link
Member

Choose a reason for hiding this comment

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

IIUC all of these will work correctly anyway since we don't allow anything besides low ASCII, right?

for i := 0; i < len(k); i++ {
r := k[i]
if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' {
return errors.New("header key contains not 0-9a-z-_. characters")
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
}
}
if strings.HasSuffix(k, "-bin") {
continue
}
// check value
for _, val := range vals {
if hasNotPrintable(val) {
return errors.New("header val contains not printable ASCII characters")
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
return nil
}

// hasNotPrintable return true if msg contains any characters which are not in %x20-%x7E
func hasNotPrintable(msg string) bool {
// for i that saving a conversion if not using for range
for i := 0; i < len(msg); i++ {
Copy link
Member

Choose a reason for hiding this comment

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

Same question re: range.

if msg[i] < 0x20 || msg[i] > 0x7E {
return true
}
}
return false
}
27 changes: 27 additions & 0 deletions internal/metadata/metadata_test.go
Expand Up @@ -19,6 +19,8 @@
package metadata

import (
"errors"
"reflect"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -84,3 +86,28 @@ func TestSet(t *testing.T) {
})
}
}

func TestValidate(t *testing.T) {
for _, test := range []struct {
md metadata.MD
want error
}{
{
md: map[string][]string{string(rune(0x19)): {"testVal"}},
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
want: errors.New("header key contains not 0-9a-z-_. characters"),
},
{
md: map[string][]string{"test": {string(rune(0x19))}},
want: errors.New("header val contains not printable ASCII characters"),
},
{
md: map[string][]string{"test-bin": {string(rune(0x19))}},
want: nil,
},
} {
err := Validate(test.md)
if !reflect.DeepEqual(err, test.want) {
t.Errorf("validating metadata which is %v got err :%v, want err :%v", test.md, err, test.want)
}
}
}
20 changes: 19 additions & 1 deletion stream.go
Expand Up @@ -36,6 +36,7 @@ import (
"google.golang.org/grpc/internal/channelz"
"google.golang.org/grpc/internal/grpcrand"
"google.golang.org/grpc/internal/grpcutil"
imetadata "google.golang.org/grpc/internal/metadata"
iresolver "google.golang.org/grpc/internal/resolver"
"google.golang.org/grpc/internal/serviceconfig"
"google.golang.org/grpc/internal/transport"
Expand Down Expand Up @@ -164,6 +165,11 @@ func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth
}

func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
if md, _, ok := metadata.FromOutgoingContextRaw(ctx); ok {
if err := imetadata.Validate(md); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
if channelz.IsOn() {
cc.incrCallsStarted()
defer func() {
Expand Down Expand Up @@ -1446,11 +1452,20 @@ func (ss *serverStream) SetHeader(md metadata.MD) error {
if md.Len() == 0 {
return nil
}
err := imetadata.Validate(md)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
return ss.s.SetHeader(md)
}

func (ss *serverStream) SendHeader(md metadata.MD) error {
err := ss.t.WriteHeader(ss.s, md)
err := imetadata.Validate(md)
if err != nil {
return status.Error(codes.Internal, err.Error())
}

err = ss.t.WriteHeader(ss.s, md)
if ss.binlog != nil && !ss.serverHeaderBinlogged {
h, _ := ss.s.Header()
ss.binlog.Log(&binarylog.ServerHeader{
Expand All @@ -1465,6 +1480,9 @@ func (ss *serverStream) SetTrailer(md metadata.MD) {
if md.Len() == 0 {
return
}
if imetadata.Validate(md) != nil {
return
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
}
ss.s.SetTrailer(md)
}

Expand Down
117 changes: 117 additions & 0 deletions test/metadata_test.go
@@ -0,0 +1,117 @@
/*
*
* Copyright 2022 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package test

import (
"context"
"io"
"reflect"
"testing"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/internal/stubserver"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
testpb "google.golang.org/grpc/test/grpc_testing"
)

// TestInvalidMetadata test invalid metadata
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
func (s) TestInvalidMetadata(t *testing.T) {
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved

tests := []struct {
md metadata.MD
want error
}{
{
md: map[string][]string{string(rune(0x19)): {"testVal"}},
want: status.Error(codes.Internal, "header key contains not 0-9a-z-_. characters"),
},
{
md: map[string][]string{"test": {string(rune(0x19))}},
want: status.Error(codes.Internal, "header val contains not printable ASCII characters"),
},
{
md: map[string][]string{"test-bin": {string(rune(0x19))}},
want: nil,
},
}

ss := &stubserver.StubServer{
EmptyCallF: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
return &testpb.Empty{}, nil
},
FullDuplexCallF: func(stream testpb.TestService_FullDuplexCallServer) error {
for {
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
_, err := stream.Recv()
if err == io.EOF {
return nil
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
}
if err != nil {
return err
}
for _, test := range tests {
if err := stream.SetHeader(test.md); !reflect.DeepEqual(test.want, err) {
t.Errorf("call stream.SendHeader(md) validate metadata which is %v got err :%v, want err :%v", test.md, err, test.want)
}
if err := stream.SendHeader(test.md); !reflect.DeepEqual(test.want, err) {
t.Errorf("call stream.SendHeader(md) validate metadata which is %v got err :%v, want err :%v", test.md, err, test.want)
}
stream.SetTrailer(test.md)
}
err = stream.Send(&testpb.StreamingOutputCallResponse{})
if err != nil {
return err
}
}
},
}
if err := ss.Start(nil); err != nil {
t.Fatalf("Error starting ss endpoint server: %v", err)
}
defer ss.Stop()

for _, test := range tests {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

ctx = metadata.NewOutgoingContext(ctx, test.md)
if _, err := ss.Client.EmptyCall(ctx, &testpb.Empty{}); !reflect.DeepEqual(test.want, err) {
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
t.Fatalf("call ss.Client.EmptyCall() validate metadata which is %v got err :%v, want err :%v", test.md, err, test.want)
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
}
}

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
stream, err := ss.Client.FullDuplexCall(ctx, grpc.WaitForReady(true))
defer cancel()
if err != nil {
t.Fatalf("call ss.Client.FullDuplexCall(context.Background()) will success but got err :%v", err)
}
if err := stream.Send(&testpb.StreamingOutputCallRequest{}); err != nil {
t.Fatalf("call ss.Client stream Send(nil) will success but got err :%v", err)
}
if _, err := stream.Header(); err != nil {
t.Fatalf("call ss.Client stream Send(nil) will success but got err :%v", err)
}
if _, err := stream.Recv(); err != nil {
t.Fatalf("stream.Recv() = _, %v", err)
}
stream.CloseSend()
}