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,37 @@
package datadog.trace.instrumentation.aws;

/**
* Account identity of resources addressed by AWS SDK requests.
*
* <p>Two sources are trustworthy and used by the SDK instrumentations:
*
* <ul>
* <li>An ARN carried by the request itself (for example a DynamoDB {@code TableName} given as an
* ARN), parsed once with {@link AwsArn}.
* <li>The account that owns the credentials signing the request, when the SDK exposes it ({@code
* AwsCredentialsIdentity.accountId()} in AWS SDK for Java v2 2.26+, populated by the STS,
* SSO, profile, process and container credential providers). DynamoDB documents that a bare
* table name is resolved in the requestor's own account ("If you only provide the table name
* parameter instead of a complete ARN, the API operation will be performed on the table in
* the account to which the requestor belongs"), so for DynamoDB the caller account is the
* table owner.
* </ul>
*/
public final class AwsAccountIdentity {

private AwsAccountIdentity() {}

/** {@code true} for exactly twelve ASCII digits. */
public static boolean isAccountId(final String value) {
if (value == null || value.length() != 12) {
return false;
}
for (int i = 0; i < 12; i++) {
char c = value.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package datadog.trace.instrumentation.aws;

/**
* A parsed Amazon Resource Name: {@code arn:<partition>:<service>:<region>:<account>:<resource>}.
*
* <p>Parsed once so callers that need several fields do not re-scan the string. The AWS SDK ships
* its own parser ({@code software.amazon.awssdk.arns.Arn}) but it lives in a module that neither
* the SDK v2 2.2.0 floor these instrumentations compile against nor SDK v1 provide, so a minimal
* one is kept here.
*/
public final class AwsArn {

private static final String TABLE_PREFIX = "table/";

private final String raw;
private final String partition;
private final String service;
private final String region;
private final String account;
private final String resource;

private AwsArn(
final String raw,
final String partition,
final String service,
final String region,
final String account,
final String resource) {
this.raw = raw;
this.partition = partition;
this.service = service;
this.region = region;
this.account = account;
this.resource = resource;
}

/**
* Parses an ARN.
*
* @return the parsed ARN, or {@code null} when the value is not of the form {@code
* arn:partition:service:region:account:resource} (partition and service non-empty).
*/
public static AwsArn parse(final String value) {
if (value == null || !value.startsWith("arn:")) {
return null;
}
int c1 = value.indexOf(':', 4);
if (c1 < 0) {
return null;
}
int c2 = value.indexOf(':', c1 + 1);
if (c2 < 0) {
return null;
}
int c3 = value.indexOf(':', c2 + 1);
if (c3 < 0) {
return null;
}
int c4 = value.indexOf(':', c3 + 1);
if (c4 < 0) {
return null;
}
if (c1 == 4 || c2 == c1 + 1 || c4 == value.length() - 1) {
// empty partition, empty service or empty resource
return null;
}
return new AwsArn(
value,
value.substring(4, c1),
value.substring(c1 + 1, c2),
emptyToNull(value.substring(c2 + 1, c3)),
emptyToNull(value.substring(c3 + 1, c4)),
value.substring(c4 + 1));
}

/** The original string. */
public String raw() {
return raw;
}

/** {@code aws}, {@code aws-cn}, {@code aws-us-gov}, ... */
public String partition() {
return partition;
}

/** {@code dynamodb}, {@code sns}, {@code s3}, ... */
public String service() {
return service;
}

/** The Region, or {@code null} for global services (S3, IAM). */
public String region() {
return region;
}

/** The 12-digit account, or {@code null} when absent (S3 ARNs) or not exactly twelve digits. */
public String account() {
return AwsAccountIdentity.isAccountId(account) ? account : null;
}

/** Everything after the fifth colon. Never empty. */
public String resource() {
return resource;
}

/** Whether this ARN identifies a DynamoDB table or one of its sub-resources. */
public boolean isDynamoDbTable() {
return "dynamodb".equals(service)
&& resource.startsWith(TABLE_PREFIX)
&& resource.length() > TABLE_PREFIX.length()
&& resource.charAt(TABLE_PREFIX.length()) != '/';
}

private static String emptyToNull(final String value) {
return value.isEmpty() ? null : value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package datadog.trace.instrumentation.aws;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

class AwsAccountIdentityTest {

@ParameterizedTest(name = "{0} is an account id")
@ValueSource(strings = {"123456789012", "000000000000", "999999999999"})
void acceptsTwelveDigits(String value) {
assertTrue(AwsAccountIdentity.isAccountId(value));
}

@ParameterizedTest(name = "{0} is not an account id")
@NullAndEmptySource
@ValueSource(
strings = {"12345", "1234567890123", "12345678901a", " 23456789012", "arn:aws:s3:::b"})
void rejectsNonAccountIds(String value) {
assertFalse(AwsAccountIdentity.isAccountId(value));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package datadog.trace.instrumentation.aws;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.tabletest.junit.TableTest;

class AwsArnTest {

@ParameterizedTest(name = "parses {0}")
@CsvSource(
nullValues = "NULL",
value = {
"arn:aws:dynamodb:us-east-1:123456789012:table/orders, aws, dynamodb, us-east-1, 123456789012, table/orders",
"arn:aws:dynamodb:us-east-1:123456789012:table/orders/index/by-user, aws, dynamodb, us-east-1, 123456789012, table/orders/index/by-user",
"arn:aws-cn:dynamodb:cn-north-1:123456789012:table/orders, aws-cn, dynamodb, cn-north-1, 123456789012, table/orders",
"arn:aws-us-gov:sns:us-gov-west-1:123456789012:alerts, aws-us-gov, sns, us-gov-west-1, 123456789012, alerts",
"arn:aws:s3:::my-bucket, aws, s3, NULL, NULL, my-bucket",
"arn:aws:iam::123456789012:role/app, aws, iam, NULL, 123456789012, role/app",
"arn:aws:states:us-east-1:123456789012:stateMachine:orders:extra:colons, aws, states, us-east-1, 123456789012, stateMachine:orders:extra:colons",
})
void parsesFields(
String value,
String partition,
String service,
String region,
String account,
String resource) {
AwsArn arn = AwsArn.parse(value);
assertNotNull(arn);
assertEquals(value, arn.raw());
assertEquals(partition, arn.partition());
assertEquals(service, arn.service());
assertEquals(region, arn.region());
assertEquals(account, arn.account());
assertEquals(resource, arn.resource());
}

@ParameterizedTest(name = "rejects {0}")
@NullAndEmptySource
@ValueSource(
strings = {
"orders",
"arn:",
"arn:aws",
"arn:aws:dynamodb",
"arn:aws:dynamodb:us-east-1",
"arn:aws:dynamodb:us-east-1:123456789012",
"arn:aws:dynamodb:us-east-1:123456789012:",
"arn::dynamodb:us-east-1:123456789012:table/orders",
"arn:aws::us-east-1:123456789012:table/orders",
"table/orders",
"https://sqs.us-east-1.amazonaws.com/123456789012/q",
})
void rejectsNonArn(String value) {
assertNull(AwsArn.parse(value));
}

@ParameterizedTest(name = "account of {0} is null")
@ValueSource(
strings = {
"arn:aws:dynamodb:us-east-1:12345:table/orders",
"arn:aws:dynamodb:us-east-1:12345678901a:table/orders",
"arn:aws:dynamodb:us-east-1::table/orders",
})
void accountMustBeTwelveDigits(String value) {
AwsArn arn = AwsArn.parse(value);
assertNotNull(arn);
assertNull(arn.account());
}

@TableTest({
"Scenario | Value | Expected",
"Table | arn:aws:dynamodb:us-east-1:123456789012:table/orders | true ",
"Index | arn:aws:dynamodb:us-east-1:123456789012:table/orders/index/by-user | true ",
"Stream | arn:aws:dynamodb:us-east-1:123456789012:table/orders/stream/2024-01-01T00:00:00.000 | true ",
"Missing name | arn:aws:dynamodb:us-east-1:123456789012:table/ | false ",
"Empty name | arn:aws:dynamodb:us-east-1:123456789012:table//index/by-user | false ",
"Non-table | arn:aws:dynamodb:us-east-1:123456789012:backup/orders | false ",
"Other service | arn:aws:sns:us-east-1:123456789012:table/orders | false ",
"S3 bucket | arn:aws:s3:::my-bucket | false "
})
void identifiesDynamoDbTables(String value, boolean expected) {
assertEquals(expected, AwsArn.parse(value).isDynamoDbTable());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ addTestSuiteForDir('latestDsmTest', 'dsmTest')
addTestSuiteExtendingForDir('latestDsmForkedTest', 'latestDsmTest', 'dsmTest')

dependencies {
testImplementation libs.bundles.mockito
compileOnly group: 'com.amazonaws', name: 'aws-java-sdk-core', version: '1.11.0'
implementation project(':dd-java-agent:instrumentation:aws-java:aws-java-common')

// Include httpclient instrumentation for testing because it is a dependency for aws-sdk.
testImplementation project(':dd-java-agent:instrumentation:apache-httpclient:apache-httpclient-4.0')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import datadog.trace.bootstrap.instrumentation.api.Tags;
import datadog.trace.bootstrap.instrumentation.api.UTF8BytesString;
import datadog.trace.bootstrap.instrumentation.decorator.HttpClientDecorator;
import datadog.trace.instrumentation.aws.AwsAccountIdentity;
import datadog.trace.instrumentation.aws.AwsArn;
import java.net.URI;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -179,6 +181,23 @@ protected void doOnRequest(final AgentSpan span, final Request request) {
}
String tableName = access.getTableName(originalRequest);
if (null != tableName) {
// A DynamoDB TableName given as an ARN carries the owning account. SDK v1 does not expose
// the signing credentials to request handlers, so a bare name yields no account here. The
// existing table name tags keep the value as given, ARN or not. Other services with a
// TableName member (Timestream, Keyspaces, ...) only get the plain table name tags.
AwsArn arn =
awsSimplifiedServiceName != null && awsSimplifiedServiceName.startsWith("dynamodb")
? AwsArn.parse(tableName)
: null;
if (arn != null) {
if (arn.isDynamoDbTable()) {
span.setTag(InstrumentationTags.AWS_TABLE_ARN, arn.raw());
}
String account = arn.account();
if (account != null) {
span.setTag(InstrumentationTags.AWS_ACCOUNT, account);
}
}
span.setTag(InstrumentationTags.AWS_TABLE_NAME, tableName);
span.setTag(InstrumentationTags.TABLE_NAME, tableName);
bestPrecursor = InstrumentationTags.AWS_TABLE_NAME;
Expand Down Expand Up @@ -247,6 +266,19 @@ protected void doOnRequest(final AgentSpan span, final Request request) {
}
}

/** Tags the expected bucket owner only after S3 has accepted the request. */
public void onSuccessfulRequest(final AgentSpan span, final Request<?> request) {
if (!"s3".equalsIgnoreCase(simplifyServiceName(request.getServiceName()))) {
return;
}
final AmazonWebServiceRequest originalRequest = request.getOriginalRequest();
final String expectedBucketOwner =
GetterAccess.of(originalRequest).getExpectedBucketOwner(originalRequest);
if (AwsAccountIdentity.isAccountId(expectedBucketOwner)) {
span.setTag(InstrumentationTags.AWS_ACCOUNT, expectedBucketOwner);
}
}

public void onServiceResponse(
final AgentSpan span, final String awsService, final Response response) {
if ("s3".equalsIgnoreCase(simplifyServiceName(awsService))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ protected AwsSdkModule(String namespace, String instrumentationName) {
this.namespace = namespace;
}

@Override
public boolean isHelperClass(String className) {
// These helpers are compiled in aws-java-common, outside this module's output.
return className.equals("datadog.trace.instrumentation.aws.AwsAccountIdentity")
|| className.equals("datadog.trace.instrumentation.aws.AwsArn");
}

@Override
public Map<String, String> contextStore() {
Map<String, String> map = new java.util.HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ static GetterAccess of(final Object request) {
private final MethodHandle getPublishBatchRequestEntries;
private final MethodHandle getApproximateArrivalTimestamp;
private final MethodHandle getTableName;
private final MethodHandle getExpectedBucketOwner;

private GetterAccess(final Class<?> objectType) {
operationName =
Expand All @@ -55,6 +56,7 @@ private GetterAccess(final Class<?> objectType) {
getApproximateArrivalTimestamp =
findGetter(objectType, "getApproximateArrivalTimestamp", Date.class);
getTableName = findStringGetter(objectType, "getTableName");
getExpectedBucketOwner = findStringGetter(objectType, "getExpectedBucketOwner");
}

String getOperationNameFromType() {
Expand Down Expand Up @@ -101,6 +103,10 @@ String getTableName(final Object object) {
return invokeForString(getTableName, object);
}

String getExpectedBucketOwner(final Object object) {
return invokeForString(getExpectedBucketOwner, object);
}

Date getApproximateArrivalTimestamp(final Object object) {
return invoke(getApproximateArrivalTimestamp, object);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ public void afterResponse(final Request<?> request, final Response<?> response)
span = AgentSpan.fromContext(context);
if (span != null) {
DECORATE.onResponse(span, response);
DECORATE.onSuccessfulRequest(span, request);
DECORATE.onServiceResponse(span, request.getServiceName(), response);
DECORATE.beforeFinish(span);
span.finish();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ abstract class AWS1ClientTest extends VersionedNamingTestBase {
"S3" | "GetObject" | "GET" | "/someBucket/someKey" | AmazonS3ClientBuilder.standard().withPathStyleAccessEnabled(true).withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.getObject("someBucket", "someKey") } | ["aws.bucket.name": "someBucket", "bucketname": "someBucket", "aws.object.key": "someKey"] | "" | "aws.bucket.name" | null
"DynamoDBv2" | "CreateTable" | "POST" | "/" | AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.createTable(new CreateTableRequest("sometable", null)) } | ["aws.table.name": "sometable", "tablename": "sometable"] | "" | "aws.table.name" | null
"DynamoDBv2" | "GetItem" | "POST" | "/" | AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.getItem(new GetItemRequest("sometable", ["attribute": new AttributeValue("somevalue")])) } | ["aws.table.name": "sometable", "tablename": "sometable"] | "" | "aws.table.name" | null
"DynamoDBv2" | "GetItem" | "POST" | "/" | AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.getItem(new GetItemRequest("arn:aws:dynamodb:us-east-1:123456789012:table/sometable", ["attribute": new AttributeValue("somevalue")])) } | ["aws.table.name": "arn:aws:dynamodb:us-east-1:123456789012:table/sometable", "tablename": "arn:aws:dynamodb:us-east-1:123456789012:table/sometable", "aws.table.arn": "arn:aws:dynamodb:us-east-1:123456789012:table/sometable", "aws_account": "123456789012"] | "" | "aws.table.name" | null
"Kinesis" | "DeleteStream" | "POST" | "/" | AmazonKinesisClientBuilder.standard().withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.deleteStream(new DeleteStreamRequest().withStreamName("somestream")) } | ["aws.stream.name": "somestream", "streamname": "somestream"] | "" | "aws.stream.name" | null
"SQS" | "CreateQueue" | "POST" | "/" | AmazonSQSClientBuilder.standard().withEndpointConfiguration(endpoint).withCredentials(credentialsProvider).build() | { c -> c.createQueue(new CreateQueueRequest("somequeue")) } | ["aws.queue.name": "somequeue", "queuename": "somequeue"] | """

Expand Down
Loading
Loading