mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(elbv2): support path-pattern regex conditions (#9387)
Listener rules now accept PathPatternConfig.RegexValues. CreateRule, ModifyRule, DescribeRules and CloudFormation keep the expressions, and both admission paths validate them before a mutation: glob and regex values can't be mixed, an expression must compile under RE2/J and avoid the syntax the ALB guide leaves out, and the condition and per-rule evaluation limits apply. The three refusals for mixed values, invalid syntax and too many values use AWS's recorded ValidationError messages. The data plane compiles a rule chain's expressions once and matches the request path without its query string, leaving glob matching as it was. Co-authored-by: Tyler Parmelee <7409652+tparmelee@users.noreply.github.com> Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
11 files changed
+849
-14
No files matched your search
+135
@@ -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<String> 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<String> 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<List<RuleCondition>> 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)));
|
||||
|
||||
+337
@@ -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|<item>)$";
|
||||
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<List<RuleCondition>> rejectedConditions = List.of(
|
||||
List.of(misplaced), List.of(fourRegexes), List.of(regex, threeHosts));
|
||||
List<String> 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<RuleCondition> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Compiled> 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<Compiled> 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<Compiled> patterns = ElbV2DataPlane.compilePathRegexes(List.of("/Api/.*"));
|
||||
assertTrue(ElbV2DataPlane.pathRegexMatches(patterns, "/Api/x"));
|
||||
assertFalse(ElbV2DataPlane.pathRegexMatches(patterns, "/api/x"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpressionThatDoesNotCompileNeverMatches() {
|
||||
List<Compiled> 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)/b",
|
||||
"(/a)\\1", "(?<part>/a)\\k<part>", "(?>/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<Compiled> 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package io.floci.aws.services.elbv2;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
final class PathRegexFixtures {
|
||||
|
||||
static final List<String> MATCH_PATTERNS = List.of(
|
||||
"^/api/(items|orders)(/.*)?$", "^/status/[0-9]+$");
|
||||
|
||||
private PathRegexFixtures() {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user