feat(xray): support TagResource, UntagResource and ListTagsForResource (#10067)

XrayRouteFilter now claims /TagResource, /UntagResource and /ListTagsForResource, so an xray-signed call there no longer reaches Marketplace Catalog's handler, and CreateSamplingRule keeps its Tags. A sampling rule's tags are changed and read by the rule's ARN, with AWS's key, value and 50-tag limits; a group's ARN, the Default rule's, or one from another Region or account answers ResourceNotFoundException with "Resource <arn> not found". IAM reads a rule's tags for aws:ResourceTag conditions.
This commit is contained in:
soreavis authored and GitHub committed 2026-12-03 15:07:57 -04:00
1 parent b95c6b21e2
commit fcd6a89300
12 files changed
+732 -4

No files matched your search

@@ -9,10 +9,12 @@ import software.amazon.awssdk.services.xray.model.BatchGetTracesResponse;
import software.amazon.awssdk.services.xray.model.GetSamplingTargetsResponse;
import software.amazon.awssdk.services.xray.model.GetServiceGraphResponse;
import software.amazon.awssdk.services.xray.model.GetTraceSummariesResponse;
import software.amazon.awssdk.services.xray.model.ResourceNotFoundException;
import software.amazon.awssdk.services.xray.model.SamplingRuleRecord;
import software.amazon.awssdk.services.xray.model.SamplingStatisticsDocument;
import software.amazon.awssdk.services.xray.model.Service;
import software.amazon.awssdk.services.xray.model.ServiceId;
import software.amazon.awssdk.services.xray.model.Tag;
import software.amazon.awssdk.services.xray.model.TraceSummary;
import java.time.Instant;
@@ -20,8 +22,11 @@ import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.assertj.core.api.Assertions.within;
class XrayTest {
@@ -136,6 +141,34 @@ class XrayTest {
assertThat(response.unprocessedStatistics()).isEmpty();
}
@Test
@DisplayName("A sampling rule keeps its create-time tags, and the tag calls change and list them by its ARN")
void samplingRuleTags() {
String name = "sdk-tags-" + UUID.randomUUID().toString().substring(0, 8);
String arn = xray.createSamplingRule(r -> r
.samplingRule(rule -> rule.ruleName(name).priority(9000).fixedRate(0.1).reservoirSize(1)
.serviceName("*").serviceType("*").host("*").httpMethod("*").urlPath("*")
.resourceARN("*").version(1))
.tags(Tag.builder().key("team").value("orders").build()))
.samplingRuleRecord().samplingRule().ruleARN();
try {
assertThat(xray.listTagsForResource(r -> r.resourceARN(arn)).tags())
.extracting(Tag::key, Tag::value)
.containsExactly(tuple("team", "orders"));
xray.tagResource(r -> r.resourceARN(arn).tags(Tag.builder().key("env").value("local").build()));
xray.untagResource(r -> r.resourceARN(arn).tagKeys("team"));
assertThat(xray.listTagsForResource(r -> r.resourceARN(arn)).tags())
.extracting(Tag::key, Tag::value)
.containsExactly(tuple("env", "local"));
assertThatThrownBy(() -> xray.listTagsForResource(r -> r.resourceARN(arn + "-gone")))
.isInstanceOf(ResourceNotFoundException.class);
} finally {
xray.deleteSamplingRule(r -> r.ruleName(name));
}
}
@Test
@DisplayName("GetServiceGraph answers one node per service and the call between them")
void serviceGraph() {
+1 -1
View File
@@ -4095,7 +4095,7 @@ floci populates:
groups, cache clusters, snapshots, subnet groups, parameter groups and serverless caches, DMS for its endpoints,
replication instances, replication tasks and replication subnet groups, SageMaker for its models, endpoint
configurations, endpoints and training jobs, BCM Data Exports for its exports, Rekognition for its collections,
Macie for its member accounts, API Gateway for its REST APIs,
Macie for its member accounts, X-Ray for its sampling rules, API Gateway for its REST APIs,
stages, custom domain names, API keys, usage plans and VPC links and its HTTP and WebSocket APIs and their stages,
S3 for its general purpose buckets once ABAC is enabled on them (`PutBucketAbac`), S3 evaluating the key "only
after you enable ABAC on your bucket", and Amazon Managed Service for Prometheus for its workspaces and rule
+1 -1
View File
@@ -65,7 +65,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 54 |
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 26 |
| [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 |
| [X-Ray](xray.md) | `/TraceSegments`, `/Traces`, `/TraceSummaries`, `/ServiceGraph`, `/TraceGraph`, `/GetSamplingRules`, `/CreateSamplingRule`, `/SamplingTargets`, `/TelemetryRecords` | REST JSON | 11 |
| [X-Ray](xray.md) | `/TraceSegments`, `/Traces`, `/TraceSummaries`, `/ServiceGraph`, `/TraceGraph`, `/GetSamplingRules`, `/CreateSamplingRule`, `/SamplingTargets`, `/TelemetryRecords`, `/TagResource`, `/UntagResource`, `/ListTagsForResource` | REST JSON | 14 |
| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 25 |
| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact`, `/putContactInformation`, `/getContactInformation`, `/getAccountInformation`, `/putAccountName` | REST JSON | 7 |
| [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}`, `/policy/validation` | REST JSON | 5 |
+10 -1
View File
@@ -53,6 +53,9 @@ printf '{"format": "json", "version": 1}\n%s\n' \
| `DeleteSamplingRule` | Deletes a rule by name or ARN; the `Default` rule cannot be deleted. |
| `GetSamplingTargets` | Answers the fixed rate and reservoir quota the daemon should sample at. |
| `PutTelemetryRecords` | Accepts the segment and connection counters the daemon reports. |
| `TagResource` | Adds or replaces tags on a sampling rule, up to 50 per rule. |
| `UntagResource` | Removes tags from a sampling rule by key. |
| `ListTagsForResource` | Lists the tags of a sampling rule. |
<!-- floci:actions:end -->
`PutTraceSegments` accepts up to 100 documents per call and reports the ones it refuses
@@ -78,10 +81,16 @@ answers each rule's fixed rate with its reservoir size as the quota, renewed eve
`LastRuleModification` moves when any rule of the Region changes, so a daemon that did not name the
changed rule still refetches the set.
A sampling rule keeps the `Tags` it was created with, and the tagging operations change them by the
rule's ARN. IAM reads them for `aws:ResourceTag/<key>` conditions. A key beginning with `aws:` is
refused, as is a 51st tag. `ListTagsForResource` answers every tag in one page and ignores
`NextToken`. Groups are not served and the `Default` rule is not stored, so their ARNs answer
`ResourceNotFoundException`.
## Not emulated
Floci stores, serves and aggregates traces; it does not analyse them. Insights, trace retrieval
jobs, indexing rules, groups and tags are not served: their paths are not claimed by this service, so
jobs, indexing rules and groups are not served: their paths are not claimed by this service, so
a call to them reaches whatever else claims the path (S3's `/{bucket}` routes) rather than answering
an AWS-shaped error.
@@ -352,6 +352,33 @@ public class XrayController {
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/TagResource")
public Response tagResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
xrayService.tagResource(readTree(body), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/UntagResource")
public Response untagResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
xrayService.untagResource(readTree(body), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/ListTagsForResource")
public Response listTagsForResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode tags = response.putArray("Tags");
xrayService.tagsForResource(readTree(body), region)
.forEach((key, value) -> tags.addObject().put("Key", key).put("Value", value));
return Response.ok(response).build();
}
private ObjectNode samplingRuleRecord(SamplingRule rule) {
ObjectNode record = objectMapper.createObjectNode();
ObjectNode ruleNode = record.putObject("SamplingRule");
@@ -30,7 +30,8 @@ public class XrayRouteFilter implements ContainerRequestFilter {
private static final Set<String> SERVED_PATHS = Set.of("/TraceSegments", "/Traces",
"/TraceSummaries", "/ServiceGraph", "/TraceGraph", "/GetSamplingRules",
"/CreateSamplingRule", "/UpdateSamplingRule", "/DeleteSamplingRule",
"/SamplingTargets", "/TelemetryRecords");
"/SamplingTargets", "/TelemetryRecords", "/TagResource", "/UntagResource",
"/ListTagsForResource");
private static final Predicate<String> PUBLIC_PATHS = SERVED_PATHS::contains;
@@ -377,6 +377,10 @@ public class XrayService implements Resettable {
private static final int MAX_SAMPLING_RULES = 25;
/** The daemon asks for targets every 10 seconds, so that is the quota's lifetime. */
private static final int SAMPLING_INTERVAL_SECONDS = 10;
/** AWS allows fifty user tags on a sampling rule. */
private static final int MAX_TAGS = 50;
/** A tag call lists at most two hundred tags or tag keys. */
private static final int MAX_TAGS_PER_CALL = 200;
/** One target the daemon should sample at, for a client and a rule. */
public record Target(String ruleName, Double fixedRate, Integer reservoirQuota,
@@ -409,6 +413,13 @@ public class XrayService implements Resettable {
private SamplingRule createSamplingRuleLocked(JsonNode request, String region) {
SamplingRule requested = parseRule(requireObject(request.path("SamplingRule"), "SamplingRule"));
if (request.path("Tags").isArray()) {
Map<String, String> tags = tags(request.path("Tags"));
if (tags.size() > MAX_TAGS) {
throw validation("A sampling rule takes at most " + MAX_TAGS + " tags.");
}
requested.setTags(tags);
}
String key = storageKey(region, requested.getRuleName());
if (DEFAULT_RULE_NAME.equals(requested.getRuleName())) {
throw validation("Sampling rule name " + DEFAULT_RULE_NAME + " is reserved.");
@@ -562,6 +573,98 @@ public class XrayService implements Resettable {
return records.size();
}
public Map<String, String> tagsForResource(JsonNode request, String region) {
requireObject(request, "Request payload");
return taggedRule(request, region).getTags();
}
public void tagResource(JsonNode request, String region) {
requireObject(request, "Request payload");
synchronized (lockFor(region)) {
SamplingRule rule = taggedRule(request, region).copy();
rule.getTags().putAll(tags(request.path("Tags")));
if (rule.getTags().size() > MAX_TAGS) {
throw new AwsException("TooManyTagsException",
"A sampling rule takes at most " + MAX_TAGS + " tags.", 400);
}
rules.put(storageKey(region, rule.getRuleName()), rule);
}
}
public void untagResource(JsonNode request, String region) {
requireObject(request, "Request payload");
synchronized (lockFor(region)) {
SamplingRule rule = taggedRule(request, region).copy();
JsonNode keys = request.path("TagKeys");
if (!keys.isArray() || keys.size() > MAX_TAGS_PER_CALL) {
throw validation("TagKeys must be a list of at most " + MAX_TAGS_PER_CALL + " keys.");
}
for (JsonNode key : keys) {
if (!isString(key, 1, 128)) {
throw validation("Each TagKeys entry is a key of 1 to 128 characters.");
}
rule.getTags().remove(key.stringValue());
}
rules.put(storageKey(region, rule.getRuleName()), rule);
}
}
/** The tags IAM reads for the sampling rule an ARN names, in the ARN's own account and Region. */
Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, SERVICE)) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
if (!parsed.resource().startsWith("sampling-rule/")) {
return Map.of();
}
return AccountAwareStorageBackend.readInAccount(rules, parsed.accountId(),
storageKey(parsed.region(), parsed.resource().substring("sampling-rule/".length())))
.filter(rule -> arn.equals(rule.getRuleArn()))
.map(SamplingRule::getTags)
.orElse(Map.of());
}
/**
* The stored rule a tag call's ResourceARN names. Groups are not served and the Default rule is
* synthesised, never stored, so neither is found.
*/
private SamplingRule taggedRule(JsonNode request, String region) {
String arn = requiredText(request, "ResourceARN");
return rules.scan(key -> key.startsWith(region + "::")).stream()
.filter(rule -> arn.equals(rule.getRuleArn()))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Resource " + arn + " not found", 404));
}
/** The tags a request lists, refused whole when one breaks the limits AWS documents for them. */
private static Map<String, String> tags(JsonNode list) {
if (!list.isArray() || list.size() > MAX_TAGS_PER_CALL) {
throw validation("Tags must be a list of at most " + MAX_TAGS_PER_CALL + " tags.");
}
Map<String, String> tags = new LinkedHashMap<>();
for (JsonNode tag : list) {
JsonNode key = tag.path("Key");
JsonNode value = tag.path("Value");
if (!isString(key, 1, 128) || key.stringValue().startsWith("aws:") || !isString(value, 0, 256)) {
throw validation("Each tag needs a Key of 1 to 128 characters that does not begin with aws:"
+ " and a Value of at most 256.");
}
tags.put(key.stringValue(), value.stringValue());
}
return tags;
}
/** Whether a node is a string of min to max characters, counted by code point as AWS counts them. */
private static boolean isString(JsonNode node, int min, int max) {
if (!node.isString()) {
return false;
}
int characters = node.stringValue().codePointCount(0, node.stringValue().length());
return characters >= min && characters <= max;
}
/** The rule AWS serves in every Region, so a daemon always has something to sample at. */
private SamplingRule defaultRule(String region) {
long now = Instant.now().getEpochSecond();
@@ -0,0 +1,40 @@
package io.floci.aws.services.xray;
import io.floci.aws.core.common.StoredResourceArns;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* What IAM asks X-Ray of the resources a request names: the tags X-Ray holds on a sampling rule, which an
* {@code aws:ResourceTag} condition reads.
*/
@ApplicationScoped
public class XrayStoredResourceArns implements StoredResourceArns {
private final XrayService xray;
@Inject
public XrayStoredResourceArns(XrayService xray) {
this.xray = xray;
}
@Override
public String namespace() {
return XrayService.SERVICE;
}
/** X-Ray stores no resource a request names but by its ARN or its format's variables. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Map<String, String> storedTags(String arn) {
return StoredResourceArns.withEmptyValues(xray.storedTags(arn));
}
}
@@ -28,6 +28,7 @@ public class SamplingRule {
private String urlPath;
private Integer version;
private Map<String, String> attributes = new LinkedHashMap<>();
private Map<String, String> tags = new LinkedHashMap<>();
private long createdAt;
private long modifiedAt;
@@ -50,6 +51,7 @@ public class SamplingRule {
copy.urlPath = urlPath;
copy.version = version;
copy.attributes = new LinkedHashMap<>(attributes);
copy.tags = new LinkedHashMap<>(tags);
copy.createdAt = createdAt;
copy.modifiedAt = modifiedAt;
return copy;
@@ -159,6 +161,14 @@ public class SamplingRule {
this.attributes = attributes == null ? new LinkedHashMap<>() : attributes;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new LinkedHashMap<>() : tags;
}
public long getCreatedAt() {
return createdAt;
}
@@ -81,6 +81,145 @@ class XrayIamEnforcementIntegrationTest {
.then().statusCode(200);
}
@Test
void aKeyAllowedToListTagsIsRefusedTheCallsThatChangeThem() {
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["xray:CreateSamplingRule","xray:ListTagsForResource"],"Resource":"*"}]}
""");
String name = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
String arn = "arn:aws:xray:us-east-1:" + ACCOUNT + ":sampling-rule/" + name;
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body(ruleBody(name, ",\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]"))
.when().post("/CreateSamplingRule")
.then().statusCode(403);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body(ruleBody(name, ""))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"ResourceARN\":\"" + arn + "\"}")
.when().post("/ListTagsForResource")
.then().statusCode(200).body("Tags.size()", equalTo(0));
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body("{\"ResourceARN\":\"" + arn + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]}")
.when().post("/TagResource")
.then().statusCode(403);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[\"team\"]}")
.when().post("/UntagResource")
.then().statusCode(403);
}
@Test
void aKeyAllowedTheTagCallsOnOneRuleTagsItAndNoOther() {
String name = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
String other = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
String arn = "arn:aws:xray:us-east-1:" + ACCOUNT + ":sampling-rule/" + name;
String otherArn = "arn:aws:xray:us-east-1:" + ACCOUNT + ":sampling-rule/" + other;
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["xray:CreateSamplingRule","xray:TagResource","xray:UntagResource"],"Resource":"%s"}]}
""".formatted(arn));
given().header("Authorization", auth(allowedKey, "xray"))
.contentType("application/json").body(ruleBody(other, ""))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body(ruleBody(name, ""))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body("{\"ResourceARN\":\"" + arn + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]}")
.when().post("/TagResource")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[\"team\"]}")
.when().post("/UntagResource")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body("{\"ResourceARN\":\"" + otherArn + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]}")
.when().post("/TagResource")
.then().statusCode(403);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"ResourceARN\":\"" + otherArn + "\",\"TagKeys\":[\"team\"]}")
.when().post("/UntagResource")
.then().statusCode(403);
}
@Test
void aDenyOnAResourceTagHoldsWhileTheRuleCarriesTheTag() {
String name = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
String arn = "arn:aws:xray:us-east-1:" + ACCOUNT + ":sampling-rule/" + name;
given().header("Authorization", auth(allowedKey, "xray"))
.contentType("application/json")
.body(ruleBody(name, ",\"Tags\":[{\"Key\":\"protected\",\"Value\":\"true\"}]"))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"xray:*","Resource":"*"},
{"Effect":"Deny","Action":"xray:DeleteSamplingRule","Resource":"*",
"Condition":{"StringEquals":{"aws:ResourceTag/protected":"true"}}}]}
""");
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"RuleName\":\"" + name + "\"}")
.when().post("/DeleteSamplingRule")
.then().statusCode(403);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[\"protected\"]}")
.when().post("/UntagResource")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json").body("{\"RuleName\":\"" + name + "\"}")
.when().post("/DeleteSamplingRule")
.then().statusCode(200);
}
@Test
void anAllowOnAResourceTagAdmitsOnlyTheTaggedRule() {
String tagged = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
String untagged = "iam-tags-" + UUID.randomUUID().toString().substring(0, 8);
given().header("Authorization", auth(allowedKey, "xray"))
.contentType("application/json")
.body(ruleBody(tagged, ",\"Tags\":[{\"Key\":\"team\",\"Value\":\"orders\"}]"))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
given().header("Authorization", auth(allowedKey, "xray"))
.contentType("application/json").body(ruleBody(untagged, ""))
.when().post("/CreateSamplingRule")
.then().statusCode(200);
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"xray:UpdateSamplingRule",
"Resource":"*","Condition":{"StringEquals":{"aws:ResourceTag/team":"orders"}}}]}
""");
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body("{\"SamplingRuleUpdate\":{\"RuleName\":\"" + tagged + "\",\"Priority\":7}}")
.when().post("/UpdateSamplingRule")
.then().statusCode(200);
given().header("Authorization", auth(key, "xray"))
.contentType("application/json")
.body("{\"SamplingRuleUpdate\":{\"RuleName\":\"" + untagged + "\",\"Priority\":7}}")
.when().post("/UpdateSamplingRule")
.then().statusCode(403);
}
private static String ruleBody(String name, String tags) {
return "{\"SamplingRule\":{\"RuleName\":\"" + name + "\",\"Priority\":5,\"FixedRate\":0.5,"
+ "\"ReservoirSize\":1,\"ServiceName\":\"*\",\"ServiceType\":\"*\",\"Host\":\"*\","
+ "\"HTTPMethod\":\"*\",\"URLPath\":\"*\",\"Version\":1}" + tags + "}";
}
private static String segmentBody() {
double now = Instant.now().getEpochSecond();
String document = "{\"trace_id\":\"" + TRACE_ID + "\",\"id\":\"0f1e2d3c4b5a6978\","
@@ -277,6 +277,88 @@ class XrayIntegrationTest {
.statusCode(200);
}
@Test
void samplingRuleTagsWorkThroughTheWire() throws Exception {
String arn = "arn:aws:xray:us-east-1:000000000000:sampling-rule/tagged-rule";
xray().body(bodyOf(Map.of("SamplingRule", samplingRule("tagged-rule"),
"Tags", List.of(Map.of("Key", "team", "Value", "orders")))))
.when()
.post("/CreateSamplingRule")
.then()
.statusCode(200)
.body("SamplingRuleRecord.SamplingRule.RuleARN", equalTo(arn));
xray().body(bodyOf(Map.of("ResourceARN", arn)))
.when()
.post("/ListTagsForResource")
.then()
.statusCode(200)
.body("Tags", hasSize(1))
.body("Tags[0].Key", equalTo("team"))
.body("Tags[0].Value", equalTo("orders"));
xray().body(bodyOf(Map.of("ResourceARN", arn,
"Tags", List.of(Map.of("Key", "env", "Value", "local")))))
.when()
.post("/TagResource")
.then()
.statusCode(200);
xray().body(bodyOf(Map.of("ResourceARN", arn, "TagKeys", List.of("team"))))
.when()
.post("/UntagResource")
.then()
.statusCode(200);
xray().body(bodyOf(Map.of("ResourceARN", arn)))
.when()
.post("/ListTagsForResource")
.then()
.statusCode(200)
.body("Tags", hasSize(1))
.body("Tags[0].Key", equalTo("env"))
.body("Tags[0].Value", equalTo("local"));
xray().body(bodyOf(Map.of("ResourceARN", "arn:aws:xray:us-east-1:000000000000:sampling-rule/ghost")))
.when()
.post("/ListTagsForResource")
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void aTagCallSignedForAnotherServiceIsNotClaimedByXray() throws Exception {
String arn = "arn:aws:xray:us-east-1:000000000000:sampling-rule/unclaimed-rule";
xray().body(bodyOf(Map.of("SamplingRule", samplingRule("unclaimed-rule"))))
.when()
.post("/CreateSamplingRule")
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID
+ "/20260101/" + REGION + "/s3/aws4_request")
.body(bodyOf(Map.of("ResourceARN", arn,
"Tags", List.of(Map.of("Key", "team", "Value", "s3-claim")))))
.when()
.post("/TagResource");
xray().body(bodyOf(Map.of("ResourceARN", arn)))
.when()
.post("/ListTagsForResource")
.then()
.statusCode(200)
.body("Tags", hasSize(0));
}
private static Map<String, Object> samplingRule(String name) {
return Map.of("RuleName", name, "Priority", 5, "FixedRate", 0.5, "ReservoirSize", 4,
"ServiceName", "*", "ServiceType", "*", "Host", "*",
"HTTPMethod", "*", "URLPath", "*", "Version", 1);
}
private static RequestSpecification xray() {
return xray(REGION);
}
@@ -3,20 +3,29 @@ package io.floci.aws.services.xray;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.JacksonConfig;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.core.storage.StorageJson;
import io.floci.aws.services.xray.model.SamplingRule;
import io.floci.aws.services.xray.model.Trace;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -445,5 +454,280 @@ class XrayServiceTest {
assertEquals(1, accepted);
}
@Test
void aRuleKeepsTheTagsItWasCreatedWithAndTheTagCallsChangeThem() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"},{\"Key\":\"env\",\"Value\":\"\"}]")), REGION).getRuleArn();
assertEquals(Map.of("team", "orders", "env", ""), tags(arn));
service.tagResource(objectMapper.readTree(tagRequest(arn,
"[{\"Key\":\"team\",\"Value\":\"payments\"},{\"Key\":\"tier\",\"Value\":\"gold\"}]")), REGION);
assertEquals(Map.of("team", "payments", "env", "", "tier", "gold"), tags(arn));
Map<String, String> held = tags(arn);
service.untagResource(objectMapper.readTree("{\"ResourceARN\":\"" + arn
+ "\",\"TagKeys\":[\"env\",\"absent\"]}"), REGION);
assertEquals(Map.of("team", "payments", "tier", "gold"), tags(arn));
assertEquals(3, held.size(), "a tag call publishes new tags, it does not edit the ones a reader holds");
service.updateSamplingRule(objectMapper.readTree(
"{\"SamplingRuleUpdate\":{\"RuleName\":\"orders\",\"FixedRate\":0.25}}"), REGION);
assertEquals(Map.of("team", "payments", "tier", "gold"), tags(arn), "an update keeps the tags");
}
@Test
void aCreateWhoseTagsAreNotAListMakesAnUntaggedRule() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5), "null")),
REGION).getRuleArn();
assertEquals(Map.of(), tags(arn));
}
@Test
void deletingARuleDropsItsTags() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
service.deleteSamplingRule(objectMapper.readTree("{\"RuleName\":\"orders\"}"), REGION);
assertEquals("ResourceNotFoundException",
assertThrows(AwsException.class, () -> tags(arn)).getErrorCode());
service.createSamplingRule(objectMapper.readTree(rule("orders", 1, 0.5)), REGION);
assertEquals(Map.of(), tags(arn));
}
@Test
void aTagCallNamingNoStoredRuleIsNotFound() throws Exception {
service.createSamplingRule(objectMapper.readTree(rule("orders", 1, 0.5)), REGION);
service.createSamplingRule(objectMapper.readTree(rule("orders", 1, 0.5)), "eu-west-1");
for (String arn : List.of("arn:aws:xray:us-east-1:000000000000:sampling-rule/ghost",
"arn:aws:xray:us-east-1:000000000000:sampling-rule/Default",
"arn:aws:xray:us-east-1:000000000000:group/orders/ABCDEFGHIJKLMNOPQRSTUVWXYZ012345",
"arn:aws:xray:eu-west-1:000000000000:sampling-rule/orders",
"arn:aws:xray:us-east-1:111111111111:sampling-rule/orders")) {
AwsException listed = assertThrows(AwsException.class, () -> tags(arn), arn);
assertEquals("ResourceNotFoundException", listed.getErrorCode(), arn);
assertEquals(404, listed.getHttpStatus(), arn);
assertEquals("Resource " + arn + " not found", listed.getMessage(), arn);
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, () -> service.tagResource(
objectMapper.readTree(tagRequest(arn, "[]")), REGION), arn).getErrorCode(), arn);
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, () -> service.untagResource(
objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[]}"), REGION), arn)
.getErrorCode(), arn);
}
}
@Test
void aRuleTakesAtMostFiftyTags() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5), tagList(50))),
REGION).getRuleArn();
service.tagResource(objectMapper.readTree(tagRequest(arn, "[{\"Key\":\"key-1\",\"Value\":\"new\"}]")), REGION);
AwsException tooMany = assertThrows(AwsException.class, () -> service.tagResource(
objectMapper.readTree(tagRequest(arn, "[{\"Key\":\"key-51\",\"Value\":\"v\"}]")), REGION));
assertEquals("TooManyTagsException", tooMany.getErrorCode());
assertEquals(400, tooMany.getHttpStatus());
assertEquals(50, tags(arn).size());
assertEquals("new", tags(arn).get("key-1"), "replacing a key the rule has adds no tag");
AwsException refused = assertThrows(AwsException.class, () -> service.createSamplingRule(
objectMapper.readTree(withTags(rule("payments", 2, 0.5), tagList(51))), REGION));
assertEquals("InvalidRequestException", refused.getErrorCode());
assertEquals(2, service.samplingRules(REGION).size(), "the refused rule is not created");
}
@Test
void anInvalidTagIsRefusedAndNoTagOfTheCallIsApplied() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
for (String tag : List.of("{\"Key\":\"\",\"Value\":\"v\"}",
"{\"Key\":123,\"Value\":\"v\"}",
"{\"Key\":\"" + "k".repeat(129) + "\",\"Value\":\"v\"}",
"{\"Key\":\"aws:team\",\"Value\":\"v\"}",
"{\"Key\":\"k\"}",
"{\"Key\":\"k\",\"Value\":\"" + "v".repeat(257) + "\"}")) {
String tags = "[{\"Key\":\"tier\",\"Value\":\"gold\"}," + tag + "]";
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> service.tagResource(
objectMapper.readTree(tagRequest(arn, tags)), REGION), tag).getErrorCode(), tag);
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> service.createSamplingRule(
objectMapper.readTree(withTags(rule("payments", 2, 0.5), tags)), REGION), tag).getErrorCode(), tag);
}
for (String key : List.of("\"\"", "\"" + "k".repeat(129) + "\"", "null")) {
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> service.untagResource(
objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[\"team\"," + key + "]}"),
REGION), key).getErrorCode(), key);
}
assertEquals(Map.of("team", "orders"), tags(arn));
assertEquals(2, service.samplingRules(REGION).size(), "no refused rule is created");
// U+10400 is one character in two UTF-16 units, and AWS counts characters.
for (String character : List.of("k", "𐐀")) {
String key = character.repeat(128);
service.tagResource(objectMapper.readTree(tagRequest(arn,
"[{\"Key\":\"" + key + "\",\"Value\":\"" + character.repeat(256) + "\"}]")), REGION);
assertEquals(character.repeat(256), tags(arn).get(key));
service.untagResource(objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":[\"" + key
+ "\"]}"), REGION);
assertEquals(Map.of("team", "orders"), tags(arn), "an untag takes a key of 128 characters");
}
}
@Test
void aTagCallListsAtMostTwoHundredEntries() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
String tier = "{\"Key\":\"tier\",\"Value\":\"gold\"}";
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> service.tagResource(
objectMapper.readTree(tagRequest(arn, copies(201, tier))), REGION)).getErrorCode());
assertEquals("InvalidRequestException", assertThrows(AwsException.class, () -> service.untagResource(
objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":" + copies(201, "\"team\"") + "}"),
REGION)).getErrorCode());
assertEquals(Map.of("team", "orders"), tags(arn));
service.tagResource(objectMapper.readTree(tagRequest(arn, copies(200, tier))), REGION);
service.untagResource(objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\",\"TagKeys\":"
+ copies(200, "\"team\"") + "}"), REGION);
assertEquals(Map.of("tier", "gold"), tags(arn));
}
@Test
void aTagCallWithoutTheListItActsOnIsRefused() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(rule("orders", 1, 0.5)), REGION).getRuleArn();
String named = "{\"ResourceARN\":\"" + arn + "\"}";
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> service.tagResource(objectMapper.readTree(named), REGION)).getErrorCode());
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> service.untagResource(objectMapper.readTree(named), REGION)).getErrorCode());
assertEquals("InvalidRequestException", assertThrows(AwsException.class,
() -> service.tagsForResource(objectMapper.readTree("{}"), REGION)).getErrorCode());
}
@Test
void racingTagCallsOnOneRuleLoseNoChange() throws Exception {
int racers = 16;
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("race", 1, 0.1),
tagList(racers))), REGION).getRuleArn();
ExecutorService pool = Executors.newFixedThreadPool(racers);
CountDownLatch start = new CountDownLatch(1);
List<Future<Object>> results = new ArrayList<>();
try {
for (int i = 1; i <= racers; i++) {
String key = "key-" + i;
results.add(pool.submit(() -> {
start.await();
service.untagResource(objectMapper.readTree("{\"ResourceARN\":\"" + arn
+ "\",\"TagKeys\":[\"" + key + "\"]}"), REGION);
service.tagResource(objectMapper.readTree(tagRequest(arn,
"[{\"Key\":\"new-" + key + "\",\"Value\":\"v\"}]")), REGION);
return null;
}));
}
start.countDown();
for (Future<Object> result : results) {
result.get(10, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
assertEquals(IntStream.rangeClosed(1, racers).boxed()
.collect(Collectors.toMap(i -> "new-key-" + i, i -> "v")), tags(arn));
}
@Test
void aTagCallWhoseBodyIsNotAnObjectIsRefused() {
assertEquals("Request payload is required.", assertThrows(AwsException.class,
() -> service.tagsForResource(objectMapper.readTree("[]"), REGION)).getMessage());
assertEquals("Request payload is required.", assertThrows(AwsException.class,
() -> service.tagResource(objectMapper.readTree("[]"), REGION)).getMessage());
assertEquals("Request payload is required.", assertThrows(AwsException.class,
() -> service.untagResource(objectMapper.readTree("[]"), REGION)).getMessage());
}
@Test
void aRuleWhoseNameHoldsASlashIsTaggedByItsArn() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders/eu", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
assertEquals(Map.of("team", "orders"), tags(arn));
}
@Test
void aRulesTagsSurviveARestart(@TempDir Path dir) throws Exception {
Path file = dir.resolve("xray-sampling-rules.json");
service = new XrayService(AccountAwareStorageBackend.inMemory("000000000000"), storedRules(file));
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
service = new XrayService(AccountAwareStorageBackend.inMemory("000000000000"), storedRules(file));
assertEquals(Map.of("team", "orders"), tags(arn));
}
@Test
void iamReadsARulesTagsByItsArnInItsOwnAccountAndRegion() throws Exception {
String arn = service.createSamplingRule(objectMapper.readTree(withTags(rule("orders", 1, 0.5),
"[{\"Key\":\"team\",\"Value\":\"orders\"}]")), REGION).getRuleArn();
assertEquals(Map.of("team", "orders"), service.storedTags(arn));
for (String other : List.of(arn.replace(REGION, "eu-west-1"), arn.replace("000000000000", "111111111111"),
arn.replace("arn:aws:", "arn:aws-cn:"), "arn:aws:xray:us-east-1:000000000000:sampling-rule/Default",
"arn:aws:xray:us-east-1:000000000000:group/g/1", "not-an-arn")) {
assertEquals(Map.of(), service.storedTags(other), other);
}
}
@Test
void iamReadsTheTagsOfARuleAnotherAccountHolds() {
AccountAwareStorageBackend<SamplingRule> rules = AccountAwareStorageBackend.inMemory("000000000000");
service = new XrayService(AccountAwareStorageBackend.inMemory("000000000000"), rules);
String arn = "arn:aws:xray:us-east-1:111111111111:sampling-rule/orders";
SamplingRule other = new SamplingRule();
other.setRuleName("orders");
other.setRuleArn(arn);
other.setTags(Map.of("team", "payments"));
AccountAwareStorageBackend.putInAccount(rules, "111111111111", REGION + "::orders", other);
assertEquals(Map.of("team", "payments"), service.storedTags(arn));
}
@Test
void aStoredRuleWhoseTagsAreNullIsUntagged() {
SamplingRule stored = StorageJson.mapper().readValue("{\"ruleName\":\"orders\",\"tags\":null}",
SamplingRule.class);
assertEquals(Map.of(), stored.copy().getTags());
}
private static AccountAwareStorageBackend<SamplingRule> storedRules(Path file) {
AccountAwareStorageBackend<SamplingRule> rules = new AccountAwareStorageBackend<>(
new PersistentStorage<>(file, new TypeReference<Map<String, SamplingRule>>() {}), null, "000000000000");
rules.load();
return rules;
}
private Map<String, String> tags(String arn) throws Exception {
return service.tagsForResource(objectMapper.readTree("{\"ResourceARN\":\"" + arn + "\"}"), REGION);
}
private static String tagRequest(String arn, String tags) {
return "{\"ResourceARN\":\"" + arn + "\",\"Tags\":" + tags + "}";
}
private static String withTags(String createRequest, String tags) {
return createRequest.substring(0, createRequest.length() - 1) + ",\"Tags\":" + tags + "}";
}
private static String tagList(int count) {
return IntStream.rangeClosed(1, count).mapToObj(i -> "{\"Key\":\"key-" + i + "\",\"Value\":\"v\"}")
.collect(Collectors.joining(",", "[", "]"));
}
private static String copies(int count, String entry) {
return "[" + String.join(",", Collections.nCopies(count, entry)) + "]";
}
}