mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
feat(ec2): EC2 Instance Connect Endpoint tunnel (open-tunnel / eice SSH over WebSocket) (#7519)
This commit is contained in:
1 parent
c769ce055a
commit
475fb1822a
15 files changed
+1249
-15
No files matched your search
@@ -4,9 +4,16 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.services.ec2.model.GroupIdentifier;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.IpRange;
|
||||
import io.floci.aws.services.ec2.model.NetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.PrefixListEntry;
|
||||
import io.floci.aws.services.ec2.model.PrefixListId;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2.model.UserIdGroupPair;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
@@ -387,4 +394,81 @@ class Ec2InstanceConnectEndpointServiceTest {
|
||||
assertEquals("InvalidNetworkInterfaceID.NotFound", assertThrows(AwsException.class, () -> service
|
||||
.describeNetworkInterfaces(REGION, List.of(eniId), Map.of())).getErrorCode());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void tunnelReachNeedsTheEndpointsEgressAndTheInstancesIngress() {
|
||||
Ec2Service service = mockModeService();
|
||||
String vpcId = service.createVpc(REGION, "10.73.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(REGION, vpcId, "10.73.1.0/24", "us-east-1a").getSubnetId();
|
||||
String eiceGroup = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId();
|
||||
String hostGroup = service.createSecurityGroup(REGION, "host", "x", vpcId).getGroupId();
|
||||
service.revokeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("-1", null, null, null, "0.0.0.0/0")));
|
||||
service.authorizeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("tcp", 22, 22, hostGroup, null)));
|
||||
Instance instance = service.runInstances(REGION, "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
|
||||
List.of(hostGroup), subnetId, null, List.of(), null, null).getInstances().getFirst();
|
||||
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId,
|
||||
List.of(eiceGroup), null, null, List.of(), null);
|
||||
|
||||
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 22), "no ingress on the host yet");
|
||||
service.authorizeSecurityGroupIngress(REGION, hostGroup, List.of(permission("tcp", 22, 22, eiceGroup, null)));
|
||||
assertTrue(service.instanceConnectEndpointMayReach(endpoint, instance, 22));
|
||||
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 3389), "the endpoint may only send 22");
|
||||
assertTrue(service.findRunningInstanceByPrivateIp(REGION, vpcId, instance.getPrivateIpAddress()).isEmpty(),
|
||||
"a pending instance is not a tunnel target");
|
||||
// Mock mode has no container to report the launch; mark it running as the launch would.
|
||||
service.getInstance(REGION, instance.getInstanceId()).orElseThrow().setState(InstanceState.running());
|
||||
assertEquals(instance.getInstanceId(), service.findRunningInstanceByPrivateIp(REGION, vpcId,
|
||||
instance.getPrivateIpAddress()).orElseThrow().getInstanceId());
|
||||
|
||||
service.deleteInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId());
|
||||
assertTrue(service.findUsableInstanceConnectEndpoint(REGION, endpoint.getInstanceConnectEndpointId())
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tunnelReachHonoursPrefixListRules() {
|
||||
Ec2Service service = mockModeService();
|
||||
String vpcId = service.createVpc(REGION, "10.74.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(REGION, vpcId, "10.74.1.0/24", "us-east-1a").getSubnetId();
|
||||
String eiceGroup = service.createSecurityGroup(REGION, "eice", "x", vpcId).getGroupId();
|
||||
String hostGroup = service.createSecurityGroup(REGION, "host", "x", vpcId).getGroupId();
|
||||
String subnetList = service.createManagedPrefixList(REGION, "subnet", "IPv4", 2,
|
||||
List.of(new PrefixListEntry("10.74.1.0/24", null)), List.of()).getPrefixListId();
|
||||
service.revokeSecurityGroupEgress(REGION, eiceGroup, List.of(permission("-1", null, null, null, "0.0.0.0/0")));
|
||||
service.authorizeSecurityGroupEgress(REGION, eiceGroup, List.of(prefixListPermission(subnetList)));
|
||||
Instance instance = service.runInstances(REGION, "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
|
||||
List.of(hostGroup), subnetId, null, List.of(), null, null).getInstances().getFirst();
|
||||
InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(REGION, subnetId,
|
||||
List.of(eiceGroup), null, null, List.of(), null);
|
||||
|
||||
assertFalse(service.instanceConnectEndpointMayReach(endpoint, instance, 22), "no ingress on the host yet");
|
||||
service.authorizeSecurityGroupIngress(REGION, hostGroup, List.of(prefixListPermission(subnetList)));
|
||||
assertTrue(service.instanceConnectEndpointMayReach(endpoint, instance, 22),
|
||||
"both sides name the subnet through a prefix list");
|
||||
}
|
||||
|
||||
private static IpPermission prefixListPermission(String prefixListId) {
|
||||
IpPermission permission = permission("tcp", 22, 22, null, null);
|
||||
permission.setPrefixListIds(new ArrayList<>(List.of(new PrefixListId(prefixListId, null))));
|
||||
return permission;
|
||||
}
|
||||
|
||||
private static IpPermission permission(String protocol, Integer from, Integer to, String groupId, String cidr) {
|
||||
IpPermission permission = new IpPermission();
|
||||
permission.setIpProtocol(protocol);
|
||||
permission.setFromPort(from);
|
||||
permission.setToPort(to);
|
||||
if (groupId != null) {
|
||||
UserIdGroupPair pair = new UserIdGroupPair();
|
||||
pair.setGroupId(groupId);
|
||||
permission.setUserIdGroupPairs(new ArrayList<>(List.of(pair)));
|
||||
}
|
||||
if (cidr != null) {
|
||||
IpRange range = new IpRange();
|
||||
range.setCidrIp(cidr);
|
||||
permission.setIpRanges(new ArrayList<>(List.of(range)));
|
||||
}
|
||||
return permission;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The tunnel is a Vert.x route, outside the JAX-RS filters that set the request's account. It must
|
||||
* still read the endpoint from the account the presigned credential names: before, every lookup
|
||||
* fell back to the default account, so another account's endpoint was never found and a caller
|
||||
* from any account reached the default account's instances.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class InstanceConnectTunnelAccountIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
|
||||
@Inject
|
||||
InstanceConnectTunnelHandler handler;
|
||||
|
||||
@Test
|
||||
void theEndpointIsLookedUpInTheCredentialsAccountOnly() {
|
||||
String vpcId = XmlParser.extractFirst(ec2("CreateVpc", "CidrBlock", "10.91.0.0/16"), "vpcId", null);
|
||||
String subnetId = XmlParser.extractFirst(
|
||||
ec2("CreateSubnet", "VpcId", vpcId, "CidrBlock", "10.91.1.0/24"), "subnetId", null);
|
||||
String endpointId = XmlParser.extractFirst(
|
||||
ec2("CreateInstanceConnectEndpoint", "SubnetId", subnetId), "instanceConnectEndpointId", null);
|
||||
assertTrue(endpointId.startsWith("eice-"), endpointId);
|
||||
|
||||
InstanceConnectTunnelHandler.Refusal asOwner = refusal(ACCOUNT, endpointId);
|
||||
assertEquals(404, asOwner.status);
|
||||
assertTrue(asOwner.getMessage().startsWith("No running instance"),
|
||||
"the owner's credential finds the endpoint: " + asOwner.getMessage());
|
||||
|
||||
InstanceConnectTunnelHandler.Refusal asDefault = refusal("000000000000", endpointId);
|
||||
assertEquals(404, asDefault.status);
|
||||
assertTrue(asDefault.getMessage().startsWith("No available EC2 Instance Connect Endpoint"),
|
||||
"another account's credential does not: " + asDefault.getMessage());
|
||||
}
|
||||
|
||||
private InstanceConnectTunnelHandler.Refusal refusal(String accessKey, String endpointId) {
|
||||
String query = "instanceConnectEndpointId=" + endpointId + "&remotePort=22&privateIpAddress=10.91.1.200&"
|
||||
+ EnforcementFixtures.presignedQuery(accessKey, "ec2-instance-connect");
|
||||
return assertThrows(InstanceConnectTunnelHandler.Refusal.class,
|
||||
() -> handler.resolve("/openTunnel", query, name -> null));
|
||||
}
|
||||
|
||||
private static String ec2(String action, String... params) {
|
||||
RequestSpecification request = given().formParam("Action", action)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261019/us-east-1/ec2/aws4_request");
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.IamEnforcementFilter;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.model.AccessKey;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* The EC2 User Guide's OpenTunnel policies, through the path the tunnel handler takes: the shared
|
||||
* filter fills {@code ec2-instance-connect:remotePort}, {@code privateIpAddress} and
|
||||
* {@code maxTunnelDuration} from the query parameters, by the table in request-condition-keys.json.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class InstanceConnectTunnelConditionKeysIntegrationTest {
|
||||
|
||||
private static final String ACTION = "ec2-instance-connect:OpenTunnel";
|
||||
private static final String ENDPOINT = "arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/eice-0123456789abcdef0";
|
||||
|
||||
@Inject
|
||||
IamService iam;
|
||||
@Inject
|
||||
IamEnforcementFilter enforcement;
|
||||
|
||||
@Test
|
||||
void anAllowScopedToPortAddressAndDurationAppliesToTheTunnelsQuery() {
|
||||
String key = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ec2-instance-connect:OpenTunnel",
|
||||
"Resource":"*","Condition":{
|
||||
"NumericEquals":{"ec2-instance-connect:remotePort":22},
|
||||
"IpAddress":{"ec2-instance-connect:privateIpAddress":"10.0.0.0/24"},
|
||||
"NumericLessThanEquals":{"ec2-instance-connect:maxTunnelDuration":600}}}]}""");
|
||||
|
||||
assertDoesNotThrow(() -> open(key, "22", "10.0.0.5", "300"));
|
||||
assertDenied(key, "3389", "10.0.0.5", "300");
|
||||
assertDenied(key, "22", "10.0.1.5", "300");
|
||||
assertDenied(key, "22", "10.0.0.5", "900");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyScopedToAPortRefusesThatPortOnly() {
|
||||
String key = userWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2-instance-connect:OpenTunnel","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"ec2-instance-connect:OpenTunnel","Resource":"*",
|
||||
"Condition":{"NumericEquals":{"ec2-instance-connect:remotePort":3389}}}]}""");
|
||||
|
||||
assertDoesNotThrow(() -> open(key, "22", "10.0.0.5", "300"));
|
||||
assertDenied(key, "3389", "10.0.0.5", "300");
|
||||
}
|
||||
|
||||
private String userWith(String policy) {
|
||||
String user = "eice-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
iam.createUser(user, "/");
|
||||
iam.putUserPolicy(user, "tunnel", policy);
|
||||
AccessKey key = iam.createAccessKey(user);
|
||||
return key.getAccessKeyId();
|
||||
}
|
||||
|
||||
private void open(String accessKeyId, String port, String ip, String max) {
|
||||
Map<String, String> query = Map.of("remotePort", port, "privateIpAddress", ip, "maxTunnelDuration", max);
|
||||
enforcement.authorizeRequestParameters(auth(accessKeyId, "ec2-instance-connect"), ACTION, ENDPOINT,
|
||||
query::get);
|
||||
}
|
||||
|
||||
private void assertDenied(String accessKeyId, String port, String ip, String max) {
|
||||
assertThrows(AwsException.class, () -> open(accessKeyId, port, ip, max), port + " " + ip + " " + max);
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.IamEnforcementFilter;
|
||||
import io.floci.aws.core.common.SessionAccountLookup;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.nullable;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class InstanceConnectTunnelHandlerTest {
|
||||
|
||||
private static final String EICE = "eice-0123456789abcdef0";
|
||||
private static final String HOST = EICE + ".localhost.floci.io";
|
||||
private static final String ARN = "arn:aws:ec2:us-east-1:000000000000:instance-connect-endpoint/" + EICE;
|
||||
/**
|
||||
* Produced by AWS CLI 2.38.1's own signer ({@code InstanceConnectEndpointRequestSigner}) with access
|
||||
* key AKIAFLOCITUNNELTEST1 and secret {@code tunnelsecret}: the exact URL {@code open-tunnel} dials.
|
||||
*/
|
||||
private static final String CLI_QUERY = "instanceConnectEndpointId=" + EICE
|
||||
+ "&remotePort=22&privateIpAddress=10.0.1.10&maxTunnelDuration=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256"
|
||||
+ "&X-Amz-Credential=AKIAFLOCITUNNELTEST1%2F20261019%2Fus-east-1%2Fec2-instance-connect%2Faws4_request"
|
||||
+ "&X-Amz-Date=20261019T183743Z&X-Amz-Expires=60&X-Amz-SignedHeaders=host"
|
||||
+ "&X-Amz-Signature=52d3a1720534fa6940d19223dba7516507774db4c7f24e50c92116cd63fee0b2";
|
||||
private static final Instant NOW = Instant.parse("2026-10-19T18:38:13Z");
|
||||
|
||||
private Ec2Service ec2;
|
||||
private EmulatorConfig config;
|
||||
private IamService iam;
|
||||
private SessionAccountLookup sessions;
|
||||
private IamEnforcementFilter enforcement;
|
||||
private InstanceConnectTunnelHandler handler;
|
||||
private Instance instance;
|
||||
private InstanceConnectEndpoint endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ec2 = mock(Ec2Service.class);
|
||||
config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
when(config.services().ec2instanceconnect().enabled()).thenReturn(true);
|
||||
iam = mock(IamService.class);
|
||||
sessions = mock(SessionAccountLookup.class);
|
||||
enforcement = mock(IamEnforcementFilter.class);
|
||||
when(sessions.resolveAccountId(anyString())).thenReturn(Optional.empty());
|
||||
when(iam.findSecretKey(eq("AKIAFLOCITUNNELTEST1"), nullable(String.class)))
|
||||
.thenReturn(Optional.of("tunnelsecret"));
|
||||
handler = new InstanceConnectTunnelHandler(ec2, null, config, iam, new AccountResolver("000000000000"),
|
||||
sessions, enforcement, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
endpoint = new InstanceConnectEndpoint();
|
||||
endpoint.setInstanceConnectEndpointId(EICE);
|
||||
endpoint.setInstanceConnectEndpointArn(ARN);
|
||||
endpoint.setVpcId("vpc-1");
|
||||
instance = new Instance();
|
||||
instance.setInstanceId("i-0123456789abcdef0");
|
||||
instance.setPrivateIpAddress("10.0.1.10");
|
||||
instance.setContainerBridgeIp("192.168.97.5");
|
||||
when(ec2.findUsableInstanceConnectEndpoint(anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(ec2.findUsableInstanceConnectEndpoint("us-east-1", EICE)).thenReturn(Optional.of(endpoint));
|
||||
when(ec2.findRunningInstanceByPrivateIp(anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(ec2.findRunningInstanceByPrivateIp("us-east-1", "vpc-1", "10.0.1.10")).thenReturn(Optional.of(instance));
|
||||
when(ec2.instanceConnectEndpointMayReach(eq(endpoint), eq(instance), anyInt())).thenReturn(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesTheCliUrlToTheInstancesReachableAddress() {
|
||||
InstanceConnectTunnelHandler.Target target = resolve(CLI_QUERY);
|
||||
|
||||
assertEquals("192.168.97.5", target.host());
|
||||
assertEquals(22, target.port());
|
||||
assertEquals(3600, target.maxSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sshIsAlsoOfferedOnThePublishedHostPort() {
|
||||
assertEquals(0, resolve(CLI_QUERY).fallbackPort(), "nothing published, nothing to fall back to");
|
||||
|
||||
instance.setSshHostPort(32022);
|
||||
InstanceConnectTunnelHandler.Target target = resolve(CLI_QUERY);
|
||||
assertEquals("127.0.0.1", target.fallbackHost());
|
||||
assertEquals(32022, target.fallbackPort());
|
||||
assertEquals("192.168.97.5", target.host(), "the container address is still tried first");
|
||||
|
||||
assertEquals(0, resolve(CLI_QUERY.replace("remotePort=22", "remotePort=3389")).fallbackPort(),
|
||||
"only SSH is published");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesEveryTunnelWhenTheServiceIsDisabled() {
|
||||
when(config.services().ec2instanceconnect().enabled()).thenReturn(false);
|
||||
assertEquals(404, refusal(CLI_QUERY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesWhatAwsRefuses() {
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("ec2-instance-connect%2Faws4", "ec2%2Faws4")));
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Algorithm=AWS4-HMAC-SHA256&", "")));
|
||||
assertEquals(400, refusal(CLI_QUERY.replace("remotePort=22", "remotePort=6443")));
|
||||
assertEquals(400, refusal(CLI_QUERY.replace("maxTunnelDuration=3600", "maxTunnelDuration=3601")));
|
||||
assertEquals(404, refusal(CLI_QUERY.replace("instanceConnectEndpointId=" + EICE,
|
||||
"instanceConnectEndpointId=eice-0000000000000000f")));
|
||||
assertEquals(404, refusal(CLI_QUERY.replace("10.0.1.10", "10.0.1.99")));
|
||||
for (String bad : List.of("not-an-ip", "10.0.0.256", "::1", "10.0.1")) {
|
||||
assertEquals(400, refusal(CLI_QUERY.replace("10.0.1.10", bad)), bad);
|
||||
}
|
||||
when(ec2.instanceConnectEndpointMayReach(eq(endpoint), eq(instance), anyInt())).thenReturn(false);
|
||||
assertEquals(403, refusal(CLI_QUERY), "security groups deny");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiryIsBoundedAndAFutureSigningTimeIsRefused() {
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=20261019T183600Z")),
|
||||
"signed 133 s ago, valid 60 s");
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=0")));
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=604801")));
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Expires=60", "X-Amz-Expires=9223372036854775807")),
|
||||
"used to overflow Instant.plusSeconds into a 500");
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=20261019T185000Z")),
|
||||
"signed twelve minutes ahead");
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Date=20261019T183743Z", "X-Amz-Date=yesterday")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withSignatureValidationTheCliSignatureVerifiesAndATamperedOneDoesNot() {
|
||||
when(config.auth().validateSignatures()).thenReturn(true);
|
||||
|
||||
assertEquals(22, resolve(CLI_QUERY).port());
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("privateIpAddress=10.0.1.10", "privateIpAddress=10.0.1.11")),
|
||||
"the target is covered by the signature");
|
||||
assertEquals(403, refusal(CLI_QUERY.replace("X-Amz-Signature=52", "X-Amz-Signature=53")));
|
||||
when(iam.findSecretKey(eq("AKIAFLOCITUNNELTEST1"), nullable(String.class))).thenReturn(Optional.empty());
|
||||
assertEquals(403, refusal(CLI_QUERY), "an access key Floci never issued");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutSignatureValidationTheSignatureIsNotChecked() {
|
||||
assertEquals(22, resolve(CLI_QUERY.replace("X-Amz-Signature=52", "X-Amz-Signature=53")).port());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withIamEnforcementOpenTunnelIsAuthorizedOnTheEndpoint() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(iam.isKnownAccessKey("AKIAFLOCITUNNELTEST1")).thenReturn(true);
|
||||
|
||||
resolve(CLI_QUERY);
|
||||
ArgumentCaptor<Function<String, String>> parameter = ArgumentCaptor.forClass(Function.class);
|
||||
verify(enforcement).authorizeRequestParameters(
|
||||
eq("AWS4-HMAC-SHA256 Credential=AKIAFLOCITUNNELTEST1/20261019/us-east-1/ec2-instance-connect/aws4_request"),
|
||||
eq("ec2-instance-connect:OpenTunnel"), eq(ARN), parameter.capture());
|
||||
assertEquals("22", parameter.getValue().apply("remotePort"));
|
||||
assertEquals("10.0.1.10", parameter.getValue().apply("privateIpAddress"));
|
||||
assertEquals("3600", parameter.getValue().apply("maxTunnelDuration"));
|
||||
|
||||
// Omitted, it is the 3600 the tunnel opens with, so a policy on it still applies.
|
||||
clearInvocations(enforcement);
|
||||
resolve(CLI_QUERY.replace("&maxTunnelDuration=3600", ""));
|
||||
verify(enforcement).authorizeRequestParameters(anyString(), anyString(), anyString(), parameter.capture());
|
||||
assertEquals("3600", parameter.getValue().apply("maxTunnelDuration"));
|
||||
|
||||
doThrow(new AwsException("AccessDenied", "denied", 403)).when(enforcement)
|
||||
.authorizeRequestParameters(anyString(), anyString(), anyString(), any());
|
||||
assertEquals(403, refusal(CLI_QUERY));
|
||||
|
||||
when(iam.isKnownAccessKey("AKIAFLOCITUNNELTEST1")).thenReturn(false);
|
||||
assertEquals(403, refusal(CLI_QUERY), "an unknown key is refused under enforcement");
|
||||
}
|
||||
|
||||
private InstanceConnectTunnelHandler.Target resolve(String query) {
|
||||
return handler.resolve("/openTunnel", query, name -> "host".equals(name) ? HOST : null);
|
||||
}
|
||||
|
||||
private int refusal(String query) {
|
||||
return assertThrows(InstanceConnectTunnelHandler.Refusal.class, () -> resolve(query)).status;
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceConnectEndpoint;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.UpgradeRejectedException;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
import io.vertx.core.net.NetServer;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import io.vertx.ext.web.Router;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* {@code open()} against real sockets: a WebSocket client, the handler on a Vert.x router, and a local
|
||||
* TCP server standing in for the instance's port. {@code resolve()} (covered by
|
||||
* {@link InstanceConnectTunnelHandlerTest}) is replaced so the tunnel dials that server.
|
||||
*/
|
||||
class InstanceConnectTunnelOpenTest {
|
||||
|
||||
private Vertx vertx;
|
||||
private NetServer instancePort;
|
||||
private HttpServer floci;
|
||||
private HttpClient client;
|
||||
private final CompletableFuture<NetSocket> instanceSide = new CompletableFuture<>();
|
||||
private final CompletableFuture<Void> instanceSideClosed = new CompletableFuture<>();
|
||||
private int targetPort;
|
||||
private int maxSeconds = 60;
|
||||
/** Written by the instance as soon as the tunnel connects, before it reads anything, as sshd does. */
|
||||
private String banner;
|
||||
/** When set, the instance accepts the connection and closes it at once. */
|
||||
private boolean closeOnConnect;
|
||||
/** When set, the address the instance reports is dead and only the published port reaches it. */
|
||||
private boolean publishedPortOnly;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
instancePort = vertx.createNetServer().connectHandler(socket -> {
|
||||
instanceSide.complete(socket);
|
||||
if (closeOnConnect) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
if (banner != null) {
|
||||
socket.write(banner);
|
||||
}
|
||||
socket.handler(socket::write);
|
||||
socket.closeHandler(ignored -> instanceSideClosed.complete(null));
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
targetPort = instancePort.actualPort();
|
||||
|
||||
InstanceConnectTunnelHandler handler = new InstanceConnectTunnelHandler(null, vertx, null, null, null,
|
||||
null, null) {
|
||||
@Override
|
||||
Target resolve(String rawPath, String rawQuery, UnaryOperator<String> header) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-0123456789abcdef0");
|
||||
instance.setPrivateIpAddress("10.0.1.10");
|
||||
if (publishedPortOnly) {
|
||||
return new Target(new InstanceConnectEndpoint(), instance, "127.0.0.1", closedPort(), maxSeconds,
|
||||
"127.0.0.1", targetPort);
|
||||
}
|
||||
return new Target(new InstanceConnectEndpoint(), instance, "127.0.0.1", targetPort, maxSeconds, null, 0);
|
||||
}
|
||||
};
|
||||
Router router = Router.router(vertx);
|
||||
handler.init(router);
|
||||
floci = vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
client = vertx.createHttpClient();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bytesCrossTheTunnelBothWays() throws Exception {
|
||||
WebSocket webSocket = connect();
|
||||
CompletableFuture<Buffer> echoed = new CompletableFuture<>();
|
||||
webSocket.binaryMessageHandler(echoed::complete);
|
||||
webSocket.writeBinaryMessage(Buffer.buffer("SSH-2.0-test\r\n"));
|
||||
|
||||
assertEquals("SSH-2.0-test\r\n", echoed.get(5, TimeUnit.SECONDS).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBannerTheInstanceWritesOnConnectReachesTheClient() throws Exception {
|
||||
banner = "SSH-2.0-OpenSSH_9.6\r\n";
|
||||
CompletableFuture<Buffer> received = new CompletableFuture<>();
|
||||
// The handler is set inside the completion callback, so the client cannot itself lose the frame.
|
||||
client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH)
|
||||
.onSuccess(ws -> ws.binaryMessageHandler(received::complete))
|
||||
.onFailure(received::completeExceptionally);
|
||||
|
||||
assertEquals(banner, received.get(5, TimeUnit.SECONDS).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingTheWebSocketClosesTheInstanceConnection() throws Exception {
|
||||
WebSocket webSocket = connect();
|
||||
instanceSide.get(5, TimeUnit.SECONDS);
|
||||
webSocket.close();
|
||||
|
||||
instanceSideClosed.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInstanceClosingClosesTheWebSocket() throws Exception {
|
||||
WebSocket webSocket = connect();
|
||||
CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
webSocket.closeHandler(ignored -> closed.complete(null));
|
||||
instanceSide.get(5, TimeUnit.SECONDS).close();
|
||||
|
||||
closed.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceThatClosesBeforeTheUpgradeCompletesStillClosesTheWebSocket() throws Exception {
|
||||
closeOnConnect = true;
|
||||
CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH).onSuccess(ws -> {
|
||||
if (ws.isClosed()) {
|
||||
closed.complete(null);
|
||||
} else {
|
||||
ws.closeHandler(ignored -> closed.complete(null));
|
||||
}
|
||||
}).onFailure(closed::completeExceptionally);
|
||||
|
||||
closed.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxTunnelDurationClosesBothSides() throws Exception {
|
||||
maxSeconds = 1;
|
||||
WebSocket webSocket = connect();
|
||||
CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
webSocket.closeHandler(ignored -> closed.complete(null));
|
||||
|
||||
closed.get(5, TimeUnit.SECONDS);
|
||||
instanceSideClosed.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreachableInstanceIsA504BeforeTheUpgrade() throws Exception {
|
||||
instancePort.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
|
||||
ExecutionException failed = assertThrows(ExecutionException.class, this::connect);
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failed.getCause());
|
||||
assertEquals(504, rejected.getStatus());
|
||||
assertTrue(rejected.getBody() == null || rejected.getBody().toString().contains("Unable to reach"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressFlociCannotRouteToFallsBackToThePublishedPort() throws Exception {
|
||||
publishedPortOnly = true;
|
||||
WebSocket webSocket = connect();
|
||||
CompletableFuture<Buffer> echoed = new CompletableFuture<>();
|
||||
webSocket.binaryMessageHandler(echoed::complete);
|
||||
webSocket.writeBinaryMessage(Buffer.buffer("SSH-2.0-test\r\n"));
|
||||
|
||||
assertEquals("SSH-2.0-test\r\n", echoed.get(5, TimeUnit.SECONDS).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenBothAddressesRefuseTheAnswerIsA504() throws Exception {
|
||||
publishedPortOnly = true;
|
||||
instancePort.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
|
||||
ExecutionException failed = assertThrows(ExecutionException.class, this::connect);
|
||||
assertEquals(504, assertInstanceOf(UpgradeRejectedException.class, failed.getCause()).getStatus());
|
||||
}
|
||||
|
||||
private static int closedPort() {
|
||||
try (ServerSocket probe = new ServerSocket(0)) {
|
||||
return probe.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private WebSocket connect() throws Exception {
|
||||
return client.webSocket(floci.actualPort(), "127.0.0.1", InstanceConnectTunnelHandler.PATH)
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.model.AccessKey;
|
||||
import io.floci.aws.testing.TestAccounts;
|
||||
import io.floci.aws.testing.ValidateSignaturesProfile;
|
||||
import io.floci.aws.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* With signature validation on, a tunnel signed by an IAM access key that belongs to another
|
||||
* account has to get past the signature check: the secret is stored in that account, so it is only
|
||||
* found once the request runs as that account.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
class InstanceConnectTunnelSignedAccountIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
InstanceConnectTunnelHandler handler;
|
||||
@Inject
|
||||
IamService iam;
|
||||
@Inject
|
||||
Ec2Service ec2;
|
||||
|
||||
@Test
|
||||
void anAccessKeyOfAnotherAccountPassesTheSignatureCheck() throws Exception {
|
||||
String account = TestAccounts.randomId();
|
||||
AccessKey key = RequestScopes.callAs(account, () -> {
|
||||
iam.createUser("eice-user", "/");
|
||||
return iam.createAccessKey("eice-user");
|
||||
});
|
||||
String endpointId = RequestScopes.callAs(account, REGION, () -> {
|
||||
String vpcId = ec2.createVpc(REGION, "10.92.0.0/16", false).getVpcId();
|
||||
String subnetId = ec2.createSubnet(REGION, vpcId, "10.92.1.0/24", "us-east-1a").getSubnetId();
|
||||
return ec2.createInstanceConnectEndpoint(REGION, subnetId, List.of(), null, null, List.of(), null)
|
||||
.getInstanceConnectEndpointId();
|
||||
});
|
||||
|
||||
String query = signedQuery(key, endpointId);
|
||||
InstanceConnectTunnelHandler.Refusal refusal = assertThrows(InstanceConnectTunnelHandler.Refusal.class,
|
||||
() -> handler.resolve("/openTunnel", query, name -> "host".equals(name) ? "localhost" : null));
|
||||
// Past the signature and the endpoint lookup, refused only for want of an instance.
|
||||
assertEquals(404, refusal.status, refusal.getMessage());
|
||||
assertTrue(refusal.getMessage().startsWith("No running instance"), refusal.getMessage());
|
||||
|
||||
String tampered = query.replace("remotePort=22", "remotePort=3389");
|
||||
assertEquals(403, assertThrows(InstanceConnectTunnelHandler.Refusal.class,
|
||||
() -> handler.resolve("/openTunnel", tampered, name -> "host".equals(name) ? "localhost" : null)).status);
|
||||
}
|
||||
|
||||
/** A presigned tunnel URL as the AWS CLI signs it: GET, the query, the host header, an empty body. */
|
||||
private static String signedQuery(AccessKey key, String endpointId) throws Exception {
|
||||
return AwsRequestSigner.signedAs(key.getAccessKeyId(), key.getSecretAccessKey(), "ec2-instance-connect")
|
||||
.presignedUri("GET", URI.create("http://localhost/openTunnel"), Map.of(
|
||||
"instanceConnectEndpointId", endpointId, "remotePort", "22",
|
||||
"privateIpAddress", "10.92.1.200"), new byte[0]).getRawQuery();
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,31 @@ class IamPolicyEvaluatorTest {
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "s3:ListBucket", "*", over));
|
||||
}
|
||||
|
||||
@Test
|
||||
void openTunnelConditionKeysScopeAnAllowToPortAddressAndDuration() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"ec2-instance-connect:OpenTunnel","Resource":"*","Condition":{
|
||||
"NumericEquals":{"ec2-instance-connect:remotePort":22},
|
||||
"IpAddress":{"ec2-instance-connect:privateIpAddress":"10.0.0.0/24"},
|
||||
"NumericLessThanEquals":{"ec2-instance-connect:maxTunnelDuration":600}}}]}""";
|
||||
String action = "ec2-instance-connect:OpenTunnel";
|
||||
String port = "ec2-instance-connect:remotePort";
|
||||
String ip = "ec2-instance-connect:privateIpAddress";
|
||||
String max = "ec2-instance-connect:maxTunnelDuration";
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"), max, List.of("300"))));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
Map.of(port, List.of("3389"), ip, List.of("10.0.0.5"), max, List.of("300"))));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
Map.of(port, List.of("22"), ip, List.of("10.0.1.5"), max, List.of("300"))));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"), max, List.of("900"))));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
Map.of(port, List.of("22"), ip, List.of("10.0.0.5"))), "a key the caller never supplies");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullConditionReadsUnquotedBooleanValues() {
|
||||
String requireAbsent = """
|
||||
|
||||
Reference in new issue
Block a user