Skip to content

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

fix(cognito): merge identities that share a login under AUTH=true (#2287)

iot-rocket9ba121af25a8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91a120b4..a5b09326 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,63 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-### Added
-- **Cognito — user pool feature plans** — `CreateUserPool`, `UpdateUserPool` and `AWS::Cognito::UserPool` ignored `UserPoolTier`; a pool now stores and describes its tier (`ESSENTIALS` by default, `PLUS` when created with threat protection on), keeps it when an update omits it, and refuses threat protection on `ESSENTIALS` and password history on `LITE` with `FeatureUnavailableInTierException` or, on a tier change, `TierChangeNotAllowedException`. Contributed by @iot-rocket.
-### Fixed
-- **IoT — topic rule name errors** — `CreateTopicRule` refused a name outside `^[a-zA-Z0-9_]+$` or longer than 128 characters with its own `Invalid ruleName: must match [a-zA-Z0-9_]{1,128}`; it now answers AWS's 400 `InvalidRequestException` validation message, which names the failed pattern, the failed length or both, and the topic rule calls that already checked the name give the length part too. A valid name followed by a newline passed the name check, so `CreateTopicRule` stored a rule under it; all six calls refuse it now. Contributed by @iot-rocket.
-- **IoT — unknown topic rules answer 401** — `GetTopicRule`, `ReplaceTopicRule`, `EnableTopicRule` and `DisableTopicRule` on a rule that does not exist answered 404 `ResourceNotFoundException` and `DeleteTopicRule` answered 200; they now answer 401 `UnauthorizedException` (`Access to topic rule '<name>' was denied`) as AWS does, and `GetTopicRule`, `ReplaceTopicRule` and `DeleteTopicRule` refuse a name outside the rule name pattern with the 400 `InvalidRequestException` that `EnableTopicRule` gives. Contributed by @iot-rocket.
-- **IoT — MQTT clients are held to the reserved topics AWS lets them use** — a client could subscribe to any `$` filter and publish to the replies AWS IoT writes itself (fleet provisioning, Jobs, Device Defender, MQTT file delivery, Device Location and commands), and an MQTT 5 publish to another `$` topic got DISCONNECT 0x87; the broker now refuses, before the policy check, a filter outside the reserved filters a client may use (SUBACK 0x8F on MQTT 5, a closed connection on 3.1.1) and a publish to those replies or to any other unknown `$` topic (PUBACK 0x90 on MQTT 5 and DISCONNECT 0x90 at QoS 0, a closed connection on 3.1.1), and HTTPS `Publish` answers "Topic can't start with $" for the fleet provisioning and Device Location replies, as AWS does. Contributed by @iot-rocket.
-- **IAM — trust policies with `NotPrincipal`** — `CreateRole`, `UpdateAssumeRolePolicy` and `AWS::IAM::Role` stored a trust policy with a `NotPrincipal` statement; they now answer `MalformedPolicyDocument` with IAM's message, `Allow with NotPrincipal is not allowed.` when an `Allow` statement carries it and `AssumeRole policy must not contain NotPrincipal field.` for a `Deny`, with `AUTH` on or off. Contributed by @iot-rocket.
-- **S3 — `x-amz-grant-*` headers** — `PutBucketAcl` and `PutObjectAcl` answered the grant headers with 400 `MissingSecurityHeader`, and `CreateBucket`, `PutObject` and `CopyObject` dropped them. On buckets with ACLs enabled all five now set an ACL of exactly the named grants, in the order S3 lists them, and refuse what S3 refuses: a malformed grant, an unknown group, an email grantee, and grant headers next to `x-amz-acl` or an ACL body. On a bucket with ACLs disabled (`BucketOwnerEnforced`) `PutBucketAcl` and `PutObjectAcl` refuse grant headers with 400 `AccessControlListNotSupported`. Contributed by @iot-rocket.
-- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.
-- **IoT — `NaN` and `Infinity` in job documents and shadow updates** — `CreateJob` and `CreateJobTemplate` (inline and `documentSource`) and `UpdateThingShadow` (HTTP and the MQTT `update`, `get` and `delete` topics) accepted `NaN`, `Infinity` and `-Infinity`, and a shadow wrote them back as bare tokens, which is not JSON; they are now refused as invalid JSON with the messages AWS gives (`Payload contains invalid json` for shadows, also for any other invalid shadow payload), and a shadow number beyond a double's range, such as `1E400`, is stored as the string `"Infinity"` or `"-Infinity"` as on AWS. Contributed by @iot-rocket.
-- **AppSync — GraphQL requests under `AUTH=true` follow the API's authentication type** — a GraphQL call to `/v1/apis/{apiId}/graphql` signed with an IAM key was authorized as `appsync:UpdateGraphqlApi` whatever the API's authentication type, and the API's own host served an `AWS_IAM` API to any signed call; an API key request now ignores its signature, and a SigV4 request to an `AWS_IAM` API is authorized on both endpoints as `appsync:GraphQL` on each top-level field, answering 401 `Permission denied` when no field is allowed, a field error for each denied one, and 400 `BadRequestException` for a wrong signature. Contributed by @iot-rocket.
-- **Auth — a signed call to a REST API method without authorization is anonymous to the API policy** — under `AUTH=true` a SigV4-signed call to a method whose `authorizationType` is `NONE` was judged as its signer, so a user the API policy names, or one whose identity policy allows the invoke, got through; API Gateway evaluates every call to such a method as anonymous, signed or not, and now so does MiniStack, answering `ACCESS_DENIED` unless the policy allows everyone. Contributed by @iot-rocket.
-- **API Gateway — methods without `AWS_IAM` authorization read no credentials under `AUTH=true`** — a REST method with `NONE` or `COGNITO_USER_POOLS` authorization, or an HTTP API route without authorization, refused a SigV4-signed caller whose policies did not allow `execute-api:Invoke` or whose signature failed; such a call now reaches the method, and its own authorizer if it has one, whatever it is signed with. Contributed by @iot-rocket.
-- **AppSync — data-plane error responses** — Event API `POST /event` refusals answered `{"__type", "message"}` with MiniStack's own messages, and the GraphQL endpoint answered 500 for a body that is not a JSON object, a message-only 400 for a missing query and 200 for an unparseable one; both now answer AWS's `{"errors": [{"errorType", "message"}]}` envelope with AWS's error types, messages and `x-amzn-ErrorType` header (`SerializationException`, `MalformedHttpRequestException`, `ResourceNotFoundException` for an unknown API, `UnknownOperationException` for another path on an Event API host), and the publish endpoint answers `application/json`. Contributed by @iot-rocket.
-### Added
-- **Auth — bucket policies see S3's request condition keys under `AUTH=true`** — `s3:x-amz-server-side-encryption`, `s3:x-amz-acl` and `s3:ExistingObjectTag/<key>` were absent from every request but a signed browser POST, so the common "require encryption" Deny refused even an `AES256` upload; a write now carries its encryption and canned ACL headers (an upload part and the completion the encryption header of their `CreateMultipartUpload`), and `GetObject` / `HeadObject` the object's tags, for bucket and identity policies alike. Contributed by @iot-rocket.
-### Fixed
-- **API Gateway — presigned calls to `AWS_IAM` REST methods under `AUTH=true`** — a request signed in its query string (`X-Amz-Signature`) with an IAM user or STS session key answered 403 `MissingAuthenticationTokenException` on an `AWS_IAM` method even when correctly signed; under `AUTH=true`, which verifies that signature, it now reaches the method as on AWS. Contributed by @iot-rocket.
-### Added
-- **IoT — MQTT over WebSocket evaluates the signer's IAM policies under `AUTH=true`** — a session signed with an IAM user or STS session key could connect under any client id and publish, subscribe and receive on any topic; with `AUTH=true` its CONNECT, will, PUBLISH, SUBSCRIBE and deliveries now need the key's IAM policies to allow `iot:Connect`, `iot:Publish` (and `iot:RetainPublish`), `iot:Subscribe` and `iot:Receive` on the client, topic and topic filter ARNs, with the same refusals as a certificate session. Contributed by @iot-rocket.
-- **Auth — WebSocket handshakes are verified for IAM user and STS session keys** — under `AUTH=true` an MQTT-over-WebSocket upgrade or an `AWS_IAM` WebSocket `$connect` signed with such a key was accepted with a wrong secret, a date more than 5 minutes off or a wrong session token; the signature in the query string or `Authorization` header is now checked like that of other requests, IoT answers 403 `Forbidden` and expects the session token after the signed part of the URL, and API Gateway names the canonical string it expected. Contributed by @iot-rocket.
-- **Auth — WebSocket handshakes are verified for IAM user and STS session keys** — under `AUTH=true` an MQTT-over-WebSocket upgrade or an `AWS_IAM` WebSocket `$connect` signed with such a key was accepted with a wrong secret, a date more than 5 minutes off or a wrong session token; the signature in the query string or `Authorization` header is now checked like that of other requests, IoT answers 403 `Forbidden` and expects the session token after the signed part of the URL, and API Gateway names the canonical string it expected. Contributed by @iot-rocket.
-- **RDS Data, S3 Control — calls are authorized under `AUTH=true`** — RDS Data calls and S3 Control tagging calls were served whatever the caller's policies allowed; each RDS Data call is now authorized as `rds-data:<operation>` on the cluster its `resourceArn` names, and `ListTagsForResource`, `TagResource` and `UntagResource` as `s3:<operation>` on the bucket, with a 403 denial (`AccessDeniedException` from RDS Data, `AccessDenied` from S3 Control) naming the action and resource, as on AWS. Contributed by @iot-rocket.
-- **SES v2 — calls are authorized under `AUTH=true`** — SES v2 calls were served whatever the caller's policies allowed; each is now authorized as `ses:<operation>` on the configuration set, contact list, custom verification email template, dedicated IP pool, identity or template its path or create body names (`*` otherwise), and a denial answers 403 `AccessDeniedException` naming the action and resource, as on AWS. Contributed by @iot-rocket.
-
### Fixed
-- **Auth — requests that map to no IAM action are authenticated** — under `AUTH=true` a request MiniStack maps to no IAM action (SES v2, RDS Data, S3 Control, or a service MiniStack does not implement such as X-Ray) was served with a wrong secret, an unknown key, a session key without its token or a stale signature; it now answers the credential error AWS sends for the service, for example `InvalidSignatureException` 403 from SES v2 and RDS Data and `SignatureDoesNotMatch` 403 from S3 Control. Contributed by @iot-rocket.
-### Fixed
-- **Cognito — `AdminDisableUser` revokes the user's tokens under `AUTH=true`** — a disabled user's access and refresh tokens kept working, also after `AdminEnableUser`; with `AUTH=true` they are now refused with `User is disabled.` while the user is disabled, and the sessions from before stay revoked once the user is enabled again (`Access Token has been revoked`, `Refresh Token has been revoked`, `invalid_grant` at `/oauth2/token`), as AWS does, and the access token of a deleted user gets `UserNotFoundException: User does not exist.` Contributed by @iot-rocket.
-- **Cognito — `/oauth2/userInfo` requires the `openid` scope under `AUTH=true`** — an access token without the `openid` scope, such as the token of a user pool API sign-in or of a Hosted UI grant of `email` alone, returned the user's attributes; with `AUTH=true` it now answers 401 `invalid_token` `Access token does not contain the 'openid' scope` once the token, its `username` and the user have passed the other checks. Contributed by @iot-rocket.
-- **Cognito — `/oauth2/userInfo` verifies the access token under `AUTH=true`** — the endpoint returned the user's attributes for any JWT carrying a user's `sub`, including an ID token, a token with an altered payload, a revoked or expired token and the token of a disabled or deleted user; with `AUTH=true` it now answers 401 `invalid_token` with AWS's `error_description` and `WWW-Authenticate` for each case. Contributed by @iot-rocket.
-- **Cognito — `/oauth2/userInfo` verifies the access token under `AUTH=true`** — the endpoint returned the user's attributes for any JWT carrying a user's `sub`, including an ID token, a token with an altered payload, a revoked or expired token and the token of a disabled or deleted user; with `AUTH=true` it now answers 401 `invalid_token` with AWS's `error_description` and `WWW-Authenticate` for each case. Contributed by @iot-rocket.
+- **Cognito Identity — identities merge on a login another identity holds under `AUTH=true`** — `GetCredentialsForIdentity` and `GetOpenIdToken` answered for the calling identity when its `Logins` belonged to another identity, `GetId` returned only one of two identities holding its logins, and an identity with a login took a call that carried none of its own; with `AUTH=true` an identity without a login now gives way to the login's identity, an identity with a login takes the other identity's logins, the merged-away identity is disabled (`DescribeIdentity` and `ListIdentities` list `DISABLED`, `HideDisabled` leaves it out, calls with its old login answer for the identity it merged into) and a call with none of the identity's own logins answers `NotAuthorizedException`. Contributed by @iot-rocket.
- **Cognito Identity — `GetId` and `GetCredentialsForIdentity` check `Logins` under `AUTH=true`** — both calls took any token in `Logins`, `GetCredentialsForIdentity` vended authenticated credentials from the stored login when the request carried none, `GetId` created a new identity for a login that already had one, and a login given to an identity without one was not kept; with `AUTH=true` both calls refuse the tokens `GetOpenIdToken` refuses with the same `NotAuthorizedException` messages (and a Google login that is no JWT), `GetCredentialsForIdentity` refuses a request without `Logins` for an identity with a login, `GetId` returns the identity that holds the login, and `GetCredentialsForIdentity` and `GetOpenIdToken` link the login to an identity that had none, as AWS does. Contributed by @iot-rocket.
- **Cognito Identity — `GetOpenIdToken` checks `Logins` under `AUTH=true`** — the call issued a token for an identity with a login when the request carried no `Logins`, and for any token in `Logins`; with `AUTH=true` it now answers `NotAuthorizedException` as AWS does, with `Access to Identity '<identity id>' is forbidden.` without `Logins` and, for a user pool login, when the token is no ID token of a trusted app client, has a bad signature, expired more than five minutes ago or belongs to another user than the identity's login. Contributed by @iot-rocket.
-- **Cognito Identity — `GetOpenIdToken` checks `Logins` under `AUTH=true`** — the call issued a token for an identity with a login when the request carried no `Logins`, and for any token in `Logins`; with `AUTH=true` it now answers `NotAuthorizedException` as AWS does, with `Access to Identity '<identity id>' is forbidden.` without `Logins` and, for a user pool login, when the token is no ID token of a trusted app client, has a bad signature, expired more than five minutes ago or belongs to another user than the identity's login. Contributed by @iot-rocket.
-- **IoT Data — denials answer `ForbiddenException` under `AUTH=true`** — the data plane (Publish, retained messages, shadows) answered an IAM denial or a failed authentication with `AccessDeniedException`, `InvalidSignatureException` or `UnrecognizedClientException` and the principal and action in the message; it now answers 403 `ForbiddenException` as AWS does, with no message for a policy denial and `Forbidden` for a failed authentication. Contributed by @iot-rocket.
-- **IoT — `aws:ResourceTag` conditions and the denied resource under `AUTH=true`** — a policy condition on `aws:ResourceTag/<key>` never matched for IoT, so a tag-scoped Allow denied every call and a tag-scoped Deny never applied; it now reads the tags of the thing group, policy, job or other IoT resource the call names, and an IoT denial names that resource (`on resource: <arn>`, `*` for a call that names none) as AWS does. Contributed by @iot-rocket.
-- **IoT — tagging calls are authorized on the tagged resource under `AUTH=true`** — `TagResource`, `UntagResource` and `ListTagsForResource` were checked against resource `*`, so a policy scoped to a thing group, job or other IoT ARN denied them even on that resource, and only `Resource: "*"` let them through; they are now checked against the `resourceArn` the request names. Contributed by @iot-rocket.
-- **IoT — tagging calls are authorized on the tagged resource under `AUTH=true`** — `TagResource`, `UntagResource` and `ListTagsForResource` were checked against resource `*`, so a policy scoped to a thing group, job or other IoT ARN denied them even on that resource, and only `Resource: "*"` let them through; they are now checked against the `resourceArn` the request names. Contributed by @iot-rocket.
-- **AppSync — data-plane error responses** — Event API `POST /event` refusals answered `{"__type", "message"}` with MiniStack's own messages, and the GraphQL endpoint answered 500 for a body that is not a JSON object, a message-only 400 for a missing query and 200 for an unparseable one; both now answer AWS's `{"errors": [{"errorType", "message"}]}` envelope with AWS's error types, messages and `x-amzn-ErrorType` header (`SerializationException`, `MalformedHttpRequestException`, `ResourceNotFoundException` for an unknown API, `UnknownOperationException` for another path on an Event API host), and the publish endpoint answers `application/json`. Contributed by @iot-rocket.
-- **Cognito — OAuth scope checks for federation and `client_credentials`** — `/oauth2/authorize` with an `identity_provider` went on to the identity provider whatever the `scope`; it now redirects to the callback with `error_description=invalid_scope` (and the `state`) when a requested scope is not in the client's `AllowedOAuthScopes`, as the managed login does. The `client_credentials` grant answered `invalid_scope` to any request naming an undefined resource server scope; it now ignores those once a defined scope is requested, so `api/read bogus/x` is granted `api/read` and `api/admin bogus/x` answers `invalid_grant`, as AWS does. Contributed by @iot-rocket.
-- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.
-- **CloudTrail — `RecursiveLogging` on trails** — `CreateTrail` and `UpdateTrail` ignored `RecursiveLogging` and no trail response carried it; trails now store it (default `true`, kept by an `UpdateTrail` that leaves it out) and return it from `CreateTrail`, `UpdateTrail`, `GetTrail` and `DescribeTrails`. Contributed by @iot-rocket.
-- **CloudWatch — composite alarms follow their rule** — a composite alarm stayed in `INSUFFICIENT_DATA` whatever its children did and `DeleteAlarms` removed alarms that composite alarms depend on; a composite alarm now evaluates its `AlarmRule` (`ALARM`, `OK`, `INSUFFICIENT_DATA`, `TRUE`, `FALSE`, `AND`, `OR`, `NOT`, `AT_LEAST`) when it is created or updated and whenever a child changes state, with the `StateReason`, `StateReasonData` and history items AWS writes, `PutCompositeAlarm` refuses an unknown child or a malformed rule with `ValidationError`, `DeleteAlarms` refuses an alarm a composite alarm depends on and more than one composite alarm per call, and `DescribeAlarmHistory` returns composite alarm items only for `AlarmTypes=["CompositeAlarm"]`, as AWS does. Contributed by @iot-rocket.
-- **IoT — unacknowledged QoS 1 messages survive a persistent session reconnect** — a QoS 1 message the subscriber had not acknowledged was dropped when its persistent session disconnected; the session now keeps it with its packet identifier, and the resumed connection sends it again once its retransmit interval has passed (at once when it passed while the client was offline, ahead of the messages queued meanwhile), continuing the session's packet identifiers. Contributed by @iot-rocket.
-- **IoT — job documents nested too deep** — `CreateJob` and `CreateJobTemplate` accepted an inline document that is not JSON, and a document nested deeper than Python's JSON parser goes answered 500 (from `documentSource`, or inline once it headed a thing's queue, after which every later `CreateJob` for that thing answered 500 too); they now refuse a document that is not JSON or nests more than 1000 levels deep with AWS's `InvalidRequestException`, and a device gets a 1000-level document compact. Contributed by @iot-rocket.
-- **IoT — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.
-- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
-- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
-- **IoT — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.
-- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
-- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
-- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
-- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
-- **IoT Jobs — a status a device may not set is refused first** — `UpdateJobExecution` (HTTP and the MQTT `update` topic) to QUEUED, CANCELED or TIMED_OUT answered `ResourceNotFoundException` for an unknown job or thing and the version error for a stale `expectedVersion`; it now refuses the status first with `InvalidStateTransitionException` (over MQTT `InvalidStateTransition` without `executionState`), as AWS does. Contributed by @iot-rocket.
-- **IoT — unknown topic rules answer 401** — `GetTopicRule`, `ReplaceTopicRule`, `EnableTopicRule` and `DisableTopicRule` on a rule that does not exist answered 404 `ResourceNotFoundException` and `DeleteTopicRule` answered 200; they now answer 401 `UnauthorizedException` (`Access to topic rule '<name>' was denied`) as AWS does, and `GetTopicRule`, `ReplaceTopicRule` and `DeleteTopicRule` refuse a name outside the rule name pattern with the 400 `InvalidRequestException` that `EnableTopicRule` gives. Contributed by @iot-rocket.
-- **S3 — bucket configuration validation** — `PutBucketVersioning` accepted any `Status` or `MfaDelete` and stored it, `PutBucketLifecycleConfiguration` accepted any rule `Status` or transition `StorageClass` and non-positive days, and `PutBucketEncryption` accepted any `SSEAlgorithm`. Out-of-enum values now return 400 `MalformedXML` (`The XML you provided was not well-formed or did not validate against our published schema`, now the message for every `MalformedXML`). A zero or negative `Expiration` `Days` or `NoncurrentVersionExpiration` `NoncurrentDays` returns 400 `InvalidArgument` (`'Days' for Expiration action must be a positive integer`).
## [1.5.29] — 2026-10-17
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index f89d1799..c2c1c467 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -7596,7 +7596,7 @@ def _get_id(data):
error = _identity_logins_error(pool, None, logins)
if error:
return error
- owner = _login_owner(pool, logins)
+ owner = _link_logins(pool, None, logins)
if owner:
return json_response({"IdentityId": owner})
identity_id = _identity_id(iid)
@@ -7657,7 +7657,7 @@ def _get_credentials_for_identity(data):
error = _identity_logins_error(candidate, identity_id, logins)
if error:
return error
- _link_logins(candidate, identity_id, logins)
+ identity_id = _link_logins(candidate, identity_id, logins)
if not logins:
logins = candidate["_identities"][identity_id].get("Logins") or {}
break
@@ -7711,13 +7711,15 @@ _LOGIN_TOKEN_CLOCK_SKEW = 300
def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):
"""The NotAuthorizedException for Logins AWS would not accept for an identity (None: a new one), or None."""
- stored = (pool["_identities"][identity_id].get("Logins") or {}) if identity_id else {}
+ identity = pool["_identities"][identity_id] if identity_id else {}
+ stored = identity.get("Logins") or {}
if not logins:
- if not stored:
+ if not stored and not identity.get("_merged_into"):
return None
return error_response_json("NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.", 400)
unsupported = "Token is not from a supported provider of this identity pool."
not_oidc = "Invalid login token. Not a valid OpenId Connect identity token."
+ mismatch = "Logins don't match. Please include at least one valid login for this identity or identity pool."
skewed_now = int(time.time()) - _LOGIN_TOKEN_CLOCK_SKEW
for provider, token in logins.items():
clients = [p.get("ClientId") for p in pool.get("CognitoIdentityProviders") or []
@@ -7744,11 +7746,14 @@ def _identity_logins_error(pool: dict, identity_id: str | None, logins: dict):
elif not isinstance(claims.get("exp"), (int, float)) or skewed_now >= claims["exp"]:
message = f"Invalid login token. Token expired: {skewed_now} >= {claims.get('exp')}"
elif provider in stored and _token_claims(stored[provider]).get("sub") != claims.get("sub"):
- message = ("Logins don't match. Please include at least one valid login "
- "for this identity or identity pool.")
+ message = mismatch
else:
continue
return error_response_json("NotAuthorizedException", message, 400)
+ # An identity with a login needs one of its own; a disabled one, a login another identity holds.
+ none_of_its_own = stored and not stored.keys() & logins.keys()
+ if none_of_its_own or identity.get("_merged_into") and not _login_owner(pool, logins):
+ return error_response_json("NotAuthorizedException", mismatch, 400)
return None
@@ -7763,12 +7768,38 @@ def _login_owner(pool: dict, logins: dict):
return None
-def _link_logins(pool: dict, identity_id: str, logins: dict) -> None:
- """Give an identity without a login the call's Logins unless another identity holds them."""
- identity = pool["_identities"][identity_id]
- if logins and not identity.get("Logins") and not _login_owner(pool, logins):
- identity["Logins"] = dict(logins)
- identity["LastModifiedDate"] = _now_epoch()
+def _link_logins(pool: dict, identity_id: str | None, logins: dict):
+ """Link Logins to the identity the call answers for, merge the identities holding them into it, return its id."""
+ identities = pool["_identities"]
+ caller = identities[identity_id] if identity_id else None
+ # An identity with a login answers for itself; one without (or disabled) gives way to the login's identity.
+ target = identity_id if caller and caller.get("Logins") else _login_owner(pool, logins) or identity_id
+ if target is None:
+ return None
+ identity = identities[target]
+ merged = dict.fromkeys(_login_owner(pool, {provider: token}) for provider, token in logins.items())
+ if target != identity_id and caller and not caller.get("_merged_into"):
+ merged[identity_id] = None
+ merged.pop(None, None)
+ merged.pop(target, None)
+ now = _now_epoch()
+ linked = dict(logins)
+ for other_id in merged:
+ other = identities[other_id]
+ linked = {**(other.get("Logins") or {}), **linked}
+ other.update(Logins={}, _merged_into=target, LastModifiedDate=now)
+ added = {provider: token for provider, token in linked.items() if provider not in (identity.get("Logins") or {})}
+ if added:
+ identity["Logins"] = {**(identity.get("Logins") or {}), **added}
+ identity["LastModifiedDate"] = now
+ return target
+
+
+def _identity_login_names(identity: dict) -> list:
+ """An identity's Logins as DescribeIdentity lists them; DISABLED and the region once merged into another."""
+ if identity.get("_merged_into"):
+ return ["DISABLED", identity["IdentityId"].partition(":")[0]]
+ return list((identity.get("Logins") or {}).keys())
def _get_open_id_token(data):
@@ -7784,7 +7815,7 @@ def _get_open_id_token(data):
error = _identity_logins_error(pool, identity_id, logins)
if error:
return error
- _link_logins(pool, identity_id, logins)
+ identity_id = _link_logins(pool, identity_id, logins)
logins = logins or pool["_identities"][identity_id].get("Logins") or {}
break
if not pool_id:
@@ -7894,11 +7925,12 @@ def _list_identities(data):
if not pool:
return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)
max_results = min(data.get("MaxResults", 60), 60)
- identities = list(pool["_identities"].values())[:max_results]
+ identities = [i for i in pool["_identities"].values()
+ if not (data.get("HideDisabled") and i.get("_merged_into"))][:max_results]
return json_response({
"IdentityPoolId": iid,
"Identities": [
- {"IdentityId": i["IdentityId"], "Logins": list(i.get("Logins", {}).keys()),
+ {"IdentityId": i["IdentityId"], "Logins": _identity_login_names(i),
"CreationDate": i["CreationDate"], "LastModifiedDate": i["LastModifiedDate"]}
for i in identities
],
@@ -7912,7 +7944,7 @@ def _describe_identity(data):
if identity:
return json_response({
"IdentityId": identity_id,
- "Logins": list(identity.get("Logins", {}).keys()),
+ "Logins": _identity_login_names(identity),
"CreationDate": identity["CreationDate"],
"LastModifiedDate": identity["LastModifiedDate"],
})
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 439ea0cb..66127aab 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -1412,12 +1412,13 @@ def _identity_logins(cognito_idp, cognito_identity):
pid, cid = pool_with_users("u1", "u2", "u3", "u4", "u5")
other_cid = cognito_idp.create_user_pool_client(UserPoolId=pid, ClientName="other", ExplicitAuthFlows=[
"ALLOW_USER_PASSWORD_AUTH"])["UserPoolClient"]["ClientId"]
- pid_b, cid_b = pool_with_users("u4")
+ pid_b, cid_b = pool_with_users("u4", "u5", "u6")
u1 = sign_in(cid, "u1")
tokens = {
"u1": u1["IdToken"], "u1 access": u1["AccessToken"], "u2": sign_in(cid, "u2")["IdToken"],
"u3": sign_in(cid, "u3")["IdToken"], "u4": sign_in(cid, "u4")["IdToken"], "u5": sign_in(cid, "u5")["IdToken"],
- "b": sign_in(cid_b, "u4")["IdToken"],
+ "b": sign_in(cid_b, "u4")["IdToken"], "b5": sign_in(cid_b, "u5")["IdToken"],
+ "b6": sign_in(cid_b, "u6")["IdToken"],
"u1 other client": sign_in(other_cid, "u1")["IdToken"],
}
provider = f"cognito-idp.us-east-1.amazonaws.com/{pid}"
@@ -1435,7 +1436,7 @@ def _identity_logins(cognito_idp, cognito_identity):
return SimpleNamespace(
call=call, tokens=tokens, provider=provider, provider_b=f"cognito-idp.us-east-1.amazonaws.com/{pid_b}",
- pool=iid,
+ client=cid, client_b=cid_b, pool=iid,
unauth=cognito_identity.get_id(IdentityPoolId=iid)["IdentityId"],
u1=cognito_identity.get_id(IdentityPoolId=iid, Logins={provider: tokens["u1"]})["IdentityId"],
)
@@ -1541,6 +1542,80 @@ def test_cognito_identity_without_login_takes_one(auth_enabled, cognito_idp, cog
assert found != identity_id
+def test_cognito_identity_without_login_merges_into_the_logins_identity(auth_enabled, cognito_idp, cognito_identity):
+ ctx = _identity_logins(cognito_idp, cognito_identity)
+ provider, tokens = ctx.provider, ctx.tokens
+ mismatch = "Logins don't match. Please include at least one valid login for this identity or identity pool."
+ for action, user in (("get_credentials_for_identity", "u3"), ("get_open_id_token", "u4")):
+ holder = ctx.call("get_id", IdentityPoolId=ctx.pool, Logins={provider: tokens[user]})["IdentityId"]
+ identity_id = ctx.call("get_id", IdentityPoolId=ctx.pool)["IdentityId"]
+ result = ctx.call(action, IdentityId=identity_id, Logins={provider: tokens[user]})
+ logins = ctx.call("describe_identity", IdentityId=identity_id)["Logins"]
+ if not auth_enabled:
+ assert (result["IdentityId"], logins) == (identity_id, [])
+ continue
+ # The call answers for the identity that holds the login and disables the caller's.
+ assert (result["IdentityId"], logins) == (holder, ["DISABLED", "us-east-1"])
+ if action == "get_open_id_token":
+ assert _decode_jwt_claims(result["Token"])["sub"] == holder
+ assert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens[user]})["IdentityId"] == holder
+ assert ctx.call(action, IdentityId=identity_id) == (
+ "NotAuthorizedException", f"Access to Identity '{identity_id}' is forbidden.")
+ assert ctx.call(action, IdentityId=identity_id, Logins={provider: tokens["u2"]}) == (
+ "NotAuthorizedException", mismatch)
+ listed = {hide: [i["IdentityId"] for i in ctx.call(
+ "list_identities", IdentityPoolId=ctx.pool, MaxResults=60, HideDisabled=hide)["Identities"]]
+ for hide in (False, True)}
+ assert (identity_id in listed[False], identity_id in listed[True]) == (True, False)
+
+
+def test_cognito_identity_merges_the_identities_holding_its_logins(auth_enabled, cognito_idp, cognito_identity):
+ ctx = _identity_logins(cognito_idp, cognito_identity)
+ provider, provider_b, tokens = ctx.provider, ctx.provider_b, ctx.tokens
+ cognito_identity.update_identity_pool(
+ IdentityPoolId=ctx.pool, IdentityPoolName="IdentityLogins", AllowUnauthenticatedIdentities=True,
+ CognitoIdentityProviders=[{"ProviderName": provider, "ClientId": ctx.client},
+ {"ProviderName": provider_b, "ClientId": ctx.client_b}])
+
+ def get_id(logins):
+ return ctx.call("get_id", IdentityPoolId=ctx.pool, Logins=logins)["IdentityId"]
+
+ def logins_of(identity_id):
+ return sorted(ctx.call("describe_identity", IdentityId=identity_id)["Logins"])
+
+ held_b = get_id({provider_b: tokens["b"]})
+ result = ctx.call("get_credentials_for_identity", IdentityId=ctx.u1,
+ Logins={provider: tokens["u1"], provider_b: tokens["b"]})
+ assert result["IdentityId"] == ctx.u1
+ u3 = get_id({provider: tokens["u3"]})
+ only_new_login = ctx.call("get_credentials_for_identity", IdentityId=u3, Logins={provider_b: tokens["b5"]})
+ u5, b6 = get_id({provider: tokens["u5"]}), get_id({provider_b: tokens["b6"]})
+ both_held = get_id({provider: tokens["u5"], provider_b: tokens["b6"]})
+ if not auth_enabled:
+ assert (logins_of(ctx.u1), logins_of(held_b)) == ([provider], [provider_b])
+ assert only_new_login["IdentityId"] == u3
+ assert both_held not in (u5, b6)
+ return
+ # The caller keeps its identity, takes the other identity's logins and disables it.
+ assert (logins_of(ctx.u1), logins_of(held_b)) == (sorted([provider, provider_b]), ["DISABLED", "us-east-1"])
+ assert get_id({provider_b: tokens["b"]}) == ctx.u1
+ assert ctx.call("get_credentials_for_identity", IdentityId=held_b,
+ Logins={provider_b: tokens["b"]})["IdentityId"] == ctx.u1
+ # An identity with a login needs one of its own; a new login next to it is linked.
+ assert only_new_login == (
+ "NotAuthorizedException",
+ "Logins don't match. Please include at least one valid login for this identity or identity pool.")
+ result = ctx.call("get_credentials_for_identity", IdentityId=u3,
+ Logins={provider: tokens["u3"], provider_b: tokens["b5"]})
+ assert (result["IdentityId"], logins_of(u3)) == (u3, sorted([provider, provider_b]))
+ # GetId keeps one of two identities holding its logins and disables the other.
+ assert both_held in (u5, b6)
+ other = b6 if both_held == u5 else u5
+ assert (logins_of(both_held), logins_of(other)) == (sorted([provider, provider_b]), ["DISABLED", "us-east-1"])
+
+
def test_cognito_get_open_id_token_expired_login_under_auth(monkeypatch):
from ministack.core.responses import AccountRegionScopedDict