feat(logs): add AssociateKmsKey and DisassociateKmsKey for log groups (#2584)

* feat(logs): AssociateKmsKey / DisassociateKmsKey for log groups

floci had no CloudWatch Logs KMS association at all, so LZA's
Custom::UpdateSubscriptionFilter Lambda got UnsupportedOperation, the
resource reported FAILED, AWSAccelerator-LoggingStack rolled back, and
CDK's readback surfaced the misleading "NoStack: CloudFormationStack
object does not hold a stack".

The Lambda reads logGroup.kmsKeyId from DescribeLogGroups and only calls
AssociateKmsKey when it differs from the target key ARN, so storing the
association is not enough -- DescribeLogGroups has to echo kmsKeyId back
or the association never converges and it re-associates every deploy.

- LogGroup: kmsKeyId field
- CloudWatchLogsService: associateKmsKey / disassociateKmsKey, both
  ResourceNotFoundException on an unknown group; associate rejects a
  blank kmsKeyId with InvalidParameterException
- CloudWatchLogsHandler: AssociateKmsKey / DisassociateKmsKey actions
  (name or ARN identifier), and kmsKeyId emitted by DescribeLogGroups
  only when a key is associated

(cherry picked from commit d548de18dc5c5dc8de96cb3b37a3935915be9da2)

* fix(logs): accept resourceIdentifier on Associate/DisassociateKmsKey and require an identifier

The ARN alternative for these two operations is resourceIdentifier on the
wire (unlike the query operations' logGroupIdentifier), so SDK requests
identifying the group by ARN previously failed with ResourceNotFoundException.
A request with neither identifier now returns InvalidParameterException
instead of resolving a null group name. Both actions documented in the
cloudwatch supported-actions table.

* fix(logs): reject KMS requests naming both logGroupName and resourceIdentifier

AWS models the two identifiers as mutually exclusive — exactly one is
required. Supplying both previously succeeded against the named group
while silently ignoring the ARN target.

* fix(logs): enforce the modeled input constraints on the pre-existing operations

logEvents (1-10000 on PutLogEvents), logStreamNames (1-100 on
FilterLogEvents) and the Random/ByLogStream distribution enum on
PutSubscriptionFilter now answer the modeled InvalidParameterException
instead of being accepted verbatim. Included here because this PR
already hardens the same handler; found by a model-grounded constraint
sweep.

* fix(logs): treat a present-but-blank KMS target identifier as present

A blank logGroupName beside a valid resourceIdentifier slipped past the
exclusivity check as "absent" and the mutation proceeded on the valid
field. Presence is now membership (non-null), and a blank chosen
identifier is rejected outright — the model pins both to min length 1.

* fix(logs): store kmsKeyId on CreateLogGroup, reject query-result identifiers, and treat null lists as absent

CreateLogGroup modeled kmsKeyId but the handler never read it, so an
encrypted-at-creation request was accepted, stored nowhere, and absent
from DescribeLogGroups. Both AssociateKmsKey and DisassociateKmsKey
resolve resourceIdentifier through extractLogGroupNameFromArn, which
only recognizes the :log-group: form; the modeled :query-result: form
(account-wide GetQueryResults encryption, a separate feature) fell
through unchanged and became a misleading ResourceNotFoundException
naming a log group the caller never specified. FilterLogEvents also
used request.has("logStreamNames"), which is true for an explicit
JSON null, tripping the min-1 bound the same way an empty array does;
AWS treats an explicit null on an optional member as absent.

Fixes all three: plumb kmsKeyId through a new createLogGroup overload
and store it when non-blank; recognize and reject the query-result
resourceIdentifier form as unsupported instead of mangling it;  switch
to hasNonNull for logStreamNames, matching the idiom already used in
resolveKmsTargetLogGroupName. Also fixes requireListSize's
fully-qualified JsonNode parameter and a stray blank line.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 10:50:05 -04:00
1 parent d8ef1c8d7b
commit 4435c62848
7 files changed
+418 -2

No files matched your search

@@ -528,4 +528,165 @@ class CloudWatchLogsHandlerTest {
() -> handler.handle("StartQuery", request, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
// ──────────────────────────── AssociateKmsKey / DisassociateKmsKey ────────────────────────────
private static final String KEY_ARN =
"arn:aws:kms:" + REGION + ":" + ACCOUNT + ":key/1234abcd-12ab-34cd-56ef-1234567890ab";
@Test
void associateKmsKeyIsEchoedBackByDescribeLogGroups() {
// LZA's Custom::UpdateSubscriptionFilter Lambda reads logGroup.kmsKeyId from
// DescribeLogGroups and only calls AssociateKmsKey when it differs from the target
// key ARN. If DescribeLogGroups never surfaces the field, the association never
// converges and the Lambda re-associates on every deploy.
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", GROUP);
associate.put("kmsKeyId", KEY_ARN);
assertEquals(200, handler.handle("AssociateKmsKey", associate, REGION).getStatus());
JsonNode group = describeGroup();
assertEquals(KEY_ARN, group.path("kmsKeyId").asText());
}
@Test
void describeLogGroupsOmitsKmsKeyIdWhenNoKeyIsAssociated() {
assertThat(describeGroup().has("kmsKeyId"), is(false));
}
@Test
void disassociateKmsKeyClearsTheAssociation() {
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", GROUP);
associate.put("kmsKeyId", KEY_ARN);
handler.handle("AssociateKmsKey", associate, REGION);
ObjectNode disassociate = MAPPER.createObjectNode();
disassociate.put("logGroupName", GROUP);
assertEquals(200, handler.handle("DisassociateKmsKey", disassociate, REGION).getStatus());
assertThat(describeGroup().has("kmsKeyId"), is(false));
}
@Test
void associateKmsKeyResolvesAnArnResourceIdentifier() {
// The wire field for the ARN alternative on Associate/DisassociateKmsKey is
// resourceIdentifier (not the logGroupIdentifier the query operations use).
ObjectNode associate = MAPPER.createObjectNode();
associate.put("resourceIdentifier", GROUP_ARN);
associate.put("kmsKeyId", KEY_ARN);
assertEquals(200, handler.handle("AssociateKmsKey", associate, REGION).getStatus());
assertEquals(KEY_ARN, describeGroup().path("kmsKeyId").asText());
}
@Test
void associateKmsKeyWithBothIdentifiersThrowsInvalidParameter() {
// AWS models the two identifiers as mutually exclusive: exactly one is required.
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", GROUP);
associate.put("resourceIdentifier", GROUP_ARN);
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void associateKmsKeyWithBlankNameBesideValidArnThrowsInvalidParameter() {
// A present-but-blank identifier is not "absent": the model pins logGroupName
// to min length 1, so blank + a valid counterpart must reject, not silently
// proceed on the valid one.
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", "");
associate.put("resourceIdentifier", GROUP_ARN);
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void associateKmsKeyWithOnlyABlankIdentifierThrowsInvalidParameter() {
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", "");
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void associateKmsKeyWithoutAnyIdentifierThrowsInvalidParameter() {
ObjectNode associate = MAPPER.createObjectNode();
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void associateKmsKeyOnUnknownLogGroupThrows() {
ObjectNode associate = MAPPER.createObjectNode();
associate.put("logGroupName", "/nope");
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
}
@Test
void createLogGroupWithKmsKeyIdIsEchoedBackByDescribeLogGroups() {
// CreateLogGroup models kmsKeyId (Required: No) as the normal way to create an
// encrypted group in one call; it must be stored and surfaced the same way
// AssociateKmsKey's result is.
String newGroup = "/aws/rds/instance/encrypted-at-creation/postgresql";
ObjectNode create = MAPPER.createObjectNode();
create.put("logGroupName", newGroup);
create.put("kmsKeyId", KEY_ARN);
assertEquals(200, handler.handle("CreateLogGroup", create, REGION).getStatus());
ObjectNode describeRequest = MAPPER.createObjectNode();
describeRequest.put("logGroupNamePrefix", newGroup);
Response response = handler.handle("DescribeLogGroups", describeRequest, REGION);
ArrayNode groups = (ArrayNode) ((ObjectNode) response.getEntity()).path("logGroups");
assertEquals(1, groups.size());
assertEquals(KEY_ARN, groups.get(0).path("kmsKeyId").asText());
}
@Test
void associateKmsKeyWithQueryResultResourceIdentifierIsRejectedAsUnsupported() {
// arn:...:query-result:* is a real, modeled resourceIdentifier form (account-wide
// GetQueryResults encryption), but it is a genuinely different feature from
// per-log-group encryption. extractLogGroupNameFromArn only recognizes :log-group:,
// so left unchecked this ARN falls through unchanged and becomes a log group NAME,
// producing a ResourceNotFoundException that names a log group the caller never
// specified. It must be rejected as unsupported instead.
ObjectNode associate = MAPPER.createObjectNode();
associate.put("resourceIdentifier",
"arn:aws:logs:" + REGION + ":" + ACCOUNT + ":query-result:*");
associate.put("kmsKeyId", KEY_ARN);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("AssociateKmsKey", associate, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
assertThat(ex.getMessage(), containsString("query-result"));
}
private JsonNode describeGroup() {
ObjectNode request = MAPPER.createObjectNode();
request.put("logGroupNamePrefix", GROUP);
Response response = handler.handle("DescribeLogGroups", request, REGION);
assertEquals(200, response.getStatus());
ArrayNode groups = (ArrayNode) ((ObjectNode) response.getEntity()).path("logGroups");
assertEquals(1, groups.size());
return groups.get(0);
}
}
@@ -0,0 +1,92 @@
package io.github.hectorvent.floci.services.cloudwatch.logs;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Enforcement of the input constraints the 2014-03-28 model pins on the
* pre-existing operations: logEvents list 1-10000 on PutLogEvents,
* logStreamNames list 1-100 on FilterLogEvents, and the Random/ByLogStream
* distribution enum on PutSubscriptionFilter. All were previously accepted
* verbatim.
*/
class CloudWatchLogsInputConstraintTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String GROUP = "constraint-group";
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudWatchLogsHandler handler;
@BeforeEach
void setUp() {
CloudWatchLogsService service = new CloudWatchLogsService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
10_000,
new RegionResolver(REGION, ACCOUNT)
);
handler = new CloudWatchLogsHandler(service, MAPPER);
service.createLogGroup(GROUP, null, null, REGION);
service.createLogStream(GROUP, "s1", REGION);
}
private static AwsException expect400(Runnable call) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals(400, e.getHttpStatus());
assertEquals("InvalidParameterException", e.getErrorCode());
return e;
}
@Test
void putLogEvents_emptyList_isRejected() {
ObjectNode request = MAPPER.createObjectNode();
request.put("logGroupName", GROUP).put("logStreamName", "s1");
request.putArray("logEvents");
expect400(() -> handler.handle("PutLogEvents", request, REGION));
}
@Test
void filterLogEvents_tooManyStreamNames_isRejected() {
ObjectNode request = MAPPER.createObjectNode();
request.put("logGroupName", GROUP);
ArrayNode names = request.putArray("logStreamNames");
for (int i = 0; i <= 100; i++) {
names.add("s" + i);
}
expect400(() -> handler.handle("FilterLogEvents", request, REGION));
}
@Test
void filterLogEvents_explicitNullStreamNames_isTreatedAsAbsent() {
// request.has("logStreamNames") is true for an explicit JSON null, and mapping
// NullNode to size 0 trips the min-1 bound below. AWS treats an explicit null on
// an optional member as absent, so this must succeed, not 400.
ObjectNode request = MAPPER.createObjectNode();
request.put("logGroupName", GROUP);
request.putNull("logStreamNames");
assertEquals(200, handler.handle("FilterLogEvents", request, REGION).getStatus());
}
@Test
void putSubscriptionFilter_unknownDistribution_isRejected() {
ObjectNode request = MAPPER.createObjectNode();
request.put("logGroupName", GROUP).put("filterName", "f")
.put("filterPattern", "").put("destinationArn",
"arn:aws:lambda:us-east-1:000000000000:function:fn")
.put("distribution", "RoundRobin");
expect400(() -> handler.handle("PutSubscriptionFilter", request, REGION));
}
}
@@ -20,6 +20,8 @@ import static org.junit.jupiter.api.Assertions.*;
class CloudWatchLogsServiceTest {
private static final String REGION = "us-east-1";
private static final String KEY_ARN =
"arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab";
private CloudWatchLogsService service;
@@ -166,6 +168,48 @@ class CloudWatchLogsServiceTest {
assertNull(group.getRetentionInDays());
}
// ──────────────────────────── KMS key association ────────────────────────────
@Test
void associateAndDisassociateKmsKey() {
service.createLogGroup("/app/logs", null, null, REGION);
assertNull(service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId(),
"a freshly created log group has no CMK associated");
service.associateKmsKey("/app/logs", KEY_ARN, REGION);
assertEquals(KEY_ARN, service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
service.disassociateKmsKey("/app/logs", REGION);
assertNull(service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
}
@Test
void associateKmsKeyReplacesAnExistingAssociation() {
service.createLogGroup("/app/logs", null, null, REGION);
service.associateKmsKey("/app/logs", KEY_ARN, REGION);
String other = "arn:aws:kms:us-east-1:000000000000:key/99999999-9999-9999-9999-999999999999";
service.associateKmsKey("/app/logs", other, REGION);
assertEquals(other, service.describeLogGroups("/app/logs", REGION).getFirst().getKmsKeyId());
}
@Test
void associateKmsKeyOnMissingGroupThrows() {
assertThrows(AwsException.class, () -> service.associateKmsKey("/missing", KEY_ARN, REGION));
}
@Test
void associateKmsKeyWithoutKeyIdThrows() {
service.createLogGroup("/app/logs", null, null, REGION);
assertThrows(AwsException.class, () -> service.associateKmsKey("/app/logs", "", REGION));
}
@Test
void disassociateKmsKeyOnMissingGroupThrows() {
assertThrows(AwsException.class, () -> service.disassociateKmsKey("/missing", REGION));
}
@Test
void tagAndUntagLogGroup() {
service.createLogGroup("/app/logs", null, Map.of("env", "prod"), REGION);