MSP-8974 up deps
This commit is contained in:
1 parent
0abaaf740f
commit
a0aafd93b9
602 files changed
+47724
-13295
No files matched your search
+47
@@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string {
|
||||
|
||||
// Parse parses the string representation of path template
|
||||
func Parse(tmpl string) (Compiler, error) {
|
||||
return parse(tmpl)
|
||||
}
|
||||
|
||||
// Segment is a top-level segment of a parsed path template.
|
||||
type Segment struct {
|
||||
// FieldPath is the field path bound by a variable segment, e.g. "name"
|
||||
// for "{name=projects/*}". It is empty for literal and wildcard segments.
|
||||
FieldPath string
|
||||
// Value is the literal or wildcard ("*" or "**") of a non-variable
|
||||
// segment, or the pattern of a variable segment, e.g. "projects/*" for
|
||||
// "{name=projects/*}". A variable without an explicit pattern, such as
|
||||
// "{name}", has the pattern "*".
|
||||
Value string
|
||||
}
|
||||
|
||||
// SplitTemplate parses the string representation of path template and
|
||||
// returns its top-level segments and its verb. The root template "/" has no
|
||||
// segments.
|
||||
func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) {
|
||||
t, err := parse(tmpl)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for _, s := range t.segments {
|
||||
switch s := s.(type) {
|
||||
case literal:
|
||||
if s == eof {
|
||||
continue
|
||||
}
|
||||
segments = append(segments, Segment{Value: string(s)})
|
||||
case variable:
|
||||
pattern := make([]string, 0, len(s.segments))
|
||||
for _, vs := range s.segments {
|
||||
pattern = append(pattern, vs.String())
|
||||
}
|
||||
segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")})
|
||||
default:
|
||||
segments = append(segments, Segment{Value: s.String()})
|
||||
}
|
||||
}
|
||||
return segments, t.verb, nil
|
||||
}
|
||||
|
||||
func parse(tmpl string) (template, error) {
|
||||
if !strings.HasPrefix(tmpl, "/") {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
|
||||
}
|
||||
@@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) {
|
||||
if err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
|
||||
}
|
||||
if err := expectPChars(verb); err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)}
|
||||
}
|
||||
|
||||
return template{
|
||||
segments: segs,
|
||||
|
||||
+6
@@ -38,6 +38,7 @@ go_library(
|
||||
"@org_golang_google_protobuf//reflect/protoreflect",
|
||||
"@org_golang_google_protobuf//reflect/protoregistry",
|
||||
"@org_golang_google_protobuf//types/known/durationpb",
|
||||
"@org_golang_google_protobuf//types/known/emptypb",
|
||||
"@org_golang_google_protobuf//types/known/fieldmaskpb",
|
||||
"@org_golang_google_protobuf//types/known/structpb",
|
||||
"@org_golang_google_protobuf//types/known/timestamppb",
|
||||
@@ -49,13 +50,16 @@ go_test(
|
||||
name = "runtime_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"context_internal_test.go",
|
||||
"context_test.go",
|
||||
"convert_test.go",
|
||||
"errors_test.go",
|
||||
"fieldmask_empty_object_test.go",
|
||||
"fieldmask_test.go",
|
||||
"handler_test.go",
|
||||
"marshal_httpbodyproto_test.go",
|
||||
"marshal_json_test.go",
|
||||
"marshal_jsonpb_bench_test.go",
|
||||
"marshal_jsonpb_test.go",
|
||||
"marshal_proto_test.go",
|
||||
"marshaler_registry_test.go",
|
||||
@@ -63,6 +67,7 @@ go_test(
|
||||
"mux_test.go",
|
||||
"pattern_test.go",
|
||||
"query_fuzz_test.go",
|
||||
"query_internal_test.go",
|
||||
"query_test.go",
|
||||
],
|
||||
embed = [":runtime"],
|
||||
@@ -76,6 +81,7 @@ go_test(
|
||||
"@org_golang_google_genproto_googleapis_rpc//status",
|
||||
"@org_golang_google_grpc//:grpc",
|
||||
"@org_golang_google_grpc//codes",
|
||||
"@org_golang_google_grpc//credentials/insecure",
|
||||
"@org_golang_google_grpc//health/grpc_health_v1",
|
||||
"@org_golang_google_grpc//metadata",
|
||||
"@org_golang_google_grpc//status",
|
||||
|
||||
+76
-14
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
@@ -36,6 +37,13 @@ const metadataHeaderBinarySuffix = "-Bin"
|
||||
const xForwardedFor = "X-Forwarded-For"
|
||||
const xForwardedHost = "X-Forwarded-Host"
|
||||
|
||||
// gRPC metadata keys are lower-case, so these two are appended to the pairs under their
|
||||
// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request
|
||||
// path, where it allocated a new string for a compile-time constant on every call, and lets
|
||||
// metadata.Pairs skip its own lower-casing for these keys as well.
|
||||
const xForwardedForKey = "x-forwarded-for"
|
||||
const xForwardedHostKey = "x-forwarded-host"
|
||||
|
||||
// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound
|
||||
// header isn't present. If the value is 0 the sent `context` will not have a timeout.
|
||||
var DefaultContextTimeout = 0 * time.Second
|
||||
@@ -107,6 +115,10 @@ func isValidGRPCMetadataKey(key string) bool {
|
||||
// This means 0-9 a-z _ - .
|
||||
// Only lowercase letters are valid in the wire protocol, but the client library will normalize
|
||||
// uppercase ASCII to lowercase, so uppercase ASCII is also acceptable.
|
||||
// An empty key is not a valid header name, and gRPC fails the call with one.
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode.
|
||||
for _, ch := range bytes {
|
||||
validLowercaseLetter := ch >= 'a' && ch <= 'z'
|
||||
@@ -146,7 +158,21 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
|
||||
}
|
||||
}
|
||||
var pairs []string
|
||||
// Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the
|
||||
// gateway derives below add two more. Sizing for that up front replaces the handful of
|
||||
// reallocations an empty slice goes through while it doubles.
|
||||
pairs := make([]string, 0, 2*(len(req.Header)+2))
|
||||
// For backwards-compatibility, pass through 'authorization' header with no prefix.
|
||||
// It is added before the header loop so that it is always the first
|
||||
// "authorization" value: the loop iterates a map, so a header the matcher
|
||||
// forwards under the same key (Grpc-Metadata-Authorization with the default
|
||||
// matcher) would otherwise land ahead of it in random order, and a backend
|
||||
// reading the first value would get the client-forwarded one.
|
||||
for _, val := range req.Header.Values("Authorization") {
|
||||
if isValidGRPCMetadataTextValue(val) {
|
||||
pairs = append(pairs, "authorization", val)
|
||||
}
|
||||
}
|
||||
for key, vals := range req.Header {
|
||||
key = textproto.CanonicalMIMEHeaderKey(key)
|
||||
switch key {
|
||||
@@ -156,11 +182,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
|
||||
for _, val := range vals {
|
||||
// For backwards-compatibility, pass through 'authorization' header with no prefix.
|
||||
if key == "Authorization" {
|
||||
pairs = append(pairs, "authorization", val)
|
||||
}
|
||||
if h, ok := mux.incomingHeaderMatcher(key); ok {
|
||||
// The gateway derives x-forwarded-host and x-forwarded-for below from
|
||||
// the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends
|
||||
// rely on those metadata keys for client host/IP decisions. Refuse a
|
||||
// forwarded header that the matcher strips into one of them (e.g.
|
||||
// Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value
|
||||
// in ahead of the gateway-set one.
|
||||
if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) {
|
||||
grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h)
|
||||
continue
|
||||
}
|
||||
if !isValidGRPCMetadataKey(h) {
|
||||
grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h)
|
||||
continue
|
||||
@@ -182,28 +214,52 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
}
|
||||
}
|
||||
if host := req.Header.Get(xForwardedHost); host != "" {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedHost), host)
|
||||
} else if req.Host != "" {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host)
|
||||
if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) {
|
||||
pairs = append(pairs, xForwardedHostKey, host)
|
||||
} else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) {
|
||||
pairs = append(pairs, xForwardedHostKey, req.Host)
|
||||
}
|
||||
|
||||
xff := req.Header.Values(xForwardedFor)
|
||||
// Validate each X-Forwarded-For value on its own, so that an invalid
|
||||
// client-supplied value is dropped without also dropping the remote
|
||||
// address the gateway appends.
|
||||
var xff []string
|
||||
for _, value := range req.Header.Values(xForwardedFor) {
|
||||
if isValidGRPCMetadataTextValue(value) {
|
||||
xff = append(xff, value)
|
||||
}
|
||||
}
|
||||
if addr := req.RemoteAddr; addr != "" {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) {
|
||||
xff = append(xff, remoteIP)
|
||||
}
|
||||
}
|
||||
if len(xff) > 0 {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", "))
|
||||
pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", "))
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
ctx, _ = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
md := metadata.Pairs(pairs...)
|
||||
var annotated metadata.MD
|
||||
for _, mda := range mux.metadataAnnotators {
|
||||
md = metadata.Join(md, mda(ctx, req))
|
||||
annotated = metadata.Join(annotated, mda(ctx, req))
|
||||
}
|
||||
// Annotators are the gateway's own code, so their values replace whatever
|
||||
// the request headers put under the same key. Joining them after the
|
||||
// header values would let a client send Grpc-Metadata-<key> and have its
|
||||
// value read first by a backend that trusts the annotator.
|
||||
//
|
||||
// With no annotators registered -- the default -- there is nothing to merge, and
|
||||
// metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and
|
||||
// appends every key's values into a fresh slice, so the result is an identical copy of md
|
||||
// bought with one allocation per key.
|
||||
if len(annotated) > 0 {
|
||||
for k := range annotated {
|
||||
delete(md, strings.ToLower(k))
|
||||
}
|
||||
md = metadata.Join(md, annotated)
|
||||
}
|
||||
if len(md) == 0 {
|
||||
return ctx, nil, nil
|
||||
@@ -302,10 +358,16 @@ func timeoutDecode(s string) (time.Duration, error) {
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
|
||||
}
|
||||
t, err := strconv.ParseInt(s[:size-1], 10, 64)
|
||||
t, err := strconv.ParseUint(s[:size-1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Guard against overflowing time.Duration, which is an int64 nanosecond
|
||||
// count: without this a large value wraps to a bogus (often negative)
|
||||
// deadline instead of the long timeout the client asked for.
|
||||
if t > uint64(math.MaxInt64)/uint64(d) {
|
||||
return time.Duration(math.MaxInt64), nil
|
||||
}
|
||||
return d * time.Duration(t), nil
|
||||
}
|
||||
|
||||
|
||||
+50
-17
@@ -3,6 +3,7 @@ package runtime
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// parseFloat parses a floating point value the way the proto3 JSON mapping
|
||||
// does: a decimal number, or the exact strings "Infinity", "-Infinity" and
|
||||
// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"),
|
||||
// underscore digit separators ("1_000") and alternate infinity/NaN spellings
|
||||
// ("Inf", "nan", "infinity"), none of which protojson (and so the request body
|
||||
// and backend) accept. Reject those so a value bound from a query or path
|
||||
// parameter can't differ from the same value sent in the body.
|
||||
func parseFloat(val string, bitSize int) (float64, error) {
|
||||
switch val {
|
||||
case "Infinity":
|
||||
return math.Inf(1), nil
|
||||
case "-Infinity":
|
||||
return math.Inf(-1), nil
|
||||
case "NaN":
|
||||
return math.NaN(), nil
|
||||
}
|
||||
if strings.ContainsAny(val, "xX_") {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
f, err := strconv.ParseFloat(val, bitSize)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// ParseFloat only yields Inf/NaN without an error for the alternate
|
||||
// spellings handled above; overflow returns a range error instead.
|
||||
if math.IsInf(f, 0) || math.IsNaN(f) {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Float64 converts the given string representation into representation of a floating point number into float64.
|
||||
func Float64(val string) (float64, error) {
|
||||
return strconv.ParseFloat(val, 64)
|
||||
return parseFloat(val, 64)
|
||||
}
|
||||
|
||||
// Float64Slice converts 'val' where individual floating point numbers are separated by
|
||||
@@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) {
|
||||
|
||||
// Float32 converts the given string representation of a floating point number into float32.
|
||||
func Float32(val string) (float32, error) {
|
||||
f, err := strconv.ParseFloat(val, 32)
|
||||
f, err := parseFloat(val, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) {
|
||||
|
||||
// Int64 converts the given string representation of an integer into int64.
|
||||
func Int64(val string) (int64, error) {
|
||||
return strconv.ParseInt(val, 0, 64)
|
||||
return strconv.ParseInt(val, 10, 64)
|
||||
}
|
||||
|
||||
// Int64Slice converts 'val' where individual integers are separated by
|
||||
@@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) {
|
||||
|
||||
// Int32 converts the given string representation of an integer into int32.
|
||||
func Int32(val string) (int32, error) {
|
||||
i, err := strconv.ParseInt(val, 0, 32)
|
||||
i, err := strconv.ParseInt(val, 10, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) {
|
||||
|
||||
// Uint64 converts the given string representation of an integer into uint64.
|
||||
func Uint64(val string) (uint64, error) {
|
||||
return strconv.ParseUint(val, 0, 64)
|
||||
return strconv.ParseUint(val, 10, 64)
|
||||
}
|
||||
|
||||
// Uint64Slice converts 'val' where individual integers are separated by
|
||||
@@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) {
|
||||
|
||||
// Uint32 converts the given string representation of an integer into uint32.
|
||||
func Uint32(val string) (uint32, error) {
|
||||
i, err := strconv.ParseUint(val, 0, 32)
|
||||
i, err := strconv.ParseUint(val, 10, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// Bytes converts the given string representation of a byte sequence into a slice of bytes
|
||||
// A bytes sequence is encoded in URL-safe base64 without padding
|
||||
// Bytes converts the given string representation of a byte sequence into a slice of bytes.
|
||||
// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or
|
||||
// without padding.
|
||||
func Bytes(val string) ([]byte, error) {
|
||||
b, err := base64.StdEncoding.DecodeString(val)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enc := base64.StdEncoding
|
||||
if strings.ContainsAny(val, "-_") {
|
||||
enc = base64.URLEncoding
|
||||
}
|
||||
return b, nil
|
||||
if len(val)%4 != 0 {
|
||||
enc = enc.WithPadding(base64.NoPadding)
|
||||
}
|
||||
return enc.DecodeString(val)
|
||||
}
|
||||
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe
|
||||
// base64 without padding, are separated by 'sep' into a slice of byte slices.
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or
|
||||
// URL-safe base64, are separated by 'sep' into a slice of byte slices.
|
||||
func BytesSlice(val, sep string) ([][]byte, error) {
|
||||
s := strings.Split(val, sep)
|
||||
values := make([][]byte, len(s))
|
||||
|
||||
+2
-1
@@ -134,7 +134,8 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
if s.Code() == codes.Unauthenticated {
|
||||
w.Header().Set("WWW-Authenticate", s.Message())
|
||||
// Canonical spelling, so Header.Set does not have to build one.
|
||||
w.Header().Set("Www-Authenticate", s.Message())
|
||||
}
|
||||
|
||||
buf, merr := marshaler.Marshal(respRw)
|
||||
|
||||
+52
-24
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
@@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
}
|
||||
|
||||
if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
|
||||
_, hasTypeField := v.(map[string]interface{})["@type"]
|
||||
if hasTypeField {
|
||||
queue = append(queue, fieldMaskPathItem{path: k})
|
||||
continue
|
||||
} else {
|
||||
vm, _ := v.(map[string]interface{})
|
||||
if _, hasTypeField := vm["@type"]; !hasTypeField {
|
||||
return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName())
|
||||
}
|
||||
|
||||
newPath := string(fd.FullName().Name())
|
||||
if item.path != "" {
|
||||
newPath = item.path + "." + newPath
|
||||
}
|
||||
queue = append(queue, fieldMaskPathItem{path: newPath})
|
||||
continue
|
||||
}
|
||||
|
||||
child := fieldMaskPathItem{
|
||||
@@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
queue = append(queue, child)
|
||||
}
|
||||
}
|
||||
case ok && len(m) == 0:
|
||||
fallthrough
|
||||
case len(item.path) > 0:
|
||||
// otherwise, it's a leaf node so print its path
|
||||
// otherwise, it's a leaf node (an empty object counts as one) so
|
||||
// print its path. The root has no path: an empty body such as {}
|
||||
// sets nothing, and an empty path is not a valid FieldMask path.
|
||||
fm.Paths = append(fm.Paths, item.path)
|
||||
}
|
||||
}
|
||||
@@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool {
|
||||
// passed in name and json value.
|
||||
func buildPathsBlindly(name string, in interface{}) []string {
|
||||
m, ok := in.(map[string]interface{})
|
||||
if !ok {
|
||||
if !ok || len(m) == 0 {
|
||||
return []string{name}
|
||||
}
|
||||
|
||||
// A google.protobuf.Struct/Value field carries arbitrary client JSON, so
|
||||
// its nesting depth is attacker controlled. Keep each queue entry pointing
|
||||
// at its parent and its own segment rather than carrying the full path
|
||||
// string, so a path is concatenated once at the leaf (O(depth)) instead of
|
||||
// rebuilding the growing prefix at every level (O(depth^2)). A deeply
|
||||
// nested object otherwise makes this allocate quadratically in the depth
|
||||
// while producing only a handful of paths.
|
||||
type pathNode struct {
|
||||
parent *pathNode
|
||||
segment string
|
||||
}
|
||||
type queueItem struct {
|
||||
path *pathNode
|
||||
node map[string]any
|
||||
}
|
||||
|
||||
var paths []string
|
||||
queue := []fieldMaskPathItem{{path: name, node: m}}
|
||||
queue := []queueItem{{path: &pathNode{segment: name}, node: m}}
|
||||
for len(queue) > 0 {
|
||||
cur := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
m, ok := cur.node.(map[string]interface{})
|
||||
if !ok {
|
||||
// This should never happen since we should always check that we only add
|
||||
// nodes of type map[string]interface{} to the queue.
|
||||
continue
|
||||
}
|
||||
for k, v := range m {
|
||||
if mi, ok := v.(map[string]interface{}); ok {
|
||||
queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi})
|
||||
} else {
|
||||
// This is not a struct, so there are no more levels to descend.
|
||||
curPath := cur.path + "." + k
|
||||
paths = append(paths, curPath)
|
||||
for k, v := range cur.node {
|
||||
child := &pathNode{parent: cur.path, segment: k}
|
||||
if mi, ok := v.(map[string]any); ok && len(mi) > 0 {
|
||||
queue = append(queue, queueItem{path: child, node: mi})
|
||||
continue
|
||||
}
|
||||
// No populated object remains, so there are no more levels to
|
||||
// descend. Walk back to the root to materialize the path once.
|
||||
var segments []string
|
||||
n := 0
|
||||
for p := child; p != nil; p = p.parent {
|
||||
segments = append(segments, p.segment)
|
||||
n += len(p.segment) + 1
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(n - 1)
|
||||
for i := len(segments) - 1; i >= 0; i-- {
|
||||
b.WriteString(segments[i])
|
||||
if i > 0 {
|
||||
b.WriteByte('.')
|
||||
}
|
||||
}
|
||||
paths = append(paths, b.String())
|
||||
}
|
||||
}
|
||||
return paths
|
||||
|
||||
+4
-1
@@ -210,7 +210,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
|
||||
}
|
||||
|
||||
func requestAcceptsTrailers(req *http.Request) bool {
|
||||
te := req.Header.Get("TE")
|
||||
// "Te", not "TE": Header.Get canonicalises the key it is given, and a key that is already
|
||||
// canonical is returned as is, while any other spelling costs an allocated copy on every
|
||||
// call. This one runs once per response.
|
||||
te := req.Header.Get("Te")
|
||||
return strings.Contains(strings.ToLower(te), "trailers")
|
||||
}
|
||||
|
||||
|
||||
+99
-3
@@ -5,11 +5,13 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
)
|
||||
|
||||
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
|
||||
@@ -30,6 +32,21 @@ func (*JSONPb) ContentType(_ interface{}) string {
|
||||
|
||||
// Marshal marshals "v" into JSON.
|
||||
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
|
||||
if p, ok := v.(proto.Message); ok {
|
||||
// protojson already returns a freshly allocated slice that the caller owns, so
|
||||
// routing it through a bytes.Buffer only added an allocation and a copy of the
|
||||
// whole message per call. Every unary response goes through here.
|
||||
//
|
||||
// The error is returned with a nil slice rather than whatever protojson produced
|
||||
// alongside it, matching what the bytes.Buffer path did: marshalTo returned before
|
||||
// writing anything, so a failed Marshal never handed back partial output.
|
||||
b, err := j.MarshalOptions.Marshal(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := j.marshalTo(&buf, v); err != nil {
|
||||
return nil, err
|
||||
@@ -251,18 +268,36 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
|
||||
}
|
||||
|
||||
m := make(map[string]*json.RawMessage)
|
||||
if err := d.Decode(&m); err != nil {
|
||||
var raw json.RawMessage
|
||||
if err := d.Decode(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
m := make(map[string]*json.RawMessage)
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return err
|
||||
}
|
||||
// encoding/json keeps the last value of a repeated key, while protojson
|
||||
// rejects a duplicate map key, also when two spellings convert to the
|
||||
// same key (e.g. "1" and "01"). Reject both here too.
|
||||
if k, ok := duplicateObjectKey(raw); ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen := make(map[any]struct{}, len(m))
|
||||
for k, v := range m {
|
||||
result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
|
||||
if err := result[1].Interface(); err != nil {
|
||||
return err.(error)
|
||||
}
|
||||
bk := result[0]
|
||||
if _, ok := seen[bk.Interface()]; ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen[bk.Interface()] = struct{}{}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if v == nil {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
null := json.RawMessage("null")
|
||||
v = &null
|
||||
}
|
||||
@@ -293,6 +328,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
|
||||
}
|
||||
for _, item := range sl {
|
||||
if string(item) == "null" {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
|
||||
return err
|
||||
@@ -308,11 +348,30 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
}
|
||||
switch v := repr.(type) {
|
||||
case string:
|
||||
// TODO(yugui) Should use proto.StructProperties?
|
||||
// protojson writes enums by name, so accept the name here too.
|
||||
if e, ok := rv.Interface().(protoreflect.Enum); ok {
|
||||
if ev := e.Descriptor().Values().ByName(protoreflect.Name(v)); ev != nil {
|
||||
rv.SetInt(int64(ev.Number()))
|
||||
return nil
|
||||
}
|
||||
if unmarshaler.DiscardUnknown {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value %q for enum %s", v, e.Descriptor().FullName())
|
||||
}
|
||||
return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
|
||||
case float64:
|
||||
// Enum values are int32 on the wire. A fractional or out-of-range
|
||||
// number would otherwise be silently truncated/wrapped into a bogus
|
||||
// enum here, unlike protojson which rejects it, so reject it too.
|
||||
if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 {
|
||||
return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface())
|
||||
}
|
||||
rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
|
||||
return nil
|
||||
case nil:
|
||||
// protojson leaves a null enum field unset.
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
|
||||
}
|
||||
@@ -320,6 +379,43 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
// rejectNullEnumItem returns an error when t is an enum other than
|
||||
// google.protobuf.NullValue. protojson leaves a null enum field unset, but
|
||||
// rejects null as a list item or map value of such an enum.
|
||||
func rejectNullEnumItem(t reflect.Type) error {
|
||||
e, ok := reflect.Zero(t).Interface().(protoreflect.Enum)
|
||||
if !ok || e.Descriptor().FullName() == "google.protobuf.NullValue" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value null for enum %s", e.Descriptor().FullName())
|
||||
}
|
||||
|
||||
// duplicateObjectKey returns the first key that appears more than once in the
|
||||
// JSON object in data.
|
||||
func duplicateObjectKey(data []byte) (string, bool) {
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
if t, err := d.Token(); err != nil || t != json.Delim('{') {
|
||||
return "", false
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
for d.More() {
|
||||
t, err := d.Token()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
k, _ := t.(string)
|
||||
if _, ok := seen[k]; ok {
|
||||
return k, true
|
||||
}
|
||||
seen[k] = struct{}{}
|
||||
var v json.RawMessage
|
||||
if err := d.Decode(&v); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
type protoEnum interface {
|
||||
fmt.Stringer
|
||||
EnumDescriptor() ([]byte, []int)
|
||||
|
||||
+7
@@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ReadAll drains the reader, so a call with nothing left to read has
|
||||
// to report io.EOF like the other decoders. Otherwise it decodes an
|
||||
// empty message every time, and a loop decoding until io.EOF, such as
|
||||
// the generated client streaming handlers, never terminates.
|
||||
if len(buffer) == 0 {
|
||||
return io.EOF
|
||||
}
|
||||
return marshaller.Unmarshal(buffer, value)
|
||||
})
|
||||
}
|
||||
|
||||
+12
@@ -44,6 +44,18 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out
|
||||
}
|
||||
|
||||
for _, contentTypeVal := range r.Header[contentTypeHeader] {
|
||||
// A header that is already exactly a registered media type -- "application/json",
|
||||
// which is what clients send -- needs no parsing. mime.ParseMediaType allocates a
|
||||
// parameter map even when the value carries no parameters, and it would return this
|
||||
// value unchanged, so the lookup below would be the same one.
|
||||
//
|
||||
// This is also what the Accept loop above already does: the registry is keyed by the
|
||||
// strings passed to WithMarshalerOption, and that loop matches the header value
|
||||
// against them directly.
|
||||
if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok {
|
||||
inbound = m
|
||||
break
|
||||
}
|
||||
contentType, _, err := mime.ParseMediaType(contentTypeVal)
|
||||
if err != nil {
|
||||
grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err)
|
||||
|
||||
+132
-27
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
@@ -44,7 +45,9 @@ const (
|
||||
UnescapingModeDefault = UnescapingModeLegacy
|
||||
)
|
||||
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2F)")
|
||||
// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an
|
||||
// escaped path separator has to be recognized in either spelling.
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])")
|
||||
|
||||
// A HandlerFunc handles a specific pair of path pattern and HTTP method.
|
||||
type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)
|
||||
@@ -75,6 +78,7 @@ type ServeMux struct {
|
||||
unescapingMode UnescapingMode
|
||||
writeContentLength bool
|
||||
disableChunkedEncoding bool
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// ServeMuxOption is an option that can be given to a ServeMux on construction.
|
||||
@@ -137,6 +141,19 @@ func WithDisableChunkedEncoding() ServeMuxOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least
|
||||
// one path segment when preceded by another segment. For example,
|
||||
// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still
|
||||
// provides an empty segment, so "/v3/files/" continues to match.
|
||||
//
|
||||
// This option applies to all patterns registered with the ServeMux, including
|
||||
// generated routes and routes registered with HandlePath.
|
||||
func WithStrictDeepWildcardMatching() ServeMuxOption {
|
||||
return func(mux *ServeMux) {
|
||||
mux.strictDeepWildcard = true
|
||||
}
|
||||
}
|
||||
|
||||
// SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters.
|
||||
// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be
|
||||
// done with careful consideration.
|
||||
@@ -151,24 +168,55 @@ type HeaderMatcherFunc func(string) (string, bool)
|
||||
|
||||
// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header
|
||||
// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function.
|
||||
// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
|
||||
// Other headers are not added to the gRPC metadata.
|
||||
//
|
||||
// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the
|
||||
// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an
|
||||
// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the
|
||||
// WithLegacyHeaderMatching option, to keep forwarding those headers.
|
||||
func DefaultHeaderMatcher(key string) (string, bool) {
|
||||
switch key = textproto.CanonicalMIMEHeaderKey(key); {
|
||||
case isPermanentHTTPHeader(key):
|
||||
if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) {
|
||||
return MetadataPrefix + key, true
|
||||
case strings.HasPrefix(key, MetadataHeaderPrefix):
|
||||
return key[len(MetadataHeaderPrefix):], true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the
|
||||
// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped
|
||||
// to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
|
||||
//
|
||||
// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for
|
||||
// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway.
|
||||
func LegacyHeaderMatcher(key string) (string, bool) {
|
||||
switch key = textproto.CanonicalMIMEHeaderKey(key); {
|
||||
case isPermanentHTTPHeader(key):
|
||||
return MetadataPrefix + key, true
|
||||
case strings.HasPrefix(key, MetadataHeaderPrefix):
|
||||
mdKey := key[len(MetadataHeaderPrefix):]
|
||||
// The grpcgateway- namespace is reserved for permanent HTTP headers the
|
||||
// gateway maps itself, so refuse to forward a Grpc-Metadata- header that
|
||||
// strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client
|
||||
// inject a value indistinguishable from the gateway-set grpcgateway-host.
|
||||
if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) {
|
||||
return "", false
|
||||
}
|
||||
return mdKey, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header
|
||||
// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again.
|
||||
func WithLegacyHeaderMatching() ServeMuxOption {
|
||||
return WithIncomingHeaderMatcher(LegacyHeaderMatcher)
|
||||
}
|
||||
|
||||
func defaultOutgoingHeaderMatcher(key string) (string, bool) {
|
||||
return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true
|
||||
return MetadataHeaderPrefix + key, true
|
||||
}
|
||||
|
||||
func defaultOutgoingTrailerMatcher(key string) (string, bool) {
|
||||
return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true
|
||||
return MetadataTrailerPrefix + key, true
|
||||
}
|
||||
|
||||
// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.
|
||||
@@ -376,15 +424,28 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux {
|
||||
serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher
|
||||
}
|
||||
|
||||
// Options such as WithHealthEndpointAt register handlers while the options
|
||||
// are still being applied, so they were wrapped with only the middlewares
|
||||
// configured before them. Rewrap them now that all middlewares are known.
|
||||
if len(serveMux.middlewares) > 0 {
|
||||
chain := chainMiddlewares(serveMux.middlewares)
|
||||
for _, handlers := range serveMux.handlers {
|
||||
for i := range handlers {
|
||||
handlers[i].h = chain(handlers[i].raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return serveMux
|
||||
}
|
||||
|
||||
// Handle associates "h" to the pair of HTTP method and path pattern.
|
||||
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
|
||||
raw := h
|
||||
if len(s.middlewares) > 0 {
|
||||
h = chainMiddlewares(s.middlewares)(h)
|
||||
}
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...)
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...)
|
||||
}
|
||||
|
||||
// HandlePath allows users to configure custom path handlers.
|
||||
@@ -415,11 +476,22 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// TODO(v3): remove UnescapingModeLegacy
|
||||
if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
unescapingMode := s.unescapingMode
|
||||
if unescapingMode != UnescapingModeLegacy {
|
||||
if r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
} else {
|
||||
// net/url only sets RawPath when the request path is not in its
|
||||
// default encoding. Without it, Path is all there is and it has
|
||||
// already been unescaped once, so unescaping it again while matching
|
||||
// would decode a sequence like %252F twice.
|
||||
unescapingMode = UnescapingModeLegacy
|
||||
}
|
||||
}
|
||||
|
||||
if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
|
||||
// "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a
|
||||
// canonicalised copy of any other, and this lookup happens on every request.
|
||||
if override := r.Header.Get("X-Http-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
sterr := status.Error(codes.InvalidArgument, err.Error())
|
||||
@@ -434,7 +506,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the
|
||||
// path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default
|
||||
// behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved
|
||||
if s.unescapingMode == UnescapingModeAllCharacters {
|
||||
if unescapingMode == UnescapingModeAllCharacters {
|
||||
pathComponents = encodedPathSplitter.Split(path[1:], -1)
|
||||
} else {
|
||||
pathComponents = strings.Split(path[1:], "/")
|
||||
@@ -460,20 +532,33 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
if idx == 0 {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound)
|
||||
return
|
||||
// The last component is the bare verb with nothing before it,
|
||||
// which this pattern cannot match. Other patterns still might, so
|
||||
// move on rather than ending the search with a 404.
|
||||
continue
|
||||
}
|
||||
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
// Only copy the components when the verb has to be split off the last
|
||||
// one. MatchAndEscape never mutates its input, so sharing the slice
|
||||
// across handlers is safe, and copying it per handler otherwise costs
|
||||
// len(pathComponents) allocations for every registered pattern.
|
||||
comps := pathComponents
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
if err != nil {
|
||||
// ErrNotMatch is returned once for every registered pattern the request does not
|
||||
// match, so it is by far the most common error reaching this branch. Checking it
|
||||
// first keeps errors.As off that path: its target parameter is an any, so &mse is
|
||||
// boxed onto the heap on every call -- one allocation per route a request did not
|
||||
// match, which grows with the number of registered routes.
|
||||
if errors.Is(err, ErrNotMatch) {
|
||||
continue
|
||||
}
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
@@ -495,11 +580,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Note we are not eagerly checking the request here as we want to return the
|
||||
// right HTTP status code, and we need to process the fallback candidates in
|
||||
// order to do that.
|
||||
for m, handlers := range s.handlers {
|
||||
// GET is tried first when the request is subject to path length fallback:
|
||||
// map iteration order is random, and a match for another method would
|
||||
// otherwise return 405 before the GET handler is reached.
|
||||
methods := make([]string, 0, len(s.handlers))
|
||||
if s.isPathLengthFallback(r) {
|
||||
methods = append(methods, http.MethodGet)
|
||||
}
|
||||
for m := range s.handlers {
|
||||
if m == http.MethodGet && s.isPathLengthFallback(r) {
|
||||
continue
|
||||
}
|
||||
methods = append(methods, m)
|
||||
}
|
||||
for _, m := range methods {
|
||||
if m == r.Method {
|
||||
continue
|
||||
}
|
||||
for _, h := range handlers {
|
||||
for _, h := range s.handlers[m] {
|
||||
var verb string
|
||||
patVerb := h.pat.Verb()
|
||||
|
||||
@@ -508,14 +606,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
comps := pathComponents
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
if err != nil {
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
@@ -558,12 +656,19 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp
|
||||
}
|
||||
|
||||
func (s *ServeMux) isPathLengthFallback(r *http.Request) bool {
|
||||
return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
|
||||
if s.disablePathLengthFallback || r.Method != http.MethodPost {
|
||||
return false
|
||||
}
|
||||
// Like net/http's ParseForm, ignore parameters such as charset.
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
return err == nil && mediaType == "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
pat Pattern
|
||||
h HandlerFunc
|
||||
// raw is h before middlewares were applied.
|
||||
raw HandlerFunc
|
||||
}
|
||||
|
||||
func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
|
||||
|
||||
+83
-5
@@ -26,6 +26,9 @@ func (e MalformedSequenceError) Error() string {
|
||||
type op struct {
|
||||
code utilities.OpCode
|
||||
operand int
|
||||
// multisegment is set on an OpPush that is one segment of a variable
|
||||
// spanning several segments, such as the "*" in {name=shelves/*}.
|
||||
multisegment bool
|
||||
}
|
||||
|
||||
// Pattern is a template pattern of http request paths defined in
|
||||
@@ -43,6 +46,20 @@ type Pattern struct {
|
||||
tailLen int
|
||||
// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
|
||||
verb string
|
||||
// strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one
|
||||
// remaining path component.
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// PatternOpt configures optional behavior of a Pattern.
|
||||
type PatternOpt func(*Pattern)
|
||||
|
||||
// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another
|
||||
// segment refuse to match zero path segments. For example, "/v3/files/{path=**}"
|
||||
// will not match "/v3/files". A bare "**" with nothing preceding it still matches
|
||||
// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
func WithStrictDeepWildcard() PatternOpt {
|
||||
return func(p *Pattern) { p.strictDeepWildcard = true }
|
||||
}
|
||||
|
||||
// NewPattern returns a new Pattern from the given definition values.
|
||||
@@ -51,6 +68,12 @@ type Pattern struct {
|
||||
// "version" must be 1 for now.
|
||||
// It returns an error if the given definition is invalid.
|
||||
func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) {
|
||||
return NewPatternWithOptions(version, ops, pool, verb)
|
||||
}
|
||||
|
||||
// NewPatternWithOptions is like NewPattern but additionally accepts options that modify
|
||||
// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard.
|
||||
func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) {
|
||||
if version != 1 {
|
||||
grpclog.Errorf("unsupported version: %d", version)
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
@@ -106,6 +129,15 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
}
|
||||
stack++
|
||||
// The segments of a variable are the ops pushed right before its
|
||||
// OpConcatN, so these are the ones of a multi-segment variable.
|
||||
if op.operand > 1 {
|
||||
for j := len(typedOps) - op.operand; j < len(typedOps); j++ {
|
||||
if typedOps[j].code == utilities.OpPush {
|
||||
typedOps[j].multisegment = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case utilities.OpCapture:
|
||||
if op.operand < 0 || len(pool) <= op.operand {
|
||||
grpclog.Errorf("variable name index out of bound: %d", op.operand)
|
||||
@@ -129,14 +161,18 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
|
||||
}
|
||||
typedOps = append(typedOps, op)
|
||||
}
|
||||
return Pattern{
|
||||
pat := Pattern{
|
||||
ops: typedOps,
|
||||
pool: pool,
|
||||
vars: vars,
|
||||
stacksize: maxstack,
|
||||
tailLen: tailLen,
|
||||
verb: verb,
|
||||
}, nil
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(&pat)
|
||||
}
|
||||
return pat, nil
|
||||
}
|
||||
|
||||
// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.
|
||||
@@ -152,6 +188,10 @@ func MustPattern(p Pattern, err error) Pattern {
|
||||
// matched but contained malformed escape sequences. If successful, the function
|
||||
// returns a mapping from field paths to their captured values.
|
||||
func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) {
|
||||
return p.matchAndEscape(components, verb, unescapingMode, false)
|
||||
}
|
||||
|
||||
func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) {
|
||||
if p.verb != verb {
|
||||
if p.verb != "" {
|
||||
return nil, ErrNotMatch
|
||||
@@ -165,8 +205,29 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
}
|
||||
|
||||
var pos int
|
||||
stack := make([]string, 0, p.stacksize)
|
||||
captured := make([]string, len(p.vars))
|
||||
|
||||
// Scratch space for the match. Neither backing array escapes -- only the individual
|
||||
// strings they hold are copied into the returned bindings -- so fixed-size arrays keep
|
||||
// both off the heap for the patterns generated code registers, where the stack size and
|
||||
// the variable count are single digits.
|
||||
//
|
||||
// This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per
|
||||
// registered pattern until one matches, and both allocations happened before the
|
||||
// non-match return below, so a request paid for them once for every route it did not
|
||||
// match. With a few dozen routes registered that was the largest single source of
|
||||
// allocations in routing.
|
||||
var stackArr, capturedArr [8]string
|
||||
stack := stackArr[:0]
|
||||
if p.stacksize > len(stackArr) {
|
||||
stack = make([]string, 0, p.stacksize)
|
||||
}
|
||||
var captured []string
|
||||
if n := len(p.vars); n <= len(capturedArr) {
|
||||
captured = capturedArr[:n]
|
||||
} else {
|
||||
captured = make([]string, n)
|
||||
}
|
||||
|
||||
l := len(components)
|
||||
for _, op := range p.ops {
|
||||
var err error
|
||||
@@ -184,7 +245,14 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
} else if op.code == utilities.OpPush {
|
||||
if c, err = unescape(c, unescapingMode, false); err != nil {
|
||||
// google.api.http decodes a variable spanning several segments
|
||||
// "except %2F and %2f", so a "*" in it can't add a path separator
|
||||
// to the bound value. Other escapes are decoded as for {var}.
|
||||
mode := unescapingMode
|
||||
if op.multisegment && mode == UnescapingModeAllExceptReserved {
|
||||
mode = UnescapingModeAllExceptSlash
|
||||
}
|
||||
if c, err = unescape(c, mode, op.multisegment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -196,6 +264,16 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
end -= p.tailLen
|
||||
if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end {
|
||||
// A deep wildcard ("**") is allowed to match zero path segments when it is
|
||||
// the first thing being matched in the pattern (pos == 0). But once a literal
|
||||
// or variable segment has already consumed a component, "**" needs the request
|
||||
// path to continue past that segment — it cannot succeed with nothing left to
|
||||
// consume at all (though an empty trailing segment, e.g. from a trailing slash,
|
||||
// still counts as a real component and is fine).
|
||||
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
c := strings.Join(components[pos:end], "/")
|
||||
if c, err = unescape(c, unescapingMode, true); err != nil {
|
||||
return nil, err
|
||||
|
||||
+145
-17
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -16,13 +15,41 @@ import (
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/reflect/protoregistry"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
field_mask "google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`)
|
||||
// splitMapKey splits a query parameter name of the form "field[key]" into the part before the
|
||||
// bracket and the key inside it, reporting whether the name has that shape at all.
|
||||
//
|
||||
// This replaces a FindStringSubmatch against `^(.*)\[(.*)\]$`, which ran for every query
|
||||
// parameter and cost two allocations each -- the submatch slice and the backtracker's state --
|
||||
// to answer a question that is two index operations. The returned strings are slices of the
|
||||
// caller's key, so nothing is copied; the caller rebuilds "[key]" as key[len(prefix):] rather
|
||||
// than concatenating it back together.
|
||||
//
|
||||
// The regexp is matched exactly, including two details worth spelling out:
|
||||
//
|
||||
// - The first group is greedy, so the bracket that counts is the last one before the final
|
||||
// "]". "a[b]c]" splits into "a" and "b]c", which is what LastIndexByte over everything but
|
||||
// the final byte finds.
|
||||
// - Go's regexp does not let "." match a newline and anchors ^ and $ at the ends of the text,
|
||||
// so a key containing a newline could never match the pattern no matter where the brackets
|
||||
// sat. The explicit newline check keeps that, rather than quietly starting to treat
|
||||
// "a\n[b]" as a map key.
|
||||
func splitMapKey(key string) (prefix, inner string, ok bool) {
|
||||
if len(key) < 2 || key[len(key)-1] != ']' || strings.IndexByte(key, '\n') >= 0 {
|
||||
return "", "", false
|
||||
}
|
||||
open := strings.LastIndexByte(key[:len(key)-1], '[')
|
||||
if open < 0 {
|
||||
return "", "", false
|
||||
}
|
||||
return key[:open], key[open+1 : len(key)-1], true
|
||||
}
|
||||
|
||||
var currentQueryParser QueryParameterParser = &DefaultQueryParser{}
|
||||
|
||||
@@ -44,30 +71,67 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili
|
||||
type DefaultQueryParser struct{}
|
||||
|
||||
// Parse populates "values" into "msg".
|
||||
// A value is ignored if its key starts with one of the elements in "filter".
|
||||
// A value is ignored if its key starts with one of the elements in "filter",
|
||||
// or names a field that contains one of them.
|
||||
func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
|
||||
// A field is addressable by both its proto name and its JSON name, so two
|
||||
// keys can set the same one. Record which fields have been set and refuse a
|
||||
// second key for a field, the way protojson refuses a duplicate field in a
|
||||
// body, instead of letting map iteration order pick the value that survives.
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for key, values := range values {
|
||||
if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 {
|
||||
key = match[1]
|
||||
values = append([]string{match[2]}, values...)
|
||||
fieldKey, mapKey := key, ""
|
||||
if prefix, inner, ok := splitMapKey(key); ok {
|
||||
fieldKey, mapKey = prefix, key[len(prefix):]
|
||||
values = append([]string{inner}, values...)
|
||||
}
|
||||
|
||||
msgValue := msg.ProtoReflect()
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(key, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) {
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) {
|
||||
continue
|
||||
}
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil {
|
||||
field := strings.Join(fieldPath, ".") + mapKey
|
||||
if _, ok := seen[field]; ok {
|
||||
return fmt.Errorf("duplicate field %q", field)
|
||||
}
|
||||
seen[field] = struct{}{}
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// containsFilteredField reports whether fieldPath names a field that contains
|
||||
// one of the sequences in filter, such as "id" for a path parameter bound to
|
||||
// "id.value". Setting such a field from the query, which the parser can do for
|
||||
// well-known types like wrappers and timestamps, would replace the whole
|
||||
// message and with it the value already bound from the path or body.
|
||||
func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool {
|
||||
if len(filter.Base) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
var i int
|
||||
for _, t := range fieldPath {
|
||||
code, ok := filter.Encoding[t]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
j := filter.Base[i] + code
|
||||
if len(filter.Check) <= j || filter.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PopulateFieldFromPath sets a value in a nested Protobuf structure.
|
||||
func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error {
|
||||
fieldPath := strings.Split(fieldPathString, ".")
|
||||
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value})
|
||||
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false)
|
||||
}
|
||||
|
||||
func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string {
|
||||
@@ -102,7 +166,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str
|
||||
return newFieldPath
|
||||
}
|
||||
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error {
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error {
|
||||
if len(fieldPath) < 1 {
|
||||
return errors.New("no field path")
|
||||
}
|
||||
@@ -149,6 +213,18 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin
|
||||
msgValue = msgValue.Mutable(fieldDescriptor).Message()
|
||||
}
|
||||
|
||||
// A key using the map syntax (field[key]=value) must name a map field,
|
||||
// or a repeated field of key/value messages laid out like map entries.
|
||||
// Otherwise the bracket content would be bound as if it were a regular
|
||||
// value: appended as a phantom element of a repeated field, or counted
|
||||
// as a second value for a singular one.
|
||||
if hasMapKey && !fieldDescriptor.IsMap() {
|
||||
if isKeyValueList(fieldDescriptor) {
|
||||
return populateKeyValueListField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
}
|
||||
return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name())
|
||||
}
|
||||
|
||||
switch {
|
||||
case fieldDescriptor.IsList():
|
||||
return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
@@ -205,6 +281,48 @@ func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protorefl
|
||||
return nil
|
||||
}
|
||||
|
||||
// isKeyValueList reports whether fieldDescriptor is a repeated message field
|
||||
// whose message has exactly a singular "key" and a singular "value" field.
|
||||
// Such a field is shaped like a map entry list, but can hold more than one
|
||||
// value for a key.
|
||||
func isKeyValueList(fieldDescriptor protoreflect.FieldDescriptor) bool {
|
||||
if !fieldDescriptor.IsList() || fieldDescriptor.Message() == nil {
|
||||
return false
|
||||
}
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
if fields.Len() != 2 {
|
||||
return false
|
||||
}
|
||||
key, value := fields.ByName("key"), fields.ByName("value")
|
||||
return key != nil && key.Cardinality() != protoreflect.Repeated &&
|
||||
value != nil && value.Cardinality() != protoreflect.Repeated
|
||||
}
|
||||
|
||||
// populateKeyValueListField appends one key/value message to list for each of
|
||||
// values[1:], all with the key values[0].
|
||||
func populateKeyValueListField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error {
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
keyField, valueField := fields.ByName("key"), fields.ByName("value")
|
||||
|
||||
key, err := parseField(keyField, values[0])
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
|
||||
for _, value := range values[1:] {
|
||||
v, err := parseField(valueField, value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
entry := list.NewElement()
|
||||
entry.Message().Set(keyField, key)
|
||||
entry.Message().Set(valueField, v)
|
||||
list.Append(entry)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) {
|
||||
switch fieldDescriptor.Kind() {
|
||||
case protoreflect.BoolKind:
|
||||
@@ -224,7 +342,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
// Look for enum by name
|
||||
v := enum.Descriptor().Values().ByName(protoreflect.Name(value))
|
||||
if v == nil {
|
||||
i, err := strconv.Atoi(value)
|
||||
i, err := strconv.ParseInt(value, 10, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value)
|
||||
}
|
||||
@@ -259,13 +377,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
}
|
||||
return protoreflect.ValueOfUint64(v), nil
|
||||
case protoreflect.FloatKind:
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
v, err := parseFloat(value, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
return protoreflect.ValueOfFloat32(float32(v)), nil
|
||||
case protoreflect.DoubleKind:
|
||||
v, err := strconv.ParseFloat(value, 64)
|
||||
v, err := parseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -305,13 +423,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
}
|
||||
msg = durationpb.New(d)
|
||||
case "google.protobuf.DoubleValue":
|
||||
v, err := strconv.ParseFloat(value, 64)
|
||||
v, err := parseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = wrapperspb.Double(v)
|
||||
case "google.protobuf.FloatValue":
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
v, err := parseFloat(value, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -356,7 +474,9 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
msg = wrapperspb.Bytes(v)
|
||||
case "google.protobuf.FieldMask":
|
||||
fm := &field_mask.FieldMask{}
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
if value != "" {
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
}
|
||||
msg = fm
|
||||
case "google.protobuf.Value":
|
||||
var v structpb.Value
|
||||
@@ -370,6 +490,14 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = &v
|
||||
case "google.protobuf.Empty":
|
||||
// An Empty carries nothing, so the only thing the value can say is that the
|
||||
// field is present. Accept the two spellings of "no content" and reject
|
||||
// anything else, rather than silently ignoring it.
|
||||
if value != "" && value != "{}" {
|
||||
return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value)
|
||||
}
|
||||
msg = &emptypb.Empty{}
|
||||
default:
|
||||
return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName()))
|
||||
}
|
||||
|
||||
+12
-4
@@ -72,6 +72,7 @@ func (n node) children(seqs [][]int) []*node {
|
||||
if lastVal == seqs[i][n.col+1] {
|
||||
continue
|
||||
}
|
||||
lastVal = seqs[i][n.col+1]
|
||||
last.right = i
|
||||
last = &node{
|
||||
row: i,
|
||||
@@ -156,6 +157,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
|
||||
var i int
|
||||
for _, t := range seq {
|
||||
// A sequence ending at this node is already a prefix of seq, even if
|
||||
// a longer sequence shares the path and the walk could carry on.
|
||||
if da.hasTerminator(i) {
|
||||
return true
|
||||
}
|
||||
code, ok := da.Encoding[t]
|
||||
if !ok {
|
||||
break
|
||||
@@ -166,9 +172,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return da.hasTerminator(i)
|
||||
}
|
||||
|
||||
// hasTerminator reports whether a sequence in the DoubleArray ends at node i.
|
||||
func (da *DoubleArray) hasTerminator(i int) bool {
|
||||
j := da.Base[i] + len(da.Encoding)
|
||||
if len(da.Check) <= j || da.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return j < len(da.Check) && da.Check[j] == i+1
|
||||
}
|
||||
Reference in new issue
Block a user