| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package baggage // import "go.opentelemetry.io/otel/baggage" |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"net/url" |
| 10 |
"strings" |
| 11 |
"unicode/utf8" |
| 12 |
|
| 13 |
"go.opentelemetry.io/otel/internal/baggage" |
| 14 |
) |
| 15 |
|
| 16 |
const ( |
| 17 |
maxMembers = 64 |
| 18 |
maxBytesPerBaggageString = 8192 |
| 19 |
|
| 20 |
listDelimiter = "," |
| 21 |
keyValueDelimiter = "=" |
| 22 |
propertyDelimiter = ";" |
| 23 |
) |
| 24 |
|
| 25 |
var ( |
| 26 |
errInvalidKey = errors.New("invalid key") |
| 27 |
errInvalidValue = errors.New("invalid value") |
| 28 |
errInvalidProperty = errors.New("invalid baggage list-member property") |
| 29 |
errInvalidMember = errors.New("invalid baggage list-member") |
| 30 |
errMemberNumber = errors.New("too many list-members in baggage-string") |
| 31 |
errBaggageBytes = errors.New("baggage-string too large") |
| 32 |
) |
| 33 |
|
| 34 |
// Property is an additional metadata entry for a baggage list-member. |
| 35 |
type Property struct { |
| 36 |
key, value string |
| 37 |
|
| 38 |
// hasValue indicates if a zero-value value means the property does not |
| 39 |
// have a value or if it was the zero-value. |
| 40 |
hasValue bool |
| 41 |
} |
| 42 |
|
| 43 |
// NewKeyProperty returns a new Property for key. |
| 44 |
// |
| 45 |
// The passed key must be valid, non-empty UTF-8 string. |
| 46 |
// If key is invalid, an error will be returned. |
| 47 |
// However, the specific Propagators that are used to transmit baggage entries across |
| 48 |
// component boundaries may impose their own restrictions on Property key. |
| 49 |
// For example, the W3C Baggage specification restricts the Property keys to strings that |
| 50 |
// satisfy the token definition from RFC7230, Section 3.2.6. |
| 51 |
// For maximum compatibility, alphanumeric value are strongly recommended to be used as Property key. |
| 52 |
func NewKeyProperty(key string) (Property, error) { |
| 53 |
if !validateBaggageName(key) { |
| 54 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) |
| 55 |
} |
| 56 |
|
| 57 |
p := Property{key: key} |
| 58 |
return p, nil |
| 59 |
} |
| 60 |
|
| 61 |
// NewKeyValueProperty returns a new Property for key with value. |
| 62 |
// |
| 63 |
// The passed key must be compliant with W3C Baggage specification. |
| 64 |
// The passed value must be percent-encoded as defined in W3C Baggage specification. |
| 65 |
// |
| 66 |
// Notice: Consider using [NewKeyValuePropertyRaw] instead |
| 67 |
// that does not require percent-encoding of the value. |
| 68 |
func NewKeyValueProperty(key, value string) (Property, error) { |
| 69 |
if !validateKey(key) { |
| 70 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) |
| 71 |
} |
| 72 |
|
| 73 |
if !validateValue(value) { |
| 74 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value) |
| 75 |
} |
| 76 |
decodedValue, err := url.PathUnescape(value) |
| 77 |
if err != nil { |
| 78 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value) |
| 79 |
} |
| 80 |
return NewKeyValuePropertyRaw(key, decodedValue) |
| 81 |
} |
| 82 |
|
| 83 |
// NewKeyValuePropertyRaw returns a new Property for key with value. |
| 84 |
// |
| 85 |
// The passed key must be valid, non-empty UTF-8 string. |
| 86 |
// The passed value must be valid UTF-8 string. |
| 87 |
// However, the specific Propagators that are used to transmit baggage entries across |
| 88 |
// component boundaries may impose their own restrictions on Property key. |
| 89 |
// For example, the W3C Baggage specification restricts the Property keys to strings that |
| 90 |
// satisfy the token definition from RFC7230, Section 3.2.6. |
| 91 |
// For maximum compatibility, alphanumeric value are strongly recommended to be used as Property key. |
| 92 |
func NewKeyValuePropertyRaw(key, value string) (Property, error) { |
| 93 |
if !validateBaggageName(key) { |
| 94 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) |
| 95 |
} |
| 96 |
if !validateBaggageValue(value) { |
| 97 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value) |
| 98 |
} |
| 99 |
|
| 100 |
p := Property{ |
| 101 |
key: key, |
| 102 |
value: value, |
| 103 |
hasValue: true, |
| 104 |
} |
| 105 |
return p, nil |
| 106 |
} |
| 107 |
|
| 108 |
func newInvalidProperty() Property { |
| 109 |
return Property{} |
| 110 |
} |
| 111 |
|
| 112 |
// parseProperty attempts to decode a Property from the passed string. It |
| 113 |
// returns an error if the input is invalid according to the W3C Baggage |
| 114 |
// specification. |
| 115 |
func parseProperty(property string) (Property, error) { |
| 116 |
if property == "" { |
| 117 |
return newInvalidProperty(), nil |
| 118 |
} |
| 119 |
|
| 120 |
p, ok := parsePropertyInternal(property) |
| 121 |
if !ok { |
| 122 |
return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidProperty, property) |
| 123 |
} |
| 124 |
|
| 125 |
return p, nil |
| 126 |
} |
| 127 |
|
| 128 |
// validate ensures p conforms to the W3C Baggage specification, returning an |
| 129 |
// error otherwise. |
| 130 |
func (p Property) validate() error { |
| 131 |
errFunc := func(err error) error { |
| 132 |
return fmt.Errorf("invalid property: %w", err) |
| 133 |
} |
| 134 |
|
| 135 |
if !validateBaggageName(p.key) { |
| 136 |
return errFunc(fmt.Errorf("%w: %q", errInvalidKey, p.key)) |
| 137 |
} |
| 138 |
if !p.hasValue && p.value != "" { |
| 139 |
return errFunc(errors.New("inconsistent value")) |
| 140 |
} |
| 141 |
if p.hasValue && !validateBaggageValue(p.value) { |
| 142 |
return errFunc(fmt.Errorf("%w: %q", errInvalidValue, p.value)) |
| 143 |
} |
| 144 |
return nil |
| 145 |
} |
| 146 |
|
| 147 |
// Key returns the Property key. |
| 148 |
func (p Property) Key() string { |
| 149 |
return p.key |
| 150 |
} |
| 151 |
|
| 152 |
// Value returns the Property value. Additionally, a boolean value is returned |
| 153 |
// indicating if the returned value is the empty if the Property has a value |
| 154 |
// that is empty or if the value is not set. |
| 155 |
func (p Property) Value() (string, bool) { |
| 156 |
return p.value, p.hasValue |
| 157 |
} |
| 158 |
|
| 159 |
// String encodes Property into a header string compliant with the W3C Baggage |
| 160 |
// specification. |
| 161 |
// It would return empty string if the key is invalid with the W3C Baggage |
| 162 |
// specification. This could happen for a UTF-8 key, as it may contain |
| 163 |
// invalid characters. |
| 164 |
func (p Property) String() string { |
| 165 |
// W3C Baggage specification does not allow percent-encoded keys. |
| 166 |
if !validateKey(p.key) { |
| 167 |
return "" |
| 168 |
} |
| 169 |
|
| 170 |
if p.hasValue { |
| 171 |
return fmt.Sprintf("%s%s%v", p.key, keyValueDelimiter, valueEscape(p.value)) |
| 172 |
} |
| 173 |
return p.key |
| 174 |
} |
| 175 |
|
| 176 |
type properties []Property |
| 177 |
|
| 178 |
func fromInternalProperties(iProps []baggage.Property) properties { |
| 179 |
if len(iProps) == 0 { |
| 180 |
return nil |
| 181 |
} |
| 182 |
|
| 183 |
props := make(properties, len(iProps)) |
| 184 |
for i, p := range iProps { |
| 185 |
props[i] = Property{ |
| 186 |
key: p.Key, |
| 187 |
value: p.Value, |
| 188 |
hasValue: p.HasValue, |
| 189 |
} |
| 190 |
} |
| 191 |
return props |
| 192 |
} |
| 193 |
|
| 194 |
func (p properties) asInternal() []baggage.Property { |
| 195 |
if len(p) == 0 { |
| 196 |
return nil |
| 197 |
} |
| 198 |
|
| 199 |
iProps := make([]baggage.Property, len(p)) |
| 200 |
for i, prop := range p { |
| 201 |
iProps[i] = baggage.Property{ |
| 202 |
Key: prop.key, |
| 203 |
Value: prop.value, |
| 204 |
HasValue: prop.hasValue, |
| 205 |
} |
| 206 |
} |
| 207 |
return iProps |
| 208 |
} |
| 209 |
|
| 210 |
func (p properties) Copy() properties { |
| 211 |
if len(p) == 0 { |
| 212 |
return nil |
| 213 |
} |
| 214 |
|
| 215 |
props := make(properties, len(p)) |
| 216 |
copy(props, p) |
| 217 |
return props |
| 218 |
} |
| 219 |
|
| 220 |
// validate ensures each Property in p conforms to the W3C Baggage |
| 221 |
// specification, returning an error otherwise. |
| 222 |
func (p properties) validate() error { |
| 223 |
for _, prop := range p { |
| 224 |
if err := prop.validate(); err != nil { |
| 225 |
return err |
| 226 |
} |
| 227 |
} |
| 228 |
return nil |
| 229 |
} |
| 230 |
|
| 231 |
// String encodes properties into a header string compliant with the W3C Baggage |
| 232 |
// specification. |
| 233 |
func (p properties) String() string { |
| 234 |
props := make([]string, 0, len(p)) |
| 235 |
for _, prop := range p { |
| 236 |
s := prop.String() |
| 237 |
|
| 238 |
// Ignored empty properties. |
| 239 |
if s != "" { |
| 240 |
props = append(props, s) |
| 241 |
} |
| 242 |
} |
| 243 |
return strings.Join(props, propertyDelimiter) |
| 244 |
} |
| 245 |
|
| 246 |
// Member is a list-member of a baggage-string as defined by the W3C Baggage |
| 247 |
// specification. |
| 248 |
type Member struct { |
| 249 |
key, value string |
| 250 |
properties properties |
| 251 |
|
| 252 |
// hasData indicates whether the created property contains data or not. |
| 253 |
// Properties that do not contain data are invalid with no other check |
| 254 |
// required. |
| 255 |
hasData bool |
| 256 |
} |
| 257 |
|
| 258 |
// NewMember returns a new Member from the passed arguments. |
| 259 |
// |
| 260 |
// The passed key must be compliant with W3C Baggage specification. |
| 261 |
// The passed value must be percent-encoded as defined in W3C Baggage specification. |
| 262 |
// |
| 263 |
// Notice: Consider using [NewMemberRaw] instead |
| 264 |
// that does not require percent-encoding of the value. |
| 265 |
func NewMember(key, value string, props ...Property) (Member, error) { |
| 266 |
if !validateKey(key) { |
| 267 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) |
| 268 |
} |
| 269 |
|
| 270 |
if !validateValue(value) { |
| 271 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) |
| 272 |
} |
| 273 |
decodedValue, err := url.PathUnescape(value) |
| 274 |
if err != nil { |
| 275 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) |
| 276 |
} |
| 277 |
return NewMemberRaw(key, decodedValue, props...) |
| 278 |
} |
| 279 |
|
| 280 |
// NewMemberRaw returns a new Member from the passed arguments. |
| 281 |
// |
| 282 |
// The passed key must be valid, non-empty UTF-8 string. |
| 283 |
// The passed value must be valid UTF-8 string. |
| 284 |
// However, the specific Propagators that are used to transmit baggage entries across |
| 285 |
// component boundaries may impose their own restrictions on baggage key. |
| 286 |
// For example, the W3C Baggage specification restricts the baggage keys to strings that |
| 287 |
// satisfy the token definition from RFC7230, Section 3.2.6. |
| 288 |
// For maximum compatibility, alphanumeric value are strongly recommended to be used as baggage key. |
| 289 |
func NewMemberRaw(key, value string, props ...Property) (Member, error) { |
| 290 |
m := Member{ |
| 291 |
key: key, |
| 292 |
value: value, |
| 293 |
properties: properties(props).Copy(), |
| 294 |
hasData: true, |
| 295 |
} |
| 296 |
if err := m.validate(); err != nil { |
| 297 |
return newInvalidMember(), err |
| 298 |
} |
| 299 |
return m, nil |
| 300 |
} |
| 301 |
|
| 302 |
func newInvalidMember() Member { |
| 303 |
return Member{} |
| 304 |
} |
| 305 |
|
| 306 |
// parseMember attempts to decode a Member from the passed string. It returns |
| 307 |
// an error if the input is invalid according to the W3C Baggage |
| 308 |
// specification. |
| 309 |
func parseMember(member string) (Member, error) { |
| 310 |
var props properties |
| 311 |
keyValue, properties, found := strings.Cut(member, propertyDelimiter) |
| 312 |
if found { |
| 313 |
// Parse the member properties. |
| 314 |
for pStr := range strings.SplitSeq(properties, propertyDelimiter) { |
| 315 |
p, err := parseProperty(pStr) |
| 316 |
if err != nil { |
| 317 |
return newInvalidMember(), err |
| 318 |
} |
| 319 |
props = append(props, p) |
| 320 |
} |
| 321 |
} |
| 322 |
// Parse the member key/value pair. |
| 323 |
|
| 324 |
// Take into account a value can contain equal signs (=). |
| 325 |
k, v, found := strings.Cut(keyValue, keyValueDelimiter) |
| 326 |
if !found { |
| 327 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member) |
| 328 |
} |
| 329 |
// "Leading and trailing whitespaces are allowed but MUST be trimmed |
| 330 |
// when converting the header into a data structure." |
| 331 |
key := strings.TrimSpace(k) |
| 332 |
if !validateKey(key) { |
| 333 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) |
| 334 |
} |
| 335 |
|
| 336 |
rawVal := strings.TrimSpace(v) |
| 337 |
if !validateValue(rawVal) { |
| 338 |
return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, v) |
| 339 |
} |
| 340 |
|
| 341 |
// Decode a percent-encoded value. |
| 342 |
unescapeVal, err := url.PathUnescape(rawVal) |
| 343 |
if err != nil { |
| 344 |
return newInvalidMember(), fmt.Errorf("%w: %w", errInvalidValue, err) |
| 345 |
} |
| 346 |
|
| 347 |
value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) |
| 348 |
return Member{key: key, value: value, properties: props, hasData: true}, nil |
| 349 |
} |
| 350 |
|
| 351 |
// replaceInvalidUTF8Sequences replaces invalid UTF-8 sequences with '�'. |
| 352 |
func replaceInvalidUTF8Sequences(c int, unescapeVal string) string { |
| 353 |
if utf8.ValidString(unescapeVal) { |
| 354 |
return unescapeVal |
| 355 |
} |
| 356 |
// W3C baggage spec: |
| 357 |
// https://github.com/w3c/baggage/blob/8c215efbeebd3fa4b1aceb937a747e56444f22f3/baggage/HTTP_HEADER_FORMAT.md?plain=1#L69 |
| 358 |
|
| 359 |
var b strings.Builder |
| 360 |
b.Grow(c) |
| 361 |
for i := 0; i < len(unescapeVal); { |
| 362 |
r, size := utf8.DecodeRuneInString(unescapeVal[i:]) |
| 363 |
if r == utf8.RuneError && size == 1 { |
| 364 |
// Invalid UTF-8 sequence found, replace it with '�' |
| 365 |
_, _ = b.WriteString("�") |
| 366 |
} else { |
| 367 |
_, _ = b.WriteRune(r) |
| 368 |
} |
| 369 |
i += size |
| 370 |
} |
| 371 |
|
| 372 |
return b.String() |
| 373 |
} |
| 374 |
|
| 375 |
// validate ensures m conforms to the W3C Baggage specification. |
| 376 |
// A key must be an ASCII string, returning an error otherwise. |
| 377 |
func (m Member) validate() error { |
| 378 |
if !m.hasData { |
| 379 |
return fmt.Errorf("%w: %q", errInvalidMember, m) |
| 380 |
} |
| 381 |
|
| 382 |
if !validateBaggageName(m.key) { |
| 383 |
return fmt.Errorf("%w: %q", errInvalidKey, m.key) |
| 384 |
} |
| 385 |
if !validateBaggageValue(m.value) { |
| 386 |
return fmt.Errorf("%w: %q", errInvalidValue, m.value) |
| 387 |
} |
| 388 |
return m.properties.validate() |
| 389 |
} |
| 390 |
|
| 391 |
// Key returns the Member key. |
| 392 |
func (m Member) Key() string { return m.key } |
| 393 |
|
| 394 |
// Value returns the Member value. |
| 395 |
func (m Member) Value() string { return m.value } |
| 396 |
|
| 397 |
// Properties returns a copy of the Member properties. |
| 398 |
func (m Member) Properties() []Property { return m.properties.Copy() } |
| 399 |
|
| 400 |
// String encodes Member into a header string compliant with the W3C Baggage |
| 401 |
// specification. |
| 402 |
// It would return empty string if the key is invalid with the W3C Baggage |
| 403 |
// specification. This could happen for a UTF-8 key, as it may contain |
| 404 |
// invalid characters. |
| 405 |
func (m Member) String() string { |
| 406 |
// W3C Baggage specification does not allow percent-encoded keys. |
| 407 |
if !validateKey(m.key) { |
| 408 |
return "" |
| 409 |
} |
| 410 |
|
| 411 |
s := m.key + keyValueDelimiter + valueEscape(m.value) |
| 412 |
if len(m.properties) > 0 { |
| 413 |
s += propertyDelimiter + m.properties.String() |
| 414 |
} |
| 415 |
return s |
| 416 |
} |
| 417 |
|
| 418 |
// Baggage is a list of baggage members representing the baggage-string as |
| 419 |
// defined by the W3C Baggage specification. |
| 420 |
type Baggage struct { //nolint:golint |
| 421 |
list baggage.List |
| 422 |
} |
| 423 |
|
| 424 |
// New returns a new valid Baggage. It returns an error if it results in a |
| 425 |
// Baggage exceeding limits set in that specification. |
| 426 |
// |
| 427 |
// If the resulting Baggage exceeds the maximum allowed members or bytes, |
| 428 |
// members are dropped until the limits are satisfied and an error is returned |
| 429 |
// along with the partial result. |
| 430 |
// |
| 431 |
// It expects all the provided members to have already been validated. |
| 432 |
func New(members ...Member) (Baggage, error) { |
| 433 |
if len(members) == 0 { |
| 434 |
return Baggage{}, nil |
| 435 |
} |
| 436 |
|
| 437 |
b := make(baggage.List) |
| 438 |
for _, m := range members { |
| 439 |
if !m.hasData { |
| 440 |
return Baggage{}, errInvalidMember |
| 441 |
} |
| 442 |
// OpenTelemetry resolves duplicates by last-one-wins. |
| 443 |
b[m.key] = baggage.Item{ |
| 444 |
Value: m.value, |
| 445 |
Properties: m.properties.asInternal(), |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
var truncateErr error |
| 450 |
|
| 451 |
// Check member count after deduplication. |
| 452 |
if len(b) > maxMembers { |
| 453 |
truncateErr = errors.Join(truncateErr, errMemberNumber) |
| 454 |
for k := range b { |
| 455 |
if len(b) <= maxMembers { |
| 456 |
break |
| 457 |
} |
| 458 |
delete(b, k) |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
// Check byte size and drop members if necessary. |
| 463 |
totalBytes := 0 |
| 464 |
first := true |
| 465 |
for k := range b { |
| 466 |
m := Member{ |
| 467 |
key: k, |
| 468 |
value: b[k].Value, |
| 469 |
properties: fromInternalProperties(b[k].Properties), |
| 470 |
} |
| 471 |
memberSize := len(m.String()) |
| 472 |
if !first { |
| 473 |
memberSize++ // comma separator |
| 474 |
} |
| 475 |
if totalBytes+memberSize > maxBytesPerBaggageString { |
| 476 |
truncateErr = errors.Join(truncateErr, fmt.Errorf("%w: %d", errBaggageBytes, totalBytes+memberSize)) |
| 477 |
delete(b, k) |
| 478 |
continue |
| 479 |
} |
| 480 |
totalBytes += memberSize |
| 481 |
first = false |
| 482 |
} |
| 483 |
|
| 484 |
return Baggage{b}, truncateErr |
| 485 |
} |
| 486 |
|
| 487 |
// Parse attempts to decode a baggage-string from the passed string. It |
| 488 |
// returns an error if the input is invalid according to the W3C Baggage |
| 489 |
// specification. |
| 490 |
// |
| 491 |
// If there are duplicate list-members contained in baggage, the last one |
| 492 |
// defined (reading left-to-right) will be the only one kept. This diverges |
| 493 |
// from the W3C Baggage specification which allows duplicate list-members, but |
| 494 |
// conforms to the OpenTelemetry Baggage specification. |
| 495 |
// |
| 496 |
// If the baggage-string exceeds the maximum allowed members (64) or bytes |
| 497 |
// (8192), members are dropped until the limits are satisfied and an error is |
| 498 |
// returned along with the partial result. |
| 499 |
// |
| 500 |
// Invalid members are skipped and the error is returned along with the |
| 501 |
// partial result containing the valid members. |
| 502 |
func Parse(bStr string) (Baggage, error) { |
| 503 |
if bStr == "" { |
| 504 |
return Baggage{}, nil |
| 505 |
} |
| 506 |
|
| 507 |
b := make(baggage.List) |
| 508 |
sizes := make(map[string]int) // Track per-key byte sizes |
| 509 |
var totalBytes int |
| 510 |
var truncateErr error |
| 511 |
for memberStr := range strings.SplitSeq(bStr, listDelimiter) { |
| 512 |
// Check member count limit. |
| 513 |
if len(b) >= maxMembers { |
| 514 |
truncateErr = errors.Join(truncateErr, errMemberNumber) |
| 515 |
break |
| 516 |
} |
| 517 |
|
| 518 |
m, err := parseMember(memberStr) |
| 519 |
if err != nil { |
| 520 |
truncateErr = errors.Join(truncateErr, err) |
| 521 |
continue // skip invalid member, keep processing |
| 522 |
} |
| 523 |
|
| 524 |
// Check byte size limit. |
| 525 |
// Account for comma separator between members. |
| 526 |
memberBytes := len(m.String()) |
| 527 |
_, existingKey := b[m.key] |
| 528 |
if !existingKey && len(b) > 0 { |
| 529 |
memberBytes++ // comma separator only for new keys |
| 530 |
} |
| 531 |
|
| 532 |
// Calculate new totalBytes if we add/overwrite this key |
| 533 |
var newTotalBytes int |
| 534 |
if oldSize, exists := sizes[m.key]; exists { |
| 535 |
// Overwriting existing key: subtract old size, add new size |
| 536 |
newTotalBytes = totalBytes - oldSize + memberBytes |
| 537 |
} else { |
| 538 |
// New key |
| 539 |
newTotalBytes = totalBytes + memberBytes |
| 540 |
} |
| 541 |
|
| 542 |
if newTotalBytes > maxBytesPerBaggageString { |
| 543 |
truncateErr = errors.Join(truncateErr, errBaggageBytes) |
| 544 |
break |
| 545 |
} |
| 546 |
|
| 547 |
// OpenTelemetry resolves duplicates by last-one-wins. |
| 548 |
b[m.key] = baggage.Item{ |
| 549 |
Value: m.value, |
| 550 |
Properties: m.properties.asInternal(), |
| 551 |
} |
| 552 |
sizes[m.key] = memberBytes |
| 553 |
totalBytes = newTotalBytes |
| 554 |
} |
| 555 |
|
| 556 |
if len(b) == 0 { |
| 557 |
return Baggage{}, truncateErr |
| 558 |
} |
| 559 |
return Baggage{b}, truncateErr |
| 560 |
} |
| 561 |
|
| 562 |
// Member returns the baggage list-member identified by key. |
| 563 |
// |
| 564 |
// If there is no list-member matching the passed key the returned Member will |
| 565 |
// be a zero-value Member. |
| 566 |
// The returned member is not validated, as we assume the validation happened |
| 567 |
// when it was added to the Baggage. |
| 568 |
func (b Baggage) Member(key string) Member { |
| 569 |
v, ok := b.list[key] |
| 570 |
if !ok { |
| 571 |
// We do not need to worry about distinguishing between the situation |
| 572 |
// where a zero-valued Member is included in the Baggage because a |
| 573 |
// zero-valued Member is invalid according to the W3C Baggage |
| 574 |
// specification (it has an empty key). |
| 575 |
return newInvalidMember() |
| 576 |
} |
| 577 |
|
| 578 |
return Member{ |
| 579 |
key: key, |
| 580 |
value: v.Value, |
| 581 |
properties: fromInternalProperties(v.Properties), |
| 582 |
hasData: true, |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
// Members returns all the baggage list-members. |
| 587 |
// The order of the returned list-members is not significant. |
| 588 |
// |
| 589 |
// The returned members are not validated, as we assume the validation happened |
| 590 |
// when they were added to the Baggage. |
| 591 |
func (b Baggage) Members() []Member { |
| 592 |
if len(b.list) == 0 { |
| 593 |
return nil |
| 594 |
} |
| 595 |
|
| 596 |
members := make([]Member, 0, len(b.list)) |
| 597 |
for k, v := range b.list { |
| 598 |
members = append(members, Member{ |
| 599 |
key: k, |
| 600 |
value: v.Value, |
| 601 |
properties: fromInternalProperties(v.Properties), |
| 602 |
hasData: true, |
| 603 |
}) |
| 604 |
} |
| 605 |
return members |
| 606 |
} |
| 607 |
|
| 608 |
// SetMember returns a copy of the Baggage with the member included. If the |
| 609 |
// baggage contains a Member with the same key, the existing Member is |
| 610 |
// replaced. |
| 611 |
// |
| 612 |
// If member is invalid according to the W3C Baggage specification, an error |
| 613 |
// is returned with the original Baggage. |
| 614 |
func (b Baggage) SetMember(member Member) (Baggage, error) { |
| 615 |
if !member.hasData { |
| 616 |
return b, errInvalidMember |
| 617 |
} |
| 618 |
|
| 619 |
n := len(b.list) |
| 620 |
if _, ok := b.list[member.key]; !ok { |
| 621 |
n++ |
| 622 |
} |
| 623 |
list := make(baggage.List, n) |
| 624 |
|
| 625 |
for k, v := range b.list { |
| 626 |
// Do not copy if we are just going to overwrite. |
| 627 |
if k == member.key { |
| 628 |
continue |
| 629 |
} |
| 630 |
list[k] = v |
| 631 |
} |
| 632 |
|
| 633 |
list[member.key] = baggage.Item{ |
| 634 |
Value: member.value, |
| 635 |
Properties: member.properties.asInternal(), |
| 636 |
} |
| 637 |
|
| 638 |
return Baggage{list: list}, nil |
| 639 |
} |
| 640 |
|
| 641 |
// DeleteMember returns a copy of the Baggage with the list-member identified |
| 642 |
// by key removed. |
| 643 |
func (b Baggage) DeleteMember(key string) Baggage { |
| 644 |
n := len(b.list) |
| 645 |
if _, ok := b.list[key]; ok { |
| 646 |
n-- |
| 647 |
} |
| 648 |
list := make(baggage.List, n) |
| 649 |
|
| 650 |
for k, v := range b.list { |
| 651 |
if k == key { |
| 652 |
continue |
| 653 |
} |
| 654 |
list[k] = v |
| 655 |
} |
| 656 |
|
| 657 |
return Baggage{list: list} |
| 658 |
} |
| 659 |
|
| 660 |
// Len returns the number of list-members in the Baggage. |
| 661 |
func (b Baggage) Len() int { |
| 662 |
return len(b.list) |
| 663 |
} |
| 664 |
|
| 665 |
// String encodes Baggage into a header string compliant with the W3C Baggage |
| 666 |
// specification. |
| 667 |
// It would ignore members where the member key is invalid with the W3C Baggage |
| 668 |
// specification. This could happen for a UTF-8 key, as it may contain |
| 669 |
// invalid characters. |
| 670 |
func (b Baggage) String() string { |
| 671 |
members := make([]string, 0, len(b.list)) |
| 672 |
for k, v := range b.list { |
| 673 |
s := Member{ |
| 674 |
key: k, |
| 675 |
value: v.Value, |
| 676 |
properties: fromInternalProperties(v.Properties), |
| 677 |
}.String() |
| 678 |
|
| 679 |
// Ignored empty members. |
| 680 |
if s != "" { |
| 681 |
members = append(members, s) |
| 682 |
} |
| 683 |
} |
| 684 |
return strings.Join(members, listDelimiter) |
| 685 |
} |
| 686 |
|
| 687 |
// parsePropertyInternal attempts to decode a Property from the passed string. |
| 688 |
// It follows the spec at https://www.w3.org/TR/baggage/#definition. |
| 689 |
func parsePropertyInternal(s string) (p Property, ok bool) { |
| 690 |
// For the entire function we will use " key = value " as an example. |
| 691 |
// Attempting to parse the key. |
| 692 |
// First skip spaces at the beginning "< >key = value " (they could be empty). |
| 693 |
index := skipSpace(s, 0) |
| 694 |
|
| 695 |
// Parse the key: " <key> = value ". |
| 696 |
keyStart := index |
| 697 |
keyEnd := index |
| 698 |
for _, c := range s[keyStart:] { |
| 699 |
if !validateKeyChar(c) { |
| 700 |
break |
| 701 |
} |
| 702 |
keyEnd++ |
| 703 |
} |
| 704 |
|
| 705 |
// If we couldn't find any valid key character, |
| 706 |
// it means the key is either empty or invalid. |
| 707 |
if keyStart == keyEnd { |
| 708 |
return p, ok |
| 709 |
} |
| 710 |
|
| 711 |
// Skip spaces after the key: " key< >= value ". |
| 712 |
index = skipSpace(s, keyEnd) |
| 713 |
|
| 714 |
if index == len(s) { |
| 715 |
// A key can have no value, like: " key ". |
| 716 |
ok = true |
| 717 |
p.key = s[keyStart:keyEnd] |
| 718 |
return p, ok |
| 719 |
} |
| 720 |
|
| 721 |
// If we have not reached the end and we can't find the '=' delimiter, |
| 722 |
// it means the property is invalid. |
| 723 |
if s[index] != keyValueDelimiter[0] { |
| 724 |
return p, ok |
| 725 |
} |
| 726 |
|
| 727 |
// Attempting to parse the value. |
| 728 |
// Match: " key =< >value ". |
| 729 |
index = skipSpace(s, index+1) |
| 730 |
|
| 731 |
// Match the value string: " key = <value> ". |
| 732 |
// A valid property can be: " key =". |
| 733 |
// Therefore, we don't have to check if the value is empty. |
| 734 |
valueStart := index |
| 735 |
valueEnd := index |
| 736 |
for _, c := range s[valueStart:] { |
| 737 |
if !validateValueChar(c) { |
| 738 |
break |
| 739 |
} |
| 740 |
valueEnd++ |
| 741 |
} |
| 742 |
|
| 743 |
// Skip all trailing whitespaces: " key = value< >". |
| 744 |
index = skipSpace(s, valueEnd) |
| 745 |
|
| 746 |
// If after looking for the value and skipping whitespaces |
| 747 |
// we have not reached the end, it means the property is |
| 748 |
// invalid, something like: " key = value value1". |
| 749 |
if index != len(s) { |
| 750 |
return p, ok |
| 751 |
} |
| 752 |
|
| 753 |
// Decode a percent-encoded value. |
| 754 |
rawVal := s[valueStart:valueEnd] |
| 755 |
unescapeVal, err := url.PathUnescape(rawVal) |
| 756 |
if err != nil { |
| 757 |
return p, ok |
| 758 |
} |
| 759 |
value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) |
| 760 |
|
| 761 |
ok = true |
| 762 |
p.key = s[keyStart:keyEnd] |
| 763 |
p.hasValue = true |
| 764 |
|
| 765 |
p.value = value |
| 766 |
return p, ok |
| 767 |
} |
| 768 |
|
| 769 |
func skipSpace(s string, offset int) int { |
| 770 |
i := offset |
| 771 |
for ; i < len(s); i++ { |
| 772 |
c := s[i] |
| 773 |
if c != ' ' && c != '\t' { |
| 774 |
break |
| 775 |
} |
| 776 |
} |
| 777 |
return i |
| 778 |
} |
| 779 |
|
| 780 |
var safeKeyCharset = [utf8.RuneSelf]bool{ |
| 781 |
// 0x23 to 0x27 |
| 782 |
'#': true, |
| 783 |
'$': true, |
| 784 |
'%': true, |
| 785 |
'&': true, |
| 786 |
'\'': true, |
| 787 |
|
| 788 |
// 0x30 to 0x39 |
| 789 |
'0': true, |
| 790 |
'1': true, |
| 791 |
'2': true, |
| 792 |
'3': true, |
| 793 |
'4': true, |
| 794 |
'5': true, |
| 795 |
'6': true, |
| 796 |
'7': true, |
| 797 |
'8': true, |
| 798 |
'9': true, |
| 799 |
|
| 800 |
// 0x41 to 0x5a |
| 801 |
'A': true, |
| 802 |
'B': true, |
| 803 |
'C': true, |
| 804 |
'D': true, |
| 805 |
'E': true, |
| 806 |
'F': true, |
| 807 |
'G': true, |
| 808 |
'H': true, |
| 809 |
'I': true, |
| 810 |
'J': true, |
| 811 |
'K': true, |
| 812 |
'L': true, |
| 813 |
'M': true, |
| 814 |
'N': true, |
| 815 |
'O': true, |
| 816 |
'P': true, |
| 817 |
'Q': true, |
| 818 |
'R': true, |
| 819 |
'S': true, |
| 820 |
'T': true, |
| 821 |
'U': true, |
| 822 |
'V': true, |
| 823 |
'W': true, |
| 824 |
'X': true, |
| 825 |
'Y': true, |
| 826 |
'Z': true, |
| 827 |
|
| 828 |
// 0x5e to 0x7a |
| 829 |
'^': true, |
| 830 |
'_': true, |
| 831 |
'`': true, |
| 832 |
'a': true, |
| 833 |
'b': true, |
| 834 |
'c': true, |
| 835 |
'd': true, |
| 836 |
'e': true, |
| 837 |
'f': true, |
| 838 |
'g': true, |
| 839 |
'h': true, |
| 840 |
'i': true, |
| 841 |
'j': true, |
| 842 |
'k': true, |
| 843 |
'l': true, |
| 844 |
'm': true, |
| 845 |
'n': true, |
| 846 |
'o': true, |
| 847 |
'p': true, |
| 848 |
'q': true, |
| 849 |
'r': true, |
| 850 |
's': true, |
| 851 |
't': true, |
| 852 |
'u': true, |
| 853 |
'v': true, |
| 854 |
'w': true, |
| 855 |
'x': true, |
| 856 |
'y': true, |
| 857 |
'z': true, |
| 858 |
|
| 859 |
// remainder |
| 860 |
'!': true, |
| 861 |
'*': true, |
| 862 |
'+': true, |
| 863 |
'-': true, |
| 864 |
'.': true, |
| 865 |
'|': true, |
| 866 |
'~': true, |
| 867 |
} |
| 868 |
|
| 869 |
// validateBaggageName checks if the string is a valid OpenTelemetry Baggage name. |
| 870 |
// Baggage name is a valid, non-empty UTF-8 string. |
| 871 |
func validateBaggageName(s string) bool { |
| 872 |
if s == "" { |
| 873 |
return false |
| 874 |
} |
| 875 |
|
| 876 |
return utf8.ValidString(s) |
| 877 |
} |
| 878 |
|
| 879 |
// validateBaggageValue checks if the string is a valid OpenTelemetry Baggage value. |
| 880 |
// Baggage value is a valid UTF-8 strings. |
| 881 |
// Empty string is also a valid UTF-8 string. |
| 882 |
func validateBaggageValue(s string) bool { |
| 883 |
return utf8.ValidString(s) |
| 884 |
} |
| 885 |
|
| 886 |
// validateKey checks if the string is a valid W3C Baggage key. |
| 887 |
func validateKey(s string) bool { |
| 888 |
if s == "" { |
| 889 |
return false |
| 890 |
} |
| 891 |
|
| 892 |
for _, c := range s { |
| 893 |
if !validateKeyChar(c) { |
| 894 |
return false |
| 895 |
} |
| 896 |
} |
| 897 |
|
| 898 |
return true |
| 899 |
} |
| 900 |
|
| 901 |
func validateKeyChar(c int32) bool { |
| 902 |
return c >= 0 && c < int32(utf8.RuneSelf) && safeKeyCharset[c] |
| 903 |
} |
| 904 |
|
| 905 |
// validateValue checks if the string is a valid W3C Baggage value. |
| 906 |
func validateValue(s string) bool { |
| 907 |
for _, c := range s { |
| 908 |
if !validateValueChar(c) { |
| 909 |
return false |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
return true |
| 914 |
} |
| 915 |
|
| 916 |
var safeValueCharset = [utf8.RuneSelf]bool{ |
| 917 |
'!': true, // 0x21 |
| 918 |
|
| 919 |
// 0x23 to 0x2b |
| 920 |
'#': true, |
| 921 |
'$': true, |
| 922 |
'%': true, |
| 923 |
'&': true, |
| 924 |
'\'': true, |
| 925 |
'(': true, |
| 926 |
')': true, |
| 927 |
'*': true, |
| 928 |
'+': true, |
| 929 |
|
| 930 |
// 0x2d to 0x3a |
| 931 |
'-': true, |
| 932 |
'.': true, |
| 933 |
'/': true, |
| 934 |
'0': true, |
| 935 |
'1': true, |
| 936 |
'2': true, |
| 937 |
'3': true, |
| 938 |
'4': true, |
| 939 |
'5': true, |
| 940 |
'6': true, |
| 941 |
'7': true, |
| 942 |
'8': true, |
| 943 |
'9': true, |
| 944 |
':': true, |
| 945 |
|
| 946 |
// 0x3c to 0x5b |
| 947 |
'<': true, // 0x3C |
| 948 |
'=': true, // 0x3D |
| 949 |
'>': true, // 0x3E |
| 950 |
'?': true, // 0x3F |
| 951 |
'@': true, // 0x40 |
| 952 |
'A': true, // 0x41 |
| 953 |
'B': true, // 0x42 |
| 954 |
'C': true, // 0x43 |
| 955 |
'D': true, // 0x44 |
| 956 |
'E': true, // 0x45 |
| 957 |
'F': true, // 0x46 |
| 958 |
'G': true, // 0x47 |
| 959 |
'H': true, // 0x48 |
| 960 |
'I': true, // 0x49 |
| 961 |
'J': true, // 0x4A |
| 962 |
'K': true, // 0x4B |
| 963 |
'L': true, // 0x4C |
| 964 |
'M': true, // 0x4D |
| 965 |
'N': true, // 0x4E |
| 966 |
'O': true, // 0x4F |
| 967 |
'P': true, // 0x50 |
| 968 |
'Q': true, // 0x51 |
| 969 |
'R': true, // 0x52 |
| 970 |
'S': true, // 0x53 |
| 971 |
'T': true, // 0x54 |
| 972 |
'U': true, // 0x55 |
| 973 |
'V': true, // 0x56 |
| 974 |
'W': true, // 0x57 |
| 975 |
'X': true, // 0x58 |
| 976 |
'Y': true, // 0x59 |
| 977 |
'Z': true, // 0x5A |
| 978 |
'[': true, // 0x5B |
| 979 |
|
| 980 |
// 0x5d to 0x7e |
| 981 |
']': true, // 0x5D |
| 982 |
'^': true, // 0x5E |
| 983 |
'_': true, // 0x5F |
| 984 |
'`': true, // 0x60 |
| 985 |
'a': true, // 0x61 |
| 986 |
'b': true, // 0x62 |
| 987 |
'c': true, // 0x63 |
| 988 |
'd': true, // 0x64 |
| 989 |
'e': true, // 0x65 |
| 990 |
'f': true, // 0x66 |
| 991 |
'g': true, // 0x67 |
| 992 |
'h': true, // 0x68 |
| 993 |
'i': true, // 0x69 |
| 994 |
'j': true, // 0x6A |
| 995 |
'k': true, // 0x6B |
| 996 |
'l': true, // 0x6C |
| 997 |
'm': true, // 0x6D |
| 998 |
'n': true, // 0x6E |
| 999 |
'o': true, // 0x6F |
| 1000 |
'p': true, // 0x70 |
| 1001 |
'q': true, // 0x71 |
| 1002 |
'r': true, // 0x72 |
| 1003 |
's': true, // 0x73 |
| 1004 |
't': true, // 0x74 |
| 1005 |
'u': true, // 0x75 |
| 1006 |
'v': true, // 0x76 |
| 1007 |
'w': true, // 0x77 |
| 1008 |
'x': true, // 0x78 |
| 1009 |
'y': true, // 0x79 |
| 1010 |
'z': true, // 0x7A |
| 1011 |
'{': true, // 0x7B |
| 1012 |
'|': true, // 0x7C |
| 1013 |
'}': true, // 0x7D |
| 1014 |
'~': true, // 0x7E |
| 1015 |
} |
| 1016 |
|
| 1017 |
func validateValueChar(c int32) bool { |
| 1018 |
return c >= 0 && c < int32(utf8.RuneSelf) && safeValueCharset[c] |
| 1019 |
} |
| 1020 |
|
| 1021 |
// valueEscape escapes the string so it can be safely placed inside a baggage value, |
| 1022 |
// replacing special characters with %XX sequences as needed. |
| 1023 |
// |
| 1024 |
// The implementation is based on: |
| 1025 |
// https://github.com/golang/go/blob/f6509cf5cdbb5787061b784973782933c47f1782/src/net/url/url.go#L285. |
| 1026 |
func valueEscape(s string) string { |
| 1027 |
hexCount := 0 |
| 1028 |
for i := 0; i < len(s); i++ { |
| 1029 |
c := s[i] |
| 1030 |
if shouldEscape(c) { |
| 1031 |
hexCount++ |
| 1032 |
} |
| 1033 |
} |
| 1034 |
|
| 1035 |
if hexCount == 0 { |
| 1036 |
return s |
| 1037 |
} |
| 1038 |
|
| 1039 |
var buf [64]byte |
| 1040 |
var t []byte |
| 1041 |
|
| 1042 |
required := len(s) + 2*hexCount |
| 1043 |
if required <= len(buf) { |
| 1044 |
t = buf[:required] |
| 1045 |
} else { |
| 1046 |
t = make([]byte, required) |
| 1047 |
} |
| 1048 |
|
| 1049 |
j := 0 |
| 1050 |
for i := 0; i < len(s); i++ { |
| 1051 |
c := s[i] |
| 1052 |
if shouldEscape(s[i]) { |
| 1053 |
const upperhex = "0123456789ABCDEF" |
| 1054 |
t[j] = '%' |
| 1055 |
t[j+1] = upperhex[c>>4] |
| 1056 |
t[j+2] = upperhex[c&15] |
| 1057 |
j += 3 |
| 1058 |
} else { |
| 1059 |
t[j] = c |
| 1060 |
j++ |
| 1061 |
} |
| 1062 |
} |
| 1063 |
|
| 1064 |
return string(t) |
| 1065 |
} |
| 1066 |
|
| 1067 |
// shouldEscape returns true if the specified byte should be escaped when |
| 1068 |
// appearing in a baggage value string. |
| 1069 |
func shouldEscape(c byte) bool { |
| 1070 |
if c == '%' { |
| 1071 |
// The percent character must be encoded so that percent-encoding can work. |
| 1072 |
return true |
| 1073 |
} |
| 1074 |
return !validateValueChar(int32(c)) |
| 1075 |
} |