fix(logs): enforce group permissions for lifecycle changes (#5840)

* fix(logs): enforce group permissions for lifecycle changes

* fix(logs): accept bare group ARNs in lifecycle policies
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-16 20:59:38 -04:00
1 parent 534571b2a3
commit 92be67d2df
20 files changed
+1128 -56

No files matched your search

@@ -100,19 +100,37 @@ public class IamConditionContextResolver {
case "ec2" -> ec2ConditionContext(action, ctx);
case "dynamodb" -> dynamoDbConditionContext(action, ctx);
case "iam" -> iamConditionContext(action, ctx);
case "logs" -> logStreamConditionContext(action, ctx);
case "logs" -> logsConditionContext(action, ctx);
default -> null;
};
}
/** Stream access uses the owning log group's tags, in the handler's account and region. */
private Map<String, List<String>> logStreamConditionContext(String action, ContainerRequestContext ctx) {
/** Group mutations and stream access use the handler's group and request scope. */
private Map<String, List<String>> logsConditionContext(String action, ContainerRequestContext ctx) {
if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action)
|| LogGroupTagTarget.supports(action))) {
|| LogGroupTagTarget.supports(action) || "logs:CreateLogGroup".equals(action) || "logs:DeleteLogGroup".equals(action)
|| "logs:PutRetentionPolicy".equals(action) || "logs:DeleteRetentionPolicy".equals(action))) {
return null;
}
JsonNode body = bufferedJsonBody(ctx);
if (body == null || !logsService.isResolvable()) {
if (body == null) {
return null;
}
if ("logs:CreateLogGroup".equals(action)) {
JsonNode tags = body.path("tags");
if (!tags.isObject() || tags.isEmpty()) {
return null;
}
Map<String, List<String>> conditions = new LinkedHashMap<>();
List<String> keys = new ArrayList<>();
tags.properties().forEach(entry -> {
keys.add(entry.getKey());
conditions.put("aws:RequestTag/" + entry.getKey(), List.of(entry.getValue().asText()));
});
conditions.put("aws:TagKeys", keys);
return conditions;
}
if (!logsService.isResolvable()) {
return null;
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
@@ -417,7 +417,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
List<String> resources = resolveResourceArns(credentialScope,
"logs".equals(credentialScope)
? arnBuilder.buildLogStreamResources(action, ctx, region, accountId, requestPartition())
? arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition())
: arnBuilder.buildResources(credentialScope, ctx, region, accountId));
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
@@ -518,6 +518,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return;
}
// Tagged group creation requires either tagging permission, using the same resolved
// caller (including session, boundary and SCP ceilings) as the primary operation.
if ("logs:CreateLogGroup".equals(action) && conditionContext != null
&& !conditionContext.getOrDefault("aws:TagKeys", List.of()).isEmpty()) {
String groupResource = resources.getFirst();
String taggingResource = groupResource.substring(0, groupResource.length() - 2);
Map<String, List<String>> taggingContext = IamConditionContextResolver.withGlobalContext(
conditionContext, taggingResource, region, accountId, accountId);
Map<String, List<String>> groupContext = IamConditionContextResolver.withGlobalContext(
conditionContext, groupResource, region, accountId, accountId);
if (evaluator.evaluate(caller, null, "logs:TagResource", taggingResource, taggingContext) == Decision.DENY
&& evaluator.evaluate(caller, null, "logs:TagLogGroup", groupResource, groupContext) == Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}",
akid, "logs:TagResource", taggingResource);
ctx.abortWith(accessDeniedForRequest("logs:TagResource", credentialScope, ctx, taggingResource));
return;
}
}
// A PutObject carrying If-Match compares against the object it replaces, and S3 authorizes
// that read as s3:GetObject, WITHOUT the object's tags in the request context. Measured
// against real AWS: under a GetObject allow conditioned on s3:ExistingObjectTag the
@@ -90,6 +90,7 @@ public class CloudWatchLogsHandler {
private Response handleCreateLogGroup(JsonNode request, String region) {
String name = request.path("logGroupName").asText();
requireLogGroupName(name);
Integer retentionInDays = request.has("retentionInDays")
? request.path("retentionInDays").asInt() : null;
boolean deletionProtectionEnabled = request.path("deletionProtectionEnabled").asBoolean(false);
@@ -101,6 +102,7 @@ public class CloudWatchLogsHandler {
private Response handleDeleteLogGroup(JsonNode request, String region) {
String name = request.path("logGroupName").asText();
requireLogGroupName(name);
logsService.deleteLogGroup(name, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -264,10 +266,14 @@ public class CloudWatchLogsHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
private static void requireLogStreamNames(String group, String stream) {
private static void requireLogGroupName(String group) {
if (group.isEmpty() || group.length() > 512 || !LOG_GROUP_NAME.matcher(group).matches()) {
throw new AwsException("InvalidParameterException", "Invalid logGroupName.", 400);
}
}
private static void requireLogStreamNames(String group, String stream) {
requireLogGroupName(group);
int streamLength = stream.codePointCount(0, stream.length());
if (streamLength < 1 || streamLength > 512 || stream.indexOf(':') >= 0 || stream.indexOf('*') >= 0) {
throw new AwsException("InvalidParameterException", "Invalid logStreamName.", 400);
@@ -510,6 +516,7 @@ public class CloudWatchLogsHandler {
private Response handlePutRetentionPolicy(JsonNode request, String region) {
String groupName = request.path("logGroupName").asText();
requireLogGroupName(groupName);
int days = request.path("retentionInDays").asInt();
logsService.putRetentionPolicy(groupName, days, region);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -517,6 +524,7 @@ public class CloudWatchLogsHandler {
private Response handleDeleteRetentionPolicy(JsonNode request, String region) {
String groupName = request.path("logGroupName").asText();
requireLogGroupName(groupName);
logsService.deleteRetentionPolicy(groupName, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -522,7 +522,11 @@ public class CloudWatchLogsMetricFilterService implements Resettable {
synchronized (store) {
String account = regionResolver.getAccountId();
String prefix = groupPrefix(event.region(), event.logGroupName());
store.keys().stream().filter(key -> key.startsWith(prefix)).toList().forEach(store::delete);
store.keys().stream().filter(storedKey -> storedKey.startsWith(prefix)
&& store.get(storedKey).map(filter -> event.logGroupName().equals(filter.getLogGroupName())
&& storedKey.equals(key(event.region(), event.logGroupName(), filter.getFilterName())))
.orElse(false))
.toList().forEach(store::delete);
pending.values().removeIf(p -> p.owner().account().equals(account)
&& p.owner().region().equals(event.region()) && p.owner().group().equals(event.logGroupName()));
forgetCompletedOutages();
@@ -285,6 +285,7 @@ public class CloudWatchLogsService implements ResourceProvider {
synchronized (metricFilterStore) {
String key = groupKey(region, name);
LogGroup group = groupStore.get(key)
.filter(stored -> name.equals(stored.getLogGroupName()))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + name, 400));
if (group.isDeletionProtectionEnabled()) {
@@ -301,15 +302,22 @@ public class CloudWatchLogsService implements ResourceProvider {
.toList();
for (String sk : streamKeys) {
LogStream stream = streamStore.get(sk).orElse(null);
if (stream != null) {
if (stream != null && name.equals(stream.getLogGroupName())
&& sk.equals(streamKey(region, name, stream.getLogStreamName()))) {
deleteEventsForStream(region, name, stream.getLogStreamName());
streamStore.delete(sk);
}
}
metricFilterStore.keys().stream().filter(k -> k.startsWith(streamPrefix))
metricFilterStore.keys().stream().filter(k -> k.startsWith(streamPrefix)
&& metricFilterStore.get(k).map(filter -> name.equals(filter.getLogGroupName())
&& k.equals(streamPrefix + filter.getFilterName())).orElse(false))
.toList().forEach(metricFilterStore::delete);
String subscriptionPrefix = subscriptionFilterKeyPrefix(region, name);
subscriptionFilterStore.keys().stream().filter(k -> k.startsWith(subscriptionPrefix))
subscriptionFilterStore.keys().stream().filter(k -> k.startsWith(subscriptionPrefix)
&& subscriptionFilterStore.get(k)
.map(filter -> name.equals(filter.getLogGroupName())
&& k.equals(subscriptionFilterKey(region, name, filter.getFilterName())))
.orElse(false))
.toList().forEach(subscriptionFilterStore::delete);
groupStore.delete(key);
LOG.infov("Deleted log group: {0}", name);
@@ -358,6 +366,7 @@ public class CloudWatchLogsService implements ResourceProvider {
public void putRetentionPolicy(String groupName, int days, String region) {
String key = groupKey(region, groupName);
LogGroup group = groupStore.get(key)
.filter(stored -> groupName.equals(stored.getLogGroupName()))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + groupName, 400));
group.setRetentionInDays(days);
@@ -367,6 +376,7 @@ public class CloudWatchLogsService implements ResourceProvider {
public void deleteRetentionPolicy(String groupName, String region) {
String key = groupKey(region, groupName);
LogGroup group = groupStore.get(key)
.filter(stored -> groupName.equals(stored.getLogGroupName()))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + groupName, 400));
group.setRetentionInDays(null);
@@ -908,7 +908,7 @@ public class IamPolicyEvaluator {
return false;
}
return matchesAction(stmt, action)
&& matchesResource(stmt, resource, ctx)
&& matchesResource(stmt, action, resource, ctx)
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
}
@@ -944,7 +944,7 @@ public class IamPolicyEvaluator {
PrincipalMatch match = principalMatch(stmt, principal);
if (match == PrincipalMatch.NONE
|| !matchesAction(stmt, action)
|| !matchesResource(stmt, resource, ctx)
|| !matchesResource(stmt, action, resource, ctx)
|| !matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt))) {
return PrincipalMatch.NONE;
}
@@ -1121,7 +1121,7 @@ public class IamPolicyEvaluator {
private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
Map<String, List<String>> ctx) {
return matchesAction(stmt, action)
&& matchesResource(stmt, resource, ctx)
&& matchesResource(stmt, action, resource, ctx)
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
}
@@ -1142,15 +1142,44 @@ public class IamPolicyEvaluator {
}
/** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */
private boolean matchesResource(PolicyStatement stmt, String resource,
private boolean matchesResource(PolicyStatement stmt, String action, String resource,
Map<String, List<String>> ctx) {
if (stmt.getResources() != null) {
return matchesAnyResource(stmt.getResources(), resource, ctx, policyVariables(stmt));
List<String> patterns = stmt.getResources() != null ? stmt.getResources() : stmt.getNotResources();
if (patterns == null) {
return false;
}
if (stmt.getNotResources() != null) {
return !matchesAnyResource(stmt.getNotResources(), resource, ctx, policyVariables(stmt));
String alias = logGroupResourceAlias(action, resource);
boolean matched = matchesAnyResource(patterns, resource, ctx, policyVariables(stmt))
|| alias != null && matchesAnyResource(patterns, alias, ctx, policyVariables(stmt));
return stmt.getResources() != null ? matched : !matched;
}
/**
* Group-management policies accept both documented bare group ARNs and legacy :* ARNs.
* Match them inside each statement so explicit denies, NotResource and caller ceilings
* retain their normal precedence. Stream actions and the three ARN tag APIs stay distinct.
*/
private static String logGroupResourceAlias(String action, String resource) {
if (action == null || !switch (action) {
case "logs:createloggroup", "logs:deleteloggroup", "logs:putretentionpolicy",
"logs:deleteretentionpolicy", "logs:tagloggroup" -> true;
default -> false;
} || !AwsArnUtils.isArnFor(resource, "logs")) {
return null;
}
return false;
String target = AwsArnUtils.parse(resource).resource();
if (!target.startsWith("log-group:")) {
return null;
}
String name = target.substring("log-group:".length());
boolean suffixed = name.endsWith(":*");
if (suffixed) {
name = name.substring(0, name.length() - 2);
}
if (name.isEmpty() || name.indexOf(':') >= 0 || name.indexOf('*') >= 0 || name.indexOf('?') >= 0) {
return null;
}
return suffixed ? resource.substring(0, resource.length() - 2) : resource + ":*";
}
/**
@@ -98,11 +98,16 @@ public class ResourceArnBuilder {
};
}
/** Uses the serving operation, not an independently parsed target header. */
public List<String> buildLogStreamResources(String action, ContainerRequestContext ctx,
String region, String accountId, String partition) {
if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action)
|| LogGroupTagTarget.supports(action))) {
/** Uses the serving operation and the same raw names as the handler. */
public List<String> buildLogResources(String action, ContainerRequestContext ctx,
String region, String accountId, String partition) {
boolean stream = "logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action);
boolean group = switch (action) {
case "logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy",
"logs:DeleteRetentionPolicy" -> true;
default -> false;
};
if (!stream && !group && !LogGroupTagTarget.supports(action)) {
return List.of("*");
}
JsonNode body = readJsonBody(ctx);
@@ -112,11 +117,10 @@ public class ResourceArnBuilder {
if (LogGroupTagTarget.supports(action)) {
return List.of(LogGroupTagTarget.resolve(body.path("resourceArn").asText(), region, accountId, partition).arn());
}
// Match the handler's coercion and raw names, including whitespace and numeric values.
String group = body.path("logGroupName").asText();
String stream = body.path("logStreamName").asText();
return List.of(new AwsArnUtils.Arn(partition, "logs", region, accountId,
"log-group:" + group + ":log-stream:" + stream).toString());
String name = body.path("logGroupName").asText();
String resource = "log-group:" + name + (stream
? ":log-stream:" + body.path("logStreamName").asText() : ":*");
return List.of(new AwsArnUtils.Arn(partition, "logs", region, accountId, resource).toString());
}
// ── IAM ─────────────────────────────────────────────────────────────────────