Revert back to the custom decode method for Otel decoding

https://github.com/spring-projects/spring-framework/issues/34570

See gh-44677
This commit is contained in:
Moritz Halbritter
2025-03-13 11:26:23 +01:00
parent 03974f2f87
commit 3bd75f6ce5
2 changed files with 43 additions and 3 deletions

View File

@@ -16,6 +16,7 @@
package org.springframework.boot.actuate.autoconfigure.opentelemetry;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -138,7 +139,7 @@ public final class OpenTelemetryResourceAttributes {
if (index > 0) {
String key = attribute.substring(0, index);
String value = attribute.substring(index + 1);
attributes.put(key.trim(), StringUtils.uriDecode(value.trim(), StandardCharsets.UTF_8));
attributes.put(key.trim(), decode(value.trim()));
}
}
String otelServiceName = getEnv("OTEL_SERVICE_NAME");
@@ -152,4 +153,43 @@ public final class OpenTelemetryResourceAttributes {
return this.getEnv.apply(name);
}
/**
* Decodes a percent-encoded string. Converts sequences like '%HH' (where HH
* represents hexadecimal digits) back into their literal representations.
* <p>
* Inspired by {@code org.apache.commons.codec.net.PercentCodec}.
* @param value value to decode
* @return the decoded string
*/
private static String decode(String value) {
if (value.indexOf('%') < 0) {
return value;
}
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (b != '%') {
bos.write(b);
continue;
}
int u = decodeHex(bytes, i + 1);
int l = decodeHex(bytes, i + 2);
if (u >= 0 && l >= 0) {
bos.write((u << 4) + l);
}
else {
throw new IllegalArgumentException(
"Failed to decode percent-encoded characters at index %d in the value: '%s'".formatted(i,
value));
}
i += 2;
}
return bos.toString(StandardCharsets.UTF_8);
}
private static int decodeHex(byte[] bytes, int index) {
return (index < bytes.length) ? Character.digit(bytes[index], 16) : -1;
}
}

View File

@@ -121,7 +121,7 @@ class OpenTelemetryResourceAttributesTests {
void illegalArgumentExceptionShouldBeThrownWhenDecodingIllegalHexCharPercentEncodedValue() {
this.environmentVariables.put("OTEL_RESOURCE_ATTRIBUTES", "key=abc%ß");
assertThatIllegalArgumentException().isThrownBy(this::getAttributes)
.withMessage("Invalid encoded sequence \"\"");
.withMessage("Failed to decode percent-encoded characters at index 3 in the value: 'abc%ß'");
}
@Test
@@ -134,7 +134,7 @@ class OpenTelemetryResourceAttributesTests {
void illegalArgumentExceptionShouldBeThrownWhenDecodingInvalidPercentEncodedValue() {
this.environmentVariables.put("OTEL_RESOURCE_ATTRIBUTES", "key=%");
assertThatIllegalArgumentException().isThrownBy(this::getAttributes)
.withMessage("Invalid encoded sequence \"%\"");
.withMessage("Failed to decode percent-encoded characters at index 0 in the value: '%'");
}
@Test