feat(kinesis): support stream consumer resource tags (#8057)

* feat(kinesis): support stream consumer resource tags

* fix(kinesis): validate resource tags before updates

* refactor(kinesis): rely on generated tag constraints

* fix(kinesis): align resource tag characters with Tag type

* fix(kinesis): accept colons in resource tags
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-12 19:16:10 -04:00
1 parent 91ec6d29ef
commit f41c4ee5c0
7 files changed
+470 -18

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Global Accelerator](globalaccelerator.md) | `POST /` + `X-Amz-Target: GlobalAccelerator_V20180706.*` | JSON 1.1 | 22 |
| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 44 |
| [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 |
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 29 |
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 32 |
| [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 |
| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 17 |
| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 12 |
+3
View File
@@ -21,6 +21,9 @@
| `AddTagsToStream` | Tag a stream |
| `RemoveTagsFromStream` | Remove tags |
| `ListTagsForStream` | List tags |
| `TagResource` | Add or update tags on a stream or consumer |
| `UntagResource` | Remove tags from a stream or consumer |
| `ListTagsForResource` | List tags on a stream or consumer |
| `StartStreamEncryption` | Enable KMS encryption |
| `StopStreamEncryption` | Disable encryption |
| `SplitShard` | Split a shard into two |
@@ -67,6 +67,9 @@ public class KinesisJsonHandler {
case "AddTagsToStream" -> () -> handleAddTagsToStream(request, region);
case "RemoveTagsFromStream" -> () -> handleRemoveTagsFromStream(request, region);
case "ListTagsForStream" -> () -> handleListTagsForStream(request, region);
case "TagResource" -> () -> handleTagResource(request, region);
case "UntagResource" -> () -> handleUntagResource(request, region);
case "ListTagsForResource" -> () -> handleListTagsForResource(request, region);
case "StartStreamEncryption" -> () -> handleStartStreamEncryption(request, region);
case "StopStreamEncryption" -> () -> handleStopStreamEncryption(request, region);
case "SplitShard" -> () -> handleSplitShard(request, region);
@@ -346,7 +349,8 @@ public class KinesisJsonHandler {
private Response handleRegisterStreamConsumer(JsonNode request, String region) {
String streamArn = request.path("StreamARN").asText();
String consumerName = request.path("ConsumerName").asText();
KinesisConsumer consumer = service.registerStreamConsumer(streamArn, consumerName, region);
Map<String, String> tags = parseTags(request);
KinesisConsumer consumer = service.registerStreamConsumer(streamArn, consumerName, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("Consumer", consumerToNode(consumer));
return Response.ok(response).build();
@@ -467,26 +471,54 @@ public class KinesisJsonHandler {
private Response handleRemoveTagsFromStream(JsonNode request, String region) {
String streamName = resolveStreamName(request);
service.removeTagsFromStream(streamName, parseTagKeys(request.path("TagKeys")), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private List<String> parseTagKeys(JsonNode tagKeysNode) {
List<String> tagKeys = new ArrayList<>();
for (JsonNode node : request.path("TagKeys")) {
for (JsonNode node : tagKeysNode) {
tagKeys.add(node.textValue());
}
service.removeTagsFromStream(streamName, tagKeys, region);
return Response.ok(objectMapper.createObjectNode()).build();
return tagKeys;
}
private Response handleListTagsForStream(JsonNode request, String region) {
String streamName = resolveStreamName(request);
Map<String, String> tags = service.listTagsForStream(streamName, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode tagsArray = response.putArray("Tags");
response.set("Tags", tagsToArray(tags));
response.put("HasMoreTags", false);
return Response.ok(response).build();
}
private Response handleTagResource(JsonNode request, String region) {
Map<String, String> tags = parseTags(request);
service.tagResource(request.path("ResourceARN").asText(null), tags, region);
return Response.ok().build();
}
private Response handleUntagResource(JsonNode request, String region) {
List<String> keys = parseTagKeys(request.path("TagKeys"));
service.untagResource(request.path("ResourceARN").asText(null), keys, region);
return Response.ok().build();
}
private Response handleListTagsForResource(JsonNode request, String region) {
Map<String, String> tags = service.listTagsForResource(request.path("ResourceARN").asText(null), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("Tags", tagsToArray(tags));
return Response.ok(response).build();
}
private ArrayNode tagsToArray(Map<String, String> tags) {
ArrayNode tagsArray = objectMapper.createArrayNode();
tags.forEach((k, v) -> {
ObjectNode tagNode = tagsArray.addObject();
tagNode.put("Key", k);
tagNode.put("Value", v);
});
response.put("HasMoreTags", false);
return Response.ok(response).build();
return tagsArray;
}
private Map<String, String> parseTags(JsonNode request) {
@@ -55,6 +55,8 @@ public class KinesisService implements ResourceProvider {
private static final int MAX_RECORD_SIZE_KIB = 10240;
private static final int MAX_RECORDS_PER_REQUEST = 500;
private static final int MAX_REQUEST_SIZE_BYTES = 10 * 1024 * 1024;
private static final Pattern VALID_RESOURCE_TAG_CHARACTERS =
Pattern.compile("[\\p{L}\\p{Nd}\\s_./=+%@:-]*", Pattern.UNICODE_CHARACTER_CLASS);
/**
* UpdateShardCount's documented default limits: the per-account/region shard-per-stream
* ceiling, and how many scaling calls a stream may take in a rolling 24-hour window.
@@ -221,23 +223,34 @@ public class KinesisService implements ResourceProvider {
}
public KinesisConsumer registerStreamConsumer(String streamArn, String consumerName, String region) {
return registerStreamConsumer(streamArn, consumerName, Map.of(), region);
}
public KinesisConsumer registerStreamConsumer(String streamArn, String consumerName,
Map<String, String> tags, String region) {
validateResourceTagLimit(Map.of(), tags);
String consumerArn = streamArn + "/consumer/" + consumerName + ":" + System.currentTimeMillis();
KinesisConsumer consumer = new KinesisConsumer(consumerName, consumerArn, streamArn);
consumerStore.put(region + "::" + consumerArn, consumer);
consumer.getTags().putAll(tags);
synchronized (consumerStore) {
consumerStore.put(regionKey(region, consumerArn), consumer);
}
LOG.infov("Registered Kinesis consumer: {0} for stream {1}", consumerName, streamArn);
return consumer;
}
public void deregisterStreamConsumer(String streamArn, String consumerName, String consumerArn, String region) {
String resolvedArn = consumerArn;
if (resolvedArn == null && streamArn != null && consumerName != null) {
resolvedArn = consumerStore.scan(k -> true).stream()
.filter(c -> c.getStreamArn().equals(streamArn) && c.getConsumerName().equals(consumerName))
.findFirst().map(KinesisConsumer::getConsumerArn).orElse(null);
}
if (resolvedArn != null) {
consumerStore.delete(region + "::" + resolvedArn);
LOG.infov("Deregistered Kinesis consumer: {0}", resolvedArn);
synchronized (consumerStore) {
String resolvedArn = consumerArn;
if (resolvedArn == null && streamArn != null && consumerName != null) {
resolvedArn = consumerStore.scan(k -> true).stream()
.filter(c -> c.getStreamArn().equals(streamArn) && c.getConsumerName().equals(consumerName))
.findFirst().map(KinesisConsumer::getConsumerArn).orElse(null);
}
if (resolvedArn != null) {
consumerStore.delete(regionKey(region, resolvedArn));
LOG.infov("Deregistered Kinesis consumer: {0}", resolvedArn);
}
}
}
@@ -291,6 +304,95 @@ public class KinesisService implements ResourceProvider {
return resolveStream(streamName, region).getTags();
}
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
if (isConsumerTagResource(resourceArn, region)) {
String key = regionKey(region, resourceArn);
synchronized (consumerStore) {
KinesisConsumer consumer = resolveConsumerForTags(key);
validateResourceTagLimit(consumer.getTags(), tags);
consumer.getTags().putAll(tags);
consumerStore.put(key, consumer);
}
return;
}
String streamName = streamNameFromTagArn(resourceArn);
String key = regionKey(region, streamName);
synchronized (lockFor(key)) {
KinesisStream stream = describeStreamByArn(resourceArn, region);
validateResourceTagLimit(stream.getTags(), tags);
stream.getTags().putAll(tags);
store.put(key, stream);
}
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
if (isConsumerTagResource(resourceArn, region)) {
String key = regionKey(region, resourceArn);
synchronized (consumerStore) {
KinesisConsumer consumer = resolveConsumerForTags(key);
tagKeys.forEach(consumer.getTags()::remove);
consumerStore.put(key, consumer);
}
return;
}
String streamName = streamNameFromTagArn(resourceArn);
String key = regionKey(region, streamName);
synchronized (lockFor(key)) {
KinesisStream stream = describeStreamByArn(resourceArn, region);
tagKeys.forEach(stream.getTags()::remove);
store.put(key, stream);
}
}
public Map<String, String> listTagsForResource(String resourceArn, String region) {
if (isConsumerTagResource(resourceArn, region)) {
synchronized (consumerStore) {
return new HashMap<>(resolveConsumerForTags(regionKey(region, resourceArn)).getTags());
}
}
String streamName = streamNameFromTagArn(resourceArn);
synchronized (lockFor(regionKey(region, streamName))) {
return new HashMap<>(describeStreamByArn(resourceArn, region).getTags());
}
}
private boolean isConsumerTagResource(String resourceArn, String region) {
AwsArnUtils.Arn arn = AwsArnUtils.parseIfArnIn(resourceArn, "kinesis", region)
.orElseThrow(() -> new AwsException("InvalidArgumentException",
"ResourceARN must name a Kinesis resource in this region", 400));
if (!arn.accountId().equals(regionResolver.getAccountId())) {
throw new AwsException("ResourceNotFoundException", "Kinesis resource not found", 400);
}
if (!arn.resource().startsWith("stream/")) {
throw new AwsException("InvalidArgumentException", "ResourceARN must name a stream or consumer", 400);
}
return arn.resource().contains("/consumer/");
}
private String streamNameFromTagArn(String resourceArn) {
return AwsArnUtils.parse(resourceArn).resource().substring("stream/".length());
}
private KinesisConsumer resolveConsumerForTags(String key) {
return consumerStore.get(key)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Consumer not found", 400));
}
private void validateResourceTagLimit(Map<String, String> current, Map<String, String> added) {
for (Map.Entry<String, String> entry : added.entrySet()) {
if (entry.getKey() == null || !VALID_RESOURCE_TAG_CHARACTERS.matcher(entry.getKey()).matches()
|| entry.getKey().regionMatches(true, 0, "aws:", 0, 4)
|| entry.getValue() == null || !VALID_RESOURCE_TAG_CHARACTERS.matcher(entry.getValue()).matches()) {
throw new AwsException("InvalidArgumentException", "Invalid tag key or value", 400);
}
}
Set<String> keys = new HashSet<>(current.keySet());
keys.addAll(added.keySet());
if (keys.size() > 50 && added.keySet().stream().anyMatch(key -> !current.containsKey(key))) {
throw new AwsException("LimitExceededException", "A Kinesis resource can have at most 50 tags", 400);
}
}
public void startStreamEncryption(String streamName, String encryptionType, String keyId, String region) {
String key = regionKey(region, streamName);
synchronized (lockFor(key)) {
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -13,6 +15,7 @@ public class KinesisConsumer {
private String consumerStatus;
private Instant consumerCreationTimestamp;
private String streamArn;
private Map<String, String> tags = new HashMap<>();
public KinesisConsumer() {}
@@ -38,4 +41,7 @@ public class KinesisConsumer {
public String getStreamArn() { return streamArn; }
public void setStreamArn(String streamArn) { this.streamArn = streamArn; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new HashMap<>() : tags; }
}
@@ -1105,6 +1105,75 @@ class KinesisIntegrationTest {
.body("Records.size()", equalTo(2));
}
@Test
@Order(59)
void consumerResourceTagsRoundTripOverJsonProtocol() {
createStream("resource-tags-test", 1);
String streamArn = given()
.header("X-Amz-Target", "Kinesis_20131202.DescribeStreamSummary")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"StreamName\":\"resource-tags-test\"}")
.when().post("/")
.then().statusCode(200)
.extract().jsonPath().getString("StreamDescriptionSummary.StreamARN");
String consumerArn = given()
.header("X-Amz-Target", "Kinesis_20131202.RegisterStreamConsumer")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"StreamARN\":\"" + streamArn + "\",\"ConsumerName\":\"tagged-consumer\","
+ "\"Tags\":{\"team\":\"red\"}}")
.when().post("/")
.then().statusCode(200)
.extract().jsonPath().getString("Consumer.ConsumerARN");
given()
.header("X-Amz-Target", "Kinesis_20131202.ListTagsForResource")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ResourceARN\":\"" + consumerArn + "\"}")
.when().post("/")
.then().statusCode(200)
.body("Tags.size()", equalTo(1))
.body("Tags[0].Key", equalTo("team"))
.body("Tags[0].Value", equalTo("red"))
.body("HasMoreTags", nullValue());
Response tagged = given()
.header("X-Amz-Target", "Kinesis_20131202.TagResource")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ResourceARN\":\"" + consumerArn + "\",\"Tags\":{\"env\":\"dev\"}}")
.when().post("/")
.then().statusCode(200)
.extract().response();
assertEquals("", tagged.asString());
given()
.header("X-Amz-Target", "Kinesis_20131202.ListTagsForResource")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ResourceARN\":\"" + consumerArn + "\"}")
.when().post("/")
.then().statusCode(200)
.body("Tags.Key", hasItems("team", "env"));
Response untagged = given()
.header("X-Amz-Target", "Kinesis_20131202.UntagResource")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ResourceARN\":\"" + consumerArn + "\",\"TagKeys\":[\"team\"]}")
.when().post("/")
.then().statusCode(200)
.extract().response();
assertEquals("", untagged.asString());
given()
.header("X-Amz-Target", "Kinesis_20131202.ListTagsForResource")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ResourceARN\":\"" + consumerArn + "\"}")
.when().post("/")
.then().statusCode(200)
.body("Tags.size()", equalTo(1))
.body("Tags[0].Key", equalTo("env"));
}
@Test
@Order(60)
void subscribeToShard_returnsRecords() throws Exception {
@@ -15,6 +15,8 @@ import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
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.math.BigDecimal;
@@ -26,6 +28,7 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -132,6 +135,243 @@ class KinesisJsonHandlerTest {
assertThat(handler.handle("CreateStream", req, REGION).getStatus(), is(200));
}
@Test
void registerStreamConsumerPreservesTagsForResourceOperations() {
createStream("test-stream");
ObjectNode registration = MAPPER.createObjectNode()
.put("StreamARN", STREAM_ARN)
.put("ConsumerName", "tagged-consumer");
registration.putObject("Tags").put("team", "red");
String consumerArn = responseEntity(handler.handle("RegisterStreamConsumer", registration, REGION))
.path("Consumer").path("ConsumerARN").asText();
ObjectNode resource = MAPPER.createObjectNode().put("ResourceARN", consumerArn);
Response listed = handler.handle("ListTagsForResource", resource, REGION);
assertEquals(200, listed.getStatus());
assertEquals("team", responseEntity(listed).path("Tags").get(0).path("Key").asText());
assertEquals("red", responseEntity(listed).path("Tags").get(0).path("Value").asText());
ObjectNode tagRequest = resource.deepCopy();
tagRequest.putObject("Tags").put("env", "dev");
assertEquals(200, handler.handle("TagResource", tagRequest, REGION).getStatus());
JsonNode tags = responseEntity(handler.handle("ListTagsForResource", resource, REGION)).path("Tags");
assertEquals(2, tags.size());
assertEquals("red", tagValue(tags, "team"));
assertEquals("dev", tagValue(tags, "env"));
}
@Test
void resourceTagOperationsKeepStreamAndConsumerTagsSeparate() {
createStream("test-stream");
String consumerArn = service.registerStreamConsumer(STREAM_ARN, "tagged-consumer", REGION)
.getConsumerArn();
ObjectNode streamRequest = MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN);
streamRequest.putObject("Tags").put("owner", "stream");
assertEquals(200, handler.handle("TagResource", streamRequest, REGION).getStatus());
ObjectNode consumerRequest = MAPPER.createObjectNode().put("ResourceARN", consumerArn);
consumerRequest.putObject("Tags").put("owner", "consumer");
assertEquals(200, handler.handle("TagResource", consumerRequest, REGION).getStatus());
ObjectNode streamArnOnly = MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN);
ObjectNode consumerArnOnly = MAPPER.createObjectNode().put("ResourceARN", consumerArn);
assertEquals("stream", tagValue(responseEntity(handler.handle("ListTagsForResource", streamArnOnly, REGION))
.path("Tags"), "owner"));
assertEquals("consumer", tagValue(responseEntity(handler.handle("ListTagsForResource", consumerArnOnly, REGION))
.path("Tags"), "owner"));
consumerArnOnly.putArray("TagKeys").add("owner");
assertEquals(200, handler.handle("UntagResource", consumerArnOnly, REGION).getStatus());
consumerArnOnly.remove("TagKeys");
assertEquals(0, responseEntity(handler.handle("ListTagsForResource", consumerArnOnly, REGION))
.path("Tags").size());
assertEquals("stream", tagValue(responseEntity(handler.handle("ListTagsForResource", streamArnOnly, REGION))
.path("Tags"), "owner"));
ObjectNode legacyList = MAPPER.createObjectNode().put("StreamName", "test-stream");
assertEquals("stream", tagValue(responseEntity(handler.handle("ListTagsForStream", legacyList, REGION))
.path("Tags"), "owner"));
streamArnOnly.putArray("TagKeys").add("owner");
assertEquals(200, handler.handle("UntagResource", streamArnOnly, REGION).getStatus());
streamArnOnly.remove("TagKeys");
assertEquals(0, responseEntity(handler.handle("ListTagsForResource", streamArnOnly, REGION))
.path("Tags").size());
assertEquals(0, responseEntity(handler.handle("ListTagsForResource", consumerArnOnly, REGION))
.path("Tags").size());
}
@Test
void resourceTagsRejectForeignAndMissingResources() {
createStream("test-stream");
String consumerArn = service.registerStreamConsumer(STREAM_ARN, "tagged-consumer", REGION)
.getConsumerArn();
ObjectNode request = MAPPER.createObjectNode();
request.put("ResourceARN", consumerArn.replace(ACCOUNT, "999999999999"));
AwsException foreign = assertThrows(AwsException.class,
() -> handler.handle("ListTagsForResource", request, REGION));
assertEquals("ResourceNotFoundException", foreign.getErrorCode());
request.put("ResourceARN", consumerArn.replace(REGION, "us-west-2"));
AwsException otherRegion = assertThrows(AwsException.class,
() -> handler.handle("ListTagsForResource", request, REGION));
assertEquals("InvalidArgumentException", otherRegion.getErrorCode());
service.deregisterStreamConsumer(null, null, consumerArn, REGION);
request.put("ResourceARN", consumerArn);
AwsException deleted = assertThrows(AwsException.class,
() -> handler.handle("ListTagsForResource", request, REGION));
assertEquals("ResourceNotFoundException", deleted.getErrorCode());
}
@Test
void resourceTagsEnforceCapacityWithoutPartialWrites() {
createStream("test-stream");
ObjectNode request = MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN);
ObjectNode tags = request.putObject("Tags");
for (int i = 0; i < 50; i++) {
tags.put("key" + i, "value");
}
assertEquals(200, handler.handle("TagResource", request, REGION).getStatus());
request.set("Tags", MAPPER.createObjectNode().put("overflow", "value"));
AwsException overLimit = assertThrows(AwsException.class,
() -> handler.handle("TagResource", request, REGION));
assertEquals("LimitExceededException", overLimit.getErrorCode());
ObjectNode list = MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN);
assertEquals(50, responseEntity(handler.handle("ListTagsForResource", list, REGION)).path("Tags").size());
request.set("Tags", MAPPER.createObjectNode().put("key0", "updated"));
assertEquals(200, handler.handle("TagResource", request, REGION).getStatus());
assertEquals("updated", tagValue(responseEntity(handler.handle("ListTagsForResource", list, REGION))
.path("Tags"), "key0"));
}
@Test
void tagResourceRejectsInvalidCharactersWithoutChangingEitherResource() {
createStream("test-stream");
String consumerArn = service.registerStreamConsumer(STREAM_ARN, "tagged-consumer", REGION)
.getConsumerArn();
for (String arn : List.of(STREAM_ARN, consumerArn)) {
ObjectNode request = MAPPER.createObjectNode().put("ResourceARN", arn);
request.putObject("Tags").put("valid", "initial");
assertEquals(200, handler.handle("TagResource", request, REGION).getStatus());
for (String key : List.of("bad*key")) {
request.set("Tags", MAPPER.createObjectNode().put(key, "value"));
AwsException badKey = assertThrows(AwsException.class,
() -> handler.handle("TagResource", request, REGION));
assertEquals("InvalidArgumentException", badKey.getErrorCode());
}
for (String value : List.of("bad*value")) {
request.set("Tags", MAPPER.createObjectNode().put("valid", value));
AwsException badValue = assertThrows(AwsException.class,
() -> handler.handle("TagResource", request, REGION));
assertEquals("InvalidArgumentException", badValue.getErrorCode());
}
JsonNode tags = responseEntity(handler.handle("ListTagsForResource",
MAPPER.createObjectNode().put("ResourceARN", arn), REGION)).path("Tags");
assertEquals(1, tags.size());
assertEquals("initial", tagValue(tags, "valid"));
}
}
@Test
void tagResourceAcceptsDocumentedUnicodeAndSymbols() {
createStream("test-stream");
String consumerArn = service.registerStreamConsumer(STREAM_ARN, "tagged-consumer", REGION)
.getConsumerArn();
String key = "\u00c9quipe_./=+@-:%9";
String value = "\u7a7a \u767d%:";
for (String arn : List.of(STREAM_ARN, consumerArn)) {
ObjectNode request = MAPPER.createObjectNode().put("ResourceARN", arn);
request.putObject("Tags").put(key, value);
assertEquals(200, handler.handle("TagResource", request, REGION).getStatus());
JsonNode tags = responseEntity(handler.handle("ListTagsForResource",
MAPPER.createObjectNode().put("ResourceARN", arn), REGION)).path("Tags");
assertEquals(value, tagValue(tags, key));
}
}
@Test
void tagResourceRejectsReservedTagKeyPrefix() {
createStream("test-stream");
String consumerArn = service.registerStreamConsumer(STREAM_ARN, "tagged-consumer", REGION)
.getConsumerArn();
for (String arn : List.of(STREAM_ARN, consumerArn)) {
ObjectNode request = MAPPER.createObjectNode().put("ResourceARN", arn);
request.putObject("Tags").put("AWS:owner", "user");
AwsException reserved = assertThrows(AwsException.class,
() -> handler.handle("TagResource", request, REGION));
assertEquals("InvalidArgumentException", reserved.getErrorCode());
assertEquals(0, responseEntity(handler.handle("ListTagsForResource",
MAPPER.createObjectNode().put("ResourceARN", arn), REGION)).path("Tags").size());
}
}
@Test
void tagResourceUpdatesLegacyStreamBeyondCapacityWithoutAddingKeys() {
createStream("test-stream");
ObjectNode add = MAPPER.createObjectNode().put("StreamName", "test-stream");
ObjectNode legacyTags = add.putObject("Tags");
for (int i = 0; i < 51; i++) {
legacyTags.put("key" + i, "old");
}
assertEquals(200, handler.handle("AddTagsToStream", add, REGION).getStatus());
ObjectNode request = MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN);
request.putObject("Tags").put("key0", "updated");
assertEquals(200, handler.handle("TagResource", request, REGION).getStatus());
request.set("Tags", MAPPER.createObjectNode().put("key1", "would-change").put("new", "value"));
AwsException overLimit = assertThrows(AwsException.class,
() -> handler.handle("TagResource", request, REGION));
assertEquals("LimitExceededException", overLimit.getErrorCode());
JsonNode tags = responseEntity(handler.handle("ListTagsForResource",
MAPPER.createObjectNode().put("ResourceARN", STREAM_ARN), REGION)).path("Tags");
assertEquals(51, tags.size());
assertEquals("updated", tagValue(tags, "key0"));
assertEquals("old", tagValue(tags, "key1"));
}
private static Stream<Arguments> rejectedRegistrationTags() {
ObjectNode tooManyTags = MAPPER.createObjectNode();
for (int i = 0; i < 51; i++) {
tooManyTags.put("key" + i, "value");
}
return Stream.of(
Arguments.of("empty map", MAPPER.createObjectNode(), "InvalidArgumentException"),
Arguments.of("invalid key", MAPPER.createObjectNode().put("bad*key", "value"),
"InvalidArgumentException"),
Arguments.of("reserved prefix", MAPPER.createObjectNode().put("aws:owner", "user"),
"InvalidArgumentException"),
Arguments.of("over capacity", tooManyTags, "LimitExceededException"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("rejectedRegistrationTags")
void invalidRegistrationTagsDoNotCreateConsumer(String scenario, JsonNode tags, String errorCode) {
createStream("test-stream");
ObjectNode request = MAPPER.createObjectNode()
.put("StreamARN", STREAM_ARN)
.put("ConsumerName", "tagged-consumer");
request.set("Tags", tags);
AwsException error = assertThrows(AwsException.class,
() -> handler.handle("RegisterStreamConsumer", request, REGION));
assertEquals(errorCode, error.getErrorCode());
assertTrue(service.listStreamConsumers(STREAM_ARN, REGION).isEmpty());
}
private String tagValue(JsonNode tags, String key) {
for (JsonNode tag : tags) {
if (key.equals(tag.path("Key").asText())) {
return tag.path("Value").asText();
}
}
return null;
}
private ObjectNode responseEntity(Response response) {
return (ObjectNode) response.getEntity();
}