diff --git a/docs/services/eks.md b/docs/services/eks.md index 13cb29fd5e..586f3bc8e4 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -100,6 +100,56 @@ Floci tags the cluster security group with the standard AWS system tags: - **Backfill**: Existing persisted clusters that were created before this feature receive an auto-generated cluster security group during startup backfill if their VPC is present. - **Rules**: In accordance with AWS EKS behavior, the cluster security group includes a self-referencing inbound rule allowing all traffic from members of the same security group to enable control plane and node communication, a self-referencing outbound rule for Elastic Fabric Adapter (EFA) traffic, and the standard EC2 outbound rule. +## Encryption and logging configuration + +EKS clusters support configuring KMS envelope encryption for secrets and control plane logging export. + +### Encryption configuration + +`CreateCluster` accepts an `encryptionConfig` array specifying the encryption provider for Kubernetes resources: + +```json +{ + "encryptionConfig": [ + { + "resources": ["secrets"], + "provider": { + "keyArn": "arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012" + } + } + ] +} +``` + +- **Supported resources**: Only `["secrets"]` is supported by AWS EKS. Specifying any other resource or leaving resources empty causes `InvalidParameterException` (HTTP 400). +- **Provider**: `provider.keyArn` must be non-empty. +- **Cardinality**: AWS allows at most one encryption configuration entry. Specifying more than one causes `InvalidParameterException` (HTTP 400). +- **Omission**: When omitted at creation time, `encryptionConfig` is not populated and is omitted from `DescribeCluster` responses (null or omitted, no synthetic default). +- **Scope**: Floci stores and returns the encryption configuration faithfully. Envelope encryption of Secrets at the Kubernetes storage layer and KMS cryptographic operations are out of scope. + +### Logging configuration + +`CreateCluster` accepts control plane logging configuration in `logging.clusterLogging`: + +```json +{ + "logging": { + "clusterLogging": [ + { + "types": ["api", "audit"], + "enabled": true + } + ] + } +} +``` + +- **Supported log types**: The valid EKS log types are `api`, `audit`, `authenticator`, `controllerManager`, and `scheduler`. Specifying an unrecognized type causes `InvalidParameterException` (HTTP 400). +- **Response normalization**: AWS EKS always returns the status of all five log types. Enabled types are returned first (`enabled: true`), followed by disabled types (`enabled: false`). +- **Default logging**: When omitted or empty at creation time, Floci returns all five log types disabled in a single entry (`enabled: false`). +- **Backfill**: Existing persisted clusters created before this feature was introduced are automatically backfilled on startup with default disabled logging. +- **Scope**: Floci stores and returns control plane logging configuration. Shipping log streams to Amazon CloudWatch Logs log groups is out of scope. + ## Modes ### Mock mode (`mock: true`) @@ -565,5 +615,4 @@ The following EKS features are not yet supported: - `UpdateClusterConfig` / `UpdateClusterVersion` - Add-ons (`CreateAddon`, `DescribeAddon`, `ListAddons`) - Identity provider configs -- Access entries and policies -- Encryption config +- Access policies diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index 27ddc6386c..c6b91b9d98 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -19,16 +19,20 @@ import io.github.hectorvent.floci.services.eks.model.Cluster; import io.github.hectorvent.floci.services.eks.model.AccessConfig; import io.github.hectorvent.floci.services.eks.model.ClusterIdentity; import io.github.hectorvent.floci.services.eks.model.ClusterStatus; -import io.github.hectorvent.floci.services.eks.model.OidcIdentity; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest; import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest; +import io.github.hectorvent.floci.services.eks.model.EncryptionConfig; import io.github.hectorvent.floci.services.eks.model.FargateProfile; import io.github.hectorvent.floci.services.eks.model.FargateProfileStatus; import io.github.hectorvent.floci.services.eks.model.KubernetesNetworkConfig; +import io.github.hectorvent.floci.services.eks.model.LogSetup; +import io.github.hectorvent.floci.services.eks.model.Logging; import io.github.hectorvent.floci.services.eks.model.Nodegroup; import io.github.hectorvent.floci.services.eks.model.NodegroupScalingConfig; import io.github.hectorvent.floci.services.eks.model.NodegroupStatus; +import io.github.hectorvent.floci.services.eks.model.OidcIdentity; +import io.github.hectorvent.floci.services.eks.model.Provider; import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig; import com.fasterxml.jackson.core.type.TypeReference; import jakarta.annotation.PostConstruct; @@ -40,8 +44,10 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.HexFormat; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -61,6 +67,10 @@ public class EksService implements TagHandler, ResourceProvider { private static final Logger LOG = Logger.getLogger(EksService.class); + private static final List ALL_LOG_TYPES = List.of( + "api", "audit", "authenticator", "controllerManager", "scheduler" + ); + /** The AWS charset for EKS cluster names. It admits no dot, which the Docker-name account * qualifier relies on — see EksClusterManager#accountQualifiedName. */ static final String CLUSTER_NAME_REGEX = "[0-9A-Za-z][A-Za-z0-9\\-_]*"; @@ -104,6 +114,7 @@ public class EksService implements TagHandler, ResourceProvider { public void init() { backfillOidcIdentities(); backfillClusterSecurityGroups(); + backfillLogging(); if (!config.services().eks().mock()) { restorePersistedClusters(); startReadinessPoller(); @@ -323,6 +334,23 @@ public class EksService implements TagHandler, ResourceProvider { } } + void backfillLogging() { + for (AccountAwareStorageBackend.AccountEntry entry : allClusterEntries()) { + Cluster cluster = entry.value(); + if (cluster.getLogging() != null) { + continue; + } + String accountId = entry.accountId(); + if (cluster.getAccountId() == null) { + cluster.setAccountId(accountId); + } + cluster.setLogging(defaultLogging()); + putClusterForAccount(accountId, cluster); + LOG.infov("Backfilled default logging for existing EKS cluster {0} in account {1}", + cluster.getName(), accountId); + } + } + private String resolveClusterRegion(Cluster cluster) { if (cluster.getArn() != null && !cluster.getArn().isBlank()) { try { @@ -408,6 +436,8 @@ public class EksService implements TagHandler, ResourceProvider { } cluster.setResourcesVpcConfig(vpcConfig); cluster.setKubernetesNetworkConfig(buildNetworkConfig(request.getKubernetesNetworkConfig())); + cluster.setLogging(buildLogging(request.getLogging())); + cluster.setEncryptionConfig(buildEncryptionConfig(request.getEncryptionConfig())); cluster.setStatus(ClusterStatus.CREATING); cluster.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>()); cluster.setPlatformVersion("eks.1"); @@ -467,9 +497,13 @@ public class EksService implements TagHandler, ResourceProvider { } public Cluster describeCluster(String name) { - return storage.get(name) + Cluster cluster = storage.get(name) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "No cluster found for name: " + name, 404)); + if (cluster.getLogging() == null) { + cluster.setLogging(defaultLogging()); + } + return cluster; } public List listClusters() { @@ -783,6 +817,81 @@ public class EksService implements TagHandler, ResourceProvider { return config; } + static Logging defaultLogging() { + return new Logging(List.of(new LogSetup(new ArrayList<>(ALL_LOG_TYPES), false))); + } + + private Logging buildLogging(Logging requestedLogging) { + if (requestedLogging == null || requestedLogging.getClusterLogging() == null + || requestedLogging.getClusterLogging().isEmpty()) { + return defaultLogging(); + } + + Set enabledTypes = new LinkedHashSet<>(); + Set specifiedTypes = new HashSet<>(); + + for (LogSetup setup : requestedLogging.getClusterLogging()) { + if (setup == null || setup.getTypes() == null) { + continue; + } + for (String type : setup.getTypes()) { + if (!ALL_LOG_TYPES.contains(type)) { + throw new AwsException("InvalidParameterException", + "'" + type + "' is not a valid log type", 400); + } + specifiedTypes.add(type); + if (Boolean.TRUE.equals(setup.getEnabled())) { + enabledTypes.add(type); + } else { + enabledTypes.remove(type); + } + } + } + + if (specifiedTypes.isEmpty()) { + return defaultLogging(); + } + + List enabledList = ALL_LOG_TYPES.stream() + .filter(enabledTypes::contains) + .collect(Collectors.toList()); + List disabledList = ALL_LOG_TYPES.stream() + .filter(t -> !enabledTypes.contains(t)) + .collect(Collectors.toList()); + + List entries = new ArrayList<>(); + if (!enabledList.isEmpty()) { + entries.add(new LogSetup(enabledList, true)); + } + if (!disabledList.isEmpty()) { + entries.add(new LogSetup(disabledList, false)); + } + + return new Logging(entries); + } + + private List buildEncryptionConfig(List requestedConfigs) { + if (requestedConfigs == null || requestedConfigs.isEmpty()) { + return null; + } + if (requestedConfigs.size() > 1) { + throw new AwsException("InvalidParameterException", + "Only one encryption configuration is allowed", 400); + } + EncryptionConfig config = requestedConfigs.getFirst(); + if (config == null || config.getResources() == null || config.getResources().isEmpty() + || !List.of("secrets").equals(config.getResources())) { + throw new AwsException("InvalidParameterException", + "Invalid k8s resource and provider for encryption", 400); + } + if (config.getProvider() == null || config.getProvider().getKeyArn() == null + || config.getProvider().getKeyArn().isBlank()) { + throw new AwsException("InvalidParameterException", + "Invalid k8s resource and provider for encryption", 400); + } + return List.of(new EncryptionConfig(List.of("secrets"), new Provider(config.getProvider().getKeyArn()))); + } + private String nodeGroupKey(String clusterName, String nodegroupName) { return clusterName + "/" + nodegroupName; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java index 42a4c05a63..08da352b36 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java @@ -3,10 +3,12 @@ package io.github.hectorvent.floci.services.eks.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.List; import java.util.Map; @RegisterForReflection @@ -38,6 +40,13 @@ public class Cluster { @JsonProperty("kubernetesNetworkConfig") private KubernetesNetworkConfig kubernetesNetworkConfig; + @JsonProperty("logging") + private Logging logging; + + @JsonProperty("encryptionConfig") + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private List encryptionConfig; + @JsonProperty("status") private ClusterStatus status; @@ -131,6 +140,12 @@ public class Cluster { public int getHostPort() { return hostPort; } public void setHostPort(int hostPort) { this.hostPort = hostPort; } + public Logging getLogging() { return logging; } + public void setLogging(Logging logging) { this.logging = logging; } + + public List getEncryptionConfig() { return encryptionConfig; } + public void setEncryptionConfig(List encryptionConfig) { this.encryptionConfig = encryptionConfig; } + public String getDockerName() { return dockerName; } public void setDockerName(String dockerName) { this.dockerName = dockerName; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java index e67debeca0..ece677f390 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; import java.util.Map; @RegisterForReflection @@ -25,6 +26,12 @@ public class CreateClusterRequest { @JsonProperty("kubernetesNetworkConfig") private KubernetesNetworkConfig kubernetesNetworkConfig; + @JsonProperty("encryptionConfig") + private List encryptionConfig; + + @JsonProperty("logging") + private Logging logging; + @JsonProperty("tags") private Map tags; @@ -56,6 +63,12 @@ public class CreateClusterRequest { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + public List getEncryptionConfig() { return encryptionConfig; } + public void setEncryptionConfig(List encryptionConfig) { this.encryptionConfig = encryptionConfig; } + + public Logging getLogging() { return logging; } + public void setLogging(Logging logging) { this.logging = logging; } + public String getClientRequestToken() { return clientRequestToken; } public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/EncryptionConfig.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/EncryptionConfig.java new file mode 100644 index 0000000000..85e9c45aff --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/EncryptionConfig.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Objects; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class EncryptionConfig { + + @JsonProperty("resources") + private List resources; + + @JsonProperty("provider") + private Provider provider; + + public EncryptionConfig() {} + + public EncryptionConfig(List resources, Provider provider) { + this.resources = resources; + this.provider = provider; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public Provider getProvider() { + return provider; + } + + public void setProvider(Provider provider) { + this.provider = provider; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EncryptionConfig that = (EncryptionConfig) o; + return Objects.equals(resources, that.resources) && Objects.equals(provider, that.provider); + } + + @Override + public int hashCode() { + return Objects.hash(resources, provider); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/LogSetup.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/LogSetup.java new file mode 100644 index 0000000000..c9c1b44988 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/LogSetup.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Objects; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class LogSetup { + + @JsonProperty("types") + private List types; + + @JsonProperty("enabled") + private Boolean enabled; + + public LogSetup() {} + + public LogSetup(List types, Boolean enabled) { + this.types = types; + this.enabled = enabled; + } + + public List getTypes() { + return types; + } + + public void setTypes(List types) { + this.types = types; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LogSetup logSetup = (LogSetup) o; + return Objects.equals(types, logSetup.types) && Objects.equals(enabled, logSetup.enabled); + } + + @Override + public int hashCode() { + return Objects.hash(types, enabled); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Logging.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Logging.java new file mode 100644 index 0000000000..b032976145 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Logging.java @@ -0,0 +1,47 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Objects; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class Logging { + + @JsonProperty("clusterLogging") + private List clusterLogging; + + public Logging() {} + + public Logging(List clusterLogging) { + this.clusterLogging = clusterLogging; + } + + public List getClusterLogging() { + return clusterLogging; + } + + public void setClusterLogging(List clusterLogging) { + this.clusterLogging = clusterLogging; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Logging logging = (Logging) o; + return Objects.equals(clusterLogging, logging.clusterLogging); + } + + @Override + public int hashCode() { + return Objects.hash(clusterLogging); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Provider.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Provider.java new file mode 100644 index 0000000000..2963734cb5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Provider.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.eks.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Objects; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class Provider { + + @JsonProperty("keyArn") + private String keyArn; + + public Provider() {} + + public Provider(String keyArn) { + this.keyArn = keyArn; + } + + public String getKeyArn() { + return keyArn; + } + + public void setKeyArn(String keyArn) { + this.keyArn = keyArn; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Provider provider = (Provider) o; + return Objects.equals(keyArn, provider.keyArn); + } + + @Override + public int hashCode() { + return Objects.hash(keyArn); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksEncryptionLoggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksEncryptionLoggingIntegrationTest.java new file mode 100644 index 0000000000..bf7fb4cef6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksEncryptionLoggingIntegrationTest.java @@ -0,0 +1,185 @@ +package io.github.hectorvent.floci.services.eks; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EksEncryptionLoggingIntegrationTest { + + private static final String JSON = "application/json"; + private static final String CLUSTER_WITH_ENC_LOG = "it-enc-log-cluster"; + private static final String CLUSTER_DEFAULT = "it-default-enc-log-cluster"; + private static final String KMS_KEY_ARN = + "arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012"; + + @Test + @Order(1) + void createClusterWithEncryptionConfigAndLoggingReturnsBothInWireResponse() { + String payload = "{" + + "\"name\":\"" + CLUSTER_WITH_ENC_LOG + "\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"," + + "\"encryptionConfig\":[{" + + " \"resources\":[\"secrets\"]," + + " \"provider\":{\"keyArn\":\"" + KMS_KEY_ARN + "\"}" + + "}]," + + "\"logging\":{" + + " \"clusterLogging\":[{" + + " \"types\":[\"api\",\"audit\"]," + + " \"enabled\":true" + + " }]" + + "}" + + "}"; + + given().contentType(JSON) + .body(payload) + .when().post("/clusters") + .then().statusCode(200) + .body("cluster.name", equalTo(CLUSTER_WITH_ENC_LOG)) + .body("cluster.encryptionConfig", hasSize(1)) + .body("cluster.encryptionConfig[0].resources", hasSize(1)) + .body("cluster.encryptionConfig[0].resources[0]", equalTo("secrets")) + .body("cluster.encryptionConfig[0].provider.keyArn", equalTo(KMS_KEY_ARN)) + .body("cluster.logging.clusterLogging", hasSize(2)) + .body("cluster.logging.clusterLogging[0].enabled", equalTo(true)) + .body("cluster.logging.clusterLogging[0].types", containsInAnyOrder("api", "audit")) + .body("cluster.logging.clusterLogging[1].enabled", equalTo(false)) + .body("cluster.logging.clusterLogging[1].types", containsInAnyOrder("authenticator", "controllerManager", "scheduler")); + } + + @Test + @Order(2) + void describeClusterReturnsEncryptionConfigAndLoggingInWireResponse() { + given().contentType(JSON) + .when().get("/clusters/" + CLUSTER_WITH_ENC_LOG) + .then().statusCode(200) + .body("cluster.name", equalTo(CLUSTER_WITH_ENC_LOG)) + .body("cluster.encryptionConfig", hasSize(1)) + .body("cluster.encryptionConfig[0].resources", hasSize(1)) + .body("cluster.encryptionConfig[0].resources[0]", equalTo("secrets")) + .body("cluster.encryptionConfig[0].provider.keyArn", equalTo(KMS_KEY_ARN)) + .body("cluster.logging.clusterLogging", hasSize(2)) + .body("cluster.logging.clusterLogging[0].enabled", equalTo(true)) + .body("cluster.logging.clusterLogging[0].types", containsInAnyOrder("api", "audit")) + .body("cluster.logging.clusterLogging[1].enabled", equalTo(false)) + .body("cluster.logging.clusterLogging[1].types", containsInAnyOrder("authenticator", "controllerManager", "scheduler")); + } + + @Test + @Order(3) + void deleteClusterWithEncryptionAndLoggingCleansUp() { + given().contentType(JSON) + .when().delete("/clusters/" + CLUSTER_WITH_ENC_LOG) + .then().statusCode(200); + } + + @Test + @Order(4) + void createClusterWithoutEncryptionConfigOrLoggingOmitsEncryptionConfigAndPopulatesDefaultLogging() { + String payload = "{" + + "\"name\":\"" + CLUSTER_DEFAULT + "\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"" + + "}"; + + given().contentType(JSON) + .body(payload) + .when().post("/clusters") + .then().statusCode(200) + .body("cluster.name", equalTo(CLUSTER_DEFAULT)) + .body("cluster.encryptionConfig", nullValue()) + .body("cluster.logging.clusterLogging", hasSize(1)) + .body("cluster.logging.clusterLogging[0].enabled", equalTo(false)) + .body("cluster.logging.clusterLogging[0].types", + containsInAnyOrder("api", "audit", "authenticator", "controllerManager", "scheduler")); + } + + @Test + @Order(5) + void describeClusterWithoutEncryptionConfigOmitsEncryptionConfigAndReturnsDefaultLogging() { + given().contentType(JSON) + .when().get("/clusters/" + CLUSTER_DEFAULT) + .then().statusCode(200) + .body("cluster.name", equalTo(CLUSTER_DEFAULT)) + .body("cluster.encryptionConfig", nullValue()) + .body("cluster.logging.clusterLogging", hasSize(1)) + .body("cluster.logging.clusterLogging[0].enabled", equalTo(false)) + .body("cluster.logging.clusterLogging[0].types", + containsInAnyOrder("api", "audit", "authenticator", "controllerManager", "scheduler")); + } + + @Test + @Order(6) + void deleteClusterDefaultCleansUp() { + given().contentType(JSON) + .when().delete("/clusters/" + CLUSTER_DEFAULT) + .then().statusCode(200); + } + + @Test + @Order(7) + void createClusterWithInvalidLogTypeReturns400() { + String payload = "{" + + "\"name\":\"it-invalid-log\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"," + + "\"logging\":{" + + " \"clusterLogging\":[{" + + " \"types\":[\"invalidLogType\"]," + + " \"enabled\":true" + + " }]" + + "}" + + "}"; + + given().contentType(JSON) + .body(payload) + .when().post("/clusters") + .then().statusCode(400) + .body("message", equalTo("'invalidLogType' is not a valid log type")); + } + + @Test + @Order(8) + void createClusterWithInvalidEncryptionResourcesReturns400() { + String payload = "{" + + "\"name\":\"it-invalid-enc-res\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"," + + "\"encryptionConfig\":[{" + + " \"resources\":[\"configmaps\"]," + + " \"provider\":{\"keyArn\":\"" + KMS_KEY_ARN + "\"}" + + "}]" + + "}"; + + given().contentType(JSON) + .body(payload) + .when().post("/clusters") + .then().statusCode(400) + .body("message", equalTo("Invalid k8s resource and provider for encryption")); + } + + @Test + @Order(9) + void createClusterWithMissingEncryptionKeyArnReturns400() { + String payload = "{" + + "\"name\":\"it-invalid-enc-key\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"," + + "\"encryptionConfig\":[{" + + " \"resources\":[\"secrets\"]," + + " \"provider\":{\"keyArn\":\"\"}" + + "}]" + + "}"; + + given().contentType(JSON) + .body(payload) + .when().post("/clusters") + .then().statusCode(400) + .body("message", equalTo("Invalid k8s resource and provider for encryption")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java index 3859201232..0c692476d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java @@ -23,12 +23,16 @@ import io.github.hectorvent.floci.services.eks.model.OidcIdentity; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest; import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest; +import io.github.hectorvent.floci.services.eks.model.EncryptionConfig; import io.github.hectorvent.floci.services.eks.model.FargateProfile; import io.github.hectorvent.floci.services.eks.model.FargateProfileStatus; import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.eks.model.LogSetup; +import io.github.hectorvent.floci.services.eks.model.Logging; import io.github.hectorvent.floci.services.eks.model.Nodegroup; import io.github.hectorvent.floci.services.eks.model.NodegroupScalingConfig; import io.github.hectorvent.floci.services.eks.model.NodegroupStatus; +import io.github.hectorvent.floci.services.eks.model.Provider; import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -1518,4 +1522,229 @@ class EksServiceTest { boolean leaked = allSgs.stream().anyMatch(sg -> sg.getGroupName().startsWith("eks-cluster-sg-cluster-tag-fail-")); assertFalse(leaked, "Cluster security group should have been deleted when tagging failed"); } + + private CreateClusterRequest createTestClusterRequest(String name) { + CreateClusterRequest req = new CreateClusterRequest(); + req.setName(name); + req.setRoleArn("arn:aws:iam::000000000000:role/eks-role"); + req.setVersion("1.29"); + return req; + } + + @Test + void createClusterWithEncryptionConfigAndLogging() { + CreateClusterRequest req = createTestClusterRequest("enc-log-cluster"); + req.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("secrets"), new Provider("arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012")) + )); + req.setLogging(new Logging(List.of( + new LogSetup(List.of("api", "audit"), true), + new LogSetup(List.of("authenticator", "controllerManager", "scheduler"), false) + ))); + + Cluster created = eksService.createCluster(req); + assertNotNull(created.getEncryptionConfig()); + assertEquals(1, created.getEncryptionConfig().size()); + assertEquals(List.of("secrets"), created.getEncryptionConfig().getFirst().getResources()); + assertEquals("arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012", + created.getEncryptionConfig().getFirst().getProvider().getKeyArn()); + + assertNotNull(created.getLogging()); + List logSetups = created.getLogging().getClusterLogging(); + assertEquals(2, logSetups.size()); + assertEquals(List.of("api", "audit"), logSetups.get(0).getTypes()); + assertTrue(logSetups.get(0).getEnabled()); + assertEquals(List.of("authenticator", "controllerManager", "scheduler"), logSetups.get(1).getTypes()); + assertFalse(logSetups.get(1).getEnabled()); + + Cluster described = eksService.describeCluster("enc-log-cluster"); + assertEquals(created.getEncryptionConfig(), described.getEncryptionConfig()); + assertEquals(created.getLogging(), described.getLogging()); + } + + @Test + void createClusterWithoutEncryptionConfigOrLoggingUsesDefaults() { + CreateClusterRequest req = createTestClusterRequest("default-cluster"); + + Cluster created = eksService.createCluster(req); + assertNull(created.getEncryptionConfig()); + + assertNotNull(created.getLogging()); + List logSetups = created.getLogging().getClusterLogging(); + assertEquals(1, logSetups.size()); + assertEquals(List.of("api", "audit", "authenticator", "controllerManager", "scheduler"), + logSetups.getFirst().getTypes()); + assertFalse(logSetups.getFirst().getEnabled()); + + Cluster described = eksService.describeCluster("default-cluster"); + assertNull(described.getEncryptionConfig()); + assertNotNull(described.getLogging()); + assertEquals(logSetups, described.getLogging().getClusterLogging()); + } + + @Test + void createClusterWithPartiallyEnabledLoggingSplitsEntries() { + CreateClusterRequest req = createTestClusterRequest("partial-log-cluster"); + req.setLogging(new Logging(List.of( + new LogSetup(List.of("authenticator", "api"), true) + ))); + + Cluster created = eksService.createCluster(req); + assertNotNull(created.getLogging()); + List logSetups = created.getLogging().getClusterLogging(); + assertEquals(2, logSetups.size()); + assertEquals(List.of("api", "authenticator"), logSetups.get(0).getTypes()); + assertTrue(logSetups.get(0).getEnabled()); + assertEquals(List.of("audit", "controllerManager", "scheduler"), logSetups.get(1).getTypes()); + assertFalse(logSetups.get(1).getEnabled()); + } + + @Test + void createClusterWithInvalidLogTypeThrowsInvalidParameterException() { + CreateClusterRequest req = createTestClusterRequest("invalid-log-cluster"); + req.setLogging(new Logging(List.of( + new LogSetup(List.of("nonexistentLogType"), true) + ))); + + AwsException ex = assertThrows(AwsException.class, () -> eksService.createCluster(req)); + assertEquals("InvalidParameterException", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void createClusterWithInvalidEncryptionResourcesThrowsInvalidParameterException() { + CreateClusterRequest req1 = createTestClusterRequest("invalid-enc-res-1"); + req1.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("configmaps"), new Provider("arn:aws:kms:us-east-1:000000000000:key/12345678")) + )); + AwsException ex1 = assertThrows(AwsException.class, () -> eksService.createCluster(req1)); + assertEquals("InvalidParameterException", ex1.getErrorCode()); + assertEquals(400, ex1.getHttpStatus()); + + CreateClusterRequest req2 = createTestClusterRequest("invalid-enc-res-2"); + req2.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("Secrets"), new Provider("arn:aws:kms:us-east-1:000000000000:key/12345678")) + )); + AwsException ex2 = assertThrows(AwsException.class, () -> eksService.createCluster(req2)); + assertEquals("InvalidParameterException", ex2.getErrorCode()); + assertEquals(400, ex2.getHttpStatus()); + } + + @Test + void createClusterWithMultipleEncryptionConfigsThrowsInvalidParameterException() { + CreateClusterRequest req = createTestClusterRequest("multiple-enc-cluster"); + req.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("secrets"), new Provider("arn:aws:kms:us-east-1:000000000000:key/1")), + new EncryptionConfig(List.of("secrets"), new Provider("arn:aws:kms:us-east-1:000000000000:key/2")) + )); + AwsException ex = assertThrows(AwsException.class, () -> eksService.createCluster(req)); + assertEquals("InvalidParameterException", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void createClusterWithMissingEncryptionKeyArnThrowsInvalidParameterException() { + CreateClusterRequest req1 = createTestClusterRequest("missing-keyarn-1"); + req1.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("secrets"), null) + )); + AwsException ex1 = assertThrows(AwsException.class, () -> eksService.createCluster(req1)); + assertEquals("InvalidParameterException", ex1.getErrorCode()); + assertEquals(400, ex1.getHttpStatus()); + + CreateClusterRequest req2 = createTestClusterRequest("missing-keyarn-2"); + req2.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("secrets"), new Provider("")) + )); + AwsException ex2 = assertThrows(AwsException.class, () -> eksService.createCluster(req2)); + assertEquals("InvalidParameterException", ex2.getErrorCode()); + assertEquals(400, ex2.getHttpStatus()); + } + + @Test + void backfillLoggingPopulatesDefaultLoggingForPreExistingClusters() { + StorageBackend rawClusters = new InMemoryStorage<>(); + AccountAwareStorageBackend clusterStore = + new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"); + + Cluster legacyCluster = new Cluster(); + legacyCluster.setName("legacy-eks"); + legacyCluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/legacy-eks"); + legacyCluster.setAccountId("000000000000"); + legacyCluster.setStatus(ClusterStatus.ACTIVE); + legacyCluster.setLogging(null); + legacyCluster.setEncryptionConfig(null); + clusterStore.putForAccount("000000000000", "legacy-eks", legacyCluster); + + StorageFactory storageFactory = fixedStorageFactory(clusterStore); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + EksService service = new EksService(storageFactory, testConfig(true), regionResolver, null, + realEc2Service(), new EksOidcService(fixedStorageFactory(new InMemoryStorage()), new ObjectMapper()), mock(EksAccessEntryService.class)); + + assertDoesNotThrow(service::init); + + Cluster described = service.describeCluster("legacy-eks"); + assertNotNull(described.getLogging()); + assertEquals(1, described.getLogging().getClusterLogging().size()); + assertEquals(List.of("api", "audit", "authenticator", "controllerManager", "scheduler"), + described.getLogging().getClusterLogging().getFirst().getTypes()); + assertFalse(described.getLogging().getClusterLogging().getFirst().getEnabled()); + assertNull(described.getEncryptionConfig()); + } + + @Test + void backfillLoggingPreservesExistingLogging() { + StorageBackend rawClusters = new InMemoryStorage<>(); + AccountAwareStorageBackend clusterStore = + new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"); + + Cluster existingCluster = new Cluster(); + existingCluster.setName("custom-logging-eks"); + existingCluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/custom-logging-eks"); + existingCluster.setAccountId("000000000000"); + existingCluster.setStatus(ClusterStatus.ACTIVE); + Logging customLogging = new Logging(List.of(new LogSetup(List.of("api"), true))); + existingCluster.setLogging(customLogging); + clusterStore.putForAccount("000000000000", "custom-logging-eks", existingCluster); + + StorageFactory storageFactory = fixedStorageFactory(clusterStore); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + EksService service = new EksService(storageFactory, testConfig(true), regionResolver, null, + realEc2Service(), new EksOidcService(fixedStorageFactory(new InMemoryStorage()), new ObjectMapper()), mock(EksAccessEntryService.class)); + + assertDoesNotThrow(service::init); + + Cluster described = service.describeCluster("custom-logging-eks"); + assertEquals(customLogging, described.getLogging()); + } + + @Test + void restartRoundTripPreservesEncryptionConfigAndLogging() { + StorageBackend rawClusters = new InMemoryStorage<>(); + AccountAwareStorageBackend clusterStore = + new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"); + StorageFactory storageFactory = fixedStorageFactory(clusterStore); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + + EksService service1 = new EksService(storageFactory, testConfig(true), regionResolver, null, + realEc2Service(), new EksOidcService(fixedStorageFactory(new InMemoryStorage()), new ObjectMapper()), mock(EksAccessEntryService.class)); + service1.init(); + + CreateClusterRequest req = createTestClusterRequest("restart-cluster"); + req.setEncryptionConfig(List.of( + new EncryptionConfig(List.of("secrets"), new Provider("arn:aws:kms:us-east-1:000000000000:key/persist-key")) + )); + req.setLogging(new Logging(List.of( + new LogSetup(List.of("api", "audit"), true) + ))); + Cluster created = service1.createCluster(req); + + EksService service2 = new EksService(storageFactory, testConfig(true), regionResolver, null, + realEc2Service(), new EksOidcService(fixedStorageFactory(new InMemoryStorage()), new ObjectMapper()), mock(EksAccessEntryService.class)); + service2.init(); + + Cluster described = service2.describeCluster("restart-cluster"); + assertEquals(created.getEncryptionConfig(), described.getEncryptionConfig()); + assertEquals(created.getLogging(), described.getLogging()); + } }