Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Copyright 2018-Present The CloudEvents Authors
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 io.cloudevents.core.message.impl;

import io.cloudevents.core.v1.CloudEventV1;
import io.cloudevents.rw.CloudEventRWException;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

/**
* Encodes and decodes the values of CloudEvents HTTP headers in binary mode, as described in section 3.1.3.2
* "HTTP Header Values" of the HTTP protocol binding.
*/
public final class HttpHeaderValues {

private static final char[] UPPER_HEX = "0123456789ABCDEF".toCharArray();

private HttpHeaderValues() {
}

/**
* Percent-encode an attribute value for its HTTP header. The bytes of its UTF-8 form outside U+0021-U+007E are
* encoded, along with {@code %} and {@code "}. A space is only encoded when it is leading or trailing. The value
* of {@code datacontenttype} is returned as is, since it goes to the Content-Type header.
*
* @param name the attribute name
* @param value the attribute value
* @return the header value
* @throws CloudEventRWException if the value can't be encoded as UTF-8
*/
public static String encode(String name, String value) throws CloudEventRWException {
if (value == null || CloudEventV1.DATACONTENTTYPE.equals(name) || !needsEncoding(value)) {
return value;
}
byte[] bytes;
try {
ByteBuffer buffer = StandardCharsets.UTF_8.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.encode(CharBuffer.wrap(value));
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
} catch (CharacterCodingException e) {
throw CloudEventRWException.newInvalidAttributeValue(name, value, e);
}
int first = 0;
int last = bytes.length;
while (first < last && bytes[first] == ' ') {
first++;
}
while (last > first && bytes[last - 1] == ' ') {
last--;
}
StringBuilder builder = new StringBuilder(bytes.length);
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i] & 0xFF;
if ((b == ' ' && i >= first && i < last) || (b > 0x20 && b < 0x7F && b != '%' && b != '"')) {
builder.append((char) b);
} else {
builder.append('%').append(UPPER_HEX[b >> 4]).append(UPPER_HEX[b & 0xF]);
}
}
return builder.toString();
}

/**
* Decode an HTTP header value to an attribute value. Leading and trailing spaces and tabs are removed, double
* quotes that aren't percent-encoded are removed, a backslash within double quotes escapes the next character
* and percent-encoded bytes are decoded. A {@code %} that isn't followed by two hex digits is kept as is.
*
* @param name the attribute name, used in the exception
* @param value the header value
* @return the attribute value
* @throws CloudEventRWException if the decoded bytes are not valid UTF-8
*/
public static String decode(String name, String value) throws CloudEventRWException {
if (value == null) {
return null;
}
int start = 0;
int end = value.length();
while (start < end && isSpaceOrTab(value.charAt(start))) {
start++;
}
while (end > start && isSpaceOrTab(value.charAt(end - 1))) {
end--;
}
String trimmed = value.substring(start, end);
if (trimmed.indexOf('%') < 0 && trimmed.indexOf('"') < 0) {
return trimmed;
}

// The quotes and the backslash escapes within them are processed before the percent-decoding
StringBuilder unquoted = new StringBuilder(trimmed.length());
boolean inQuote = false;
for (int i = 0; i < trimmed.length(); i++) {
char c = trimmed.charAt(i);
if (c == '"') {
inQuote = !inQuote;
} else if (c == '\\' && inQuote && i + 1 < trimmed.length()) {
unquoted.append(trimmed.charAt(++i));
} else {
unquoted.append(c);
}
}

ByteArrayOutputStream bytes = new ByteArrayOutputStream(unquoted.length());
int i = 0;
while (i < unquoted.length()) {
char c = unquoted.charAt(i);
if (c == '%' && i + 2 < unquoted.length()
&& hexValue(unquoted.charAt(i + 1)) >= 0 && hexValue(unquoted.charAt(i + 2)) >= 0) {
bytes.write(hexValue(unquoted.charAt(i + 1)) << 4 | hexValue(unquoted.charAt(i + 2)));
i += 3;
} else if (c < 0x80) {
bytes.write(c);
i++;
} else {
int codePoint = Character.codePointAt(unquoted, i);
bytes.writeBytes(new String(Character.toChars(codePoint)).getBytes(StandardCharsets.UTF_8));
i += Character.charCount(codePoint);
}
}

try {
return StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes.toByteArray()))
.toString();
} catch (CharacterCodingException e) {
throw CloudEventRWException.newInvalidAttributeValue(name, value, e);
}
}

private static boolean needsEncoding(String value) {
int last = value.length() - 1;
for (int i = 0; i <= last; i++) {
char c = value.charAt(i);
if (c == ' ' ? (i == 0 || i == last) : (c < 0x21 || c > 0x7E || c == '%' || c == '"')) {
return true;
}
}
return false;
}

private static boolean isSpaceOrTab(char c) {
return c == ' ' || c == '\t';
}

private static int hexValue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright 2018-Present The CloudEvents Authors
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 io.cloudevents.core.message.impl;

import io.cloudevents.rw.CloudEventRWException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

class HttpHeaderValuesTest {

@ParameterizedTest
@MethodSource
void encode(String value, String expected) {
assertThat(HttpHeaderValues.encode("subject", value)).isEqualTo(expected);
}

private static Stream<Arguments> encode() {
return Stream.of(
Arguments.of("plain", "plain"),
Arguments.of("", ""),
Arguments.of("a b", "a b"),
Arguments.of(" a b ", "%20a b%20"),
Arguments.of(" ", "%20%20%20"),
Arguments.of(" ", "%20"),
Arguments.of("a ", "a%20%20"),
Arguments.of("100%", "100%25"),
Arguments.of("say \"hi\"", "say %22hi%22"),
Arguments.of("tab\there", "tab%09here"),
Arguments.of("a\r\nb", "a%0D%0Ab"),
Arguments.of("x\u007Fy", "x%7Fy"),
Arguments.of("!~", "!~"),
Arguments.of("Euro \u20AC \uD83D\uDE00", "Euro %E2%82%AC %F0%9F%98%80")
);
}

@ParameterizedTest
@MethodSource
void decode(String value, String expected) {
assertThat(HttpHeaderValues.decode("subject", value)).isEqualTo(expected);
}

private static Stream<Arguments> decode() {
return Stream.of(
Arguments.of("plain", "plain"),
Arguments.of("a b", "a b"),
Arguments.of("a%20b", "a b"),
Arguments.of("%20lead", " lead"),
Arguments.of(" padded\t", "padded"),
Arguments.of("100%25", "100%"),
Arguments.of("Euro %e2%82%ac", "Euro \u20AC"),
Arguments.of("Euro %E2%82%AC %F0%9F%98%80", "Euro \u20AC \uD83D\uDE00"),
Arguments.of("%41BC", "ABC"),
Arguments.of("100%", "100%"),
Arguments.of("100%4", "100%4"),
Arguments.of("100%zz", "100%zz"),
Arguments.of("%22quoted%22", "\"quoted\""),
Arguments.of("\" a \"", " a "),
Arguments.of("\"quoted value\"", "quoted value"),
Arguments.of("\"a\\\"b\"", "a\"b"),
Arguments.of("a\\b", "a\\b"),
Arguments.of("\"\\%41\"", "A"),
Arguments.of("%\"4\"1", "A"),
Arguments.of("Gr\u00FC\u00DFe", "Gr\u00FC\u00DFe")
);
}

@ParameterizedTest
@ValueSource(strings = {"%C0%A0", "%FF", "%ED%A0%80", "%E2%82", "a%80b"})
void decodeRejectsInvalidUtf8(String value) {
CloudEventRWException exception = assertThrows(CloudEventRWException.class,
() -> HttpHeaderValues.decode("subject", value));
assertThat(exception.getKind()).isEqualTo(CloudEventRWException.CloudEventRWExceptionKind.INVALID_ATTRIBUTE_VALUE);
}

@ParameterizedTest
@ValueSource(strings = {"plain", " a b ", "100%", "say \"hi\"", "a\\b", "tab\there", "Euro \u20AC \uD83D\uDE00", "%41"})
void roundTrip(String value) {
assertThat(HttpHeaderValues.decode("subject", HttpHeaderValues.encode("subject", value))).isEqualTo(value);
}

@Test
void encodeKeepsDataContentType() {
assertThat(HttpHeaderValues.encode("datacontenttype", "text/plain; charset=\"utf-8\""))
.isEqualTo("text/plain; charset=\"utf-8\"");
}

@Test
void encodeRejectsLoneSurrogate() {
CloudEventRWException exception = assertThrows(CloudEventRWException.class,
() -> HttpHeaderValues.encode("subject", "a\uD800b"));
assertThat(exception.getKind()).isEqualTo(CloudEventRWException.CloudEventRWExceptionKind.INVALID_ATTRIBUTE_VALUE);
}

@Test
void nullValues() {
assertThat(HttpHeaderValues.encode("subject", null)).isNull();
assertThat(HttpHeaderValues.decode("subject", null)).isNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.cloudevents.core.data.BytesCloudEventData;
import io.cloudevents.core.impl.StringUtils;
import io.cloudevents.core.message.impl.BaseGenericBinaryMessageReaderImpl;
import io.cloudevents.core.message.impl.HttpHeaderValues;

import java.util.function.BiConsumer;
import java.util.function.Consumer;
Expand Down Expand Up @@ -58,7 +59,8 @@ protected String toCloudEventsKey(String key) {

@Override
protected void forEachHeader(BiConsumer<String, String> fn) {
forEachHeader.accept(fn);
forEachHeader.accept((key, value) ->
fn.accept(key, isCloudEventsHeader(key) ? HttpHeaderValues.decode(toCloudEventsKey(key), value) : value));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.cloudevents.SpecVersion;
import io.cloudevents.core.format.EventFormat;
import io.cloudevents.core.message.MessageWriter;
import io.cloudevents.core.message.impl.HttpHeaderValues;
import io.cloudevents.rw.CloudEventContextWriter;
import io.cloudevents.rw.CloudEventRWException;
import io.cloudevents.rw.CloudEventWriter;
Expand Down Expand Up @@ -64,7 +65,7 @@ public CloudEventContextWriter withContextAttribute(String name, String value) t
if (headerName == null) {
headerName = "ce-" + name;
}
putHeader.accept(headerName, value);
putHeader.accept(headerName, HttpHeaderValues.encode(name, value));
return this;
}

Expand Down
Loading
Loading