Skip to content

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

fix(cfn,s3): provisioners, checksum (#833)

Nahuel Nucera47ea2fb336d6
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 0f3a62bb..c696508a 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -87,8 +87,6 @@ async def _urlopen_async(request_or_url, timeout_seconds: float):
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
_PROXY_TIMEOUT_SECONDS = _timeout_from_env("MINISTACK_APIGW_PROXY_TIMEOUT_SECONDS", 30.0)
_JWKS_TIMEOUT_SECONDS = _timeout_from_env("MINISTACK_APIGW_JWKS_TIMEOUT_SECONDS", 5.0)
-_OIDC_TIMEOUT_SECONDS = _timeout_from_env("MINISTACK_APIGW_OIDC_TIMEOUT_SECONDS", 5.0)
-_OIDC_CACHE_TTL_SECONDS = _timeout_from_env("MINISTACK_APIGW_OIDC_CACHE_TTL_SECONDS", 7200.0)
# ---- Module-level state ----
_apis = AccountScopedDict() # api_id -> api object
@@ -514,11 +512,13 @@ async def _fetch_oidc_jwks_uri(issuer: str) -> str | None:
jwks_uri = None
try:
url = f"{issuer}/.well-known/openid-configuration"
- _, _, body = await _urlopen_async(url, _OIDC_TIMEOUT_SECONDS)
+ _, _, body = await _urlopen_async(url, _JWKS_TIMEOUT_SECONDS)
jwks_uri = (json.loads(body or b"{}") or {}).get("jwks_uri")
except (OSError, ValueError, json.JSONDecodeError):
jwks_uri = None
- _oidc_config_cache[issuer] = {"jwks_uri": jwks_uri, "expiresAt": now + _OIDC_CACHE_TTL_SECONDS}
+ # Mirror _fetch_jwks (line ~543) which hardcodes `now + 7200`; no separate
+ # env knob for OIDC discovery — it shares the JWT-auth external-fetch path.
+ _oidc_config_cache[issuer] = {"jwks_uri": jwks_uri, "expiresAt": now + 7200}
return jwks_uri
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 325482e8..4527a6e5 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -677,8 +677,29 @@ def _resolve_api_by_key(api_key_value):
return None
-def _invoke_lambda_authorizer(api_id, authorizer_config, request_headers):
- """Invoke the Lambda authorizer; return an identity dict or None on failure/rejection.
+class _AuthorizerRejected(Exception):
+ """Sentinel raised when the Lambda authorizer denies a request.
+
+ AWS docs are explicit: an authorizer returning `isAuthorized:false`, an
+ authorizer Lambda that's unreachable, or an authorizer that raises must all
+ surface to the client as `UnauthorizedException` (HTTP 401). Callers catch
+ this and emit the standard AppSync error envelope.
+ """
+
+
+def _invoke_lambda_authorizer(
+ api_id, authorizer_config, request_headers,
+ *,
+ query: str = "",
+ variables: dict | None = None,
+ operation_name: str | None = None,
+):
+ """Invoke the Lambda authorizer.
+
+ Returns the identity dict (`{}` when authorized with no `resolverContext`,
+ or `{"resolverContext": {...}}` when present). Raises ``_AuthorizerRejected``
+ for any failure mode AWS treats as unauthorized: missing authorizer Lambda,
+ invocation error, malformed response, or ``isAuthorized:false``.
AWS stores the authorizer Lambda under ``lambdaAuthorizerConfig.authorizerUri``
(which ``_create_graphql_api`` persists verbatim). ministack's AppSync Events
@@ -686,19 +707,32 @@ def _invoke_lambda_authorizer(api_id, authorizer_config, request_headers):
"""
func_arn = authorizer_config.get("authorizerUri") or authorizer_config.get("authorizer_uri")
if not func_arn:
- return None
+ # Misconfigured API (lambdaAuthorizerConfig present but no Uri). Treat
+ # as authorized — this is a config error surface, not a per-request
+ # rejection signal.
+ return {}
import ministack.services.lambda_svc as _lambda_svc
func_name = func_arn.rsplit(":", 1)[-1]
func = _lambda_svc._functions.get(func_name)
if not func:
- logger.warning("Lambda authorizer %s not found in ministack — skipping auth", func_name)
- return None
+ logger.warning("Lambda authorizer %s not found in ministack", func_name)
+ raise _AuthorizerRejected("authorizer Lambda not found")
+ # AWS-verified authorizer event shape — apiId / accountId / requestId /
+ # queryString / operationName / variables / requestHeaders all present per
+ # the AppSync Developer Guide AWS_LAMBDA authorization section.
authorizer_event = {
"authorizationToken": request_headers.get("authorization", ""),
- "requestContext": {"operationName": "unknown"},
+ "requestContext": {
+ "apiId": api_id,
+ "accountId": get_account_id(),
+ "requestId": new_uuid(),
+ "queryString": query,
+ "operationName": operation_name or "unknown",
+ "variables": variables or {},
+ },
"requestHeaders": request_headers,
}
@@ -706,29 +740,40 @@ def _invoke_lambda_authorizer(api_id, authorizer_config, request_headers):
result = _lambda_svc._execute_function(func, authorizer_event)
except Exception as e:
logger.warning("Lambda authorizer invocation failed: %s", e)
- return None
+ raise _AuthorizerRejected("authorizer invocation failed") from e
if not isinstance(result, dict) or result.get("error"):
logger.warning("Lambda authorizer execution error")
- return None
+ raise _AuthorizerRejected("authorizer execution error")
body = result.get("body")
if isinstance(body, str):
try:
body = json.loads(body)
except Exception:
- return None
+ raise _AuthorizerRejected("authorizer returned non-JSON body")
if not isinstance(body, dict):
- return None
+ raise _AuthorizerRejected("authorizer returned non-dict body")
if not body.get("isAuthorized", False):
logger.warning("Lambda authorizer rejected request")
- return None
+ raise _AuthorizerRejected("isAuthorized=false")
resolver_context = body.get("resolverContext")
if resolver_context:
return {"resolverContext": resolver_context}
- return None
+ return {}
+
+
+def _unauthorized_response():
+ """AppSync's wire-shape for an authorizer rejection: HTTP 401 with a
+ GraphQL `errors` envelope carrying `UnauthorizedException`."""
+ return _json(401, {
+ "errors": [{
+ "errorType": "UnauthorizedException",
+ "message": "You are not authorized to make this call.",
+ }],
+ })
def _execute_graphql(api_id, data, request_headers=None):
@@ -760,13 +805,20 @@ def _execute_graphql(api_id, data, request_headers=None):
is_mutation = query_clean.strip().startswith("mutation")
# Determine identity from the Lambda authorizer (AWS_LAMBDA auth mode).
+ # AWS contract: a rejected authorizer must surface as UnauthorizedException
+ # (HTTP 401), not as a HTTP 200 with identity=null.
identity = None
api = _apis.get(api_id, {})
if api.get("lambdaAuthorizerConfig"):
- identity = _invoke_lambda_authorizer(
- api_id, api["lambdaAuthorizerConfig"], request_headers or {}
- )
- # If identity is None, the request proceeds with identity=None (API_KEY behavior).
+ try:
+ identity = _invoke_lambda_authorizer(
+ api_id, api["lambdaAuthorizerConfig"], request_headers or {},
+ query=query,
+ variables=variables,
+ operation_name=operation_name,
+ )
+ except _AuthorizerRejected:
+ return _unauthorized_response()
results = {}
errors = []
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index badc9064..55dcc314 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -767,6 +767,227 @@ def _appconfig_application_delete(physical_id, props):
_appconfig._tags.pop(_appconfig._app_arn(physical_id), None)
+# --- AppConfig Environment ---
+
+def _appconfig_environment_create(logical_id, props, stack_name):
+ app_id = props.get("ApplicationId")
+ if not app_id:
+ raise ValueError("AWS::AppConfig::Environment requires ApplicationId")
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ env_id = _appconfig._gen_id()
+ _appconfig._environments[f"{app_id}/{env_id}"] = {
+ "ApplicationId": app_id,
+ "Id": env_id,
+ "Name": name,
+ "Description": props.get("Description", ""),
+ "State": "READY_FOR_DEPLOYMENT",
+ "Monitors": props.get("Monitors", []),
+ "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),
+ }
+ cfn_tags = props.get("Tags") or []
+ if cfn_tags:
+ _appconfig._apply_tags(
+ _appconfig._env_arn(app_id, env_id),
+ {t["Key"]: t["Value"] for t in cfn_tags if "Key" in t},
+ )
+ # Ref → environment ID; GetAtt EnvironmentId per AWS CFN reference.
+ return env_id, {"EnvironmentId": env_id}
+
+
+def _appconfig_environment_delete(physical_id, props):
+ app_id = props.get("ApplicationId", "")
+ _appconfig._environments.pop(f"{app_id}/{physical_id}", None)
+ _appconfig._tags.pop(_appconfig._env_arn(app_id, physical_id), None)
+
+
+# --- AppConfig ConfigurationProfile ---
+
+def _appconfig_configuration_profile_create(logical_id, props, stack_name):
+ app_id = props.get("ApplicationId")
+ if not app_id:
+ raise ValueError("AWS::AppConfig::ConfigurationProfile requires ApplicationId")
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=128)
+ profile_id = _appconfig._gen_id()
+ _appconfig._config_profiles[f"{app_id}/{profile_id}"] = {
+ "ApplicationId": app_id,
+ "Id": profile_id,
+ "Name": name,
+ "Description": props.get("Description", ""),
+ "LocationUri": props.get("LocationUri", "hosted"),
+ "RetrievalRoleArn": props.get("RetrievalRoleArn", ""),
+ "Validators": props.get("Validators", []),
+ "Type": props.get("Type", "AWS.Freeform"),
+ "KmsKeyIdentifier": props.get("KmsKeyIdentifier", ""),
+ "DeletionProtectionCheck": props.get("DeletionProtectionCheck", "ACCOUNT_DEFAULT"),
+ }
+ cfn_tags = props.get("Tags") or []
+ if cfn_tags:
+ _appconfig._apply_tags(
+ _appconfig._profile_arn(app_id, profile_id),
+ {t["Key"]: t["Value"] for t in cfn_tags if "Key" in t},
+ )
+ # Ref → configuration profile ID; GetAtt ConfigurationProfileId, KmsKeyArn.
+ # KmsKeyArn is only populated when a KMS key was supplied; CDK reads it as
+ # an empty string in that case.
+ return profile_id, {
+ "ConfigurationProfileId": profile_id,
+ "KmsKeyArn": props.get("KmsKeyIdentifier", ""),
+ }
+
+
+def _appconfig_configuration_profile_delete(physical_id, props):
+ app_id = props.get("ApplicationId", "")
+ _appconfig._config_profiles.pop(f"{app_id}/{physical_id}", None)
+ _appconfig._tags.pop(_appconfig._profile_arn(app_id, physical_id), None)
+
+
+# --- AppConfig HostedConfigurationVersion ---
+
+def _appconfig_hosted_version_create(logical_id, props, stack_name):
+ app_id = props.get("ApplicationId")
+ profile_id = props.get("ConfigurationProfileId")
+ if not app_id or not profile_id:
+ raise ValueError(
+ "AWS::AppConfig::HostedConfigurationVersion requires "
+ "ApplicationId and ConfigurationProfileId"
+ )
+ content = props.get("Content", "")
+ # CDK / Fn::ToJsonString may pass parsed JSON; AWS wire shape is a string.
+ if isinstance(content, (dict, list)):
+ content = json.dumps(content)
+ existing = [
+ v for k, v in _appconfig._hosted_versions.items()
+ if k.startswith(f"{app_id}/{profile_id}/")
+ ]
+ version_number = len(existing) + 1
+ # AWS optimistic-concurrency: if LatestVersionNumber is supplied, it must
+ # match the most-recent version_number — otherwise reject with a
+ # ConflictException-shape error (mirrors real AppConfig's lock check).
+ latest_lock = props.get("LatestVersionNumber")
+ if latest_lock is not None and int(latest_lock) != version_number - 1:
+ raise ValueError(
+ f"AWS::AppConfig::HostedConfigurationVersion LatestVersionNumber "
+ f"mismatch: supplied {latest_lock}, current latest is {version_number - 1}"
+ )
+ _appconfig._hosted_versions[f"{app_id}/{profile_id}/{version_number}"] = {
+ "ApplicationId": app_id,
+ "ConfigurationProfileId": profile_id,
+ "VersionNumber": version_number,
+ "ContentType": props.get("ContentType", "application/json"),
+ "Content": content,
+ "Description": props.get("Description", ""),
+ "VersionLabel": props.get("VersionLabel", ""),
+ }
+ # Ref → version number; GetAtt VersionNumber.
+ return str(version_number), {"VersionNumber": version_number}
+
+
+def _appconfig_hosted_version_delete(physical_id, props):
+ app_id = props.get("ApplicationId", "")
+ profile_id = props.get("ConfigurationProfileId", "")
+ _appconfig._hosted_versions.pop(
+ f"{app_id}/{profile_id}/{physical_id}", None
+ )
+
+
+# --- AppConfig DeploymentStrategy ---
+
+def _appconfig_deployment_strategy_create(logical_id, props, stack_name):
+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ strategy_id = _appconfig._gen_id()
+ _appconfig._deployment_strategies[strategy_id] = {
+ "Id": strategy_id,
+ "Name": name,
+ "Description": props.get("Description", ""),
+ "DeploymentDurationInMinutes": props.get("DeploymentDurationInMinutes", 0),
+ "GrowthType": props.get("GrowthType", "LINEAR"),
+ "GrowthFactor": props.get("GrowthFactor", 100.0),
+ "FinalBakeTimeInMinutes": props.get("FinalBakeTimeInMinutes", 0),
+ "ReplicateTo": props.get("ReplicateTo", "NONE"),
+ }
+ cfn_tags = props.get("Tags") or []
+ if cfn_tags:
+ _appconfig._apply_tags(
+ _appconfig._strategy_arn(strategy_id),
+ {t["Key"]: t["Value"] for t in cfn_tags if "Key" in t},
+ )
+ # Ref → deployment strategy ID; GetAtt is `Id` (singular) per AWS reference.
+ return strategy_id, {"Id": strategy_id}
+
+
+def _appconfig_deployment_strategy_delete(physical_id, props):
+ _appconfig._deployment_strategies.pop(physical_id, None)
+ _appconfig._tags.pop(_appconfig._strategy_arn(physical_id), None)
+
+
+# --- AppConfig Deployment ---
+
+def _appconfig_deployment_create(logical_id, props, stack_name):
+ app_id = props.get("ApplicationId")
+ env_id = props.get("EnvironmentId")
+ strategy_id = props.get("DeploymentStrategyId")
+ profile_id = props.get("ConfigurationProfileId")
+ if not all([app_id, env_id, strategy_id, profile_id]):
+ raise ValueError(
+ "AWS::AppConfig::Deployment requires ApplicationId, EnvironmentId, "
+ "DeploymentStrategyId, and ConfigurationProfileId"
+ )
+ existing = [
+ v for k, v in _appconfig._deployments.items()
+ if k.startswith(f"{app_id}/{env_id}/")
+ ]
+ deploy_num = len(existing) + 1
+ now = _appconfig._now_iso()
+ _appconfig._deployments[f"{app_id}/{env_id}/{deploy_num}"] = {
+ "ApplicationId": app_id,
+ "EnvironmentId": env_id,
+ "DeploymentStrategyId": strategy_id,
+ "ConfigurationProfileId": profile_id,
+ "DeploymentNumber": deploy_num,
+ "ConfigurationName": _appconfig._config_profiles.get(
+ f"{app_id}/{profile_id}", {}
+ ).get("Name", ""),
+ "ConfigurationLocationUri": "hosted",
+ "ConfigurationVersion": props.get("ConfigurationVersion", ""),
+ "Description": props.get("Description", ""),
+ "State": "COMPLETE",
+ "PercentageComplete": 100.0,
+ "StartedAt": now,
+ "CompletedAt": now,
+ "KmsKeyIdentifier": props.get("KmsKeyIdentifier", ""),
+ "DynamicExtensionParameters": props.get("DynamicExtensionParameters", []),
+ }
+ cfn_tags = props.get("Tags") or []
+ if cfn_tags:
+ # Deployment doesn't have its own ARN helper; use the standard AppConfig
+ # ARN shape so ListTagsForResource keeps working post-create.
+ deploy_arn = (
+ f"arn:aws:appconfig:{_appconfig.get_region()}:"
+ f"{_appconfig.get_account_id()}:application/{app_id}/"
+ f"environment/{env_id}/deployment/{deploy_num}"
+ )
+ _appconfig._apply_tags(
+ deploy_arn,
+ {t["Key"]: t["Value"] for t in cfn_tags if "Key" in t},
+ )
+ # GetAtt DeploymentNumber, State. Ref is documented as having no return
+ # value on the AWS CFN page; we return the deploy_num as the physical id
+ # so CDK templates that Ref a Deployment still resolve.
+ return str(deploy_num), {"DeploymentNumber": deploy_num, "State": "COMPLETE"}
+
+
+def _appconfig_deployment_delete(physical_id, props):
+ app_id = props.get("ApplicationId", "")
+ env_id = props.get("EnvironmentId", "")
+ _appconfig._deployments.pop(f"{app_id}/{env_id}/{physical_id}", None)
+ deploy_arn = (
+ f"arn:aws:appconfig:{_appconfig.get_region()}:"
+ f"{_appconfig.get_account_id()}:application/{app_id}/"
+ f"environment/{env_id}/deployment/{physical_id}"
+ )
+ _appconfig._tags.pop(deploy_arn, None)
+
+
# --- CloudWatch Logs LogGroup ---
def _cwlogs_create(logical_id, props, stack_name):
@@ -3897,6 +4118,26 @@ _RESOURCE_HANDLERS = {
"create": _appconfig_application_create,
"delete": _appconfig_application_delete,
},
+ "AWS::AppConfig::Environment": {
+ "create": _appconfig_environment_create,
+ "delete": _appconfig_environment_delete,
+ },
+ "AWS::AppConfig::ConfigurationProfile": {
+ "create": _appconfig_configuration_profile_create,
+ "delete": _appconfig_configuration_profile_delete,
+ },
+ "AWS::AppConfig::HostedConfigurationVersion": {
+ "create": _appconfig_hosted_version_create,
+ "delete": _appconfig_hosted_version_delete,
+ },
+ "AWS::AppConfig::DeploymentStrategy": {
+ "create": _appconfig_deployment_strategy_create,
+ "delete": _appconfig_deployment_strategy_delete,
+ },
+ "AWS::AppConfig::Deployment": {
+ "create": _appconfig_deployment_create,
+ "delete": _appconfig_deployment_delete,
+ },
"AWS::Logs::LogGroup": {"create": _cwlogs_create, "delete": _cwlogs_delete},
"AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},
"AWS::Events::EventBus": {"create": _eb_event_bus_create, "delete": _eb_event_bus_delete},
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index a5d4321d..e190f4be 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -30,9 +30,11 @@ import json
import logging
import os
import re
+import struct
import shutil
import threading
import time
+import zlib
from urllib.parse import parse_qs as _parse_qs
from urllib.parse import quote as url_quote
from urllib.parse import unquote as url_unquote
@@ -519,7 +521,8 @@ def _extract_user_metadata(headers: dict) -> dict:
return meta
-def _build_object_record(body: bytes, headers: dict, etag: str = None) -> dict:
+def _build_object_record(body: bytes, headers: dict, etag: str = None,
+ checksums: dict | None = None) -> dict:
content_type = headers.get("content-type", "application/octet-stream")
content_encoding = headers.get("content-encoding")
preserved = {}
@@ -538,10 +541,106 @@ def _build_object_record(body: bytes, headers: dict, etag: str = None) -> dict:
"metadata": _extract_user_metadata(headers),
"preserved_headers": preserved,
"storage_class": headers.get("x-amz-storage-class") or "STANDARD",
+ # AWS-shape checksums (SHA256 / SHA1 / CRC32 / CRC32C / CRC64NVME),
+ # stored uppercase-keyed and base64-encoded per the S3 wire contract.
+ # Surfaced on Get/HeadObject via the `x-amz-checksum-*` headers only
+ # when the caller sends `x-amz-checksum-mode: ENABLED`.
+ "checksums": checksums or {},
}
-def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "") -> dict:
+# ---------------------------------------------------------------------------
+# AWS-shape checksum handling (SHA256 / SHA1 / CRC32 / CRC32C / CRC64NVME)
+# ---------------------------------------------------------------------------
+
+_S3_CHECKSUM_HEADERS = ("crc32", "crc32c", "crc64nvme", "sha1", "sha256")
+
+
+def _compute_s3_checksum(algorithm: str, body: bytes) -> str | None:
+ """Return base64-encoded checksum for the given AWS S3 algorithm name.
+
+ Supports SHA256 / SHA1 / CRC32 via stdlib. CRC32C / CRC64NVME require
+ optional native libs (`google-crc32c` / `crc64nvme-py`) that aren't part of
+ the stdlib; we return None for those, and the caller falls back to the
+ client-supplied value (if any) instead of failing the put.
+ """
+ algo = (algorithm or "").upper().replace("_", "")
+ if algo == "SHA256":
+ return base64.b64encode(hashlib.sha256(body).digest()).decode()
+ if algo == "SHA1":
+ return base64.b64encode(hashlib.sha1(body).digest()).decode()
+ if algo == "CRC32":
+ crc = zlib.crc32(body) & 0xFFFFFFFF
+ return base64.b64encode(struct.pack(">I", crc)).decode()
+ return None
+
+
+def _resolve_object_checksums(body: bytes, headers: dict):
+ """Build the stored checksum dict and validate any client-supplied values.
+
+ AWS PutObject contract:
+ - `x-amz-checksum-{alg}` headers carry a client-computed value.
+ - `x-amz-sdk-checksum-algorithm: ALG` asks the server to compute that
+ algorithm; the resulting value is returned alongside the response.
+ - When the SDK both names an algorithm AND supplies its value, the
+ server-computed value MUST match the supplied one or the request is
+ rejected with `BadDigest` (HTTP 400).
+
+ Ministack-specific: CRC32C / CRC64NVME require optional native libraries
+ that the "no new dependencies" rule forbids us from adding. Rather than
+ silently accept an unverifiable checksum (which would round-trip on Get
+ without ever being validated against the body — a worse failure mode than
+ refusing the request), we reject the put with a clear error. SHA256 / SHA1
+ / CRC32 work end-to-end.
+
+ Returns ``(checksums_dict, error_response_or_None)``.
+ """
+ provided = {}
+ unverifiable = set()
+ for alg in _S3_CHECKSUM_HEADERS:
+ val = headers.get(f"x-amz-checksum-{alg}")
+ if val:
+ provided[alg.upper()] = val
+ if _compute_s3_checksum(alg.upper(), b"") is None:
+ unverifiable.add(alg.upper())
+
+ sdk_alg_raw = headers.get("x-amz-sdk-checksum-algorithm")
+ if sdk_alg_raw:
+ sdk_key = sdk_alg_raw.upper().replace("_", "")
+ if _compute_s3_checksum(sdk_alg_raw, b"") is None:
+ unverifiable.add(sdk_key)
+
+ if unverifiable:
+ return {}, _error(
+ "InvalidRequest",
+ (
+ f"Checksum algorithm not supported in this ministack build: "
+ f"{', '.join(sorted(unverifiable))}. Supported: SHA256, SHA1, CRC32. "
+ f"CRC32C and CRC64NVME require optional native dependencies that "
+ f"ministack does not bundle; use SHA256 instead, or omit the "
+ f"checksum header."
+ ),
+ 400,
+ )
+
+ checksums = dict(provided)
+ if sdk_alg_raw:
+ sdk_key = sdk_alg_raw.upper().replace("_", "")
+ computed = _compute_s3_checksum(sdk_alg_raw, body)
+ if computed is not None:
+ existing = provided.get(sdk_key)
+ if existing and existing != computed:
+ return {}, _error(
+ "BadDigest",
+ f"The {sdk_key} you specified did not match the calculated checksum.",
+ 400,
+ )
+ checksums[sdk_key] = computed
+ return checksums, None
+
+
+def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "",
+ include_checksums: bool = False) -> dict:
h = {
"Content-Type": obj["content_type"],
"ETag": obj["etag"],
@@ -568,6 +667,18 @@ def _object_response_headers(obj: dict, bucket_name: str = "", key: str = "") ->
hold = _object_legal_hold.get((bucket_name, key))
if hold:
h["x-amz-object-lock-legal-hold"] = hold
+ # AWS only returns x-amz-checksum-* headers when the request opted in via
+ # `x-amz-checksum-mode: ENABLED` — silent on Head/Get otherwise to match
+ # the documented contract and avoid leaking checksums into clients that
+ # didn't ask for them.
+ if include_checksums:
+ stored = obj.get("checksums") or {}
+ for alg, val in stored.items():
+ h[f"x-amz-checksum-{alg.lower()}"] = val
+ if stored:
+ # Single PutObject = FULL_OBJECT; multipart-uploaded objects would
+ # be COMPOSITE — out of scope here.
+ h["x-amz-checksum-type"] = "FULL_OBJECT"
return h
@@ -644,7 +755,7 @@ def _dispatch(
)
if method == "HEAD":
- return _head_object(bucket, key)
+ return _head_object(bucket, key, headers)
if method == "DELETE":
if "uploadId" in query_params:
@@ -1868,8 +1979,12 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
if precondition_err:
return precondition_err
+ checksums, csum_err = _resolve_object_checksums(body, headers)
+ if csum_err:
+ return csum_err
+
etag = f'"{md5_hash(body)}"'
- obj = _build_object_record(body, headers, etag=etag)
+ obj = _build_object_record(body, headers, etag=etag, checksums=checksums)
bucket["objects"][key] = obj
# --- Object Lock headers on PutObject ---
@@ -1908,6 +2023,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
"is_latest": True,
"data": body,
"storage_class": obj.get("storage_class") or "STANDARD",
+ "checksums": obj.get("checksums") or {},
})
# Mark all previous versions as not latest
for v in _object_versions[vkey][:-1]:
@@ -2201,6 +2317,15 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =
"Last-Modified": iso_to_rfc7231(v["last_modified"]),
"x-amz-version-id": v["version_id"],
}
+ # Versioned reads honor `x-amz-checksum-mode: ENABLED` the same
+ # way current-version reads do — the stored per-version
+ # checksums are looked up and surfaced as `x-amz-checksum-*`.
+ if (headers.get("x-amz-checksum-mode") or "").upper() == "ENABLED":
+ stored = v.get("checksums") or {}
+ for alg, val in stored.items():
+ resp_headers[f"x-amz-checksum-{alg.lower()}"] = val
+ if stored:
+ resp_headers["x-amz-checksum-type"] = "FULL_OBJECT"
return 200, resp_headers, v["data"]
return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")
@@ -2213,9 +2338,16 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =
)
obj = bucket["objects"][key]
- resp_headers = _object_response_headers(obj, bucket_name, key)
-
range_header = headers.get("range", "")
+ # AWS returns whole-object checksums only on full-object responses (HTTP
+ # 200). On a 206 Partial Content reply the bytes are a slice, and a
+ # whole-object checksum can't validate them — boto3 raises
+ # `FlexibleChecksumError` if it sees one alongside sliced bytes.
+ checksum_mode_on = (headers.get("x-amz-checksum-mode") or "").upper() == "ENABLED"
+ include_checksums = checksum_mode_on and not range_header
+ resp_headers = _object_response_headers(obj, bucket_name, key,
+ include_checksums=include_checksums)
+
body = _read_body(bucket_name, key, obj)
if range_header:
rng = _parse_range(range_header, obj["size"])
@@ -2248,7 +2380,8 @@ def _range_error_xml(bucket_name: str, key: str) -> Element:
return root
-def _head_object(bucket_name: str, key: str):
+def _head_object(bucket_name: str, key: str, headers: dict | None = None):
+ headers = headers or {}
bucket = _ensure_bucket(bucket_name)
if bucket is None:
return _no_such_bucket(bucket_name)
@@ -2261,7 +2394,9 @@ def _head_object(bucket_name: str, key: str):
)
obj = bucket["objects"][key]
- return 200, _object_response_headers(obj, bucket_name, key), b""
+ include_checksums = (headers.get("x-amz-checksum-mode") or "").upper() == "ENABLED"
+ return 200, _object_response_headers(obj, bucket_name, key,
+ include_checksums=include_checksums), b""
def _delete_object(bucket_name: str, key: str, headers: dict | None = None):
@@ -2416,6 +2551,18 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
new_etag = src_obj["etag"]
last_modified = now_iso()
src_body = _read_body(src_bucket_name, src_key, src_obj)
+ # AWS CopyObject preserves the source's whole-object checksum unless the
+ # caller asks for a different algorithm via `x-amz-checksum-algorithm` /
+ # `x-amz-sdk-checksum-algorithm`. The latter case is handled by the same
+ # resolver as PutObject, against the copied body.
+ dest_checksums = dict(src_obj.get("checksums") or {})
+ if headers.get("x-amz-sdk-checksum-algorithm") or any(
+ headers.get(f"x-amz-checksum-{a}") for a in _S3_CHECKSUM_HEADERS
+ ):
+ resolved, csum_err = _resolve_object_checksums(src_body, headers)
+ if csum_err:
+ return csum_err
+ dest_checksums.update(resolved)
dest_obj = {
"body": src_body,
"content_type": content_type,
@@ -2426,6 +2573,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
"metadata": metadata,
"preserved_headers": preserved,
"storage_class": dest_sc,
+ "checksums": dest_checksums,
}
dest_bucket["objects"][dest_key] = dest_obj
@@ -3834,6 +3982,7 @@ def _persist_object(bucket: str, key: str, obj):
"metadata": obj.get("metadata", {}),
"preserved_headers": obj.get("preserved_headers", {}),
"storage_class": obj.get("storage_class", "STANDARD"),
+ "checksums": obj.get("checksums", {}),
}
_atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)
# Drop body from in-memory record to save RAM
@@ -3994,6 +4143,7 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):
"metadata": meta.get("metadata", {}),
"preserved_headers": meta.get("preserved_headers", {}),
"storage_class": meta.get("storage_class", "STANDARD"),
+ "checksums": meta.get("checksums", {}),
}
diff --git a/tests/conftest.py b/tests/conftest.py
index fcc849a0..336b66a1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -82,20 +82,20 @@ _SERIAL_TESTS = {
# AppSync Lambda-resolver event-shape tests cold-start Lambdas under a 10s
# urlopen timeout (Test 6 spawns two functions). Same cold-start-under-xdist
# flakiness as the apigw Lambda tests above — run them in the serial phase.
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_field_name",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_arguments",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_api_key_header",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_custom_headers_forwarded",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_no_identity_in_api_key_mode",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_identity_from_authorizer",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_not_found_no_crash",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_returns_errors",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_source_empty_for_root",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_event_variables_substituted",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_unhandled_exception_becomes_error",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_authorizer_rejection_identity_null",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_missing_authorizer_degrades",
- "tests/test_appsync_lambda_event.py::test_appsync_lambda_failing_authorizer_degrades",
+ "tests/test_appsync.py::test_appsync_lambda_event_field_name",
+ "tests/test_appsync.py::test_appsync_lambda_event_arguments",
+ "tests/test_appsync.py::test_appsync_lambda_event_api_key_header",
+ "tests/test_appsync.py::test_appsync_lambda_event_custom_headers_forwarded",
+ "tests/test_appsync.py::test_appsync_lambda_event_no_identity_in_api_key_mode",
+ "tests/test_appsync.py::test_appsync_lambda_event_identity_from_authorizer",
+ "tests/test_appsync.py::test_appsync_lambda_not_found_no_crash",
+ "tests/test_appsync.py::test_appsync_lambda_returns_errors",
+ "tests/test_appsync.py::test_appsync_lambda_event_source_empty_for_root",
+ "tests/test_appsync.py::test_appsync_lambda_event_variables_substituted",
+ "tests/test_appsync.py::test_appsync_lambda_unhandled_exception_becomes_error",
+ "tests/test_appsync.py::test_appsync_lambda_authorizer_rejection_returns_unauthorized",
+ "tests/test_appsync.py::test_appsync_lambda_missing_authorizer_returns_unauthorized",
+ "tests/test_appsync.py::test_appsync_lambda_failing_authorizer_returns_unauthorized",
}
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index 4ea82d53..cb806008 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -2,6 +2,7 @@ import io
import json
import os
import time
+import urllib.request
import uuid as _uuid_mod
import zipfile
from urllib.parse import urlparse
@@ -9,6 +10,8 @@ from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
+_ENDPOINT = "http://localhost:4566"
+
def test_appsync_create_and_list_api():
"""Create a GraphQL API and list it."""
@@ -305,3 +308,366 @@ def test_appsync_graphql_empty_query():
assert False, "Should have failed"
except urllib.error.HTTPError as e:
assert e.code == 400
+
+
+# ---------------------------------------------------------------------------
+# AppSync Lambda resolver event shape — verifies full AppSyncResolverEvent is built.
+# ---------------------------------------------------------------------------
+
+def _appsync_lambda_zip(handler_code: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", handler_code)
+ return buf.getvalue()
+
+
+def _appsync_create_lambda(lam, fn_name, handler_code):
+ try:
+ lam.delete_function(FunctionName=fn_name)
+ except Exception:
+ pass
+ lam.create_function(
+ FunctionName=fn_name,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": _appsync_lambda_zip(handler_code)},
+ )
+ return lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]
+
+
+def _appsync_graphql_post(api_url, query, variables=None, headers=None):
+ """Send a GraphQL POST request to the AppSync endpoint."""
+ payload = {"query": query}
+ if variables:
+ payload["variables"] = variables
+ req = urllib.request.Request(
+ api_url,
+ data=json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json", **(headers or {})},
+ method="POST",
+ )
+ with urllib.request.urlopen(req, timeout=10) as r:
+ return json.loads(r.read())
+
+
+def _appsync_setup_api_with_lambda_resolver(appsync, lam, fn_name, handler_code):
+ """Create an AppSync API with API_KEY auth and a Lambda resolver for 'testField'."""
+ fn_arn = _appsync_create_lambda(lam, fn_name, handler_code)
+
+ api = appsync.create_graphql_api(
+ name=f"test-api-{fn_name}",
+ authenticationType="API_KEY",
+ )
+ api_id = api["graphqlApi"]["apiId"]
+ api_key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
+ graphql_url = f"{_ENDPOINT}/v1/apis/{api_id}/graphql"
+
+ appsync.create_data_source(
+ apiId=api_id,
+ name="LambdaDS",
+ type="AWS_LAMBDA",
+ lambdaConfig={"lambdaFunctionArn": fn_arn},
+ )
+ appsync.create_resolver(
+ apiId=api_id,
+ typeName="Query",
+ fieldName="testField",
+ dataSourceName="LambdaDS",
+ kind="UNIT",
+ )
+ return api_id, api_key, graphql_url
+
+
+_APPSYNC_IDENTITY_PROBE_RESOLVER = (
+ "def handler(event, ctx):\n"
+ " return {'hasIdentity': event.get('identity') is not None}\n"
+)
+
+
+def _appsync_setup_lambda_auth_api(appsync, lam, name, authorizer_arn, resolver_code):
+ """Create an AWS_LAMBDA-auth API with the given authorizer ARN and a Lambda resolver."""
+ resolver_arn = _appsync_create_lambda(lam, f"{name}-resolver", resolver_code)
+
+ api = appsync.create_graphql_api(
+ name=name,
+ authenticationType="AWS_LAMBDA",
+ lambdaAuthorizerConfig={"authorizerUri": authorizer_arn},
+ )
+ api_id = api["graphqlApi"]["apiId"]
+ graphql_url = f"{_ENDPOINT}/v1/apis/{api_id}/graphql"
+
+ appsync.create_data_source(
+ apiId=api_id, name="LambdaDS", type="AWS_LAMBDA",
+ lambdaConfig={"lambdaFunctionArn": resolver_arn},
+ )
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="testField",
+ dataSourceName="LambdaDS", kind="UNIT",
+ )
+ return api_id, graphql_url
+
+
+def _appsync_expect_unauthorized(url, query, headers):
+ """A rejected AWS_LAMBDA authorizer must surface as HTTP 401 with an
+ `UnauthorizedException` errors envelope, per the AppSync Developer Guide."""
+ import urllib.error
+
+ req = urllib.request.Request(
+ url,
+ data=json.dumps({"query": query}).encode(),
+ headers={"Content-Type": "application/json", **(headers or {})},
+ method="POST",
+ )
+ try:
+ urllib.request.urlopen(req, timeout=10)
+ except urllib.error.HTTPError as exc:
+ assert exc.code == 401, f"expected 401, got {exc.code}"
+ body = json.loads(exc.read())
+ assert "errors" in body and body["errors"]
+ assert body["errors"][0]["errorType"] == "UnauthorizedException"
+ return body
+ raise AssertionError("expected HTTP 401 but request succeeded")
+
+
+def test_appsync_lambda_event_field_name(appsync, lam):
+ """Lambda event must contain info.fieldName matching the queried GraphQL field."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " return {'fieldName': event.get('info', {}).get('fieldName')}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "field-name-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { fieldName } }", headers={"x-api-key": api_key})
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["fieldName"] == "testField"
+
+
+def test_appsync_lambda_event_arguments(appsync, lam):
+ """Lambda event must contain parsed arguments from the GraphQL query."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " args = event.get('arguments', {})\n"
+ " return {'receivedId': args.get('params', {}).get('id', 'missing')}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "args-test", handler)
+ resp = _appsync_graphql_post(
+ url, 'query { testField(params: {id: "issuer-abc"}) { receivedId } }',
+ headers={"x-api-key": api_key},
+ )
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["receivedId"] == "issuer-abc"
+
+
+def test_appsync_lambda_event_api_key_header(appsync, lam):
+ """The x-api-key header must be in event.request.headers so isApiKeyAuthenticated() works."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " headers = event.get('request', {}).get('headers', {})\n"
+ " return {'hasApiKey': 'x-api-key' in headers}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "api-key-header-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { hasApiKey } }", headers={"x-api-key": api_key})
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["hasApiKey"] is True
+
+
+def test_appsync_lambda_event_custom_headers_forwarded(appsync, lam):
+ """x-request-id, x-session-id, x-user-id, x-workflow, x-process must be in event.request.headers."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " h = event.get('request', {}).get('headers', {})\n"
+ " return {\n"
+ " 'requestId': h.get('x-request-id', ''),\n"
+ " 'sessionId': h.get('x-session-id', ''),\n"
+ " 'userId': h.get('x-user-id', ''),\n"
+ " 'workflow': h.get('x-workflow', ''),\n"
+ " 'process': h.get('x-process', ''),\n"
+ " }\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "custom-headers-test", handler)
+ resp = _appsync_graphql_post(
+ url, "{ testField { requestId sessionId userId workflow process } }",
+ headers={
+ "x-api-key": api_key,
+ "x-request-id": "req-abc-123",
+ "x-session-id": "sess-xyz-456",
+ "x-user-id": "user-789",
+ "x-workflow": "LOGIN",
+ "x-process": "OTP_VERIFY",
+ },
+ )
+ assert "errors" not in resp
+ data = resp["data"]["testField"]
+ assert data["requestId"] == "req-abc-123"
+ assert data["sessionId"] == "sess-xyz-456"
+ assert data["userId"] == "user-789"
+ assert data["workflow"] == "LOGIN"
+ assert data["process"] == "OTP_VERIFY"
+
+
+def test_appsync_lambda_event_no_identity_in_api_key_mode(appsync, lam):
+ """In API_KEY auth mode, event.identity must be absent or null."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " return {'hasIdentity': event.get('identity') is not None}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "no-identity-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { hasIdentity } }", headers={"x-api-key": api_key})
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["hasIdentity"] is False
+
+
+def test_appsync_lambda_event_identity_from_authorizer(appsync, lam):
+ """AWS_LAMBDA auth mode — identity.resolverContext from authorizer is in Lambda event."""
+ authorizer_code = (
+ "def handler(event, ctx):\n"
+ " return {\n"
+ " 'isAuthorized': True,\n"
+ " 'resolverContext': {\n"
+ " 'customId': 'test-user-id',\n"
+ " 'email': '[email protected]',\n"
+ " 'cognitoGroups': 'admin',\n"
+ " }\n"
+ " }\n"
+ )
+ resolver_code = (
+ "def handler(event, ctx):\n"
+ " identity = event.get('identity') or {}\n"
+ " rc = identity.get('resolverContext') or {}\n"
+ " return {\n"
+ " 'customId': rc.get('customId', ''),\n"
+ " 'email': rc.get('email', ''),\n"
+ " }\n"
+ )
+ auth_arn = _appsync_create_lambda(lam, "lambda-authorizer-test", authorizer_code)
+ resolver_arn = _appsync_create_lambda(lam, "lambda-resolver-test", resolver_code)
+
+ api = appsync.create_graphql_api(
+ name="lambda-auth-api",
+ authenticationType="AWS_LAMBDA",
+ lambdaAuthorizerConfig={"authorizerUri": auth_arn},
+ )
+ api_id = api["graphqlApi"]["apiId"]
+ url = f"{_ENDPOINT}/v1/apis/{api_id}/graphql"
+ appsync.create_data_source(
+ apiId=api_id, name="LambdaDS", type="AWS_LAMBDA",
+ lambdaConfig={"lambdaFunctionArn": resolver_arn},
+ )
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="testField",
+ dataSourceName="LambdaDS", kind="UNIT",
+ )
+ resp = _appsync_graphql_post(url, "{ testField { customId email } }",
+ headers={"Authorization": "Bearer fake-jwt-token"})
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["customId"] == "test-user-id"
+ assert resp["data"]["testField"]["email"] == "[email protected]"
+
+
+def test_appsync_lambda_not_found_no_crash(appsync):
+ """If Lambda function doesn't exist in ministack, AppSync returns a response (no crash)."""
+ api = appsync.create_graphql_api(name="lambda-missing-api", authenticationType="API_KEY")
+ api_id = api["graphqlApi"]["apiId"]
+ api_key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
+ appsync.create_data_source(
+ apiId=api_id, name="MissingLambdaDS", type="AWS_LAMBDA",
+ lambdaConfig={"lambdaFunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:does-not-exist"},
+ )
+ appsync.create_resolver(
+ apiId=api_id, typeName="Query", fieldName="testField",
+ dataSourceName="MissingLambdaDS", kind="UNIT",
+ )
+ resp = _appsync_graphql_post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql", "{ testField }",
+ headers={"x-api-key": api_key})
+ assert "data" in resp or "errors" in resp
+
+
+def test_appsync_lambda_returns_errors(appsync, lam):
+ """Lambda returning {errors: ['INTERNAL_SERVER_ERROR']} is passed through correctly."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " return {'errors': ['INTERNAL_SERVER_ERROR'], 'data': None}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "error-response-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { id } }", headers={"x-api-key": api_key})
+ assert resp["data"]["testField"]["errors"] == ["INTERNAL_SERVER_ERROR"]
+
+
+def test_appsync_lambda_event_source_empty_for_root(appsync, lam):
+ """event.source must be {} (empty) for top-level Query fields."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " s = event.get('source')\n"
+ " return {'sourceIsEmpty': s == {} or s is None}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "source-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { sourceIsEmpty } }", headers={"x-api-key": api_key})
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["sourceIsEmpty"] is True
+
+
+def test_appsync_lambda_event_variables_substituted(appsync, lam):
+ """Variables in the query must be resolved to values before the event is built."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " args = event.get('arguments', {})\n"
+ " return {'id': args.get('params', {}).get('id', 'missing')}\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "variables-test", handler)
+ resp = _appsync_graphql_post(
+ url, "query GetTest($id: ID!) { testField(params: {id: $id}) { id } }",
+ variables={"id": "issuer-from-var"},
+ headers={"x-api-key": api_key},
+ )
+ assert "errors" not in resp
+ assert resp["data"]["testField"]["id"] == "issuer-from-var"
+
+
+def test_appsync_lambda_unhandled_exception_becomes_error(appsync, lam):
+ """A Lambda that raises must yield a GraphQL `errors` entry, not fake `data`."""
+ handler = (
+ "def handler(event, ctx):\n"
+ " raise Exception('boom')\n"
+ )
+ _, api_key, url = _appsync_setup_api_with_lambda_resolver(appsync, lam, "raise-test", handler)
+ resp = _appsync_graphql_post(url, "{ testField { id } }", headers={"x-api-key": api_key})
+ field = resp.get("data", {}).get("testField")
+ assert field is None or "errorMessage" not in field
+ assert "errors" in resp or (isinstance(field, dict) and "errors" in field)
+
+
+def test_appsync_lambda_authorizer_rejection_returns_unauthorized(appsync, lam):
+ """AWS_LAMBDA auth — `isAuthorized:false` must reject with `UnauthorizedException` (HTTP 401)."""
+ authorizer = (
+ "def handler(event, ctx):\n"
+ " return {'isAuthorized': False, 'resolverContext': {'should': 'not-leak'}}\n"
+ )
+ auth_arn = _appsync_create_lambda(lam, "authz-reject-test", authorizer)
+ _, url = _appsync_setup_lambda_auth_api(appsync, lam, "authz-reject-api", auth_arn,
+ _APPSYNC_IDENTITY_PROBE_RESOLVER)
+ _appsync_expect_unauthorized(url, "{ testField { hasIdentity } }",
+ headers={"Authorization": "Bearer fake-jwt"})
+
+
+def test_appsync_lambda_missing_authorizer_returns_unauthorized(appsync, lam):
+ """AWS_LAMBDA auth — missing authorizer Lambda must reject with `UnauthorizedException` (HTTP 401)."""
+ _, url = _appsync_setup_lambda_auth_api(
+ appsync, lam, "authz-missing-api",
+ "arn:aws:lambda:us-east-1:000000000000:function:authorizer-does-not-exist",
+ _APPSYNC_IDENTITY_PROBE_RESOLVER,
+ )
+ _appsync_expect_unauthorized(url, "{ testField { hasIdentity } }",
+ headers={"Authorization": "Bearer fake-jwt"})
+
+
+def test_appsync_lambda_failing_authorizer_returns_unauthorized(appsync, lam):
+ """AWS_LAMBDA auth — raising authorizer must reject with `UnauthorizedException` (HTTP 401)."""
+ authorizer = (
+ "def handler(event, ctx):\n"
+ " raise Exception('authorizer boom')\n"
+ )
+ auth_arn = _appsync_create_lambda(lam, "authz-raise-test", authorizer)
+ _, url = _appsync_setup_lambda_auth_api(appsync, lam, "authz-raise-api", auth_arn,
+ _APPSYNC_IDENTITY_PROBE_RESOLVER)
+ _appsync_expect_unauthorized(url, "{ testField { hasIdentity } }",
+ headers={"Authorization": "Bearer fake-jwt"})
diff --git a/tests/test_appsync_lambda_event.py b/tests/test_appsync_lambda_event.py
deleted file mode 100644
index f3ba7592..00000000
--- a/tests/test_appsync_lambda_event.py
+++ /dev/null
@@ -1,425 +0,0 @@
-"""Tests for AppSync Lambda resolver event shape — verifies full AppSyncResolverEvent is built."""
-
-import io
-import json
-import urllib.request
-import zipfile
-
-import pytest
-
-ENDPOINT = "http://localhost:4566"
-
-
-# ── Helpers ───────────────────────────────────────────────────────────────────
-
-def _make_zip(handler_code: str) -> bytes:
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w") as zf:
- zf.writestr("index.py", handler_code)
- return buf.getvalue()
-
-
-def _create_lambda(lam, fn_name, handler_code):
- try:
- lam.delete_function(FunctionName=fn_name)
- except Exception:
- pass
- lam.create_function(
- FunctionName=fn_name,
- Runtime="python3.12",
- Role="arn:aws:iam::000000000000:role/test-role",
- Handler="index.handler",
- Code={"ZipFile": _make_zip(handler_code)},
- )
- return lam.get_function(FunctionName=fn_name)["Configuration"]["FunctionArn"]
-
-
-def _graphql_post(api_url, query, variables=None, headers=None):
- """Send a GraphQL POST request to the AppSync endpoint."""
- payload = {"query": query}
- if variables:
- payload["variables"] = variables
- req = urllib.request.Request(
- api_url,
- data=json.dumps(payload).encode(),
- headers={"Content-Type": "application/json", **(headers or {})},
- method="POST",
- )
- with urllib.request.urlopen(req, timeout=10) as r:
- return json.loads(r.read())
-
-
-def _setup_api_with_lambda_resolver(appsync, lam, fn_name, handler_code):
- """Create an AppSync API with API_KEY auth and a Lambda resolver for 'testField'."""
- fn_arn = _create_lambda(lam, fn_name, handler_code)
-
- api = appsync.create_graphql_api(
- name=f"test-api-{fn_name}",
- authenticationType="API_KEY",
- )
- api_id = api["graphqlApi"]["apiId"]
- api_key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
- # Path-based endpoint: the central router maps only /v1/apis* to AppSync.
- # A bare /graphql POST from this client is routed to S3.
- graphql_url = f"{ENDPOINT}/v1/apis/{api_id}/graphql"
-
- appsync.create_data_source(
- apiId=api_id,
- name="LambdaDS",
- type="AWS_LAMBDA",
- lambdaConfig={"lambdaFunctionArn": fn_arn},
- )
- appsync.create_resolver(
- apiId=api_id,
- typeName="Query",
- fieldName="testField",
- dataSourceName="LambdaDS",
- kind="UNIT",
- )
- return api_id, api_key, graphql_url
-
-
-# Resolver that simply reports whether event.identity was populated — used by the
-# AWS_LAMBDA authorizer degradation tests below.
-_IDENTITY_PROBE_RESOLVER = (
- "def handler(event, ctx):\n"
- " return {'hasIdentity': event.get('identity') is not None}\n"
-)
-
-
-def _setup_lambda_auth_api(appsync, lam, name, authorizer_arn, resolver_code):
- """Create an AWS_LAMBDA-auth API with the given authorizer ARN and a Lambda resolver."""
- resolver_arn = _create_lambda(lam, f"{name}-resolver", resolver_code)
-
- api = appsync.create_graphql_api(
- name=name,
- authenticationType="AWS_LAMBDA",
- lambdaAuthorizerConfig={"authorizerUri": authorizer_arn},
- )
- api_id = api["graphqlApi"]["apiId"]
- graphql_url = f"{ENDPOINT}/v1/apis/{api_id}/graphql"
-
- appsync.create_data_source(
- apiId=api_id, name="LambdaDS", type="AWS_LAMBDA",
- lambdaConfig={"lambdaFunctionArn": resolver_arn},
- )
- appsync.create_resolver(
- apiId=api_id, typeName="Query", fieldName="testField",
- dataSourceName="LambdaDS", kind="UNIT",
- )
- return api_id, graphql_url
-
-
-# ── Test 1: info.fieldName is present in Lambda event ─────────────────────────
-
-def test_appsync_lambda_event_field_name(appsync, lam):
- """Lambda event must contain info.fieldName matching the queried GraphQL field (AWS-standard shape)."""
- handler = (
- "def handler(event, ctx):\n"
- " # Return the field-value dict directly: ministack places the handler's\n"
- " # return value verbatim under data.<fieldName> (no body/data unwrap).\n"
- " return {'fieldName': event.get('info', {}).get('fieldName')}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "field-name-test", handler)
-
- resp = _graphql_post(url, "{ testField { fieldName } }", headers={"x-api-key": api_key})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["fieldName"] == "testField"
-
-
-# ── Test 2: arguments are passed correctly ────────────────────────────────────
-
-def test_appsync_lambda_event_arguments(appsync, lam):
- """Lambda event must contain parsed arguments from the GraphQL query."""
- handler = (
- "def handler(event, ctx):\n"
- " args = event.get('arguments', {})\n"
- " return {'receivedId': args.get('params', {}).get('id', 'missing')}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "args-test", handler)
-
- resp = _graphql_post(
- url,
- 'query { testField(params: {id: "issuer-abc"}) { receivedId } }',
- headers={"x-api-key": api_key},
- )
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["receivedId"] == "issuer-abc"
-
-
-# ── Test 3: request.headers.x-api-key is forwarded ───────────────────────────
-
-def test_appsync_lambda_event_api_key_header(appsync, lam):
- """The x-api-key header must be in event.request.headers so isApiKeyAuthenticated() works."""
- handler = (
- "def handler(event, ctx):\n"
- " headers = event.get('request', {}).get('headers', {})\n"
- " return {'hasApiKey': 'x-api-key' in headers}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "api-key-header-test", handler)
-
- resp = _graphql_post(url, "{ testField { hasApiKey } }", headers={"x-api-key": api_key})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["hasApiKey"] is True
-
-
-# ── Test 4: all custom headers forwarded ─────────────────────────────────────
-
-def test_appsync_lambda_event_custom_headers_forwarded(appsync, lam):
- """x-request-id, x-session-id, x-user-id, x-workflow, x-process must be in event.request.headers."""
- handler = (
- "def handler(event, ctx):\n"
- " headers = event.get('request', {}).get('headers', {})\n"
- " return {\n"
- " 'requestId': headers.get('x-request-id', ''),\n"
- " 'sessionId': headers.get('x-session-id', ''),\n"
- " 'userId': headers.get('x-user-id', ''),\n"
- " 'workflow': headers.get('x-workflow', ''),\n"
- " 'process': headers.get('x-process', ''),\n"
- " }\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "custom-headers-test", handler)
-
- resp = _graphql_post(url, "{ testField { requestId sessionId userId workflow process } }", headers={
- "x-api-key": api_key,
- "x-request-id": "req-abc-123",
- "x-session-id": "sess-xyz-456",
- "x-user-id": "user-789",
- "x-workflow": "LOGIN",
- "x-process": "OTP_VERIFY",
- })
-
- assert "errors" not in resp
- data = resp["data"]["testField"]
- assert data["requestId"] == "req-abc-123"
- assert data["sessionId"] == "sess-xyz-456"
- assert data["userId"] == "user-789"
- assert data["workflow"] == "LOGIN"
- assert data["process"] == "OTP_VERIFY"
-
-
-# ── Test 5: identity is absent in API_KEY mode ───────────────────────────────
-
-def test_appsync_lambda_event_no_identity_in_api_key_mode(appsync, lam):
- """In API_KEY auth mode, event.identity must be absent or null."""
- handler = (
- "def handler(event, ctx):\n"
- " return {'hasIdentity': event.get('identity') is not None}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "no-identity-test", handler)
-
- resp = _graphql_post(url, "{ testField { hasIdentity } }", headers={"x-api-key": api_key})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["hasIdentity"] is False
-
-
-# ── Test 6: Lambda authorizer sets identity.resolverContext ──────────────────
-
-def test_appsync_lambda_event_identity_from_authorizer(appsync, lam):
- """AWS_LAMBDA auth mode — identity.resolverContext from authorizer is in Lambda event."""
- authorizer_code = (
- "def handler(event, ctx):\n"
- " return {\n"
- " 'isAuthorized': True,\n"
- " 'resolverContext': {\n"
- " 'customId': 'test-user-id',\n"
- " 'email': '[email protected]',\n"
- " 'cognitoGroups': 'admin',\n"
- " }\n"
- " }\n"
- )
- resolver_code = (
- "def handler(event, ctx):\n"
- " identity = event.get('identity') or {}\n"
- " rc = identity.get('resolverContext') or {}\n"
- " return {\n"
- " 'customId': rc.get('customId', ''),\n"
- " 'email': rc.get('email', ''),\n"
- " }\n"
- )
- auth_arn = _create_lambda(lam, "lambda-authorizer-test", authorizer_code)
- resolver_arn = _create_lambda(lam, "lambda-resolver-test", resolver_code)
-
- api = appsync.create_graphql_api(
- name="lambda-auth-api",
- authenticationType="AWS_LAMBDA",
- lambdaAuthorizerConfig={"authorizerUri": auth_arn},
- )
- api_id = api["graphqlApi"]["apiId"]
- url = f"{ENDPOINT}/v1/apis/{api_id}/graphql"
-
- appsync.create_data_source(
- apiId=api_id, name="LambdaDS", type="AWS_LAMBDA",
- lambdaConfig={"lambdaFunctionArn": resolver_arn},
- )
- appsync.create_resolver(
- apiId=api_id, typeName="Query", fieldName="testField",
- dataSourceName="LambdaDS", kind="UNIT",
- )
-
- resp = _graphql_post(url, "{ testField { customId email } }", headers={
- "Authorization": "Bearer fake-jwt-token",
- })
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["customId"] == "test-user-id"
- assert resp["data"]["testField"]["email"] == "[email protected]"
-
-
-# ── Test 7: Lambda not found — graceful fallback, no HTTP 500 ────────────────
-
-def test_appsync_lambda_not_found_no_crash(appsync):
- """If Lambda function doesn't exist in ministack, AppSync returns a response (no crash)."""
- api = appsync.create_graphql_api(name="lambda-missing-api", authenticationType="API_KEY")
- api_id = api["graphqlApi"]["apiId"]
- api_key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
-
- appsync.create_data_source(
- apiId=api_id, name="MissingLambdaDS", type="AWS_LAMBDA",
- lambdaConfig={"lambdaFunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:does-not-exist"},
- )
- appsync.create_resolver(
- apiId=api_id, typeName="Query", fieldName="testField",
- dataSourceName="MissingLambdaDS", kind="UNIT",
- )
-
- # Should not raise an exception — returns a response (possibly with null data)
- resp = _graphql_post(f"{ENDPOINT}/v1/apis/{api_id}/graphql", "{ testField }", headers={"x-api-key": api_key})
- assert "data" in resp or "errors" in resp # any response is OK — just no crash
-
-
-# ── Test 8: Lambda returns errors array ──────────────────────────────────────
-
-def test_appsync_lambda_returns_errors(appsync, lam):
- """Lambda returning {errors: ['INTERNAL_SERVER_ERROR']} is passed through correctly."""
- handler = (
- "def handler(event, ctx):\n"
- " # The resolver's OWN error envelope, returned directly. ministack passes\n"
- " # it through under data.testField. This is NOT a Lambda execution\n"
- " # failure (see Test 11 for that path).\n"
- " return {'errors': ['INTERNAL_SERVER_ERROR'], 'data': None}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "error-response-test", handler)
-
- resp = _graphql_post(url, "{ testField { id } }", headers={"x-api-key": api_key})
-
- # Errors should be surfaced, not cause HTTP 500
- assert resp["data"]["testField"]["errors"] == ["INTERNAL_SERVER_ERROR"]
-
-
-# ── Test 9: source is empty dict for root fields ──────────────────────────────
-
-def test_appsync_lambda_event_source_empty_for_root(appsync, lam):
- """event.source must be {} (empty) for top-level Query fields."""
- handler = (
- "def handler(event, ctx):\n"
- " source = event.get('source')\n"
- " return {'sourceIsEmpty': source == {} or source is None}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "source-test", handler)
-
- resp = _graphql_post(url, "{ testField { sourceIsEmpty } }", headers={"x-api-key": api_key})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["sourceIsEmpty"] is True
-
-
-# ── Test 10: GraphQL variables are substituted before Lambda invocation ───────
-
-def test_appsync_lambda_event_variables_substituted(appsync, lam):
- """Variables in the query must be resolved to values before the event is built."""
- handler = (
- "def handler(event, ctx):\n"
- " args = event.get('arguments', {})\n"
- " params = args.get('params', {})\n"
- " # Should be 'issuer-from-var', not '$id'\n"
- " return {'id': params.get('id', 'missing')}\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "variables-test", handler)
-
- resp = _graphql_post(
- url,
- "query GetTest($id: ID!) { testField(params: {id: $id}) { id } }",
- variables={"id": "issuer-from-var"},
- headers={"x-api-key": api_key},
- )
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["id"] == "issuer-from-var"
-
-
-# ── Test 11: unhandled Lambda exception surfaces as a GraphQL error ───────────
-
-def test_appsync_lambda_unhandled_exception_becomes_error(appsync, lam):
- """A Lambda that raises must yield a GraphQL `errors` entry, not fake `data`."""
- handler = (
- "def handler(event, ctx):\n"
- " raise Exception('boom')\n"
- )
- api_id, api_key, url = _setup_api_with_lambda_resolver(appsync, lam, "raise-test", handler)
-
- resp = _graphql_post(url, "{ testField { id } }", headers={"x-api-key": api_key})
-
- # The RIE error payload (errorMessage/errorType) must NOT leak through as data.
- field = resp.get("data", {}).get("testField")
- assert field is None or "errorMessage" not in field
- # The failure is surfaced as an errors entry (top-level or under the field).
- assert "errors" in resp or (isinstance(field, dict) and "errors" in field)
-
-
-# ── Test 12: authorizer rejection (isAuthorized:false) → identity null ────────
-
-def test_appsync_lambda_authorizer_rejection_identity_null(appsync, lam):
- """AWS_LAMBDA auth — an authorizer returning isAuthorized:false must NOT block the
- request: it proceeds (HTTP 200) with event.identity null, and the rejecting
- authorizer's resolverContext must NOT leak into the resolver."""
- authorizer = (
- "def handler(event, ctx):\n"
- " return {'isAuthorized': False, 'resolverContext': {'should': 'not-leak'}}\n"
- )
- auth_arn = _create_lambda(lam, "authz-reject-test", authorizer)
- _, url = _setup_lambda_auth_api(appsync, lam, "authz-reject-api", auth_arn, _IDENTITY_PROBE_RESOLVER)
-
- resp = _graphql_post(url, "{ testField { hasIdentity } }", headers={"Authorization": "Bearer fake-jwt"})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["hasIdentity"] is False
-
-
-# ── Test 13: missing authorizer Lambda → graceful fallback ────────────────────
-
-def test_appsync_lambda_missing_authorizer_degrades(appsync, lam):
- """AWS_LAMBDA auth — a lambdaAuthorizerConfig.authorizerUri pointing at a function
- that does not exist must degrade gracefully (HTTP 200, identity null), not crash."""
- _, url = _setup_lambda_auth_api(
- appsync, lam, "authz-missing-api",
- "arn:aws:lambda:us-east-1:000000000000:function:authorizer-does-not-exist",
- _IDENTITY_PROBE_RESOLVER,
- )
-
- resp = _graphql_post(url, "{ testField { hasIdentity } }", headers={"Authorization": "Bearer fake-jwt"})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["hasIdentity"] is False
-
-
-# ── Test 14: failing (raising) authorizer Lambda → graceful fallback ──────────
-
-def test_appsync_lambda_failing_authorizer_degrades(appsync, lam):
- """AWS_LAMBDA auth — an authorizer that raises must be caught (HTTP 200, identity
- null), not surface as an HTTP 500 / GraphQL error."""
- authorizer = (
- "def handler(event, ctx):\n"
- " raise Exception('authorizer boom')\n"
- )
- auth_arn = _create_lambda(lam, "authz-raise-test", authorizer)
- _, url = _setup_lambda_auth_api(appsync, lam, "authz-raise-api", auth_arn, _IDENTITY_PROBE_RESOLVER)
-
- resp = _graphql_post(url, "{ testField { hasIdentity } }", headers={"Authorization": "Bearer fake-jwt"})
-
- assert "errors" not in resp
- assert resp["data"]["testField"]["hasIdentity"] is False
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 8e95f457..7d3b2cb9 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1448,6 +1448,129 @@ def test_cfn_appconfig_application(cfn, appconfig_client):
)
+def test_cfn_appconfig_full_stack(cfn, appconfig_client):
+ """Issue #832: end-to-end AppConfig CFN stack — Application + Environment +
+ ConfigurationProfile + HostedConfigurationVersion + DeploymentStrategy +
+ Deployment, with Ref / Fn::GetAtt cross-references."""
+ template = json.dumps({
+ "Resources": {
+ "App": {
+ "Type": "AWS::AppConfig::Application",
+ "Properties": {"Name": "cfn-832-app"},
+ },
+ "Env": {
+ "Type": "AWS::AppConfig::Environment",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "Name": "cfn-832-env",
+ "Description": "from cfn",
+ "Tags": [{"Key": "stage", "Value": "test"}],
+ },
+ },
+ "Profile": {
+ "Type": "AWS::AppConfig::ConfigurationProfile",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "Name": "cfn-832-profile",
+ "LocationUri": "hosted",
+ "Type": "AWS.Freeform",
+ },
+ },
+ "HCV": {
+ "Type": "AWS::AppConfig::HostedConfigurationVersion",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "ConfigurationProfileId": {"Ref": "Profile"},
+ "Content": '{"flag":true}',
+ "ContentType": "application/json",
+ },
+ },
+ "Strategy": {
+ "Type": "AWS::AppConfig::DeploymentStrategy",
+ "Properties": {
+ "Name": "cfn-832-strategy",
+ "DeploymentDurationInMinutes": 0,
+ "GrowthFactor": 100,
+ "ReplicateTo": "NONE",
+ },
+ },
+ "Deploy": {
+ "Type": "AWS::AppConfig::Deployment",
+ "Properties": {
+ "ApplicationId": {"Ref": "App"},
+ "EnvironmentId": {"Ref": "Env"},
+ "ConfigurationProfileId": {"Ref": "Profile"},
+ "DeploymentStrategyId": {"Ref": "Strategy"},
+ "ConfigurationVersion": {"Fn::GetAtt": ["HCV", "VersionNumber"]},
+ "Tags": [{"Key": "owner", "Value": "cfn-832"}],
+ },
+ },
+ },
+ })
+ cfn.create_stack(StackName="cfn-832", TemplateBody=template)
+ _wait_stack(cfn, "cfn-832")
+
+ try:
+ # Application
+ app = next(a for a in appconfig_client.list_applications()["Items"]
+ if a["Name"] == "cfn-832-app")
+ app_id = app["Id"]
+
+ # Environment
+ envs = appconfig_client.list_environments(ApplicationId=app_id)["Items"]
+ env = next(e for e in envs if e["Name"] == "cfn-832-env")
+ assert env["Description"] == "from cfn"
+
+ # ConfigurationProfile
+ profiles = appconfig_client.list_configuration_profiles(ApplicationId=app_id)["Items"]
+ profile = next(p for p in profiles if p["Name"] == "cfn-832-profile")
+ assert profile["LocationUri"] == "hosted"
+
+ # HostedConfigurationVersion — version number 1 for the first one.
+ hcvs = appconfig_client.list_hosted_configuration_versions(
+ ApplicationId=app_id, ConfigurationProfileId=profile["Id"],
+ )["Items"]
+ assert any(h["VersionNumber"] == 1 for h in hcvs)
+
+ # DeploymentStrategy
+ strategies = appconfig_client.list_deployment_strategies()["Items"]
+ strategy = next(s for s in strategies if s["Name"] == "cfn-832-strategy")
+ assert strategy["DeploymentDurationInMinutes"] == 0
+ assert strategy["ReplicateTo"] == "NONE"
+
+ # Deployment — uses Fn::GetAtt HCV.VersionNumber as ConfigurationVersion.
+ deployments = appconfig_client.list_deployments(
+ ApplicationId=app_id, EnvironmentId=env["Id"],
+ )["Items"]
+ assert len(deployments) == 1
+ # Fn::GetAtt HCV.VersionNumber resolves to the int 1; the Deployment
+ # stores whatever the engine hands the provisioner, so accept either
+ # form when asserting the wiring.
+ assert str(deployments[0]["ConfigurationVersion"]) == "1"
+ assert deployments[0]["State"] == "COMPLETE"
+
+ # Deployment Tags are stored and resolvable via ListTagsForResource.
+ deploy_arn = (
+ f"arn:aws:appconfig:us-east-1:000000000000:application/{app_id}/"
+ f"environment/{env['Id']}/deployment/{deployments[0]['DeploymentNumber']}"
+ )
+ tags = appconfig_client.list_tags_for_resource(ResourceArn=deploy_arn)["Tags"]
+ assert tags.get("owner") == "cfn-832"
+
+ # CFN-side: every logical resource resolved to a physical id.
+ resources = cfn.describe_stack_resources(StackName="cfn-832")["StackResources"]
+ by_logical = {r["LogicalResourceId"]: r["PhysicalResourceId"] for r in resources}
+ for logical in ("App", "Env", "Profile", "HCV", "Strategy", "Deploy"):
+ assert by_logical.get(logical), f"{logical} has no PhysicalResourceId"
+ finally:
+ cfn.delete_stack(StackName="cfn-832")
+ _wait_stack(cfn, "cfn-832")
+
+ # Post-delete: app is gone (cascade also wipes children).
+ apps_after = appconfig_client.list_applications()["Items"]
+ assert not any(a["Name"] == "cfn-832-app" for a in apps_after)
+
+
def test_cfn_lambda_nodejs_inline_zip(cfn, lam):
"""CFN inline ZipFile with Node.js runtime should write index.js, not index.py."""
template = json.dumps({
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 8ffab220..1d743bab 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -2616,3 +2616,164 @@ def test_s3_put_object_acl_xml_body(s3):
assert perms == ["FULL_CONTROL", "READ"]
s3.delete_object(Bucket=bucket, Key="k")
s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_put_object_with_sha256_checksum_roundtrips(s3):
+ """PutObject + ChecksumAlgorithm=SHA256 must be retrievable via
+ GetObject(ChecksumMode='ENABLED'). Issue #831."""
+ import base64
+ import hashlib
+
+ bucket = "checksum-sha256-bucket"
+ s3.create_bucket(Bucket=bucket)
+ body = b"hello checksum world" * 64
+ expected = base64.b64encode(hashlib.sha256(body).digest()).decode()
+
+ s3.put_object(Bucket=bucket, Key="k", Body=body, ChecksumAlgorithm="SHA256")
+
+ head = s3.head_object(Bucket=bucket, Key="k", ChecksumMode="ENABLED")
+ assert head["ChecksumSHA256"] == expected
+
+ got = s3.get_object(Bucket=bucket, Key="k", ChecksumMode="ENABLED")
+ assert got["ChecksumSHA256"] == expected
+ assert got["Body"].read() == body
+
+ s3.delete_object(Bucket=bucket, Key="k")
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_put_object_with_explicit_sha256_value_validated(s3):
+ """PutObject with both ChecksumAlgorithm + ChecksumSHA256: the supplied
+ value must match the server-computed one (BadDigest otherwise)."""
+ import base64
+ import hashlib
+
+ from botocore.exceptions import ClientError
+
+ bucket = "checksum-validate-bucket"
+ s3.create_bucket(Bucket=bucket)
+ body = b"trust but verify"
+ good = base64.b64encode(hashlib.sha256(body).digest()).decode()
+
+ # Matching value → accepted.
+ s3.put_object(Bucket=bucket, Key="ok", Body=body,
+ ChecksumAlgorithm="SHA256", ChecksumSHA256=good)
+ head = s3.head_object(Bucket=bucket, Key="ok", ChecksumMode="ENABLED")
+ assert head["ChecksumSHA256"] == good
+
+ # Mismatched value → BadDigest.
+ bad = base64.b64encode(hashlib.sha256(b"tampered").digest()).decode()
+ with pytest.raises(ClientError) as exc:
+ s3.put_object(Bucket=bucket, Key="bad", Body=body,
+ ChecksumAlgorithm="SHA256", ChecksumSHA256=bad)
+ assert exc.value.response["Error"]["Code"] == "BadDigest"
+
+ s3.delete_object(Bucket=bucket, Key="ok")
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_versioned_get_returns_stored_checksum(s3):
+ """A versioned GetObject(?versionId=X) with ChecksumMode=ENABLED must
+ return the per-version checksum that was stored at put time. Issue #831
+ in-scope follow-up: the original fix added checksums to the current-version
+ path; the versioned-read branch had its own early-return."""
+ import base64
+ import hashlib
+
+ bucket = "checksum-versioned-bucket"
+ s3.create_bucket(Bucket=bucket)
+ s3.put_bucket_versioning(
+ Bucket=bucket,
+ VersioningConfiguration={"Status": "Enabled"},
+ )
+
+ body_a = b"version A body"
+ body_b = b"version B body - different bytes entirely"
+ expected_a = base64.b64encode(hashlib.sha256(body_a).digest()).decode()
+ expected_b = base64.b64encode(hashlib.sha256(body_b).digest()).decode()
+
+ pa = s3.put_object(Bucket=bucket, Key="k", Body=body_a, ChecksumAlgorithm="SHA256")
+ pb = s3.put_object(Bucket=bucket, Key="k", Body=body_b, ChecksumAlgorithm="SHA256")
+ va = pa["VersionId"]
+ vb = pb["VersionId"]
+ assert va != vb
+
+ got_a = s3.get_object(Bucket=bucket, Key="k", VersionId=va, ChecksumMode="ENABLED")
+ got_b = s3.get_object(Bucket=bucket, Key="k", VersionId=vb, ChecksumMode="ENABLED")
+ assert got_a["ChecksumSHA256"] == expected_a
+ assert got_b["ChecksumSHA256"] == expected_b
+ assert got_a["Body"].read() == body_a
+ assert got_b["Body"].read() == body_b
+
+ s3.delete_object(Bucket=bucket, Key="k", VersionId=va)
+ s3.delete_object(Bucket=bucket, Key="k", VersionId=vb)
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_put_object_rejects_unsupported_crc32c_explicitly(s3):
+ """CRC32C requires an optional native library ministack doesn't bundle.
+ Rather than silently accept-without-validation, the put must fail loudly
+ so clients see the gap. Issue #831 follow-up: no silent failures."""
+ import base64
+ import os
+
+ from botocore.exceptions import ClientError
+
+ bucket = "checksum-crc32c-reject-bucket"
+ s3.create_bucket(Bucket=bucket)
+ fake_crc32c = base64.b64encode(os.urandom(4)).decode()
+ with pytest.raises(ClientError) as exc:
+ s3.put_object(
+ Bucket=bucket, Key="k", Body=b"x",
+ ChecksumAlgorithm="CRC32C",
+ ChecksumCRC32C=fake_crc32c,
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidRequest"
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_s3_copy_object_preserves_source_checksum(s3):
+ """CopyObject must propagate the source's stored checksum to the
+ destination so GetObject(dest, ChecksumMode='ENABLED') returns the same
+ SHA256 as the source. Issue #831 in-scope follow-up."""
+ import base64
+ import hashlib
+
+ src_bucket = "checksum-copy-src"
+ dst_bucket = "checksum-copy-dst"
+ s3.create_bucket(Bucket=src_bucket)
+ s3.create_bucket(Bucket=dst_bucket)
+ body = b"copy me with my checksum intact"
+ expected = base64.b64encode(hashlib.sha256(body).digest()).decode()
+
+ s3.put_object(Bucket=src_bucket, Key="k", Body=body, ChecksumAlgorithm="SHA256")
+ s3.copy_object(
+ Bucket=dst_bucket, Key="k",
+ CopySource={"Bucket": src_bucket, "Key": "k"},
+ )
+ got = s3.get_object(Bucket=dst_bucket, Key="k", ChecksumMode="ENABLED")
+ assert got["ChecksumSHA256"] == expected
+
+ s3.delete_object(Bucket=src_bucket, Key="k")
+ s3.delete_object(Bucket=dst_bucket, Key="k")
+ s3.delete_bucket(Bucket=src_bucket)
+ s3.delete_bucket(Bucket=dst_bucket)
+
+
+def test_s3_put_object_with_crc32_checksum_roundtrips(s3):
+ """CRC32 is the other stdlib-supported algorithm — verify the same path."""
+ import base64
+ import struct
+ import zlib
+
+ bucket = "checksum-crc32-bucket"
+ s3.create_bucket(Bucket=bucket)
+ body = b"crc32 payload"
+ expected = base64.b64encode(struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)).decode()
+
+ s3.put_object(Bucket=bucket, Key="k", Body=body, ChecksumAlgorithm="CRC32")
+ got = s3.get_object(Bucket=bucket, Key="k", ChecksumMode="ENABLED")
+ assert got["ChecksumCRC32"] == expected
+
+ s3.delete_object(Bucket=bucket, Key="k")
+ s3.delete_bucket(Bucket=bucket)