mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(sns): support SMS account preferences (#4597)
* feat(sns): support SMS account preferences * fix(sns): include result element in SetSMSAttributes response * fix(sns): validate SMS sender IDs and cover JSON updates * refactor(sns): centralize SMS preference storage key
This commit is contained in:
1 parent
18ef1f58e9
commit
78c06239be
7 files changed
+280
No files matched your search
@@ -5,6 +5,8 @@ import software.amazon.awssdk.services.sns.SnsClient;
|
||||
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
|
||||
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
|
||||
import software.amazon.awssdk.services.sns.model.DeleteTopicRequest;
|
||||
import software.amazon.awssdk.services.sns.model.GetSmsAttributesRequest;
|
||||
import software.amazon.awssdk.services.sns.model.GetSmsAttributesResponse;
|
||||
import software.amazon.awssdk.services.sns.model.GetTopicAttributesRequest;
|
||||
import software.amazon.awssdk.services.sns.model.GetTopicAttributesResponse;
|
||||
import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicRequest;
|
||||
@@ -16,6 +18,7 @@ import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
|
||||
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
|
||||
import software.amazon.awssdk.services.sns.model.PublishRequest;
|
||||
import software.amazon.awssdk.services.sns.model.PublishResponse;
|
||||
import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest;
|
||||
import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest;
|
||||
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
|
||||
import software.amazon.awssdk.services.sns.model.SubscribeResponse;
|
||||
@@ -576,4 +579,26 @@ class SnsTest {
|
||||
sqs.deleteQueue(software.amazon.awssdk.services.sqs.model.DeleteQueueRequest.builder()
|
||||
.queueUrl(batchQueueUrl).build());
|
||||
}
|
||||
@Test
|
||||
@Order(17)
|
||||
void smsPreferencesRoundTrip() {
|
||||
sns.setSMSAttributes(SetSmsAttributesRequest.builder()
|
||||
.attributes(Map.of("DefaultSMSType", "Transactional", "MonthlySpendLimit", "10"))
|
||||
.build());
|
||||
|
||||
GetSmsAttributesResponse selected = sns.getSMSAttributes(GetSmsAttributesRequest.builder()
|
||||
.attributes("DefaultSMSType")
|
||||
.build());
|
||||
assertThat(selected.attributes()).containsExactly(entry("DefaultSMSType", "Transactional"));
|
||||
|
||||
GetSmsAttributesResponse all = sns.getSMSAttributes();
|
||||
assertThat(all.attributes()).containsEntry("DefaultSMSType", "Transactional")
|
||||
.containsEntry("MonthlySpendLimit", "10");
|
||||
|
||||
sns.setSMSAttributes(SetSmsAttributesRequest.builder()
|
||||
.attributes(Map.of("DefaultSMSType", "", "MonthlySpendLimit", ""))
|
||||
.build());
|
||||
assertThat(sns.getSMSAttributes().attributes())
|
||||
.doesNotContainKeys("DefaultSMSType", "MonthlySpendLimit");
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@
|
||||
| `ListTopics` | List all topics |
|
||||
| `GetTopicAttributes` | Get topic configuration |
|
||||
| `SetTopicAttributes` | Update topic configuration |
|
||||
| `GetSMSAttributes` | Read account SMS preferences in this region |
|
||||
| `SetSMSAttributes` | Set account SMS preferences in this region |
|
||||
| `Subscribe` | Subscribe an endpoint (SQS, HTTP, Lambda, email) |
|
||||
| `Unsubscribe` | Remove a subscription |
|
||||
| `ListSubscriptions` | List all subscriptions |
|
||||
@@ -35,6 +37,12 @@
|
||||
| `SetEndpointAttributes` | Update endpoint attributes (e.g. `Enabled=false` to simulate token expiry) |
|
||||
| `ListEndpointsByPlatformApplication` | List endpoints under a platform app |
|
||||
|
||||
SMS preferences are stored per account and region. `GetSMSAttributes` can select individual
|
||||
names; omitting the list returns all configured preferences. In Floci, setting an empty value
|
||||
clears that preference. SMS delivery
|
||||
remains mocked, so these settings do not generate delivery
|
||||
reports or CloudWatch delivery logs.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -44,6 +44,8 @@ public class SnsJsonHandler {
|
||||
case "ListTopics" -> handleListTopics(request, region);
|
||||
case "GetTopicAttributes" -> handleGetTopicAttributes(request, region);
|
||||
case "SetTopicAttributes" -> handleSetTopicAttributes(request, region);
|
||||
case "SetSMSAttributes" -> handleSetSmsAttributes(request, region);
|
||||
case "GetSMSAttributes" -> handleGetSmsAttributes(request, region);
|
||||
case "Subscribe" -> handleSubscribe(request, region);
|
||||
case "Unsubscribe" -> handleUnsubscribe(request, region);
|
||||
case "ListSubscriptions" -> handleListSubscriptions(request, region);
|
||||
@@ -125,6 +127,31 @@ public class SnsJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleSetSmsAttributes(JsonNode request, String region) {
|
||||
Map<String, String> attributes = jsonNodeToMap(request.path("attributes"));
|
||||
if (attributes.isEmpty()) {
|
||||
throw new AwsException("InvalidParameter", "SMS attributes are required.", 400);
|
||||
}
|
||||
snsService.setSmsAttributes(attributes, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleGetSmsAttributes(JsonNode request, String region) {
|
||||
List<String> names = new ArrayList<>();
|
||||
JsonNode requested = request.path("attributes");
|
||||
if (requested.isArray()) {
|
||||
for (JsonNode name : requested) {
|
||||
names.add(name.asText());
|
||||
}
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode attributes = response.putObject("attributes");
|
||||
for (Map.Entry<String, String> entry : snsService.getSmsAttributes(names, region).entrySet()) {
|
||||
attributes.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleSubscribe(JsonNode request, String region) {
|
||||
String topicArn = request.path("TopicArn").asText(null);
|
||||
String protocol = request.path("Protocol").asText(null);
|
||||
|
||||
@@ -43,6 +43,8 @@ public class SnsQueryHandler {
|
||||
case "ListTopics" -> handleListTopics(params, region);
|
||||
case "GetTopicAttributes" -> handleGetTopicAttributes(params, region);
|
||||
case "SetTopicAttributes" -> handleSetTopicAttributes(params, region);
|
||||
case "SetSMSAttributes" -> handleSetSmsAttributes(params, region);
|
||||
case "GetSMSAttributes" -> handleGetSmsAttributes(params, region);
|
||||
case "Subscribe" -> handleSubscribe(params, region);
|
||||
case "Unsubscribe" -> handleUnsubscribe(params, region);
|
||||
case "ListSubscriptions" -> handleListSubscriptions(params, region);
|
||||
@@ -132,6 +134,33 @@ public class SnsQueryHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleSetSmsAttributes(MultivaluedMap<String, String> params, String region) {
|
||||
Map<String, String> attributes = extractSnsAttributes(params, "attributes");
|
||||
if (attributes.isEmpty()) {
|
||||
return xmlErrorResponse("InvalidParameter", "SMS attributes are required.", 400);
|
||||
}
|
||||
snsService.setSmsAttributes(attributes, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetSMSAttributes", AwsNamespaces.SNS)).build();
|
||||
}
|
||||
|
||||
private Response handleGetSmsAttributes(MultivaluedMap<String, String> params, String region) {
|
||||
List<String> names = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = getParam(params, "attributes.member." + i);
|
||||
if (name == null) {
|
||||
break;
|
||||
}
|
||||
names.add(name);
|
||||
}
|
||||
Map<String, String> attributes = snsService.getSmsAttributes(names, region);
|
||||
XmlBuilder xml = new XmlBuilder().start("attributes");
|
||||
for (Map.Entry<String, String> entry : attributes.entrySet()) {
|
||||
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
|
||||
}
|
||||
xml.end("attributes");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetSMSAttributes", AwsNamespaces.SNS, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleSubscribe(MultivaluedMap<String, String> params, String region) {
|
||||
String topicArn = getParam(params, "TopicArn");
|
||||
String protocol = getParam(params, "Protocol");
|
||||
|
||||
@@ -53,6 +53,7 @@ import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -68,6 +69,10 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SnsService.class);
|
||||
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
|
||||
private static final Set<String> SMS_ATTRIBUTE_NAMES = Set.of("MonthlySpendLimit",
|
||||
"DeliveryStatusIAMRole", "DeliveryStatusSuccessSamplingRate", "DefaultSenderID",
|
||||
"DefaultSMSType", "UsageReportS3Bucket");
|
||||
private static final Pattern SMS_SENDER_ID = Pattern.compile("(?=.*[A-Za-z])[A-Za-z0-9]{1,11}");
|
||||
/** Includes the original send and two immediate retries for local SQS fan-out. */
|
||||
private static final int SQS_SUBSCRIPTION_DELIVERY_ATTEMPTS = 3;
|
||||
private static final String SUBSCRIPTION_REDRIVE_POLICY = "RedrivePolicy";
|
||||
@@ -111,6 +116,7 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, PlatformEndpoint> platformEndpointStore;
|
||||
private final Deque<PushNotification> pushCapture = new ConcurrentLinkedDeque<>();
|
||||
private final StorageBackend<String, SentSms> smsStore;
|
||||
private final StorageBackend<String, Map<String, String>> smsAttributesStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final SqsService sqsService;
|
||||
private final LambdaService lambdaService;
|
||||
@@ -142,6 +148,9 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
storageFactory.create("sns", "sns-sms.json",
|
||||
new TypeReference<Map<String, SentSms>>() {
|
||||
}),
|
||||
storageFactory.create("sns", "sns-sms-attributes.json",
|
||||
new TypeReference<Map<String, Map<String, String>>>() {
|
||||
}),
|
||||
regionResolver,
|
||||
sqsService,
|
||||
lambdaService,
|
||||
@@ -194,6 +203,7 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
this.platformAppStore = platformAppStore;
|
||||
this.platformEndpointStore = platformEndpointStore;
|
||||
this.smsStore = new InMemoryStorage<>();
|
||||
this.smsAttributesStore = new InMemoryStorage<>();
|
||||
this.regionResolver = regionResolver;
|
||||
this.sqsService = sqsService;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -222,11 +232,26 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
RegionResolver regionResolver, SqsService sqsService,
|
||||
LambdaService lambdaService, FirehoseService firehoseService,
|
||||
String baseUrl, ObjectMapper objectMapper) {
|
||||
this(topicStore, subscriptionStore, platformAppStore, platformEndpointStore,
|
||||
smsStore, new InMemoryStorage<>(), regionResolver, sqsService,
|
||||
lambdaService, firehoseService, baseUrl, objectMapper);
|
||||
}
|
||||
|
||||
SnsService(StorageBackend<String, Topic> topicStore,
|
||||
StorageBackend<String, Subscription> subscriptionStore,
|
||||
StorageBackend<String, PlatformApplication> platformAppStore,
|
||||
StorageBackend<String, PlatformEndpoint> platformEndpointStore,
|
||||
StorageBackend<String, SentSms> smsStore,
|
||||
StorageBackend<String, Map<String, String>> smsAttributesStore,
|
||||
RegionResolver regionResolver, SqsService sqsService,
|
||||
LambdaService lambdaService, FirehoseService firehoseService,
|
||||
String baseUrl, ObjectMapper objectMapper) {
|
||||
this.topicStore = topicStore;
|
||||
this.subscriptionStore = subscriptionStore;
|
||||
this.platformAppStore = platformAppStore;
|
||||
this.platformEndpointStore = platformEndpointStore;
|
||||
this.smsStore = smsStore;
|
||||
this.smsAttributesStore = smsAttributesStore;
|
||||
this.regionResolver = regionResolver;
|
||||
this.sqsService = sqsService;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -241,6 +266,66 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
fifoDeduplicationCache.clear();
|
||||
}
|
||||
|
||||
public synchronized void setSmsAttributes(Map<String, String> attributes, String region) {
|
||||
String key = smsAttributesKey(region);
|
||||
Map<String, String> updated = new LinkedHashMap<>(smsAttributesStore.get(key).orElse(Map.of()));
|
||||
for (Map.Entry<String, String> entry : attributes.entrySet()) {
|
||||
String name = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
if (!SMS_ATTRIBUTE_NAMES.contains(name) || value == null) {
|
||||
throw new AwsException("InvalidParameter", "Invalid SMS attribute: " + name, 400);
|
||||
}
|
||||
if (value.isEmpty()) {
|
||||
updated.remove(name);
|
||||
continue;
|
||||
}
|
||||
if ("DefaultSMSType".equals(name)
|
||||
&& !"Promotional".equals(value) && !"Transactional".equals(value)) {
|
||||
throw new AwsException("InvalidParameter", "Invalid DefaultSMSType: " + value, 400);
|
||||
}
|
||||
if ("DefaultSenderID".equals(name) && !SMS_SENDER_ID.matcher(value).matches()) {
|
||||
throw new AwsException("InvalidParameter", "Invalid DefaultSenderID: " + value, 400);
|
||||
}
|
||||
if ("MonthlySpendLimit".equals(name)) {
|
||||
try {
|
||||
if (new BigDecimal(value).signum() < 0) {
|
||||
throw new NumberFormatException("negative amount");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidParameter", "Invalid MonthlySpendLimit: " + value, 400);
|
||||
}
|
||||
}
|
||||
if ("DeliveryStatusSuccessSamplingRate".equals(name)) {
|
||||
try {
|
||||
int rate = Integer.parseInt(value);
|
||||
if (rate < 0 || rate > 100) {
|
||||
throw new NumberFormatException("out of range");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidParameter",
|
||||
"Invalid DeliveryStatusSuccessSamplingRate: " + value, 400);
|
||||
}
|
||||
}
|
||||
updated.put(name, value);
|
||||
}
|
||||
smsAttributesStore.put(key, updated);
|
||||
}
|
||||
|
||||
public Map<String, String> getSmsAttributes(List<String> names, String region) {
|
||||
String key = smsAttributesKey(region);
|
||||
Map<String, String> stored = smsAttributesStore.get(key).orElse(Map.of());
|
||||
if (names == null || names.isEmpty()) {
|
||||
return new LinkedHashMap<>(stored);
|
||||
}
|
||||
Map<String, String> selected = new LinkedHashMap<>();
|
||||
for (String name : names) {
|
||||
if (stored.containsKey(name)) {
|
||||
selected.put(name, stored.get(name));
|
||||
}
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
public Topic createTopic(String name, Map<String, String> attributes,
|
||||
Map<String, String> tags, String region) {
|
||||
if (name == null || name.isBlank()) {
|
||||
@@ -2217,6 +2302,10 @@ public class SnsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private String smsAttributesKey(String region) {
|
||||
return regionResolver.getAccountId() + "::" + region;
|
||||
}
|
||||
|
||||
private static String topicKey(String region, String arn) {
|
||||
return "topic::" + region + "::" + arn;
|
||||
}
|
||||
|
||||
@@ -1291,4 +1291,54 @@ class SnsIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(150)
|
||||
void smsAttributesRoundTripAcrossQueryAndJsonProtocols() {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "SetSMSAttributes")
|
||||
.formParam("attributes.entry.1.key", "DefaultSMSType")
|
||||
.formParam("attributes.entry.1.value", "Transactional")
|
||||
.formParam("attributes.entry.2.key", "MonthlySpendLimit")
|
||||
.formParam("attributes.entry.2.value", "10")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<SetSMSAttributesResult>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetSMSAttributes")
|
||||
.formParam("attributes.member.1", "DefaultSMSType")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<key>DefaultSMSType</key>"))
|
||||
.body(containsString("<value>Transactional</value>"))
|
||||
.body(not(containsString("MonthlySpendLimit")));
|
||||
|
||||
given()
|
||||
.contentType(SNS_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "SNS_20100331.SetSMSAttributes")
|
||||
.body("{\"attributes\":{\"DefaultSMSType\":\"Promotional\",\"DefaultSenderID\":\"Brand123\"}}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(SNS_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "SNS_20100331.GetSMSAttributes")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("attributes.DefaultSMSType", equalTo("Promotional"))
|
||||
.body("attributes.DefaultSenderID", equalTo("Brand123"))
|
||||
.body("attributes.MonthlySpendLimit", equalTo("10"));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SnsServiceTest {
|
||||
|
||||
@@ -65,6 +66,57 @@ class SnsServiceTest {
|
||||
assertEquals("arn:aws:sns:us-east-1:000000000000:my-topic", topic.getTopicArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void smsAttributesAreScopedToAccountAndRegion() {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("111122223333", "444455556666", "111122223333");
|
||||
SnsService service = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), regionResolver, null, null, null, BASE_URL, new ObjectMapper());
|
||||
|
||||
service.setSmsAttributes(Map.of("DefaultSMSType", "Transactional", "MonthlySpendLimit", "10"), REGION);
|
||||
|
||||
assertTrue(service.getSmsAttributes(List.of(), REGION).isEmpty());
|
||||
assertEquals(Map.of("DefaultSMSType", "Transactional", "MonthlySpendLimit", "10"),
|
||||
service.getSmsAttributes(List.of(), REGION));
|
||||
assertTrue(service.getSmsAttributes(List.of(), "us-west-2").isEmpty());
|
||||
assertEquals(Map.of("DefaultSMSType", "Transactional"),
|
||||
service.getSmsAttributes(List.of("DefaultSMSType"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void smsAttributesRejectInvalidValuesWithoutChangingStoredSettings() {
|
||||
snsService.setSmsAttributes(Map.of("DefaultSMSType", "Promotional"), REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> snsService.setSmsAttributes(
|
||||
Map.of("DefaultSMSType", "Bulk"), REGION));
|
||||
assertThrows(AwsException.class, () -> snsService.setSmsAttributes(
|
||||
Map.of("DeliveryStatusSuccessSamplingRate", "101"), REGION));
|
||||
assertThrows(AwsException.class, () -> snsService.setSmsAttributes(
|
||||
Map.of("DefaultSenderID", "12345678901"), REGION));
|
||||
assertThrows(AwsException.class, () -> snsService.setSmsAttributes(
|
||||
Map.of("DefaultSenderID", "TooLongSender"), REGION));
|
||||
assertThrows(AwsException.class, () -> snsService.setSmsAttributes(
|
||||
Map.of("DefaultSenderID", "Brand-Name"), REGION));
|
||||
assertEquals(Map.of("DefaultSMSType", "Promotional"),
|
||||
snsService.getSmsAttributes(List.of(), REGION));
|
||||
|
||||
snsService.setSmsAttributes(Map.of("DefaultSenderID", "Brand123"), REGION);
|
||||
assertEquals(Map.of("DefaultSMSType", "Promotional", "DefaultSenderID", "Brand123"),
|
||||
snsService.getSmsAttributes(List.of(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySmsAttributeResetsOnlyThatPreference() {
|
||||
snsService.setSmsAttributes(Map.of("DefaultSMSType", "Transactional",
|
||||
"MonthlySpendLimit", "10"), REGION);
|
||||
|
||||
snsService.setSmsAttributes(Map.of("DefaultSMSType", ""), REGION);
|
||||
|
||||
assertEquals(Map.of("MonthlySpendLimit", "10"),
|
||||
snsService.getSmsAttributes(List.of(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTopic_fifoWithContentBasedDeduplication() {
|
||||
Topic topic = snsService.createTopic("my-topic.fifo",
|
||||
|
||||
Reference in new issue
Block a user