Skip to content

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

fix(eks, s3): fix id asoc, s3 fanout (#1710)

Nahuel Nucerad5c7e257f524
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e044edc1..20576301 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,11 +8,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **EKS — Pod Identity associations** — the five operations did not exist, so a controller that reads pod identity to find its role (the AWS Load Balancer Controller among them) could not run against MiniStack at all. `CreatePodIdentityAssociation`, `DescribePodIdentityAssociation`, `ListPodIdentityAssociations` (filtered by `namespace` and `serviceAccount`), `UpdatePodIdentityAssociation` and `DeletePodIdentityAssociation` serve the association records, with one association per namespace and service account, an `externalId` minted for a `targetRoleArn` chain, and the summary shape on the list. Nothing runs inside the cluster: the association is a control-plane record, which is what the API serves. Reported by @josephaw1022
- **EKS — managed Access Policy authorization in k3s** — `AmazonEKSClusterAdminPolicy`, `AmazonEKSAdminPolicy`, `AmazonEKSEditPolicy`, `AmazonEKSViewPolicy`, and `AmazonEKSAdminViewPolicy` now grant their published Kubernetes permissions under `AUTH=true`. Cluster and namespace scopes, including namespace wildcard patterns, are reconciled to managed k3s RBAC bindings after policy changes and when matching namespaces appear; disassociating a policy or deleting its Access Entry revokes the bindings.
### Fixed
+- **S3 — a notification configuration whose destination does not exist is refused** — `PutBucketNotificationConfiguration` stored the configuration and swallowed the failed test delivery, so a queue or topic that was not there looked like a successful setup and no event ever arrived. AWS verifies an SNS or SQS destination by sending it a test notification, and "if the message fails, the entire PUT action will fail, and Amazon S3 will not add the configuration to your bucket": a missing queue or topic is now `InvalidArgument` (400) with nothing stored. A Lambda destination is still not checked, since AWS verifies that one through the function's permissions. Reported by @ortizgui.
- **EKS — AWS CLI kubeconfig authentication** — k3s accepts `aws eks get-token` credentials through a MiniStack TokenReview webhook, so `aws eks update-kubeconfig` works without copying a container's admin kubeconfig. `AUTH=false` permits local bearer tokens; `AUTH=true` validates IAM credentials and requires creator or Access Entry grants, including account-scoped STS sessions. Fixes #1140.
-### Fixed
- **IAM — a resource-scoped policy matches, instead of denying** — `extract_resource_arn` returned `*` for three whole families of request, and a resource-scoped policy can never match `*`, so under `AUTH=true` the only grant that worked was one written as `Resource: "*"`. First, IoT mapped six path prefixes to ARNs but not `/jobs` or `/provisioning-templates`, and neither data plane had a branch at all: a client signs those with the `iotdata` and `iotjobsdata` scopes, so they arrive as their own service keys and fell through. That rules out what the CDK emits: its `AwsCustomResource` for an IoT job grants `iot:CreateJob` on exactly `job/<jobId>` plus the target `thinggroup/<name>`, the scoping AWS documents, and a CloudFormation stack carrying one failed to deploy here with `is not authorized to perform: iot:CreateJob` while deploying on AWS. A publish and a retained message now resolve to their topic, which carries every level (`topic/sensors/rack-1/temperature`), and a shadow or job execution to its thing. `Publish` also resolves an action again: its URI label is non-greedy, so the SDK percent-encodes the separators and the ASGI server hands them back decoded, and a route compiled as one segment then matched no topic below the first level. Second, the query-protocol services (EC2, CloudFormation, CloudWatch, Auto Scaling, ElastiCache) carry their parameters in a form-encoded body when the SDK POSTs, which botocore does, so nothing reached the query string and every branch reading it resolved nothing: `ec2:AuthorizeSecurityGroupIngress` scoped to one security group was denied for that group. The router already parsed that body to find `Action` and now keeps the rest of it, merged underneath the query string, which still wins. Third, an `execute-api` invoke was authorized against `*` as well, so a policy naming one API and stage, which is what `grantExecute` and every service-to-service grant emit, never matched; it now resolves to `arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/<METHOD>/<path>`, built by the same helper the Lambda authorizer's method ARN uses, and authorized once the stage is known so a v2 API on `$default` is not charged for a stage segment it does not have. Contributed by @iot-rocket.
- **CloudFormation — `AWS::IAM::Policy` is provisioned inline, not as a managed policy** — the document was stored as an account-global customer-managed policy and attached to the Roles, Users and Groups the resource named, where CloudFormation embeds it on each of them the way `PutRolePolicy`, `PutUserPolicy` and `PutGroupPolicy` do. The difference is that an inline policy is scoped to its entity, so the same `PolicyName` can exist on many entities at once, and CDK relies on it: it derives `PolicyName` from the construct path, so every stack granting something to a role reached by the same path emits the same name. Twenty of one deployment's twenty-seven policies collapsed onto two records, and each deploy took the grants away from the stacks before it; under `AUTH=true` those roles were then denied the actions their own templates granted. The document now goes onto each entity through the existing inline handlers, so `ListRolePolicies`, `GetRolePolicy` and the `RolePolicyList` of `GetAccountAuthorizationDetails` report it and the IAM evaluator finds it. The physical id is generated rather than being the `PolicyName`, which is what AWS returns: measured against the account, a stack with an explicit `PolicyName` of `ms0049-refprobe-explicit-name` answers `Ref` with `ms0049--Pol-AW24HieEB0iX`, and `list-policies --scope Local` over an estate of forty deployed stacks counts zero. `AWS::IAM::ManagedPolicy` is unchanged. Contributed by @iot-rocket.
- **Lambda — dispatch SQS event source batches concurrently** — one thread polled every mapping and waited for each invoke, so a handler that took 10 seconds held a message on an unrelated queue for about 8.6 seconds, and `ScalingConfig.MaximumConcurrency` was stored but ignored. SQS batches are now invoked off the poll thread, up to `MaximumConcurrency` batches per mapping (default 5), lowered to the function's `ReservedConcurrentExecutions` so a mapping does not throttle its own function. Kinesis and DynamoDB Streams mappings still process one batch at a time. Contributed by @ThailerL.
diff --git a/README.md b/README.md
index 021cf98c..4a97e24d 100644
--- a/README.md
+++ b/README.md
@@ -601,7 +601,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 52 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry |
| **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists |
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
-| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
+| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
| **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |
| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` |
| **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix |
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 3cc63a38..fa8d4646 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -12,6 +12,9 @@ Supports:
Nodegroups: CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup
IdP configs: AssociateIdentityProviderConfig, DescribeIdentityProviderConfig,
DisassociateIdentityProviderConfig, ListIdentityProviderConfigs
+ Pod identity: CreatePodIdentityAssociation, DescribePodIdentityAssociation,
+ ListPodIdentityAssociations, UpdatePodIdentityAssociation,
+ DeletePodIdentityAssociation
Authentication: AWS IAM exec tokens through a k3s TokenReview webhook
Tags: TagResource, UntagResource, ListTagsForResource
"""
@@ -90,6 +93,7 @@ _access_entries = AccountRegionScopedDict() # "cluster\x00principalArn" -> acces
_access_policies = AccountRegionScopedDict()# "cluster\x00principalArn\x00policyArn" -> associated policy
_tags = AccountScopedDict() # arn -> {key: value}
_idp_configs = AccountRegionScopedDict() # "cluster\x00idp_name" -> idp record
+_pod_identity_associations = AccountRegionScopedDict() # "cluster\x00associationId" -> association
_port_counter_lock = threading.Lock()
_port_counter = [EKS_BASE_PORT]
_oidc_keypair_lock = threading.Lock()
@@ -178,6 +182,7 @@ def reset():
_access_policies.clear()
_tags.clear()
_idp_configs.clear()
+ _pod_identity_associations.clear()
_port_counter[0] = EKS_BASE_PORT
_stop_all_k3s()
@@ -199,6 +204,7 @@ def get_state():
"access_policies": copy.deepcopy(_access_policies),
"tags": copy.deepcopy(_tags),
"idp_configs": copy.deepcopy(_idp_configs),
+ "pod_identity_associations": copy.deepcopy(_pod_identity_associations),
"port_counter": _port_counter[0],
}
@@ -248,6 +254,7 @@ def restore_state(data):
(_access_entries, "access_entries", "\x00"),
(_access_policies, "access_policies", "\x00"),
(_idp_configs, "idp_configs", "\x00"),
+ (_pod_identity_associations, "pod_identity_associations", "\x00"),
):
_restore_cluster_child_store(
store,
@@ -329,6 +336,18 @@ def _ap_key(cluster_name: str, principal_arn: str, policy_arn: str) -> str:
return f"{cluster_name}\x00{principal_arn}\x00{policy_arn}"
+def _pia_key(cluster_name: str, association_id: str) -> str:
+ return f"{cluster_name}\x00{association_id}"
+
+
+def _pod_identity_association_arn(cluster_name, association_id):
+ # AWS: arn:aws:eks:{region}:{account}:podidentityassociation/{cluster}/{associationId}.
+ return (
+ f"arn:aws:eks:{get_region()}:{get_account_id()}:"
+ f"podidentityassociation/{cluster_name}/{association_id}"
+ )
+
+
def _now():
return int(time.time())
@@ -798,6 +817,15 @@ def _delete_cluster(name):
if ng:
_tags.pop(ng.get("nodegroupArn", ""), None)
+ # Pod identity associations belong to the cluster, so they go with it.
+ # Left behind they outlive it, and a cluster recreated under the same name
+ # would inherit the previous one's associations and their role ARNs.
+ prefix = f"{name}\x00"
+ for key in [k for k in _pod_identity_associations if str(k).startswith(prefix)]:
+ assoc = _pod_identity_associations.pop(key, None)
+ if assoc:
+ _tags.pop(assoc.get("associationArn", ""), None)
+
arn = cluster["arn"]
cluster["status"] = "DELETING"
result = _sanitize(cluster)
@@ -1067,6 +1095,140 @@ def _list_access_entries(cluster_name, query):
return _json_resp(200, {"accessEntries": arns[:max_results]})
+# ---------------------------------------------------------------------------
+# EKS Pod Identity associations
+#
+# A pod identity association binds a Kubernetes service account in a namespace
+# to an IAM role. The EKS Pod Identity Agent and the controllers that read it
+# (the AWS Load Balancer Controller among them) list and describe these
+# records; nothing here runs inside the cluster, so the association is a
+# control-plane record, which is what the API serves.
+# ---------------------------------------------------------------------------
+
+def _pod_identity_summary(assoc):
+ """The PodIdentityAssociationSummary shape ListPodIdentityAssociations
+ returns: six of the full record's members, not the whole association."""
+ return {
+ "clusterName": assoc["clusterName"],
+ "namespace": assoc["namespace"],
+ "serviceAccount": assoc["serviceAccount"],
+ "associationArn": assoc["associationArn"],
+ "associationId": assoc["associationId"],
+ "ownerArn": assoc.get("ownerArn", ""),
+ }
+
+
+def _create_pod_identity_association(cluster_name, body):
+ if cluster_name not in _clusters:
+ return _error(404, "ResourceNotFoundException",
+ f"No cluster found for name: {cluster_name}.")
+ namespace = body.get("namespace", "")
+ service_account = body.get("serviceAccount", "")
+ role_arn = body.get("roleArn", "")
+ for name, value in (("namespace", namespace), ("serviceAccount", service_account),
+ ("roleArn", role_arn)):
+ if not value:
+ return _error(400, "InvalidParameterException", f"{name} is required.")
+ # One association per (namespace, service account): a second one is
+ # ResourceInUseException, which the operation documents.
+ for key, existing in list(_pod_identity_associations.items()):
+ if (key.startswith(f"{cluster_name}\x00")
+ and existing["namespace"] == namespace
+ and existing["serviceAccount"] == service_account):
+ return _error(409, "ResourceInUseException",
+ f"Association already exists for service account "
+ f"{service_account} in namespace {namespace}.")
+ association_id = "a-" + new_uuid().replace("-", "")[:16]
+ now = _now()
+ assoc = {
+ "clusterName": cluster_name,
+ "namespace": namespace,
+ "serviceAccount": service_account,
+ "roleArn": role_arn,
+ "associationArn": _pod_identity_association_arn(cluster_name, association_id),
+ "associationId": association_id,
+ "tags": body.get("tags", {}),
+ "createdAt": now,
+ "modifiedAt": now,
+ "ownerArn": "",
+ "disableSessionTags": bool(body.get("disableSessionTags", False)),
+ }
+ if body.get("targetRoleArn"):
+ # A target role makes this a role-chaining association, and AWS mints
+ # the externalId the target role's trust policy matches on.
+ assoc["targetRoleArn"] = body["targetRoleArn"]
+ assoc["externalId"] = new_uuid()
+ if body.get("policy"):
+ assoc["policy"] = body["policy"]
+ _pod_identity_associations[_pia_key(cluster_name, association_id)] = assoc
+ if assoc["tags"]:
+ _tags[assoc["associationArn"]] = dict(assoc["tags"])
+ return _json_resp(200, {"association": assoc})
+
+
+def _describe_pod_identity_association(cluster_name, association_id):
+ assoc = _pod_identity_associations.get(_pia_key(cluster_name, association_id))
+ if not assoc:
+ return _error(404, "ResourceNotFoundException",
+ f"No pod identity association found for ID: {association_id}.")
+ return _json_resp(200, {"association": assoc})
+
+
+def _list_pod_identity_associations(cluster_name, query):
+ if cluster_name not in _clusters:
+ return _error(404, "ResourceNotFoundException",
+ f"No cluster found for name: {cluster_name}.")
+ namespace = query.get("namespace")
+ service_account = query.get("serviceAccount")
+ prefix = f"{cluster_name}\x00"
+ summaries = []
+ for key, assoc in _pod_identity_associations.items():
+ if not key.startswith(prefix):
+ continue
+ if namespace is not None and assoc["namespace"] != namespace:
+ continue
+ if service_account is not None and assoc["serviceAccount"] != service_account:
+ continue
+ summaries.append(_pod_identity_summary(assoc))
+ summaries.sort(key=lambda a: a["associationId"])
+ max_results = int(query.get("maxResults", 100))
+ return _json_resp(200, {"associations": summaries[:max_results]})
+
+
+def _update_pod_identity_association(cluster_name, association_id, body):
+ key = _pia_key(cluster_name, association_id)
+ assoc = _pod_identity_associations.get(key)
+ if not assoc:
+ return _error(404, "ResourceNotFoundException",
+ f"No pod identity association found for ID: {association_id}.")
+ # The request carries only the mutable members; namespace and service
+ # account are not among them, so an association keeps the pair it was
+ # created for.
+ if body.get("roleArn"):
+ assoc["roleArn"] = body["roleArn"]
+ if "disableSessionTags" in body:
+ assoc["disableSessionTags"] = bool(body["disableSessionTags"])
+ if body.get("targetRoleArn"):
+ assoc["targetRoleArn"] = body["targetRoleArn"]
+ assoc.setdefault("externalId", new_uuid())
+ if body.get("policy"):
+ assoc["policy"] = body["policy"]
+ assoc["modifiedAt"] = _now()
+ return _json_resp(200, {"association": assoc})
+
+
+def _delete_pod_identity_association(cluster_name, association_id):
+ key = _pia_key(cluster_name, association_id)
+ assoc = _pod_identity_associations.get(key)
+ if not assoc:
+ return _error(404, "ResourceNotFoundException",
+ f"No pod identity association found for ID: {association_id}.")
+ _tags.pop(assoc.get("associationArn", ""), None)
+ _pod_identity_associations.pop(key, None)
+ # The deleted association is the response body, as the operation documents.
+ return _json_resp(200, {"association": assoc})
+
+
def _delete_access_entry(cluster_name, principal_arn):
key = _ae_key(cluster_name, principal_arn)
entry = _access_entries.get(key)
@@ -2275,6 +2437,26 @@ def _handle_request_sync(method, path, headers, body_bytes, query_params):
if method == "DELETE":
return _delete_nodegroup(cluster_name, ng_name)
+ # /clusters/{name}/pod-identity-associations — Create / List
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/pod-identity-associations", path)
+ if m:
+ cluster_name = m.group(1)
+ if method == "POST":
+ return _create_pod_identity_association(cluster_name, body)
+ if method == "GET":
+ return _list_pod_identity_associations(cluster_name, query)
+
+ # /clusters/{name}/pod-identity-associations/{associationId}
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/pod-identity-associations/([A-Za-z0-9_-]+)", path)
+ if m:
+ cluster_name, association_id = m.group(1), m.group(2)
+ if method == "GET":
+ return _describe_pod_identity_association(cluster_name, association_id)
+ if method == "POST":
+ return _update_pod_identity_association(cluster_name, association_id, body)
+ if method == "DELETE":
+ return _delete_pod_identity_association(cluster_name, association_id)
+
# POST /clusters/{name}/encryption-config/associate — AssociateEncryptionConfig
m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/encryption-config/associate", path)
if m:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 631255e9..4b01719a 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -3060,11 +3060,44 @@ def _validate_notification_target_arn(target_type: str, arn: str, bucket_region:
return None
+def _notification_destination_exists(target_type: str, arn: str, bucket_region: str) -> bool:
+ """Whether the queue or topic an SQS/SNS destination names is there.
+
+ S3 verifies an SNS or SQS destination by sending it a test notification,
+ and "if the message fails, the entire PUT action will fail, and Amazon S3
+ will not add the configuration to your bucket". A Lambda destination is
+ verified through its function permissions instead, which this emulator
+ does not model, so a Lambda target is not checked here.
+ """
+ spec = _parse_delivery_notification_target(target_type, arn, bucket_region)
+ if not spec:
+ return False
+ if target_type == "sqs":
+ from ministack.services import sqs as _sqs
+
+ return bool(_queue_name_from_sqs_arn_spec(spec)) and _sqs._queue_by_arn(str(spec)) is not None
+ from ministack.services import sns as _sns
+
+ return bool(_topic_name_from_sns_arn_spec(spec)) and _sns._topics.get(arn) is not None
+
+
def _validate_notification_configs(configs: list[dict], bucket_region: str) -> tuple | None:
for cfg in configs:
error = _validate_notification_target_arn(cfg["type"], cfg["arn"], bucket_region)
if error:
return error
+ # The destination check is second: an ARN that does not parse is reported
+ # as malformed before anything tries to reach what it names.
+ unreachable = [
+ cfg["arn"] for cfg in configs
+ if cfg["type"] in ("sqs", "sns")
+ and not _notification_destination_exists(cfg["type"], cfg["arn"], bucket_region)
+ ]
+ if unreachable:
+ return _invalid_notification_config(
+ "Unable to validate the following destination configurations: "
+ + ", ".join(unreachable)
+ )
return None
diff --git a/tests/test_eks.py b/tests/test_eks.py
index c32dafa4..5d5a5454 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -948,6 +948,165 @@ def _create_basic_cluster(eks):
return cn
+def test_eks_pod_identity_association_lifecycle(eks):
+ """EKS Pod Identity: the five operations a controller reading pod identity
+ needs. Create returns the full association, List the six-field summary,
+ Describe the record, Update the mutable members, and Delete answers with
+ the association it removed."""
+ cn = _create_basic_cluster(eks)
+ role = f"arn:aws:iam::000000000000:role/lbc-{_uid()}"
+ try:
+ created = eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system",
+ serviceAccount="aws-load-balancer-controller",
+ roleArn=role, tags={"team": "platform"},
+ )["association"]
+ assoc_id = created["associationId"]
+ assert created["clusterName"] == cn
+ assert created["namespace"] == "kube-system"
+ assert created["serviceAccount"] == "aws-load-balancer-controller"
+ assert created["roleArn"] == role
+ assert created["tags"] == {"team": "platform"}
+ assert created["associationArn"] == (
+ f"arn:aws:eks:{REGION}:000000000000:podidentityassociation/{cn}/{assoc_id}")
+ assert created["createdAt"] == created["modifiedAt"]
+
+ described = eks.describe_pod_identity_association(
+ clusterName=cn, associationId=assoc_id)["association"]
+ assert described["roleArn"] == role
+
+ # The list shape is the summary, not the whole association.
+ listed = eks.list_pod_identity_associations(clusterName=cn)["associations"]
+ assert len(listed) == 1
+ assert set(listed[0]) == {
+ "clusterName", "namespace", "serviceAccount",
+ "associationArn", "associationId", "ownerArn",
+ }
+
+ updated = eks.update_pod_identity_association(
+ clusterName=cn, associationId=assoc_id, roleArn=role + "-v2")["association"]
+ assert updated["roleArn"] == role + "-v2"
+ # namespace and serviceAccount are not members of the update request.
+ assert updated["namespace"] == "kube-system"
+ assert updated["serviceAccount"] == "aws-load-balancer-controller"
+
+ deleted = eks.delete_pod_identity_association(
+ clusterName=cn, associationId=assoc_id)["association"]
+ assert deleted["associationId"] == assoc_id
+ assert eks.list_pod_identity_associations(clusterName=cn)["associations"] == []
+ with pytest.raises(ClientError) as e:
+ eks.describe_pod_identity_association(clusterName=cn, associationId=assoc_id)
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
+def test_eks_pod_identity_associations_go_with_the_cluster(eks):
+ """A recreated cluster must not inherit the previous one's associations."""
+ cn = _create_basic_cluster(eks)
+ eks.create_pod_identity_association(
+ clusterName=cn, namespace="default", serviceAccount="app",
+ roleArn=f"arn:aws:iam::000000000000:role/pod-{_uid()}",
+ )
+ assert eks.list_pod_identity_associations(clusterName=cn)["associations"]
+
+ eks.delete_cluster(name=cn)
+ eks.create_cluster(name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
+ resourcesVpcConfig={"subnetIds": ["subnet-1"]})
+ try:
+ assert eks.list_pod_identity_associations(clusterName=cn)["associations"] == []
+ finally:
+ eks.delete_cluster(name=cn)
+
+
+def test_eks_pod_identity_association_list_filters(eks):
+ """ListPodIdentityAssociations filters on namespace and serviceAccount,
+ the two query parameters the operation takes."""
+ cn = _create_basic_cluster(eks)
+ role = "arn:aws:iam::000000000000:role/r"
+ try:
+ eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system", serviceAccount="lbc", roleArn=role)
+ eks.create_pod_identity_association(
+ clusterName=cn, namespace="apps", serviceAccount="web", roleArn=role)
+
+ by_ns = eks.list_pod_identity_associations(
+ clusterName=cn, namespace="apps")["associations"]
+ assert [a["serviceAccount"] for a in by_ns] == ["web"]
+ by_sa = eks.list_pod_identity_associations(
+ clusterName=cn, serviceAccount="lbc")["associations"]
+ assert [a["namespace"] for a in by_sa] == ["kube-system"]
+ assert len(eks.list_pod_identity_associations(clusterName=cn)["associations"]) == 2
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
+def test_eks_pod_identity_association_duplicate_and_missing(eks):
+ """One association per namespace and service account, and an unknown
+ cluster or association id is ResourceNotFoundException."""
+ cn = _create_basic_cluster(eks)
+ role = "arn:aws:iam::000000000000:role/r"
+ try:
+ eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system", serviceAccount="dup", roleArn=role)
+ with pytest.raises(ClientError) as e:
+ eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system", serviceAccount="dup", roleArn=role)
+ assert e.value.response["Error"]["Code"] == "ResourceInUseException"
+
+ with pytest.raises(ClientError) as e:
+ eks.describe_pod_identity_association(clusterName=cn, associationId="a-nope")
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ with pytest.raises(ClientError) as e:
+ eks.list_pod_identity_associations(clusterName=f"no-such-{_uid()}")
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ with pytest.raises(ClientError) as e:
+ eks.create_pod_identity_association(
+ clusterName=f"no-such-{_uid()}", namespace="n",
+ serviceAccount="s", roleArn=role)
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
+def test_eks_pod_identity_association_target_role_gets_an_external_id(eks):
+ """A target role makes the association role-chaining, and AWS mints the
+ externalId its trust policy matches on."""
+ cn = _create_basic_cluster(eks)
+ try:
+ assoc = eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system", serviceAccount="chained",
+ roleArn="arn:aws:iam::000000000000:role/source",
+ targetRoleArn="arn:aws:iam::000000000000:role/target",
+ disableSessionTags=True,
+ )["association"]
+ assert assoc["targetRoleArn"] == "arn:aws:iam::000000000000:role/target"
+ assert assoc["externalId"]
+ assert assoc["disableSessionTags"] is True
+
+ plain = eks.create_pod_identity_association(
+ clusterName=cn, namespace="kube-system", serviceAccount="plain",
+ roleArn="arn:aws:iam::000000000000:role/source")["association"]
+ assert "externalId" not in plain
+ assert plain["disableSessionTags"] is False
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
def test_eks_access_entry_create_describe_delete(eks):
cn = _create_basic_cluster(eks)
principal = f"arn:aws:iam::000000000000:user/test-{_uid()}"
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 1575702d..7f3c6525 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -1778,6 +1778,9 @@ def test_s3_notification_validates_target_region_against_bucket_region(s3):
Bucket=bkt,
CreateBucketConfiguration={"LocationConstraint": "us-west-2"},
)
+ # The destination has to exist: AWS verifies an SQS or SNS target by sending
+ # it a test notification and fails the whole PUT when that does not arrive.
+ _regional_client("sqs", "us-west-2").create_queue(QueueName="s3-west-region-q")
s3.put_bucket_notification_configuration(
Bucket=bkt,