mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(autoscaling): preserve launch configuration user data (#5600)
* fix(autoscaling): preserve launch configuration user data * fix(autoscaling): reject unusable launch configuration data
This commit is contained in:
1 parent
86b19047f3
commit
ddc0e0257b
10 files changed
+604
-19
No files matched your search
+81
@@ -0,0 +1,81 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
|
||||
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
|
||||
import software.amazon.awssdk.services.autoscaling.model.LaunchConfiguration;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DisplayName("Auto Scaling launch-configuration user data")
|
||||
class AutoScalingConfigurationUserDataTest {
|
||||
static Stream<Arguments> userData() {
|
||||
return Stream.of(false, true).flatMap(fromInstance -> Stream.of(null, "", "YQ", "/w",
|
||||
"H4sIAAAAAAAC/1NW1E/KzNMvzuBKTc7IV8hIzcnJ5wIAedQ/FxUAAAA=")
|
||||
.map(encoded -> Arguments.of(fromInstance, encoded)));
|
||||
}
|
||||
|
||||
static Stream<String> rejectedData() {
|
||||
return Stream.of("not base64!", "H4sI", Base64.getEncoder().encodeToString(new byte[16385]));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("rejectedData")
|
||||
void rejectedDataLeavesConfigurationNameReusable(String encoded) {
|
||||
String name = TestFixtures.uniqueName("asg-invalid-data");
|
||||
try (AutoScalingClient asg = TestFixtures.autoScalingClient()) {
|
||||
AutoScalingException error = assertThrows(AutoScalingException.class, () ->
|
||||
asg.createLaunchConfiguration(r -> r.launchConfigurationName(name)
|
||||
.imageId("ami-amazonlinux2023").instanceType("t3.micro").userData(encoded)));
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue");
|
||||
assertThat(asg.describeLaunchConfigurations(r -> r.launchConfigurationNames(name))
|
||||
.launchConfigurations()).isEmpty();
|
||||
asg.createLaunchConfiguration(r -> r.launchConfigurationName(name)
|
||||
.imageId("ami-amazonlinux2023").instanceType("t3.micro").userData("YQ=="));
|
||||
asg.deleteLaunchConfiguration(r -> r.launchConfigurationName(name));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("userData")
|
||||
@DisplayName("Direct input and source instances retain their encoded data")
|
||||
void configurationRetainsOriginalEncoding(boolean fromInstance, String encoded) {
|
||||
String name = TestFixtures.uniqueName("asg-config-data");
|
||||
try (AutoScalingClient asg = TestFixtures.autoScalingClient(); Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
String instanceId = fromInstance ? ec2.runInstances(r -> r.imageId("ami-amazonlinux2023")
|
||||
.instanceType("t3.micro").minCount(1).maxCount(1).userData(encoded))
|
||||
.instances().get(0).instanceId() : null;
|
||||
try {
|
||||
asg.createLaunchConfiguration(r -> r.launchConfigurationName(name).instanceId(instanceId)
|
||||
.imageId(fromInstance ? null : "ami-amazonlinux2023")
|
||||
.instanceType(fromInstance ? null : "t3.micro").userData(fromInstance ? null : encoded));
|
||||
try {
|
||||
LaunchConfiguration configuration = asg.describeLaunchConfigurations(r -> r
|
||||
.launchConfigurationNames(name)).launchConfigurations().get(0);
|
||||
assertThat(configuration.launchConfigurationName()).isEqualTo(name);
|
||||
assertThat(configuration.imageId()).isEqualTo("ami-amazonlinux2023");
|
||||
if (encoded == null || encoded.isEmpty()) {
|
||||
assertThat(configuration.userData()).isNullOrEmpty();
|
||||
} else {
|
||||
assertThat(configuration.userData()).isEqualTo(encoded);
|
||||
}
|
||||
} finally {
|
||||
asg.deleteLaunchConfiguration(r -> r.launchConfigurationName(name));
|
||||
}
|
||||
} finally {
|
||||
if (instanceId != null) {
|
||||
ec2.terminateInstances(r -> r.instanceIds(instanceId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,6 +144,17 @@ associated activities.
|
||||
|
||||
## Launch Source Compatibility
|
||||
|
||||
New launch configurations preserve their original base64 user data when launching instances, including
|
||||
binary and gzip payloads. Configurations derived from an instance retain its original encoding when
|
||||
available. Existing stored configurations retain their previous interpretation because older records
|
||||
mixed encoded input and decoded text; recreate a configuration to use byte-preserving launches.
|
||||
When deriving a configuration from an instance, omitted and blank user-data overrides continue to
|
||||
inherit the source instance's data. Creation checks the final selected data before saving: it must
|
||||
pass the shared EC2 decoder's base64 and 16 KiB raw-data checks. The decoder also rejects malformed
|
||||
gzip and expansion beyond 10 MiB; this is Floci's execution safety limit, not an AWS API limit.
|
||||
Invalid marked data in an older saved configuration is contained as a launch failure so reconciliation
|
||||
can still save the group and check refresh progress.
|
||||
|
||||
Auto Scaling groups preserve either a launch configuration, a top-level launch template, or a `MixedInstancesPolicy`. These launch sources are mutually exclusive in create/update requests. When a mixed instances policy is supplied, Floci stores and returns:
|
||||
|
||||
- `LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId`
|
||||
|
||||
+24
-2
@@ -25,7 +25,9 @@ import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -365,7 +367,9 @@ public class AutoScalingReconciler {
|
||||
propagatedInstanceTags(asg, launchSource),
|
||||
launchSource.userData(),
|
||||
launchSource.iamInstanceProfile(),
|
||||
launchSource.associatePublicIpAddress());
|
||||
launchSource.associatePublicIpAddress(), null, 0, null, null, null,
|
||||
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
|
||||
: encodeLegacyUserData(launchSource.userData()));
|
||||
|
||||
List<String> launchedInstanceIds = new ArrayList<>();
|
||||
for (Instance ec2Inst : reservation.getInstances()) {
|
||||
@@ -559,6 +563,16 @@ public class AutoScalingReconciler {
|
||||
private LaunchSource resolveLaunchSource(AutoScalingGroup asg) {
|
||||
LaunchConfiguration lc = resolveLaunchConfiguration(asg);
|
||||
if (lc != null) {
|
||||
String userData = lc.getUserData();
|
||||
if (Boolean.TRUE.equals(lc.getUserDataBase64Encoded())) {
|
||||
try {
|
||||
userData = Ec2UserDataDecoder.decode(userData);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("ASG {0}: cannot decode user data for launch configuration {1}: {2}",
|
||||
asg.getAutoScalingGroupName(), lc.getLaunchConfigurationName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new LaunchSource(
|
||||
lc.getLaunchConfigurationName(),
|
||||
lc.getImageId(),
|
||||
@@ -566,7 +580,8 @@ public class AutoScalingReconciler {
|
||||
lc.getKeyName(),
|
||||
lc.getSecurityGroups(),
|
||||
List.of(),
|
||||
lc.getUserData(),
|
||||
userData,
|
||||
Boolean.TRUE.equals(lc.getUserDataBase64Encoded()) ? lc.getUserData() : null,
|
||||
lc.getIamInstanceProfile(),
|
||||
null,
|
||||
null,
|
||||
@@ -597,6 +612,7 @@ public class AutoScalingReconciler {
|
||||
version.getData().getInstanceTags(),
|
||||
Ec2UserDataDecoder.decodeIfMissing(
|
||||
version.getData().getUserData(), version.getData().getEncodedUserData()),
|
||||
null,
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
asg.getLaunchTemplateId(),
|
||||
asg.getLaunchTemplateName(),
|
||||
@@ -628,6 +644,7 @@ public class AutoScalingReconciler {
|
||||
version.getData().getInstanceTags(),
|
||||
Ec2UserDataDecoder.decodeIfMissing(
|
||||
version.getData().getUserData(), version.getData().getEncodedUserData()),
|
||||
null,
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
specification.getLaunchTemplateId() == null
|
||||
? mixedLaunchTemplate.getLaunchTemplateId()
|
||||
@@ -641,6 +658,10 @@ public class AutoScalingReconciler {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String encodeLegacyUserData(String userData) {
|
||||
return userData == null ? null : Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private LaunchConfiguration resolveLaunchConfiguration(AutoScalingGroup asg) {
|
||||
String lcName = asg.getLaunchConfigurationName();
|
||||
if (lcName == null || lcName.isBlank()) {
|
||||
@@ -736,6 +757,7 @@ public class AutoScalingReconciler {
|
||||
List<String> securityGroupIds,
|
||||
List<io.github.hectorvent.floci.services.ec2.model.Tag> instanceTags,
|
||||
String userData,
|
||||
String encodedUserData,
|
||||
String iamInstanceProfile,
|
||||
String launchTemplateId,
|
||||
String launchTemplateName,
|
||||
|
||||
+10
-1
@@ -9,14 +9,17 @@ import io.github.hectorvent.floci.core.storage.StorageBackedMap;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.*;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -195,13 +198,18 @@ public class AutoScalingService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
if (isBlank(userData)) {
|
||||
userData = source.getUserData();
|
||||
userData = source.getEncodedUserData();
|
||||
if (userData == null && source.getUserData() != null) {
|
||||
userData = Base64.getEncoder().encodeToString(
|
||||
source.getUserData().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
if (isBlank(iamInstanceProfile)) {
|
||||
iamInstanceProfile = source.getIamInstanceProfileArn();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ec2UserDataDecoder.decode(userData);
|
||||
LaunchConfiguration lc = new LaunchConfiguration();
|
||||
lc.setLaunchConfigurationName(name);
|
||||
lc.setLaunchConfigurationArn(
|
||||
@@ -212,6 +220,7 @@ public class AutoScalingService {
|
||||
lc.setKeyName(keyName);
|
||||
lc.setSecurityGroups(securityGroups != null ? new ArrayList<>(securityGroups) : new ArrayList<>());
|
||||
lc.setUserData(userData);
|
||||
lc.setUserDataBase64Encoded(Boolean.TRUE);
|
||||
lc.setIamInstanceProfile(iamInstanceProfile);
|
||||
lc.setAssociatePublicIpAddress(associatePublicIpAddress);
|
||||
// AWS documents InstanceMonitoring as enabled by default and always returns the
|
||||
|
||||
+6
@@ -18,6 +18,9 @@ public class LaunchConfiguration {
|
||||
private String keyName;
|
||||
private List<String> securityGroups = new ArrayList<>();
|
||||
private String userData;
|
||||
// Historical configurations mixed API base64 and decoded instance text. An absent marker
|
||||
// retains their existing launch behavior; only newly created records have known encoding.
|
||||
private Boolean userDataBase64Encoded;
|
||||
private String iamInstanceProfile;
|
||||
// Nullable on purpose: AWS treats an absent flag as "fall back to the
|
||||
// subnet's MapPublicIpOnLaunch" and an explicit false as an override.
|
||||
@@ -53,6 +56,9 @@ public class LaunchConfiguration {
|
||||
public String getUserData() { return userData; }
|
||||
public void setUserData(String v) { this.userData = v; }
|
||||
|
||||
public Boolean getUserDataBase64Encoded() { return userDataBase64Encoded; }
|
||||
public void setUserDataBase64Encoded(Boolean v) { this.userDataBase64Encoded = v; }
|
||||
|
||||
public String getIamInstanceProfile() { return iamInstanceProfile; }
|
||||
public void setIamInstanceProfile(String v) { this.iamInstanceProfile = v; }
|
||||
|
||||
|
||||
+6
-5
@@ -67,7 +67,8 @@ class AutoScalingCapacitySuspensionTest {
|
||||
when(ec2.describeLaunchTemplateVersions(eq(REGION), eq("lt-original"), isNull(), anyList()))
|
||||
.thenReturn(List.of(template));
|
||||
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
|
||||
anyList(), any(), any(), any())).thenReturn(reservation("i-replacement"));
|
||||
anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull()))
|
||||
.thenReturn(reservation("i-replacement"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -82,7 +83,7 @@ class AutoScalingCapacitySuspensionTest {
|
||||
if (paused) {
|
||||
verify(ec2, never()).terminateInstances(anyString(), anyList());
|
||||
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull());
|
||||
assertEquals(List.of("i-original"), group.getInstances().stream()
|
||||
.map(AsgInstance::getInstanceId).toList());
|
||||
service.resumeProcesses(REGION, "suspended-group", processes);
|
||||
@@ -93,7 +94,7 @@ class AutoScalingCapacitySuspensionTest {
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-original"));
|
||||
} else {
|
||||
verify(ec2).runInstances(eq(REGION), any(), any(), eq(1), eq(1), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +161,7 @@ class AutoScalingCapacitySuspensionTest {
|
||||
clearInvocations(ec2);
|
||||
reconciler.reconcile(group);
|
||||
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull());
|
||||
verify(ec2, never()).terminateInstances(anyString(), anyList());
|
||||
} finally {
|
||||
releaseOperation.countDown();
|
||||
@@ -182,7 +183,7 @@ class AutoScalingCapacitySuspensionTest {
|
||||
clearInvocations(ec2);
|
||||
reconciler.reconcile(group);
|
||||
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull());
|
||||
if (recreate) {
|
||||
assertTrue(service.describeAutoScalingGroups(REGION, List.of("suspended-group"))
|
||||
.getFirst().getInstances().isEmpty());
|
||||
|
||||
+48
-10
@@ -25,6 +25,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
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.assertNull;
|
||||
@@ -34,6 +35,7 @@ import static org.mockito.Mockito.anyList;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -100,6 +102,32 @@ class AutoScalingReconcilerTest {
|
||||
verify(asgService).completeInstanceRefreshIfSettled("us-east-1", "app-asg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedSavedConfigurationDoesNotSkipGroupPersistenceOrRefreshCheck() {
|
||||
AutoScalingService service = scalingService();
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
AutoScalingGroup group = new AutoScalingGroup();
|
||||
group.setRegion("us-east-1");
|
||||
group.setAutoScalingGroupName("bad-data");
|
||||
group.setDesiredCapacity(1);
|
||||
group.setLaunchConfigurationName("saved-bad-data");
|
||||
LaunchConfiguration configuration = new LaunchConfiguration();
|
||||
configuration.setImageId("ami-test");
|
||||
configuration.setInstanceType("t3.micro");
|
||||
configuration.setUserData("not base64!");
|
||||
configuration.setUserDataBase64Encoded(true);
|
||||
when(service.describeLaunchConfigurations("us-east-1", List.of("saved-bad-data")))
|
||||
.thenReturn(List.of(configuration));
|
||||
when(service.saveAutoScalingGroupIfPresent(group)).thenReturn(true);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(service, ec2, mock(ElbV2Service.class));
|
||||
assertDoesNotThrow(() -> reconciler.reconcile(group));
|
||||
assertEquals(0, group.getInstances().size());
|
||||
verify(service).saveAutoScalingGroupIfPresent(group);
|
||||
verify(service).completeInstanceRefreshIfSettled("us-east-1", "bad-data");
|
||||
verify(ec2, never()).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
|
||||
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scaleOutUsesRequestedLaunchTemplateVersionData() {
|
||||
AutoScalingService asgService = scalingService();
|
||||
@@ -143,7 +171,8 @@ class AutoScalingReconcilerTest {
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
|
||||
anyList(), eq("#!/bin/bash\necho hi\n"),
|
||||
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null))).thenReturn(reservation);
|
||||
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
@@ -155,7 +184,8 @@ class AutoScalingReconcilerTest {
|
||||
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
|
||||
tags.capture(), eq("#!/bin/bash\necho hi\n"),
|
||||
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null));
|
||||
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any());
|
||||
assertNull(version.getData().getUserData());
|
||||
assertEquals(propagatedTags.size(), tags.getValue().size());
|
||||
assertEquals("app.ClusterId", tags.getValue().get(0).getKey());
|
||||
@@ -180,7 +210,8 @@ class AutoScalingReconcilerTest {
|
||||
reservation.setInstances(List.of(ec2Instance));
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()),
|
||||
eq(null), eq(null), eq(null))).thenReturn(reservation);
|
||||
eq(null), eq(null), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
@@ -204,7 +235,8 @@ class AutoScalingReconcilerTest {
|
||||
reservation.setInstances(List.of(ec2Instance));
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()),
|
||||
eq(null), eq(null), eq(null))).thenReturn(reservation);
|
||||
eq(null), eq(null), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
@@ -248,13 +280,15 @@ class AutoScalingReconcilerTest {
|
||||
reservation.setInstances(List.of(ec2Instance));
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
|
||||
anyList(), eq(null), eq(null), eq(associatePublicIp))).thenReturn(reservation);
|
||||
anyList(), eq(null), eq(null), eq(associatePublicIp),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
|
||||
anyList(), eq(null), eq(null), eq(associatePublicIp));
|
||||
anyList(), eq(null), eq(null), eq(associatePublicIp),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -286,7 +320,8 @@ class AutoScalingReconcilerTest {
|
||||
reservation.setInstances(List.of(ec2Instance));
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-7"), eq("t3.micro"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
|
||||
eq(List.of()), eq(null), eq(null), eq(null))).thenReturn(reservation);
|
||||
eq(List.of()), eq(null), eq(null), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
@@ -336,7 +371,8 @@ class AutoScalingReconcilerTest {
|
||||
reservation.setInstances(List.of(ec2Instance));
|
||||
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
|
||||
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null))).thenReturn(reservation);
|
||||
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
@@ -347,7 +383,8 @@ class AutoScalingReconcilerTest {
|
||||
assertEquals("t3.small", asg.getInstances().getFirst().getInstanceType());
|
||||
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
|
||||
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
|
||||
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null));
|
||||
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any());
|
||||
assertNull(version.getData().getUserData());
|
||||
}
|
||||
|
||||
@@ -418,7 +455,8 @@ class AutoScalingReconcilerTest {
|
||||
org.mockito.ArgumentMatchers.any(),
|
||||
org.mockito.ArgumentMatchers.any(),
|
||||
org.mockito.ArgumentMatchers.any(),
|
||||
org.mockito.ArgumentMatchers.any());
|
||||
org.mockito.ArgumentMatchers.any(),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+52
-1
@@ -21,9 +21,16 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -138,6 +145,49 @@ class AutoScalingServiceTest {
|
||||
assertTrue(service.describeAutoScalingGroups(REGION, List.of("missing-image-asg")).isEmpty());
|
||||
}
|
||||
|
||||
static Stream<String> rejectedUserData() throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(bytes)) {
|
||||
gzip.write(new byte[10 * 1024 * 1024 + 1]);
|
||||
}
|
||||
return Stream.of("not base64!", "YQ==\n", "H4sI", Base64.getEncoder().encodeToString(new byte[16385]),
|
||||
Base64.getEncoder().encodeToString(bytes.toByteArray()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("rejectedUserData")
|
||||
void createLaunchConfigurationRejectsUnlaunchableDataBeforeSaving(String data) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createLaunchConfiguration(REGION,
|
||||
"invalid-data", null, "ami-test", "t3.micro", null, List.of(), data, null, null));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(service.describeLaunchConfigurations(REGION, List.of("invalid-data")).isEmpty());
|
||||
service.createLaunchConfiguration(REGION, "invalid-data", null, "ami-test", "t3.micro", null,
|
||||
List.of(), "YQ==", null, null);
|
||||
assertEquals("YQ==", service.describeLaunchConfigurations(REGION, List.of("invalid-data"))
|
||||
.getFirst().getUserData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLaunchConfigurationChecksSelectedInheritedDataAndAllowsValidOverride() {
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
service.ec2Service = ec2;
|
||||
Instance source = new Instance();
|
||||
source.setImageId("ami-test");
|
||||
source.setInstanceType("t3.micro");
|
||||
source.setEncodedUserData("not base64!");
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(List.of(source));
|
||||
when(ec2.describeInstances(REGION, List.of("i-source"), Map.of())).thenReturn(List.of(reservation));
|
||||
assertThrows(AwsException.class, () -> service.createLaunchConfiguration(REGION, "inherited-invalid",
|
||||
"i-source", null, null, null, List.of(), null, null, null));
|
||||
assertTrue(service.describeLaunchConfigurations(REGION, List.of("inherited-invalid")).isEmpty());
|
||||
LaunchConfiguration overridden = service.createLaunchConfiguration(REGION, "overridden-valid",
|
||||
"i-source", null, null, null, List.of(), "Yg==", null, null);
|
||||
assertEquals("Yg==", overridden.getUserData());
|
||||
assertEquals("not base64!", source.getEncodedUserData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLaunchConfigurationRejectsMissingImageOrInstanceTypeWithoutInstanceId() {
|
||||
AwsException missingImage = assertThrows(AwsException.class, () -> service.createLaunchConfiguration(REGION,
|
||||
@@ -207,7 +257,8 @@ class AutoScalingServiceTest {
|
||||
assertEquals("m7g.large", launchConfiguration.getInstanceType());
|
||||
assertEquals("source-key", launchConfiguration.getKeyName());
|
||||
assertEquals(List.of("sg-source"), launchConfiguration.getSecurityGroups());
|
||||
assertEquals("source-user-data", launchConfiguration.getUserData());
|
||||
assertEquals("c291cmNlLXVzZXItZGF0YQ==", launchConfiguration.getUserData());
|
||||
assertEquals(Boolean.TRUE, launchConfiguration.getUserDataBase64Encoded());
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/source",
|
||||
launchConfiguration.getIamInstanceProfile());
|
||||
assertEquals(launchConfiguration,
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class LaunchConfigurationUserDataStorageTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
@TempDir Path directory;
|
||||
private final List<StorageFactory> factories = new ArrayList<>();
|
||||
|
||||
static Stream<Arguments> representations() {
|
||||
return Stream.of("persistent", "hybrid", "wal").flatMap(mode -> Stream.of(
|
||||
Arguments.of(mode, "new", "YQ", "a", "YQ"),
|
||||
Arguments.of(mode, "new", "/w", "\ufffd", "/w"),
|
||||
Arguments.of(mode, "new", "", null, ""),
|
||||
Arguments.of(mode, "new", null, null, null),
|
||||
Arguments.of(mode, "source", "/w", "\ufffd", "/w"),
|
||||
Arguments.of(mode, "source-legacy", "YQ==", "YQ==", "WVE9PQ=="),
|
||||
Arguments.of(mode, "legacy", "YQ==", "YQ==", "WVE9PQ=="),
|
||||
Arguments.of(mode, "legacy", "literal text", "literal text", "bGl0ZXJhbCB0ZXh0")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("representations")
|
||||
void reloadRetainsKnownEncodingWithoutGuessingLegacyText(String mode, String origin,
|
||||
String input, String text, String encoded)
|
||||
throws IOException {
|
||||
AutoScalingService service = storedService(mode);
|
||||
LaunchConfiguration created;
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
service.ec2Service = ec2;
|
||||
if (origin.startsWith("source")) {
|
||||
Instance source = new Instance();
|
||||
source.setImageId("ami-original");
|
||||
source.setInstanceType("t3.micro");
|
||||
source.setUserData(origin.equals("source-legacy") ? input : "\ufffd");
|
||||
source.setEncodedUserData(origin.equals("source-legacy") ? null : input);
|
||||
Reservation sourceReservation = new Reservation();
|
||||
sourceReservation.setInstances(List.of(source));
|
||||
when(ec2.describeInstances(REGION, List.of("i-source"), Map.of()))
|
||||
.thenReturn(List.of(sourceReservation));
|
||||
created = service.createLaunchConfiguration(REGION, "config", "i-source", null,
|
||||
null, null, List.of(), null, null, null);
|
||||
} else if (origin.equals("legacy")) {
|
||||
created = new ObjectMapper().readValue("""
|
||||
{"launchConfigurationName":"config","imageId":"ami-original",
|
||||
"instanceType":"t3.micro","region":"us-east-1"}
|
||||
""", LaunchConfiguration.class);
|
||||
assertNull(created.getUserDataBase64Encoded());
|
||||
created.setUserData(input);
|
||||
AccountAwareStorageBackend<LaunchConfiguration> store = service.storageFactory.create("autoscaling",
|
||||
"autoscaling-launch-configurations.json", new TypeReference<Map<String, LaunchConfiguration>>() {});
|
||||
store.put(REGION + "::config", created);
|
||||
} else {
|
||||
created = service.createLaunchConfiguration(REGION, "config", null, "ami-original",
|
||||
"t3.micro", null, List.of(), input, null, null);
|
||||
}
|
||||
factories.removeFirst().shutdownAll();
|
||||
String snapshot = mode.equals("wal") ? "autoscaling-launch-configurations-snapshot.json"
|
||||
: "autoscaling-launch-configurations.json";
|
||||
assertTrue(Files.exists(directory.resolve(snapshot)), "No real launch-configuration snapshot was written");
|
||||
service = storedService(mode);
|
||||
service.ec2Service = ec2;
|
||||
LaunchConfiguration restored = service.describeLaunchConfigurations(REGION, List.of("config")).getFirst();
|
||||
assertNotSame(created, restored);
|
||||
assertEquals(origin.equals("legacy") ? null : Boolean.TRUE, restored.getUserDataBase64Encoded());
|
||||
assertEquals(origin.equals("legacy") ? input : encoded, restored.getUserData());
|
||||
service.createAutoScalingGroup(REGION, "group", "config", null, null, null, null,
|
||||
0, 1, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0,
|
||||
List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("group")).getFirst();
|
||||
Instance launched = new Instance();
|
||||
launched.setInstanceId("i-created");
|
||||
Reservation result = new Reservation();
|
||||
result.setInstances(List.of(launched));
|
||||
when(ec2.runInstances(eq(REGION), eq("ami-original"), eq("t3.micro"), eq(1), eq(1),
|
||||
isNull(), anyList(), isNull(), isNull(), anyList(), eq(text), isNull(), isNull(),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), eq(encoded))).thenReturn(result);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(service, ec2, mock(ElbV2Service.class));
|
||||
try {
|
||||
reconciler.reconcile(group);
|
||||
assertEquals(List.of("i-created"), group.getInstances().stream().map(i -> i.getInstanceId()).toList());
|
||||
verify(ec2).runInstances(eq(REGION), eq("ami-original"), eq("t3.micro"), eq(1), eq(1),
|
||||
isNull(), anyList(), isNull(), isNull(), anyList(), eq(text), isNull(), isNull(),
|
||||
isNull(), eq(0), isNull(), isNull(), isNull(), eq(encoded));
|
||||
assertEquals(origin.equals("legacy") ? null : Boolean.TRUE, restored.getUserDataBase64Encoded());
|
||||
assertEquals(origin.equals("legacy") ? input : encoded, restored.getUserData());
|
||||
} finally {
|
||||
reconciler.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private AutoScalingService storedService(String mode) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
EmulatorConfig.WalConfig wal = mock(EmulatorConfig.WalConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(storage.persistentPath()).thenReturn(directory.toString());
|
||||
when(storage.wal()).thenReturn(wal);
|
||||
when(wal.compactionIntervalMs()).thenReturn(60000L);
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode("autoscaling")).thenReturn(mode);
|
||||
when(access.storageFlushInterval("autoscaling")).thenReturn(60000L);
|
||||
StorageFactory factory = new StorageFactory(config, access);
|
||||
factories.add(factory);
|
||||
AutoScalingService service = new AutoScalingService();
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
service.storageFactory = factory;
|
||||
service.initializeStorage();
|
||||
return service;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeStorage() {
|
||||
factories.forEach(StorageFactory::shutdownAll);
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingReconciler;
|
||||
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class AutoScalingConfigurationUserDataIntegrationTest {
|
||||
@Inject AutoScalingReconciler reconciler;
|
||||
@InjectSpy AutoScalingService asg;
|
||||
@Inject Ec2Service ec2;
|
||||
|
||||
@BeforeEach
|
||||
void isolateDirectReconciliation() {
|
||||
// The custom background executor lists every group with null region and names.
|
||||
doReturn(List.of()).when(asg).describeAutoScalingGroups(isNull(), isNull());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreBackgroundEnumeration() {
|
||||
reset(asg);
|
||||
}
|
||||
|
||||
static Stream<Arguments> launchSources() {
|
||||
return Stream.concat(Stream.of("query", "cfn").flatMap(source ->
|
||||
Stream.of(null, "", "YQ==", "YQ", "/w", Base64.getEncoder().encodeToString(new byte[16384]), "H4sIAAAAAAAC/1NW1E/KzNMvzuBKTc7IV8hIzcnJ5wIAedQ/FxUAAAA=")
|
||||
.map(data -> Arguments.of(source, data))), Stream.of(Arguments.of("cfn-intrinsic", "YQ==")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("launchSources")
|
||||
void launchPreservesOriginalEncodingAndImdsBytes(String source, String encoded) throws Exception {
|
||||
String name = "userdata-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
createConfiguration(source, name, encoded);
|
||||
try {
|
||||
if (!source.equals("query")) {
|
||||
String status = request("cloudformation", "DescribeStacks").formParam("StackName", name)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus");
|
||||
assertEquals("CREATE_COMPLETE", status);
|
||||
}
|
||||
String configurationData = request("autoscaling", "DescribeLaunchConfigurations")
|
||||
.formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("DescribeLaunchConfigurationsResponse."
|
||||
+ "DescribeLaunchConfigurationsResult.LaunchConfigurations.member.UserData");
|
||||
assertEquals(encoded == null ? "" : encoded, configurationData);
|
||||
RequestSpecification group = request("autoscaling", "CreateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", name).formParam("MinSize", 0)
|
||||
.formParam("MaxSize", 1).formParam("DesiredCapacity", 0)
|
||||
.formParam("AvailabilityZones.member.1", "us-east-1a");
|
||||
group.formParam("LaunchConfigurationName", name);
|
||||
group.post("/").then().statusCode(200);
|
||||
try {
|
||||
request("autoscaling", "SetDesiredCapacity").formParam("AutoScalingGroupName", name)
|
||||
.formParam("DesiredCapacity", 1).post("/").then().statusCode(200);
|
||||
reconciler.reconcile(asg.describeAutoScalingGroups("us-east-1", List.of(name)).getFirst());
|
||||
String id = request("autoscaling", "DescribeAutoScalingGroups")
|
||||
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
|
||||
.extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult."
|
||||
+ "AutoScalingGroups.member.Instances.member.InstanceId");
|
||||
assertNotNull(id);
|
||||
Instance instance = ec2.describeInstances("us-east-1", List.of(id), Map.of()).getFirst()
|
||||
.getInstances().getFirst();
|
||||
String actual = request("ec2", "DescribeInstanceAttribute").formParam("InstanceId", id)
|
||||
.formParam("Attribute", "userData").post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("DescribeInstanceAttributeResponse.userData.value");
|
||||
try (Ec2MetadataTestFixture metadata = new Ec2MetadataTestFixture()) {
|
||||
metadata.start(null, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), instance);
|
||||
HttpResponse<byte[]> response = metadata.get("/latest/user-data", null,
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertAll(
|
||||
() -> assertEquals(encoded == null ? "" : encoded, actual),
|
||||
() -> assertEquals(normalize(Ec2UserDataDecoder.decode(encoded)), normalize(instance.getUserData())),
|
||||
() -> assertEquals(encoded == null || encoded.isEmpty() ? 404 : 200, response.statusCode()),
|
||||
() -> {
|
||||
if (encoded != null && !encoded.isEmpty()) {
|
||||
assertArrayEquals(Base64.getDecoder().decode(encoded), response.body());
|
||||
}
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
request("autoscaling", "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", name)
|
||||
.formParam("ForceDelete", true).post("/").then().statusCode(200);
|
||||
}
|
||||
} finally {
|
||||
deleteConfiguration(source, name);
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> rejectedConfigurations() {
|
||||
return Stream.of("query", "cfn").flatMap(source -> Stream.of("not base64!", "H4sI",
|
||||
Base64.getEncoder().encodeToString(new byte[16385])).map(data -> Arguments.of(source, data)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("rejectedConfigurations")
|
||||
void invalidConfigurationFailsWithoutLeavingLaunchSource(String source, String data) {
|
||||
String name = "rejected-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
if (source.equals("query")) {
|
||||
String code = request("autoscaling", "CreateLaunchConfiguration")
|
||||
.formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
|
||||
.formParam("InstanceType", "t3.micro").formParam("UserData", data)
|
||||
.post("/").then().statusCode(400).extract().xmlPath().getString("ErrorResponse.Error.Code");
|
||||
assertEquals("InvalidParameterValue", code);
|
||||
} else {
|
||||
createConfiguration(source, name, data);
|
||||
try {
|
||||
String status = request("cloudformation", "DescribeStacks").formParam("StackName", name)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus");
|
||||
assertEquals("ROLLBACK_COMPLETE", status);
|
||||
String events = request("cloudformation", "DescribeStackEvents").formParam("StackName", name)
|
||||
.post("/").then().statusCode(200).extract().asString();
|
||||
assertTrue(events.contains("UserData"));
|
||||
} finally {
|
||||
deleteConfiguration(source, name);
|
||||
}
|
||||
}
|
||||
assertTrue(asg.describeLaunchConfigurations("us-east-1", List.of(name)).isEmpty());
|
||||
createConfiguration("query", name, "YQ==");
|
||||
deleteConfiguration("query", name);
|
||||
}
|
||||
|
||||
private void createConfiguration(String source, String name, String encoded) {
|
||||
if (source.equals("query")) {
|
||||
RequestSpecification create = request("autoscaling", "CreateLaunchConfiguration")
|
||||
.formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
|
||||
.formParam("InstanceType", "t3.micro");
|
||||
if (encoded != null) {
|
||||
create.formParam("UserData", encoded);
|
||||
}
|
||||
create.post("/").then().statusCode(200);
|
||||
} else {
|
||||
String data = encoded == null ? "" : ", \"UserData\": "
|
||||
+ (source.equals("cfn-intrinsic") ? "{\"Fn::Base64\": \"a\"}" : "\"" + encoded + "\"");
|
||||
String template = "{\"Resources\":{\"Lc\":{\"Type\":\"AWS::AutoScaling::LaunchConfiguration\","
|
||||
+ "\"Properties\":{\"LaunchConfigurationName\":\"" + name
|
||||
+ "\",\"ImageId\":\"ami-amazonlinux2023\",\"InstanceType\":\"t3.micro\"" + data + "}}}}";
|
||||
request("cloudformation", "CreateStack").formParam("StackName", name)
|
||||
.formParam("TemplateBody", template).post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteConfiguration(String source, String name) {
|
||||
if (source.equals("query")) {
|
||||
request("autoscaling", "DeleteLaunchConfiguration").formParam("LaunchConfigurationName", name)
|
||||
.post("/").then().statusCode(200);
|
||||
} else {
|
||||
request("cloudformation", "DeleteStack").formParam("StackName", name)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> inheritedData() {
|
||||
return Stream.of(Arguments.of("YQ==", null), Arguments.of("/w", null),
|
||||
Arguments.of("H4sIAAAAAAAC/1NW1E/KzNMvzuBKTc7IV8hIzcnJ5wIAedQ/FxUAAAA=", null),
|
||||
Arguments.of("YQ==", "Yg=="), Arguments.of("YQ==", ""),
|
||||
Arguments.of("YQ==", " "));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("inheritedData")
|
||||
void configurationCopiesSourceEncodingUnlessOverridden(String sourceData, String override) {
|
||||
String name = "inherited-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String id = request("ec2", "RunInstances").formParam("ImageId", "ami-amazonlinux2023")
|
||||
.formParam("InstanceType", "t3.micro").formParam("UserData", sourceData)
|
||||
.post("/").then().statusCode(200).extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
try {
|
||||
RequestSpecification create = request("autoscaling", "CreateLaunchConfiguration")
|
||||
.formParam("LaunchConfigurationName", name).formParam("InstanceId", id);
|
||||
if (override != null) {
|
||||
create.formParam("UserData", override);
|
||||
}
|
||||
create.post("/").then().statusCode(200);
|
||||
try {
|
||||
String actual = request("autoscaling", "DescribeLaunchConfigurations")
|
||||
.formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("DescribeLaunchConfigurationsResponse."
|
||||
+ "DescribeLaunchConfigurationsResult.LaunchConfigurations.member.UserData");
|
||||
assertEquals(override == null || override.isBlank() ? sourceData : override, actual);
|
||||
} finally {
|
||||
request("autoscaling", "DeleteLaunchConfiguration").formParam("LaunchConfigurationName", name)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
} finally {
|
||||
request("ec2", "TerminateInstances").formParam("InstanceId.1", id).post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static RequestSpecification request(String service, String action) {
|
||||
return given().header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/us-east-1/"
|
||||
+ service + "/aws4_request, SignedHeaders=host, Signature=abc").formParam("Action", action);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user