fix(eventbridge): validate scheduled rule rate expressions (#7996) (#8113)

* fix(eventbridge): validate scheduled rule rate expressions

Validate schedule expressions before PutRule creates or mutates a rule. Reject mismatched rate units with the AWS ValidationException while preserving existing rule state and timers. Keep stored-expression parsing tolerant.

Add service, SDK and scheduler regression coverage.

Closes #7996.

* refactor(eventbridge): share rate parsing and cover legacy stack updates

Use one matcher and parsed value/unit helper for strict API validation and tolerant stored-expression execution. Keep unit agreement checks at the API boundary.

Add a CloudFormation SDK regression proving that unrelated stack updates already skip unchanged legacy rules while direct PutRule calls remain strict. Correct the outdated test comment suggesting every resource is re-provisioned.

* refactor(eventbridge): share AWS rate validation with Scheduler

Move positive value, supported unit and singular/plural constraints into core.common.AwsRateExpressions. Both API validators call the shared checks while their execution parsers retain support for legacy stored expressions.

Parse Scheduler rates once per call and retain its checked interval conversion. Add cross-service tests for matching acceptance and rejection reasons.

Addresses review 5876298647 on #8113.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-12 11:26:00 -04:00
1 parent f3b61cc368
commit 14f01c80e8
12 files changed
+371 -46

No files matched your search

@@ -0,0 +1,33 @@
package io.floci.aws.core.common;
import java.util.Locale;
import java.util.Set;
/** Rate constraints shared by EventBridge rules and EventBridge Scheduler API requests. */
public final class AwsRateExpressions {
private static final Set<String> UNITS = Set.of("minute", "minutes", "hour", "hours", "day", "days");
private AwsRateExpressions() {
}
/** Validates a parsed rate without restricting the parsers used for previously stored schedules. */
public static void validate(long value, String unit) {
requirePositiveValue(value);
String normalizedUnit = unit == null ? "" : unit.toLowerCase(Locale.ROOT);
if (!UNITS.contains(normalizedUnit)) {
throw new IllegalArgumentException("Rate unit must be minute(s), hour(s), or day(s)");
}
boolean plural = normalizedUnit.endsWith("s");
if ((value == 1) == plural) {
throw new IllegalArgumentException("Rate unit must be singular for 1 and plural for values greater than 1");
}
}
/** Positive values are also required when executing previously stored expressions. */
public static void requirePositiveValue(long value) {
if (value < 1) {
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
}
}
}
@@ -363,6 +363,13 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
if (eventPattern != null && !eventPattern.isBlank()) {
validateEventPattern(eventPattern);
}
if (scheduleExpression != null && !scheduleExpression.isBlank()) {
try {
ScheduleExpressionParser.validate(scheduleExpression);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Parameter ScheduleExpression is not valid.", 400);
}
}
String effectiveBus = resolvedBusName(busName);
ensureBusExists(effectiveBus, region);
@@ -4,9 +4,12 @@ import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import io.floci.aws.core.common.AwsCronDefinitions;
import io.floci.aws.core.common.AwsRateExpressions;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -32,28 +35,25 @@ public final class ScheduleExpressionParser {
return expression != null && CRON_PATTERN.matcher(expression.trim()).matches();
}
/** Validates API input without changing parsing of previously stored expressions. */
public static void validate(String expression) {
if (isCronExpression(expression)) {
getNextFireTime(expression, ZonedDateTime.now(ZoneOffset.UTC));
return;
}
Rate rate = parseRate(expression);
AwsRateExpressions.validate(rate.value(), rate.unit());
}
public static long parseRateToMillis(String expression) {
if (expression == null || expression.isBlank()) {
throw new IllegalArgumentException("Schedule expression cannot be null or blank");
}
Matcher rateMatcher = RATE_PATTERN.matcher(expression.trim());
if (!rateMatcher.matches()) {
throw new IllegalArgumentException("Not a valid rate expression: " + expression);
}
int value = Integer.parseInt(rateMatcher.group(1));
if (value < 1) {
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
}
String unit = rateMatcher.group(2).toLowerCase();
return switch (unit) {
Rate rate = parseRate(expression);
int value = rate.value();
return switch (rate.unit()) {
case "minute", "minutes" -> value * 60 * 1000L;
case "hour", "hours" -> value * 60 * 60 * 1000L;
case "day", "days" -> value * 24 * 60 * 60 * 1000L;
case "week", "weeks" -> value * 7 * 24 * 60 * 60 * 1000L;
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
default -> throw new IllegalArgumentException("Unknown rate unit: " + rate.unit());
};
}
@@ -85,6 +85,20 @@ public final class ScheduleExpressionParser {
return Math.max(millis, 1000);
}
private static Rate parseRate(String expression) {
if (expression == null || expression.isBlank()) {
throw new IllegalArgumentException("Schedule expression cannot be null or blank");
}
Matcher matcher = RATE_PATTERN.matcher(expression.trim());
if (!matcher.matches()) {
throw new IllegalArgumentException("Not a valid rate expression: " + expression);
}
int value = Integer.parseInt(matcher.group(1));
AwsRateExpressions.requirePositiveValue(value);
String unit = matcher.group(2).toLowerCase(Locale.ROOT);
return new Rate(value, unit);
}
private static String normalizeCronExpression(String cronExpression) {
String[] fields = cronExpression.trim().split("\\s+");
if (fields.length != 6) {
@@ -93,4 +107,6 @@ public final class ScheduleExpressionParser {
}
return "0 " + cronExpression;
}
private record Rate(int value, String unit) {}
}
@@ -4,6 +4,7 @@ import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import io.floci.aws.core.common.AwsCronDefinitions;
import io.floci.aws.core.common.AwsRateExpressions;
import java.time.Instant;
import java.time.LocalDateTime;
@@ -12,6 +13,7 @@ import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -37,10 +39,6 @@ public final class SchedulerExpressionParser {
"^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?|weeks?)\\s*\\)$",
Pattern.CASE_INSENSITIVE);
private static final Pattern AWS_RATE_PATTERN = Pattern.compile(
"^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?)\\s*\\)$",
Pattern.CASE_INSENSITIVE);
private static final Pattern CRON_PATTERN = Pattern.compile(
"^cron\\((.+)\\)$",
Pattern.CASE_INSENSITIVE);
@@ -71,17 +69,9 @@ public final class SchedulerExpressionParser {
switch (classify(expression)) {
case AT -> parseAt(expression, timezone);
case RATE -> {
Matcher rate = AWS_RATE_PATTERN.matcher(expression.trim());
if (!rate.matches()) {
throw new IllegalArgumentException("Week-based rates are not supported by Scheduler");
}
parseRateMillis(expression);
long value = Long.parseLong(rate.group(1));
String unit = rate.group(2);
boolean plural = unit.endsWith("s") || unit.endsWith("S");
if ((value == 1) == plural) {
throw new IllegalArgumentException("Rate unit must be singular for 1 and plural for values greater than 1");
}
Rate rate = parseRate(expression);
AwsRateExpressions.validate(rate.value(), rate.unit());
rate.toMillis();
}
case CRON -> {
parseCron(expression);
@@ -108,22 +98,17 @@ public final class SchedulerExpressionParser {
* Parses a {@code rate(...)} expression and returns the interval in milliseconds.
*/
public static long parseRateMillis(String expression) {
return parseRate(expression).toMillis();
}
private static Rate parseRate(String expression) {
Matcher m = RATE_PATTERN.matcher(expression.trim());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid rate() expression: " + expression);
}
long value = Long.parseLong(m.group(1));
if (value < 1) {
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
}
String unit = m.group(2).toLowerCase();
return switch (unit) {
case "minute", "minutes" -> Math.multiplyExact(value, 60_000L);
case "hour", "hours" -> Math.multiplyExact(value, 3_600_000L);
case "day", "days" -> Math.multiplyExact(value, 86_400_000L);
case "week", "weeks" -> Math.multiplyExact(value, 604_800_000L);
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
};
AwsRateExpressions.requirePositiveValue(value);
return new Rate(value, m.group(2).toLowerCase(Locale.ROOT));
}
/**
@@ -165,4 +150,16 @@ public final class SchedulerExpressionParser {
}
return ZoneId.of(timezone);
}
private record Rate(long value, String unit) {
long toMillis() {
return switch (unit) {
case "minute", "minutes" -> Math.multiplyExact(value, 60_000L);
case "hour", "hours" -> Math.multiplyExact(value, 3_600_000L);
case "day", "days" -> Math.multiplyExact(value, 86_400_000L);
case "week", "weeks" -> Math.multiplyExact(value, 604_800_000L);
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
};
}
}
}