Skip to content

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

fix(cloudfront): report function status after publish and association (#2208)

Fábio André Ramos Rodriguesd51e89b42298
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 36a72057..6c5e0683 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `ASSOCIATED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.
+- **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`.
+- **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.
+### Fixed
+- **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.
- **AppSync — GraphQL requests on the API's own host** — a `POST /graphql` to `{apiId}.appsync-api.{region}.{host}`, the endpoint `uris.GRAPHQL` reports, was routed to AppSync Events when unsigned and found its API only by `x-api-key` when signed, so an `AWS_IAM` API could not be called there once a second API existed; the host label now selects the API (in the host's region for an unsigned request) and `/graphql` on an Event API host answers `404 ResourceNotFoundException`, as on AWS. Contributed by @iot-rocket.
- **Cognito — no ID token without `openid`** — the `/oauth2/token` authorization code and refresh token grants returned an `id_token` whatever was granted; they now return one only when the grant carries `openid`, as AWS does, and a refresh token from `InitiateAuth` or `AdminInitiateAuth` still gets one. Contributed by @iot-rocket.
- **Cognito — token endpoint access tokens carry the granted scopes** — `/oauth2/token` wrote `aws.cognito.signin.user.admin` into every access token whatever was granted; the authorization code, client credentials and refresh token grants now write the requested scopes the app client allows (all of them when none are requested, only resource server scopes for client credentials) in the order AWS lists them, refreshed tokens keep the original scopes, and the pre token generation event's `request.scopes` lists them, so API Gateway scope checks decide as on AWS. Contributed by @iot-rocket.
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 91a2a1e6..460110bd 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -737,6 +737,26 @@ def _function_summary_builder(fn: dict, stage: str, status: str, last_modified:
return build
+def _function_arns_in(dist):
+ try:
+ root = fromstring(dist.get("config_xml") or "")
+ except Exception:
+ return set()
+ return {el.text for el in root.iter() if el.tag.split("}")[-1] == "FunctionARN" and el.text}
+
+
+def _function_dev_status(fn):
+ """DEVELOPMENT-stage Status: UNPUBLISHED until PublishFunction has copied
+ the current development version to LIVE (an UpdateFunction since then makes
+ it UNPUBLISHED again), then ASSOCIATED while a distribution's cache behavior
+ references the function and UNASSOCIATED otherwise."""
+ if not fn.get("live_etag") or fn.get("published_dev_etag") != fn["dev_etag"]:
+ return "UNPUBLISHED"
+ if any(fn["arn"] in _function_arns_in(d) for d in _distributions.values()):
+ return "ASSOCIATED"
+ return "UNASSOCIATED"
+
+
def _cf_parse_function_config(cfg_el):
if cfg_el is None:
return None, _error("InvalidArgument", "FunctionConfig is required.", 400)
@@ -798,6 +818,8 @@ def _cf_create_function(headers, body):
"last_modified_live": None,
"dev_etag": dev_etag,
"live_etag": None,
+ # The dev_etag PublishFunction last copied to LIVE (see _function_dev_status).
+ "published_dev_etag": None,
# The body PublishFunction froze; LIVE serves this, not the working copy.
"live_body": None,
}
@@ -820,7 +842,7 @@ def _cf_list_functions(query_params):
summaries = []
for fn in _functions.values():
if stage_filter in ("", "DEVELOPMENT"):
- summaries.append((fn, "DEVELOPMENT", "UNPUBLISHED", fn["last_modified_dev"]))
+ summaries.append((fn, "DEVELOPMENT", _function_dev_status(fn), fn["last_modified_dev"]))
if stage_filter in ("", "LIVE") and fn["live_etag"]:
summaries.append((fn, "LIVE", "DEPLOYED", fn["last_modified_live"] or fn["last_modified_dev"]))
@@ -851,7 +873,7 @@ def _cf_describe_function(name: str, stage: str):
elif stage == "DEVELOPMENT":
etag = fn["dev_etag"]
lm = fn["last_modified_dev"]
- st = "UNPUBLISHED"
+ st = _function_dev_status(fn)
else:
return _error("InvalidArgument", "Invalid Stage value.", 400)
@@ -897,6 +919,7 @@ def _cf_publish_function(name: str, headers):
now = _now_iso()
fn["live_etag"] = new_uuid()
fn["last_modified_live"] = now
+ fn["published_dev_etag"] = fn["dev_etag"]
# Publishing copies DEVELOPMENT to LIVE; later updates to the development
# body must not reach the stage that is serving traffic.
fn["live_body"] = {
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index c79780b9..fa806c0a 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -897,6 +897,69 @@ def test_cloudfront_function_update_keeps_the_published_live_stage(cloudfront):
)
+def test_cloudfront_function_development_status_follows_publish_and_association(cloudfront):
+ """The DEVELOPMENT stage reports UNPUBLISHED only while it holds changes that
+ were never published, then UNASSOCIATED, or ASSOCIATED while a cache
+ behavior references the function. Terraform's aws_cloudfront_function.status
+ reads this stage."""
+ name = f"fn-status-{_uuid_mod.uuid4().hex[:8]}"
+
+ def dev_status():
+ return cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")["FunctionSummary"]["Status"]
+
+ def listed_dev_status():
+ items = cloudfront.list_functions(Stage="DEVELOPMENT")["FunctionList"].get("Items", [])
+ return next(it["Status"] for it in items if it["Name"] == name)
+
+ cr = cloudfront.create_function(
+ Name=name,
+ FunctionConfig={"Comment": "v1", "Runtime": "cloudfront-js-2.0"},
+ FunctionCode=b"function handler(event) { return event.request; }",
+ )
+ assert cr["FunctionSummary"]["Status"] == "UNPUBLISHED"
+ assert dev_status() == "UNPUBLISHED"
+
+ cloudfront.publish_function(Name=name, IfMatch=_cf_resp_etag(cr))
+ assert dev_status() == "UNASSOCIATED"
+ assert listed_dev_status() == "UNASSOCIATED"
+
+ upd = cloudfront.update_function(
+ Name=name,
+ IfMatch=_cf_resp_etag(cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")),
+ FunctionConfig={"Comment": "v2", "Runtime": "cloudfront-js-2.0"},
+ FunctionCode=b"function handler(event) { return event.request; } // v2",
+ )
+ assert upd["FunctionSummary"]["Status"] == "UNPUBLISHED"
+ assert dev_status() == "UNPUBLISHED"
+ assert listed_dev_status() == "UNPUBLISHED"
+
+ cloudfront.publish_function(Name=name, IfMatch=_cf_resp_etag(upd))
+ assert dev_status() == "UNASSOCIATED"
+
+ fn_arn = cloudfront.describe_function(Name=name, Stage="LIVE")["FunctionSummary"]["FunctionMetadata"]["FunctionARN"]
+ cfg = copy.deepcopy(_CF_DIST_CONFIG)
+ cfg["CallerReference"] = f"cf-fn-status-{_uuid_mod.uuid4().hex[:12]}"
+ cfg["DefaultCacheBehavior"]["FunctionAssociations"] = {
+ "Quantity": 1,
+ "Items": [{"FunctionARN": fn_arn, "EventType": "viewer-request"}],
+ }
+ dist = cloudfront.create_distribution(DistributionConfig=cfg)
+ assert dev_status() == "ASSOCIATED"
+ assert listed_dev_status() == "ASSOCIATED"
+
+ dist_id = dist["Distribution"]["Id"]
+ cfg["Enabled"] = False
+ cfg["DefaultCacheBehavior"]["FunctionAssociations"] = {"Quantity": 0}
+ upd_dist = cloudfront.update_distribution(Id=dist_id, IfMatch=dist["ETag"], DistributionConfig=cfg)
+ assert dev_status() == "UNASSOCIATED"
+
+ cloudfront.delete_distribution(Id=dist_id, IfMatch=upd_dist["ETag"])
+ cloudfront.delete_function(
+ Name=name,
+ IfMatch=_cf_resp_etag(cloudfront.describe_function(Name=name, Stage="DEVELOPMENT")),
+ )
+
+
def test_cloudfront_function_duplicate_name(cloudfront):
name = f"fn-dup-{_uuid_mod.uuid4().hex[:8]}"
cloudfront.create_function(