Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): compare numeric and boolean condition values (#5086)
Abhigya7d9e38cf56e7
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.javaindex 4a2190214e..8401c30d68 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java@@ -12,7 +12,14 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.math.BigDecimal;+import java.time.DateTimeException;import java.time.Instant;+import java.time.LocalDate;+import java.time.OffsetDateTime;+import java.time.YearMonth;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;@@ -20,6 +27,7 @@ import java.util.Map;import java.util.Set;import java.util.TreeSet;import java.util.concurrent.ConcurrentHashMap;+import java.util.function.IntPredicate;import java.util.regex.Matcher;import java.util.regex.Pattern;@@ -87,6 +95,9 @@ public class IamPolicyEvaluator {// only guards against growth from many distinct session policies.static final int MAX_CACHED_DOCUMENTS = 2048;+ private static final Pattern EPOCH_SECONDS = Pattern.compile("-?\\d+");+ private static final Pattern YEAR_MONTH = Pattern.compile("\\d{4}-\\d{2}");+// Matches an IAM policy variable such as ${aws:username} inside a Resource pattern or a// Condition value. Stops at the first ',' or '}' so a default value (${key, 'default'}),// whose default may itself contain '{{' / '}}' placeholder markers, doesn't get swept into@@ -1085,18 +1096,18 @@ public class IamPolicyEvaluator {case "ArnEquals", "ArnLike" -> matchesArnCondition(condValue, ctxValue);case "ArnNotEquals", "ArnNotLike"-> !matchesArnCondition(condValue, ctxValue);case "Bool" -> Boolean.parseBoolean(condValue) == Boolean.parseBoolean(ctxValue);- case "NumericEquals" -> compareNumeric(ctxValue, condValue) == 0;- case "NumericNotEquals" -> compareNumeric(ctxValue, condValue) != 0;- case "NumericLessThan" -> compareNumeric(ctxValue, condValue) < 0;- case "NumericLessThanEquals" -> compareNumeric(ctxValue, condValue) <= 0;- case "NumericGreaterThan" -> compareNumeric(ctxValue, condValue) > 0;- case "NumericGreaterThanEquals" -> compareNumeric(ctxValue, condValue) >= 0;- case "DateEquals" -> compareDates(ctxValue, condValue) == 0;- case "DateNotEquals" -> compareDates(ctxValue, condValue) != 0;- case "DateLessThan" -> compareDates(ctxValue, condValue) < 0;- case "DateLessThanEquals" -> compareDates(ctxValue, condValue) <= 0;- case "DateGreaterThan" -> compareDates(ctxValue, condValue) > 0;- case "DateGreaterThanEquals" -> compareDates(ctxValue, condValue) >= 0;+ case "NumericEquals" -> compareNumeric(ctxValue, condValue, order -> order == 0);+ case "NumericNotEquals" -> compareNumeric(ctxValue, condValue, order -> order != 0);+ case "NumericLessThan" -> compareNumeric(ctxValue, condValue, order -> order < 0);+ case "NumericLessThanEquals" -> compareNumeric(ctxValue, condValue, order -> order <= 0);+ case "NumericGreaterThan" -> compareNumeric(ctxValue, condValue, order -> order > 0);+ case "NumericGreaterThanEquals" -> compareNumeric(ctxValue, condValue, order -> order >= 0);+ case "DateEquals" -> compareDates(ctxValue, condValue, order -> order == 0);+ case "DateNotEquals" -> compareDates(ctxValue, condValue, order -> order != 0);+ case "DateLessThan" -> compareDates(ctxValue, condValue, order -> order < 0);+ case "DateLessThanEquals" -> compareDates(ctxValue, condValue, order -> order <= 0);+ case "DateGreaterThan" -> compareDates(ctxValue, condValue, order -> order > 0);+ case "DateGreaterThanEquals" -> compareDates(ctxValue, condValue, order -> order >= 0);case "IpAddress" -> matchesIpAddress(condValue, ctxValue);case "NotIpAddress" -> !matchesIpAddress(condValue, ctxValue);default -> {@@ -1106,20 +1117,52 @@ public class IamPolicyEvaluator {};}- private int compareNumeric(String ctxValue, String condValue) {+ /**+ * Compares exactly, so integers beyond a double's precision stay distinct. A value that+ * does not parse never satisfies the operator, so it cannot pass as equal.+ */+ private static boolean compareNumeric(String ctxValue, String condValue, IntPredicate test) {+ if (ctxValue == null || condValue == null) {+ return false;+ }try {- return Double.compare(Double.parseDouble(ctxValue), Double.parseDouble(condValue));+ return test.test(new BigDecimal(ctxValue.trim()).compareTo(new BigDecimal(condValue.trim())));} catch (NumberFormatException e) {- return 0;+ LOG.debugv("Numeric condition on non-numeric value {0} vs {1}: no match", ctxValue, condValue);+ return false;}}- private int compareDates(String ctxValue, String condValue) {+ /** A value that does not parse as a date never satisfies the operator. */+ private static boolean compareDates(String ctxValue, String condValue, IntPredicate test) {+ if (ctxValue == null || condValue == null) {+ return false;+ }try {- return Instant.parse(ctxValue).compareTo(Instant.parse(condValue));- } catch (Exception e) {- return 0;+ return test.test(parseConditionDate(ctxValue).compareTo(parseConditionDate(condValue)));+ } catch (DateTimeException | ArithmeticException | NumberFormatException e) {+ LOG.debugv("Date condition on non-date value {0} vs {1}: no match", ctxValue, condValue);+ return false;+ }+ }++ /**+ * Reads epoch seconds or a W3C ISO 8601 profile date: {@code YYYY-MM}, {@code YYYY-MM-DD},+ * or a date-time with or without seconds and fraction. A bare {@code YYYY} is read as epoch+ * seconds, as the two forms cannot be told apart. Dates without a time start at midnight UTC.+ */+ private static Instant parseConditionDate(String value) {+ String trimmed = value.trim();+ if (EPOCH_SECONDS.matcher(trimmed).matches()) {+ return Instant.ofEpochSecond(Long.parseLong(trimmed));+ }+ if (trimmed.indexOf('T') >= 0 || trimmed.indexOf('t') >= 0) {+ return OffsetDateTime.parse(trimmed, DateTimeFormatter.ISO_OFFSET_DATE_TIME).toInstant();+ }+ if (YEAR_MONTH.matcher(trimmed).matches()) {+ return YearMonth.parse(trimmed).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();}+ return LocalDate.parse(trimmed).atStartOfDay(ZoneOffset.UTC).toInstant();}private boolean matchesIpAddress(String condValue, String ctxValue) {@@ -1318,10 +1361,9 @@ public class IamPolicyEvaluator {Map<String, Map<String, List<String>>> result = new LinkedHashMap<>();condNode.fields().forEachRemaining(opEntry -> {Map<String, List<String>> kvMap = new LinkedHashMap<>();- boolean boolOperator = "Bool".equals(parseOperator(opEntry.getKey()).baseOp());opEntry.getValue().fields().forEachRemaining(kvEntry -> {JsonNode value = kvEntry.getValue();- kvMap.put(kvEntry.getKey(), boolOperator && value.isBoolean()+ kvMap.put(kvEntry.getKey(), value.isBoolean() || value.isNumber()? List.of(value.asText()) : nodeToList(value));});result.put(opEntry.getKey(), kvMap);diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.javaindex 3543385418..b06300b952 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyConditionMatchingTest.java@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;+import java.util.Collections;import java.util.List;import java.util.Map;@@ -81,6 +82,43 @@ class IamPolicyConditionMatchingTest {assertEquals(negated, decision("NotIpAddress", List.of(range), List.of(sourceIp)));}+ @ParameterizedTest+ @CsvSource({+ "NumericEquals, 10, invalid, DENY",+ "NumericNotEquals, 10, invalid, DENY",+ "NumericLessThanEquals, 10, invalid, DENY",+ "NumericEquals, 10, 10.0, ALLOW",+ "NumericLessThanEquals, 9007199254740992, 9007199254740993, DENY",+ "NumericGreaterThan, 9007199254740992, 9007199254740993, ALLOW",+ "DateEquals, 2026-01-01T00:00:00Z, invalid, DENY",+ "DateNotEquals, 2026-01-01T00:00:00Z, invalid, DENY",+ "DateLessThan, 2026-01-01T00:00:00Z, 2025-12-31T23:59:59Z, ALLOW",+ "DateEquals, 1893456000, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01-01, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01-01T00:00Z, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01-01T05:30+05:30, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01-01T00:00:00.000Z, 2030-01-01T00:00:00Z, ALLOW",+ "DateGreaterThanEquals, 2020-01-01, 2026-10-05T04:58:46Z, ALLOW",+ "DateLessThan, 2020-01-01, 1577836800, DENY",+ "DateLessThan, 2020-01-01, 1577836799, ALLOW",+ "DateEquals, 2030-01-01t00:00:00z, 2030-01-01T00:00:00Z, ALLOW",+ "DateEquals, 2030-01-01T00:00, 2030-01-01T00:00:00Z, DENY",+ "DateEquals, 2030-13-01, 2030-01-01T00:00:00Z, DENY",+ "DateEquals, 99999999999999999999, 2030-01-01T00:00:00Z, DENY"+ })+ void numericAndDateConditionsCompareExactlyAndRejectUnparsableValues(String operator, String policyValue,+ String requestValue, Decision expected) {+ assertEquals(expected, decision(operator, List.of(policyValue), List.of(requestValue)));+ }++ @ParameterizedTest+ @CsvSource({"NumericEquals, 10", "NumericNotEquals, 10", "DateEquals, 2026-01-01T00:00:00Z",+ "DateNotEquals, 2026-01-01T00:00:00Z"})+ void numericAndDateConditionsNeverMatchANullRequestValue(String operator, String policyValue) {+ assertEquals(Decision.DENY, decision(operator, List.of(policyValue), Collections.singletonList(null)));+ }+@Testvoid setOperatorsRemainCaseSensitive() {assertEquals(Decision.DENY, decision("ForAllValues:StringLike",diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.javaindex f07fe8a1bf..f1ed6fa25b 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java@@ -64,6 +64,38 @@ class IamPolicyEvaluatorTest {assertFalse(IamPolicyEvaluator.isSupportedConditionOperator("forallvalues:StringEquals"));}+ @Test+ void numericAndBooleanScalarConditionValuesAreCompared() {+ String policy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",+ "Resource":"*","Condition":{"NumericLessThanEquals":{"s3:max-keys":10},+ "StringEquals":{"aws:MultiFactorAuthPresent":true}}}]}""";+ Map<String, List<String>> within = Map.of("s3:max-keys", List.of("10"),+ "aws:MultiFactorAuthPresent", List.of("true"));+ Map<String, List<String>> over = Map.of("s3:max-keys", List.of("11"),+ "aws:MultiFactorAuthPresent", List.of("true"));++ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "s3:ListBucket", "*", within));+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "s3:ListBucket", "*", over));+ }++ @Test+ void nullConditionReadsUnquotedBooleanValues() {+ String requireAbsent = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",+ "Resource":"*","Condition":{"Null":{"aws:TokenIssueTime":true}}}]}""";+ String requirePresent = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",+ "Resource":"*","Condition":{"Null":{"aws:TokenIssueTime":false}}}]}""";+ Map<String, List<String>> absent = Map.of();+ Map<String, List<String>> present = Map.of("aws:TokenIssueTime", List.of("2030-01-01T00:00:00Z"));++ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(requireAbsent), "s3:ListBucket", "*", absent));+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(requireAbsent), "s3:ListBucket", "*", present));+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(requirePresent), "s3:ListBucket", "*", absent));+ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(requirePresent), "s3:ListBucket", "*", present));+ }+@Testvoid wildcardMatchesLiteralAsteriskInValue() {assertTrue(IamPolicyEvaluator.caseSensitiveGlobMatches("a*", "a*b"));