mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ec2): decode CloudFormation launch template user data (#4711)
* fix(ec2): decode CloudFormation launch template user data * fix(ec2): bound and recover launch template user data * fix(ec2): honor explicit user data over legacy templates
This commit is contained in:
1 parent
a338a430cc
commit
3df7fb17ee
14 files changed
+449
-59
No files matched your search
@@ -122,12 +122,25 @@ public final class UserDataPipeline {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.acquire();
|
||||
byte[] decompressed = decompressGzipWithLimit(payload);
|
||||
if (decompressed == null) {
|
||||
LOG.warnv("UserData decompressed past {0} bytes; discarding as oversized",
|
||||
MAX_DECOMPRESSED_USER_DATA_BYTES);
|
||||
}
|
||||
return decompressed;
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("Interrupted while waiting for UserData decompression budget; discarding payload");
|
||||
return null;
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("UserData starts with the gzip magic bytes but could not be decompressed: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns null for oversized content; both API decoding and guest execution share this budget. */
|
||||
public static byte[] decompressGzipWithLimit(byte[] payload) throws IOException, InterruptedException {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.acquire();
|
||||
try {
|
||||
Runnable hook = userDataDecompressionTestHook;
|
||||
if (hook != null) {
|
||||
@@ -145,16 +158,11 @@ public final class UserDataPipeline {
|
||||
while ((read = gzip.read(buffer)) != -1) {
|
||||
totalRead += read;
|
||||
if (totalRead > MAX_DECOMPRESSED_USER_DATA_BYTES) {
|
||||
LOG.warnv("UserData decompressed past {0} bytes; discarding as oversized",
|
||||
MAX_DECOMPRESSED_USER_DATA_BYTES);
|
||||
return null;
|
||||
}
|
||||
decompressed.write(buffer, 0, read);
|
||||
}
|
||||
return decompressed.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("UserData starts with the gzip magic bytes but could not be decompressed: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
} finally {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.release();
|
||||
|
||||
+5
-2
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity;
|
||||
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 io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
@@ -592,7 +593,8 @@ public class AutoScalingReconciler {
|
||||
version.getData().getKeyName(),
|
||||
version.getData().effectiveSecurityGroupIds(),
|
||||
version.getData().getInstanceTags(),
|
||||
version.getData().getUserData(),
|
||||
Ec2UserDataDecoder.decodeIfMissing(
|
||||
version.getData().getUserData(), version.getData().getEncodedUserData()),
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
asg.getLaunchTemplateId(),
|
||||
asg.getLaunchTemplateName(),
|
||||
@@ -622,7 +624,8 @@ public class AutoScalingReconciler {
|
||||
version.getData().getKeyName(),
|
||||
version.getData().effectiveSecurityGroupIds(),
|
||||
version.getData().getInstanceTags(),
|
||||
version.getData().getUserData(),
|
||||
Ec2UserDataDecoder.decodeIfMissing(
|
||||
version.getData().getUserData(), version.getData().getEncodedUserData()),
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
specification.getLaunchTemplateId() == null
|
||||
? mixedLaunchTemplate.getLaunchTemplateId()
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
// A LaunchTemplate the stack references but that does not resolve is a real error, as on
|
||||
// AWS: let it fail the resource rather than silently launching with default config.
|
||||
LaunchTemplateData ltData = ec2Service.resolveLaunchTemplateData(region, ltId, ltName,
|
||||
ltRef.path("Version").asText(null));
|
||||
ltRef.path("Version").asText(null), false);
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
imageId = ltData.getImageId();
|
||||
}
|
||||
|
||||
+4
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -53,7 +54,9 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
|
||||
data.setInstanceType(node.path("InstanceType").asText(null));
|
||||
data.setKeyName(node.path("KeyName").asText(null));
|
||||
// CFN carries UserData already base64-encoded.
|
||||
data.setEncodedUserData(node.path("UserData").asText(null));
|
||||
String encodedUserData = node.path("UserData").asText(null);
|
||||
data.setEncodedUserData(encodedUserData);
|
||||
data.setUserData(Ec2UserDataDecoder.decode(encodedUserData));
|
||||
data.setIamInstanceProfile(iamInstanceProfile(node.path("IamInstanceProfile")));
|
||||
if (node.has("SecurityGroupIds")) {
|
||||
List<String> securityGroupIds = new ArrayList<>();
|
||||
|
||||
@@ -16,14 +16,11 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Ec2QueryHandler {
|
||||
@@ -728,7 +725,7 @@ public class Ec2QueryHandler {
|
||||
String userDataEncoded = p.getFirst("UserData");
|
||||
String userData = null;
|
||||
if (userDataEncoded != null && !userDataEncoded.isBlank()) {
|
||||
userData = decodeUserData(userDataEncoded);
|
||||
userData = Ec2UserDataDecoder.decode(userDataEncoded);
|
||||
}
|
||||
|
||||
String iamInstanceProfileArn = resolveIamInstanceProfileArn(p);
|
||||
@@ -760,7 +757,8 @@ public class Ec2QueryHandler {
|
||||
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
|
||||
String creditSpecificationCpuCredits = p.getFirst("CreditSpecification.CpuCredits");
|
||||
|
||||
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(p, region);
|
||||
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(
|
||||
p, region, userDataEncoded == null || userDataEncoded.isBlank());
|
||||
if (launchTemplateData != null) {
|
||||
if (launchTemplateData.getMetadataOptions() != null) {
|
||||
metadataOptions = LaunchTemplateData.MetadataOptions.merge(
|
||||
@@ -837,14 +835,15 @@ public class Ec2QueryHandler {
|
||||
throw new AwsException("InvalidParameterValue", name + " must be a positive integer", 400);
|
||||
}
|
||||
|
||||
private LaunchTemplateData resolveRunInstancesLaunchTemplateData(MultivaluedMap<String, String> p, String region) {
|
||||
private LaunchTemplateData resolveRunInstancesLaunchTemplateData(MultivaluedMap<String, String> p, String region,
|
||||
boolean decodeUserData) {
|
||||
String id = p.getFirst("LaunchTemplate.LaunchTemplateId");
|
||||
String name = p.getFirst("LaunchTemplate.LaunchTemplateName");
|
||||
String version = p.getFirst("LaunchTemplate.Version");
|
||||
if ((id == null || id.isBlank()) && (name == null || name.isBlank())) {
|
||||
return null;
|
||||
}
|
||||
return service.resolveLaunchTemplateData(region, id, name, version);
|
||||
return service.resolveLaunchTemplateData(region, id, name, version, decodeUserData);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1447,7 +1446,7 @@ public class Ec2QueryHandler {
|
||||
// describes back exactly as sent.
|
||||
String userDataEncoded = p.getFirst("UserData.Value");
|
||||
if (userDataEncoded != null) {
|
||||
service.modifyInstanceUserData(region, instanceId, decodeUserData(userDataEncoded), userDataEncoded);
|
||||
service.modifyInstanceUserData(region, instanceId, Ec2UserDataDecoder.decode(userDataEncoded), userDataEncoded);
|
||||
}
|
||||
// Find which attribute is being modified
|
||||
for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value")) {
|
||||
@@ -5219,7 +5218,7 @@ public class Ec2QueryHandler {
|
||||
|
||||
String encodedUserData = p.getFirst(prefix + ".UserData");
|
||||
data.setEncodedUserData(encodedUserData);
|
||||
data.setUserData(decodeUserData(encodedUserData));
|
||||
data.setUserData(Ec2UserDataDecoder.decode(encodedUserData));
|
||||
|
||||
String profileArn = p.getFirst(prefix + ".IamInstanceProfile.Arn");
|
||||
String profileName = p.getFirst(prefix + ".IamInstanceProfile.Name");
|
||||
@@ -5564,27 +5563,6 @@ public class Ec2QueryHandler {
|
||||
return value != null ? String.valueOf(value) : null;
|
||||
}
|
||||
|
||||
private String decodeUserData(String userDataEncoded) {
|
||||
if (userDataEncoded == null || userDataEncoded.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(userDataEncoded);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid base64 content.", 400);
|
||||
}
|
||||
if (decoded.length >= 2 && (decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(decoded))) {
|
||||
decoded = gzip.readAllBytes();
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid gzip content.", 400);
|
||||
}
|
||||
}
|
||||
return new String(decoded, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String vpcEndpointXml(VpcEndpoint endpoint) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("vpcEndpointId", endpoint.getVpcEndpointId())
|
||||
|
||||
@@ -6679,13 +6679,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
}
|
||||
|
||||
public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version) {
|
||||
return resolveLaunchTemplateData(region, id, name, version, true);
|
||||
}
|
||||
|
||||
public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version,
|
||||
boolean decodeUserData) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
String resolvedVersion = resolveLaunchTemplateVersion(
|
||||
launchTemplate,
|
||||
version,
|
||||
launchTemplate.getDefaultVersionNumber());
|
||||
return new LaunchTemplateData(versionData(launchTemplate, resolvedVersion));
|
||||
LaunchTemplateData data = new LaunchTemplateData(versionData(launchTemplate, resolvedVersion));
|
||||
if (decodeUserData) {
|
||||
data.setUserData(Ec2UserDataDecoder.decodeIfMissing(data.getUserData(), data.getEncodedUserData()));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public LaunchTemplate deleteLaunchTemplate(String region, String id, String name) {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
public final class Ec2UserDataDecoder {
|
||||
|
||||
private static final int MAX_USER_DATA_BYTES = 16 * 1024;
|
||||
private static final int MAX_ENCODED_USER_DATA_LENGTH = ((MAX_USER_DATA_BYTES + 2) / 3) * 4;
|
||||
|
||||
private Ec2UserDataDecoder() {
|
||||
}
|
||||
|
||||
public static String decodeIfMissing(String userData, String encodedUserData) {
|
||||
return userData != null ? userData : decode(encodedUserData);
|
||||
}
|
||||
|
||||
public static String decode(String encoded) {
|
||||
if (encoded == null || encoded.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
if (encoded.length() > MAX_ENCODED_USER_DATA_LENGTH) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData exceeds the 16 KiB limit.", 400);
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(encoded);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid base64 content.", 400);
|
||||
}
|
||||
if (decoded.length > MAX_USER_DATA_BYTES) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData exceeds the 16 KiB limit.", 400);
|
||||
}
|
||||
if (decoded.length >= 2 && (decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
try {
|
||||
decoded = UserDataPipeline.decompressGzipWithLimit(decoded);
|
||||
if (decoded == null) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData exceeds the decompressed size limit.", 400);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AwsException("InternalError", "Interrupted while decoding UserData.", 500);
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("InvalidParameterValue", "UserData is not valid gzip content.", 400);
|
||||
}
|
||||
}
|
||||
return new String(decoded, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user