fix(scheduler): validate expressions and target role ARNs (#4561)

* fix(scheduler): validate expressions and target role ARNs

* fix(scheduler): keep persisted weekly schedules firing

* test(scheduler): use valid role ARNs in SDK error cases

* fix(scheduler): validate rate units and format constraint errors

* fix(scheduler): match AWS validation message details

* fix(scheduler): exempt quoted model pattern from partition scan

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
This commit is contained in:
vamsiakandVamsi Akavarapu authored and GitHub committed 2026-10-02 13:28:09 -04:00
1 parent a833551d03
commit 3ce093f208
9 files changed
+335 -61

No files matched your search

@@ -11,6 +11,7 @@ import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -19,10 +20,11 @@ import java.util.regex.Pattern;
*
* Supported forms (matches the AWS API):
* <ul>
* <li>{@code at(YYYY-MM-DDTHH:mm:ss)} — one-time fire at the given instant
* <li>{@code at(YYYY-MM-DDTHH:mm:ss)}: one-time fire at the given instant
* (interpreted in {@code scheduleExpressionTimezone}, default UTC).</li>
* <li>{@code rate(N unit)} — repeating fire every N minutes/hours/days/weeks.</li>
* <li>{@code cron(fields)} — six-field AWS EventBridge cron (minute hour DOM month DOW year).</li>
* <li>{@code rate(N unit)}: repeating fire every N minutes/hours/days;
* previously persisted week-based schedules remain readable.</li>
* <li>{@code cron(fields)}: six-field AWS EventBridge cron (minute hour DOM month DOW year).</li>
* </ul>
*/
public final class SchedulerExpressionParser {
@@ -35,12 +37,17 @@ 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);
private static final DateTimeFormatter AT_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss")
.withResolverStyle(ResolverStyle.STRICT);
private static final CronParser CRON_PARSER = AwsCronDefinitions.newParser();
@@ -59,6 +66,30 @@ public final class SchedulerExpressionParser {
throw new IllegalArgumentException("Unsupported schedule expression: " + expression);
}
/** Checks the complete expression before a schedule is persisted. */
public static void validate(String expression, String timezone) {
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");
}
}
case CRON -> {
parseCron(expression);
resolveZone(timezone);
}
}
}
/**
* Parses an {@code at(...)} expression and returns the fire instant.
* The timestamp is interpreted in {@code timezone} (default UTC).
@@ -81,16 +112,16 @@ public final class SchedulerExpressionParser {
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid rate() expression: " + expression);
}
int value = Integer.parseInt(m.group(1));
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" -> value * 60_000L;
case "hour", "hours" -> value * 3_600_000L;
case "day", "days" -> value * 86_400_000L;
case "week", "weeks" -> value * 604_800_000L;
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);
};
}
@@ -100,6 +131,18 @@ public final class SchedulerExpressionParser {
* evaluated in {@code timezone} (default UTC).
*/
public static Instant nextCronFire(String expression, Instant from, String timezone) {
Cron cron = parseCron(expression);
ExecutionTime exec = ExecutionTime.forCron(cron);
ZoneId zone = resolveZone(timezone);
ZonedDateTime zdt = from.atZone(zone);
return exec.nextExecution(zdt)
.map(ZonedDateTime::toInstant)
.orElseThrow(() -> new IllegalStateException(
"No next fire time for cron expression: " + expression));
}
private static Cron parseCron(String expression) {
Matcher m = CRON_PATTERN.matcher(expression.trim());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid cron() expression: " + expression);
@@ -113,14 +156,7 @@ public final class SchedulerExpressionParser {
}
Cron cron = CRON_PARSER.parse("0 " + cronFields);
cron.validate();
ExecutionTime exec = ExecutionTime.forCron(cron);
ZoneId zone = resolveZone(timezone);
ZonedDateTime zdt = from.atZone(zone);
return exec.nextExecution(zdt)
.map(ZonedDateTime::toInstant)
.orElseThrow(() -> new IllegalStateException(
"No next fire time for cron expression: " + expression));
return cron;
}
private static ZoneId resolveZone(String timezone) {
@@ -19,6 +19,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.DateTimeException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -31,6 +32,9 @@ public class SchedulerService {
// AWS EventBridge Scheduler name constraints: [0-9a-zA-Z-_.]+, 1-64 chars.
private static final Pattern NAME_PATTERN = Pattern.compile("[0-9a-zA-Z\\-_.]{1,64}");
private static final Pattern ROLE_ARN_PATTERN = Pattern.compile(
"arn:(?:" + AwsArnUtils.PARTITION_REGEX + "):iam::\\d{12}:role/[\\w+=,.@/-]+");
private static final String ROLE_ARN_MODEL_PATTERN = "^arn:aws(-[a-z]+)?:iam::\\d{12}:role\\/[\\w+=,.@\\/-]+$"; // partition-literal: the Scheduler model's RoleArn pattern, quoted verbatim in the error message
private static final String DEFAULT_GROUP = "default";
// FAIL_ON_TRAILING_TOKENS matters here: without it an Input of "{} garbage" parses as the
// leading object and the rest is silently dropped, so a value AWS rejects would be stored.
@@ -344,6 +348,17 @@ public class SchedulerService {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at 'scheduleExpression' failed to satisfy constraint: Member must not be null", 400);
}
if (req.getScheduleExpression().length() > 256) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + req.getScheduleExpression()
+ "' at 'scheduleExpression' failed to satisfy constraint: Member must have length less than or equal to 256", 400);
}
try {
SchedulerExpressionParser.validate(req.getScheduleExpression(), req.getScheduleExpressionTimezone());
} catch (IllegalArgumentException | DateTimeException | ArithmeticException e) {
throw new AwsException("ValidationException",
"Invalid ScheduleExpression: " + e.getMessage(), 400);
}
if (req.getFlexibleTimeWindow() == null) {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at 'flexibleTimeWindow' failed to satisfy constraint: Member must not be null", 400);
@@ -380,6 +395,17 @@ public class SchedulerService {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at 'target.roleArn' failed to satisfy constraint: Member must not be null", 400);
}
if (req.getTarget().getRoleArn().length() > 1600) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + req.getTarget().getRoleArn()
+ "' at 'target.roleArn' failed to satisfy constraint: Member must have length less than or equal to 1600", 400);
}
if (!ROLE_ARN_PATTERN.matcher(req.getTarget().getRoleArn()).matches()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + req.getTarget().getRoleArn()
+ "' at 'target.roleArn' failed to satisfy constraint: Member must satisfy regular expression pattern: "
+ ROLE_ARN_MODEL_PATTERN, 400);
}
if (req.getTarget().getDeadLetterConfig() != null
&& (req.getTarget().getDeadLetterConfig().getArn() == null
|| req.getTarget().getDeadLetterConfig().getArn().isBlank())) {