mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(elbv2): terminate HTTPS with ACM and IAM certificates (#5959)
* feat(elbv2): serve HTTPS listeners with ACM and IAM certificates Route HTTPS traffic with SNI and refresh certificates when they change. * fix(elbv2): preserve attached ACM certificates Refuse revocation while a listener uses the certificate and keep certificate listings responsive when many listeners are configured.
This commit is contained in:
1 parent
73da37b90e
commit
0da0c80824
19 files changed
+5284
-471
No files matched your search
@@ -1,7 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
@@ -11,13 +14,17 @@ import io.github.hectorvent.floci.services.acm.model.CertificateStatus;
|
||||
import io.github.hectorvent.floci.services.acm.model.CertificateType;
|
||||
import io.github.hectorvent.floci.services.acm.model.DomainValidation;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.acm.model.RevocationReason;
|
||||
import io.github.hectorvent.floci.services.acm.model.ValidationMethod;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.ThreadInfo;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
@@ -28,18 +35,26 @@ import java.security.cert.TrustAnchor;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
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.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -113,6 +128,189 @@ class AcmServiceTest {
|
||||
assertEquals(replacement.privateKeyPem(), service.getCertificate(existing.getArn(), REGION).getPrivateKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingAcmExistsButCannotSupplyAnElbCertificate() {
|
||||
AcmService pending = newService(3600);
|
||||
Certificate certificate = pending.requestCertificate("pending.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
CertificateReferenceResolver resolver = new CertificateReferenceResolver(null, pending);
|
||||
assertTrue(resolver.exists(REGION, certificate.getArn()));
|
||||
assertEquals(false, resolver.isUsableAcmCertificate(REGION, certificate.getArn()));
|
||||
String owner = "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/test/one/two";
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> resolver.publishedMaterial(owner, REGION, certificate.getArn()));
|
||||
assertEquals("CertificateNotFound", failure.getErrorCode());
|
||||
assertEquals(CertificateStatus.PENDING_VALIDATION, pending.getCertificate(certificate.getArn(), REGION).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachedExportableCertificateCannotBeRevokedUntilDetached() {
|
||||
Certificate certificate = service.requestCertificate("revoke.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, new CertificateOptions(null, "ENABLED"), Map.of(), REGION);
|
||||
String owner = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/revoke";
|
||||
service.addInUseBy(certificate.getArn(), owner, REGION);
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> service.revokeCertificate(certificate.getArn(), RevocationReason.KEY_COMPROMISE, REGION));
|
||||
assertAll(
|
||||
() -> assertEquals("ResourceInUseException", failure.getErrorCode()),
|
||||
() -> assertEquals(400, failure.getHttpStatus()),
|
||||
() -> assertEquals(CertificateStatus.ISSUED, service.getCertificate(certificate.getArn(), REGION).getStatus()),
|
||||
() -> assertEquals(List.of(owner), service.certificateInUseBy(certificate)));
|
||||
service.removeInUseBy(certificate.getArn(), owner, REGION);
|
||||
assertEquals(CertificateStatus.REVOKED,
|
||||
service.revokeCertificate(certificate.getArn(), RevocationReason.KEY_COMPROMISE, REGION).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPageScansLiveConsumersOnceAndRetainsPersistedUses() {
|
||||
Certificate first = service.requestCertificate("first.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
Certificate second = service.requestCertificate("second.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
service.requestCertificate("unused.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
service.addInUseBy(first.getArn(), "persisted-owner", REGION);
|
||||
AtomicInteger scans = new AtomicInteger();
|
||||
AcmCertificateReferenceProvider provider = mock();
|
||||
when(provider.acmCertificateReferences()).thenAnswer(call -> {
|
||||
scans.incrementAndGet();
|
||||
return List.of(new AcmCertificateReferenceProvider.CertificateReference(second.getArn(), "live-owner"));
|
||||
});
|
||||
Instance<AcmCertificateReferenceProvider> providers = mock();
|
||||
when(providers.iterator()).thenAnswer(call -> List.of(provider).iterator());
|
||||
service.referenceProviders = providers;
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
AcmJsonHandler handler = new AcmJsonHandler(service, mapper);
|
||||
JsonNode response = (JsonNode) handler.handle("ListCertificates", mapper.createObjectNode(), REGION).getEntity();
|
||||
Map<String, Boolean> uses = new HashMap<>();
|
||||
response.path("CertificateSummaryList").forEach(row -> uses.put(row.path("CertificateArn").asText(),
|
||||
row.path("InUse").asBoolean()));
|
||||
assertAll(
|
||||
() -> assertEquals(1, scans.get()),
|
||||
() -> assertEquals(3, uses.size()),
|
||||
() -> assertEquals(true, uses.get(first.getArn())),
|
||||
() -> assertEquals(true, uses.get(second.getArn())),
|
||||
() -> assertEquals(1L, uses.values().stream().filter(value -> !value).count()));
|
||||
scans.set(0);
|
||||
JsonNode page = (JsonNode) handler.handle("ListCertificates", mapper.createObjectNode().put("MaxItems", 1),
|
||||
REGION).getEntity();
|
||||
assertEquals(1, page.path("CertificateSummaryList").size());
|
||||
assertTrue(page.has("NextToken"));
|
||||
assertEquals(1, scans.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void capturedCertificateSummarySurvivesDeletion() {
|
||||
Certificate certificate = service.requestCertificate("list.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
service.deleteCertificate(certificate.getArn(), REGION);
|
||||
assertEquals(List.of(), service.certificateInUseBy(certificate));
|
||||
Map<String, List<String>> snapshot = service.certificateInUseBy(List.of(certificate));
|
||||
assertEquals(List.of(), snapshot.get(certificate.getArn()));
|
||||
assertThrows(UnsupportedOperationException.class, () -> snapshot.put("other", List.of()));
|
||||
assertThrows(UnsupportedOperationException.class, () -> snapshot.get(certificate.getArn()).add("other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOlderImportNotificationReadsTheNewestCommittedMaterial() throws Exception {
|
||||
CertificateGenerator.GeneratedCertificate original = ca.issueServerCertificate(
|
||||
"rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);
|
||||
Certificate certificate = service.importCertificate(original.certificatePem(), original.privateKeyPem(),
|
||||
ca.caPem(), null, Map.of(), REGION);
|
||||
CertificateGenerator.GeneratedCertificate first = ca.issueServerCertificate(
|
||||
"rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);
|
||||
CertificateGenerator.GeneratedCertificate second = ca.issueServerCertificate(
|
||||
"rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicBoolean pause = new AtomicBoolean(true);
|
||||
List<String> material = new CopyOnWriteArrayList<>();
|
||||
AcmCertificateReferenceProvider consumer = new AcmCertificateReferenceProvider() {
|
||||
@Override
|
||||
public List<CertificateReference> acmCertificateReferences() { return List.of(); }
|
||||
|
||||
@Override
|
||||
public void certificateReimported(String arn, String region) {
|
||||
if (pause.getAndSet(false)) {
|
||||
entered.countDown();
|
||||
try {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(failure);
|
||||
}
|
||||
}
|
||||
material.add(service.supplyWithCertificatesHeld(() -> service.getCertificate(arn, region).getCertificateBody()));
|
||||
}
|
||||
};
|
||||
Instance<AcmCertificateReferenceProvider> providers = mock();
|
||||
when(providers.iterator()).thenAnswer(call -> List.of(consumer).iterator());
|
||||
service.referenceProviders = providers;
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<Certificate> older = worker.submit(() -> service.importCertificate(first.certificatePem(),
|
||||
first.privateKeyPem(), ca.caPem(), certificate.getArn(), Map.of(), REGION));
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
service.importCertificate(second.certificatePem(), second.privateKeyPem(), ca.caPem(),
|
||||
certificate.getArn(), Map.of(), REGION);
|
||||
release.countDown();
|
||||
older.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(List.of(second.certificatePem(), second.certificatePem()), material);
|
||||
} finally {
|
||||
release.countDown();
|
||||
worker.shutdownNow();
|
||||
assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeleteWaitsForReferencePublicationThenObservesTheConsumer() throws Exception {
|
||||
Certificate certificate = service.requestCertificate("delete.example.test", List.of(), ValidationMethod.DNS,
|
||||
null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);
|
||||
String consumer = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/guarded";
|
||||
CountDownLatch held = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
CountDownLatch deleting = new CountDownLatch(1);
|
||||
AtomicLong holder = new AtomicLong();
|
||||
AtomicLong waiter = new AtomicLong();
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> publication = workers.submit(() -> service.supplyWithCertificatesHeld(() -> {
|
||||
holder.set(Thread.currentThread().threadId());
|
||||
held.countDown();
|
||||
try {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(failure);
|
||||
}
|
||||
service.addInUseBy(certificate.getArn(), consumer, REGION);
|
||||
return null;
|
||||
}));
|
||||
assertTrue(held.await(5, TimeUnit.SECONDS));
|
||||
Future<AwsException> deletion = workers.submit(() -> {
|
||||
waiter.set(Thread.currentThread().threadId());
|
||||
deleting.countDown();
|
||||
return assertThrows(AwsException.class, () -> service.deleteCertificate(certificate.getArn(), REGION));
|
||||
});
|
||||
assertTrue(deleting.await(5, TimeUnit.SECONDS));
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
|
||||
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(waiter.get());
|
||||
assertEquals(Thread.State.BLOCKED, info.getThreadState());
|
||||
assertEquals(holder.get(), info.getLockOwnerId());
|
||||
});
|
||||
release.countDown();
|
||||
publication.get(10, TimeUnit.SECONDS);
|
||||
assertEquals("ResourceInUseException", deletion.get(10, TimeUnit.SECONDS).getErrorCode());
|
||||
service.removeInUseBy(certificate.getArn(), consumer, REGION);
|
||||
service.deleteCertificate(certificate.getArn(), REGION);
|
||||
} finally {
|
||||
release.countDown();
|
||||
workers.shutdownNow();
|
||||
assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
private AcmService newService(int validationWaitSeconds) {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.testutil.LogCapture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.ThreadInfo;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
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.function.Supplier;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.allowPublications;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.applyPublication;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2ServiceTest.serviceWithStorage;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2ServiceTest.sharedStorageFactory;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ElbV2CertificatePublicationServiceTest {
|
||||
private static final String REGION = "us-west-2";
|
||||
private static final List<String> ALB_SUBNETS = List.of("subnet-a", "subnet-b");
|
||||
private static final String HELD_CERTIFICATE = "arn:aws:iam::000000000000:server-certificate/held";
|
||||
private static final String OTHER_CERTIFICATE = "arn:aws:iam::000000000000:server-certificate/other";
|
||||
|
||||
@Mock
|
||||
ElbV2DataPlane dataPlane;
|
||||
|
||||
@Mock
|
||||
ElbV2HealthChecker healthChecker;
|
||||
|
||||
private ElbV2Service service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = serviceWithStorage(null, dataPlane, healthChecker);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"create", "modify", "add"})
|
||||
void unavailableAcmCannotBePublishedWithoutALiveTlsRuntime(String operation) {
|
||||
String lb = service.createLoadBalancer(REGION, "pending-acm", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
Listener existing = service.createListener(REGION, lb, "HTTPS", 9443, null,
|
||||
List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());
|
||||
String pending = "arn:aws:acm:us-west-2:000000000000:certificate/pending";
|
||||
CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);
|
||||
AtomicBoolean issued = new AtomicBoolean();
|
||||
when(resolver.exists(anyString(), anyString())).thenReturn(true);
|
||||
when(resolver.isUsableAcmCertificate(REGION, pending)).thenAnswer(call -> issued.get());
|
||||
lenient().doAnswer(call -> call.getArgument(1, Supplier.class).get()).when(resolver).supplyWhileHeld(any(), any());
|
||||
service.certificateResolver = resolver;
|
||||
Runnable request = () -> {
|
||||
if ("create".equals(operation)) {
|
||||
service.createListener(REGION, lb, "HTTPS", 9444, null, List.of(pending), List.of(), List.of(), Map.of());
|
||||
} else if ("modify".equals(operation)) {
|
||||
service.modifyListener(REGION, existing.getListenerArn(), null, null, null, List.of(pending), null, null);
|
||||
} else {
|
||||
service.addListenerCertificates(REGION, existing.getListenerArn(), List.of(pending));
|
||||
}
|
||||
};
|
||||
AwsException failure = assertThrows(AwsException.class, request::run);
|
||||
assertEquals("CertificateNotFound", failure.getErrorCode());
|
||||
assertEquals(1, service.describeListeners(REGION, lb, List.of()).size());
|
||||
assertEquals(List.of(HELD_CERTIFICATE), existing.getCertificates());
|
||||
issued.set(true);
|
||||
assertDoesNotThrow(request::run);
|
||||
assertEquals("create".equals(operation) ? 2 : 1, service.describeListeners(REGION, lb, List.of()).size());
|
||||
assertEquals("add".equals(operation) ? List.of(HELD_CERTIFICATE, pending)
|
||||
: "modify".equals(operation) ? List.of(pending) : List.of(HELD_CERTIFICATE), existing.getCertificates());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void portOnlyChangesRetryAProtocolConflictFromAnObsoleteSnapshot(boolean atPublication) {
|
||||
LoadBalancer lb = service.createLoadBalancer(REGION, "protocol-retry", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of());
|
||||
Listener listener = service.createListener(REGION, lb.getLoadBalancerArn(), "HTTPS", 9443, null,
|
||||
List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());
|
||||
AtomicBoolean first = new AtomicBoolean(true);
|
||||
Runnable conflict = () -> {
|
||||
if (first.compareAndSet(true, false)) {
|
||||
service.modifyListener(REGION, listener.getListenerArn(), "HTTP", null, null, null, null, null);
|
||||
throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);
|
||||
}
|
||||
};
|
||||
if (atPublication) {
|
||||
doAnswer(call -> {
|
||||
Listener prospective = call.getArgument(0);
|
||||
if (Integer.valueOf(9090).equals(prospective.getPort())) {
|
||||
conflict.run();
|
||||
}
|
||||
return applyPublication(call);
|
||||
}).when(dataPlane).publishListener(any(), eq(REGION), any(), any(), any(), any());
|
||||
} else {
|
||||
doAnswer(call -> {
|
||||
conflict.run();
|
||||
return null;
|
||||
}).when(dataPlane).requireCompatibleListenerProtocol(listener.getListenerArn(), 9090, "HTTPS");
|
||||
}
|
||||
Listener moved = assertDoesNotThrow(() -> service.modifyListener(REGION, listener.getListenerArn(),
|
||||
null, 9090, null, null, null, null));
|
||||
assertEquals("HTTP", moved.getProtocol());
|
||||
assertEquals(9090, moved.getPort());
|
||||
assertEquals(List.of(HELD_CERTIFICATE), moved.getCertificates());
|
||||
assertFalse(first.get());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void unchangedProtocolConflictsRemainTerminal(boolean atPublication) {
|
||||
LoadBalancer lb = service.createLoadBalancer(REGION, "protocol-refusal", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of());
|
||||
Listener listener = service.createListener(REGION, lb.getLoadBalancerArn(), "HTTPS", 9443, null,
|
||||
List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());
|
||||
AtomicReference<Integer> refusals = new AtomicReference<>(0);
|
||||
if (atPublication) {
|
||||
doAnswer(call -> {
|
||||
refusals.updateAndGet(count -> count + 1);
|
||||
throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);
|
||||
}).when(dataPlane).publishListener(any(), eq(REGION), any(), any(), any(), any());
|
||||
} else {
|
||||
doAnswer(call -> {
|
||||
refusals.updateAndGet(count -> count + 1);
|
||||
throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);
|
||||
}).when(dataPlane).requireCompatibleListenerProtocol(listener.getListenerArn(), 9090, "HTTPS");
|
||||
}
|
||||
AwsException refusal = assertThrows(AwsException.class, () -> service.modifyListener(REGION,
|
||||
listener.getListenerArn(), null, 9090, null, null, null, null));
|
||||
assertEquals("InvalidConfigurationRequest", refusal.getErrorCode());
|
||||
assertEquals(1, refusals.get());
|
||||
assertEquals(9443, listener.getPort());
|
||||
assertEquals("HTTPS", listener.getProtocol());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedParentRefusesAListenerWaitingForItsPublicationFence() throws Exception {
|
||||
LoadBalancer lb = service.createLoadBalancer(REGION, "parent-fence", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of());
|
||||
CountDownLatch publicationEntered = new CountDownLatch(1);
|
||||
AtomicReference<Thread> publisher = new AtomicReference<>();
|
||||
doAnswer(call -> {
|
||||
publisher.set(Thread.currentThread());
|
||||
publicationEntered.countDown();
|
||||
return applyPublication(call);
|
||||
}).when(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<Listener> creation;
|
||||
synchronized (lb) {
|
||||
creation = worker.submit(() -> service.createListener(REGION, lb.getLoadBalancerArn(), "HTTP", 9090,
|
||||
null, List.of(), List.of(), List.of(), Map.of()));
|
||||
assertTrue(publicationEntered.await(5, TimeUnit.SECONDS));
|
||||
long owner = Thread.currentThread().threadId();
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
|
||||
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(publisher.get().threadId());
|
||||
assertNotNull(info);
|
||||
assertEquals(Thread.State.BLOCKED, info.getThreadState());
|
||||
assertEquals(owner, info.getLockOwnerId());
|
||||
});
|
||||
service.deleteLoadBalancer(REGION, lb.getLoadBalancerArn());
|
||||
}
|
||||
ExecutionException refused = assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
|
||||
assertEquals("LoadBalancerNotFound", ((AwsException) refused.getCause()).getErrorCode());
|
||||
assertTrue(service.describeListeners(REGION, lb.getLoadBalancerArn(), List.of()).isEmpty());
|
||||
assertTrue(service.describeRules(REGION, null, List.of()).isEmpty());
|
||||
} finally {
|
||||
worker.shutdownNow();
|
||||
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerRefusedUnderTheCertificateGuardLeavesTheListenerWhereItWas() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "sample-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String tgArn = createTargetGroup("sample-tg");
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTPS", 443, "ELBSecurityPolicy-2016-08", List.of(HELD_CERTIFICATE),
|
||||
List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
service.certificateResolver = deletedOnTheSecondLook();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(
|
||||
REGION, listenerArn, "TLS", 8443, "ELBSecurityPolicy-TLS13-1-2-2021-06",
|
||||
List.of(OTHER_CERTIFICATE), null, null));
|
||||
|
||||
assertEquals("CertificateNotFound", e.getErrorCode());
|
||||
Listener listener = service.describeListeners(REGION, lbArn, List.of(listenerArn)).getFirst();
|
||||
assertEquals(Integer.valueOf(443), listener.getPort());
|
||||
assertEquals("HTTPS", listener.getProtocol());
|
||||
assertEquals("ELBSecurityPolicy-2016-08", listener.getSslPolicy());
|
||||
assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates());
|
||||
verify(dataPlane, never()).removeListener(anyString(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerProtocolAloneTakesTheGuardForTheCertificatesItPutsIntoService() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "sample-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String tgArn = createTargetGroup("sample-tg");
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTP", 80, null, List.of(HELD_CERTIFICATE),
|
||||
List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
service.certificateResolver = deletedOnTheSecondLook();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(
|
||||
REGION, listenerArn, "HTTPS", null, null, null, null, null));
|
||||
|
||||
assertEquals("CertificateNotFound", e.getErrorCode());
|
||||
assertEquals("HTTP", service.describeListeners(REGION, lbArn, List.of(listenerArn))
|
||||
.getFirst().getProtocol());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void oneBrokenSavedListenerDoesNotPreventHealthyRestoration(boolean domainFailure) {
|
||||
StorageFactory factory = sharedStorageFactory();
|
||||
ElbV2Service first = serviceWithStorage(factory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));
|
||||
String lb = first.createLoadBalancer(REGION, "restore-isolation", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
Listener broken = first.createListener(REGION, lb, "HTTP", 9080, null,
|
||||
List.of(), List.of(), List.of(), Map.of());
|
||||
Listener healthy = first.createListener(REGION, lb, "HTTP", 9081, null,
|
||||
List.of(), List.of(), List.of(), Map.of());
|
||||
ElbV2DataPlane runtime = mock(ElbV2DataPlane.class);
|
||||
ElbV2Service reloaded = serviceWithStorage(factory, runtime, mock(ElbV2HealthChecker.class));
|
||||
AtomicBoolean firstRestore = new AtomicBoolean(true);
|
||||
doAnswer(call -> {
|
||||
if (firstRestore.getAndSet(false)) {
|
||||
if (domainFailure) {
|
||||
throw new AwsException("CertificateNotFound", "controlled missing stored material", 400);
|
||||
}
|
||||
throw new IllegalStateException("controlled unusable stored material");
|
||||
}
|
||||
return applyPublication(call);
|
||||
}).when(runtime).publishListener(any(), eq(REGION), any(), any(), any(), any());
|
||||
List<LogRecord> warnings = LogCapture.capture(ElbV2Service.class,
|
||||
() -> assertDoesNotThrow(reloaded::restorePersistedRuntime));
|
||||
String reason = domainFailure ? "controlled missing stored material" : "controlled unusable stored material";
|
||||
assertTrue(warnings.stream().anyMatch(record -> record.getParameters() != null
|
||||
&& record.getParameters().length == 3
|
||||
&& reason.equals(record.getParameters()[2])), "restore warning must explain why the listener was skipped");
|
||||
ArgumentCaptor<Listener> restored = ArgumentCaptor.captor();
|
||||
verify(runtime, times(2)).publishListener(restored.capture(), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(List.of(broken.getListenerArn(), healthy.getListenerArn()).stream().sorted().toList(),
|
||||
restored.getAllValues().stream().map(Listener::getListenerArn).sorted().toList());
|
||||
assertEquals(2, reloaded.describeListeners(REGION, lb, List.of()).size());
|
||||
allowPublications(runtime);
|
||||
assertDoesNotThrow(reloaded::restorePersistedRuntime);
|
||||
assertEquals(2, reloaded.describeListeners(REGION, lb, List.of()).size());
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolver that finds the certificate once and not again, which is what a
|
||||
* {@code DeleteServerCertificate} landing between the check outside the guard and the one
|
||||
* under it looks like from inside the call.
|
||||
*/
|
||||
private static CertificateReferenceResolver deletedOnTheSecondLook() {
|
||||
CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);
|
||||
AtomicBoolean held = new AtomicBoolean();
|
||||
when(resolver.exists(anyString(), anyString())).thenAnswer(call -> !held.get());
|
||||
doAnswer(invocation -> {
|
||||
held.set(true);
|
||||
try {
|
||||
return invocation.getArgument(1, Supplier.class).get();
|
||||
} finally {
|
||||
held.set(false);
|
||||
}
|
||||
}).when(resolver).supplyWhileHeld(any(), any());
|
||||
return resolver;
|
||||
}
|
||||
|
||||
private String createTargetGroup(String name) {
|
||||
return service.createTargetGroup(
|
||||
REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",
|
||||
"HTTP", "traffic-port", true, "/v1/ready", 30, 5, 5, 2, "200",
|
||||
"ipv4", Map.of()).getTargetGroupArn();
|
||||
}
|
||||
|
||||
private static Action forwardAction(String targetGroupArn) {
|
||||
Action action = new Action();
|
||||
action.setType("forward");
|
||||
action.setTargetGroupArn(targetGroupArn);
|
||||
return action;
|
||||
}
|
||||
}
|
||||
+29
@@ -157,6 +157,35 @@ class ElbV2DefaultAttributesIntegrationTest {
|
||||
not(hasItem("idle_timeout.timeout_seconds")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGatewayListenerRetainsItsControlPlaneWithoutAPort() {
|
||||
String arn = createLoadBalancer("attrs-gwlb-listener", "gateway", "10.120.");
|
||||
try {
|
||||
String listener = given().header("Authorization", AUTH).formParam("Action", "CreateListener")
|
||||
.formParam("LoadBalancerArn", arn).formParam("Protocol", "GENEVE")
|
||||
.formParam("DefaultActions.member.1.Type", "fixed-response")
|
||||
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
|
||||
.when().post("/").then().statusCode(200).extract()
|
||||
.path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
|
||||
given().header("Authorization", AUTH).formParam("Action", "ModifyListener")
|
||||
.formParam("ListenerArn", listener)
|
||||
.formParam("DefaultActions.member.1.Type", "fixed-response")
|
||||
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "201")
|
||||
.when().post("/").then().statusCode(200);
|
||||
given().header("Authorization", AUTH).formParam("Action", "DescribeListeners")
|
||||
.formParam("ListenerArns.member.1", listener).when().post("/").then().statusCode(200)
|
||||
.body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Protocol", equalTo("GENEVE"))
|
||||
.body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port.text()", equalTo(""))
|
||||
.body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.DefaultActions.member.FixedResponseConfig.StatusCode",
|
||||
equalTo("201"));
|
||||
given().header("Authorization", AUTH).formParam("Action", "DeleteListener")
|
||||
.formParam("ListenerArn", listener).when().post("/").then().statusCode(200);
|
||||
} finally {
|
||||
given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")
|
||||
.formParam("LoadBalancerArn", arn).when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aModifiedAttributeWinsOverItsDefaultAndTheRestStillReport() {
|
||||
String arn = createLoadBalancer("attrs-modified", "application", "10.99.");
|
||||
|
||||
+1783
File diff suppressed because it is too large.
Load diff
+5
@@ -241,6 +241,11 @@ class ElbV2ListenerCertificateIntegrationTest {
|
||||
assertEquals(List.of(certificate), listenerCertificates(listener));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anHttpListenerStillNeedsNoCertificate() {
|
||||
createListener("HTTP", null).statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTlsListenerIsHeldToTheSameCheckAsAnHttpsOne() {
|
||||
// The reference brackets the member for HTTPS and TLS, so both, not HTTPS alone.
|
||||
|
||||
+624
@@ -0,0 +1,624 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.TlsProxyServer;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpServerResponse;
|
||||
import io.vertx.core.net.SSLOptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.ThreadInfo;
|
||||
import java.net.BindException;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
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 ElbV2ListenerOwnershipTest {
|
||||
private static final String REGION = "us-west-2";
|
||||
private static final String HOST = "shared.example.test";
|
||||
private static final String CERTIFICATE = "arn:aws:acm:us-west-2:000000000000:certificate/shared";
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void unusableSavedMaterialCannotClaimAPortOrPublishControlState(boolean emptyDefault) {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
Listener listener = listener("unusable", 8443, true);
|
||||
CertificateMaterial valid = fixture.plane.certificateResolver.publishedMaterial(listener.getListenerArn(), REGION, CERTIFICATE);
|
||||
CertificateGenerator.GeneratedCertificate other = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
HOST, List.of(), KeyAlgorithm.RSA_2048);
|
||||
CertificateMaterial broken = new CertificateMaterial(CERTIFICATE, valid.certificateBody(), other.privateKeyPem(), null);
|
||||
when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(broken);
|
||||
if (emptyDefault) {
|
||||
listener.setCertificates(List.of());
|
||||
}
|
||||
AtomicInteger publications = new AtomicInteger();
|
||||
try {
|
||||
assertThrows(RuntimeException.class, () -> fixture.plane.publishListener(listener, REGION, 8443,
|
||||
() -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("unpublished")), admitted -> admitted.get()));
|
||||
assertEquals(0, publications.get());
|
||||
assertTrue(registry.isEmpty());
|
||||
assertEquals(0, fixture.creations(8443));
|
||||
listener.setCertificates(List.of(CERTIFICATE));
|
||||
when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(valid);
|
||||
assertTrue(fixture.plane.publishListener(listener, REGION, 8443,
|
||||
() -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("retry")), admitted -> admitted.get()));
|
||||
assertEquals(1, publications.get());
|
||||
fixture.serves(8443, "retry");
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void materialChangedBeforeAdmissionCannotPublishAnOlderPreparedSnapshot() {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
Listener listener = listener("overtaken", 8443, true);
|
||||
CertificateGenerator.GeneratedCertificate newer = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
HOST, List.of(), KeyAlgorithm.RSA_2048);
|
||||
CertificateMaterial current = new CertificateMaterial(CERTIFICATE, newer.certificatePem(), newer.privateKeyPem(), null);
|
||||
AtomicInteger publications = new AtomicInteger();
|
||||
try {
|
||||
assertFalse(fixture.plane.publishListener(listener, REGION, 8443,
|
||||
() -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("stale")), operation -> {
|
||||
when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE)))
|
||||
.thenReturn(current);
|
||||
return operation.get();
|
||||
}));
|
||||
assertEquals(0, publications.get());
|
||||
assertTrue(registry.isEmpty());
|
||||
assertEquals(0, fixture.creations(8443));
|
||||
assertTrue(fixture.plane.publishListener(listener, REGION, 8443,
|
||||
() -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("current")), operation -> operation.get()));
|
||||
assertEquals(List.of(current), registry.get(listener.getListenerArn()).certificates());
|
||||
assertEquals(1, publications.get());
|
||||
fixture.serves(8443, "current");
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
|
||||
void refusedControlPublicationRestoresTheExactRuntimeReservation(boolean existing, boolean throwsFailure) {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
Listener first = listener("publication", 8443, false);
|
||||
Listener next = listener("publication", 9443, false);
|
||||
try {
|
||||
if (existing) {
|
||||
publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("old")));
|
||||
}
|
||||
ElbV2DataPlane.ListenerBinding expected = registry.get(first.getListenerArn());
|
||||
AtomicInteger callbacks = new AtomicInteger();
|
||||
if (throwsFailure) {
|
||||
assertThrows(IllegalArgumentException.class, () -> fixture.plane.publishListener(next, REGION, 8443,
|
||||
() -> {
|
||||
callbacks.incrementAndGet();
|
||||
throw new IllegalArgumentException("refused control publication");
|
||||
}, () -> List.of(rule("unpublished")), admitted -> admitted.get()));
|
||||
} else {
|
||||
assertFalse(fixture.plane.publishListener(next, REGION, 8443, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return false;
|
||||
}, () -> List.of(rule("unpublished")), admitted -> admitted.get()));
|
||||
}
|
||||
assertEquals(1, callbacks.get());
|
||||
assertSame(expected, registry.get(first.getListenerArn()));
|
||||
assertEquals(0, fixture.creations(9443));
|
||||
assertEquals(0, fixture.closes(8443));
|
||||
if (existing) {
|
||||
fixture.serves(8443, "old");
|
||||
fixture.plane.recompileRules(first.getListenerArn(), () -> List.of(rule("latest")));
|
||||
} else {
|
||||
assertTrue(registry.isEmpty());
|
||||
}
|
||||
assertTrue(fixture.plane.publishListener(next, REGION, 8443, () -> true,
|
||||
() -> List.of(rule("initial")), admitted -> admitted.get()));
|
||||
fixture.serves(9443, existing ? "latest" : "initial");
|
||||
assertEquals(1, fixture.creations(9443));
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void noPortControlCallbacksRunWithoutCreatingAGeneveSocket(boolean mockMode) {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
when(fixture.plane.config.services().elbv2().mock()).thenReturn(mockMode);
|
||||
Listener gateway = listener("gateway", 8443, false);
|
||||
gateway.setPort(null);
|
||||
gateway.setProtocol("GENEVE");
|
||||
AtomicInteger callbacks = new AtomicInteger();
|
||||
try {
|
||||
assertTrue(fixture.plane.publishListener(gateway, REGION, null, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return true;
|
||||
}, () -> {
|
||||
throw new AssertionError("control-only publication must not initialize socket rules");
|
||||
}, admitted -> admitted.get()));
|
||||
assertTrue(fixture.plane.updateListener(null, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return true;
|
||||
}));
|
||||
assertTrue(fixture.plane.removeListener(gateway.getListenerArn(), null, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return true;
|
||||
}));
|
||||
assertEquals(3, callbacks.get());
|
||||
assertTrue(registry.isEmpty());
|
||||
assertTrue(fixture.created.isEmpty());
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentRuntimeAndStoppedRuntimeStillApplyControlCallbacks() {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
Listener listener = listener("stopped", 8443, false);
|
||||
AtomicInteger callbacks = new AtomicInteger();
|
||||
try {
|
||||
assertTrue(fixture.plane.removeListener(listener.getListenerArn(), 8443, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return true;
|
||||
}));
|
||||
fixture.plane.shutdown();
|
||||
assertTrue(fixture.plane.publishListener(listener, REGION, 8443, () -> {
|
||||
callbacks.incrementAndGet();
|
||||
return true;
|
||||
}, () -> {
|
||||
throw new AssertionError("stopped runtime must not compile socket rules");
|
||||
}, admitted -> admitted.get()));
|
||||
assertEquals(2, callbacks.get());
|
||||
assertTrue(registry.isEmpty());
|
||||
assertTrue(fixture.created.isEmpty());
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void delayedRuleRefreshReadsCurrentMembershipInsideThePortGate() throws Exception {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch holding = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Thread> owner = new AtomicReference<>();
|
||||
AtomicReference<Thread> refresher = new AtomicReference<>();
|
||||
AtomicReference<List<Rule>> current = new AtomicReference<>(List.of(rule("old")));
|
||||
AtomicInteger reads = new AtomicInteger();
|
||||
Listener listener = listener("rules", 8443, false);
|
||||
try {
|
||||
publishRuntime(fixture.plane, listener, REGION, listener.getPort(), current.get());
|
||||
// Qualify the JDK Future to distinguish it from Vert.x Future.
|
||||
java.util.concurrent.Future<?> held = workers.submit(() -> fixture.plane.updateListener(8443, () -> {
|
||||
owner.set(Thread.currentThread());
|
||||
holding.countDown();
|
||||
try {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(interrupted);
|
||||
}
|
||||
return true;
|
||||
}));
|
||||
assertTrue(holding.await(5, TimeUnit.SECONDS));
|
||||
java.util.concurrent.Future<?> refreshed = workers.submit(() -> {
|
||||
refresher.set(Thread.currentThread());
|
||||
fixture.plane.recompileRules(listener.getListenerArn(), () -> {
|
||||
reads.incrementAndGet();
|
||||
return current.get();
|
||||
});
|
||||
});
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
|
||||
assertNotNull(refresher.get());
|
||||
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(refresher.get().threadId(), 30);
|
||||
assertNotNull(info);
|
||||
assertEquals(Thread.State.BLOCKED, info.getThreadState());
|
||||
assertEquals(owner.get().threadId(), info.getLockOwnerId());
|
||||
assertTrue(Arrays.stream(info.getStackTrace()).anyMatch(frame -> frame.getMethodName().equals("onPort")));
|
||||
});
|
||||
assertEquals(0, reads.get(), "rule membership must not be read before acquiring the gate");
|
||||
current.set(List.of(rule("added"), rule("old")));
|
||||
publishRuntime(fixture.plane, listener("unrelated", 10443, false), REGION, null, List.of(rule("progress")));
|
||||
fixture.serves(10443, "progress");
|
||||
release.countDown();
|
||||
held.get(5, TimeUnit.SECONDS);
|
||||
refreshed.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, reads.get());
|
||||
fixture.serves(8443, "added");
|
||||
} finally {
|
||||
release.countDown();
|
||||
workers.shutdownNow();
|
||||
try {
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void competingInitialClaimsRetryAgainstThePublishedBinding(boolean secure) throws Exception {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
Listener first = listener("same", 8443, secure);
|
||||
Listener second = listener("same", 9443, secure);
|
||||
registry.arn = first.getListenerArn();
|
||||
try {
|
||||
// Prime release-handler registration before pausing a port gate.
|
||||
publishRuntime(fixture.plane, listener("prime", 10443, false), REGION, null, List.of(rule("prime")));
|
||||
// Qualify the JDK Future to distinguish it from Vert.x Future.
|
||||
java.util.concurrent.Future<?> initial = workers.submit(() -> {
|
||||
registry.worker = Thread.currentThread();
|
||||
registry.pauseInitial = true;
|
||||
publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));
|
||||
});
|
||||
assertTrue(registry.entered.await(5, TimeUnit.SECONDS));
|
||||
workers.submit(() -> publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second"))))
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
fixture.serves(9443, "second");
|
||||
registry.release.countDown();
|
||||
initial.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, registry.failedClaims.get(), "the actual putIfAbsent must lose before retrying");
|
||||
fixture.serves(8443, "first");
|
||||
assertEquals(1, fixture.closes(9443));
|
||||
publishRuntime(fixture.plane, listener("other", 9443, secure), REGION, null, List.of(rule("reused")));
|
||||
fixture.serves(9443, "reused");
|
||||
verify(fixture.plane.tlsProxyServer, times(1)).onPortReleased(any());
|
||||
} finally {
|
||||
registry.release.countDown();
|
||||
workers.shutdownNow();
|
||||
try {
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void stopCannotEraseSameArnPublishedOnAnotherPort(boolean secure) throws Exception {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
Listener first = listener("same", 8443, secure);
|
||||
Listener second = listener("same", 9443, secure);
|
||||
registry.arn = first.getListenerArn();
|
||||
try {
|
||||
publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));
|
||||
// Qualify the JDK Future to distinguish it from Vert.x Future.
|
||||
java.util.concurrent.Future<?> stopping = workers.submit(() -> {
|
||||
registry.worker = Thread.currentThread();
|
||||
registry.pauseRemoval = true;
|
||||
removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());
|
||||
});
|
||||
assertTrue(registry.entered.await(5, TimeUnit.SECONDS));
|
||||
workers.submit(() -> publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second"))))
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
fixture.serves(9443, "second");
|
||||
registry.release.countDown();
|
||||
stopping.get(5, TimeUnit.SECONDS);
|
||||
fixture.serves(9443, "second");
|
||||
assertEquals(1, fixture.closes(8443));
|
||||
assertEquals(0, fixture.closes(9443));
|
||||
int creations = fixture.creations(9443);
|
||||
publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));
|
||||
assertEquals(creations, fixture.creations(9443));
|
||||
fixture.serves(9443, "second");
|
||||
removeRuntime(fixture.plane, second.getListenerArn(), second.getPort());
|
||||
assertEquals(1, fixture.closes(9443));
|
||||
publishRuntime(fixture.plane, listener("other", 8443, secure), REGION, null, List.of(rule("reused")));
|
||||
fixture.serves(8443, "reused");
|
||||
} finally {
|
||||
registry.release.countDown();
|
||||
workers.shutdownNow();
|
||||
try {
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void aPublisherQueuedOnARetiringPortStateRetriesItsIdentity(boolean failedClose) throws Exception {
|
||||
Fixture fixture = new Fixture(new Registry());
|
||||
CountDownLatch insideClose = new CountDownLatch(1);
|
||||
CountDownLatch releaseClose = new CountDownLatch(1);
|
||||
AtomicReference<Throwable> stoppingFailure = new AtomicReference<>();
|
||||
AtomicReference<Throwable> publisherFailure = new AtomicReference<>();
|
||||
Listener first = listener("first", 8443, false);
|
||||
Listener second = listener("second", 8443, false);
|
||||
Thread stopping = Thread.ofPlatform().unstarted(() -> {
|
||||
try {
|
||||
removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());
|
||||
} catch (Throwable failure) {
|
||||
stoppingFailure.set(failure);
|
||||
}
|
||||
});
|
||||
Thread publishing = Thread.ofPlatform().unstarted(() -> {
|
||||
try {
|
||||
publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));
|
||||
} catch (Throwable failure) {
|
||||
publisherFailure.set(failure);
|
||||
}
|
||||
});
|
||||
try {
|
||||
publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));
|
||||
doAnswer(ignored -> {
|
||||
insideClose.countDown();
|
||||
assertTrue(releaseClose.await(10, TimeUnit.SECONDS));
|
||||
return failedClose ? Future.failedFuture(new IllegalStateException("controlled close failure"))
|
||||
: Future.succeededFuture();
|
||||
}).when(fixture.servers.get(8443)).close();
|
||||
stopping.start();
|
||||
assertTrue(insideClose.await(5, TimeUnit.SECONDS));
|
||||
publishing.start();
|
||||
await().atMost(5, TimeUnit.SECONDS).until(() -> {
|
||||
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(publishing.threadId(), 30);
|
||||
return info != null && info.getThreadState() == Thread.State.BLOCKED
|
||||
&& info.getLockOwnerId() == stopping.threadId()
|
||||
&& Arrays.stream(info.getStackTrace()).anyMatch(frame ->
|
||||
frame.getClassName().equals(ElbV2DataPlane.class.getName())
|
||||
&& frame.getMethodName().equals("onPort"));
|
||||
});
|
||||
publishRuntime(fixture.plane, listener("unrelated", 9443, false), REGION, null, List.of(rule("unrelated")));
|
||||
fixture.serves(9443, "unrelated");
|
||||
releaseClose.countDown();
|
||||
stopping.join(5_000);
|
||||
publishing.join(5_000);
|
||||
assertFalse(stopping.isAlive());
|
||||
assertFalse(publishing.isAlive());
|
||||
assertNull(stoppingFailure.get());
|
||||
assertNull(publisherFailure.get());
|
||||
assertEquals(2, fixture.creations(8443), "queued publisher must bind using the current port state");
|
||||
fixture.serves(8443, "second");
|
||||
fixture.serves(9443, "unrelated");
|
||||
} finally {
|
||||
releaseClose.countDown();
|
||||
stopping.interrupt();
|
||||
publishing.interrupt();
|
||||
stopping.join(5_000);
|
||||
publishing.join(5_000);
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedClosePermitsABoundedBindAttemptAndIdenticalPublicationCanRetry() {
|
||||
Fixture fixture = new Fixture(new Registry());
|
||||
Promise<Void> close = Promise.promise();
|
||||
Listener first = listener("first", 8443, false);
|
||||
Listener second = listener("second", 8443, false);
|
||||
try {
|
||||
publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));
|
||||
doReturn(close.future()).when(fixture.servers.get(8443)).close();
|
||||
removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());
|
||||
publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));
|
||||
assertEquals(1, fixture.creations(8443), "pending close must defer the next bind");
|
||||
publishRuntime(fixture.plane, listener("unrelated", 9443, false), REGION, null, List.of(rule("unrelated")));
|
||||
fixture.serves(9443, "unrelated");
|
||||
// A failed close does not establish that the old physical socket is free.
|
||||
fixture.failNextListenPort = 8443;
|
||||
close.fail(new IllegalStateException("controlled close failure"));
|
||||
assertEquals(2, fixture.creations(8443));
|
||||
assertEquals(1, fixture.closes(8443), "failed replacement must be closed");
|
||||
publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));
|
||||
assertEquals(3, fixture.creations(8443));
|
||||
fixture.serves(8443, "second");
|
||||
fixture.serves(9443, "unrelated");
|
||||
} finally {
|
||||
close.tryComplete();
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Registry extends ConcurrentHashMap<String, ElbV2DataPlane.ListenerBinding> {
|
||||
private final CountDownLatch entered = new CountDownLatch(1);
|
||||
private final CountDownLatch release = new CountDownLatch(1);
|
||||
private final AtomicInteger reads = new AtomicInteger();
|
||||
private final AtomicInteger failedClaims = new AtomicInteger();
|
||||
private final AtomicBoolean paused = new AtomicBoolean();
|
||||
private volatile Thread worker;
|
||||
private String arn;
|
||||
private volatile boolean pauseInitial;
|
||||
private volatile boolean pauseRemoval;
|
||||
|
||||
@Override
|
||||
public ElbV2DataPlane.ListenerBinding get(Object key) {
|
||||
ElbV2DataPlane.ListenerBinding actual = super.get(key);
|
||||
// Shared publication first checks its expected binding, then install checks the claim.
|
||||
if (Thread.currentThread() == worker && arn.equals(key) && pauseInitial
|
||||
&& reads.incrementAndGet() == 3 && actual == null) {
|
||||
pause();
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ElbV2DataPlane.ListenerBinding putIfAbsent(String key, ElbV2DataPlane.ListenerBinding value) {
|
||||
ElbV2DataPlane.ListenerBinding previous = super.putIfAbsent(key, value);
|
||||
if (Thread.currentThread() == worker && arn.equals(key) && previous != null) {
|
||||
failedClaims.incrementAndGet();
|
||||
}
|
||||
return previous;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object key, Object value) {
|
||||
boolean removed = super.remove(key, value);
|
||||
if (Thread.currentThread() == worker && arn.equals(key) && pauseRemoval && removed) {
|
||||
pause();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
private void pause() {
|
||||
if (paused.compareAndSet(false, true)) {
|
||||
entered.countDown();
|
||||
try {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS), "registry boundary was not released");
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Fixture {
|
||||
private final ElbV2DataPlane plane;
|
||||
private final Map<Integer, Handler<HttpServerRequest>> handlers = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, AtomicInteger> created = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, AtomicInteger> closed = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();
|
||||
private volatile int failNextListenPort = -1;
|
||||
|
||||
private Fixture(Registry registry) {
|
||||
plane = new ElbV2DataPlane(registry);
|
||||
plane.config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElbV2ServiceConfig config = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
when(plane.config.services()).thenReturn(services);
|
||||
when(services.elbv2()).thenReturn(config);
|
||||
when(config.mock()).thenReturn(false);
|
||||
when(plane.config.port()).thenReturn(4566);
|
||||
plane.tlsProxyServer = mock(TlsProxyServer.class);
|
||||
when(plane.tlsProxyServer.reservesPort(anyInt())).thenReturn(false);
|
||||
plane.elbV2Service = mock(ElbV2Service.class);
|
||||
LoadBalancer balancer = new LoadBalancer();
|
||||
balancer.setDnsName(HOST);
|
||||
when(plane.elbV2Service.getLoadBalancer(eq(REGION), anyString())).thenReturn(balancer);
|
||||
plane.certificateResolver = mock(CertificateReferenceResolver.class);
|
||||
CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
HOST, List.of(), KeyAlgorithm.RSA_2048);
|
||||
CertificateMaterial material = new CertificateMaterial(CERTIFICATE, pair.certificatePem(), pair.privateKeyPem(), null);
|
||||
when(plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(material);
|
||||
plane.vertx = mock(Vertx.class);
|
||||
when(plane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call -> {
|
||||
int port = ((HttpServerOptions) call.getArgument(0)).getPort();
|
||||
created.computeIfAbsent(port, ignored -> new AtomicInteger()).incrementAndGet();
|
||||
HttpServer server = mock(HttpServer.class);
|
||||
servers.put(port, server);
|
||||
when(server.requestHandler(any())).thenAnswer(handler -> {
|
||||
handlers.put(port, handler.getArgument(0));
|
||||
return server;
|
||||
});
|
||||
when(server.listen()).thenAnswer(ignored -> {
|
||||
if (failNextListenPort == port) {
|
||||
failNextListenPort = -1;
|
||||
return Future.failedFuture(new BindException("controlled occupied port"));
|
||||
}
|
||||
return Future.succeededFuture(server);
|
||||
});
|
||||
when(server.close()).thenAnswer(ignored -> {
|
||||
closed.computeIfAbsent(port, key -> new AtomicInteger()).incrementAndGet();
|
||||
return Future.succeededFuture();
|
||||
});
|
||||
when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true));
|
||||
return server;
|
||||
});
|
||||
}
|
||||
|
||||
private int creations(int port) {
|
||||
AtomicInteger count = created.get(port);
|
||||
return count == null ? 0 : count.get();
|
||||
}
|
||||
|
||||
private int closes(int port) {
|
||||
AtomicInteger count = closed.get(port);
|
||||
return count == null ? 0 : count.get();
|
||||
}
|
||||
|
||||
private void serves(int port, String body) {
|
||||
HttpServerRequest request = mock(HttpServerRequest.class);
|
||||
HttpServerResponse response = mock(HttpServerResponse.class);
|
||||
when(request.host()).thenReturn(HOST);
|
||||
when(request.response()).thenReturn(response);
|
||||
when(response.setStatusCode(anyInt())).thenReturn(response);
|
||||
handlers.get(port).handle(request);
|
||||
verify(response).setStatusCode(200);
|
||||
verify(response).end(body);
|
||||
}
|
||||
}
|
||||
|
||||
private static Listener listener(String name, int port, boolean secure) {
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/shared/1/" + name);
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/shared/1");
|
||||
listener.setPort(port);
|
||||
listener.setProtocol(secure ? "HTTPS" : "HTTP");
|
||||
listener.setCertificates(secure ? List.of(CERTIFICATE) : List.of());
|
||||
return listener;
|
||||
}
|
||||
|
||||
private static Rule rule(String body) {
|
||||
Action action = new Action();
|
||||
action.setType("fixed-response");
|
||||
action.setFixedResponseStatusCode("200");
|
||||
action.setFixedResponseMessageBody(body);
|
||||
Rule rule = new Rule();
|
||||
rule.setDefault(true);
|
||||
rule.setActions(List.of(action));
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
|
||||
final class ElbV2PublicationTestSupport {
|
||||
private ElbV2PublicationTestSupport() { }
|
||||
|
||||
static void publishRuntime(ElbV2DataPlane plane, Listener listener, String region,
|
||||
Integer previousPort, List<Rule> rules) {
|
||||
while (!plane.publishListener(listener, region, previousPort, () -> {
|
||||
plane.recompileRules(listener.getListenerArn(), () -> rules);
|
||||
return true;
|
||||
}, () -> rules, Supplier::get)) {
|
||||
// The service retries a runtime reservation changed by another publisher.
|
||||
}
|
||||
}
|
||||
|
||||
static void removeRuntime(ElbV2DataPlane plane, String arn, Integer storedPort) {
|
||||
while (!plane.removeListener(arn, storedPort, () -> true)) {
|
||||
// Retry an identity changed while waiting for its port gate.
|
||||
}
|
||||
}
|
||||
|
||||
static boolean applyPublication(InvocationOnMock call) {
|
||||
Function<Supplier<Boolean>, Boolean> admission = call.getArgument(5);
|
||||
return admission.apply(() -> call.getArgument(3, BooleanSupplier.class).getAsBoolean());
|
||||
}
|
||||
|
||||
static void allowPublications(ElbV2DataPlane dataPlane) {
|
||||
lenient().doAnswer(ElbV2PublicationTestSupport::applyPublication)
|
||||
.when(dataPlane).publishListener(any(Listener.class), anyString(), any(), any(), any(), any());
|
||||
lenient().doAnswer(call -> call.getArgument(1, BooleanSupplier.class).getAsBoolean())
|
||||
.when(dataPlane).updateListener(any(), any());
|
||||
lenient().doAnswer(call -> call.getArgument(2, BooleanSupplier.class).getAsBoolean())
|
||||
.when(dataPlane).removeListener(anyString(), any(), any());
|
||||
}
|
||||
|
||||
}
|
||||
+417
-1
@@ -2,23 +2,48 @@ package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.TlsProxyServer;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpServerResponse;
|
||||
import io.vertx.core.net.PemKeyCertOptions;
|
||||
import io.vertx.core.net.SSLOptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.IntConsumer;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -124,7 +149,7 @@ class ElbV2ReservedPortTest {
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1");
|
||||
listener.setPort(443);
|
||||
|
||||
assertDoesNotThrow(() -> dataPlane.startListener(listener, "us-west-2", List.of()),
|
||||
assertDoesNotThrow(() -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of()),
|
||||
"the released-port replay re-entered the server map for the key it was computing");
|
||||
verify(vertx, times(1)).createHttpServer(any(HttpServerOptions.class));
|
||||
}
|
||||
@@ -135,4 +160,395 @@ class ElbV2ReservedPortTest {
|
||||
assertFalse(dataPlane.isReservedByFloci(80));
|
||||
assertFalse(dataPlane.isReservedByFloci(8080));
|
||||
}
|
||||
@Test
|
||||
void identicalRestartRetriesAFailedTlsRefresh() {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
when(elbv2.mock()).thenReturn(false);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(services.elbv2()).thenReturn(elbv2);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);
|
||||
HttpServer server = mock(HttpServer.class);
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
when(server.close()).thenReturn(Future.succeededFuture());
|
||||
when(server.updateSSLOptions(any(SSLOptions.class), eq(true)))
|
||||
.thenReturn(Future.failedFuture(new IllegalStateException("controlled TLS refresh failure")),
|
||||
Future.succeededFuture(true));
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(server);
|
||||
String region = "us-west-2";
|
||||
String owner = "arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/lb/1/2";
|
||||
String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/current";
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn(owner);
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTPS");
|
||||
listener.setCertificates(List.of(certificateArn));
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName("tls.example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn())).thenReturn(loadBalancer);
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate old = generator.generateSelfSignedCertificate(
|
||||
"tls.example.test", List.of(), KeyAlgorithm.RSA_2048);
|
||||
CertificateGenerator.GeneratedCertificate replacement = generator.generateSelfSignedCertificate(
|
||||
"tls.example.test", List.of(), KeyAlgorithm.RSA_2048);
|
||||
CertificateMaterial first = new CertificateMaterial(certificateArn, old.certificatePem(), old.privateKeyPem(), null);
|
||||
CertificateMaterial next = new CertificateMaterial(certificateArn,
|
||||
replacement.certificatePem(), replacement.privateKeyPem(), null);
|
||||
when(dataPlane.certificateResolver.publishedMaterial(owner, region, certificateArn)).thenReturn(first, next, next);
|
||||
try {
|
||||
publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());
|
||||
publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());
|
||||
verify(server).updateSSLOptions(any(SSLOptions.class), eq(true));
|
||||
publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());
|
||||
ArgumentCaptor<SSLOptions> options = ArgumentCaptor.forClass(SSLOptions.class);
|
||||
verify(server, times(2)).updateSSLOptions(options.capture(), eq(true));
|
||||
for (SSLOptions attempt : options.getAllValues()) {
|
||||
PemKeyCertOptions material = assertInstanceOf(PemKeyCertOptions.class, attempt.getKeyCertOptions());
|
||||
assertEquals(1, material.getCertValues().size());
|
||||
assertEquals(replacement.certificatePem().stripTrailing() + "\n",
|
||||
material.getCertValues().getFirst().toString());
|
||||
assertEquals(1, material.getKeyValues().size());
|
||||
assertEquals(replacement.privateKeyPem(), material.getKeyValues().getFirst().toString());
|
||||
}
|
||||
} finally {
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void movingSecureListenerRefreshesTheSurvivingOldPort() {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
when(elbv2.mock()).thenReturn(false);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(services.elbv2()).thenReturn(elbv2);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);
|
||||
HttpServer oldServer = mock(HttpServer.class);
|
||||
HttpServer newServer = mock(HttpServer.class);
|
||||
for (HttpServer server : List.of(oldServer, newServer)) {
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
when(server.close()).thenReturn(Future.succeededFuture());
|
||||
}
|
||||
when(oldServer.updateSSLOptions(any(SSLOptions.class), eq(true)))
|
||||
.thenReturn(Future.succeededFuture(true));
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class)))
|
||||
.thenAnswer(invocation -> ((HttpServerOptions) invocation.getArgument(0)).getPort() == 8443
|
||||
? oldServer : newServer);
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
Listener survivor = new Listener();
|
||||
Listener moved = new Listener();
|
||||
CertificateGenerator.GeneratedCertificate survivorCertificate = null;
|
||||
for (Listener listener : List.of(survivor, moved)) {
|
||||
String name = listener == survivor ? "survivor" : "moved";
|
||||
String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/" + name;
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTPS");
|
||||
listener.setCertificates(List.of(certificateArn));
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName(name + ".example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))
|
||||
.thenReturn(loadBalancer);
|
||||
CertificateGenerator.GeneratedCertificate certificate = generator.generateSelfSignedCertificate(
|
||||
name + ".example.test", List.of(), KeyAlgorithm.RSA_2048);
|
||||
if (listener == survivor) {
|
||||
survivorCertificate = certificate;
|
||||
}
|
||||
when(dataPlane.certificateResolver.publishedMaterial(listener.getListenerArn(), "us-west-2", certificateArn))
|
||||
.thenReturn(new CertificateMaterial(certificateArn,
|
||||
certificate.certificatePem(), certificate.privateKeyPem(), null));
|
||||
}
|
||||
try {
|
||||
publishRuntime(dataPlane, survivor, "us-west-2", survivor.getPort(), List.of());
|
||||
publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of());
|
||||
ArgumentCaptor<SSLOptions> initial = ArgumentCaptor.forClass(SSLOptions.class);
|
||||
verify(oldServer).updateSSLOptions(initial.capture(), eq(true));
|
||||
assertEquals(2, assertInstanceOf(PemKeyCertOptions.class,
|
||||
initial.getValue().getKeyCertOptions()).getCertValues().size());
|
||||
|
||||
moved.setPort(9443);
|
||||
publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of());
|
||||
|
||||
ArgumentCaptor<SSLOptions> refreshed = ArgumentCaptor.forClass(SSLOptions.class);
|
||||
verify(oldServer, times(2)).updateSSLOptions(refreshed.capture(), eq(true));
|
||||
PemKeyCertOptions retained = assertInstanceOf(PemKeyCertOptions.class,
|
||||
refreshed.getAllValues().getLast().getKeyCertOptions());
|
||||
assertEquals(List.of(survivorCertificate.certificatePem().stripTrailing() + "\n"),
|
||||
retained.getCertValues().stream().map(value -> value.toString()).toList());
|
||||
assertEquals(List.of(survivorCertificate.privateKeyPem()),
|
||||
retained.getKeyValues().stream().map(value -> value.toString()).toList());
|
||||
verify(newServer).listen();
|
||||
verify(oldServer, never()).close();
|
||||
} finally {
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastListenerCloseCompletesBeforeItsPortIsReused() {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(elb.mock()).thenReturn(false);
|
||||
when(services.elbv2()).thenReturn(elb);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
HttpServer oldServer = mock(HttpServer.class);
|
||||
HttpServer replacement = mock(HttpServer.class);
|
||||
Promise<Void> close = Promise.promise();
|
||||
when(oldServer.close()).thenReturn(close.future());
|
||||
when(replacement.close()).thenReturn(Future.succeededFuture());
|
||||
for (HttpServer server : List.of(oldServer, replacement)) {
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
}
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(oldServer, replacement);
|
||||
Listener first = new Listener();
|
||||
Listener second = new Listener();
|
||||
for (Listener listener : List.of(first, second)) {
|
||||
String name = listener == first ? "first" : "second";
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTP");
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName(name + ".example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))
|
||||
.thenReturn(loadBalancer);
|
||||
}
|
||||
try {
|
||||
publishRuntime(dataPlane, first, "us-west-2", first.getPort(), List.of());
|
||||
verify(oldServer).listen();
|
||||
removeRuntime(dataPlane, first.getListenerArn(), first.getPort());
|
||||
verify(oldServer).close();
|
||||
publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of());
|
||||
verify(replacement, never()).listen();
|
||||
close.complete();
|
||||
verify(replacement).listen();
|
||||
removeRuntime(dataPlane, second.getListenerArn(), second.getPort());
|
||||
verify(replacement).close();
|
||||
} finally {
|
||||
close.tryComplete();
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingOldPortClosePreservesAMovedListenerAndLaterPortReuse() {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(elb.mock()).thenReturn(false);
|
||||
when(services.elbv2()).thenReturn(elb);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
HttpServer oldServer = mock(HttpServer.class);
|
||||
HttpServer movedServer = mock(HttpServer.class);
|
||||
HttpServer reusedServer = mock(HttpServer.class);
|
||||
Promise<Void> oldClose = Promise.promise();
|
||||
for (HttpServer server : List.of(oldServer, movedServer, reusedServer)) {
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
when(server.close()).thenReturn(Future.succeededFuture());
|
||||
}
|
||||
when(oldServer.close()).thenReturn(oldClose.future());
|
||||
when(dataPlane.vertx.createHttpServer(argThat(options -> options != null && options.getPort() == 8443)))
|
||||
.thenReturn(oldServer, reusedServer);
|
||||
when(dataPlane.vertx.createHttpServer(argThat(options -> options != null && options.getPort() == 9443))).thenReturn(movedServer);
|
||||
Listener old = new Listener();
|
||||
Listener moved = new Listener();
|
||||
Listener reused = new Listener();
|
||||
for (Listener listener : List.of(old, moved, reused)) {
|
||||
String name = listener == old ? "old" : listener == moved ? "moved" : "reused";
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTP");
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName(name + ".example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))
|
||||
.thenReturn(loadBalancer);
|
||||
}
|
||||
try {
|
||||
publishRuntime(dataPlane, old, "us-west-2", old.getPort(), List.of(fixedRule("old")));
|
||||
assertFixedResponse(oldServer, "old.example.test", "old");
|
||||
removeRuntime(dataPlane, old.getListenerArn(), old.getPort());
|
||||
verify(oldServer).close();
|
||||
publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of(fixedRule("pending")));
|
||||
verify(reusedServer, never()).listen();
|
||||
moved.setPort(9443);
|
||||
publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of(fixedRule("moved")));
|
||||
verify(movedServer).listen();
|
||||
oldClose.complete();
|
||||
verify(reusedServer, never()).listen();
|
||||
verify(movedServer, never()).close();
|
||||
assertFixedResponse(movedServer, "moved.example.test", "moved");
|
||||
publishRuntime(dataPlane, reused, "us-west-2", reused.getPort(), List.of(fixedRule("reused")));
|
||||
verify(reusedServer).listen();
|
||||
assertFixedResponse(reusedServer, "reused.example.test", "reused");
|
||||
removeRuntime(dataPlane, reused.getListenerArn(), reused.getPort());
|
||||
verify(reusedServer).close();
|
||||
verify(movedServer, never()).close();
|
||||
removeRuntime(dataPlane, moved.getListenerArn(), moved.getPort());
|
||||
verify(movedServer).close();
|
||||
} finally {
|
||||
oldClose.tryComplete();
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"factory", "handler", "listen", "failed-future"})
|
||||
void identicalStartRecoversFromServerAcquisitionFailure(String stage) {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(elb.mock()).thenReturn(false);
|
||||
when(services.elbv2()).thenReturn(elb);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
HttpServer failed = mock(HttpServer.class);
|
||||
HttpServer replacement = mock(HttpServer.class);
|
||||
for (HttpServer server : List.of(failed, replacement)) {
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
when(server.close()).thenReturn(Future.succeededFuture());
|
||||
}
|
||||
IllegalStateException failure = new IllegalStateException("controlled " + stage + " failure");
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(failed, replacement);
|
||||
switch (stage) {
|
||||
case "factory" -> when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class)))
|
||||
.thenThrow(failure).thenReturn(replacement);
|
||||
case "handler" -> when(failed.requestHandler(any())).thenThrow(failure);
|
||||
case "listen" -> when(failed.listen()).thenThrow(failure);
|
||||
case "failed-future" -> when(failed.listen()).thenReturn(Future.failedFuture(failure));
|
||||
default -> throw new IllegalArgumentException(stage);
|
||||
}
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/retry/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/retry/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTP");
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName("retry.example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))
|
||||
.thenReturn(loadBalancer);
|
||||
try {
|
||||
if ("failed-future".equals(stage)) {
|
||||
assertDoesNotThrow(() -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered"))));
|
||||
} else {
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered")))));
|
||||
}
|
||||
if (!"factory".equals(stage)) {
|
||||
verify(failed).close();
|
||||
}
|
||||
publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered")));
|
||||
verify(replacement).listen();
|
||||
assertFixedResponse(replacement, "retry.example.test", "recovered");
|
||||
removeRuntime(dataPlane, listener.getListenerArn(), listener.getPort());
|
||||
verify(replacement).close();
|
||||
verify(dataPlane.vertx, times(2)).createHttpServer(any(HttpServerOptions.class));
|
||||
} finally {
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void obsoleteListenFailureCannotRemoveReplacement(boolean deferClose) {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(elb.mock()).thenReturn(false);
|
||||
when(services.elbv2()).thenReturn(elb);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
HttpServer oldServer = mock(HttpServer.class);
|
||||
HttpServer replacement = mock(HttpServer.class);
|
||||
Promise<HttpServer> oldListen = Promise.promise();
|
||||
Promise<Void> oldClose = Promise.promise();
|
||||
when(oldServer.requestHandler(any())).thenReturn(oldServer);
|
||||
when(oldServer.listen()).thenReturn(oldListen.future());
|
||||
when(oldServer.close()).thenReturn(deferClose ? oldClose.future() : Future.succeededFuture());
|
||||
when(replacement.requestHandler(any())).thenReturn(replacement);
|
||||
when(replacement.listen()).thenReturn(Future.succeededFuture(replacement));
|
||||
when(replacement.close()).thenReturn(Future.succeededFuture());
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(oldServer, replacement);
|
||||
Listener first = new Listener();
|
||||
Listener second = new Listener();
|
||||
for (Listener listener : List.of(first, second)) {
|
||||
String name = listener == first ? "old" : "replacement";
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTP");
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName(name + ".example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))
|
||||
.thenReturn(loadBalancer);
|
||||
}
|
||||
try {
|
||||
publishRuntime(dataPlane, first, "us-west-2", first.getPort(), List.of());
|
||||
verify(oldServer).listen();
|
||||
removeRuntime(dataPlane, first.getListenerArn(), first.getPort());
|
||||
verify(oldServer).close();
|
||||
publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of(fixedRule("replacement")));
|
||||
if (deferClose) {
|
||||
verify(replacement, never()).listen();
|
||||
oldClose.complete();
|
||||
}
|
||||
verify(replacement).listen();
|
||||
oldListen.fail(new IllegalStateException("obsolete listen failure"));
|
||||
verify(replacement, never()).close();
|
||||
assertFixedResponse(replacement, "replacement.example.test", "replacement");
|
||||
publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of(fixedRule("replacement")));
|
||||
verify(dataPlane.vertx, times(2)).createHttpServer(any(HttpServerOptions.class));
|
||||
removeRuntime(dataPlane, second.getListenerArn(), second.getPort());
|
||||
verify(replacement).close();
|
||||
} finally {
|
||||
oldClose.tryComplete();
|
||||
oldListen.tryFail(new IllegalStateException("test cleanup"));
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static Rule fixedRule(String body) {
|
||||
Action action = new Action();
|
||||
action.setType("fixed-response");
|
||||
action.setFixedResponseStatusCode("200");
|
||||
action.setFixedResponseMessageBody(body);
|
||||
Rule rule = new Rule();
|
||||
rule.setDefault(true);
|
||||
rule.setActions(List.of(action));
|
||||
return rule;
|
||||
}
|
||||
|
||||
private static void assertFixedResponse(HttpServer server, String host, String body) {
|
||||
ArgumentCaptor<Handler<HttpServerRequest>> handler = ArgumentCaptor.captor();
|
||||
verify(server).requestHandler(handler.capture());
|
||||
HttpServerRequest request = mock(HttpServerRequest.class);
|
||||
HttpServerResponse response = mock(HttpServerResponse.class);
|
||||
when(request.host()).thenReturn(host);
|
||||
when(request.response()).thenReturn(response);
|
||||
when(response.setStatusCode(anyInt())).thenReturn(response);
|
||||
handler.getValue().handle(request);
|
||||
verify(response).setStatusCode(200);
|
||||
verify(response).end(body);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
@@ -38,12 +37,14 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.allowPublications;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -53,10 +54,10 @@ import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -88,6 +89,7 @@ class ElbV2ServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new ElbV2Service();
|
||||
allowPublications(dataPlane);
|
||||
service.dataPlane = dataPlane;
|
||||
service.healthChecker = healthChecker;
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
@@ -153,6 +155,37 @@ class ElbV2ServiceTest {
|
||||
assertEquals(List.of(first), service.describeListenerCertificates(REGION, listenerArn));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void missingHttpsDefaultIsRefusedEvenWithoutACertificateResolver(List<String> certificates) {
|
||||
String lbArn = service.createLoadBalancer(REGION, "missing-create", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
clearInvocations(dataPlane);
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> service.createListener(
|
||||
REGION, lbArn, "HTTPS", 9443, null, certificates, List.of(), List.of(), Map.of()));
|
||||
assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());
|
||||
assertTrue(service.describeListeners(REGION, lbArn, List.of()).isEmpty());
|
||||
assertTrue(service.describeRules(REGION, null, List.of()).isEmpty());
|
||||
verifyNoInteractions(dataPlane);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void missingEffectiveDefaultCannotChangeAnHttpListener(List<String> certificates) {
|
||||
String lbArn = service.createLoadBalancer(REGION, "missing-modify", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
Listener listener = service.createListener(REGION, lbArn, "HTTP", 8080, null,
|
||||
List.of(), List.of(), List.of(), Map.of());
|
||||
clearInvocations(dataPlane);
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> service.modifyListener(
|
||||
REGION, listener.getListenerArn(), "HTTPS", 9443, "unchanged", certificates, null, null));
|
||||
assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());
|
||||
assertEquals("HTTP", listener.getProtocol());
|
||||
assertEquals(8080, listener.getPort());
|
||||
assertTrue(listener.getCertificates().isEmpty());
|
||||
verifyNoInteractions(dataPlane);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removalCannotDeleteADefaultPublishedByConcurrentModification() throws Exception {
|
||||
String lbArn = service.createLoadBalancer(REGION, "default-replacement-lb", "internal", "application", "ipv4",
|
||||
@@ -184,7 +217,9 @@ class ElbV2ServiceTest {
|
||||
service.modifyListener(REGION, listener, null, null, null, List.of(additional), null, null);
|
||||
assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener));
|
||||
releaseRemoval.countDown();
|
||||
removal.get(5, TimeUnit.SECONDS);
|
||||
ExecutionException refused = assertThrows(ExecutionException.class,
|
||||
() -> removal.get(5, TimeUnit.SECONDS));
|
||||
assertEquals("OperationNotPermitted", ((AwsException) refused.getCause()).getErrorCode());
|
||||
assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener));
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> service.removeListenerCertificates(REGION, listener, List.of(additional)));
|
||||
@@ -208,6 +243,114 @@ class ElbV2ServiceTest {
|
||||
assertEquals(List.of(), service.describeListenerCertificates(REGION, listenerArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerProtocolAndCertificateRestartsListener() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "tls-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTP", 9443, null, List.of(),
|
||||
List.of(), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
|
||||
service.modifyListener(
|
||||
REGION, listenerArn, "HTTPS", null, "ELBSecurityPolicy-TLS13-1-2-2021-06",
|
||||
List.of("arn:aws:acm:us-west-2:000000000000:certificate/first"), null, null);
|
||||
|
||||
ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();
|
||||
verify(dataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals("HTTPS", listenerCaptor.getValue().getProtocol());
|
||||
assertEquals(List.of("arn:aws:acm:us-west-2:000000000000:certificate/first"),
|
||||
listenerCaptor.getValue().getCertificates());
|
||||
verify(dataPlane, never()).recompileRules(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void identicalExplicitTlsModificationReappliesTheDataPlane() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "tls-retry-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String first = "arn:aws:acm:us-west-2:000000000000:certificate/first";
|
||||
String replacement = "arn:aws:acm:us-west-2:000000000000:certificate/replacement";
|
||||
String listenerArn = service.createListener(REGION, lbArn, "HTTPS", 9443, null,
|
||||
List.of(first), List.of(), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
|
||||
service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null);
|
||||
assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn));
|
||||
verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null);
|
||||
|
||||
verify(dataPlane, times(2)).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn));
|
||||
verify(dataPlane, never()).recompileRules(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listenerCertificateLifecycleRefreshesDataPlane() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "certificate-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String firstCertificate = "arn:aws:acm:us-west-2:000000000000:certificate/first";
|
||||
String secondCertificate = "arn:aws:acm:us-west-2:000000000000:certificate/second";
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTPS", 9443, null, List.of(firstCertificate),
|
||||
List.of(), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
|
||||
service.addListenerCertificates(REGION, listenerArn, List.of(secondCertificate));
|
||||
service.removeListenerCertificates(REGION, listenerArn, List.of(secondCertificate));
|
||||
|
||||
verify(dataPlane, times(2))
|
||||
.publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(List.of(firstCertificate),
|
||||
service.describeListenerCertificates(REGION, listenerArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultRemovalWithAdditionalCertificateDoesNotRefreshAndCanRemoveAdditional() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "default-certificate-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String first = "arn:aws:acm:us-west-2:000000000000:certificate/default";
|
||||
String additional = "arn:aws:acm:us-west-2:000000000000:certificate/additional";
|
||||
String listener = service.createListener(REGION, lbArn, "HTTPS", 9443, null,
|
||||
List.of(first, additional), List.of(), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> service.removeListenerCertificates(REGION, listener, List.of(first)));
|
||||
assertEquals("OperationNotPermitted", rejected.getErrorCode());
|
||||
assertEquals(List.of(first, additional), service.describeListenerCertificates(REGION, listener));
|
||||
verifyNoInteractions(dataPlane);
|
||||
service.removeListenerCertificates(REGION, listener, List.of(additional));
|
||||
assertEquals(List.of(first), service.describeListenerCertificates(REGION, listener));
|
||||
verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initializeStorageRestoresHttpsListenerCertificate() {
|
||||
SharedStorageFactory storageFactory = new SharedStorageFactory();
|
||||
ElbV2Service first = serviceWithStorage(
|
||||
storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));
|
||||
String lbArn = first.createLoadBalancer(
|
||||
REGION, "persisted-https-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/persisted";
|
||||
String listenerArn = first.createListener(
|
||||
REGION, lbArn, "HTTPS", 9443, "ELBSecurityPolicy-TLS13-1-2-2021-06",
|
||||
List.of(certificateArn), List.of(), List.of(), Map.of()).getListenerArn();
|
||||
|
||||
ElbV2DataPlane reloadedDataPlane = mock(ElbV2DataPlane.class);
|
||||
ElbV2Service reloaded = serviceWithStorage(storageFactory, reloadedDataPlane, mock(ElbV2HealthChecker.class));
|
||||
reloaded.restorePersistedRuntime();
|
||||
|
||||
ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();
|
||||
verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());
|
||||
assertEquals("HTTPS", listenerCaptor.getValue().getProtocol());
|
||||
assertEquals(List.of(certificateArn), listenerCaptor.getValue().getCertificates());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerDefaultActionsRecompilesRulesWithoutRestartingListener() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
@@ -224,13 +367,12 @@ class ElbV2ServiceTest {
|
||||
REGION, listenerArn, null, null, null, null,
|
||||
List.of(forwardAction(newTgArn)), null);
|
||||
|
||||
ArgumentCaptor<List<Rule>> rulesCaptor = ArgumentCaptor.captor();
|
||||
ArgumentCaptor<Supplier<List<Rule>>> rulesCaptor = ArgumentCaptor.captor();
|
||||
verify(dataPlane).recompileRules(eq(listenerArn), rulesCaptor.capture());
|
||||
verify(dataPlane, never()).stopListener(anyString());
|
||||
verify(dataPlane, never()).startListener(any(Listener.class), anyString(), anyList());
|
||||
verify(dataPlane, never()).restartListener(any(Listener.class), anyString(), anyList());
|
||||
verify(dataPlane, never()).removeListener(anyString(), any(), any());
|
||||
verify(dataPlane, never()).publishListener(any(Listener.class), anyString(), any(), any(), any(), any());
|
||||
|
||||
Rule defaultRule = rulesCaptor.getValue().stream()
|
||||
Rule defaultRule = rulesCaptor.getValue().get().stream()
|
||||
.filter(Rule::isDefault)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
@@ -255,69 +397,8 @@ class ElbV2ServiceTest {
|
||||
|
||||
service.modifyListener(REGION, listenerArn, null, 10000, null, null, null, null);
|
||||
|
||||
verify(dataPlane).restartListener(any(Listener.class), eq(REGION), anyList());
|
||||
verify(dataPlane, never()).stopListener(anyString());
|
||||
verify(dataPlane, never()).startListener(any(Listener.class), anyString(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerRefusedUnderTheCertificateGuardLeavesTheListenerWhereItWas() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "sample-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String tgArn = createTargetGroup("sample-tg");
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTPS", 443, "ELBSecurityPolicy-2016-08", List.of(HELD_CERTIFICATE),
|
||||
List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
service.certificateResolver = deletedOnTheSecondLook();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(
|
||||
REGION, listenerArn, "TLS", 8443, "ELBSecurityPolicy-TLS13-1-2-2021-06",
|
||||
List.of(OTHER_CERTIFICATE), null, null));
|
||||
|
||||
assertEquals("CertificateNotFound", e.getErrorCode());
|
||||
Listener listener = service.describeListeners(REGION, lbArn, List.of(listenerArn)).getFirst();
|
||||
assertEquals(Integer.valueOf(443), listener.getPort());
|
||||
assertEquals("HTTPS", listener.getProtocol());
|
||||
assertEquals("ELBSecurityPolicy-2016-08", listener.getSslPolicy());
|
||||
assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates());
|
||||
verify(dataPlane, never()).restartListener(any(Listener.class), anyString(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyListenerProtocolAloneTakesTheGuardForTheCertificatesItPutsIntoService() {
|
||||
String lbArn = service.createLoadBalancer(
|
||||
REGION, "sample-lb", "internal", "application", "ipv4",
|
||||
ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();
|
||||
String tgArn = createTargetGroup("sample-tg");
|
||||
String listenerArn = service.createListener(
|
||||
REGION, lbArn, "HTTP", 80, null, List.of(HELD_CERTIFICATE),
|
||||
List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();
|
||||
clearInvocations(dataPlane);
|
||||
service.certificateResolver = deletedOnTheSecondLook();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(
|
||||
REGION, listenerArn, "HTTPS", null, null, null, null, null));
|
||||
|
||||
assertEquals("CertificateNotFound", e.getErrorCode());
|
||||
assertEquals("HTTP", service.describeListeners(REGION, lbArn, List.of(listenerArn))
|
||||
.getFirst().getProtocol());
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolver that finds the certificate once and not again, which is what a
|
||||
* {@code DeleteServerCertificate} landing between the check outside the guard and the one
|
||||
* under it looks like from inside the call.
|
||||
*/
|
||||
private static CertificateReferenceResolver deletedOnTheSecondLook() {
|
||||
CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);
|
||||
when(resolver.exists(anyString(), anyString())).thenReturn(true, false);
|
||||
doAnswer(invocation -> {
|
||||
invocation.getArgument(1, Runnable.class).run();
|
||||
return null;
|
||||
}).when(resolver).runWhileHeld(any(), any());
|
||||
return resolver;
|
||||
verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
verify(dataPlane, never()).removeListener(anyString(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -465,7 +546,7 @@ class ElbV2ServiceTest {
|
||||
verify(reloadedHealthChecker).addTargets(eq(tgArn), targetsCaptor.capture(), any(TargetGroup.class));
|
||||
assertEquals("i-1234567890abcdef0", targetsCaptor.getValue().getFirst().getId());
|
||||
assertEquals(8080, targetsCaptor.getValue().getFirst().getPort());
|
||||
verify(reloadedDataPlane).startListener(any(Listener.class), eq(REGION), anyList());
|
||||
verify(reloadedDataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());
|
||||
|
||||
reloaded.removeTags(List.of(rule.getRuleArn()), List.of("env"));
|
||||
ElbV2Service updatedReload = serviceWithStorage(storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));
|
||||
@@ -502,7 +583,7 @@ class ElbV2ServiceTest {
|
||||
reloaded.restorePersistedRuntime();
|
||||
|
||||
ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();
|
||||
verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList());
|
||||
verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());
|
||||
verify(reloadedHealthChecker).startMonitoring(any(TargetGroup.class));
|
||||
}
|
||||
@@ -523,7 +604,7 @@ class ElbV2ServiceTest {
|
||||
reloaded.restorePersistedRuntime();
|
||||
|
||||
ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();
|
||||
verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList());
|
||||
verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());
|
||||
assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());
|
||||
}
|
||||
|
||||
@@ -621,7 +702,11 @@ class ElbV2ServiceTest {
|
||||
return condition;
|
||||
}
|
||||
|
||||
private static ElbV2Service serviceWithStorage(StorageFactory storageFactory,
|
||||
static StorageFactory sharedStorageFactory() {
|
||||
return new SharedStorageFactory();
|
||||
}
|
||||
|
||||
static ElbV2Service serviceWithStorage(StorageFactory storageFactory,
|
||||
ElbV2DataPlane dataPlane,
|
||||
ElbV2HealthChecker healthChecker) {
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
@@ -629,11 +714,12 @@ class ElbV2ServiceTest {
|
||||
return serviceWithStorage(storageFactory, dataPlane, healthChecker, ec2Service);
|
||||
}
|
||||
|
||||
private static ElbV2Service serviceWithStorage(StorageFactory storageFactory,
|
||||
static ElbV2Service serviceWithStorage(StorageFactory storageFactory,
|
||||
ElbV2DataPlane dataPlane,
|
||||
ElbV2HealthChecker healthChecker,
|
||||
Ec2Service ec2Service) {
|
||||
ElbV2Service service = new ElbV2Service();
|
||||
allowPublications(dataPlane);
|
||||
service.dataPlane = dataPlane;
|
||||
service.healthChecker = healthChecker;
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.TlsProxyServer;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
|
||||
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.github.hectorvent.floci.testing.InlineMocks;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpServerResponse;
|
||||
import io.vertx.core.net.PemKeyCertOptions;
|
||||
import io.vertx.core.net.SSLOptions;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ElbV2TlsCohortTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void concurrentMaterialPublicationKeepsSharedAliasesAmbiguous(boolean pauseOptionsCapture) throws Exception {
|
||||
String region = "us-west-2";
|
||||
String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/shared";
|
||||
String alias = "replacement.example.test";
|
||||
ElbV2DataPlane dataPlane = new ElbV2DataPlane();
|
||||
dataPlane.config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
when(dataPlane.config.services()).thenReturn(services);
|
||||
when(services.elbv2()).thenReturn(elb);
|
||||
when(elb.mock()).thenReturn(false);
|
||||
when(dataPlane.config.port()).thenReturn(4566);
|
||||
dataPlane.tlsProxyServer = mock(TlsProxyServer.class);
|
||||
when(dataPlane.tlsProxyServer.reservesPort(anyInt())).thenReturn(false);
|
||||
dataPlane.vertx = mock(Vertx.class);
|
||||
dataPlane.elbV2Service = mock(ElbV2Service.class);
|
||||
dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);
|
||||
HttpServer server = mock(HttpServer.class);
|
||||
HttpServer otherServer = mock(HttpServer.class);
|
||||
when(otherServer.requestHandler(any())).thenReturn(otherServer);
|
||||
when(otherServer.listen()).thenReturn(Future.succeededFuture(otherServer));
|
||||
when(otherServer.close()).thenReturn(Future.succeededFuture());
|
||||
when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call ->
|
||||
((HttpServerOptions) call.getArgument(0)).getPort() == 9443 ? otherServer : server);
|
||||
when(server.requestHandler(any())).thenReturn(server);
|
||||
when(server.listen()).thenReturn(Future.succeededFuture(server));
|
||||
when(server.close()).thenReturn(Future.succeededFuture());
|
||||
when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true));
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
CertificateMaterial seed = material(generator, certificateArn, "seed.example.test");
|
||||
CertificateMaterial first = InlineMocks.inlineSpy(material(generator, certificateArn, "old.example.test"));
|
||||
CertificateMaterial replacement = material(generator, certificateArn, alias);
|
||||
Listener left = listener("left", certificateArn);
|
||||
Listener right = listener("right", certificateArn);
|
||||
Listener unrelated = listener("unrelated", certificateArn);
|
||||
unrelated.setPort(9443);
|
||||
AtomicReference<CertificateMaterial> leftMaterial = new AtomicReference<>(seed);
|
||||
AtomicReference<CertificateMaterial> rightMaterial = new AtomicReference<>(seed);
|
||||
when(dataPlane.certificateResolver.publishedMaterial(left.getListenerArn(), region, certificateArn))
|
||||
.thenAnswer(ignored -> leftMaterial.get());
|
||||
when(dataPlane.certificateResolver.publishedMaterial(right.getListenerArn(), region, certificateArn))
|
||||
.thenAnswer(ignored -> rightMaterial.get());
|
||||
when(dataPlane.certificateResolver.publishedMaterial(unrelated.getListenerArn(), region, certificateArn))
|
||||
.thenReturn(seed);
|
||||
for (Listener listener : List.of(left, right, unrelated)) {
|
||||
LoadBalancer loadBalancer = new LoadBalancer();
|
||||
loadBalancer.setDnsName(listener == left ? "left.example.test" : "right.example.test");
|
||||
when(dataPlane.elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn())).thenReturn(loadBalancer);
|
||||
}
|
||||
CountDownLatch insideSecondPeer = new CountDownLatch(1);
|
||||
CountDownLatch releaseFirst = new CountDownLatch(1);
|
||||
CountDownLatch secondResolved = new CountDownLatch(1);
|
||||
AtomicReference<Thread> firstWorker = new AtomicReference<>();
|
||||
AtomicInteger reads = new AtomicInteger();
|
||||
AtomicInteger keyReads = new AtomicInteger();
|
||||
AtomicBoolean paused = new AtomicBoolean();
|
||||
// Pair validation reads key/body once before the coordinated cohort/SSL-options reads.
|
||||
if (pauseOptionsCapture) {
|
||||
doAnswer(invocation -> {
|
||||
if (Thread.currentThread() == firstWorker.get() && keyReads.incrementAndGet() == 2
|
||||
&& paused.compareAndSet(false, true)) {
|
||||
insideSecondPeer.countDown();
|
||||
assertTrue(releaseFirst.await(10, TimeUnit.SECONDS), "options capture was not released");
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(first).privateKey();
|
||||
} else {
|
||||
doAnswer(invocation -> {
|
||||
if (Thread.currentThread() == firstWorker.get() && reads.incrementAndGet() == 4
|
||||
&& paused.compareAndSet(false, true)) {
|
||||
insideSecondPeer.countDown();
|
||||
assertTrue(releaseFirst.await(10, TimeUnit.SECONDS), "first publisher was not released");
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
}).when(first).certificateBody();
|
||||
}
|
||||
ExecutorService workers = Executors.newFixedThreadPool(3);
|
||||
try {
|
||||
publishRuntime(dataPlane, left, region, left.getPort(), List.of(fixedRule("left")));
|
||||
publishRuntime(dataPlane, right, region, right.getPort(), List.of(fixedRule("right")));
|
||||
ArgumentCaptor<Handler<HttpServerRequest>> handler = ArgumentCaptor.captor();
|
||||
verify(server).requestHandler(handler.capture());
|
||||
leftMaterial.set(first);
|
||||
rightMaterial.set(replacement);
|
||||
when(dataPlane.certificateResolver.publishedMaterial(right.getListenerArn(), region, certificateArn))
|
||||
.thenAnswer(ignored -> {
|
||||
secondResolved.countDown();
|
||||
return rightMaterial.get();
|
||||
});
|
||||
// Qualify the JDK Future to distinguish it from Vert.x Future.
|
||||
java.util.concurrent.Future<?> firstPublication = workers.submit(() -> {
|
||||
firstWorker.set(Thread.currentThread());
|
||||
publishRuntime(dataPlane, left, region, left.getPort(), List.of(fixedRule("left")));
|
||||
});
|
||||
assertTrue(insideSecondPeer.await(5, TimeUnit.SECONDS), "publisher did not reach the controlled cohort boundary");
|
||||
java.util.concurrent.Future<?> secondPublication = workers.submit(() ->
|
||||
publishRuntime(dataPlane, right, region, right.getPort(), List.of(fixedRule("right"))));
|
||||
assertTrue(secondResolved.await(5, TimeUnit.SECONDS), "second publisher did not resolve its material");
|
||||
workers.submit(() -> publishRuntime(dataPlane, unrelated, region, unrelated.getPort(), List.of(fixedRule("unrelated"))))
|
||||
.get(1, TimeUnit.SECONDS);
|
||||
verify(otherServer).listen();
|
||||
try {
|
||||
secondPublication.get(3, TimeUnit.SECONDS);
|
||||
} catch (TimeoutException expected) {
|
||||
// A correct port-local coordinator may hold this publisher until the first is released.
|
||||
} finally {
|
||||
releaseFirst.countDown();
|
||||
}
|
||||
firstPublication.get(5, TimeUnit.SECONDS);
|
||||
secondPublication.get(5, TimeUnit.SECONDS);
|
||||
HttpServerRequest request = mock(HttpServerRequest.class);
|
||||
HttpServerResponse response = mock(HttpServerResponse.class);
|
||||
when(request.host()).thenReturn(alias);
|
||||
when(request.response()).thenReturn(response);
|
||||
when(response.setStatusCode(anyInt())).thenReturn(response);
|
||||
handler.getValue().handle(request);
|
||||
verify(response).setStatusCode(502);
|
||||
verify(response).end("No listener for host");
|
||||
ArgumentCaptor<SSLOptions> updates = ArgumentCaptor.forClass(SSLOptions.class);
|
||||
verify(server, atLeastOnce()).updateSSLOptions(updates.capture(), eq(true));
|
||||
List<SSLOptions> orderedUpdates = updates.getAllValues();
|
||||
PemKeyCertOptions preceding = assertInstanceOf(PemKeyCertOptions.class,
|
||||
orderedUpdates.get(orderedUpdates.size() - 2).getKeyCertOptions());
|
||||
assertEquals(List.of(first.privateKey()),
|
||||
preceding.getKeyValues().stream().map(value -> value.toString()).toList());
|
||||
PemKeyCertOptions finalOptions = assertInstanceOf(PemKeyCertOptions.class,
|
||||
orderedUpdates.getLast().getKeyCertOptions());
|
||||
assertEquals(List.of(replacement.privateKey()),
|
||||
finalOptions.getKeyValues().stream().map(value -> value.toString()).toList());
|
||||
assertEquals(List.of(replacement.certificateBody().stripTrailing() + "\n"),
|
||||
finalOptions.getCertValues().stream().map(value -> value.toString()).toList());
|
||||
removeRuntime(dataPlane, right.getListenerArn(), right.getPort());
|
||||
HttpServerRequest survivingRequest = mock(HttpServerRequest.class);
|
||||
HttpServerResponse survivingResponse = mock(HttpServerResponse.class);
|
||||
when(survivingRequest.host()).thenReturn(alias);
|
||||
when(survivingRequest.response()).thenReturn(survivingResponse);
|
||||
when(survivingResponse.setStatusCode(anyInt())).thenReturn(survivingResponse);
|
||||
handler.getValue().handle(survivingRequest);
|
||||
verify(survivingResponse).setStatusCode(200);
|
||||
verify(survivingResponse).end("left");
|
||||
} finally {
|
||||
releaseFirst.countDown();
|
||||
workers.shutdownNow();
|
||||
try {
|
||||
assertTrue(workers.awaitTermination(Duration.ofSeconds(5).toMillis(), TimeUnit.MILLISECONDS));
|
||||
} finally {
|
||||
dataPlane.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CertificateMaterial material(CertificateGenerator generator, String arn, String host) {
|
||||
CertificateGenerator.GeneratedCertificate pair = generator.generateSelfSignedCertificate(
|
||||
host, List.of(), KeyAlgorithm.RSA_2048);
|
||||
return new CertificateMaterial(arn, pair.certificatePem(), pair.privateKeyPem(), null);
|
||||
}
|
||||
|
||||
private static Listener listener(String name, String certificateArn) {
|
||||
Listener listener = new Listener();
|
||||
listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");
|
||||
listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");
|
||||
listener.setPort(8443);
|
||||
listener.setProtocol("HTTPS");
|
||||
listener.setCertificates(List.of(certificateArn));
|
||||
return listener;
|
||||
}
|
||||
|
||||
private static Rule fixedRule(String body) {
|
||||
Action action = new Action();
|
||||
action.setType("fixed-response");
|
||||
action.setFixedResponseStatusCode("200");
|
||||
action.setFixedResponseMessageBody(body);
|
||||
Rule rule = new Rule();
|
||||
rule.setDefault(true);
|
||||
rule.setActions(List.of(action));
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user