feat(ec2-instance-connect): SendSSHPublicKey, verified by the unmodified AWS agent (#7473)

This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-08 18:24:23 -04:00
1 parent 0de5566d22
commit 3701d4d041
28 files changed
+1295 -11

No files matched your search

+1 -1
View File
@@ -299,7 +299,7 @@ Floci supports local emulation for application services, data services, eventing
| Core app services | S3, SQS, SNS, DynamoDB, Lambda, Lambda MicroVMs, Lambda Web Functions, IAM, STS, KMS, Payment Cryptography, Secrets Manager, SSM |
| Events and workflows | EventBridge, EventBridge V2, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) |
| API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator |
| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |
| Containers and compute | ECS, EC2, EC2 Instance Connect, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Redshift Serverless, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker |
| Databases and caching | Aurora DSQL, RDS, RDS Data API, Neptune, DocumentDB, DMS, MemoryDB, ElastiCache, Timestream for InfluxDB |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations |
@@ -229,6 +229,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>ec2</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ec2instanceconnect</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
@@ -56,6 +56,7 @@ import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Subnet;
import software.amazon.awssdk.services.ec2.model.Vpc;
import software.amazon.awssdk.services.ec2instanceconnect.Ec2InstanceConnectClient;
import software.amazon.awssdk.services.ecr.EcrClient;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.efs.EfsClient;
@@ -1846,6 +1847,14 @@ public final class TestFixtures {
.build();
}
public static Ec2InstanceConnectClient ec2InstanceConnectClient() {
return Ec2InstanceConnectClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();
}
public static EfsClient efsClient() {
return EfsClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,53 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2instanceconnect.Ec2InstanceConnectClient;
import software.amazon.awssdk.services.ec2instanceconnect.model.Ec2InstanceNotFoundException;
import software.amazon.awssdk.services.ec2instanceconnect.model.InvalidArgsException;
import software.amazon.awssdk.services.ec2instanceconnect.model.SendSshPublicKeyResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("EC2 Instance Connect")
class Ec2InstanceConnectTest {
private static final String ED25519 =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
@Test
@DisplayName("SendSSHPublicKey succeeds for a running instance and rejects a key SSH cannot use")
void sendSshPublicKey() {
try (Ec2Client ec2 = TestFixtures.ec2Client();
Ec2InstanceConnectClient connect = TestFixtures.ec2InstanceConnectClient()) {
String instanceId = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890")
.instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)).instances().get(0).instanceId();
try {
ec2.waiter().waitUntilInstanceRunning(r -> r.instanceIds(instanceId));
SendSshPublicKeyResponse response = connect.sendSSHPublicKey(r -> r.instanceId(instanceId)
.instanceOSUser("ec2-user").sshPublicKey(ED25519));
assertThat(response.success()).isTrue();
assertThat(response.requestId()).isNotBlank();
assertThatThrownBy(() -> connect.sendSSHPublicKey(r -> r.instanceId(instanceId)
.instanceOSUser("ec2-user").sshPublicKey("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 " + "c".repeat(80))))
.isInstanceOf(InvalidArgsException.class);
} finally {
ec2.terminateInstances(r -> r.instanceIds(instanceId));
}
}
}
@Test
@DisplayName("SendSSHPublicKey on an unknown instance raises EC2InstanceNotFoundException")
void unknownInstance() {
try (Ec2InstanceConnectClient connect = TestFixtures.ec2InstanceConnectClient()) {
assertThatThrownBy(() -> connect.sendSSHPublicKey(r -> r.instanceId("i-0000000000000000f")
.instanceOSUser("ec2-user").sshPublicKey(ED25519)))
.isInstanceOf(Ec2InstanceNotFoundException.class);
}
}
}
+61
View File
@@ -0,0 +1,61 @@
# EC2 Instance Connect
**Protocol:** JSON 1.1 (`X-Amz-Target: AWSEC2InstanceConnectService.*`)
**Endpoint:** `http://localhost:4566/`
`SendSSHPublicKey` pushes a public key that an instance's
[EC2 Instance Connect agent](https://github.com/aws/aws-ec2-instance-connect-config) accepts for 60
seconds, as on AWS. The agent runs unmodified: Floci serves the signed keys and their signing
material through IMDS, and the agent verifies them exactly as it does on EC2.
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `SendSSHPublicKey` | Push a public key for an OS user; the instance's agent accepts it for 60 seconds |
| `SendSerialConsoleSSHPublicKey` | Rejected with `SerialConsoleSessionUnsupportedException` once the instance is found: Docker-backed instances have no serial console |
<!-- floci:actions:end -->
## Validation
Requests are checked against the service model and the instance, with AWS's error codes:
- `InvalidArgsException`: an instance ID, OS user or availability zone outside the model's
pattern, a key shorter than 80 or longer than 4096 characters, a key spanning more than one line
or holding any other control character, a key type other than RSA,
ED25519 or ECDSA, a key whose encoded type differs from its prefix, or an RSA key under 2048
bits.
- `EC2InstanceNotFoundException`: no such instance in the region, or not in the given zone.
- `SerialConsoleSessionUnsupportedException`: `SendSerialConsoleSSHPublicKey` on an existing instance.
- `EC2InstanceStateInvalidException`: the instance is not `running`.
## What the instance sees
IMDS serves the agent's paths under `/latest/meta-data/`:
| Path | Content |
| --- | --- |
| `services/domain` | `amazonaws.com` |
| `managed-ssh-keys/active-keys/<user>/` | The user's live keys, each as `#Timestamp=`, `#Instance=`, `#Caller=` and `#Request=` lines, the key, and a base64 RSA-PSS (SHA-256, salt 32) signature; answers `HEAD`, and `404` when there is none |
| `managed-ssh-keys/signer-cert/` | PEM chain: the signer (`CN=managed-ssh-signer.<region>.amazonaws.com`), a Floci intermediate, Floci's local CA |
| `managed-ssh-keys/signer-ocsp/` | The upper-case SHA-1 fingerprints of the signer and the intermediate |
| `managed-ssh-keys/signer-ocsp/<fingerprint>` | A base64 DER OCSP response, `good`, signed by that certificate's issuer |
On EC2 the chain ends at a public root the AMI already trusts. Floci's ends at its local CA (the
one `GET /_floci/ca.pem` serves), so at launch Floci adds that CA to the guest's system trust
store as `Floci_Local_CA.crt` and runs `update-ca-certificates`; the agent finds it as
`/etc/ssl/certs/Floci_Local_CA.pem`. Images without `update-ca-certificates` are left alone, and
the agent there refuses Floci's keys.
The agent also checks that it runs on EC2: `/sys/hypervisor/uuid` starting with `ec2`, or the DMI
`board_asset_tag` equal to the instance ID. A Docker container has neither, so the guest image
must provide one (the instance ID is in the guest's `AWS_EC2_INSTANCE_ID` environment variable).
## Not emulated
- IAM authorization of `SendSSHPublicKey` beyond Floci's general IAM enforcement, and the
`ec2:osuser` condition key.
- The signing material lives in memory: a restart issues a new intermediate and signers under the
same local CA, so guests keep verifying.
- EC2 Instance Connect Endpoint tunnels.
+1
View File
@@ -89,6 +89,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 |
| [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 |
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 224 |
| [EC2 Instance Connect](ec2-instance-connect.md) | `POST /` + `X-Amz-Target: AWSEC2InstanceConnectService.*` | JSON 1.1 | 2 |
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 34 |
+1
View File
@@ -182,6 +182,7 @@ nav:
- MWAA: services/mwaa.md
- OpenSearch: services/opensearch.md
- EC2: services/ec2.md
- EC2 Instance Connect: services/ec2-instance-connect.md
- Lightsail: services/lightsail.md
- AppConfig: services/appconfig.md
- Bedrock: services/bedrock.md
@@ -882,6 +882,7 @@ public interface EmulatorConfig {
LakeFormationServiceConfig lakeformation();
EfsServiceConfig efs();
Ec2InstanceConnectServiceConfig ec2instanceconnect();
CodeGuruReviewerServiceConfig codegurureviewer();
CodeArtifactServiceConfig codeartifact();
QuickSightServiceConfig quicksight();
@@ -1207,6 +1208,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface Ec2InstanceConnectServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface EfsServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -27,6 +27,7 @@ import io.floci.aws.services.configservice.ConfigServiceJsonHandler;
import io.floci.aws.services.cur.CurJsonHandler;
import io.floci.aws.services.datasync.DataSyncJsonHandler;
import io.floci.aws.services.dms.DmsJsonHandler;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectJsonHandler;
import io.floci.aws.services.ecr.EcrJsonHandler;
import io.floci.aws.services.ecs.EcsJsonHandler;
import io.floci.aws.services.emr.EmrHandler;
@@ -115,6 +116,7 @@ public class AwsJson11Controller {
private final CodeDeployJsonHandler codeDeployJsonHandler;
private final CodePipelineJsonHandler codePipelineJsonHandler;
private final Ec2MessagesJsonHandler ec2MessagesJsonHandler;
private final InstanceConnectJsonHandler instanceConnectJsonHandler;
private final TransferHandler transferHandler;
private final TextractJsonHandler textractJsonHandler;
private final ComprehendJsonHandler comprehendJsonHandler;
@@ -172,6 +174,7 @@ public class AwsJson11Controller {
CodeDeployJsonHandler codeDeployJsonHandler,
CodePipelineJsonHandler codePipelineJsonHandler,
Ec2MessagesJsonHandler ec2MessagesJsonHandler,
InstanceConnectJsonHandler instanceConnectJsonHandler,
TransferHandler transferHandler,
TextractJsonHandler textractJsonHandler,
ComprehendJsonHandler comprehendJsonHandler,
@@ -233,6 +236,7 @@ public class AwsJson11Controller {
this.codeDeployJsonHandler = codeDeployJsonHandler;
this.codePipelineJsonHandler = codePipelineJsonHandler;
this.ec2MessagesJsonHandler = ec2MessagesJsonHandler;
this.instanceConnectJsonHandler = instanceConnectJsonHandler;
this.transferHandler = transferHandler;
this.textractJsonHandler = textractJsonHandler;
this.comprehendJsonHandler = comprehendJsonHandler;
@@ -340,6 +344,7 @@ public class AwsJson11Controller {
case "codepipeline" -> codePipelineJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);
case "ec2-instance-connect" -> instanceConnectJsonHandler.handle(action, request, region);
case "transfer" -> transferHandler.handle(action, request, region);
case "textract" -> textractJsonHandler.handle(action, request, region);
case "comprehend" -> comprehendJsonHandler.handle(action, request, region);
@@ -641,6 +641,10 @@ public class ResolvedServiceCatalog {
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonSSMMessageDeliveryService."), Set.of("ec2messages"), Set.of(), Set.of()),
descriptor("ec2-instance-connect", "ec2-instance-connect", config.services().ec2instanceconnect().enabled(), false,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AWSEC2InstanceConnectService."), Set.of("ec2-instance-connect"), Set.of(), Set.of()),
descriptor("transfer", "transfer", config.services().transfer().enabled(), true,
"transfer", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
@@ -583,6 +583,8 @@ public class Ec2ContainerManager {
configureLinkLocalMetadataEndpoint(started.namespace() == null
? containerId : started.namespace().helperId(), instanceId, flociHost, imdsPort);
installInstanceConnectTrustAnchor(containerId, instanceId);
// Publish security-group TCP ingress ports on the host via socat sidecars.
if (appPorts != null && !appPorts.isEmpty()) {
portForwardManager.reconcile(instance, appPorts);
@@ -1738,6 +1740,40 @@ public class Ec2ContainerManager {
}
}
/**
* Adds Floci's local CA to the guest's system trust store, so the unmodified EC2 Instance
* Connect agent can verify the signer chain Floci serves through IMDS. On EC2 that chain ends
* at a public root the AMI already trusts. The agent finds the root by its common name, as
* {@code /etc/ssl/certs/<CN with underscores>.pem}, which is the name
* {@code update-ca-certificates} gives a {@code <stem>.crt} it installs. Best effort: images
* without a Debian-family trust store are left alone.
*/
private void installInstanceConnectTrustAnchor(String containerId, String instanceId) {
metadataServer.instanceConnect().ifPresent(keys -> {
try {
String dir = "/usr/local/share/ca-certificates";
ContainerExec.Result probe = execInContainerForResult(containerId, new String[]{"sh", "-c",
"[ -d " + dir + " ] && command -v update-ca-certificates >/dev/null"}, 5);
if (probe.exitCode() != 0) {
LOG.debugv("EC2 instance {0} has no update-ca-certificates trust store; EC2 Instance Connect "
+ "keys cannot be verified there", instanceId);
return;
}
RetryingTarCopier.copyBytes(dockerClient, containerId, dir, keys.trustAnchorFileStem() + ".crt",
keys.trustAnchorPem().getBytes(StandardCharsets.UTF_8), 0644);
ContainerExec.Result update = execInContainerForResult(containerId,
new String[]{"update-ca-certificates"}, 60);
if (update.exitCode() != 0) {
LOG.warnv("Could not refresh the trust store of EC2 instance {0}: {1}", instanceId,
update.summary());
}
} catch (Exception e) {
LOG.warnv("Could not install the EC2 Instance Connect trust anchor in EC2 instance {0}: {1}",
instanceId, e.getMessage());
}
});
}
private void injectSshKey(String containerId, String publicKey) {
try {
// Ensure .ssh directory exists with correct permissions
@@ -1,9 +1,11 @@
package io.floci.aws.services.ec2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.iam.model.InstanceProfile;
@@ -34,6 +36,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
/**
* IMDS-compatible HTTP server bound to port 9169 on the Floci host.
@@ -67,17 +70,30 @@ public class Ec2MetadataServer {
private final Set<Instance> synthesizedProfiles = ConcurrentHashMap.newKeySet();
private volatile HttpServer httpServer;
private final InstanceConnectKeys instanceConnect;
@Inject
public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService) {
this(vertx, config, iamService, Clock.systemUTC());
public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService,
InstanceConnectKeys instanceConnect) {
this(vertx, config, iamService, Clock.systemUTC(), instanceConnect);
}
Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService, Clock clock) {
this(vertx, config, iamService, clock, null);
}
Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService, Clock clock,
InstanceConnectKeys instanceConnect) {
this.vertx = vertx;
this.config = config;
this.credentials = new Ec2InstanceCredentials(iamService);
this.clock = clock;
this.instanceConnect = instanceConnect;
}
/** EC2 Instance Connect's signing material, for installing its trust anchor in guests; empty in tests. */
public Optional<InstanceConnectKeys> instanceConnect() {
return Optional.ofNullable(instanceConnect);
}
/** Called by Ec2ContainerManager after a container starts to register its IP. */
@@ -178,6 +194,17 @@ public class Ec2MetadataServer {
router.get("/latest/meta-data/tags/instance").handler(ctx -> handleInstanceTagKeys(ctx));
router.get("/latest/meta-data/tags/instance/").handler(ctx -> handleInstanceTagKeys(ctx));
router.getWithRegex("/latest/meta-data/tags/instance/.+").handler(ctx -> handleInstanceTagValue(ctx));
router.get("/latest/meta-data/services/domain").handler(ctx -> handleText(ctx, inst -> AwsRegions.dnsSuffixFor(inst.getRegion())));
// EC2 Instance Connect. The agent probes active-keys with HEAD before fetching it. Blocking
// handlers: the first call generates RSA key pairs and every one signs, which must not stall the event loop.
router.route("/latest/meta-data/managed-ssh-keys/active-keys/:user").method(HttpMethod.GET)
.method(HttpMethod.HEAD).blockingHandler(this::handleManagedSshKeys);
router.get("/latest/meta-data/managed-ssh-keys/signer-cert").blockingHandler(ctx -> handleInstanceConnect(ctx,
(keys, inst) -> keys.signerCertificateChain(inst.getRegion())));
router.get("/latest/meta-data/managed-ssh-keys/signer-ocsp").blockingHandler(ctx -> handleInstanceConnect(ctx,
(keys, inst) -> String.join("\n", keys.ocspStaples(inst.getRegion()).keySet())));
router.get("/latest/meta-data/managed-ssh-keys/signer-ocsp/:fingerprint").blockingHandler(ctx -> handleInstanceConnect(ctx,
(keys, inst) -> keys.ocspStaples(inst.getRegion()).get(ctx.pathParam("fingerprint"))));
router.get("/latest/user-data").handler(ctx -> handleUserData(ctx));
router.get("/latest/dynamic/instance-identity/document").handler(ctx -> handleIdentityDocument(ctx));
@@ -275,6 +302,31 @@ public class Ec2MetadataServer {
.end(value);
}
private void handleManagedSshKeys(RoutingContext ctx) {
handleInstanceConnect(ctx, (keys, inst) -> keys.activeKeysDocument(inst.getRegion(),
inst.getInstanceId(), ctx.pathParam("user")).orElse(null));
}
private void handleInstanceConnect(RoutingContext ctx,
BiFunction<InstanceConnectKeys, Instance, String> body) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
return;
}
String value = instanceConnect == null ? null : body.apply(instanceConnect, inst);
if (value == null) {
ctx.response().setStatusCode(404).end("not-available");
return;
}
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain");
if (ctx.request().method() == HttpMethod.HEAD) {
ctx.response().putHeader("content-length", String.valueOf(value.getBytes(StandardCharsets.UTF_8).length))
.end();
} else {
ctx.response().end(value);
}
}
private void handleMac(RoutingContext ctx) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
@@ -0,0 +1,162 @@
package io.floci.aws.services.ec2instanceconnect;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SshPublicKeys;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.time.Clock;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* EC2 Instance Connect ({@code X-Amz-Target: AWSEC2InstanceConnectService.*}).
*
* <p>{@code SendSSHPublicKey} validates the request against the service model and the instance's
* state, then hands the key to {@link InstanceConnectKeys}, which serves it signed to the
* instance's agent through IMDS for {@link InstanceConnectKeys#KEY_LIFETIME}. The serial console
* operation is answered with {@code SerialConsoleSessionUnsupportedException} once the instance is
* found: Docker-backed instances have no serial console.
*/
@ApplicationScoped
public class InstanceConnectJsonHandler {
// Patterns and bounds from the service model (ec2-instance-connect 2018-04-02).
private static final Pattern INSTANCE_ID = Pattern.compile("^i-[a-f0-9]+$");
private static final Pattern OS_USER = Pattern.compile(
"(^[A-Za-z_][A-Za-z0-9@._-]{0,30}[A-Za-z0-9$_-]?$)"
+ "|(^(?=.{2,32}$)[0-9]{1,32}[A-Za-z@._-][A-Za-z0-9@._-]*[A-Za-z0-9$_-]?$)");
private static final Pattern AVAILABILITY_ZONE = Pattern.compile("^(\\w+-){2,3}\\d+\\w+$");
/** The key types AWS documents for EC2 Instance Connect: RSA (2048 bits or more), ED25519 and ECDSA. */
private static final Set<String> KEY_TYPES = Set.of("ssh-rsa", "ssh-ed25519",
"ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521");
private static final int MIN_RSA_BITS = 2048;
private final Ec2Service ec2Service;
private final InstanceConnectKeys keys;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final Clock clock;
@Inject
public InstanceConnectJsonHandler(Ec2Service ec2Service, InstanceConnectKeys keys,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this(ec2Service, keys, regionResolver, objectMapper, Clock.systemUTC());
}
InstanceConnectJsonHandler(Ec2Service ec2Service, InstanceConnectKeys keys, RegionResolver regionResolver,
ObjectMapper objectMapper, Clock clock) {
this.ec2Service = ec2Service;
this.keys = keys;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.clock = clock;
}
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "SendSSHPublicKey" -> sendSshPublicKey(request, region);
case "SendSerialConsoleSSHPublicKey" -> sendSerialConsoleSshPublicKey(request, region);
default -> throw new AwsException("UnknownOperationException",
"Operation " + action + " is not supported.", 400);
};
}
private Response sendSshPublicKey(JsonNode request, String region) {
String instanceId = required(request, "InstanceId");
String osUser = required(request, "InstanceOSUser");
String publicKey = required(request, "SSHPublicKey");
String zone = request.path("AvailabilityZone").asText(null);
if (instanceId.length() < 10 || instanceId.length() > 32 || !INSTANCE_ID.matcher(instanceId).matches()) {
throw invalid("Invalid instance ID: " + instanceId);
}
if (osUser.length() > 32 || !OS_USER.matcher(osUser).matches()) {
throw invalid("Invalid InstanceOSUser: " + osUser);
}
if (publicKey.length() < 80 || publicKey.length() > 4096) {
throw invalid("SSHPublicKey must be between 80 and 4096 characters long.");
}
if (publicKey.trim().chars().anyMatch(Character::isISOControl)) {
// The key is copied verbatim into the signed active-keys document, whose framing is
// line-based: an embedded newline would let one key forge lines for another.
throw invalid("SSHPublicKey must be a single line without control characters.");
}
validatePublicKey(publicKey.trim());
if (zone != null && (zone.length() < 6 || zone.length() > 32 || !AVAILABILITY_ZONE.matcher(zone).matches())) {
throw invalid("Invalid AvailabilityZone: " + zone);
}
Instance instance = ec2Service.getInstance(region, instanceId)
.orElseThrow(() -> new AwsException("EC2InstanceNotFoundException",
"Instance not found: " + instanceId, 400));
String instanceZone = instance.getPlacement() != null ? instance.getPlacement().getAvailabilityZone() : null;
if (zone != null && instanceZone != null && !zone.equals(instanceZone)) {
throw new AwsException("EC2InstanceNotFoundException",
"Instance not found in availability zone " + zone + ": " + instanceId, 400);
}
String state = instance.getState() != null ? instance.getState().getName() : null;
if (!"running".equals(state)) {
throw new AwsException("EC2InstanceStateInvalidException",
"Instance " + instanceId + " is not in a valid state for this operation: " + state, 400);
}
String requestId = UUID.randomUUID().toString();
String caller = regionResolver.buildGlobalArn("iam", "root");
keys.add(new InstanceConnectKeys.ActiveKey(instanceId, osUser, publicKey.trim(),
clock.instant().plus(InstanceConnectKeys.KEY_LIFETIME), caller, requestId));
ObjectNode response = objectMapper.createObjectNode();
response.put("RequestId", requestId);
response.put("Success", true);
return Response.ok(response).build();
}
/** Docker-backed instances have no serial console; AWS checks the instance exists before saying so. */
private Response sendSerialConsoleSshPublicKey(JsonNode request, String region) {
String instanceId = required(request, "InstanceId");
ec2Service.getInstance(region, instanceId)
.orElseThrow(() -> new AwsException("EC2InstanceNotFoundException",
"Instance not found: " + instanceId, 400));
throw new AwsException("SerialConsoleSessionUnsupportedException",
"The EC2 serial console is not supported for instance " + instanceId + ".", 400);
}
private static String required(JsonNode request, String field) {
JsonNode value = request.get(field);
if (value == null || value.isNull() || value.asText().isEmpty()) {
throw invalid(field + " is required.");
}
return value.asText();
}
/** One OpenSSH public key line: a supported type, its base64 blob carrying the same type, RSA of 2048 bits or more. */
static void validatePublicKey(String line) {
String[] parts = line.split("\\s+");
if (parts.length < 2 || !KEY_TYPES.contains(parts[0])) {
throw invalid("Unsupported or malformed SSH public key. Supported types: RSA, ED25519 and ECDSA.");
}
byte[] blob = SshPublicKeys.decodeBlob(line);
if (!SshPublicKeys.carriesAKey(blob)) {
throw invalid("Malformed SSH public key.");
}
if (!SshPublicKeys.keyType(blob).equals(parts[0])) {
throw invalid("The SSH public key's type does not match its encoded data.");
}
if ("ssh-rsa".equals(parts[0]) && SshPublicKeys.rsaKeyOf(blob).getModulus().bitLength() < MIN_RSA_BITS) {
throw invalid("RSA keys must be at least " + MIN_RSA_BITS + " bits long.");
}
}
private static AwsException invalid(String message) {
return new AwsException("InvalidArgsException", message, 400);
}
}
@@ -0,0 +1,291 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.config.FlociCertificateAuthority;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.services.acm.CertificateGenerator;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.CertificateStatus;
import org.bouncycastle.cert.ocsp.OCSPResp;
import org.bouncycastle.cert.ocsp.OCSPRespBuilder;
import org.bouncycastle.cert.ocsp.jcajce.JcaBasicOCSPRespBuilder;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* The instance side of EC2 Instance Connect: the keys {@code SendSSHPublicKey} pushed, and the
* signing material the unmodified AWS agent ({@code aws-ec2-instance-connect-config}) verifies
* them with, served through IMDS under {@code managed-ssh-keys/}.
*
* <p>The agent's contract, which this class exists to satisfy:
* <ul>
* <li>{@code signer-cert/} is a PEM chain: the signer first, then each issuer. The signer's CN
* must be {@code managed-ssh-signer.<region>.<domain>}, and the last certificate's CN must
* name a trusted file {@code /etc/ssl/certs/<CN with spaces as underscores>.pem}.</li>
* <li>Every certificate below that trusted one needs an OCSP staple at
* {@code signer-ocsp/<upper-case SHA-1 fingerprint>} (base64 DER), signed by its issuer,
* reporting {@code good}.</li>
* <li>{@code active-keys/<user>/} holds one entry per key: {@code #Timestamp=} (expiry, epoch
* seconds), {@code #Instance=}, {@code #Caller=} and {@code #Request=} lines, the key line,
* then a base64 RSA-PSS (SHA-256, MGF1-SHA-256, salt 32) signature over those lines, and a
* blank line.</li>
* </ul>
*
* <p>The chain is signer, a Floci intermediate, and Floci's local CA, which Floci installs into
* each guest's trust store. On AWS the chain ends at a public root the AMI already trusts.
* Signing material lives in memory: a restart issues a new intermediate and signers under the
* same persistent root, so guests keep verifying.
*/
@ApplicationScoped
public class InstanceConnectKeys implements Resettable {
/** AWS keeps a pushed key for 60 seconds. */
public static final Duration KEY_LIFETIME = Duration.ofSeconds(60);
static final String INTERMEDIATE_CN = "Floci EC2 Instance Connect Intermediate CA";
private static final Duration INTERMEDIATE_VALIDITY = Duration.ofDays(365);
private static final Duration SIGNER_VALIDITY = Duration.ofDays(30);
/** Material is reissued once it is this close to expiry, so a verification never races it. */
private static final Duration RENEW_BEFORE = Duration.ofDays(1);
private static final Duration STAPLE_VALIDITY = Duration.ofDays(7);
public record ActiveKey(String instanceId, String osUser, String publicKey, Instant expiresAt,
String caller, String requestId) {}
private record Issued(X509Certificate certificate, PrivateKey key) {}
private final Supplier<FlociCertificateAuthority> rootCa;
private final CertificateGenerator generator;
private final Clock clock;
private final Map<String, List<ActiveKey>> keysByInstance = new ConcurrentHashMap<>();
private final Map<String, Issued> signers = new ConcurrentHashMap<>();
private Issued intermediate;
@Inject
public InstanceConnectKeys(Instance<FlociCertificateAuthority> rootCa,
CertificateGenerator generator) {
this(rootCa::get, generator, Clock.systemUTC());
}
InstanceConnectKeys(Supplier<FlociCertificateAuthority> rootCa, CertificateGenerator generator, Clock clock) {
this.rootCa = rootCa;
this.generator = generator;
this.clock = clock;
}
// ── Keys ──────────────────────────────────────────────────────────────────
public void add(ActiveKey key) {
// Expired keys go here rather than on terminate: a key lives 60 seconds, so this bounds the
// map to instances that received one within the last minute.
keysByInstance.entrySet().removeIf(entry -> live(entry.getValue()).isEmpty());
keysByInstance.compute(key.instanceId(), (id, existing) -> {
List<ActiveKey> live = live(existing);
live.add(key);
return live;
});
}
/** The signed authorized-keys document for {@code osUser}, or empty when no key is live. */
public Optional<String> activeKeysDocument(String region, String instanceId, String osUser) {
List<ActiveKey> forUser = live(keysByInstance.get(instanceId)).stream()
.filter(key -> key.osUser().equals(osUser))
.toList();
if (forUser.isEmpty()) {
return Optional.empty();
}
PrivateKey signingKey = signer(region).key();
StringBuilder document = new StringBuilder();
for (ActiveKey key : forUser) {
String signed = "#Timestamp=" + key.expiresAt().getEpochSecond() + "\n"
+ "#Instance=" + key.instanceId() + "\n"
+ "#Caller=" + key.caller() + "\n"
+ "#Request=" + key.requestId() + "\n"
+ key.publicKey().trim() + "\n";
document.append(signed).append(sign(signingKey, signed)).append("\n\n");
}
return Optional.of(document.toString());
}
int trackedInstanceCount() {
return keysByInstance.size();
}
private List<ActiveKey> live(List<ActiveKey> keys) {
Instant now = clock.instant();
List<ActiveKey> live = new ArrayList<>();
if (keys != null) {
keys.stream().filter(key -> key.expiresAt().isAfter(now)).forEach(live::add);
}
return live;
}
private static String sign(PrivateKey key, String data) {
try {
Signature signature = Signature.getInstance("RSASSA-PSS");
signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
signature.initSign(key);
signature.update(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signature.sign());
} catch (Exception e) {
throw new IllegalStateException("Failed to sign an EC2 Instance Connect key", e);
}
}
// ── Signing material ──────────────────────────────────────────────────────
/**
* The signer certificate, then the intermediate, then the root: what {@code signer-cert/} serves.
* Synchronized with {@link #signer} and {@link #intermediate} so a rotation between the two reads
* cannot mix generations.
*/
public synchronized String signerCertificateChain(String region) {
try {
return generator.toPem(signer(region).certificate())
+ generator.toPem(intermediate().certificate())
+ rootCa.get().caPem();
} catch (Exception e) {
throw new IllegalStateException("Failed to encode the EC2 Instance Connect signer chain", e);
}
}
/** OCSP staples by upper-case SHA-1 fingerprint, each base64 DER: the signer's and the intermediate's. */
public synchronized Map<String, String> ocspStaples(String region) {
Issued signer = signer(region);
Issued intermediate = intermediate();
FlociCertificateAuthority root = rootCa.get();
Map<String, String> staples = new LinkedHashMap<>();
staples.put(sha1Fingerprint(signer.certificate()),
staple(signer.certificate(), intermediate.certificate(), intermediate.key()));
staples.put(sha1Fingerprint(intermediate.certificate()),
staple(intermediate.certificate(), root.certificate(), root.key()));
return staples;
}
/** The root guests must trust, and the file name the agent looks it up by. */
public String trustAnchorPem() {
return rootCa.get().caPem();
}
public String trustAnchorFileStem() {
String dn = rootCa.get().certificate().getSubjectX500Principal().getName();
String cn = dn.replaceFirst("(?s).*CN=([^,]+).*", "$1");
return cn.trim().replaceAll(" +", "_");
}
public static String signerCommonName(String region) {
return "managed-ssh-signer." + region + "." + AwsRegions.dnsSuffixFor(region);
}
private synchronized Issued intermediate() {
if (intermediate == null || expiresSoon(intermediate.certificate())) {
FlociCertificateAuthority root = rootCa.get();
intermediate = issue(INTERMEDIATE_CN, true,
X500Name.getInstance(root.certificate().getSubjectX500Principal().getEncoded()),
root.certificate(), root.key(), INTERMEDIATE_VALIDITY);
signers.clear();
}
return intermediate;
}
private synchronized Issued signer(String region) {
Issued issuer = intermediate();
Issued current = signers.get(region);
if (current == null || expiresSoon(current.certificate())) {
current = issue(signerCommonName(region), false,
X500Name.getInstance(issuer.certificate().getSubjectX500Principal().getEncoded()),
issuer.certificate(), issuer.key(), SIGNER_VALIDITY);
signers.put(region, current);
}
return current;
}
private boolean expiresSoon(X509Certificate certificate) {
return certificate.getNotAfter().toInstant().isBefore(clock.instant().plus(RENEW_BEFORE));
}
private Issued issue(String commonName, boolean asCa, X500Name issuerDn, X509Certificate issuerCert,
PrivateKey issuerKey, Duration validity) {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
Instant now = clock.instant();
X509Certificate cert = generator.signCertificate(new X500Name("CN=" + commonName), pair.getPublic(),
issuerDn, issuerKey, List.of(), asCa, null, now.minus(5, ChronoUnit.MINUTES),
now.plus(validity), issuerCert.getPublicKey());
return new Issued(cert, pair.getPrivate());
} catch (Exception e) {
throw new IllegalStateException("Failed to issue " + commonName, e);
}
}
private String staple(X509Certificate certificate, X509Certificate issuer, PrivateKey issuerKey) {
try {
DigestCalculatorProvider digests = new JcaDigestCalculatorProviderBuilder().build();
CertificateID id = new CertificateID(digests.get(CertificateID.HASH_SHA1),
new JcaX509CertificateHolder(issuer), certificate.getSerialNumber());
BasicOCSPRespBuilder builder = new JcaBasicOCSPRespBuilder(issuer.getPublicKey(),
digests.get(CertificateID.HASH_SHA1));
Instant now = clock.instant();
builder.addResponse(id, CertificateStatus.GOOD, Date.from(now.minus(5, ChronoUnit.MINUTES)),
Date.from(now.plus(STAPLE_VALIDITY)), null);
String algorithm = issuerKey instanceof ECKey ? "SHA256withECDSA" : "SHA256withRSA";
BasicOCSPResp basic = builder.build(new JcaContentSignerBuilder(algorithm).build(issuerKey),
new X509CertificateHolder[0], Date.from(now));
OCSPResp response = new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, basic);
return Base64.getEncoder().encodeToString(response.getEncoded());
} catch (Exception e) {
throw new IllegalStateException("Failed to staple " + certificate.getSubjectX500Principal(), e);
}
}
static String sha1Fingerprint(X509Certificate certificate) {
try {
return HexFormat.of().withUpperCase()
.formatHex(MessageDigest.getInstance("SHA-1").digest(certificate.getEncoded()));
} catch (Exception e) {
throw new IllegalStateException("Cannot fingerprint " + certificate.getSubjectX500Principal(), e);
}
}
@Override
public synchronized void clear() {
keysByInstance.clear();
signers.clear();
intermediate = null;
}
}
+2
View File
@@ -1018,6 +1018,8 @@ floci:
enabled: true
efs:
enabled: true
ec2instanceconnect:
enabled: true
organizations:
enabled: true
# management-account-email: "" # When set, overrides the management-account email reported by DescribeOrganization and account listings.
@@ -1,10 +1,10 @@
{
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-06", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-07", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "rekognition": ["rekognition"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]},
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"},
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controltower": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not Line truncated
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"],
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controltower": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not Line truncated
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"],
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgentId}", "discoveryjob": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}/job/${DiscoveryJobId}", "location": "arn:${Partition}:datasync:${Region}:${Account}:location/${LocationId}", "storagesystem": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}", "task": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}", "taskexecution": "arn:${Partition}:datasLine truncated
"unqualified": {"states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
@@ -0,0 +1,34 @@
package io.floci.aws.core.common;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** EC2 Instance Connect has its own enabled flag; turning it off leaves EC2 on. */
@QuarkusTest
@TestProfile(InstanceConnectEnablementIntegrationTest.InstanceConnectDisabledProfile.class)
class InstanceConnectEnablementIntegrationTest {
@Inject
ServiceRegistry serviceRegistry;
@Test
void ownFlagDisablesOnlyInstanceConnect() {
assertFalse(serviceRegistry.isServiceEnabled("ec2-instance-connect"));
assertTrue(serviceRegistry.isServiceEnabled("ec2"));
}
public static final class InstanceConnectDisabledProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ec2instanceconnect.enabled", "false");
}
}
}
@@ -2,10 +2,12 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.PartitionMatrix;
import io.floci.aws.testing.PartitionMatrix.PartitionCase;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.arc.Arc;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.config.JsonPathConfig;
import io.restassured.response.Response;
@@ -45,7 +47,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
"aps", "autoscaling", "backup", "batch", "bcmdataexports", "bedrock", "bedrockagentcorecontrol", "ce",
"cloudfront", "cloudmap", "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito",
"configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dsql", "dynamodb", "ec2",
"ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless",
"ec2instanceconnect", "ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless",
"eventbridge", "eventbridgev2", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
"paymentcryptography", "pipes", "quicksight", "ram", "rds", "redshift", "redshiftserverless",
@@ -534,6 +536,51 @@ class PartitionCrossServiceSmokeIntegrationTest {
PartitionMatrix.assertGlobalArnIn(partitionCase, created.xmlPath().getString("CreateIpamResponse.ipam.ipamArn"));
}
/**
* SendSSHPublicKey answers only RequestId and Success; the caller ARN it mints is read back
* from the signed active-keys document IMDS would serve the instance, and the signer host from
* the name its certificate is issued under.
*/
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void instanceConnectCallerArnAndSignerHost(PartitionCase partitionCase) {
String region = offered(partitionCase, "ec2-instance-connect");
String instanceId = signed(region, "ec2")
.formParam("Action", "RunInstances")
.formParam("Version", "2016-11-15")
.formParam("ImageId", "ami-0123456789abcdef0")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("RunInstancesResponse.instancesSet.item.instanceId");
cleanup.register(() -> signed(region, "ec2")
.formParam("Action", "TerminateInstances")
.formParam("Version", "2016-11-15")
.formParam("InstanceId.1", instanceId)
.when().post("/"));
// A mock launch settles on the next describe, as it does for any other caller.
String state = signed(region, "ec2")
.formParam("Action", "DescribeInstances")
.formParam("Version", "2016-11-15")
.formParam("InstanceId.1", instanceId)
.when().post("/").then().statusCode(200).extract().xmlPath()
.getString("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name");
assertEquals("running", state);
json11(region, "ec2-instance-connect", "AWSEC2InstanceConnectService.SendSSHPublicKey",
"{\"InstanceId\":\"" + instanceId + "\",\"InstanceOSUser\":\"admin\",\"SSHPublicKey\":\""
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl smoke\"}")
.when().post("/").then().statusCode(200);
String document = Arc.container().instance(InstanceConnectKeys.class).get()
.activeKeysDocument(region, instanceId, "admin").orElseThrow();
String caller = document.lines().filter(line -> line.startsWith("#Caller="))
.findFirst().orElseThrow().substring("#Caller=".length());
PartitionMatrix.assertGlobalArnIn(partitionCase, caller);
assertRegionalHostIn(partitionCase, InstanceConnectKeys.signerCommonName(region));
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void apiGatewayDomainNameArn(PartitionCase partitionCase) {
@@ -43,6 +43,7 @@ import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.services.ec2.model.InstanceState;
import io.floci.aws.services.ec2.net.VpcNetworkManager;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -300,7 +301,7 @@ class Ec2ContainerManagerTest {
networks.put(second, new ContainerNetwork().withIpv4Address(sharedFirst ? "10.0.1.10" : "192.0.2.10"));
when(settings.getNetworks()).thenReturn(networks);
when(command.exec()).thenReturn(response);
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
Ec2ContainerManager manager = managerWith(lifecycle, docker, server);
Instance guest = instance("i-multinetwork");
guest.setDockerContainerId(TEST_CONTAINER_ID);
@@ -0,0 +1,91 @@
package io.floci.aws.services.ec2;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.vertx.core.Context;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The IMDS paths the unmodified EC2 Instance Connect agent reads, in the shape it reads them:
* with a trailing slash, and {@code active-keys} probed with HEAD before it is fetched.
*/
class Ec2MetadataInstanceConnectTest {
@Test
void servesTheAgentsPathsWithTrailingSlashesAndHead() throws Exception {
InstanceConnectKeys keys = mock(InstanceConnectKeys.class);
when(keys.activeKeysDocument(anyString(), eq("i-0123456789abcdef0"), anyString())).thenReturn(Optional.empty());
when(keys.activeKeysDocument(anyString(), eq("i-0123456789abcdef0"), eq("admin")))
.thenReturn(Optional.of("#Timestamp=1\nssh-ed25519 AAAA\nc2ln\n\n"));
when(keys.signerCertificateChain(anyString())).thenReturn("CHAIN");
Map<String, String> staples = new LinkedHashMap<>();
staples.put("AA11", "c3RhcGxlMQ==");
staples.put("BB22", "c3RhcGxlMg==");
when(keys.ocspStaples(anyString())).thenReturn(staples);
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture().withInstanceConnect(keys)) {
imds.instance().setRegion("us-east-1");
imds.start();
String token = imds.putToken("60").body();
String keysPath = "/latest/meta-data/managed-ssh-keys/";
assertEquals("i-0123456789abcdef0", imds.get("/latest/meta-data/instance-id/", token).body());
assertEquals("amazonaws.com", imds.get("/latest/meta-data/services/domain/", token).body());
assertEquals(200, imds.head(keysPath + "active-keys/admin/", token).statusCode());
assertEquals(404, imds.head(keysPath + "active-keys/root/", token).statusCode());
assertEquals("#Timestamp=1\nssh-ed25519 AAAA\nc2ln\n\n",
imds.get(keysPath + "active-keys/admin/", token).body());
assertEquals("CHAIN", imds.get(keysPath + "signer-cert/", token).body());
assertEquals("AA11\nBB22", imds.get(keysPath + "signer-ocsp/", token).body());
assertEquals("c3RhcGxlMg==", imds.get(keysPath + "signer-ocsp/BB22", token).body());
assertEquals(404, imds.get(keysPath + "signer-ocsp/CC33", token).statusCode());
}
}
@Test
void keyGenerationAndSigningRunOffTheEventLoop() throws Exception {
AtomicBoolean onEventLoop = new AtomicBoolean();
InstanceConnectKeys keys = mock(InstanceConnectKeys.class);
when(keys.signerCertificateChain(anyString())).thenAnswer(inv -> {
onEventLoop.set(Context.isOnEventLoopThread());
return "CHAIN";
});
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture().withInstanceConnect(keys)) {
imds.instance().setRegion("us-east-1");
imds.start();
String token = imds.putToken("60").body();
assertEquals("CHAIN", imds.get("/latest/meta-data/managed-ssh-keys/signer-cert", token).body());
assertFalse(onEventLoop.get(), "signing must not run on the Vert.x event loop");
}
}
@Test
void servicesDomainIsTheInstanceRegionsPartitionDomain() throws Exception {
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture()) {
imds.instance().setRegion("cn-north-1");
imds.start();
String token = imds.putToken("60").body();
assertEquals("amazonaws.com.cn", imds.get("/latest/meta-data/services/domain", token).body());
}
}
@Test
void managedSshKeysAreAbsentWithoutInstanceConnect() throws Exception {
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture()) {
imds.start();
String token = imds.putToken("60").body();
assertEquals(404, imds.get("/latest/meta-data/managed-ssh-keys/signer-cert/", token).statusCode());
}
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.ec2;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Placement;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import org.junit.jupiter.api.Test;
import java.util.List;
@@ -15,7 +16,7 @@ class Ec2MetadataServerTest {
@Test
void reconciliationAndTerminationPreserveOtherInstances() {
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
Instance first = new Instance();
first.setInstanceId("i-first");
Instance second = new Instance();
@@ -100,7 +101,7 @@ class Ec2MetadataServerTest {
@Test
void staleContainerUnregisterDoesNotRemoveCurrentRegistration() {
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
Instance oldInstance = new Instance();
oldInstance.setInstanceId("i-old");
Instance currentInstance = new Instance();
@@ -2,6 +2,7 @@ package io.floci.aws.services.ec2;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.testing.MutableClock;
import io.floci.aws.testutil.FreePorts;
@@ -34,6 +35,7 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
private final Instance instance = instance("i-0123456789abcdef0");
private Vertx vertx;
private Ec2MetadataServer server;
private InstanceConnectKeys instanceConnect;
private String endpoint;
void start() throws Exception {
@@ -53,7 +55,7 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
int port = FreePorts.anyInterfacePort();
when(config.services().ec2().imdsPort()).thenReturn(port);
vertx = Vertx.vertx();
server = new Ec2MetadataServer(vertx, config, iam, serverClock);
server = new Ec2MetadataServer(vertx, config, iam, serverClock, instanceConnect);
server.start().get(10, TimeUnit.SECONDS);
endpoint = "http://127.0.0.1:" + port;
if (registeredInstance != null) {
@@ -76,6 +78,18 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
}
}
/** Serves EC2 Instance Connect from {@code keys}; call before {@link #start()}. */
Ec2MetadataTestFixture withInstanceConnect(InstanceConnectKeys keys) {
this.instanceConnect = keys;
return this;
}
HttpResponse<String> head(String path, String token) throws Exception {
return client.send(HttpRequest.newBuilder(URI.create(endpoint + path)).timeout(Duration.ofSeconds(5))
.header(TOKEN_HEADER, token).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString());
}
MutableClock clock() {
return clock;
}
@@ -0,0 +1,66 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.Ec2Requests.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class InstanceConnectIntegrationTest {
private static final String JSON_1_1 = "application/x-amz-json-1.1";
private static final String ED25519 =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response send(String instanceId, String key) {
return given()
.header("X-Amz-Target", "AWSEC2InstanceConnectService.SendSSHPublicKey")
.contentType(JSON_1_1)
.body("{\"InstanceId\":\"" + instanceId + "\",\"InstanceOSUser\":\"ec2-user\",\"SSHPublicKey\":\""
+ key + "\"}")
.post("/");
}
@Test
void sendsAKeyToARunningInstanceAndRejectsWhatAwsRejects() {
String instanceId = ec2("RunInstances", "000000000000", "us-east-1")
.formParam("ImageId", "ami-0abcdef1234567890")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1").formParam("MaxCount", "1")
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
// Mock mode settles a launch on the first DescribeInstances; the key needs a running instance.
ec2("DescribeInstances", "000000000000", "us-east-1").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
equalTo("running"));
send(instanceId, ED25519).then().statusCode(200)
.body("Success", equalTo(true))
.body("RequestId", not(emptyString()));
send(instanceId, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 " + "c".repeat(80)).then().statusCode(400)
.body("__type", equalTo("InvalidArgsException"));
} finally {
ec2("TerminateInstances", "000000000000", "us-east-1").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200);
}
}
@Test
void unknownInstanceIsAModeledError() {
send("i-0000000000000000f", ED25519).then().statusCode(400)
.body("__type", equalTo("EC2InstanceNotFoundException"));
}
}
@@ -0,0 +1,189 @@
package io.floci.aws.services.ec2instanceconnect;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceState;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
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.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class InstanceConnectJsonHandlerTest {
private static final String REGION = "us-east-1";
private static final String INSTANCE = "i-0123456789abcdef0";
private static final Instant NOW = Instant.parse("2026-10-16T12:00:00Z");
private static final String ED25519 =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
private final ObjectMapper mapper = new ObjectMapper();
private Ec2Service ec2;
private InstanceConnectKeys keys;
private InstanceConnectJsonHandler handler;
private Instance instance;
@BeforeEach
void setUp() {
ec2 = mock(Ec2Service.class);
keys = mock(InstanceConnectKeys.class);
handler = handlerIn("us-east-1");
instance = new Instance();
instance.setInstanceId(INSTANCE);
instance.setState(InstanceState.running());
when(ec2.getInstance(REGION, INSTANCE)).thenReturn(Optional.of(instance));
}
@Test
void storesTheKeyForSixtySecondsAndReportsSuccess() {
Response response = handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION);
assertEquals(200, response.getStatus());
assertEquals(true, ((ObjectNode) response.getEntity()).get("Success").asBoolean());
ArgumentCaptor<InstanceConnectKeys.ActiveKey> stored = ArgumentCaptor.forClass(InstanceConnectKeys.ActiveKey.class);
verify(keys).add(stored.capture());
assertEquals("admin", stored.getValue().osUser());
assertEquals(NOW.plusSeconds(60), stored.getValue().expiresAt());
assertEquals(((ObjectNode) response.getEntity()).get("RequestId").asText(), stored.getValue().requestId());
assertEquals("arn:aws:iam::000000000000:root", stored.getValue().caller());
}
@Test
void theCallerArnIsInTheDeploymentsPartition() {
handlerIn("us-gov-west-1").handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION);
ArgumentCaptor<InstanceConnectKeys.ActiveKey> stored = ArgumentCaptor.forClass(InstanceConnectKeys.ActiveKey.class);
verify(keys).add(stored.capture());
assertEquals("arn:aws-us-gov:iam::000000000000:root", stored.getValue().caller());
}
private InstanceConnectJsonHandler handlerIn(String defaultRegion) {
return new InstanceConnectJsonHandler(ec2, keys, new RegionResolver(defaultRegion, "000000000000"), mapper,
Clock.fixed(NOW, ZoneOffset.UTC));
}
@Test
void rejectsWhatTheServiceModelAndAwsReject() {
Map<ObjectNode, String> cases = new LinkedHashMap<>();
cases.put(request("instance-1", "admin", ED25519), "InvalidArgsException");
cases.put(request(INSTANCE, "bad user", ED25519), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", "ssh-ed25519 AAAA"), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", "ssh-dss " + "A".repeat(100)), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", rsaKey(1024)), "InvalidArgsException");
// Right type, no key material: SSH could not use these, so they must not report Success.
cases.put(request(INSTANCE, "admin", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 " + "c".repeat(80)), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", sshKey("ssh-ed25519", new byte[31])), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp384", 65, (byte) 4)), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp256", 64, (byte) 4)), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp256", 65, (byte) 2)), "InvalidArgsException");
// An ssh-rsa blob with an empty exponent and a zero modulus, and a type label that disagrees with the blob.
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-rsa", new byte[0], new byte[256]) + " test"), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-ed25519", new byte[32]) + " test"), "InvalidArgsException");
// RFC 4251 s5: a 2048-bit modulus with its top bit set and no leading 0x00 is a negative mpint.
byte[] unsignedModulus = new byte[256];
unsignedModulus[0] = (byte) 0x80;
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-rsa", new byte[] {1, 0, 1}, unsignedModulus) + " test"), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", ED25519 + "\n#Timestamp=9999999999\n" + ED25519), "InvalidArgsException");
cases.put(request(INSTANCE, "admin", ED25519.replace("user@host", "us\u0007er@host")), "InvalidArgsException");
cases.put(request("i-0000000000000000f", "admin", ED25519), "EC2InstanceNotFoundException");
cases.forEach((request, code) -> assertEquals(code, assertThrows(AwsException.class,
() -> handler.handle("SendSSHPublicKey", request, REGION)).getErrorCode(), request.toString()));
instance.setState(InstanceState.stopped());
assertEquals("EC2InstanceStateInvalidException", assertThrows(AwsException.class,
() -> handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION)).getErrorCode());
verify(keys, never()).add(any());
}
@Test
void serialConsoleIsUnsupportedOnceTheInstanceIsFound() {
ObjectNode request = request(INSTANCE, "admin", ED25519);
assertEquals("SerialConsoleSessionUnsupportedException", assertThrows(AwsException.class,
() -> handler.handle("SendSerialConsoleSSHPublicKey", request, REGION)).getErrorCode());
ObjectNode missing = request("i-0000000000000000f", "admin", ED25519);
assertEquals("EC2InstanceNotFoundException", assertThrows(AwsException.class,
() -> handler.handle("SendSerialConsoleSSHPublicKey", missing, REGION)).getErrorCode());
}
@Test
void acceptsAnRsaKeyOf2048Bits() {
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", rsaKey(2048)), REGION);
verify(keys).add(any());
}
@Test
void acceptsWellFormedEd25519AndEcdsaKeys() {
// ECDSA lines are real ssh-keygen -t ecdsa output (throwaway keys, public half only).
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", sshKey("ssh-ed25519", new byte[32])), REGION);
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKhKXIBq6uSFm4w/wDQuFN9HzZFxgqLbSpaTJB+J6aAHWXBU7rpF1xa7s4dpFzLTSb+xn8JbKWbLozKoeIWV8hw= test"), REGION);
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBJFY0hkoTsJID0TIS1BgpJVWTDguQ7sTojV4dfGqMEKjMSAoOnXUdGV1Y+AIhF4rZE9IKsHsjtxg4JYesYz7FR+9CTxHjog7BGzYmVcsVSnRL3t68fT7S3cXhoVkV/3WZA== test"), REGION);
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBABCp6D79VfVN1Td7nP/lhUWST6qIkN28rgBp1FhyKO2UCTwxObXTOEL7WvfyQ+/J60K21J1ovjtlcC61YhWx0F7eAC/glgVeIBd0leLmmv3YGJkmE7POLgg4nfVXNLJayW3Q8rgyNAROCIC++3Avdn9GZIPrrFnyo1M0aNeW03/dLE2Xg== test"), REGION);
verify(keys, times(4)).add(any());
}
/** An ssh-ed25519 line carrying {@code material} as its key. */
private static String sshKey(String type, byte[] material) {
return type + " " + blob(type, material) + " test";
}
private static String ecdsaKey(String typeCurve, String blobCurve, int pointLength, byte first) {
byte[] point = new byte[pointLength];
point[0] = first;
return "ecdsa-sha2-" + typeCurve + " " + blob("ecdsa-sha2-" + typeCurve, blobCurve.getBytes(StandardCharsets.US_ASCII), point)
+ " test";
}
private static String blob(String type, byte[]... fields) {
byte[] t = type.getBytes(StandardCharsets.US_ASCII);
int size = 4 + t.length;
for (byte[] f : fields) {
size += 4 + f.length;
}
ByteBuffer b = ByteBuffer.allocate(size).putInt(t.length).put(t);
for (byte[] f : fields) {
b.putInt(f.length).put(f);
}
return Base64.getEncoder().encodeToString(b.array());
}
private ObjectNode request(String instanceId, String user, String key) {
ObjectNode node = mapper.createObjectNode();
node.put("InstanceId", instanceId);
node.put("InstanceOSUser", user);
node.put("SSHPublicKey", key);
return node;
}
/** An ssh-rsa line whose modulus has exactly {@code bits} bits; only its size is ever checked. */
private static String rsaKey(int bits) {
byte[] type = "ssh-rsa".getBytes(StandardCharsets.US_ASCII);
byte[] exponent = BigInteger.valueOf(65537).toByteArray();
byte[] modulus = BigInteger.ONE.shiftLeft(bits - 1).toByteArray();
ByteBuffer blob = ByteBuffer.allocate(12 + type.length + exponent.length + modulus.length);
blob.putInt(type.length).put(type).putInt(exponent.length).put(exponent).putInt(modulus.length).put(modulus);
return "ssh-rsa " + Base64.getEncoder().encodeToString(blob.array()) + " test";
}
}
@@ -0,0 +1,147 @@
package io.floci.aws.services.ec2instanceconnect;
import io.floci.aws.config.FlociCertificateAuthority;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.testing.ManualClock;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.OCSPResp;
import org.bouncycastle.cert.ocsp.SingleResp;
import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class InstanceConnectKeysTest {
private static final String REGION = "us-east-1";
private static final Instant NOW = Instant.parse("2026-10-16T12:00:00Z");
private static final String KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl test";
@TempDir
Path tlsDir;
private FlociCertificateAuthority root;
private ManualClock clock;
private InstanceConnectKeys keys;
@BeforeEach
void setUp() {
root = FlociCertificateAuthority.loadOrCreate(tlsDir);
clock = new ManualClock(NOW);
keys = new InstanceConnectKeys(() -> root, new CertificateGenerator(), clock);
}
@Test
void chainIsSignerThenIntermediateThenRootWithTheAgentsExpectedSignerName() throws Exception {
List<X509Certificate> chain = parseChain(keys.signerCertificateChain(REGION));
assertEquals(3, chain.size());
assertEquals("CN=managed-ssh-signer.us-east-1.amazonaws.com", chain.get(0).getSubjectX500Principal().getName());
assertEquals("CN=" + InstanceConnectKeys.INTERMEDIATE_CN, chain.get(1).getSubjectX500Principal().getName());
assertEquals(root.certificate(), chain.get(2));
chain.get(0).verify(chain.get(1).getPublicKey());
chain.get(1).verify(root.certificate().getPublicKey());
assertTrue(chain.get(1).getBasicConstraints() >= 0, "the intermediate is a CA");
assertEquals(-1, chain.get(0).getBasicConstraints(), "the signer is not");
assertEquals("Floci_Local_CA", keys.trustAnchorFileStem());
}
@Test
void theSignerNameUsesTheRegionsPartitionDomain() throws Exception {
assertEquals("CN=managed-ssh-signer.cn-north-1.amazonaws.com.cn",
parseChain(keys.signerCertificateChain("cn-north-1")).get(0).getSubjectX500Principal().getName());
}
@Test
void eachNonRootCertificateHasAGoodStapleSignedByItsIssuer() throws Exception {
List<X509Certificate> chain = parseChain(keys.signerCertificateChain(REGION));
Map<String, String> staples = keys.ocspStaples(REGION);
assertEquals(2, staples.size());
for (int i = 0; i < 2; i++) {
X509Certificate cert = chain.get(i);
X509Certificate issuer = chain.get(i + 1);
String staple = staples.get(InstanceConnectKeys.sha1Fingerprint(cert));
BasicOCSPResp basic = (BasicOCSPResp) new OCSPResp(Base64.getDecoder().decode(staple)).getResponseObject();
assertTrue(basic.isSignatureValid(new JcaContentVerifierProviderBuilder().build(issuer.getPublicKey())));
SingleResp single = basic.getResponses()[0];
assertNull(single.getCertStatus(), "null is OCSP 'good'");
CertificateID expected = new CertificateID(new JcaDigestCalculatorProviderBuilder().build()
.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuer), cert.getSerialNumber());
assertEquals(expected, single.getCertID());
}
}
@Test
void activeKeysAreSignedWithRsaPssOverTheHeaderAndKeyLines() throws Exception {
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "arn:aws:iam::000000000000:root", "req-1"));
String document = keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "admin").orElseThrow();
String[] lines = document.split("\n", -1);
assertEquals("#Timestamp=" + NOW.plusSeconds(60).getEpochSecond(), lines[0]);
assertEquals("#Instance=i-0123456789abcdef0", lines[1]);
assertEquals(KEY, lines[4]);
assertEquals("", lines[6], "a blank line ends each entry");
String signed = String.join("\n", List.of(lines).subList(0, 5)) + "\n";
X509Certificate signer = parseChain(keys.signerCertificateChain(REGION)).getFirst();
Signature verifier = Signature.getInstance("RSASSA-PSS");
verifier.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
verifier.initVerify(signer.getPublicKey());
verifier.update(signed.getBytes(StandardCharsets.UTF_8));
assertTrue(verifier.verify(Base64.getDecoder().decode(lines[5])));
}
@Test
void keysAreScopedToTheirUserAndExpireAfterSixtySeconds() {
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-1"));
assertTrue(keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "root").isEmpty());
assertTrue(keys.activeKeysDocument(REGION, "i-0000000000000000f", "admin").isEmpty());
clock.advance(Duration.ofSeconds(60));
assertTrue(keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "admin").isEmpty());
}
@Test
void expiredKeysAreDroppedWhenTheNextKeyArrives() {
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-1"));
clock.advance(Duration.ofSeconds(61));
keys.add(new InstanceConnectKeys.ActiveKey("i-0000000000000000f", "admin", KEY,
clock.instant().plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-2"));
assertEquals(1, keys.trackedInstanceCount(), "the first instance's expired key is not kept");
}
private static List<X509Certificate> parseChain(String pem) throws Exception {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
List<X509Certificate> chain = new ArrayList<>();
factory.generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)))
.forEach(cert -> chain.add((X509Certificate) cert));
return chain;
}
}
+2
View File
@@ -508,6 +508,8 @@ floci:
enabled: true
efs:
enabled: true
ec2instanceconnect:
enabled: true
organizations:
enabled: true
rum:
+1
View File
@@ -235,6 +235,7 @@ NOT_COVERED: dict[str, str] = {
"dlm": _REST,
"dms": _LATER,
"ec2": _LATER,
"ec2-instance-connect": _LATER,
"ecs": _LATER,
"elasticache": _LATER,
"elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, "
+4
View File
@@ -25,6 +25,10 @@ services:
doc: docs/services/access-analyzer.md
sources:
- { path: services/accessanalyzer/AccessAnalyzerController.java, mode: rest }
- service: ec2-instance-connect
doc: docs/services/ec2-instance-connect.md
sources:
- { path: services/ec2instanceconnect/InstanceConnectJsonHandler.java, mode: switch }
- service: acm
doc: docs/services/acm.md
sources: