Skip to content

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

fix(iam): resolve caller, transport, tag and principal-tag condition keys, and trust-policy principal tags under AUTH=true (#2154)

iot-rocket1127d93f3808
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adf4cffd..f6ba7569 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,47 +7,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-## [1.5.27] — 2026-10-13
-
-### Added
-- **API Gateway — failed SigV4 authentication answers through the gateway responses** — under `AUTH=true` a REST API invoke that failed authentication got the generic JSON error and ignored the API's gateway responses; a wrong secret, a skewed clock or a credential date other than the request date now answers `INVALID_SIGNATURE` (`InvalidSignatureException`), an expired session `EXPIRED_TOKEN` (`ExpiredTokenException`), and an unknown key or a malformed `Authorization` header `DEFAULT_4XX` with the matching `x-amzn-ErrorType`, 403 with `{"message": ...}`. Contributed by @iot-rocket.
-- **Auth — the request time of a header-signed request is checked** — under `AUTH=true` a request signed with an IAM user or STS session key was served whatever its time; one signed more than 15 minutes (STS, IAM, SNS, SQS, DynamoDB, S3, ECR, RDS, ElastiCache) or 5 minutes (the default for other services) from the server clock answers `SignatureDoesNotMatch` / `InvalidSignatureException` with AWS's `Signature expired` or `Signature not yet current` message, `RequestTimeTooSkewed` from S3 and `AuthFailure` from EC2. Contributed by @iot-rocket.
-- **Auth — the session token of a header-signed request is checked** — under `AUTH=true` an STS session key sent without its token was accepted and now answers as an unknown key, and a wrong token, or a token with an IAM user key, answers `InvalidClientTokenId` (`UnrecognizedClientException` from JSON services, `InvalidToken` 400 from S3), as on AWS. Contributed by @iot-rocket.
-- **Auth — header signatures are verified for IAM user and STS session keys** — under `AUTH=true` a request signed with such a key and the wrong secret, or changed after signing, was served; it now answers `SignatureDoesNotMatch` (or the service's `InvalidSignatureException`), an `Authorization` header without its `Signature` or `SignedHeaders` answers `IncompleteSignature` (Lambda `MissingAuthenticationTokenException`, S3 `AuthorizationHeaderMalformed`) and a credential date other than the request date `SignatureDoesNotMatch` (S3 `AuthorizationHeaderMalformed`), S3 unsigned, streaming and signed-chunk payloads are checked the same way, and the root key still accepts any secret. Contributed by @iot-rocket.
-- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.
-- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.
-- **IoT — `TagResource`, `UntagResource` and `ListTagsForResource`** — the three operations answered `Unsupported IoT path`, so the tags the Create calls accept could not be read back. They now work on thing types, thing groups, policies, topic rules, jobs, job templates, CA certificates, provisioning templates and domain configurations with AWS's limits and errors, Create calls and CloudFormation `Tags` write the same tags, and deleting a resource drops them. Contributed by @iot-rocket.
-- **IoT — retained messages** — `GetRetainedMessage` and `ListRetainedMessages` answered 501 `not yet implemented`; they now return the broker's retained messages (newest first, paged by `maxResults` and `nextToken`, with the user properties of an MQTT 5 publish), and a `PERSIST_STATE=1` restart keeps each message's `lastModifiedTime` and user properties. Contributed by @iot-rocket.
-- **IoT — `ListJobExecutionsForJob`** — `GET /jobs/{jobId}/things` answered 400 `Unsupported IoT path`; it now lists every execution of the job, earlier ones of a rejoined thing included, most recently updated first, with the `status` filter and `maxResults` / `nextToken` paging. Contributed by @iot-rocket.
-- **IoT — `DeleteJobExecution`** — `DELETE /things/{thingName}/jobs/{jobId}/executionNumber/{executionNumber}` answered 400 `Unsupported IoT path`; it now deletes the execution (an `IN_PROGRESS` one only with `force`), drops it from the job's lists and counts, completes the job when only finished executions are left, and publishes the `deleted` job execution event and the thing's `jobs/notify` topics; a `CONTINUOUS` job's thing left with no execution gets none back until it leaves the group, which leaves a `REMOVED` execution 1. Contributed by @iot-rocket.
-- **Cognito — `InboundFederation` trigger on SAML and OIDC sign-in** — `LambdaConfig.InboundFederation` was stored but never invoked; SAML and OIDC federated sign-in now call the Lambda with `InboundFederation_ExternalProvider`, the provider-prefixed `userName` and the IdP's `samlResponse` or `idToken`. A non-empty `userAttributesToMap` replaces the IdP attributes before `AttributeMapping`, `{}` keeps them, and a failing or missing function fails the sign-in with `UserLambdaValidationException`. Contributed by @kjdev.
-
-### Fixed
-- **Step Functions — aws-sdk Parameters for JSON-protocol services take the wire names** — `ecs` and `ecr` received an aws-sdk task's PascalCase `Parameters` as sent, so their handlers ignored them (`describeClusters` with `Clusters` described `default`, `describeRepositories` with `RepositoryNames` returned every repository), and `sfn` and `cloudwatchlogs` lowercased every key, map keys included, so `tagResource` stored `Team-Name` as `team-Name`; the parameters are now renamed by the operation's input model, with map keys such as tag keys kept as written. Reported by @lucasmfraser.
-- **Step Functions — aws-sdk results for JSON-protocol services keep the SDK's shape at every depth** — only the result's top-level keys took the SDK's names, so nested members kept their wire casing (`Executions[].executionArn`, `SecretList[].ARN`), timestamps stayed epoch numbers and absent members came back as `null`; the result is now shaped by the service's output model: structure members renamed at every depth (DynamoDB's `BOOL`, `NULL` and `SS` as `Bool`, `Nul` and `Ss`), map keys such as attribute names and tag keys kept as sent, timestamps as ISO 8601 with milliseconds, and absent members left out. A leading acronym is now lowered in every aws-sdk result, including two-letter names and ones with digits (`ID` as `Id`, `EC2InstanceId` as `Ec2InstanceId`, `MD5OfMessageBody` as `Md5OfMessageBody`). Contributed by @lucasmfraser.
-- **S3 — `s3:prefix`, `s3:delimiter` and `s3:max-keys` under `AUTH=true`** — `ListObjects`, `ListObjectsV2` and `ListObjectVersions` set none of the three condition keys, so a `ListBucket` or `ListBucketVersions` grant scoped by them, such as `StringLike` on `s3:prefix` for one user's home folder, never matched and the listing answered `AccessDenied`; they now carry the request's `prefix`, `delimiter` and `max-keys`, path-style and virtual-hosted. Reported by @bettiah.
-- **Idle memory** — the IoT mTLS listener built its TLS context at boot, which imported `cryptography` and minted the broker certificate before any device connected. It now binds port 8883 without TLS and builds the context on the first connection, and `x509_utils` imports `cryptography` on first use: an idle container drops from about 36.7 to 32.8 MiB.
-- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.
-- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.
-- **IAM — user and role tag keys are case-insensitive** — `TagUser` and `TagRole` with `department` added a second tag beside `Department`, and `UntagUser` and `UntagRole` missed a key spelled differently; user and role tag keys now compare without case and keep the spelling last written, and `CreateUser`, `CreateRole`, `TagUser` and `TagRole` refuse keys that repeat without case with `InvalidInput` `Duplicate tag keys found. Please note that Tag keys are case insensitive.`, as does an `AWS::IAM::User` or `AWS::IAM::Role` whose stack tag differs from one of its own tags only in case. Other IAM resources keep case-sensitive keys. Contributed by @gakuto-cw21.
-- **Signer — signing material checks in `PutSigningProfile`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; the Lambda and Notation platforms now refuse any `signingMaterial` (`InvalidProfileParameters`), and with `AUTH=true` the IoT and FreeRTOS platforms refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, with AWS's errors. Contributed by @iot-rocket.
-- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`. Contributed by @lucasmfraser.
-- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.
-- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.
-- **Step Functions — `ListExecutions` order and pagination** — executions came back oldest first, so `maxResults=1` returned the oldest, and `nextToken` was an offset; they now come back most recent first (running executions by `startDate`, the rest by `stopDate`), the token resumes after the last execution returned so one started between pages is not repeated, an unreadable token answers `InvalidToken` and `maxResults=0` uses the default, as on AWS. Contributed by @lucasmfraser.
-- **Cognito — confirmation codes are checked under `AUTH=true`** — `ConfirmSignUp` and `ConfirmForgotPassword` accepted any code, and `ConfirmForgotPassword` changed the password even when no reset was requested; with `AUTH=true` they take only the issued code (`123456` for sign-up and `654321` for a password reset, as before), answer a wrong one with `CodeMismatchException` and a code that was never issued with `ExpiredCodeException`, and `ConfirmSignUp` refuses a user who is not `UNCONFIRMED` with `NotAuthorizedException`, as AWS does. Contributed by @iot-rocket.
-- **Cognito — `ExplicitAuthFlows` is enforced for the password flows under `AUTH=true`** — with `AUTH=true` a client that lists its auth flows now refuses `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` unless the list enables them (the legacy `USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` names included), with the `InvalidParameterException` AWS returns. Contributed by @iot-rocket.
-- **Cognito — `CUSTOM_AUTH` on clients without `ALLOW_` flows** — a client created without `ExplicitAuthFlows`, or with only the legacy names, refused `CUSTOM_AUTH`; it is now enabled, as on AWS, and a client whose `ALLOW_` list leaves it out answers `CUSTOM_AUTH is not enabled for the client.` as AWS does. Contributed by @iot-rocket.
-- **CloudFormation — API Gateway v2 stage `Ref`** — `Ref` returned `<apiId>/<stageName>`, causing an `AWS::ApiGatewayV2::ApiMapping` using the reference as its `Stage` to fail with `Invalid stage identifier specified`; new stages now return the stage name. Stage updates, replacement on `ApiId` or `StageName` changes, and deletion use the resolved resource properties, including for stacks with legacy physical IDs. Contributed by @matuscongrady.
-- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.
-- **IoT — deleting things, certificates, policies and thing types still in use** — `DeleteThing` detached a thing's certificates and deleted it, and `DeleteCertificate` refused only an `ACTIVE` certificate. Now `DeleteThing` refuses a thing with a certificate attached, `DeleteCertificate` refuses a certificate with things attached and, without `forceDelete`, one with policies attached (`forceDelete` detaches them), `DeletePolicy` refuses a policy with non-default versions and `DeleteThingType` one that things still use, all with AWS's messages. Contributed by @iot-rocket.
-- **IoT — `RegisterCertificate` under an inactive CA** — a certificate issued by a CA that is not `ACTIVE` registered anyway; it is now refused with `CertificateStateException`, with or without `caCertificatePem`. An unregistered CA and a CA that did not issue the certificate are refused with AWS's codes and messages. Contributed by @iot-rocket.
-- **IoT — rule SQL `principal()` and `traceid()`** — both resolved to Undefined; `principal()` now returns the client certificate id for mTLS, the caller's `GetCallerIdentity` `UserId` for HTTP Publish and SigV4 WebSocket sessions (also their lifecycle events' `principalIdentifier`) and the rule role's session for a republish, and `traceid()` returns a per-message id that the errorAction document carries as `cloudwatchTraceId`. Contributed by @iot-rocket.
-- **CloudFormation — `AWS::Logs::LogGroup` delete** — a stack delete or a `LogGroupName` replacement removed only the group record, so a metric filter or resource policy added through the Logs API stayed and came back with a new group of the same name; the group is now deleted through `DeleteLogGroup`. Contributed by @iot-rocket.
+### Fixed
+- **STS — trust policies see principal tags, session tags and web identities under `AUTH=true`** — `AssumeRole` trust conditions had no `aws:PrincipalTag/*`, a `Service` principal matched any IAM user whose ARN contained the service name, `Tags` passed without `sts:TagSession` in the trust policy, and `AssumeRoleWithWebIdentity` skipped the trust policy; trust conditions now see the caller's keys and the session tags as `aws:RequestTag/*` and `aws:TagKeys`, a `Service` principal no longer matches an IAM user, session tags need `sts:TagSession`, and a web identity needs a `Federated` principal naming its issuer, with `<issuer>:aud`, `:sub` and `:amr` evaluated. Under `AUTH=true` session tag keys that differ only in case answer `InvalidParameterValue`. Contributed by @iot-rocket.
+- **IAM — `aws:ResourceTag/*` under `AUTH=true`** — the key was always absent outside CloudWatch Logs, so a tag-scoped grant denied every request; a request on an existing SQS queue, SNS topic, DynamoDB table, Lambda function, IAM user or role, SSM parameter, Secrets Manager secret or KMS key now sees that resource's tags. Contributed by @iot-rocket.
+- **IAM — `aws:RequestTag/*` and `aws:TagKeys` under `AUTH=true`** — only CloudWatch Logs filled them; a call whose API takes `Tags` or `TagKeys` (create, tag and untag calls such as `CreateQueue`, `CreateTable`, `CreateUser`, `PutParameter`, `CreateSecret`, `CreateKey`) now carries the tags it sets and the keys it names, `aws:TagKeys` is absent on a call that names none, and Lambda `TagResource`, `UntagResource` and `ListTags` are authorized against the ARN in the path instead of skipped. Contributed by @iot-rocket.
+- **IAM — caller and transport condition keys under `AUTH=true`** — identity policies saw none of the caller's keys and a fixed `127.0.0.1` over plain HTTP; they now see `aws:username`, `aws:userid`, `aws:PrincipalTag/*` (the user's or role's tags, `AssumeRole` session tags taking precedence; in `rds-db:connect` too), for temporary credentials `aws:MultiFactorAuthPresent` and `aws:TokenIssueTime`, the client's address as `aws:SourceIp` and `aws:SecureTransport` as `true` over HTTPS or behind a proxy that sends `X-Forwarded-Proto: https`, and `AssumedRoleId` starts with the role's `RoleId` with or without `AUTH`. Contributed by @iot-rocket.
- **Cognito Identity — `GetOpenIdToken` claims** — the token was a user-pool ID token with an empty audience; it is now issued by `https://cognito-identity.amazonaws.com` with the identity pool id as `aud`, the identity id as `sub`, an `amr` list naming the login providers and the user-pool sign-in, the pool ARN in `https://cognito-identity.amazonaws.com/identity-pool-arn` and a 10-minute lifetime. An identity id that no pool knows gets `ResourceNotFoundException` instead of a token. Contributed by @iot-rocket.
-- **CloudTrail — new trails start with logging off** — `CreateTrail` left a new trail logging, and `GetTrailStatus` reported a `StartLoggingTime` an hour back and a `LatestDeliveryTime` of now. A new trail now reports `IsLogging` false until `StartLogging`, and `GetTrailStatus` returns only the `StartLoggingTime` and `StopLoggingTime` of calls made (a restart keeps the last stop time), without `LatestDeliveryTime` or empty error strings. Contributed by @iot-rocket.
-- **CloudFormation — EventBridge rules accept a bus ARN** — `AWS::Events::Rule` stored an ARN-valued `EventBusName` as the bus name, so `PutEvents` succeeded without delivering to its targets. Create, update, delete and drift detection now resolve the ARN through the existing EventBridge parser and use the bus name internally. Contributed by @matuscongrady.
-- **Cognito — SAML `/oauth2/authorize` with `MetadataFile`** — a SAML provider created with only `MetadataFile` was refused with `InvalidParameterException`; the IdP sign-in URL now comes from `IDPSSOEndpoint`, then the metadata's HTTP-Redirect `SingleSignOnService`, then `MetadataURL`. Contributed by @kjdev.
## [1.5.26] — 2026-10-11
diff --git a/ministack/app.py b/ministack/app.py
index 1b536122..0d838520 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -218,6 +218,7 @@ from ministack.core.hypercorn_compat import install as _install_hypercorn_compat
from ministack.core.iam_evaluator import (
AmbiguousAccessKeyError,
find_iam_access_key_account,
+ pin_request_origin,
pin_signed_body,
pin_signed_request,
)
@@ -2606,6 +2607,7 @@ async def _dispatch_service_request(
extract_iam_action,
extract_resource_arn,
logs_service_context,
+ request_tag_context,
s3_service_context,
)
from ministack.core.iam_evaluator import AuthError, enforce, pin_request_caller
@@ -2639,6 +2641,8 @@ async def _dispatch_service_request(
service_context = logs_service_context(
iam_action.split(":", 1)[1], body, resource_arn, region, get_account_id()
)
+ service_context = {**request_tag_context(service, iam_action, body, routing_params),
+ **(service_context or {})}
# A DynamoDB transaction is not itself an IAM action: each item is
# authorized as the single-item action it performs, on its table.
transaction_checks = (
@@ -2865,6 +2869,9 @@ async def app(scope, receive, send):
# USE_SSL terminates TLS here, so no proxy sets the header; fill it in.
if scope.get("scheme") == "https":
headers.setdefault("x-forwarded-proto", "https")
+ if AUTH:
+ pin_request_origin((scope.get("client") or ("127.0.0.1",))[0],
+ headers.get("x-forwarded-proto", "").split(",")[0].strip().lower() == "https")
request_id = str(uuid.uuid4())
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 377df845..7fc51690 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -396,6 +396,8 @@ def s3_additional_checks(method: str, path: str, headers: dict, body: bytes,
# Lambda REST path → IAM action
def _lambda_action(method: str, path: str) -> str | None:
parts = [p for p in path.split("/") if p]
+ if parts[1:2] == ["tags"]:
+ return {"POST": "TagResource", "DELETE": "UntagResource"}.get(method, "ListTags")
if "functions" not in parts:
if "layers" in parts:
if method == "GET":
@@ -543,8 +545,8 @@ def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:
return compiled, specificity, required_query
-def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern, str, int, dict[str, str]]]:
- """Load a botocore service model and compile its URI routes."""
+def _load_botocore_model(botocore_service: str) -> dict:
+ """Load a botocore service model, or {} when there is none."""
try:
import gzip
@@ -556,30 +558,33 @@ def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern,
svc_dir = os.path.join(data_dir, botocore_service)
if not os.path.isdir(svc_dir):
- return []
+ return {}
versions = sorted(os.listdir(svc_dir))
if not versions:
- return []
+ return {}
model_path = os.path.join(svc_dir, versions[-1], "service-2.json.gz")
if not os.path.exists(model_path):
model_path = os.path.join(svc_dir, versions[-1], "service-2.json")
if not os.path.exists(model_path):
- return []
+ return {}
try:
if model_path.endswith(".gz"):
import gzip
with gzip.open(model_path, "rt") as f:
- model = json.load(f)
- else:
- with open(model_path) as f:
- model = json.load(f)
+ return json.load(f)
+ with open(model_path) as f:
+ return json.load(f)
except Exception:
logger.debug("AUTH: failed to load botocore model for %s", botocore_service)
- return []
+ return {}
+
+def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern, str, int, dict[str, str]]]:
+ """Load a botocore service model and compile its URI routes."""
+ model = _load_botocore_model(botocore_service)
routes = []
for op_name, op_def in model.get("operations", {}).items():
http = op_def.get("http", {})
@@ -897,6 +902,8 @@ def extract_resource_arn(service: str, method: str, path: str,
if service == "lambda":
# Path: /2015-03-31/functions/{name}/...
path_parts = [p for p in path.split("/") if p]
+ if path_parts[1:2] == ["tags"] and len(path_parts) > 2:
+ return unquote("/".join(path_parts[2:]))
if "functions" in path_parts:
fi = path_parts.index("functions")
if fi + 1 < len(path_parts):
@@ -1849,6 +1856,60 @@ def dynamodb_service_context(body: bytes) -> dict:
return context
+_TAG_MEMBERS = frozenset({"Tags", "tags", "TagKeys"})
+_TAG_OPERATIONS: dict[str, frozenset[str]] = {}
+_QUERY_TAG_RE = re.compile(r"^((?:.+\.)?Tags?(?:\.member)?\.\d+)\.Key$")
+_QUERY_TAG_KEY_RE = re.compile(r"^(?:TagKeys?(?:\.member)?\.\d+|tagKeys)$")
+
+
+def _tag_operations(service: str) -> frozenset[str]:
+ """The operations of *service* whose input carries tags or tag keys."""
+ if service not in _TAG_OPERATIONS:
+ ops = set()
+ for name in _BOTOCORE_SERVICE_MAP.get(service) or [service]:
+ model = _load_botocore_model(name)
+ shapes = model.get("shapes", {})
+ for op_name, op in model.get("operations", {}).items():
+ members = shapes.get(op.get("input", {}).get("shape"), {}).get("members", {})
+ if _TAG_MEMBERS & members.keys():
+ ops.add(op_name)
+ _TAG_OPERATIONS[service] = frozenset(ops)
+ return _TAG_OPERATIONS[service]
+
+
+def request_tag_context(service: str, iam_action: str, body: bytes, params: dict) -> dict:
+ """aws:RequestTag/<key> for every tag a request sets and aws:TagKeys for every key it sets or removes."""
+ if iam_action.split(":", 1)[-1] not in _tag_operations(service):
+ return {}
+ tags: list[tuple[str, str]] = []
+ keys: list[str] = []
+ try:
+ data = json.loads(body) if body[:1] == b"{" else {}
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ data = {}
+ if isinstance(data, dict):
+ raw = data.get("Tags", data.get("tags"))
+ if isinstance(raw, dict):
+ tags += [(str(k), str(v)) for k, v in raw.items()]
+ for tag in raw if isinstance(raw, list) else []:
+ if isinstance(tag, dict):
+ key = tag.get("Key", tag.get("TagKey", tag.get("key")))
+ tags.append((str(key), str(tag.get("Value", tag.get("TagValue", tag.get("value", ""))))))
+ if isinstance(data.get("TagKeys"), list):
+ keys += [str(k) for k in data["TagKeys"]]
+ for name, value in params.items():
+ match = _QUERY_TAG_RE.match(name)
+ if match:
+ tags.append((_query_param(params, name), _query_param(params, f"{match.group(1)}.Value")))
+ elif _QUERY_TAG_KEY_RE.match(name):
+ keys += value if isinstance(value, list) else [value]
+ values: dict[str, list[str]] = {}
+ for name, value in tags:
+ values.setdefault(f"aws:RequestTag/{name}".lower(), []).append(value)
+ context: dict = {key: found[0] if len(found) == 1 else found for key, found in values.items()}
+ if tags or keys:
+ context["aws:TagKeys"] = [name for name, _ in tags] + keys
+ return context
# Authentication failures by the evaluator's code: the Query API code and
# status (also REST-XML and the query-compatible JSON services), the JSON code,
# and S3's code, status and message.
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 86efac4e..cd69fee4 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -25,6 +25,9 @@ from typing import Any
logger = logging.getLogger("ministack")
+_request_origin: contextvars.ContextVar[tuple[str, bool]] = contextvars.ContextVar(
+ "ministack_request_origin", default=("127.0.0.1", False))
+
# ---------------------------------------------------------------------------
# Data structures
@@ -49,11 +52,12 @@ class EvalContext:
action: str # "s3:PutObject"
resource_arn: str # "*" until per-service resource ARN construction
region: str
- source_ip: str = "127.0.0.1"
- secure_transport: bool = False
+ source_ip: str = field(default_factory=lambda: _request_origin.get()[0])
+ secure_transport: bool = field(default_factory=lambda: _request_origin.get()[1])
request_tags: dict[str, str] = field(default_factory=dict)
tag_keys: list[str] = field(default_factory=list)
service_context: dict[str, Any] = field(default_factory=dict)
+ principal_keys: dict[str, Any] = field(default_factory=dict)
@dataclass
@@ -70,6 +74,7 @@ class PrincipalInfo:
type: str # "User", "AssumedRole", "Root"
account: str
policies: list[list[ParsedStatement]] | None # None = root (allow-all)
+ keys: dict[str, Any] = field(default_factory=dict)
@dataclass
@@ -223,6 +228,8 @@ def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
# role conditions its S3 grant on this key, so leaving it unresolved
# denied every `cdk deploy` under AUTH=true.
return _account_from_arn(ctx.resource_arn) or ctx.principal_account
+ if k in ctx.principal_keys:
+ return ctx.principal_keys[k]
if k in ctx.service_context:
return ctx.service_context[k]
if k == "aws:principalorgid":
@@ -636,6 +643,11 @@ def pin_request_caller(headers: dict, query_params: dict | None = None) -> None:
_request_caller_arn.set(request_caller_arn(headers, query_params))
+def pin_request_origin(source_ip: str, secure_transport: bool) -> None:
+ """Remember the caller's address and transport for this request's policy checks."""
+ _request_origin.set((source_ip, secure_transport))
+
+
def caller_arn() -> str:
"""The pinned caller ARN, or the caller account's root ARN."""
from ministack.core.responses import get_account_id
@@ -1042,6 +1054,31 @@ def _is_root_key(access_key_id: str) -> bool:
return is_root_access_key(access_key_id)
+def _principal_keys(credential: ResolvedCredential) -> dict[str, Any]:
+ """The condition keys that describe the caller, keyed in lower case."""
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_svc
+
+ keys: dict[str, Any] = {"aws:userid": credential.principal_id}
+ entity = {}
+ if credential.principal_type == "User":
+ keys["aws:username"] = credential.principal_name
+ entity = iam_svc._users.get_scoped(credential.account_id, None, credential.principal_name)
+ elif credential.principal_type == "AssumedRole":
+ entity = iam_svc._roles.get_scoped(
+ credential.account_id, None, _role_name_from_assumed_arn(credential.principal_arn))
+ tags = list((entity or {}).get("Tags") or [])
+ session = sts_svc._sessions.get(credential.access_key_id)
+ if session is not None:
+ tags += session.get("SessionTags") or []
+ keys["aws:multifactorauthpresent"] = "false"
+ if isinstance(session.get("IssuedAt"), (int, float)):
+ keys["aws:tokenissuetime"] = _dt.datetime.fromtimestamp(
+ session["IssuedAt"], _dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ keys.update({f"aws:principaltag/{t['Key'].lower()}": t["Value"] for t in tags})
+ return keys
+
+
def resolve_principal(access_key_id: str,
account_id: str, credential: ResolvedCredential | None = None) -> PrincipalInfo | AuthError:
"""Resolve an access key to a principal and their policies.
@@ -1074,6 +1111,7 @@ def resolve_principal(access_key_id: str,
type=credential.principal_type,
account=credential.account_id,
policies=policies,
+ keys=_principal_keys(credential),
)
@@ -1213,6 +1251,12 @@ def resolve_caller_identity(access_key_id: str) -> dict | None:
return None
+def _names_condition_key(policies: list[list[ParsedStatement]], prefix: str) -> bool:
+ """Whether a condition in *policies* uses a key starting with *prefix* (lower case)."""
+ return any(key.lower().startswith(prefix) for stmts in policies for stmt in stmts
+ for block in stmt.conditions.values() if isinstance(block, dict) for key in block)
+
+
def enforce(access_key_id: str, iam_action: str, service: str,
region: str, resource_arn: str = "*",
service_context: dict[str, Any] | None = None) -> EvalResult | AuthError | None:
@@ -1242,6 +1286,13 @@ def enforce(access_key_id: str, iam_action: str, service: str,
if principal.policies is None:
return None
+ context = {key.lower(): value for key, value in (service_context or {}).items()}
+ # A request that names no tags has no aws:TagKeys.
+ context.setdefault("aws:tagkeys", None)
+ if _names_condition_key(principal.policies, "aws:resourcetag/"):
+ from ministack.services.tagging import resource_tags
+ for name, value in (resource_tags(resource_arn) or {}).items():
+ context.setdefault(f"aws:resourcetag/{name}".lower(), value)
ctx = EvalContext(
principal_arn=principal.arn,
principal_type=principal.type,
@@ -1249,9 +1300,8 @@ def enforce(access_key_id: str, iam_action: str, service: str,
action=iam_action,
resource_arn=resource_arn,
region=region,
- service_context={
- key.lower(): value for key, value in (service_context or {}).items()
- },
+ service_context=context,
+ principal_keys=principal.keys,
)
result = evaluate(ctx, principal.policies)
@@ -1319,6 +1369,8 @@ def evaluate_trust_policy(trust_doc: str | dict,
- ``{"AWS": "ACCT"}`` — account ID shorthand
- ``{"Service": "lambda.amazonaws.com"}`` — service principal
- ``{"AWS": ["arn1", "arn2"]}`` — list of principals
+ - ``{"Federated": "PROVIDER"}`` — web identity provider, for
+ ``sts:AssumeRoleWithWebIdentity`` only
"""
if isinstance(trust_doc, str):
try:
@@ -1340,6 +1392,7 @@ def evaluate_trust_policy(trust_doc: str | dict,
principal_account=_account_from_arn(caller_arn) or "",
action="sts:AssumeRole", resource_arn="*", region="",
)
+ federated = ctx.action == "sts:AssumeRoleWithWebIdentity"
allowed = False
for stmt in statements:
if not isinstance(stmt, dict):
@@ -1353,11 +1406,11 @@ def evaluate_trust_policy(trust_doc: str | dict,
actions = [actions]
if isinstance(not_actions, str):
not_actions = [not_actions]
- if not (actions or not_actions) or not _action_matches("sts:AssumeRole", actions, not_actions):
+ if not (actions or not_actions) or not _action_matches(ctx.action, actions, not_actions):
continue
# Check Principal
principal = stmt.get("Principal", {})
- if not _principal_matches(principal, caller_arn):
+ if not _trust_principal_matches(principal, caller_arn, federated):
continue
if not _conditions_met(stmt.get("Condition", {}), ctx):
continue
@@ -1368,6 +1421,16 @@ def evaluate_trust_policy(trust_doc: str | dict,
return allowed
+def _trust_principal_matches(principal: Any, caller_arn: str, federated: bool) -> bool:
+ """Whether a trust-policy Principal names the caller or, if *federated*, the provider."""
+ if not federated:
+ return _principal_matches(principal, caller_arn)
+ if principal == "*":
+ return True
+ providers = principal.get("Federated", []) if isinstance(principal, dict) else []
+ return caller_arn in ([providers] if isinstance(providers, str) else providers)
+
+
def _principal_matches(principal: Any, caller_arn: str) -> bool:
"""Check if a trust policy Principal matches the caller."""
if principal == "*":
@@ -1402,20 +1465,8 @@ def _principal_matches(principal: Any, caller_arn: str) -> bool:
# Also match account root against any principal in that account
if p.endswith(":root") and f":{p.split(':')[4]}:" in caller_arn:
return True
- # Service principals — match if the caller ARN looks like it came from
- # that service (e.g., lambda.amazonaws.com allows Lambda-invoked assumes).
- # In local dev, service principals are typically used by MiniStack's own
- # service dispatch (Lambda, ECS, etc.), so we also allow if the caller
- # is root (service-to-service calls use root credentials internally).
- svc_principals = principal.get("Service", [])
- if isinstance(svc_principals, str):
- svc_principals = [svc_principals]
- if svc_principals:
- if ":root" in caller_arn:
- return True
- for svc in svc_principals:
- # Extract service prefix: "lambda.amazonaws.com" → "lambda"
- svc_prefix = svc.split(".")[0] if "." in svc else svc
- if svc_prefix in caller_arn:
- return True
+ # No IAM principal is a service, but MiniStack's own service calls
+ # use root credentials, so a Service principal lets root through.
+ if principal.get("Service") and caller_arn.endswith(":root"):
+ return True
return False
diff --git a/ministack/core/rds_iam.py b/ministack/core/rds_iam.py
index e552f5c1..a6035f37 100644
--- a/ministack/core/rds_iam.py
+++ b/ministack/core/rds_iam.py
@@ -295,7 +295,7 @@ def authorize_rds_iam_token(
result = evaluate(EvalContext(
principal_arn=principal.arn, principal_type=principal.type,
principal_account=account_id, action="rds-db:connect",
- resource_arn=resource_arn, region=region,
+ resource_arn=resource_arn, region=region, principal_keys=principal.keys,
), principal.policies)
if result.decision != "Allow":
return RdsIamAuthorizationError(result.decision)
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 81629070..d0e6ddb6 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -1626,6 +1626,8 @@ def _build_simulate_results_real(actions, resource_arn, principal_arn,
action=action,
resource_arn=resource_arn,
region=get_region(),
+ source_ip="127.0.0.1",
+ secure_transport=False,
)
result = evaluate(ctx, policies)
raw = result.decision
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index 8abe59b4..3d840f32 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -9,6 +9,7 @@ Actions:
"""
import base64
+import dataclasses
import hashlib
import hmac
import json
@@ -22,6 +23,7 @@ from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.iam_evaluator import (
AmbiguousAccessKeyError,
CredentialResolutionError,
+ _principal_keys,
find_iam_access_key_account,
is_root_access_key,
resolve_credential,
@@ -38,7 +40,16 @@ from ministack.core.router import extract_access_key_id
# Shared helpers — IAM and STS are a natural pair; STS is stateless
# and reuses IAM's XML builders and credential generators.
-from ministack.services.iam import _error, _future, _gen_secret, _gen_session_access_key, _gen_session_token, _p, _xml
+from ministack.services.iam import (
+ _error,
+ _extract_tags,
+ _future,
+ _gen_secret,
+ _gen_session_access_key,
+ _gen_session_token,
+ _p,
+ _xml,
+)
_sessions: dict[str, dict] = {}
@@ -62,6 +73,7 @@ def _session_expired(session) -> bool:
def register_session(access_key: str, session: dict) -> None:
"""Register a temporary-credential session (AssumeRole, identity pools)."""
_evict_expired_sessions()
+ session.setdefault("IssuedAt", time.time())
_sessions[access_key] = session
@@ -104,6 +116,7 @@ def _caller_identity(
"principalType": credential.principal_type,
"principalName": credential.principal_name,
"isTemporary": credential.session_token is not None,
+ "principalKeys": _principal_keys(credential),
}
@@ -171,10 +184,81 @@ def _assumed_role_arn(role_arn: str, session_name: str):
return f"arn:{spec.partition}:sts::{spec.account_id}:assumed-role/{role_name}/{session_name}", None
+def _role_id(role_arn: str) -> str:
+ """The RoleId of the role *role_arn* names, or a new one for a role that is not stored."""
+ from ministack.services import iam as iam_svc
+
+ try:
+ spec = parse_arn(role_arn)
+ role = iam_svc._roles.get_scoped(spec.account_id, None, spec.resource.rsplit("/", 1)[-1])
+ except ArnParseError:
+ role = None
+ return (role or {}).get("RoleId") or "AROA" + new_uuid().replace("-", "")[:17].upper()
+
+
+def _session_tags(params: dict, check=True):
+ """The session tags of a request, from the query or the JSON form, or, if *check*, their validation error."""
+ tags = params.get("Tags")
+ if isinstance(tags, list) and tags and isinstance(tags[0], dict):
+ tags = [{"Key": str(t.get("Key")), "Value": str(t.get("Value", ""))} for t in tags]
+ else:
+ tags = _extract_tags(params)
+ if check and len({t["Key"].lower() for t in tags}) < len(tags):
+ return None, _error(400, "InvalidParameterValue",
+ "Duplicate tag keys found. Please note that Tag keys are case insensitive.", ns="sts")
+ return tags, None
+
+
def _invalid_role_arn(role_arn: str):
return _error(400, "ValidationError", f"Invalid RoleArn: {role_arn}", ns="sts")
+_WELL_KNOWN_WEB_IDENTITY_PROVIDERS = {
+ "accounts.google.com", "cognito-identity.amazonaws.com", "graph.facebook.com", "www.amazon.com",
+}
+
+
+def _web_identity_principal(token: str, provider_id: str, role_arn: str):
+ """The Federated principal a web identity token names, with its condition keys."""
+ from ministack.services.cognito import _decode_id_token_unverified
+
+ try:
+ claims = _decode_id_token_unverified(token)
+ except (ValueError, TypeError):
+ claims = {}
+ if not isinstance(claims, dict):
+ claims = {}
+ host = str(claims.get("iss") or provider_id or "").split("://", 1)[-1].rstrip("/")
+ principal = host
+ if host and host not in _WELL_KNOWN_WEB_IDENTITY_PROVIDERS:
+ parts = role_arn.split(":")
+ principal = f"arn:{parts[1]}:iam::{parts[4]}:oidc-provider/{host}"
+ return principal, {f"{host}:{k}".lower(): claims[k] for k in ("aud", "sub", "amr") if k in claims}
+
+
+def _web_identity_trust_denied(role_arn: str, params: dict, use_json: bool):
+ """AccessDenied unless the role's trust policy lets the token's provider assume it."""
+ from ministack.core.iam_evaluator import EvalContext, evaluate_trust_policy
+ from ministack.services import iam as iam_svc
+
+ account = role_arn.split(":")[4]
+ role = iam_svc._roles.get_scoped(account, None, role_arn.rsplit("/", 1)[-1])
+ provider, keys = _web_identity_principal(
+ _p(params, "WebIdentityToken"), _p(params, "ProviderId"), role_arn)
+ trust_context = EvalContext(
+ principal_arn=provider, principal_type="WebIdentityUser", principal_account=account,
+ action="sts:AssumeRoleWithWebIdentity", resource_arn=role_arn, region=get_region(),
+ service_context=keys,
+ )
+ if role is not None and evaluate_trust_policy(
+ role.get("AssumeRolePolicyDocument", "{}"), provider, trust_context):
+ return None
+ message = "Not authorized to perform sts:AssumeRoleWithWebIdentity"
+ if use_json:
+ return error_response_json("AccessDenied", message, 403)
+ return _error(403, "AccessDenied", message, ns="sts")
+
+
async def handle_request(method, path, headers, body, query_params):
params = dict(query_params)
content_type = headers.get("content-type", "")
@@ -224,6 +308,10 @@ async def handle_request(method, path, headers, body, query_params):
role_arn = _p(params, "RoleArn")
session_name = _p(params, "RoleSessionName")
assumed_arn, validation_error = _assumed_role_arn(role_arn, session_name)
+ if validation_error:
+ return validation_error
+ from ministack.app import AUTH
+ session_tags, validation_error = _session_tags(params, check=AUTH)
if validation_error:
return validation_error
caller = _caller_identity(headers, query_params)
@@ -231,7 +319,6 @@ async def handle_request(method, path, headers, body, query_params):
return _credential_error_response(caller)
# When AUTH=true, validate role exists and trust policy permits the caller
- from ministack.app import AUTH
if AUTH:
from ministack.core.iam_evaluator import EvalContext, evaluate_trust_policy
from ministack.services import iam as iam_svc
@@ -272,10 +359,19 @@ async def handle_request(method, path, headers, body, query_params):
"sts:externalid": _p(params, "ExternalId", None),
"sts:rolesessionname": _p(params, "RoleSessionName", None),
},
+ principal_keys=caller["principalKeys"],
+ request_tags={t["Key"]: t["Value"] for t in session_tags},
+ tag_keys=[t["Key"] for t in session_tags],
)
+ denied_action = None
if not evaluate_trust_policy(trust_doc, caller_arn, trust_context):
+ denied_action = "sts:AssumeRole"
+ elif session_tags and not evaluate_trust_policy(
+ trust_doc, caller_arn, dataclasses.replace(trust_context, action="sts:TagSession")):
+ denied_action = "sts:TagSession"
+ if denied_action:
message = (f"User: {caller_arn} is not authorized to perform: "
- f"sts:AssumeRole on resource: {role_arn}")
+ f"{denied_action} on resource: {role_arn}")
if use_json:
return error_response_json("AccessDenied", message, 403)
return _error(403, "AccessDenied", message, ns="sts")
@@ -285,7 +381,7 @@ async def handle_request(method, path, headers, body, query_params):
access_key = _gen_session_access_key()
secret_key = _gen_secret()
session_token = _gen_session_token()
- role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ role_id = _role_id(role_arn)
register_session(access_key, {
"Arn": assumed_arn,
"UserId": f"{role_id}:{session_name}",
@@ -296,6 +392,7 @@ async def handle_request(method, path, headers, body, query_params):
"PrincipalType": "AssumedRole",
"SourceAccessKeyId": caller["accessKey"],
"SourcePrincipalArn": caller["userArn"],
+ "SessionTags": session_tags,
})
if use_json:
return json_response({
@@ -325,11 +422,16 @@ async def handle_request(method, path, headers, body, query_params):
assumed_arn, validation_error = _assumed_role_arn(role_arn, session)
if validation_error:
return validation_error
+ from ministack.app import AUTH
+ if AUTH:
+ denied = _web_identity_trust_denied(role_arn, params, use_json)
+ if denied:
+ return denied
duration = int(_p(params, "DurationSeconds") or 3600)
access_key = _gen_session_access_key()
secret_key = _gen_secret()
session_token = _gen_session_token()
- role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
+ role_id = _role_id(role_arn)
register_session(access_key, {
"Arn": assumed_arn,
"UserId": f"{role_id}:{session}",
diff --git a/ministack/services/tagging.py b/ministack/services/tagging.py
index 690858c3..09dceb89 100644
--- a/ministack/services/tagging.py
+++ b/ministack/services/tagging.py
@@ -246,6 +246,48 @@ _COLLECTORS = {
}
+def _collect_iam():
+ import ministack.services.iam as svc
+ for store in (svc._users, svc._roles):
+ for entity in store.values():
+ yield entity.get("Arn", ""), _normalise_list(entity.get("Tags"))
+
+
+def _collect_ssm():
+ import ministack.services.ssm as svc
+ for arn, tags in svc._tags.items():
+ yield arn, _normalise_flat(tags)
+
+
+def _collect_secretsmanager():
+ import ministack.services.secretsmanager as svc
+ for secret in svc._secrets.values():
+ yield secret.get("ARN", ""), _normalise_list(secret.get("Tags"))
+
+
+# ARN service -> collector, for resolving aws:ResourceTag
+_RESOURCE_TAG_COLLECTORS = {
+ "dynamodb": _collect_dynamodb,
+ "iam": _collect_iam,
+ "kms": _collect_kms,
+ "lambda": _collect_lambda,
+ "secretsmanager": _collect_secretsmanager,
+ "sns": _collect_sns,
+ "sqs": _collect_sqs,
+ "ssm": _collect_ssm,
+}
+
+
+def resource_tags(arn: str) -> dict[str, str] | None:
+ """The tags of the resource *arn* names, or None when it is not a known resource."""
+ parts = arn.split(":", 5)
+ collect = _RESOURCE_TAG_COLLECTORS.get(parts[2]) if len(parts) == 6 else None
+ for candidate, tags in collect() if collect else ():
+ if candidate == arn:
+ return {t["Key"]: t["Value"] for t in tags}
+ return None
+
+
# ── Helpers ───────────────────────────────────────────────────────────────────
def _account():
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 00a7b7a0..14315849 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -12,6 +12,7 @@ the MiniStack server and work with AUTH=false.
import asyncio
import contextlib
+import contextvars
import io
import json
import re
@@ -748,12 +749,11 @@ class TestTrustPolicy:
"Action": "sts:AssumeRole"}]}
assert evaluate_trust_policy(trust, "arn:aws:iam::123456789012:root")
- def test_service_principal_allows_matching_service(self):
- """Service principal matches callers containing the service name."""
+ def test_service_principal_denies_user_named_after_service(self):
trust = {"Statement": [{"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"}]}
- assert evaluate_trust_policy(trust, "arn:aws:lambda:us-east-1:123:function:test")
+ assert not evaluate_trust_policy(trust, "arn:aws:iam::123456789012:user/lambda-ops")
def test_service_principal_denies_unrelated_user(self):
"""A service principal does NOT allow arbitrary IAM users."""
@@ -790,6 +790,20 @@ class TestTrustPolicy:
"Action": "sts:AssumeRole"}]}
assert not evaluate_trust_policy(trust, "arn:aws:iam::123:user/a")
+ def test_federated_principal_matches_only_web_identity(self):
+ provider = "arn:aws:iam::123456789012:oidc-provider/issuer.example.com"
+ trust = {"Statement": [
+ {"Effect": "Allow", "Principal": {"Federated": provider},
+ "Action": "sts:AssumeRoleWithWebIdentity"},
+ {"Effect": "Allow", "Principal": {"AWS": "123456789012"},
+ "Action": "sts:AssumeRoleWithWebIdentity"}]}
+ other = "arn:aws:iam::123456789012:oidc-provider/other.example.com"
+ for arn, allowed in ((provider, True), (other, False)):
+ ctx = EvalContext(principal_arn=arn, principal_type="WebIdentityUser",
+ principal_account="123456789012", action="sts:AssumeRoleWithWebIdentity",
+ resource_arn="*", region="")
+ assert evaluate_trust_policy(trust, arn, ctx) is allowed
+
def test_string_json_input(self):
trust_str = json.dumps({"Statement": [{"Effect": "Allow", "Principal": "*",
"Action": "sts:AssumeRole"}]})
@@ -1154,6 +1168,287 @@ class TestCustomerManagedPolicyResolution:
assert (get_account_id(), get_region()) == (self.OTHER, "eu-west-1")
+def _iam_user(name, tags=()):
+ """A stored IAM user with one access key; yields the key and a setter for its inline policy."""
+ from ministack.core.responses import get_account_id
+ from ministack.services import iam as iam_svc
+ key = "AKIATEST" + name.upper().replace("-", "")
+ iam_svc._access_keys[key] = {"UserName": name, "AccessKeyId": key, "SecretAccessKey": "s",
+ "Status": "Active", "CreateDate": "2024-01-01"}
+ iam_svc._users[name] = {"UserName": name, "Arn": f"arn:aws:iam::{get_account_id()}:user/{name}",
+ "UserId": "AIDA" + name.upper().replace("-", ""), "Path": "/",
+ "AttachedPolicies": [], "Tags": list(tags)}
+ try:
+ yield key, lambda doc: iam_svc._user_inline_policies.__setitem__(name, {"p": doc})
+ finally:
+ iam_svc._access_keys.pop(key, None)
+ iam_svc._users.pop(name, None)
+ iam_svc._user_inline_policies.pop(name, None)
+
+
+def _allows(access_key, put_policy, condition):
+ """Whether *access_key* may call sqs:ListQueues under a policy gated on *condition*."""
+ put_policy(json.dumps({"Statement": [{
+ "Effect": "Allow", "Action": "sqs:ListQueues", "Resource": "*", "Condition": condition}]}))
+ return enforce(access_key, "sqs:ListQueues", "sqs", "us-east-1") is None
+
+
+class TestGlobalConditionKeys:
+ """The caller and transport condition keys."""
+
+ @pytest.fixture
+ def user(self):
+ with _iam_user("ck-user", [{"Key": "Team", "Value": "blue"}]) as user:
+ yield user
+
+ @pytest.fixture
+ def role_session(self):
+ from ministack.core.responses import get_account_id
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_svc
+ trust = {"Statement": [{"Effect": "Allow", "Principal": {"AWS": get_account_id()},
+ "Action": ["sts:AssumeRole", "sts:TagSession"]}]}
+ iam_svc._roles["ck-role"] = {"RoleName": "ck-role", "RoleId": "AROACKROLE", "AttachedPolicies": [],
+ "Arn": f"arn:aws:iam::{get_account_id()}:role/ck-role", "InlinePolicies": {},
+ "AssumeRolePolicyDocument": json.dumps(trust),
+ "Tags": [{"Key": "team", "Value": "red"}, {"Key": "dept", "Value": "ops"}]}
+ body = (f"Action=AssumeRole&RoleArn=arn:aws:iam::{get_account_id()}:role/ck-role&RoleSessionName=s1"
+ "&Tags.member.1.Key=team&Tags.member.1.Value=green").encode()
+ status, _, out = asyncio.run(sts_svc.handle_request("POST", "/", {}, body, {}))
+ assert status == 200
+ key = re.search(r"<AccessKeyId>([^<]+)", out.decode()).group(1)
+ yield key, lambda doc: iam_svc._roles["ck-role"]["InlinePolicies"].__setitem__("p", doc)
+ sts_svc._sessions.pop(key, None)
+ iam_svc._roles.pop("ck-role", None)
+
+ @pytest.mark.parametrize("condition,allowed", [
+ ({"StringEquals": {"aws:username": "ck-user"}}, True),
+ ({"StringEquals": {"aws:userid": "AIDACKUSER"}}, True),
+ ({"StringEquals": {"aws:PrincipalTag/team": "blue"}}, True),
+ ({"StringEquals": {"aws:PrincipalTag/Team": "red"}}, False),
+ ({"Null": {"aws:MultiFactorAuthPresent": "false"}}, False),
+ ({"Null": {"aws:TokenIssueTime": "false"}}, False),
+ ])
+ def test_iam_user_keys(self, user, condition, allowed):
+ assert _allows(*user, condition) is allowed
+
+ def test_assumed_role_id_starts_with_the_role_id(self, role_session):
+ from ministack.services import sts as sts_svc
+ assert sts_svc._sessions[role_session[0]]["UserId"] == "AROACKROLE:s1"
+
+ @pytest.mark.parametrize("condition,allowed", [
+ ({"Null": {"aws:username": "true"}}, True),
+ ({"StringEquals": {"aws:userid": "AROACKROLE:s1"}}, True),
+ ({"StringEquals": {"aws:PrincipalTag/team": "green"}}, True),
+ ({"StringEquals": {"aws:PrincipalTag/dept": "ops"}}, True),
+ ({"Bool": {"aws:MultiFactorAuthPresent": "false"}}, True),
+ ({"DateGreaterThan": {"aws:TokenIssueTime": "2020-01-01T00:00:00Z"}}, True),
+ ])
+ def test_assumed_role_session_keys(self, role_session, condition, allowed):
+ assert _allows(*role_session, condition) is allowed
+
+ def test_assume_role_json_protocol_keeps_session_tags(self, role_session):
+ from ministack.core.responses import get_account_id
+ from ministack.services import sts as sts_svc
+ body = json.dumps({"RoleArn": f"arn:aws:iam::{get_account_id()}:role/ck-role", "RoleSessionName": "s2",
+ "Tags": [{"Key": "team", "Value": "white"}]}).encode()
+ headers = {"content-type": "application/x-amz-json-1.1",
+ "x-amz-target": "AWSSecurityTokenServiceV20110615.AssumeRole"}
+ status, _, out = asyncio.run(sts_svc.handle_request("POST", "/", headers, body, {}))
+ key = json.loads(out)["Credentials"]["AccessKeyId"]
+ try:
+ assert _allows(key, role_session[1], {"StringEquals": {"aws:PrincipalTag/team": "white"}})
+ finally:
+ sts_svc._sessions.pop(key, None)
+
+ @pytest.mark.parametrize("condition,allowed", [
+ ({"IpAddress": {"aws:SourceIp": "10.1.2.0/24"}}, True),
+ ({"IpAddress": {"aws:SourceIp": "127.0.0.1/32"}}, False),
+ ({"Bool": {"aws:SecureTransport": "true"}}, True),
+ ])
+ def test_request_origin_keys(self, user, condition, allowed):
+ from ministack.core.iam_evaluator import pin_request_origin
+
+ def decide():
+ pin_request_origin("10.1.2.3", True)
+ return _allows(*user, condition)
+ assert contextvars.copy_context().run(decide) is allowed
+
+ def test_policy_simulation_ignores_the_request_origin(self):
+ from ministack.core.iam_evaluator import pin_request_origin
+ from ministack.services import iam as iam_svc
+ doc = json.dumps({"Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"},
+ {"Effect": "Deny", "Action": "s3:GetObject", "Resource": "*",
+ "Condition": {"Bool": {"aws:SecureTransport": "false"}}}]})
+ body = urlencode({"Action": "SimulateCustomPolicy", "PolicyInputList.member.1": doc,
+ "ActionNames.member.1": "s3:GetObject"}).encode()
+
+ def simulate():
+ pin_request_origin("10.1.2.3", True)
+ return asyncio.run(iam_svc.handle_request("POST", "/", {}, body, {}))[2]
+ assert b"<EvalDecision>explicitDeny</EvalDecision>" in contextvars.copy_context().run(simulate)
+
+ @pytest.mark.parametrize("auth,scheme,headers,origin", [
+ (True, "https", [], ("10.9.8.7", True)),
+ (True, "http", [], ("10.9.8.7", False)),
+ (True, "http", [(b"x-forwarded-proto", b"https")], ("10.9.8.7", True)),
+ (False, "https", [], ("127.0.0.1", False)),
+ ])
+ def test_http_request_pins_the_client_address_and_scheme(self, monkeypatch, auth, scheme, headers, origin):
+ from ministack import app as app_mod
+ seen = []
+
+ async def capture(*args):
+ ctx = EvalContext("", "", "", "", "*", "us-east-1")
+ seen.append((ctx.source_ip, ctx.secure_transport))
+ return 200, {}, b"ok"
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ async def send(message):
+ pass
+
+ monkeypatch.setattr(app_mod, "_handle_pre_body_request", capture)
+ monkeypatch.setattr(app_mod, "AUTH", auth)
+ asyncio.run(app_mod.app({"type": "http", "method": "GET", "path": "/", "scheme": scheme,
+ "client": ("10.9.8.7", 50000), "headers": [(b"host", b"sts.localhost"), *headers],
+ "query_string": b""}, receive, send))
+ assert seen == [origin]
+
+
+class TestRequestTagContext:
+ """aws:RequestTag/* and aws:TagKeys of create, tag and untag calls."""
+
+ @pytest.mark.parametrize("service,action,body,params,context", [
+ ("sqs", "sqs:CreateQueue", b'{"QueueName":"q","tags":{"env":"dev"}}', {},
+ {"aws:requesttag/env": "dev", "aws:TagKeys": ["env"]}),
+ ("sqs", "sqs:CreateQueue", b"", {"Tag.1.Key": ["env"], "Tag.1.Value": ["dev"]},
+ {"aws:requesttag/env": "dev", "aws:TagKeys": ["env"]}),
+ ("dynamodb", "dynamodb:TagResource", b'{"Tags":[{"Key":"env","Value":"dev"},{"Key":"t","Value":"1"}]}', {},
+ {"aws:requesttag/env": "dev", "aws:requesttag/t": "1", "aws:TagKeys": ["env", "t"]}),
+ ("kms", "kms:CreateKey", b'{"Tags":[{"TagKey":"env","TagValue":"dev"}]}', {},
+ {"aws:requesttag/env": "dev", "aws:TagKeys": ["env"]}),
+ ("iam", "iam:CreateUser", b"", {"Tags.member.1.Key": ["env"], "Tags.member.1.Value": ["dev"]},
+ {"aws:requesttag/env": "dev", "aws:TagKeys": ["env"]}),
+ ("sqs", "sqs:CreateQueue", b'{"QueueName":"q","tags":{"Env":"a","env":"b"}}', {},
+ {"aws:requesttag/env": ["a", "b"], "aws:TagKeys": ["Env", "env"]}),
+ ("sns", "sns:UntagResource", b"", {"TagKeys.member.1": ["env"]}, {"aws:TagKeys": ["env"]}),
+ ("ssm", "ssm:RemoveTagsFromResource", b'{"TagKeys":["env"]}', {}, {"aws:TagKeys": ["env"]}),
+ ("lambda", "lambda:UntagResource", b"", {"tagKeys": ["env", "temp"]}, {"aws:TagKeys": ["env", "temp"]}),
+ ("sqs", "sqs:CreateQueue", b'{"QueueName":"q"}', {}, {}),
+ ("lambda", "lambda:InvokeFunction", b'{"Tags":{"env":"dev"}}', {}, {}),
+ ("sqs", "sqs:SendMessage", b'{"MessageBody":"x","tags":{"env":"dev"}}', {}, {}),
+ ])
+ def test_wire_shapes(self, service, action, body, params, context):
+ from ministack.core.iam_actions import request_tag_context
+ assert request_tag_context(service, action, body, params) == context
+
+ @pytest.mark.parametrize("tags,allowed", [
+ ({"env": "dev"}, True),
+ ({"env": "prod"}, False),
+ ({"env": "dev", "blocked": "1"}, False),
+ ({}, False),
+ ])
+ def test_create_is_decided_by_the_request_tags(self, tags, allowed):
+ from ministack.core.iam_actions import request_tag_context
+ body = json.dumps({"QueueName": "q", "tags": tags}).encode()
+ context = request_tag_context("sqs", "sqs:CreateQueue", body, {})
+ with _iam_user("rt-user") as (key, put_policy):
+ put_policy(json.dumps({"Statement": [
+ {"Effect": "Allow", "Action": "sqs:CreateQueue", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:RequestTag/env": "dev"}}},
+ {"Effect": "Deny", "Action": "sqs:CreateQueue", "Resource": "*",
+ "Condition": {"ForAnyValue:StringEquals": {"aws:TagKeys": "blocked"}}},
+ ]}))
+ denied = enforce(key, "sqs:CreateQueue", "sqs", "us-east-1", service_context=context)
+ assert (denied is None) is allowed
+
+ @pytest.mark.parametrize("tags,allowed", [({}, True), ({"env": "dev"}, False)])
+ def test_tag_keys_is_absent_without_tags(self, tags, allowed):
+ from ministack.core.iam_actions import request_tag_context
+ body = json.dumps({"QueueName": "q", "tags": tags}).encode()
+ context = request_tag_context("sqs", "sqs:CreateQueue", body, {})
+ with _iam_user("rt-null") as (key, put_policy):
+ put_policy(json.dumps({"Statement": [{"Effect": "Allow", "Action": "sqs:CreateQueue", "Resource": "*",
+ "Condition": {"Null": {"aws:TagKeys": "true"}}}]}))
+ assert (enforce(key, "sqs:CreateQueue", "sqs", "us-east-1", service_context=context) is None) is allowed
+
+ @pytest.mark.parametrize("method,grant,allowed", [
+ ("POST", "function:f", True), ("GET", "function:f*", True), ("DELETE", "function:g", False)])
+ def test_lambda_tag_calls_match_a_function_scoped_grant(self, method, grant, allowed):
+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn
+ path = "/2017-03-31/tags/arn:aws:lambda:us-east-1:000000000000:function:f"
+ action = extract_iam_action("lambda", method, path, {}, b"", {})
+ arn = extract_resource_arn("lambda", method, path, {}, b"", {}, "us-east-1", "000000000000")
+ with _iam_user("rt-fn") as (key, put_policy):
+ put_policy(json.dumps({"Statement": [{
+ "Effect": "Allow", "Action": ["lambda:TagResource", "lambda:UntagResource", "lambda:ListTags"],
+ "Resource": f"arn:aws:lambda:us-east-1:000000000000:{grant}"}]}))
+ denied = enforce(key, action, "lambda", "us-east-1", resource_arn=arn)
+ assert (denied is None) is allowed
+
+
+class TestResourceTagCondition:
+ """aws:ResourceTag/* from the tags of the resource a request names."""
+
+ def test_resource_tags_come_from_each_store(self):
+ from ministack.core.responses import get_account_id, get_region
+ from ministack.services import iam as iam_svc
+ from ministack.services import secretsmanager as sm
+ from ministack.services import sns, ssm
+ from ministack.services.tagging import resource_tags
+
+ acct, region = get_account_id(), get_region()
+ topic = f"arn:aws:sns:{region}:{acct}:rt-topic"
+ param = f"arn:aws:ssm:{region}:{acct}:parameter/rt-param"
+ sns._topics[topic] = {"tags": {"env": "dev"}}
+ ssm._tags[param] = {"env": "dev"}
+ secret = sm.create_secret_in_process("rt-secret", "v")
+ sm._secrets["rt-secret"]["Tags"] = [{"Key": "env", "Value": "dev"}]
+ iam_svc._roles["rt-role"] = {"RoleName": "rt-role", "Arn": f"arn:aws:iam::{acct}:role/rt-role",
+ "Tags": [{"Key": "env", "Value": "dev"}]}
+ try:
+ for arn in (topic, param, secret, f"arn:aws:iam::{acct}:role/rt-role"):
+ assert resource_tags(arn) == {"env": "dev"}, arn
+ assert resource_tags(f"arn:aws:sns:{region}:{acct}:missing") is None
+ assert resource_tags("arn:aws:s3:::bucket") is None
+ assert resource_tags("*") is None
+ finally:
+ sns._topics.pop(topic, None)
+ ssm._tags.pop(param, None)
+ sm._secrets.pop("rt-secret", None)
+ iam_svc._roles.pop("rt-role", None)
+
+ @pytest.mark.parametrize("condition,resource,allowed", [
+ ({"StringEquals": {"aws:ResourceTag/env": "dev"}}, "rt-dev", True),
+ ({"StringEquals": {"aws:ResourceTag/ENV": "dev"}}, "rt-dev", True),
+ ({"StringEquals": {"aws:ResourceTag/env": "dev"}}, "rt-prod", False),
+ ({"StringEquals": {"aws:ResourceTag/env": "dev"}}, "rt-missing", False),
+ ({"Null": {"aws:ResourceTag/env": "true"}}, "rt-missing", True),
+ ])
+ def test_read_is_decided_by_the_resource_tags(self, condition, resource, allowed):
+ from ministack.core.responses import get_account_id
+ with _iam_user("rt-reader") as (key, put_policy), _iam_user("rt-dev", [{"Key": "env", "Value": "dev"}]), \
+ _iam_user("rt-prod", [{"Key": "env", "Value": "prod"}]):
+ put_policy(json.dumps({"Statement": [
+ {"Effect": "Allow", "Action": "iam:GetUser", "Resource": "*", "Condition": condition}]}))
+ denied = enforce(key, "iam:GetUser", "iam", "us-east-1",
+ resource_arn=f"arn:aws:iam::{get_account_id()}:user/{resource}")
+ assert (denied is None) is allowed
+
+ def test_tags_a_service_supplies_keep_precedence(self):
+ from ministack.core.responses import get_account_id
+ with _iam_user("rt-ctx") as (key, put_policy), _iam_user("rt-prod", [{"Key": "env", "Value": "prod"}]):
+ put_policy(json.dumps({"Statement": [{"Effect": "Allow", "Action": "iam:GetUser", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/env": "dev"}}}]}))
+ denied = enforce(key, "iam:GetUser", "iam", "us-east-1", service_context={"aws:ResourceTag/env": "dev"},
+ resource_arn=f"arn:aws:iam::{get_account_id()}:user/rt-prod")
+ assert denied is None
+
+
class TestSeededAwsManagedPolicies:
"""The AWS-managed policies CDK, SAM and Serverless attach by their real ARNs
resolve to a document: the service-role/* path is the only one AWS has for the
@@ -1473,6 +1768,14 @@ class TestResourceArn:
from ministack.core.iam_actions import extract_resource_arn
assert extract_resource_arn("lambda", "POST", "/2015-03-31/functions/my-func/invocations", {}, b"", {}, "us-east-1", "123") == "arn:aws:lambda:us-east-1:123:function:my-func"
+ @pytest.mark.parametrize("arn", [
+ "arn:aws:lambda:us-east-1:123:function:f", "arn%3Aaws%3Alambda%3Aus-east-1%3A123%3Afunction%3Af"])
+ @pytest.mark.parametrize("method", ["GET", "POST", "DELETE"])
+ def test_lambda_tags(self, method, arn):
+ from ministack.core.iam_actions import extract_resource_arn
+ resolved = extract_resource_arn("lambda", method, f"/2017-03-31/tags/{arn}", {}, b"", {}, "us-east-1", "123")
+ assert resolved == "arn:aws:lambda:us-east-1:123:function:f"
+
def test_sqs_queue_url(self):
from ministack.core.iam_actions import extract_resource_arn
assert extract_resource_arn("sqs", "POST", "/", {}, b"", {"QueueUrl": ["http://localhost:4566/000000000000/my-queue"]}, "us-east-1", "123") == "arn:aws:sqs:us-east-1:123:my-queue"
@@ -2388,6 +2691,13 @@ class TestActionExtraction:
assert extract_iam_action("lambda", "POST", "/2015-03-31/functions", {}, b"", {}) == "lambda:CreateFunction"
assert extract_iam_action("lambda", "POST", "/2015-03-31/functions/f/invocations", {}, b"", {}) == "lambda:InvokeFunction"
+ def test_lambda_tags_rest(self):
+ from ministack.core.iam_actions import extract_iam_action
+ path = "/2017-03-31/tags/arn:aws:lambda:us-east-1:000000000000:function:f"
+ assert extract_iam_action("lambda", "POST", path, {}, b"", {}) == "lambda:TagResource"
+ assert extract_iam_action("lambda", "DELETE", path, {}, b"", {"tagKeys": ["a"]}) == "lambda:UntagResource"
+ assert extract_iam_action("lambda", "GET", path, {}, b"", {}) == "lambda:ListTags"
+
def test_unknown_service_returns_none(self):
from ministack.core.iam_actions import extract_iam_action
assert extract_iam_action("unknown_svc", "GET", "/", {}, b"", {}) is None
@@ -4865,6 +5175,50 @@ def test_trust_not_action_denies(trust_api, operation, deny_first, excluded, con
_assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")
+def _tags(protocol, **tags):
+ if protocol == "json":
+ return {"Tags": [{"Key": key, "Value": value} for key, value in tags.items()]}
+ return {f"Tags.member.{n}.{field}": text for n, (key, value) in enumerate(tags.items(), 1)
+ for field, text in (("Key", key), ("Value", value))}
+
+
+def test_trust_conditions_see_the_caller_principal_tags(trust_api):
+ call, _, _ = trust_api
+ _install_policy(trust_api, "CreateRole", _document(dict(
+ ALLOW, Condition={"StringEquals": {"aws:PrincipalTag/team": "blue"}})))
+ _assume(trust_api, 403, RoleSessionName="untagged")
+ assert call("iam", "TagUser", UserName="trust-deployer", **_tags("query", team="blue"))[0] == 200
+ _assume(trust_api, 200, RoleSessionName="tagged")
+
+
[email protected]("actions, tagged, expected", [
+ ("sts:AssumeRole", False, 200),
+ ("sts:AssumeRole", True, 403),
+ (["sts:AssumeRole", "sts:TagSession"], True, 200),
+])
+def test_trust_session_tags_need_tag_session(trust_api, actions, tagged, expected):
+ call, sessions, protocol = trust_api
+ _install_policy(trust_api, "CreateRole", _document(dict(ALLOW, Action=actions)))
+ status, _, body = call("sts", "AssumeRole", RoleArn=ROLE_ARN, RoleSessionName="tags",
+ **(_tags(protocol, team="blue") if tagged else {}))
+ assert status == expected, body
+ if expected == 403:
+ assert f"{CALLER} is not authorized to perform: sts:TagSession on resource: {ROLE_ARN}".encode() in body
+ elif tagged:
+ assert [s["SessionTags"] for s in sessions.values()] == [[{"Key": "team", "Value": "blue"}]]
+
+
[email protected]("key, expected", [("team", 200), ("dept", 403)])
+def test_trust_conditions_see_session_tags_as_request_tags(trust_api, key, expected):
+ _, _, protocol = trust_api
+ _install_policy(trust_api, "CreateRole", _document(ALLOW, dict(
+ ALLOW, Action="sts:TagSession", Condition={"StringLike": {"aws:RequestTag/team": "*"}})))
+ call, _, _ = trust_api
+ status, _, body = call("sts", "AssumeRole", RoleArn=ROLE_ARN, RoleSessionName="tags",
+ **_tags(protocol, **{key: "blue"}))
+ assert status == expected, body
+
+
@pytest.mark.parametrize("operation", ["CreateRole", "UpdateAssumeRolePolicy"])
@pytest.mark.parametrize("policy", [
_document(ALLOW, dict(ALLOW, Effect="Deny")),
diff --git a/tests/test_rds_iam.py b/tests/test_rds_iam.py
index 1cace031..529a2934 100644
--- a/tests/test_rds_iam.py
+++ b/tests/test_rds_iam.py
@@ -484,6 +484,13 @@ class TestResourceBoundAuthorization:
assert isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection) is allowed
+ @pytest.mark.parametrize("user,allowed", [("alice", True), ("bob", False)])
+ def test_policy_conditions_see_the_caller(self, user, allowed):
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {
+ "grant": _authz_policy(Condition={"StringEquals": {"aws:username": user}}),
+ })
+ assert isinstance(authorize_rds_iam_token(_authz_token(), **AUTHZ_ARGS), AuthorizedRdsConnection) is allowed
+
def test_cluster_dictionary_endpoint_uses_advertised_port(self):
rds._clusters.set_scoped(ACCOUNT, REGION, "database", {
"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
diff --git a/tests/test_sts.py b/tests/test_sts.py
index 1f8d6a81..d5208349 100644
--- a/tests/test_sts.py
+++ b/tests/test_sts.py
@@ -118,6 +118,34 @@ def test_sts_assume_role(sts):
assert "AssumedRoleId" in assumed
[email protected]("auth, status", [(True, 400), (False, 200)])
+def test_sts_assume_role_refuses_session_tag_keys_differing_in_case_under_auth(monkeypatch, auth, status):
+ import asyncio
+
+ import ministack.app as app_mod
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_mod
+
+ monkeypatch.setattr(app_mod, "AUTH", auth)
+ role = f"tag-case-{os.urandom(4).hex()}"
+ trust = {"Statement": [{"Effect": "Allow", "Principal": {"AWS": "000000000000"},
+ "Action": ["sts:AssumeRole", "sts:TagSession"]}]}
+ iam_svc._roles[role] = {"RoleName": role, "Arn": f"arn:aws:iam::000000000000:role/{role}", "Tags": [],
+ "AssumeRolePolicyDocument": json.dumps(trust)}
+ body = (f"Action=AssumeRole&Version=2011-06-15&RoleSessionName=tags&RoleArn=arn:aws:iam::000000000000:role/{role}"
+ "&Tags.member.1.Key=team&Tags.member.1.Value=blue&Tags.member.2.Key=TEAM&Tags.member.2.Value=red").encode()
+ headers = {"content-type": "application/x-www-form-urlencoded",
+ "authorization": "AWS4-HMAC-SHA256 Credential=test/20260930/us-east-1/sts/aws4_request"}
+ try:
+ got, _headers, payload = asyncio.run(sts_mod.handle_request("POST", "/", headers, body, {}))
+ finally:
+ iam_svc._roles.pop(role, None)
+ assert got == status
+ if auth:
+ assert b"<Code>InvalidParameterValue</Code>" in payload
+ assert b"Tag keys are case insensitive" in payload
+
+
def test_sts_assumed_role_arn_uses_sts_service(sts):
"""Real AWS returns AssumeRole's AssumedRoleUser.Arn under the sts
service, not iam — e.g. arn:aws:sts::123456789012:assumed-role/demo/Sess.
@@ -504,13 +532,15 @@ def test_sts_policies_reach_only_get_access_key_info(monkeypatch, auth_enabled,
def test_sts_assume_role_with_web_identity(sts, iam):
iam.create_role(
RoleName="test-oidc-role",
- AssumeRolePolicyDocument='{"Version":"2012-10-17","Statement":[]}',
+ AssumeRolePolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": "sts:AssumeRoleWithWebIdentity",
+ "Principal": {"Federated": "arn:aws:iam::000000000000:oidc-provider/oidc.example.com"}}]}),
)
role_arn = "arn:aws:iam::000000000000:role/test-oidc-role"
resp = sts.assume_role_with_web_identity(
RoleArn=role_arn,
RoleSessionName="ci-session",
- WebIdentityToken="fake-oidc-token-value",
+ WebIdentityToken=_web_token({"iss": "https://oidc.example.com", "aud": "ci", "sub": "ci-user"}),
)
creds = resp["Credentials"]
assert "AccessKeyId" in creds
@@ -519,6 +549,53 @@ def test_sts_assume_role_with_web_identity(sts, iam):
assert "Expiration" in creds
+def _web_token(claims):
+ import base64
+
+ def b64(obj):
+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
+ return f"{b64({'alg': 'RS256'})}.{b64(claims)}.sig"
+
+
[email protected]("role,status", [
+ ("trust-web", 200), ("trust-web-aud", 403), ("trust-web-aws", 403),
+])
+def test_sts_assume_role_with_web_identity_checks_trust(monkeypatch, role, status):
+ import asyncio
+ from urllib.parse import urlencode
+
+ from ministack import app as app_mod
+ from ministack.core.responses import request_scope
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_svc
+
+ account, host = "000000000000", "issuer.example.com/pool"
+ provider = f"arn:aws:iam::{account}:oidc-provider/{host}"
+
+ def federated(aud):
+ return [{"Effect": "Allow", "Action": "sts:AssumeRoleWithWebIdentity", "Principal": {"Federated": provider},
+ "Condition": {"StringEquals": {f"{host}:aud": aud}}}]
+ trust = {"trust-web": federated("client-a"), "trust-web-aud": federated("client-b"),
+ "trust-web-aws": [{"Effect": "Allow", "Action": "sts:AssumeRoleWithWebIdentity",
+ "Principal": {"AWS": account}}]}[role]
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ iam_svc._roles.set_scoped(account, None, role, {
+ "RoleName": role, "Arn": f"arn:aws:iam::{account}:role/{role}", "Tags": [],
+ "AssumeRolePolicyDocument": json.dumps({"Version": "2012-10-17", "Statement": trust})})
+ body = urlencode({"Action": "AssumeRoleWithWebIdentity", "RoleSessionName": "trust",
+ "RoleArn": f"arn:aws:iam::{account}:role/{role}",
+ "WebIdentityToken": _web_token({"iss": f"https://{host}", "aud": "client-a", "sub": "u-1"})})
+ try:
+ with request_scope(account, "us-east-1"):
+ got, _, payload = asyncio.run(sts_svc.handle_request(
+ "POST", "/", {"content-type": "application/x-www-form-urlencoded"}, body.encode(), {}))
+ finally:
+ iam_svc._roles.pop_scoped(account, None, role, None)
+ assert got == status
+ if status == 403:
+ assert b"Not authorized to perform sts:AssumeRoleWithWebIdentity" in payload
+
+
def _gwit_post(data: bytes):
"""POST raw form-encoded body to STS GetWebIdentityToken (boto3 has no client method)."""
import urllib.error