Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds '+' character to allowed characters in baggage value #4898

Merged
merged 7 commits into from Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,144 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.baggage.propagation;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.BitSet;
import javax.annotation.Nullable;

/**
* Note: This class is based on code from Apache Commons Codec. It is comprised of code from these
* classes:
*
* <ul>
* <li><a
* href="https://github.com/apache/commons-codec/blob/482df6cabfb288acb6ab3e4a732fdb93aecfa7c2/src/main/java/org/apache/commons/codec/net/URLCodec.java">org.apache.commons.codec.net.URLCodec</a>
* <li><a
* href="https://github.com/apache/commons-codec/blob/482df6cabfb288acb6ab3e4a732fdb93aecfa7c2/src/main/java/org/apache/commons/codec/net/Utils.java">org.apache.commons.codec.net.Utils</a>
* </ul>
*
* <p>Implements baggage-octet decoding in accordance with th <a
* href="https://w3c.github.io/baggage/#definition">Baggage header content</a> specification. All
* US-ASCII characters excluding CTLs, whitespace, DQUOTE, comma, semicolon and backslash are
* encoded in `www-form-urlencoded` encoding scheme.
*/
class BaggageCodec {

private static final byte ESCAPE_CHAR = '%';

private static final BitSet WWW_FORM_URL_SAFE = new BitSet(256);
jack-berg marked this conversation as resolved.
Show resolved Hide resolved

// Static initializer for www_form_url
static {
// alpha characters
for (int i = 'a'; i <= 'z'; i++) {
WWW_FORM_URL_SAFE.set(i);
}
for (int i = 'A'; i <= 'Z'; i++) {
WWW_FORM_URL_SAFE.set(i);
}
// numeric characters
for (int i = '0'; i <= '9'; i++) {
WWW_FORM_URL_SAFE.set(i);
}
// special chars
WWW_FORM_URL_SAFE.set('-');
WWW_FORM_URL_SAFE.set('_');
WWW_FORM_URL_SAFE.set('.');
WWW_FORM_URL_SAFE.set('*');
// blank to be replaced with +
WWW_FORM_URL_SAFE.set(' ');
}

private BaggageCodec() {}

/**
* Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped
* characters are converted back to their original representation.
*
* @param bytes array of URL safe characters
* @return array of original bytes
*/
@Nullable
static byte[] decode(@Nullable byte[] bytes) {
jack-berg marked this conversation as resolved.
Show resolved Hide resolved
if (bytes == null) {
return null;
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i];
if (b == ESCAPE_CHAR) {
jack-berg marked this conversation as resolved.
Show resolved Hide resolved
try {
int u = Utils.digit16(bytes[++i]);
int l = Utils.digit16(bytes[++i]);
buffer.write((char) ((u << 4) + l));
} catch (ArrayIndexOutOfBoundsException e) {
throw new DecoderException("Invalid URL encoding: ", e);
}
} else {
buffer.write(b);
}
}
return buffer.toByteArray();
}

/**
* Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped
* characters are converted back to their original representation.
*
* @param value string of URL safe characters
* @param charset encoding of given string
* @return decoded value
*/
@Nullable
static String decode(@Nullable String value, Charset charset) {
Copy link
Member

Choose a reason for hiding this comment

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

Looks like value is never null. Can remove the @Nullable annotation on the value argument, and also maybe on the response. That should improve test coverage.

Same recommendation applies to private static byte[] decode(@Nullable byte[] bytes) above.

if (value == null) {
return null;
}

byte[] bytes = decode(value.getBytes(StandardCharsets.US_ASCII));
return new String(bytes, charset);
}

static class Utils {
jack-berg marked this conversation as resolved.
Show resolved Hide resolved

/** Radix used in encoding and decoding. */
private static final int RADIX = 16;

private Utils() {}

/**
* Returns the numeric value of the character {@code b} in radix 16.
*
* @param b The byte to be converted.
* @return The numeric value represented by the character in radix 16.
*/
static int digit16(byte b) {
int i = Character.digit((char) b, RADIX);
if (i == -1) {
throw new DecoderException(
"Invalid URL encoding: not a valid digit (radix " + RADIX + "): " + b);
}
return i;
}
}

public static class DecoderException extends RuntimeException implements Serializable {
jack-berg marked this conversation as resolved.
Show resolved Hide resolved

private static final long serialVersionUID = 4717632118051490483L;

public DecoderException(String message, Throwable cause) {
super(message, cause);
}

public DecoderException(String message) {
super(message);
}
}
}
Expand Up @@ -7,8 +7,6 @@

import io.opentelemetry.api.baggage.BaggageBuilder;
import io.opentelemetry.api.baggage.BaggageEntryMetadata;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;

Expand Down Expand Up @@ -64,6 +62,8 @@ void parseInto(BaggageBuilder baggageBuilder) {
} else {
skipToNext = true;
}
} else if (state == State.VALUE) {
skipToNext = !value.tryNextChar(current, i);
}
break;
}
Expand Down Expand Up @@ -146,20 +146,7 @@ private static String decodeValue(@Nullable String value) {
if (value == null) {
return null;
}
try {
return URLDecoder.decode(encodeAllowedCharacters(value), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return null;
}
}

/**
* Encodes allowed '+' character into percent, so that URLDecoder won't treat it as a space
* character.
*/
private static String encodeAllowedCharacters(String value) {
value = value.replace("+", "%2B");
return value;
return BaggageCodec.decode(value, StandardCharsets.UTF_8);
}

/**
Expand Down
Expand Up @@ -18,8 +18,11 @@
import io.opentelemetry.api.baggage.BaggageEntryMetadata;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.runner.Result;
Expand Down Expand Up @@ -62,6 +65,17 @@ public void roundTripAsciiValues(
Baggage extractedBaggage = Baggage.fromContext(extractedContext);
assertThat(extractedBaggage).isEqualTo(baggage);
}

@Fuzz
public void baggageOctet(@From(BaggageOctetGenerator.class) String baggageValue) {
Map<String, String> carrier = new HashMap<>();
carrier.put("baggage", "key=" + baggageValue);
Context context =
baggagePropagator.extract(Context.current(), carrier, new MapTextMapGetter());
Baggage baggage = Baggage.fromContext(context);
String value = baggage.getEntryValue("key");
assertThat(value).isEqualTo(baggageValue);
}
}

// driver methods to avoid having to use the vintage junit engine, and to enable increasing the
Expand All @@ -79,9 +93,15 @@ void roundTripFuzzing() {
assertThat(result.wasSuccessful()).isTrue();
}

private static Result runTestCase(String roundTripRandomValues) {
@Test
void baggageOctetFuzzing() {
Result result = runTestCase("baggageOctet");
assertThat(result.wasSuccessful()).isTrue();
}

private static Result runTestCase(String testCaseName) {
return GuidedFuzzing.run(
TestCases.class, roundTripRandomValues, new NoGuidance(10000, System.out), System.out);
TestCases.class, testCaseName, new NoGuidance(10000, System.out), System.out);
}

public static class AsciiGenerator extends AbstractStringGenerator {
Expand Down Expand Up @@ -109,4 +129,25 @@ public String get(Map<String, String> carrier, String key) {
return carrier.get(key);
}
}

public static class BaggageOctetGenerator extends AbstractStringGenerator {

private static final Set<Character> excluded =
new HashSet<>(Arrays.asList(' ', '"', ',', ';', '\\', '%'));

@Override
protected int nextCodePoint(SourceOfRandomness random) {
while (true) {
char c = random.nextChar(' ', '~');
if (!excluded.contains(c)) {
return c;
}
}
}

@Override
protected boolean codePointInRange(int codePoint) {
return !excluded.contains((char) codePoint);
}
}
}
Expand Up @@ -473,34 +473,4 @@ void inject_nullSetter() {
W3CBaggagePropagator.getInstance().inject(context, carrier, null);
assertThat(carrier).isEmpty();
}

@Test
void shouldAllowBase64SpecialCharacters() {
String encodedInBase64 =
"MngJIFNQIAkhCSIJIwkkCSUJJgknCSgJKQkqCSsJLAktCS4JLwozeAkwCTEJMgkzCTQJNQk2CTcJOAk5CToJOwk8CT0JPgk/CjR4CUAJQQlCCUMJRAlFCUYJRwlICUkJSglLCUwJTQlOCU8KNXgJUAlRCVIJUwlUCVUJVglXCVgJWQlaCVsJXAldCV4JXwo2eAlgCWEJYgljCWQJZQlmCWcJaAlpCWoJawlsCW0JbglvCjd4CXAJcQlyCXMJdAl1CXYJdwl4CXkJegl7CXwJfQl+CQo4eAkJCQkJCQkJCQkJCQkJCQkKOXgJCQkJCQkJCQkJCQkJCQkJCkF4CU5CU1AJwqEJwqIJwqMJwqQJwqUJwqYJwqcJwqgJwqkJwqoJwqsJwqwJU0hZCcKuCcKvCkJ4CcKwCcKxCcKyCcKzCcK0CcK1CcK2CcK3CcK4CcK5CcK6CcK7CcK8CcK9CcK+CcK/CkN4CcOACcOBCcOCCcODCcOECcOFCcOGCcOHCcOICcOJCcOKCcOLCcOMCcONCcOOCcOPCkR4CcOQCcORCcOSCcOTCcOUCcOVCcOWCcOXCcOYCcOZCcOaCcObCcOcCcOdCcOeCcOfCkV4CcOgCcOhCcOiCcOjCcOkCcOlCcOmCcOnCcOoCcOpCcOqCcOrCcOsCcOtCcOuCcOvCkZ4CcOwCcOxCcOyCcOzCcO0CcO1CcO2CcO3CcO4CcO5CcO6CcO7CcO8CcO9CcO+CcO/Cgo=";

W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance();

Context result =
propagator.extract(
Context.root(),
ImmutableMap.of(
"baggage",
"key1= value1; metadata-key = value; othermetadata, "
+ "key2 =value2 , key3 =\tvalue3 , foo="
+ encodedInBase64),
getter);

Baggage expectedBaggage =
Baggage.builder()
.put(
"key1",
"value1",
BaggageEntryMetadata.create("metadata-key = value; othermetadata"))
.put("key2", "value2", BaggageEntryMetadata.empty())
.put("key3", "value3")
.put("foo", encodedInBase64)
.build();
assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage);
}
}
7 changes: 6 additions & 1 deletion docs/apidiffs/current_vs_latest/opentelemetry-api.txt
@@ -1,2 +1,7 @@
Comparing source compatibility of against
No changes.
+++ NEW CLASS: PUBLIC(+) STATIC(+) io.opentelemetry.api.baggage.propagation.BaggageCodec$DecoderException (compatible)
+++ CLASS FILE FORMAT VERSION: 52.0 <- n.a.
+++ NEW INTERFACE: java.io.Serializable
+++ NEW SUPERCLASS: java.lang.RuntimeException
+++ NEW CONSTRUCTOR: PUBLIC(+) BaggageCodec$DecoderException(java.lang.String)
+++ NEW CONSTRUCTOR: PUBLIC(+) BaggageCodec$DecoderException(java.lang.String, java.lang.Throwable)