mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(sns): sign deliveries with a served RSA certificate like AWS (#5189)
* feat(sns): sign deliveries with a served RSA certificate like AWS Replace the EXAMPLE Signature and SigningCertURL placeholders with real signatures over the documented canonical string. Notifications and subscription confirmations delivered to HTTP/HTTPS endpoints, Lambda records and non-raw SQS envelopes are signed with SHA1withRSA, or SHA256withRSA when the topic sets SignatureVersion to 2. The RSA 2048 key and its self-signed certificate are kept in SNS storage and the certificate is served at /_aws/sns/SimpleNotificationService-<fingerprint>.pem, so a new key always gets a new URL. The SQS envelope now carries UnsubscribeURL and the Lambda record a real UnsubscribeUrl, as on AWS. * fix(sns): drop a delivery when signing fails and regenerate the key on reset A signing failure in the Lambda, SQS and HTTP builders was caught with the JSON fallback and delivered an empty placeholder as if it had succeeded. Only a JSON serialization error falls back now; a signing failure fails that delivery. SnsMessageSigner is now Resettable: a reset drops the cached key instead of writing it back to the cleared store, so the next delivery generates a new one. * style(sns): sort SnsService imports * refactor(sns): build the SQS envelope with the builder Firehose uses buildSnsSqsEnvelope duplicated buildSnsEnvelope apart from the signature and UnsubscribeURL. buildSnsEnvelope now takes the subscription ARN and signature version and adds both only when a subscription is given, so SQS and Firehose share one builder again.
This commit is contained in:
1 parent
1b61945f28
commit
c0b2b299b0
8 files changed
+840
-35
No files matched your search
+2
-2
@@ -198,8 +198,8 @@ class SnsHttpDeliveryIntegrationTest {
|
||||
assertEquals("Hello HTTP endpoint!", envelope.get("Message").asText());
|
||||
assertEquals("Test Subject", envelope.get("Subject").asText());
|
||||
assertEquals("1", envelope.get("SignatureVersion").asText());
|
||||
assertEquals("EXAMPLE", envelope.get("Signature").asText());
|
||||
assertEquals("EXAMPLE", envelope.get("SigningCertURL").asText());
|
||||
assertFalse(envelope.get("Signature").asText().isEmpty());
|
||||
assertTrue(envelope.get("SigningCertURL").asText().endsWith(".pem"));
|
||||
assertTrue(envelope.get("UnsubscribeURL").asText().contains("Action=Unsubscribe"));
|
||||
assertNotNull(envelope.get("MessageId").asText());
|
||||
assertNotNull(envelope.get("Timestamp").asText());
|
||||
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
package io.github.hectorvent.floci.services.sns;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Signature;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Verifies SNS deliveries the way an AWS SDK message validator does: fetch the certificate from
|
||||
* {@code SigningCertURL}, rebuild the canonical string for the message type, and check the
|
||||
* base64 signature with SHA1withRSA ({@code SignatureVersion} 1) or SHA256withRSA (2).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class SnsMessageSignatureIntegrationTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:4566";
|
||||
private static final String CERT_PREFIX = BASE_URL + "/_aws/sns/SimpleNotificationService-";
|
||||
private static final List<String> NOTIFICATION_FIELDS =
|
||||
List.of("Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type");
|
||||
private static final List<String> CONFIRMATION_FIELDS =
|
||||
List.of("Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type");
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final List<String> received = new CopyOnWriteArrayList<>();
|
||||
private static HttpServer httpServer;
|
||||
private static int httpPort;
|
||||
|
||||
@BeforeAll
|
||||
static void startHttpServer() throws IOException {
|
||||
httpServer = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
httpPort = httpServer.getAddress().getPort();
|
||||
httpServer.createContext("/signed", exchange -> {
|
||||
received.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
exchange.close();
|
||||
});
|
||||
httpServer.start();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopHttpServer() {
|
||||
if (httpServer != null) {
|
||||
httpServer.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void clearReceived() {
|
||||
received.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpConfirmationAndNotification_verifyAgainstServedCertificate() throws Exception {
|
||||
String topicArn = createTopic("signed-http-topic");
|
||||
subscribe(topicArn, "http", "http://localhost:" + httpPort + "/signed");
|
||||
|
||||
JsonNode confirmation = MAPPER.readTree(awaitMessage(0));
|
||||
assertEquals("SubscriptionConfirmation", confirmation.get("Type").asText());
|
||||
assertEquals("1", confirmation.get("SignatureVersion").asText());
|
||||
assertTrue(verify(confirmation, "SigningCertURL"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ConfirmSubscription")
|
||||
.formParam("TopicArn", topicArn)
|
||||
.formParam("Token", confirmation.get("Token").asText())
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
publish(topicArn, "Hello signed HTTP", "Signed subject");
|
||||
JsonNode notification = MAPPER.readTree(awaitMessage(1));
|
||||
assertEquals("Notification", notification.get("Type").asText());
|
||||
assertEquals("Signed subject", notification.get("Subject").asText());
|
||||
assertEquals("1", notification.get("SignatureVersion").asText());
|
||||
assertTrue(verify(notification, "SigningCertURL"));
|
||||
assertEquals(confirmation.get("SigningCertURL").asText(), notification.get("SigningCertURL").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsEnvelope_verifiesAndTamperedMessageFails() throws Exception {
|
||||
String queueUrl = createQueue("signed-envelope-queue");
|
||||
String topicArn = createTopic("signed-sqs-topic");
|
||||
subscribe(topicArn, "sqs", queueUrl);
|
||||
|
||||
publish(topicArn, "Hello signed SQS", null);
|
||||
JsonNode envelope = MAPPER.readTree(receiveBody(queueUrl));
|
||||
|
||||
assertEquals("Notification", envelope.get("Type").asText());
|
||||
assertFalse(envelope.has("Subject"));
|
||||
assertEquals("1", envelope.get("SignatureVersion").asText());
|
||||
assertTrue(envelope.get("UnsubscribeURL").asText().contains("Action=Unsubscribe"));
|
||||
assertTrue(verify(envelope, "SigningCertURL"));
|
||||
|
||||
ObjectNode tampered = envelope.deepCopy();
|
||||
tampered.put("Message", "Hello forged SQS");
|
||||
assertFalse(verify(tampered, "SigningCertURL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signatureVersion2Topic_signsWithSha256() throws Exception {
|
||||
String queueUrl = createQueue("signed-v2-queue");
|
||||
String topicArn = createTopic("signed-v2-topic");
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "SetTopicAttributes")
|
||||
.formParam("TopicArn", topicArn)
|
||||
.formParam("AttributeName", "SignatureVersion")
|
||||
.formParam("AttributeValue", "2")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
subscribe(topicArn, "sqs", queueUrl);
|
||||
|
||||
publish(topicArn, "Hello SHA256", "v2");
|
||||
JsonNode envelope = MAPPER.readTree(receiveBody(queueUrl));
|
||||
|
||||
assertEquals("2", envelope.get("SignatureVersion").asText());
|
||||
assertTrue(verify(envelope, "SigningCertURL"));
|
||||
assertFalse(verifyWith(envelope, "SigningCertURL", "SHA1withRSA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownCertificateName_isNotFound() {
|
||||
given()
|
||||
.when()
|
||||
.get("/_aws/sns/SimpleNotificationService-00000000000000000000000000000000.pem")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
private static boolean verify(JsonNode message, String certUrlField) throws Exception {
|
||||
String algorithm = "2".equals(message.get("SignatureVersion").asText()) ? "SHA256withRSA" : "SHA1withRSA";
|
||||
return verifyWith(message, certUrlField, algorithm);
|
||||
}
|
||||
|
||||
private static boolean verifyWith(JsonNode message, String certUrlField, String algorithm) throws Exception {
|
||||
String certUrl = message.get(certUrlField).asText();
|
||||
assertTrue(certUrl.startsWith(CERT_PREFIX), certUrl);
|
||||
assertTrue(certUrl.endsWith(".pem"), certUrl);
|
||||
|
||||
ExtractableResponse<Response> response = given()
|
||||
.when()
|
||||
.get(certUrl.substring(BASE_URL.length()))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract();
|
||||
assertTrue(response.contentType().startsWith("application/x-pem-file"), response.contentType());
|
||||
X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(new ByteArrayInputStream(response.asByteArray()));
|
||||
|
||||
List<String> fields = "Notification".equals(message.get("Type").asText())
|
||||
? NOTIFICATION_FIELDS
|
||||
: CONFIRMATION_FIELDS;
|
||||
StringBuilder canonical = new StringBuilder();
|
||||
for (String field : fields) {
|
||||
JsonNode value = message.get(field);
|
||||
if (value != null && !value.isNull()) {
|
||||
canonical.append(field).append('\n').append(value.asText()).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
Signature verifier = Signature.getInstance(algorithm);
|
||||
verifier.initVerify(certificate.getPublicKey());
|
||||
verifier.update(canonical.toString().getBytes(StandardCharsets.UTF_8));
|
||||
return verifier.verify(Base64.getDecoder().decode(message.get("Signature").asText()));
|
||||
}
|
||||
|
||||
private static String awaitMessage(int index) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (received.size() <= index && System.nanoTime() < deadline) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
assertTrue(received.size() > index, "no HTTP delivery #" + index);
|
||||
return received.get(index);
|
||||
}
|
||||
|
||||
private static String createTopic(String name) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateTopic")
|
||||
.formParam("Name", name)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
|
||||
}
|
||||
|
||||
private static String createQueue(String name) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateQueue")
|
||||
.formParam("QueueName", name)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
}
|
||||
|
||||
private static void subscribe(String topicArn, String protocol, String endpoint) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "Subscribe")
|
||||
.formParam("TopicArn", topicArn)
|
||||
.formParam("Protocol", protocol)
|
||||
.formParam("Endpoint", endpoint)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<SubscriptionArn>"));
|
||||
}
|
||||
|
||||
private static void publish(String topicArn, String message, String subject) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "Publish")
|
||||
.formParam("TopicArn", topicArn)
|
||||
.formParam("Message", message);
|
||||
if (subject != null) {
|
||||
request.formParam("Subject", subject);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String receiveBody(String queueUrl) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ReceiveMessage")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "1")
|
||||
.formParam("WaitTimeSeconds", "2")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath().getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Body");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package io.github.hectorvent.floci.services.sns;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.sns.model.SnsSigningKey;
|
||||
import io.github.hectorvent.floci.services.sns.model.Topic;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Signature;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class SnsMessageSignerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String BASE_URL = "http://localhost:4566";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void lambdaRecord_isSignedAndVerifiesAgainstServedCertificate() throws Exception {
|
||||
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
SnsService service = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), null, lambdaService, null, BASE_URL, MAPPER, signer);
|
||||
Topic topic = service.createTopic("signed-lambda-topic", null, null, REGION);
|
||||
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:signed";
|
||||
service.subscribe(topic.getTopicArn(), "lambda", functionArn, REGION, Map.of());
|
||||
|
||||
service.publish(topic.getTopicArn(), null, "hello lambda", null, REGION);
|
||||
|
||||
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invoke(eq(REGION), eq(functionArn), payload.capture(), eq(InvocationType.Event));
|
||||
JsonNode sns = MAPPER.readTree(payload.getValue()).get("Records").get(0).get("Sns");
|
||||
|
||||
assertEquals("1", sns.get("SignatureVersion").asText());
|
||||
assertTrue(sns.get("Subject").isNull());
|
||||
assertEquals(signer.certificateUrl(), sns.get("SigningCertUrl").asText());
|
||||
assertTrue(sns.get("UnsubscribeUrl").asText().startsWith(BASE_URL + "/?Action=Unsubscribe&SubscriptionArn="));
|
||||
assertTrue(verifies(signer, sns, "SigningCertUrl", "SHA1withRSA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingFailure_doesNotDeliverAnUnsignedPlaceholder() {
|
||||
SnsMessageSigner signer = mock(SnsMessageSigner.class);
|
||||
doThrow(new IllegalStateException("Failed to sign SNS message"))
|
||||
.when(signer).sign(any(ObjectNode.class), anyString(), anyString());
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
SnsService service = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), null, lambdaService, null, BASE_URL, MAPPER, signer);
|
||||
Topic topic = service.createTopic("unsigned-lambda-topic", null, null, REGION);
|
||||
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:unsigned";
|
||||
service.subscribe(topic.getTopicArn(), "lambda", functionArn, REGION, Map.of());
|
||||
|
||||
service.publish(topic.getTopicArn(), null, "hello lambda", null, REGION);
|
||||
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any(InvocationType.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reset_generatesANewKeyInsteadOfRestoringTheOldOne() {
|
||||
AccountAwareStorageBackend<SnsSigningKey> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
SnsMessageSigner signer = newSigner(store);
|
||||
String before = signer.certificateUrl();
|
||||
|
||||
store.clear();
|
||||
signer.clear();
|
||||
String after = signer.certificateUrl();
|
||||
|
||||
assertNotEquals(before, after);
|
||||
assertEquals(after, newSigner(store).certificateUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notificationCanonicalString_includesSubjectOnlyWhenPresent() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("Type", "Notification");
|
||||
node.put("MessageId", "id-1");
|
||||
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:t");
|
||||
node.putNull("Subject");
|
||||
node.put("Message", "body");
|
||||
node.put("Timestamp", "2026-10-06T00:00:00.000Z");
|
||||
|
||||
assertEquals("Message\nbody\nMessageId\nid-1\nTimestamp\n2026-10-06T00:00:00.000Z\n"
|
||||
+ "TopicArn\narn:aws:sns:us-east-1:000000000000:t\nType\nNotification\n",
|
||||
SnsMessageSigner.canonicalString(node));
|
||||
|
||||
node.put("Subject", "s");
|
||||
assertTrue(SnsMessageSigner.canonicalString(node).contains("MessageId\nid-1\nSubject\ns\nTimestamp\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmationCanonicalString_usesSubscribeUrlAndToken() {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("Type", "SubscriptionConfirmation");
|
||||
node.put("MessageId", "id-2");
|
||||
node.put("Token", "tok");
|
||||
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:t");
|
||||
node.put("Message", "confirm");
|
||||
node.put("SubscribeURL", "http://localhost:4566/?Action=ConfirmSubscription");
|
||||
node.put("Timestamp", "2026-10-06T00:00:00.000Z");
|
||||
|
||||
assertEquals("Message\nconfirm\nMessageId\nid-2\n"
|
||||
+ "SubscribeURL\nhttp://localhost:4566/?Action=ConfirmSubscription\n"
|
||||
+ "Timestamp\n2026-10-06T00:00:00.000Z\nToken\ntok\n"
|
||||
+ "TopicArn\narn:aws:sns:us-east-1:000000000000:t\nType\nSubscriptionConfirmation\n",
|
||||
SnsMessageSigner.canonicalString(node));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signatureVersion2_signsWithSha256AndTamperingFails() throws Exception {
|
||||
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
ObjectNode node = notification("payload");
|
||||
signer.sign(node, "2", "SigningCertURL");
|
||||
|
||||
assertEquals("2", node.get("SignatureVersion").asText());
|
||||
assertTrue(verifies(signer, node, "SigningCertURL", "SHA256withRSA"));
|
||||
assertFalse(verifies(signer, node, "SigningCertURL", "SHA1withRSA"));
|
||||
|
||||
node.put("Message", "forged");
|
||||
assertFalse(verifies(signer, node, "SigningCertURL", "SHA256withRSA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedKey_isReusedAndANewKeyGetsANewUrl() {
|
||||
AccountAwareStorageBackend<SnsSigningKey> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
String first = newSigner(store).certificateUrl();
|
||||
String restarted = newSigner(store).certificateUrl();
|
||||
String fresh = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT)).certificateUrl();
|
||||
|
||||
assertTrue(first.matches("http://localhost:4566/_aws/sns/SimpleNotificationService-[0-9a-f]{32}\\.pem"), first);
|
||||
assertEquals(first, restarted);
|
||||
assertNotEquals(first, fresh);
|
||||
}
|
||||
|
||||
@Test
|
||||
void certificatePem_onlyForTheCurrentFileName() {
|
||||
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
String url = signer.certificateUrl();
|
||||
String fileName = url.substring(url.lastIndexOf('/') + 1);
|
||||
|
||||
assertTrue(signer.certificatePem(fileName).orElseThrow().startsWith("-----BEGIN CERTIFICATE-----"));
|
||||
assertTrue(signer.certificatePem("SimpleNotificationService-0.pem").isEmpty());
|
||||
}
|
||||
|
||||
private static SnsMessageSigner newSigner(AccountAwareStorageBackend<SnsSigningKey> store) {
|
||||
return new SnsMessageSigner(store, ACCOUNT, new CertificateGenerator(), BASE_URL);
|
||||
}
|
||||
|
||||
private static ObjectNode notification(String message) {
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("Type", "Notification");
|
||||
node.put("MessageId", "6f1b4bb4-6c0c-4d6f-9d64-6d5b4d4d4d4d");
|
||||
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:signed");
|
||||
node.put("Timestamp", "2026-10-06T10:00:00.000Z");
|
||||
node.put("Message", message);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static boolean verifies(SnsMessageSigner signer, JsonNode message, String certUrlField,
|
||||
String algorithm) throws Exception {
|
||||
String url = message.get(certUrlField).asText();
|
||||
String pem = signer.certificatePem(url.substring(url.lastIndexOf('/') + 1)).orElseThrow();
|
||||
X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
|
||||
String type = message.get("Type").asText();
|
||||
String[] fields = "Notification".equals(type)
|
||||
? new String[] {"Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"}
|
||||
: new String[] {"Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"};
|
||||
StringBuilder canonical = new StringBuilder();
|
||||
for (String field : fields) {
|
||||
JsonNode value = message.get(field);
|
||||
if (value != null && !value.isNull()) {
|
||||
canonical.append(field).append('\n').append(value.asText()).append('\n');
|
||||
}
|
||||
}
|
||||
Signature verifier = Signature.getInstance(algorithm);
|
||||
verifier.initVerify(certificate.getPublicKey());
|
||||
verifier.update(canonical.toString().getBytes(StandardCharsets.UTF_8));
|
||||
return verifier.verify(Base64.getDecoder().decode(message.get("Signature").asText()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user