From 55bb5c0f6eb7f747f1e0b4cde3b8d2245d17cf6f Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:17:46 +0300 Subject: [PATCH] fix(cloudformation): clear dropped descriptions and the trail key prefix (#7884) --- docs/services/cloudformation.md | 13 +- .../CloudTrailCfnProvisioner.java | 3 + .../CognitoUserPoolGroupCfnProvisioner.java | 3 + .../LambdaVersionAliasCfnProvisioner.java | 3 + .../SecretsManagerCfnProvisioner.java | 3 + .../cloudtrail/CloudTrailService.java | 69 ++++++--- .../aws/services/cognito/CognitoService.java | 27 +++- .../aws/services/lambda/LambdaService.java | 28 +++- .../secretsmanager/SecretsManagerService.java | 39 +++-- ...rmationCloudTrailTrailIntegrationTest.java | 122 +++++++++++++++ ...onCognitoUserPoolGroupIntegrationTest.java | 114 ++++++++++++++ ...mationLambdaAddressingIntegrationTest.java | 144 ++++++++++++++++++ ...onSecretsManagerSecretIntegrationTest.java | 122 +++++++++++++++ .../CloudTrailCfnProvisionerTest.java | 103 ++++++++++++- ...ognitoUserPoolGroupCfnProvisionerTest.java | 125 ++++++++++++++- .../LambdaVersionAliasCfnProvisionerTest.java | 138 +++++++++++++++-- .../provisioners/ProvisionContexts.java | 43 ++++++ .../SecretsManagerCfnProvisionerTest.java | 104 +++++++++++-- .../cloudtrail/CloudTrailServiceTest.java | 120 +++++++++++++++ .../services/cognito/CognitoServiceTest.java | 87 +++++++++++ .../services/lambda/LambdaServiceTest.java | 102 +++++++++++++ .../SecretsManagerServiceTest.java | 111 ++++++++++++++ .../io/floci/aws/testing/CfnRequests.java | 16 ++ .../resources/cloudformation/drop-policy.tsv | 27 ++++ 24 files changed, 1594 insertions(+), 72 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudTrailTrailIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecretsManagerSecretIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java create mode 100644 src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 1a9289afef..2fbb7b44bb 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -765,7 +765,8 @@ regenerates it from AWS's published schemas, and `cfn-schema-drift.yml` compares A property the previous template declared and the new template drops is cleared on `UpdateStack`, goes back to its create default, or is kept, on the AppSync resources, the EC2 networking types (`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), an -`AWS::ApiGatewayV2::Stage`, an `AWS::EC2::Instance` and an `AWS::ECS::Service`. Kept: required members +`AWS::ApiGatewayV2::Stage`, an `AWS::EC2::Instance`, an `AWS::ECS::Service`, an `AWS::Lambda::Alias`, an +`AWS::SecretsManager::Secret`, an `AWS::Cognito::UserPoolGroup` and an `AWS::CloudTrail::Trail`. Kept: required members (`AuthenticationType`, `Type`, a function's `DataSourceName`), a data source's and a function's `Name`, an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resolver's `DataSourceName`, a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s `StageName` and an @@ -778,11 +779,15 @@ their defaults, and the instance profile it supplied is disassociated. A service template clears it; a failed stabilisation puts the prior values back, and a deployment configuration the service did not have goes back to none. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped. +An `Alias`'s, a `Secret`'s and a `UserPoolGroup`'s dropped `Description` and a `Trail`'s dropped +`S3KeyPrefix` are cleared. A dropped `RoutingConfig` removes the alias weights. The other members of +those four types are kept or create-only when dropped, as the drop policy table lists them, except a +`Secret`'s `Tags`, which every update drives to the template. An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are not cleared either. -A property the stack never declared keeps the value set outside it, with one exception: a GraphQL API's -`Tags` and `EnvironmentVariables`, which every update drives to the template. The table says so on -those rows. The three `NatGateway` `Secondary*` properties count as one +A property the stack never declared keeps the value set outside it, with these exceptions, which every +update drives to the template: a GraphQL API's `Tags` and `EnvironmentVariables`, a Secret's `Tags` and +a Lambda alias's `RoutingConfig`. The table says so on those rows. The three `NatGateway` `Secondary*` properties count as one address set: when the new or the previous template declares any of them, an update brings all three to the template. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java index 20b969bfaf..1e626ff287 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java @@ -70,6 +70,9 @@ public class CloudTrailCfnProvisioner implements CfnResourceProvisioner { trail = trailService.updateTrail(ctx.region(), previousPhysicalId, s3BucketName, s3KeyPrefix, snsTopicName, includeGlobalServiceEvents, isMultiRegionTrail, enableLogFileValidation, isOrganizationTrail); + if (s3KeyPrefix == null && ctx.droppedProperties(props).contains("S3KeyPrefix")) { + trail = trailService.replaceTrailS3KeyPrefix(ctx.region(), previousPhysicalId, null); + } applySelectors(resolved, ctx.region(), previousPhysicalId); if (resolved.has("IsLogging")) { if (resolved.path("IsLogging").asBoolean()) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java index 49b13613b4..d0ddf1464d 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java @@ -95,6 +95,9 @@ public class CognitoUserPoolGroupCfnProvisioner implements CfnResourceProvisione cognitoService.createGroup(userPoolId, groupName, description, precedence, roleArn); } else { cognitoService.updateGroup(userPoolId, groupName, description, precedence, roleArn); + if (description == null && ctx.droppedProperties(props).contains("Description")) { + cognitoService.replaceGroupDescription(userPoolId, groupName, null); + } } r.setPhysicalId(groupName); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java index 238af6ddfd..40b6a04a1a 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java @@ -151,6 +151,9 @@ public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisioner // LambdaService#updateAlias while null keeps what is there. alias = lambdaService.updateAlias(ctx.region(), functionName, aliasName, functionVersion, description, routingConfig != null ? routingConfig : Map.of()); + if (description == null && ctx.droppedProperties(props).contains("Description")) { + alias = lambdaService.replaceAliasDescription(ctx.region(), functionName, aliasName, null); + } } r.setPhysicalId(alias.getAliasArn()); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java index 9deb725791..8d76d6e918 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java @@ -184,6 +184,9 @@ public class SecretsManagerCfnProvisioner implements CfnResourceProvisioner { String region = ctx.region(); String arn = prior.getArn(); Secret secret = secretsManagerService.updateSecret(arn, description, kmsKeyId, region); + if (description == null && ctx.droppedProperties(props).contains("Description")) { + secret = secretsManagerService.replaceSecretDescription(arn, null, region); + } String secretString = ctx.resolveOptional(props, "SecretString"); if (secretString != null && !secretString.equals(currentValue(arn, region))) { secretsManagerService.putSecretValue(arn, secretString, null, null, region, null); diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java index 38413e33ca..954cdea3a1 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java @@ -187,35 +187,66 @@ public class CloudTrailService { Boolean includeGlobalServiceEvents, Boolean isMultiRegionTrail, Boolean enableLogFileValidation, Boolean isOrganizationTrail, String kmsKeyId, String cloudWatchLogsLogGroupArn, String cloudWatchLogsRoleArn) { + return rewriteTrail(region, trailNameOrArn, existing -> { + Trail updated = withSettings(existing, false, s3KeyPrefix, s3BucketName, snsTopicArn, + includeGlobalServiceEvents, isMultiRegionTrail, enableLogFileValidation, isOrganizationTrail, + kmsKeyId, cloudWatchLogsLogGroupArn, cloudWatchLogsRoleArn); + validateCloudWatchLogs(updated.cloudWatchLogsLogGroupArn(), updated.cloudWatchLogsRoleArn()); + return updated; + }); + } + + /** + * Writes the S3 key prefix exactly as given, null included, which {@link #updateTrail} reads as + * "keep". Only a CloudFormation update that drops the prefix calls it. + */ + public Trail replaceTrailS3KeyPrefix(String region, String trailNameOrArn, String s3KeyPrefix) { + return rewriteTrail(region, trailNameOrArn, existing -> withSettings(existing, true, s3KeyPrefix, + null, null, null, null, null, null, null, null, null)); + } + + /** Reads the stored trail under its lock, stores what {@code change} returns for it, and returns that. */ + private Trail rewriteTrail(String region, String trailNameOrArn, Function change) { Trail resolved = findTrailOrThrow(region, trailNameOrArn); String key = regionKey(resolved.homeRegion(), resolved.name()); return withTrailLock(key, () -> { CloudTrailEntry entry = store.get(key).orElseThrow(() -> new AwsException( "TrailNotFoundException", "Unknown trail: " + trailNameOrArn, 400)); - Trail existing = entry.trail(); - Trail updated = new Trail( - existing.name(), - existing.trailArn(), - s3BucketName != null ? s3BucketName : existing.s3BucketName(), - s3KeyPrefix != null ? s3KeyPrefix : existing.s3KeyPrefix(), - snsTopicArn != null ? snsTopicArn : existing.snsTopicArn(), - includeGlobalServiceEvents != null ? includeGlobalServiceEvents : existing.includeGlobalServiceEvents(), - isMultiRegionTrail != null ? isMultiRegionTrail : existing.isMultiRegionTrail(), - existing.homeRegion(), - enableLogFileValidation != null ? enableLogFileValidation : existing.logFileValidationEnabled(), - existing.hasCustomEventSelectors(), - existing.hasInsightSelectors(), - isOrganizationTrail != null ? isOrganizationTrail : existing.isOrganizationTrail(), - kmsKeyId != null ? blankToNull(kmsKeyId) : existing.kmsKeyId(), - cloudWatchLogsLogGroupArn != null - ? blankToNull(cloudWatchLogsLogGroupArn) : existing.cloudWatchLogsLogGroupArn(), - cloudWatchLogsRoleArn != null ? blankToNull(cloudWatchLogsRoleArn) : existing.cloudWatchLogsRoleArn()); - validateCloudWatchLogs(updated.cloudWatchLogsLogGroupArn(), updated.cloudWatchLogsRoleArn()); + Trail updated = change.apply(entry.trail()); store.put(key, entry.withTrail(updated)); return updated; }); } + /** + * {@code existing} with each non-null setting replaced; an empty KMS or CloudWatch Logs value removes + * that setting. {@code replacePrefix} writes {@code s3KeyPrefix} as given, null included. + */ + private static Trail withSettings(Trail existing, boolean replacePrefix, String s3KeyPrefix, + String s3BucketName, String snsTopicArn, + Boolean includeGlobalServiceEvents, Boolean isMultiRegionTrail, + Boolean enableLogFileValidation, Boolean isOrganizationTrail, + String kmsKeyId, String cloudWatchLogsLogGroupArn, + String cloudWatchLogsRoleArn) { + return new Trail( + existing.name(), + existing.trailArn(), + s3BucketName != null ? s3BucketName : existing.s3BucketName(), + replacePrefix || s3KeyPrefix != null ? s3KeyPrefix : existing.s3KeyPrefix(), + snsTopicArn != null ? snsTopicArn : existing.snsTopicArn(), + includeGlobalServiceEvents != null ? includeGlobalServiceEvents : existing.includeGlobalServiceEvents(), + isMultiRegionTrail != null ? isMultiRegionTrail : existing.isMultiRegionTrail(), + existing.homeRegion(), + enableLogFileValidation != null ? enableLogFileValidation : existing.logFileValidationEnabled(), + existing.hasCustomEventSelectors(), + existing.hasInsightSelectors(), + isOrganizationTrail != null ? isOrganizationTrail : existing.isOrganizationTrail(), + kmsKeyId != null ? blankToNull(kmsKeyId) : existing.kmsKeyId(), + cloudWatchLogsLogGroupArn != null + ? blankToNull(cloudWatchLogsLogGroupArn) : existing.cloudWatchLogsLogGroupArn(), + cloudWatchLogsRoleArn != null ? blankToNull(cloudWatchLogsRoleArn) : existing.cloudWatchLogsRoleArn()); + } + public List describeTrails(String region, List trailNameOrArnList) { if (trailNameOrArnList == null || trailNameOrArnList.isEmpty()) { List results = new ArrayList<>(); diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoService.java b/src/main/java/io/floci/aws/services/cognito/CognitoService.java index 9e9f99677c..699d46e231 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoService.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoService.java @@ -102,6 +102,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; import java.util.regex.Pattern; import static io.floci.aws.core.common.ReservedTags.rejectUnknownReservedTags; @@ -3441,13 +3442,31 @@ public class CognitoService implements ResourceProvider { public CognitoGroup updateGroup(String userPoolId, String groupName, String description, Integer precedence, String roleArn) { + CognitoGroup group = rewriteGroup(userPoolId, groupName, stored -> { + if (description != null) stored.setDescription(description); + if (precedence != null) stored.setPrecedence(precedence); + if (roleArn != null) stored.setRoleArn(roleArn); + }); + LOG.infov("Updated Cognito group: {0} in pool {1}", groupName, userPoolId); + return group; + } + + /** + * Writes the group description exactly as given, null included, which {@link #updateGroup} reads + * as "keep". Only a CloudFormation update that drops the description calls it. + */ + public CognitoGroup replaceGroupDescription(String userPoolId, String groupName, String description) { + CognitoGroup group = rewriteGroup(userPoolId, groupName, stored -> stored.setDescription(description)); + LOG.infov("Replaced Cognito group description: {0} in pool {1}", groupName, userPoolId); + return group; + } + + /** Reads the stored group, applies {@code change} to it, stamps the modification date and stores it. */ + private CognitoGroup rewriteGroup(String userPoolId, String groupName, Consumer change) { CognitoGroup group = getGroup(userPoolId, groupName); - if (description != null) group.setDescription(description); - if (precedence != null) group.setPrecedence(precedence); - if (roleArn != null) group.setRoleArn(roleArn); + change.accept(group); group.setLastModifiedDate(System.currentTimeMillis() / 1000L); groupStore.put(groupKey(userPoolId, groupName), group); - LOG.infov("Updated Cognito group: {0} in pool {1}", groupName, userPoolId); return group; } diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaService.java b/src/main/java/io/floci/aws/services/lambda/LambdaService.java index bc7910e617..9fc86a9f24 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -78,6 +78,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -3306,15 +3307,34 @@ public class LambdaService implements ResourceProvider { public LambdaAlias updateAlias(String region, String functionName, String aliasName, String functionVersion, String description, Map routingConfig) { + return rewriteAlias(region, functionName, aliasName, functionVersion, description, (fn, alias) -> { + warmPool.validateProvisionedAliasUpdate(fn, aliasName, functionVersion); + if (functionVersion != null) alias.setFunctionVersion(functionVersion); + if (description != null) alias.setDescription(description); + if (routingConfig != null) alias.setRoutingConfig(routingConfig.isEmpty() ? null : routingConfig); + }); + } + + /** + * Writes the alias description exactly as given, null included, which {@link #updateAlias} reads + * as "keep". Only a CloudFormation update that drops the description calls it. + */ + public LambdaAlias replaceAliasDescription(String region, String functionName, String aliasName, + String description) { + return rewriteAlias(region, functionName, aliasName, null, description, + (fn, alias) -> alias.setDescription(description)); + } + + /** Validates the alias members, then under the function's lock applies {@code change} to the stored alias and saves it. */ + private LambdaAlias rewriteAlias(String region, String functionName, String aliasName, + String functionVersion, String description, + BiConsumer change) { validateAliasName(aliasName); validateAliasMembers(functionVersion, description); LambdaFunction fn = getFunction(region, functionName); synchronized (lockForConcurrencyOp(fn.getFunctionArn())) { LambdaAlias alias = getAlias(region, functionName, aliasName); - warmPool.validateProvisionedAliasUpdate(fn, aliasName, functionVersion); - if (functionVersion != null) alias.setFunctionVersion(functionVersion); - if (description != null) alias.setDescription(description); - if (routingConfig != null) alias.setRoutingConfig(routingConfig.isEmpty() ? null : routingConfig); + change.accept(fn, alias); alias.setLastModifiedDate(System.currentTimeMillis() / 1000L); alias.setRevisionId(UUID.randomUUID().toString()); if (aliasStore != null) aliasStore.save(region, alias); diff --git a/src/main/java/io/floci/aws/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/floci/aws/services/secretsmanager/SecretsManagerService.java index bf8dfe78c1..08f0a0d24e 100644 --- a/src/main/java/io/floci/aws/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/floci/aws/services/secretsmanager/SecretsManagerService.java @@ -440,6 +440,35 @@ public class SecretsManagerService implements ResourceProvider { } public Secret updateSecret(String secretId, String description, String kmsKeyId, String region) { + Secret secret = rewriteSecret(secretId, kmsKeyId, region, stored -> { + if (description != null) { + stored.setDescription(description); + } + if (kmsKeyId != null) { + // AWS: "If you set this to an empty string, Secrets Manager uses the AWS managed key + // aws/secretsmanager" - which DescribeSecret reports by omitting KmsKeyId entirely. + stored.setKmsKeyId(kmsKeyId.isEmpty() ? null : kmsKeyId); + } + }); + LOG.infov("Updated secret metadata: {0}", secret.getName()); + return secret; + } + + /** + * Writes the description exactly as given, null included, which {@link #updateSecret} reads as + * "keep". Only a CloudFormation update that drops the description calls it. + */ + public Secret replaceSecretDescription(String secretId, String description, String region) { + Secret secret = rewriteSecret(secretId, null, region, stored -> stored.setDescription(description)); + LOG.infov("Replaced secret description: {0}", secret.getName()); + return secret; + } + + /** + * Checks the secret and {@code kmsKeyId} (null for none), then under the secret's lock applies + * {@code change} to it, stamps the change date and persists it. + */ + private Secret rewriteSecret(String secretId, String kmsKeyId, String region, Consumer change) { Secret secret = resolveSecret(secretId, region); throwIfPendingDeletion(secret); throwIfReplica(secret); @@ -448,18 +477,10 @@ public class SecretsManagerService implements ResourceProvider { synchronized (lockFor(secret.getArn())) { throwIfManagedRelease(secret.getArn()); - if (description != null) { - secret.setDescription(description); - } - if (kmsKeyId != null) { - // AWS: "If you set this to an empty string, Secrets Manager uses the AWS managed key - // aws/secretsmanager" - which DescribeSecret reports by omitting KmsKeyId entirely. - secret.setKmsKeyId(kmsKeyId.isEmpty() ? null : kmsKeyId); - } + change.accept(secret); secret.setLastChangedDate(Instant.now()); persist(secret, region); - LOG.infov("Updated secret metadata: {0}", secret.getName()); return secret; } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudTrailTrailIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudTrailTrailIntegrationTest.java new file mode 100644 index 0000000000..62c11fbbae --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudTrailTrailIntegrationTest.java @@ -0,0 +1,122 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.services.cloudtrail.CloudTrailService; +import io.floci.aws.services.cloudtrail.model.Trail; +import io.floci.aws.testing.CfnRequests; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** What a stack update does with the {@code S3KeyPrefix} of an {@code AWS::CloudTrail::Trail}. */ +@QuarkusTest +class CloudFormationCloudTrailTrailIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String REGION = "us-east-1"; + + @Inject + CloudTrailService trails; + + @Test + void updateStackThatDropsTheS3KeyPrefixClearsItAndAReAddSetsItAgain() { + String name = "cfn-trail-prefix-drop-" + Long.toString(System.nanoTime(), 36); + deploy("CreateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"orig/\""), + "CREATE_COMPLETE"); + assertEquals("orig/", trails.getTrail(REGION, name).s3KeyPrefix()); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ""), "UPDATE_COMPLETE"); + assertNull(trails.getTrail(REGION, name).s3KeyPrefix()); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"back/\""), + "UPDATE_COMPLETE"); + assertEquals("back/", trails.getTrail(REGION, name).s3KeyPrefix()); + CfnStackWaits.deleteStack(name, CFN_AUTH); + } + + @Test + void updateStackWhoseS3KeyPrefixBecomesNoValueClearsIt() { + String name = "cfn-trail-prefix-novalue-" + Long.toString(System.nanoTime(), 36); + deploy("CreateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"orig/\""), + "CREATE_COMPLETE"); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", + ", \"S3KeyPrefix\": {\"Fn::If\": [\"Off\", {\"Ref\": \"AWS::NoValue\"}, \"orig/\"]}"), + "UPDATE_COMPLETE"); + + assertNull(trails.getTrail(REGION, name).s3KeyPrefix()); + CfnStackWaits.deleteStack(name, CFN_AUTH); + } + + @Test + void changedS3KeyPrefixAppliesAndAnEmptyOneIsStoredAsGivenUntilALaterDropClearsIt() { + String name = "cfn-trail-prefix-empty-" + Long.toString(System.nanoTime(), 36); + deploy("CreateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"orig/\""), + "CREATE_COMPLETE"); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"changed/\""), + "UPDATE_COMPLETE"); + assertEquals("changed/", trails.getTrail(REGION, name).s3KeyPrefix()); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"\""), "UPDATE_COMPLETE"); + assertEquals("", trails.getTrail(REGION, name).s3KeyPrefix()); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ""), "UPDATE_COMPLETE"); + assertNull(trails.getTrail(REGION, name).s3KeyPrefix()); + CfnStackWaits.deleteStack(name, CFN_AUTH); + } + + @Test + void s3KeyPrefixSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() { + String name = "cfn-trail-prefix-outside-" + Long.toString(System.nanoTime(), 36); + deploy("CreateStack", name, trailTemplate(name, "bucket-a", ""), "CREATE_COMPLETE"); + trails.updateTrail(REGION, name, null, "outside/", null, null, null, null, null); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-b", ""), "UPDATE_COMPLETE"); + + Trail stored = trails.getTrail(REGION, name); + assertEquals("outside/", stored.s3KeyPrefix()); + assertEquals("bucket-b", stored.s3BucketName()); + CfnStackWaits.deleteStack(name, CFN_AUTH); + } + + @Test + void droppingTheS3KeyPrefixLeavesTheBucketAndTheTopicAlone() { + String name = "cfn-trail-prefix-others-" + Long.toString(System.nanoTime(), 36); + deploy("CreateStack", name, trailTemplate(name, "bucket-a", ", \"S3KeyPrefix\": \"orig/\""), + "CREATE_COMPLETE"); + String topicBefore = trails.getTrail(REGION, name).snsTopicArn(); + assertNotNull(topicBefore); + + deploy("UpdateStack", name, trailTemplate(name, "bucket-a", ""), "UPDATE_COMPLETE"); + + Trail stored = trails.getTrail(REGION, name); + assertEquals("bucket-a", stored.s3BucketName()); + assertEquals(topicBefore, stored.snsTopicArn()); + CfnStackWaits.deleteStack(name, CFN_AUTH); + } + + private static void deploy(String action, String stackName, String template, String expectedStatus) { + CfnRequests.deploy(action, stackName, template, CFN_AUTH, expectedStatus); + } + + /** A trail named like its stack; {@code extraProperties} is appended to its properties. */ + private static String trailTemplate(String name, String bucket, String extraProperties) { + return """ + { + "Conditions": {"Off": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Trail": { + "Type": "AWS::CloudTrail::Trail", + "Properties": {"TrailName": "%s", "S3BucketName": "%s", "SnsTopicName": "trail-topic"%s} + } + } + } + """.formatted(name, bucket, extraProperties); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java index 4ba4d8ae51..4b1f84702d 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java @@ -1,6 +1,8 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.core.common.XmlParser; +import io.floci.aws.services.cognito.CognitoService; +import io.floci.aws.services.cognito.model.CognitoGroup; import io.floci.aws.testing.CfnRequests; import io.floci.aws.testing.CfnStackWaits; import io.quarkus.test.junit.QuarkusTest; @@ -9,6 +11,7 @@ import io.restassured.config.EncoderConfig; import io.restassured.http.ContentType; import io.restassured.parsing.Parser; import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,10 +28,14 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; @QuarkusTest class CloudFormationCognitoUserPoolGroupIntegrationTest { + @Inject + CognitoService cognitoService; + private static final String CFN_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; @@ -304,6 +311,113 @@ class CloudFormationCognitoUserPoolGroupIntegrationTest { .body("UserPool.SchemaAttributes.find { it.Name == 'custom:email' }", nullValue()); } + @Test + void updateStackThatDropsTheGroupDescriptionClearsItAndAReAddSetsItAgain() { + String stackName = "cfn-cognito-group-desc-drop-" + Long.toString(System.nanoTime(), 36); + String poolId = createStack(stackName, describedGroupTemplate(7, ", \"Description\": \"orig\"")); + assertEquals("orig", cognitoService.getGroup(poolId, "admin").getDescription()); + + updateStack(stackName, describedGroupTemplate(7, "")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + assertNull(cognitoService.getGroup(poolId, "admin").getDescription()); + + updateStack(stackName, describedGroupTemplate(7, ", \"Description\": \"back\"")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + assertEquals("back", cognitoService.getGroup(poolId, "admin").getDescription()); + deleteStackAndWait(stackName); + } + + @Test + void updateStackWhoseGroupDescriptionBecomesNoValueClearsIt() { + String stackName = "cfn-cognito-group-desc-novalue-" + Long.toString(System.nanoTime(), 36); + String poolId = createStack(stackName, describedGroupTemplate(7, ", \"Description\": \"orig\"")); + + updateStack(stackName, describedGroupTemplate(7, + ", \"Description\": {\"Fn::If\": [\"Off\", {\"Ref\": \"AWS::NoValue\"}, \"orig\"]}")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + + assertNull(cognitoService.getGroup(poolId, "admin").getDescription()); + cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admin\"}") + .statusCode(200) + .body("Group.Description", nullValue()); + deleteStackAndWait(stackName); + } + + @Test + void changedGroupDescriptionAppliesAndAnEmptyOneIsStoredAsGivenUntilALaterDropClearsIt() { + String stackName = "cfn-cognito-group-desc-empty-" + Long.toString(System.nanoTime(), 36); + String poolId = createStack(stackName, describedGroupTemplate(7, ", \"Description\": \"orig\"")); + + updateStack(stackName, describedGroupTemplate(7, ", \"Description\": \"changed\"")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + assertEquals("changed", cognitoService.getGroup(poolId, "admin").getDescription()); + + updateStack(stackName, describedGroupTemplate(7, ", \"Description\": \"\"")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + assertEquals("", cognitoService.getGroup(poolId, "admin").getDescription()); + + updateStack(stackName, describedGroupTemplate(7, "")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + assertNull(cognitoService.getGroup(poolId, "admin").getDescription()); + deleteStackAndWait(stackName); + } + + @Test + void groupDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() { + String stackName = "cfn-cognito-group-desc-outside-" + Long.toString(System.nanoTime(), 36); + String poolId = createStack(stackName, describedGroupTemplate(7, "")); + cognitoService.updateGroup(poolId, "admin", "outside", null, null); + + updateStack(stackName, describedGroupTemplate(9, "")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + + CognitoGroup stored = cognitoService.getGroup(poolId, "admin"); + assertEquals("outside", stored.getDescription()); + assertEquals(Integer.valueOf(9), stored.getPrecedence()); + deleteStackAndWait(stackName); + } + + @Test + void droppingTheGroupDescriptionLeavesThePrecedenceAndTheRoleArnAlone() { + String stackName = "cfn-cognito-group-desc-others-" + Long.toString(System.nanoTime(), 36); + String poolId = createStack(stackName, describedGroupTemplate(7, ", \"Description\": \"orig\"")); + + updateStack(stackName, describedGroupTemplate(7, "")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + + CognitoGroup stored = cognitoService.getGroup(poolId, "admin"); + assertEquals(Integer.valueOf(7), stored.getPrecedence()); + assertEquals("arn:aws:iam::000000000000:role/group-admins", stored.getRoleArn()); + deleteStackAndWait(stackName); + } + + /** One pool and an admin group with a fixed role; {@code extraGroupProperties} is appended to its properties. */ + private static String describedGroupTemplate(int precedence, String extraGroupProperties) { + return """ + { + "Conditions": {"Off": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "UserPool": { + "Type": "AWS::Cognito::UserPool", + "Properties": {"UserPoolName": "cfn-group-desc-pool"} + }, + "AdminGroup": { + "Type": "AWS::Cognito::UserPoolGroup", + "Properties": { + "UserPoolId": { "Ref": "UserPool" }, + "GroupName": "admin", + "Precedence": %d, + "RoleArn": "arn:aws:iam::000000000000:role/group-admins"%s + } + } + }, + "Outputs": { + "PoolId": { "Value": { "Ref": "UserPool" } } + } + } + """.formatted(precedence, extraGroupProperties); + } + /** Creates the stack, asserts it completed, and returns the pool id from its outputs. */ private String createStack(String stackName, String template) { given() diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java index 1d490f4198..16e1f5cdd1 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java @@ -1,12 +1,19 @@ package io.floci.aws.services.cloudformation; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.model.LambdaAlias; +import io.floci.aws.testing.CfnRequests; import io.floci.aws.testing.CfnStackWaits; import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; +import java.util.Map; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * End-to-end check that CloudFormation provisions the Lambda addressing @@ -18,6 +25,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @QuarkusTest class CloudFormationLambdaAddressingIntegrationTest { + @Inject + LambdaService lambdaService; + private static final String CFN_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; @@ -261,4 +271,138 @@ class CloudFormationLambdaAddressingIntegrationTest { // exercises all three delete paths. CfnStackWaits.awaitStackDeleted(stackName); } + + @Test + void updateStackThatDropsTheAliasDescriptionClearsItAndAReAddSetsItAgain() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-alias-desc-drop-" + suffix; + String fnName = "alias-desc-drop-fn-" + suffix; + deploy("CreateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"orig\"", "0.1"), + "CREATE_COMPLETE"); + assertEquals("orig", lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, "", "0.1"), "UPDATE_COMPLETE"); + assertNull(lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"back\"", "0.1"), + "UPDATE_COMPLETE"); + assertEquals("back", lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void updateStackWhoseAliasDescriptionBecomesNoValueClearsIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-alias-desc-novalue-" + suffix; + String fnName = "alias-desc-novalue-fn-" + suffix; + deploy("CreateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"orig\"", "0.1"), + "CREATE_COMPLETE"); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, + ", \"Description\": {\"Fn::If\": [\"Off\", {\"Ref\": \"AWS::NoValue\"}, \"orig\"]}", "0.1"), + "UPDATE_COMPLETE"); + + assertNull(lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void changedAliasDescriptionAppliesAndAnEmptyOneIsStoredAsGivenUntilALaterDropClearsIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-alias-desc-empty-" + suffix; + String fnName = "alias-desc-empty-fn-" + suffix; + deploy("CreateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"orig\"", "0.1"), + "CREATE_COMPLETE"); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"changed\"", "0.1"), + "UPDATE_COMPLETE"); + assertEquals("changed", lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"\"", "0.1"), + "UPDATE_COMPLETE"); + assertEquals("", lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, "", "0.1"), "UPDATE_COMPLETE"); + assertNull(lambdaService.getAlias("us-east-1", fnName, "live").getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void aliasDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-alias-desc-outside-" + suffix; + String fnName = "alias-desc-outside-fn-" + suffix; + deploy("CreateStack", stackName, aliasTemplate(fnName, "", "0.1"), "CREATE_COMPLETE"); + lambdaService.updateAlias("us-east-1", fnName, "live", null, "outside", null); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, "", "0.2"), "UPDATE_COMPLETE"); + + LambdaAlias stored = lambdaService.getAlias("us-east-1", fnName, "live"); + assertEquals("outside", stored.getDescription()); + assertEquals(Map.of("2", 0.2), stored.getRoutingConfig()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void droppingTheAliasDescriptionLeavesTheVersionAndTheRoutingConfigAlone() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-alias-desc-others-" + suffix; + String fnName = "alias-desc-others-fn-" + suffix; + deploy("CreateStack", stackName, aliasTemplate(fnName, ", \"Description\": \"orig\"", "0.1"), + "CREATE_COMPLETE"); + String version = lambdaService.getAlias("us-east-1", fnName, "live").getFunctionVersion(); + + deploy("UpdateStack", stackName, aliasTemplate(fnName, "", "0.1"), "UPDATE_COMPLETE"); + + LambdaAlias stored = lambdaService.getAlias("us-east-1", fnName, "live"); + assertEquals(version, stored.getFunctionVersion()); + assertEquals(Map.of("2", 0.1), stored.getRoutingConfig()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + private static void deploy(String action, String stackName, String template, String expectedStatus) { + CfnRequests.deploy(action, stackName, template, CFN_AUTH, expectedStatus, "CAPABILITY_IAM"); + } + + /** A function, a published version and the alias {@code live}; {@code aliasExtras} is appended to the alias properties. */ + private static String aliasTemplate(String fnName, String aliasExtras, String routingWeight) { + return """ + { + "Conditions": {"Off": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]} + } + }, + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "FunctionName": "%s", + "Runtime": "python3.12", + "Handler": "index.handler", + "Role": {"Fn::GetAtt": ["Role", "Arn"]}, + "Code": {"ZipFile": "def handler(e, c): return 'ok'"} + } + }, + "Ver": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Ref": "Fn"}} + }, + "Live": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "FunctionName": {"Ref": "Fn"}, + "Name": "live", + "FunctionVersion": {"Fn::GetAtt": ["Ver", "Version"]}, + "RoutingConfig": {"AdditionalVersionWeights": [ + {"FunctionVersion": "2", "FunctionWeight": %s}]}%s + } + } + } + } + """.formatted(fnName, routingWeight, aliasExtras); + } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecretsManagerSecretIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecretsManagerSecretIntegrationTest.java new file mode 100644 index 0000000000..cc0873ba28 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecretsManagerSecretIntegrationTest.java @@ -0,0 +1,122 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.services.secretsmanager.model.Secret; +import io.floci.aws.testing.CfnRequests; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** What a stack update does with the {@code Description} of an {@code AWS::SecretsManager::Secret}. */ +@QuarkusTest +class CloudFormationSecretsManagerSecretIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String REGION = "us-east-1"; + + @Inject + SecretsManagerService secrets; + + @Test + void updateStackThatDropsTheSecretDescriptionClearsItAndAReAddSetsItAgain() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-secret-desc-drop-" + suffix; + String name = "cfn-secret-desc-drop/" + suffix; + deploy("CreateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"orig\""), "CREATE_COMPLETE"); + assertEquals("orig", secrets.describeSecret(name, REGION).getDescription()); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ""), "UPDATE_COMPLETE"); + assertNull(secrets.describeSecret(name, REGION).getDescription()); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"back\""), "UPDATE_COMPLETE"); + assertEquals("back", secrets.describeSecret(name, REGION).getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void updateStackWhoseSecretDescriptionBecomesNoValueClearsIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-secret-desc-novalue-" + suffix; + String name = "cfn-secret-desc-novalue/" + suffix; + deploy("CreateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"orig\""), "CREATE_COMPLETE"); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", + ", \"Description\": {\"Fn::If\": [\"Off\", {\"Ref\": \"AWS::NoValue\"}, \"orig\"]}"), "UPDATE_COMPLETE"); + + assertNull(secrets.describeSecret(name, REGION).getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void changedSecretDescriptionAppliesAndAnEmptyOneIsStoredAsGivenUntilALaterDropClearsIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-secret-desc-empty-" + suffix; + String name = "cfn-secret-desc-empty/" + suffix; + deploy("CreateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"orig\""), "CREATE_COMPLETE"); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"changed\""), + "UPDATE_COMPLETE"); + assertEquals("changed", secrets.describeSecret(name, REGION).getDescription()); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"\""), "UPDATE_COMPLETE"); + assertEquals("", secrets.describeSecret(name, REGION).getDescription()); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ""), "UPDATE_COMPLETE"); + assertNull(secrets.describeSecret(name, REGION).getDescription()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void secretDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-secret-desc-outside-" + suffix; + String name = "cfn-secret-desc-outside/" + suffix; + deploy("CreateStack", stackName, secretTemplate(name, "v1", ""), "CREATE_COMPLETE"); + secrets.updateSecret(name, "outside", null, REGION); + + deploy("UpdateStack", stackName, secretTemplate(name, "v2", ""), "UPDATE_COMPLETE"); + + assertEquals("outside", secrets.describeSecret(name, REGION).getDescription()); + assertEquals("v2", secrets.getSecretValue(name, null, null, REGION).getSecretString()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + @Test + void droppingTheSecretDescriptionLeavesTheSecretValueAlone() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-secret-desc-others-" + suffix; + String name = "cfn-secret-desc-others/" + suffix; + deploy("CreateStack", stackName, secretTemplate(name, "v1", ", \"Description\": \"orig\""), "CREATE_COMPLETE"); + + deploy("UpdateStack", stackName, secretTemplate(name, "v1", ""), "UPDATE_COMPLETE"); + + Secret stored = secrets.describeSecret(name, REGION); + assertEquals(name, stored.getName()); + assertEquals("v1", secrets.getSecretValue(name, null, null, REGION).getSecretString()); + CfnStackWaits.deleteStack(stackName, CFN_AUTH); + } + + private static void deploy(String action, String stackName, String template, String expectedStatus) { + CfnRequests.deploy(action, stackName, template, CFN_AUTH, expectedStatus); + } + + /** A named secret; {@code extraProperties} is appended to its properties. */ + private static String secretTemplate(String name, String value, String extraProperties) { + return """ + { + "Conditions": {"Off": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Secret": { + "Type": "AWS::SecretsManager::Secret", + "Properties": {"Name": "%s", "SecretString": "%s"%s} + } + } + } + """.formatted(name, value, extraProperties); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java index 8a7ef6ca37..e5be1b10a1 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java @@ -1,14 +1,16 @@ package io.floci.aws.services.cloudformation.provisioners; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; -import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.cloudtrail.CloudTrailService; import io.floci.aws.services.cloudtrail.model.EventSelector; import io.floci.aws.services.cloudtrail.model.Trail; +import io.floci.aws.services.iam.IamService; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -16,6 +18,8 @@ import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -156,9 +160,7 @@ class CloudTrailCfnProvisionerTest { } private ProvisionContext context() { - CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); - when(engine.resolveNode(any(JsonNode.class))).thenAnswer(inv -> inv.getArgument(0)); - return new ProvisionContext(engine, "us-east-1", "111122223333", "stack"); + return new ProvisionContext(ProvisionContexts.passthroughEngine(), "us-east-1", "111122223333", "stack"); } private StackResource resource() { @@ -168,4 +170,95 @@ class CloudTrailCfnProvisionerTest { resource.setAttributes(new HashMap<>()); return resource; } + + // --- dropped S3KeyPrefix, against a real in-memory CloudTrailService --- + + private static final String WITH_PREFIX = """ + {"TrailName":"audit","S3BucketName":"dest-bucket","SnsTopicName":"topic-1","S3KeyPrefix":"orig/"} + """; + private static final String WITHOUT_PREFIX = """ + {"TrailName":"audit","S3BucketName":"dest-bucket","SnsTopicName":"topic-1"} + """; + + private CloudTrailService realTrails() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenReturn(AccountAwareStorageBackend.inMemory("111122223333")); + return new CloudTrailService(storageFactory, new RegionResolver("us-east-1", "111122223333"), + mock(IamService.class), new ObjectMapper()); + } + + private StackResource deployTrail(CloudTrailService real, String properties) throws Exception { + StackResource r = resource(); + new CloudTrailCfnProvisioner(real).provision(r, mapper.readTree(properties), context()); + return r; + } + + private void updateTrail(CloudTrailService real, StackResource r, String previous, String current) + throws Exception { + new CloudTrailCfnProvisioner(real).provision(r, mapper.readTree(current), + ProvisionContexts.update("us-east-1", "111122223333", "stack", + r.getPhysicalId(), previous)); + } + + @Test + void s3KeyPrefixDroppedFromTheTemplateIsClearedOnUpdate() throws Exception { + CloudTrailService real = realTrails(); + StackResource r = deployTrail(real, WITH_PREFIX); + assertEquals("orig/", real.getTrail("us-east-1", "audit").s3KeyPrefix()); + + updateTrail(real, r, WITH_PREFIX, WITHOUT_PREFIX); + + assertNull(real.getTrail("us-east-1", "audit").s3KeyPrefix()); + } + + @Test + void changedS3KeyPrefixStillApplies() throws Exception { + CloudTrailService real = realTrails(); + StackResource r = deployTrail(real, WITH_PREFIX); + + updateTrail(real, r, WITH_PREFIX, WITH_PREFIX.replace("orig/", "changed/")); + + assertEquals("changed/", real.getTrail("us-east-1", "audit").s3KeyPrefix()); + } + + @Test + void emptyS3KeyPrefixIsStoredAsGivenAndALaterDropClearsIt() throws Exception { + CloudTrailService real = realTrails(); + StackResource r = deployTrail(real, WITH_PREFIX); + String empty = WITH_PREFIX.replace("\"orig/\"", "\"\""); + + updateTrail(real, r, WITH_PREFIX, empty); + assertEquals("", real.getTrail("us-east-1", "audit").s3KeyPrefix()); + + updateTrail(real, r, empty, WITHOUT_PREFIX); + assertNull(real.getTrail("us-east-1", "audit").s3KeyPrefix()); + } + + @Test + void s3KeyPrefixSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() throws Exception { + CloudTrailService real = realTrails(); + StackResource r = deployTrail(real, WITHOUT_PREFIX); + real.updateTrail("us-east-1", "audit", null, "outside/", null, null, null, null, null); + + updateTrail(real, r, WITHOUT_PREFIX, WITHOUT_PREFIX.replace("dest-bucket", "other-bucket")); + + Trail stored = real.getTrail("us-east-1", "audit"); + assertEquals("outside/", stored.s3KeyPrefix()); + assertEquals("other-bucket", stored.s3BucketName()); + } + + @Test + void droppingTheS3KeyPrefixKeepsTheBucketAndTheTopic() throws Exception { + CloudTrailService real = realTrails(); + StackResource r = deployTrail(real, WITH_PREFIX); + String topicBefore = real.getTrail("us-east-1", "audit").snsTopicArn(); + assertNotNull(topicBefore); + + updateTrail(real, r, WITH_PREFIX, WITHOUT_PREFIX); + + Trail stored = real.getTrail("us-east-1", "audit"); + assertEquals("dest-bucket", stored.s3BucketName()); + assertEquals(topicBefore, stored.snsTopicArn()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java index 4a68661028..796d2ec2b1 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java @@ -1,14 +1,19 @@ package io.floci.aws.services.cloudformation.provisioners; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; -import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.acm.AcmService; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.cognito.CognitoService; +import io.floci.aws.services.cognito.model.CognitoGroup; import org.junit.jupiter.api.Test; +import java.time.Clock; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -20,8 +25,10 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -47,12 +54,8 @@ class CognitoUserPoolGroupCfnProvisionerTest { * has to be modelled there and not only on the resource. */ private ProvisionContext ctx(String priorPhysicalId) { - CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); - when(engine.resolve(any())).thenAnswer(inv -> { - JsonNode node = inv.getArgument(0); - return node == null ? null : node.asText(); - }); - return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + return new ProvisionContext(ProvisionContexts.passthroughEngine(), + "us-east-1", "000000000000", "my-stack", priorPhysicalId); } private ObjectNode props(String userPoolId, String groupName) { @@ -421,4 +424,110 @@ class CognitoUserPoolGroupCfnProvisionerTest { assertEquals("InternalFailure", thrown.getErrorCode()); } + + // --- dropped Description, against a real in-memory CognitoService --- + + private static final String ROLE = "arn:aws:iam::000000000000:role/admins"; + private static final String WITH_DESCRIPTION = """ + {"UserPoolId":"%s","GroupName":"admin","Description":"orig","Precedence":7,"RoleArn":"%s"} + """; + private static final String WITHOUT_DESCRIPTION = """ + {"UserPoolId":"%s","GroupName":"admin","Precedence":7,"RoleArn":"%s"} + """; + + private CognitoService realCognito() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); + return new CognitoService(storageFactory, config, new RegionResolver("us-east-1", "000000000000"), + null, mock(AcmService.class), null, null, null, Clock.systemUTC(), null); + } + + private static String declared(String template, String poolId) { + return template.formatted(poolId, ROLE); + } + + private StackResource deployGroup(CognitoService real, String properties) throws Exception { + StackResource r = resource(null); + new CognitoUserPoolGroupCfnProvisioner(real).provision(r, mapper.readTree(properties), ctx(null)); + return r; + } + + private void updateGroup(CognitoService real, StackResource r, String previous, String current) + throws Exception { + new CognitoUserPoolGroupCfnProvisioner(real).provision(r, mapper.readTree(current), + ProvisionContexts.update("us-east-1", "000000000000", "my-stack", + r.getPhysicalId(), previous)); + } + + @Test + void groupDescriptionDroppedFromTheTemplateIsClearedOnUpdate() throws Exception { + CognitoService real = realCognito(); + String poolId = real.createUserPool(Map.of("PoolName", "drop-pool"), "us-east-1").getId(); + String before = declared(WITH_DESCRIPTION, poolId); + StackResource r = deployGroup(real, before); + assertEquals("orig", real.getGroup(poolId, "admin").getDescription()); + + updateGroup(real, r, before, declared(WITHOUT_DESCRIPTION, poolId)); + + assertNull(real.getGroup(poolId, "admin").getDescription()); + } + + @Test + void changedGroupDescriptionStillApplies() throws Exception { + CognitoService real = realCognito(); + String poolId = real.createUserPool(Map.of("PoolName", "change-pool"), "us-east-1").getId(); + String before = declared(WITH_DESCRIPTION, poolId); + StackResource r = deployGroup(real, before); + + updateGroup(real, r, before, before.replace("orig", "changed")); + + assertEquals("changed", real.getGroup(poolId, "admin").getDescription()); + } + + @Test + void emptyGroupDescriptionIsStoredAsGivenAndALaterDropClearsIt() throws Exception { + CognitoService real = realCognito(); + String poolId = real.createUserPool(Map.of("PoolName", "empty-pool"), "us-east-1").getId(); + String before = declared(WITH_DESCRIPTION, poolId); + StackResource r = deployGroup(real, before); + String empty = before.replace("\"orig\"", "\"\""); + + updateGroup(real, r, before, empty); + assertEquals("", real.getGroup(poolId, "admin").getDescription()); + + updateGroup(real, r, empty, declared(WITHOUT_DESCRIPTION, poolId)); + assertNull(real.getGroup(poolId, "admin").getDescription()); + } + + @Test + void groupDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() throws Exception { + CognitoService real = realCognito(); + String poolId = real.createUserPool(Map.of("PoolName", "outside-pool"), "us-east-1").getId(); + String before = declared(WITHOUT_DESCRIPTION, poolId); + StackResource r = deployGroup(real, before); + real.updateGroup(poolId, "admin", "outside", null, null); + + updateGroup(real, r, before, before.replace("\"Precedence\":7", "\"Precedence\":9")); + + CognitoGroup stored = real.getGroup(poolId, "admin"); + assertEquals("outside", stored.getDescription()); + assertEquals(Integer.valueOf(9), stored.getPrecedence()); + } + + @Test + void droppingTheGroupDescriptionKeepsThePrecedenceAndTheRoleArn() throws Exception { + CognitoService real = realCognito(); + String poolId = real.createUserPool(Map.of("PoolName", "others-pool"), "us-east-1").getId(); + String before = declared(WITH_DESCRIPTION, poolId); + StackResource r = deployGroup(real, before); + + updateGroup(real, r, before, declared(WITHOUT_DESCRIPTION, poolId)); + + CognitoGroup stored = real.getGroup(poolId, "admin"); + assertEquals(Integer.valueOf(7), stored.getPrecedence()); + assertEquals(ROLE, stored.getRoleArn()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java index be38a93355..b877cf7a10 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java @@ -1,23 +1,34 @@ package io.floci.aws.services.cloudformation.provisioners; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; -import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.lambda.LambdaAliasStore; +import io.floci.aws.services.lambda.LambdaConcurrencyLimiter; +import io.floci.aws.services.lambda.LambdaFunctionStore; import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.LambdaTargetResolver; +import io.floci.aws.services.lambda.WarmPool; import io.floci.aws.services.lambda.model.LambdaAlias; import io.floci.aws.services.lambda.model.LambdaFunction; +import io.floci.aws.services.lambda.zip.CodeStore; +import io.floci.aws.services.lambda.zip.ZipExtractor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; @@ -39,14 +50,7 @@ class LambdaVersionAliasCfnProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private ProvisionContext ctx() { - // Scalar properties only: intrinsic resolution (Ref/GetAtt) is the engine's job and is - // covered by its own tests, so a passthrough keeps this a true isolated unit test. - CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); - when(engine.resolve(any())).thenAnswer(inv -> { - JsonNode node = inv.getArgument(0); - return node == null ? null : node.asText(); - }); - return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + return new ProvisionContext(ProvisionContexts.passthroughEngine(), "us-east-1", "000000000000", "my-stack"); } private StackResource resource(String type, String logicalId) { @@ -188,4 +192,118 @@ class LambdaVersionAliasCfnProvisionerTest { provisioner.delete("AWS::Lambda::Alias", "MyFuncAliasproduction-1a2b3c4d", "us-east-1"); verifyNoInteractions(lambda); } + + // --- dropped Description, against a real in-memory LambdaService --- + + private static final String WITH_DESCRIPTION = """ + {"FunctionName":"my-fn","Name":"production","FunctionVersion":"1","Description":"orig", + "RoutingConfig":{"AdditionalVersionWeights":[{"FunctionVersion":"2","FunctionWeight":0.1}]}} + """; + private static final String WITHOUT_DESCRIPTION = """ + {"FunctionName":"my-fn","Name":"production","FunctionVersion":"1", + "RoutingConfig":{"AdditionalVersionWeights":[{"FunctionVersion":"2","FunctionWeight":0.1}]}} + """; + + private LambdaService realLambda() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); + LambdaFunctionStore functionStore = new LambdaFunctionStore(storageFactory); + LambdaAliasStore aliasStore = new LambdaAliasStore(storageFactory); + LambdaService real = new LambdaService(functionStore, null, mock(LambdaConcurrencyLimiter.class), + mock(WarmPool.class), new CodeStore(Path.of("target/test-data/lambda-code")), new ZipExtractor(), + null, new RegionResolver("us-east-1", "000000000000"), null, aliasStore, + new LambdaTargetResolver(functionStore, aliasStore), null, null, null, null, null, + storageFactory, null, null, null, null, new ObjectMapper(), null); + real.createFunction("us-east-1", new HashMap<>(Map.of("FunctionName", "my-fn", "Runtime", "nodejs20.x", + "Role", "arn:aws:iam::000000000000:role/test-role", "Handler", "index.handler", + "Timeout", 10, "MemorySize", 256))); + return real; + } + + private StackResource deployAlias(LambdaService real, String properties) throws Exception { + StackResource r = resource("AWS::Lambda::Alias", "MyFuncAliasproduction"); + new LambdaVersionAliasCfnProvisioner(real).provision(r, mapper.readTree(properties), ctx()); + return r; + } + + private void updateAlias(LambdaService real, StackResource r, String previous, String current) throws Exception { + new LambdaVersionAliasCfnProvisioner(real).provision(r, mapper.readTree(current), + ProvisionContexts.update("us-east-1", "000000000000", "my-stack", + r.getPhysicalId(), previous)); + } + + @Test + void aliasDescriptionDroppedFromTheTemplateIsClearedOnUpdate() throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITH_DESCRIPTION); + assertEquals("orig", real.getAlias("us-east-1", "my-fn", "production").getDescription()); + + updateAlias(real, r, WITH_DESCRIPTION, WITHOUT_DESCRIPTION); + + assertNull(real.getAlias("us-east-1", "my-fn", "production").getDescription()); + } + + @Test + void changedAliasDescriptionStillApplies() throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITH_DESCRIPTION); + + updateAlias(real, r, WITH_DESCRIPTION, WITH_DESCRIPTION.replace("orig", "changed")); + + assertEquals("changed", real.getAlias("us-east-1", "my-fn", "production").getDescription()); + } + + @Test + void emptyAliasDescriptionIsStoredAsGivenAndALaterDropClearsIt() throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITH_DESCRIPTION); + String empty = WITH_DESCRIPTION.replace("\"orig\"", "\"\""); + + updateAlias(real, r, WITH_DESCRIPTION, empty); + assertEquals("", real.getAlias("us-east-1", "my-fn", "production").getDescription()); + + updateAlias(real, r, empty, WITHOUT_DESCRIPTION); + assertNull(real.getAlias("us-east-1", "my-fn", "production").getDescription()); + } + + @Test + void aliasDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITHOUT_DESCRIPTION); + real.updateAlias("us-east-1", "my-fn", "production", null, "outside", null); + + updateAlias(real, r, WITHOUT_DESCRIPTION, WITHOUT_DESCRIPTION.replace("\"1\"", "\"3\"")); + + LambdaAlias stored = real.getAlias("us-east-1", "my-fn", "production"); + assertEquals("outside", stored.getDescription()); + assertEquals("3", stored.getFunctionVersion()); + } + + @Test + void aliasDescriptionDroppedThenSetOutsideTheStackSurvivesALaterUpdateThatStillDoesNotDeclareIt() + throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITH_DESCRIPTION); + updateAlias(real, r, WITH_DESCRIPTION, WITHOUT_DESCRIPTION); + real.updateAlias("us-east-1", "my-fn", "production", null, "outside", null); + + updateAlias(real, r, WITHOUT_DESCRIPTION, WITHOUT_DESCRIPTION.replace("\"1\"", "\"3\"")); + + LambdaAlias stored = real.getAlias("us-east-1", "my-fn", "production"); + assertEquals("outside", stored.getDescription()); + assertEquals("3", stored.getFunctionVersion()); + } + + @Test + void droppingTheAliasDescriptionKeepsTheVersionAndTheRoutingConfig() throws Exception { + LambdaService real = realLambda(); + StackResource r = deployAlias(real, WITH_DESCRIPTION); + + updateAlias(real, r, WITH_DESCRIPTION, WITHOUT_DESCRIPTION); + + LambdaAlias stored = real.getAlias("us-east-1", "my-fn", "production"); + assertEquals("1", stored.getFunctionVersion()); + assertEquals(Map.of("2", 0.1), stored.getRoutingConfig()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java new file mode 100644 index 0000000000..3ace1997c1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContexts.java @@ -0,0 +1,43 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Contexts for provisioner unit tests that need no real intrinsic resolution: a mocked engine that + * hands scalars back as text and nodes back unchanged, and an update context carrying the previous + * template's properties, as the stack hands them over. + */ +final class ProvisionContexts { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private ProvisionContexts() { + } + + /** + * Scalar properties only: intrinsic resolution (Ref/GetAtt) is the engine's job and is covered by + * its own tests, so a passthrough keeps a provisioner test a true isolated unit test. + */ + static CloudFormationTemplateEngine passthroughEngine() { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return engine; + } + + /** An update: the prior physical id and the previous template's properties, as the stack hands them over. */ + static ProvisionContext update(String region, String accountId, String stackName, + String priorPhysicalId, String priorProperties) throws Exception { + return new ProvisionContext(passthroughEngine(), region, accountId, stackName, priorPhysicalId, + event -> {}, MAPPER.readTree(priorProperties)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisionerTest.java index 08bc14222b..fd02f36fc4 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SecretsManagerCfnProvisionerTest.java @@ -1,11 +1,13 @@ package io.floci.aws.services.cloudformation.provisioners; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; -import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.Secret; @@ -17,12 +19,14 @@ import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -43,13 +47,8 @@ class SecretsManagerCfnProvisionerTest { private final ObjectMapper mapper = new ObjectMapper(); private ProvisionContext ctx(String priorPhysicalId) { - CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); - when(engine.resolve(any())).thenAnswer(inv -> { - JsonNode node = inv.getArgument(0); - return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); - }); - when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); - return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); + return new ProvisionContext(ProvisionContexts.passthroughEngine(), + REGION, "000000000000", "my-stack", priorPhysicalId); } private static StackResource resource() { @@ -296,4 +295,91 @@ class SecretsManagerCfnProvisionerTest { eq(REGION)); assertEquals(ARN, r.getPhysicalId()); } + + // --- dropped Description, against a real in-memory SecretsManagerService --- + + private static final String WITH_DESCRIPTION = """ + {"Name":"app/db","SecretString":"v1","Description":"orig","KmsKeyId":"alias/app"} + """; + private static final String WITHOUT_DESCRIPTION = """ + {"Name":"app/db","SecretString":"v1","KmsKeyId":"alias/app"} + """; + + private SecretsManagerService realSecrets() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); + return new SecretsManagerService(storageFactory, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), + new RegionResolver(REGION, "000000000000"), null, new ObjectMapper(), null); + } + + private StackResource deploySecret(SecretsManagerService real, String properties) throws Exception { + StackResource r = resource(); + new SecretsManagerCfnProvisioner(real).provision(r, mapper.readTree(properties), ctx(null)); + return r; + } + + private void updateSecret(SecretsManagerService real, StackResource r, String previous, String current) + throws Exception { + new SecretsManagerCfnProvisioner(real).provision(r, mapper.readTree(current), + ProvisionContexts.update(REGION, "000000000000", "my-stack", + r.getPhysicalId(), previous)); + } + + @Test + void secretDescriptionDroppedFromTheTemplateIsClearedOnUpdate() throws Exception { + SecretsManagerService real = realSecrets(); + StackResource r = deploySecret(real, WITH_DESCRIPTION); + assertEquals("orig", real.describeSecret("app/db", REGION).getDescription()); + + updateSecret(real, r, WITH_DESCRIPTION, WITHOUT_DESCRIPTION); + + assertNull(real.describeSecret("app/db", REGION).getDescription()); + } + + @Test + void changedSecretDescriptionStillApplies() throws Exception { + SecretsManagerService real = realSecrets(); + StackResource r = deploySecret(real, WITH_DESCRIPTION); + + updateSecret(real, r, WITH_DESCRIPTION, WITH_DESCRIPTION.replace("orig", "changed")); + + assertEquals("changed", real.describeSecret("app/db", REGION).getDescription()); + } + + @Test + void emptySecretDescriptionIsStoredAsGivenAndALaterDropClearsIt() throws Exception { + SecretsManagerService real = realSecrets(); + StackResource r = deploySecret(real, WITH_DESCRIPTION); + String empty = WITH_DESCRIPTION.replace("\"orig\"", "\"\""); + + updateSecret(real, r, WITH_DESCRIPTION, empty); + assertEquals("", real.describeSecret("app/db", REGION).getDescription()); + + updateSecret(real, r, empty, WITHOUT_DESCRIPTION); + assertNull(real.describeSecret("app/db", REGION).getDescription()); + } + + @Test + void secretDescriptionSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() throws Exception { + SecretsManagerService real = realSecrets(); + StackResource r = deploySecret(real, WITHOUT_DESCRIPTION); + real.updateSecret("app/db", "outside", null, REGION); + + updateSecret(real, r, WITHOUT_DESCRIPTION, WITHOUT_DESCRIPTION.replace("\"v1\"", "\"v2\"")); + + assertEquals("outside", real.describeSecret("app/db", REGION).getDescription()); + assertEquals("v2", real.getSecretValue("app/db", null, null, REGION).getSecretString()); + } + + @Test + void droppingTheSecretDescriptionKeepsTheValueAndTheKmsKey() throws Exception { + SecretsManagerService real = realSecrets(); + StackResource r = deploySecret(real, WITH_DESCRIPTION); + + updateSecret(real, r, WITH_DESCRIPTION, WITHOUT_DESCRIPTION); + + assertEquals("v1", real.getSecretValue("app/db", null, null, REGION).getSecretString()); + assertEquals("alias/app", real.describeSecret("app/db", REGION).getKmsKeyId()); + } } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java new file mode 100644 index 0000000000..38d5071556 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java @@ -0,0 +1,120 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.cloudtrail.model.Trail; +import io.floci.aws.services.iam.IamService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class CloudTrailServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:trail-topic"; + + private CloudTrailService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)); + service = new CloudTrailService(storageFactory, new RegionResolver(REGION, ACCOUNT), + mock(IamService.class), new ObjectMapper()); + } + + private Trail trailWithPrefix(String name, String prefix) { + return service.createTrail(REGION, name, "trail-bucket", prefix, TOPIC, true, false, false, false); + } + + // --- replaceTrailS3KeyPrefix: a service method that does not exist on main --- + + @Test + void replaceTrailS3KeyPrefixStoresTheGivenValueAndReturnsTheUpdatedTrail() { + trailWithPrefix("replace-set", "old/"); + + Trail returned = service.replaceTrailS3KeyPrefix(REGION, "replace-set", "new/"); + + assertEquals("new/", returned.s3KeyPrefix()); + assertEquals("new/", service.getTrail(REGION, "replace-set").s3KeyPrefix()); + } + + @Test + void replaceTrailS3KeyPrefixWithNullClearsTheStoredValue() { + trailWithPrefix("replace-null", "old/"); + + Trail returned = service.replaceTrailS3KeyPrefix(REGION, "replace-null", null); + + assertNull(returned.s3KeyPrefix()); + assertNull(service.getTrail(REGION, "replace-null").s3KeyPrefix()); + assertNull(service.describeTrails(REGION, List.of("replace-null")).get(0).s3KeyPrefix()); + } + + @Test + void replaceTrailS3KeyPrefixStoresTheEmptyStringAsGiven() { + trailWithPrefix("replace-empty", "old/"); + + service.replaceTrailS3KeyPrefix(REGION, "replace-empty", ""); + + assertEquals("", service.getTrail(REGION, "replace-empty").s3KeyPrefix()); + } + + @Test + void replaceTrailS3KeyPrefixAcceptsTheTrailArn() { + Trail created = trailWithPrefix("replace-arn", "old/"); + + service.replaceTrailS3KeyPrefix(REGION, created.trailArn(), null); + + assertNull(service.getTrail(REGION, "replace-arn").s3KeyPrefix()); + } + + @Test + void replaceTrailS3KeyPrefixLeavesTheBucketAndTheTopicUntouched() { + trailWithPrefix("replace-others", "old/"); + + service.replaceTrailS3KeyPrefix(REGION, "replace-others", null); + + Trail stored = service.getTrail(REGION, "replace-others"); + assertEquals("trail-bucket", stored.s3BucketName()); + assertEquals(TOPIC, stored.snsTopicArn()); + } + + @Test + void replaceTrailS3KeyPrefixOnAnUnknownTrailThrowsWhatUpdateTrailThrows() { + AwsException fromUpdate = assertThrows(AwsException.class, () -> service.updateTrail(REGION, "no-such-trail", + null, "x/", null, null, null, null, null)); + + AwsException fromReplace = assertThrows(AwsException.class, + () -> service.replaceTrailS3KeyPrefix(REGION, "no-such-trail", "x/")); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + } + + // --- direct UpdateTrail without a prefix keeps it: unchanged from main --- + + @Test + void updateTrailWithoutAnS3KeyPrefixKeepsTheStoredPrefix() { + trailWithPrefix("update-keeps", "kept/"); + + service.updateTrail(REGION, "update-keeps", "other-bucket", null, null, null, null, null, null); + + Trail stored = service.getTrail(REGION, "update-keeps"); + assertEquals("kept/", stored.s3KeyPrefix()); + assertEquals("other-bucket", stored.s3BucketName()); + } +} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java index 857ca1a274..e610adf352 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java @@ -7411,4 +7411,91 @@ class CognitoServiceTest { assertEquals(holder.getUsername(), svc.adminGetUser(pool.getId(), "alice@example.com").getUsername()); } } + + // --- replaceGroupDescription: a service method that does not exist on main --- + + private UserPool poolWithGroup(String groupName, String description) { + UserPool pool = service.createUserPool(Map.of("PoolName", "replace-pool-" + groupName), "us-east-1"); + service.createGroup(pool.getId(), groupName, description, 7, "arn:aws:iam::000000000000:role/admins"); + return pool; + } + + @Test + void replaceGroupDescriptionStoresTheGivenValueAndReturnsTheUpdatedGroup() { + UserPool pool = poolWithGroup("set", "old"); + + CognitoGroup returned = service.replaceGroupDescription(pool.getId(), "set", "new"); + + assertEquals("new", returned.getDescription()); + assertEquals("new", service.getGroup(pool.getId(), "set").getDescription()); + } + + @Test + void replaceGroupDescriptionWithNullClearsTheStoredValue() { + UserPool pool = poolWithGroup("nulled", "old"); + + CognitoGroup returned = service.replaceGroupDescription(pool.getId(), "nulled", null); + + assertNull(returned.getDescription()); + assertNull(service.getGroup(pool.getId(), "nulled").getDescription()); + } + + @Test + void replaceGroupDescriptionStoresTheEmptyStringAsGiven() { + UserPool pool = poolWithGroup("blank", "old"); + + service.replaceGroupDescription(pool.getId(), "blank", ""); + + assertEquals("", service.getGroup(pool.getId(), "blank").getDescription()); + } + + @Test + void replaceGroupDescriptionLeavesPrecedenceAndRoleArnUntouched() { + UserPool pool = poolWithGroup("others", "old"); + + service.replaceGroupDescription(pool.getId(), "others", null); + + CognitoGroup stored = service.getGroup(pool.getId(), "others"); + assertEquals(Integer.valueOf(7), stored.getPrecedence()); + assertEquals("arn:aws:iam::000000000000:role/admins", stored.getRoleArn()); + } + + @Test + void replaceGroupDescriptionOnAnUnknownGroupThrowsWhatUpdateGroupThrows() { + UserPool pool = poolWithGroup("known", "old"); + AwsException fromUpdate = assertThrows(AwsException.class, + () -> service.updateGroup(pool.getId(), "absent", "x", null, null)); + + AwsException fromReplace = assertThrows(AwsException.class, + () -> service.replaceGroupDescription(pool.getId(), "absent", "x")); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + } + + @Test + void replaceGroupDescriptionKeepsTheBookkeepingOfUpdateGroup() { + UserPool pool = poolWithGroup("books", "old"); + long longAgo = 1_000L; + service.getGroup(pool.getId(), "books").setLastModifiedDate(longAgo); + assertEquals(longAgo, service.getGroup(pool.getId(), "books").getLastModifiedDate()); + + CognitoGroup returned = service.replaceGroupDescription(pool.getId(), "books", null); + + assertTrue(returned.getLastModifiedDate() > longAgo); + assertTrue(service.getGroup(pool.getId(), "books").getLastModifiedDate() > longAgo); + } + + // --- direct UpdateGroup without a description keeps it: unchanged from main --- + + @Test + void updateGroupWithoutADescriptionKeepsTheStoredDescription() { + UserPool pool = poolWithGroup("update-keeps", "kept"); + + service.updateGroup(pool.getId(), "update-keeps", null, 3, null); + + CognitoGroup stored = service.getGroup(pool.getId(), "update-keeps"); + assertEquals("kept", stored.getDescription()); + assertEquals(Integer.valueOf(3), stored.getPrecedence()); + } } diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaServiceTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaServiceTest.java index c7d4ec818e..d3c14e8111 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaServiceTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaServiceTest.java @@ -3393,4 +3393,106 @@ class LambdaServiceTest { assertEquals(new LambdaService.LoggingSettings("Text", null, null, "/shared/app"), LambdaService.loggingSettings(fn)); } + + private LambdaAlias aliasWithDescription(String functionName, String description) { + service.createFunction(REGION, baseRequest(functionName)); + return service.createAlias(REGION, functionName, "live", "1", description, Map.of("2", 0.1)); + } + + // --- replaceAliasDescription: service methods that do not exist on main --- + + @Test + void replaceAliasDescriptionStoresTheGivenValueAndReturnsTheUpdatedAlias() { + aliasWithDescription("alias-replace-set-fn", "old"); + + LambdaAlias returned = service.replaceAliasDescription(REGION, "alias-replace-set-fn", "live", "new"); + + assertEquals("new", returned.getDescription()); + assertEquals("new", service.getAlias(REGION, "alias-replace-set-fn", "live").getDescription()); + } + + @Test + void replaceAliasDescriptionWithNullClearsTheStoredValue() { + aliasWithDescription("alias-replace-null-fn", "old"); + + LambdaAlias returned = service.replaceAliasDescription(REGION, "alias-replace-null-fn", "live", null); + + assertNull(returned.getDescription()); + assertNull(service.getAlias(REGION, "alias-replace-null-fn", "live").getDescription()); + } + + @Test + void replaceAliasDescriptionStoresTheEmptyStringAsGiven() { + aliasWithDescription("alias-replace-empty-fn", "old"); + + service.replaceAliasDescription(REGION, "alias-replace-empty-fn", "live", ""); + + assertEquals("", service.getAlias(REGION, "alias-replace-empty-fn", "live").getDescription()); + } + + @Test + void replaceAliasDescriptionLeavesVersionAndRoutingUntouched() { + aliasWithDescription("alias-replace-others-fn", "old"); + + service.replaceAliasDescription(REGION, "alias-replace-others-fn", "live", null); + + LambdaAlias stored = service.getAlias(REGION, "alias-replace-others-fn", "live"); + assertEquals("1", stored.getFunctionVersion()); + assertEquals(Map.of("2", 0.1), stored.getRoutingConfig()); + } + + @Test + void replaceAliasDescriptionOnAnUnknownAliasThrowsWhatUpdateAliasThrows() { + service.createFunction(REGION, baseRequest("alias-replace-missing-fn")); + AwsException fromUpdate = assertThrows(AwsException.class, () -> service.updateAlias(REGION, + "alias-replace-missing-fn", "absent", null, "x", null)); + + AwsException fromReplace = assertThrows(AwsException.class, () -> service.replaceAliasDescription(REGION, + "alias-replace-missing-fn", "absent", "x")); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + } + + @Test + void replaceAliasDescriptionOnAnUnknownFunctionThrowsWhatUpdateAliasThrows() { + AwsException fromUpdate = assertThrows(AwsException.class, () -> service.updateAlias(REGION, + "alias-replace-no-such-fn", "live", null, "x", null)); + + AwsException fromReplace = assertThrows(AwsException.class, () -> service.replaceAliasDescription(REGION, + "alias-replace-no-such-fn", "live", "x")); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + } + + @Test + void replaceAliasDescriptionKeepsTheBookkeepingOfUpdateAlias() { + aliasWithDescription("alias-replace-books-fn", "old"); + LambdaAlias stored = service.getAlias(REGION, "alias-replace-books-fn", "live"); + long longAgo = 1_000L; + stored.setLastModifiedDate(longAgo); + assertEquals(longAgo, service.getAlias(REGION, "alias-replace-books-fn", "live").getLastModifiedDate()); + String revisionBefore = stored.getRevisionId(); + + LambdaAlias returned = service.replaceAliasDescription(REGION, "alias-replace-books-fn", "live", null); + + assertNotEquals(revisionBefore, returned.getRevisionId()); + assertTrue(returned.getLastModifiedDate() > longAgo); + assertTrue(service.getAlias(REGION, "alias-replace-books-fn", "live").getLastModifiedDate() > longAgo); + assertNotEquals(revisionBefore, service.getAlias(REGION, "alias-replace-books-fn", "live").getRevisionId()); + } + + // --- direct UpdateAlias without a description keeps it: unchanged from main --- + + @Test + void updateAliasWithoutADescriptionKeepsTheStoredDescription() { + aliasWithDescription("alias-update-keeps-fn", "kept"); + + service.updateAlias(REGION, "alias-update-keeps-fn", "live", "3", null, null); + + LambdaAlias stored = service.getAlias(REGION, "alias-update-keeps-fn", "live"); + assertEquals("kept", stored.getDescription()); + assertEquals("3", stored.getFunctionVersion()); + } } diff --git a/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerServiceTest.java b/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerServiceTest.java index 9f513c99b8..0ab4204066 100644 --- a/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerServiceTest.java +++ b/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerServiceTest.java @@ -21,6 +21,7 @@ import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -1627,4 +1628,114 @@ class SecretsManagerServiceTest { assertEquals(1, service.listSecrets(REGION, null, false).size()); assertEquals(2, service.listSecrets(REGION, null, true).size()); } + + // --- replaceSecretDescription: a service method that does not exist on main --- + + @Test + void replaceSecretDescriptionStoresTheGivenValueAndReturnsTheUpdatedSecret() { + service.createSecret("replace-set", "v1", null, "old", null, null, REGION); + + Secret returned = service.replaceSecretDescription("replace-set", "new", REGION); + + assertEquals("new", returned.getDescription()); + assertEquals("new", service.describeSecret("replace-set", REGION).getDescription()); + } + + @Test + void replaceSecretDescriptionWithNullClearsTheStoredValue() { + service.createSecret("replace-null", "v1", null, "old", null, null, REGION); + + Secret returned = service.replaceSecretDescription("replace-null", null, REGION); + + assertNull(returned.getDescription()); + assertNull(service.describeSecret("replace-null", REGION).getDescription()); + } + + @Test + void replaceSecretDescriptionStoresTheEmptyStringAsGiven() { + service.createSecret("replace-empty", "v1", null, "old", null, null, REGION); + + service.replaceSecretDescription("replace-empty", "", REGION); + + assertEquals("", service.describeSecret("replace-empty", REGION).getDescription()); + } + + @Test + void replaceSecretDescriptionLeavesTheValueAndTheKmsKeyUntouched() { + service.createSecret("replace-others", "the-value", null, "old", "alias/app", null, REGION); + + service.replaceSecretDescription("replace-others", null, REGION); + + assertEquals("the-value", service.getSecretValue("replace-others", null, null, REGION).getSecretString()); + assertEquals("alias/app", service.describeSecret("replace-others", REGION).getKmsKeyId()); + } + + @Test + void replaceSecretDescriptionOnAnUnknownSecretThrowsWhatUpdateSecretThrows() { + AwsException fromUpdate = assertThrows(AwsException.class, + () -> service.updateSecret("no-such-secret", "x", null, REGION)); + + AwsException fromReplace = assertThrows(AwsException.class, + () -> service.replaceSecretDescription("no-such-secret", "x", REGION)); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + } + + @Test + void replaceSecretDescriptionKeepsTheBookkeepingOfUpdateSecret() { + service.createSecret("replace-books", "v1", null, "old", null, null, REGION); + Instant longAgo = Instant.parse("2000-01-01T00:00:00Z"); + service.describeSecret("replace-books", REGION).setLastChangedDate(longAgo); + assertEquals(longAgo, service.describeSecret("replace-books", REGION).getLastChangedDate()); + + Secret returned = service.replaceSecretDescription("replace-books", null, REGION); + + assertTrue(returned.getLastChangedDate().isAfter(longAgo)); + assertTrue(service.describeSecret("replace-books", REGION).getLastChangedDate().isAfter(longAgo)); + } + + @Test + void replaceSecretDescriptionRefusesASecretPendingDeletionWhatUpdateSecretRefuses() { + service.createSecret("replace-pending", "v1", null, "old", null, null, REGION); + service.deleteSecret("replace-pending", 7, false, REGION); + AwsException fromUpdate = assertThrows(AwsException.class, + () -> service.updateSecret("replace-pending", "x", null, REGION)); + + AwsException fromReplace = assertThrows(AwsException.class, + () -> service.replaceSecretDescription("replace-pending", null, REGION)); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + assertEquals("InvalidRequestException", fromReplace.getErrorCode()); + } + + @Test + void replaceSecretDescriptionRefusesAReplicaWhatUpdateSecretRefuses() { + service.createSecret("replace-replica", "v1", null, "old", null, null, REGION); + service.replicateSecretToRegions("replace-replica", + List.of(new SecretsManagerService.ReplicaRegion("eu-west-1", null)), false, REGION); + AwsException fromUpdate = assertThrows(AwsException.class, + () -> service.updateSecret("replace-replica", "x", null, "eu-west-1")); + + AwsException fromReplace = assertThrows(AwsException.class, + () -> service.replaceSecretDescription("replace-replica", null, "eu-west-1")); + + assertEquals(fromUpdate.getErrorCode(), fromReplace.getErrorCode()); + assertEquals(fromUpdate.getHttpStatus(), fromReplace.getHttpStatus()); + assertEquals("old", service.describeSecret("replace-replica", REGION).getDescription()); + } + + // --- direct UpdateSecret without a description keeps it: unchanged from main --- + + @Test + void updateSecretWithoutADescriptionKeepsTheStoredDescription() { + service.createSecret("update-keeps", "v1", null, "kept", null, null, REGION); + + service.updateSecret("update-keeps", null, "alias/app", REGION); + + Secret stored = service.describeSecret("update-keeps", REGION); + assertEquals("kept", stored.getDescription()); + assertEquals("alias/app", stored.getKmsKeyId()); + } } diff --git a/src/test/java/io/floci/aws/testing/CfnRequests.java b/src/test/java/io/floci/aws/testing/CfnRequests.java index 1b4b279afa..c4144b20a6 100644 --- a/src/test/java/io/floci/aws/testing/CfnRequests.java +++ b/src/test/java/io/floci/aws/testing/CfnRequests.java @@ -17,6 +17,22 @@ public final class CfnRequests { return stackName == null ? request : request.formParam("StackName", stackName); } + /** + * Sends {@code CreateStack} or {@code UpdateStack} with {@code template}, asserts it was accepted, and + * waits for {@code expectedStatus}; any other terminal status fails with its reason. + */ + public static void deploy(String action, String stackName, String template, String authorization, + String expectedStatus, String... capabilities) { + RequestSpecification request = cfn(action, stackName) + .header("Authorization", authorization) + .formParam("TemplateBody", template); + for (int i = 0; i < capabilities.length; i++) { + request.formParam("Capabilities.member." + (i + 1), capabilities[i]); + } + request.when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stackName, expectedStatus, authorization); + } + public static String physicalIdUnauthenticated(String stackName, String logicalId) { return physicalId(stackName, logicalId, null); } diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 1034752385..5f9c6ab4c5 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -66,6 +66,22 @@ AWS::AppSync::Resolver ResponseMappingTemplateS3Location clear not stored by the AWS::AppSync::Resolver Runtime clear AWS::AppSync::Resolver SyncConfig clear AWS::AppSync::Resolver TypeName create-only +AWS::CloudTrail::Trail AdvancedEventSelectors keep:the selectors are only put when the template declares them +AWS::CloudTrail::Trail EnableLogFileValidation keep:the update skips an absent flag, so the stored value stays +AWS::CloudTrail::Trail EventSelectors keep:the selectors are only put when the template declares them +AWS::CloudTrail::Trail IncludeGlobalServiceEvents keep:the update skips an absent flag, so the stored value stays +AWS::CloudTrail::Trail IsLogging keep:logging is only started or stopped when the template declares it +AWS::CloudTrail::Trail IsMultiRegionTrail keep:the update skips an absent flag, so the stored value stays +AWS::CloudTrail::Trail IsOrganizationTrail keep:the update skips an absent flag, so the stored value stays +AWS::CloudTrail::Trail S3BucketName keep:the update skips a null, so the stored bucket stays +AWS::CloudTrail::Trail S3KeyPrefix clear +AWS::CloudTrail::Trail SnsTopicName keep:the update skips a null, so the stored topic stays +AWS::CloudTrail::Trail TrailName keep:the update finds the trail by its physical id +AWS::Cognito::UserPoolGroup Description clear +AWS::Cognito::UserPoolGroup GroupName create-only a drop gives the group a generated name, so the group is replaced +AWS::Cognito::UserPoolGroup Precedence keep:the update skips a null, so the stored value stays +AWS::Cognito::UserPoolGroup RoleArn keep:the update skips a null, so the stored value stays +AWS::Cognito::UserPoolGroup UserPoolId create-only a drop fails: the provisioner requires it AWS::EC2::EIP Tags clear AWS::EC2::Instance AvailabilityZone create-only a drop differs from the declared value, so the instance is replaced AWS::EC2::Instance IamInstanceProfile clear the profile is disassociated, unless a launch template still supplies one, which takes its place @@ -112,3 +128,14 @@ AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network AWS::ECS::Service ServiceName keep:the prior name is reused AWS::ECS::Service ServiceRegistries keep:AWS removes registries only through a declared empty list AWS::ECS::Service TaskDefinition keep:required for the ECS controller +AWS::Lambda::Alias Description clear +AWS::Lambda::Alias FunctionName create-only a drop fails: the provisioner requires it +AWS::Lambda::Alias FunctionVersion keep:the update skips a null, so the stored version stays +AWS::Lambda::Alias Name create-only a drop fails: the provisioner requires it +AWS::Lambda::Alias RoutingConfig clear an empty map removes the weights, also when the template never declared it, so weights set outside the stack go +AWS::SecretsManager::Secret Description clear +AWS::SecretsManager::Secret GenerateSecretString keep:a dropped configuration adds no version, so the stored value stays +AWS::SecretsManager::Secret KmsKeyId keep:the update skips a null, so the stored key stays +AWS::SecretsManager::Secret Name create-only a drop of an explicit name replaces the secret with one under a generated name +AWS::SecretsManager::Secret SecretString keep:a dropped value adds no version, so the stored value stays, unless the template now generates one +AWS::SecretsManager::Secret Tags clear every update drives the tags to the template, also when the template never declared them