/
decoder.go
447 lines (400 loc) · 13.4 KB
/
decoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright 2018 Istio 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 yaml
import (
"errors"
"fmt"
"math"
"time"
"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/gogo/protobuf/types"
multierror "github.com/hashicorp/go-multierror"
"istio.io/api/policy/v1beta1"
"istio.io/istio/mixer/pkg/attribute"
"istio.io/istio/mixer/pkg/protobuf/yaml/wire"
)
type (
// Decoder transforms protobuf-encoded bytes to attribute values.
Decoder struct {
resolver Resolver
fields map[wire.Number]*descriptor.FieldDescriptorProto
}
)
// NewDecoder creates a decoder specific to a dynamic proto descriptor.
// Additionally, it takes as input an optional field mask to avoid decoding
// unused field values. Field mask is keyed by the message proto field names.
// A nil field mask implies all fields are decoded.
// This decoder is specialized to a single-level proto schema (no nested field dereferences
// in the resulting output).
func NewDecoder(resolver Resolver, msgName string, fieldMask map[string]bool) *Decoder {
message := resolver.ResolveMessage(msgName)
fields := make(map[wire.Number]*descriptor.FieldDescriptorProto)
for _, f := range message.Field {
if fieldMask == nil || fieldMask[f.GetName()] {
fields[f.GetNumber()] = f
}
}
return &Decoder{
resolver: resolver,
fields: fields,
}
}
// Decode function parses wire-encoded bytes to attribute values. The keys are field names
// in the message specified by the field mask.
// Attribute prefix is appended to the field names in the output attribute bag.
func (d *Decoder) Decode(b []byte, out *attribute.MutableBag, attrPrefix string) error {
visitor := &decodeVisitor{
decoder: d,
out: out,
attrPrefix: attrPrefix,
}
for len(b) > 0 {
_, _, n := wire.ConsumeField(visitor, b)
if n < 0 {
return wire.ParseError(n)
}
b = b[n:]
}
return visitor.err
}
type decodeVisitor struct {
decoder *Decoder
out *attribute.MutableBag
attrPrefix string
err error
}
func (dv *decodeVisitor) setValue(f *descriptor.FieldDescriptorProto, val interface{}) {
name := dv.attrPrefix + f.GetName()
if f.IsRepeated() {
var arr *attribute.List
old, ok := dv.out.Get(name)
if !ok {
arr = attribute.NewList(name)
dv.out.Set(name, arr)
} else {
arr = old.(*attribute.List)
}
arr.Append(val)
} else {
dv.out.Set(name, val)
}
}
// varint coalesces all primitive integers and enums to int64 type
func (dv *decodeVisitor) Varint(n wire.Number, v uint64) {
f, exists := dv.decoder.fields[n]
if !exists {
return
}
var val interface{}
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
val = wire.DecodeBool(v)
case descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_UINT64:
val = int64(v)
case descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64:
val = wire.DecodeZigZag(v)
case descriptor.FieldDescriptorProto_TYPE_ENUM:
val = int64(v)
default:
dv.err = multierror.Append(dv.err, fmt.Errorf("unexpected field type %q for varint encoding", f.GetType()))
return
}
dv.setValue(f, val)
}
func (dv *decodeVisitor) Fixed32(n wire.Number, v uint32) {
f, exists := dv.decoder.fields[n]
if !exists {
return
}
var val interface{}
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
val = int64(v)
case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
val = int64(v)
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
val = float64(math.Float32frombits(v))
default:
dv.err = multierror.Append(dv.err, fmt.Errorf("unexpected field type %q for fixed32 encoding", f.GetType()))
return
}
dv.setValue(f, val)
}
func (dv *decodeVisitor) Fixed64(n wire.Number, v uint64) {
f, exists := dv.decoder.fields[n]
if !exists {
return
}
var val interface{}
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_FIXED64:
val = int64(v)
case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
val = int64(v)
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
val = math.Float64frombits(v)
default:
dv.err = multierror.Append(dv.err, fmt.Errorf("unexpected field type %q for fixed64 encoding", f.GetType()))
return
}
dv.setValue(f, val)
}
type mapVisitor struct {
desc *descriptor.DescriptorProto
key, value string
}
// TODO: only string maps are supported since mixer's IL only supports string maps
func (mv *mapVisitor) Varint(wire.Number, uint64) {}
func (mv *mapVisitor) Fixed32(wire.Number, uint32) {}
func (mv *mapVisitor) Fixed64(wire.Number, uint64) {}
func (mv *mapVisitor) Bytes(n wire.Number, v []byte) {
switch n {
case mv.desc.Field[0].GetNumber():
mv.key = string(v)
case mv.desc.Field[1].GetNumber():
mv.value = string(v)
}
}
func (dv *decodeVisitor) Bytes(n wire.Number, v []byte) {
f, exists := dv.decoder.fields[n]
if !exists {
return
}
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_STRING:
dv.setValue(f, string(v))
return
case descriptor.FieldDescriptorProto_TYPE_BYTES:
dv.setValue(f, v)
return
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
name := dv.attrPrefix + f.GetName()
if isMap(dv.decoder.resolver, f) {
// validate proto type to be map<string, string>
mapType := dv.decoder.resolver.ResolveMessage(f.GetTypeName())
if mapType == nil || len(mapType.Field) < 2 {
dv.err = multierror.Append(dv.err, fmt.Errorf("unresolved or incorrect map field type %q", f.GetName()))
return
}
if mapType.Field[0].GetType() != descriptor.FieldDescriptorProto_TYPE_STRING ||
mapType.Field[1].GetType() != descriptor.FieldDescriptorProto_TYPE_STRING {
dv.err = multierror.Append(dv.err, errors.New("only map<string, string> is supported in expressions"))
return
}
// translate map<X, Y> proto3 field type to record Mixer type (map[string]string)
var m attribute.StringMap
val, ok := dv.out.Get(name)
if !ok {
m = attribute.NewStringMap(name)
} else {
m = val.(attribute.StringMap)
}
visitor := &mapVisitor{desc: mapType}
for len(v) > 0 {
_, _, m := wire.ConsumeField(visitor, v)
if m < 0 {
dv.err = multierror.Append(dv.err, fmt.Errorf("failed to parse map field %q: %v", f.GetName(), wire.ParseError(m)))
return
}
v = v[m:]
}
m.Set(visitor.key, visitor.value)
dv.out.Set(name, m)
return
}
// parse the entirety of the message recursively for value types
if _, ok := valueResolver.descriptors[f.GetTypeName()]; ok && !f.IsRepeated() {
decoder := NewDecoder(valueResolver, f.GetTypeName(), nil)
inner := attribute.GetMutableBag(nil)
defer inner.Done()
if err := decoder.Decode(v, inner, ""); err != nil {
dv.err = multierror.Append(dv.err, fmt.Errorf("failed to decode field %q: %v", f.GetName(), err))
return
}
switch f.GetTypeName() {
case ".istio.policy.v1beta1.Value":
// pop oneof inner value from the bag to the field value
names := inner.Names()
if len(names) == 1 {
if val, ok := inner.Get(names[0]); ok {
dv.out.Set(name, val)
}
}
case ".istio.policy.v1beta1.IPAddress",
".istio.policy.v1beta1.Duration",
".istio.policy.v1beta1.DNSName":
if value, ok := inner.Get("value"); ok {
dv.out.Set(name, value)
}
case ".google.protobuf.Duration":
seconds, secondsOk := inner.Get("seconds")
nanos, nanosOk := inner.Get("nanos")
if secondsOk || nanosOk {
// must default to int64 for casting to work
if seconds == nil {
seconds = int64(0)
}
if nanos == nil {
nanos = int64(0)
}
dv.out.Set(name, time.Duration(seconds.(int64))*time.Second+time.Duration(nanos.(int64)))
}
}
return
}
// TODO: implement sub-message decoding
return
}
// fallback into packed repeated encoding
if f.IsRepeated() && (f.IsPacked() || f.IsPacked3()) {
var m int
for len(v) > 0 {
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_BOOL,
descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_UINT64,
descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64,
descriptor.FieldDescriptorProto_TYPE_ENUM:
var elt uint64
elt, m = wire.ConsumeVarint(v)
if m < 0 {
dv.err = multierror.Append(dv.err, fmt.Errorf("failed to parse packed varint field %q", f.GetName()))
return
}
dv.Varint(n, elt)
case descriptor.FieldDescriptorProto_TYPE_FIXED32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_FLOAT:
var elt uint32
elt, m = wire.ConsumeFixed32(v)
if m < 0 {
dv.err = multierror.Append(dv.err, fmt.Errorf("failed to parse packed fixed32 field %q", f.GetName()))
return
}
dv.Fixed32(n, elt)
case descriptor.FieldDescriptorProto_TYPE_FIXED64,
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
descriptor.FieldDescriptorProto_TYPE_DOUBLE:
var elt uint64
elt, m = wire.ConsumeFixed64(v)
if m < 0 {
dv.err = multierror.Append(dv.err, fmt.Errorf("failed to parse packed fixed64 field %q", f.GetName()))
return
}
dv.Fixed64(n, elt)
default:
dv.err = multierror.Append(dv.err, fmt.Errorf("unexpected field type %q for packed repeated bytes encoding", f.GetType()))
return
}
v = v[m:]
}
return
}
dv.err = multierror.Append(dv.err, fmt.Errorf("unexpected field type %q for bytes encoding", f.GetType()))
}
type valueTypeResolver struct {
descriptors map[string]*descriptor.DescriptorProto
}
func getDescriptorProto(msg descriptor.Message) *descriptor.DescriptorProto {
_, desc := descriptor.ForMessage(msg)
return desc
}
func newValueTypeResolver() *valueTypeResolver {
out := &valueTypeResolver{
descriptors: map[string]*descriptor.DescriptorProto{
".istio.policy.v1beta1.Value": getDescriptorProto(&v1beta1.Value{}),
".istio.policy.v1beta1.IPAddress": getDescriptorProto(&v1beta1.IPAddress{}),
".istio.policy.v1beta1.Duration": getDescriptorProto(&v1beta1.Duration{}),
".istio.policy.v1beta1.TimeStamp": getDescriptorProto(&v1beta1.TimeStamp{}),
".istio.policy.v1beta1.DNSName": getDescriptorProto(&v1beta1.DNSName{}),
".google.protobuf.Duration": getDescriptorProto(&types.Duration{}),
".google.protobuf.Timestamp": getDescriptorProto(&types.Timestamp{}),
},
}
return out
}
func (vtr *valueTypeResolver) ResolveMessage(msg string) *descriptor.DescriptorProto {
return vtr.descriptors[msg]
}
func (vtr *valueTypeResolver) ResolveEnum(string) *descriptor.EnumDescriptorProto {
return nil
}
func (vtr *valueTypeResolver) ResolveService(string) (*descriptor.ServiceDescriptorProto, string) {
return nil, ""
}
var (
valueResolver = newValueTypeResolver()
)
// DecodeType converts protobuf types to mixer's IL types.
// Note that due to absence of corresponding types for a variety of concrete values produced by the decoder,
// the returned value may be an unspecified type.
func DecodeType(resolver Resolver, desc *descriptor.FieldDescriptorProto) v1beta1.ValueType {
if desc.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
fieldType := resolver.ResolveMessage(desc.GetTypeName())
if fieldType != nil && len(fieldType.Field) == 2 &&
fieldType.GetOptions().GetMapEntry() &&
fieldType.Field[0].GetType() == descriptor.FieldDescriptorProto_TYPE_STRING &&
fieldType.Field[1].GetType() == descriptor.FieldDescriptorProto_TYPE_STRING {
return v1beta1.STRING_MAP
}
if desc.IsRepeated() {
return v1beta1.VALUE_TYPE_UNSPECIFIED
}
switch desc.GetTypeName() {
case ".istio.policy.v1beta1.Value":
return v1beta1.VALUE_TYPE_UNSPECIFIED
case ".istio.policy.v1beta1.IPAddress":
return v1beta1.IP_ADDRESS
case ".istio.policy.v1beta1.Duration", ".google.protobuf.Duration":
return v1beta1.DURATION
case ".istio.policy.v1beta1.TimeStamp", ".google.protobuf.Timestamp":
return v1beta1.TIMESTAMP
case ".istio.policy.v1beta1.DNSName":
return v1beta1.DNS_NAME
}
}
// array types are missing
if desc.IsRepeated() {
return v1beta1.VALUE_TYPE_UNSPECIFIED
}
switch desc.GetType() {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
return v1beta1.BOOL
case descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_UINT64,
descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64,
descriptor.FieldDescriptorProto_TYPE_ENUM,
descriptor.FieldDescriptorProto_TYPE_FIXED32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_FIXED64,
descriptor.FieldDescriptorProto_TYPE_SFIXED64:
return v1beta1.INT64
case descriptor.FieldDescriptorProto_TYPE_FLOAT,
descriptor.FieldDescriptorProto_TYPE_DOUBLE:
return v1beta1.DOUBLE
case descriptor.FieldDescriptorProto_TYPE_STRING:
return v1beta1.STRING
}
return v1beta1.VALUE_TYPE_UNSPECIFIED
}