mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 15:21:05 -05:00
feat(ssm): support agent-backed Session Manager sessions (#9492)
Session Manager for Linux EC2 guests running the stock SSM agent and the Session Manager plugin: interactive shells, SSH and port forwarding, with StartSession, ResumeSession, TerminateSession, DescribeSessions and GetConnectionStatus, and session document validation. Direct SendCommand execution on instances without the agent is unchanged. StartSession and GetConnectionStatus are checked on the EC2 target, and StartSession on the selected or default session document, read from the Session Manager guide and API reference pages vendored in tools/aws/sources/ssm-session-permissions.json. Replaces #9366, rebased onto main with the generated IAM table refreshed. On top of it, GetConnectionStatus echoes the Target it was asked about, as AWS answers. The agent's OpenDataChannel is checked on the session ARN, as the client's is, so a deny on one session reaches the instance role. Starting a session deletes the account's history older than the 30 days DescribeSessions lists. Closes #9365 Co-authored-by: James McMahon <james@jamesmcmahon.co.uk>
This commit is contained in:
1 parent
798c21df62
commit
05b77db069
52 files changed
+5656
-139
No files matched your search
@@ -54,6 +54,10 @@ starts() {
|
||||
# The image a test constant pins, or empty (and a log line) when the constant cannot be read.
|
||||
# TestImages is found by name rather than by its package path, which a package rename changes.
|
||||
TEST_IMAGES="$(find src/test/java -path '*/testing/TestImages.java' -print -quit)"
|
||||
if starts SsmSessionManagerDockerNightlyIntegrationTest; then
|
||||
pull debian:bookworm-slim
|
||||
pull postgres:17
|
||||
fi
|
||||
if starts Ec2PublishedConnectionNightlyIntegrationTest; then
|
||||
ecr public.ecr.aws/docker/library/alpine:latest
|
||||
pull alpine/socat
|
||||
|
||||
@@ -64,6 +64,9 @@ on:
|
||||
- 'tools/aws/sources/ec2-id-examples.json'
|
||||
- 'tools/aws/fetch_ec2_id_examples.py'
|
||||
- 'tools/aws/test_fetch_ec2_id_examples.py'
|
||||
- 'tools/aws/fetch_ssm_session_permissions.py'
|
||||
- 'tools/aws/sources/ssm-session-permissions.json'
|
||||
- 'tools/aws/test_fetch_ssm_session_permissions.py'
|
||||
- 'src/main/resources/aws/dynamodb-condition-keys.json'
|
||||
- 'tools/aws/regen_dynamodb_condition_keys.py'
|
||||
- 'tools/aws/test_regen_dynamodb_condition_keys.py'
|
||||
|
||||
@@ -654,6 +654,8 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json
|
||||
tools/aws/fetch_dynamodb_permissions.py tools/aws/test_fetch_dynamodb_permissions.py \
|
||||
tools/aws/sources/iam-identifiers.json tools/aws/fetch_iam_identifiers.py tools/aws/test_fetch_iam_identifiers.py \
|
||||
tools/aws/sources/ec2-id-examples.json tools/aws/fetch_ec2_id_examples.py tools/aws/test_fetch_ec2_id_examples.py \
|
||||
tools/aws/sources/ssm-session-permissions.json tools/aws/fetch_ssm_session_permissions.py \
|
||||
tools/aws/test_fetch_ssm_session_permissions.py \
|
||||
tools/aws/sources/required-resource-types.json tools/aws/fetch_required_resource_types.py \
|
||||
tools/aws/test_fetch_required_resource_types.py
|
||||
CLOUDTRAIL_S3_DATA_EVENTS_PATHS := src/main/resources/aws/cloudtrail-s3-data-events.json \
|
||||
@@ -887,7 +889,7 @@ iam-request-resources-verify: ## CI gate (online): every vendored operation must
|
||||
fi
|
||||
|
||||
iam-request-resources-test: ## Run the IAM request resource generator's unit tests
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_iam_request_resources.py tools/aws/test_fetch_ec2_id_examples.py -q
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_iam_request_resources.py tools/aws/test_fetch_ec2_id_examples.py tools/aws/test_fetch_ssm_session_permissions.py -q
|
||||
|
||||
cfn-property-types-sync: ## Regenerate src/main/resources/aws/cfn-property-types.json from AWS's resource schemas (commit the result)
|
||||
$(PYTHON) tools/aws/regen_cfn_property_types.py
|
||||
|
||||
@@ -314,7 +314,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
|
||||
| Service | How it works | Notable features |
|
||||
|---|---|---|
|
||||
| SSM | In-process + EC2 containers | Parameter Store (version history, labels, SecureString, tagging); Run Command (SendCommand, GetCommandInvocation, direct EC2 container execution, agent polling) |
|
||||
| SSM | In-process + EC2 containers | Parameter Store (version history, labels, SecureString, tagging); Run Command (SendCommand, GetCommandInvocation, direct EC2 container execution, agent polling); Session Manager (Linux shells, SSH, port forwarding) |
|
||||
| SQS | In-process | Standard and FIFO queues, DLQ, visibility timeout, batch operations, tagging |
|
||||
| SNS | In-process | Topics, subscriptions, SQS, Lambda and HTTP delivery, tagging |
|
||||
| S3 | In-process | Versioning, multipart upload, pre-signed URLs, Object Lock, object annotations, event notifications |
|
||||
|
||||
@@ -25,7 +25,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
|
||||
| Service | Endpoint | Protocol | Supported operations |
|
||||
|---|---|---|---|
|
||||
| [SSM](ssm.md) | `POST /` + `X-Amz-Target: AmazonSSM.*` / `AmazonSSMMessageDeliveryService.*` | JSON 1.1 | 48 |
|
||||
| [SSM](ssm.md) | `POST /` + `X-Amz-Target: AmazonSSM.*` / `AmazonSSMMessageDeliveryService.*`; Session Manager WebSockets | JSON 1.1 / WebSocket | 53 |
|
||||
| [SQS](sqs.md) | `POST /` with `Action=` param | Query / JSON | 23 |
|
||||
| [SNS](sns.md) | `POST /` with `Action=` param | Query / JSON | 39 |
|
||||
| [S3](s3.md) | `/{bucket}/{key}` | REST XML | 58 |
|
||||
|
||||
+73
-1
@@ -95,6 +95,16 @@ without a label filter continue to return the latest version of each parameter.
|
||||
| `ListCommandInvocations` | List command invocation records |
|
||||
| `CancelCommand` | Cancel pending or in-progress command invocations |
|
||||
|
||||
### Session Manager
|
||||
|
||||
| Action | Description |
|
||||
|---|---|
|
||||
| `StartSession` | Start a session on a connected managed instance and return a stream URL and token |
|
||||
| `ResumeSession` | Return a fresh stream token for an existing session |
|
||||
| `TerminateSession` | End a session |
|
||||
| `DescribeSessions` | List active sessions or session history for the caller's account and region |
|
||||
| `GetConnectionStatus` | Report whether the target has an open agent control channel |
|
||||
|
||||
### Documents
|
||||
|
||||
| Action | Description |
|
||||
@@ -142,6 +152,68 @@ The service settings Floci knows are `/ssm/documents/console/public-sharing-perm
|
||||
| `DeleteMessage` | Agent discards a command message |
|
||||
| `GetEndpoint` | Returns Floci's own base URL as the endpoint for the requested protocol |
|
||||
|
||||
## Use Session Manager with a Linux EC2 guest
|
||||
|
||||
1. Enable [TLS](../configuration/tls.md) on Floci. Launch a Linux guest in EC2 Docker mode with the
|
||||
stock Amazon SSM Agent installed. Attach an instance profile with `AmazonSSMManagedInstanceCore`
|
||||
so the agent can sign requests with the instance credentials from IMDS.
|
||||
2. In `/etc/amazon/ssm/amazon-ssm-agent.json`, point `Ssm.Endpoint` and `Mgs.Endpoint` at the Floci HTTPS
|
||||
endpoint the guest can reach, for example `https://host.docker.internal:4566`.
|
||||
Set `Mds.Endpoint` to the same URL if the agent also uses `ec2messages`.
|
||||
Set `SSL_CERT_FILE=/etc/floci-ca-bundle.pem` in the agent service environment and restart the agent.
|
||||
3. Install the AWS CLI and a Session Manager plugin with support for `AWS_SSM_PLUGIN_ADDITIONAL_STREAM_HOSTS`.
|
||||
Set that variable to the hostname or IP address in the client's Floci endpoint, without the port.
|
||||
For HTTPS, trust the Floci CA in both tools. On Linux, use `AWS_CA_BUNDLE` for the CLI and
|
||||
`SSL_CERT_FILE` for the plugin. See [TLS client configuration](../configuration/tls.md#quick-start).
|
||||
4. Use credentials in the guest's account and select the guest's region. Run `get-connection-status` first.
|
||||
Once the response says `connected`, start a shell.
|
||||
|
||||
```bash
|
||||
export AWS_SSM_PLUGIN_ADDITIONAL_STREAM_HOSTS=localhost
|
||||
export AWS_CA_BUNDLE="$PWD/floci-root-ca.pem"
|
||||
export SSL_CERT_FILE="$AWS_CA_BUNDLE"
|
||||
export FLOCI_ENDPOINT=https://localhost:4566
|
||||
export INSTANCE_ID=i-0123456789abcdef0
|
||||
|
||||
aws --endpoint-url "$FLOCI_ENDPOINT" --region us-east-1 ssm get-connection-status \
|
||||
--target "$INSTANCE_ID"
|
||||
aws --endpoint-url "$FLOCI_ENDPOINT" --region us-east-1 ssm start-session \
|
||||
--target "$INSTANCE_ID"
|
||||
```
|
||||
|
||||
With IAM enforcement on, `ssm:StartSession` requires permission on both the target EC2 instance
|
||||
and the session document. `ssm:GetConnectionStatus` requires permission on the target EC2 instance.
|
||||
If the caller omits `DocumentName`, grant access to `document/SSM-SessionManagerRunShell` in the
|
||||
caller's account and request region, even when the document has yet to be created. Grant the other
|
||||
Session Manager actions the caller uses. For a client that signs its stream upgrade, grant
|
||||
`ssmmessages:OpenDataChannel` on the session ARN.
|
||||
|
||||
### Session documents and transport
|
||||
|
||||
When `DocumentName` is omitted, `StartSession` uses the account's `SSM-SessionManagerRunShell` document
|
||||
if it exists in the request region. Otherwise it starts a standard shell with default settings.
|
||||
An explicit `DocumentName` must exist. Custom documents use the `Session` type and schema `1.0`.
|
||||
Floci accepts `Standard_Stream` and `Port` documents, with `String` and `StringList` parameters.
|
||||
|
||||
| AWS-owned document | Behaviour |
|
||||
|---|---|
|
||||
| `AWS-StartSSHSession` | Carries SSH to the guest. The guest needs an SSH server and its own SSH credentials. |
|
||||
| `AWS-StartPortForwardingSession` | Forwards a local TCP port to a port on the guest. |
|
||||
| `AWS-StartPortForwardingSessionToRemoteHost` | Forwards a local TCP port to a host and port that the guest can reach. |
|
||||
|
||||
The Session Manager plugin opens the stream URL returned by Floci. The URL uses the address and
|
||||
port of the caller's API endpoint. Its scheme is `ws` for HTTP and `wss` for HTTPS. The agent uses the
|
||||
`ssmmessages` control and data channels on its configured endpoint.
|
||||
|
||||
The Session Manager plugin calls `ResumeSession` when it reconnects after losing its connection.
|
||||
`ResumeSession` issues a new token for the existing session ID.
|
||||
The message gateway keeps live channels and tokens in memory. Restarting Floci ends live sessions.
|
||||
With an SSM storage mode that persists metadata, completed session records survive restart and
|
||||
recovered active records appear as `Failed`.
|
||||
|
||||
Session Manager supports Linux EC2 guests. Windows guests, hybrid managed nodes, interactive command
|
||||
documents, KMS session encryption, and S3 or CloudWatch session logging are outside the supported scope.
|
||||
|
||||
## Run Command Execution
|
||||
|
||||
`SendCommand` supports the `AWS-RunShellScript` document. For EC2 instances launched by Floci in real Docker mode, Floci creates the command invocation, returns the command response, and then runs the script asynchronously inside the target instance container. Callers observe completion through `GetCommandInvocation`. `stdout`, `stderr`, response code, start time, and end time are recorded on the invocation.
|
||||
@@ -188,7 +260,7 @@ coercion/upper-bound handling are not a complete document-schema implementation.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_SSM_ENABLED` | `true` | Enable or disable the service |
|
||||
| `FLOCI_SERVICES_SSM_ENABLED` | `true` | Enable SSM and its `ec2messages` and `ssmmessages` routes |
|
||||
| `FLOCI_SERVICES_SSM_MAX_PARAMETER_HISTORY` | `5` | Number of parameter versions retained per parameter |
|
||||
| `FLOCI_STORAGE_SERVICES_SSM_MODE` | *(global default)* | Storage mode override for SSM (`memory`, `persistent`, `hybrid`, `wal`) |
|
||||
| `FLOCI_STORAGE_SERVICES_SSM_FLUSH_INTERVAL_MS` | `5000` | Flush interval for `hybrid`/`wal` storage modes (milliseconds) |
|
||||
|
||||
@@ -349,7 +349,7 @@ public class AwsJson11Controller {
|
||||
String action = targetMatch.action();
|
||||
return switch (serviceKey) {
|
||||
case "ssm" -> ssmJsonHandler.handle(
|
||||
action, request, region, authorization);
|
||||
action, request, region, authorization, baseUri);
|
||||
case "events" -> eventBridgeHandler.handle(action, request, region);
|
||||
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
|
||||
case "elasticmapreduce" -> emrHandler.handle(action, request, region);
|
||||
|
||||
@@ -966,7 +966,7 @@ public final class RequestResources {
|
||||
// elements each name their own (above), so a list of none names nothing (a PutEvents of no entries).
|
||||
boolean perElement = resource.fill().values().stream().anyMatch(RequestResourceMembers.Member::eachElement);
|
||||
if (stored != null && account.equals(accountId) && !perElement) {
|
||||
stored.findDefault(resource.types().getFirst(), region).ifPresent(arns::add);
|
||||
stored.findImplicitDefault(resource.types().getFirst(), region).ifPresent(arns::add);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -657,6 +657,10 @@ public class ResolvedServiceCatalog {
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AmazonSSMMessageDeliveryService.", "EC2WindowsMessageDeliveryService."),
|
||||
Set.of("ec2messages"), Set.of(), Set.of()),
|
||||
descriptor("ssmmessages", "ssmmessages", config.services().ssm().enabled(), false,
|
||||
null, null, 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("ssmmessages"), 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),
|
||||
|
||||
@@ -208,6 +208,14 @@ public interface StoredResourceArns {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The default used for an omitted resource when its rule does not declare a default.
|
||||
* Services whose defaults apply only where declared can return empty.
|
||||
*/
|
||||
default Optional<String> findImplicitDefault(String type, String region) {
|
||||
return findDefault(type, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an ARN naming another account than the caller's, {@code accountId}, names a resource the service holds
|
||||
* in that account and acts on there, never as the caller's resource of that name (the sink an OAM link is made
|
||||
|
||||
@@ -153,7 +153,7 @@ public class AwsServiceRouter {
|
||||
case "sqs" -> sqsHandler.handle(action, requestBody, region);
|
||||
case "sns" -> snsHandler.handle(action, requestBody, region);
|
||||
case "events" -> eventBridgeHandler.handle(action, requestBody, region);
|
||||
case "ssm" -> ssmHandler.handle(action, requestBody, region, null);
|
||||
case "ssm" -> ssmHandler.handle(action, requestBody, region, null, null);
|
||||
case "kinesis" -> kinesisHandler.handle(action, requestBody, region);
|
||||
case "logs" -> logsHandler.handle(action, requestBody, region);
|
||||
case "monitoring" -> metricsHandler.handle(action, requestBody, region);
|
||||
|
||||
@@ -5658,6 +5658,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
session.getOriginAccountId(), session.getRoleArn(), session.getEc2RoleId(), session.getEc2InstanceId()));
|
||||
}
|
||||
|
||||
public record Ec2InstanceIdentity(String accountId, String instanceId) {}
|
||||
|
||||
/** Returns the instance bound to a live IMDS credential with the matching session token. */
|
||||
public Optional<Ec2InstanceIdentity> findEc2InstanceIdentity(String accessKeyId, String sessionToken) {
|
||||
if (sessionToken == null || sessionToken.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return currentSession(accessKeyId)
|
||||
.filter(session -> session.getEc2InstanceId() != null && !session.getEc2InstanceId().isBlank())
|
||||
.filter(session -> hasMatchingSessionToken(session, sessionToken))
|
||||
.map(session -> new Ec2InstanceIdentity(session.getOriginAccountId(), session.getEc2InstanceId()));
|
||||
}
|
||||
|
||||
private Optional<SessionCredential> currentSession(String accessKeyId) {
|
||||
return findSessionAnyAccount(accessKeyId).filter(session -> !isExpired(session, clock.instant()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import io.floci.aws.services.ssm.model.SsmDocument;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
final class BuiltinSessionDocuments {
|
||||
static final String OWNER = "Amazon";
|
||||
|
||||
private static final Map<String, String> CONTENT = Map.of(
|
||||
"AWS-StartSSHSession", load("AWS-StartSSHSession"),
|
||||
"AWS-StartPortForwardingSession", load("AWS-StartPortForwardingSession"),
|
||||
"AWS-StartPortForwardingSessionToRemoteHost", load("AWS-StartPortForwardingSessionToRemoteHost"));
|
||||
|
||||
private BuiltinSessionDocuments() {}
|
||||
|
||||
static boolean contains(String name) {
|
||||
return name != null && CONTENT.containsKey(name);
|
||||
}
|
||||
|
||||
static Optional<SsmDocument> find(String name) {
|
||||
return Optional.ofNullable(name == null ? null : CONTENT.get(name)).map(content -> document(name, content));
|
||||
}
|
||||
|
||||
static List<SsmDocument> list() {
|
||||
return CONTENT.entrySet().stream()
|
||||
.map(entry -> document(entry.getKey(), entry.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static SsmDocument document(String name, String content) {
|
||||
SsmDocument document = new SsmDocument(name, content, "Session");
|
||||
document.setOwner(OWNER);
|
||||
document.setCreatedDate(null);
|
||||
return document;
|
||||
}
|
||||
|
||||
private static String load(String name) {
|
||||
String path = "/ssm/" + name + ".json";
|
||||
try (InputStream input = Objects.requireNonNull(BuiltinSessionDocuments.class.getResourceAsStream(path), path)) {
|
||||
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not read built-in AWS document " + name, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
@@ -49,19 +50,21 @@ public class SsmJsonHandler {
|
||||
|
||||
private final SsmService ssmService;
|
||||
private final SsmCommandService commandService;
|
||||
private final SsmSessionJsonHandler sessionHandler;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final IamEnforcementFilter iamEnforcementFilter;
|
||||
|
||||
@Inject
|
||||
public SsmJsonHandler(SsmService ssmService, SsmCommandService commandService, ObjectMapper objectMapper,
|
||||
IamEnforcementFilter iamEnforcementFilter) {
|
||||
IamEnforcementFilter iamEnforcementFilter, SsmSessionJsonHandler sessionHandler) {
|
||||
this.ssmService = ssmService;
|
||||
this.commandService = commandService;
|
||||
this.sessionHandler = sessionHandler;
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamEnforcementFilter = iamEnforcementFilter;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region, String authorization) {
|
||||
public Response handle(String action, JsonNode request, String region, String authorization, URI baseUri) {
|
||||
return switch (action) {
|
||||
// Parameter Store
|
||||
case "PutParameter" -> handlePutParameter(request, region);
|
||||
@@ -87,6 +90,8 @@ public class SsmJsonHandler {
|
||||
case "ListCommandInvocations" -> handleListCommandInvocations(request, region);
|
||||
case "CancelCommand" -> handleCancelCommand(request, region);
|
||||
case "DescribeInstanceInformation" -> handleDescribeInstanceInformation(request, region);
|
||||
case "StartSession", "ResumeSession", "TerminateSession", "DescribeSessions", "GetConnectionStatus" ->
|
||||
sessionHandler.handle(action, request, region, baseUri);
|
||||
// Service settings (LZA ssm-block-public-document-sharing)
|
||||
case "GetServiceSetting" -> handleGetServiceSetting(request, region);
|
||||
case "UpdateServiceSetting" -> handleUpdateServiceSetting(request, region);
|
||||
@@ -538,12 +543,10 @@ public class SsmJsonHandler {
|
||||
private static final Pattern DOCUMENT_NAME = Pattern.compile("^[a-zA-Z0-9_\\-.]{3,128}$");
|
||||
|
||||
/**
|
||||
* {@code GetDocument} and {@code DescribeDocument} model a wider {@code Name} pattern than
|
||||
* the other five document operations: botocore's {@code Name} member on these two allows
|
||||
* {@code :} and {@code /}, because {@code DescribeDocument} accepts the document's full ARN
|
||||
* when reading a document shared from another account. The other five reject that shape.
|
||||
* {@code GetDocument}, {@code DescribeDocument} and {@code StartSession} allow the
|
||||
* {@code :} and {@code /} characters used by a full document ARN.
|
||||
*/
|
||||
private static final Pattern DOCUMENT_NAME_OR_ARN = Pattern.compile("^[a-zA-Z0-9_\\-.:/]{3,128}$");
|
||||
static final Pattern DOCUMENT_NAME_OR_ARN = Pattern.compile("^[a-zA-Z0-9_\\-.:/]{3,128}$");
|
||||
|
||||
private String requireDocumentName(JsonNode request) {
|
||||
return requireDocumentName(request, DOCUMENT_NAME);
|
||||
@@ -1652,6 +1655,11 @@ public class SsmJsonHandler {
|
||||
ObjectNode documentNode = objectMapper.createObjectNode();
|
||||
documentNode.put("Name", document.getName());
|
||||
documentNode.put("DocumentType", document.getDocumentType());
|
||||
documentNode.put("Owner", document.getOwner());
|
||||
if ("Session".equals(document.getDocumentType())) {
|
||||
documentNode.put("SchemaVersion", document.getSchemaVersion());
|
||||
}
|
||||
documentNode.put("DefaultVersion", String.valueOf(document.getDocumentVersion()));
|
||||
documentNode.put("DocumentVersion", effectiveVersion);
|
||||
documentNode.put("Content", effectiveContent);
|
||||
documentNode.put("Status", document.getStatus());
|
||||
|
||||
@@ -37,6 +37,8 @@ import io.floci.aws.services.ssm.model.PatchBaselineIdentity;
|
||||
import io.floci.aws.services.ssm.model.ServiceSetting;
|
||||
import io.floci.aws.services.ssm.model.SsmAssociation;
|
||||
import io.floci.aws.services.ssm.model.SsmDocument;
|
||||
import io.floci.aws.services.ssm.session.SessionDocumentResolver;
|
||||
import io.floci.aws.services.ssm.session.SsmSessionService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -1608,23 +1610,23 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
*/
|
||||
private SsmDocument associatedDocument(String nameOrArn, String region) {
|
||||
if (!AwsArnUtils.looksLikeArn(nameOrArn)) {
|
||||
return getDocument(nameOrArn, region);
|
||||
return requireOwnedDocument(nameOrArn, region);
|
||||
}
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(nameOrArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("Failed to parse document name as ARN: {0}", nameOrArn);
|
||||
return getDocument(nameOrArn, region);
|
||||
return requireOwnedDocument(nameOrArn, region);
|
||||
}
|
||||
if (!"ssm".equals(arn.service()) || !arn.resource().startsWith(DOCUMENT_PREFIX)
|
||||
|| !arn.region().equals(region) || !arn.partition().equals(regionResolver.partitionForRegion(region))) {
|
||||
return getDocument(nameOrArn, region);
|
||||
return requireOwnedDocument(nameOrArn, region);
|
||||
}
|
||||
String name = arn.resource().substring(DOCUMENT_PREFIX.length());
|
||||
String caller = regionResolver.getAccountId();
|
||||
if (arn.accountId().equals(caller)) {
|
||||
return getDocument(name, region);
|
||||
return requireOwnedDocument(name, region);
|
||||
}
|
||||
if (!documentSharedWith(arn.accountId(), name, region).contains(caller)) {
|
||||
throw new AwsException("InvalidDocument", "Document " + nameOrArn + " does not exist.", 400);
|
||||
@@ -1635,13 +1637,33 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
}
|
||||
|
||||
public SsmDocument getDocument(String name, String region) {
|
||||
SsmDocument document = documentStore.get(regionKey(region, name))
|
||||
.orElseThrow(() -> new AwsException("InvalidDocument",
|
||||
"Document " + name + " does not exist.", 400));
|
||||
if (document.getOwner() == null) {
|
||||
document.setOwner(regionResolver.getAccountId());
|
||||
}
|
||||
return document;
|
||||
return findDocument(name, region).orElseThrow(() -> missingDocument(name));
|
||||
}
|
||||
|
||||
public Optional<SsmDocument> findDocument(String name, String region) {
|
||||
return BuiltinSessionDocuments.find(name).or(() -> findOwnedDocument(name, region));
|
||||
}
|
||||
|
||||
public static String documentArn(String region, String accountId, String name) {
|
||||
String owner = BuiltinSessionDocuments.contains(name) ? "" : accountId;
|
||||
return AwsArnUtils.Arn.of("ssm", region, owner, DOCUMENT_PREFIX + name).toString();
|
||||
}
|
||||
|
||||
private SsmDocument requireOwnedDocument(String name, String region) {
|
||||
return findOwnedDocument(name, region).orElseThrow(() -> missingDocument(name));
|
||||
}
|
||||
|
||||
private Optional<SsmDocument> findOwnedDocument(String name, String region) {
|
||||
return documentStore.get(regionKey(region, name)).map(document -> {
|
||||
if (document.getOwner() == null) {
|
||||
document.setOwner(regionResolver.getAccountId());
|
||||
}
|
||||
return document;
|
||||
});
|
||||
}
|
||||
|
||||
private static AwsException missingDocument(String name) {
|
||||
return new AwsException("InvalidDocument", "Document " + name + " does not exist.", 400);
|
||||
}
|
||||
|
||||
public synchronized SsmDocument createDocument(String name, String content, String documentType, String region) {
|
||||
@@ -1651,6 +1673,9 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
public synchronized SsmDocument createDocument(String name, String content, String documentType,
|
||||
Map<String, String> tags, String region) {
|
||||
validateTagKeys(tags);
|
||||
if (BuiltinSessionDocuments.contains(name)) {
|
||||
throw new AwsException("InvalidDocumentName", "Document name " + name + " is reserved.", 400);
|
||||
}
|
||||
String storageKey = regionKey(region, name);
|
||||
if (documentStore.get(storageKey).isPresent()) {
|
||||
throw new AwsException("DocumentAlreadyExists",
|
||||
@@ -1687,7 +1712,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
* is resolved first.
|
||||
*/
|
||||
public List<String> describeDocumentPermission(String name, String region) {
|
||||
getDocument(name, region);
|
||||
requireOwnedDocument(name, region);
|
||||
return documentPermissionStore.get(regionKey(region, name))
|
||||
.map(List::copyOf)
|
||||
.orElse(List.of());
|
||||
@@ -1699,7 +1724,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
* <p>Only the document's owner may share it. Ownership here <em>is</em> the storage
|
||||
* partition: {@code documentStore} is an {@code AccountAwareStorageBackend}, whose key
|
||||
* prefix is the caller's account from {@code RequestContext} — the same resolution
|
||||
* {@code RegionResolver.getAccountId()} performs — so {@link #getDocument} can only
|
||||
* {@code RegionResolver.getAccountId()} performs — so {@link #requireOwnedDocument} can only
|
||||
* resolve a document in the caller's own partition. A caller that does not own the
|
||||
* document therefore gets InvalidDocument, which is AWS's answer for a document the
|
||||
* caller cannot see. Deriving the check from the partition rather than a second stored
|
||||
@@ -1707,7 +1732,7 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
*/
|
||||
public synchronized void modifyDocumentPermission(String name, List<String> accountIdsToAdd,
|
||||
List<String> accountIdsToRemove, String region) {
|
||||
getDocument(name, region);
|
||||
requireOwnedDocument(name, region);
|
||||
String storageKey = regionKey(region, name);
|
||||
List<String> accountIds = new ArrayList<>(
|
||||
documentPermissionStore.get(storageKey).orElse(List.of()));
|
||||
@@ -1723,13 +1748,14 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
|
||||
public List<SsmDocument> listDocuments(String region, Map<String, List<String>> filters) {
|
||||
String prefix = regionKey(region, "");
|
||||
List<SsmDocument> docs = documentStore.scan(k -> k.startsWith(prefix));
|
||||
List<SsmDocument> docs = new ArrayList<>(documentStore.scan(k -> k.startsWith(prefix)));
|
||||
String accountId = regionResolver.getAccountId();
|
||||
for (SsmDocument d : docs) {
|
||||
if (d.getOwner() == null) {
|
||||
d.setOwner(accountId);
|
||||
}
|
||||
}
|
||||
docs.addAll(BuiltinSessionDocuments.list());
|
||||
if (filters == null || filters.isEmpty()) {
|
||||
return docs;
|
||||
}
|
||||
@@ -1753,26 +1779,14 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every document visible through {@code documentStore} already belongs to the caller's
|
||||
* account (it is an account-partitioned store), so "Self"/"Private"/"All" and the caller's own
|
||||
* account id all match every visible document; "Amazon"/"Public"/"ThirdParty" match none, since
|
||||
* no AWS-owned or other-account documents are ever visible here. Documents created before the
|
||||
* {@code Owner} field existed persist with a null owner; since the store already guarantees the
|
||||
* caller's own partition, such a document is normalized to the current caller's account ID so
|
||||
* that it both matches owner filters and serializes its effective owner in list responses.
|
||||
*/
|
||||
private boolean matchesOwner(String filterValue, String documentOwner, String accountId) {
|
||||
if ("Self".equalsIgnoreCase(filterValue) || "Private".equalsIgnoreCase(filterValue)
|
||||
|| "All".equalsIgnoreCase(filterValue)) {
|
||||
return true;
|
||||
}
|
||||
if ("Amazon".equalsIgnoreCase(filterValue) || "Public".equalsIgnoreCase(filterValue)
|
||||
|| "ThirdParty".equalsIgnoreCase(filterValue)) {
|
||||
return false;
|
||||
}
|
||||
String effectiveOwner = documentOwner != null ? documentOwner : accountId;
|
||||
return filterValue.equals(effectiveOwner);
|
||||
return switch (filterValue.toLowerCase(Locale.ROOT)) {
|
||||
case "all" -> true;
|
||||
case "self", "private" -> accountId.equals(documentOwner);
|
||||
case "amazon" -> BuiltinSessionDocuments.OWNER.equals(documentOwner);
|
||||
case "public", "thirdparty" -> false;
|
||||
default -> filterValue.equals(documentOwner);
|
||||
};
|
||||
}
|
||||
|
||||
private List<String> findFilterValues(Map<String, List<String>> filters, String targetKey) {
|
||||
@@ -2197,17 +2211,45 @@ public class SsmService implements ResourceProvider, StoredResourceArns {
|
||||
|
||||
/**
|
||||
* The {@code parameter/<name>} ARN a legacy {@code parameter<name>} ARN of the caller's partition, Region and
|
||||
* account names, which the tagging operations act on as {@link #parameterTagName} reads it; empty for any other
|
||||
* value, whose ARN is the one its name renders.
|
||||
* account names, which the tagging operations act on as {@link #parameterTagName} reads it, or the ARN of an
|
||||
* AWS-owned Session document. Other resource identifiers use their regular ARN template.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"parameter".equals(type) || names.size() != 1) {
|
||||
if (names.size() != 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String name = names.getFirst();
|
||||
if ("document".equals(type) && BuiltinSessionDocuments.contains(name)) {
|
||||
return Optional.of(documentArn(region, regionResolver.getAccountId(), name));
|
||||
}
|
||||
if (!"parameter".equals(type)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String arn = withLegacyParameterSlash(name, regionResolver.partitionForRegion(region), region,
|
||||
regionResolver.getAccountId());
|
||||
return arn == null || arn.equals(name) ? Optional.empty() : Optional.of(arn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findDefault(String type, String region) {
|
||||
return "document".equals(type)
|
||||
? Optional.of(regionResolver.buildArn("ssm", region,
|
||||
DOCUMENT_PREFIX + SessionDocumentResolver.DEFAULT_DOCUMENT_NAME))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findImplicitDefault(String type, String region) {
|
||||
// Only a request with a declared default can select the shell document by omitting its name.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
if (!"Target".equals(member) || !SsmSessionService.isEc2Target(value)) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of(regionResolver.buildArn("ec2", region, "instance/" + value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.EpochSeconds;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.services.ssm.session.SsmSession;
|
||||
import io.floci.aws.services.ssm.session.SsmSessionService;
|
||||
import io.floci.aws.services.ssm.session.SsmSessionService.SessionConnection;
|
||||
import io.floci.aws.services.ssm.session.SsmSessionService.SessionFilter;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.floci.aws.services.ssm.SsmJsonDeserialization.serializationException;
|
||||
import static io.floci.aws.services.ssm.SsmJsonHandler.DOCUMENT_NAME_OR_ARN;
|
||||
|
||||
@ApplicationScoped
|
||||
class SsmSessionJsonHandler {
|
||||
private static final Pattern REASON = Pattern.compile("^.{1,256}$");
|
||||
|
||||
private final SsmSessionService sessions;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
SsmSessionJsonHandler(SsmSessionService sessions, ObjectMapper mapper) {
|
||||
this.sessions = sessions;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
Response handle(String action, JsonNode request, String region, URI baseUri) {
|
||||
return switch (action) {
|
||||
case "StartSession" -> start(request, region, baseUri);
|
||||
case "ResumeSession" -> connection(sessions.resume(region, sessionId(request), baseUri));
|
||||
case "TerminateSession" -> terminate(request, region);
|
||||
case "DescribeSessions" -> describe(request, region);
|
||||
case "GetConnectionStatus" -> connectionStatus(request, region);
|
||||
default -> throw new IllegalArgumentException("Unknown Session Manager action " + action);
|
||||
};
|
||||
}
|
||||
|
||||
private Response connectionStatus(JsonNode request, String region) {
|
||||
String target = requiredText(request.path("Target"), "target", 1, 400);
|
||||
return Response.ok(mapper.createObjectNode()
|
||||
.put("Target", target)
|
||||
.put("Status", sessions.isConnected(region, target) ? "connected" : "notconnected")).build();
|
||||
}
|
||||
|
||||
private Response start(JsonNode request, String region, URI baseUri) {
|
||||
String target = requiredText(request.path("Target"), "target", 1, 400);
|
||||
String name = optionalPattern(request.path("DocumentName"), "documentName", DOCUMENT_NAME_OR_ARN);
|
||||
String reason = optionalPattern(request.path("Reason"), "reason", REASON);
|
||||
return connection(sessions.start(region, target, name, reason, parameters(request.path("Parameters")), baseUri));
|
||||
}
|
||||
|
||||
private Response connection(SessionConnection session) {
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("SessionId", session.sessionId());
|
||||
response.put("StreamUrl", session.streamUrl());
|
||||
response.put("TokenValue", session.tokenValue());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response terminate(JsonNode request, String region) {
|
||||
String sessionId = sessionId(request);
|
||||
sessions.terminate(region, sessionId);
|
||||
return Response.ok(mapper.createObjectNode().put("SessionId", sessionId)).build();
|
||||
}
|
||||
|
||||
private Response describe(JsonNode request, String region) {
|
||||
String state = requiredText(request.path("State"), "state", 1, Integer.MAX_VALUE);
|
||||
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "SerializationException");
|
||||
String nextToken = Pagination.parseNextToken(request, "NextToken", "SerializationException");
|
||||
PaginatedResult<SsmSession> page = sessions.describe(region, state, filters(request.path("Filters")),
|
||||
maxResults, nextToken);
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
ArrayNode entries = response.putArray("Sessions");
|
||||
for (SsmSession session : page.items()) {
|
||||
ObjectNode entry = entries.addObject();
|
||||
entry.put("SessionId", session.sessionId());
|
||||
entry.put("Target", session.target());
|
||||
entry.put("Owner", session.owner());
|
||||
entry.put("Status", session.status());
|
||||
entry.put("DocumentName", session.documentName());
|
||||
entry.put("AccessType", "Standard");
|
||||
entry.put("StartDate", EpochSeconds.fromInstant(session.startDate()));
|
||||
if (session.endDate() != null) {
|
||||
entry.put("EndDate", EpochSeconds.fromInstant(session.endDate()));
|
||||
}
|
||||
if (session.reason() != null) {
|
||||
entry.put("Reason", session.reason());
|
||||
}
|
||||
}
|
||||
if (page.nextToken() != null) {
|
||||
response.put("NextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> parameters(JsonNode node) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return Map.of();
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw serializationException(node, "a map");
|
||||
}
|
||||
Map<String, List<String>> parameters = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> parameter : node.properties()) {
|
||||
String key = parameter.getKey();
|
||||
validateLength("parameters key", key, 1, 255);
|
||||
JsonNode array = parameter.getValue();
|
||||
if (!array.isArray()) {
|
||||
throw serializationException(array, "a list");
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode value : array) {
|
||||
values.add(requiredText(value, "parameters." + key + " member", 1, 65535));
|
||||
}
|
||||
parameters.put(key, values);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private static List<SessionFilter> filters(JsonNode node) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return List.of();
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw serializationException(node, "a list");
|
||||
}
|
||||
if (node.size() < 1 || node.size() > 6) {
|
||||
throw SmithyValidationErrors.validationException(
|
||||
"Value at 'filters' failed to satisfy constraint: Member must contain between 1 and 6 elements");
|
||||
}
|
||||
List<SessionFilter> filters = new ArrayList<>();
|
||||
for (JsonNode filter : node) {
|
||||
if (!filter.isObject()) {
|
||||
throw serializationException(filter, "a structure");
|
||||
}
|
||||
filters.add(new SessionFilter(requiredText(filter.path("key"), "filters key", 1, Integer.MAX_VALUE),
|
||||
requiredText(filter.path("value"), "filters value", 1, 400)));
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
private static String sessionId(JsonNode request) {
|
||||
return requiredText(request.path("SessionId"), "sessionId", 1, 96);
|
||||
}
|
||||
|
||||
private static String requiredText(JsonNode node, String path, int minLength, int maxLength) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull(path));
|
||||
}
|
||||
String text = readText(node);
|
||||
validateLength(path, text, minLength, maxLength);
|
||||
return text;
|
||||
}
|
||||
|
||||
private static String optionalPattern(JsonNode node, String path, Pattern pattern) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
String text = readText(node);
|
||||
if (!pattern.matcher(text).matches()) {
|
||||
throw SmithyValidationErrors.validationException("Value at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must satisfy regular expression pattern: " + pattern.pattern());
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
private static String readText(JsonNode node) {
|
||||
if (!node.isTextual()) {
|
||||
throw serializationException(node, "a String");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
private static void validateLength(String path, String value, int min, int max) {
|
||||
String violation = SmithyValidationErrors.lengthOutOfRange(path, value, min, max);
|
||||
if (violation != null) {
|
||||
throw SmithyValidationErrors.validationException(violation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package io.floci.aws.services.ssm.session;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DeadlineCharSequence;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.ssm.SsmService;
|
||||
import io.floci.aws.services.ssm.model.SsmDocument;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SessionDocumentResolver {
|
||||
public static final String DEFAULT_DOCUMENT_NAME = "SSM-SessionManagerRunShell";
|
||||
|
||||
private static final String IMPLICIT_SHELL = """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream"}
|
||||
""";
|
||||
private static final ObjectMapper DOCUMENT_MAPPER = new ObjectMapper(new YAMLFactory());
|
||||
private static final int MAX_DOCUMENT_BYTES = 65_536;
|
||||
private static final long PATTERN_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1);
|
||||
|
||||
private final SsmService ssmService;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
SessionDocumentResolver(SsmService ssmService, RegionResolver regionResolver) {
|
||||
this.ssmService = ssmService;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public ResolvedDocument resolve(String region, String documentName, Map<String, List<String>> parameters) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String name = documentName == null ? DEFAULT_DOCUMENT_NAME : documentName(documentName, region, accountId);
|
||||
SsmDocument document = ssmService.findDocument(name, region).orElse(null);
|
||||
String source;
|
||||
if (document == null && documentName == null) {
|
||||
source = IMPLICIT_SHELL;
|
||||
} else if (document == null) {
|
||||
throw missingDocument(documentName);
|
||||
} else if (!"Session".equals(document.getDocumentType())) {
|
||||
throw invalidDocument("Document type: '" + document.getDocumentType()
|
||||
+ "' is not supported. Only type: 'Session' is supported for session manager.");
|
||||
} else {
|
||||
source = document.getContent();
|
||||
}
|
||||
JsonNode content = parseDocument(name, source);
|
||||
Map<String, Object> resolved = resolveParameters(content.path("parameters"), parameters);
|
||||
validateInputs(content.path("inputs"));
|
||||
return new ResolvedDocument(name, SsmService.documentArn(region, accountId, name),
|
||||
content, resolved);
|
||||
}
|
||||
|
||||
private static String documentName(String nameOrArn, String region, String accountId) {
|
||||
if (!AwsArnUtils.looksLikeArn(nameOrArn)) {
|
||||
return nameOrArn;
|
||||
}
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(nameOrArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw missingDocument(nameOrArn);
|
||||
}
|
||||
String prefix = "document/";
|
||||
if (!arn.resource().startsWith(prefix)) {
|
||||
throw missingDocument(nameOrArn);
|
||||
}
|
||||
String name = arn.resource().substring(prefix.length());
|
||||
if (!nameOrArn.equals(SsmService.documentArn(region, accountId, name))) {
|
||||
throw missingDocument(nameOrArn);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static AwsException missingDocument(String name) {
|
||||
return invalidDocument("Document with name " + name + " does not exist.");
|
||||
}
|
||||
|
||||
private static JsonNode parseDocument(String name, String source) {
|
||||
if (source != null && (source.length() > MAX_DOCUMENT_BYTES
|
||||
|| source.getBytes(StandardCharsets.UTF_8).length > MAX_DOCUMENT_BYTES)) {
|
||||
throw invalidDocument("Document " + name + " exceeds the " + MAX_DOCUMENT_BYTES + " byte size limit.");
|
||||
}
|
||||
try {
|
||||
JsonNode content = source == null ? null : DOCUMENT_MAPPER.readTree(source);
|
||||
if (content == null || !content.isObject()
|
||||
|| !"1.0".equals(content.path("schemaVersion").asText())
|
||||
|| (content.hasNonNull("parameters") && !content.path("parameters").isObject())) {
|
||||
throw invalidDocument("Document " + name + " does not contain a valid Session document.");
|
||||
}
|
||||
String sessionType = content.path("sessionType").asText();
|
||||
if (!"Standard_Stream".equals(sessionType) && !"Port".equals(sessionType)) {
|
||||
throw invalidDocument("Session type '" + sessionType + "' is not supported.");
|
||||
}
|
||||
return content;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw invalidDocument("Document " + name + " does not contain a valid Session document.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> resolveParameters(JsonNode definitions, Map<String, List<String>> supplied) {
|
||||
for (String name : supplied.keySet()) {
|
||||
if (!definitions.has(name)) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" is not defined in the document.");
|
||||
}
|
||||
}
|
||||
Map<String, Object> resolved = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> entry : definitions.properties()) {
|
||||
String name = entry.getKey();
|
||||
JsonNode definition = entry.getValue();
|
||||
boolean scalar = switch (definition.path("type").asText()) {
|
||||
case "String" -> true;
|
||||
case "StringList" -> false;
|
||||
default -> throw invalidDocument("Parameter \"" + name + "\" has an unsupported type.");
|
||||
};
|
||||
List<String> values = supplied.containsKey(name)
|
||||
? supplied.get(name) : defaultValues(name, definition.path("default"), scalar);
|
||||
if (scalar && values.size() != 1) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" takes exactly one value, got " + values.size() + ".");
|
||||
}
|
||||
if (!scalar) {
|
||||
validateLength(name, definition, values.size(), "minItems", "maxItems");
|
||||
}
|
||||
validateValues(name, definition, values);
|
||||
validatePattern(name, definition.path("allowedPattern").asText(), values);
|
||||
resolved.put(name, scalar ? values.getFirst() : List.copyOf(values));
|
||||
}
|
||||
return Map.copyOf(resolved);
|
||||
}
|
||||
|
||||
private static List<String> defaultValues(String name, JsonNode defaultValue, boolean scalar) {
|
||||
if (defaultValue.isMissingNode() || defaultValue.isNull()) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" requires a value.");
|
||||
}
|
||||
if (scalar && defaultValue.isTextual()) {
|
||||
return List.of(defaultValue.textValue());
|
||||
}
|
||||
if (!scalar && defaultValue.isArray()) {
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode value : defaultValue) {
|
||||
if (!value.isTextual()) {
|
||||
throw invalidDocument("Parameter \"" + name + "\" has an invalid default value.");
|
||||
}
|
||||
values.add(value.textValue());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
throw invalidDocument("Parameter \"" + name + "\" has an invalid default value.");
|
||||
}
|
||||
|
||||
private static void validateValues(String name, JsonNode definition, List<String> values) {
|
||||
JsonNode allowedValues = definition.path("allowedValues");
|
||||
if (!allowedValues.isMissingNode() && !allowedValues.isArray()) {
|
||||
throw invalidDocument("Parameter \"" + name + "\" has invalid allowedValues.");
|
||||
}
|
||||
for (String value : values) {
|
||||
if (allowedValues.isArray()
|
||||
&& allowedValues.valueStream().noneMatch(allowed -> value.equals(allowed.textValue()))) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" has value \"" + value
|
||||
+ "\" outside its allowedValues.");
|
||||
}
|
||||
validateLength(name, definition, value.length(), "minChars", "maxChars");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateLength(String name, JsonNode definition, int length, String min, String max) {
|
||||
if (length < definition.path(min).asInt(0)) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" violates " + min + ".");
|
||||
}
|
||||
if (length > definition.path(max).asInt(Integer.MAX_VALUE)) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" violates " + max + ".");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validatePattern(String name, String allowedPattern, List<String> values) {
|
||||
if (allowedPattern.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Pattern pattern = Pattern.compile(allowedPattern);
|
||||
long deadline = System.nanoTime() + PATTERN_TIMEOUT_NANOS;
|
||||
for (String value : values) {
|
||||
if (!pattern.matcher(new DeadlineCharSequence(value, deadline, "AllowedPattern timed out")).matches()) {
|
||||
throw invalidParameters("Parameter \"" + name + "\" has value \"" + value
|
||||
+ "\" not matching \"" + allowedPattern + "\".");
|
||||
}
|
||||
}
|
||||
} catch (PatternSyntaxException | IllegalStateException e) {
|
||||
throw invalidDocument("Parameter \"" + name + "\" has an invalid or overly complex allowedPattern.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateInputs(JsonNode inputs) {
|
||||
if (!inputs.isMissingNode() && !inputs.isObject()) {
|
||||
throw invalidDocument("Session document inputs must be an object.");
|
||||
}
|
||||
if (!inputs.path("kmsKeyId").asText().isBlank()
|
||||
|| !inputs.path("s3BucketName").asText().isBlank()
|
||||
|| !inputs.path("cloudWatchLogGroupName").asText().isBlank()) {
|
||||
throw invalidDocument("Session Manager KMS encryption and session logging are not supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalidDocument(String message) {
|
||||
return new AwsException("InvalidDocument", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException invalidParameters(String message) {
|
||||
return new AwsException("InvalidParameters", message, 400);
|
||||
}
|
||||
|
||||
public record ResolvedDocument(String name, String arn, JsonNode content, Map<String, Object> parameters) { }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.floci.aws.services.ssm.session;
|
||||
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionState;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
public record SsmSession(String sessionId, String target, String owner, String documentName,
|
||||
String reason, SessionState state, Instant startDate, Instant endDate) {
|
||||
public boolean active() {
|
||||
return endDate == null;
|
||||
}
|
||||
|
||||
public String status() {
|
||||
return switch (state) {
|
||||
case CONNECTED -> "Connected";
|
||||
case DISCONNECTED -> "Disconnected";
|
||||
case TERMINATED -> "Terminated";
|
||||
case FAILED -> "Failed";
|
||||
};
|
||||
}
|
||||
|
||||
SsmSession transition(SessionState next, Instant now) {
|
||||
Instant end = switch (next) {
|
||||
case TERMINATED, FAILED -> now;
|
||||
case CONNECTED, DISCONNECTED -> null;
|
||||
};
|
||||
return new SsmSession(sessionId, target, owner, documentName, reason, next, startDate, end);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package io.floci.aws.services.ssm.session;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.ssm.session.SessionDocumentResolver.ResolvedDocument;
|
||||
import io.floci.aws.services.ssmmessages.DataChannelRouter;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.Node;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionRequest;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionState;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.UriBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SsmSessionService implements Resettable {
|
||||
private static final int MAX_RESULTS = 200;
|
||||
private static final Duration HISTORY_RETENTION = Duration.ofDays(30);
|
||||
private static final Pattern EC2_TARGET = Pattern.compile("i-(?:[0-9a-f]{8}|[0-9a-f]{17})");
|
||||
|
||||
private final AccountAwareStorageBackend<SsmSession> sessions;
|
||||
private final SsmMessageGateway gateway;
|
||||
private final SessionDocumentResolver documents;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RequestContext requestContext;
|
||||
private final IamService iam;
|
||||
private final Clock clock;
|
||||
private final URI baseUri;
|
||||
private boolean resetting;
|
||||
|
||||
@Inject
|
||||
public SsmSessionService(StorageFactory storage, SsmMessageGateway gateway, SessionDocumentResolver documents,
|
||||
RegionResolver regionResolver, RequestContext requestContext, IamService iam,
|
||||
Clock clock, EmulatorConfig config) {
|
||||
this(storage.create("ssm", "ssm-sessions.json", new TypeReference<>() {}), gateway, documents, regionResolver,
|
||||
requestContext, iam, clock, URI.create(config.effectiveBaseUrl()));
|
||||
}
|
||||
|
||||
SsmSessionService(AccountAwareStorageBackend<SsmSession> sessions, SsmMessageGateway gateway,
|
||||
SessionDocumentResolver documents, RegionResolver regionResolver, RequestContext requestContext,
|
||||
IamService iam, Clock clock, URI baseUri) {
|
||||
this.sessions = sessions;
|
||||
this.gateway = gateway;
|
||||
this.documents = documents;
|
||||
this.regionResolver = regionResolver;
|
||||
this.requestContext = requestContext;
|
||||
this.iam = iam;
|
||||
this.clock = clock;
|
||||
this.baseUri = baseUri;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void closeRecoveredSessions() {
|
||||
// Agent sockets and channel tokens live in memory. A recovered active row has no live session.
|
||||
Instant now = clock.instant();
|
||||
for (AccountEntry<SsmSession> entry : sessions.scanAllAccountEntries(key -> true)) {
|
||||
if (entry.value().active()) {
|
||||
sessions.putForAccount(entry.accountId(), entry.key(), entry.value().transition(SessionState.FAILED, now));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized SessionConnection start(String region, String target, String documentName, String reason,
|
||||
Map<String, List<String>> parameters, URI requestBaseUri) {
|
||||
Node node = node(region, target);
|
||||
if (!isEc2Target(target) || resetting || !gateway.isConnected(node)) {
|
||||
throw new AwsException("TargetNotConnected", target + " is not connected.", 400);
|
||||
}
|
||||
String owner = ownerArn(node.accountId());
|
||||
ResolvedDocument document = documents.resolve(region, documentName, parameters);
|
||||
deleteExpiredHistory();
|
||||
String sessionId = sessionId(owner);
|
||||
String arn = AwsArnUtils.Arn.of("ssm", region, node.accountId(), "session/" + sessionId).toString();
|
||||
String url = streamUrl(sessionId, requestBaseUri);
|
||||
String key = sessionKey(region, sessionId);
|
||||
SessionRequest request = new SessionRequest(sessionId, arn, owner, node, document.name(), document.content(),
|
||||
document.parameters());
|
||||
sessions.put(key, new SsmSession(sessionId, target, owner, document.name(), reason,
|
||||
SessionState.CONNECTED, clock.instant(), null));
|
||||
String token;
|
||||
try {
|
||||
token = gateway.startSession(request, state -> RequestScopes.runAs(node.accountId(), region,
|
||||
() -> transition(key, state)));
|
||||
} catch (RuntimeException e) {
|
||||
sessions.delete(key);
|
||||
throw e;
|
||||
}
|
||||
return new SessionConnection(sessionId, url, token);
|
||||
}
|
||||
|
||||
public synchronized SessionConnection resume(String region, String sessionId, URI requestBaseUri) {
|
||||
SsmSession session = requireActive(region, sessionId);
|
||||
String token = gateway.resumeSession(node(region, session.target()), sessionId)
|
||||
.orElseThrow(SsmSessionService::invalidSessionState);
|
||||
return new SessionConnection(sessionId, streamUrl(sessionId, requestBaseUri), token);
|
||||
}
|
||||
|
||||
public synchronized void terminate(String region, String sessionId) {
|
||||
SsmSession session = requireActive(region, sessionId);
|
||||
gateway.terminateSession(node(region, session.target()), sessionId);
|
||||
transition(sessionKey(region, sessionId), SessionState.TERMINATED);
|
||||
}
|
||||
|
||||
public synchronized boolean isConnected(String region, String target) {
|
||||
return isEc2Target(target) && !resetting && gateway.isConnected(node(region, target));
|
||||
}
|
||||
|
||||
public static boolean isEc2Target(String target) {
|
||||
return EC2_TARGET.matcher(target).matches();
|
||||
}
|
||||
|
||||
public synchronized PaginatedResult<SsmSession> describe(String region, String state, List<SessionFilter> filters,
|
||||
Integer maxResults, String nextToken) {
|
||||
boolean active = switch (state) {
|
||||
case "Active" -> true;
|
||||
case "History" -> false;
|
||||
default -> throw new AwsException("ValidationException", "State must be Active or History.", 400);
|
||||
};
|
||||
if (maxResults != null && (maxResults < 1 || maxResults > MAX_RESULTS)) {
|
||||
throw new AwsException("ValidationException", "MaxResults must be between 1 and 200.", 400);
|
||||
}
|
||||
List<Predicate<SsmSession>> predicates = filters.stream().map(SsmSessionService::filter).toList();
|
||||
Instant cutoff = clock.instant().minus(HISTORY_RETENTION);
|
||||
String prefix = sessionKey(region, "");
|
||||
List<SsmSession> matching = sessions.scan(key -> key.startsWith(prefix)).stream()
|
||||
.filter(session -> active == session.active())
|
||||
.filter(session -> active || !session.endDate().isBefore(cutoff))
|
||||
.filter(session -> predicates.stream().allMatch(predicate -> predicate.test(session)))
|
||||
.toList();
|
||||
return Pagination.paginate(matching, SsmSessionService::cursor,
|
||||
maxResults == null ? MAX_RESULTS : maxResults, nextToken,
|
||||
regionResolver.getAccountId() + "/" + region + "/" + state,
|
||||
ignored -> new AwsException("InvalidNextToken", "Invalid next token.", 400));
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void beforeReset() {
|
||||
resetting = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
// StorageFactory clears the metadata and the message gateway closes live channels.
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void afterReset() {
|
||||
resetting = false;
|
||||
}
|
||||
|
||||
private synchronized void transition(String key, SessionState state) {
|
||||
if (resetting) {
|
||||
return;
|
||||
}
|
||||
sessions.get(key).filter(SsmSession::active).filter(session -> session.state() != state)
|
||||
.ifPresent(session -> sessions.put(key, session.transition(state, clock.instant())));
|
||||
}
|
||||
|
||||
// DescribeSessions lists History for 30 days. Each start drops the caller's older rows, so the store stays bounded.
|
||||
private void deleteExpiredHistory() {
|
||||
Instant cutoff = clock.instant().minus(HISTORY_RETENTION);
|
||||
for (String key : sessions.keys()) {
|
||||
if (sessions.get(key).filter(session -> !session.active() && session.endDate().isBefore(cutoff))
|
||||
.isPresent()) {
|
||||
sessions.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SsmSession requireActive(String region, String sessionId) {
|
||||
if (resetting) {
|
||||
throw invalidSessionState();
|
||||
}
|
||||
return sessions.get(sessionKey(region, sessionId)).filter(SsmSession::active)
|
||||
.orElseThrow(SsmSessionService::invalidSessionState);
|
||||
}
|
||||
|
||||
private static AwsException invalidSessionState() {
|
||||
return new AwsException("ValidationException", "Session is not in a valid state", 400);
|
||||
}
|
||||
|
||||
private Node node(String region, String target) {
|
||||
return new Node(regionResolver.getAccountId(), region, target);
|
||||
}
|
||||
|
||||
private String ownerArn(String accountId) {
|
||||
String accessKey = requestContext.getAccessKeyId();
|
||||
return iam.resolveCallerArn(accessKey)
|
||||
.map(arn -> {
|
||||
if (!accountId.equals(AwsArnUtils.parse(arn).accountId())) {
|
||||
throw new AwsException("AccessDeniedException", "Could not identify the session caller.", 403);
|
||||
}
|
||||
return arn;
|
||||
})
|
||||
.orElseGet(() -> regionResolver.buildGlobalArn("iam", accountId, "root"));
|
||||
}
|
||||
|
||||
private static String sessionId(String ownerArn) {
|
||||
String resource = AwsArnUtils.parse(ownerArn).resource();
|
||||
String prefix = resource.substring(resource.lastIndexOf('/') + 1);
|
||||
return prefix + "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 26);
|
||||
}
|
||||
|
||||
private String streamUrl(String sessionId, URI requestBaseUri) {
|
||||
URI endpoint = requestBaseUri != null ? requestBaseUri : baseUri;
|
||||
return UriBuilder.fromUri(endpoint)
|
||||
.scheme("https".equalsIgnoreCase(endpoint.getScheme()) ? "wss" : "ws")
|
||||
.path(DataChannelRouter.CHANNEL_PATH_PREFIX)
|
||||
.segment(sessionId)
|
||||
.queryParam("role", "publish_subscribe")
|
||||
.build().toString();
|
||||
}
|
||||
|
||||
private static String sessionKey(String region, String sessionId) {
|
||||
return region + "|" + sessionId;
|
||||
}
|
||||
|
||||
private static String cursor(SsmSession session) {
|
||||
long reverseStart = Long.MAX_VALUE - session.startDate().toEpochMilli();
|
||||
return String.format(Locale.ROOT, "%019d/%s", reverseStart, session.sessionId());
|
||||
}
|
||||
|
||||
private static Predicate<SsmSession> filter(SessionFilter filter) {
|
||||
String value = filter.value();
|
||||
return switch (filter.key()) {
|
||||
case "SessionId" -> session -> session.sessionId().equals(value);
|
||||
case "Target" -> session -> session.target().equals(value);
|
||||
case "Owner" -> session -> session.owner().equals(value);
|
||||
case "Status" -> session -> session.status().equals(value);
|
||||
case "AccessType" -> session -> "Standard".equals(value);
|
||||
case "InvokedBefore" -> {
|
||||
Instant before = filterTime(filter);
|
||||
yield session -> session.startDate().isBefore(before);
|
||||
}
|
||||
case "InvokedAfter" -> {
|
||||
Instant after = filterTime(filter);
|
||||
yield session -> !session.startDate().isBefore(after);
|
||||
}
|
||||
default -> throw new AwsException("InvalidFilterKey", "Invalid filter key " + filter.key() + ".", 400);
|
||||
};
|
||||
}
|
||||
|
||||
private static Instant filterTime(SessionFilter filter) {
|
||||
try {
|
||||
return Instant.parse(filter.value());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new AwsException("BadRequest", "Invalid filter value " + filter.value()
|
||||
+ " for filter key " + filter.key(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
public record SessionConnection(String sessionId, String streamUrl, String tokenValue) {}
|
||||
public record SessionFilter(String key, String value) {}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -118,6 +119,19 @@ public record AgentMessage(
|
||||
return payload == null ? "" : new String(payload, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** Validates the frame bounds before relaying the original bytes to the other peer. */
|
||||
static String gatewayMessageType(Buffer frame) {
|
||||
if (frame.length() < PAYLOAD_OFFSET || frame.getInt(0) != HEADER_LENGTH
|
||||
|| frame.getInt(HEADER_LENGTH) != frame.length() - PAYLOAD_OFFSET) {
|
||||
throw new IllegalArgumentException("Invalid agent message length");
|
||||
}
|
||||
String type = frame.getString(Integer.BYTES, Integer.BYTES + MESSAGE_TYPE_LENGTH).trim();
|
||||
if (type.isEmpty()) {
|
||||
throw new IllegalArgumentException("Missing agent message type");
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private byte[] paddedMessageType() {
|
||||
byte[] padded = new byte[MESSAGE_TYPE_LENGTH];
|
||||
Arrays.fill(padded, (byte) ' ');
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.IamEnforcementFilter;
|
||||
import io.floci.aws.core.common.RequestHost;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.auth.CredentialScope;
|
||||
import io.floci.aws.core.common.auth.SigV4Canonicalization;
|
||||
import io.floci.aws.core.common.auth.SigV4RequestValidator;
|
||||
import io.floci.aws.core.common.auth.SigV4SignedRequest;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpVersion;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.floci.aws.core.common.auth.SigV4RequestValidator.LEGACY_ACCESS_KEY_ID;
|
||||
import static io.floci.aws.core.common.auth.SigV4RequestValidator.LEGACY_SECRET_KEY;
|
||||
|
||||
/** Authenticates the signed HTTP requests that enter the message gateway outside JAX-RS. */
|
||||
@ApplicationScoped
|
||||
public class ChannelAuthentication {
|
||||
|
||||
public static final String SIGNING_SERVICE = "ssmmessages";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ChannelAuthentication.class);
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
private static final String DATE = "X-Amz-Date";
|
||||
private static final String TOKEN = "X-Amz-Security-Token";
|
||||
private static final Set<String> PRESIGN_PARAMETERS = Set.of("X-Amz-Algorithm", "X-Amz-Credential",
|
||||
DATE, "X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature", TOKEN);
|
||||
private static final byte[] EMPTY_BODY = new byte[0];
|
||||
|
||||
private final IamService iamService;
|
||||
private final AccountResolver accountResolver;
|
||||
private final IamEnforcementFilter iamEnforcement;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public ChannelAuthentication(IamService iamService, AccountResolver accountResolver,
|
||||
IamEnforcementFilter iamEnforcement) {
|
||||
this(iamService, accountResolver, iamEnforcement, Clock.systemUTC());
|
||||
}
|
||||
|
||||
ChannelAuthentication(IamService iamService, AccountResolver accountResolver,
|
||||
IamEnforcementFilter iamEnforcement, Clock clock) {
|
||||
this.iamService = iamService;
|
||||
this.accountResolver = accountResolver;
|
||||
this.iamEnforcement = iamEnforcement;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public record AgentIdentity(String accountId, String region, String instanceId) {}
|
||||
|
||||
private record Claim(SigV4SignedRequest signature, CredentialScope scope, String sessionToken, String host) {}
|
||||
|
||||
/** Returns the signing instance. The caller must match it to the target of the requested channel. */
|
||||
public AgentIdentity authenticateAgent(HttpServerRequest request, byte[] body, String action) {
|
||||
Claim claim = readClaim(request);
|
||||
IamService.Ec2InstanceIdentity instance = signingInstance(claim).orElseThrow(ChannelAuthentication::denied);
|
||||
return authenticateAgent(request, body, action, "*", claim, instance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates the signing instance when an IMDS credential signs a data-channel upgrade, authorised on the
|
||||
* session the channel belongs to.
|
||||
*/
|
||||
public Optional<AgentIdentity> authenticateAgentUpgradeIfClaimed(HttpServerRequest request, String action,
|
||||
String sessionArn) {
|
||||
Claim claim = readClaim(request);
|
||||
return signingInstance(claim)
|
||||
.map(instance -> authenticateAgent(request, EMPTY_BODY, action, sessionArn, claim, instance));
|
||||
}
|
||||
|
||||
private Optional<IamService.Ec2InstanceIdentity> signingInstance(Claim claim) {
|
||||
return claim == null ? Optional.empty()
|
||||
: iamService.findEc2InstanceIdentity(claim.scope().accessKeyId(), claim.sessionToken());
|
||||
}
|
||||
|
||||
private AgentIdentity authenticateAgent(HttpServerRequest request, byte[] body, String action, String resource,
|
||||
Claim claim, IamService.Ec2InstanceIdentity instance) {
|
||||
if (claim.signature().presigned()) {
|
||||
throw denied();
|
||||
}
|
||||
String key = claim.scope().accessKeyId();
|
||||
String region = claim.scope().region();
|
||||
return RequestScopes.callAs(instance.accountId(), region, () -> {
|
||||
String secret = iamService.findSecretKey(key, claim.sessionToken())
|
||||
.orElseThrow(ChannelAuthentication::denied);
|
||||
verify(request, body, claim, secret);
|
||||
iamEnforcement.authorizeRequestParameters(request.getHeader(AUTHORIZATION), action, resource,
|
||||
request::getParam);
|
||||
return new AgentIdentity(instance.accountId(), region, instance.instanceId());
|
||||
});
|
||||
}
|
||||
|
||||
/** Verifies and authorises a client WebSocket's SigV4 claim when present. The channel grant is still required. */
|
||||
public Optional<String> authorizeClient(HttpServerRequest request, String accountId, String region, String sessionArn) {
|
||||
Claim claim = readClaim(request);
|
||||
if (claim == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String key = claim.scope().accessKeyId();
|
||||
boolean legacy = LEGACY_ACCESS_KEY_ID.equals(key);
|
||||
String callerAccount = legacy ? accountResolver.resolve(null) : iamService.resolveAccountId(key).orElse(null);
|
||||
if (!accountId.equals(callerAccount) || !region.equals(claim.scope().region())) {
|
||||
throw denied();
|
||||
}
|
||||
return RequestScopes.callAs(callerAccount, region, () -> {
|
||||
String secret = legacy ? LEGACY_SECRET_KEY : iamService.findSecretKey(key, claim.sessionToken())
|
||||
.orElseThrow(ChannelAuthentication::denied);
|
||||
verify(request, EMPTY_BODY, claim, secret);
|
||||
iamEnforcement.authorizeRequestParameters(AccountResolver.SIGV4_SCHEME + " Credential="
|
||||
+ claim.signature().credential(), "ssmmessages:OpenDataChannel", sessionArn, request::getParam);
|
||||
return Optional.of(key);
|
||||
});
|
||||
}
|
||||
|
||||
private Claim readClaim(HttpServerRequest request) {
|
||||
MultiMap headers = request.headers();
|
||||
String authorization = single(headers.getAll(AUTHORIZATION));
|
||||
Map<String, List<String>> params = queryParameters(request.query());
|
||||
boolean presigned = PRESIGN_PARAMETERS.stream().anyMatch(params::containsKey);
|
||||
if (presigned && authorization != null) {
|
||||
throw denied();
|
||||
}
|
||||
if (!presigned && authorization == null) {
|
||||
return null;
|
||||
}
|
||||
if (presigned && !SigV4SignedRequest.ALGORITHM.equals(single(params.get("X-Amz-Algorithm")))) {
|
||||
throw denied();
|
||||
}
|
||||
SigV4SignedRequest signature = presigned
|
||||
? SigV4SignedRequest.fromQuery(name -> single(params.get(name)))
|
||||
: SigV4SignedRequest.fromHeader(authorization, single(headers.getAll(DATE)));
|
||||
CredentialScope scope = signature == null ? null : CredentialScope.parse(signature.credential());
|
||||
String host = single(headers.getAll("host"));
|
||||
if (host == null && request.version() == HttpVersion.HTTP_2) {
|
||||
host = RequestHost.of(request);
|
||||
}
|
||||
if (scope == null || !SIGNING_SERVICE.equals(scope.service()) || !signature.amzDate().startsWith(scope.date())
|
||||
|| signature.freshness(clock.instant()) != SigV4SignedRequest.Freshness.FRESH
|
||||
|| !SigV4RequestValidator.containsHeader(signature.signedHeaders(), "host")
|
||||
|| host == null || host.isBlank()) {
|
||||
throw denied();
|
||||
}
|
||||
String sessionToken = presigned ? single(params.get(TOKEN)) : single(headers.getAll(TOKEN));
|
||||
if (!presigned && (!SigV4RequestValidator.containsHeader(signature.signedHeaders(), "x-amz-date")
|
||||
|| (sessionToken != null && !SigV4RequestValidator.containsHeader(signature.signedHeaders(),
|
||||
"x-amz-security-token")))) {
|
||||
throw denied();
|
||||
}
|
||||
return new Claim(signature, scope, sessionToken, host);
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> queryParameters(String rawQuery) {
|
||||
if (rawQuery == null || rawQuery.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return QueryStringDecoder.builder().hasPath(false).semicolonIsNormalChar(true).htmlQueryDecoding(false)
|
||||
.maxParams(rawQuery.length()).build(rawQuery).parameters();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
throw denied();
|
||||
}
|
||||
}
|
||||
|
||||
private static void verify(HttpServerRequest request, byte[] body, Claim claim, String secret) {
|
||||
SigV4SignedRequest signed = claim.signature();
|
||||
try {
|
||||
String headers = SigV4Canonicalization.canonicalHeaders(signed.signedHeaders(),
|
||||
name -> "host".equals(name) ? SigV4RequestValidator.normalizeHeaderValue(claim.host())
|
||||
: request.headers().getAll(name).stream().map(SigV4RequestValidator::normalizeHeaderValue)
|
||||
.collect(Collectors.joining(",")));
|
||||
String query = SigV4Canonicalization.canonicalQueryString(request.query(), signed.presigned());
|
||||
if (matches(request, claim, secret, headers, query, Digests.sha256Hex(body))
|
||||
|| (signed.presigned() && matches(request, claim, secret, headers, query, "UNSIGNED-PAYLOAD"))) {
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "Message gateway signature could not be verified");
|
||||
}
|
||||
throw denied();
|
||||
}
|
||||
|
||||
private static boolean matches(HttpServerRequest request, Claim claim, String secret, String headers,
|
||||
String query, String payloadHash) throws Exception {
|
||||
SigV4SignedRequest signed = claim.signature();
|
||||
return SigV4Canonicalization.signatureMatches(request.method().name(), request.path(), query, headers,
|
||||
signed.signedHeaders(), payloadHash, signed.amzDate(), claim.scope(), secret, signed.signature());
|
||||
}
|
||||
|
||||
private static String single(List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (values.size() != 1) {
|
||||
throw denied();
|
||||
}
|
||||
return values.getFirst();
|
||||
}
|
||||
|
||||
private static AwsException denied() {
|
||||
return new AwsException("AccessDeniedException", "The message gateway request could not be authenticated.", 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Base64Url;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import io.vertx.core.Context;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** The in-memory control connections and paired Session Manager data channels. */
|
||||
@ApplicationScoped
|
||||
public class SsmMessageGateway implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SsmMessageGateway.class);
|
||||
private static final Duration GRANT_TTL = Duration.ofMinutes(5);
|
||||
private static final Duration HANDSHAKE_TTL = Duration.ofSeconds(30);
|
||||
private static final int MAX_QUEUED_BYTES = 4 * 1024 * 1024;
|
||||
private static final int MAX_QUEUED_MESSAGES = 4096;
|
||||
private static final long SERVICE_MESSAGE_FLAGS = 3;
|
||||
private static final String SESSION_STATE_MESSAGE = "agent_session_state";
|
||||
private static final String TASK_COMPLETE_MESSAGE = "agent_task_complete";
|
||||
|
||||
public record Node(String accountId, String region, String instanceId) { }
|
||||
|
||||
public record SessionRequest(String sessionId, String sessionArn, String ownerArn, Node node,
|
||||
String documentName, JsonNode documentContent, Map<String, Object> parameters) { }
|
||||
|
||||
@RegisterForReflection
|
||||
public enum SessionState { CONNECTED, DISCONNECTED, TERMINATED, FAILED }
|
||||
|
||||
record SessionTarget(String sessionArn, Node node) { }
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final Vertx vertx;
|
||||
private final Clock clock;
|
||||
private final Context eventContext;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
// Opening and closing sockets, grants and queues all use the same monitor. No socket I/O waits on it.
|
||||
private final Set<Connection> connections = new HashSet<>();
|
||||
private final Map<Node, Connection> controls = new HashMap<>();
|
||||
private final Map<Node, Grant> controlGrants = new HashMap<>();
|
||||
private final Map<String, Session> sessions = new HashMap<>();
|
||||
private long generation;
|
||||
private long sweepTimer;
|
||||
private boolean resetting;
|
||||
private boolean stopping;
|
||||
|
||||
@Inject
|
||||
public SsmMessageGateway(ObjectMapper mapper, Vertx vertx, Clock clock) {
|
||||
this.mapper = mapper;
|
||||
this.vertx = vertx;
|
||||
this.clock = clock;
|
||||
this.eventContext = vertx.getOrCreateContext();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void scheduleExpiry() {
|
||||
sweepTimer = vertx.setPeriodic(1000, ignored -> expire());
|
||||
}
|
||||
|
||||
public synchronized boolean isConnected(Node node) {
|
||||
Connection connection = controls.get(node);
|
||||
return !resetting && connection != null && !connection.socket.isClosed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the session grant and dispatches the AWS Session document to the connected agent.
|
||||
* State callbacks are ordered, asynchronous and scoped to the node's account and region.
|
||||
*/
|
||||
public synchronized String startSession(SessionRequest request, Consumer<SessionState> onStateChange) {
|
||||
if (!isConnected(request.node())) {
|
||||
throw targetNotConnected();
|
||||
}
|
||||
Map<String, Object> task = Map.of(
|
||||
"SessionId", request.sessionId(),
|
||||
"SessionOwner", request.ownerArn(),
|
||||
"DocumentName", request.documentName(),
|
||||
"DocumentContent", request.documentContent(),
|
||||
"Parameters", request.parameters());
|
||||
Buffer dispatch = frame("interactive_shell", Map.of("SchemaVersion", 1, "TaskId", request.sessionId(),
|
||||
"Topic", "StartSession", "Content", new String(json(task), StandardCharsets.UTF_8)));
|
||||
Session session = new Session(request.sessionId(), new SessionTarget(request.sessionArn(), request.node()),
|
||||
onStateChange);
|
||||
if (sessions.putIfAbsent(request.sessionId(), session) != null) {
|
||||
throw new IllegalArgumentException("Session id is already registered");
|
||||
}
|
||||
Future<Void> sent = sendControl(request.node(), dispatch);
|
||||
if (sent.failed()) {
|
||||
sessions.remove(request.sessionId(), session);
|
||||
throw targetNotConnected();
|
||||
}
|
||||
sent.onFailure(ignored -> dispatchFailed(session));
|
||||
return session.client.grant.value();
|
||||
}
|
||||
|
||||
public synchronized Optional<String> resumeSession(Node node, String sessionId) {
|
||||
Session session = activeSession(sessionId);
|
||||
if (session == null || session.terminating || !session.target.node().equals(node)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
session.client.grant = grant(null);
|
||||
return Optional.of(session.client.grant.value());
|
||||
}
|
||||
|
||||
public synchronized void terminateSession(Node node, String sessionId) {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null && session.target.node().equals(node)) {
|
||||
stopAgent(session);
|
||||
finish(session, SessionState.TERMINATED);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized Optional<SessionTarget> sessionTarget(String sessionId) {
|
||||
return Optional.ofNullable(activeSession(sessionId)).map(session -> session.target);
|
||||
}
|
||||
|
||||
synchronized long generation() {
|
||||
return generation;
|
||||
}
|
||||
|
||||
synchronized String createControlGrant(Node node) {
|
||||
if (stopping || resetting) {
|
||||
throw targetNotConnected();
|
||||
}
|
||||
Grant grant = grant(null);
|
||||
controlGrants.put(node, grant);
|
||||
return grant.value();
|
||||
}
|
||||
|
||||
synchronized Optional<String> createAgentGrant(Node node, String sessionId, String clientId) {
|
||||
Session session = activeSession(sessionId);
|
||||
if (session == null || session.terminating || !session.target.node().equals(node)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
session.agent.grant = grant(clientId);
|
||||
return Optional.of(session.agent.grant.value());
|
||||
}
|
||||
|
||||
synchronized void openControl(Node node, ServerWebSocket socket, long expectedGeneration) {
|
||||
Connection connection = new Connection(socket);
|
||||
register(connection, expectedGeneration, (token, opening) -> {
|
||||
Grant grant = controlGrants.get(node);
|
||||
if (!valid(grant, token)) {
|
||||
return false;
|
||||
}
|
||||
controlGrants.remove(node);
|
||||
Connection previous = controls.put(node, connection);
|
||||
if (previous != null) {
|
||||
previous.socket.close();
|
||||
}
|
||||
return true;
|
||||
}, frame -> readControl(node, connection, frame), () -> controls.remove(node, connection));
|
||||
}
|
||||
|
||||
synchronized void openData(String sessionId, SessionTarget target, boolean agentAllowed, boolean clientAllowed,
|
||||
ServerWebSocket socket, long expectedGeneration) {
|
||||
Session session = activeSession(sessionId);
|
||||
if (session == null || !session.target.equals(target)) {
|
||||
socket.close((short) 1008, "Session unavailable");
|
||||
return;
|
||||
}
|
||||
Connection connection = new Connection(socket);
|
||||
register(connection, expectedGeneration, (token, opening) ->
|
||||
attachData(session, connection, token, opening, agentAllowed, clientAllowed),
|
||||
frame -> receiveData(session, connection.dataPeer, session.otherPeer(connection.dataPeer),
|
||||
connection, frame),
|
||||
() -> {
|
||||
Peer side = connection.dataPeer;
|
||||
if (side != null) {
|
||||
detach(session, side, session.otherPeer(side), connection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void register(Connection connection, long expectedGeneration, BiPredicate<String, JsonNode> claim,
|
||||
Consumer<Buffer> binary, Runnable detach) {
|
||||
ServerWebSocket socket = connection.socket;
|
||||
if (stopping || resetting || generation != expectedGeneration || socket.isClosed()) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
connections.add(connection);
|
||||
connection.timer = vertx.setTimer(HANDSHAKE_TTL.toMillis(), ignored -> handshakeExpired(connection));
|
||||
socket.closeHandler(ignored -> disconnected(connection, detach));
|
||||
socket.exceptionHandler(ignored -> {
|
||||
disconnected(connection, detach);
|
||||
socket.close();
|
||||
});
|
||||
socket.textMessageHandler(text -> authenticate(connection, claim, text));
|
||||
socket.binaryMessageHandler(frame -> receive(connection, binary, frame));
|
||||
}
|
||||
|
||||
private synchronized void authenticate(Connection connection, BiPredicate<String, JsonNode> claim, String text) {
|
||||
if (resetting || !connections.contains(connection) || connection.authenticated || connection.rejected) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonNode opening = text.length() <= 16 * 1024 ? mapper.readTree(text) : null;
|
||||
if (opening == null || !"1.0".equals(opening.path("MessageSchemaVersion").textValue())) {
|
||||
reject(connection, (short) 1002, "Malformed opening message");
|
||||
return;
|
||||
}
|
||||
String token = opening.path("TokenValue").textValue();
|
||||
if (token != null && claim.test(token, opening)) {
|
||||
connection.authenticated = true;
|
||||
vertx.cancelTimer(connection.timer);
|
||||
} else {
|
||||
reject(connection, (short) 1008, "Invalid channel token");
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
reject(connection, (short) 1002, "Malformed opening message");
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void receive(Connection connection, Consumer<Buffer> binary, Buffer frame) {
|
||||
if (resetting || !connections.contains(connection) || connection.rejected) {
|
||||
return;
|
||||
}
|
||||
if (!connection.authenticated) {
|
||||
reject(connection, (short) 1008, "Channel is not authenticated");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
binary.accept(frame);
|
||||
} catch (IllegalArgumentException e) {
|
||||
reject(connection, (short) 1002, "Malformed agent message");
|
||||
}
|
||||
}
|
||||
|
||||
private static void reject(Connection connection, short code, String reason) {
|
||||
connection.rejected = true;
|
||||
connection.socket.close(code, reason);
|
||||
}
|
||||
|
||||
private synchronized void disconnected(Connection connection, Runnable detach) {
|
||||
if (connections.remove(connection)) {
|
||||
vertx.cancelTimer(connection.timer);
|
||||
detach.run();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handshakeExpired(Connection connection) {
|
||||
if (!connection.authenticated && connections.remove(connection)) {
|
||||
reject(connection, (short) 1008, "Opening message timed out");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean attachData(Session session, Connection connection, String token, JsonNode opening,
|
||||
boolean agentAllowed, boolean clientAllowed) {
|
||||
if (session.finished || session.terminating) {
|
||||
return false;
|
||||
}
|
||||
Peer side;
|
||||
if (valid(session.agent.grant, token)) {
|
||||
if (!agentAllowed || !matchesAgentOpening(session, session.agent.grant, opening)) {
|
||||
return false;
|
||||
}
|
||||
side = session.agent;
|
||||
} else if (clientAllowed && valid(session.client.grant, token)) {
|
||||
side = session.client;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (side.connection != null && !side.connection.socket.isClosed() && side.attachedGrant == side.grant) {
|
||||
return false;
|
||||
}
|
||||
Connection previous = side.connection;
|
||||
connection.dataPeer = side;
|
||||
side.connection = connection;
|
||||
side.attachedGrant = side.grant;
|
||||
if (previous != null) {
|
||||
previous.socket.close();
|
||||
}
|
||||
flush(session, side, session.otherPeer(side));
|
||||
updateConnectivity(session);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean matchesAgentOpening(Session session, Grant grant, JsonNode opening) {
|
||||
// The stock session worker can use an empty ClientId for both creation and opening.
|
||||
JsonNode clientId = opening.path("ClientId");
|
||||
return (clientId.isMissingNode() || clientId.isNull() || clientId.isTextual())
|
||||
&& Objects.equals(grant.binding(), clientId.textValue())
|
||||
&& session.target.node().instanceId().equals(opening.path("ClientInstanceId").textValue());
|
||||
}
|
||||
|
||||
private void detach(Session session, Peer side, Peer other, Connection connection) {
|
||||
if (side.connection != connection) {
|
||||
return;
|
||||
}
|
||||
side.connection = null;
|
||||
if (session.finished) {
|
||||
side.queue.clear();
|
||||
side.queuedBytes = 0;
|
||||
return;
|
||||
}
|
||||
if (side == session.agent && session.completion != null) {
|
||||
finish(session, session.completion);
|
||||
return;
|
||||
}
|
||||
updateConnectivity(session);
|
||||
updateBackpressure(other, side);
|
||||
}
|
||||
|
||||
private void receiveData(Session session, Peer side, Peer other, Connection connection, Buffer buffer) {
|
||||
if (session.finished || side.connection != connection) {
|
||||
return;
|
||||
}
|
||||
String messageType = AgentMessage.gatewayMessageType(buffer);
|
||||
if (SESSION_STATE_MESSAGE.equals(messageType)) {
|
||||
if (side != session.agent) {
|
||||
throw new IllegalArgumentException("Session state must come from the agent");
|
||||
}
|
||||
readSessionState(session, readJson(AgentMessage.decode(buffer.getBytes())));
|
||||
return;
|
||||
}
|
||||
if (other.queue.size() >= MAX_QUEUED_MESSAGES || buffer.length() > MAX_QUEUED_BYTES - other.queuedBytes) {
|
||||
// An absent or stalled peer cannot leave unbounded stream data in the emulator.
|
||||
connection.socket.close((short) 1013, "Data channel buffer full");
|
||||
return;
|
||||
}
|
||||
queue(other, buffer);
|
||||
updateBackpressure(side, other);
|
||||
flush(session, other, side);
|
||||
}
|
||||
|
||||
private static void queue(Peer peer, Buffer buffer) {
|
||||
peer.queue.addLast(buffer);
|
||||
peer.queuedBytes += buffer.length();
|
||||
}
|
||||
|
||||
private void flush(Session session, Peer destination, Peer source) {
|
||||
Connection connection = destination.connection;
|
||||
if (connection == null || connection.socket.isClosed() || destination.writing) {
|
||||
return;
|
||||
}
|
||||
Buffer first = destination.queue.peekFirst();
|
||||
if (first == null) {
|
||||
if (session.finished) {
|
||||
connection.socket.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
destination.writing = true;
|
||||
connection.socket.writeBinaryMessage(first).onComplete(result -> connection.context.runOnContext(ignored ->
|
||||
written(session, destination, source, connection, first, result.succeeded())));
|
||||
}
|
||||
|
||||
private synchronized void written(Session session, Peer destination, Peer source, Connection connection,
|
||||
Buffer buffer, boolean successful) {
|
||||
destination.writing = false;
|
||||
if (successful && destination.queue.peekFirst() == buffer && destination.connection == connection) {
|
||||
destination.queuedBytes -= destination.queue.removeFirst().length();
|
||||
} else if (!successful && destination.connection == connection) {
|
||||
detach(session, destination, source, connection);
|
||||
connection.socket.close();
|
||||
}
|
||||
updateBackpressure(source, destination);
|
||||
flush(session, destination, source);
|
||||
}
|
||||
|
||||
private static void updateBackpressure(Peer source, Peer destination) {
|
||||
Connection connection = source.connection;
|
||||
if (connection == null || connection.socket.isClosed()) {
|
||||
return;
|
||||
}
|
||||
boolean congested = destination.connection != null
|
||||
&& (destination.queuedBytes >= MAX_QUEUED_BYTES / 2
|
||||
|| destination.queue.size() >= MAX_QUEUED_MESSAGES / 2);
|
||||
if (congested && !connection.paused) {
|
||||
connection.paused = true;
|
||||
connection.socket.pause();
|
||||
} else if (!congested && connection.paused) {
|
||||
connection.paused = false;
|
||||
connection.socket.resume();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateConnectivity(Session session) {
|
||||
if (session.terminating || session.finished) {
|
||||
return;
|
||||
}
|
||||
if (session.agentReady && session.agent.connection != null && session.client.connection != null) {
|
||||
session.deadline = null;
|
||||
publishState(session, SessionState.CONNECTED);
|
||||
} else if (session.state == SessionState.CONNECTED) {
|
||||
session.deadline = clock.instant().plus(GRANT_TTL);
|
||||
publishState(session, SessionState.DISCONNECTED);
|
||||
}
|
||||
}
|
||||
|
||||
private void readSessionState(Session session, JsonNode payload) {
|
||||
if (!session.id.equals(payload.path("SessionId").textValue())) {
|
||||
throw new IllegalArgumentException("Session state is for a different session");
|
||||
}
|
||||
switch (payload.path("SessionState").asText()) {
|
||||
case "Connected" -> {
|
||||
session.agentReady = true;
|
||||
updateConnectivity(session);
|
||||
}
|
||||
case "Terminating" -> {
|
||||
session.terminating = true;
|
||||
session.deadline = clock.instant().plus(HANDSHAKE_TTL);
|
||||
}
|
||||
default -> LOG.debugv("Ignored unknown agent state for session {0}", session.id);
|
||||
}
|
||||
}
|
||||
|
||||
private void readControl(Node node, Connection connection, Buffer frame) {
|
||||
if (controls.get(node) != connection) {
|
||||
return;
|
||||
}
|
||||
String kind = AgentMessage.gatewayMessageType(frame);
|
||||
AgentMessage message = AgentMessage.decode(frame.getBytes());
|
||||
switch (kind) {
|
||||
case TASK_COMPLETE_MESSAGE -> completeTask(node, message);
|
||||
default -> LOG.debugv("Ignored message of type {0} on the agent control channel", kind);
|
||||
}
|
||||
}
|
||||
|
||||
private void completeTask(Node node, AgentMessage message) {
|
||||
JsonNode payload = readJson(message);
|
||||
String id = payload.path("TaskId").asText("");
|
||||
String topic = payload.path("Topic").asText("");
|
||||
if (id.isBlank() || topic.isBlank()) {
|
||||
throw new IllegalArgumentException("Invalid task completion");
|
||||
}
|
||||
Session session = sessions.get(id);
|
||||
if (session != null && !session.target.node().equals(node)) {
|
||||
throw new IllegalArgumentException("Task completion is for a different instance");
|
||||
}
|
||||
sendControl(node, frame("agent_task_acknowledge", Map.of("SchemaVersion", 1, "TaskId", id,
|
||||
"Topic", topic, "MessageId", message.messageId().toString())));
|
||||
if (session != null && session.completion == null) {
|
||||
session.completion = "Success".equals(payload.path("FinalTaskStatus").asText())
|
||||
? SessionState.TERMINATED : SessionState.FAILED;
|
||||
if (session.agent.connection == null) {
|
||||
finish(session, session.completion);
|
||||
} else {
|
||||
// Completion arrives over a separate socket. Let the agent's final stream data drain first.
|
||||
session.terminating = true;
|
||||
session.deadline = clock.instant().plus(HANDSHAKE_TTL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void stopAgent(Session session) {
|
||||
Node node = session.target.node();
|
||||
Buffer close = frame(AgentMessage.CHANNEL_CLOSED, Map.of(
|
||||
"MessageType", AgentMessage.CHANNEL_CLOSED,
|
||||
"MessageId", UUID.randomUUID().toString(),
|
||||
"DestinationId", node.instanceId(), "SessionId", session.id,
|
||||
"SchemaVersion", 1, "CreatedDate", clock.instant().toString()));
|
||||
Future<Void> sent = sendControl(node, close);
|
||||
if (sent.failed() && session.agent.connection != null) {
|
||||
session.agent.connection.socket.writeBinaryMessage(close);
|
||||
}
|
||||
}
|
||||
|
||||
private void finish(Session session, SessionState state) {
|
||||
if (!sessions.remove(session.id, session)) {
|
||||
return;
|
||||
}
|
||||
session.finished = true;
|
||||
publishState(session, state);
|
||||
if (session.agent.connection != null) {
|
||||
session.agent.connection.socket.close();
|
||||
}
|
||||
if (session.client.connection != null) {
|
||||
queue(session.client, frame(AgentMessage.CHANNEL_CLOSED, Map.of("SessionId", session.id, "Output", "")));
|
||||
flush(session, session.client, session.agent);
|
||||
Connection connection = session.client.connection;
|
||||
connection.timer = vertx.setTimer(HANDSHAKE_TTL.toMillis(), ignored -> connection.socket.close());
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void dispatchFailed(Session session) {
|
||||
finish(session, SessionState.FAILED);
|
||||
}
|
||||
|
||||
private void publishState(Session session, SessionState state) {
|
||||
if (session.state != state) {
|
||||
session.state = state;
|
||||
publish(session.target.node(), () -> session.onStateChange.accept(state));
|
||||
}
|
||||
}
|
||||
|
||||
private void publish(Node node, Runnable event) {
|
||||
long expectedGeneration = generation;
|
||||
eventContext.runOnContext(ignored -> {
|
||||
if (callbacksEnabled(expectedGeneration)) {
|
||||
try {
|
||||
RequestScopes.runAs(node.accountId(), node.region(), event);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Message gateway callback failed for instance {0}", node.instanceId());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private synchronized boolean callbacksEnabled(long expectedGeneration) {
|
||||
return !resetting && !stopping && generation == expectedGeneration;
|
||||
}
|
||||
|
||||
private Future<Void> sendControl(Node node, Buffer frame) {
|
||||
Connection connection = controls.get(node);
|
||||
if (resetting || connection == null || connection.socket.isClosed() || connection.socket.writeQueueFull()) {
|
||||
return Future.failedFuture(targetNotConnected());
|
||||
}
|
||||
return connection.socket.writeBinaryMessage(frame);
|
||||
}
|
||||
|
||||
private JsonNode readJson(AgentMessage message) {
|
||||
try {
|
||||
JsonNode parsed = mapper.readTree(message.payloadAsString());
|
||||
if (parsed != null && parsed.isObject()) {
|
||||
return parsed;
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid agent message payload");
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException("Invalid agent message payload", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Buffer frame(String kind, Object payload) {
|
||||
AgentMessage message = new AgentMessage(kind, 1, clock.millis(), 0, SERVICE_MESSAGE_FLAGS,
|
||||
UUID.randomUUID(), 0, json(payload));
|
||||
return Buffer.buffer(message.encode());
|
||||
}
|
||||
|
||||
private byte[] json(Object payload) {
|
||||
try {
|
||||
return mapper.writeValueAsBytes(payload);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Message gateway payload could not be serialized", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Session activeSession(String sessionId) {
|
||||
Session session = sessions.get(sessionId);
|
||||
return resetting || session == null || expired(session.deadline, clock.instant()) ? null : session;
|
||||
}
|
||||
|
||||
private synchronized void expire() {
|
||||
if (resetting || stopping) {
|
||||
return;
|
||||
}
|
||||
Instant now = clock.instant();
|
||||
controlGrants.values().removeIf(grant -> expired(grant.expires(), now));
|
||||
for (Session session : List.copyOf(sessions.values())) {
|
||||
if (expired(session.deadline, now)) {
|
||||
stopAgent(session);
|
||||
SessionState terminal = session.terminating ? SessionState.TERMINATED : SessionState.FAILED;
|
||||
finish(session, session.completion == null ? terminal : session.completion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean expired(Instant deadline, Instant now) {
|
||||
return deadline != null && !now.isBefore(deadline);
|
||||
}
|
||||
|
||||
private Grant grant(String binding) {
|
||||
byte[] token = new byte[32];
|
||||
random.nextBytes(token);
|
||||
return new Grant(Base64Url.encode(token), clock.instant().plus(GRANT_TTL), binding);
|
||||
}
|
||||
|
||||
private boolean valid(Grant grant, String token) {
|
||||
return grant != null && !expired(grant.expires(), clock.instant()) && MessageDigest.isEqual(
|
||||
grant.value().getBytes(StandardCharsets.UTF_8), token.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static AwsException targetNotConnected() {
|
||||
return new AwsException("TargetNotConnected", "The target instance is not connected.", 400);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void beforeReset() {
|
||||
resetting = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void afterReset() {
|
||||
resetting = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void clear() {
|
||||
generation++;
|
||||
List<Connection> disconnect = List.copyOf(connections);
|
||||
connections.clear();
|
||||
controls.clear();
|
||||
controlGrants.clear();
|
||||
sessions.clear();
|
||||
for (Connection connection : disconnect) {
|
||||
vertx.cancelTimer(connection.timer);
|
||||
connection.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
synchronized void shutdown() {
|
||||
stopping = true;
|
||||
vertx.cancelTimer(sweepTimer);
|
||||
clear();
|
||||
}
|
||||
|
||||
private record Grant(String value, Instant expires, String binding) { }
|
||||
|
||||
private static final class Connection {
|
||||
private final ServerWebSocket socket;
|
||||
private final Context context = Vertx.currentContext();
|
||||
private Peer dataPeer;
|
||||
private long timer;
|
||||
private boolean authenticated;
|
||||
private boolean rejected;
|
||||
private boolean paused;
|
||||
|
||||
private Connection(ServerWebSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Peer {
|
||||
private final Deque<Buffer> queue = new ArrayDeque<>();
|
||||
private Connection connection;
|
||||
private Grant grant;
|
||||
private Grant attachedGrant;
|
||||
private int queuedBytes;
|
||||
private boolean writing;
|
||||
}
|
||||
|
||||
private final class Session {
|
||||
private final String id;
|
||||
private final SessionTarget target;
|
||||
private final Consumer<SessionState> onStateChange;
|
||||
private final Peer agent = new Peer();
|
||||
private final Peer client = new Peer();
|
||||
private Instant deadline = clock.instant().plus(GRANT_TTL);
|
||||
private SessionState state;
|
||||
private SessionState completion;
|
||||
private boolean agentReady;
|
||||
private boolean terminating;
|
||||
private boolean finished;
|
||||
|
||||
private Session(String id, SessionTarget target, Consumer<SessionState> onStateChange) {
|
||||
this.id = id;
|
||||
this.target = target;
|
||||
this.onStateChange = onStateChange;
|
||||
client.grant = grant(null);
|
||||
}
|
||||
|
||||
private Peer otherPeer(Peer peer) {
|
||||
return peer == agent ? client : agent;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.XmlBuilder;
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import io.vertx.ext.web.handler.BodyHandler;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SsmMessageGatewayRoutes implements DataChannelHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SsmMessageGatewayRoutes.class);
|
||||
private static final String CONTROL_PATH = "/v1/control-channel/:instanceId";
|
||||
private static final String DATA_PATH = DataChannelRouter.CHANNEL_PATH_PREFIX + ":sessionId";
|
||||
private static final byte[] EMPTY_BODY = new byte[0];
|
||||
|
||||
private final SsmMessageGateway gateway;
|
||||
private final ChannelAuthentication authentication;
|
||||
private final ObjectMapper mapper;
|
||||
private final boolean enabled;
|
||||
|
||||
@Inject
|
||||
public SsmMessageGatewayRoutes(SsmMessageGateway gateway, ChannelAuthentication authentication,
|
||||
ObjectMapper mapper, EmulatorConfig config) {
|
||||
this(gateway, authentication, mapper, config.services().ssm().enabled());
|
||||
}
|
||||
|
||||
SsmMessageGatewayRoutes(SsmMessageGateway gateway, ChannelAuthentication authentication,
|
||||
ObjectMapper mapper, boolean enabled) {
|
||||
this.gateway = gateway;
|
||||
this.authentication = authentication;
|
||||
this.mapper = mapper;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
void init(@Observes Router router) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
BodyHandler body = BodyHandler.create().setBodyLimit(16 * 1024).setHandleFileUploads(false);
|
||||
router.post(CONTROL_PATH).handler(body).handler(this::createControl);
|
||||
router.get(CONTROL_PATH).handler(this::openControl);
|
||||
router.post(DATA_PATH).handler(body).handler(this::createData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSession(String sessionId) {
|
||||
return enabled && gateway.sessionTarget(sessionId).isPresent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void open(String sessionId, RoutingContext context) {
|
||||
long generation = gateway.generation();
|
||||
try {
|
||||
SsmMessageGateway.SessionTarget target = gateway.sessionTarget(sessionId)
|
||||
.orElseThrow(SsmMessageGatewayRoutes::closedSession);
|
||||
if (!"publish_subscribe".equals(context.request().getParam("role"))) {
|
||||
throw invalidRequest();
|
||||
}
|
||||
boolean agentAllowed = canOpenAgent(context, target);
|
||||
boolean clientAllowed = canOpenClient(context, target, agentAllowed);
|
||||
upgrade(context, socket ->
|
||||
gateway.openData(sessionId, target, agentAllowed, clientAllowed, socket, generation));
|
||||
} catch (AwsException e) {
|
||||
error(context, e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canOpenAgent(RoutingContext context, SsmMessageGateway.SessionTarget target) {
|
||||
try {
|
||||
return authentication.authenticateAgentUpgradeIfClaimed(context.request(), "ssmmessages:OpenDataChannel",
|
||||
target.sessionArn())
|
||||
.map(SsmMessageGatewayRoutes::node).filter(target.node()::equals).isPresent();
|
||||
} catch (AwsException expected) {
|
||||
if (expected.getHttpStatus() != 403) {
|
||||
throw expected;
|
||||
}
|
||||
// A denied agent claim may still be an authorised client; its grant selects the side.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canOpenClient(RoutingContext context, SsmMessageGateway.SessionTarget target, boolean agentAllowed) {
|
||||
try {
|
||||
authentication.authorizeClient(context.request(), target.node().accountId(),
|
||||
target.node().region(), target.sessionArn());
|
||||
return true;
|
||||
} catch (AwsException expected) {
|
||||
if (!agentAllowed || expected.getHttpStatus() != 403) {
|
||||
throw expected;
|
||||
}
|
||||
// An authorised agent need not also hold client permission on the session.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void createControl(RoutingContext context) {
|
||||
try {
|
||||
byte[] body = context.body().buffer().getBytes();
|
||||
ChannelAuthentication.AgentIdentity identity = authentication.authenticateAgent(
|
||||
context.request(), body, "ssmmessages:CreateControlChannel");
|
||||
requireInstance(context, identity);
|
||||
readRequest(body);
|
||||
created(context, gateway.createControlGrant(node(identity)));
|
||||
} catch (AwsException e) {
|
||||
error(context, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void openControl(RoutingContext context) {
|
||||
if (!"websocket".equalsIgnoreCase(context.request().getHeader("Upgrade"))) {
|
||||
context.next();
|
||||
return;
|
||||
}
|
||||
long generation = gateway.generation();
|
||||
try {
|
||||
ChannelAuthentication.AgentIdentity identity = authentication.authenticateAgent(
|
||||
context.request(), EMPTY_BODY, "ssmmessages:OpenControlChannel");
|
||||
requireInstance(context, identity);
|
||||
if (!"subscribe".equals(context.request().getParam("role"))) {
|
||||
throw invalidRequest();
|
||||
}
|
||||
upgrade(context, socket -> gateway.openControl(node(identity), socket, generation));
|
||||
} catch (AwsException e) {
|
||||
error(context, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createData(RoutingContext context) {
|
||||
try {
|
||||
byte[] body = context.body().buffer().getBytes();
|
||||
ChannelAuthentication.AgentIdentity identity = authentication.authenticateAgent(
|
||||
context.request(), body, "ssmmessages:CreateDataChannel");
|
||||
JsonNode clientId = readRequest(body).path("ClientId");
|
||||
if (!clientId.isMissingNode() && !clientId.isNull() && !clientId.isTextual()) {
|
||||
throw invalidRequest();
|
||||
}
|
||||
String sessionId = context.pathParam("sessionId");
|
||||
SsmMessageGateway.SessionTarget target = gateway.sessionTarget(sessionId)
|
||||
.orElseThrow(SsmMessageGatewayRoutes::closedSession);
|
||||
if (!target.node().equals(node(identity))) {
|
||||
throw accessDenied();
|
||||
}
|
||||
created(context, gateway.createAgentGrant(node(identity), sessionId, clientId.textValue())
|
||||
.orElseThrow(SsmMessageGatewayRoutes::closedSession));
|
||||
} catch (AwsException e) {
|
||||
error(context, e);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode readRequest(byte[] body) {
|
||||
try {
|
||||
JsonNode request = mapper.readTree(body);
|
||||
if (request == null || !"1.0".equals(request.path("MessageSchemaVersion").textValue())
|
||||
|| request.path("RequestId").asText("").isBlank()) {
|
||||
throw invalidRequest();
|
||||
}
|
||||
return request;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw invalidRequest();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("In-memory request body could not be read", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void upgrade(RoutingContext context, Consumer<ServerWebSocket> accepted) {
|
||||
context.request().toWebSocket().onSuccess(accepted::accept)
|
||||
.onFailure(cause -> LOG.debugv(cause, "Message gateway WebSocket upgrade failed"));
|
||||
}
|
||||
|
||||
private static SsmMessageGateway.Node node(ChannelAuthentication.AgentIdentity identity) {
|
||||
return new SsmMessageGateway.Node(identity.accountId(), identity.region(), identity.instanceId());
|
||||
}
|
||||
|
||||
private static void requireInstance(RoutingContext context, ChannelAuthentication.AgentIdentity identity) {
|
||||
if (!identity.instanceId().equals(context.pathParam("instanceId"))) {
|
||||
throw accessDenied();
|
||||
}
|
||||
}
|
||||
|
||||
private static void created(RoutingContext context, String token) {
|
||||
String body = new XmlBuilder().start("ChannelOutput")
|
||||
.elem("MessageSchemaVersion", "1.0").elem("TokenValue", token)
|
||||
.end("ChannelOutput").build();
|
||||
context.response().setStatusCode(201).putHeader("Content-Type", "application/xml").end(body);
|
||||
}
|
||||
|
||||
private static void error(RoutingContext context, AwsException e) {
|
||||
context.response().setStatusCode(e.getHttpStatus())
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.putHeader("x-amzn-errortype", e.getErrorCode())
|
||||
.end(new JsonObject().put("message", e.getMessage()).encode());
|
||||
}
|
||||
|
||||
private static AwsException invalidRequest() {
|
||||
return new AwsException("ValidationException", "Invalid message gateway request.", 400);
|
||||
}
|
||||
|
||||
private static AwsException accessDenied() {
|
||||
return new AwsException("AccessDeniedException", "The instance does not own this channel.", 403);
|
||||
}
|
||||
|
||||
private static AwsException closedSession() {
|
||||
return new AwsException("ResourceNotFoundException", "Session is already terminated", 404);
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,7 @@ quarkus:
|
||||
- bedrock/*.yaml
|
||||
- eks/*.json
|
||||
- aws/*.json
|
||||
- ssm/*.json
|
||||
- proto/**/*.proto
|
||||
- iam/service-linked-roles.tsv
|
||||
- cloudformation/*.json
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.44.9 (local/aws/botocore)", "retrieved": "2026-11-25", "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.44.9 (local/aws/botocore)", "retrieved": "2026-11-26", "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"], "account": ["account"], "acm": ["acm"], "apigateway": ["apigateway", "apigatewayv2"], "application-autoscaling": ["application-autoscaling"], "aps": ["amp"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "bedrock": ["bedrock", "bedrock-agent", "bedrock-agent-runtime", "bedrock-data-automation", "bedrock-data-automation-runtime", "bedrock-runtime"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "dynamodb": ["dynamodb", "dynamodbstreams"], "ec2": ["ec2"], "ec2-instance-connect": ["ec2-instance-connect"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticache": ["elasticache"], "elasticfilesystem": ["efs"], "elasticloadbalancing": ["elb", "elb-proxy", "elbv2"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "iam": ["iam", "iam-toolbox"], "identitystore": ["identitystore"], "inspector2": ["inspector2"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "kms": ["kms"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "memorydb": ["memorydb"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "pipes": ["pipes"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53": ["route53"], "route53resolver": ["route53resolver"], "s3": ["s3", "s3control"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "sagemaker": ["sagemaker", "sagemaker-a2i-runtime", "sagemaker-edge", "sagemaker-featurestore-runtime", "sagemaker-gateway-runtime", "sagemaker-inference-router-runtime", "sagemaker-metrics", "sagemaker-runtime", "sagemakerjobruntime", "sagemakertrainingsessionruntime"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"notCovered": {"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", "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", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "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", "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", "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 have its model yet", "dlm": "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", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "execute-api": "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", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "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", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "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", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "organizations": "not read yet: a later batch, with the tesLine truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifygen3", "amplifyuibuilder", "aoss", "apiportal", "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", "bcm-data-hub", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "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", "end-user-messaging", "entityresolution", "evs", "finops-agent", "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", "osm", "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", "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"],
|
||||
"notCovered": {"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", "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", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "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", "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", "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 have its model yet", "dlm": "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", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "execute-api": "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", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "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", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "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", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "organizations": "not read yet: a later batch, with the tesLine truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifygen3", "amplifyuibuilder", "aoss", "apiportal", "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", "bcm-data-hub", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "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", "end-user-messaging", "entityresolution", "evs", "finops-agent", "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", "osm", "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", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "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"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "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}"}, "apigateway": {"AccessLogSettings": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/accesslogsettings", "Account": "arn:${Partition}:apigateway:${Region}::/account", "Api": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}", "ApiKey": "arn:${Partition}:apigateway:${Region}::/apikeys/${ApiKeyId}", "ApiKeys": "arn:${Partition}:apigateway:${Region}::/apikeys", "ApiMapping": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings/${ApiMappingId}", "ApiMappings": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings", "Apis": "arn:${Partition}:apigateway:${Region}::/apis", "Authorizer": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers/${AuthorizerId}", "Authorizers": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers", "AuthorizersCache": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/cache/authorizers", "BasePathMapping": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings/${BasePath}", "BasePathMappings": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings", "ClientCertificate": "arn:${Partition}:apigateway:${Region}::/clientcertificates/${ClientCertificateId}", "ClientCertificates": "arn:${Partition}:apigateway:${Region}::/clientcertificates", "Cors": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/cors", "Deployment": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments/${DeploymentId}", "Deployments": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments", "DocumentationPart": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts/${DocumentationPartId}", "DocumentationParts": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts", "DocumentationVersion": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions/${DocumentationVersionId}", "DocumentationVersions": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions", "DomainName": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}", "DomainNameAccessAssociation": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnameaccessassociations/domainname/${DomainName}/${SourceType}/${SourceId}", "DomainNameAccessAssociations": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnameaccessassociations", "DomainNames": "arn:${Partition}:apigateway:${Region}::/domainnames", "ExportedAPI": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/exports/${Specification}", "GatewayResponse": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses/${ResponseType}", "GatewayResponses": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses", "Integration": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}", "IntegrationResponse": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses/${IntegrationResponseId}", "IntegrationResponses": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses", "Integrations": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations", "Method": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}", "MethodResponse": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}/responses/${StatusCode}", "Model": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}", "ModelTemplate": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}/template", "Models": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models", "Portal": "arn:${Partition}:apigateway:${Region}:${Account}:/portals/${PortalId}", "PortalProduct": "arn:${Partition}:apigateway:${Region}:${Account}:/portalproducts/$Line truncated
|
||||
"pathFormats": {"apigateway": {"/restapis/{restapi_id}/models/{model_name}/default_template (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/models/${ModelName}/default_template", "/restapis/{restapi_id}/stages/{stage_name}/cache/authorizers (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/cache/authorizers", "/restapis/{restapi_id}/stages/{stage_name}/cache/data (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/cache/data", "/restapis/{restapi_id}/stages/{stage_name}/exports/{export_type} (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/exports/${ExportType}", "/sdktypes (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/sdktypes", "/sdktypes/{sdktype_id} (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/sdktypes/${SdktypeId}", "/usageplans/{usageplanId}/keys/{keyId}/usage (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsageplanId}/keys/${KeyId}/usage", "/usageplans/{usageplanId}/usage (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsageplanId}/usage", "Authorizer (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/authorizers/${Id}", "Authorizers (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/authorizers", "Deployment (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/deployments/${Id}", "Deployments (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/deployments", "Integration (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/resources/${ResourceId}/methods/${HttpMethod}/integration", "IntegrationResponse (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/resources/${ResourceId}/methods/${HttpMethod}/integration/responses/${StatusCode}", "Model (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/models/${ModelName}", "Models (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/models", "Stage (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/stages/${StageName}", "Stages (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/stages"}},
|
||||
"resourceTagKeys": {"access-analyzer": {"Analyzer": ["aws:ResourceTag/"]}, "acm": {"acme-domain-validation": ["aws:ResourceTag/"], "acme-endpoint": ["aws:ResourceTag/"], "acme-external-account-binding": ["aws:ResourceTag/"], "certificate": ["aws:ResourceTag/"]}, "apigateway": {"AccessLogSettings": ["aws:ResourceTag/"], "Api": ["aws:ResourceTag/"], "ApiKey": ["aws:ResourceTag/"], "ApiKeys": ["aws:ResourceTag/"], "ApiMapping": ["aws:ResourceTag/"], "ApiMappings": ["aws:ResourceTag/"], "Apis": ["aws:ResourceTag/"], "Authorizer": ["aws:ResourceTag/"], "Authorizers": ["aws:ResourceTag/"], "AuthorizersCache": ["aws:ResourceTag/"], "BasePathMapping": ["aws:ResourceTag/"], "BasePathMappings": ["aws:ResourceTag/"], "ClientCertificate": ["aws:ResourceTag/"], "ClientCertificates": ["aws:ResourceTag/"], "Cors": ["aws:ResourceTag/"], "Deployment": ["aws:ResourceTag/"], "Deployments": ["aws:ResourceTag/"], "DocumentationPart": ["aws:ResourceTag/"], "DocumentationParts": ["aws:ResourceTag/"], "DocumentationVersion": ["aws:ResourceTag/"], "DocumentationVersions": ["aws:ResourceTag/"], "DomainName": ["aws:ResourceTag/"], "DomainNameAccessAssociations": ["aws:ResourceTag/"], "DomainNames": ["aws:ResourceTag/"], "ExportedAPI": ["aws:ResourceTag/"], "GatewayResponse": ["aws:ResourceTag/"], "GatewayResponses": ["aws:ResourceTag/"], "Integration": ["aws:ResourceTag/"], "IntegrationResponse": ["aws:ResourceTag/"], "IntegrationResponses": ["aws:ResourceTag/"], "Integrations": ["aws:ResourceTag/"], "Method": ["aws:ResourceTag/"], "MethodResponse": ["aws:ResourceTag/"], "Model": ["aws:ResourceTag/"], "ModelTemplate": ["aws:ResourceTag/"], "Models": ["aws:ResourceTag/"], "Portal": ["aws:ResourceTag/"], "PortalProduct": ["aws:ResourceTag/"], "PrivateBasePathMapping": ["aws:ResourceTag/"], "PrivateBasePathMappings": ["aws:ResourceTag/"], "PrivateDomainName": ["aws:ResourceTag/"], "ProductPage": ["aws:ResourceTag/"], "ProductRestEndpointPage": ["aws:ResourceTag/"], "RequestValidator": ["aws:ResourceTag/"], "RequestValidators": ["aws:ResourceTag/"], "Resource": ["aws:ResourceTag/"], "Resources": ["aws:ResourceTag/"], "RestApi": ["aws:ResourceTag/"], "RestApis": ["aws:ResourceTag/"], "Route": ["aws:ResourceTag/"], "RouteRequestParameter": ["aws:ResourceTag/"], "RouteResponse": ["aws:ResourceTag/"], "RouteResponses": ["aws:ResourceTag/"], "RouteSettings": ["aws:ResourceTag/"], "Routes": ["aws:ResourceTag/"], "RoutingRule": ["aws:ResourceTag/"], "Sdk": ["aws:ResourceTag/"], "Stage": ["aws:ResourceTag/"], "Stages": ["aws:ResourceTag/"], "Template": ["aws:ResourceTag/"], "UsagePlan": ["aws:ResourceTag/"], "UsagePlanKey": ["aws:ResourceTag/"], "UsagePlanKeys": ["aws:ResourceTag/"], "UsagePlans": ["aws:ResourceTag/"], "VpcLink": ["aws:ResourceTag/"], "VpcLinks": ["aws:ResourceTag/"]}, "application-autoscaling": {"ScalableTarget": ["aws:ResourceTag/"]}, "aps": {"anomalydetector": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/"], "rulegroupsnamespace": ["aws:ResourceTag/"], "scraper": ["aws:ResourceTag/"], "workspace": ["aws:ResourceTag/"]}, "athena": {"capacity-reservation": ["aws:ResourceTag/"], "datacatalog": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"], "system-table": ["aws:ResourceTag/"], "workgroup": ["aws:ResourceTag/"]}, "bcm-data-exports": {"billingview": ["aws:ResourceTag/"], "export": ["aws:ResourceTag/"]}, "bcm-pricing-calculator": {"bill-estimate": ["aws:ResourceTag/"], "bill-scenario": ["aws:ResourceTag/"], "workload-estimate": ["aws:ResourceTag/"]}, "bedrock": {"advanced-prompt-optimization-job": ["aws:ResourceTag/"], "agent": ["aws:ResourceTag/"], "agent-alias": ["aws:ResourceTag/"], "application-inference-profile": ["aws:ResourceTag/"], "async-invoke": ["aws:ResourceTag/"], "automated-reasoning-policy": ["aws:ResourceTag/"], "automated-reasoning-policy-version": ["aws:ResourceTag/"], "blueprint": ["aws:ResourceTag/"], "blueprint-optimization-invocation": ["aws:ResourceTag/"], "custom-model": ["aws:ResourceTag/"], "custom-model-deployment": ["aws:ResourceTag/"], "data-automation-invocation-job": ["aws:ResourceTag/"], "data-automation-library": ["aws:ResourceTag/"], "data-automation-library-ingestion-job": ["aws:ResourceTag/"], "data-automation-project": ["aws:ResourceTag/"], "evaluation-job": ["aws:ResourceTag/"], "flow": ["aws:ResourceTag/"], "flow-alias": ["aws:ResourceTag/"], "guardrail": ["aws:ResourceTag/"], "imported-model": ["aws:ResourceTag/"], "knowledge-base": ["aws:ResourceTag/"], "model-copy-job": ["aws:ResourceTag/"], "model-customization-job": ["aws:ResourceTag/"], "model-evaluation-job": ["aws:ResourceTag/"], "model-import-job": ["aws:ResourceTag/"], "model-invocation-job": ["aws:ResourceTag/"], "project": ["aws:ResourceTag/"], "prompt": ["aws:ResourceTag/"], "prompt-router": ["aws:ResourceTag/"], "prompt-version": ["aws:ResourceTag/"], "provisioned-model": ["aws:ResourceTag/"], "retrieval-instruction": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"]}, "budgets": {"budget": ["aws:ResourceTag/Line truncated
|
||||
@@ -7195,7 +7195,7 @@
|
||||
"ssm:GetCalendarState": {"action": "ssm:GetCalendarState", "types": ["document"], "resources": []},
|
||||
"ssm:GetCloudConnector": {"action": "ssm:GetCloudConnector", "types": ["cloud-connector"], "resources": [{"type": "cloud-connector", "fill": {"CloudConnectorId": "CloudConnectorId"}}]},
|
||||
"ssm:GetCommandInvocation": {"action": "ssm:GetCommandInvocation", "types": [], "resources": []},
|
||||
"ssm:GetConnectionStatus": {"action": "ssm:GetConnectionStatus", "types": ["instance", "managed-instance", "task"], "resources": []},
|
||||
"ssm:GetConnectionStatus": {"action": "ssm:GetConnectionStatus", "types": ["instance", "managed-instance", "task"], "resources": [{"types": ["instance"], "through": "Target"}]},
|
||||
"ssm:GetDefaultPatchBaseline": {"action": "ssm:GetDefaultPatchBaseline", "types": ["patchbaseline"], "resources": []},
|
||||
"ssm:GetDeployablePatchSnapshotForInstance": {"action": "ssm:GetDeployablePatchSnapshotForInstance", "types": [], "resources": []},
|
||||
"ssm:GetDocument": {"action": "ssm:GetDocument", "types": ["document"], "resources": [{"type": "document", "fill": {"DocumentName": "Name"}}]},
|
||||
@@ -7258,7 +7258,7 @@
|
||||
"ssm:StartAutomationExecution": {"action": "ssm:StartAutomationExecution", "types": ["automation-definition", "automation-execution", "document"], "resources": [{"type": "automation-definition", "fill": {"VersionId": "DocumentVersion"}}, {"type": "automation-execution", "fill": {}, "made": true}, {"type": "document", "fill": {"DocumentName": "DocumentName"}}]},
|
||||
"ssm:StartChangeRequestExecution": {"action": "ssm:StartChangeRequestExecution", "types": ["automation-definition", "automation-execution", "document"], "resources": [{"type": "automation-definition", "fill": {"VersionId": "DocumentVersion"}}, {"type": "document", "fill": {"DocumentName": "DocumentName"}}]},
|
||||
"ssm:StartExecutionPreview": {"action": "ssm:StartExecutionPreview", "types": [], "resources": []},
|
||||
"ssm:StartSession": {"action": "ssm:StartSession", "types": ["document", "instance", "managed-instance", "task"], "resources": [{"type": "document", "fill": {"DocumentName": "DocumentName"}}]},
|
||||
"ssm:StartSession": {"action": "ssm:StartSession", "types": ["document", "instance", "managed-instance", "task"], "resources": [{"type": "document", "fill": {"DocumentName": "DocumentName"}, "defaults": {"DocumentName": "document"}}, {"types": ["instance"], "through": "Target"}]},
|
||||
"ssm:StopAutomationExecution": {"action": "ssm:StopAutomationExecution", "types": ["automation-execution"], "resources": [{"type": "automation-execution", "fill": {"AutomationExecutionId": "AutomationExecutionId"}}]},
|
||||
"ssm:TerminateSession": {"action": "ssm:TerminateSession", "types": ["session"], "resources": [{"type": "session", "fill": {"SessionId": "SessionId"}}]},
|
||||
"ssm:UnlabelParameterVersion": {"action": "ssm:UnlabelParameterVersion", "types": ["parameter"], "resources": [{"type": "parameter", "fill": {"ParameterNameWithoutLeadingSlash": "Name"}}]},
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schemaVersion":"1.0",
|
||||
"description":"Document to start port forwarding session over Session Manager",
|
||||
"sessionType":"Port",
|
||||
"parameters":{
|
||||
"portNumber":{
|
||||
"type":"String",
|
||||
"description":"(Optional) Port number of the server on the instance",
|
||||
"allowedPattern":"^([1-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
|
||||
"default": "80"
|
||||
},
|
||||
"localPortNumber":{
|
||||
"type":"String",
|
||||
"description":"(Optional) Port number on local machine to forward traffic to. An open port is chosen at run-time if not provided",
|
||||
"allowedPattern":"^([0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
|
||||
"default": "0"
|
||||
}
|
||||
},
|
||||
"properties":{
|
||||
"portNumber":"{{ portNumber }}",
|
||||
"type":"LocalPortForwarding",
|
||||
"localPortNumber":"{{ localPortNumber }}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"schemaVersion":"1.0",
|
||||
"description":"Document to start port forwarding session over Session Manager to remote host",
|
||||
"sessionType":"Port",
|
||||
"parameters":{
|
||||
"portNumber":{
|
||||
"type":"String",
|
||||
"description":"(Optional) Port number of the server on the instance",
|
||||
"allowedPattern":"^([1-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
|
||||
"default": "80"
|
||||
},
|
||||
"localPortNumber":{
|
||||
"type":"String",
|
||||
"description":"(Optional) Port number on local machine to forward traffic to. An open port is chosen at run-time if not provided",
|
||||
"allowedPattern":"^([0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
|
||||
"default": "0"
|
||||
},
|
||||
"host": {
|
||||
"type": "String",
|
||||
"description": "(Optional) Hostname or IP address of the destination server",
|
||||
"allowedPattern":"^[^,$^&\\(\\)!;'\"<>\\`{}\\[\\]\\|#=]{3,}$",
|
||||
"default": "localhost"
|
||||
}
|
||||
},
|
||||
"properties":{
|
||||
"portNumber":"{{ portNumber }}",
|
||||
"type":"LocalPortForwarding",
|
||||
"localPortNumber":"{{ localPortNumber }}",
|
||||
"host": "{{ host }}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schemaVersion":"1.0",
|
||||
"description":"Document to open SSH connection over session manager to an instance",
|
||||
"sessionType":"Port",
|
||||
"parameters":{
|
||||
"portNumber":{
|
||||
"type":"String",
|
||||
"description":"(Optional) Port number of SSH server on the instance",
|
||||
"allowedPattern":"^([1-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
|
||||
"default": "22"
|
||||
}
|
||||
},
|
||||
"properties":{
|
||||
"portNumber":"{{ portNumber }}"
|
||||
}
|
||||
}
|
||||
@@ -275,6 +275,18 @@ class RequestResourcesTest {
|
||||
assertFalse(arns.stream().anyMatch(arn -> arn.contains("document/arn:")), arns.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startSessionChecksTheTargetAndTheDefaultDocumentForAnOmittedName() {
|
||||
String target = "i-0123456789abcdef0";
|
||||
String instance = "arn:aws:ec2:us-east-1:000000000000:instance/" + target;
|
||||
String document = "arn:aws:ssm:us-east-1:000000000000:document/SSM-SessionManagerRunShell";
|
||||
StoredResourceArns stored = mock(StoredResourceArns.class);
|
||||
when(stored.through("Target", target, "us-east-1")).thenReturn(List.of(instance));
|
||||
when(stored.findDefault("document", "us-east-1")).thenReturn(Optional.of(document));
|
||||
assertEquals(List.of(document, instance),
|
||||
of("ssm:StartSession", json("{\"Target\":\"" + target + "\"}"), stored));
|
||||
}
|
||||
|
||||
/**
|
||||
* DynamoDB is built by hand, but the table reads {@code ListTables}: AWS was measured to check it on the literal
|
||||
* {@code table/*} of the request's partition, Region and account, whatever table its request names, though the
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/** Interrupts only the test client's transport, leaving the agent and shell running. */
|
||||
final class SessionConnectProxy implements AutoCloseable {
|
||||
private static final Logger LOG = Logger.getLogger(SessionConnectProxy.class);
|
||||
private final ServerSocket listener;
|
||||
private final URI endpoint;
|
||||
private final Set<Socket> sockets = ConcurrentHashMap.newKeySet();
|
||||
private final Set<Socket> tunnels = ConcurrentHashMap.newKeySet();
|
||||
private final AtomicInteger connections = new AtomicInteger();
|
||||
|
||||
SessionConnectProxy(URI endpoint) throws IOException {
|
||||
this.endpoint = endpoint;
|
||||
listener = new ServerSocket(0, 50, InetAddress.getByName(endpoint.getHost()));
|
||||
Thread.ofVirtual().start(() -> {
|
||||
while (!listener.isClosed()) {
|
||||
try {
|
||||
Socket client = listener.accept();
|
||||
sockets.add(client);
|
||||
Thread.ofVirtual().start(() -> forward(client));
|
||||
} catch (IOException e) {
|
||||
if (!listener.isClosed()) {
|
||||
LOG.warnv(e, "Session test proxy failed to accept a connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
int port() {
|
||||
return listener.getLocalPort();
|
||||
}
|
||||
|
||||
int connections() {
|
||||
return connections.get();
|
||||
}
|
||||
|
||||
void disconnect() throws IOException {
|
||||
for (Socket socket : tunnels) {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void forward(Socket client) {
|
||||
try (client; Socket remote = new Socket()) {
|
||||
client.setSoTimeout(10000);
|
||||
String header = header(client.getInputStream());
|
||||
String[] request = header.substring(0, header.indexOf("\r\n")).split(" ", 3);
|
||||
boolean connect = "CONNECT".equals(request[0]);
|
||||
URI destination = URI.create(connect ? "http://" + request[1] : request[1]);
|
||||
if (!endpoint.getHost().equals(destination.getHost()) || endpoint.getPort() != destination.getPort()) {
|
||||
throw new IOException("Session test proxy only forwards to its Floci endpoint");
|
||||
}
|
||||
remote.connect(new InetSocketAddress(destination.getHost(), destination.getPort()), 5000);
|
||||
sockets.add(remote);
|
||||
if (connect) {
|
||||
tunnels.add(client);
|
||||
tunnels.add(remote);
|
||||
connections.incrementAndGet();
|
||||
client.getOutputStream().write("HTTP/1.1 200 Connection Established\r\n\r\n"
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
client.getOutputStream().flush();
|
||||
} else {
|
||||
String path = destination.getRawPath();
|
||||
if (destination.getRawQuery() != null) {
|
||||
path += "?" + destination.getRawQuery();
|
||||
}
|
||||
remote.getOutputStream().write((request[0] + " " + path + " " + request[2]
|
||||
+ header.substring(header.indexOf("\r\n"))).getBytes(StandardCharsets.US_ASCII));
|
||||
}
|
||||
client.setSoTimeout(0);
|
||||
Thread upstream = Thread.ofVirtual().start(() -> pipe(client, remote));
|
||||
pipe(remote, client);
|
||||
upstream.join(1000);
|
||||
sockets.remove(remote);
|
||||
tunnels.remove(remote);
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Session test proxy connection closed");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
sockets.remove(client);
|
||||
tunnels.remove(client);
|
||||
}
|
||||
}
|
||||
|
||||
private static String header(InputStream input) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
int tail = 0;
|
||||
while (bytes.size() < 65536) {
|
||||
int value = input.read();
|
||||
if (value < 0) {
|
||||
throw new IOException("Proxy request ended before its headers");
|
||||
}
|
||||
bytes.write(value);
|
||||
tail = (tail << 8) | value;
|
||||
if (tail == 0x0d0a0d0a) {
|
||||
return bytes.toString(StandardCharsets.US_ASCII);
|
||||
}
|
||||
}
|
||||
throw new IOException("Proxy request headers exceed 64 KiB");
|
||||
}
|
||||
|
||||
private static void pipe(Socket source, Socket destination) {
|
||||
try {
|
||||
source.getInputStream().transferTo(destination.getOutputStream());
|
||||
destination.shutdownOutput();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Session test proxy stream interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
listener.close();
|
||||
for (Socket socket : sockets) {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,7 +367,8 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
|
||||
SsmCommandService commandService = new SsmCommandService(
|
||||
new SingleCommandStoreFactory(commandStore), objectMapper, regionResolver, executor);
|
||||
SsmJsonHandler jsonHandler = new SsmJsonHandler(mock(SsmService.class), commandService, objectMapper, null);
|
||||
SsmJsonHandler jsonHandler = new SsmJsonHandler(mock(SsmService.class), commandService, objectMapper,
|
||||
null, mock(SsmSessionJsonHandler.class));
|
||||
|
||||
Command command = commandService.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
@@ -385,7 +386,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
ObjectNode listRequest = objectMapper.createObjectNode().put("CommandId", command.getCommandId());
|
||||
AtomicBoolean listReturned = new AtomicBoolean(false);
|
||||
Thread listThread = new Thread(() -> {
|
||||
jsonHandler.handle("ListCommands", listRequest, "us-west-2", null);
|
||||
jsonHandler.handle("ListCommands", listRequest, "us-west-2", null, null);
|
||||
listReturned.set(true);
|
||||
});
|
||||
listThread.start();
|
||||
|
||||
@@ -645,76 +645,89 @@ class SsmIntegrationTest {
|
||||
|
||||
@Test
|
||||
void document_createGetUpdateRoundTrip() {
|
||||
// Create — mirrors LZA's session-manager-settings Lambda (DocumentType Session)
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentType": "Session",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":false}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DocumentDescription.Name", equalTo("SSM-SessionManagerRunShell"))
|
||||
.body("DocumentDescription.DocumentType", equalTo("Session"))
|
||||
.body("DocumentDescription.DocumentVersion", equalTo("1"))
|
||||
.body("DocumentDescription.Status", equalTo("Active"));
|
||||
try {
|
||||
// Create — mirrors LZA's session-manager-settings Lambda (DocumentType Session)
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.CreateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentType": "Session",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":false}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DocumentDescription.Name", equalTo("SSM-SessionManagerRunShell"))
|
||||
.body("DocumentDescription.DocumentType", equalTo("Session"))
|
||||
.body("DocumentDescription.DocumentVersion", equalTo("1"))
|
||||
.body("DocumentDescription.Status", equalTo("Active"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.GetDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Name", equalTo("SSM-SessionManagerRunShell"))
|
||||
.body("DocumentType", equalTo("Session"))
|
||||
.body("DocumentVersion", equalTo("1"))
|
||||
.body("Content", containsString("runAsEnabled"));
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.GetDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Name", equalTo("SSM-SessionManagerRunShell"))
|
||||
.body("DocumentType", equalTo("Session"))
|
||||
.body("DocumentVersion", equalTo("1"))
|
||||
.body("Content", containsString("runAsEnabled"));
|
||||
|
||||
// Update with changed content bumps the version
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentVersion": "$LATEST",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DocumentDescription.DocumentVersion", equalTo("2"));
|
||||
// Update with changed content bumps the version
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentVersion": "$LATEST",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DocumentDescription.DocumentVersion", equalTo("2"));
|
||||
|
||||
// Update with identical content fails DuplicateDocumentContent
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentVersion": "$LATEST",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("DuplicateDocumentContent"));
|
||||
// Update with identical content fails DuplicateDocumentContent
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.UpdateDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"Name": "SSM-SessionManagerRunShell",
|
||||
"DocumentVersion": "$LATEST",
|
||||
"Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}"
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("DuplicateDocumentContent"));
|
||||
} finally {
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.DeleteDocument")
|
||||
.contentType(SSM_CONTENT_TYPE)
|
||||
.body("""
|
||||
{ "Name": "SSM-SessionManagerRunShell" }
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Document parameter validation (botocore: DocumentName ^[a-zA-Z0-9_\-.]{3,128}$) ──
|
||||
|
||||
@@ -35,15 +35,15 @@ class SsmJsonHandlerSecretReferenceTest {
|
||||
when(ssmService.getParameters(List.of(NAME), true, REGION)).thenReturn(List.of(replacement));
|
||||
doThrow(new AwsException("AccessDenied", "denied", 403)).when(iamEnforcementFilter)
|
||||
.authorizeAdditionalResource("auth", "secretsmanager:GetSecretValue", REPLACEMENT_ARN);
|
||||
SsmJsonHandler handler = new SsmJsonHandler(ssmService, null, objectMapper, iamEnforcementFilter);
|
||||
SsmJsonHandler handler = new SsmJsonHandler(ssmService, null, objectMapper, iamEnforcementFilter, null);
|
||||
|
||||
ObjectNode getParameter = objectMapper.createObjectNode().put("Name", NAME).put("WithDecryption", true);
|
||||
ObjectNode getParameters = objectMapper.createObjectNode().put("WithDecryption", true);
|
||||
getParameters.putArray("Names").add(NAME);
|
||||
|
||||
assertEquals("An error occurred while calling one AWS dependency service.", assertThrows(AwsException.class,
|
||||
() -> handler.handle("GetParameter", getParameter, REGION, "auth")).getMessage());
|
||||
() -> handler.handle("GetParameter", getParameter, REGION, "auth", null)).getMessage());
|
||||
assertEquals("An error occurred while calling one AWS dependency service.", assertThrows(AwsException.class,
|
||||
() -> handler.handle("GetParameters", getParameters, REGION, "auth")).getMessage());
|
||||
() -> handler.handle("GetParameters", getParameters, REGION, "auth", null)).getMessage());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestResources;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
@@ -19,6 +20,8 @@ import io.floci.aws.services.ssm.model.SsmAssociation;
|
||||
import io.floci.aws.services.ssm.model.SsmDocument;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -80,6 +83,22 @@ class SsmServiceTest {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"mi-0123456789abcdef0", "ecs:cluster_container_runtime", "i-*",
|
||||
"i-0123456789abcdef0/suffix", "arn:aws:ec2:us-east-1:111122223333:instance/i-0123456789abcdef0"})
|
||||
void resolvesNoSessionResourceForAnUnsupportedTarget(String target) {
|
||||
assertEquals(List.of(), ssmService.through("Target", target, "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAssociationWithoutANameDoesNotSelectTheSessionDocument() throws Exception {
|
||||
String id = "d50f951e-8dff-4640-9a67-143a0e039b30";
|
||||
assertEquals(List.of("arn:aws:ssm:us-east-1:000000000000:association/" + id),
|
||||
RequestResources.ofBody("ssm:UpdateAssociation",
|
||||
MAPPER.readTree("{\"AssociationId\":\"" + id + "\"}"),
|
||||
"aws", "us-east-1", "000000000000", ssmService));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDocumentPermissionEmptyByDefault() {
|
||||
ssmService.createDocument("MyDoc", "{}", "Command", "us-east-1");
|
||||
@@ -1117,13 +1136,14 @@ class SsmServiceTest {
|
||||
ssmService.createDocument("Doc3", "{}", "Command", "us-west-2");
|
||||
|
||||
List<SsmDocument> eastDocs = ssmService.listDocuments("us-east-1", null);
|
||||
assertEquals(2, eastDocs.size());
|
||||
assertEquals(5, eastDocs.size());
|
||||
assertTrue(eastDocs.stream().anyMatch(d -> "Doc1".equals(d.getName())));
|
||||
assertTrue(eastDocs.stream().anyMatch(d -> "Doc2".equals(d.getName())));
|
||||
|
||||
List<SsmDocument> westDocs = ssmService.listDocuments("us-west-2", Map.of());
|
||||
assertEquals(1, westDocs.size());
|
||||
assertEquals("Doc3", westDocs.get(0).getName());
|
||||
assertEquals(4, westDocs.size());
|
||||
assertTrue(westDocs.stream().anyMatch(d -> "Doc3".equals(d.getName())));
|
||||
assertFalse(westDocs.stream().anyMatch(d -> "Doc1".equals(d.getName()) || "Doc2".equals(d.getName())));
|
||||
|
||||
// Filter by DocumentType
|
||||
List<SsmDocument> commandDocs = ssmService.listDocuments("us-east-1", Map.of("DocumentType", List.of("Command")));
|
||||
@@ -1139,23 +1159,36 @@ class SsmServiceTest {
|
||||
List<SsmDocument> blankNameDocs = ssmService.listDocuments("us-east-1", Map.of("Name", List.of("")));
|
||||
assertTrue(blankNameDocs.isEmpty());
|
||||
|
||||
// Owner=Self/All/the caller's account id match every visible document (all are self-owned)
|
||||
// Self excludes AWS-owned documents; All includes them.
|
||||
List<SsmDocument> selfDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("Self")));
|
||||
assertEquals(2, selfDocs.size());
|
||||
List<SsmDocument> allDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("All")));
|
||||
assertEquals(2, allDocs.size());
|
||||
assertEquals(5, allDocs.size());
|
||||
|
||||
// Owner=Amazon/Public/another account id match none: no AWS-owned or cross-account documents
|
||||
// Amazon selects the built-in documents.
|
||||
List<SsmDocument> amazonDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("Amazon")));
|
||||
assertTrue(amazonDocs.isEmpty());
|
||||
assertEquals(3, amazonDocs.size());
|
||||
assertTrue(amazonDocs.stream().allMatch(d -> "Amazon".equals(d.getOwner())));
|
||||
|
||||
// Filter by PlatformTypes (all documents default to Windows/Linux/MacOS)
|
||||
List<SsmDocument> windowsDocs = ssmService.listDocuments("us-east-1", Map.of("PlatformTypes", List.of("Windows")));
|
||||
assertEquals(2, windowsDocs.size());
|
||||
assertEquals(5, windowsDocs.size());
|
||||
List<SsmDocument> aixDocs = ssmService.listDocuments("us-east-1", Map.of("PlatformTypes", List.of("AIX")));
|
||||
assertTrue(aixDocs.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unfilteredListIncludesBuiltinDocumentsAndRegionalAccountDocuments() {
|
||||
ssmService.createDocument("EastDoc", "{}", "Command", "us-east-1");
|
||||
ssmService.createDocument("WestDoc", "{}", "Command", "us-west-2");
|
||||
|
||||
List<SsmDocument> documents = ssmService.listDocuments("us-west-2", null);
|
||||
|
||||
assertEquals(List.of("AWS-StartPortForwardingSession", "AWS-StartPortForwardingSessionToRemoteHost",
|
||||
"AWS-StartSSHSession", "WestDoc"),
|
||||
documents.stream().map(SsmDocument::getName).sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testListDocuments_LegacyNullOwnerMatchesSelfAndAccountId() {
|
||||
InMemoryStorage<String, SsmDocument> legacyDocumentStore = new InMemoryStorage<>();
|
||||
@@ -1176,8 +1209,9 @@ class SsmServiceTest {
|
||||
assertEquals("123456789012", accountDocs.get(0).getOwner());
|
||||
|
||||
List<SsmDocument> unfilteredDocs = service.listDocuments("us-east-1", null);
|
||||
assertEquals(1, unfilteredDocs.size());
|
||||
assertEquals("123456789012", unfilteredDocs.get(0).getOwner());
|
||||
assertEquals(4, unfilteredDocs.size());
|
||||
assertEquals("123456789012", unfilteredDocs.stream()
|
||||
.filter(d -> "LegacyDoc".equals(d.getName())).findFirst().orElseThrow().getOwner());
|
||||
|
||||
assertTrue(service.listDocuments("us-east-1", Map.of("Owner", List.of("999999999999"))).isEmpty());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils.Arn;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.Node;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionRequest;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionState;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.SignedIamEnforcementProfile;
|
||||
import io.floci.aws.testing.SignedIamUsers;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.DocumentType;
|
||||
import software.amazon.awssdk.services.ssm.model.GetConnectionStatusResponse;
|
||||
import software.amazon.awssdk.services.ssm.model.ResumeSessionResponse;
|
||||
import software.amazon.awssdk.services.ssm.model.Session;
|
||||
import software.amazon.awssdk.services.ssm.model.SessionFilter;
|
||||
import software.amazon.awssdk.services.ssm.model.SsmException;
|
||||
import software.amazon.awssdk.services.ssm.model.StartSessionResponse;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
import software.amazon.awssdk.services.sts.model.Credentials;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
class SsmSessionApiIntegrationTest {
|
||||
private static final String MISSING_TARGET = "i-0123456789abcdef0";
|
||||
private static final String MISSING_SESSION = "session-test-0123456789abcdef0";
|
||||
private static final String CONNECTED_TARGET = "i-fedcba98765432100";
|
||||
private static final Node CONNECTED_NODE = new Node("000000000000", "us-east-1", CONNECTED_TARGET);
|
||||
|
||||
@InjectMock SsmMessageGateway gateway;
|
||||
|
||||
@Inject SsmService documents;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
private SsmClient ssm;
|
||||
|
||||
@BeforeEach
|
||||
void connect() {
|
||||
ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void disconnect() {
|
||||
ssm.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictAuthenticationRejectsUnknownSessionCaller() {
|
||||
String target = "i-11111111111111111";
|
||||
when(gateway.isConnected(new Node("000000000000", "us-east-1", target))).thenReturn(true);
|
||||
try (SsmClient caller = AwsTestClients.create(SsmClient.builder(), "local", Region.US_EAST_1, endpoint)) {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> caller.startSession(r -> r.target(target)));
|
||||
assertEquals(403, error.statusCode());
|
||||
assertEquals("UnrecognizedClientException", error.awsErrorDetails().errorCode());
|
||||
assertNoSessionsForTarget(target);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictAuthenticationRejectsUnsignedSessionCaller() {
|
||||
String target = "i-22222222222222222";
|
||||
when(gateway.isConnected(new Node("000000000000", "us-east-1", target))).thenReturn(true);
|
||||
RestAssured.given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonSSM.StartSession")
|
||||
.body(("{\"Target\":\"" + target + "\"}").getBytes(StandardCharsets.UTF_8)).post(endpoint)
|
||||
.then().statusCode(403)
|
||||
.body(containsString("MissingAuthenticationTokenException"));
|
||||
assertNoSessionsForTarget(target);
|
||||
}
|
||||
|
||||
private void assertNoSessionsForTarget(String target) {
|
||||
assertTrue(ssm.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("Target").value(target))).sessions().isEmpty());
|
||||
assertTrue(ssm.describeSessions(r -> r.state("History")
|
||||
.filters(f -> f.key("Target").value(target))).sessions().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTargetIsNotConnected() {
|
||||
GetConnectionStatusResponse status = ssm.getConnectionStatus(r -> r.target(MISSING_TARGET));
|
||||
assertEquals(MISSING_TARGET, status.target());
|
||||
assertEquals("notconnected", status.statusAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionStatusRequiresPermissionOnTheRequestedInstance() throws Exception {
|
||||
when(gateway.isConnected(CONNECTED_NODE)).thenReturn(true);
|
||||
String arn = Arn.of("ec2", "us-east-1", "000000000000", "instance/" + CONNECTED_TARGET).toString();
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ssm:GetConnectionStatus","Resource":"%s"}
|
||||
]}
|
||||
""".formatted(arn);
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-status-", "status", policy);
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
assertEquals("connected", caller.getConnectionStatus(r -> r.target(CONNECTED_TARGET)).statusAsString());
|
||||
SsmException denied = assertThrows(SsmException.class,
|
||||
() -> caller.getConnectionStatus(r -> r.target(MISSING_TARGET)));
|
||||
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"mi-0123456789abcdef0", "ecs:cluster_container_runtime"})
|
||||
void unsupportedTargetCannotStartASession(String target) {
|
||||
when(gateway.isConnected(new Node("000000000000", "us-east-1", target))).thenReturn(true);
|
||||
SsmException error = assertThrows(SsmException.class, () -> ssm.startSession(r -> r.target(target)));
|
||||
assertEquals("TargetNotConnected", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"i-01234567", "i-0123456789abcdef0"})
|
||||
void iamResolvesTheTargetInTheRequestAccountAndPartition(String target) {
|
||||
RequestScopes.runAs("111122223333", "us-gov-west-1", () -> assertEquals(
|
||||
List.of("arn:aws-us-gov:ec2:us-gov-west-1:111122223333:instance/" + target),
|
||||
documents.through("Target", target, "us-gov-west-1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamResolvesTheImplicitDocumentWithoutStorage() {
|
||||
String region = "cn-north-1";
|
||||
String name = "SSM-SessionManagerRunShell";
|
||||
RequestScopes.runAs("111122223333", region, () -> {
|
||||
assertTrue(documents.findDocument(name, region).isEmpty());
|
||||
assertEquals(Optional.of("arn:aws-cn:ssm:cn-north-1:111122223333:document/" + name),
|
||||
documents.findDefault("document", region));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void cannotStartSessionForMissingTarget() {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> ssm.startSession(r -> r.target(MISSING_TARGET)));
|
||||
assertEquals("TargetNotConnected", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreachableTargetIsReportedBeforeMissingDocument() {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> ssm.startSession(r -> r.target(MISSING_TARGET).documentName("missing-document")));
|
||||
assertEquals("TargetNotConnected", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cannotResumeUnknownSession() {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> ssm.resumeSession(r -> r.sessionId(MISSING_SESSION)));
|
||||
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cannotTerminateUnknownSession() {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> ssm.terminateSession(r -> r.sessionId(MISSING_SESSION)));
|
||||
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownSessionHasNeitherActiveNorHistoricalEntry() {
|
||||
SessionFilter filter = SessionFilter.builder().key("SessionId").value(MISSING_SESSION).build();
|
||||
assertTrue(ssm.describeSessions(r -> r.state("Active").filters(filter)).sessions().isEmpty());
|
||||
assertTrue(ssm.describeSessions(r -> r.state("History").filters(filter)).sessions().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startReturnsReachableChannelAndPublishesActiveMetadata() {
|
||||
connectGateway();
|
||||
StartSessionResponse response = ssm.startSession(r -> r.target(CONNECTED_TARGET).reason("API integration"));
|
||||
try {
|
||||
URI url = URI.create(response.streamUrl());
|
||||
assertEquals("ws", url.getScheme());
|
||||
assertEquals(RestAssured.port, url.getPort());
|
||||
assertEquals("/v1/data-channel/" + response.sessionId(), url.getPath());
|
||||
assertEquals("role=publish_subscribe", url.getQuery());
|
||||
assertEquals("initial-token", response.tokenValue());
|
||||
Session session = sessions("Active", response.sessionId()).getFirst();
|
||||
assertEquals(CONNECTED_TARGET, session.target());
|
||||
assertEquals("Connected", session.statusAsString());
|
||||
assertEquals("API integration", session.reason());
|
||||
assertNotNull(session.startDate());
|
||||
} finally {
|
||||
ssm.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void startSessionGrantRequiresPermissionOnTheSelectedDocument(boolean useCustomDocument)
|
||||
throws Exception {
|
||||
connectGateway();
|
||||
String customDocument = "session-iam-" + UUID.randomUUID();
|
||||
ssm.createDocument(r -> r.name(customDocument).documentType(DocumentType.SESSION)
|
||||
.content("""
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream"}
|
||||
"""));
|
||||
String permittedDocument = useCustomDocument ? customDocument : "SSM-SessionManagerRunShell";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ssm:StartSession","Resource":"arn:aws:ec2:us-east-1:000000000000:instance/%s"},
|
||||
{"Effect":"Allow","Action":"ssm:StartSession","Resource":"arn:aws:ssm:us-east-1:000000000000:document/%s"}
|
||||
]}
|
||||
""".formatted(CONNECTED_TARGET, permittedDocument);
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-session-", "session", policy);
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
StartSessionResponse session = caller.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(useCustomDocument ? customDocument : null));
|
||||
try {
|
||||
assertEquals("initial-token", session.tokenValue());
|
||||
} finally {
|
||||
ssm.terminateSession(r -> r.sessionId(session.sessionId()));
|
||||
}
|
||||
SsmException denied = assertThrows(SsmException.class, () -> caller.startSession(r -> r
|
||||
.target(CONNECTED_TARGET).documentName(useCustomDocument ? null : customDocument)));
|
||||
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
ssm.deleteDocument(r -> r.name(customDocument));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"AWS-StartSSHSession, us-east-1, false",
|
||||
"AWS-StartSSHSession, us-east-1, true",
|
||||
"AWS-StartPortForwardingSession, us-east-1, false",
|
||||
"AWS-StartPortForwardingSession, us-east-1, true",
|
||||
"AWS-StartPortForwardingSessionToRemoteHost, us-east-1, false",
|
||||
"AWS-StartPortForwardingSessionToRemoteHost, us-east-1, true",
|
||||
"AWS-StartPortForwardingSession, us-gov-west-1, false",
|
||||
"AWS-StartPortForwardingSession, us-gov-west-1, true"
|
||||
})
|
||||
void awsOwnedSessionDocumentAllowsExactEmptyAccountGrant(String name, String regionName, boolean useArn)
|
||||
throws Exception {
|
||||
Region region = Region.of(regionName);
|
||||
connectGateway();
|
||||
when(gateway.isConnected(new Node("000000000000", regionName, CONNECTED_TARGET))).thenReturn(true);
|
||||
String documentArn = Arn.of("ssm", regionName, "", "document/" + name).toString();
|
||||
Map<String, List<String>> parameters = name.endsWith("ToRemoteHost")
|
||||
? Map.of("host", List.of("localhost")) : Map.of();
|
||||
String policy = startSessionPolicy(regionName, documentArn);
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-builtin-", "session", policy);
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), region, endpoint);
|
||||
SsmClient admin = AwsTestClients.create(SsmClient.builder(), "test", region, endpoint)) {
|
||||
StartSessionResponse session = caller.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(useArn ? documentArn : name).parameters(parameters));
|
||||
try {
|
||||
assertEquals("initial-token", session.tokenValue());
|
||||
assertNotNull(session.sessionId());
|
||||
} finally {
|
||||
admin.terminateSession(r -> r.sessionId(session.sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"AWS-StartSSHSession, us-east-1, false",
|
||||
"AWS-StartSSHSession, us-east-1, true",
|
||||
"AWS-StartPortForwardingSession, us-east-1, false",
|
||||
"AWS-StartPortForwardingSession, us-east-1, true",
|
||||
"AWS-StartPortForwardingSessionToRemoteHost, us-east-1, false",
|
||||
"AWS-StartPortForwardingSessionToRemoteHost, us-east-1, true",
|
||||
"AWS-StartPortForwardingSession, us-gov-west-1, false",
|
||||
"AWS-StartPortForwardingSession, us-gov-west-1, true"
|
||||
})
|
||||
void awsOwnedSessionDocumentRejectsCallerAccountGrant(String name, String regionName, boolean useArn)
|
||||
throws Exception {
|
||||
Region region = Region.of(regionName);
|
||||
connectGateway();
|
||||
when(gateway.isConnected(new Node("000000000000", regionName, CONNECTED_TARGET))).thenReturn(true);
|
||||
String documentArn = Arn.of("ssm", regionName, "", "document/" + name).toString();
|
||||
Map<String, List<String>> parameters = name.endsWith("ToRemoteHost")
|
||||
? Map.of("host", List.of("localhost")) : Map.of();
|
||||
String wrongOwnerArn = Arn.of("ssm", regionName, "000000000000", "document/" + name).toString();
|
||||
String policy = startSessionPolicy(regionName, wrongOwnerArn);
|
||||
AtomicReference<StartSessionResponse> started = new AtomicReference<>();
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-builtin-", "session", policy);
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), region, endpoint);
|
||||
SsmClient admin = AwsTestClients.create(SsmClient.builder(), "test", region, endpoint)) {
|
||||
try {
|
||||
SsmException denied = assertThrows(SsmException.class, () -> started.set(caller.startSession(r -> r
|
||||
.target(CONNECTED_TARGET).documentName(useArn ? documentArn : name).parameters(parameters))));
|
||||
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
if (started.get() != null) {
|
||||
admin.terminateSession(r -> r.sessionId(started.get().sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false, false", "false, true", "true, false", "true, true"})
|
||||
void accountOwnedSessionDocumentAllowsExactCallerAccountGrant(boolean useDefaultDocument, boolean useArn)
|
||||
throws Exception {
|
||||
connectGateway();
|
||||
String name = useDefaultDocument ? "SSM-SessionManagerRunShell" : "session-owned-" + UUID.randomUUID();
|
||||
ssm.createDocument(r -> r.name(name).documentType(DocumentType.SESSION)
|
||||
.content("""
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream"}
|
||||
"""));
|
||||
String documentArn = Arn.of("ssm", "us-east-1", "000000000000", "document/" + name).toString();
|
||||
String policy = startSessionPolicy("us-east-1", documentArn);
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-owned-", "session", policy);
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
StartSessionResponse session = caller.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(useArn ? documentArn : name));
|
||||
try {
|
||||
assertEquals("initial-token", session.tokenValue());
|
||||
} finally {
|
||||
ssm.terminateSession(r -> r.sessionId(session.sessionId()));
|
||||
}
|
||||
} finally {
|
||||
ssm.deleteDocument(r -> r.name(name));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"false, false, Bool, false", "false, true, Bool, false",
|
||||
"true, false, Bool, false", "true, true, Bool, false",
|
||||
"false, false, Null, true", "false, true, Null, true",
|
||||
"true, false, Null, true", "true, true, Null, true"
|
||||
})
|
||||
void assumedRoleSessionDocumentConditionKeyIsAbsent(boolean customDocument, boolean conditionOnDocument,
|
||||
String operator, boolean allowed) {
|
||||
connectGateway();
|
||||
String name = "session-condition-" + UUID.randomUUID();
|
||||
String role = "session-condition-" + UUID.randomUUID();
|
||||
String targetArn = Arn.of("ec2", "us-east-1", "000000000000", "instance/" + CONNECTED_TARGET).toString();
|
||||
String documentArn = Arn.of("ssm", "us-east-1", "000000000000", "document/"
|
||||
+ (customDocument ? name : "SSM-SessionManagerRunShell")).toString();
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ssm:StartSession","Resource":"%s"},
|
||||
{"Effect":"Allow","Action":"ssm:StartSession","Resource":"%s",
|
||||
"Condition":{"%s":{"ssm:SessionDocumentAccessCheck":"true"}}}
|
||||
]}
|
||||
""".formatted(conditionOnDocument ? targetArn : documentArn,
|
||||
conditionOnDocument ? documentArn : targetArn, operator);
|
||||
ssm.createDocument(r -> r.name(name).documentType(DocumentType.SESSION)
|
||||
.content("""
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream"}
|
||||
"""));
|
||||
try (IamClient iam = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1, endpoint);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), "test", Region.US_EAST_1, endpoint)) {
|
||||
String roleArn = iam.createRole(r -> r.roleName(role).assumeRolePolicyDocument("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::000000000000:root"},"Action":"sts:AssumeRole"}]}
|
||||
""")).role().arn();
|
||||
try {
|
||||
iam.putRolePolicy(r -> r.roleName(role).policyName("session").policyDocument(policy));
|
||||
try {
|
||||
Credentials credentials = sts.assumeRole(r -> r.roleArn(roleArn).roleSessionName("condition-test"))
|
||||
.credentials();
|
||||
try (SsmClient caller = AwsTestClients.create(SsmClient.builder(), AwsSessionCredentials.create(
|
||||
credentials.accessKeyId(), credentials.secretAccessKey(), credentials.sessionToken()),
|
||||
Region.US_EAST_1, endpoint)) {
|
||||
AtomicReference<StartSessionResponse> started = new AtomicReference<>();
|
||||
try {
|
||||
if (allowed) {
|
||||
started.set(caller.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(customDocument ? name : null)));
|
||||
assertEquals("initial-token", started.get().tokenValue());
|
||||
} else {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> started.set(caller.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(customDocument ? name : null))));
|
||||
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
} finally {
|
||||
if (started.get() != null) {
|
||||
ssm.terminateSession(r -> r.sessionId(started.get().sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
iam.deleteRolePolicy(r -> r.roleName(role).policyName("session"));
|
||||
}
|
||||
} finally {
|
||||
iam.deleteRole(r -> r.roleName(role));
|
||||
}
|
||||
} finally {
|
||||
ssm.deleteDocument(r -> r.name(name));
|
||||
}
|
||||
}
|
||||
|
||||
private String startSessionPolicy(String region, String documentArn) {
|
||||
String targetArn = Arn.of("ec2", region, "000000000000", "instance/" + CONNECTED_TARGET).toString();
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ssm:StartSession","Resource":["%s","%s"]}
|
||||
]}
|
||||
""".formatted(targetArn, documentArn);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"[]", "\"shell\"", "42", "true", "null"})
|
||||
void rejectsNonObjectInputsBeforeDispatchingSessionTask(String inputs) {
|
||||
connectGateway();
|
||||
BlockingQueue<SessionRequest> tasks = new LinkedBlockingQueue<>();
|
||||
when(gateway.startSession(any(), any())).thenAnswer(call -> {
|
||||
tasks.add(call.getArgument(0));
|
||||
return "initial-token";
|
||||
});
|
||||
String document = "session-inputs-" + UUID.randomUUID();
|
||||
ssm.createDocument(r -> r.name(document).documentType(DocumentType.SESSION).content("""
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream","inputs":%s}
|
||||
""".formatted(inputs)));
|
||||
AtomicReference<StartSessionResponse> started = new AtomicReference<>();
|
||||
try {
|
||||
assertAll(
|
||||
() -> {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> started.set(ssm.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(document))));
|
||||
assertEquals("InvalidDocument", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
},
|
||||
() -> assertNull(tasks.poll(),
|
||||
"Invalid session inputs must not dispatch a session task"));
|
||||
} finally {
|
||||
try {
|
||||
if (started.get() != null) {
|
||||
ssm.terminateSession(r -> r.sessionId(started.get().sessionId()));
|
||||
}
|
||||
} finally {
|
||||
ssm.deleteDocument(r -> r.name(document));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOversizedStoredSessionDocumentBeforeDispatchAndCanStillStartSession() {
|
||||
AtomicReference<Consumer<SessionState>> listener = connectGateway();
|
||||
String document = "session-oversized-" + UUID.randomUUID();
|
||||
String shell = "{\"schemaVersion\":\"1.0\",\"sessionType\":\"Standard_Stream\"}";
|
||||
String oversized = shell + " ".repeat(65_537 - shell.length());
|
||||
ssm.createDocument(r -> r.name(document).documentType(DocumentType.SESSION).content(oversized));
|
||||
AtomicReference<StartSessionResponse> unexpectedStart = new AtomicReference<>();
|
||||
try {
|
||||
assertAll(
|
||||
() -> {
|
||||
SsmException error = assertThrows(SsmException.class,
|
||||
() -> unexpectedStart.set(ssm.startSession(r -> r.target(CONNECTED_TARGET)
|
||||
.documentName(document))));
|
||||
assertEquals("InvalidDocument", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
},
|
||||
() -> assertNull(listener.get(), "Oversized documents must not dispatch a session task"),
|
||||
() -> {
|
||||
StartSessionResponse ordinary = ssm.startSession(r -> r.target(CONNECTED_TARGET));
|
||||
try {
|
||||
assertEquals("initial-token", ordinary.tokenValue());
|
||||
} finally {
|
||||
ssm.terminateSession(r -> r.sessionId(ordinary.sessionId()));
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
if (unexpectedStart.get() != null) {
|
||||
ssm.terminateSession(r -> r.sessionId(unexpectedStart.get().sessionId()));
|
||||
}
|
||||
} finally {
|
||||
ssm.deleteDocument(r -> r.name(document));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resumeReturnsFreshTokenForSameSessionId() {
|
||||
connectGateway();
|
||||
StartSessionResponse original = ssm.startSession(r -> r.target(CONNECTED_TARGET));
|
||||
try {
|
||||
when(gateway.resumeSession(CONNECTED_NODE, original.sessionId())).thenReturn(Optional.of("resume-token"));
|
||||
ResumeSessionResponse resumed = ssm.resumeSession(r -> r.sessionId(original.sessionId()));
|
||||
assertEquals(original.sessionId(), resumed.sessionId());
|
||||
assertEquals(original.streamUrl(), resumed.streamUrl());
|
||||
assertNotEquals(original.tokenValue(), resumed.tokenValue());
|
||||
} finally {
|
||||
ssm.terminateSession(r -> r.sessionId(original.sessionId()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void agentCompletionMovesSessionToHistoryAndIgnoresLateConnectionEvent() throws Exception {
|
||||
AtomicReference<Consumer<SessionState>> listener = connectGateway();
|
||||
String sessionId = ssm.startSession(r -> r.target(CONNECTED_TARGET)).sessionId();
|
||||
CompletableFuture.runAsync(() -> {
|
||||
listener.get().accept(SessionState.TERMINATED);
|
||||
listener.get().accept(SessionState.CONNECTED);
|
||||
}).get(5, TimeUnit.SECONDS);
|
||||
assertTrue(sessions("Active", sessionId).isEmpty());
|
||||
Session history = sessions("History", sessionId).getFirst();
|
||||
assertEquals("Terminated", history.statusAsString());
|
||||
assertNotNull(history.endDate());
|
||||
}
|
||||
|
||||
private List<Session> sessions(String state, String sessionId) {
|
||||
return ssm.describeSessions(r -> r.state(state).filters(f -> f.key("SessionId").value(sessionId))).sessions();
|
||||
}
|
||||
|
||||
private AtomicReference<Consumer<SessionState>> connectGateway() {
|
||||
AtomicReference<Consumer<SessionState>> listener = new AtomicReference<>();
|
||||
when(gateway.isConnected(CONNECTED_NODE)).thenReturn(true);
|
||||
when(gateway.startSession(any(), any())).thenAnswer(call -> {
|
||||
listener.set(call.getArgument(1));
|
||||
return "initial-token";
|
||||
});
|
||||
return listener;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.ValidateSignaturesProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.DocumentDescription;
|
||||
import software.amazon.awssdk.services.ssm.model.DocumentIdentifier;
|
||||
import software.amazon.awssdk.services.ssm.model.DocumentKeyValuesFilter;
|
||||
import software.amazon.awssdk.services.ssm.model.GetDocumentResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
class SsmSessionDocumentIntegrationTest {
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private SsmClient ssm;
|
||||
|
||||
@BeforeEach
|
||||
void connect() {
|
||||
ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void disconnect() {
|
||||
ssm.close();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"AWS-StartSSHSession, 22",
|
||||
"AWS-StartPortForwardingSession, 80",
|
||||
"AWS-StartPortForwardingSessionToRemoteHost, 80"
|
||||
})
|
||||
void builtinSessionDocumentsAreReadableWithAwsMetadata(String name, String defaultPort) throws Exception {
|
||||
DocumentDescription description = ssm.describeDocument(r -> r.name(name)).document();
|
||||
assertEquals(name, description.name());
|
||||
assertEquals("Amazon", description.owner());
|
||||
assertEquals("Session", description.documentTypeAsString());
|
||||
assertEquals("1.0", description.schemaVersion());
|
||||
assertEquals("1", description.defaultVersion());
|
||||
|
||||
GetDocumentResponse result = ssm.getDocument(r -> r.name(name).documentVersion(description.defaultVersion()));
|
||||
JsonNode content = objectMapper.readTree(result.content());
|
||||
assertEquals("Port", content.path("sessionType").asText());
|
||||
assertEquals(defaultPort, content.at("/parameters/portNumber/default").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsAllBuiltinSessionDocumentsWithAwsMetadata() {
|
||||
List<DocumentIdentifier> documents = ssm.listDocuments(r -> r.filters(
|
||||
DocumentKeyValuesFilter.builder().key("Owner").values("Amazon").build(),
|
||||
DocumentKeyValuesFilter.builder().key("DocumentType").values("Session").build(),
|
||||
DocumentKeyValuesFilter.builder().key("PlatformTypes").values("Linux").build()))
|
||||
.documentIdentifiers();
|
||||
|
||||
assertEquals(List.of("AWS-StartPortForwardingSession", "AWS-StartPortForwardingSessionToRemoteHost",
|
||||
"AWS-StartSSHSession"),
|
||||
documents.stream().map(DocumentIdentifier::name).sorted().toList());
|
||||
for (DocumentIdentifier document : documents) {
|
||||
assertEquals("Amazon", document.owner());
|
||||
assertEquals("Session", document.documentTypeAsString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void filtersBuiltinDocumentsByNamePrefix() {
|
||||
List<DocumentIdentifier> documents = ssm.listDocuments(r -> r.filters(
|
||||
f -> f.key("Name").values("AWS-StartPortForwarding"))).documentIdentifiers();
|
||||
|
||||
assertEquals(List.of("AWS-StartPortForwardingSession", "AWS-StartPortForwardingSessionToRemoteHost"),
|
||||
documents.stream().map(DocumentIdentifier::name).sorted().toList());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Owner, Self", "Owner, Private", "Owner, 000000000000", "DocumentType, Command", "PlatformTypes, AIX"})
|
||||
void excludesBuiltinDocumentsWhenAFilterDoesNotMatch(String key, String value) {
|
||||
List<DocumentIdentifier> documents = ssm.listDocuments(r -> r.filters(
|
||||
DocumentKeyValuesFilter.builder().key("Name").values("AWS-Start").build(),
|
||||
DocumentKeyValuesFilter.builder().key(key).values(value).build())).documentIdentifiers();
|
||||
|
||||
assertTrue(documents.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.command.BuildImageResultCallback;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.AccessKey;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.SsmException;
|
||||
import software.amazon.awssdk.services.ssm.model.StartSessionResponse;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Stock Linux agent with signed heartbeat readiness and, for sessions, an open control channel. */
|
||||
final class SsmSessionFixture implements AutoCloseable {
|
||||
static final String IMAGE = "floci-ssm-session-test:local";
|
||||
static final String AGENT_VERSION = "3.3.5828.0";
|
||||
static final String ACCOUNT = "000000000000";
|
||||
static final Region REGION = Region.US_EAST_1;
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
final String name = "ssm-session-" + UUID.randomUUID();
|
||||
final DockerClient docker;
|
||||
final ContainerBuilder builder;
|
||||
final ContainerLifecycleManager lifecycle;
|
||||
final Ec2Service instances;
|
||||
final URI endpoint;
|
||||
final int tlsPort;
|
||||
final Path logs = Path.of("target", "ssm-session-logs", name);
|
||||
final List<String> documents = new ArrayList<>();
|
||||
final List<AccessKey> users = new ArrayList<>();
|
||||
final List<String> containers = new ArrayList<>();
|
||||
final List<String> networks = new ArrayList<>();
|
||||
final List<Session> sessions = new ArrayList<>();
|
||||
Ec2Client ec2;
|
||||
IamClient iam;
|
||||
SsmClient ssm;
|
||||
AccessKey operator;
|
||||
String instance;
|
||||
String guest;
|
||||
boolean roleCreated;
|
||||
boolean profileCreated;
|
||||
|
||||
SsmSessionFixture(DockerClient docker, ContainerBuilder builder, ContainerLifecycleManager lifecycle,
|
||||
Ec2Service instances, int httpPort, int tlsPort) {
|
||||
this.docker = docker;
|
||||
this.builder = builder;
|
||||
this.lifecycle = lifecycle;
|
||||
this.instances = instances;
|
||||
this.tlsPort = tlsPort;
|
||||
String gateway = docker.inspectNetworkCmd().withNetworkId("bridge").exec().getIpam().getConfig()
|
||||
.getFirst().getGateway();
|
||||
endpoint = URI.create("http://" + gateway + ":" + httpPort);
|
||||
}
|
||||
|
||||
void start() throws Exception {
|
||||
Files.createDirectories(logs);
|
||||
try (BuildImageResultCallback callback = new BuildImageResultCallback()) {
|
||||
docker.buildImageCmd(Path.of("src/test/resources/ssm/session-manager").toFile())
|
||||
.withTags(Set.of(IMAGE)).withRemove(true).exec(callback).awaitImageId(600, TimeUnit.SECONDS);
|
||||
}
|
||||
ec2 = AwsTestClients.create(Ec2Client.builder(), "test", REGION, endpoint);
|
||||
iam = AwsTestClients.create(IamClient.builder(), "test", REGION, endpoint);
|
||||
iam.createRole(r -> r.roleName(name).assumeRolePolicyDocument("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}
|
||||
"""));
|
||||
roleCreated = true;
|
||||
iam.attachRolePolicy(r -> r.roleName(name).policyArn("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"));
|
||||
iam.createInstanceProfile(r -> r.instanceProfileName(name));
|
||||
profileCreated = true;
|
||||
iam.addRoleToInstanceProfile(r -> r.instanceProfileName(name).roleName(name));
|
||||
operator = createUser("{\"Effect\":\"Allow\",\"Action\":[\"ssm:*\",\"ssmmessages:*\"],\"Resource\":\"*\"}");
|
||||
ssm = client(operator);
|
||||
String userData = """
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
mkdir -p /etc/amazon/ssm /etc/systemd/system/amazon-ssm-agent.service.d
|
||||
printf '%%s' '{"Ssm":{"Endpoint":"%1$s"},"Mgs":{"Endpoint":"%2$s"},"Mds":{"Endpoint":"%1$s"},
|
||||
"Agent":{"TelemetryMetricsToSSM":false,"GlobalEnhancedTelemetryEnabled":false}}' \
|
||||
> /etc/amazon/ssm/amazon-ssm-agent.json
|
||||
printf '[Service]\\nEnvironment=SSL_CERT_FILE=/etc/floci-ca-bundle.pem\\n' \
|
||||
> /etc/systemd/system/amazon-ssm-agent.service.d/floci.conf
|
||||
cat > /etc/systemd/system/floci-session-echo.service <<'UNIT'
|
||||
[Unit]
|
||||
Description=Session Manager fixture loopback echo
|
||||
[Service]
|
||||
ExecStart=/usr/bin/socat TCP-LISTEN:18080,bind=127.0.0.1,reuseaddr,fork EXEC:cat
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now amazon-ssm-agent floci-session-echo.service
|
||||
""".formatted("https://host.docker.internal:" + tlsPort,
|
||||
"https://host.docker.internal:" + tlsPort);
|
||||
instance = ec2.runInstances(r -> r.imageId("ami-0f10c155a90000001").instanceType("t3.micro")
|
||||
.minCount(1).maxCount(1).iamInstanceProfile(p -> p.name(name))
|
||||
.metadataOptions(m -> m.httpTokens("required").httpEndpoint("enabled"))
|
||||
.userData(Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8))))
|
||||
.instances().getFirst().instanceId();
|
||||
await().pollInterval(Duration.ofMillis(500)).atMost(Duration.ofSeconds(90)).untilAsserted(() -> {
|
||||
assertTrue(ssm.describeInstanceInformation(r -> r.filters(f -> f.key("InstanceIds").values(instance)))
|
||||
.instanceInformationList().stream().anyMatch(i -> instance.equals(i.instanceId())
|
||||
&& AGENT_VERSION.equals(i.agentVersion()) && "Online".equals(i.pingStatusAsString())));
|
||||
assertEquals("connected",
|
||||
ssm.getConnectionStatus(r -> r.target(instance)).statusAsString());
|
||||
});
|
||||
guest = instances.getInstance(REGION.id(), instance).orElseThrow().getDockerContainerId();
|
||||
}
|
||||
|
||||
AccessKey createUser(String statements) {
|
||||
String user = name + "-" + users.size();
|
||||
iam.createUser(r -> r.userName(user));
|
||||
AccessKey key = iam.createAccessKey(r -> r.userName(user)).accessKey();
|
||||
users.add(key);
|
||||
iam.putUserPolicy(r -> r.userName(user).policyName("sessions")
|
||||
.policyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"));
|
||||
return key;
|
||||
}
|
||||
|
||||
SsmClient client(AccessKey key) {
|
||||
return AwsTestClients.create(SsmClient.builder(), AwsBasicCredentials.create(key.accessKeyId(),
|
||||
key.secretAccessKey()), REGION, endpoint);
|
||||
}
|
||||
|
||||
String document(String content, String type) {
|
||||
String document = name + "-doc-" + documents.size();
|
||||
ssm.createDocument(r -> r.name(document).documentType(type).documentFormat("JSON").content(content));
|
||||
documents.add(document);
|
||||
return document;
|
||||
}
|
||||
|
||||
Session startSession(String document, Map<String, List<String>> parameters) throws Exception {
|
||||
return startSession(ssm, operator, document, parameters);
|
||||
}
|
||||
|
||||
Session startSession(SsmClient client, AccessKey key, String document,
|
||||
Map<String, List<String>> parameters) throws Exception {
|
||||
StartSessionResponse response = client.startSession(r -> r.target(instance).documentName(document)
|
||||
.parameters(parameters));
|
||||
Session session = new Session(client, key, response, document, parameters);
|
||||
sessions.add(session);
|
||||
assertEquals(endpoint.getHost(), URI.create(response.streamUrl()).getHost(),
|
||||
"Session stream must use the client-reachable request endpoint");
|
||||
return session;
|
||||
}
|
||||
|
||||
String container(List<String> command) {
|
||||
String id = lifecycle.createAndStartEphemeral(builder.newContainer(IMAGE)
|
||||
.withName(name + "-client-" + containers.size()).withHostDockerInternalOnLinux()
|
||||
.withEntrypoint(command).build()).containerId();
|
||||
containers.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
record RemoteTarget(String container, String address, String guestAddress) { }
|
||||
|
||||
RemoteTarget remoteTarget(boolean postgres) {
|
||||
String network = docker.createNetworkCmd().withName(name + "-remote-" + networks.size())
|
||||
.withInternal(true).exec().getId();
|
||||
networks.add(network);
|
||||
docker.connectToNetworkCmd().withNetworkId(network).withContainerId(guest).exec();
|
||||
ContainerBuilder.Builder spec = builder.newContainer(postgres ? "postgres:17" : IMAGE)
|
||||
.withName(name + "-remote-" + containers.size()).withDockerNetwork(Optional.of(network));
|
||||
if (postgres) {
|
||||
spec.withEnv("POSTGRES_PASSWORD", "session-test").withEnv("POSTGRES_DB", "session_test")
|
||||
.withEntrypoint(List.of("docker-entrypoint.sh")).withCmd(List.of("postgres"));
|
||||
} else {
|
||||
spec.withEntrypoint(List.of("socat", "TCP-LISTEN:18080,reuseaddr,fork", "EXEC:cat"));
|
||||
}
|
||||
String id = lifecycle.createAndStartEphemeral(spec.build()).containerId();
|
||||
containers.add(id);
|
||||
String networkName = docker.inspectNetworkCmd().withNetworkId(network).exec().getName();
|
||||
String address = docker.inspectContainerCmd(id).exec().getNetworkSettings().getNetworks()
|
||||
.get(networkName).getIpAddress();
|
||||
String guestAddress = docker.inspectContainerCmd(guest).exec().getNetworkSettings().getNetworks()
|
||||
.get(networkName).getIpAddress();
|
||||
if (postgres) {
|
||||
// The image starts a temporary Unix socket server to initialise the database.
|
||||
await().atMost(Duration.ofSeconds(30))
|
||||
.until(() -> exec(id, "pg_isready -h 127.0.0.1 -U postgres", 3).exitCode() == 0);
|
||||
}
|
||||
return new RemoteTarget(id, address, guestAddress);
|
||||
}
|
||||
|
||||
ContainerExec.Result exec(String container, String script, int seconds) {
|
||||
return ContainerExec.run(docker, container, new String[]{"sh", "-c", script}, seconds);
|
||||
}
|
||||
|
||||
String successfulExec(String container, String script) {
|
||||
ContainerExec.Result result = exec(container, script, 15);
|
||||
assertEquals(0L, result.exitCode(), result.summary());
|
||||
return result.stdout();
|
||||
}
|
||||
|
||||
static String quote(String value) {
|
||||
return "'" + value.replace("'", "'\"'\"'") + "'";
|
||||
}
|
||||
|
||||
final class Session implements AutoCloseable {
|
||||
final SsmClient owner;
|
||||
final AccessKey credentials;
|
||||
final StartSessionResponse response;
|
||||
final String request;
|
||||
String clientContainer;
|
||||
boolean terminated;
|
||||
boolean closed;
|
||||
|
||||
Session(SsmClient owner, AccessKey credentials, StartSessionResponse response,
|
||||
String document, Map<String, List<String>> parameters) throws IOException {
|
||||
this.owner = owner;
|
||||
this.credentials = credentials;
|
||||
this.response = response;
|
||||
Map<String, Object> fields = new LinkedHashMap<>();
|
||||
fields.put("Target", instance);
|
||||
if (document != null) {
|
||||
fields.put("DocumentName", document);
|
||||
}
|
||||
fields.put("Parameters", parameters);
|
||||
request = JSON.writeValueAsString(fields);
|
||||
}
|
||||
|
||||
String pluginCommand() throws IOException {
|
||||
String payload = JSON.writeValueAsString(Map.of("SessionId", response.sessionId(),
|
||||
"StreamUrl", response.streamUrl(), "TokenValue", response.tokenValue()));
|
||||
String host = endpoint.getHost();
|
||||
return "env AWS_ACCESS_KEY_ID=" + quote(credentials.accessKeyId())
|
||||
+ " AWS_SECRET_ACCESS_KEY=" + quote(credentials.secretAccessKey())
|
||||
+ " AWS_DEFAULT_REGION=us-east-1 AWS_EC2_METADATA_DISABLED=true"
|
||||
+ " AWS_SSM_PLUGIN_ADDITIONAL_STREAM_HOSTS=" + quote(host)
|
||||
+ " session-manager-plugin " + quote(payload) + " us-east-1 StartSession '' "
|
||||
+ quote(request) + " " + quote(endpoint.toString());
|
||||
}
|
||||
|
||||
String clientContainer() {
|
||||
if (clientContainer == null) {
|
||||
clientContainer = container(List.of("sleep", "infinity"));
|
||||
}
|
||||
return clientContainer;
|
||||
}
|
||||
|
||||
String shell(String input) throws Exception {
|
||||
// Keep stdin open until the remote shell exits. The plugin returns immediately on local EOF.
|
||||
attach();
|
||||
send(input);
|
||||
awaitExit();
|
||||
return output();
|
||||
}
|
||||
|
||||
void attach() throws Exception {
|
||||
attach("");
|
||||
}
|
||||
|
||||
void attach(String environment) throws Exception {
|
||||
successfulExec(clientContainer(), "mkfifo /tmp/input; "
|
||||
+ "(exec 3<>/tmp/input; " + environment + " " + pluginCommand()
|
||||
+ " </tmp/input >/tmp/plugin.log 2>&1; echo $? >/tmp/plugin.exit) "
|
||||
+ ">/tmp/driver.log 2>&1 & echo $! >/tmp/plugin.pid");
|
||||
}
|
||||
|
||||
void send(String input) {
|
||||
successfulExec(clientContainer, "printf %s " + quote(input) + " > /tmp/input");
|
||||
}
|
||||
|
||||
String output() {
|
||||
return successfulExec(clientContainer, "cat /tmp/plugin.log");
|
||||
}
|
||||
|
||||
void awaitOutput(String marker) {
|
||||
await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
|
||||
String text = output();
|
||||
assertTrue(text.contains(marker), text);
|
||||
});
|
||||
}
|
||||
|
||||
void awaitExit() {
|
||||
await().atMost(Duration.ofSeconds(30)).untilAsserted(() ->
|
||||
assertEquals("0", successfulExec(clientContainer, "cat /tmp/plugin.exit").trim()));
|
||||
}
|
||||
|
||||
void terminate() {
|
||||
owner.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
terminated = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (clientContainer != null) {
|
||||
ContainerExec.Result result = exec(clientContainer, "cat /tmp/plugin.log 2>/dev/null || true", 5);
|
||||
Files.writeString(logs.resolve(response.sessionId() + ".log"), result.stdout() + result.stderr());
|
||||
}
|
||||
} finally {
|
||||
if (!terminated) {
|
||||
try {
|
||||
terminate();
|
||||
} catch (SsmException e) {
|
||||
if (!"ValidationException".equals(e.awsErrorDetails().errorCode())) {
|
||||
throw e;
|
||||
}
|
||||
// A shell that exited normally is already terminated.
|
||||
}
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
List<Executable> cleanup = new ArrayList<>();
|
||||
for (Session session : sessions) {
|
||||
cleanup.add(session::close);
|
||||
}
|
||||
if (instance != null) {
|
||||
cleanup.add(() -> {
|
||||
String id = instances.getInstance(REGION.id(), instance).orElseThrow().getDockerContainerId();
|
||||
ContainerExec.Result log = exec(id, "cat /var/log/amazon/ssm/amazon-ssm-agent.log", 5);
|
||||
Files.writeString(logs.resolve("agent.log"), log.stdout() + log.stderr());
|
||||
});
|
||||
cleanup.add(() -> {
|
||||
String id = instances.getInstance(REGION.id(), instance).orElseThrow().getDockerContainerId();
|
||||
ec2.terminateInstances(r -> r.instanceIds(instance));
|
||||
await().atMost(Duration.ofSeconds(30)).until(() -> docker.listContainersCmd()
|
||||
.withShowAll(true).withIdFilter(List.of(id)).exec().isEmpty());
|
||||
});
|
||||
}
|
||||
for (String container : containers) {
|
||||
cleanup.add(() -> lifecycle.removeIfExistsStrict(container, true));
|
||||
}
|
||||
for (String network : networks) {
|
||||
cleanup.add(() -> docker.removeNetworkCmd(network).exec());
|
||||
}
|
||||
for (String document : documents) {
|
||||
cleanup.add(() -> ssm.deleteDocument(r -> r.name(document)));
|
||||
}
|
||||
for (AccessKey key : users) {
|
||||
cleanup.add(() -> iam.deleteUserPolicy(r -> r.userName(key.userName()).policyName("sessions")));
|
||||
cleanup.add(() -> iam.deleteAccessKey(r -> r.userName(key.userName()).accessKeyId(key.accessKeyId())));
|
||||
cleanup.add(() -> iam.deleteUser(r -> r.userName(key.userName())));
|
||||
}
|
||||
if (profileCreated) {
|
||||
cleanup.add(() -> iam.removeRoleFromInstanceProfile(r -> r.instanceProfileName(name).roleName(name)));
|
||||
cleanup.add(() -> iam.deleteInstanceProfile(r -> r.instanceProfileName(name)));
|
||||
}
|
||||
if (roleCreated) {
|
||||
cleanup.add(() -> iam.detachRolePolicy(r -> r.roleName(name)
|
||||
.policyArn("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore")));
|
||||
cleanup.add(() -> iam.deleteRole(r -> r.roleName(name)));
|
||||
}
|
||||
try {
|
||||
assertAll("SSM fixture cleanup", cleanup);
|
||||
} finally {
|
||||
if (ssm != null) {
|
||||
ssm.close();
|
||||
}
|
||||
if (iam != null) {
|
||||
iam.close();
|
||||
}
|
||||
if (ec2 != null) {
|
||||
ec2.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.config.SelfSignedTlsProfile;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.TestAccounts;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.model.InstanceStateName;
|
||||
import software.amazon.awssdk.services.iam.model.AccessKey;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.InvocationDoesNotExistException;
|
||||
import software.amazon.awssdk.services.ssm.model.ResumeSessionResponse;
|
||||
import software.amazon.awssdk.services.ssm.model.Session;
|
||||
import software.amazon.awssdk.services.ssm.model.SsmException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
@TestProfile(SsmSessionManagerDockerNightlyIntegrationTest.Profile.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
@Timeout(120)
|
||||
class SsmSessionManagerDockerNightlyIntegrationTest {
|
||||
public static class Profile extends SelfSignedTlsProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
Map<String, String> settings = new HashMap<>(super.getConfigOverrides());
|
||||
settings.put("floci.services.ec2.mock", "false");
|
||||
Path catalog = Path.of("target/ssm-session-image-catalog.yaml").toAbsolutePath();
|
||||
try {
|
||||
String contents = Files.readString(Path.of("src/test/resources/ssm/session-manager/image-catalog.yaml"));
|
||||
if ("aarch64".equals(System.getProperty("os.arch"))) {
|
||||
contents = contents.replace("architecture: x86_64", "architecture: arm64");
|
||||
}
|
||||
Files.writeString(catalog, contents);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Cannot prepare the Session Manager test AMI catalogue", e);
|
||||
}
|
||||
settings.put("floci.services.ec2.image-catalog-path", catalog.toString());
|
||||
settings.put("floci.auth.validate-signatures", "true");
|
||||
settings.put("floci.services.iam.enforcement-enabled", "true");
|
||||
settings.put("floci.network.security-group-enforcement.enabled", "false");
|
||||
settings.put("floci.services.ec2.volume-block-devices", "false");
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
private static final String SHELL_DOCUMENT = """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream",
|
||||
"parameters":{"sample":{"type":"String","default":"example","allowedPattern":"^[a-z]+$"},
|
||||
"requiredSample":{"type":"String","allowedPattern":"^[a-z]+$"}},
|
||||
"inputs":{"runAsEnabled":false,"shellProfile":{"linux":
|
||||
"printf 'PROFILE=%s:%s\\n' '{{ sample }}' '{{ requiredSample }}'"}}}
|
||||
""";
|
||||
|
||||
@Inject DockerClient docker;
|
||||
@Inject ContainerBuilder builder;
|
||||
@Inject ContainerLifecycleManager lifecycle;
|
||||
@Inject Ec2Service instances;
|
||||
@Inject IamService identities;
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port") int tlsPort;
|
||||
@TestHTTPResource URI httpEndpoint;
|
||||
|
||||
private SsmSessionFixture fixture;
|
||||
|
||||
@BeforeAll
|
||||
@Timeout(720)
|
||||
void startGuest() throws Exception {
|
||||
fixture = new SsmSessionFixture(docker, builder, lifecycle, instances, httpEndpoint.getPort(), tlsPort);
|
||||
fixture.start();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
@Timeout(120)
|
||||
void stopGuest() throws Exception {
|
||||
if (fixture != null) {
|
||||
fixture.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellRunsInsideGuestAndExitsCleanly() throws Exception {
|
||||
String guestHostname = fixture.successfulExec(fixture.guest, "hostname").trim();
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
String output = session.shell("printf 'HOST=%s\\n' \"$(hostname)\"; printf 'USER=%s\\n' \"$(id -un)\"; exit\n");
|
||||
assertTrue(output.contains("HOST=" + guestHostname), output);
|
||||
assertTrue(output.contains("USER=ssm-user"), output);
|
||||
awaitHistory(session.response.sessionId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startListsSessionBeforeClientAttaches() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
Session listed = fixture.ssm.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("SessionId").value(session.response.sessionId())))
|
||||
.sessions().getFirst();
|
||||
assertEquals(session.response.sessionId(), listed.sessionId());
|
||||
assertEquals(fixture.instance, listed.target());
|
||||
assertEquals("Connected", listed.statusAsString());
|
||||
assertNotNull(listed.startDate());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectedSessionCanBeResumedWithoutClosingItsShell() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
session.attach();
|
||||
session.send("export CANARY=still-running; printf 'BEFORE=%s\\n' \"$CANARY\"\n");
|
||||
session.awaitOutput("BEFORE=still-running");
|
||||
ResumeSessionResponse resumed = fixture.ssm.resumeSession(
|
||||
r -> r.sessionId(session.response.sessionId()));
|
||||
assertEquals(session.response.sessionId(), resumed.sessionId());
|
||||
assertNotEquals(session.response.tokenValue(), resumed.tokenValue());
|
||||
session.send("printf 'AFTER=%s\\n' \"$CANARY\"; exit\n");
|
||||
session.awaitOutput("AFTER=still-running");
|
||||
session.awaitExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminationClosesAttachedClientAndPreventsResume() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
session.attach();
|
||||
session.send("printf 'READY=%s\\n' ready\n");
|
||||
session.awaitOutput("READY=ready");
|
||||
session.terminate();
|
||||
session.awaitExit();
|
||||
awaitHistory(session.response.sessionId());
|
||||
assertError("ValidationException", () -> fixture.ssm.resumeSession(r -> r.sessionId(session.response.sessionId())));
|
||||
assertError("ValidationException", () -> fixture.ssm.terminateSession(r -> r.sessionId(session.response.sessionId())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void simultaneousSessionsHaveIndependentShellState() throws Exception {
|
||||
try (SsmSessionFixture.Session first = fixture.startSession(null, Map.of());
|
||||
SsmSessionFixture.Session second = fixture.startSession(null, Map.of())) {
|
||||
assertNotEquals(first.response.sessionId(), second.response.sessionId());
|
||||
first.attach();
|
||||
second.attach();
|
||||
first.send("export CANARY=first; printf 'STATE=%s\\n' \"$CANARY\"\n");
|
||||
second.send("printf 'STATE=%s\\n' \"${CANARY-unset}\"; exit\n");
|
||||
first.awaitOutput("STATE=first");
|
||||
second.awaitOutput("STATE=unset");
|
||||
first.terminate();
|
||||
first.awaitExit();
|
||||
second.awaitExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void localForwardingCarriesConcurrentConnectionsToGuestLoopback() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession("AWS-StartPortForwardingSession",
|
||||
Map.of("portNumber", List.of("18080"), "localPortNumber", List.of("15432")))) {
|
||||
session.attach();
|
||||
session.awaitOutput("Port 15432 opened");
|
||||
assertEquals("firstsecond", forwardedEcho(session, "first", "second"));
|
||||
session.terminate();
|
||||
session.awaitExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void remoteForwardingReachesPrivateDestinationFromGuest() throws Exception {
|
||||
SsmSessionFixture.RemoteTarget target = fixture.remoteTarget(false);
|
||||
try (SsmSessionFixture.Session session = fixture.startSession("AWS-StartPortForwardingSessionToRemoteHost",
|
||||
Map.of("host", List.of(target.address()), "portNumber", List.of("18080"),
|
||||
"localPortNumber", List.of("15432")))) {
|
||||
assertNotEquals(0L, fixture.exec(session.clientContainer(),
|
||||
"printf direct | socat -T 1 - TCP:" + target.address() + ":18080,connect-timeout=1", 3).exitCode(),
|
||||
"Remote destination must not be directly reachable from the client");
|
||||
session.attach();
|
||||
session.awaitOutput("Port 15432 opened");
|
||||
assertEquals("firstsecond", forwardedEcho(session, "first", "second"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void postgresQueryTravelsThroughGuest() throws Exception {
|
||||
SsmSessionFixture.RemoteTarget target = fixture.remoteTarget(true);
|
||||
try (SsmSessionFixture.Session session = fixture.startSession("AWS-StartPortForwardingSessionToRemoteHost",
|
||||
Map.of("host", List.of(target.address()), "portNumber", List.of("5432"),
|
||||
"localPortNumber", List.of("15432")))) {
|
||||
session.attach();
|
||||
session.awaitOutput("Port 15432 opened");
|
||||
String output = fixture.successfulExec(session.clientContainer,
|
||||
"PGPASSWORD=session-test PGCONNECT_TIMEOUT=5 psql -h 127.0.0.1 -p 15432 "
|
||||
+ "-U postgres -d session_test -Atc 'select inet_client_addr(), 6 * 7'");
|
||||
assertEquals(target.guestAddress() + "|42", output.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sshAuthenticatesAndRunsCommandWithoutLocalTerminal() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession("AWS-StartSSHSession", Map.of())) {
|
||||
String client = session.clientContainer();
|
||||
fixture.successfulExec(client, "ssh-keygen -q -t ed25519 -N '' -f /tmp/client-key");
|
||||
String publicKey = fixture.successfulExec(client, "cat /tmp/client-key.pub");
|
||||
fixture.successfulExec(fixture.guest, "printf %s " + SsmSessionFixture.quote(publicKey)
|
||||
+ " > /home/session-test/.ssh/authorized_keys; chown -R session-test:session-test "
|
||||
+ "/home/session-test/.ssh; chmod 700 /home/session-test/.ssh; "
|
||||
+ "chmod 600 /home/session-test/.ssh/authorized_keys");
|
||||
String hostKey = fixture.successfulExec(fixture.guest, "cat /etc/ssh/ssh_host_ed25519_key.pub");
|
||||
fixture.successfulExec(client, "printf %s " + SsmSessionFixture.quote("session-target " + hostKey)
|
||||
+ " > /tmp/known_hosts; printf %s "
|
||||
+ SsmSessionFixture.quote("#!/bin/sh\nexec " + session.pluginCommand() + "\n")
|
||||
+ " > /tmp/proxy; chmod 700 /tmp/proxy");
|
||||
String output = fixture.successfulExec(client,
|
||||
"ssh -T -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=yes "
|
||||
+ "-o UserKnownHostsFile=/tmp/known_hosts -o ProxyCommand=/tmp/proxy "
|
||||
+ "-i /tmp/client-key session-test@session-target 'id -un'");
|
||||
assertEquals("session-test", output.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stockPluginResumesSameShellAfterTransportLoss() throws Exception {
|
||||
try (SessionConnectProxy proxy = new SessionConnectProxy(fixture.endpoint);
|
||||
SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
session.attach("HTTPS_PROXY=http://host.docker.internal:" + proxy.port()
|
||||
+ " HTTP_PROXY=http://host.docker.internal:" + proxy.port() + " NO_PROXY=");
|
||||
session.send("export CANARY=retained; printf 'SHELL=%s:%s\\n' \"$$\" \"$CANARY\"\n");
|
||||
await().atMost(Duration.ofSeconds(30)).until(() -> proxy.connections() > 0);
|
||||
session.awaitOutput(":retained");
|
||||
String before = session.output().lines().filter(line -> line.matches("SHELL=[0-9]+:retained\\r?"))
|
||||
.findFirst().orElseThrow().trim();
|
||||
int connections = proxy.connections();
|
||||
proxy.disconnect();
|
||||
await().atMost(Duration.ofSeconds(30)).until(() -> proxy.connections() > connections);
|
||||
session.send("printf 'SHELL=%s:%s\\n' \"$$\" \"$CANARY\"; exit\n");
|
||||
await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> assertEquals(2,
|
||||
session.output().lines().map(String::trim).filter(before::equals).count()));
|
||||
session.awaitExit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void runCommandStillWorksWithConnectedSessionAgent() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
session.attach();
|
||||
session.send("printf 'SESSION=%s\\n' connected\n");
|
||||
session.awaitOutput("SESSION=connected");
|
||||
String command = fixture.ssm.sendCommand(r -> r.instanceIds(fixture.instance)
|
||||
.documentName("AWS-RunShellScript").parameters(Map.of("commands", List.of("printf command-output"))))
|
||||
.command().commandId();
|
||||
await().ignoreException(InvocationDoesNotExistException.class).atMost(Duration.ofSeconds(30))
|
||||
.untilAsserted(() -> assertEquals("command-output",
|
||||
fixture.ssm.getCommandInvocation(r -> r.commandId(command).instanceId(fixture.instance))
|
||||
.standardOutputContent()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void customShellUsesDefaultAndSuppliedParameters() throws Exception {
|
||||
String document = fixture.document(SHELL_DOCUMENT, "Session");
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(document,
|
||||
Map.of("requiredSample", List.of("given")))) {
|
||||
assertTrue(session.shell("exit\n").contains("PROFILE=example:given"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void customPortDocumentAppliesDefaultPort() throws Exception {
|
||||
String document = fixture.document("""
|
||||
{"schemaVersion":"1.0","sessionType":"Port","parameters":{
|
||||
"portNumber":{"type":"String","default":"18080"},
|
||||
"localPortNumber":{"type":"String","default":"15432"}},
|
||||
"properties":{"type":"LocalPortForwarding","portNumber":"{{ portNumber }}",
|
||||
"localPortNumber":"{{ localPortNumber }}"}}
|
||||
""", "Session");
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(document, Map.of())) {
|
||||
session.attach();
|
||||
session.awaitOutput("Port 15432 opened");
|
||||
assertEquals("default-port", forwardedEcho(session, "default-port"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountShellPreferencesOverrideImplicitFallback() throws Exception {
|
||||
String name = "SSM-SessionManagerRunShell";
|
||||
fixture.ssm.createDocument(r -> r.name(name).documentType("Session").content("""
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream",
|
||||
"inputs":{"runAsEnabled":false,"shellProfile":{"linux":"export DEFAULT_CANARY=account-default"}}}
|
||||
"""));
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
assertTrue(session.shell("printf 'PREFERENCE=%s\\n' \"$DEFAULT_CANARY\"; exit\n")
|
||||
.contains("PREFERENCE=account-default"));
|
||||
} finally {
|
||||
fixture.ssm.deleteDocument(r -> r.name(name));
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Map<String, List<String>>> invalidParameters() {
|
||||
return Stream.of(Map.of(), Map.of("requiredSample", List.of("UPPER")),
|
||||
Map.of("requiredSample", List.of("a", "b")), Map.of("requiredSample", List.of()),
|
||||
Map.of("requiredSample", List.of("valid"), "unknown", List.of("value")),
|
||||
Map.of("RequiredSample", List.of("valid")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("invalidParameters")
|
||||
void rejectsInvalidDocumentParameters(Map<String, List<String>> parameters) {
|
||||
String document = fixture.document(SHELL_DOCUMENT, "Session");
|
||||
assertError("InvalidParameters", () -> fixture.ssm.startSession(r -> r.target(fixture.instance)
|
||||
.documentName(document).parameters(parameters)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitMissingDefaultDocumentIsNotImplicitShellFallback() {
|
||||
assertError("InvalidDocument", () -> fixture.ssm.startSession(r -> r.target(fixture.instance)
|
||||
.documentName("SSM-SessionManagerRunShell")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandDocumentCannotStartSession() {
|
||||
String document = fixture.document("{\"schemaVersion\":\"2.2\",\"mainSteps\":[]}", "Command");
|
||||
assertError("InvalidDocument", () -> fixture.ssm.startSession(r -> r.target(fixture.instance).documentName(document)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountCannotSeeOrStartSessionsForGuest() throws Exception {
|
||||
String account = TestAccounts.randomId();
|
||||
String user = fixture.name + "-foreign";
|
||||
// The emulator and SDK each define an AccessKey type.
|
||||
io.floci.aws.services.iam.model.AccessKey key = RequestScopes.callAs(account, () -> {
|
||||
identities.createUser(user, "/");
|
||||
identities.putUserPolicy(user, "sessions",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"ssm:*\",\"Resource\":\"*\"}]}");
|
||||
return identities.createAccessKey(user);
|
||||
});
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of());
|
||||
SsmClient other = AwsTestClients.create(SsmClient.builder(), key.getAccessKeyId(), key.getSecretAccessKey(),
|
||||
SsmSessionFixture.REGION, fixture.endpoint)) {
|
||||
assertTrue(other.describeSessions(r -> r.state("Active")).sessions().isEmpty());
|
||||
assertEquals("notconnected", other.getConnectionStatus(r -> r.target(fixture.instance)).statusAsString());
|
||||
assertError("TargetNotConnected", () -> other.startSession(r -> r.target(fixture.instance)));
|
||||
} finally {
|
||||
RequestScopes.runAs(account, () -> {
|
||||
identities.deleteUserPolicy(user, "sessions");
|
||||
identities.deleteAccessKey(user, key.getAccessKeyId());
|
||||
identities.deleteUser(user);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherRegionCannotSeeSessionsOrConnectToGuest() throws Exception {
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of());
|
||||
SsmClient other = AwsTestClients.create(SsmClient.builder(), fixture.operator.accessKeyId(),
|
||||
fixture.operator.secretAccessKey(), Region.EU_WEST_1, fixture.endpoint)) {
|
||||
assertTrue(other.describeSessions(r -> r.state("Active")).sessions().isEmpty());
|
||||
assertEquals("notconnected", other.getConnectionStatus(r -> r.target(fixture.instance)).statusAsString());
|
||||
assertError("TargetNotConnected", () -> other.startSession(r -> r.target(fixture.instance)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetPermissionAloneDoesNotAuthoriseImplicitDefaultDocument() {
|
||||
AccessKey user = fixture.createUser("{\"Effect\":\"Allow\",\"Action\":\"ssm:StartSession\",\"Resource\":\""
|
||||
+ targetArn() + "\"}");
|
||||
try (SsmClient restricted = fixture.client(user)) {
|
||||
assertError("AccessDeniedException", () -> restricted.startSession(r -> r.target(fixture.instance)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetAndAmazonOwnedDocumentPermissionsAuthoriseSession() throws Exception {
|
||||
AccessKey user = fixture.createUser("{\"Effect\":\"Allow\",\"Action\":\"ssm:StartSession\",\"Resource\":[\""
|
||||
+ targetArn() + "\",\"arn:aws:ssm:us-east-1::document/AWS-StartPortForwardingSession\"]},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"ssm:TerminateSession\",\"Resource\":\"*\"}");
|
||||
try (SsmClient restricted = fixture.client(user);
|
||||
SsmSessionFixture.Session session = fixture.startSession(restricted, user,
|
||||
"AWS-StartPortForwardingSession", Map.of())) {
|
||||
assertFalse(session.response.sessionId().isBlank());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void documentPermissionAloneDoesNotAuthoriseTarget() {
|
||||
AccessKey user = fixture.createUser("{\"Effect\":\"Allow\",\"Action\":\"ssm:StartSession\","
|
||||
+ "\"Resource\":\"arn:aws:ssm:us-east-1::document/AWS-StartSSHSession\"}");
|
||||
try (SsmClient restricted = fixture.client(user)) {
|
||||
assertError("AccessDeniedException", () -> restricted.startSession(r -> r.target(fixture.instance)
|
||||
.documentName("AWS-StartSSHSession")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitDocumentDenyOverridesSessionAllow() {
|
||||
AccessKey user = fixture.createUser("{\"Effect\":\"Allow\",\"Action\":\"ssm:*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"ssm:StartSession\","
|
||||
+ "\"Resource\":\"arn:aws:ssm:us-east-1::document/AWS-StartSSHSession\"}");
|
||||
try (SsmClient restricted = fixture.client(user)) {
|
||||
assertError("AccessDeniedException", () -> restricted.startSession(r -> r.target(fixture.instance)
|
||||
.documentName("AWS-StartSSHSession")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppedGuestRejectsNewSessionsAndReconnectsAfterRestart() throws Exception {
|
||||
fixture.ec2.stopInstances(r -> r.instanceIds(fixture.instance));
|
||||
try {
|
||||
awaitGuestState(InstanceStateName.STOPPED, "notconnected", Duration.ofSeconds(45));
|
||||
assertError("TargetNotConnected", () -> fixture.ssm.startSession(r -> r.target(fixture.instance)));
|
||||
} finally {
|
||||
fixture.ec2.startInstances(r -> r.instanceIds(fixture.instance));
|
||||
awaitGuestState(InstanceStateName.RUNNING, "connected", Duration.ofSeconds(60));
|
||||
}
|
||||
try (SsmSessionFixture.Session session = fixture.startSession(null, Map.of())) {
|
||||
assertTrue(session.shell("printf 'RESTORED=%s\\n' yes; exit\n").contains("RESTORED=yes"));
|
||||
}
|
||||
}
|
||||
|
||||
private void awaitGuestState(InstanceStateName state, String connectionStatus, Duration timeout) {
|
||||
await().atMost(timeout).untilAsserted(() -> {
|
||||
assertEquals(state, fixture.ec2.describeInstances(r -> r.instanceIds(fixture.instance))
|
||||
.reservations().getFirst().instances().getFirst().state().name());
|
||||
assertEquals(connectionStatus,
|
||||
fixture.ssm.getConnectionStatus(r -> r.target(fixture.instance)).statusAsString());
|
||||
});
|
||||
}
|
||||
|
||||
private String targetArn() {
|
||||
return "arn:aws:ec2:us-east-1:" + SsmSessionFixture.ACCOUNT + ":instance/" + fixture.instance;
|
||||
}
|
||||
|
||||
private String forwardedEcho(SsmSessionFixture.Session session, String... payloads) {
|
||||
// The plugin closes a multiplexed stream on local EOF. Keep all connections open through the reads.
|
||||
String probe = """
|
||||
sockets=()
|
||||
for payload in "$@"; do
|
||||
exec {socket}<>/dev/tcp/127.0.0.1/15432
|
||||
sockets+=("$socket")
|
||||
printf '%s' "$payload" >&"$socket"
|
||||
done
|
||||
index=0
|
||||
for payload in "$@"; do
|
||||
IFS= read -r -t 5 -N "${#payload}" -u "${sockets[$index]}" response
|
||||
printf '%s' "$response"
|
||||
index=$((index + 1))
|
||||
done
|
||||
""";
|
||||
String arguments = String.join(" ", Stream.of(payloads).map(SsmSessionFixture::quote).toList());
|
||||
return fixture.successfulExec(session.clientContainer(),
|
||||
"LC_ALL=C timeout 8s bash -ec " + SsmSessionFixture.quote(probe) + " echo-probe " + arguments);
|
||||
}
|
||||
|
||||
private void awaitHistory(String sessionId) {
|
||||
await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
|
||||
assertTrue(fixture.ssm.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("SessionId").value(sessionId))).sessions().isEmpty());
|
||||
List<Session> entries = fixture.ssm.describeSessions(r -> r.state("History")
|
||||
.filters(f -> f.key("SessionId").value(sessionId))).sessions();
|
||||
assertEquals(1, entries.size());
|
||||
Session history = entries.getFirst();
|
||||
assertEquals("Terminated", history.statusAsString());
|
||||
assertNotNull(history.endDate());
|
||||
});
|
||||
}
|
||||
|
||||
private static void assertError(String code, Executable action) {
|
||||
SsmException error = assertThrows(SsmException.class, action);
|
||||
assertEquals(code, error.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package io.floci.aws.services.ssm;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils.Arn;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.Node;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.SignedIamUsers;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.Session;
|
||||
import software.amazon.awssdk.services.ssm.model.StartSessionResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class SsmSessionPermissiveIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String TARGET = "i-fedcba98765432100";
|
||||
|
||||
@InjectMock SsmMessageGateway gateway;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"us-east-1, aws", "us-gov-west-1, aws-us-gov", "cn-north-1, aws-cn"})
|
||||
void arbitraryDummyKeyUsesPartitionRootOwner(String region, String partition) {
|
||||
connectGateway(ACCOUNT, region);
|
||||
try (SsmClient caller = AwsTestClients.create(SsmClient.builder(), "local", Region.of(region), endpoint)) {
|
||||
StartSessionResponse response = caller.startSession(r -> r.target(TARGET));
|
||||
try {
|
||||
assertOwner(caller, response.sessionId(), Arn.global(partition, "iam", ACCOUNT, "root").toString(), "root");
|
||||
assertEquals("initial-token", response.tokenValue());
|
||||
} finally {
|
||||
caller.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsignedCallerUsesDefaultAccountRootOwner() {
|
||||
connectGateway(ACCOUNT, "us-east-1");
|
||||
Response response = given().contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonSSM.StartSession")
|
||||
.body(("{\"Target\":\"" + TARGET + "\"}").getBytes(StandardCharsets.UTF_8)).post(endpoint);
|
||||
String sessionId = response.jsonPath().getString("SessionId");
|
||||
try (SsmClient admin = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1, endpoint)) {
|
||||
try {
|
||||
assertEquals(200, response.statusCode(), response.asString());
|
||||
assertOwner(admin, sessionId, Arn.global("aws", "iam", ACCOUNT, "root").toString(), "root");
|
||||
assertEquals("initial-token", response.jsonPath().getString("TokenValue"));
|
||||
} finally {
|
||||
if (sessionId != null) {
|
||||
admin.terminateSession(r -> r.sessionId(sessionId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"test", "123456789012"})
|
||||
void recognisedRootKeyRetainsRootOwnership(String key) {
|
||||
String account = "test".equals(key) ? ACCOUNT : key;
|
||||
connectGateway(account, "us-east-1");
|
||||
try (SsmClient caller = AwsTestClients.create(SsmClient.builder(), key, Region.US_EAST_1, endpoint)) {
|
||||
StartSessionResponse response = caller.startSession(r -> r.target(TARGET));
|
||||
try {
|
||||
assertOwner(caller, response.sessionId(), Arn.global("aws", "iam", account, "root").toString(), "root");
|
||||
} finally {
|
||||
caller.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamUserRetainsUserOwnership() throws Exception {
|
||||
connectGateway(ACCOUNT, "us-east-1");
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "ssm-owner-");
|
||||
SsmClient caller = AwsTestClients.create(SsmClient.builder(), user.accessKeyId(),
|
||||
user.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
StartSessionResponse response = caller.startSession(r -> r.target(TARGET));
|
||||
try {
|
||||
assertOwner(caller, response.sessionId(),
|
||||
Arn.global("aws", "iam", ACCOUNT, "user/" + user.name()).toString(), user.name());
|
||||
} finally {
|
||||
caller.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootOwnedSessionIsNotVisibleInAnotherAccount() {
|
||||
connectGateway("123456789012", "us-east-1");
|
||||
try (SsmClient owner = AwsTestClients.create(SsmClient.builder(), "123456789012", Region.US_EAST_1, endpoint);
|
||||
SsmClient other = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1, endpoint)) {
|
||||
StartSessionResponse response = owner.startSession(r -> r.target(TARGET));
|
||||
try {
|
||||
assertEquals(1, owner.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("SessionId").value(response.sessionId()))).sessions().size());
|
||||
assertTrue(other.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("SessionId").value(response.sessionId()))).sessions().isEmpty());
|
||||
} finally {
|
||||
owner.terminateSession(r -> r.sessionId(response.sessionId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void connectGateway(String account, String region) {
|
||||
when(gateway.isConnected(new Node(account, region, TARGET))).thenReturn(true);
|
||||
when(gateway.startSession(any(), any())).thenReturn("initial-token");
|
||||
}
|
||||
|
||||
private void assertOwner(SsmClient caller, String sessionId, String owner, String prefix) {
|
||||
List<Session> sessions = caller.describeSessions(r -> r.state("Active")
|
||||
.filters(f -> f.key("SessionId").value(sessionId))).sessions();
|
||||
assertEquals(1, sessions.size());
|
||||
assertEquals(owner, sessions.getFirst().owner());
|
||||
assertTrue(sessionId.startsWith(prefix + "-"), sessionId);
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
package io.floci.aws.services.ssm.session;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.ssm.SsmService;
|
||||
import io.floci.aws.services.ssm.model.SsmDocument;
|
||||
import io.floci.aws.services.ssm.session.SessionDocumentResolver.ResolvedDocument;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SessionDocumentResolverServiceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String DEFAULT = SessionDocumentResolver.DEFAULT_DOCUMENT_NAME;
|
||||
private static final String CUSTOM = "CustomSession";
|
||||
private static final int SESSION_DOCUMENT_BYTE_LIMIT = 65_536;
|
||||
|
||||
private static final String CUSTOM_SHELL = """
|
||||
schemaVersion: '1.0'
|
||||
sessionType: Standard_Stream
|
||||
parameters:
|
||||
requiredSample:
|
||||
type: String
|
||||
allowedPattern: '^[a-z]+$'
|
||||
sample:
|
||||
type: String
|
||||
default: example
|
||||
labels:
|
||||
type: StringList
|
||||
allowedPattern: '^[a-z]+$'
|
||||
default: [first, second]
|
||||
inputs:
|
||||
shellProfile:
|
||||
linux: 'echo {{ requiredSample }}'
|
||||
""";
|
||||
|
||||
private final SsmService ssm = mock(SsmService.class);
|
||||
private final RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
private final SessionDocumentResolver resolver = new SessionDocumentResolver(ssm, regionResolver);
|
||||
|
||||
@BeforeEach
|
||||
void setAccount() {
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentPreferencesFallBackToImplicitShell() {
|
||||
ResolvedDocument document = resolver.resolve(REGION, null, Map.of());
|
||||
assertEquals(DEFAULT, document.name());
|
||||
assertEquals("Standard_Stream", document.content().path("sessionType").asText());
|
||||
assertTrue(document.parameters().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitDefaultMustExistInAccount() {
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, DEFAULT, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void implicitDefaultReadsStoredAccountPreferences() {
|
||||
stored(DEFAULT, "Session", CUSTOM_SHELL);
|
||||
ResolvedDocument document = resolver.resolve(REGION, null, Map.of("requiredSample", List.of("given")));
|
||||
assertEquals("echo {{ requiredSample }}", document.content().at("/inputs/shellProfile/linux").asText());
|
||||
assertEquals("arn:aws:ssm:" + REGION + ":" + ACCOUNT + ":document/" + DEFAULT, document.arn());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"123456789012, CustomSession", "'', AWS-StartSSHSession"})
|
||||
void resolvesExplicitCanonicalDocumentArn(String account, String name) {
|
||||
stored(name, "Session", "{\"schemaVersion\":\"1.0\",\"sessionType\":\"Port\"}");
|
||||
String arn = "arn:aws:ssm:" + REGION + ":" + account + ":document/" + name;
|
||||
ResolvedDocument document = resolver.resolve(REGION, arn, Map.of());
|
||||
assertEquals(name, document.name());
|
||||
assertEquals(arn, document.arn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherAccountArnDoesNotResolveByLocalName() {
|
||||
stored(CUSTOM, "Session", CUSTOM_SHELL);
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION,
|
||||
"arn:aws:ssm:us-east-1:999999999999:document/" + CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesDefaultsAndConvertsScalarParametersForAgentDispatch() {
|
||||
stored(CUSTOM, "Session", CUSTOM_SHELL);
|
||||
ResolvedDocument document = resolver.resolve(REGION, CUSTOM, Map.of("requiredSample", List.of("given")));
|
||||
assertEquals(Map.of("requiredSample", "given", "sample", "example", "labels", List.of("first", "second")),
|
||||
document.parameters());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyListOverridesDocumentDefault() {
|
||||
stored(CUSTOM, "Session", CUSTOM_SHELL);
|
||||
ResolvedDocument document = resolver.resolve(REGION, CUSTOM,
|
||||
Map.of("requiredSample", List.of("given"), "labels", List.of()));
|
||||
assertEquals(List.of(), document.parameters().get("labels"));
|
||||
}
|
||||
|
||||
static Stream<Map<String, List<String>>> invalidParameters() {
|
||||
return Stream.of(Map.of(), Map.of("RequiredSample", List.of("given")),
|
||||
Map.of("requiredSample", List.of()), Map.of("requiredSample", List.of("first", "second")),
|
||||
Map.of("requiredSample", List.of("UPPER")),
|
||||
Map.of("requiredSample", List.of("given"), "labels", List.of("valid", "BAD")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("invalidParameters")
|
||||
void rejectsInvalidParameters(Map<String, List<String>> parameters) {
|
||||
stored(CUSTOM, "Session", CUSTOM_SHELL);
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, parameters));
|
||||
assertEquals("InvalidParameters", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNonSessionDocument() {
|
||||
stored(CUSTOM, "Command", "{\"schemaVersion\":\"2.2\",\"mainSteps\":[]}");
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ascii", "café glacé"})
|
||||
void acceptsStoredSessionAtUtf8ByteLimit(String description) {
|
||||
String source = sessionDocumentOfSize(description, SESSION_DOCUMENT_BYTE_LIMIT);
|
||||
stored(CUSTOM, "Session", source);
|
||||
|
||||
ResolvedDocument document = resolver.resolve(REGION, CUSTOM, Map.of());
|
||||
assertEquals(description, document.content().path("description").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ascii", "café glacé"})
|
||||
void rejectsStoredSessionOneUtf8ByteOverLimit(String description) {
|
||||
String source = sessionDocumentOfSize(description, SESSION_DOCUMENT_BYTE_LIMIT + 1);
|
||||
stored(CUSTOM, "Session", source);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsupportedSessionType() {
|
||||
stored(CUSTOM, "Session", "{\"schemaVersion\":\"1.0\",\"sessionType\":\"InteractiveCommands\"}");
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"allowedValues: [first] | outside its allowedValues",
|
||||
"minItems: 3 | violates minItems",
|
||||
"maxItems: 1 | violates maxItems",
|
||||
"minChars: 8 | violates minChars",
|
||||
"maxChars: 4 | violates maxChars"
|
||||
})
|
||||
void validatesDeclaredListConstraints(String declaration, String description) {
|
||||
stored(CUSTOM, "Session", """
|
||||
schemaVersion: '1.0'
|
||||
sessionType: Port
|
||||
parameters:
|
||||
labels:
|
||||
type: StringList
|
||||
%s
|
||||
""".formatted(declaration));
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> resolver.resolve(REGION, CUSTOM, Map.of("labels", List.of("first", "second"))));
|
||||
assertEquals("InvalidParameters", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains(description));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"[]", "\"shell\"", "42", "true", "null"})
|
||||
void rejectsPresentNonObjectInputs(String inputs) {
|
||||
stored(CUSTOM, "Session", """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream","inputs":%s}
|
||||
""".formatted(inputs));
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsEmptyInputsObject() {
|
||||
stored(CUSTOM, "Session", """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream","inputs":{}}
|
||||
""");
|
||||
ResolvedDocument document = resolver.resolve(REGION, CUSTOM, Map.of());
|
||||
assertTrue(document.content().path("inputs").isObject());
|
||||
assertTrue(document.content().path("inputs").isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"kmsKeyId", "s3BucketName", "cloudWatchLogGroupName"})
|
||||
void rejectsDocumentsRequiringUnsupportedEncryptionOrLogging(String setting) {
|
||||
stored(CUSTOM, "Session", """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream","inputs":{"%s":"example"}}
|
||||
""".formatted(setting));
|
||||
AwsException error = assertThrows(AwsException.class, () -> resolver.resolve(REGION, CUSTOM, Map.of()));
|
||||
assertEquals("InvalidDocument", error.getErrorCode());
|
||||
}
|
||||
|
||||
private void stored(String name, String type, String source) {
|
||||
when(ssm.findDocument(name, REGION)).thenReturn(Optional.of(new SsmDocument(name, source, type)));
|
||||
}
|
||||
|
||||
private static String sessionDocumentOfSize(String description, int bytes) {
|
||||
String document = """
|
||||
{"schemaVersion":"1.0","sessionType":"Standard_Stream","description":"%s"}
|
||||
""".formatted(description);
|
||||
String source = document + " ".repeat(bytes - document.getBytes(StandardCharsets.UTF_8).length);
|
||||
assertEquals(bytes, source.getBytes(StandardCharsets.UTF_8).length);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package io.floci.aws.services.ssm.session;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.ssm.session.SessionDocumentResolver.ResolvedDocument;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.Node;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceAccessMode;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
|
||||
class SsmSessionServiceTest {
|
||||
@Test
|
||||
void resolvedCallerInAnotherAccountCannotFallBackToRoot() {
|
||||
String account = "123456789012";
|
||||
String region = "us-east-1";
|
||||
String target = "i-fedcba98765432100";
|
||||
RequestContext context = mock(RequestContext.class);
|
||||
IamService iam = mock(IamService.class);
|
||||
SsmMessageGateway gateway = mock(SsmMessageGateway.class);
|
||||
when(context.getAccessKeyId()).thenReturn("foreign-user-key");
|
||||
when(iam.resolveCallerArn("foreign-user-key"))
|
||||
.thenReturn(Optional.of("arn:aws:iam::999999999999:user/foreign"));
|
||||
when(gateway.isConnected(new Node(account, region, target))).thenReturn(true);
|
||||
SsmSessionService service = new SsmSessionService(AccountAwareStorageBackend.inMemory(account), gateway,
|
||||
mock(SessionDocumentResolver.class), new RegionResolver(region, account), context, iam,
|
||||
Clock.systemUTC(), URI.create("http://localhost:4566"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.start(region, target, null, null, Map.of(), null));
|
||||
|
||||
assertEquals("AccessDeniedException", error.getErrorCode());
|
||||
assertTrue(service.describe(region, "Active", List.of(), null, null).items().isEmpty());
|
||||
assertTrue(service.describe(region, "History", List.of(), null, null).items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startingASessionDeletesHistoryOlderThanItsRetention() {
|
||||
String account = "123456789012";
|
||||
String region = "us-east-1";
|
||||
String target = "i-fedcba98765432100";
|
||||
RequestContext context = mock(RequestContext.class);
|
||||
IamService iam = mock(IamService.class);
|
||||
SsmMessageGateway gateway = mock(SsmMessageGateway.class);
|
||||
SessionDocumentResolver documents = mock(SessionDocumentResolver.class);
|
||||
when(context.getAccessKeyId()).thenReturn("operator-key");
|
||||
when(iam.resolveCallerArn("operator-key")).thenReturn(Optional.of("arn:aws:iam::123456789012:user/operator"));
|
||||
when(gateway.isConnected(new Node(account, region, target))).thenReturn(true);
|
||||
when(gateway.startSession(any(), any())).thenReturn("token");
|
||||
when(documents.resolve(region, null, Map.of())).thenReturn(new ResolvedDocument(
|
||||
"SSM-SessionManagerRunShell", "arn:aws:ssm:us-east-1:123456789012:document/SSM-SessionManagerRunShell",
|
||||
new ObjectMapper().createObjectNode(), Map.of()));
|
||||
AccountAwareStorageBackend<SsmSession> storage = AccountAwareStorageBackend.inMemory(account);
|
||||
MutableClock clock = new MutableClock();
|
||||
SsmSessionService service = new SsmSessionService(storage, gateway, documents,
|
||||
new RegionResolver(region, account), context, iam, clock, URI.create("http://localhost:4566"));
|
||||
|
||||
String first = service.start(region, target, null, null, Map.of(), null).sessionId();
|
||||
service.terminate(region, first);
|
||||
clock.advance(Duration.ofDays(29));
|
||||
String second = service.start(region, target, null, null, Map.of(), null).sessionId();
|
||||
assertEquals(2, storage.keys().size(), "a session that ended 29 days ago is still History");
|
||||
|
||||
clock.advance(Duration.ofDays(2));
|
||||
String third = service.start(region, target, null, null, Map.of(), null).sessionId();
|
||||
|
||||
assertEquals(Set.of(region + "|" + second, region + "|" + third), storage.keys());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.IamEnforcementFilter;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import io.floci.aws.testutil.AwsRequestSigner;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpVersion;
|
||||
import io.vertx.core.net.HostAndPort;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceAccessMode;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
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.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
|
||||
class ChannelAuthenticationTest {
|
||||
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final String INSTANCE = "i-0123456789abcdef0";
|
||||
private static final String KEY = "ASIAINSTANCE";
|
||||
private static final String SECRET = "instance-secret";
|
||||
private static final String TOKEN = "agent+session/token=";
|
||||
private static final String GATEWAY = "ssmmessages";
|
||||
private static final String CREATE = "ssmmessages:CreateControlChannel";
|
||||
private static final String SESSION_ARN = "arn:aws:ssm:eu-west-1:111122223333:session/example-session";
|
||||
private static final Instant NOW = Instant.parse("2026-11-23T21:00:00Z");
|
||||
private static final URI CONTROL = URI.create("http://localhost:4566/v1/control-channel/" + INSTANCE);
|
||||
private static final URI DATA = URI.create("http://localhost:4566/v1/data-channel/example-session");
|
||||
private static final byte[] BODY = "{\"MessageSchemaVersion\":\"1.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
private static final byte[] EMPTY = new byte[0];
|
||||
|
||||
private final IamService iam = mock(IamService.class);
|
||||
private final IamEnforcementFilter iamEnforcement = mock(IamEnforcementFilter.class);
|
||||
private final ChannelAuthentication authentication = new ChannelAuthentication(iam, new AccountResolver(ACCOUNT),
|
||||
iamEnforcement, Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
@Test
|
||||
void signedAgentPostIdentifiesTheInstanceFromItsImdsCredential() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = agentRequest(HttpMethod.POST, CONTROL, BODY, GATEWAY);
|
||||
assertEquals(new ChannelAuthentication.AgentIdentity(ACCOUNT, REGION, INSTANCE),
|
||||
authentication.authenticateAgent(request, BODY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedAgentPostAcceptsHttp2AuthorityAsTheSignedHost() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = http2AgentPost(CONTROL.getHost());
|
||||
|
||||
assertEquals(new ChannelAuthentication.AgentIdentity(ACCOUNT, REGION, INSTANCE),
|
||||
authentication.authenticateAgent(request, BODY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheHttp2AuthorityInvalidatesTheSignature() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = http2AgentPost("other-host");
|
||||
|
||||
assertThrows(AwsException.class, () -> authentication.authenticateAgent(request, BODY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedAgentUpgradeUsesTheSameIdentityBinding() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = agentRequest(HttpMethod.GET, DATA, EMPTY, GATEWAY);
|
||||
assertEquals(Optional.of(new ChannelAuthentication.AgentIdentity(ACCOUNT, REGION, INSTANCE)),
|
||||
authentication.authenticateAgentUpgradeIfClaimed(request, "ssmmessages:OpenDataChannel", SESSION_ARN));
|
||||
// OpenDataChannel acts on the session, so a deny on one session's ARN reaches the agent too.
|
||||
verify(iamEnforcement).authorizeRequestParameters(anyString(), eq("ssmmessages:OpenDataChannel"),
|
||||
eq(SESSION_ARN), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheAgentPostBodyInvalidatesItsSignature() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = agentRequest(HttpMethod.POST, CONTROL, BODY, GATEWAY);
|
||||
assertThrows(AwsException.class, () -> authentication.authenticateAgent(request, EMPTY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedNonImdsCredentialCannotActAsAnAgent() throws Exception {
|
||||
when(iam.findSecretKey(KEY, TOKEN)).thenReturn(Optional.of(SECRET));
|
||||
HttpServerRequest request = agentRequest(HttpMethod.POST, CONTROL, BODY, GATEWAY);
|
||||
assertThrows(AwsException.class, () -> authentication.authenticateAgent(request, BODY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void agentCredentialsSignedForAnotherServiceAreRefused() throws Exception {
|
||||
instanceCredentials();
|
||||
HttpServerRequest request = agentRequest(HttpMethod.POST, CONTROL, BODY, "ssm");
|
||||
assertThrows(AwsException.class, () -> authentication.authenticateAgent(request, BODY, CREATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPresignedClientUpgradeResolvesItsIdentity() throws Exception {
|
||||
when(iam.resolveAccountId(KEY)).thenReturn(Optional.of(ACCOUNT));
|
||||
when(iam.findSecretKey(KEY, TOKEN)).thenReturn(Optional.of(SECRET));
|
||||
URI presigned = signer(KEY, SECRET, GATEWAY).presignedUri("GET", DATA,
|
||||
Map.of("X-Amz-Security-Token", TOKEN), EMPTY);
|
||||
assertEquals(Optional.of(KEY),
|
||||
authentication.authorizeClient(request(HttpMethod.GET, presigned, Map.of()), ACCOUNT, REGION, SESSION_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeaderSignedClientUpgradeMustMatchTheGrantAccount() throws Exception {
|
||||
when(iam.resolveAccountId(KEY)).thenReturn(Optional.of(ACCOUNT));
|
||||
when(iam.findSecretKey(KEY, TOKEN)).thenReturn(Optional.of(SECRET));
|
||||
HttpServerRequest signed = agentRequest(HttpMethod.GET, DATA, EMPTY, GATEWAY);
|
||||
assertThrows(AwsException.class, () -> authentication.authorizeClient(signed, "444455556666", REGION, SESSION_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartialSigningClaimIsRefused() {
|
||||
URI partial = URI.create(DATA + "?X-Amz-Signature=invalid");
|
||||
HttpServerRequest request = request(HttpMethod.GET, partial, Map.of());
|
||||
assertThrows(AwsException.class, () -> authentication.authorizeClient(request, ACCOUNT, REGION, SESSION_ARN));
|
||||
}
|
||||
|
||||
private void instanceCredentials() {
|
||||
when(iam.findEc2InstanceIdentity(KEY, TOKEN)).thenReturn(Optional.of(
|
||||
new IamService.Ec2InstanceIdentity(ACCOUNT, INSTANCE)));
|
||||
when(iam.findSecretKey(KEY, TOKEN)).thenReturn(Optional.of(SECRET));
|
||||
}
|
||||
|
||||
private static HttpServerRequest agentRequest(HttpMethod method, URI uri, byte[] body, String service)
|
||||
throws Exception {
|
||||
Map<String, String> headers = signer(KEY, SECRET, service).headersFor(method.name(), uri,
|
||||
Map.of("x-amz-security-token", TOKEN), body);
|
||||
headers.put("X-Amz-Security-Token", TOKEN);
|
||||
return request(method, uri, headers);
|
||||
}
|
||||
|
||||
private static HttpServerRequest http2AgentPost(String authorityHost) throws Exception {
|
||||
Map<String, String> bodyHeaders = Map.of("content-type", "application/json",
|
||||
"content-length", Integer.toString(BODY.length), "x-amz-security-token", TOKEN);
|
||||
Map<String, String> signed = signer(KEY, SECRET, GATEWAY).headersFor("POST", CONTROL, bodyHeaders, BODY);
|
||||
HttpServerRequest request = request(HttpMethod.POST, CONTROL, signed);
|
||||
request.headers().remove("Host").addAll(bodyHeaders);
|
||||
when(request.version()).thenReturn(HttpVersion.HTTP_2);
|
||||
when(request.authority()).thenReturn(HostAndPort.create(authorityHost, CONTROL.getPort()));
|
||||
return request;
|
||||
}
|
||||
|
||||
private static AwsRequestSigner signer(String key, String secret, String service) {
|
||||
return AwsRequestSigner.signedAs(key, secret, service).inRegion(REGION).signedAt(NOW);
|
||||
}
|
||||
|
||||
private static HttpServerRequest request(HttpMethod method, URI uri, Map<String, String> signed) {
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", uri.getAuthority()).addAll(signed);
|
||||
HttpServerRequest request = mock(HttpServerRequest.class);
|
||||
when(request.method()).thenReturn(method);
|
||||
when(request.path()).thenReturn(uri.getRawPath());
|
||||
when(request.query()).thenReturn(uri.getRawQuery());
|
||||
when(request.headers()).thenReturn(headers);
|
||||
when(request.getHeader("Authorization")).thenReturn(headers.get("Authorization"));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
package io.floci.aws.services.ssmmessages;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.IamEnforcementFilter;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.Node;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionRequest;
|
||||
import io.floci.aws.services.ssmmessages.SsmMessageGateway.SessionState;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import io.floci.aws.testutil.AwsRequestSigner;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.UpgradeRejectedException;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
import io.vertx.core.http.WebSocketConnectOptions;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.Router;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceAccessMode;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
|
||||
class SsmMessageGatewayServiceTest {
|
||||
|
||||
private static final Node NODE = new Node("000000000000", "us-east-1", "i-0123456789abcdef0");
|
||||
private static final Node ANOTHER_NODE = new Node("000000000000", "us-east-1", "i-00000000000000000");
|
||||
private static final String SECRET = "instance-profile-secret";
|
||||
private static final String SECURITY_TOKEN = "instance+profile/token=";
|
||||
private static final String SECURITY_TOKEN_HEADER = "X-Amz-Security-Token";
|
||||
private static final byte[] EMPTY_BODY = new byte[0];
|
||||
private static final String CONTROL_PATH = "/v1/control-channel/" + NODE.instanceId();
|
||||
private static final String SESSION_ID = "operator-abcd";
|
||||
private static final String SESSION_ARN = "arn:aws:ssm:us-east-1:000000000000:session/" + SESSION_ID;
|
||||
private static final String DATA_PATH = DataChannelRouter.CHANNEL_PATH_PREFIX + SESSION_ID;
|
||||
private static final String DATA_ROLE = "publish_subscribe";
|
||||
private static final String OPEN_DATA_PATH = DATA_PATH + "?role=" + DATA_ROLE;
|
||||
private static final String OPEN_DATA_ACTION = "ssmmessages:OpenDataChannel";
|
||||
|
||||
private final Vertx vertx = Vertx.vertx();
|
||||
private final HttpClient client = vertx.createHttpClient();
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final MutableClock clock = new MutableClock();
|
||||
private final IamEnforcementFilter iamEnforcement = mock(IamEnforcementFilter.class);
|
||||
private final SsmMessageGateway gateway = new SsmMessageGateway(mapper, vertx, clock);
|
||||
private final BlockingQueue<SessionState> states = new LinkedBlockingQueue<>();
|
||||
private int port;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws Exception {
|
||||
gateway.scheduleExpiry();
|
||||
IamService iam = mock(IamService.class);
|
||||
registerInstanceCredentials(iam, NODE);
|
||||
registerInstanceCredentials(iam, ANOTHER_NODE);
|
||||
ChannelAuthentication auth = new ChannelAuthentication(iam, new AccountResolver(NODE.accountId()),
|
||||
iamEnforcement, clock);
|
||||
Router router = Router.router(vertx);
|
||||
SsmMessageGatewayRoutes routes = new SsmMessageGatewayRoutes(gateway, auth, mapper, true);
|
||||
new DataChannelRouter(List.of(routes)).init(router);
|
||||
routes.init(router);
|
||||
port = result(vertx.createHttpServer().requestHandler(router).listen(0)).actualPort();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeServer() throws Exception {
|
||||
gateway.shutdown();
|
||||
result(vertx.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void controlChannelIsOnlineOnlyOnceTheOpeningTokenIsValidated() throws Exception {
|
||||
TestPeer invalid = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
String grant = createGrant(CONTROL_PATH);
|
||||
invalid.open("incorrect", false);
|
||||
assertEquals(1008, invalid.closed());
|
||||
assertFalse(gateway.isConnected(NODE));
|
||||
|
||||
TestPeer valid = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
valid.open(grant, false);
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> gateway.isConnected(NODE));
|
||||
result(valid.socket.close());
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> !gateway.isConnected(NODE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceCannotMintAnotherInstancesControlGrant() throws Exception {
|
||||
ChannelResponse response = createChannel(CONTROL_PATH, ANOTHER_NODE);
|
||||
assertEquals(403, response.statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingControlConnectionRejectsSessionStart() {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> gateway.startSession(sessionRequest(), states::add));
|
||||
assertEquals("TargetNotConnected", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startDispatchesTheDocumentAndTypedParametersInAnInteractiveShellTask() throws Exception {
|
||||
TestPeer control = connectControl();
|
||||
gateway.startSession(sessionRequest(), states::add);
|
||||
|
||||
AgentMessage dispatch = AgentMessage.decode(control.next().getBytes());
|
||||
assertEquals("interactive_shell", dispatch.messageType());
|
||||
JsonNode envelope = mapper.readTree(dispatch.payloadAsString());
|
||||
assertEquals("StartSession", envelope.path("Topic").asText());
|
||||
assertEquals(SESSION_ID, envelope.path("TaskId").asText());
|
||||
JsonNode content = mapper.readTree(envelope.path("Content").asText());
|
||||
assertEquals(sessionRequest().documentContent(), content.path("DocumentContent"));
|
||||
assertEquals(mapper.valueToTree(sessionRequest().parameters()), content.path("Parameters"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void dataFromEitherPeerReachesTheOtherUnchanged(boolean agentFirst) throws Exception {
|
||||
String pluginGrant = start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
TestPeer first = dataPeer(agentFirst ? NODE : null);
|
||||
first.open(agentFirst ? agentGrant : pluginGrant, agentFirst);
|
||||
byte[] original = AgentMessage.outbound(agentFirst ? "output_stream_data" : "input_stream_data",
|
||||
9, 1, new byte[] {-1, 0, 12, 14}).encode();
|
||||
first.send(Buffer.buffer(original));
|
||||
|
||||
TestPeer second = dataPeer(agentFirst ? null : NODE);
|
||||
second.open(agentFirst ? pluginGrant : agentGrant, !agentFirst);
|
||||
assertArrayEquals(original, second.next().getBytes());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void instanceProfileClientCanOpenDataChannel(boolean targetsOwnInstance) throws Exception {
|
||||
String clientGrant = start();
|
||||
TestPeer clientPeer = dataPeer(targetsOwnInstance ? NODE : ANOTHER_NODE);
|
||||
|
||||
assertClientReceivesAgentOutput(clientPeer, clientGrant);
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedInstanceProfileClientCanOpenDataChannel() throws Exception {
|
||||
String clientGrant = start();
|
||||
URI presigned = signer(NODE).presignedUri("GET", requestUri(DATA_PATH),
|
||||
Map.of("role", DATA_ROLE, SECURITY_TOKEN_HEADER, SECURITY_TOKEN), EMPTY_BODY);
|
||||
TestPeer clientPeer = connect(presigned.getRawPath() + "?" + presigned.getRawQuery(), Map.of());
|
||||
|
||||
assertClientReceivesAgentOutput(clientPeer, clientGrant);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedClientCannotOpenDataChannelWithoutSessionPermission() throws Exception {
|
||||
String clientGrant = start();
|
||||
denyOpenOn(SESSION_ARN);
|
||||
|
||||
assertDataOpenDenied(NODE, clientGrant, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceCannotClaimAnAgentGrantForAnotherInstance() throws Exception {
|
||||
start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
|
||||
assertDataOpenDenied(ANOTHER_NODE, agentGrant, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsignedPeerCannotClaimAnAgentGrantByNamingTheTargetInstance() throws Exception {
|
||||
start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
|
||||
assertDataOpenDenied(null, agentGrant, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetInstanceCannotOpenAgentChannelWhenDeniedOnTheSession() throws Exception {
|
||||
start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
denyOpenOn(SESSION_ARN);
|
||||
|
||||
assertDataOpenDenied(NODE, agentGrant, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetInstanceCannotOpenAgentChannelWithWrongToken() throws Exception {
|
||||
start();
|
||||
createGrant(DATA_PATH);
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open("incorrect", true);
|
||||
|
||||
assertEquals(1008, agent.closed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientCannotClaimTheAgentGrant() throws Exception {
|
||||
start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
|
||||
TestPeer clientUsingAgentGrant = dataPeer(null);
|
||||
clientUsingAgentGrant.open(agentGrant, false);
|
||||
assertEquals(1008, clientUsingAgentGrant.closed());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void agentWithNoClientIdCanClaimItsDataGrant(String clientId) throws Exception {
|
||||
String pluginGrant = start();
|
||||
String agentGrant = createGrant(DATA_PATH, clientId);
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(agentGrant, true, clientId);
|
||||
TestPeer plugin = dataPeer(null);
|
||||
plugin.open(pluginGrant, false);
|
||||
|
||||
Buffer output = message("output_stream_data", Map.of("payload", "stock agent output"));
|
||||
agent.send(output);
|
||||
assertEquals(output, plugin.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
void agentCannotClaimAGrantIssuedForADifferentClientId() throws Exception {
|
||||
start();
|
||||
String agentGrant = createGrant(DATA_PATH);
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(agentGrant, true, "other-client-id");
|
||||
|
||||
assertEquals(1008, agent.closed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshingAClientGrantKeepsTheOldSocketUntilTheNewGrantIsClaimed() throws Exception {
|
||||
String pluginGrant = start();
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(createGrant(DATA_PATH), true);
|
||||
TestPeer current = dataPeer(null);
|
||||
current.open(pluginGrant, false);
|
||||
agent.send(message("agent_session_state", Map.of("SessionId", SESSION_ID, "SessionState", "Connected")));
|
||||
assertEquals(SessionState.CONNECTED, states.poll(10, TimeUnit.SECONDS));
|
||||
|
||||
String replacement = gateway.resumeSession(NODE, SESSION_ID).orElseThrow();
|
||||
assertNotEquals(pluginGrant, replacement);
|
||||
Buffer frame = message("output_stream_data", Map.of("payload", "before-replace"));
|
||||
agent.send(frame);
|
||||
assertEquals(frame, current.next());
|
||||
|
||||
TestPeer stale = dataPeer(null);
|
||||
stale.open(pluginGrant, false);
|
||||
assertEquals(1008, stale.closed());
|
||||
|
||||
TestPeer resumed = dataPeer(null);
|
||||
resumed.open(replacement, false);
|
||||
assertEquals(1000, current.closed());
|
||||
Buffer after = message("output_stream_data", Map.of("payload", "after-replace"));
|
||||
agent.send(after);
|
||||
assertEquals(after, resumed.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completedTaskIsAcknowledgedAndClosesTheClientChannel() throws Exception {
|
||||
TestPeer control = connectControl();
|
||||
String pluginGrant = gateway.startSession(sessionRequest(), states::add);
|
||||
control.next();
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(createGrant(DATA_PATH), true);
|
||||
TestPeer plugin = dataPeer(null);
|
||||
plugin.open(pluginGrant, false);
|
||||
agent.send(message("agent_session_state", Map.of("SessionId", SESSION_ID, "SessionState", "Connected")));
|
||||
assertEquals(SessionState.CONNECTED, states.poll(10, TimeUnit.SECONDS));
|
||||
|
||||
Buffer complete = message("agent_task_complete", Map.of("TaskId", SESSION_ID, "Topic", "agent_task_complete",
|
||||
"FinalTaskStatus", "Success"));
|
||||
control.send(complete);
|
||||
AgentMessage reply = AgentMessage.decode(control.next().getBytes());
|
||||
assertEquals("agent_task_acknowledge", reply.messageType());
|
||||
assertEquals(AgentMessage.decode(complete.getBytes()).messageId().toString(),
|
||||
mapper.readTree(reply.payloadAsString()).path("MessageId").asText());
|
||||
|
||||
Buffer tail = message("output_stream_data", Map.of("payload", "last output"));
|
||||
agent.send(tail);
|
||||
result(agent.socket.close());
|
||||
assertEquals(tail, plugin.next());
|
||||
assertEquals("channel_closed", AgentMessage.decode(plugin.next().getBytes()).messageType());
|
||||
assertEquals(SessionState.TERMINATED, states.poll(10, TimeUnit.SECONDS));
|
||||
assertTrue(gateway.resumeSession(NODE, SESSION_ID).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredControlGrantCannotMakeTheNodeOnline() throws Exception {
|
||||
String grant = createGrant(CONTROL_PATH);
|
||||
clock.advance(Duration.ofMinutes(6));
|
||||
TestPeer control = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
control.open(grant, false);
|
||||
assertEquals(1008, control.closed());
|
||||
assertFalse(gateway.isConnected(NODE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectedSessionOutlivesTheOpeningGrant() throws Exception {
|
||||
DataPeers peers = connectedPeers();
|
||||
clock.advance(Duration.ofMinutes(6));
|
||||
|
||||
Buffer data = message("output_stream_data", Map.of("payload", "after-grant-expiry"));
|
||||
peers.agent.send(data);
|
||||
assertEquals(data, peers.plugin.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disconnectedSessionExpiresAndAsksTheAgentToStop() throws Exception {
|
||||
DataPeers peers = connectedPeers();
|
||||
result(peers.plugin.socket.close());
|
||||
assertEquals(SessionState.DISCONNECTED, states.poll(10, TimeUnit.SECONDS));
|
||||
|
||||
clock.advance(Duration.ofMinutes(6));
|
||||
assertEquals(AgentMessage.CHANNEL_CLOSED, AgentMessage.decode(peers.control.next().getBytes()).messageType());
|
||||
assertEquals(SessionState.FAILED, states.poll(10, TimeUnit.SECONDS));
|
||||
assertTrue(gateway.resumeSession(NODE, SESSION_ID).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetClosesRegisteredAndOpeningSocketsAndRejectsPriorGrants() throws Exception {
|
||||
DataPeers peers = connectedPeers();
|
||||
TestPeer opening = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
String priorGrant = createGrant(CONTROL_PATH);
|
||||
gateway.beforeReset();
|
||||
gateway.clear();
|
||||
gateway.afterReset();
|
||||
|
||||
assertEquals(1000, peers.control.closed());
|
||||
assertEquals(1000, peers.agent.closed());
|
||||
assertEquals(1000, peers.plugin.closed());
|
||||
assertEquals(1000, opening.closed());
|
||||
assertFalse(gateway.isConnected(NODE));
|
||||
assertTrue(gateway.resumeSession(NODE, SESSION_ID).isEmpty());
|
||||
|
||||
TestPeer replay = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
replay.open(priorGrant, false);
|
||||
assertEquals(1008, replay.closed());
|
||||
}
|
||||
|
||||
private DataPeers connectedPeers() throws Exception {
|
||||
TestPeer control = connectControl();
|
||||
String grant = gateway.startSession(sessionRequest(), states::add);
|
||||
control.next();
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(createGrant(DATA_PATH), true);
|
||||
TestPeer plugin = dataPeer(null);
|
||||
plugin.open(grant, false);
|
||||
agent.send(message("agent_session_state", Map.of("SessionId", SESSION_ID, "SessionState", "Connected")));
|
||||
assertEquals(SessionState.CONNECTED, states.poll(10, TimeUnit.SECONDS));
|
||||
return new DataPeers(control, agent, plugin);
|
||||
}
|
||||
|
||||
private record DataPeers(TestPeer control, TestPeer agent, TestPeer plugin) { }
|
||||
|
||||
private TestPeer connectControl() throws Exception {
|
||||
TestPeer control = connect(CONTROL_PATH + "?role=subscribe", NODE);
|
||||
control.open(createGrant(CONTROL_PATH), false);
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> gateway.isConnected(NODE));
|
||||
return control;
|
||||
}
|
||||
|
||||
private String start() throws Exception {
|
||||
TestPeer control = connectControl();
|
||||
String grant = gateway.startSession(sessionRequest(), states::add);
|
||||
control.next();
|
||||
return grant;
|
||||
}
|
||||
|
||||
private SessionRequest sessionRequest() {
|
||||
String accountArn = "arn:aws:iam::000000000000:user/operator";
|
||||
return new SessionRequest(SESSION_ID, SESSION_ARN, accountArn, NODE, "document",
|
||||
mapper.createObjectNode().put("sessionType", "Port"), Map.of("host", "name", "list", List.of("value")));
|
||||
}
|
||||
|
||||
private ChannelResponse createChannel(String path, Node signer) throws Exception {
|
||||
return createChannel(path, signer, "client-id");
|
||||
}
|
||||
|
||||
private ChannelResponse createChannel(String path, Node signer, String clientId) throws Exception {
|
||||
JsonObject body = new JsonObject().put("MessageSchemaVersion", "1.0").put("RequestId", "request-id");
|
||||
if (clientId != null) {
|
||||
body.put("ClientId", clientId);
|
||||
}
|
||||
String encoded = body.encode();
|
||||
Map<String, String> headers = signedHeaders("POST", path, signer, encoded.getBytes(StandardCharsets.UTF_8));
|
||||
return result(client.request(HttpMethod.POST, port, "localhost", path).compose(req -> {
|
||||
headers.forEach(req::putHeader);
|
||||
Future<ChannelResponse> response = req.response().compose(reply -> reply.body()
|
||||
.map(payload -> new ChannelResponse(reply.statusCode(), payload.toString())));
|
||||
return req.end(encoded).compose(ignored -> response);
|
||||
}));
|
||||
}
|
||||
|
||||
private String createGrant(String path) throws Exception {
|
||||
return createGrant(path, "client-id");
|
||||
}
|
||||
|
||||
private String createGrant(String path, String clientId) throws Exception {
|
||||
ChannelResponse response = createChannel(path, NODE, clientId);
|
||||
assertEquals(201, response.statusCode());
|
||||
String token = XmlParser.extractFirst(response.body(), "TokenValue", "");
|
||||
assertFalse(token.isEmpty(), () -> "A successful channel response must contain a token: " + response.body());
|
||||
return token;
|
||||
}
|
||||
|
||||
private record ChannelResponse(int statusCode, String body) { }
|
||||
|
||||
private TestPeer dataPeer(Node signer) throws Exception {
|
||||
return connect(OPEN_DATA_PATH, signer);
|
||||
}
|
||||
|
||||
private TestPeer connect(String path, Node signer) throws Exception {
|
||||
return connect(path, signer == null ? Map.of() : signedHeaders("GET", path, signer, EMPTY_BODY));
|
||||
}
|
||||
|
||||
private TestPeer connect(String path, Map<String, String> headers) throws Exception {
|
||||
WebSocketConnectOptions options = new WebSocketConnectOptions().setPort(port).setHost("localhost").setURI(path);
|
||||
headers.forEach(options::addHeader);
|
||||
return new TestPeer(result(client.webSocket(options)));
|
||||
}
|
||||
|
||||
private void assertClientReceivesAgentOutput(TestPeer clientPeer, String clientGrant) throws Exception {
|
||||
TestPeer agent = dataPeer(NODE);
|
||||
agent.open(createGrant(DATA_PATH), true);
|
||||
clientPeer.open(clientGrant, false);
|
||||
|
||||
Buffer output = message("output_stream_data", Map.of("payload", "agent output"));
|
||||
agent.send(output);
|
||||
assertEquals(output, clientPeer.next());
|
||||
}
|
||||
|
||||
private void assertDataOpenDenied(Node signer, String grant, boolean agent) throws Exception {
|
||||
TestPeer peer;
|
||||
try {
|
||||
peer = dataPeer(signer);
|
||||
} catch (ExecutionException failure) {
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(403, rejected.getStatus());
|
||||
return;
|
||||
}
|
||||
peer.open(grant, agent);
|
||||
assertEquals(1008, peer.closed());
|
||||
}
|
||||
|
||||
private void denyOpenOn(String resource) {
|
||||
doThrow(new AwsException("AccessDeniedException", "OpenDataChannel denied by IAM", 403))
|
||||
.when(iamEnforcement).authorizeRequestParameters(anyString(), eq(OPEN_DATA_ACTION), eq(resource), any());
|
||||
}
|
||||
|
||||
private URI requestUri(String path) {
|
||||
return URI.create("http://localhost:" + port + path);
|
||||
}
|
||||
|
||||
private Map<String, String> signedHeaders(String method, String path, Node node, byte[] body) throws Exception {
|
||||
Map<String, String> headers = signer(node).headersFor(method, requestUri(path),
|
||||
Map.of("x-amz-security-token", SECURITY_TOKEN), body);
|
||||
headers.put(SECURITY_TOKEN_HEADER, SECURITY_TOKEN);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private AwsRequestSigner signer(Node node) {
|
||||
return AwsRequestSigner.signedAs(instanceAccessKey(node), SECRET, ChannelAuthentication.SIGNING_SERVICE)
|
||||
.inRegion(node.region()).signedAt(clock.instant());
|
||||
}
|
||||
|
||||
private static String instanceAccessKey(Node node) {
|
||||
return "ASIA" + node.instanceId().substring(2);
|
||||
}
|
||||
|
||||
private static void registerInstanceCredentials(IamService iam, Node node) {
|
||||
String key = instanceAccessKey(node);
|
||||
when(iam.findEc2InstanceIdentity(key, SECURITY_TOKEN)).thenReturn(Optional.of(
|
||||
new IamService.Ec2InstanceIdentity(node.accountId(), node.instanceId())));
|
||||
when(iam.findSecretKey(key, SECURITY_TOKEN)).thenReturn(Optional.of(SECRET));
|
||||
when(iam.resolveAccountId(key)).thenReturn(Optional.of(node.accountId()));
|
||||
}
|
||||
|
||||
private Buffer message(String kind, Object value) throws Exception {
|
||||
return Buffer.buffer(AgentMessage.outbound(kind, 0, 0, mapper.writeValueAsBytes(value)).encode());
|
||||
}
|
||||
|
||||
private static <T> T result(Future<T> future) throws Exception {
|
||||
return future.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static final class TestPeer {
|
||||
private final WebSocket socket;
|
||||
private final BlockingQueue<Buffer> received = new LinkedBlockingQueue<>();
|
||||
private final CompletableFuture<Short> close = new CompletableFuture<>();
|
||||
|
||||
private TestPeer(WebSocket socket) {
|
||||
this.socket = socket;
|
||||
socket.binaryMessageHandler(received::add);
|
||||
socket.closeHandler(ignored -> close.complete(socket.closeStatusCode()));
|
||||
}
|
||||
|
||||
void open(String token, boolean agent) throws Exception {
|
||||
open(token, agent, "client-id");
|
||||
}
|
||||
|
||||
void open(String token, boolean agent, String clientId) throws Exception {
|
||||
JsonObject request = new JsonObject().put("MessageSchemaVersion", "1.0")
|
||||
.put("RequestId", "request-id").put("TokenValue", token);
|
||||
if (clientId != null) {
|
||||
request.put("ClientId", clientId);
|
||||
}
|
||||
if (agent) {
|
||||
request.put("ClientInstanceId", NODE.instanceId());
|
||||
}
|
||||
result(socket.writeTextMessage(request.encode()));
|
||||
}
|
||||
|
||||
void send(Buffer frame) throws Exception {
|
||||
result(socket.writeBinaryMessage(frame));
|
||||
}
|
||||
|
||||
Buffer next() throws InterruptedException {
|
||||
Buffer next = received.poll(10, TimeUnit.SECONDS);
|
||||
assertNotNull(next, () -> "the peer must receive a frame (close code " + socket.closeStatusCode()
|
||||
+ ", reason: " + socket.closeReason() + ")");
|
||||
return next;
|
||||
}
|
||||
|
||||
short closed() throws Exception {
|
||||
return close.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
systemd systemd-sysv ca-certificates curl iproute2 procps openssh-server openssh-client socat postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN agent_arch="$(dpkg --print-architecture)" \
|
||||
&& case "$agent_arch" in arm64) plugin_arch=arm64;; amd64) plugin_arch=64bit;; *) exit 1;; esac \
|
||||
&& curl -fsSL "https://s3.us-east-1.amazonaws.com/amazon-ssm-us-east-1/3.3.5828.0/debian_${agent_arch}/amazon-ssm-agent.deb" -o /tmp/agent.deb \
|
||||
&& curl -fsSL "https://s3.amazonaws.com/session-manager-downloads/plugin/1.2.896.0/ubuntu_${plugin_arch}/session-manager-plugin.deb" -o /tmp/plugin.deb \
|
||||
&& apt-get install -y /tmp/agent.deb /tmp/plugin.deb \
|
||||
&& rm /tmp/agent.deb /tmp/plugin.deb \
|
||||
&& systemctl disable amazon-ssm-agent.service
|
||||
RUN useradd -m -s /bin/sh session-test && passwd -d session-test \
|
||||
&& mkdir -p /run/sshd /home/session-test/.ssh \
|
||||
&& printf 'PasswordAuthentication no\nPermitRootLogin no\n' > /etc/ssh/sshd_config.d/session-test.conf
|
||||
@@ -0,0 +1,9 @@
|
||||
defaultDockerImage: floci-ssm-session-test:local
|
||||
images:
|
||||
- imageId: ami-0f10c155a90000001
|
||||
dockerImage: floci-ssm-session-test:local
|
||||
name: ssm-session-test
|
||||
description: Linux guest with the stock SSM Agent
|
||||
architecture: x86_64
|
||||
creationDate: "2026-11-23T00:00:00.000Z"
|
||||
guestRuntime: systemd
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Vendor AWS's Session Manager request and permission examples for the IAM tables."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = "https://docs.aws.amazon.com/systems-manager/latest"
|
||||
DEFAULT_PAGE = f"{ROOT}/userguide/getting-started-default-session-document.html"
|
||||
HYBRID_PAGE = f"{ROOT}/userguide/systems-manager-hybrid-multicloud.html"
|
||||
SESSIONS_PAGE = f"{ROOT}/userguide/session-manager-working-with-sessions-start.html"
|
||||
API_PAGES = {name: f"{ROOT}/APIReference/API_{name}.html" for name in ("StartSession", "GetConnectionStatus")}
|
||||
PAGES = (DEFAULT_PAGE, HYBRID_PAGE, SESSIONS_PAGE, *API_PAGES.values())
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "tools/aws/sources/ssm-session-permissions.json"
|
||||
|
||||
|
||||
def blocks(page: str, tag: str) -> list[str]:
|
||||
"""Copy the contents of a paragraph or code block without the surrounding HTML."""
|
||||
return [html.unescape(re.sub(r"<[^>]+>", "", fragment)).strip()
|
||||
for fragment in re.findall(rf"<{tag}\b[^>]*>(.*?)</{tag}>", page, re.S)]
|
||||
|
||||
|
||||
def one(values: Iterable[str], page: str, description: str) -> str:
|
||||
found = list(values)
|
||||
if len(found) != 1:
|
||||
raise ValueError(f"{page}: expected one {description}, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def sample_request(page: str, operation: str, url: str) -> dict[str, object]:
|
||||
block = one((block for block in blocks(page, "pre")
|
||||
if f"X-Amz-Target: AmazonSSM.{operation}\n" in block), url, "sample request")
|
||||
_, separator, body = block.partition("\n\n")
|
||||
if not separator:
|
||||
raise ValueError(f"{url}: sample request has no body")
|
||||
request = json.loads(body)
|
||||
if not isinstance(request, dict):
|
||||
raise ValueError(f"{url}: sample request body is not a JSON object")
|
||||
return request
|
||||
|
||||
|
||||
def build(pages: Mapping[str, str]) -> dict[str, object]:
|
||||
paragraphs = [" ".join(block.split()) for block in blocks(pages[DEFAULT_PAGE], "p")]
|
||||
default_sentences = one((p for p in paragraphs if "This is the default session document." in p),
|
||||
DEFAULT_PAGE, "default document description")
|
||||
default_use = one((p for p in paragraphs if p.startswith("By default, Session Manager uses")),
|
||||
DEFAULT_PAGE, "default document usage")
|
||||
permission_sentence = one((p for p in paragraphs if p.startswith("To start a default shell session,")),
|
||||
DEFAULT_PAGE, "default shell permission description")
|
||||
default_blocks = blocks(pages[DEFAULT_PAGE], "pre")
|
||||
command = one((block for block in default_blocks if block.startswith("aws ssm ")), DEFAULT_PAGE, "CLI example")
|
||||
policy = one((block for block in default_blocks if '"Statement"' in block), DEFAULT_PAGE, "IAM policy example")
|
||||
|
||||
prefixes = one((" ".join(p.split()) for p in blocks(pages[HYBRID_PAGE], "p")
|
||||
if "managed nodes are distinguished from Amazon EC2 instances" in " ".join(p.split())),
|
||||
HYBRID_PAGE, "managed node ID prefix description")
|
||||
ecs_command = next((block for block in blocks(pages[SESSIONS_PAGE], "pre")
|
||||
if block.startswith("aws ssm ") and "--target ecs:" in block), None)
|
||||
if ecs_command is None:
|
||||
raise ValueError(f"{SESSIONS_PAGE}: missing ECS CLI example")
|
||||
|
||||
return {
|
||||
"_source": {
|
||||
"pages": list(PAGES),
|
||||
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
||||
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
"note": "The default session document description, CLI and IAM policy examples, managed node ID "
|
||||
"prefixes, an ECS CLI example and the API reference sample request bodies.",
|
||||
},
|
||||
"defaultDescription": default_sentences,
|
||||
"defaultUse": default_use,
|
||||
"defaultPermission": permission_sentence,
|
||||
"defaultCommand": command,
|
||||
"defaultPolicy": json.loads(policy),
|
||||
"managedNodePrefixes": prefixes,
|
||||
"ecsCommand": ecs_command,
|
||||
"sessionRequests": {name: sample_request(pages[url], name, url) for name, url in API_PAGES.items()},
|
||||
}
|
||||
|
||||
|
||||
def fetch_url(url: str) -> str:
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
return response.read().decode("utf-8")
|
||||
|
||||
|
||||
def fetch_all(fetch: Callable[[str], str] = fetch_url) -> tuple[dict[str, str]]:
|
||||
return ({url: fetch(url) for url in PAGES},)
|
||||
|
||||
|
||||
def stale(vendored: Mapping[str, object], pages: Mapping[str, str]) -> bool:
|
||||
"""Whether AWS gives different facts, ignoring the retrieval date."""
|
||||
built = build(pages)
|
||||
return any(vendored.get(key) != value for key, value in built.items() if key != "_source")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None, fetch: Callable[[str], str] = fetch_url) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
pages, = fetch_all(fetch)
|
||||
if args.verify:
|
||||
if stale(json.loads(OUTPUT.read_text(encoding="utf-8")), pages):
|
||||
print(f"error: {OUTPUT.name} no longer matches AWS; run {Path(__file__).name}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{OUTPUT.name} matches the AWS Session Manager documentation")
|
||||
else:
|
||||
OUTPUT.write_text(json.dumps(build(pages), indent=2) + "\n", encoding="utf-8")
|
||||
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)}")
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"error: could not vendor AWS Session Manager permissions ({e})", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -339,6 +339,7 @@ import fetch_ec2_id_examples
|
||||
import fetch_iam_identifiers
|
||||
import fetch_kms_api_permissions
|
||||
import fetch_required_resource_types
|
||||
import fetch_ssm_session_permissions
|
||||
from regen_iam_authorized_actions import (ROUTES as ROUTES_FILE, authorized_actions, fetch_references,
|
||||
load_s3_required, s3_query_parameters, s3_version_choices,
|
||||
vendored_sections)
|
||||
@@ -547,7 +548,8 @@ PATH_SOURCES: dict[str, Path] = {
|
||||
# an operation acts on where its request does not say ("If you do not specify a user name, IAM determines the user name
|
||||
# implicitly based on the AWS access key ID used to sign the request to this operation"; "must have permission to
|
||||
# change the role group with the old name and the new name"); tools/aws/fetch_iam_identifiers.py vendors those pages
|
||||
# and `with_paths`, `with_renames`, `with_signing_user`, `with_same_as_arn` and `with_formats` read them. Each file is
|
||||
# and `with_paths`, `with_renames`, `with_signing_user`, `with_same_as_arn` and `with_formats` read them. For SSM,
|
||||
# the Session Manager guide and API examples identify the EC2 target and implicit shell document. Each file is
|
||||
# written by its own script from the pages, unchanged, and the generator only reads it: nothing about an operation is
|
||||
# stated here.
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
@@ -555,12 +557,14 @@ PERMISSION_SOURCES: dict[str, Path] = {
|
||||
"kms": REPO_ROOT / "tools/aws/sources/kms-api-permissions.json",
|
||||
"dynamodb": REPO_ROOT / "tools/aws/sources/dynamodb-permissions.json",
|
||||
"iam": REPO_ROOT / "tools/aws/sources/iam-identifiers.json",
|
||||
"ssm": REPO_ROOT / "tools/aws/sources/ssm-session-permissions.json",
|
||||
}
|
||||
# The script that writes each namespace's permission source, whose pages `verify_sources` reads it against.
|
||||
PERMISSION_FETCHERS = {
|
||||
"kms": fetch_kms_api_permissions,
|
||||
"dynamodb": fetch_dynamodb_permissions,
|
||||
"iam": fetch_iam_identifiers,
|
||||
"ssm": fetch_ssm_session_permissions,
|
||||
}
|
||||
|
||||
# Fetched API response examples supplement the identifier prefixes in botocore.
|
||||
@@ -653,6 +657,7 @@ NOT_COVERED: dict[str, str] = {
|
||||
"named in the path",
|
||||
"ses": _LATER,
|
||||
"signin": _REST,
|
||||
"ssmmessages": "channel routes authorise agent and client resources directly rather than through generated request mappings",
|
||||
"sso-oauth": _REST,
|
||||
"swf": "not read yet: the Service Reference gives a domain's ARN no Region, `swf::<account>:/domain/<name>`, "
|
||||
"while the SWF Developer Guide gives it as arn:aws:swf:Region:AccountID:/domain/DomainName, as Floci mints "
|
||||
@@ -2951,6 +2956,8 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
resources = with_signing_user(resources, operation, types, of_operation("signingUser"), models)
|
||||
resources = with_same_as_arn(resources, operation, types, of_operation("sameAsArn"), formats, models)
|
||||
resources = with_formats(resources, operation, types, of_operation("formats"), models)
|
||||
if namespace_of(operation) == "ssm" and source is not None:
|
||||
resources = session_permissions(resources, operation, source, types, formats, models)
|
||||
uses = MEASURED.get(operation, (None, ""))[0]
|
||||
# An entry naming only another action AWS checks gives the operation no resources of its own.
|
||||
if uses is not None and not (uses and all("action" in use for use in uses)):
|
||||
@@ -3467,6 +3474,82 @@ def _held_shapes(models: dict[str, dict], member: str) -> set[str]:
|
||||
if shape.get("type") == "structure" for name, held in shape.get("members", {}).items() if name == member}
|
||||
|
||||
|
||||
def session_permissions(resources: list[dict], operation: str, source: dict, types: list[str],
|
||||
formats: dict[str, str], models: dict[str, dict]) -> list[dict]:
|
||||
"""Join the EC2 CLI and policy examples to the scalar API member the two sample requests share."""
|
||||
requests = source.get("sessionRequests", {})
|
||||
if requests.keys() != fetch_ssm_session_permissions.API_PAGES.keys():
|
||||
raise ValueError("SSM Session Manager evidence is missing an API sample request")
|
||||
name = operation.split(":", 1)[1]
|
||||
if name not in requests:
|
||||
return resources
|
||||
|
||||
# The reader handles EC2 IDs. The guide distinguishes hybrid IDs and the ECS command has a composite target.
|
||||
prefixes = source.get("managedNodePrefixes", "")
|
||||
if not re.search(r'distinguished from Amazon EC2 instances with the prefix "[a-z]+-"\. '
|
||||
r'Amazon EC2 instance IDs use the prefix "i-"\.', prefixes) \
|
||||
or not re.search(r"--target ecs:<[^>]+>_<[^>]+>_<[^>]+>", source.get("ecsCommand", "")):
|
||||
raise ValueError(f"{operation}: the SSM guide no longer distinguishes EC2, hybrid and ECS targets")
|
||||
cli = re.fullmatch(r"aws ssm ([a-z-]+)\s+--([a-z-]+) (i-[A-Za-z0-9]+)",
|
||||
source.get("defaultCommand", "").replace("\\\n", ""))
|
||||
if cli is None:
|
||||
raise ValueError(f"{operation}: the SSM default shell command must name only an EC2 target")
|
||||
start = "".join(word.title() for word in cli[1].split("-"))
|
||||
if start not in requests:
|
||||
raise ValueError(f"{operation}: the SSM default shell command has no API sample")
|
||||
candidates = [member for member, value in requests[start].items() if member.lower() == cli[2]
|
||||
and value == cli[3]]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f"{operation}: the SSM CLI target does not match its API sample")
|
||||
target = candidates[0]
|
||||
target_shape = _request_shapes(models, start).get(target)
|
||||
sample_target = requests[name].get(target)
|
||||
if not target_shape or _request_shapes(models, name).get(target) != target_shape \
|
||||
or any(model["shapes"].get(target_shape, {}).get("type") != "string" for model in models.values()) \
|
||||
or target in optional_members(models, name) \
|
||||
or not isinstance(sample_target, str) or not re.fullmatch(r"i-[A-Za-z0-9]+", sample_target):
|
||||
raise ValueError(f"{operation}: the SSM API sample has no EC2 target of the shared scalar shape")
|
||||
|
||||
action = f"ssm:{start}"
|
||||
arns = {arn for statement in source.get("defaultPolicy", {}).get("Statement", [])
|
||||
if statement.get("Effect") == "Allow" and set(statement.get("Action", [])) == {action}
|
||||
and "Condition" not in statement for arn in statement.get("Resource", [])}
|
||||
instances = [example_type(arn, formats, action)[0] for arn in arns
|
||||
if re.fullmatch(r"arn:[^:]+:ec2:[^:]+:[0-9]{12}:instance/[^:/]+", arn)]
|
||||
if len(instances) != 1 or instances[0] not in types:
|
||||
raise ValueError(f"{operation}: the SSM policy example has no single EC2 type allowed by the reference")
|
||||
target_rule = {"types": instances, "through": target}
|
||||
if name != start:
|
||||
return [*resources, target_rule]
|
||||
return [*with_session_default(resources, operation, source, types, formats, models, requests[name], arns),
|
||||
target_rule]
|
||||
|
||||
|
||||
def with_session_default(resources: list[dict], operation: str, source: dict, types: list[str],
|
||||
formats: dict[str, str], models: dict[str, dict], request: dict[str, object],
|
||||
arns: set[str]) -> list[dict]:
|
||||
"""Mark the omitted document member whose account-owned default appears in the policy example."""
|
||||
default = re.search(r"called ([A-Za-z0-9_-]+)\. This is the default session document\.",
|
||||
source.get("defaultDescription", ""))
|
||||
if default is None or "default session document when a user starts a session by using an AWS CLI command" \
|
||||
not in source.get("defaultUse", "") or "must specify the default session document in the IAM policy" \
|
||||
not in source.get("defaultPermission", ""):
|
||||
raise ValueError(f"{operation}: the SSM guide no longer identifies a required default document")
|
||||
documents = [example_type(arn, formats, operation) for arn in arns
|
||||
if re.fullmatch(r"arn:[^:]+:ssm:[^:]+:[0-9]{12}:document/" + re.escape(default[1]), arn)]
|
||||
if len(documents) != 1 or documents[0][0] not in types:
|
||||
raise ValueError(f"{operation}: the SSM policy example has no account-owned default document")
|
||||
kind, variables = documents[0]
|
||||
optional = optional_members(models, operation.split(":", 1)[1])
|
||||
defaulted = {member: kind for resource in resources if resource.get("type") == kind
|
||||
for variable, member in resource.get("fill", {}).items()
|
||||
if variable in variables and member in optional and member not in request}
|
||||
with_defaults = with_documented_defaults(resources, formats, defaulted)
|
||||
if len(defaulted) != 1 or with_defaults == resources:
|
||||
raise ValueError(f"{operation}: the default document does not match an omitted request member")
|
||||
return with_defaults
|
||||
|
||||
|
||||
def permission_resources(operation: str, checked_as: str, resources: list[dict], row: dict | None,
|
||||
known: dict[str, list[str]], formats: dict[str, str],
|
||||
models: dict[str, dict]) -> tuple[list[dict], dict | None]:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"_source": {
|
||||
"pages": [
|
||||
"https://docs.aws.amazon.com/systems-manager/latest/userguide/getting-started-default-session-document.html",
|
||||
"https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-hybrid-multicloud.html",
|
||||
"https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html",
|
||||
"https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartSession.html",
|
||||
"https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetConnectionStatus.html"
|
||||
],
|
||||
"fetcher": "tools/aws/fetch_ssm_session_permissions.py",
|
||||
"retrieved": "2026-11-25",
|
||||
"note": "The default session document description, CLI and IAM policy examples, managed node ID prefixes, an ECS CLI example and the API reference sample request bodies."
|
||||
},
|
||||
"defaultDescription": "When you configure Session Manager for your AWS account or when you change session preferences in the Systems Manager console, the system creates an SSM session document called SSM-SessionManagerRunShell. This is the default session document. Session Manager uses this document to store your session preferences, which include information like the following:",
|
||||
"defaultUse": "By default, Session Manager uses the default session document when a user starts a session from the AWS Management Console. This applies to either Fleet Manager or Session Manager in the Systems Manager console, or EC2 Connect in the Amazon EC2 console. Session Manager also uses the default session document when a user starts a session by using an AWS CLI command like the following example:",
|
||||
"defaultPermission": "To start a default shell session, you must specify the default session document in the IAM policy, as shown in the following example.",
|
||||
"defaultCommand": "aws ssm start-session \\\n --target i-02573cafcfEXAMPLE",
|
||||
"defaultPolicy": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "EnableSSMSession",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"ssm:StartSession"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:ec2:us-east-1:111122223333:instance/instance-id",
|
||||
"arn:aws:ssm:us-east-1:111122223333:document/SSM-SessionManagerRunShell"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"ssmmessages:OpenDataChannel"
|
||||
],
|
||||
"Resource": [
|
||||
"*"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"managedNodePrefixes": "After you finish configuring your non-EC2 machines for Systems Manager as described in this section, your hybrid-activated machines are listed in the AWS Management Console and described as managed nodes. In the console, the IDs of your hybrid-activated managed nodes are distinguished from Amazon EC2 instances with the prefix \"mi-\". Amazon EC2 instance IDs use the prefix \"i-\".",
|
||||
"ecsCommand": "aws ssm start-session \\\n --target ecs:<ECS_cluster_name>_<ECS_container_ID>_<container_runtime_ID> \\\n --document-name AWS-StartPortForwardingSessionToRemoteHost \\\n --parameters '{\"host\":[\"URL\"],\"portNumber\":[\"port_number\"], \"localPortNumber\":[\"port_number\"]}'",
|
||||
"sessionRequests": {
|
||||
"StartSession": {
|
||||
"Target": "i-02573cafcfEXAMPLE"
|
||||
},
|
||||
"GetConnectionStatus": {
|
||||
"Target": "i-02573cafcfEXAMPLE"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Tests for the AWS Session Manager documentation extract."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import fetch_ssm_session_permissions as f
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages() -> dict[str, str]:
|
||||
default = """
|
||||
<p>The system creates a document called <code>SSM-SessionManagerRunShell</code>.
|
||||
This is the default session document.</p>
|
||||
<p>By default, Session Manager uses the default session document when a user starts a session by using an
|
||||
AWS CLI command like the following example:</p>
|
||||
<p>To start a default shell session, you must specify the default session document in the IAM policy.</p>
|
||||
<pre><code>aws ssm start-session --target i-02573cafcfEXAMPLE</code></pre>
|
||||
<pre><code><span>{</span>"Statement": [{"Effect": "Allow", "Action": ["ssm:StartSession"],
|
||||
"Resource": ["arn:aws:ec2:us-east-1:111122223333:instance/<code>instance-id</code>",
|
||||
"arn:aws:ssm:us-east-1:111122223333:document/SSM-SessionManagerRunShell"]}]}</code></pre>
|
||||
"""
|
||||
return {
|
||||
f.DEFAULT_PAGE: default,
|
||||
f.HYBRID_PAGE: '<p>Hybrid managed nodes are distinguished from Amazon EC2 instances with the prefix "mi-". '
|
||||
'Amazon EC2 instance IDs use the prefix "i-".</p>',
|
||||
f.SESSIONS_PAGE: "<pre><code>aws ssm start-session --target ecs:<cluster>_<container>_<id>"
|
||||
"</code></pre>",
|
||||
**{url: f'<pre><code>POST / HTTP/1.1\nX-Amz-Target: AmazonSSM.{operation}\n'
|
||||
'\n<span>{</span>"Target": "i-02573cafcfEXAMPLE"}</code></pre>'
|
||||
for operation, url in f.API_PAGES.items()},
|
||||
}
|
||||
|
||||
|
||||
def test_extract_copies_the_guide_facts_and_api_requests(pages: dict[str, str]) -> None:
|
||||
source = f.build(pages)
|
||||
assert source["_source"]["pages"] == list(pages)
|
||||
assert source["defaultDescription"] == (
|
||||
"The system creates a document called SSM-SessionManagerRunShell. This is the default session document."
|
||||
)
|
||||
assert source["defaultPolicy"]["Statement"][0]["Resource"] == [
|
||||
"arn:aws:ec2:us-east-1:111122223333:instance/instance-id",
|
||||
"arn:aws:ssm:us-east-1:111122223333:document/SSM-SessionManagerRunShell",
|
||||
]
|
||||
assert source["defaultCommand"] == "aws ssm start-session --target i-02573cafcfEXAMPLE"
|
||||
assert source["sessionRequests"] == {name: {"Target": "i-02573cafcfEXAMPLE"} for name in f.API_PAGES}
|
||||
assert source["managedNodePrefixes"].endswith('Amazon EC2 instance IDs use the prefix "i-".')
|
||||
assert source["ecsCommand"] == "aws ssm start-session --target ecs:<cluster>_<container>_<id>"
|
||||
|
||||
|
||||
def test_changed_api_example_makes_the_extract_stale(pages: dict[str, str]) -> None:
|
||||
source = f.build(pages)
|
||||
assert not f.stale(source, pages)
|
||||
page = f.API_PAGES["GetConnectionStatus"]
|
||||
pages[page] = pages[page].replace("i-02573cafcfEXAMPLE", "mi-02573cafcfEXAMPLE")
|
||||
assert f.stale(source, pages)
|
||||
|
||||
|
||||
def test_missing_policy_example_fails_extraction(pages: dict[str, str]) -> None:
|
||||
pages[f.DEFAULT_PAGE] = pages[f.DEFAULT_PAGE].replace('"Statement"', '"Other"')
|
||||
with pytest.raises(ValueError, match="IAM policy example"):
|
||||
f.build(pages)
|
||||
|
||||
|
||||
def test_missing_api_sample_request_fails_extraction(pages: dict[str, str]) -> None:
|
||||
pages[f.API_PAGES["GetConnectionStatus"]] = "<pre>{}</pre>"
|
||||
with pytest.raises(ValueError, match="sample request"):
|
||||
f.build(pages)
|
||||
@@ -3758,3 +3758,78 @@ def test_the_vendored_ec2_examples_give_tag_calls_the_endpoint_prefix_and_leave_
|
||||
"vpc-endpoint": "vpce-"}
|
||||
assert r.id_targets("ec2:DeleteVpcEndpoints", ["vpc-endpoint"], formats, models, merged) == \
|
||||
r.id_targets("ec2:DeleteVpcEndpoints", ["vpc-endpoint"], formats, models, known)
|
||||
|
||||
|
||||
SSM_SESSION_FORMATS = {
|
||||
"document": "arn:${Partition}:ssm:${Region}:${Account}:document/${DocumentName}",
|
||||
"instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}",
|
||||
"managed-instance": "arn:${Partition}:ssm:${Region}:${Account}:managed-instance/${InstanceId}",
|
||||
"task": "arn:${Partition}:ecs:${Region}:${Account}:task/${TaskId}",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session_models() -> dict[str, dict]:
|
||||
return {"ssm": {
|
||||
"metadata": {"protocol": "json"},
|
||||
"operations": {operation: {"input": {"shape": operation + "Request"}}
|
||||
for operation in ("StartSession", "GetConnectionStatus", "SendCommand")},
|
||||
"shapes": {
|
||||
"StartSessionRequest": {"type": "structure", "required": ["Target"], "members": {
|
||||
"DocumentName": {"shape": "DocumentName"}, "Target": {"shape": "SessionTarget"}}},
|
||||
"GetConnectionStatusRequest": {"type": "structure", "required": ["Target"], "members": {
|
||||
"Target": {"shape": "SessionTarget"}}},
|
||||
"SendCommandRequest": {"type": "structure", "required": ["Target"], "members": {
|
||||
"Target": {"shape": "SessionTarget"}}},
|
||||
"DocumentName": {"type": "string"},
|
||||
"SessionTarget": {"type": "string", "min": 1, "max": 400},
|
||||
},
|
||||
}}
|
||||
|
||||
|
||||
def test_start_session_names_both_the_document_and_ec2_target(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:StartSession"
|
||||
upstream = {"action": operation, "types": list(SSM_SESSION_FORMATS)}
|
||||
assert r.entry_for(operation, upstream, SSM_SESSION_FORMATS, session_models)["resources"] == [
|
||||
{"type": "document", "fill": {"DocumentName": "DocumentName"}, "defaults": {"DocumentName": "document"}},
|
||||
{"types": ["instance"], "through": "Target"},
|
||||
]
|
||||
|
||||
|
||||
def test_connection_status_names_only_the_ec2_target(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:GetConnectionStatus"
|
||||
upstream = {"action": operation, "types": ["instance", "managed-instance", "task"]}
|
||||
assert r.entry_for(operation, upstream, SSM_SESSION_FORMATS, session_models)["resources"] == [
|
||||
{"types": ["instance"], "through": "Target"},
|
||||
]
|
||||
|
||||
|
||||
def test_session_evidence_does_not_apply_to_another_ssm_target(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:SendCommand"
|
||||
upstream = {"action": operation, "types": ["instance", "managed-instance"]}
|
||||
assert r.entry_for(operation, upstream, SSM_SESSION_FORMATS, session_models)["resources"] == []
|
||||
|
||||
|
||||
def test_connection_status_requires_the_shared_scalar_shape(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:GetConnectionStatus"
|
||||
session_models["ssm"]["shapes"]["GetConnectionStatusRequest"]["members"]["Target"]["shape"] = "DocumentName"
|
||||
upstream = {"action": operation, "types": ["instance", "managed-instance", "task"]}
|
||||
with pytest.raises(ValueError, match="shared scalar shape"):
|
||||
r.entry_for(operation, upstream, SSM_SESSION_FORMATS, session_models)
|
||||
|
||||
|
||||
def test_connection_status_requires_the_ec2_type_in_the_reference(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:GetConnectionStatus"
|
||||
upstream = {"action": operation, "types": ["managed-instance", "task"]}
|
||||
with pytest.raises(ValueError, match="EC2 type allowed by the reference"):
|
||||
r.entry_for(operation, upstream, SSM_SESSION_FORMATS, session_models)
|
||||
|
||||
|
||||
def test_start_session_requires_an_account_owned_default_in_the_policy(session_models: dict[str, dict]) -> None:
|
||||
operation = "ssm:StartSession"
|
||||
source = r.load_permission_source("ssm")
|
||||
source["defaultPolicy"]["Statement"][0]["Resource"].pop()
|
||||
with pytest.raises(ValueError, match="no account-owned default document"):
|
||||
r.session_permissions([{"type": "document", "fill": {"DocumentName": "DocumentName"}}],
|
||||
operation, source, list(SSM_SESSION_FORMATS),
|
||||
SSM_SESSION_FORMATS, session_models)
|
||||
@@ -50,6 +50,7 @@ aliases:
|
||||
application-autoscaling: applicationautoscaling
|
||||
elasticbeanstalk: elastic-beanstalk
|
||||
ec2messages: ssm # SSM Messages facet, documented alongside ssm.md
|
||||
ssmmessages: ssm # Session Manager channels, documented alongside ssm.md
|
||||
iotdata: iot # IoT Data row shares iot.md with IoT Core
|
||||
resource-explorer-2: resource-explorer # API version suffix; the page is resource-explorer.md
|
||||
bedrock-agentcore-control: bedrock-agentcore # control plane owns the page; the data-plane row is the facet
|
||||
|
||||
@@ -531,6 +531,7 @@ deferred_handlers:
|
||||
- { path: services/sns/SnsQueryHandler.java } # multi-table doc
|
||||
- { path: services/ssm/Ec2MessagesJsonHandler.java } # multi-table doc
|
||||
- { path: services/ssm/SsmJsonHandler.java } # multi-table doc
|
||||
- { path: services/ssm/SsmSessionJsonHandler.java } # dispatch already counted from SsmJsonHandler
|
||||
- { path: services/textract/TextractJsonHandler.java } # no standalone action table yet
|
||||
- { path: services/transcribe/TranscribeJsonHandler.java } # no standalone action table yet
|
||||
- { path: services/transfer/TransferHandler.java } # multi-table doc
|
||||
Reference in new issue
Block a user