feat(sns): add topic permissions, the SMS sandbox and SMS opt-out (#5570)

SNS's Query routing set listed ten names that neither SNS handler dispatched, so a
request for any of them was answered UnsupportedOperation. All ten are real SNS
operations, and both the Query and JSON protocols now serve them.

AddPermission and RemovePermission edit the topic's Policy attribute the way AWS
does, going by LocalStack's recordings of the same calls against a live account:
the label becomes the statement's Sid, each account its root principal, and a single
account or action is written as a string. A duplicate label, an action outside SNS
and a missing topic get AWS's errors. A label the policy does not hold leaves it
unchanged, since no source shows what AWS answers there. Floci stores topic policies
but does not evaluate them under enforcement, so the grant only shows in
GetTopicAttributes.

The default topic policy now matches what AWS returns for a new topic: Version
2008-10-17 with an AWS:SourceOwner condition, where Floci has had 2012-10-17 and
AWS:SourceAccount since the first commit. AddPermission builds on it.

GetSMSSandboxAccountStatus reports the account outside the sandbox, because Floci
delivers SMS to any number. The sandbox numbers still work per account and region,
without the limits AWS lifts outside the sandbox. CreateSMSSandboxPhoneNumber texts a
six-digit code through the same path as Publish, so a test reads it from /_aws/sns,
and VerifySMSSandboxPhoneNumber checks it.

No number is ever opted out. AWS opts a number out when its owner replies STOP, and
nothing reaches Floci that way, so CheckIfPhoneNumberIsOptedOut answers false,
ListPhoneNumbersOptedOut is empty, and OptInPhoneNumber checks only the E.164 format,
with AWS's error for a malformed number.

AddPermission takes only twelve-digit account IDs, so a malformed one cannot end up as
a principal in the stored policy.

Each of these edits reads a record, changes it and writes it back. AddPermission,
RemovePermission and SetTopicAttributes, which writes the same Policy attribute, are
synchronized, as are the sandbox's create, verify and delete, so overlapping requests
cannot lose a grant or bring back a deleted number. A number whose verification text
cannot be recorded is put back as it was. The tests park the first of two edits inside
that window and check the second waits. testing.ThreadStates holds the wait they use,
which several other test classes still carry their own copies of.

With SNS dispatching AddPermission and RemovePermission, the last two rows of the
Query routing gap file, SQS's two names reaching SNS without a Version, are gone,
leaving 171. The SNS row in docs/services/index.md now counts 39 operations, up
from a stale 17.

Refs #5549
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-13 17:55:05 -05:00
1 parent a88ef42b4b
commit b7a1bde2dc
12 files changed
+1589 -27

No files matched your search

@@ -0,0 +1,286 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.sns.model.SentSms;
import io.github.hectorvent.floci.services.sns.model.SmsSandboxPhoneNumber;
import io.github.hectorvent.floci.services.sns.model.Topic;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.List;
import java.util.Optional;
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.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
/**
* Edits to a topic's policy and to an SMS sandbox number read a record, change it and write it
* back. These tests park the first of two overlapping edits inside that window and check the
* second waits for it, and that a sandbox number whose verification text fails is put back.
*/
class SnsPolicyAndSandboxEditsTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String GRANTEE = "111122223333";
private static final String BASE_URL = "http://localhost:4566";
private static final String PHONE_NUMBER = "+15555550100";
@Test
void anOverlappingGrantWaitsSoBothGrantsLand() throws Exception {
ObjectMapper mapper = Mockito.spy(new ObjectMapper());
SnsService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
mapper);
String topicArn = service.createTopic("edits", null, null, REGION).getTopicArn();
service.addPermission(topicArn, "existing", List.of(GRANTEE), List.of("Publish"), REGION);
whileAGrantIsParked(mapper, service, topicArn,
() -> service.addPermission(topicArn, "second", List.of(GRANTEE), List.of("Subscribe"), REGION));
String policy = service.getTopicAttributes(topicArn, REGION).get("Policy");
for (String sid : List.of("existing", "first", "second")) {
assertTrue(policy.contains("\"Sid\":\"" + sid + "\""), sid + " is missing from " + policy);
}
}
@Test
void aPolicySetWhileAGrantIsBeingWrittenIsNotUndone() throws Exception {
ObjectMapper mapper = Mockito.spy(new ObjectMapper());
SnsService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
mapper);
String topicArn = service.createTopic("replaced", null, null, REGION).getTopicArn();
service.addPermission(topicArn, "existing", List.of(GRANTEE), List.of("Publish"), REGION);
String replacement = "{\"Version\":\"2008-10-17\",\"Statement\":[]}";
whileAGrantIsParked(mapper, service, topicArn,
() -> service.setTopicAttributes(topicArn, "Policy", replacement, REGION));
assertEquals(replacement, service.getTopicAttributes(topicArn, REGION).get("Policy"),
"the grant wrote back a policy read before it was replaced");
}
@Test
void aRemovalWhileAGrantIsBeingWrittenIsNotUndone() throws Exception {
ObjectMapper mapper = Mockito.spy(new ObjectMapper());
SnsService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
mapper);
String topicArn = service.createTopic("removed", null, null, REGION).getTopicArn();
service.addPermission(topicArn, "existing", List.of(GRANTEE), List.of("Publish"), REGION);
whileAGrantIsParked(mapper, service, topicArn,
() -> service.removePermission(topicArn, "existing", REGION));
String policy = service.getTopicAttributes(topicArn, REGION).get("Policy");
assertTrue(policy.contains("\"Sid\":\"first\""), "the grant is missing from " + policy);
assertTrue(!policy.contains("\"Sid\":\"existing\""), "the removed statement came back in " + policy);
}
@Test
void aVerificationCannotBringBackANumberDeletedMeanwhile() throws Exception {
ParkingStore<SmsSandboxPhoneNumber> sandbox = new ParkingStore<>();
InMemoryStorage<String, SentSms> texts = new InMemoryStorage<>();
SnsService service = service(new InMemoryStorage<>(), texts, sandbox, new ObjectMapper());
service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION);
String code = onlyCodeTexted(service);
// The verification parks right after reading the number, before writing it back verified.
sandbox.parkNextRead();
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> verify = pool.submit(() -> service.verifySmsSandboxPhoneNumber(PHONE_NUMBER, code, REGION));
assertTrue(sandbox.awaitParked(), "the verification must reach its read of the number");
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<?> delete = pool.submit(() -> {
deleteThread.set(Thread.currentThread());
service.deleteSmsSandboxPhoneNumber(PHONE_NUMBER, REGION);
});
awaitBlockedOrDone(deleteThread, delete);
sandbox.release();
verify.get(2, TimeUnit.SECONDS);
delete.get(2, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
assertTrue(service.listSmsSandboxPhoneNumbers(null, null, REGION).items().isEmpty(),
"a number deleted while it was being verified came back");
}
@Test
void aResendCannotBringBackANumberDeletedMeanwhile() throws Exception {
ParkingStore<SmsSandboxPhoneNumber> sandbox = new ParkingStore<>();
SnsService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), sandbox, new ObjectMapper());
service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION);
// The resend parks right after reading the number, before storing its fresh code.
sandbox.parkNextRead();
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> resend = pool.submit(() -> service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION));
assertTrue(sandbox.awaitParked(), "the resend must reach its read of the number");
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<?> delete = pool.submit(() -> {
deleteThread.set(Thread.currentThread());
service.deleteSmsSandboxPhoneNumber(PHONE_NUMBER, REGION);
});
awaitBlockedOrDone(deleteThread, delete);
sandbox.release();
resend.get(2, TimeUnit.SECONDS);
delete.get(2, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
assertTrue(service.listSmsSandboxPhoneNumbers(null, null, REGION).items().isEmpty(),
"a number deleted while a code was being resent came back");
}
@Test
void aNumberWhoseTextFailsIsNotLeftBehind() {
FailingTexts texts = new FailingTexts();
SnsService service = service(new InMemoryStorage<>(), texts, new InMemoryStorage<>(), new ObjectMapper());
texts.failing = true;
assertThrows(IllegalStateException.class,
() -> service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION));
assertTrue(service.listSmsSandboxPhoneNumbers(null, null, REGION).items().isEmpty(),
"a number nobody could receive a code for was left pending");
}
@Test
void aResendWhoseTextFailsKeepsTheCodeAlreadySent() {
FailingTexts texts = new FailingTexts();
SnsService service = service(new InMemoryStorage<>(), texts, new InMemoryStorage<>(), new ObjectMapper());
service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION);
String firstCode = onlyCodeTexted(service);
texts.failing = true;
assertThrows(IllegalStateException.class,
() -> service.createSmsSandboxPhoneNumber(PHONE_NUMBER, null, REGION));
texts.failing = false;
service.verifySmsSandboxPhoneNumber(PHONE_NUMBER, firstCode, REGION);
assertEquals(SmsSandboxPhoneNumber.VERIFIED,
service.listSmsSandboxPhoneNumbers(null, null, REGION).items().get(0).getStatus());
}
/**
* Starts a grant labelled {@code first} and parks it right after it parses the stored policy,
* before it writes the policy back, then runs {@code overlapping} on another thread. Correct
* code leaves {@code overlapping} blocked until the grant is released.
*/
private static void whileAGrantIsParked(ObjectMapper mapper, SnsService service, String topicArn,
Runnable overlapping) throws Exception {
CountDownLatch parsed = new CountDownLatch(1);
CountDownLatch resume = new CountDownLatch(1);
AtomicBoolean parkNext = new AtomicBoolean(true);
doAnswer(invocation -> {
Object tree = invocation.callRealMethod();
if (parkNext.getAndSet(false)) {
parsed.countDown();
resume.await();
}
return tree;
}).when(mapper).readTree(anyString());
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<?> grant = pool.submit(() ->
service.addPermission(topicArn, "first", List.of(GRANTEE), List.of("Publish"), REGION));
assertTrue(parsed.await(2, TimeUnit.SECONDS), "the grant must reach its parse of the policy");
AtomicReference<Thread> overlappingThread = new AtomicReference<>();
Future<?> other = pool.submit(() -> {
overlappingThread.set(Thread.currentThread());
overlapping.run();
});
awaitBlockedOrDone(overlappingThread, other);
resume.countDown();
grant.get(2, TimeUnit.SECONDS);
other.get(2, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
}
private static SnsService service(InMemoryStorage<String, Topic> topics, InMemoryStorage<String, SentSms> texts,
InMemoryStorage<String, SmsSandboxPhoneNumber> sandbox, ObjectMapper mapper) {
return new SnsService(topics, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
texts, new InMemoryStorage<>(), sandbox, new RegionResolver(REGION, ACCOUNT), null, null, null,
BASE_URL, mapper, SnsMessageSigner.inMemory(BASE_URL));
}
private static String onlyCodeTexted(SnsService service) {
List<SentSms> sent = service.getSentMessages();
assertEquals(1, sent.size(), "expected exactly one verification text, got " + sent.size());
Matcher code = Pattern.compile("[0-9]{6}").matcher(sent.get(0).getMessage());
assertTrue(code.find(), "no code in " + sent);
return code.group();
}
/** A store whose next read, once armed, parks after reading until released. */
private static final class ParkingStore<V> extends InMemoryStorage<String, V> {
private final AtomicBoolean parkNext = new AtomicBoolean();
private final CountDownLatch parked = new CountDownLatch(1);
private final CountDownLatch released = new CountDownLatch(1);
void parkNextRead() {
parkNext.set(true);
}
boolean awaitParked() throws InterruptedException {
return parked.await(2, TimeUnit.SECONDS);
}
void release() {
released.countDown();
}
@Override
public Optional<V> get(String key) {
Optional<V> value = super.get(key);
if (parkNext.getAndSet(false)) {
parked.countDown();
try {
released.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
return value;
}
}
/** Where SNS records the SMS it sends, made to fail on demand. */
private static final class FailingTexts extends InMemoryStorage<String, SentSms> {
private volatile boolean failing;
@Override
public void put(String key, SentSms value) {
if (failing) {
throw new IllegalStateException("the SMS store is unavailable");
}
super.put(key, value);
}
}
}
@@ -0,0 +1,236 @@
package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The SMS sandbox and opt-out operations. Floci answers as an account that has left the sandbox,
* since it delivers SMS to any number, and a verification code is "texted" the way every SMS is
* here: stored for {@code GET /_aws/sns} to read back.
*/
@QuarkusTest
class SnsSmsSandboxIntegrationTest {
private static final Pattern CODE = Pattern.compile("[0-9]{6}");
private static final String INVALID_PHONE_NUMBER =
"Invalid parameter: PhoneNumber Reason: input incorrectly formatted";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void theAccountIsOutsideTheSandbox() {
query("GetSMSSandboxAccountStatus", Map.of())
.statusCode(200)
.body("GetSMSSandboxAccountStatusResponse.GetSMSSandboxAccountStatusResult.IsInSandbox",
equalTo("false"));
json("GetSMSSandboxAccountStatus", "{}")
.statusCode(200)
.body("IsInSandbox", equalTo(false));
}
@Test
void aSandboxNumberIsVerifiedWithTheCodeTextedToIt() {
String phoneNumber = addSandboxNumber();
assertEquals("Pending", statusOf(phoneNumber));
String code = codeTextedTo(phoneNumber);
String wrong = String.format("%06d", (Integer.parseInt(code) + 1) % 1_000_000);
query("VerifySMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber, "OneTimePassword", wrong))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("VerificationException"));
assertEquals("Pending", statusOf(phoneNumber));
query("VerifySMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber, "OneTimePassword", code))
.statusCode(200);
assertEquals("Verified", statusOf(phoneNumber));
}
@Test
void aDeletedNumberIsGoneAndCannotBeDeletedTwice() {
String phoneNumber = addSandboxNumber();
query("DeleteSMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber)).statusCode(200);
assertTrue(!allSandboxNumbers().containsKey(phoneNumber), phoneNumber + " is still listed");
query("DeleteSMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber))
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
query("VerifySMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber, "OneTimePassword", "123456"))
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
}
@Test
void theListPagesThroughMaxResults() {
List<String> added = List.of(addSandboxNumber(), addSandboxNumber(), addSandboxNumber());
List<String> seen = new ArrayList<>();
String nextToken = null;
do {
Map<String, String> params = new HashMap<>(Map.of("MaxResults", "1"));
if (nextToken != null) {
params.put("NextToken", nextToken);
}
XmlPath page = query("ListSMSSandboxPhoneNumbers", params).statusCode(200).extract().xmlPath();
List<String> numbers = page.getList(
"ListSMSSandboxPhoneNumbersResponse.ListSMSSandboxPhoneNumbersResult.PhoneNumbers.member.PhoneNumber");
assertTrue(numbers.size() <= 1, "a page held " + numbers);
seen.addAll(numbers);
nextToken = page.getString(
"ListSMSSandboxPhoneNumbersResponse.ListSMSSandboxPhoneNumbersResult.NextToken");
} while (nextToken != null && !nextToken.isEmpty());
assertTrue(seen.containsAll(added), "paging returned " + seen + ", missing some of " + added);
query("ListSMSSandboxPhoneNumbers", Map.of("MaxResults", "101"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"));
}
@Test
void aMalformedSandboxNumberIsRefused() {
query("CreateSMSSandboxPhoneNumber", Map.of("PhoneNumber", "not-a-number"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message", equalTo(INVALID_PHONE_NUMBER));
}
@Test
void theJsonProtocolReachesTheSameSandbox() {
String phoneNumber = randomPhoneNumber();
cleanup.register(() -> query("DeleteSMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber)));
json("CreateSMSSandboxPhoneNumber", "{\"PhoneNumber\": \"%s\", \"LanguageCode\": \"en-US\"}"
.formatted(phoneNumber))
.statusCode(200);
json("VerifySMSSandboxPhoneNumber", "{\"PhoneNumber\": \"%s\", \"OneTimePassword\": \"%s\"}"
.formatted(phoneNumber, codeTextedTo(phoneNumber)))
.statusCode(200);
assertEquals("Verified", statusOf(phoneNumber));
json("ListSMSSandboxPhoneNumbers", "{\"MaxResults\": 100}")
.statusCode(200)
.body("PhoneNumbers.PhoneNumber", hasItem(phoneNumber));
}
@Test
void noNumberIsEverOptedOut() {
query("CheckIfPhoneNumberIsOptedOut", Map.of("phoneNumber", "+4411111111"))
.statusCode(200)
.body("CheckIfPhoneNumberIsOptedOutResponse.CheckIfPhoneNumberIsOptedOutResult.isOptedOut",
equalTo("false"));
List<String> optedOut = query("ListPhoneNumbersOptedOut", Map.of())
.statusCode(200)
.extract().xmlPath()
.getList("ListPhoneNumbersOptedOutResponse.ListPhoneNumbersOptedOutResult.phoneNumbers.member");
assertTrue(optedOut.isEmpty(), "opted out: " + optedOut);
json("ListPhoneNumbersOptedOut", "{}")
.statusCode(200)
.body("phoneNumbers", empty());
}
@Test
void optingInANumberThatIsNotOptedOutSucceeds() {
query("OptInPhoneNumber", Map.of("phoneNumber", "+4411111111")).statusCode(200);
json("OptInPhoneNumber", "{\"phoneNumber\": \"+4411111111\"}").statusCode(200);
}
@Test
void aMalformedNumberIsRefusedByTheOptOutCalls() {
query("OptInPhoneNumber", Map.of("phoneNumber", "invalid"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message", equalTo(INVALID_PHONE_NUMBER));
query("CheckIfPhoneNumberIsOptedOut", Map.of("phoneNumber", "invalid"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"));
}
private String addSandboxNumber() {
String phoneNumber = randomPhoneNumber();
cleanup.register(() -> query("DeleteSMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber)));
query("CreateSMSSandboxPhoneNumber", Map.of("PhoneNumber", phoneNumber, "LanguageCode", "en-US"))
.statusCode(200);
return phoneNumber;
}
/** A number of its own for each test, so one test's sandbox entry and texts are not another's. */
private static String randomPhoneNumber() {
return String.format("+1555%07d", ThreadLocalRandom.current().nextInt(10_000_000));
}
private static String codeTextedTo(String phoneNumber) {
List<String> texts = given()
.queryParam("phone", phoneNumber)
.when().get("/_aws/sns")
.then().statusCode(200)
.extract().jsonPath().getList("messages.Message");
assertEquals(1, texts.size(), "expected one verification text to " + phoneNumber + ", got " + texts);
Matcher code = CODE.matcher(texts.get(0));
assertTrue(code.find(), "no six-digit code in " + texts.get(0));
return code.group();
}
private static String statusOf(String phoneNumber) {
String status = allSandboxNumbers().get(phoneNumber);
assertTrue(status != null, phoneNumber + " is not listed");
return status;
}
private static Map<String, String> allSandboxNumbers() {
XmlPath page = query("ListSMSSandboxPhoneNumbers", Map.of("MaxResults", "100"))
.statusCode(200).extract().xmlPath();
String members = "ListSMSSandboxPhoneNumbersResponse.ListSMSSandboxPhoneNumbersResult.PhoneNumbers.member";
List<String> numbers = page.getList(members + ".PhoneNumber");
List<String> statuses = page.getList(members + ".Status");
Map<String, String> byNumber = new HashMap<>();
for (int i = 0; i < numbers.size(); i++) {
byNumber.put(numbers.get(i), statuses.get(i));
}
return byNumber;
}
private static ValidatableResponse query(String action, Map<String, String> params) {
RequestSpecification spec = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-03-31");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static ValidatableResponse json(String action, String body) {
return given()
.contentType("application/x-amz-json-1.0")
.header("X-Amz-Target", "SNS_20100331." + action)
.body(body)
.when().post("/").then();
}
}
@@ -0,0 +1,231 @@
package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@code AddPermission} and {@code RemovePermission}, which edit a topic's policy. The expected
* documents are the ones AWS returned in LocalStack's recordings of the same calls against a live
* account ({@code test_topic_add_permission}, {@code test_topic_add_multiple_permissions},
* {@code test_topic_remove_permission}, {@code test_add_permission_errors}), and the default
* policy is the one AWS returns for a new topic ({@code test_create_topic_with_attributes}).
*/
@QuarkusTest
class SnsTopicPermissionIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String GRANTEE = "111122223333";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aNewTopicCarriesTheDefaultPolicyAwsReturns() {
String topicArn = createTopic();
JsonPath policy = policyOf(topicArn);
assertEquals("2008-10-17", policy.getString("Version"));
assertEquals("__default_policy_ID", policy.getString("Id"));
assertEquals(1, policy.getList("Statement").size());
assertEquals("__default_statement_ID", policy.getString("Statement[0].Sid"));
assertEquals("*", policy.getString("Statement[0].Principal.AWS"));
assertEquals(List.of("SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission",
"SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe",
"SNS:ListSubscriptionsByTopic", "SNS:Publish"),
policy.getList("Statement[0].Action"));
assertEquals(topicArn, policy.getString("Statement[0].Resource"));
assertEquals(ACCOUNT_ID, policy.getString("Statement[0].Condition.StringEquals.'AWS:SourceOwner'"));
}
@Test
void addPermissionAppendsALabelledStatementToTheDefaultPolicy() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "publish-grant",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "Publish"))
.statusCode(200);
JsonPath policy = policyOf(topicArn);
assertEquals(2, policy.getList("Statement").size());
assertEquals("__default_statement_ID", policy.getString("Statement[0].Sid"));
assertEquals("publish-grant", policy.getString("Statement[1].Sid"));
assertEquals("Allow", policy.getString("Statement[1].Effect"));
// One account and one action are written as strings, not lists of one.
assertEquals("arn:aws:iam::" + GRANTEE + ":root", policy.getString("Statement[1].Principal.AWS"));
assertEquals("SNS:Publish", policy.getString("Statement[1].Action"));
assertEquals(topicArn, policy.getString("Statement[1].Resource"));
}
@Test
void severalAccountsAndActionsAreWrittenAsLists() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "two-grants",
"AWSAccountId.member.1", GRANTEE, "AWSAccountId.member.2", ACCOUNT_ID,
"ActionName.member.1", "Publish", "ActionName.member.2", "Subscribe"))
.statusCode(200);
JsonPath policy = policyOf(topicArn);
assertEquals(List.of("arn:aws:iam::" + GRANTEE + ":root", "arn:aws:iam::" + ACCOUNT_ID + ":root"),
policy.getList("Statement[1].Principal.AWS"));
assertEquals(List.of("SNS:Publish", "SNS:Subscribe"), policy.getList("Statement[1].Action"));
}
@Test
void aLabelAlreadyInThePolicyIsRefused() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "taken",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "Publish"))
.statusCode(200);
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "taken",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "AddPermission"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message", equalTo("Invalid parameter: Statement already exists"));
}
@Test
void anActionSnsDoesNotHaveIsRefused() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "bogus",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "InvalidAction"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"))
.body("ErrorResponse.Error.Message",
equalTo("Invalid parameter: Policy statement action out of service scope!"));
assertEquals(1, policyOf(topicArn).getList("Statement").size());
}
@Test
void anAccountIdThatIsNotTwelveDigitsIsRefusedOnBothProtocols() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "bad-account",
"AWSAccountId.member.1", GRANTEE, "AWSAccountId.member.2", "abc:def",
"ActionName.member.1", "Publish"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameter"));
json("AddPermission", """
{"TopicArn": "%s", "Label": "bad-account", "AWSAccountId": ["abc:def"], "ActionName": ["Publish"]}
""".formatted(topicArn))
.statusCode(400)
.body("__type", equalTo("InvalidParameter"));
assertEquals(1, policyOf(topicArn).getList("Statement").size());
}
@Test
void bothCallsAnswerNotFoundForAMissingTopic() {
String missing = createTopic() + "-not-existing";
query("AddPermission", Map.of("TopicArn", missing, "Label", "any",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "Publish"))
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NotFound"))
.body("ErrorResponse.Error.Message", equalTo("Topic does not exist"));
query("RemovePermission", Map.of("TopicArn", missing, "Label", "any"))
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NotFound"))
.body("ErrorResponse.Error.Message", equalTo("Topic does not exist"));
}
@Test
void removePermissionTakesTheStatementBackOut() {
String topicArn = createTopic();
query("AddPermission", Map.of("TopicArn", topicArn, "Label", "temporary",
"AWSAccountId.member.1", GRANTEE, "ActionName.member.1", "Publish"))
.statusCode(200);
query("RemovePermission", Map.of("TopicArn", topicArn, "Label", "temporary")).statusCode(200);
JsonPath policy = policyOf(topicArn);
assertEquals(1, policy.getList("Statement").size());
assertEquals("__default_statement_ID", policy.getString("Statement[0].Sid"));
}
@Test
void removingALabelThePolicyDoesNotHoldLeavesItAsItIs() {
String topicArn = createTopic();
String before = rawPolicyOf(topicArn);
query("RemovePermission", Map.of("TopicArn", topicArn, "Label", "never-added")).statusCode(200);
assertEquals(before, rawPolicyOf(topicArn));
}
@Test
void theJsonProtocolEditsTheSamePolicy() {
String topicArn = createTopic();
json("AddPermission", """
{"TopicArn": "%s", "Label": "json-grant", "AWSAccountId": ["%s"], "ActionName": ["Publish"]}
""".formatted(topicArn, GRANTEE))
.statusCode(200);
assertEquals("json-grant", policyOf(topicArn).getString("Statement[1].Sid"));
json("RemovePermission", """
{"TopicArn": "%s", "Label": "json-grant"}
""".formatted(topicArn))
.statusCode(200);
assertEquals(1, policyOf(topicArn).getList("Statement").size());
}
private String createTopic() {
String topicArn = query("CreateTopic", Map.of("Name", "permission-" + UUID.randomUUID()))
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
cleanup.register(() -> query("DeleteTopic", Map.of("TopicArn", topicArn)).statusCode(200));
return topicArn;
}
private static JsonPath policyOf(String topicArn) {
return JsonPath.from(rawPolicyOf(topicArn));
}
private static String rawPolicyOf(String topicArn) {
return query("GetTopicAttributes", Map.of("TopicArn", topicArn))
.statusCode(200)
.extract().xmlPath()
.getString("GetTopicAttributesResponse.GetTopicAttributesResult.Attributes.entry"
+ ".find { it.key == 'Policy' }.value");
}
private static ValidatableResponse query(String action, Map<String, String> params) {
RequestSpecification spec = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-03-31");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static ValidatableResponse json(String action, String body) {
return given()
.contentType("application/x-amz-json-1.0")
.header("X-Amz-Target", "SNS_20100331." + action)
.body(body)
.when().post("/").then();
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.testing;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/** Waiting for a thread to reach a lock, for tests that force two requests to overlap. */
public final class ThreadStates {
private ThreadStates() {}
/**
* Returns once {@code thread} is blocked entering a monitor, or {@code task} has finished,
* whichever comes first. Code that serializes correctly leaves the second request blocked
* behind the first; code that does not lets it run to the end, which the caller's assertions
* then catch. Polls every 5 ms and gives up after five seconds rather than hang a broken test.
*/
public static void awaitBlockedOrDone(AtomicReference<Thread> thread, Future<?> task)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline && !task.isDone()) {
Thread current = thread.get();
if (current != null && current.getState() == Thread.State.BLOCKED) {
return;
}
Thread.sleep(5);
}
}
}