Skip to content

Commit 2ffe47c

Browse files
committed
Adding overflow protection
1 parent 61ca958 commit 2ffe47c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/VersionedRecordExtension.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,17 @@ public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite contex
175175
String existingVersionValueKey = VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER.apply(versionAttributeKey.get());
176176

177177
long increment = versionIncrementByFromAnnotation;
178+
179+
/*
180+
since the new incrementBy and StartAt functionality can now accept any positive number, though unlikely
181+
to happen in a rela life scenario, we should add overflow protection.
182+
*/
183+
if (existingVersion > Long.MAX_VALUE - increment) {
184+
throw new IllegalStateException(
185+
String.format("Version overflow detected. Current version %d + increment %d would exceed Long.MAX_VALUE",
186+
existingVersion, increment));
187+
}
188+
178189
newVersionValue = AttributeValue.builder().n(Long.toString(existingVersion + increment)).build();
179190

180191
condition = Expression.builder()

services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/extensions/VersionedRecordExtensionTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,30 @@ public void customStartingValueAndIncrementWithImmutableClass_worksAsExpected()
582582
.build()));
583583
}
584584

585+
@Test(expected = IllegalStateException.class)
586+
public void versionOverflowThrowsException() {
587+
VersionedRecordExtension recordExtension = VersionedRecordExtension.builder()
588+
.incrementBy(2L)
589+
.build();
590+
591+
FakeVersionedThroughAnnotationItem item = new FakeVersionedThroughAnnotationItem();
592+
item.setId(UUID.randomUUID().toString());
593+
item.setVersion(Long.MAX_VALUE - 1);
594+
595+
TableSchema<FakeVersionedThroughAnnotationItem> schema =
596+
TableSchema.fromBean(FakeVersionedThroughAnnotationItem.class);
597+
598+
Map<String, AttributeValue> inputMap =
599+
new HashMap<>(schema.itemToMap(item, true));
600+
601+
recordExtension.beforeWrite(DefaultDynamoDbExtensionContext
602+
.builder()
603+
.items(inputMap)
604+
.tableMetadata(schema.tableMetadata())
605+
.operationContext(PRIMARY_CONTEXT)
606+
.build());
607+
}
608+
585609
public static Stream<Arguments> customIncrementForExistingVersionValues() {
586610
return Stream.of(
587611
Arguments.of(0L, 1L, 5L, "6"),

0 commit comments

Comments
 (0)