diff --git a/docs/services/elb.md b/docs/services/elb.md index 81b7c470ce..49b08ac302 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -152,6 +152,8 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on - `HealthCheckProtocol` defaults to `HTTP` for `HTTP` and `HTTPS` target groups and for target type `alb`, and to `TCP` for every other protocol, as for Network and Gateway Load Balancers. A health check uses `HTTP`, `HTTPS` or `TCP`. `TCP` is refused for `HTTP` and `HTTPS` target groups and for target type `alb`. `GENEVE`, `TLS`, `UDP`, `TCP_UDP`, `QUIC` and `TCP_QUIC` are refused for every target group. Each refusal is a `ValidationError` naming the protocols the target group takes, such as `Health check protocol 'TCP' must be one of 'HTTP, HTTPS'`, from `CreateTargetGroup` and `ModifyTargetGroup` alike, and changes nothing. - A `TCP` check has no `HealthCheckPath` or `Matcher`. Naming either for one, the default `TCP` check included, is refused with `InvalidConfigurationRequest` (`Health check paths are not supported for TCP health checks`, and the same for matchers). Moving a `TCP` check to `HTTP` or `HTTPS` takes both, or `ModifyTargetGroup` answers `ValidationError` `Path and return code are required for layer 7 health checks.`. Moving a check to `TCP` drops its path and matcher. - Each `CreateListener` automatically creates an immutable default rule (`priority=default`, `isDefault=true`). This rule cannot be deleted; use `ModifyListener` to change its action. +- `PathPatternConfig.RegexValues` supports regex conditions in `CreateRule`, `ModifyRule`, `DescribeRules`, and CloudFormation `ListenerRule`. Each expression is 1 to 128 characters; a condition accepts either glob `Values` or `RegexValues`. Rules containing path regexes allow at most three match evaluations per condition and five across the rule. Expressions match the whole request path, excluding its query string, and multiple expressions are ORed. Matching uses RE2/J with bounded, linear-time execution. Lookarounds, backreferences, atomic groups, possessive quantifiers, recursion, subroutines, and Unicode character classes are rejected. Escaped or quoted literal text remains valid. Existing `Values` glob matching is unchanged. +- Mixed glob and regex values, invalid regex syntax, and excess per-rule match values return AWS's `ValidationError` messages. The syntax error does not echo the submitted pattern. - Rule priorities are unique per listener: `CreateRule` and `SetRulePriorities` only reject a priority held by another rule on the same listener. `SetRulePriorities` is atomic: all priority assignments are validated before any change is committed. - `DeleteTargetGroup` is rejected with `ResourceInUse` while the target group is referenced by any listener or rule. - HTTPS and TLS certificate ARNs must refer to existing IAM server certificates or ACM certificates. `CreateListener`, `ModifyListener` and `AddListenerCertificates` reject a blank or unknown ARN with `CertificateNotFound`. When `ModifyListener` changes the protocol to HTTPS or TLS, it checks any inherited certificate ARNs too. An HTTPS listener also needs a default certificate: `CreateListener` and `ModifyListener` reject an absent or empty effective certificate list with `InvalidConfigurationRequest`. A referenced IAM server certificate cannot be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the certificate is removed from the listener. Writes recording a new IAM certificate reference hold IAM's certificate lock, so the certificate cannot be deleted between the check and the write. A refused change preserves the listener's previous port, protocol, policy and certificates. diff --git a/pom.xml b/pom.xml index 71a7432428..d31a8c4df0 100644 --- a/pom.xml +++ b/pom.xml @@ -101,6 +101,11 @@ + + com.google.re2j + re2j + 1.8 + io.opentelemetry.proto opentelemetry-proto diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java index 00a1a8e3ad..af6bbe4f32 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java @@ -11,6 +11,7 @@ import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.elbv2.ElbV2HealthChecker; import io.floci.aws.services.elbv2.ElbV2Service; import io.floci.aws.services.elbv2.ElbV2Service.ListenerCertificate; +import io.floci.aws.services.elbv2.PathPatternRegexValues; import io.floci.aws.services.elbv2.model.Action; import io.floci.aws.services.elbv2.model.AvailabilityZone; import io.floci.aws.services.elbv2.model.Listener; @@ -1014,6 +1015,9 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { if (pathCfg.path("Values").isArray()) { condition.setPathPatternValues(toStringList(pathCfg.path("Values"))); } + if (pathCfg.path("RegexValues").isArray()) { + condition.setPathPatternRegexValues(toStringList(pathCfg.path("RegexValues"))); + } JsonNode hostCfg = item.path("HostHeaderConfig"); if (hostCfg.path("Values").isArray()) { condition.setHostHeaderValues(toStringList(hostCfg.path("Values"))); @@ -1046,6 +1050,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { } result.add(condition); } + PathPatternRegexValues.validateConditions(result); return result; } diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java index 352d7396d6..25d60b31c9 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.TlsProxyServer; import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.CertificateReferenceResolver; import io.floci.aws.core.common.CertificateReferenceResolver.CertificateMaterial; import io.floci.aws.core.common.Pem; @@ -14,6 +15,7 @@ import io.floci.aws.core.common.WebSocketUpgrades; import io.floci.aws.core.common.tls.ReloadingKeyManager; import io.floci.aws.services.ec2.Ec2InstancePorts; import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.elbv2.PathPatternRegexValues.Compiled; import io.floci.aws.services.elbv2.model.Action; import io.floci.aws.services.elbv2.model.Listener; import io.floci.aws.services.elbv2.model.LoadBalancer; @@ -66,7 +68,9 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -1779,6 +1783,22 @@ public class ElbV2DataPlane { return last; } + static List compilePathRegexes(List regexValues) { + List compiled = new ArrayList<>(); + for (String regex : regexValues) { + try { + compiled.add(PathPatternRegexValues.compile(regex)); + } catch (AwsException e) { + LOG.warnv("Ignoring path-pattern regex value that does not compile: {0}", regex); + } + } + return List.copyOf(compiled); + } + + static boolean pathRegexMatches(List patterns, String path) { + return path != null && patterns.stream().anyMatch(p -> p.matches(path)); + } + private static boolean globMatches(String pattern, String text) { if (text == null) { return false; @@ -1800,6 +1820,8 @@ public class ElbV2DataPlane { final Rule rule; final Action action; final List hostHeaderPatterns; + private final Map> pathRegexes = + Collections.synchronizedMap(new IdentityHashMap<>()); CompiledRule(Rule rule) { this.rule = rule; @@ -1833,6 +1855,17 @@ public class ElbV2DataPlane { return hostHeaderPatterns.stream().anyMatch(p -> globMatches(p, host)); } + /** + * ALB regex path conditions: the condition holds when any expression matches the whole + * request path (not its query string). Expressions are compiled once per rule chain; one + * that does not compile never matches. + */ + private boolean matchesPathRegex(RuleCondition condition, String path) { + List patterns = pathRegexes.computeIfAbsent(condition, + c -> compilePathRegexes(c.getPathPatternRegexValues())); + return pathRegexMatches(patterns, path); + } + boolean matches(HttpServerRequest req) { if (rule.isDefault()) { return true; @@ -1863,10 +1896,13 @@ public class ElbV2DataPlane { yield patterns.stream().anyMatch(p -> globMatches(p, effectiveHost)); } case "path-pattern" -> { + String path = req.path(); + if (!condition.getPathPatternRegexValues().isEmpty()) { + yield matchesPathRegex(condition, path); + } List patterns = condition.getPathPatternValues().isEmpty() ? condition.getValues() : condition.getPathPatternValues(); - String path = req.path(); yield patterns.stream().anyMatch(p -> globMatches(p, path)); } case "http-header" -> { diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java index 47c673d734..6b9e3daf01 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java @@ -1051,10 +1051,23 @@ public class ElbV2QueryHandler { for (String v : c.getHostHeaderValues()) xml.start("member").raw(v).end("member"); xml.end("Values").end("HostHeaderConfig"); } - if (!c.getPathPatternValues().isEmpty()) { - xml.start("PathPatternConfig").start("Values"); - for (String v : c.getPathPatternValues()) xml.start("member").raw(v).end("member"); - xml.end("Values").end("PathPatternConfig"); + if (!c.getPathPatternValues().isEmpty() || !c.getPathPatternRegexValues().isEmpty()) { + xml.start("PathPatternConfig"); + if (!c.getPathPatternValues().isEmpty()) { + xml.start("Values"); + for (String value : c.getPathPatternValues()) { + xml.start("member").raw(value).end("member"); + } + xml.end("Values"); + } + if (!c.getPathPatternRegexValues().isEmpty()) { + xml.start("RegexValues"); + for (String value : c.getPathPatternRegexValues()) { + xml.elem("member", value); + } + xml.end("RegexValues"); + } + xml.end("PathPatternConfig"); } if (c.getHttpHeaderName() != null) { xml.start("HttpHeaderConfig") @@ -1361,6 +1374,8 @@ public class ElbV2QueryHandler { v++; } c.setValues(legacyValues); + String pathConfig = "Conditions.member." + i + ".PathPatternConfig."; + c.setPathPatternRegexValues(readMembers(p, pathConfig + "RegexValues.member.")); switch (field) { case "host-header" -> { @@ -1376,16 +1391,12 @@ public class ElbV2QueryHandler { else c.setHostHeaderValues(new ArrayList<>(legacyValues)); } case "path-pattern" -> { - List vals = new ArrayList<>(); - int j = 1; - while (true) { - String val = p.getFirst("Conditions.member." + i + ".PathPatternConfig.Values.member." + j); - if (val == null) break; - vals.add(val); - j++; + List vals = readMembers(p, pathConfig + "Values.member."); + if (!vals.isEmpty()) { + c.setPathPatternValues(vals); + } else { + c.setPathPatternValues(new ArrayList<>(legacyValues)); } - if (!vals.isEmpty()) c.setPathPatternValues(vals); - else c.setPathPatternValues(new ArrayList<>(legacyValues)); } case "http-header" -> { c.setHttpHeaderName(p.getFirst("Conditions.member." + i + ".HttpHeaderConfig.HttpHeaderName")); @@ -1440,9 +1451,21 @@ public class ElbV2QueryHandler { result.add(c); i++; } + PathPatternRegexValues.validateConditions(result); return result; } + private static List readMembers(MultivaluedMap parameters, String prefix) { + List values = new ArrayList<>(); + for (int i = 1; ; i++) { + String value = parameters.getFirst(prefix + i); + if (value == null) { + return values; + } + values.add(value); + } + } + private List parseTargets(MultivaluedMap p) { List result = new ArrayList<>(); int i = 1; diff --git a/src/main/java/io/floci/aws/services/elbv2/PathPatternRegexValues.java b/src/main/java/io/floci/aws/services/elbv2/PathPatternRegexValues.java new file mode 100644 index 0000000000..cce419b3c3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/elbv2/PathPatternRegexValues.java @@ -0,0 +1,129 @@ +package io.floci.aws.services.elbv2; + +import com.google.re2j.Pattern; +import com.google.re2j.PatternSyntaxException; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.elbv2.model.RuleCondition; + +import java.util.List; + +/** Shared admission and linear-time matching for path-pattern regex conditions. */ +public final class PathPatternRegexValues { + + private static final int MAX_CONDITION_EVALUATIONS = 3; + private static final int MAX_RULE_EVALUATIONS = 5; + + private PathPatternRegexValues() { + } + + /** Validates regex-bearing rules at both public admission paths before mutation. */ + public static void validateConditions(List conditions) { + boolean hasRegex = conditions.stream().anyMatch(c -> !c.getPathPatternRegexValues().isEmpty()); + if (!hasRegex) { + return; + } + int evaluations = 0; + for (RuleCondition condition : conditions) { + List regexValues = condition.getPathPatternRegexValues(); + if (!regexValues.isEmpty() && !"path-pattern".equals(condition.getField())) { + throw new AwsException("ValidationError", + "PathPatternConfig.RegexValues requires the path-pattern field.", 400); + } + int conditionEvaluations = matchEvaluations(condition); + if (conditionEvaluations > MAX_CONDITION_EVALUATIONS) { + throw new AwsException("ValidationError", + "A condition can have at most three match evaluations.", 400); + } + evaluations += conditionEvaluations; + if (evaluations > MAX_RULE_EVALUATIONS) { + throw new AwsException("ValidationError", + "A rule can only have '5' condition values and regex values", 400); + } + } + for (RuleCondition condition : conditions) { + if (!condition.getPathPatternRegexValues().isEmpty()) { + validate(condition.getPathPatternRegexValues(), + !condition.getValues().isEmpty() || !condition.getPathPatternValues().isEmpty()); + } + } + } + + private static int matchEvaluations(RuleCondition condition) { + return switch (condition.getField()) { + case "path-pattern" -> condition.getPathPatternRegexValues().isEmpty() + ? valueCount(condition.getPathPatternValues(), condition.getValues()) + : condition.getPathPatternRegexValues().size(); + case "host-header" -> valueCount(condition.getHostHeaderValues(), condition.getValues()); + case "http-header" -> condition.getHttpHeaderValues().size(); + case "http-request-method" -> condition.getHttpMethodValues().size(); + case "source-ip" -> condition.getSourceIpValues().size(); + case "query-string" -> condition.getQueryStringValues().size(); + case null, default -> condition.getValues().size(); + }; + } + + private static int valueCount(List configured, List legacy) { + return configured.isEmpty() ? legacy.size() : configured.size(); + } + + public static void validate(List regexValues, boolean hasGlobValues) { + if (hasGlobValues) { + throw new AwsException("ValidationError", + "You must provide exactly one of the following: ['Values' 'RegexValues']" + + " for config of type 'PathPatternConfig'", 400); + } + if (regexValues.size() > MAX_CONDITION_EVALUATIONS) { + throw new AwsException("ValidationError", + "A condition can have at most three match evaluations.", 400); + } + for (String regex : regexValues) { + compile(regex); + } + } + + static Compiled compile(String regex) { + if (regex.isEmpty() || regex.length() > 128) { + throw new AwsException("ValidationError", + "Each path-pattern regex value must be between 1 and 128 characters.", 400); + } + try { + if (hasUnicodeClass(regex)) { + throw new PatternSyntaxException("Unicode character classes are unsupported", regex); + } + return new Compiled(Pattern.compile(regex)); + } catch (PatternSyntaxException e) { + throw new AwsException("ValidationError", + "One or more provided condition regex values are not valid", 400); + } + } + + private static boolean hasUnicodeClass(String regex) { + boolean quoted = false; + for (int i = 0; i + 1 < regex.length(); i++) { + if (regex.charAt(i) != '\\') { + continue; + } + char escaped = regex.charAt(i + 1); + if (quoted) { + if (escaped == 'E') { + quoted = false; + i++; + } + } else { + i++; + if (escaped == 'Q') { + quoted = true; + } else if (escaped == 'p' || escaped == 'P') { + return true; + } + } + } + return false; + } + + record Compiled(Pattern pattern) { + boolean matches(String path) { + return pattern.matcher(path).matches(); + } + } +} diff --git a/src/main/java/io/floci/aws/services/elbv2/model/RuleCondition.java b/src/main/java/io/floci/aws/services/elbv2/model/RuleCondition.java index 44a85238c8..01180e6879 100644 --- a/src/main/java/io/floci/aws/services/elbv2/model/RuleCondition.java +++ b/src/main/java/io/floci/aws/services/elbv2/model/RuleCondition.java @@ -16,6 +16,7 @@ public class RuleCondition { // typed configs private List hostHeaderValues = new ArrayList<>(); private List pathPatternValues = new ArrayList<>(); + private List pathPatternRegexValues = new ArrayList<>(); private String httpHeaderName; private List httpHeaderValues = new ArrayList<>(); private List httpMethodValues = new ArrayList<>(); @@ -36,6 +37,12 @@ public class RuleCondition { public List getPathPatternValues() { return pathPatternValues; } public void setPathPatternValues(List pathPatternValues) { this.pathPatternValues = pathPatternValues; } + /** {@code PathPatternConfig.RegexValues}: regular expressions matched against the whole request path. */ + public List getPathPatternRegexValues() { return pathPatternRegexValues; } + public void setPathPatternRegexValues(List pathPatternRegexValues) { + this.pathPatternRegexValues = pathPatternRegexValues != null ? pathPatternRegexValues : new ArrayList<>(); + } + public String getHttpHeaderName() { return httpHeaderName; } public void setHttpHeaderName(String httpHeaderName) { this.httpHeaderName = httpHeaderName; } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java index 4f9f45d771..82d1ddd08a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java @@ -398,6 +398,141 @@ class ElbV2CfnProvisionerTest { assertEquals("v", conds.getValue().get(2).getQueryStringValues().get(0).getKey()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void invalidRuleRegexIsRejectedBeforeCreateOrUpdate(boolean update) { + when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN))); + for (String invalid : List.of("", "a".repeat(129))) { + ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "75"); + props.putArray("Conditions").addObject().put("Field", "path-pattern").putObject("PathPatternConfig") + .putArray("RegexValues").add(invalid); + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule"), props, + update ? ctx(RULE_ARN) : ctx())); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + verify(elb, never()).createRule(anyString(), anyString(), anyList(), anyInt(), anyList(), any()); + verify(elb, never()).modifyRule(anyString(), anyString(), anyList(), anyList()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ruleRejectsUncompilableRegexWithTheAwsMessage(boolean update) { + for (String invalid : List.of("^/bad/(unclosed", "/a(?=b)", "\\p{L}")) { + ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "75"); + props.putArray("Conditions").addObject().put("Field", "path-pattern").putObject("PathPatternConfig") + .putArray("RegexValues").add(invalid); + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule"), props, + update ? ctx(RULE_ARN) : ctx())); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("One or more provided condition regex values are not valid", error.getMessage()); + } + verify(elb, never()).createRule(anyString(), anyString(), anyList(), anyInt(), anyList(), any()); + verify(elb, never()).modifyRule(anyString(), anyString(), anyList(), anyList()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void mixedGlobAndRegexIsRejectedBeforeCreateOrUpdate(boolean update) { + when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN))); + for (boolean legacy : List.of(false, true)) { + ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "75"); + ObjectNode condition = props.putArray("Conditions").addObject().put("Field", "path-pattern"); + ObjectNode path = condition.putObject("PathPatternConfig"); + path.putArray("RegexValues").add("^/api/.*$"); + (legacy ? condition : path).putArray("Values").add("/api/*"); + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule"), props, + update ? ctx(RULE_ARN) : ctx())); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("You must provide exactly one of the following: ['Values' 'RegexValues']" + + " for config of type 'PathPatternConfig'", + error.getMessage()); + } + verify(elb, never()).createRule(anyString(), anyString(), anyList(), anyInt(), anyList(), any()); + verify(elb, never()).modifyRule(anyString(), anyString(), anyList(), anyList()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void misplacedRegexAndEvaluationOverflowAreRejectedBeforeCreateOrUpdate(boolean update) throws Exception { + when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN))); + List invalidConditions = List.of( + """ + [{ + "Field": "host-header", + "PathPatternConfig": {"RegexValues": ["("]} + }] + """, + """ + [{ + "Field": "path-pattern", + "PathPatternConfig": {"RegexValues": ["/a", "/b", "/c", "/d"]} + }] + """, + """ + [ + { + "Field": "path-pattern", + "PathPatternConfig": {"RegexValues": ["/a", "/b", "/c"]} + }, + { + "Field": "host-header", + "HostHeaderConfig": {"Values": ["a.example.com", "b.example.com", "c.example.com"]} + } + ] + """); + List expectedMessages = List.of( + "PathPatternConfig.RegexValues requires the path-pattern field.", + "A condition can have at most three match evaluations.", + "A rule can only have '5' condition values and regex values"); + for (int i = 0; i < invalidConditions.size(); i++) { + ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "75"); + props.set("Conditions", mapper.readTree(invalidConditions.get(i))); + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule"), props, + update ? ctx(RULE_ARN) : ctx())); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals(expectedMessages.get(i), error.getMessage()); + } + verify(elb, never()).createRule(anyString(), anyString(), anyList(), anyInt(), anyList(), any()); + verify(elb, never()).modifyRule(anyString(), anyString(), anyList(), anyList()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ruleParsesPathPatternRegexValues(boolean update) { + when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN))); + when(elb.modifyRule(eq(REGION), eq(RULE_ARN), anyList(), anyList())).thenReturn(rule(LISTENER_ARN)); + when(elb.createRule(eq(REGION), eq(LISTENER_ARN), anyList(), eq(75), anyList(), eq(Map.of()))) + .thenReturn(rule(LISTENER_ARN)); + ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "75"); + props.putArray("Conditions").addObject().put("Field", "path-pattern").putObject("PathPatternConfig") + .putArray("RegexValues").add("^/api/(items|orders)(/.*)?$").add("/a").add("/b"); + props.withArray("Conditions").addObject().put("Field", "host-header").putObject("HostHeaderConfig") + .putArray("Values").add("a.example.com").add("b.example.com"); + props.putArray("Actions").addObject().put("Type", "forward").put("TargetGroupArn", TG_ARN); + + provisioner.provision(resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule"), props, + update ? ctx(RULE_ARN) : ctx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> conds = ArgumentCaptor.forClass(List.class); + if (update) { + verify(elb).modifyRule(eq(REGION), eq(RULE_ARN), conds.capture(), anyList()); + } else { + verify(elb).createRule(eq(REGION), eq(LISTENER_ARN), conds.capture(), eq(75), anyList(), eq(Map.of())); + } + assertEquals(List.of("^/api/(items|orders)(/.*)?$", "/a", "/b"), + conds.getValue().get(0).getPathPatternRegexValues()); + assertEquals(List.of(), conds.getValue().get(0).getPathPatternValues()); + } + @Test void anUnchangedRuleIsModifiedInPlaceAndAMovedRuleIsReplaced() { when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN))); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexDataPlaneIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexDataPlaneIntegrationTest.java new file mode 100644 index 0000000000..c75c3e4c47 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexDataPlaneIntegrationTest.java @@ -0,0 +1,337 @@ +package io.floci.aws.services.elbv2; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.RdsMockProfile; +import io.floci.aws.testutil.FreePorts; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.Rule; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.RuleCondition; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.services.elbv2.PathRegexFixtures.MATCH_PATTERNS; +import static io.floci.aws.testing.AlbFixtures.createListener; +import static io.floci.aws.testing.AlbFixtures.createLoadBalancer; +import static io.floci.aws.testing.AlbFixtures.createTargetGroup; +import static io.floci.aws.testing.AlbFixtures.deleteLoadBalancer; +import static io.floci.aws.testing.AlbFixtures.deleteTargetGroup; +import static io.floci.aws.testing.AlbFixtures.registerTarget; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Public ALB path-regex routing through local HTTP targets. */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class ElbV2PathRegexDataPlaneIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261122/us-east-1/elasticloadbalancing/aws4_request"; + + @Inject + Vertx vertx; + + private HttpServer primary; + private HttpServer secondary; + private String loadBalancerArn; + private String primaryTg; + private String secondaryTg; + private String listenerArn; + private int listenerPort; + + @BeforeEach + void startTargetsAndListener() throws Exception { + primary = backend("primary"); + secondary = backend("secondary"); + listenerPort = FreePorts.anyInterfacePort(); + loadBalancerArn = createLoadBalancer("regex-split-lb"); + primaryTg = createTargetGroup("regex-primary", "ip", primary.actualPort()); + secondaryTg = createTargetGroup("regex-secondary", "ip", secondary.actualPort()); + registerTarget(primaryTg, "127.0.0.1", primary.actualPort()); + registerTarget(secondaryTg, "127.0.0.1", secondary.actualPort()); + listenerArn = createListener(loadBalancerArn, primaryTg, listenerPort); + await().atMost(Duration.ofSeconds(3)).ignoreExceptions() + .untilAsserted(() -> assertEquals("primary", get("/api/items").asString())); + } + + @AfterEach + void cleanUp() { + assertAll( + () -> deleteLoadBalancer(loadBalancerArn), + () -> deleteTargetGroup(primaryTg), + () -> deleteTargetGroup(secondaryTg), + () -> closeBackend(primary), + () -> closeBackend(secondary)); + } + + @Test + void regexRuleSendsMatchingPathsToTheWeightedTargetGroups() { + String ruleArn = createSplitRule(0, 100); + + for (int i = 0; i < 20; i++) { + assertEquals("secondary", get("/api/items").asString()); + assertEquals("secondary", get("/status/200").asString()); + assertEquals("secondary", get("/api/orders/42").asString()); + } + assertEquals("primary", get("/assets/logo").asString()); + assertEquals("primary", get("/health").asString()); + // The path, not the query string, is matched. + assertEquals("primary", get("/assets/logo?q=/api/items").asString()); + + modifySplitRule(ruleArn, 70, 30); + int toSecondary = 0; + int samples = 400; + for (int i = 0; i < samples; i++) { + if ("secondary".equals(get("/api/items").asString())) { + toSecondary++; + } + } + assertTrue(toSecondary > samples * 0.15 && toSecondary < samples * 0.45, + "expected about 30% on the secondary, got " + toSecondary + " of " + samples); + + modifySplitRule(ruleArn, 100, 0); + for (int i = 0; i < 20; i++) { + assertEquals("primary", get("/api/items").asString()); + } + } + + @Test + void describeRulesReturnsRegexValuesToTheSdk() { + createSplitRule(70, 30); + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + Rule rule = client.describeRules(r -> r.listenerArn(listenerArn)).rules().stream() + .filter(r -> "75".equals(r.priority())).findFirst().orElseThrow(); + RuleCondition condition = rule.conditions().get(0); + assertEquals("path-pattern", condition.field()); + assertEquals(MATCH_PATTERNS, condition.pathPatternConfig().regexValues()); + assertTrue(condition.pathPatternConfig().values().isEmpty()); + assertEquals(List.of(70, 30), rule.actions().get(0).forwardConfig().targetGroups().stream() + .map(t -> t.weight()).toList()); + + String sdkRule = client.createRule(r -> r.listenerArn(listenerArn).priority(80) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues("^/sdk/[0-9]+$"))) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg))) + .rules().get(0).ruleArn(); + assertEquals(List.of("^/sdk/[0-9]+$"), client.describeRules(r -> r.ruleArns(sdkRule)).rules().get(0) + .conditions().get(0).pathPatternConfig().regexValues()); + assertEquals("secondary", get("/sdk/42").asString()); + assertEquals("primary", get("/sdk/x").asString()); + } + } + + @Test + void valuesAndRegexValuesTogetherAreRejected() { + String ruleArn = createSplitRule(0, 100); + RuleCondition condition = RuleCondition.builder().field("path-pattern") + .pathPatternConfig(p -> p.values("/a/*").regexValues("^/a/.*$")).build(); + String expectedMessage = "You must provide exactly one of the following: ['Values' 'RegexValues']" + + " for config of type 'PathPatternConfig'"; + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + int initialCount = client.describeRules(r -> r.listenerArn(listenerArn)).rules().size(); + ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.createRule(r -> r.listenerArn(listenerArn).priority(90).conditions(condition) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg)))); + assertEquals(400, createError.statusCode()); + assertEquals("ValidationError", createError.awsErrorDetails().errorCode()); + assertEquals(expectedMessage, createError.awsErrorDetails().errorMessage()); + ElasticLoadBalancingV2Exception updateError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyRule(r -> r.ruleArn(ruleArn).conditions(condition))); + assertEquals(400, updateError.statusCode()); + assertEquals("ValidationError", updateError.awsErrorDetails().errorCode()); + assertEquals(expectedMessage, updateError.awsErrorDetails().errorMessage()); + assertEquals(initialCount, client.describeRules(r -> r.listenerArn(listenerArn)).rules().size()); + assertEquals(MATCH_PATTERNS, client.describeRules(r -> r.ruleArns(ruleArn)) + .rules().get(0).conditions().get(0).pathPatternConfig().regexValues()); + } + } + + @Test + void sdkRoundTripsXmlCharactersAndCanSwitchBetweenRegexAndGlobConditions() { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + String regex = "^/api/(a&b|)$"; + Rule created = client.createRule(r -> r.listenerArn(listenerArn).priority(80) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues(regex))) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg))).rules().get(0); + assertEquals(List.of(regex), created.conditions().get(0).pathPatternConfig().regexValues()); + assertEquals(List.of(regex), client.describeRules(r -> r.ruleArns(created.ruleArn())).rules().get(0) + .conditions().get(0).pathPatternConfig().regexValues()); + assertEquals("secondary", get("/api/a&b").asString()); + + Rule modified = client.modifyRule(r -> r.ruleArn(created.ruleArn()) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.values("/assets/*")))) + .rules().get(0); + assertTrue(modified.conditions().get(0).pathPatternConfig().regexValues().isEmpty()); + assertEquals("secondary", get("/assets/logo").asString()); + assertEquals("primary", get("/api/a&b").asString()); + + Rule restored = client.modifyRule(r -> r.ruleArn(created.ruleArn()) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues(regex)))) + .rules().get(0); + assertEquals(List.of(regex), restored.conditions().get(0).pathPatternConfig().regexValues()); + assertTrue(restored.conditions().get(0).pathPatternConfig().values().isEmpty()); + assertEquals("secondary", get("/api/a&b").asString()); + assertEquals("primary", get("/assets/logo").asString()); + } + } + + @Test + void invalidRegexCannotCreateOrModifySdkRules() { + String ruleArn = createSplitRule(0, 100); + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + int initialCount = client.describeRules(r -> r.listenerArn(listenerArn)).rules().size(); + for (String regex : List.of("^/bad/(unclosed", "^/a(?=b)$", "^/(?>a)$", "^/\\p{L}+$")) { + ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.createRule(r -> r.listenerArn(listenerArn).priority(90) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues(regex))) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg)))); + assertEquals("ValidationError", createError.awsErrorDetails().errorCode()); + assertEquals(400, createError.statusCode()); + assertEquals("One or more provided condition regex values are not valid", + createError.awsErrorDetails().errorMessage()); + ElasticLoadBalancingV2Exception updateError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyRule(r -> r.ruleArn(ruleArn) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues(regex))))); + assertEquals("ValidationError", updateError.awsErrorDetails().errorCode()); + assertEquals(400, updateError.statusCode()); + assertEquals("One or more provided condition regex values are not valid", + updateError.awsErrorDetails().errorMessage()); + } + assertEquals(initialCount, client.describeRules(r -> r.listenerArn(listenerArn)).rules().size()); + assertEquals(MATCH_PATTERNS, client.describeRules(r -> r.ruleArns(ruleArn)) + .rules().get(0).conditions().get(0).pathPatternConfig().regexValues()); + assertEquals("secondary", get("/api/items").asString()); + } + } + + @Test + void sdkRejectsMisplacedRegexAndEvaluationOverflowBeforeMutation() { + String ruleArn = createSplitRule(0, 100); + RuleCondition regex = RuleCondition.builder().field("path-pattern") + .pathPatternConfig(p -> p.regexValues("/a", "/b", "/c")).build(); + RuleCondition fourRegexes = RuleCondition.builder().field("path-pattern") + .pathPatternConfig(p -> p.regexValues("/a", "/b", "/c", "/d")).build(); + RuleCondition misplaced = RuleCondition.builder().field("host-header") + .pathPatternConfig(p -> p.regexValues("(")).build(); + RuleCondition threeHosts = RuleCondition.builder().field("host-header") + .hostHeaderConfig(h -> h.values("a.example.com", "b.example.com", "c.example.com")).build(); + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + int initialCount = client.describeRules(r -> r.listenerArn(listenerArn)).rules().size(); + List> rejectedConditions = List.of( + List.of(misplaced), List.of(fourRegexes), List.of(regex, threeHosts)); + List expectedMessages = List.of( + "PathPatternConfig.RegexValues requires the path-pattern field.", + "A condition can have at most three match evaluations.", + "A rule can only have '5' condition values and regex values"); + for (int i = 0; i < rejectedConditions.size(); i++) { + List conditions = rejectedConditions.get(i); + ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.createRule(r -> r.listenerArn(listenerArn).priority(90).conditions(conditions) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg)))); + assertEquals(400, createError.statusCode()); + assertEquals("ValidationError", createError.awsErrorDetails().errorCode()); + assertEquals(expectedMessages.get(i), createError.awsErrorDetails().errorMessage()); + ElasticLoadBalancingV2Exception updateError = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> client.modifyRule(r -> r.ruleArn(ruleArn).conditions(conditions))); + assertEquals(400, updateError.statusCode()); + assertEquals("ValidationError", updateError.awsErrorDetails().errorCode()); + assertEquals(expectedMessages.get(i), updateError.awsErrorDetails().errorMessage()); + } + assertEquals(initialCount, client.describeRules(r -> r.listenerArn(listenerArn)).rules().size()); + assertEquals(MATCH_PATTERNS, client.describeRules(r -> r.ruleArns(ruleArn)) + .rules().get(0).conditions().get(0).pathPatternConfig().regexValues()); + + RuleCondition twoHosts = threeHosts.toBuilder() + .hostHeaderConfig(h -> h.values("a.example.com", "b.example.com")).build(); + Rule accepted = client.createRule(r -> r.listenerArn(listenerArn).priority(90) + .conditions(regex, twoHosts).actions(a -> a.type("forward").targetGroupArn(secondaryTg))) + .rules().get(0); + assertEquals(List.of("/a", "/b", "/c"), accepted.conditions().get(0).pathPatternConfig().regexValues()); + Rule updated = client.modifyRule(r -> r.ruleArn(ruleArn).conditions(regex, twoHosts)).rules().get(0); + assertEquals(accepted.conditions(), updated.conditions()); + } + } + + @Test + void nestedRepetitionRoutesLongNonmatchingRequestsWithoutBacktracking() { + try (ElasticLoadBalancingV2Client client = AwsTestClients.create( + ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) { + client.createRule(r -> r.listenerArn(listenerArn).priority(80) + .conditions(c -> c.field("path-pattern").pathPatternConfig(p -> p.regexValues("^/(a+)+$"))) + .actions(a -> a.type("forward").targetGroupArn(secondaryTg))); + assertEquals("secondary", get("/aaaa").asString()); + assertTimeout(Duration.ofSeconds(3), () -> + assertEquals("primary", get("/" + "a".repeat(2000) + "!").asString())); + } + } + + private String createSplitRule(int primaryWeight, int secondaryWeight) { + RequestSpecification request = given().header("Authorization", AUTH) + .formParam("Action", "CreateRule") + .formParam("ListenerArn", listenerArn) + .formParam("Priority", "75"); + conditionAndAction(request, primaryWeight, secondaryWeight); + return request.post("/").then().statusCode(200).extract() + .path("CreateRuleResponse.CreateRuleResult.Rules.member.RuleArn"); + } + + private void modifySplitRule(String ruleArn, int primaryWeight, int secondaryWeight) { + RequestSpecification request = given().header("Authorization", AUTH) + .formParam("Action", "ModifyRule") + .formParam("RuleArn", ruleArn); + conditionAndAction(request, primaryWeight, secondaryWeight); + Response response = request.post("/").then().statusCode(200).extract().response(); + assertEquals(MATCH_PATTERNS, response.xmlPath().getList( + "ModifyRuleResponse.ModifyRuleResult.Rules.member.Conditions.member.PathPatternConfig.RegexValues.member")); + } + + private void conditionAndAction(RequestSpecification request, int primaryWeight, int secondaryWeight) { + request.formParam("Conditions.member.1.Field", "path-pattern"); + for (int i = 0; i < MATCH_PATTERNS.size(); i++) { + request.formParam("Conditions.member.1.PathPatternConfig.RegexValues.member." + (i + 1), + MATCH_PATTERNS.get(i)); + } + request.formParam("Actions.member.1.Type", "forward") + .formParam("Actions.member.1.ForwardConfig.TargetGroups.member.1.TargetGroupArn", primaryTg) + .formParam("Actions.member.1.ForwardConfig.TargetGroups.member.1.Weight", primaryWeight) + .formParam("Actions.member.1.ForwardConfig.TargetGroups.member.2.TargetGroupArn", secondaryTg) + .formParam("Actions.member.1.ForwardConfig.TargetGroups.member.2.Weight", secondaryWeight); + } + + private HttpServer backend(String body) throws Exception { + return vertx.createHttpServer().requestHandler(request -> request.response().end(body)) + .listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS); + } + + private void closeBackend(HttpServer backend) throws Exception { + if (backend != null) { + backend.close().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS); + } + } + + private Response get(String pathAndQuery) { + return given().baseUri("http://127.0.0.1").port(listenerPort).urlEncodingEnabled(false).get(pathAndQuery); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexTest.java new file mode 100644 index 0000000000..b9970ec1f4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2PathRegexTest.java @@ -0,0 +1,144 @@ +package io.floci.aws.services.elbv2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.elbv2.PathPatternRegexValues.Compiled; +import io.floci.aws.services.elbv2.model.RuleCondition; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; + +import static io.floci.aws.services.elbv2.PathRegexFixtures.MATCH_PATTERNS; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** {@code PathPatternConfig.RegexValues}: validation and the data plane's full-path match. */ +class ElbV2PathRegexTest { + + @Test + void alternativesAndMultipleExpressionsMatchTheExpectedPaths() { + List patterns = ElbV2DataPlane.compilePathRegexes(MATCH_PATTERNS); + for (String path : List.of("/api/items", "/api/items/42", "/api/orders", "/api/orders/42", "/status/200")) { + assertTrue(ElbV2DataPlane.pathRegexMatches(patterns, path), path); + } + for (String path : List.of("/", "/api", "/api/items-extra", "/assets/logo", "/status/ok", "/API/items")) { + assertFalse(ElbV2DataPlane.pathRegexMatches(patterns, path), path); + } + } + + @Test + void matchIsAgainstTheWholePath() { + List unanchored = ElbV2DataPlane.compilePathRegexes(List.of("/api")); + assertTrue(ElbV2DataPlane.pathRegexMatches(unanchored, "/api")); + assertFalse(ElbV2DataPlane.pathRegexMatches(unanchored, "/api/v1")); + assertFalse(ElbV2DataPlane.pathRegexMatches(unanchored, "/v1/api")); + } + + @Test + void matchIsCaseSensitive() { + List patterns = ElbV2DataPlane.compilePathRegexes(List.of("/Api/.*")); + assertTrue(ElbV2DataPlane.pathRegexMatches(patterns, "/Api/x")); + assertFalse(ElbV2DataPlane.pathRegexMatches(patterns, "/api/x")); + } + + @Test + void anExpressionThatDoesNotCompileNeverMatches() { + List patterns = ElbV2DataPlane.compilePathRegexes(List.of("(", "/ok")); + assertEquals(1, patterns.size()); + assertTrue(ElbV2DataPlane.pathRegexMatches(patterns, "/ok")); + assertFalse(ElbV2DataPlane.pathRegexMatches(patterns, null)); + } + + @Test + void validationAcceptsSupportedExpressions() { + assertDoesNotThrow(() -> PathPatternRegexValues.validate(MATCH_PATTERNS, false)); + } + + @Test + void validationRejectsValuesTogetherWithRegexValues() { + AwsException e = assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of("^/a$"), true)); + assertEquals("ValidationError", e.getErrorCode()); + assertEquals("You must provide exactly one of the following: ['Values' 'RegexValues']" + + " for config of type 'PathPatternConfig'", e.getMessage()); + } + + @Test + void validationRejectsAFourthExpressionBeforeCompiling() { + assertDoesNotThrow(() -> PathPatternRegexValues.validate(List.of("/a", "/b", "/c"), false)); + AwsException error = assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of("(", "/b", "/c", "/d"), false)); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("A condition can have at most three match evaluations.", error.getMessage()); + } + + @Test + void validationRejectsInvalidAndOverlongExpressions() { + assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of(""), false)); + AwsException error = assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of("(unclosed"), false)); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("One or more provided condition regex values are not valid", error.getMessage()); + assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of("a".repeat(129)), false)); + assertDoesNotThrow(() -> PathPatternRegexValues.validate(List.of("a".repeat(128)), false)); + } + + @Test + void validationRejectsUnsupportedAwsSyntax() { + for (String regex : List.of("/a(?=b)", "/a(?!b)", "(?<=a)/b", "(?/a)\\k", "(?>/a)", "/a*+", "/a++", "/a?+", "/a{1,2}+", + "(?R)", "(?1)", "(?&part)", "\\p{L}", "\\P{L}", "[\\p{L}]")) { + AwsException error = assertThrows(AwsException.class, + () -> PathPatternRegexValues.validate(List.of(regex), false), regex); + assertEquals("ValidationError", error.getErrorCode(), regex); + assertEquals("One or more provided condition regex values are not valid", error.getMessage(), regex); + assertTrue(ElbV2DataPlane.compilePathRegexes(List.of(regex)).isEmpty(), regex); + } + } + + @Test + void escapedUnsupportedSyntaxRemainsLiteral() { + for (String regex : List.of("/\\(\\?=a\\)", "\\\\p\\{L\\}", "\\Q\\p{L}(?=a)\\E", "/(?:a|b)+?")) { + assertDoesNotThrow(() -> PathPatternRegexValues.validate(List.of(regex), false), regex); + } + assertTrue(ElbV2DataPlane.pathRegexMatches( + ElbV2DataPlane.compilePathRegexes(List.of("\\Q\\p{L}(?=a)\\E")), "\\p{L}(?=a)")); + } + + @Test + void nestedRepetitionDoesNotBacktrackOnLongPaths() { + List patterns = ElbV2DataPlane.compilePathRegexes( + List.of("^/(a+)+$", "^/(a|aa)+$", "^/a*a*a*a*a*b$")); + assertTrue(ElbV2DataPlane.pathRegexMatches(patterns, "/" + "a".repeat(1000))); + assertTimeout(Duration.ofSeconds(3), () -> + assertFalse(ElbV2DataPlane.pathRegexMatches(patterns, "/" + "a".repeat(100_000) + "!"))); + } + + @Test + void storedConditionsRetainRegexValuesAndAcceptOlderGlobOnlyData() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + RuleCondition original = new RuleCondition(); + original.setField("path-pattern"); + original.setPathPatternRegexValues(MATCH_PATTERNS); + RuleCondition restored = mapper.readValue(mapper.writeValueAsBytes(original), RuleCondition.class); + assertTrue(ElbV2DataPlane.pathRegexMatches( + ElbV2DataPlane.compilePathRegexes(restored.getPathPatternRegexValues()), "/api/orders/42")); + assertEquals(MATCH_PATTERNS, restored.getPathPatternRegexValues()); + + RuleCondition legacy = mapper.readValue(""" + { + "field": "path-pattern", + "pathPatternValues": ["/assets/*"] + } + """, RuleCondition.class); + assertTrue(legacy.getPathPatternRegexValues().isEmpty()); + assertEquals(List.of("/assets/*"), legacy.getPathPatternValues()); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/PathRegexFixtures.java b/src/test/java/io/floci/aws/services/elbv2/PathRegexFixtures.java new file mode 100644 index 0000000000..2d1355dc19 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/PathRegexFixtures.java @@ -0,0 +1,12 @@ +package io.floci.aws.services.elbv2; + +import java.util.List; + +final class PathRegexFixtures { + + static final List MATCH_PATTERNS = List.of( + "^/api/(items|orders)(/.*)?$", "^/status/[0-9]+$"); + + private PathRegexFixtures() { + } +}