Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(ec2): Verified Access control plane (#2405)

Kacper Harabasz70deb12adb65
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 72049f2a..4d4fef37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
- **SSM — service settings** — `GetServiceSetting`, `UpdateServiceSetting` and `ResetServiceSetting`, per account and region, persisted. `SettingValue` is validated for the ids whose accepted values AWS documents, and `/ssm/parameter-store/default-parameter-tier` sets the `Tier` of a `PutParameter` that names none. Unblocks Terraform's `aws_ssm_service_setting`. Contributed by @skialpine.
- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.
+- **EC2 — Verified Access control plane** — instances, trust providers (`oidc`, and `jamf`, `crowdstrike` and `jumpcloud` devices), groups, `load-balancer` and `network-interface` endpoints, trust provider attach and detach, instance logging configuration, and group and endpoint policies, per account and region, as the `aws_verifiedaccess_*` Terraform resources call them. Codes, messages and check order follow AWS: an instance takes one user trust provider, a provider attaches to one instance, a group needs a user provider and locks it, a group or instance with endpoints can't be deleted or moved, and endpoints need an existing load balancer or ENI, subnets, security groups and certificate. An endpoint answers `pending` on create and `updating` on modify, and is `active` on the next read; OIDC client secrets read back as `REDACTED`. No access evaluation or Cedar parsing; `rds` and `cidr` endpoints, `NativeApplicationOidcOptions` and `CidrEndpointsCustomSubDomain` answer `UnsupportedOperation`. Contributed by @kharabasz.
### Fixed
- **Lambda — publishing on create or code update leaves `$LATEST` unpublished** — `CreateFunction` and `UpdateFunctionCode` with `Publish: true` overwrote `$LATEST`'s `Version` with the new version number. `ListVersionsByFunction` then listed that number twice and no `$LATEST`, `GetFunctionConfiguration` without a qualifier reported it, and invoking `$LATEST` set `AWS_LAMBDA_FUNCTION_VERSION` to it. `$LATEST` now stays `$LATEST`, as on AWS; the create and update responses are unchanged. Contributed by @skialpine.
diff --git a/README.md b/README.md
index 131f065b..386b4d19 100644
--- a/README.md
+++ b/README.md
@@ -640,7 +640,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetDatabase, ListDatabases, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; databases and tables come from the Glue Data Catalog, and `CREATE EXTERNAL TABLE` / `DROP TABLE` change it; S3 Tables are queryable as `"s3tablescatalog/<bucket>".<namespace>.<table>`; partitioned Glue tables keep their Glue partition types; result pagination; column type metadata |
| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId`; `DeliveryStreamType=KinesisStreamAsSource` consumes records from the source Kinesis stream on `PutRecord` / `PutRecords` and forwards them to the configured S3 destination, honoring `Prefix` and `DeliveryStartTimestamp`; `ProcessingConfiguration.Processors[].Type=Lambda` invoked per-batch with the AWS-shape event (`{invocationId, deliveryStreamArn, region, records:[{recordId, approximateArrivalTimestamp, data}]}`) — `Ok` records ship the transformed data downstream, `Dropped`/`ProcessingFailed` are omitted, Lambda failures pass records through unchanged (best-effort per AWS); S3 prefixes evaluate timestamp, random-string, error-output-type and dynamic partition keys (JQ `MetadataExtraction` or Lambda `partitionKeys`); `DataFormatConversionConfiguration` writes Parquet from the Glue schema (DuckDB, full image) |
| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; private zones with VPC associations; alias records, weighted/failover/latency routing; marker-based pagination |
-| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, AssociateIamInstanceProfile, DescribeIamInstanceProfileAssociations, DisassociateIamInstanceProfile, ReplaceIamInstanceProfileAssociation, DescribeImages, RegisterImage, DeregisterImage, ModifyImageAttribute, DescribeImageAttribute, ResetImageAttribute, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreatePlacementGroup, DeletePlacementGroup, DescribePlacementGroups, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, ModifyVpcEndpoint, DescribePrefixLists, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, DescribeAddressesAttribute, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList, DeleteManagedPrefixList, CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway, DetachVpnGateway, DeleteVpnGateway, EnableVgwRoutePropagation, DisableVgwRoutePropagation, CreateCustomerGateway, DescribeCustomerGateways, DeleteCustomerGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations, DescribeInstanceStatus, DescribeVpcClassicLink, DescribeVpcClassicLinkDnsSupport, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate, CreateFleet, DescribeFleets | 133 actions; EC2 Fleet (`CreateFleet` / `DescribeFleets`) with `instant`-type synchronous launch and `maintain` / `request` async fulfillment, multi-config × multi-override round-robin capacity distribution, and `DefaultTargetCapacityType`-driven spot/on-demand selection — unblocks Karpenter / Cluster Autoscaler local validation; IAM instance profile association lifecycle is persisted (`Associate*`, `Describe*`, `Replace*`, `Disassociate*`) so Terraform `aws_instance.iam_instance_profile` round-trips without drift; `AuthorizeSecurityGroupIngress` is idempotent on duplicate rules (same behavior as egress; avoids Terraform re-apply failures); metadata-only instance records by default — `RegisterImage` with a container reference makes an AMI whose launches get a real box, so SSM Run Command returns a real exit code (see *Instances with a real box*); CreateVpc provisions per-VPC default route table, network ACL, and security group; cross-account AMI sharing via launch permissions (`ModifyImageAttribute` add/remove, `Group=all` makes the image public, `DescribeImages` shows shared images with the owner's `OwnerId`, `ExecutableUsers` honored, shared AMIs launch); full Terraform VPC module v6.6.0 compatible; VPN/Customer gateways, managed prefix lists, VPC endpoints with modify support; launch templates with versioning ($Latest/$Default) |
+| **EC2** | RunInstances, DescribeInstances, DescribeInstanceAttribute, DescribeInstanceTypes, DescribeVpcAttribute, TerminateInstances, StopInstances, StartInstances, RebootInstances, AssociateIamInstanceProfile, DescribeIamInstanceProfileAssociations, DisassociateIamInstanceProfile, ReplaceIamInstanceProfileAssociation, DescribeImages, RegisterImage, DeregisterImage, ModifyImageAttribute, DescribeImageAttribute, ResetImageAttribute, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, DescribeSecurityGroupRules, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreatePlacementGroup, DeletePlacementGroup, DescribePlacementGroups, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, ReplaceRouteTableAssociation, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, ModifyVpcEndpoint, DescribePrefixLists, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, DescribeAddressesAttribute, CreateTags, DeleteTags, DescribeTags, CreateNatGateway, DescribeNatGateways, DeleteNatGateway, CreateNetworkAcl, DescribeNetworkAcls, DeleteNetworkAcl, CreateNetworkAclEntry, DeleteNetworkAclEntry, ReplaceNetworkAclEntry, ReplaceNetworkAclAssociation, CreateFlowLogs, DescribeFlowLogs, DeleteFlowLogs, CreateVpcPeeringConnection, AcceptVpcPeeringConnection, DescribeVpcPeeringConnections, DeleteVpcPeeringConnection, CreateDhcpOptions, AssociateDhcpOptions, DescribeDhcpOptions, DeleteDhcpOptions, CreateEgressOnlyInternetGateway, DescribeEgressOnlyInternetGateways, DeleteEgressOnlyInternetGateway, CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList, DeleteManagedPrefixList, CreateVpnGateway, DescribeVpnGateways, AttachVpnGateway, DetachVpnGateway, DeleteVpnGateway, EnableVgwRoutePropagation, DisableVgwRoutePropagation, CreateCustomerGateway, DescribeCustomerGateways, DeleteCustomerGateway, DescribeInstanceCreditSpecifications, DescribeInstanceMaintenanceOptions, DescribeInstanceAutoRecoveryAttribute, ModifyInstanceMaintenanceOptions, DescribeInstanceTopology, DescribeSpotInstanceRequests, DescribeCapacityReservations, DescribeInstanceStatus, DescribeVpcClassicLink, DescribeVpcClassicLinkDnsSupport, CreateLaunchTemplate, CreateLaunchTemplateVersion, DescribeLaunchTemplates, DescribeLaunchTemplateVersions, ModifyLaunchTemplate, DeleteLaunchTemplate, CreateFleet, DescribeFleets, CreateVerifiedAccessInstance, DescribeVerifiedAccessInstances, ModifyVerifiedAccessInstance, DeleteVerifiedAccessInstance, CreateVerifiedAccessTrustProvider, DescribeVerifiedAccessTrustProviders, ModifyVerifiedAccessTrustProvider, DeleteVerifiedAccessTrustProvider, AttachVerifiedAccessTrustProvider, DetachVerifiedAccessTrustProvider, ModifyVerifiedAccessInstanceLoggingConfiguration, DescribeVerifiedAccessInstanceLoggingConfigurations, CreateVerifiedAccessGroup, DescribeVerifiedAccessGroups, ModifyVerifiedAccessGroup, DeleteVerifiedAccessGroup, GetVerifiedAccessGroupPolicy, ModifyVerifiedAccessGroupPolicy, CreateVerifiedAccessEndpoint, DescribeVerifiedAccessEndpoints, ModifyVerifiedAccessEndpoint, DeleteVerifiedAccessEndpoint, GetVerifiedAccessEndpointPolicy, ModifyVerifiedAccessEndpointPolicy | 157 actions; EC2 Fleet (`CreateFleet` / `DescribeFleets`) with `instant`-type synchronous launch and `maintain` / `request` async fulfillment, multi-config × multi-override round-robin capacity distribution, and `DefaultTargetCapacityType`-driven spot/on-demand selection — unblocks Karpenter / Cluster Autoscaler local validation; IAM instance profile association lifecycle is persisted (`Associate*`, `Describe*`, `Replace*`, `Disassociate*`) so Terraform `aws_instance.iam_instance_profile` round-trips without drift; `AuthorizeSecurityGroupIngress` is idempotent on duplicate rules (same behavior as egress; avoids Terraform re-apply failures); metadata-only instance records by default — `RegisterImage` with a container reference makes an AMI whose launches get a real box, so SSM Run Command returns a real exit code (see *Instances with a real box*); CreateVpc provisions per-VPC default route table, network ACL, and security group; cross-account AMI sharing via launch permissions (`ModifyImageAttribute` add/remove, `Group=all` makes the image public, `DescribeImages` shows shared images with the owner's `OwnerId`, `ExecutableUsers` honored, shared AMIs launch); full Terraform VPC module v6.6.0 compatible; VPN/Customer gateways, managed prefix lists, VPC endpoints with modify support; launch templates with versioning ($Latest/$Default); Verified Access control plane (instances, trust providers, groups, `load-balancer` / `network-interface` endpoints, logging configuration, group and endpoint policies; no access evaluation) |
| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |
| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, PutFileSystemPolicy, DescribeFileSystemPolicy, DeleteFileSystemPolicy, UpdateFileSystemProtection, CreateReplicationConfiguration, DescribeReplicationConfigurations, DeleteReplicationConfiguration, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist or it is in a replication configuration; `CreateMountTarget` checks the subnet, security groups, zone and address; replication creates records only, nothing is copied; CFN `AWS::EFS::FileSystem`, `MountTarget` and `AccessPoint` supported |
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index bb59a506..f9e8515e 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -950,6 +950,69 @@ def _ses_v2_resource_arn(method: str, path: str, body: bytes, region: str, accou
return f"arn:aws:ses:{region}:{account_id}:{resource_type}/{name}" if name else "*"
+# Verified Access creates are authorized on a wildcard of the new resource's
+# type; the other calls on the id they name, in this order.
+_VERIFIED_ACCESS_CREATE_RESOURCES = {
+ "CreateVerifiedAccessInstance": "verified-access-instance",
+ "CreateVerifiedAccessTrustProvider": "verified-access-trust-provider",
+}
+_VERIFIED_ACCESS_ID_FIELDS = (
+ ("VerifiedAccessEndpointId", "Endpoint", "verified-access-endpoint"),
+ ("VerifiedAccessGroupId", "Group", "verified-access-group"),
+ ("VerifiedAccessInstanceId", "Instance", "verified-access-instance"),
+ ("VerifiedAccessTrustProviderId", "TrustProvider", "verified-access-trust-provider"),
+)
+
+
+def _verified_access_resource(action, query_params, region, account_id):
+ """The resource AWS names in a Verified Access denial: the id's ARN when
+ the resource exists, ``<type>/*`` when it does not. Attach and Detach move
+ on to the trust provider when the instance id is malformed, and
+ CreateVerifiedAccessEndpoint names the first subnet it knows, then the first
+ security group it knows, then a known network interface, then the group, then ``verified-access-endpoint/*``."""
+ from ministack.services import ec2
+
+ def name(kind, rtype, value):
+ record = ec2._VA_STORES[kind].get_scoped(account_id, region, value)
+ # A deleting endpoint answers NotFound, so it is named like a missing one.
+ if record is not None and record.get("Status") != "deleting":
+ return f"arn:aws:ec2:{region}:{account_id}:{rtype}/{value}"
+ return f"arn:aws:ec2:{region}:{account_id}:{rtype}/*"
+
+ new = _VERIFIED_ACCESS_CREATE_RESOURCES.get(action)
+ if new:
+ return f"arn:aws:ec2:{region}:{account_id}:{new}/*"
+ if action == "CreateVerifiedAccessEndpoint":
+ for field, store, rtype in (("LoadBalancerOptions.SubnetId", ec2._subnets, "subnet"),
+ ("SecurityGroupId", ec2._security_groups, "security-group")):
+ for index in range(1, 1 + sum(1 for k in query_params if k.startswith(field + "."))):
+ value = _query_param(query_params, f"{field}.{index}")
+ if value and store.contains_scoped(account_id, region, value):
+ return f"arn:aws:ec2:{region}:{account_id}:{rtype}/{value}"
+ eni = _query_param(query_params, "NetworkInterfaceOptions.NetworkInterfaceId")
+ if eni and ec2._network_interfaces.contains_scoped(account_id, region, eni):
+ return f"arn:aws:ec2:{region}:{account_id}:network-interface/{eni}"
+ group = _query_param(query_params, "VerifiedAccessGroupId")
+ if group:
+ return name("Group", "verified-access-group", group)
+ return f"arn:aws:ec2:{region}:{account_id}:verified-access-endpoint/*"
+ fields = _VERIFIED_ACCESS_ID_FIELDS
+ if action == "ModifyVerifiedAccessGroup":
+ # Moving a group is checked on the instance it moves to first.
+ fields = sorted(fields, key=lambda f: f[0] != "VerifiedAccessInstanceId")
+ # Attach, Detach and a group move skip a malformed instance id.
+ skips_bad_instance = action in ("AttachVerifiedAccessTrustProvider", "DetachVerifiedAccessTrustProvider",
+ "ModifyVerifiedAccessGroup")
+ for field, kind, rtype in fields:
+ value = _query_param(query_params, field)
+ if not value:
+ continue
+ if skips_bad_instance and kind == "Instance" and ec2._va_bad_id(kind, value, prefix_only=True):
+ continue
+ return name(kind, rtype, value)
+ return "*"
+
+
def extract_resource_arn(service: str, method: str, path: str,
headers: dict, body: bytes,
query_params: dict, region: str,
@@ -1594,6 +1657,12 @@ def extract_resource_arn(service: str, method: str, path: str,
if service == "ec2":
# EC2 uses query params. Try resource ID fields in priority order.
+ # Verified Access: the resource AWS names when it denies the call.
+ # These come before the generic fields: CreateVerifiedAccessEndpoint
+ # also carries SecurityGroupId.1.
+ action = _query_param(query_params, "Action")
+ if "VerifiedAccess" in action and not action.startswith("DescribeVerifiedAccess"):
+ return _verified_access_resource(action, query_params, region, account_id)
_EC2_RESOURCE_FIELDS = [
("InstanceId.1", "instance"),
("InstanceId", "instance"),
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 02d63dfa..b00dfc05 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -60,6 +60,10 @@ Supports:
Launch Tmpl: CreateLaunchTemplate, CreateLaunchTemplateVersion,
DescribeLaunchTemplates, DescribeLaunchTemplateVersions,
ModifyLaunchTemplate, DeleteLaunchTemplate
+ Verified Access: Create/Describe/Modify/Delete for instances, trust providers,
+ groups and endpoints (load-balancer, network-interface);
+ Attach/DetachVerifiedAccessTrustProvider; instance logging
+ configuration; group and endpoint policies (control plane only)
"""
import copy
@@ -132,6 +136,10 @@ _launch_templates = AccountRegionScopedDict() # lt_id -> launch template recor
_fleets = AccountRegionScopedDict() # fleet_id -> fleet record
_iam_instance_profile_associations = AccountRegionScopedDict() # assoc_id -> association record
_images = AccountRegionScopedDict() # ami_id -> registered image record
+_va_instances = AccountRegionScopedDict() # vai_id -> Verified Access instance record
+_va_trust_providers = AccountRegionScopedDict() # vatp_id -> Verified Access trust provider record
+_va_groups = AccountRegionScopedDict() # vagr_id -> Verified Access group record
+_va_endpoints = AccountRegionScopedDict() # vae_id -> Verified Access endpoint record
# Seed defaults once per account/region; do not recreate user-deleted defaults
# on every later EC2 request in a scope.
_default_initialized_scopes = set()
@@ -232,6 +240,10 @@ def get_state():
"launch_templates": copy.deepcopy(_launch_templates),
"fleets": copy.deepcopy(_fleets),
"iam_instance_profile_associations": copy.deepcopy(_iam_instance_profile_associations),
+ "va_instances": copy.deepcopy(_va_instances),
+ "va_trust_providers": copy.deepcopy(_va_trust_providers),
+ "va_groups": copy.deepcopy(_va_groups),
+ "va_endpoints": copy.deepcopy(_va_endpoints),
}
@@ -264,6 +276,10 @@ def _clear_state():
_fleets.clear()
_iam_instance_profile_associations.clear()
_images.clear()
+ _va_instances.clear()
+ _va_trust_providers.clear()
+ _va_groups.clear()
+ _va_endpoints.clear()
_default_initialized_scopes.clear()
@@ -378,6 +394,10 @@ def _restore_state(data):
data.get("iam_instance_profile_associations", {})
)
_restore_regional_store(_images, data.get("images", {}))
+ _restore_regional_store(_va_instances, data.get("va_instances", {}))
+ _restore_regional_store(_va_trust_providers, data.get("va_trust_providers", {}))
+ _restore_regional_store(_va_groups, data.get("va_groups", {}))
+ _restore_regional_store(_va_endpoints, data.get("va_endpoints", {}))
if "default_initialized_scopes" not in data:
_infer_default_initialized_scopes_from_restored_stores()
_reconcile_backed_instances_after_restore()
@@ -4817,6 +4837,10 @@ def _guess_resource_type(resource_id):
"pg-": "placement-group",
"ami-": "image",
"tgw-": "transit-gateway",
+ "vai-": "verified-access-instance",
+ "vatp-": "verified-access-trust-provider",
+ "vagr-": "verified-access-group",
+ "vae-": "verified-access-endpoint",
}
for prefix, rtype in _PREFIX_MAP.items():
if resource_id.startswith(prefix):
@@ -7230,6 +7254,1425 @@ def _describe_fleets(p):
return _xml(200, "DescribeFleetsResponse", f"<fleetSet>{fleet_set_xml}</fleetSet>")
+# ---------------------------------------------------------------------------
+# Verified Access (control plane)
+# ---------------------------------------------------------------------------
+# Instances, trust providers, groups, endpoints, trust provider attachments,
+# instance logging configuration and group/endpoint policies: the operations
+# the Terraform aws_verifiedaccess_* resources call. No access evaluation and
+# no Cedar parsing. Codes, messages and check order follow AWS's answers;
+# responses list their members in AWS's (alphabetical) order.
+
+_VA_TRUST_PROVIDER_TYPES = ("user", "device")
+_VA_USER_TRUST_PROVIDER_TYPES = ("oidc", "iam-identity-center")
+_VA_DEVICE_TRUST_PROVIDER_TYPES = ("jamf", "crowdstrike", "jumpcloud")
+# jamf and crowdstrike take no PublicSigningKeyUrl.
+_VA_DEVICE_TYPES_WITHOUT_KEY_URL = ("jamf", "crowdstrike")
+# The key URLs AWS fills in when a request leaves them out.
+_VA_DEFAULT_KEY_URLS = {
+ "crowdstrike": "https://assets-public.falcon.crowdstrike.com/zta/jwk.json",
+ "jumpcloud": "https://go.jumpcloud.com/.well-known/jwks.json",
+}
+_VA_ENDPOINT_TYPES = ("load-balancer", "network-interface", "rds", "cidr")
+_VA_ATTACHMENT_TYPES = ("vpc",)
+# AWS checks the OIDC members in this order.
+_VA_OIDC_FIELDS = ("Issuer", "AuthorizationEndpoint", "TokenEndpoint",
+ "UserInfoEndpoint", "ClientId", "ClientSecret", "Scope")
+_VA_OIDC_URL_FIELDS = ("Issuer", "AuthorizationEndpoint", "TokenEndpoint", "UserInfoEndpoint")
+_VA_POLICY_REFERENCE_RE = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")
+_VA_DEFAULT_LOG_VERSION = "ocsf-1.0.0-rc.2"
+_VA_LOG_VERSIONS = ("ocsf-0.1", "ocsf-1.0.0-rc.2")
+# (request member, the field it needs when enabled, its other fields)
+_VA_LOG_DESTINATIONS = (
+ ("S3", "BucketName", ("BucketName", "Prefix", "BucketOwner")),
+ ("CloudWatchLogs", "LogGroup", ("LogGroup",)),
+ ("KinesisDataFirehose", "DeliveryStream", ("DeliveryStream",)),
+)
+# Id members as (request member, min length, max length). AWS checks the
+# length, then the pattern, before it looks the id up.
+_VA_ID_MEMBERS = {
+ "Instance": ("VerifiedAccessInstanceId", 5, 21),
+ "TrustProvider": ("VerifiedAccessTrustProviderId", 6, 22),
+ "Group": ("VerifiedAccessGroupId", 6, 22),
+ "Endpoint": ("VerifiedAccessEndpointId", 5, 21),
+}
+_VA_ID_PATTERN = re.compile(r"[a-z0-9-]+")
+_VA_UNSUPPORTED_CIDR_SUBDOMAIN = (
+ "MiniStack does not emulate cidr Verified Access endpoints, so CidrEndpointsCustomSubDomain is not supported")
+
+
+def _va_hex17():
+ # Every id AWS returned has 17 hex digits and starts with 0.
+ return "0" + "".join(random.choices("0123456789abcdef", k=16))
+
+
+def _va_id(prefix):
+ return f"{prefix}-{_va_hex17()}"
+
+
+def _va_now():
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
+
+
+def _va_bool(value):
+ return "true" if value else "false"
+
+
+def _va_text(tag, value):
+ if value is None or value == "":
+ return ""
+ return f"<{tag}>{_esc(str(value))}</{tag}>"
+
+
+def _va_struct(p, prefix, fields):
+ out = {}
+ for field in fields:
+ val = _p(p, f"{prefix}.{field}")
+ if val != "":
+ out[field] = val
+ return out
+
+
+def _va_has_prefix(p, prefix):
+ """True when the request carries the member ``prefix`` or any of its members."""
+ lead = prefix + "."
+ return any(key == prefix or key.startswith(lead) for key in p)
+
+
+def _va_indexed(p, prefix):
+ """Sorted list indexes N present as ``prefix.N.*`` (gaps allowed)."""
+ lead = prefix + "."
+ indexes = set()
+ for key in p:
+ if key.startswith(lead):
+ head = key[len(lead):].split(".", 1)[0]
+ if head.isdigit():
+ indexes.add(int(head))
+ return sorted(indexes)
+
+
+# ── Errors ──────────────────────────────────────────────────
+
+
+def _va_invalid(message):
+ return _error("InvalidParameterValue", _esc(message), 400)
+
+
+def _va_missing_value(message):
+ return _error("MissingParameter", _esc(message), 400)
+
+
+def _va_combination(message):
+ return _error("InvalidParameterCombination", _esc(message), 400)
+
+
+def _va_unsupported(message):
+ return _error("UnsupportedOperation", _esc(message), 400)
+
+
+def _va_missing(*names):
+ """MissingParameter naming the absent required members, sorted by name."""
+ names = sorted(names)
+ if len(names) == 1:
+ message = (f"The request must include the {names[0]} parameter. "
+ "Add the required parameter and retry the request.")
+ else:
+ message = (f"The request must include the following parameters: {', '.join(names)}. "
+ "Add the required parameters and retry the request.")
+ return _error("MissingParameter", message, 400)
+
+
+def _va_require(p, *names):
+ absent = [name for name in names if not _va_has_prefix(p, name)]
+ return _va_missing(*absent) if absent else None
+
+
+def _va_bad_id(kind, value, prefix_only=False):
+ """Length, then pattern. Some calls hold only the part before the first
+ hyphen to the pattern; the others hold the whole id."""
+ member, low, high = _VA_ID_MEMBERS[kind]
+ if not low <= len(value) <= high:
+ return _va_invalid(f"Length of parameter {member} must be between {low} and {high}")
+ if not _VA_ID_PATTERN.fullmatch(value.split("-", 1)[0] if prefix_only else value):
+ return _va_invalid(f"Value of parameter {member} must match regular expression [a-z0-9-]+")
+ return None
+
+
+def _va_listed_not_found(kind, resource_id):
+ """NotFound as the Describe calls (and trust provider calls) word it."""
+ return _error(f"InvalidVerifiedAccess{kind}Id.NotFound",
+ f"VerifiedAccess{kind} {_esc(resource_id)} does not exist", 400)
+
+
+def _va_not_found(kind, resource_id):
+ """NotFound as the calls on one resource word it."""
+ rtype = {"Instance": "instance", "TrustProvider": "trust-provider",
+ "Group": "group", "Endpoint": "endpoint"}[kind]
+ return _error(f"InvalidVerifiedAccess{kind}Id.NotFound",
+ f"The verified-access-{rtype} ID '{_esc(resource_id)}' does not exist", 400)
+
+
+_VA_STORES = {}
+
+
+def _va_lookup(p, kind, prefix_only=True, listed=False):
+ """(record, error) for the id member of ``kind``: format, then existence.
+ Trust provider calls hold the whole id to the pattern and word NotFound as
+ the Describe calls do."""
+ value = _p(p, _VA_ID_MEMBERS[kind][0])
+ err = _va_bad_id(kind, value, prefix_only=prefix_only)
+ if err:
+ return None, err
+ record = _VA_STORES[kind].get(value)
+ if record is None or record.get("Status") == "deleting":
+ return None, (_va_listed_not_found if listed else _va_not_found)(kind, value)
+ return record, None
+
+
+# ── Shared request parts ────────────────────────────────────
+
+
+def _va_kms_key_error(key_arn):
+ """AWS looks the key up in KMS; a key ARN MiniStack's KMS doesn't hold is refused."""
+ from ministack.services import kms
+
+ parts = key_arn.split(":")
+ if key_arn.startswith("arn:") and len(parts) >= 6 and parts[4] != get_account_id():
+ return _error("UnauthorizedOperation", "User does not have permission to invoke required action: kms:DescribeKey", 403)
+ if key_arn.startswith("arn:") and len(parts) >= 6 and parts[5].startswith("alias/"):
+ return _va_invalid("Invalid value for parameter KmsKeyArn")
+ # The key is looked up in the caller's region, whatever region the ARN names.
+ key = kms._keys.get(key_arn.rsplit("/", 1)[-1]) if key_arn.startswith("arn:") and ":key/" in key_arn else None
+ if key is None or (len(parts) >= 6 and parts[3] != get_region()):
+ return _va_invalid(f"Could not find the following key: {key_arn}")
+ if key.get("KeyState") in ("Disabled", "PendingDeletion"):
+ return _va_invalid(f"The provided KMS key {key_arn} is disabled")
+ return None
+
+
+def _va_sse_from(p, current=None):
+ """(sse, error) for an optional SseSpecification. Without a key AWS stores
+ the customer managed key as disabled."""
+ if not _va_has_prefix(p, "SseSpecification"):
+ return current or {"CustomerManagedKeyEnabled": False, "KmsKeyArn": ""}, None
+ enabled = _p(p, "SseSpecification.CustomerManagedKeyEnabled") == "true"
+ key_arn = _p(p, "SseSpecification.KmsKeyArn")
+ if not enabled:
+ return {"CustomerManagedKeyEnabled": False, "KmsKeyArn": ""}, None
+ if not key_arn:
+ return None, _va_missing_value("Invalid value for parameter KmsKeyArn")
+ err = _va_kms_key_error(key_arn)
+ if err:
+ return None, err
+ return {"CustomerManagedKeyEnabled": True, "KmsKeyArn": key_arn}, None
+
+
+def _va_sse_xml(sse):
+ sse = sse or {}
+ return ("<sseSpecification>"
+ f"<customerManagedKeyEnabled>{_va_bool(sse.get('CustomerManagedKeyEnabled'))}</customerManagedKeyEnabled>"
+ f"{_va_text('kmsKeyArn', sse.get('KmsKeyArn'))}"
+ "</sseSpecification>")
+
+
+def _va_description_xml(record):
+ value = record.get("Description") or ""
+ return f"<description>{_esc(value)}</description>" if value else "<description/>"
+
+
+def _va_tags_xml(resource_id, with_tags):
+ # Create and Describe responses carry the tags; the others don't.
+ return _tag_set_xml(resource_id) if with_tags else ""
+
+
+def _va_next_token_xml(token):
+ return f"<nextToken>{token}</nextToken>" if token else ""
+
+
+def _va_describe(p, kind, bounds, members=(), exclusive=False):
+ """Run the checks shared by the Verified Access Describe* calls.
+
+ ``kind`` names the id list (``<member>.N``), ``members`` the single-id
+ members the call also takes, in the order AWS checks them, and
+ ``exclusive`` that those members cannot be sent together. ``bounds`` is the
+ MaxResults range AWS enforces, which is not always the botocore one.
+ The checks run in AWS's order: MaxResults is an integer, the id list is not
+ paged, ids are well formed, MaxResults is in range, the members are well
+ formed and not combined, NextToken is one MiniStack issued, and ids and members exist.
+ Filter names other than the tag filters are ignored, as AWS ignores them.
+ Returns (selected_records, next_token, error_response).
+ """
+ id_member = _VA_ID_MEMBERS[kind][0]
+ ids = _parse_member_list(p, id_member)
+ values = [(m, _p(p, _VA_ID_MEMBERS[m][0])) for m in members]
+ max_results = _p(p, "MaxResults")
+ token = _p(p, "NextToken")
+ if max_results and not re.fullmatch(r"-?[0-9]+", max_results):
+ return None, None, _va_invalid(f"Invalid integer value {max_results}")
+ if ids and token:
+ return None, None, _va_combination(f"The parameters {id_member}s and NextToken cannot be used together")
+ if ids and max_results:
+ return None, None, _va_combination(f"The parameters {id_member}s and MaxResults cannot be used together")
+ for value in ids:
+ err = _va_bad_id(kind, value)
+ if err:
+ return None, None, err
+ low, high = bounds
+ if max_results and not low <= int(max_results) <= high:
+ return None, None, _va_invalid(f"The parameter MaxResults must be between {low} and {high}")
+ for member, value in values:
+ err = value and _va_bad_id(member, value)
+ if err:
+ return None, None, err
+ sent = [_VA_ID_MEMBERS[m][0] for m, value in values if value]
+ if exclusive and len(sent) > 1:
+ return None, None, _va_combination(f"The parameters {sent[0]} and {sent[1]} cannot be used together")
+ records = list(_VA_STORES[kind].values())
+ if token and (not token.isdigit() or int(token) > len(records)):
+ return None, None, _va_invalid("Next token is invalid")
+ for value in ids:
+ if value not in _VA_STORES[kind]:
+ return None, None, _va_listed_not_found(kind, value)
+ for member, value in values:
+ if value and value not in _VA_STORES[member]:
+ return None, None, _va_listed_not_found(member, value)
+ filters = _parse_filters(p)
+ selected = [
+ r for r in records
+ if (not ids or r[id_member] in ids)
+ and all(not value or r[_VA_ID_MEMBERS[member][0]] == value for member, value in values)
+ ]
+ # AWS takes the page first and applies the tag filters to it, so a page
+ # can hold fewer than MaxResults records and still carry a NextToken.
+ start = int(token) if token else 0
+ end = start + int(max_results) if max_results else len(selected)
+ page = [r for r in selected[start:end] if _resource_matches_tag_filters(r[id_member], filters)]
+ return page, str(end) if end < len(selected) else "", None
+
+
+# ── Trust providers ────────────────────────────────────────
+
+
+def _va_trust_provider_condensed_xml(tp, with_description):
+ # Only DescribeVerifiedAccessInstances lists the provider's description.
+ description = _va_text("description", tp.get("Description")) if with_description else ""
+ return ("<item>"
+ f"{description}"
+ f"{_va_text('deviceTrustProviderType', tp.get('DeviceTrustProviderType'))}"
+ f"<trustProviderType>{tp['TrustProviderType']}</trustProviderType>"
+ f"{_va_text('userTrustProviderType', tp.get('UserTrustProviderType'))}"
+ f"<verifiedAccessTrustProviderId>{tp['VerifiedAccessTrustProviderId']}</verifiedAccessTrustProviderId>"
+ "</item>")
+
+
+def _va_trust_provider_xml(tp, tag="verifiedAccessTrustProvider", with_tags=False):
+ device = tp.get("DeviceOptions") or {}
+ device_xml = ""
+ if device:
+ device_xml = ("<deviceOptions>"
+ f"{_va_text('publicSigningKeyUrl', device.get('PublicSigningKeyUrl'))}"
+ f"{_va_text('tenantId', device.get('TenantId'))}"
+ "</deviceOptions>")
+ oidc = tp.get("OidcOptions") or {}
+ oidc_xml = ""
+ if oidc:
+ # AWS answers the client secret as REDACTED.
+ oidc_xml = ("<oidcOptions>"
+ f"{_va_text('authorizationEndpoint', oidc.get('AuthorizationEndpoint'))}"
+ f"{_va_text('clientId', oidc.get('ClientId'))}"
+ f"{_va_text('clientSecret', 'REDACTED' if oidc.get('ClientSecret') else '')}"
+ f"{_va_text('issuer', oidc.get('Issuer'))}"
+ f"{_va_text('scope', oidc.get('Scope'))}"
+ f"{_va_text('tokenEndpoint', oidc.get('TokenEndpoint'))}"
+ f"{_va_text('userInfoEndpoint', oidc.get('UserInfoEndpoint'))}"
+ "</oidcOptions>")
+ return (f"<{tag}>"
+ f"<creationTime>{tp['CreationTime']}</creationTime>"
+ f"{_va_description_xml(tp)}"
+ f"{device_xml}"
+ f"{_va_text('deviceTrustProviderType', tp.get('DeviceTrustProviderType'))}"
+ f"<lastUpdatedTime>{tp['LastUpdatedTime']}</lastUpdatedTime>"
+ f"{oidc_xml}"
+ f"<policyReferenceName>{_esc(tp['PolicyReferenceName'])}</policyReferenceName>"
+ f"{_va_sse_xml(tp.get('SseSpecification'))}"
+ f"{_va_tags_xml(tp['VerifiedAccessTrustProviderId'], with_tags)}"
+ f"<trustProviderType>{tp['TrustProviderType']}</trustProviderType>"
+ f"{_va_text('userTrustProviderType', tp.get('UserTrustProviderType'))}"
+ f"<verifiedAccessTrustProviderId>{tp['VerifiedAccessTrustProviderId']}</verifiedAccessTrustProviderId>"
+ f"</{tag}>")
+
+
+def _va_https_url(value):
+ scheme, sep, rest = value.partition("://")
+ return scheme == "https" and sep and rest.split("/", 1)[0] != ""
+
+
+def _va_oidc_error(oidc, required):
+ """AWS checks the OIDC members one at a time in its order: present (on
+ create), then an HTTPS URL; then the Scope length."""
+ for field in _VA_OIDC_FIELDS:
+ if required and not oidc.get(field):
+ return _va_missing_value(f"Missing required parameter {field} in OidcOptions")
+ if field in _VA_OIDC_URL_FIELDS and field in oidc and not _va_https_url(oidc[field]):
+ return _va_invalid(f"Parameter {field} in OidcOptions must be a valid HTTPS URL")
+ if "Scope" in oidc and not 1 <= len(oidc["Scope"]) <= 256:
+ return _va_invalid("Length of parameter Scope in OidcOptions must be between 1 and 256")
+ return None
+
+
+def _va_create_user_provider_error(p, user_type):
+ if not user_type:
+ return _va_missing_value("Missing UserTrustProviderType parameter required when TrustProviderType is user")
+ if user_type not in _VA_USER_TRUST_PROVIDER_TYPES:
+ return _va_invalid("The value of userTrustProviderType you provided is not valid")
+ if user_type == "iam-identity-center":
+ if _va_has_prefix(p, "OidcOptions"):
+ return _va_combination("Parameter OidcOptions is not allowed when UserTrustProviderType is iam-identity-center")
+ # What AWS answers in an organization without IAM Identity Center;
+ # MiniStack emulates no Identity Center instance.
+ return _va_invalid("IAM Identity Center is not enabled on your organization")
+ if _va_has_prefix(p, "NativeApplicationOidcOptions"):
+ return _va_unsupported("MiniStack does not emulate NativeApplicationOidcOptions")
+ if not _va_has_prefix(p, "OidcOptions"):
+ return _va_missing_value(
+ "Missing OidcOptions or NativeApplicationOidcOptions parameter required when UserTrustProviderType is oidc")
+ # The OIDC members come before the device members.
+ err = _va_oidc_error(_va_struct(p, "OidcOptions", _VA_OIDC_FIELDS), required=True)
+ if err:
+ return err
+ for member in ("DeviceTrustProviderType", "DeviceOptions"):
+ if _va_has_prefix(p, member):
+ return _va_combination(f"Parameter {member} is not allowed when TrustProviderType is user")
+ return None
+
+
+def _va_create_device_provider_error(p, device_type):
+ if device_type and device_type not in _VA_DEVICE_TRUST_PROVIDER_TYPES:
+ return _va_invalid("The value of deviceTrustProviderType you provided is not valid")
+ if _va_has_prefix(p, "UserTrustProviderType"):
+ return _va_combination("Parameter UserTrustProviderType is not allowed when TrustProviderType is device")
+ if _va_has_prefix(p, "OidcOptions"):
+ return _va_combination("Parameter OidcOptions is not allowed when TrustProviderType is device")
+ if not device_type:
+ return _va_missing_value("Missing DeviceTrustProviderType parameter required when TrustProviderType is device")
+ if not _va_has_prefix(p, "DeviceOptions"):
+ return _va_missing_value("Missing DeviceOptions parameter required when TrustProviderType is device")
+ if not _p(p, "DeviceOptions.TenantId"):
+ return _va_missing_value("Missing required parameter TenantId in DeviceOptions")
+ key_url = _p(p, "DeviceOptions.PublicSigningKeyUrl")
+ if key_url and device_type in _VA_DEVICE_TYPES_WITHOUT_KEY_URL:
+ return _va_invalid(f"Parameter PublicSigningKeyUrl is not allowed when DeviceTrustProviderType is {device_type}")
+ if key_url and not _va_https_url(key_url):
+ return _va_invalid("Parameter PublicSigningKeyUrl must be a valid HTTPS URL")
+ return None
+
+
+def _create_verified_access_trust_provider(p):
+ err = _va_require(p, "TrustProviderType", "PolicyReferenceName")
+ if err:
+ return err
+ tp_type = _p(p, "TrustProviderType")
+ if tp_type not in _VA_TRUST_PROVIDER_TYPES:
+ return _va_invalid("The value of trustProviderType you provided is not valid")
+ policy_ref = _p(p, "PolicyReferenceName")
+ if not 1 <= len(policy_ref) <= 32:
+ return _va_invalid("Length of parameter PolicyReferenceName must be between 1 and 32")
+ if not _VA_POLICY_REFERENCE_RE.fullmatch(policy_ref):
+ return _va_invalid("Value of parameter PolicyReferenceName must match regular expression [a-zA-Z_][a-zA-Z0-9_]*")
+ user_type = _p(p, "UserTrustProviderType")
+ device_type = _p(p, "DeviceTrustProviderType")
+ if tp_type == "user":
+ err = _va_create_user_provider_error(p, user_type)
+ else:
+ err = _va_create_device_provider_error(p, device_type)
+ if err:
+ return err
+ sse, err = _va_sse_from(p)
+ if err:
+ return err
+ device = {}
+ if tp_type == "device":
+ device = _va_struct(p, "DeviceOptions", ("TenantId", "PublicSigningKeyUrl"))
+ if device_type in _VA_DEFAULT_KEY_URLS:
+ device.setdefault("PublicSigningKeyUrl", _VA_DEFAULT_KEY_URLS[device_type])
+ now = _va_now()
+ tp_id = _va_id("vatp")
+ record = {
+ "VerifiedAccessTrustProviderId": tp_id,
+ "Description": _p(p, "Description"),
+ "TrustProviderType": tp_type,
+ "UserTrustProviderType": user_type if tp_type == "user" else "",
+ "DeviceTrustProviderType": device_type if tp_type == "device" else "",
+ "OidcOptions": _va_struct(p, "OidcOptions", _VA_OIDC_FIELDS) if tp_type == "user" else {},
+ "DeviceOptions": device,
+ "PolicyReferenceName": policy_ref,
+ "CreationTime": now,
+ "LastUpdatedTime": now,
+ "SseSpecification": sse,
+ }
+ _va_trust_providers[tp_id] = record
+ _parse_tag_specs(p, "verified-access-trust-provider", tp_id)
+ return _xml(200, "CreateVerifiedAccessTrustProviderResponse", _va_trust_provider_xml(record, with_tags=True))
+
+
+def _describe_verified_access_trust_providers(p):
+ selected, token, err = _va_describe(p, "TrustProvider", (5, 1000))
+ if err:
+ return err
+ items = "".join(_va_trust_provider_xml(tp, tag="item", with_tags=True) for tp in selected)
+ return _xml(200, "DescribeVerifiedAccessTrustProvidersResponse",
+ f"<verifiedAccessTrustProviderSet>{items}</verifiedAccessTrustProviderSet>"
+ f"{_va_next_token_xml(token)}")
+
+
+def _modify_verified_access_trust_provider(p):
+ err = _va_require(p, "VerifiedAccessTrustProviderId")
+ if err:
+ return err
+ tp, err = _va_lookup(p, "TrustProvider", prefix_only=False, listed=True)
+ if err:
+ return err
+ sse, err = _va_sse_from(p, tp.get("SseSpecification"))
+ if err:
+ return err
+ oidc_update = _va_struct(p, "OidcOptions", _VA_OIDC_FIELDS)
+ if tp["TrustProviderType"] == "user":
+ err = _va_oidc_error(oidc_update, required=False)
+ if err:
+ return err
+ if _va_has_prefix(p, "DeviceOptions"):
+ return _va_invalid("Parameter DeviceOptions is not allowed when TrustProviderType is user")
+ if tp["TrustProviderType"] == "device":
+ if _va_has_prefix(p, "OidcOptions"):
+ return _va_invalid("Parameter OidcOptions is not allowed when TrustProviderType is device")
+ if tp["DeviceTrustProviderType"] in _VA_DEVICE_TYPES_WITHOUT_KEY_URL and _va_has_prefix(p, "DeviceOptions"):
+ return _va_invalid(
+ f"Parameter DeviceOptions is not allowed when DeviceTrustProviderType is {tp['DeviceTrustProviderType']}")
+ if _va_has_prefix(p, "NativeApplicationOidcOptions"):
+ return _va_unsupported("MiniStack does not emulate NativeApplicationOidcOptions")
+ if oidc_update:
+ tp["OidcOptions"] = {**tp["OidcOptions"], **oidc_update}
+ device_update = _va_struct(p, "DeviceOptions", ("PublicSigningKeyUrl",))
+ if device_update and not _va_https_url(device_update["PublicSigningKeyUrl"]):
+ return _va_invalid("Parameter PublicSigningKeyUrl must be a valid HTTPS URL")
+ if device_update:
+ tp["DeviceOptions"] = {**tp["DeviceOptions"], **device_update}
+ if "Description" in p:
+ tp["Description"] = _p(p, "Description")
+ tp["SseSpecification"] = sse
+ # AWS answers with the time from before the change; the next read has the new one.
+ body = _va_trust_provider_xml(tp)
+ tp["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessTrustProviderResponse", body)
+
+
+def _va_instance_of(tp_id):
+ return next((inst for inst in _va_instances.values() if tp_id in inst["TrustProviderIds"]), None)
+
+
+def _delete_verified_access_trust_provider(p):
+ err = _va_require(p, "VerifiedAccessTrustProviderId")
+ if err:
+ return err
+ tp, err = _va_lookup(p, "TrustProvider", prefix_only=False, listed=True)
+ if err:
+ return err
+ if _va_instance_of(tp["VerifiedAccessTrustProviderId"]):
+ return _va_invalid("VerifiedAccessTrustProvider has existing attachments. "
+ "Please remove all VerifiedAccessTrustProvider attachments before deleting.")
+ body = _va_trust_provider_xml(tp)
+ _va_trust_providers.pop(tp["VerifiedAccessTrustProviderId"], None)
+ _tags.pop(tp["VerifiedAccessTrustProviderId"], None)
+ return _xml(200, "DeleteVerifiedAccessTrustProviderResponse", body)
+
+
+# ── Instances ──────────────────────────────────────────────
+
+
+def _va_instance_xml(inst, tag="verifiedAccessInstance", with_tags=False):
+ providers = "".join(
+ _va_trust_provider_condensed_xml(_va_trust_providers[tp_id], with_description=with_tags and tag == "item")
+ for tp_id in inst["TrustProviderIds"] if tp_id in _va_trust_providers
+ )
+ return (f"<{tag}>"
+ f"<creationTime>{inst['CreationTime']}</creationTime>"
+ f"{_va_description_xml(inst)}"
+ f"<fipsEnabled>{_va_bool(inst.get('FipsEnabled'))}</fipsEnabled>"
+ f"<lastUpdatedTime>{inst['LastUpdatedTime']}</lastUpdatedTime>"
+ f"{_va_tags_xml(inst['VerifiedAccessInstanceId'], with_tags)}"
+ f"<verifiedAccessInstanceId>{inst['VerifiedAccessInstanceId']}</verifiedAccessInstanceId>"
+ f"<verifiedAccessTrustProviderSet>{providers}</verifiedAccessTrustProviderSet>"
+ f"</{tag}>")
+
+
+def _create_verified_access_instance(p):
+ if _va_has_prefix(p, "CidrEndpointsCustomSubDomain"):
+ return _va_unsupported(_VA_UNSUPPORTED_CIDR_SUBDOMAIN)
+ now = _va_now()
+ inst_id = _va_id("vai")
+ record = {
+ "VerifiedAccessInstanceId": inst_id,
+ "Description": _p(p, "Description"),
+ "TrustProviderIds": [],
+ "CreationTime": now,
+ "LastUpdatedTime": now,
+ "FipsEnabled": _p(p, "FIPSEnabled") == "true",
+ "AccessLogs": None,
+ }
+ _va_instances[inst_id] = record
+ _parse_tag_specs(p, "verified-access-instance", inst_id)
+ return _xml(200, "CreateVerifiedAccessInstanceResponse", _va_instance_xml(record, with_tags=True))
+
+
+def _describe_verified_access_instances(p):
+ selected, token, err = _va_describe(p, "Instance", (5, 200))
+ if err:
+ return err
+ items = "".join(_va_instance_xml(inst, tag="item", with_tags=True) for inst in selected)
+ return _xml(200, "DescribeVerifiedAccessInstancesResponse",
+ f"<verifiedAccessInstanceSet>{items}</verifiedAccessInstanceSet>"
+ f"{_va_next_token_xml(token)}")
+
+
+def _modify_verified_access_instance(p):
+ err = _va_require(p, "VerifiedAccessInstanceId")
+ if err:
+ return err
+ inst, err = _va_lookup(p, "Instance")
+ if err:
+ return err
+ if _va_has_prefix(p, "CidrEndpointsCustomSubDomain"):
+ return _va_unsupported(_VA_UNSUPPORTED_CIDR_SUBDOMAIN)
+ if "Description" in p:
+ inst["Description"] = _p(p, "Description")
+ inst["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessInstanceResponse", _va_instance_xml(inst))
+
+
+def _delete_verified_access_instance(p):
+ err = _va_require(p, "VerifiedAccessInstanceId")
+ if err:
+ return err
+ inst, err = _va_lookup(p, "Instance")
+ if err:
+ return err
+ inst_id = inst["VerifiedAccessInstanceId"]
+ if any(ep["VerifiedAccessInstanceId"] == inst_id for ep in _va_live_endpoints()):
+ return _va_invalid(f"VerifiedAccessInstance {inst_id} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before deleting.")
+ if inst["TrustProviderIds"]:
+ return _va_invalid(f"{inst_id} has existing attachments. "
+ "Remove all VerifiedAccessTrustProvider attachments before deleting.")
+ body = _va_instance_xml(inst)
+ _va_drop_endpoints(lambda ep: ep["VerifiedAccessInstanceId"] != inst_id)
+ _va_instances.pop(inst_id, None)
+ _tags.pop(inst_id, None)
+ return _xml(200, "DeleteVerifiedAccessInstanceResponse", body)
+
+
+def _va_attachment_args(p, detach):
+ """(instance, trust provider, error) for Attach/Detach. AWS looks up each
+ well-formed id first, instance before provider, and reports a malformed id
+ (the provider's first) only when no lookup failed. Attach holds the
+ provider id's prefix to the pattern, Detach the whole id."""
+ err = _va_require(p, "VerifiedAccessInstanceId", "VerifiedAccessTrustProviderId")
+ if err:
+ return None, None, err
+ inst_id = _p(p, "VerifiedAccessInstanceId")
+ tp_id = _p(p, "VerifiedAccessTrustProviderId")
+ inst_bad = _va_bad_id("Instance", inst_id, prefix_only=True)
+ tp_bad = _va_bad_id("TrustProvider", tp_id, prefix_only=not detach)
+ inst = _va_instances.get(inst_id)
+ if not inst_bad and inst is None:
+ return None, None, _va_not_found("Instance", inst_id)
+ tp = _va_trust_providers.get(tp_id)
+ if not tp_bad and tp is None:
+ not_found = _va_listed_not_found if detach else _va_not_found
+ return None, None, not_found("TrustProvider", tp_id)
+ if inst_bad or tp_bad:
+ return None, None, tp_bad or inst_bad
+ return inst, tp, None
+
+
+def _va_user_provider_locked(inst, tp):
+ """A user trust provider can't be attached or detached while the instance has groups."""
+ if tp["TrustProviderType"] != "user":
+ return None
+ inst_id = inst["VerifiedAccessInstanceId"]
+ if any(g["VerifiedAccessInstanceId"] == inst_id for g in _va_groups.values()):
+ return _error("VerifiedAccessGroupAttachmentExists",
+ f"VerifiedAccessInstance {inst_id} is not empty. Please remove all VerifiedAccessGroups "
+ "before attaching or detaching a VerifiedAccessTrustProvider with TrustProviderType user", 400)
+ return None
+
+
+def _attach_verified_access_trust_provider(p):
+ inst, tp, err = _va_attachment_args(p, detach=False)
+ if err:
+ return err
+ tp_id = tp["VerifiedAccessTrustProviderId"]
+ err = _va_user_provider_locked(inst, tp)
+ if err:
+ return err
+ # AWS names the instance in the request, also when another instance holds the provider.
+ if _va_instance_of(tp_id):
+ return _error("VerifiedAccessTrustProviderAttachmentLimitExceeded",
+ f"VerifiedAccessTrustProvider {tp_id} is already attached to "
+ f"VerifiedAccessInstance {inst['VerifiedAccessInstanceId']}", 400)
+ if tp["TrustProviderType"] == "user" and any(
+ _va_trust_providers.get(other, {}).get("TrustProviderType") == "user" for other in inst["TrustProviderIds"]):
+ return _error("VerifiedAccessTrustProviderAttachmentLimitExceeded",
+ "Cannot have more than 1 VerifiedAccessTrustProvider with TrustProviderType user "
+ "attached to a VerifiedAccessInstance", 400)
+ inst["TrustProviderIds"].append(tp_id)
+ if tp["TrustProviderType"] == "device":
+ inst["HadDeviceProvider"] = True
+ # As on Modify, the response carries the times from before the change.
+ body = _va_trust_provider_xml(tp) + _va_instance_xml(inst)
+ inst["LastUpdatedTime"] = tp["LastUpdatedTime"] = _va_now()
+ return _xml(200, "AttachVerifiedAccessTrustProviderResponse", body)
+
+
+def _detach_verified_access_trust_provider(p):
+ inst, tp, err = _va_attachment_args(p, detach=True)
+ if err:
+ return err
+ tp_id = tp["VerifiedAccessTrustProviderId"]
+ inst_id = inst["VerifiedAccessInstanceId"]
+ err = _va_user_provider_locked(inst, tp)
+ if err:
+ return err
+ if tp_id not in inst["TrustProviderIds"]:
+ return _va_invalid(f"Trust provider {tp_id} is not attached to instance {inst_id}")
+ inst["TrustProviderIds"].remove(tp_id)
+ body = _va_trust_provider_xml(tp) + _va_instance_xml(inst)
+ inst["LastUpdatedTime"] = tp["LastUpdatedTime"] = _va_now()
+ return _xml(200, "DetachVerifiedAccessTrustProviderResponse", body)
+
+
+# ── Instance logging configuration ─────────────────────────
+
+
+def _va_default_access_logs():
+ return {
+ "S3": {"Enabled": False},
+ "CloudWatchLogs": {"Enabled": False},
+ "KinesisDataFirehose": {"Enabled": False},
+ "LogVersion": _VA_DEFAULT_LOG_VERSION,
+ "IncludeTrustContext": False,
+ }
+
+
+def _va_logging_xml(inst, tag="loggingConfiguration"):
+ logs = inst.get("AccessLogs") or _va_default_access_logs()
+
+ def dest_xml(name, xml_tag, fields):
+ # An enabled destination reports a successful delivery, as AWS does
+ # for a destination that exists; a disabled one reports only that.
+ dest = logs[name]
+ if not dest.get("Enabled"):
+ return f"<{xml_tag}><enabled>false</enabled></{xml_tag}>"
+ parts = [(x, _va_text(x, dest.get(k))) for k, x in fields]
+ parts += [("deliveryStatus", "<deliveryStatus><code>success</code></deliveryStatus>"),
+ ("enabled", "<enabled>true</enabled>")]
+ return f"<{xml_tag}>" + "".join(xml for _, xml in sorted(parts)) + f"</{xml_tag}>"
+
+ return (f"<{tag}>"
+ "<accessLogs>"
+ + dest_xml("CloudWatchLogs", "cloudWatchLogs", (("LogGroup", "logGroup"),))
+ + f"<includeTrustContext>{_va_bool(logs['IncludeTrustContext'])}</includeTrustContext>"
+ + dest_xml("KinesisDataFirehose", "kinesisDataFirehose", (("DeliveryStream", "deliveryStream"),))
+ + f"<logVersion>{_esc(logs['LogVersion'])}</logVersion>"
+ + dest_xml("S3", "s3", (("BucketName", "bucketName"), ("BucketOwner", "bucketOwner"),
+ ("Prefix", "prefix")))
+ + "</accessLogs>"
+ f"<verifiedAccessInstanceId>{inst['VerifiedAccessInstanceId']}</verifiedAccessInstanceId>"
+ f"</{tag}>")
+
+
+def _va_log_destination_exists(name, value):
+ """AWS checks that the bucket, log group or delivery stream exists."""
+ if name == "S3":
+ from ministack.services import s3
+
+ return value in s3._buckets
+ if name == "CloudWatchLogs":
+ from ministack.services import cloudwatch_logs
+
+ return value in cloudwatch_logs._log_groups
+ from ministack.services import firehose
+
+ return value in firehose._streams
+
+
+def _modify_verified_access_instance_logging_configuration(p):
+ err = _va_require(p, "VerifiedAccessInstanceId", "AccessLogs")
+ if err:
+ return err
+ inst, err = _va_lookup(p, "Instance")
+ if err:
+ return err
+ updates = {}
+ for name, needed, fields in _VA_LOG_DESTINATIONS:
+ prefix = f"AccessLogs.{name}"
+ if not _va_has_prefix(p, prefix):
+ continue
+ enabled = _p(p, f"{prefix}.Enabled") == "true"
+ values = _va_struct(p, prefix, fields)
+ if not enabled:
+ for field in fields:
+ if field in values:
+ return _va_combination(f"The parameter {prefix}.{field} cannot be used "
+ f"when {prefix}.Enabled is false")
+ updates[name] = {"Enabled": False}
+ continue
+ if needed not in values:
+ return _va_missing_value(f"Missing required parameter {prefix}.{needed}")
+ updates[name] = {"Enabled": True, **values}
+ version = _p(p, "AccessLogs.LogVersion").lower() or _VA_DEFAULT_LOG_VERSION
+ if version not in _VA_LOG_VERSIONS:
+ return _va_invalid("Invalid value for parameter LogVersion")
+ include_trust = _p(p, "AccessLogs.IncludeTrustContext") == "true"
+ if include_trust and version == "ocsf-0.1":
+ return _va_combination("The LogVersion ocsf-0.1 is not compatible with IncludeTrustContext true")
+ for name, needed, _ in _VA_LOG_DESTINATIONS:
+ dest = updates.get(name)
+ if dest and dest["Enabled"] and not _va_log_destination_exists(name, dest[needed]):
+ return _error("LogDestinationNotFound",
+ f"Log destination resource identified by AccessLogs.{name}.{needed} was not found", 400)
+ # A bucket that exists, named as another account's, is refused.
+ if dest and dest["Enabled"] and dest.get("BucketOwner", get_account_id()) != get_account_id():
+ return _error("LogDestinationPermissionIssue",
+ f"User does not have permission to configure log destination resource identified by "
+ f"AccessLogs.{name}.{needed} for log delivery", 400)
+ logs = copy.deepcopy(inst.get("AccessLogs") or _va_default_access_logs())
+ for name, dest in updates.items():
+ if name == "S3" and dest["Enabled"]:
+ dest.setdefault("BucketOwner", get_account_id())
+ logs[name] = dest
+ # LogVersion and IncludeTrustContext fall back to their defaults when a
+ # request leaves them out; destinations it leaves out are kept.
+ logs["LogVersion"] = version
+ logs["IncludeTrustContext"] = include_trust
+ inst["AccessLogs"] = logs
+ inst["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessInstanceLoggingConfigurationResponse", _va_logging_xml(inst))
+
+
+def _describe_verified_access_instance_logging_configurations(p):
+ selected, token, err = _va_describe(p, "Instance", (1, 10))
+ if err:
+ return err
+ items = "".join(_va_logging_xml(inst, tag="item") for inst in selected)
+ # This Describe lists nextToken first.
+ return _xml(200, "DescribeVerifiedAccessInstanceLoggingConfigurationsResponse",
+ f"{_va_next_token_xml(token)}<loggingConfigurationSet>{items}</loggingConfigurationSet>")
+
+
+# ── Groups ─────────────────────────────────────────────────
+
+
+def _va_group_xml(group, tag="verifiedAccessGroup", with_tags=False):
+ return (f"<{tag}>"
+ f"<creationTime>{group['CreationTime']}</creationTime>"
+ f"{_va_text('deletionTime', group.get('DeletionTime'))}"
+ f"{_va_description_xml(group)}"
+ f"<lastUpdatedTime>{group['LastUpdatedTime']}</lastUpdatedTime>"
+ f"<owner>{group['Owner']}</owner>"
+ f"{_va_sse_xml(group.get('SseSpecification'))}"
+ f"{_va_tags_xml(group['VerifiedAccessGroupId'], with_tags)}"
+ f"<verifiedAccessGroupArn>{group['VerifiedAccessGroupArn']}</verifiedAccessGroupArn>"
+ f"<verifiedAccessGroupId>{group['VerifiedAccessGroupId']}</verifiedAccessGroupId>"
+ f"<verifiedAccessInstanceId>{group['VerifiedAccessInstanceId']}</verifiedAccessInstanceId>"
+ f"</{tag}>")
+
+
+def _create_verified_access_group(p):
+ err = _va_require(p, "VerifiedAccessInstanceId")
+ if err:
+ return err
+ inst, err = _va_lookup(p, "Instance")
+ if err:
+ return err
+ inst_id = inst["VerifiedAccessInstanceId"]
+ sse, err = _va_sse_from(p)
+ if err:
+ return err
+ if not inst["TrustProviderIds"]:
+ return _va_invalid(f"Must attach a TrustProvider to Instance {inst_id} before you can create a Group")
+ if not any(_va_trust_providers.get(tp_id, {}).get("TrustProviderType") == "user" for tp_id in inst["TrustProviderIds"]):
+ return _va_invalid(f"Must attach a 'user' TrustProvider to Instance {inst_id} before you can create a Group")
+ now = _va_now()
+ group_id = _va_id("vagr")
+ policy = _p(p, "PolicyDocument")
+ record = {
+ "VerifiedAccessGroupId": group_id,
+ "VerifiedAccessInstanceId": inst_id,
+ "Description": _p(p, "Description"),
+ "Owner": get_account_id(),
+ "VerifiedAccessGroupArn": f"arn:aws:ec2:{get_region()}:{get_account_id()}:verified-access-group/{group_id}",
+ "CreationTime": now,
+ "LastUpdatedTime": now,
+ "SseSpecification": sse,
+ "PolicyEnabled": bool(policy),
+ "PolicyDocument": policy,
+ }
+ _va_groups[group_id] = record
+ _parse_tag_specs(p, "verified-access-group", group_id)
+ return _xml(200, "CreateVerifiedAccessGroupResponse", _va_group_xml(record, with_tags=True))
+
+
+def _describe_verified_access_groups(p):
+ selected, token, err = _va_describe(p, "Group", (5, 200), members=("Instance",))
+ if err:
+ return err
+ items = "".join(_va_group_xml(group, tag="item", with_tags=True) for group in selected)
+ return _xml(200, "DescribeVerifiedAccessGroupsResponse",
+ f"<verifiedAccessGroupSet>{items}</verifiedAccessGroupSet>"
+ f"{_va_next_token_xml(token)}")
+
+
+def _modify_verified_access_group(p):
+ err = _va_require(p, "VerifiedAccessGroupId")
+ if err:
+ return err
+ moving = _va_has_prefix(p, "VerifiedAccessInstanceId")
+ if not moving:
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ else:
+ # AWS looks up the target instance, then the group, before it reports
+ # a malformed id.
+ inst_id, group_id = _p(p, "VerifiedAccessInstanceId"), _p(p, "VerifiedAccessGroupId")
+ inst_bad = _va_bad_id("Instance", inst_id, prefix_only=True)
+ group_bad = _va_bad_id("Group", group_id, prefix_only=True)
+ inst = _va_instances.get(inst_id)
+ if not inst_bad and inst is None:
+ return _va_not_found("Instance", inst_id)
+ group = _va_groups.get(group_id)
+ if not group_bad and group is None:
+ return _va_not_found("Group", group_id)
+ if group_bad or inst_bad:
+ return group_bad or inst_bad
+ if moving:
+ group_id = group["VerifiedAccessGroupId"]
+ if inst["VerifiedAccessInstanceId"] != group["VerifiedAccessInstanceId"] and any(
+ ep["VerifiedAccessGroupId"] == group_id for ep in _va_live_endpoints()):
+ return _va_invalid(f"VerifiedAccessGroup {group_id} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before changing VerifiedAccessInstanceId.")
+ group["VerifiedAccessInstanceId"] = inst["VerifiedAccessInstanceId"]
+ if "Description" in p:
+ group["Description"] = _p(p, "Description")
+ if moving:
+ # A move answers with the time from before the change.
+ body = _va_group_xml(group)
+ group["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessGroupResponse", body)
+ group["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessGroupResponse", _va_group_xml(group))
+
+
+def _delete_verified_access_group(p):
+ err = _va_require(p, "VerifiedAccessGroupId")
+ if err:
+ return err
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ group_id = group["VerifiedAccessGroupId"]
+ if any(ep["VerifiedAccessGroupId"] == group_id for ep in _va_live_endpoints()):
+ return _va_invalid(f"VerifiedAccessGroup {group_id} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before deleting.")
+ body = _va_group_xml(dict(group, DeletionTime=_va_now()))
+ _va_drop_endpoints(lambda ep: ep["VerifiedAccessGroupId"] != group_id)
+ _va_groups.pop(group_id, None)
+ _tags.pop(group_id, None)
+ return _xml(200, "DeleteVerifiedAccessGroupResponse", body)
+
+
+def _va_get_policy_xml(record):
+ body = f"<policyEnabled>{_va_bool(record.get('PolicyEnabled'))}</policyEnabled>"
+ return body + _va_text("policyDocument", record.get("PolicyDocument"))
+
+
+def _va_modify_policy(record, p):
+ """Apply a Modify*Policy request; returns an error response or None.
+ A document needs PolicyEnabled=true, PolicyEnabled=true needs a document,
+ and disabling the policy drops its document."""
+ enabled = _p(p, "PolicyEnabled")
+ has_document = "PolicyDocument" in p
+ if enabled == "true" and not has_document:
+ return _va_missing_value("Policy Document must be provided when Policy Enabled is true")
+ if has_document and enabled != "true":
+ return _va_invalid("Policy Document cannot be provided when Policy Enabled is false or missing")
+ sse, err = _va_sse_from(p, record.get("SseSpecification"))
+ if err:
+ return err
+ if enabled == "true":
+ record["PolicyEnabled"], record["PolicyDocument"] = True, _p(p, "PolicyDocument")
+ elif enabled == "false":
+ record["PolicyEnabled"], record["PolicyDocument"] = False, ""
+ record["SseSpecification"] = sse
+ record["LastUpdatedTime"] = _va_now()
+ return None
+
+
+def _va_modify_policy_xml(record):
+ return (f"{_va_text('policyDocument', record.get('PolicyDocument'))}"
+ f"<policyEnabled>{_va_bool(record.get('PolicyEnabled'))}</policyEnabled>"
+ f"{_va_sse_xml(record.get('SseSpecification'))}")
+
+
+def _get_verified_access_group_policy(p):
+ err = _va_require(p, "VerifiedAccessGroupId")
+ if err:
+ return err
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ return _xml(200, "GetVerifiedAccessGroupPolicyResponse", _va_get_policy_xml(group))
+
+
+def _modify_verified_access_group_policy(p):
+ err = _va_require(p, "VerifiedAccessGroupId")
+ if err:
+ return err
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ err = _va_modify_policy(group, p)
+ if err:
+ return err
+ return _xml(200, "ModifyVerifiedAccessGroupPolicyResponse", _va_modify_policy_xml(group))
+
+
+# ── Endpoints ──────────────────────────────────────────────
+
+
+def _va_member_items(values):
+ return "".join(f"<item>{_esc(v)}</item>" for v in values) if values else ""
+
+
+def _va_target_options_xml(tag, opts, arn_key, arn_tag):
+ if opts is None:
+ return ""
+ subnet_xml = (f"<subnetIdSet>{_va_member_items(opts.get('SubnetIds'))}</subnetIdSet>"
+ if "SubnetIds" in opts else "")
+ return (f"<{tag}>"
+ f"{_va_text(arn_tag, opts.get(arn_key))}"
+ f"{_va_text('port', opts.get('Port'))}"
+ f"{_va_text('protocol', opts.get('Protocol'))}"
+ f"{subnet_xml}"
+ f"</{tag}>")
+
+
+def _va_endpoint_xml(ep, tag="verifiedAccessEndpoint", with_tags=False):
+ return (f"<{tag}>"
+ f"{_va_text('applicationDomain', ep.get('ApplicationDomain'))}"
+ f"<attachmentType>{ep['AttachmentType']}</attachmentType>"
+ f"<creationTime>{ep['CreationTime']}</creationTime>"
+ f"{_va_description_xml(ep)}"
+ f"{_va_text('deviceValidationDomain', ep.get('DeviceValidationDomain') if _va_has_device_provider(ep) else '')}"
+ f"{_va_text('domainCertificateArn', ep.get('DomainCertificateArn'))}"
+ f"{_va_text('endpointDomain', ep.get('EndpointDomain'))}"
+ f"<endpointType>{ep['EndpointType']}</endpointType>"
+ f"<lastUpdatedTime>{ep['LastUpdatedTime']}</lastUpdatedTime>"
+ f"{_va_target_options_xml('loadBalancerOptions', ep.get('LoadBalancerOptions'), 'LoadBalancerArn', 'loadBalancerArn')}"
+ f"{_va_target_options_xml('networkInterfaceOptions', ep.get('NetworkInterfaceOptions'), 'NetworkInterfaceId', 'networkInterfaceId')}"
+ f"<securityGroupIdSet>{_va_member_items(ep.get('SecurityGroupIds'))}</securityGroupIdSet>"
+ f"{_va_sse_xml(ep.get('SseSpecification'))}"
+ f"<status><code>{ep['Status']}</code></status>"
+ f"{_va_tags_xml(ep['VerifiedAccessEndpointId'], with_tags)}"
+ f"<verifiedAccessEndpointId>{ep['VerifiedAccessEndpointId']}</verifiedAccessEndpointId>"
+ f"<verifiedAccessGroupId>{ep['VerifiedAccessGroupId']}</verifiedAccessGroupId>"
+ f"<verifiedAccessInstanceId>{ep['VerifiedAccessInstanceId']}</verifiedAccessInstanceId>"
+ f"</{tag}>")
+
+
+def _va_has_device_provider(ep):
+ """AWS lists the device validation domain once the endpoint's instance has had a
+ device trust provider, and keeps it after the provider is detached."""
+ return bool((_va_instances.get(ep["VerifiedAccessInstanceId"]) or {}).get("HadDeviceProvider"))
+
+
+def _va_live_endpoints():
+ """Endpoints that are not being deleted; AWS lets a group with only
+ deleting endpoints be deleted."""
+ return [ep for ep in _va_endpoints.values() if ep["Status"] != "deleting"]
+
+
+def _va_settle(ep):
+ """AWS answers pending on create and updating on modify, and the endpoint
+ is active once AWS has applied the change; MiniStack applies it at once,
+ so the next read sees active."""
+ if ep["Status"] in ("pending", "updating"):
+ ep["Status"] = "active"
+
+
+def _va_certificate_error(cert_arn, domain):
+ """The certificate must be in ACM and name the application domain."""
+ from ministack.services import acm
+
+ cert = acm._certificates.get(cert_arn)
+ if cert is None:
+ return _va_invalid("The CertificateArn is invalid")
+ if cert.get("Status") != "ISSUED":
+ return _va_invalid("The DomainCertificateArn provided in the request is not in ISSUED state.")
+ # MiniStack's ACM does not read the names in an imported certificate.
+ if cert.get("Type") == "IMPORTED":
+ return None
+ names = cert.get("SubjectAlternativeNames") or [cert.get("DomainName", "")]
+ # A wildcard name covers one label: *.example.com covers web.example.com,
+ # not example.com or a.b.example.com.
+ wildcard = "*." + domain.split(".", 1)[1] if "." in domain else ""
+ if domain not in names and wildcard not in names:
+ return _va_invalid("The ApplicationDomain provided is not present in the DomainCertificateArn "
+ "provided in the request.")
+ return None
+
+
+def _va_load_balancer_exists(arn):
+ from ministack.services import alb
+
+ return arn in alb._lbs
+
+
+_VA_ENDPOINT_PROTOCOLS = ("http", "https", "tcp")
+_VA_PREFIX_RE = re.compile(r"[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?")
+
+
+def _va_options_value_error(p, prefix, xml_prefix, tcp=True):
+ """Protocol and port values, both reported when both are bad; on create,
+ HTTP/HTTPS then refuses PortRanges, and tcp refuses a Port and needs
+ PortRanges. AWS names the network-interface options EniOptions here."""
+ protocol = _p(p, f"{prefix}.Protocol")
+ port = _p(p, f"{prefix}.Port")
+ bad = []
+ if protocol and protocol not in _VA_ENDPOINT_PROTOCOLS:
+ bad.append(f"The value of {xml_prefix}.protocol you provided is not valid")
+ if port and (not port.isdigit() or not 1 <= int(port) <= 65535):
+ bad.append(f"The value of {xml_prefix}.port you provided is not valid")
+ if bad:
+ return _va_invalid("; ".join(bad))
+ if tcp and protocol != "tcp" and _va_indexed(p, f"{prefix}.PortRange"):
+ # Before the missing members and every existence check.
+ return _va_invalid("Parameter PortRanges is not currently supported for the operation")
+ if tcp and protocol == "tcp":
+ if port:
+ name = "LoadBalancerOptions" if prefix == "LoadBalancerOptions" else "EniOptions"
+ return _va_invalid(f"Parameter port in {name} is not supported with 'tcp' protocol")
+ if not _va_indexed(p, f"{prefix}.PortRange"):
+ if prefix == "LoadBalancerOptions":
+ return _va_missing_value("PortRanges must be provided in LoadBalancerOptions")
+ # A network-interface endpoint reports its missing id first.
+ if not _p(p, "NetworkInterfaceOptions.NetworkInterfaceId"):
+ return _va_missing_value("Missing required parameter NetworkInterfaceId")
+ return _va_missing_value("Missing required parameter PortRanges")
+ return None
+
+
+def _va_endpoint_type_error(p, endpoint_type):
+ """The endpoint type's own options: present, alone and complete."""
+ if endpoint_type in ("rds", "cidr"):
+ key = "RdsOptions" if endpoint_type == "rds" else "CidrOptions"
+ if not _va_has_prefix(p, key):
+ return _va_missing_value(f"Missing required parameter {key}")
+ return _va_unsupported(f"MiniStack does not emulate {endpoint_type} Verified Access endpoints")
+ own, other = (("LoadBalancerOptions", "NetworkInterfaceOptions") if endpoint_type == "load-balancer"
+ else ("NetworkInterfaceOptions", "LoadBalancerOptions"))
+ if not _va_has_prefix(p, own):
+ return _va_missing_value(f"{own} must be provided if endpoint type {endpoint_type} is specified")
+ if _va_has_prefix(p, other):
+ return _va_combination(f"{other} cannot be provided if endpoint type {endpoint_type} is specified")
+ # AWS names EniOptions here for both endpoint types.
+ if not _p(p, f"{own}.Protocol"):
+ return _va_missing_value("Missing required parameter protocol in EniOptions")
+ xml_prefix = "loadBalancerOptions" if endpoint_type == "load-balancer" else "networkInterfaceOptions"
+ err = _va_options_value_error(p, own, xml_prefix)
+ if err:
+ return err
+ tcp = _p(p, f"{own}.Protocol") == "tcp"
+ if endpoint_type == "load-balancer":
+ # A tcp load balancer endpoint takes no Port, and AWS doesn't ask it for subnets.
+ for member in (("LoadBalancerArn",) if tcp else ("Port", "SubnetId", "LoadBalancerArn")):
+ if not _va_has_prefix(p, f"LoadBalancerOptions.{member}"):
+ name = "SubnetIds" if member == "SubnetId" else member
+ return _va_missing_value(f"{name} must be provided in LoadBalancerOptions")
+ elif not _p(p, "NetworkInterfaceOptions.NetworkInterfaceId"):
+ return _va_missing_value("Missing required parameter NetworkInterfaceId")
+ return None
+
+
+def _va_subnets_error(options):
+ if any(subnet not in _subnets for subnet in options.get("SubnetIds", [])):
+ return _va_invalid("Invalid value for parameter SubnetIds")
+ return None
+
+
+def _va_parse_target_options(p, prefix, arn_key=None):
+ opts = _va_struct(p, prefix, ("Protocol", "Port") + ((arn_key,) if arn_key else ()))
+ subnets = _parse_member_list(p, f"{prefix}.SubnetId")
+ if subnets:
+ opts["SubnetIds"] = subnets
+ return opts
+
+
+def _create_verified_access_endpoint(p):
+ group_id = _p(p, "VerifiedAccessGroupId")
+ if not group_id:
+ return _va_missing_value("Missing required parameter VerifiedAccessGroupId")
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ endpoint_type, attachment_type = _p(p, "EndpointType"), _p(p, "AttachmentType")
+ # Values AWS refuses are reported together, before a missing member.
+ bad = [f"The value of {name} you provided is not valid"
+ for name, value, allowed in (("endpointType", endpoint_type, _VA_ENDPOINT_TYPES),
+ ("attachmentType", attachment_type, _VA_ATTACHMENT_TYPES))
+ if value and value not in allowed]
+ if bad:
+ return _va_invalid("; ".join(bad))
+ for member, value in (("EndpointType", endpoint_type), ("AttachmentType", attachment_type)):
+ if not value:
+ return _va_missing_value(f"Required parameter {member} was empty or null in the request")
+ err = _va_endpoint_type_error(p, endpoint_type)
+ if err:
+ return err
+ if endpoint_type == "load-balancer":
+ options = _va_parse_target_options(p, "LoadBalancerOptions", "LoadBalancerArn")
+ err = _va_subnets_error(options)
+ if err:
+ return err
+ if not _va_load_balancer_exists(options["LoadBalancerArn"]):
+ return _va_invalid("The LoadBalancerArn is invalid")
+ else:
+ options = _va_parse_target_options(p, "NetworkInterfaceOptions", "NetworkInterfaceId")
+ if options["NetworkInterfaceId"] not in _network_interfaces:
+ return _va_invalid("NetworkInterfaceId is invalid")
+ security_groups = _parse_member_list(p, "SecurityGroupId")
+ if any(sg not in _security_groups for sg in security_groups):
+ return _va_invalid("The Security Group Ids are invalid")
+ inst_id = group["VerifiedAccessInstanceId"]
+ if options.get("Protocol") == "tcp":
+ if not security_groups:
+ return _va_missing_value("Security Group Ids must be provided if attachment type vpc is selected")
+ # MiniStack emulates no NativeApplicationOidcOptions provider, so a tcp endpoint is never possible.
+ return _va_invalid("TCP based endpoints require a TrustProvider with NativeApplicationOidcOptions to be "
+ "attached to the instance.")
+ for member in ("DomainCertificateArn", "ApplicationDomain", "EndpointDomainPrefix"):
+ if not _p(p, member):
+ return _va_missing_value(f"Missing required parameter {member}")
+ prefix = _p(p, "EndpointDomainPrefix")
+ if not _VA_PREFIX_RE.fullmatch(prefix):
+ return _va_invalid("The EndpointDomainPrefix provided in the request contains unsupported characters")
+ if len(prefix) > 20:
+ return _va_invalid("Provided EndpointDomainPrefix exceeds max character limit of 20 characters")
+ domain = _p(p, "ApplicationDomain")
+ err = _va_certificate_error(_p(p, "DomainCertificateArn"), domain)
+ if err:
+ return err
+ if not security_groups:
+ return _va_missing_value("Security Group Ids must be provided if attachment type vpc is selected")
+ # The group's instance (which may be gone, or hold only device providers
+ # after a move) needs an OIDC provider.
+ inst = _va_instances.get(inst_id) or {}
+ if not any(_va_trust_providers.get(tp_id, {}).get("UserTrustProviderType") == "oidc"
+ for tp_id in inst.get("TrustProviderIds", [])):
+ return _va_invalid("HTTP/HTTPS based endpoints require a TrustProvider with OidcOptions to be attached to the instance.")
+ if any(ep["VerifiedAccessInstanceId"] == inst_id and ep["ApplicationDomain"] == domain
+ for ep in _va_live_endpoints()):
+ return _va_invalid(f"ApplicationDomain provided is already in use by another endpoint in "
+ f"VerifiedAccessInstance {inst_id}. ApplicationDomain must be unique within a "
+ "Verified Access Instance.")
+ policy = _p(p, "PolicyDocument")
+ sse, err = _va_sse_from(p)
+ if err:
+ return err
+ now = _va_now()
+ ep_id = _va_id("vae")
+ edge = _va_hex17()
+ host = f"{prefix}.edge-{edge}.{inst_id}.prod.verified-access.{get_region()}"
+ # One device validation id per instance, shared by its endpoints.
+ validation_id = _va_instances[inst_id].setdefault("DeviceValidationId", _va_hex17())
+ record = {
+ "VerifiedAccessInstanceId": inst_id,
+ "VerifiedAccessGroupId": group["VerifiedAccessGroupId"],
+ "VerifiedAccessEndpointId": ep_id,
+ "ApplicationDomain": domain,
+ "EndpointType": endpoint_type,
+ "AttachmentType": _p(p, "AttachmentType"),
+ "DomainCertificateArn": _p(p, "DomainCertificateArn"),
+ "EndpointDomain": f"{host}.amazonaws.com",
+ "DeviceValidationDomain": f"edge-{edge}.vld-{validation_id}.vld.prod.verified-access.{get_region()}.amazonaws.com",
+ "SecurityGroupIds": security_groups,
+ "LoadBalancerOptions": options if endpoint_type == "load-balancer" else None,
+ "NetworkInterfaceOptions": options if endpoint_type == "network-interface" else None,
+ "Status": "pending",
+ "Description": _p(p, "Description"),
+ "CreationTime": now,
+ "LastUpdatedTime": now,
+ "SseSpecification": sse,
+ "PolicyEnabled": bool(policy),
+ "PolicyDocument": policy,
+ }
+ _va_endpoints[ep_id] = record
+ _parse_tag_specs(p, "verified-access-endpoint", ep_id)
+ return _xml(200, "CreateVerifiedAccessEndpointResponse", _va_endpoint_xml(record, with_tags=True))
+
+
+def _va_drop_endpoints(keep):
+ for ep in [ep for ep in _va_endpoints.values() if not keep(ep)]:
+ _va_endpoints.pop(ep["VerifiedAccessEndpointId"], None)
+ _tags.pop(ep["VerifiedAccessEndpointId"], None)
+
+
+def _describe_verified_access_endpoints(p):
+ # A deleting endpoint is listed once more and dropped when a new listing
+ # starts (a request without NextToken), so pages of one listing keep their offsets.
+ selected, token, err = _va_describe(p, "Endpoint", (5, 200), members=("Instance", "Group"), exclusive=True)
+ if err:
+ return err
+ if not _p(p, "NextToken") and any(ep.get("DeletingListed") for ep in _va_endpoints.values()):
+ _va_drop_endpoints(lambda ep: not ep.get("DeletingListed"))
+ selected, token, err = _va_describe(p, "Endpoint", (5, 200), members=("Instance", "Group"), exclusive=True)
+ if err:
+ return err
+ for ep in selected:
+ _va_settle(ep)
+ items = "".join(_va_endpoint_xml(ep, tag="item", with_tags=True) for ep in selected)
+ for ep in selected:
+ if ep["Status"] == "deleting":
+ ep["DeletingListed"] = True
+ return _xml(200, "DescribeVerifiedAccessEndpointsResponse",
+ f"<verifiedAccessEndpointSet>{items}</verifiedAccessEndpointSet>"
+ f"{_va_next_token_xml(token)}")
+
+
+_VA_ENDPOINT_OPTION_TYPES = (("LoadBalancerOptions", "load-balancer"), ("NetworkInterfaceOptions", "network-interface"),
+ ("RdsOptions", "rds"), ("CidrOptions", "cidr"))
+
+
+def _modify_verified_access_endpoint(p):
+ err = _va_require(p, "VerifiedAccessEndpointId")
+ if err:
+ return err
+ ep, err = _va_lookup(p, "Endpoint")
+ if err:
+ return err
+ group = None
+ if _va_has_prefix(p, "VerifiedAccessGroupId"):
+ group, err = _va_lookup(p, "Group")
+ if err:
+ return err
+ # This type's option values come before the other types' options.
+ own = "LoadBalancerOptions" if ep["EndpointType"] == "load-balancer" else "NetworkInterfaceOptions"
+ xml_prefix = "loadBalancerOptions" if own == "LoadBalancerOptions" else "networkInterfaceOptions"
+ err = _va_options_value_error(p, own, xml_prefix, tcp=False)
+ if err:
+ return err
+ for key, owner in _VA_ENDPOINT_OPTION_TYPES:
+ if ep["EndpointType"] != owner and _va_has_prefix(p, key):
+ return _va_combination(f"{key} may only be specified for Verified Access Endpoints with {owner} type")
+ if (_p(p, f"{own}.Protocol") == "tcp") != ((ep[own] or {}).get("Protocol") == "tcp") and _p(p, f"{own}.Protocol"):
+ return _va_invalid("Protocol cannot be modified between HTTP/HTTPS and TCP")
+ if _va_indexed(p, f"{own}.PortRange"):
+ return _va_invalid("Parameter PortRanges is not currently supported for the operation")
+ # The Modify*Options shapes carry no LoadBalancerArn/NetworkInterfaceId.
+ update = _va_parse_target_options(p, own)
+ err = _va_subnets_error(update)
+ if err:
+ return err
+ if group and group["VerifiedAccessInstanceId"] != ep["VerifiedAccessInstanceId"]:
+ return _va_invalid("Cannot move a VerifiedAccessEndpoint to a VerifiedAccessGroup that belongs to "
+ "a different VerifiedAccessInstance.")
+ if group:
+ ep["VerifiedAccessGroupId"] = group["VerifiedAccessGroupId"]
+ ep["VerifiedAccessInstanceId"] = group["VerifiedAccessInstanceId"]
+ if update:
+ ep[own] = {**ep[own], **update}
+ if "Description" in p:
+ ep["Description"] = _p(p, "Description")
+ ep["Status"] = "updating"
+ ep["LastUpdatedTime"] = _va_now()
+ return _xml(200, "ModifyVerifiedAccessEndpointResponse", _va_endpoint_xml(ep))
+
+
+def _delete_verified_access_endpoint(p):
+ err = _va_require(p, "VerifiedAccessEndpointId")
+ if err:
+ return err
+ ep, err = _va_lookup(p, "Endpoint")
+ if err:
+ return err
+ # AWS answers deleting; Describe lists the endpoint as deleting for a few
+ # minutes while every other call already answers NotFound. MiniStack lists
+ # it once more and then drops it.
+ ep["Status"] = "deleting"
+ body = _va_endpoint_xml(ep)
+ ep["LastUpdatedTime"] = _va_now()
+ return _xml(200, "DeleteVerifiedAccessEndpointResponse", body)
+
+
+def _get_verified_access_endpoint_policy(p):
+ err = _va_require(p, "VerifiedAccessEndpointId")
+ if err:
+ return err
+ ep, err = _va_lookup(p, "Endpoint")
+ if err:
+ return err
+ return _xml(200, "GetVerifiedAccessEndpointPolicyResponse", _va_get_policy_xml(ep))
+
+
+def _modify_verified_access_endpoint_policy(p):
+ err = _va_require(p, "VerifiedAccessEndpointId")
+ if err:
+ return err
+ ep, err = _va_lookup(p, "Endpoint")
+ if err:
+ return err
+ err = _va_modify_policy(ep, p)
+ if err:
+ return err
+ ep["Status"] = "updating"
+ return _xml(200, "ModifyVerifiedAccessEndpointPolicyResponse", _va_modify_policy_xml(ep))
+
+
+_VA_STORES.update({
+ "Instance": _va_instances,
+ "TrustProvider": _va_trust_providers,
+ "Group": _va_groups,
+ "Endpoint": _va_endpoints,
+})
+
+_VERIFIED_ACCESS_ACTIONS = {
+ "CreateVerifiedAccessInstance": _create_verified_access_instance,
+ "DescribeVerifiedAccessInstances": _describe_verified_access_instances,
+ "ModifyVerifiedAccessInstance": _modify_verified_access_instance,
+ "DeleteVerifiedAccessInstance": _delete_verified_access_instance,
+ "CreateVerifiedAccessTrustProvider": _create_verified_access_trust_provider,
+ "DescribeVerifiedAccessTrustProviders": _describe_verified_access_trust_providers,
+ "ModifyVerifiedAccessTrustProvider": _modify_verified_access_trust_provider,
+ "DeleteVerifiedAccessTrustProvider": _delete_verified_access_trust_provider,
+ "AttachVerifiedAccessTrustProvider": _attach_verified_access_trust_provider,
+ "DetachVerifiedAccessTrustProvider": _detach_verified_access_trust_provider,
+ "ModifyVerifiedAccessInstanceLoggingConfiguration": _modify_verified_access_instance_logging_configuration,
+ "DescribeVerifiedAccessInstanceLoggingConfigurations": _describe_verified_access_instance_logging_configurations,
+ "CreateVerifiedAccessGroup": _create_verified_access_group,
+ "DescribeVerifiedAccessGroups": _describe_verified_access_groups,
+ "ModifyVerifiedAccessGroup": _modify_verified_access_group,
+ "DeleteVerifiedAccessGroup": _delete_verified_access_group,
+ "GetVerifiedAccessGroupPolicy": _get_verified_access_group_policy,
+ "ModifyVerifiedAccessGroupPolicy": _modify_verified_access_group_policy,
+ "CreateVerifiedAccessEndpoint": _create_verified_access_endpoint,
+ "DescribeVerifiedAccessEndpoints": _describe_verified_access_endpoints,
+ "ModifyVerifiedAccessEndpoint": _modify_verified_access_endpoint,
+ "DeleteVerifiedAccessEndpoint": _delete_verified_access_endpoint,
+ "GetVerifiedAccessEndpointPolicy": _get_verified_access_endpoint_policy,
+ "ModifyVerifiedAccessEndpointPolicy": _modify_verified_access_endpoint_policy,
+}
+
+
_ACTION_MAP = {
"RunInstances": _run_instances,
@@ -7399,4 +8842,5 @@ _ACTION_MAP = {
"DeleteLaunchTemplate": _delete_launch_template,
"CreateFleet": _create_fleet,
"DescribeFleets": _describe_fleets,
+ **_VERIFIED_ACCESS_ACTIONS,
}
diff --git a/tests/test_ec2_verified_access.py b/tests/test_ec2_verified_access.py
new file mode 100644
index 00000000..c4a82254
--- /dev/null
+++ b/tests/test_ec2_verified_access.py
@@ -0,0 +1,1948 @@
+"""EC2 Verified Access control plane: the calls the Terraform aws_verifiedaccess_* resources make.
+
+Expected codes, messages and orders are AWS's answers in us-east-1; each test names the
+capture keys it follows (A/B/C/D/E/F: reads, W: writes, X/Y: load-balancer endpoints,
+V: device providers, groups, logging and a network-interface endpoint, Z: check orders).
+"""
+
+import uuid
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+from conftest import ENDPOINT, make_client
+
+_POLICY = 'permit(principal, action, resource) when { context.idp.email like "*@example.com" };'
+_OIDC = {
+ "Issuer": "https://login.example.com",
+ "AuthorizationEndpoint": "https://login.example.com/authorize",
+ "TokenEndpoint": "https://login.example.com/token",
+ "UserInfoEndpoint": "https://login.example.com/userinfo",
+ "ClientId": "client",
+ "ClientSecret": "secret",
+ "Scope": "openid email",
+}
+_MISSING = {"Instance": "vai-0000000000000000a", "TrustProvider": "vatp-0000000000000000a",
+ "Group": "vagr-0000000000000000a", "Endpoint": "vae-0000000000000000a"}
+
+
+def _client(region="us-east-1", account_id="test", service="ec2", validate=True):
+ return boto3.client(
+ service, endpoint_url=ENDPOINT, region_name=region,
+ aws_access_key_id=account_id, aws_secret_access_key="test",
+ config=Config(region_name=region, retries={"total_max_attempts": 1}, parameter_validation=validate),
+ )
+
+
+def raw():
+ """An EC2 client that sends requests botocore would refuse to build."""
+ return _client(validate=False)
+
+
+def _oidc_provider(ec2, ref="idp", **extra):
+ return ec2.create_verified_access_trust_provider(
+ TrustProviderType="user", UserTrustProviderType="oidc", PolicyReferenceName=ref,
+ OidcOptions=dict(_OIDC), **extra)["VerifiedAccessTrustProvider"]
+
+
+def _device_provider(ec2, device_type="jamf", **options):
+ return ec2.create_verified_access_trust_provider(
+ TrustProviderType="device", DeviceTrustProviderType=device_type, PolicyReferenceName=device_type,
+ DeviceOptions={"TenantId": "tenant-1", **options})["VerifiedAccessTrustProvider"]
+
+
+def _instance(ec2, **extra):
+ return ec2.create_verified_access_instance(**extra)["VerifiedAccessInstance"]["VerifiedAccessInstanceId"]
+
+
+def _attach(ec2, inst_id, tp_id):
+ ec2.attach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=tp_id)
+
+
+def _instance_with_provider(ec2):
+ """An instance with an OIDC provider attached: AWS refuses groups on an instance without one."""
+ inst_id = _instance(ec2)
+ tp_id = _oidc_provider(ec2)["VerifiedAccessTrustProviderId"]
+ _attach(ec2, inst_id, tp_id)
+ return inst_id, tp_id
+
+
+def _group(ec2, inst_id, **extra):
+ return ec2.create_verified_access_group(
+ VerifiedAccessInstanceId=inst_id, **extra)["VerifiedAccessGroup"]["VerifiedAccessGroupId"]
+
+
+def _error(exc):
+ err = exc.value.response["Error"]
+ return err["Code"], err["Message"]
+
+
+def _status(exc):
+ return exc.value.response["ResponseMetadata"]["HTTPStatusCode"]
+
+
+def _provider_ids(ec2, inst_id):
+ inst = ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]
+ return [p["VerifiedAccessTrustProviderId"] for p in inst["VerifiedAccessTrustProviders"]]
+
+
+def _cleanup(ec2, groups=(), instances=(), providers=()):
+ for group_id in groups:
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=group_id)
+ for inst_id in instances:
+ for tp_id in _provider_ids(ec2, inst_id):
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=tp_id)
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+ for tp_id in providers:
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id)
+
+
+# ── Trust providers ────────────────────────────────────────
+
+
+def test_verified_access_oidc_trust_provider_lifecycle(ec2):
+ """W2:create:oidc-idp, W2:describe:oidc-idp, W2:modify:oidc-scope-only, V6:delete:tp, V6:describe:tp-after-delete."""
+ tp = _oidc_provider(ec2, Description="corp idp", TagSpecifications=[
+ {"ResourceType": "verified-access-trust-provider", "Tags": [{"Key": "team", "Value": "platform"}]}])
+ tp_id = tp["VerifiedAccessTrustProviderId"]
+ assert tp_id.startswith("vatp-") and len(tp_id) == 22
+ assert (tp["TrustProviderType"], tp["UserTrustProviderType"], tp["Description"]) == ("user", "oidc", "corp idp")
+ assert tp["OidcOptions"] == {**_OIDC, "ClientSecret": "REDACTED"}
+ assert tp["SseSpecification"] == {"CustomerManagedKeyEnabled": False}
+ assert tp["Tags"] == [{"Key": "team", "Value": "platform"}]
+
+ described = ec2.describe_verified_access_trust_providers(
+ VerifiedAccessTrustProviderIds=[tp_id])["VerifiedAccessTrustProviders"][0]
+ assert described["PolicyReferenceName"] == "idp"
+ assert described["OidcOptions"]["ClientSecret"] == "REDACTED"
+
+ modified = ec2.modify_verified_access_trust_provider(
+ VerifiedAccessTrustProviderId=tp_id, Description="renamed", OidcOptions={"Scope": "openid"},
+ )["VerifiedAccessTrustProvider"]
+ assert modified["Description"] == "renamed"
+ assert modified["OidcOptions"] == {**_OIDC, "Scope": "openid", "ClientSecret": "REDACTED"}
+ assert "Tags" not in modified
+
+ deleted = ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id)["VerifiedAccessTrustProvider"]
+ assert deleted["VerifiedAccessTrustProviderId"] == tp_id
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_verified_access_trust_providers(VerifiedAccessTrustProviderIds=[tp_id])
+ assert _error(exc) == ("InvalidVerifiedAccessTrustProviderId.NotFound", f"VerifiedAccessTrustProvider {tp_id} does not exist")
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id)
+ assert _error(exc) == ("InvalidVerifiedAccessTrustProviderId.NotFound", f"VerifiedAccessTrustProvider {tp_id} does not exist")
+
+
+def test_verified_access_device_trust_providers(ec2, raw):
+ """V1:create:jamf, V1:create:crowdstrike, W2:create:jumpcloud, W2:create:jumpcloud:tenant-only, W2:modify:device-url-only, V1:modify:url-on-jamf,
+ V1:create:crowdstrike-url, W2:create:jamf."""
+ jamf = _device_provider(ec2, "jamf")
+ assert jamf["DeviceOptions"] == {"TenantId": "tenant-1"}
+ assert "UserTrustProviderType" not in jamf and jamf["Description"] == ""
+ crowdstrike = _device_provider(ec2, "crowdstrike")
+ assert crowdstrike["DeviceOptions"] == {
+ "TenantId": "tenant-1", "PublicSigningKeyUrl": "https://assets-public.falcon.crowdstrike.com/zta/jwk.json"}
+ # W2:create:jumpcloud:tenant-only: AWS fills jumpcloud's key URL in too.
+ default_jc = _device_provider(ec2, "jumpcloud")
+ assert default_jc["DeviceOptions"] == {"TenantId": "tenant-1",
+ "PublicSigningKeyUrl": "https://go.jumpcloud.com/.well-known/jwks.json"}
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=default_jc["VerifiedAccessTrustProviderId"])
+ jumpcloud = _device_provider(ec2, "jumpcloud", PublicSigningKeyUrl="https://keys.example.com")
+ modified = ec2.modify_verified_access_trust_provider(
+ VerifiedAccessTrustProviderId=jumpcloud["VerifiedAccessTrustProviderId"],
+ DeviceOptions={"PublicSigningKeyUrl": "https://keys2.example.com"})["VerifiedAccessTrustProvider"]
+ assert modified["DeviceOptions"] == {"TenantId": "tenant-1", "PublicSigningKeyUrl": "https://keys2.example.com"}
+
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_trust_provider(
+ VerifiedAccessTrustProviderId=jamf["VerifiedAccessTrustProviderId"],
+ DeviceOptions={"PublicSigningKeyUrl": "https://keys2.example.com"})
+ assert _error(exc) == ("InvalidParameterValue", "Parameter DeviceOptions is not allowed when DeviceTrustProviderType is jamf")
+ for device_type in ("jamf", "crowdstrike"):
+ with pytest.raises(ClientError) as exc:
+ _device_provider(ec2, device_type, PublicSigningKeyUrl="https://keys.example.com")
+ assert _error(exc) == ("InvalidParameterValue",
+ f"Parameter PublicSigningKeyUrl is not allowed when DeviceTrustProviderType is {device_type}")
+ _cleanup(ec2, providers=[p["VerifiedAccessTrustProviderId"] for p in (jamf, crowdstrike, jumpcloud)])
+
+
+_TP_CREATE_ERRORS = [
+ # (capture key, request, code, message)
+ ("E1:CreateVerifiedAccessTrustProvider:no-params", {}, "MissingParameter",
+ "The request must include the following parameters: PolicyReferenceName, TrustProviderType. "
+ "Add the required parameters and retry the request."),
+ ("W2:invalid:type=robot", {"TrustProviderType": "robot"}, "InvalidParameterValue",
+ "The value of trustProviderType you provided is not valid"),
+ ("W2:invalid:policy-ref=bad-chars", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf",
+ "PolicyReferenceName": "Bad Name!"}, "InvalidParameterValue",
+ "Value of parameter PolicyReferenceName must match regular expression [a-zA-Z_][a-zA-Z0-9_]*"),
+ ("W2:invalid:user+DeviceTrustProviderType", {"TrustProviderType": "user", "DeviceTrustProviderType": "jamf"},
+ "MissingParameter", "Missing UserTrustProviderType parameter required when TrustProviderType is user"),
+ ("W2:invalid:user-type=bogus", {"TrustProviderType": "user", "UserTrustProviderType": "bogus"},
+ "InvalidParameterValue", "The value of userTrustProviderType you provided is not valid"),
+ ("W2:invalid:user+both-types", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "DeviceTrustProviderType": "jamf", "OidcOptions": _OIDC},
+ "InvalidParameterCombination", "Parameter DeviceTrustProviderType is not allowed when TrustProviderType is user"),
+ ("W2:invalid:oidc+DeviceOptions", {"TrustProviderType": "user", "UserTrustProviderType": "oidc", "OidcOptions": _OIDC,
+ "DeviceOptions": {"TenantId": "t"}},
+ "InvalidParameterCombination", "Parameter DeviceOptions is not allowed when TrustProviderType is user"),
+ ("W2:invalid:oidc-without-OidcOptions", {"TrustProviderType": "user", "UserTrustProviderType": "oidc"},
+ "MissingParameter",
+ "Missing OidcOptions or NativeApplicationOidcOptions parameter required when UserTrustProviderType is oidc"),
+ ("W2:create:iam-identity-center", {"TrustProviderType": "user", "UserTrustProviderType": "iam-identity-center"},
+ "InvalidParameterValue", "IAM Identity Center is not enabled on your organization"),
+ ("V1:create:oidc-without-ClientSecret", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {k: v for k, v in _OIDC.items() if k != "ClientSecret"}},
+ "MissingParameter", "Missing required parameter ClientSecret in OidcOptions"),
+ ("W2:create:oidc-partial-options", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {"Issuer": "https://login.example.com"}},
+ "MissingParameter", "Missing required parameter AuthorizationEndpoint in OidcOptions"),
+ ("W2:create:oidc-http-issuer", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {**_OIDC, "Issuer": "http://login.example.com"}},
+ "InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL"),
+ ("V1:create:oidc-not-url", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {**_OIDC, "TokenEndpoint": "token"}},
+ "InvalidParameterValue", "Parameter TokenEndpoint in OidcOptions must be a valid HTTPS URL"),
+ ("W2:invalid:device+UserTrustProviderType", {"TrustProviderType": "device", "UserTrustProviderType": "oidc"},
+ "InvalidParameterCombination", "Parameter UserTrustProviderType is not allowed when TrustProviderType is device"),
+ ("W2:invalid:device-without-device-type", {"TrustProviderType": "device"}, "MissingParameter",
+ "Missing DeviceTrustProviderType parameter required when TrustProviderType is device"),
+ ("W2:invalid:device-type=bogus", {"TrustProviderType": "device", "DeviceTrustProviderType": "bogus"},
+ "InvalidParameterValue", "The value of deviceTrustProviderType you provided is not valid"),
+ ("W2:invalid:device+OidcOptions", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf", "OidcOptions": _OIDC},
+ "InvalidParameterCombination", "Parameter OidcOptions is not allowed when TrustProviderType is device"),
+ ("W2:create:jamf:no-options", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf"}, "MissingParameter",
+ "Missing DeviceOptions parameter required when TrustProviderType is device"),
+ ("W2:create:jamf:url-only", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf",
+ "DeviceOptions": {"PublicSigningKeyUrl": "https://keys.example.com"}},
+ "MissingParameter", "Missing required parameter TenantId in DeviceOptions"),
+ ("Z1:tp:type-bad+ref-bad", {"TrustProviderType": "robot", "PolicyReferenceName": "Bad Name!"}, "InvalidParameterValue",
+ "The value of trustProviderType you provided is not valid"),
+ ("Z1:tp:ref-too-long", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf", "DeviceOptions": {"TenantId": "t"},
+ "PolicyReferenceName": "a" * 33}, "InvalidParameterValue",
+ "Length of parameter PolicyReferenceName must be between 1 and 32"),
+ ("Z1:tp:oidc-no-options+device-type", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "DeviceTrustProviderType": "jamf"}, "MissingParameter",
+ "Missing OidcOptions or NativeApplicationOidcOptions parameter required when UserTrustProviderType is oidc"),
+ ("Z1:tp:iic+oidc-options", {"TrustProviderType": "user", "UserTrustProviderType": "iam-identity-center",
+ "OidcOptions": _OIDC}, "InvalidParameterCombination",
+ "Parameter OidcOptions is not allowed when UserTrustProviderType is iam-identity-center"),
+ ("Z1:tp:iic+device-options", {"TrustProviderType": "user", "UserTrustProviderType": "iam-identity-center",
+ "DeviceOptions": {"TenantId": "t"}}, "InvalidParameterValue",
+ "IAM Identity Center is not enabled on your organization"),
+ ("Z1:tp:oidc-missing-field+http-issuer", {"TrustProviderType": "user", "UserTrustProviderType": "oidc", "OidcOptions": {
+ k: v for k, v in {**_OIDC, "Issuer": "http://a.example.com"}.items() if k != "Scope"}},
+ "InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL"),
+ ("Z1:tp:oidc-http-userinfo", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {**_OIDC, "UserInfoEndpoint": "http://login.example.com/userinfo"}},
+ "InvalidParameterValue", "Parameter UserInfoEndpoint in OidcOptions must be a valid HTTPS URL"),
+ ("Z1:tp:oidc-issuer-upper-scheme", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {**_OIDC, "Issuer": "HTTPS://login.example.com"}},
+ "InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL"),
+ ("Z1:tp:oidc-long-scope", {"TrustProviderType": "user", "UserTrustProviderType": "oidc",
+ "OidcOptions": {**_OIDC, "Scope": "s" * 257}},
+ "InvalidParameterValue", "Length of parameter Scope in OidcOptions must be between 1 and 256"),
+ ("Z1:tp:device-type-missing+oidc", {"TrustProviderType": "device", "OidcOptions": _OIDC}, "InvalidParameterCombination",
+ "Parameter OidcOptions is not allowed when TrustProviderType is device"),
+ ("Z1:tp:device-type-bad+oidc", {"TrustProviderType": "device", "DeviceTrustProviderType": "bogus", "OidcOptions": _OIDC},
+ "InvalidParameterValue", "The value of deviceTrustProviderType you provided is not valid"),
+ ("Z1:tp:jumpcloud-http-url", {"TrustProviderType": "device", "DeviceTrustProviderType": "jumpcloud",
+ "DeviceOptions": {"TenantId": "t", "PublicSigningKeyUrl": "http://k.example.com"}},
+ "InvalidParameterValue", "Parameter PublicSigningKeyUrl must be a valid HTTPS URL"),
+ ("Z1:tp:jamf-url+sse-fake-key", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf",
+ "DeviceOptions": {"TenantId": "t", "PublicSigningKeyUrl": "https://k.example.com"},
+ "SseSpecification": {"CustomerManagedKeyEnabled": True, "KmsKeyArn":
+ "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"}},
+ "InvalidParameterValue", "Parameter PublicSigningKeyUrl is not allowed when DeviceTrustProviderType is jamf"),
+ ("Z1:tp:device-sse-enabled-no-key", {"TrustProviderType": "device", "DeviceTrustProviderType": "jamf",
+ "DeviceOptions": {"TenantId": "t"}, "SseSpecification": {"CustomerManagedKeyEnabled": True}},
+ "MissingParameter", "Invalid value for parameter KmsKeyArn"),
+]
+
+
[email protected]("key, request_params, code, message", _TP_CREATE_ERRORS, ids=[c[0] for c in _TP_CREATE_ERRORS])
+def test_verified_access_trust_provider_create_errors(raw, key, request_params, code, message):
+ params = dict(request_params)
+ if key != "E1:CreateVerifiedAccessTrustProvider:no-params":
+ params.setdefault("PolicyReferenceName", "x")
+ before = len(raw.describe_verified_access_trust_providers()["VerifiedAccessTrustProviders"])
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_trust_provider(**params)
+ assert (_status(exc), *_error(exc)) == (400, code, message)
+ assert len(raw.describe_verified_access_trust_providers()["VerifiedAccessTrustProviders"]) == before
+
+
+def test_verified_access_trust_provider_modify_errors(ec2):
+ """W2:modify:device-options-on-oidc, V1:modify:oidc-options-on-device, V1:modify:oidc-http-issuer."""
+ oidc = _oidc_provider(ec2)["VerifiedAccessTrustProviderId"]
+ device = _device_provider(ec2, "jumpcloud")["VerifiedAccessTrustProviderId"]
+ for tp_id, kwargs, message in (
+ (oidc, {"DeviceOptions": {"PublicSigningKeyUrl": "https://k.example.com"}},
+ "Parameter DeviceOptions is not allowed when TrustProviderType is user"),
+ (device, {"OidcOptions": {"Scope": "openid"}}, "Parameter OidcOptions is not allowed when TrustProviderType is device"),
+ (oidc, {"OidcOptions": {"Issuer": "http://x.example.com"}}, "Parameter Issuer in OidcOptions must be a valid HTTPS URL"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id, **kwargs)
+ assert _error(exc) == ("InvalidParameterValue", message)
+ assert ec2.describe_verified_access_trust_providers(
+ VerifiedAccessTrustProviderIds=[oidc])["VerifiedAccessTrustProviders"][0]["OidcOptions"]["Issuer"] == _OIDC["Issuer"]
+ _cleanup(ec2, providers=[oidc, device])
+
+
+# ── Instances and attachments ──────────────────────────────
+
+
+def test_verified_access_instance_attach_detach(ec2):
+ """V1:attach:jamf-to-second-instance and W3:attach:oidc-to-second-instance name the requested instance; W3:create:instance, V1:attach:*, V1:describe:after-attaches, W3:attach:oidc (response), V1:detach:crowdstrike,
+ V1:detach:crowdstrike-again, V1:attach:jamf-to-second-instance, W3:attach:second-oidc, V1:delete-tp:attached-device,
+ V1:delete:instance-with-provider-no-group, W8:delete:instance."""
+ inst_id = _instance(ec2, Description="platform", TagSpecifications=[
+ {"ResourceType": "verified-access-instance", "Tags": [{"Key": "Name", "Value": "va"}]}])
+ created = ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]
+ assert inst_id.startswith("vai-") and len(inst_id) == 21
+ assert (created["FipsEnabled"], created["VerifiedAccessTrustProviders"]) == (False, [])
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ oidc = _oidc_provider(ec2, Description="corp")["VerifiedAccessTrustProviderId"]
+ crowdstrike = _device_provider(ec2, "crowdstrike")["VerifiedAccessTrustProviderId"]
+ second_oidc = _oidc_provider(ec2, ref="idp2")["VerifiedAccessTrustProviderId"]
+ for tp_id in (jamf, oidc, crowdstrike):
+ attached = ec2.attach_verified_access_trust_provider(
+ VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=tp_id)
+ assert attached["VerifiedAccessTrustProvider"]["VerifiedAccessTrustProviderId"] == crowdstrike
+ # The attach response lists the providers without their descriptions; Describe lists them.
+ assert [p.get("Description") for p in attached["VerifiedAccessInstance"]["VerifiedAccessTrustProviders"]] == [None] * 3
+ described = ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]
+ assert [(p["VerifiedAccessTrustProviderId"], p.get("Description")) for p in described["VerifiedAccessTrustProviders"]] == [
+ (jamf, None), (oidc, "corp"), (crowdstrike, None)]
+
+ other = _instance(ec2)
+ with pytest.raises(ClientError) as exc:
+ _attach(ec2, other, jamf)
+ assert _error(exc) == ("VerifiedAccessTrustProviderAttachmentLimitExceeded",
+ f"VerifiedAccessTrustProvider {jamf} is already attached to VerifiedAccessInstance {other}")
+ with pytest.raises(ClientError) as exc:
+ _attach(ec2, inst_id, second_oidc)
+ assert _error(exc) == ("VerifiedAccessTrustProviderAttachmentLimitExceeded",
+ "Cannot have more than 1 VerifiedAccessTrustProvider with TrustProviderType user "
+ "attached to a VerifiedAccessInstance")
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=jamf)
+ assert _error(exc) == ("InvalidParameterValue", "VerifiedAccessTrustProvider has existing attachments. "
+ "Please remove all VerifiedAccessTrustProvider attachments before deleting.")
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+ assert _error(exc) == ("InvalidParameterValue", f"{inst_id} has existing attachments. "
+ "Remove all VerifiedAccessTrustProvider attachments before deleting.")
+
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=oidc)
+ assert _provider_ids(ec2, inst_id) == [jamf, crowdstrike]
+ with pytest.raises(ClientError) as exc:
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=oidc)
+ assert _error(exc) == ("InvalidParameterValue", f"Trust provider {oidc} is not attached to instance {inst_id}")
+
+ ec2.modify_verified_access_instance(VerifiedAccessInstanceId=inst_id, Description="changed")
+ assert ec2.describe_verified_access_instances(
+ VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]["Description"] == "changed"
+ _cleanup(ec2, instances=[inst_id, other], providers=[jamf, oidc, crowdstrike, second_oidc])
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+ assert _error(exc) == ("InvalidVerifiedAccessInstanceId.NotFound", f"The verified-access-instance ID '{inst_id}' does not exist")
+
+
+def test_verified_access_attachment_id_checks(ec2):
+ """W1:attach_*, W1:detach_*, V1:attach:malformed-*, V1:detach:malformed-*, W3:attach:*-missing-*, W3:detach:*-missing-*:
+ a well-formed id is looked up (instance first); a malformed one is reported only when no lookup failed."""
+ inst_id, tp_id = _instance_with_provider(ec2)
+ a, d = ec2.attach_verified_access_trust_provider, ec2.detach_verified_access_trust_provider
+ for call, inst, tp, code, message in (
+ (a, _MISSING["Instance"], _MISSING["TrustProvider"], "InvalidVerifiedAccessInstanceId.NotFound",
+ f"The verified-access-instance ID '{_MISSING['Instance']}' does not exist"),
+ (a, "abc", _MISSING["TrustProvider"], "InvalidVerifiedAccessTrustProviderId.NotFound",
+ f"The verified-access-trust-provider ID '{_MISSING['TrustProvider']}' does not exist"),
+ (a, "abc", tp_id, "InvalidParameterValue", "Length of parameter VerifiedAccessInstanceId must be between 5 and 21"),
+ (a, inst_id, "abc", "InvalidParameterValue", "Length of parameter VerifiedAccessTrustProviderId must be between 6 and 22"),
+ (d, "abc", _MISSING["TrustProvider"], "InvalidVerifiedAccessTrustProviderId.NotFound",
+ f"VerifiedAccessTrustProvider {_MISSING['TrustProvider']} does not exist"),
+ (d, _MISSING["Instance"], tp_id, "InvalidVerifiedAccessInstanceId.NotFound",
+ f"The verified-access-instance ID '{_MISSING['Instance']}' does not exist"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(VerifiedAccessInstanceId=inst, VerifiedAccessTrustProviderId=tp)
+ assert _error(exc) == (code, message)
+ _cleanup(ec2, instances=[inst_id], providers=[tp_id])
+
+
+def test_verified_access_user_provider_is_locked_while_groups_exist(ec2):
+ """V3:detach:with-group, V3:detach:device-with-group, W5:create:group-no-policy, V3:delete-instance:with-groups."""
+ inst_id, oidc = _instance_with_provider(ec2)
+ jumpcloud = _device_provider(ec2, "jumpcloud")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, inst_id, jumpcloud)
+ group_id = _group(ec2, inst_id)
+ with pytest.raises(ClientError) as exc:
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=oidc)
+ assert _error(exc) == ("VerifiedAccessGroupAttachmentExists",
+ f"VerifiedAccessInstance {inst_id} is not empty. Please remove all VerifiedAccessGroups "
+ "before attaching or detaching a VerifiedAccessTrustProvider with TrustProviderType user")
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=jumpcloud)
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+ assert _error(exc)[1] == (f"{inst_id} has existing attachments. "
+ "Remove all VerifiedAccessTrustProvider attachments before deleting.")
+
+ bare = _instance(ec2)
+ with pytest.raises(ClientError) as exc:
+ _group(ec2, bare)
+ assert _error(exc) == ("InvalidParameterValue", f"Must attach a TrustProvider to Instance {bare} before you can create a Group")
+ _cleanup(ec2, groups=[group_id], instances=[inst_id, bare], providers=[oidc, jumpcloud])
+
+
+def test_verified_access_round6_check_orders(ec2):
+ """Z2:create:group, Z2:attach:tp-inner-upper, Z2:attach:tp-upper-prefix, Z2:detach:tp-inner-upper, Z2:attach:both-malformed,
+ Z2:modify-group:group-abc+instance-fake, -group-fake+instance-abc, -group-abc+instance-real, Z2:modify-tp:oidc-device-options+bad-issuer,
+ Z2:create-group:no-provider+sse-fake."""
+ fake_key = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"
+ device_only = _instance(ec2)
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, device_only, jamf)
+ with pytest.raises(ClientError) as exc:
+ _group(ec2, device_only)
+ assert _error(exc) == ("InvalidParameterValue",
+ f"Must attach a 'user' TrustProvider to Instance {device_only} before you can create a Group")
+ bare = _instance(ec2)
+ with pytest.raises(ClientError) as exc:
+ _group(ec2, bare, SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": fake_key})
+ assert _error(exc) == ("InvalidParameterValue", f"Could not find the following key: {fake_key}")
+
+ inst_id, oidc = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ a, d = ec2.attach_verified_access_trust_provider, ec2.detach_verified_access_trust_provider
+ for call, tp, error in (
+ (a, "vatp-0000000A000000000", ("InvalidVerifiedAccessTrustProviderId.NotFound",
+ "The verified-access-trust-provider ID 'vatp-0000000A000000000' does not exist")),
+ (a, "VATP-00000000000000000", ("InvalidParameterValue",
+ "Value of parameter VerifiedAccessTrustProviderId must match regular expression [a-z0-9-]+")),
+ (d, "vatp-0000000A000000000", ("InvalidParameterValue",
+ "Value of parameter VerifiedAccessTrustProviderId must match regular expression [a-z0-9-]+")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=tp)
+ assert _error(exc) == error
+ with pytest.raises(ClientError) as exc:
+ a(VerifiedAccessInstanceId="abc", VerifiedAccessTrustProviderId="abc")
+ assert _error(exc)[1] == "Length of parameter VerifiedAccessTrustProviderId must be between 6 and 22"
+ other_oidc = _oidc_provider(ec2, ref="idp2")["VerifiedAccessTrustProviderId"]
+
+ mg = ec2.modify_verified_access_group
+ for group, inst, error in (
+ ("abc", _MISSING["Instance"], ("InvalidVerifiedAccessInstanceId.NotFound",
+ f"The verified-access-instance ID '{_MISSING['Instance']}' does not exist")),
+ (_MISSING["Group"], "abc", ("InvalidVerifiedAccessGroupId.NotFound",
+ f"The verified-access-group ID '{_MISSING['Group']}' does not exist")),
+ ("abc", inst_id, ("InvalidParameterValue", "Length of parameter VerifiedAccessGroupId must be between 6 and 22")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ mg(VerifiedAccessGroupId=group, VerifiedAccessInstanceId=inst)
+ assert _error(exc) == error
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=oidc, OidcOptions={"Issuer": "http://x.example.com"},
+ DeviceOptions={"PublicSigningKeyUrl": "https://k.example.com"})
+ assert _error(exc) == ("InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL")
+ _cleanup(ec2, groups=[group_id], instances=[device_only, bare, inst_id], providers=[jamf, oidc, other_oidc])
+
+
+def test_verified_access_round8_orders_and_orphans(ec2, raw):
+ """R1:*, R2:*, R3:* (round 8)."""
+ inst_id, oidc = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ other, other_oidc = _instance_with_provider(ec2)
+ spare = _oidc_provider(ec2, ref="idp3")["VerifiedAccessTrustProviderId"]
+ locked = ("VerifiedAccessGroupAttachmentExists",
+ f"VerifiedAccessInstance {inst_id} is not empty. Please remove all VerifiedAccessGroups before attaching "
+ "or detaching a VerifiedAccessTrustProvider with TrustProviderType user")
+ for call, tp in ((ec2.attach_verified_access_trust_provider, other_oidc),
+ (ec2.attach_verified_access_trust_provider, spare),
+ (ec2.detach_verified_access_trust_provider, spare)):
+ with pytest.raises(ClientError) as exc:
+ call(VerifiedAccessInstanceId=inst_id, VerifiedAccessTrustProviderId=tp)
+ assert _error(exc) == locked
+ with pytest.raises(ClientError) as exc:
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId="abc", VerifiedAccessTrustProviderId="abc")
+ assert _error(exc)[1] == "Length of parameter VerifiedAccessTrustProviderId must be between 6 and 22"
+ for group, inst, message in (
+ (group_id, "abc", "Length of parameter VerifiedAccessInstanceId must be between 5 and 21"),
+ (group_id, "VAI-00000000000000000", "Value of parameter VerifiedAccessInstanceId must match regular expression [a-z0-9-]+"),
+ ("abc", "abc", "Length of parameter VerifiedAccessGroupId must be between 6 and 22"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=group, VerifiedAccessInstanceId=inst)
+ assert _error(exc) == ("InvalidParameterValue", message)
+ for op, member, value in (("describe_verified_access_groups", "VerifiedAccessInstanceId", "vai-0000000A000000000"),
+ ("describe_verified_access_endpoints", "VerifiedAccessGroupId", "vagr-0000000A000000000")):
+ with pytest.raises(ClientError) as exc:
+ getattr(ec2, op)(**{member: value})
+ assert _error(exc)[1] == f"Value of parameter {member} must match regular expression [a-z0-9-]+"
+
+ # An instance holding a moved-in group and no provider can be deleted; the group stays.
+ bare = _instance(ec2)
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=group_id, VerifiedAccessInstanceId=bare)
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=bare)
+ orphan = ec2.describe_verified_access_groups(VerifiedAccessGroupIds=[group_id])["VerifiedAccessGroups"][0]
+ assert orphan["VerifiedAccessInstanceId"] == bare
+
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_trust_provider(TrustProviderType="device", UserTrustProviderType="oidc",
+ DeviceTrustProviderType="bogus", PolicyReferenceName="x")
+ assert _error(exc)[1] == "The value of deviceTrustProviderType you provided is not valid"
+ jumpcloud = _device_provider(ec2, "jumpcloud", PublicSigningKeyUrl="https://k.example.com")["VerifiedAccessTrustProviderId"]
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=jumpcloud, DeviceOptions={"PublicSigningKeyUrl": "keys"})
+ assert _error(exc) == ("InvalidParameterValue", "Parameter PublicSigningKeyUrl must be a valid HTTPS URL")
+
+ key = make_client("kms").create_key()["KeyMetadata"]
+ make_client("kms").create_alias(AliasName=f"alias/va-{uuid.uuid4().hex[:8]}", TargetKeyId=key["KeyId"])
+ sse = {"CustomerManagedKeyEnabled": True, "KmsKeyArn": key["Arn"]}
+ keyed = ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=jumpcloud, SseSpecification=sse)
+ assert keyed["VerifiedAccessTrustProvider"]["SseSpecification"] == sse
+ keyed_group = _group(ec2, other, SseSpecification=sse)
+ for arn, error in (
+ ("arn:aws:kms:us-east-1:000000000000:alias/x", ("InvalidParameterValue", "Invalid value for parameter KmsKeyArn")),
+ (key["Arn"].replace("000000000000", "123456789012"),
+ ("UnauthorizedOperation", "User does not have permission to invoke required action: kms:DescribeKey")),
+ (key["Arn"].replace("us-east-1", "us-west-2"),
+ ("InvalidParameterValue", f"Could not find the following key: {key['Arn'].replace('us-east-1', 'us-west-2')}")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_group_policy(VerifiedAccessGroupId=keyed_group,
+ SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": arn})
+ assert _error(exc) == error
+
+ before = ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[other])["VerifiedAccessInstances"][0]["LastUpdatedTime"]
+ import time
+ time.sleep(1.1)
+ ec2.modify_verified_access_instance_logging_configuration(VerifiedAccessInstanceId=other, AccessLogs={"IncludeTrustContext": True})
+ after = ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[other])["VerifiedAccessInstances"][0]["LastUpdatedTime"]
+ assert after > before
+ _cleanup(ec2, groups=[group_id, keyed_group], instances=[inst_id, other],
+ providers=[oidc, other_oidc, spare, jumpcloud])
+
+
+def test_verified_access_response_times_and_ids(ec2):
+ """V3:move:to-instance-without-provider, V3:describe:after-move, W5:modify:description, W2:modify:oidc-scope-only,
+ Q3:create:wild-one-level and Q5:create:same-domain-while-deleting (ids start with 0)."""
+ import time
+
+ inst_id, tp_id = _instance_with_provider(ec2)
+ assert inst_id[4] == "0" and tp_id[5] == "0"
+ group_id = _group(ec2, inst_id)
+ created = ec2.describe_verified_access_groups(VerifiedAccessGroupIds=[group_id])["VerifiedAccessGroups"][0]["LastUpdatedTime"]
+ time.sleep(1.1)
+ target = _instance(ec2)
+ moved = ec2.modify_verified_access_group(VerifiedAccessGroupId=group_id, VerifiedAccessInstanceId=target)["VerifiedAccessGroup"]
+ assert moved["LastUpdatedTime"] == created
+ after = ec2.describe_verified_access_groups(VerifiedAccessGroupIds=[group_id])["VerifiedAccessGroups"][0]["LastUpdatedTime"]
+ assert after > created
+ time.sleep(1.1)
+ renamed = ec2.modify_verified_access_group(VerifiedAccessGroupId=group_id, Description="x")["VerifiedAccessGroup"]
+ assert renamed["LastUpdatedTime"] > after
+ tp_before = ec2.describe_verified_access_trust_providers(
+ VerifiedAccessTrustProviderIds=[tp_id])["VerifiedAccessTrustProviders"][0]["LastUpdatedTime"]
+ time.sleep(1.1)
+ modified = ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id, Description="y")
+ assert modified["VerifiedAccessTrustProvider"]["LastUpdatedTime"] == tp_before
+ _cleanup(ec2, groups=[group_id], instances=[inst_id, target], providers=[tp_id])
+
+
+def test_verified_access_round9_kms_and_orders(ec2):
+ """S1:*, S2:* (round 9): KMS key state and region, SSE first on a provider modify."""
+ kms, kms_west = make_client("kms"), _client("us-west-2", service="kms")
+ inst_id, oidc = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ disabled = kms.create_key()["KeyMetadata"]["Arn"]
+ kms.disable_key(KeyId=disabled)
+ pending = kms.create_key()["KeyMetadata"]["Arn"]
+ kms.schedule_key_deletion(KeyId=pending, PendingWindowInDays=7)
+ west = kms_west.create_key()["KeyMetadata"]["Arn"]
+ for arn, error in ((disabled, ("InvalidParameterValue", f"The provided KMS key {disabled} is disabled")),
+ (pending, ("InvalidParameterValue", f"The provided KMS key {pending} is disabled")),
+ (west, ("InvalidParameterValue", f"Could not find the following key: {west}")),
+ ("arn:aws:kms:us-east-1:123456789012:alias/x",
+ ("UnauthorizedOperation", "User does not have permission to invoke required action: kms:DescribeKey"))):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_group_policy(VerifiedAccessGroupId=group_id,
+ SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": arn})
+ assert _error(exc) == error
+ fake_key = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"
+ jumpcloud = _device_provider(ec2, "jumpcloud", PublicSigningKeyUrl="https://k.example.com")["VerifiedAccessTrustProviderId"]
+ for tp_id, kwargs in ((jumpcloud, {"DeviceOptions": {"PublicSigningKeyUrl": "http://k.example.com"}}),
+ (oidc, {"OidcOptions": {"Issuer": "http://x.example.com"}})):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_trust_provider(VerifiedAccessTrustProviderId=tp_id, **kwargs,
+ SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": fake_key})
+ assert _error(exc) == ("InvalidParameterValue", f"Could not find the following key: {fake_key}")
+ _cleanup(ec2, groups=[group_id], instances=[inst_id], providers=[oidc, jumpcloud])
+
+
+def test_verified_access_instance_refuses_cidr_subdomain(ec2):
+ """MiniStack scope: cidr endpoints are not emulated, so the custom subdomain is refused and nothing is stored."""
+ before = len(ec2.describe_verified_access_instances()["VerifiedAccessInstances"])
+ with pytest.raises(ClientError) as exc:
+ ec2.create_verified_access_instance(CidrEndpointsCustomSubDomain="corp.example.com")
+ assert _error(exc)[0] == "UnsupportedOperation"
+ assert len(ec2.describe_verified_access_instances()["VerifiedAccessInstances"]) == before
+
+
+# ── Logging ────────────────────────────────────────────────
+
+
+def test_verified_access_logging_describe_lists_next_token_first(ec2):
+ """V4:logging:all-MaxResults-1 (round 4): the response lists nextToken before loggingConfigurationSet."""
+ import urllib.request
+
+ instances = [_instance(ec2), _instance(ec2)]
+ req = urllib.request.Request(
+ ENDPOINT, data=b"Action=DescribeVerifiedAccessInstanceLoggingConfigurations&Version=2016-11-15&MaxResults=1",
+ method="POST", headers={"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/ec2/aws4_request"})
+ with urllib.request.urlopen(req) as resp:
+ body = resp.read().decode()
+ assert -1 < body.index("<nextToken>") < body.index("<loggingConfigurationSet>")
+ _cleanup(ec2, instances=instances)
+
+
+def test_verified_access_logging_configuration(ec2):
+ """W4:describe:default, W4:log-version:*, W4:include-trust-context, V2:log:*, W4:s3+cw-enabled, W4:s3-only-in-request,
+ W4:s3-missing-bucket, W4:cw-missing-group, W4:firehose-missing, R3:logging:*."""
+ inst_id = _instance(ec2)
+ modify = ec2.modify_verified_access_instance_logging_configuration
+ default = ec2.describe_verified_access_instance_logging_configurations(
+ VerifiedAccessInstanceIds=[inst_id])["LoggingConfigurations"][0]
+ assert default == {"VerifiedAccessInstanceId": inst_id, "AccessLogs": {
+ "S3": {"Enabled": False}, "CloudWatchLogs": {"Enabled": False}, "KinesisDataFirehose": {"Enabled": False},
+ "LogVersion": "ocsf-1.0.0-rc.2", "IncludeTrustContext": False}}
+
+ logs = modify(VerifiedAccessInstanceId=inst_id, AccessLogs={"LogVersion": "OCSF-0.1"})["LoggingConfiguration"]["AccessLogs"]
+ assert logs["LogVersion"] == "ocsf-0.1"
+ # A request without LogVersion sets it back to the default.
+ logs = modify(VerifiedAccessInstanceId=inst_id, AccessLogs={"IncludeTrustContext": True})["LoggingConfiguration"]["AccessLogs"]
+ assert (logs["LogVersion"], logs["IncludeTrustContext"]) == ("ocsf-1.0.0-rc.2", True)
+ for access_logs, code, message in (
+ ({"LogVersion": "ocsf-1.0.0"}, "InvalidParameterValue", "Invalid value for parameter LogVersion"),
+ ({"LogVersion": "ocsf-0.1", "IncludeTrustContext": True}, "InvalidParameterCombination",
+ "The LogVersion ocsf-0.1 is not compatible with IncludeTrustContext true"),
+ ({"S3": {"Enabled": False, "BucketName": "b"}}, "InvalidParameterCombination",
+ "The parameter AccessLogs.S3.BucketName cannot be used when AccessLogs.S3.Enabled is false"),
+ ({"CloudWatchLogs": {"Enabled": False, "LogGroup": "/x"}}, "InvalidParameterCombination",
+ "The parameter AccessLogs.CloudWatchLogs.LogGroup cannot be used when AccessLogs.CloudWatchLogs.Enabled is false"),
+ ({"S3": {"Enabled": True}, "LogVersion": "ocsf-9"}, "MissingParameter", "Missing required parameter AccessLogs.S3.BucketName"),
+ ({"KinesisDataFirehose": {"Enabled": True}}, "MissingParameter",
+ "Missing required parameter AccessLogs.KinesisDataFirehose.DeliveryStream"),
+ ({"S3": {"Enabled": True, "BucketName": f"missing-{uuid.uuid4().hex[:8]}"},
+ "CloudWatchLogs": {"Enabled": True, "LogGroup": "/missing"}},
+ "LogDestinationNotFound", "Log destination resource identified by AccessLogs.S3.BucketName was not found"),
+ ({"CloudWatchLogs": {"Enabled": True, "LogGroup": "/missing"}}, "LogDestinationNotFound",
+ "Log destination resource identified by AccessLogs.CloudWatchLogs.LogGroup was not found"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ modify(VerifiedAccessInstanceId=inst_id, AccessLogs=access_logs)
+ assert _error(exc) == (code, message), access_logs
+
+ bucket, group = f"va-logs-{uuid.uuid4().hex[:8]}", f"/va/{uuid.uuid4().hex[:8]}"
+ make_client("s3").create_bucket(Bucket=bucket)
+ make_client("logs").create_log_group(logGroupName=group)
+ logs = modify(VerifiedAccessInstanceId=inst_id, AccessLogs={
+ "S3": {"Enabled": True, "BucketName": bucket, "Prefix": "va"},
+ "CloudWatchLogs": {"Enabled": True, "LogGroup": group}})["LoggingConfiguration"]["AccessLogs"]
+ assert logs["S3"] == {"Enabled": True, "BucketName": bucket, "Prefix": "va", "BucketOwner": "000000000000",
+ "DeliveryStatus": {"Code": "success"}}
+ assert logs["CloudWatchLogs"] == {"Enabled": True, "LogGroup": group, "DeliveryStatus": {"Code": "success"}}
+ # Destinations a request leaves out are kept.
+ logs = modify(VerifiedAccessInstanceId=inst_id, AccessLogs={"S3": {"Enabled": False}})["LoggingConfiguration"]["AccessLogs"]
+ assert logs["S3"] == {"Enabled": False}
+ assert logs["CloudWatchLogs"]["Enabled"] is True
+ modify(VerifiedAccessInstanceId=inst_id, AccessLogs={"CloudWatchLogs": {"Enabled": False}})
+ # R3:logging:firehose, R3:logging:describe-firehose.
+ stream = f"va-{uuid.uuid4().hex[:8]}"
+ make_client("firehose").create_delivery_stream(
+ DeliveryStreamName=stream, DeliveryStreamType="DirectPut",
+ S3DestinationConfiguration={"RoleARN": "arn:aws:iam::000000000000:role/fh", "BucketARN": f"arn:aws:s3:::{bucket}"})
+ logs = modify(VerifiedAccessInstanceId=inst_id, AccessLogs={
+ "KinesisDataFirehose": {"Enabled": True, "DeliveryStream": stream}})["LoggingConfiguration"]["AccessLogs"]
+ assert logs["KinesisDataFirehose"] == {"Enabled": True, "DeliveryStream": stream, "DeliveryStatus": {"Code": "success"}}
+ modify(VerifiedAccessInstanceId=inst_id, AccessLogs={"KinesisDataFirehose": {"Enabled": False}})
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+
+
+# ── Groups and policies ────────────────────────────────────
+
+
+def test_verified_access_group_lifecycle(ec2):
+ """W5:create:group, W5:describe:by-instance, W5:get-policy:new, V3:get-policy:none, W5:modify:description,
+ V3:move:to-instance-without-provider, V6:delete:group, V6:describe:group-after-delete, V6:delete:group-again."""
+ inst_id, tp_id = _instance_with_provider(ec2)
+ group = ec2.create_verified_access_group(VerifiedAccessInstanceId=inst_id, Description="apps", PolicyDocument=_POLICY,
+ TagSpecifications=[{"ResourceType": "verified-access-group",
+ "Tags": [{"Key": "team", "Value": "a"}]}])["VerifiedAccessGroup"]
+ group_id = group["VerifiedAccessGroupId"]
+ assert group_id.startswith("vagr-") and len(group_id) == 22
+ assert group["VerifiedAccessGroupArn"] == f"arn:aws:ec2:us-east-1:000000000000:verified-access-group/{group_id}"
+ assert (group["Owner"], group["SseSpecification"]) == ("000000000000", {"CustomerManagedKeyEnabled": False})
+ assert ec2.get_verified_access_group_policy(VerifiedAccessGroupId=group_id) | {"ResponseMetadata": None} == {
+ "PolicyEnabled": True, "PolicyDocument": _POLICY, "ResponseMetadata": None}
+ listed = ec2.describe_verified_access_groups(VerifiedAccessInstanceId=inst_id)["VerifiedAccessGroups"]
+ assert [(g["VerifiedAccessGroupId"], g["Tags"]) for g in listed] == [(group_id, [{"Key": "team", "Value": "a"}])]
+
+ bare_group = _group(ec2, inst_id)
+ policy = ec2.get_verified_access_group_policy(VerifiedAccessGroupId=bare_group)
+ assert (policy["PolicyEnabled"], "PolicyDocument" in policy) == (False, False)
+ modified = ec2.modify_verified_access_group(VerifiedAccessGroupId=bare_group, Description="renamed")["VerifiedAccessGroup"]
+ assert modified["Description"] == "renamed" and "Tags" not in modified
+ # A group can move to an instance without a trust provider.
+ target = _instance(ec2)
+ moved = ec2.modify_verified_access_group(VerifiedAccessGroupId=bare_group, VerifiedAccessInstanceId=target)
+ assert moved["VerifiedAccessGroup"]["VerifiedAccessInstanceId"] == target
+
+ deleted = ec2.delete_verified_access_group(VerifiedAccessGroupId=group_id)["VerifiedAccessGroup"]
+ assert deleted["DeletionTime"] and "Tags" not in deleted
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_verified_access_groups(VerifiedAccessGroupIds=[group_id])
+ assert _error(exc) == ("InvalidVerifiedAccessGroupId.NotFound", f"VerifiedAccessGroup {group_id} does not exist")
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=group_id)
+ assert _error(exc) == ("InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{group_id}' does not exist")
+ _cleanup(ec2, groups=[bare_group], instances=[inst_id, target], providers=[tp_id])
+
+
+def test_verified_access_group_policy_rules(ec2):
+ """W5:policy:*, V3:policy:*, W5:policy:sse-fake-key, W5:policy:sse-real-key, V3:policy:sse-key-not-enabled,
+ V3:create:group-sse-enabled-no-key, V3:create:group-sse-fake-key."""
+ inst_id, tp_id = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id, PolicyDocument=_POLICY)
+ modify = ec2.modify_verified_access_group_policy
+ for kwargs, code, message in (
+ ({"PolicyEnabled": True}, "MissingParameter", "Policy Document must be provided when Policy Enabled is true"),
+ ({"PolicyDocument": _POLICY}, "InvalidParameterValue", "Policy Document cannot be provided when Policy Enabled is false or missing"),
+ ({"PolicyEnabled": False, "PolicyDocument": _POLICY}, "InvalidParameterValue",
+ "Policy Document cannot be provided when Policy Enabled is false or missing"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ modify(VerifiedAccessGroupId=group_id, **kwargs)
+ assert _error(exc) == (code, message)
+ unchanged = modify(VerifiedAccessGroupId=group_id)
+ assert (unchanged["PolicyEnabled"], unchanged["PolicyDocument"]) == (True, _POLICY)
+
+ fake_key = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"
+ with pytest.raises(ClientError) as exc:
+ modify(VerifiedAccessGroupId=group_id, SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": fake_key})
+ assert _error(exc) == ("InvalidParameterValue", f"Could not find the following key: {fake_key}")
+ with pytest.raises(ClientError) as exc:
+ _group(ec2, inst_id, SseSpecification={"CustomerManagedKeyEnabled": True})
+ assert _error(exc) == ("MissingParameter", "Invalid value for parameter KmsKeyArn")
+ key_arn = make_client("kms").create_key()["KeyMetadata"]["Arn"]
+ with_key = modify(VerifiedAccessGroupId=group_id, SseSpecification={"CustomerManagedKeyEnabled": True, "KmsKeyArn": key_arn})
+ assert with_key["SseSpecification"] == {"CustomerManagedKeyEnabled": True, "KmsKeyArn": key_arn}
+ assert (with_key["PolicyEnabled"], with_key["PolicyDocument"]) == (True, _POLICY)
+ off = modify(VerifiedAccessGroupId=group_id, SseSpecification={"CustomerManagedKeyEnabled": False, "KmsKeyArn": key_arn})
+ assert off["SseSpecification"] == {"CustomerManagedKeyEnabled": False}
+
+ disabled = modify(VerifiedAccessGroupId=group_id, PolicyEnabled=False)
+ assert (disabled["PolicyEnabled"], "PolicyDocument" in disabled) == (False, False)
+ policy = ec2.get_verified_access_group_policy(VerifiedAccessGroupId=group_id)
+ assert (policy["PolicyEnabled"], "PolicyDocument" in policy) == (False, False)
+ _cleanup(ec2, groups=[group_id], instances=[inst_id], providers=[tp_id])
+
+
+# ── Describe and id checks ─────────────────────────────────
+
+
+_DESCRIBES = {
+ "instances": ("describe_verified_access_instances", "VerifiedAccessInstanceIds", "Instance", 5, 200),
+ "trust_providers": ("describe_verified_access_trust_providers", "VerifiedAccessTrustProviderIds", "TrustProvider", 5, 1000),
+ "groups": ("describe_verified_access_groups", "VerifiedAccessGroupIds", "Group", 5, 200),
+ "endpoints": ("describe_verified_access_endpoints", "VerifiedAccessEndpointIds", "Endpoint", 5, 200),
+ "logging": ("describe_verified_access_instance_logging_configurations", "VerifiedAccessInstanceIds", "Instance", 1, 10),
+}
+
+
[email protected]("name", list(_DESCRIBES))
+def test_verified_access_describe_checks(raw, name):
+ """A1:*, A12:*, B1:*, B12:*, C1:*, D1:* for each Describe call."""
+ op, member, kind, low, high = _DESCRIBES[name]
+ call = getattr(raw, op)
+ singular = member[:-1]
+ lengths = {"Instance": (5, 21), "TrustProvider": (6, 22), "Group": (6, 22), "Endpoint": (5, 21)}[kind]
+ missing = _MISSING[kind]
+ cases = [
+ ({member: [missing]}, f"InvalidVerifiedAccess{kind}Id.NotFound", f"VerifiedAccess{kind} {missing} does not exist"),
+ ({member: ["abc"]}, "InvalidParameterValue", f"Length of parameter {singular} must be between {lengths[0]} and {lengths[1]}"),
+ ({member: [missing[:4] + "_" + missing[5:]]}, "InvalidParameterValue",
+ f"Value of parameter {singular} must match regular expression [a-z0-9-]+"),
+ ({member: [missing, "abc"]}, "InvalidParameterValue",
+ f"Length of parameter {singular} must be between {lengths[0]} and {lengths[1]}"),
+ ({member: ["abc"], "MaxResults": low}, "InvalidParameterCombination",
+ f"The parameters {member} and MaxResults cannot be used together"),
+ ({member: [missing], "MaxResults": low, "NextToken": "x"}, "InvalidParameterCombination",
+ f"The parameters {member} and NextToken cannot be used together"),
+ ({"MaxResults": low - 1}, "InvalidParameterValue", f"The parameter MaxResults must be between {low} and {high}"),
+ ({"MaxResults": high + 1}, "InvalidParameterValue", f"The parameter MaxResults must be between {low} and {high}"),
+ ({"MaxResults": low - 1, "NextToken": "x"}, "InvalidParameterValue", f"The parameter MaxResults must be between {low} and {high}"),
+ ({"MaxResults": "abc"}, "InvalidParameterValue", "Invalid integer value abc"),
+ ({"NextToken": "not-a-token"}, "InvalidParameterValue", "Next token is invalid"),
+ ]
+ for params, code, message in cases:
+ with pytest.raises(ClientError) as exc:
+ call(**params)
+ assert (_status(exc), *_error(exc)) == (400, code, message), params
+ call(MaxResults=low)
+ call(MaxResults=high)
+ # Filter names AWS does not know are ignored.
+ call(Filters=[{"Name": "bogus", "Values": ["x"]}])
+
+
+def test_verified_access_describe_member_checks(raw):
+ """B1:groups:instance-missing+group-missing, C1:groups:*, C1:endpoints:*, D1:endpoints:*, D1:groups:*."""
+ vai, vagr, vae = _MISSING["Instance"], _MISSING["Group"], _MISSING["Endpoint"]
+ for op, params, code, message in (
+ ("describe_verified_access_groups", {"VerifiedAccessInstanceId": vai, "VerifiedAccessGroupIds": [vagr]},
+ "InvalidVerifiedAccessGroupId.NotFound", f"VerifiedAccessGroup {vagr} does not exist"),
+ ("describe_verified_access_groups", {"VerifiedAccessInstanceId": "abc", "VerifiedAccessGroupIds": [vagr]},
+ "InvalidParameterValue", "Length of parameter VerifiedAccessInstanceId must be between 5 and 21"),
+ ("describe_verified_access_groups", {"VerifiedAccessInstanceId": vai, "MaxResults": 0},
+ "InvalidParameterValue", "The parameter MaxResults must be between 5 and 200"),
+ ("describe_verified_access_groups", {"VerifiedAccessInstanceId": vai, "NextToken": "x"},
+ "InvalidParameterValue", "Next token is invalid"),
+ ("describe_verified_access_groups", {"VerifiedAccessInstanceId": vai},
+ "InvalidVerifiedAccessInstanceId.NotFound", f"VerifiedAccessInstance {vai} does not exist"),
+ ("describe_verified_access_endpoints", {"VerifiedAccessInstanceId": vai, "VerifiedAccessGroupId": vagr},
+ "InvalidParameterCombination", "The parameters VerifiedAccessInstanceId and VerifiedAccessGroupId cannot be used together"),
+ ("describe_verified_access_endpoints", {"VerifiedAccessInstanceId": "abc", "VerifiedAccessGroupId": "abc"},
+ "InvalidParameterValue", "Length of parameter VerifiedAccessInstanceId must be between 5 and 21"),
+ ("describe_verified_access_endpoints", {"VerifiedAccessInstanceId": vai, "VerifiedAccessGroupId": vagr, "MaxResults": 0},
+ "InvalidParameterValue", "The parameter MaxResults must be between 5 and 200"),
+ ("describe_verified_access_endpoints", {"VerifiedAccessInstanceId": vai, "VerifiedAccessEndpointIds": [vae]},
+ "InvalidVerifiedAccessEndpointId.NotFound", f"VerifiedAccessEndpoint {vae} does not exist"),
+ ("describe_verified_access_endpoints", {"VerifiedAccessGroupId": vagr},
+ "InvalidVerifiedAccessGroupId.NotFound", f"VerifiedAccessGroup {vagr} does not exist"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ getattr(raw, op)(**params)
+ assert _error(exc) == (code, message), params
+
+
+_REQUIRED = [
+ ("delete_verified_access_instance", "VerifiedAccessInstanceId"),
+ ("modify_verified_access_instance", "VerifiedAccessInstanceId"),
+ ("delete_verified_access_trust_provider", "VerifiedAccessTrustProviderId"),
+ ("modify_verified_access_trust_provider", "VerifiedAccessTrustProviderId"),
+ ("create_verified_access_group", "VerifiedAccessInstanceId"),
+ ("modify_verified_access_group", "VerifiedAccessGroupId"),
+ ("delete_verified_access_group", "VerifiedAccessGroupId"),
+ ("get_verified_access_group_policy", "VerifiedAccessGroupId"),
+ ("modify_verified_access_group_policy", "VerifiedAccessGroupId"),
+ ("modify_verified_access_endpoint", "VerifiedAccessEndpointId"),
+ ("delete_verified_access_endpoint", "VerifiedAccessEndpointId"),
+ ("get_verified_access_endpoint_policy", "VerifiedAccessEndpointId"),
+ ("modify_verified_access_endpoint_policy", "VerifiedAccessEndpointId"),
+]
+
+
[email protected]("op, member", _REQUIRED)
+def test_verified_access_missing_parameter(raw, op, member):
+ """E1:<Operation>:no-params."""
+ with pytest.raises(ClientError) as exc:
+ getattr(raw, op)()
+ assert _error(exc) == ("MissingParameter", f"The request must include the {member} parameter. "
+ "Add the required parameter and retry the request.")
+
+
+def test_verified_access_missing_parameters_listed(raw):
+ """E1:AttachVerifiedAccessTrustProvider:*, E1:DetachVerifiedAccessTrustProvider:*, E1:ModifyVerifiedAccessInstanceLoggingConfiguration:*,
+ W1:create_verified_access_endpoint:no-params."""
+ for call in (raw.attach_verified_access_trust_provider, raw.detach_verified_access_trust_provider):
+ with pytest.raises(ClientError) as exc:
+ call()
+ assert _error(exc)[1] == ("The request must include the following parameters: VerifiedAccessInstanceId, "
+ "VerifiedAccessTrustProviderId. Add the required parameters and retry the request.")
+ with pytest.raises(ClientError) as exc:
+ call(VerifiedAccessInstanceId=_MISSING["Instance"])
+ assert _error(exc)[1] == ("The request must include the VerifiedAccessTrustProviderId parameter. "
+ "Add the required parameter and retry the request.")
+ with pytest.raises(ClientError) as exc:
+ raw.modify_verified_access_instance_logging_configuration()
+ assert _error(exc)[1] == ("The request must include the following parameters: AccessLogs, VerifiedAccessInstanceId. "
+ "Add the required parameters and retry the request.")
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(EndpointType="load-balancer")
+ assert _error(exc) == ("MissingParameter", "Missing required parameter VerifiedAccessGroupId")
+
+
+_WRITE_ID_CHECKS = [
+ # (operation, member, kind, extra request members, NotFound wording)
+ ("modify_verified_access_instance", "VerifiedAccessInstanceId", "Instance", {}, "single"),
+ ("delete_verified_access_instance", "VerifiedAccessInstanceId", "Instance", {}, "single"),
+ ("modify_verified_access_instance_logging_configuration", "VerifiedAccessInstanceId", "Instance",
+ {"AccessLogs": {"IncludeTrustContext": False}}, "single"),
+ ("create_verified_access_group", "VerifiedAccessInstanceId", "Instance", {}, "single"),
+ ("modify_verified_access_trust_provider", "VerifiedAccessTrustProviderId", "TrustProvider", {}, "listed"),
+ ("delete_verified_access_trust_provider", "VerifiedAccessTrustProviderId", "TrustProvider", {}, "listed"),
+ ("modify_verified_access_group", "VerifiedAccessGroupId", "Group", {}, "single"),
+ ("delete_verified_access_group", "VerifiedAccessGroupId", "Group", {}, "single"),
+ ("modify_verified_access_group_policy", "VerifiedAccessGroupId", "Group", {}, "single"),
+ ("get_verified_access_group_policy", "VerifiedAccessGroupId", "Group", {}, "single"),
+ ("create_verified_access_endpoint", "VerifiedAccessGroupId", "Group",
+ {"EndpointType": "network-interface", "AttachmentType": "vpc"}, "single"),
+ ("modify_verified_access_endpoint", "VerifiedAccessEndpointId", "Endpoint", {}, "single"),
+ ("delete_verified_access_endpoint", "VerifiedAccessEndpointId", "Endpoint", {}, "single"),
+ ("modify_verified_access_endpoint_policy", "VerifiedAccessEndpointId", "Endpoint", {}, "single"),
+ ("get_verified_access_endpoint_policy", "VerifiedAccessEndpointId", "Endpoint", {}, "single"),
+]
+
+
[email protected]("op, member, kind, extra, wording", _WRITE_ID_CHECKS, ids=[c[0] for c in _WRITE_ID_CHECKS])
+def test_verified_access_id_checks_on_single_resource_calls(raw, op, member, kind, extra, wording):
+ """W1:<op>:missing/abc/upper/inner-upper/underscore, F1:get_verified_access_*_policy:*: trust provider calls
+ hold the whole id to the pattern; the other calls only the part before the first hyphen."""
+ missing = _MISSING[kind]
+ prefix, _, rest = missing.partition("-")
+ inner_upper = f"{prefix}-{rest[:7]}A{rest[8:]}"
+ pattern_error = ("InvalidParameterValue", f"Value of parameter {member} must match regular expression [a-z0-9-]+")
+ rtype = {"Instance": "instance", "TrustProvider": "trust-provider", "Group": "group", "Endpoint": "endpoint"}[kind]
+
+ def not_found(value):
+ if wording == "listed":
+ return f"InvalidVerifiedAccess{kind}Id.NotFound", f"VerifiedAccess{kind} {value} does not exist"
+ return f"InvalidVerifiedAccess{kind}Id.NotFound", f"The verified-access-{rtype} ID '{value}' does not exist"
+
+ lengths = {"Instance": (5, 21), "TrustProvider": (6, 22), "Group": (6, 22), "Endpoint": (5, 21)}[kind]
+ expected = {
+ missing: not_found(missing),
+ "abc": ("InvalidParameterValue", f"Length of parameter {member} must be between {lengths[0]} and {lengths[1]}"),
+ f"{prefix.upper()}-{rest}": pattern_error,
+ f"{prefix}_{rest}": pattern_error,
+ inner_upper: pattern_error if kind == "TrustProvider" else not_found(inner_upper),
+ }
+ for value, error in expected.items():
+ with pytest.raises(ClientError) as exc:
+ getattr(raw, op)(**{member: value}, **extra)
+ assert _error(exc) == error, value
+
+
+def test_verified_access_resources_are_regional_and_per_account(ec2):
+ """W6:region:instance, W6:region:tp, V3:region:group, V3:region:group-policy, W6:region:modify-instance."""
+ west, other = _client("us-west-2"), _client(account_id="123456789012")
+ inst_id, tp_id = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ for client in (west, other):
+ for call, kwargs, error in (
+ (client.describe_verified_access_instances, {"VerifiedAccessInstanceIds": [inst_id]},
+ ("InvalidVerifiedAccessInstanceId.NotFound", f"VerifiedAccessInstance {inst_id} does not exist")),
+ (client.describe_verified_access_trust_providers, {"VerifiedAccessTrustProviderIds": [tp_id]},
+ ("InvalidVerifiedAccessTrustProviderId.NotFound", f"VerifiedAccessTrustProvider {tp_id} does not exist")),
+ (client.describe_verified_access_groups, {"VerifiedAccessGroupIds": [group_id]},
+ ("InvalidVerifiedAccessGroupId.NotFound", f"VerifiedAccessGroup {group_id} does not exist")),
+ (client.get_verified_access_group_policy, {"VerifiedAccessGroupId": group_id},
+ ("InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{group_id}' does not exist")),
+ (client.modify_verified_access_instance, {"VerifiedAccessInstanceId": inst_id, "Description": "x"},
+ ("InvalidVerifiedAccessInstanceId.NotFound", f"The verified-access-instance ID '{inst_id}' does not exist")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ assert _error(exc) == error
+ _cleanup(ec2, groups=[group_id], instances=[inst_id], providers=[tp_id])
+
+
+def test_verified_access_tags_and_filters(ec2):
+ """V4:tags:describe-tags, V4:tags:delete-all, V4:tags:describe-untagged-group, W6:filter:*, V4:filter:*, V4:page:*."""
+ marker = uuid.uuid4().hex
+ tagged = [ec2.create_verified_access_trust_provider(
+ TrustProviderType="device", DeviceTrustProviderType="jumpcloud", PolicyReferenceName="j",
+ DeviceOptions={"TenantId": "t"}, TagSpecifications=[{"ResourceType": "verified-access-trust-provider",
+ "Tags": [{"Key": "run", "Value": marker}]}],
+ )["VerifiedAccessTrustProvider"]["VerifiedAccessTrustProviderId"] for _ in range(7)]
+ describe = ec2.describe_verified_access_trust_providers
+ by_tag = {tp["VerifiedAccessTrustProviderId"] for tp in describe(Filters=[{"Name": "tag:run", "Values": [marker]}])["VerifiedAccessTrustProviders"]}
+ assert by_tag == set(tagged)
+ assert describe(Filters=[{"Name": "tag:run", "Values": [marker]}, {"Name": "tag:Owner", "Values": ["nobody"]}])[
+ "VerifiedAccessTrustProviders"] == []
+ ignored = describe(Filters=[{"Name": "tag:run", "Values": [marker]}, {"Name": "bogus", "Values": ["x"]}])
+ assert len(ignored["VerifiedAccessTrustProviders"]) == 7
+ paged = [tp["VerifiedAccessTrustProviderId"]
+ for page in ec2.get_paginator("describe_verified_access_trust_providers").paginate(
+ Filters=[{"Name": "tag:run", "Values": [marker]}], PaginationConfig={"PageSize": 5})
+ for tp in page["VerifiedAccessTrustProviders"]]
+ assert sorted(paged) == sorted(tagged)
+
+ inst_id = _instance(ec2)
+ ec2.create_tags(Resources=[inst_id, tagged[0]], Tags=[{"Key": "env", "Value": "dev"}])
+ tags = ec2.describe_tags(Filters=[{"Name": "resource-id", "Values": [inst_id, tagged[0]]}, {"Name": "key", "Values": ["env"]}])["Tags"]
+ assert {(t["ResourceId"], t["ResourceType"]) for t in tags} == {
+ (inst_id, "verified-access-instance"), (tagged[0], "verified-access-trust-provider")}
+ ec2.delete_tags(Resources=[inst_id], Tags=[{"Key": "env"}])
+ assert ec2.describe_verified_access_instances(VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]["Tags"] == []
+ _cleanup(ec2, instances=[inst_id], providers=tagged)
+
+
+# ── Endpoints ──────────────────────────────────────────────
+
+
+def endpoint_fixture(ec2):
+ """An instance with a provider, a group, an internal ALB, an ENI and an issued certificate."""
+ subnets = [s["SubnetId"] for s in ec2.describe_subnets()["Subnets"]][:2]
+ lb_arn = make_client("elbv2").create_load_balancer(
+ Name=f"va-{uuid.uuid4().hex[:10]}", Subnets=subnets, Scheme="internal", Type="application",
+ )["LoadBalancers"][0]["LoadBalancerArn"]
+ eni = ec2.create_network_interface(SubnetId=subnets[0])["NetworkInterface"]["NetworkInterfaceId"]
+ vpc_id = ec2.describe_subnets(SubnetIds=subnets[:1])["Subnets"][0]["VpcId"]
+ sg = ec2.create_security_group(GroupName=f"va-{uuid.uuid4().hex[:8]}", Description="va", VpcId=vpc_id)["GroupId"]
+ cert = make_client("acm").request_certificate(
+ DomainName="app.example.com", SubjectAlternativeNames=["app.example.com", "eni.example.com"])["CertificateArn"]
+ inst_id, tp_id = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ fixture = {"lb": lb_arn, "eni": eni, "sg": sg, "cert": cert, "subnets": subnets, "instance": inst_id, "provider": tp_id,
+ "group": group_id}
+ yield fixture
+ for ep in ec2.describe_verified_access_endpoints(VerifiedAccessInstanceId=inst_id)["VerifiedAccessEndpoints"]:
+ if ep["Status"]["Code"] != "deleting":
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep["VerifiedAccessEndpointId"])
+ groups = [g["VerifiedAccessGroupId"] for g in ec2.describe_verified_access_groups()["VerifiedAccessGroups"]
+ if g["VerifiedAccessInstanceId"] == inst_id]
+ _cleanup(ec2, groups=groups, instances=[inst_id], providers=[tp_id])
+
+
+def _lb_endpoint_params(fx, **over):
+ params = dict(VerifiedAccessGroupId=fx["group"], EndpointType="load-balancer", AttachmentType="vpc",
+ DomainCertificateArn=fx["cert"], ApplicationDomain="app.example.com", EndpointDomainPrefix="app",
+ SecurityGroupIds=[fx["sg"]],
+ LoadBalancerOptions={"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]})
+ params.update(over)
+ return {k: v for k, v in params.items() if v is not None}
+
+
+def test_verified_access_endpoint_create_errors(raw, endpoint_fixture):
+ """X1:invalid:*, V5:invalid:*, Y1:invalid:*, W1:create_verified_access_endpoint:*."""
+ fx = endpoint_fixture
+ lb = {"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]}
+ eni = {"NetworkInterfaceId": fx["eni"], "Protocol": "https", "Port": 443}
+ cases = [
+ ({"EndpointType": None}, "MissingParameter", "Required parameter EndpointType was empty or null in the request"),
+ ({"EndpointType": None, "AttachmentType": None}, "MissingParameter",
+ "Required parameter EndpointType was empty or null in the request"),
+ ({"AttachmentType": None}, "MissingParameter", "Required parameter AttachmentType was empty or null in the request"),
+ ({"SecurityGroupIds": ["sg-00000000000000000"]}, "InvalidParameterValue", "The Security Group Ids are invalid"),
+ ({"LoadBalancerOptions": {**lb, "SubnetIds": ["subnet-00000000000000000"]}}, "InvalidParameterValue",
+ "Invalid value for parameter SubnetIds"),
+ ({"VerifiedAccessGroupId": _MISSING["Group"], "EndpointType": "bogus"}, "InvalidVerifiedAccessGroupId.NotFound",
+ f"The verified-access-group ID '{_MISSING['Group']}' does not exist"),
+ ({"EndpointType": "bogus"}, "InvalidParameterValue", "The value of endpointType you provided is not valid"),
+ ({"AttachmentType": "bogus"}, "InvalidParameterValue", "The value of attachmentType you provided is not valid"),
+ ({"EndpointType": "rds", "LoadBalancerOptions": None}, "MissingParameter", "Missing required parameter RdsOptions"),
+ ({"EndpointType": "cidr", "LoadBalancerOptions": None}, "MissingParameter", "Missing required parameter CidrOptions"),
+ ({"LoadBalancerOptions": None, "DomainCertificateArn": "arn:c"}, "MissingParameter",
+ "LoadBalancerOptions must be provided if endpoint type load-balancer is specified"),
+ ({"LoadBalancerOptions": None, "NetworkInterfaceOptions": eni}, "MissingParameter",
+ "LoadBalancerOptions must be provided if endpoint type load-balancer is specified"),
+ ({"LoadBalancerOptions": {k: v for k, v in lb.items() if k != "LoadBalancerArn"}}, "MissingParameter",
+ "LoadBalancerArn must be provided in LoadBalancerOptions"),
+ ({"NetworkInterfaceOptions": eni}, "InvalidParameterCombination",
+ "NetworkInterfaceOptions cannot be provided if endpoint type load-balancer is specified"),
+ ({"LoadBalancerOptions": {**lb, "PortRanges": [{"FromPort": 443, "ToPort": 443}]}}, "InvalidParameterValue",
+ "Parameter PortRanges is not currently supported for the operation"),
+ ({"DomainCertificateArn": None}, "MissingParameter", "Missing required parameter DomainCertificateArn"),
+ ({"ApplicationDomain": None}, "MissingParameter", "Missing required parameter ApplicationDomain"),
+ ({"EndpointDomainPrefix": None}, "MissingParameter", "Missing required parameter EndpointDomainPrefix"),
+ ({"LoadBalancerOptions": {**lb, "LoadBalancerArn": fx["lb"][:-16] + "0" * 16}}, "InvalidParameterValue",
+ "The LoadBalancerArn is invalid"),
+ ({"DomainCertificateArn": fx["cert"][:-12] + "0" * 12}, "InvalidParameterValue", "The CertificateArn is invalid"),
+ ({"ApplicationDomain": "other.example.com"}, "InvalidParameterValue",
+ "The ApplicationDomain provided is not present in the DomainCertificateArn provided in the request."),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None}, "MissingParameter",
+ "NetworkInterfaceOptions must be provided if endpoint type network-interface is specified"),
+ ({"EndpointType": "network-interface", "NetworkInterfaceOptions": eni}, "InvalidParameterCombination",
+ "LoadBalancerOptions cannot be provided if endpoint type network-interface is specified"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"Protocol": "https", "Port": 443}}, "MissingParameter",
+ "Missing required parameter NetworkInterfaceId"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {**eni, "NetworkInterfaceId": "eni-00000000000000000"}}, "InvalidParameterValue",
+ "NetworkInterfaceId is invalid"),
+ ]
+ for over, code, message in cases:
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert (_status(exc), *_error(exc)) == (400, code, message), over
+ assert raw.describe_verified_access_endpoints(VerifiedAccessGroupId=fx["group"])["VerifiedAccessEndpoints"] == []
+
+
+def test_verified_access_endpoint_create_check_order(raw, endpoint_fixture):
+ """Z4:invalid:*, Q3:invalid:*, R4:invalid:*, R5:*, S4:invalid:* (two faults per request: the one AWS reports)."""
+ fx = endpoint_fixture
+ lb = {"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]}
+ bad_lb = {**lb, "LoadBalancerArn": fx["lb"][:-16] + "0" * 16}
+ bad_cert = fx["cert"][:-12] + "0" * 12
+ cases = [
+ ({"EndpointType": None, "AttachmentType": "bogus"}, "InvalidParameterValue",
+ "The value of attachmentType you provided is not valid"),
+ ({"EndpointType": "bogus", "AttachmentType": "bogus"}, "InvalidParameterValue",
+ "The value of endpointType you provided is not valid; The value of attachmentType you provided is not valid"),
+ ({"EndpointType": "bogus", "AttachmentType": None}, "InvalidParameterValue", "The value of endpointType you provided is not valid"),
+ ({"AttachmentType": None, "LoadBalancerOptions": None}, "MissingParameter",
+ "Required parameter AttachmentType was empty or null in the request"),
+ ({"LoadBalancerOptions": {k: v for k, v in lb.items() if k != "Protocol"}}, "MissingParameter",
+ "Missing required parameter protocol in EniOptions"),
+ ({"LoadBalancerOptions": {"Port": 443, "PortRanges": [{"FromPort": 1, "ToPort": 2}]}}, "MissingParameter",
+ "Missing required parameter protocol in EniOptions"),
+ ({"LoadBalancerOptions": {k: v for k, v in lb.items() if k != "Port"}}, "MissingParameter",
+ "Port must be provided in LoadBalancerOptions"),
+ ({"LoadBalancerOptions": {k: v for k, v in lb.items() if k != "SubnetIds"}}, "MissingParameter",
+ "SubnetIds must be provided in LoadBalancerOptions"),
+ ({"LoadBalancerOptions": {**lb, "Protocol": "ftp"}}, "InvalidParameterValue",
+ "The value of loadBalancerOptions.protocol you provided is not valid"),
+ ({"LoadBalancerOptions": {**lb, "Port": 0}}, "InvalidParameterValue", "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Port": 443}}, "MissingParameter",
+ "Missing required parameter protocol in EniOptions"),
+ ({"SecurityGroupIds": None, "LoadBalancerOptions": {**lb, "SubnetIds": ["subnet-00000000000000000"]}},
+ "InvalidParameterValue", "Invalid value for parameter SubnetIds"),
+ ({"LoadBalancerOptions": {**lb, "SubnetIds": ["subnet-00000000000000000"]}, "DomainCertificateArn": bad_cert},
+ "InvalidParameterValue", "Invalid value for parameter SubnetIds"),
+ ({"SecurityGroupIds": ["sg-00000000000000000"], "LoadBalancerOptions": bad_lb}, "InvalidParameterValue",
+ "The LoadBalancerArn is invalid"),
+ ({"ApplicationDomain": None, "LoadBalancerOptions": bad_lb}, "InvalidParameterValue", "The LoadBalancerArn is invalid"),
+ ({"EndpointDomainPrefix": "a.b", "LoadBalancerOptions": bad_lb}, "InvalidParameterValue", "The LoadBalancerArn is invalid"),
+ ({"DomainCertificateArn": None, "ApplicationDomain": None, "EndpointDomainPrefix": None}, "MissingParameter",
+ "Missing required parameter DomainCertificateArn"),
+ ({"ApplicationDomain": None, "EndpointDomainPrefix": None}, "MissingParameter", "Missing required parameter ApplicationDomain"),
+ ({"EndpointDomainPrefix": None, "DomainCertificateArn": bad_cert}, "MissingParameter",
+ "Missing required parameter EndpointDomainPrefix"),
+ ({"SecurityGroupIds": None, "DomainCertificateArn": None}, "MissingParameter", "Missing required parameter DomainCertificateArn"),
+ ({"ApplicationDomain": None, "EndpointDomainPrefix": "a.b"}, "MissingParameter", "Missing required parameter ApplicationDomain"),
+ ({"SecurityGroupIds": ["sg-00000000000000000"], "EndpointDomainPrefix": "a.b"}, "InvalidParameterValue",
+ "The Security Group Ids are invalid"),
+ ({"SecurityGroupIds": ["sg-00000000000000000"], "ApplicationDomain": "x.other.com"}, "InvalidParameterValue",
+ "The Security Group Ids are invalid"),
+ ({"SecurityGroupIds": None, "EndpointDomainPrefix": "a.b"}, "InvalidParameterValue",
+ "The EndpointDomainPrefix provided in the request contains unsupported characters"),
+ ({"EndpointDomainPrefix": "a.b", "DomainCertificateArn": bad_cert}, "InvalidParameterValue",
+ "The EndpointDomainPrefix provided in the request contains unsupported characters"),
+ ({"EndpointDomainPrefix": "-ab"}, "InvalidParameterValue", "The EndpointDomainPrefix provided in the request contains unsupported characters"),
+ ({"EndpointDomainPrefix": "ab-"}, "InvalidParameterValue", "The EndpointDomainPrefix provided in the request contains unsupported characters"),
+ ({"EndpointDomainPrefix": "a.bbbbbbbbbbbbbbbbbbb"}, "InvalidParameterValue",
+ "The EndpointDomainPrefix provided in the request contains unsupported characters"),
+ ({"EndpointDomainPrefix": "a" * 21}, "InvalidParameterValue", "Provided EndpointDomainPrefix exceeds max character limit of 20 characters"),
+ ({"SecurityGroupIds": None}, "MissingParameter", "Security Group Ids must be provided if attachment type vpc is selected"),
+ ({"SecurityGroupIds": None, "DomainCertificateArn": bad_cert}, "InvalidParameterValue", "The CertificateArn is invalid"),
+ ({"LoadBalancerOptions": {**lb, "Protocol": "tcp"}}, "InvalidParameterValue",
+ "Parameter port in LoadBalancerOptions is not supported with 'tcp' protocol"),
+ ({"LoadBalancerOptions": {k: v for k, v in {**lb, "Protocol": "tcp"}.items() if k != "Port"}}, "MissingParameter",
+ "PortRanges must be provided in LoadBalancerOptions"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Protocol": "tcp", "Port": 443}}, "InvalidParameterValue",
+ "Parameter port in EniOptions is not supported with 'tcp' protocol"),
+ ({"LoadBalancerOptions": {k: v for k, v in {**lb, "Port": 0}.items() if k != "SubnetIds"}}, "InvalidParameterValue",
+ "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"Protocol": "https", "Port": 0}}, "InvalidParameterValue",
+ "The value of networkInterfaceOptions.port you provided is not valid"),
+ ({"DomainCertificateArn": None, "SecurityGroupIds": ["sg-00000000000000000"]}, "InvalidParameterValue",
+ "The Security Group Ids are invalid"),
+ ({"LoadBalancerOptions": {**lb, "Port": 65536}}, "InvalidParameterValue", "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"ApplicationDomain": "APP.example.com"}, "InvalidParameterValue",
+ "The ApplicationDomain provided is not present in the DomainCertificateArn provided in the request."),
+ ({"EndpointDomainPrefix": "_a-bcdefghijklmnopqr", "DomainCertificateArn": bad_cert}, "InvalidParameterValue",
+ "The CertificateArn is invalid"),
+ ({"LoadBalancerOptions": {"Protocol": "ftp", "SubnetIds": fx["subnets"], "LoadBalancerArn": fx["lb"]}},
+ "InvalidParameterValue", "The value of loadBalancerOptions.protocol you provided is not valid"),
+ ({"LoadBalancerOptions": {"Protocol": "https", "LoadBalancerArn": fx["lb"]}}, "MissingParameter",
+ "Port must be provided in LoadBalancerOptions"),
+ ({"LoadBalancerOptions": {"Protocol": "https", "Port": 443}}, "MissingParameter", "SubnetIds must be provided in LoadBalancerOptions"),
+ ({"LoadBalancerOptions": {**lb, "Port": 0, "PortRanges": [{"FromPort": 1, "ToPort": 2}]}}, "InvalidParameterValue",
+ "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"LoadBalancerOptions": {**bad_lb, "SubnetIds": ["subnet-00000000000000000"]}}, "InvalidParameterValue",
+ "Invalid value for parameter SubnetIds"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None, "NetworkInterfaceOptions": {"Port": 443}},
+ "MissingParameter", "Missing required parameter protocol in EniOptions"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Protocol": "https", "Port": 0}},
+ "InvalidParameterValue", "The value of networkInterfaceOptions.port you provided is not valid"),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Protocol": "ftp", "Port": 443}},
+ "InvalidParameterValue", "The value of networkInterfaceOptions.protocol you provided is not valid"),
+ ({"DomainCertificateArn": bad_cert, "ApplicationDomain": "x.other.com"}, "InvalidParameterValue", "The CertificateArn is invalid"),
+ ]
+ for over, code, message in cases:
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == (code, message), over
+ assert raw.describe_verified_access_endpoints(VerifiedAccessGroupId=fx["group"])["VerifiedAccessEndpoints"] == []
+
+
+def test_verified_access_endpoint_prefix_wildcard_and_device_domain(ec2, endpoint_fixture):
+ """Z4:invalid:prefix-upper, Z4:invalid:prefix-underscore, Z4:invalid:wild-cert-*, Q3:create:wild-one-level, Q3:invalid:wild-apex,
+ X2:create:lb (no device provider), Q3:create:wild-one-level (with one), Q5:create:same-domain-while-deleting."""
+ fx = endpoint_fixture
+ wild = make_client("acm").request_certificate(DomainName="*.example.com")["CertificateArn"]
+ for domain in ("example.com", "a.b.example.com"):
+ with pytest.raises(ClientError) as exc:
+ ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx, DomainCertificateArn=wild, ApplicationDomain=domain))
+ assert _error(exc) == ("InvalidParameterValue", "The ApplicationDomain provided is not present in the "
+ "DomainCertificateArn provided in the request.")
+ plain = ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, DomainCertificateArn=wild, ApplicationDomain="web.example.com", EndpointDomainPrefix="App_1"))["VerifiedAccessEndpoint"]
+ assert plain["EndpointDomain"].startswith("App_1.edge-")
+ assert "DeviceValidationDomain" not in plain
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=plain["VerifiedAccessEndpointId"])
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, fx["instance"], jamf)
+ # R5:describe:after-device: the domain shows once the instance has a device provider.
+ assert ec2.describe_verified_access_endpoints(
+ VerifiedAccessEndpointIds=[plain["VerifiedAccessEndpointId"]])["VerifiedAccessEndpoints"][0]["DeviceValidationDomain"]
+ # The domain of an endpoint that is being deleted is free again.
+ with_device = ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, DomainCertificateArn=wild, ApplicationDomain="web.example.com", EndpointDomainPrefix="web"))["VerifiedAccessEndpoint"]
+ edge = with_device["EndpointDomain"].split(".")[1]
+ validation = with_device["DeviceValidationDomain"]
+ assert validation.startswith(f"{edge}.vld-") and validation.endswith(".vld.prod.verified-access.us-east-1.amazonaws.com")
+ # One vld id per instance (Q3:create:wild-one-level and Q5:create:same-domain-while-deleting share it).
+ second = ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, DomainCertificateArn=wild, ApplicationDomain="web2.example.com", EndpointDomainPrefix="web2"))["VerifiedAccessEndpoint"]
+ assert second["DeviceValidationDomain"].split(".")[1] == validation.split(".")[1]
+ assert second["EndpointDomain"].split(".")[1] != edge
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=second["VerifiedAccessEndpointId"])
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=with_device["VerifiedAccessEndpointId"])
+ ec2.describe_verified_access_endpoints(VerifiedAccessInstanceId=fx["instance"])
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=fx["instance"], VerifiedAccessTrustProviderId=jamf)
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=jamf)
+
+
+def test_verified_access_round10_endpoints(ec2, raw, endpoint_fixture):
+ """T1:*, T3:*, T4:*, T5:* (round 10): tcp, network-interface values and protocol changes on modify,
+ the group checked first on modify, the device validation domain after a detach."""
+ fx = endpoint_fixture
+ lb = {"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]}
+ native = ("InvalidParameterValue", "TCP based endpoints require a TrustProvider with NativeApplicationOidcOptions to be "
+ "attached to the instance.")
+ for over, error in (
+ ({"ApplicationDomain": "x.other.com", "SecurityGroupIds": None},
+ ("InvalidParameterValue", "The ApplicationDomain provided is not present in the DomainCertificateArn provided in the request.")),
+ ({"LoadBalancerOptions": {**{k: v for k, v in lb.items() if k != "Port"}, "Protocol": "tcp",
+ "PortRanges": [{"FromPort": 443, "ToPort": 443}]}}, native),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Protocol": "tcp"}},
+ ("MissingParameter", "Missing required parameter PortRanges")),
+ ({"EndpointType": "network-interface", "LoadBalancerOptions": None,
+ "NetworkInterfaceOptions": {"NetworkInterfaceId": fx["eni"], "Protocol": "tcp", "PortRanges": [{"FromPort": 443, "ToPort": 443}]}},
+ native),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == error, over
+
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, fx["instance"], jamf)
+ lb_ep = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]
+ with pytest.raises(ClientError) as exc:
+ ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx, EndpointDomainPrefix="w2", SecurityGroupIds=None))
+ assert _error(exc) == ("MissingParameter", "Security Group Ids must be provided if attachment type vpc is selected")
+ eni_ep = ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, EndpointType="network-interface", LoadBalancerOptions=None, ApplicationDomain="eni.example.com",
+ EndpointDomainPrefix="eni", NetworkInterfaceOptions={"NetworkInterfaceId": fx["eni"], "Protocol": "https", "Port": 443},
+ ))["VerifiedAccessEndpoint"]
+ me = raw.modify_verified_access_endpoint
+ for ep_id, kwargs, error in (
+ (eni_ep["VerifiedAccessEndpointId"], {"NetworkInterfaceOptions": {"Port": 0}},
+ ("InvalidParameterValue", "The value of networkInterfaceOptions.port you provided is not valid")),
+ (eni_ep["VerifiedAccessEndpointId"], {"NetworkInterfaceOptions": {"Protocol": "ftp"}},
+ ("InvalidParameterValue", "The value of networkInterfaceOptions.protocol you provided is not valid")),
+ (eni_ep["VerifiedAccessEndpointId"], {"NetworkInterfaceOptions": {"Protocol": "tcp", "Port": 443}},
+ ("InvalidParameterValue", "Protocol cannot be modified between HTTP/HTTPS and TCP")),
+ (lb_ep["VerifiedAccessEndpointId"], {"LoadBalancerOptions": {"Protocol": "tcp"}},
+ ("InvalidParameterValue", "Protocol cannot be modified between HTTP/HTTPS and TCP")),
+ (lb_ep["VerifiedAccessEndpointId"], {"VerifiedAccessGroupId": _MISSING["Group"], "NetworkInterfaceOptions": {"Port": 80}},
+ ("InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{_MISSING['Group']}' does not exist")),
+ (lb_ep["VerifiedAccessEndpointId"], {"VerifiedAccessGroupId": _MISSING["Group"], "LoadBalancerOptions": {"Port": 0}},
+ ("InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{_MISSING['Group']}' does not exist")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ me(VerifiedAccessEndpointId=ep_id, **kwargs)
+ assert _error(exc) == error, kwargs
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=fx["instance"], VerifiedAccessTrustProviderId=jamf)
+ after = ec2.describe_verified_access_endpoints(VerifiedAccessEndpointIds=[lb_ep["VerifiedAccessEndpointId"]])
+ assert after["VerifiedAccessEndpoints"][0]["DeviceValidationDomain"] == lb_ep["DeviceValidationDomain"]
+ for ep in (lb_ep, eni_ep):
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep["VerifiedAccessEndpointId"])
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=jamf)
+
+
+def test_verified_access_round11_endpoints(ec2, raw, endpoint_fixture):
+ """U1:*, U3:logging:*, U4:*, U5:*, U7:* (round 11): the tcp check order on create and modify, another
+ account as the log bucket owner, the device domain without a read, and an endpoint in an orphaned group."""
+ fx = endpoint_fixture
+ lb = {"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]}
+ ranges = [{"FromPort": 443, "ToPort": 443}]
+ tcp_lb = {"Protocol": "tcp", "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"], "PortRanges": ranges}
+ native = ("InvalidParameterValue", "TCP based endpoints require a TrustProvider with NativeApplicationOidcOptions to be "
+ "attached to the instance.")
+ eni = {"EndpointType": "network-interface", "LoadBalancerOptions": None}
+ for over, error in (
+ ({"LoadBalancerOptions": {**tcp_lb, "Port": 443}},
+ ("InvalidParameterValue", "Parameter port in LoadBalancerOptions is not supported with 'tcp' protocol")),
+ ({"LoadBalancerOptions": {**lb, "Protocol": "tcp", "Port": 0}},
+ ("InvalidParameterValue", "The value of loadBalancerOptions.port you provided is not valid")),
+ ({"LoadBalancerOptions": {k: v for k, v in tcp_lb.items() if k != "LoadBalancerArn"}},
+ ("MissingParameter", "LoadBalancerArn must be provided in LoadBalancerOptions")),
+ ({"LoadBalancerOptions": {k: v for k, v in tcp_lb.items() if k != "SubnetIds"}}, native),
+ ({"LoadBalancerOptions": {**tcp_lb, "SubnetIds": ["subnet-00000000000000000"]}},
+ ("InvalidParameterValue", "Invalid value for parameter SubnetIds")),
+ ({"LoadBalancerOptions": {**tcp_lb, "LoadBalancerArn": fx["lb"][:-16] + "0" * 16}},
+ ("InvalidParameterValue", "The LoadBalancerArn is invalid")),
+ ({"LoadBalancerOptions": tcp_lb, "SecurityGroupIds": None},
+ ("MissingParameter", "Security Group Ids must be provided if attachment type vpc is selected")),
+ ({"LoadBalancerOptions": tcp_lb, "DomainCertificateArn": fx["cert"][:-12] + "0" * 12}, native),
+ ({**eni, "NetworkInterfaceOptions": {"NetworkInterfaceId": "eni-00000000000000000", "Protocol": "tcp", "PortRanges": ranges}},
+ ("InvalidParameterValue", "NetworkInterfaceId is invalid")),
+ ({**eni, "NetworkInterfaceOptions": {"Protocol": "tcp", "PortRanges": ranges}},
+ ("MissingParameter", "Missing required parameter NetworkInterfaceId")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == error, over
+
+ bucket = f"va-owner-{uuid.uuid4().hex[:8]}"
+ make_client("s3").create_bucket(Bucket=bucket)
+ lm = ec2.modify_verified_access_instance_logging_configuration
+ with pytest.raises(ClientError) as exc:
+ lm(VerifiedAccessInstanceId=fx["instance"],
+ AccessLogs={"S3": {"Enabled": True, "BucketName": bucket, "BucketOwner": "123456789012"}})
+ assert _error(exc) == ("LogDestinationPermissionIssue", "User does not have permission to configure log destination "
+ "resource identified by AccessLogs.S3.BucketName for log delivery")
+ assert _status(exc) == 400
+ account = make_client("sts").get_caller_identity()["Account"]
+ logs = lm(VerifiedAccessInstanceId=fx["instance"],
+ AccessLogs={"S3": {"Enabled": True, "BucketName": bucket, "BucketOwner": account}})["LoggingConfiguration"]
+ assert logs["AccessLogs"]["S3"]["BucketOwner"] == account
+ lm(VerifiedAccessInstanceId=fx["instance"], AccessLogs={"S3": {"Enabled": False}})
+
+ # An attach and a detach with no read between them still leave the endpoint a device validation domain.
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, fx["instance"], jamf)
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=fx["instance"], VerifiedAccessTrustProviderId=jamf)
+ ep = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]
+ assert ep["DeviceValidationDomain"]
+ ep_id = ep["VerifiedAccessEndpointId"]
+ for opts, error in (
+ ({"Port": 0, "PortRanges": [{"FromPort": 1, "ToPort": 2}]},
+ "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"Protocol": "tcp", "PortRanges": [{"FromPort": 1, "ToPort": 2}]}, "Protocol cannot be modified between HTTP/HTTPS and TCP"),
+ ({"Protocol": "tcp", "SubnetIds": ["subnet-00000000000000000"]}, "Protocol cannot be modified between HTTP/HTTPS and TCP"),
+ ({"Protocol": "tcp", "Port": 0}, "The value of loadBalancerOptions.port you provided is not valid"),
+ ({"Protocol": "ftp", "PortRanges": [{"FromPort": 1, "ToPort": 2}]},
+ "The value of loadBalancerOptions.protocol you provided is not valid"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, LoadBalancerOptions=opts)
+ assert _error(exc) == ("InvalidParameterValue", error), opts
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+ ec2.delete_verified_access_trust_provider(VerifiedAccessTrustProviderId=jamf)
+
+ # A group moved to a bare instance that is then deleted takes no HTTP/HTTPS endpoint.
+ orphan = _group(ec2, fx["instance"])
+ bare = _instance(ec2)
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=orphan, VerifiedAccessInstanceId=bare)
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=bare)
+ with pytest.raises(ClientError) as exc:
+ ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx, VerifiedAccessGroupId=orphan))
+ assert _error(exc) == ("InvalidParameterValue",
+ "HTTP/HTTPS based endpoints require a TrustProvider with OidcOptions to be attached to the instance.")
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=orphan)
+
+
+def test_verified_access_round12_check_orders(ec2, raw, endpoint_fixture):
+ """V1:invalid:*, V3:logging:*, V4:modify:*, V5:invalid:* (round 12), W1:invalid:* (round 13): the remaining pairs of two faults."""
+ fx = endpoint_fixture
+ ranges = [{"FromPort": 443, "ToPort": 443}]
+ tcp_lb = {"Protocol": "tcp", "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"], "PortRanges": ranges}
+ native = ("InvalidParameterValue", "TCP based endpoints require a TrustProvider with NativeApplicationOidcOptions to be "
+ "attached to the instance.")
+ oidc = ("InvalidParameterValue", "HTTP/HTTPS based endpoints require a TrustProvider with OidcOptions to be attached to the instance.")
+ fake_sg, fake_eni = "sg-00000000000000000", "eni-00000000000000000"
+ eni = {"EndpointType": "network-interface", "LoadBalancerOptions": None}
+ for over, error in (
+ ({"LoadBalancerOptions": {"Protocol": "tcp", "SubnetIds": fx["subnets"]}},
+ ("MissingParameter", "PortRanges must be provided in LoadBalancerOptions")),
+ ({**eni, "NetworkInterfaceOptions": {"Protocol": "tcp"}}, ("MissingParameter", "Missing required parameter NetworkInterfaceId")),
+ ({"LoadBalancerOptions": {"Protocol": "tcp", "Port": 443, "SubnetIds": fx["subnets"], "PortRanges": ranges}},
+ ("InvalidParameterValue", "Parameter port in LoadBalancerOptions is not supported with 'tcp' protocol")),
+ ({**eni, "NetworkInterfaceOptions": {"Protocol": "tcp", "Port": 443, "PortRanges": ranges}},
+ ("InvalidParameterValue", "Parameter port in EniOptions is not supported with 'tcp' protocol")),
+ ({"LoadBalancerOptions": tcp_lb, "SecurityGroupIds": [fake_sg]}, ("InvalidParameterValue", "The Security Group Ids are invalid")),
+ ({"LoadBalancerOptions": tcp_lb, "DomainCertificateArn": None}, native),
+ ({"LoadBalancerOptions": tcp_lb, "ApplicationDomain": None}, native),
+ ({"LoadBalancerOptions": tcp_lb, "EndpointDomainPrefix": None}, native),
+ ({**eni, "SecurityGroupIds": [fake_sg], "NetworkInterfaceOptions": {
+ "NetworkInterfaceId": fake_eni, "Protocol": "tcp", "PortRanges": ranges}}, ("InvalidParameterValue", "NetworkInterfaceId is invalid")),
+ ({**eni, "SecurityGroupIds": [fake_sg], "NetworkInterfaceOptions": {
+ "NetworkInterfaceId": fake_eni, "Protocol": "https", "Port": 443}}, ("InvalidParameterValue", "NetworkInterfaceId is invalid")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == error, over
+
+ bucket = f"va-pairs-{uuid.uuid4().hex[:8]}"
+ make_client("s3").create_bucket(Bucket=bucket)
+ other = {"Enabled": True, "BucketName": bucket, "BucketOwner": "123456789012"}
+ for missing in ({"CloudWatchLogs": {"Enabled": True, "LogGroup": "/va/missing"}},
+ {"KinesisDataFirehose": {"Enabled": True, "DeliveryStream": "va-missing"}}):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_instance_logging_configuration(
+ VerifiedAccessInstanceId=fx["instance"], AccessLogs={"S3": other, **missing})
+ assert _error(exc)[0] == "LogDestinationPermissionIssue", missing
+
+ ep_id = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"]
+ for kwargs, error in (
+ ({"NetworkInterfaceOptions": {"Port": 80}, "LoadBalancerOptions": {"Port": 0}},
+ ("InvalidParameterValue", "The value of loadBalancerOptions.port you provided is not valid")),
+ ({"NetworkInterfaceOptions": {"Port": 80}, "LoadBalancerOptions": {"Protocol": "ftp"}},
+ ("InvalidParameterValue", "The value of loadBalancerOptions.protocol you provided is not valid")),
+ ({"LoadBalancerOptions": {"PortRanges": ranges, "SubnetIds": ["subnet-00000000000000000"]}},
+ ("InvalidParameterValue", "Parameter PortRanges is not currently supported for the operation")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, **kwargs)
+ assert _error(exc) == error, kwargs
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+
+ # A group on an instance with no provider, then on one that was deleted, answers alike.
+ group = _group(ec2, fx["instance"])
+ bare = _instance(ec2)
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=group, VerifiedAccessInstanceId=bare)
+ fake_key = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"
+ pairs = (
+ ({}, oidc),
+ ({"SecurityGroupIds": None}, ("MissingParameter", "Security Group Ids must be provided if attachment type vpc is selected")),
+ ({"SecurityGroupIds": [fake_sg]}, ("InvalidParameterValue", "The Security Group Ids are invalid")),
+ ({"DomainCertificateArn": None}, ("MissingParameter", "Missing required parameter DomainCertificateArn")),
+ ({"ApplicationDomain": "x.other.com"},
+ ("InvalidParameterValue", "The ApplicationDomain provided is not present in the DomainCertificateArn provided in the request.")),
+ ({"SseSpecification": {"CustomerManagedKeyEnabled": True, "KmsKeyArn": fake_key}}, oidc),
+ )
+ for deleted in (False, True):
+ if deleted:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=bare)
+ for over, error in pairs:
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, VerifiedAccessGroupId=group, EndpointDomainPrefix="orphan", **over))
+ assert _error(exc) == error, (deleted, over)
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=group)
+
+
+def test_verified_access_round14_check_orders(ec2, raw, endpoint_fixture):
+ """X1:tp:*, X2:invalid:*, X3:*, X4:logging:*, X6:modify:*, X7:* (round 14): the pairs the final audit found uncaptured."""
+ oidc = {"Issuer": "https://idp.example.com", "AuthorizationEndpoint": "https://idp.example.com/auth",
+ "TokenEndpoint": "https://idp.example.com/token", "UserInfoEndpoint": "https://idp.example.com/userinfo",
+ "ClientId": "client", "ClientSecret": "secret", "Scope": "openid"}
+ user = dict(TrustProviderType="user", UserTrustProviderType="oidc", PolicyReferenceName="idp")
+ for kwargs, error in (
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k not in ("Issuer", "AuthorizationEndpoint")}},
+ ("MissingParameter", "Missing required parameter Issuer in OidcOptions")),
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k not in ("TokenEndpoint", "UserInfoEndpoint")}},
+ ("MissingParameter", "Missing required parameter TokenEndpoint in OidcOptions")),
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k not in ("UserInfoEndpoint", "ClientId")}},
+ ("MissingParameter", "Missing required parameter UserInfoEndpoint in OidcOptions")),
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k not in ("ClientId", "ClientSecret")}},
+ ("MissingParameter", "Missing required parameter ClientId in OidcOptions")),
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k not in ("ClientSecret", "Scope")}},
+ ("MissingParameter", "Missing required parameter ClientSecret in OidcOptions")),
+ ({"OidcOptions": {k: v for k, v in oidc.items() if k != "Issuer"}, "DeviceOptions": {"TenantId": "t"}},
+ ("MissingParameter", "Missing required parameter Issuer in OidcOptions")),
+ ({"OidcOptions": {**oidc, "Issuer": "http://idp.example.com"}, "DeviceTrustProviderType": "jamf"},
+ ("InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL")),
+ ({"OidcOptions": oidc, "PolicyReferenceName": "a!" * 20},
+ ("InvalidParameterValue", "Length of parameter PolicyReferenceName must be between 1 and 32")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_trust_provider(**{**user, **kwargs})
+ assert _error(exc) == error, kwargs
+
+ fx = endpoint_fixture
+ lb = {"Protocol": "https", "Port": 443, "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"]}
+ ranges = [{"FromPort": 443, "ToPort": 443}]
+ refused = ("InvalidParameterValue", "Parameter PortRanges is not currently supported for the operation")
+ eni = {"EndpointType": "network-interface", "LoadBalancerOptions": None}
+ for over, error in (
+ ({"LoadBalancerOptions": {**lb, "Protocol": "ftp", "Port": 0}},
+ ("InvalidParameterValue", "The value of loadBalancerOptions.protocol you provided is not valid; "
+ "The value of loadBalancerOptions.port you provided is not valid")),
+ ({"LoadBalancerOptions": {k: v for k, v in {**lb, "PortRanges": ranges}.items() if k != "Port"}}, refused),
+ ({"LoadBalancerOptions": {k: v for k, v in {**lb, "PortRanges": ranges}.items() if k != "SubnetIds"}}, refused),
+ ({"LoadBalancerOptions": {k: v for k, v in {**lb, "PortRanges": ranges}.items() if k != "LoadBalancerArn"}}, refused),
+ ({"LoadBalancerOptions": {**lb, "SubnetIds": ["subnet-00000000000000000"], "PortRanges": ranges}}, refused),
+ ({"SecurityGroupIds": ["sg-00000000000000000"], "LoadBalancerOptions": {**lb, "PortRanges": ranges}}, refused),
+ ({**eni, "NetworkInterfaceOptions": {"Protocol": "https", "Port": 443, "PortRanges": ranges}}, refused),
+ ({**eni, "NetworkInterfaceOptions": {"NetworkInterfaceId": "eni-00000000000000000", "Protocol": "https", "Port": 443,
+ "PortRanges": ranges}}, refused),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == error, over
+
+ for call, kwargs, error in (
+ (raw.describe_verified_access_groups, {"VerifiedAccessInstanceId": "abc", "MaxResults": 1},
+ ("InvalidParameterValue", "The parameter MaxResults must be between 5 and 200")),
+ (raw.describe_verified_access_groups, {"VerifiedAccessInstanceId": "abc", "NextToken": "bad"},
+ ("InvalidParameterValue", "Length of parameter VerifiedAccessInstanceId must be between 5 and 21")),
+ (raw.describe_verified_access_endpoints, {"VerifiedAccessInstanceId": fx["instance"], "VerifiedAccessGroupId": fx["group"],
+ "NextToken": "bad"},
+ ("InvalidParameterCombination", "The parameters VerifiedAccessInstanceId and VerifiedAccessGroupId cannot be used together")),
+ (raw.describe_verified_access_instances, {"VerifiedAccessInstanceIds": [fx["instance"]], "MaxResults": "abc", "NextToken": "bad"},
+ ("InvalidParameterValue", "Invalid integer value abc")),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ assert _error(exc) == error, kwargs
+
+ for logs in ({"CloudWatchLogs": {"Enabled": True}, "KinesisDataFirehose": {"Enabled": True}},
+ {"CloudWatchLogs": {"Enabled": True}, "KinesisDataFirehose": {"Enabled": False, "DeliveryStream": "x"}}):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_instance_logging_configuration(VerifiedAccessInstanceId=fx["instance"], AccessLogs=logs)
+ assert _error(exc) == ("MissingParameter", "Missing required parameter AccessLogs.CloudWatchLogs.LogGroup"), logs
+
+ ep_id = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"]
+ combination = ("InvalidParameterCombination",
+ "NetworkInterfaceOptions may only be specified for Verified Access Endpoints with network-interface type")
+ for opts in ({"Protocol": "tcp"}, {"PortRanges": ranges}, {"SubnetIds": ["subnet-00000000000000000"]}):
+ with pytest.raises(ClientError) as exc:
+ raw.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, NetworkInterfaceOptions={"Port": 80},
+ LoadBalancerOptions=opts)
+ assert _error(exc) == combination, opts
+ # A deleting endpoint doesn't block the instance delete; the attached provider does.
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=fx["instance"])
+ assert _error(exc)[1].endswith("has existing attachments. Remove all VerifiedAccessTrustProvider attachments before deleting.")
+
+
+def test_verified_access_round15_pages_and_pairs(ec2, raw, endpoint_fixture):
+ """Y1:tp:long-scope+device-options, Y3:endpoints:page-5, Y4:modify:* (round 15)."""
+ import urllib.request
+
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_trust_provider(
+ TrustProviderType="user", UserTrustProviderType="oidc", PolicyReferenceName="idp", DeviceOptions={"TenantId": "t"},
+ OidcOptions={"Issuer": "https://idp.example.com", "AuthorizationEndpoint": "https://idp.example.com/auth",
+ "TokenEndpoint": "https://idp.example.com/token", "UserInfoEndpoint": "https://idp.example.com/userinfo",
+ "ClientId": "client", "ClientSecret": "secret", "Scope": "s" * 300})
+ assert _error(exc) == ("InvalidParameterValue", "Length of parameter Scope in OidcOptions must be between 1 and 256")
+
+ fx = endpoint_fixture
+ names = [f"app{n}.example.com" for n in range(1, 7)]
+ cert = make_client("acm").request_certificate(DomainName=names[0], SubjectAlternativeNames=names)["CertificateArn"]
+ eps = [ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, DomainCertificateArn=cert, ApplicationDomain=name, EndpointDomainPrefix=name.split(".")[0],
+ ))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"] for name in names]
+ body = f"Action=DescribeVerifiedAccessEndpoints&Version=2016-11-15&VerifiedAccessInstanceId={fx['instance']}&MaxResults=5"
+ req = urllib.request.Request(ENDPOINT, data=body.encode(), method="POST", headers={
+ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/ec2/aws4_request"})
+ with urllib.request.urlopen(req) as resp:
+ text = resp.read().decode()
+ assert -1 < text.index("<verifiedAccessEndpointSet>") < text.index("<nextToken>")
+
+ for port in (0, 70000):
+ with pytest.raises(ClientError) as exc:
+ raw.modify_verified_access_endpoint(VerifiedAccessEndpointId=eps[0],
+ LoadBalancerOptions={"Protocol": "ftp", "Port": port})
+ assert _error(exc) == ("InvalidParameterValue", "The value of loadBalancerOptions.protocol you provided is not valid; "
+ "The value of loadBalancerOptions.port you provided is not valid"), port
+ for ep_id in eps:
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+
+
+def test_verified_access_round16_check_orders(ec2, raw, endpoint_fixture):
+ """Z1:tp:*, Z2:*, Z3:invalid:* (round 16): the pairs the audit of 08b05ab5 found uncaptured."""
+ oidc = {"Issuer": "https://idp.example.com", "AuthorizationEndpoint": "https://idp.example.com/auth",
+ "TokenEndpoint": "https://idp.example.com/token", "UserInfoEndpoint": "https://idp.example.com/userinfo",
+ "ClientId": "client", "ClientSecret": "secret", "Scope": "openid"}
+ https = ("InvalidParameterValue", "Parameter Issuer in OidcOptions must be a valid HTTPS URL")
+ for opts, extra, error in (
+ ({k: v for k, v in oidc.items() if k != "ClientId"}, {"DeviceTrustProviderType": "jamf"},
+ ("MissingParameter", "Missing required parameter ClientId in OidcOptions")),
+ ({**oidc, "Scope": "s" * 300}, {"DeviceTrustProviderType": "jamf"},
+ ("InvalidParameterValue", "Length of parameter Scope in OidcOptions must be between 1 and 256")),
+ ({**oidc, "Issuer": "http://idp.example.com"}, {"DeviceOptions": {"TenantId": "t"}}, https),
+ ({**{k: v for k, v in oidc.items() if k != "Issuer"}, "TokenEndpoint": "http://idp.example.com/token"}, {},
+ ("MissingParameter", "Missing required parameter Issuer in OidcOptions")),
+ ({**oidc, "Issuer": "http://idp.example.com", "Scope": "s" * 300}, {}, https),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_trust_provider(TrustProviderType="user", UserTrustProviderType="oidc",
+ PolicyReferenceName="idp", OidcOptions=opts, **extra)
+ assert _error(exc) == error, (opts, extra)
+
+ fake_key = "arn:aws:kms:us-east-1:000000000000:key/00000000-0000-0000-0000-000000000000"
+ sse = {"CustomerManagedKeyEnabled": True, "KmsKeyArn": fake_key}
+ for call, kwargs, code in (
+ (raw.modify_verified_access_trust_provider, {"VerifiedAccessTrustProviderId": _MISSING["TrustProvider"],
+ "OidcOptions": {"Issuer": "http://idp.example.com"}}, "TrustProvider"),
+ (raw.modify_verified_access_trust_provider, {"VerifiedAccessTrustProviderId": _MISSING["TrustProvider"],
+ "SseSpecification": sse}, "TrustProvider"),
+ (raw.modify_verified_access_instance_logging_configuration, {"VerifiedAccessInstanceId": _MISSING["Instance"],
+ "AccessLogs": {"S3": {"Enabled": True}}}, "Instance"),
+ (raw.create_verified_access_group, {"VerifiedAccessInstanceId": _MISSING["Instance"], "SseSpecification": sse}, "Instance"),
+ (raw.modify_verified_access_group, {"VerifiedAccessGroupId": _MISSING["Group"], "VerifiedAccessInstanceId": "abc"}, "Group"),
+ (raw.modify_verified_access_group_policy, {"VerifiedAccessGroupId": _MISSING["Group"], "PolicyEnabled": True}, "Group"),
+ (raw.modify_verified_access_endpoint_policy, {"VerifiedAccessEndpointId": _MISSING["Endpoint"], "PolicyEnabled": True}, "Endpoint"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ assert _error(exc)[0] == f"InvalidVerifiedAccess{code}Id.NotFound", kwargs
+
+ fx = endpoint_fixture
+ refused = ("InvalidParameterValue", "Parameter PortRanges is not currently supported for the operation")
+ ranges = [{"FromPort": 443, "ToPort": 443}]
+ eni = {"EndpointType": "network-interface", "LoadBalancerOptions": None}
+ for over, error in (
+ ({**eni, "NetworkInterfaceOptions": {"NetworkInterfaceId": "eni-00000000000000000", "Protocol": "ftp", "Port": 0}},
+ ("InvalidParameterValue", "The value of networkInterfaceOptions.protocol you provided is not valid; "
+ "The value of networkInterfaceOptions.port you provided is not valid")),
+ ({"LoadBalancerOptions": {"Protocol": "http", "LoadBalancerArn": fx["lb"], "SubnetIds": fx["subnets"], "PortRanges": ranges}},
+ refused),
+ ({**eni, "NetworkInterfaceOptions": {"Protocol": "http", "Port": 80, "PortRanges": ranges}}, refused),
+ ):
+ with pytest.raises(ClientError) as exc:
+ raw.create_verified_access_endpoint(**_lb_endpoint_params(fx, **over))
+ assert _error(exc) == error, over
+
+
+def test_verified_access_deleting_endpoint_keeps_page_offsets(ec2, endpoint_fixture):
+ """MiniStack: a deleting endpoint is listed once more; pages of that listing keep their offsets."""
+ fx = endpoint_fixture
+ wild = make_client("acm").request_certificate(DomainName="*.example.com")["CertificateArn"]
+ ids = [ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, DomainCertificateArn=wild, ApplicationDomain=f"e{n}.example.com", EndpointDomainPrefix=f"e{n}",
+ ))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"] for n in range(6)]
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ids[0])
+ first = ec2.describe_verified_access_endpoints(VerifiedAccessGroupId=fx["group"], MaxResults=5)
+ second = ec2.describe_verified_access_endpoints(VerifiedAccessGroupId=fx["group"], MaxResults=5,
+ NextToken=first["NextToken"])
+ listed = [e["VerifiedAccessEndpointId"] for e in first["VerifiedAccessEndpoints"] + second["VerifiedAccessEndpoints"]]
+ assert sorted(listed) == sorted(ids)
+ fresh = ec2.describe_verified_access_endpoints(VerifiedAccessGroupId=fx["group"])["VerifiedAccessEndpoints"]
+ assert sorted(e["VerifiedAccessEndpointId"] for e in fresh) == sorted(ids[1:])
+
+
+def test_verified_access_endpoint_modify_check_order(ec2, endpoint_fixture):
+ """Q4:modify:*, Q4:move-group:*."""
+ fx = endpoint_fixture
+ ep_id = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"]
+ other_inst, other_tp = _instance_with_provider(ec2)
+ other = _group(ec2, other_inst)
+ move = ec2.modify_verified_access_endpoint
+ for kwargs, code, message in (
+ ({"VerifiedAccessGroupId": _MISSING["Group"], "LoadBalancerOptions": {"SubnetIds": ["subnet-00000000000000000"]}},
+ "InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{_MISSING['Group']}' does not exist"),
+ ({"VerifiedAccessGroupId": other, "LoadBalancerOptions": {"PortRanges": [{"FromPort": 1, "ToPort": 2}]}},
+ "InvalidParameterValue", "Parameter PortRanges is not currently supported for the operation"),
+ ({"VerifiedAccessGroupId": other, "NetworkInterfaceOptions": {"Port": 80}}, "InvalidParameterCombination",
+ "NetworkInterfaceOptions may only be specified for Verified Access Endpoints with network-interface type"),
+ ({"VerifiedAccessGroupId": other, "LoadBalancerOptions": {"SubnetIds": ["subnet-00000000000000000"]}},
+ "InvalidParameterValue", "Invalid value for parameter SubnetIds"),
+ ({"LoadBalancerOptions": {"Protocol": "ftp"}}, "InvalidParameterValue",
+ "The value of loadBalancerOptions.protocol you provided is not valid"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ move(VerifiedAccessEndpointId=ep_id, **kwargs)
+ assert _error(exc) == (code, message), kwargs
+ same = ec2.modify_verified_access_group(VerifiedAccessGroupId=fx["group"], VerifiedAccessInstanceId=fx["instance"])
+ assert same["VerifiedAccessGroup"]["VerifiedAccessInstanceId"] == fx["instance"]
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=fx["group"], VerifiedAccessInstanceId=_MISSING["Instance"])
+ assert _error(exc)[0] == "InvalidVerifiedAccessInstanceId.NotFound"
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+ _cleanup(ec2, groups=[other], instances=[other_inst], providers=[other_tp])
+
+
+def test_verified_access_user_provider_attach_is_locked_by_groups(ec2):
+ """Q2:move-group:to-bare-instance, Q2:attach:user-while-group, Q2:attach:device-while-group, Q2:create-group:device-only."""
+ inst_id, tp_id = _instance_with_provider(ec2)
+ group_id = _group(ec2, inst_id)
+ bare = _instance(ec2)
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=group_id, VerifiedAccessInstanceId=bare)
+ user = _oidc_provider(ec2, ref="idp3")["VerifiedAccessTrustProviderId"]
+ with pytest.raises(ClientError) as exc:
+ _attach(ec2, bare, user)
+ assert _error(exc) == ("VerifiedAccessGroupAttachmentExists",
+ f"VerifiedAccessInstance {bare} is not empty. Please remove all VerifiedAccessGroups before "
+ "attaching or detaching a VerifiedAccessTrustProvider with TrustProviderType user")
+ jamf = _device_provider(ec2, "jamf")["VerifiedAccessTrustProviderId"]
+ _attach(ec2, bare, jamf)
+ _cleanup(ec2, groups=[group_id], instances=[inst_id, bare], providers=[tp_id, user, jamf])
+
+
+def test_verified_access_load_balancer_endpoint_lifecycle(ec2, endpoint_fixture):
+ """X2:create:lb, X2:describe:active, X2:modify:while-pending, X2:delete-group:endpoint-pending,
+ X2:delete-instance:with-groups-and-endpoints, X3:*, X4:modify:*-options-on-lb, V5:delete:eni-endpoint, V5:poll:delete."""
+ fx = endpoint_fixture
+ ep = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx, Description="web", PolicyDocument=_POLICY, TagSpecifications=[
+ {"ResourceType": "verified-access-endpoint", "Tags": [{"Key": "site", "Value": "app"}]}]))["VerifiedAccessEndpoint"]
+ ep_id = ep["VerifiedAccessEndpointId"]
+ assert ep_id.startswith("vae-") and len(ep_id) == 21
+ assert ep["Status"] == {"Code": "pending"}
+ domain = ep["EndpointDomain"]
+ assert domain.startswith("app.edge-") and domain.endswith(f".{fx['instance']}.prod.verified-access.us-east-1.amazonaws.com")
+ assert ep["LoadBalancerOptions"] == {"LoadBalancerArn": fx["lb"], "Port": 443, "Protocol": "https", "SubnetIds": fx["subnets"]}
+ assert "NetworkInterfaceOptions" not in ep
+ assert (ep["Tags"], ep["SseSpecification"]) == ([{"Key": "site", "Value": "app"}], {"CustomerManagedKeyEnabled": False})
+ described = ec2.describe_verified_access_endpoints(VerifiedAccessEndpointIds=[ep_id])["VerifiedAccessEndpoints"][0]
+ assert described["Status"] == {"Code": "active"}
+
+ modified = ec2.modify_verified_access_endpoint(
+ VerifiedAccessEndpointId=ep_id, Description="renamed", LoadBalancerOptions={"Port": 8443})["VerifiedAccessEndpoint"]
+ assert (modified["Status"], modified["Description"]) == ({"Code": "updating"}, "renamed")
+ assert modified["LoadBalancerOptions"]["Port"] == 8443 and modified["LoadBalancerOptions"]["LoadBalancerArn"] == fx["lb"]
+ assert "Tags" not in modified
+ for kwargs, message in (
+ ({"NetworkInterfaceOptions": {"Port": 80}}, "NetworkInterfaceOptions may only be specified for Verified Access "
+ "Endpoints with network-interface type"),
+ ({"RdsOptions": {"Port": 5432}}, "RdsOptions may only be specified for Verified Access Endpoints with rds type"),
+ ):
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, **kwargs)
+ assert _error(exc) == ("InvalidParameterCombination", message)
+
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=fx["group"])
+ assert _error(exc) == ("InvalidParameterValue", f"VerifiedAccessGroup {fx['group']} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before deleting.")
+ with pytest.raises(ClientError) as exc:
+ ec2.delete_verified_access_instance(VerifiedAccessInstanceId=fx["instance"])
+ assert _error(exc) == ("InvalidParameterValue", f"VerifiedAccessInstance {fx['instance']} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before deleting.")
+ with pytest.raises(ClientError) as exc:
+ ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))
+ assert _error(exc) == ("InvalidParameterValue", f"ApplicationDomain provided is already in use by another endpoint in "
+ f"VerifiedAccessInstance {fx['instance']}. ApplicationDomain must be unique within a Verified Access Instance.")
+
+ policy = ec2.get_verified_access_endpoint_policy(VerifiedAccessEndpointId=ep_id)
+ assert (policy["PolicyEnabled"], policy["PolicyDocument"]) == (True, _POLICY)
+ ec2.modify_verified_access_endpoint_policy(VerifiedAccessEndpointId=ep_id, PolicyEnabled=False)
+ policy = ec2.get_verified_access_endpoint_policy(VerifiedAccessEndpointId=ep_id)
+ assert (policy["PolicyEnabled"], "PolicyDocument" in policy) == (False, False)
+
+ deleted = ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)["VerifiedAccessEndpoint"]
+ assert deleted["Status"] == {"Code": "deleting"} and "Tags" not in deleted
+ # Y5:*: a deleting endpoint answers NotFound to every call but Describe, and its group can go.
+ for call in (lambda: ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id),
+ lambda: ec2.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, Description="late"),
+ lambda: ec2.get_verified_access_endpoint_policy(VerifiedAccessEndpointId=ep_id)):
+ with pytest.raises(ClientError) as exc:
+ call()
+ assert _error(exc) == ("InvalidVerifiedAccessEndpointId.NotFound",
+ f"The verified-access-endpoint ID '{ep_id}' does not exist")
+ assert ec2.describe_verified_access_endpoints(
+ VerifiedAccessEndpointIds=[ep_id])["VerifiedAccessEndpoints"][0]["Status"] == {"Code": "deleting"}
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_verified_access_endpoints(VerifiedAccessEndpointIds=[ep_id])
+ assert _error(exc) == ("InvalidVerifiedAccessEndpointId.NotFound", f"VerifiedAccessEndpoint {ep_id} does not exist")
+
+
+def test_verified_access_endpoint_and_group_moves(ec2, endpoint_fixture):
+ """Y4:move:missing-group, Y4:move:same-instance, Y4:move:other-instance, Y4:move:group-with-endpoint,
+ Y4:detach:provider-with-endpoints, Y5:delete-group:*-while-endpoint-deleting."""
+ fx = endpoint_fixture
+ ep_id = ec2.create_verified_access_endpoint(**_lb_endpoint_params(fx))["VerifiedAccessEndpoint"]["VerifiedAccessEndpointId"]
+ same = _group(ec2, fx["instance"])
+ other_inst, other_tp = _instance_with_provider(ec2)
+ other = _group(ec2, other_inst)
+ move = ec2.modify_verified_access_endpoint
+ with pytest.raises(ClientError) as exc:
+ move(VerifiedAccessEndpointId=ep_id, VerifiedAccessGroupId=_MISSING["Group"])
+ assert _error(exc) == ("InvalidVerifiedAccessGroupId.NotFound", f"The verified-access-group ID '{_MISSING['Group']}' does not exist")
+ with pytest.raises(ClientError) as exc:
+ move(VerifiedAccessEndpointId=ep_id, VerifiedAccessGroupId=other)
+ assert _error(exc) == ("InvalidParameterValue", "Cannot move a VerifiedAccessEndpoint to a VerifiedAccessGroup that "
+ "belongs to a different VerifiedAccessInstance.")
+ moved = move(VerifiedAccessEndpointId=ep_id, VerifiedAccessGroupId=same)["VerifiedAccessEndpoint"]
+ assert (moved["VerifiedAccessGroupId"], moved["Status"]) == (same, {"Code": "updating"})
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_group(VerifiedAccessGroupId=same, VerifiedAccessInstanceId=other_inst)
+ assert _error(exc) == ("InvalidParameterValue", f"VerifiedAccessGroup {same} is not empty. "
+ "Please remove all VerifiedAccessEndpoints before changing VerifiedAccessInstanceId.")
+ with pytest.raises(ClientError) as exc:
+ ec2.detach_verified_access_trust_provider(VerifiedAccessInstanceId=fx["instance"],
+ VerifiedAccessTrustProviderId=fx["provider"])
+ assert _error(exc)[0] == "VerifiedAccessGroupAttachmentExists"
+ ec2.delete_verified_access_endpoint(VerifiedAccessEndpointId=ep_id)
+ ec2.delete_verified_access_group(VerifiedAccessGroupId=same)
+ _cleanup(ec2, groups=[other], instances=[other_inst], providers=[other_tp])
+
+
+def test_verified_access_network_interface_endpoint(ec2, endpoint_fixture):
+ """V5:create:eni, V5:modify:port, V5:modify:protocol-http, V5:modify:lb-options-on-eni, V5:modify:port-ranges, V5:get-policy:none."""
+ fx = endpoint_fixture
+ ep = ec2.create_verified_access_endpoint(**_lb_endpoint_params(
+ fx, EndpointType="network-interface", LoadBalancerOptions=None, ApplicationDomain="eni.example.com",
+ EndpointDomainPrefix="eni", NetworkInterfaceOptions={"NetworkInterfaceId": fx["eni"], "Protocol": "https", "Port": 443},
+ ))["VerifiedAccessEndpoint"]
+ ep_id = ep["VerifiedAccessEndpointId"]
+ assert ep["NetworkInterfaceOptions"] == {"NetworkInterfaceId": fx["eni"], "Port": 443, "Protocol": "https"}
+ assert "LoadBalancerOptions" not in ep
+ policy = ec2.get_verified_access_endpoint_policy(VerifiedAccessEndpointId=ep_id)
+ assert (policy["PolicyEnabled"], "PolicyDocument" in policy) == (False, False)
+ modified = ec2.modify_verified_access_endpoint(
+ VerifiedAccessEndpointId=ep_id, NetworkInterfaceOptions={"Port": 8443, "Protocol": "http"})["VerifiedAccessEndpoint"]
+ assert modified["NetworkInterfaceOptions"] == {"NetworkInterfaceId": fx["eni"], "Port": 8443, "Protocol": "http"}
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id, LoadBalancerOptions={"Port": 443})
+ assert _error(exc) == ("InvalidParameterCombination",
+ "LoadBalancerOptions may only be specified for Verified Access Endpoints with load-balancer type")
+ with pytest.raises(ClientError) as exc:
+ ec2.modify_verified_access_endpoint(VerifiedAccessEndpointId=ep_id,
+ NetworkInterfaceOptions={"PortRanges": [{"FromPort": 443, "ToPort": 443}]})
+ assert _error(exc) == ("InvalidParameterValue", "Parameter PortRanges is not currently supported for the operation")
+
+
+# ── IAM ────────────────────────────────────────────────────
+
+
+def test_verified_access_iam_resource_arns():
+ """A14:*, E1:*, W7:deny:*, V3:deny:*, Z5:deny:*: the resource AWS names when it denies each call, the
+ id's ARN for a resource that exists and <type>/* for one that does not."""
+ from ministack.core.iam_actions import extract_resource_arn
+ from ministack.services import ec2 as mod
+
+ account, region = "123456789012", "us-east-1"
+ for store, key in ((mod._va_instances, "vai-00000000000000001"), (mod._va_trust_providers, "vatp-00000000000000001"),
+ (mod._va_groups, "vagr-00000000000000001"), (mod._va_endpoints, "vae-00000000000000001"),
+ (mod._subnets, "subnet-00000001"), (mod._security_groups, "sg-00000001"),
+ (mod._network_interfaces, "eni-00000001")):
+ store.set_scoped(account, region, key, {})
+ mod._va_endpoints.set_scoped(account, region, "vae-00000000000000002", {"Status": "deleting"})
+
+ def arn(params):
+ query = {k: [v] for k, v in params.items()}
+ return extract_resource_arn("ec2", "POST", "/", {}, b"", query, region, account)
+
+ prefix = f"arn:aws:ec2:{region}:{account}:"
+ vai, vatp, vagr, vae = "vai-00000000000000001", "vatp-00000000000000001", "vagr-00000000000000001", "vae-00000000000000001"
+ try:
+ for params, expected in (
+ ({"Action": "CreateVerifiedAccessInstance"}, "verified-access-instance/*"),
+ ({"Action": "CreateVerifiedAccessTrustProvider", "TrustProviderType": "user"}, "verified-access-trust-provider/*"),
+ ({"Action": "DeleteVerifiedAccessInstance", "VerifiedAccessInstanceId": vai}, f"verified-access-instance/{vai}"),
+ ({"Action": "DeleteVerifiedAccessInstance", "VerifiedAccessInstanceId": "vai-0000000000000000f"},
+ "verified-access-instance/*"),
+ ({"Action": "ModifyVerifiedAccessInstance", "VerifiedAccessInstanceId": "abc"}, "verified-access-instance/*"),
+ ({"Action": "ModifyVerifiedAccessTrustProvider", "VerifiedAccessTrustProviderId": vatp},
+ f"verified-access-trust-provider/{vatp}"),
+ ({"Action": "AttachVerifiedAccessTrustProvider", "VerifiedAccessInstanceId": vai,
+ "VerifiedAccessTrustProviderId": vatp}, f"verified-access-instance/{vai}"),
+ ({"Action": "AttachVerifiedAccessTrustProvider", "VerifiedAccessInstanceId": "abc",
+ "VerifiedAccessTrustProviderId": "vatp-0000000000000000f"}, "verified-access-trust-provider/*"),
+ ({"Action": "CreateVerifiedAccessGroup", "VerifiedAccessInstanceId": vai}, f"verified-access-instance/{vai}"),
+ ({"Action": "ModifyVerifiedAccessGroup", "VerifiedAccessGroupId": vagr}, f"verified-access-group/{vagr}"),
+ ({"Action": "ModifyVerifiedAccessGroup", "VerifiedAccessGroupId": vagr, "VerifiedAccessInstanceId": vai},
+ f"verified-access-instance/{vai}"),
+ ({"Action": "GetVerifiedAccessGroupPolicy", "VerifiedAccessGroupId": vagr}, f"verified-access-group/{vagr}"),
+ ({"Action": "ModifyVerifiedAccessEndpoint", "VerifiedAccessEndpointId": "vae-0000000000000000f",
+ "VerifiedAccessGroupId": vagr}, "verified-access-endpoint/*"),
+ ({"Action": "GetVerifiedAccessEndpointPolicy", "VerifiedAccessEndpointId": vae}, f"verified-access-endpoint/{vae}"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-1",
+ "LoadBalancerOptions.SubnetId.1": "subnet-00000001"}, "subnet/subnet-00000001"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr,
+ "LoadBalancerOptions.SubnetId.1": "subnet-0000000f"}, f"verified-access-group/{vagr}"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": "vagr-0000000000000000f"},
+ "verified-access-group/*"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-00000001"},
+ "security-group/sg-00000001"),
+ ({"Action": "ModifyVerifiedAccessGroup", "VerifiedAccessGroupId": vagr, "VerifiedAccessInstanceId": "abc"},
+ f"verified-access-group/{vagr}"),
+ ({"Action": "CreateVerifiedAccessEndpoint"}, "verified-access-endpoint/*"),
+ # U2:deny:* (round 11), V2:deny:* (round 12): every subnet is scanned, then every security group.
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-00000001",
+ "LoadBalancerOptions.SubnetId.1": "subnet-0000000f", "LoadBalancerOptions.SubnetId.2": "subnet-00000001"},
+ "subnet/subnet-00000001"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-0000000f",
+ "SecurityGroupId.2": "sg-00000001", "LoadBalancerOptions.SubnetId.1": "subnet-0000000f"},
+ "security-group/sg-00000001"),
+ # V2:deny:* (round 12): the first known security group at any index; with none known, the group.
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-00000001",
+ "SecurityGroupId.2": "sg-0000000f", "LoadBalancerOptions.SubnetId.1": "subnet-0000000f"},
+ "security-group/sg-00000001"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-0000000f",
+ "LoadBalancerOptions.SubnetId.1": "subnet-0000000f"}, f"verified-access-group/{vagr}"),
+ # X5:deny:eni-real+fake-sg-only (round 14): a known ENI with no known security group.
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-0000000f",
+ "NetworkInterfaceOptions.NetworkInterfaceId": "eni-00000001"}, "network-interface/eni-00000001"),
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "SecurityGroupId.1": "sg-00000001",
+ "NetworkInterfaceOptions.NetworkInterfaceId": "eni-00000001"}, "security-group/sg-00000001"),
+ # Z4:deny:lb-subnet+known-eni (round 16): a known subnet before a known ENI.
+ ({"Action": "CreateVerifiedAccessEndpoint", "VerifiedAccessGroupId": vagr, "LoadBalancerOptions.SubnetId.1": "subnet-00000001",
+ "NetworkInterfaceOptions.NetworkInterfaceId": "eni-00000001"}, "subnet/subnet-00000001"),
+ # U6:deny:* (round 11): a deleting endpoint is named like a missing one.
+ ({"Action": "ModifyVerifiedAccessEndpoint", "VerifiedAccessEndpointId": "vae-00000000000000002"},
+ "verified-access-endpoint/*"),
+ ({"Action": "DeleteVerifiedAccessEndpoint", "VerifiedAccessEndpointId": "vae-00000000000000002"},
+ "verified-access-endpoint/*"),
+ ):
+ assert arn(params) == prefix + expected, params
+ assert arn({"Action": "DescribeVerifiedAccessGroups", "VerifiedAccessInstanceId": vai}) == "*"
+ finally:
+ for store, key in ((mod._va_instances, vai), (mod._va_trust_providers, vatp), (mod._va_groups, vagr),
+ (mod._va_endpoints, vae), (mod._va_endpoints, "vae-00000000000000002"),
+ (mod._subnets, "subnet-00000001"), (mod._security_groups, "sg-00000001"),
+ (mod._network_interfaces, "eni-00000001")):
+ store.pop_scoped(account, region, key, None)
+
+
[email protected]("permission", ["none", "allow", "other-resource", "explicit-deny"])
+def test_verified_access_modify_permission_contract(auth_enabled, iam_user, permission):
+ """W7:deny:modify-instance: ModifyVerifiedAccessInstance is authorized on the instance ARN."""
+ admin = make_client("ec2")
+ inst_id = _instance(admin, Description="before")
+ resource = f"arn:aws:ec2:us-east-1:000000000000:verified-access-instance/{inst_id}"
+ statements = []
+ if permission != "none":
+ target = resource.replace(inst_id, "vai-00000000000000000") if permission == "other-resource" else resource
+ statements.append({"Effect": "Allow", "Action": "ec2:ModifyVerifiedAccessInstance", "Resource": target})
+ if permission == "explicit-deny":
+ statements.append({"Effect": "Deny", "Action": "ec2:ModifyVerifiedAccessInstance", "Resource": resource})
+ policy = {"Version": "2012-10-17", "Statement": statements} if statements else None
+ client = iam_user(policy=policy).client("ec2")
+ try:
+ if auth_enabled and permission != "allow":
+ with pytest.raises(ClientError) as exc:
+ client.modify_verified_access_instance(VerifiedAccessInstanceId=inst_id, Description="after")
+ assert _error(exc)[0] == "UnauthorizedOperation"
+ assert _status(exc) == 403
+ expected = "before"
+ else:
+ client.modify_verified_access_instance(VerifiedAccessInstanceId=inst_id, Description="after")
+ expected = "after"
+ assert admin.describe_verified_access_instances(
+ VerifiedAccessInstanceIds=[inst_id])["VerifiedAccessInstances"][0]["Description"] == expected
+ finally:
+ admin.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+
+
+def test_verified_access_create_permission_contract(auth_enabled, iam_user):
+ """V3:deny:create-instance: CreateVerifiedAccessInstance is authorized on verified-access-instance/*."""
+ resource = "arn:aws:ec2:us-east-1:000000000000:verified-access-instance/*"
+ allowed = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "ec2:CreateVerifiedAccessInstance", "Resource": resource},
+ {"Effect": "Allow", "Action": "ec2:DeleteVerifiedAccessInstance", "Resource": "*"}]}).client("ec2")
+ denied = iam_user().client("ec2")
+ inst_id = _instance(allowed)
+ allowed.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ denied.create_verified_access_instance()
+ assert (_status(exc), _error(exc)[0]) == (403, "UnauthorizedOperation")
+ else:
+ inst_id = _instance(denied)
+ denied.delete_verified_access_instance(VerifiedAccessInstanceId=inst_id)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 57bff697..ca29929b 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -5786,3 +5786,104 @@ def test_signer_jobs_profiles_and_tokens_survive_warm_boot():
}
finally:
mod.reset()
+
+
+def _ec2_va_populate(mod, account_id, region, label):
+ """Create one of each Verified Access resource through the handlers, in one scope."""
+ import json
+
+ from ministack.core.responses import request_scope
+ from ministack.services import acm
+
+ oidc = {"Issuer": "https://idp.example.com", "AuthorizationEndpoint": "https://idp.example.com/a",
+ "TokenEndpoint": "https://idp.example.com/t", "UserInfoEndpoint": "https://idp.example.com/u",
+ "ClientId": "c", "ClientSecret": "s", "Scope": "openid"}
+ with request_scope(account_id, region):
+ mod._ensure_defaults_initialized()
+ status, _, body = mod._create_verified_access_trust_provider({
+ "TrustProviderType": "user", "UserTrustProviderType": "oidc", "PolicyReferenceName": label,
+ **{f"OidcOptions.{k}": v for k, v in oidc.items()},
+ "TagSpecification.1.ResourceType": "verified-access-trust-provider",
+ "TagSpecification.1.Tag.1.Key": "owner", "TagSpecification.1.Tag.1.Value": label,
+ })
+ assert status == 200, body
+ tp_id = next(iter(mod._va_trust_providers))
+ status, _, body = mod._create_verified_access_instance({
+ "Description": label,
+ "TagSpecification.1.ResourceType": "verified-access-instance",
+ "TagSpecification.1.Tag.1.Key": "owner", "TagSpecification.1.Tag.1.Value": label,
+ })
+ assert status == 200, body
+ inst_id = next(iter(mod._va_instances))
+ assert mod._attach_verified_access_trust_provider({
+ "VerifiedAccessInstanceId": inst_id, "VerifiedAccessTrustProviderId": tp_id})[0] == 200
+ assert mod._modify_verified_access_instance_logging_configuration({
+ "VerifiedAccessInstanceId": inst_id, "AccessLogs.IncludeTrustContext": "true"})[0] == 200
+ assert mod._create_verified_access_group({
+ "VerifiedAccessInstanceId": inst_id, "PolicyDocument": f"permit-{label}"})[0] == 200
+ group_id = next(iter(mod._va_groups))
+ enis = set(mod._network_interfaces)
+ assert mod._create_network_interface({"SubnetId": mod._DEFAULT_SUBNET_ID})[0] == 200
+ eni_id = next(iter(set(mod._network_interfaces) - enis))
+ cert_arn = json.loads(acm._request_certificate({"DomainName": f"{label}.example.com"})[2])["CertificateArn"]
+ groups = set(mod._security_groups)
+ assert mod._create_security_group({"GroupName": f"va-{label}", "GroupDescription": "va",
+ "VpcId": mod._DEFAULT_VPC_ID})[0] == 200
+ sg_id = next(iter(set(mod._security_groups) - groups))
+ status, _, body = mod._create_verified_access_endpoint({
+ "VerifiedAccessGroupId": group_id, "EndpointType": "network-interface", "AttachmentType": "vpc",
+ "DomainCertificateArn": cert_arn, "ApplicationDomain": f"{label}.example.com", "EndpointDomainPrefix": label,
+ "NetworkInterfaceOptions.NetworkInterfaceId": eni_id, "NetworkInterfaceOptions.Port": "443",
+ "NetworkInterfaceOptions.Protocol": "https", "SecurityGroupId.1": sg_id,
+ })
+ assert status == 200, body
+ ep_id = next(iter(mod._va_endpoints))
+ return {"tp": tp_id, "inst": inst_id, "group": group_id, "ep": ep_id}
+
+
+def test_ec2_verified_access_round_trip_across_accounts():
+ from ministack.core.responses import request_scope
+
+ scopes = (("111111111111", "us-east-1", "a"), ("222222222222", "eu-west-1", "b"))
+ ids = {}
+
+ def populate(mod):
+ for account_id, region, label in scopes:
+ ids[label] = _ec2_va_populate(mod, account_id, region, label)
+
+ def observe(mod):
+ for account_id, region, label in scopes:
+ got = ids[label]
+ with request_scope(account_id, region):
+ tp = mod._va_trust_providers.get(got["tp"])
+ assert tp["PolicyReferenceName"] == label
+ assert tp["OidcOptions"]["ClientSecret"] == "s"
+ inst = mod._va_instances.get(got["inst"])
+ assert inst["Description"] == label
+ assert inst["TrustProviderIds"] == [got["tp"]]
+ assert inst["AccessLogs"]["IncludeTrustContext"] is True
+ assert mod._va_groups.get(got["group"])["PolicyDocument"] == f"permit-{label}"
+ assert mod._va_endpoints.get(got["ep"])["VerifiedAccessGroupId"] == got["group"]
+ for resource_id in (got["tp"], got["inst"]):
+ assert mod._tags.get(resource_id) == [{"Key": "owner", "Value": label}]
+ # The other tenant's resources stay invisible from this scope.
+ other = ids["b" if label == "a" else "a"]
+ with request_scope(account_id, region):
+ assert other["inst"] not in mod._va_instances
+
+ _round_trip("ec2", "ec2", populate, observe)
+
+
+def test_ec2_verified_access_reset_clears_stores():
+ from ministack.core.responses import request_scope
+
+ mod = _module("ec2")
+ mod.reset()
+ got = _ec2_va_populate(mod, "111111111111", "us-east-1", "r")
+ mod.reset()
+ with request_scope("111111111111", "us-east-1"):
+ assert got["inst"] not in mod._va_instances
+ assert got["tp"] not in mod._va_trust_providers
+ assert got["group"] not in mod._va_groups
+ assert got["ep"] not in mod._va_endpoints
+ assert mod._tags.get(got["inst"]) is None