Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(signer): CloudFormation signing profiles and profile permissions (#2039)
iot-rocketb8f44fe95ffa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e39ae84..7d3a02fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **CloudFormation — enum properties are validated before provisioning** — a template value outside an enum of the resource schema was only refused by the resource's own create, after the resources before it existed. Such a value, literal or from a parameter, now fails the create before anything is provisioned, as AWS does: one stack `CREATE_FAILED` event "Validation failed with N error(s). ..." with `DetailedStatus` `VALIDATION_FAILED`, then `ROLLBACK_IN_PROGRESS` and `ROLLBACK_COMPLETE`, with no resource event. `DescribeStackEvents` returns `DetailedStatus`. `AWS::Signer::SigningProfile` `PlatformId` is the first property checked. Contributed by @iot-rocket.+- **Signer — CloudFormation `AWS::Signer::SigningProfile` and `AWS::Signer::ProfilePermission`, profile permissions and `CancelSigningProfile`** — a template with either type was refused as an unrecognized resource type, and the profile permission API and `CancelSigningProfile` had no route. Both types now provision as AWS does: the profile's `Ref` is its ARN with `Arn`, `ProfileName`, `ProfileVersion` and `ProfileVersionArn` attributes, a generated name is `<LogicalId>_` plus 12 letters and digits, `Tags` (with the stack and `aws:cloudformation:` tags) update in place, a `PlatformId` or `SignatureValidityPeriod` change replaces the profile, a delete cancels it, and a `PlatformId` outside the schema's two values fails the resource with AWS's enum message; the permission's `Ref` is `<StatementId>|<ProfileName>`. `AddProfilePermission`, `ListProfilePermissions` and `RemoveProfilePermission` follow the revision id rules, error codes, 2000-byte policy limit and `policySizeBytes` measured on AWS, a canceled profile keeps its name and its permissions, `PutSigningProfile` refuses a name that is already taken, and `GetSigningProfile` reports the 135-month default validity period. Contributed by @iot-rocket.- **CloudFormation — `AWS::IoT::Thing`, `AWS::IoT::Certificate`, `AWS::IoT::ThingPrincipalAttachment` and `AWS::IoT::PolicyPrincipalAttachment`** — a template using any of them failed with `Unrecognized resource types`. They now provision onto the IoT registry as AWS does: `Ref` and `Fn::GetAtt` return AWS's values (`{name}|{principal}` for the attachments), `AttributePayload` and `Status` update in place, the create-only properties replace the resource, a certificate is deactivated before its delete, a thing or certificate that still has an attachment made outside the stack fails its delete with the service's message, and a `ThingName` that already exists fails the create instead of adopting the thing. A certificate comes from `CertificateSigningRequest`, from `CertificatePem` with `CACertificatePem`, or from `CertificatePem` alone in `SNI_ONLY` mode. Thing and certificate can be imported. Contributed by @iot-rocket.- **IoT — `CreateCertificateFromCsr`** — the operation was missing: `POST /certificates` answered `Unsupported IoT path`. It now signs the CSR with the local CA, as AWS signs it with its own: the certificate keeps the CSR's subject and public key and is `INACTIVE` unless `setAsActive`, and a CSR that does not parse or verify, or whose key is not RSA of at least 2048 bits or EC on P-256, P-384 or P-521, gets `InvalidRequestException` `CSR violates constraints`. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 2c1a0347..b2ac7769 100644--- a/README.md+++ b/README.md@@ -588,6 +588,8 @@ subnet = ec2.create_subnet(| `AWS::SES::EmailIdentity` | Identity | EmailIdentity || `AWS::SES::ConfigurationSet` | Configuration set name | None || `AWS::SES::ConfigurationSetEventDestination` | Event destination ID | Id |+| `AWS::Signer::SigningProfile` | Profile ARN | Arn, ProfileName, ProfileVersion, ProfileVersionArn |+| `AWS::Signer::ProfilePermission` | `<statement id>\|<profile name>` | — || `AWS::WAFv2::WebACL` | WebACL ID | Arn, Id || `AWS::CloudFront::Distribution` | Distribution ID | Arn, DomainName, Id || `AWS::CloudWatch::Alarm` | Alarm name | Arn |diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex ebc18e55..a15d18ac 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1246,12 +1246,14 @@ def extract_resource_arn(service: str, method: str, path: str,return "*"if service == "signer":- # StartSigningJob and GetSigningProfile are scoped to the profile,+ # StartSigningJob, GetSigningProfile, CancelSigningProfile and the+ # three profile-permission actions are scoped to the profile,# DescribeSigningJob to the job; ListSigningJobs and PutSigningProfile# carry no resource (Service Authorization Reference). The ARNs put a# `/` before the resource type: arn:aws:signer:r:a:/signing-profiles/nparts = [p for p in path.split("/") if p]- if parts and parts[0] == "signing-profiles" and len(parts) > 1 and method == "GET":+ if (parts and parts[0] == "signing-profiles" and len(parts) > 1+ and not (method == "PUT" and len(parts) == 2)):return f"arn:aws:signer:{region}:{account_id}:/signing-profiles/{parts[1]}"if parts and parts[0] == "signing-jobs":if len(parts) > 1:diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex f82d8c85..a1b551bf 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -590,7 +590,9 @@ def _describe_stack_events(params):f"<ResourceStatusReason>{_esc(e.get('ResourceStatusReason', ''))}</ResourceStatusReason>"f"<Timestamp>{e.get('Timestamp', '')}</Timestamp>"f"{token_xml}"- "</member>"+ + (f"<DetailedStatus>{e['DetailedStatus']}</DetailedStatus>"+ if e.get("DetailedStatus") else "")+ + "</member>")return _xml(200, "DescribeStackEventsResponse",diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex e77830c7..79acd180 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -754,6 +754,12 @@ _CUSTOM_NAME_REPLACEMENT = {"name": "TopicName","exists": "Topic creation failed because the topic already exists",},+ # Measured on an account: a SignatureValidityPeriod change under a kept+ # ProfileName, and an Action change under a kept StatementId and+ # ProfileName (the permission's identity), both fail with the refusal+ # sentence naming the physical id.+ "AWS::Signer::SigningProfile": {"name": "ProfileName"},+ "AWS::Signer::ProfilePermission": {"name": ("StatementId", "ProfileName")},# "If you specify a name, you cannot perform updates that require# replacement of this resource, but you can perform other updates"# (aws-resource-elasticloadbalancingv2-loadbalancer), which is this rule@@ -854,9 +860,16 @@ def _custom_named_replacement_error(resource_type, old_props, new_props,def _kept_custom_name(resource_type, old_props, new_props):- """The explicit name an update keeps unchanged, else None."""+ """The explicit name an update keeps unchanged, else None. A ``name``+ tuple is a name made of several properties, kept only when all are."""spec = _CUSTOM_NAME_REPLACEMENT.get(resource_type)- name = old_props.get(spec["name"]) if spec else None+ if not spec:+ return None+ if isinstance(spec["name"], tuple):+ names = [old_props.get(p) for p in spec["name"]]+ kept = all(names) and names == [new_props.get(p) for p in spec["name"]]+ return "|".join(str(n) for n in names) if kept else None+ name = old_props.get(spec["name"])return name if name and name == new_props.get(spec["name"]) else None@@ -1139,6 +1152,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {"AWS::ServiceDiscovery::PrivateDnsNamespace": ("Tags", "list"),"AWS::ServiceDiscovery::PublicDnsNamespace": ("Tags", "list"),"AWS::ServiceDiscovery::Service": ("Tags", "list"),+ "AWS::Signer::SigningProfile": ("Tags", "list"),"AWS::StepFunctions::StateMachine": ("Tags", "list"),}@@ -10485,6 +10499,145 @@ def _ses_configuration_set_event_destination_delete(physical_id, props):record.get("EventDestinations", {}).pop(dest_name, None)+# ---------------------------------------------------------------------------+# Signer SigningProfile and ProfilePermission+# ---------------------------------------------------------------------------++# The PlatformId enum of the resource schema (describe-type, 2026-10-05).+# There is no SigningMaterial property, so no template reaches the IoT+# platform, whose profiles need a certificate.+_SIGNER_CFN_PLATFORMS = ("AWSLambda-SHA384-ECDSA", "Notation-OCI-SHA384-ECDSA")++# Property enums of the resource schemas. AWS checks them before it+# provisions anything (pre-deployment PROPERTY_VALIDATION): the stack fails+# with no resource created, also when the value comes from a parameter.+_PROPERTY_ENUMS = {+ "AWS::Signer::SigningProfile": {"PlatformId": _SIGNER_CFN_PLATFORMS},+}+++def _property_enum_errors(resource_type, props):+ """``(property, reason)`` for each value outside its schema enum, with+ AWS's ValidationStatusReason."""+ return [+ (prop, f"{props[prop]} is not a valid enum value. Supported values: "+ f"[{', '.join(allowed)}]")+ for prop, allowed in _PROPERTY_ENUMS.get(resource_type, {}).items()+ if isinstance(props.get(prop), str) and props[prop] not in allowed+ ]+++def _signer_raise_on_error(resp, resource_type):+ if resp[0] >= 400:+ try:+ message = json.loads(resp[2]).get("message")+ except (ValueError, AttributeError):+ message = None+ raise ValueError(message or f"{resource_type} failed: {resp[2]!r}")+++def _signer_profile_attrs(profile):+ return {+ "Arn": profile["arn"],+ "ProfileName": profile["profileName"],+ "ProfileVersion": profile["profileVersion"],+ "ProfileVersionArn": profile["profileVersionArn"],+ }+++def _signer_profile_name_from_arn(physical_id):+ return str(physical_id).rsplit("/signing-profiles/", 1)[-1]+++def _signer_signing_profile_create(logical_id, props, stack_name):+ """Ref is the profile ARN. Without a ProfileName the name is+ ``<LogicalId>_<12 random letters and digits>`` (measured: Prof_s3JMHz2XvtHK).+ The suffix is random, not hashed from the stack: a canceled profile keeps+ its name for good, so recreating a deleted stack must not reuse one. The+ tags, stack tags and ``aws:cloudformation:`` tags included, are stored as+ given: the ``aws:`` prefix PutSigningProfile refuses is CloudFormation's own.+ The profile is created through PutSigningProfile's own path, so jobs treat+ it like any other profile."""+ import ministack.services.signer as _signer+ # The stack checks the enum before provisioning; a value that came from+ # another resource is only known here.+ for _prop, reason in _property_enum_errors("AWS::Signer::SigningProfile", props):+ raise ValueError(reason)+ platform = props.get("PlatformId")+ suffix = "".join(random.choices(string.ascii_letters + string.digits, k=12))+ # 51 + "_" + 12 keeps a long logical id inside the 64-character limit.+ name = props.get("ProfileName") or f"{logical_id[:51]}_{suffix}"+ body = {"platformId": platform}+ period = props.get("SignatureValidityPeriod")+ if isinstance(period, dict):+ value = period.get("Value")+ body["signatureValidityPeriod"] = {+ k: v for k, v in (("type", period.get("Type")),+ ("value", int(value) if value is not None else None))+ if v is not None+ }+ _signer_raise_on_error(_signer._put_signing_profile(name, body),+ "AWS::Signer::SigningProfile")+ profile = _signer._profiles[name]+ profile["tags"] = _tag_map(props.get("Tags"))+ return profile["arn"], _signer_profile_attrs(profile)+++def _signer_signing_profile_update(physical_id, old_props, new_props, stack_name):+ """Only Tags can reach this: the other properties are create-only and+ replace the profile first. Tags change in place and the profile keeps+ its version, as measured."""+ import ministack.services.signer as _signer+ profile = _signer._profiles.get(_signer_profile_name_from_arn(physical_id))+ if profile is None:+ raise ValueError(f"AWS::Signer::SigningProfile {physical_id} not found")+ if not isinstance(profile.get("tags"), dict):+ profile["tags"] = {}+ _reconcile_tag_map(profile["tags"], old_props, new_props)+ return physical_id, _signer_profile_attrs(profile)+++def _signer_signing_profile_delete(physical_id, props):+ """A signing profile cannot be deleted: CloudFormation cancels it, and+ the canceled profile keeps its name."""+ import ministack.services.signer as _signer+ _signer._cancel_signing_profile(_signer_profile_name_from_arn(physical_id))+++def _signer_current_revision(profile_name):+ import ministack.services.signer as _signer+ policy = (_signer._profiles.get(profile_name) or {}).get("policy")+ return policy["revisionId"] if policy else None+++def _signer_profile_permission_create(logical_id, props, stack_name):+ """Ref is ``<StatementId>|<ProfileName>``, as measured. The handler reads+ the policy's current revision first, so permissions on one profile do+ not conflict with each other."""+ import ministack.services.signer as _signer+ name = props.get("ProfileName", "")+ sid = props.get("StatementId", "")+ body = {+ "action": props.get("Action"),+ "principal": str(props.get("Principal", "")),+ "statementId": sid,+ "profileVersion": props.get("ProfileVersion"),+ "revisionId": _signer_current_revision(name),+ }+ _signer_raise_on_error(+ _signer._add_profile_permission(name, {k: v for k, v in body.items() if v is not None}),+ "AWS::Signer::ProfilePermission")+ return f"{sid}|{name}", {}+++def _signer_profile_permission_delete(physical_id, props):+ import ministack.services.signer as _signer+ sid, _, name = str(physical_id).partition("|")+ revision = _signer_current_revision(name)+ if revision is not None:+ _signer._remove_profile_permission(name, sid, revision)++# ---------------------------------------------------------------------------# WAFv2 WebACL# ---------------------------------------------------------------------------@@ -13661,6 +13814,10 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::SSM::Parameter": ("Name",),"AWS::SQS::Queue": ("QueueName", "FifoQueue"),"AWS::SNS::Topic": ("TopicName", "FifoTopic"),+ "AWS::Signer::SigningProfile": ("ProfileName", "PlatformId", "SignatureValidityPeriod"),+ "AWS::Signer::ProfilePermission": (+ "ProfileName", "Action", "Principal", "StatementId", "ProfileVersion",+ ),"AWS::Cognito::UserPool": (),"AWS::Lambda::Function": ("FunctionName", "PackageType", "TenancyConfig",@@ -14416,6 +14573,15 @@ _RESOURCE_HANDLERS = {},"AWS::SES::ConfigurationSet": {"create": _ses_configuration_set_create, "delete": _ses_configuration_set_delete},"AWS::SES::ConfigurationSetEventDestination": {"create": _ses_configuration_set_event_destination_create, "delete": _ses_configuration_set_event_destination_delete},+ "AWS::Signer::SigningProfile": {+ "create": _signer_signing_profile_create,+ "update": _signer_signing_profile_update,+ "delete": _signer_signing_profile_delete,+ },+ "AWS::Signer::ProfilePermission": {+ "create": _signer_profile_permission_create,+ "delete": _signer_profile_permission_delete,+ },"AWS::WAFv2::WebACL": {"create": _waf_web_acl_create,"update": _waf_web_acl_update,diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 608d1016..acfa1d19 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -25,11 +25,13 @@ from .engine import (from .provisioners import (_DEFERRED_PREDECESSOR_DELETES,_NAME_SEED,+ _PROPERTY_ENUMS,_RETAIN_REPLACED,_RETAINING_POLICIES,_custom_named_replacement_error,_delete_resource,_import_resource,+ _property_enum_errors,_property_recreation,_provision_resource,_replacing_change,@@ -148,7 +150,7 @@ CLIENT_REQUEST_TOKEN = contextvars.ContextVar("cfn_client_request_token", defauldef _add_event(stack_id, stack_name, logical_id, resource_type, status,- reason="", physical_id=""):+ reason="", physical_id="", detailed_status=""):"""Record a stack event."""from ministack.services.cloudformation import _stack_eventsevent = {@@ -165,6 +167,8 @@ def _add_event(stack_id, stack_name, logical_id, resource_type, status,token = CLIENT_REQUEST_TOKEN.get()if token:event["ClientRequestToken"] = token+ if detailed_status:+ event["DetailedStatus"] = detailed_statusif stack_id not in _stack_events:_stack_events[stack_id] = []_stack_events[stack_id].append(event)@@ -586,6 +590,57 @@ async def _roll_back_operation(stack_name: str, stack_id: str, stack: dict,stack_id)+# AWS's reasons for a create that fails its pre-deployment validation.+_VALIDATION_FAILED = (+ "Validation failed with {count} error(s). Call DescribeEvents to retrieve the "+ "full list of issues with resource and property details, resolve each error, "+ "then retry the operation.")+_VALIDATION_ROLLBACK = "Validation failure detected. See the operation's FAILED event for details."+++def _fail_property_validation(stack, stack_id, stack_name, resources_defs, ordered,+ param_values, conditions, mappings, disable_rollback):+ """Fail a create whose template sets a property outside its schema enum,+ before anything is provisioned, with the events AWS records (measured+ 2026-10-05: one count for all errors, a parameter's value is checked,+ the valid resources are not created either). A value that depends on+ another resource is left to the provisioner. AWS lists the errors+ through DescribeEvents, which is not served; they are logged."""+ errors = []+ for logical_id in ordered:+ res_def = resources_defs[logical_id]+ cond = res_def.get("Condition")+ if cond and not conditions.get(cond, True):+ continue+ rtype = res_def.get("Type", "")+ props = {}+ for prop in _PROPERTY_ENUMS.get(rtype, {}):+ raw = (res_def.get("Properties") or {}).get(prop)+ if any(name in resources_defs for name, _ in _intrinsic_references(raw)):+ continue+ props[prop] = _resolve_refs(copy.deepcopy(raw), {}, param_values, conditions,+ mappings, stack_name, stack_id)+ errors += [(logical_id, prop, reason)+ for prop, reason in _property_enum_errors(rtype, props)]+ if not errors:+ return False+ for logical_id, prop, reason in errors:+ logger.warning("Stack %s validation: /Resources/%s/Properties/%s: %s",+ stack_name, logical_id, prop, reason)+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "CREATE_FAILED", _VALIDATION_FAILED.format(count=len(errors)), stack_id,+ detailed_status="VALIDATION_FAILED")+ if disable_rollback:+ stack["StackStatus"] = "CREATE_FAILED"+ return True+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "ROLLBACK_IN_PROGRESS", _VALIDATION_ROLLBACK, stack_id)+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "ROLLBACK_COMPLETE", "", stack_id)+ stack["StackStatus"] = "ROLLBACK_COMPLETE"+ return True++async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,param_values: dict, disable_rollback: bool,tags: list, is_update: bool = False,@@ -624,6 +679,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,str(exc), stack_id)return+ if not is_update and _fail_property_validation(+ stack, stack_id, stack_name, resources_defs, ordered, param_values,+ conditions, mappings, disable_rollback):+ return+provisioned_resources: dict = stack.get("_resources", {})created_in_this_run = []# Stack-level tags reach the resources through their own tag property;diff --git a/ministack/services/signer.py b/ministack/services/signer.pyindex d1286e73..2c2258c2 100644--- a/ministack/services/signer.py+++ b/ministack/services/signer.py@@ -10,7 +10,8 @@ GET /signing-jobs/{jobId}, the profile pair lives onSupports:Jobs: StartSigningJob, DescribeSigningJob, ListSigningJobs- Profiles: PutSigningProfile, GetSigningProfile+ Profiles: PutSigningProfile, GetSigningProfile, CancelSigningProfile,+ AddProfilePermission, ListProfilePermissions, RemoveProfilePermissionBehaviour that follows the live service (measured 2026-08-26 unless noted):@@ -731,6 +732,11 @@ def _put_signing_profile(name, body):_validate_tags(body.get("tags"))):if problem is not None:return problem+ if name in _profiles:+ # A profile name is taken for good: AWS refuses a second put on an+ # Active profile and on a Canceled one alike (measured 2026-10-05).+ return _coded_error(400, "ValidationException", "ProfileAlreadyExists",+ f"Profile with name {name} already exists")profile = _register_profile(name, body)return json_response({"arn": profile["arn"],@@ -747,7 +753,203 @@ def _get_signing_profile(name):if profile is None:return _error(404, "ResourceNotFoundException",f"Signing profile {name} not found.")- return json_response(_drop_none(profile))+ shown = _drop_none({k: v for k, v in profile.items() if k != "policy"})+ # AWS reports the 135-month default on a profile put without a period.+ shown.setdefault("signatureValidityPeriod", dict(_DEFAULT_VALIDITY))+ return json_response(shown)+++# Profile permissions. The statements live on the profile record under+# "policy" ({"revisionId", "statements"}), so persistence, reset and the+# account/region scoping follow the profile. Wording, codes and ordering below+# were measured on AWS 2026-10-05 (eu-central-1, AWSLambda-SHA384-ECDSA).++_PERMISSION_ACTIONS = ("signer:StartSigningJob", "signer:GetSigningProfile",+ "signer:RevokeSignature")+_STATEMENT_ID_RE = re.compile(r"[A-Za-z0-9_-]+")+_PERMISSION_PRINCIPAL_RE = re.compile(r"[0-9]{12}|arn:aws:iam::[0-9]{12}:role/.+")+_MAX_POLICY_BYTES = 2000+++def _coded_error(status, error_type, code, message):+ """A signer error whose body carries the `code` member AWS fills in for+ these operations (for example `PolicyRevisionIdMismatch`)."""+ return error_response_json(error_type, message, status, extra={"code": code},+ content_type=REST_JSON_CONTENT_TYPE)+++def _policy_statement(profile, permission, expand_principal):+ principal = permission["principal"]+ if expand_principal and _ACCOUNT_ID_RE.fullmatch(principal):+ principal = f"arn:aws:iam::{principal}:root"+ statement = {"Sid": permission["statementId"], "Effect": "Allow",+ "Principal": {"AWS": principal}, "Action": permission["action"],+ "Resource": profile["arn"]}+ if permission.get("profileVersion"):+ statement["Condition"] = {+ "StringEquals": {"signer:ProfileVersion": permission["profileVersion"]}}+ return statement+++def _policy_size(profile, permissions, expand_principal=True):+ """The length of the compact JSON statement list. With the account id+ principals written as `arn:aws:iam::<id>:root` this is policySizeBytes;+ with the principals as given it is what the 2000-byte limit counts (2000+ was accepted and 2001 refused). Both reproduced every size measured on+ AWS, for account and role principals, with and without profileVersion."""+ statements = [_policy_statement(profile, p, expand_principal) for p in permissions]+ return len(json.dumps(statements, separators=(",", ":")))+++def _active_profile_for_permissions(name, verb):+ """`(profile, None)` for an Active profile, else `(None, error)`."""+ name_err = _validate_profile_name(name)+ if name_err:+ return None, name_err+ profile = _profiles.get(name)+ if profile is None:+ return None, _coded_error(404, "ResourceNotFoundException", "ProfileNotFound",+ f"SigningProfile with name {name} does not exist")+ if verb and profile.get("status") != "Active":+ return None, _coded_error(400, "ValidationException", "ProfileNotActive",+ f"Cannot {verb} a profile in {profile.get('status')} state")+ return profile, None+++def _add_profile_permission(name, body):+ profile, err = _active_profile_for_permissions(name, "add permission to")+ if err:+ return err+ sid = body.get("statementId")+ if not isinstance(sid, str) or not sid:+ return _coded_error(400, "ValidationException", "ValidationException",+ "statementId cannot be empty.")+ if not _STATEMENT_ID_RE.fullmatch(sid):+ return _coded_error(400, "ValidationException", "InvalidPermissionStatement",+ "Statement ID must contain only alphanumeric characters, "+ "underscores, and dashes")+ if len(sid) > 64:+ # The message says "less than 64", yet a 64-character id is accepted.+ return _coded_error(400, "ValidationException", "InvalidPermissionStatement",+ "Statement ID must be less than 64 characters length")+ # Only the shape is checked. AWS also answers 404 "Principal not found"+ # for an account or role it cannot resolve, which is not emulated.+ principal = body.get("principal")+ if not isinstance(principal, str) or not _PERMISSION_PRINCIPAL_RE.fullmatch(principal):+ return _coded_error(400, "ValidationException", "InvalidPrincipal",+ "Principal is not a valid AWS account id or IAM Role Arn")+ action = body.get("action")+ if action not in _PERMISSION_ACTIONS:+ return _coded_error(400, "ValidationException", "ValidationException",+ f"Action {action} not supported for platform "+ f"{profile.get('platformId')}. Action must be one of "+ f"[{', '.join(_PERMISSION_ACTIONS)}]")+ version = body.get("profileVersion")+ if version is not None and version != profile.get("profileVersion"):+ return _coded_error(404, "ResourceNotFoundException", "ProfileVersionNotFound",+ f"Version {version} does not exist for SigningProfile {name}.")+ permission = _drop_none({"action": action, "principal": principal,+ "statementId": sid, "profileVersion": version})+ policy = profile.get("policy")+ if policy is not None:+ for existing in policy["statements"]:+ if existing["statementId"] != sid:+ continue+ # Repeating a statement exactly is a no-op answered with the+ # current revision, before any revisionId check.+ if existing == permission:+ return json_response({"revisionId": policy["revisionId"]})+ return _coded_error(400, "ValidationException", "InvalidPermissionStatement",+ f"Statement with statementId {sid} is already in the policy")+ revision = body.get("revisionId")+ if policy is None and revision is not None:+ return _coded_error(400, "ValidationException", "ValidationException",+ "Resource Policy does not exist but revisionId was "+ "specified in the request")+ if policy is not None:+ if revision is None:+ return _coded_error(400, "ValidationException", "ValidationException",+ f"Resource Policy exists for Profile Name {name}. "+ "But no revisionId was provided in the request")+ if revision != policy["revisionId"]:+ return _revision_mismatch(revision, policy)+ statements = (policy["statements"] if policy else []) + [permission]+ if _policy_size(profile, statements, expand_principal=False) > _MAX_POLICY_BYTES:+ return _coded_error(402, "ServiceLimitExceededException", "ServiceLimitExceeded",+ f"Policy cannot exceed maximum size of {_MAX_POLICY_BYTES} bytes")+ profile["policy"] = {"revisionId": str(uuid.uuid4()), "statements": statements}+ return json_response({"revisionId": profile["policy"]["revisionId"]})+++def _revision_mismatch(revision, policy):+ return _coded_error(409, "ConflictException", "PolicyRevisionIdMismatch",+ f"Specified revisionId ({revision}) does not match the "+ f"revisionId of the existing policy ({policy['revisionId']})")+++def _no_policy(name):+ return _coded_error(404, "ResourceNotFoundException", "PolicyNotFound",+ f"No policies associated with profile {name}")+++def _list_profile_permissions(name):+ """The whole policy in one page. AWS caps a policy at 2000 bytes, which+ is a handful of statements, and answered every listing measured in one+ page, ignoring a nextToken it did not issue; nextToken is ignored here+ and never returned."""+ profile, err = _active_profile_for_permissions(name, None)+ if err:+ return err+ policy = profile.get("policy")+ if policy is None:+ return _no_policy(name)+ return json_response({+ "revisionId": policy["revisionId"],+ "policySizeBytes": _policy_size(profile, policy["statements"]),+ "permissions": [dict(p) for p in policy["statements"]],+ })+++def _remove_profile_permission(name, sid, revision):+ profile, err = _active_profile_for_permissions(name, "remove permission from")+ if err:+ return err+ policy = profile.get("policy")+ if policy is None:+ return _no_policy(name)+ if revision != policy["revisionId"]:+ return _revision_mismatch(revision, policy)+ remaining = [p for p in policy["statements"] if p["statementId"] != sid]+ if len(remaining) == len(policy["statements"]):+ return _coded_error(404, "ResourceNotFoundException", "PolicyNotFound",+ f"No policy named {sid} associated with {name} profile")+ if remaining:+ profile["policy"] = {"revisionId": str(uuid.uuid4()), "statements": remaining}+ new_revision = profile["policy"]["revisionId"]+ else:+ # The last statement takes the policy with it: a listing is+ # PolicyNotFound again and the next add needs no revisionId.+ profile.pop("policy")+ new_revision = str(uuid.uuid4())+ return json_response({"revisionId": new_revision})+++def _cancel_signing_profile(name):+ """Status becomes Canceled; the name stays taken and the permissions stay+ listable, but they can no longer be added or removed. Canceling twice+ succeeds. On the first cancel AWS issued a new revisionId for the+ policy, which is mirrored here."""+ name_err = _validate_profile_name(name)+ if name_err:+ return name_err+ profile = _profiles.get(name)+ if profile is None:+ return _coded_error(404, "ResourceNotFoundException", "ProfileNotFound",+ f"Signing Profile with name {name} does not exist.")+ if profile.get("status") == "Active" and profile.get("policy"):+ profile["policy"] = dict(profile["policy"], revisionId=str(uuid.uuid4()))+ profile["status"] = "Canceled"+ return json_response({})# ---------------------------------------------------------------------------@@ -778,7 +980,8 @@ async def handle_request(method, path, headers, body_bytes, query_params):if job_id and "/" not in job_id:return _describe_signing_job(job_id)- # PUT/GET /signing-profiles/{profileName} -- PutSigningProfile / GetSigningProfile+ # PUT/GET/DELETE /signing-profiles/{profileName} -- PutSigningProfile /+ # GetSigningProfile / CancelSigningProfileif path.startswith("/signing-profiles/"):name = urllib.parse.unquote(path[len("/signing-profiles/"):])if name and "/" not in name:@@ -786,5 +989,19 @@ async def handle_request(method, path, headers, body_bytes, query_params):return _put_signing_profile(name, body)if method == "GET":return _get_signing_profile(name)+ if method == "DELETE":+ return _cancel_signing_profile(name)+ # /signing-profiles/{profileName}/permissions[/{statementId}] --+ # AddProfilePermission / ListProfilePermissions / RemoveProfilePermission+ parts = path[len("/signing-profiles/"):].split("/")+ if len(parts) in (2, 3) and parts[0] and parts[1] == "permissions":+ name = urllib.parse.unquote(parts[0])+ if len(parts) == 2 and method == "POST":+ return _add_profile_permission(name, body)+ if len(parts) == 2 and method == "GET":+ return _list_profile_permissions(name)+ if len(parts) == 3 and parts[2] and method == "DELETE":+ return _remove_profile_permission(+ name, urllib.parse.unquote(parts[2]), query.get("revisionId"))return _error(400, "ValidationException", f"No route for {method} {path}")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex be1fec1d..c153658e 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -18705,6 +18705,183 @@ def test_cfn_ses_configuration_set_and_event_destination(cfn, ses, sesv2):ses.describe_configuration_set(ConfigurationSetName=cs_name)+def _signer_template(named, validity=30, tags=None, named_validity=None,+ action="signer:StartSigningJob"):+ named_props = {"ProfileName": named, "PlatformId": "AWSLambda-SHA384-ECDSA"}+ if named_validity:+ named_props["SignatureValidityPeriod"] = {"Type": "DAYS", "Value": named_validity}+ return json.dumps({+ "Resources": {+ "Prof": {"Type": "AWS::Signer::SigningProfile", "Properties": {+ "PlatformId": "AWSLambda-SHA384-ECDSA",+ "SignatureValidityPeriod": {"Type": "DAYS", "Value": validity},+ "Tags": tags or [{"Key": "team", "Value": "a"}]}},+ "Named": {"Type": "AWS::Signer::SigningProfile", "Properties": named_props},+ "Perm": {"Type": "AWS::Signer::ProfilePermission", "Properties": {+ "ProfileName": {"Fn::GetAtt": ["Prof", "ProfileName"]},+ "Action": action,+ "Principal": {"Ref": "AWS::AccountId"}, "StatementId": "p1"}},+ "Perm2": {"Type": "AWS::Signer::ProfilePermission", "DependsOn": "Perm",+ "Properties": {+ "ProfileName": {"Fn::GetAtt": ["Prof", "ProfileName"]},+ "ProfileVersion": {"Fn::GetAtt": ["Prof", "ProfileVersion"]},+ "Action": "signer:GetSigningProfile",+ "Principal": {"Ref": "AWS::AccountId"}, "StatementId": "p2"}},+ },+ "Outputs": {k: {"Value": v} for k, v in {+ "ProfRef": {"Ref": "Prof"}, "ProfArn": {"Fn::GetAtt": ["Prof", "Arn"]},+ "ProfName": {"Fn::GetAtt": ["Prof", "ProfileName"]},+ "ProfVersion": {"Fn::GetAtt": ["Prof", "ProfileVersion"]},+ "ProfVersionArn": {"Fn::GetAtt": ["Prof", "ProfileVersionArn"]},+ "NamedRef": {"Ref": "Named"}, "PermRef": {"Ref": "Perm"},+ }.items()},+ })+++def _signer_permission_ids(signer, name):+ try:+ listed = signer.list_profile_permissions(profileName=name)["permissions"]+ except ClientError as exc:+ return exc.response["code"]+ return [p["statementId"] for p in listed]+++def test_cfn_signer_signing_profile_and_profile_permission(cfn, signer):+ """Ref is the profile ARN (the permission's is ``StatementId|ProfileName``),+ a generated ProfileName is ``<LogicalId>_`` plus 12 letters and digits,+ the profile carries the template, stack and ``aws:cloudformation:`` tags,+ a Tags change keeps the profile, a SignatureValidityPeriod change replaces+ it and its permissions, and a delete cancels it: profiles are never+ deleted on AWS."""+ stack_name = f"cfn-signer-{_uuid_mod.uuid4().hex[:8]}"+ named = f"cfn_named_{_uuid_mod.uuid4().hex[:8]}"+ stack_tags = [{"Key": "stacktag", "Value": "x"}]+ cfn.create_stack(StackName=stack_name, TemplateBody=_signer_template(named), Tags=stack_tags)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ out = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ gen = out["ProfName"]+ assert re.fullmatch(r"Prof_[A-Za-z0-9]{12}", gen)+ assert out["ProfRef"] == out["ProfArn"]+ assert out["ProfArn"].endswith(f":/signing-profiles/{gen}")+ assert out["ProfVersionArn"] == f"{out['ProfArn']}/{out['ProfVersion']}"+ assert out["NamedRef"].endswith(f":/signing-profiles/{named}")+ assert out["PermRef"] == f"p1|{gen}"++ profile = signer.get_signing_profile(profileName=gen)+ assert profile["signatureValidityPeriod"] == {"type": "DAYS", "value": 30}+ assert profile["tags"] == {+ "team": "a", "stacktag": "x",+ "aws:cloudformation:stack-name": stack_name,+ "aws:cloudformation:stack-id": stack["StackId"],+ "aws:cloudformation:logical-id": "Prof",+ }+ listed = signer.list_profile_permissions(profileName=gen)["permissions"]+ assert listed[1] == {"action": "signer:GetSigningProfile", "principal": listed[0]["principal"],+ "statementId": "p2", "profileVersion": out["ProfVersion"]}+ assert _signer_permission_ids(signer, named) == "PolicyNotFound"++ cfn.update_stack(StackName=stack_name, Tags=stack_tags, TemplateBody=_signer_template(+ named, tags=[{"Key": "team", "Value": "b"}, {"Key": "k2", "Value": "v2"}]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ tagged = signer.get_signing_profile(profileName=gen)+ assert tagged["profileVersion"] == out["ProfVersion"]+ assert tagged["tags"]["team"] == "b" and tagged["tags"]["k2"] == "v2"++ cfn.update_stack(StackName=stack_name, Tags=stack_tags, TemplateBody=_signer_template(+ named, validity=31, tags=[{"Key": "team", "Value": "b"}, {"Key": "k2", "Value": "v2"}]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ gen2 = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["ProfName"]+ assert gen2 != gen+ assert signer.get_signing_profile(profileName=gen)["status"] == "Canceled"+ assert _signer_permission_ids(signer, gen) == "PolicyNotFound"+ assert signer.get_signing_profile(profileName=gen2)["signatureValidityPeriod"]["value"] == 31+ assert _signer_permission_ids(signer, gen2) == ["p1", "p2"]++ cfn.delete_stack(StackName=stack_name)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ for name in (gen2, named):+ assert signer.get_signing_profile(profileName=name)["status"] == "Canceled"+ assert _signer_permission_ids(signer, name) == "PolicyNotFound"+ # The canceled name stays taken.+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(profileName=named, platformId="AWSLambda-SHA384-ECDSA")+ assert exc.value.response["code"] == "ProfileAlreadyExists"+++def test_cfn_signer_custom_named_replacement_is_refused(cfn, signer):+ """A create-only change under a kept ProfileName, or under a kept+ StatementId and ProfileName, fails with the custom-named refusal that+ names the physical id; the stack rolls back."""+ stack_name = f"cfn-signer-rn-{_uuid_mod.uuid4().hex[:8]}"+ named = f"cfn_named_{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_signer_template(named))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ out = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ try:+ for template, physical_id in (+ (_signer_template(named, named_validity=7), out["NamedRef"]),+ (_signer_template(named, action="signer:RevokeSignature"), out["PermRef"]),+ ):+ cfn.update_stack(StackName=stack_name, TemplateBody=template)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in+ cfn.describe_stack_events(StackName=stack_name)["StackEvents"]]+ assert ("CloudFormation cannot update a stack when a custom-named resource "+ f"requires replacing. Rename {physical_id} and update the stack again."+ ) in reasons+ assert signer.get_signing_profile(profileName=named)["status"] == "Active"+ assert signer.list_profile_permissions(profileName=out["ProfName"])["permissions"][0][+ "action"] == "signer:StartSigningJob"+ finally:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_signer_signing_profile_platform_outside_the_schema_enum(cfn, signer):+ """The resource schema's PlatformId enum has two values. A value outside+ it, literal or from a parameter, fails the create before anything is+ provisioned: one stack-level CREATE_FAILED counting every error, then the+ rollback, with no resource event and no profile created, not even for the+ valid resource."""+ iot = "AWSIoTDeviceManagement-SHA256-ECDSA"+ stack_name = f"cfn-signer-iot-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({+ "Parameters": {"Platform": {"Type": "String", "Default": iot}},+ "Resources": {+ "Iot": {"Type": "AWS::Signer::SigningProfile",+ "Properties": {"PlatformId": {"Ref": "Platform"}}},+ "Bogus": {"Type": "AWS::Signer::SigningProfile",+ "Properties": {"PlatformId": "Bogus"}},+ "Ok": {"Type": "AWS::Signer::SigningProfile",+ "Properties": {"ProfileName": stack_name.replace("-", "_"),+ "PlatformId": "AWSLambda-SHA384-ECDSA"}},+ }}))+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ events = list(reversed(cfn.describe_stack_events(StackName=stack_name)["StackEvents"]))+ assert {e["LogicalResourceId"] for e in events} == {stack_name}+ assert [(e["ResourceStatus"], e.get("ResourceStatusReason"), e.get("DetailedStatus"))+ for e in events[1:]] == [+ ("CREATE_FAILED", "Validation failed with 2 error(s). Call DescribeEvents to retrieve "+ "the full list of issues with resource and property details, resolve each error, "+ "then retry the operation.", "VALIDATION_FAILED"),+ ("ROLLBACK_IN_PROGRESS",+ "Validation failure detected. See the operation's FAILED event for details.", None),+ ("ROLLBACK_COMPLETE", "", None),+ ]+ assert cfn.describe_stack_resources(StackName=stack_name)["StackResources"] == []+ with pytest.raises(ClientError):+ signer.get_signing_profile(profileName=stack_name.replace("-", "_"))+ finally:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++# ===========================================================================# Loud deletes — DELETE_FAILED / ROLLBACK_FAILED stack states, and the# delete handlers for the types that used to leak silentlydiff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex ad0ab6fd..3ae65642 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1656,6 +1656,17 @@ class TestResourceArn:assert extract_resource_arn("signer", "GET", "/signing-jobs", {}, b"", {"status": "Succeeded"}, "us-east-1", "123") == "*"assert extract_resource_arn("signer", "POST", "/signing-jobs", {}, b"not json", {}, "us-east-1", "123") == "*"+ def test_signer_cancel_and_profile_permissions(self):+ """CancelSigningProfile and the three profile-permission actions+ are scoped to the signing profile."""+ from ministack.core.iam_actions import extract_resource_arn+ arn = "arn:aws:signer:us-east-1:123:/signing-profiles/fleet"+ for method, path in (("DELETE", "/signing-profiles/fleet"),+ ("POST", "/signing-profiles/fleet/permissions"),+ ("GET", "/signing-profiles/fleet/permissions"),+ ("DELETE", "/signing-profiles/fleet/permissions/s1")):+ assert extract_resource_arn("signer", method, path, {}, b"{}", {}, "us-east-1", "123") == arn+def test_elb_passthrough_arn(self):from ministack.core.iam_actions import extract_resource_arnlb_arn = "arn:aws:elasticloadbalancing:us-east-1:123:loadbalancer/app/my-lb/abc"diff --git a/tests/test_signer.py b/tests/test_signer.pyindex 13a7885c..5cc23879 100644--- a/tests/test_signer.py+++ b/tests/test_signer.py@@ -701,6 +701,268 @@ def test_signer_get_unknown_profile_404(signer):assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+def test_signer_get_profile_reports_the_default_validity_period(signer):+ name = f"default_period_{_uid()}"+ signer.put_signing_profile(profileName=name, platformId=_LAMBDA_PLATFORM)+ got = signer.get_signing_profile(profileName=name)+ assert got["signatureValidityPeriod"] == {"type": "MONTHS", "value": 135}+++def test_signer_put_profile_on_a_taken_name_is_refused(signer):+ """A second put on the same name is refused, whether the profile is+ Active or Canceled, and the first profile is left as it was."""+ name = f"taken_{_uid()}"+ first = signer.put_signing_profile(profileName=name, platformId=_LAMBDA_PLATFORM)+ for _ in range(2):+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(+ profileName=name, platformId=_LAMBDA_PLATFORM,+ signatureValidityPeriod={"type": "DAYS", "value": 5})+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert exc.value.response["code"] == "ProfileAlreadyExists"+ assert exc.value.response["Error"]["Message"] == f"Profile with name {name} already exists"+ got = signer.get_signing_profile(profileName=name)+ assert got["profileVersion"] == first["profileVersion"]+ assert got["signatureValidityPeriod"] == {"type": "MONTHS", "value": 135}+ signer.cancel_signing_profile(profileName=name)+++def _signer_error(exc):+ response = exc.value.response+ return (response["ResponseMetadata"]["HTTPStatusCode"], response["Error"]["Code"],+ response.get("code"), response["Error"]["Message"])+++def _permissions_profile(signer):+ name = f"perm_{_uid()}"+ put = signer.put_signing_profile(profileName=name, platformId=_LAMBDA_PLATFORM)+ account = put["arn"].split(":")[4]+ return name, put, account+++def test_signer_profile_permissions_add_list_remove(signer):+ """The statements list in the order they were added, policySizeBytes is+ the compact JSON of the statements (account principals as+ arn:aws:iam::<id>:root, profileVersion as a condition), and removing the+ last statement removes the policy."""+ name, put, account = _permissions_profile(signer)+ with pytest.raises(ClientError) as exc:+ signer.list_profile_permissions(profileName=name)+ assert _signer_error(exc) == (404, "ResourceNotFoundException", "PolicyNotFound",+ f"No policies associated with profile {name}")++ first = signer.add_profile_permission(+ profileName=name, action="signer:StartSigningJob", principal=account, statementId="s1")+ second = signer.add_profile_permission(+ profileName=name, action="signer:RevokeSignature", principal=account,+ statementId="s3", profileVersion=put["profileVersion"], revisionId=first["revisionId"])+ assert second["revisionId"] != first["revisionId"]++ listed = signer.list_profile_permissions(profileName=name)+ assert listed["revisionId"] == second["revisionId"]+ assert "nextToken" not in listed+ assert listed["permissions"] == [+ {"action": "signer:StartSigningJob", "principal": account, "statementId": "s1"},+ {"action": "signer:RevokeSignature", "principal": account, "statementId": "s3",+ "profileVersion": put["profileVersion"]},+ ]+ statements = [+ {"Sid": "s1", "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{account}:root"},+ "Action": "signer:StartSigningJob", "Resource": put["arn"]},+ {"Sid": "s3", "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{account}:root"},+ "Action": "signer:RevokeSignature", "Resource": put["arn"],+ "Condition": {"StringEquals": {"signer:ProfileVersion": put["profileVersion"]}}},+ ]+ assert listed["policySizeBytes"] == len(json.dumps(statements, separators=(",", ":")))+ # A nextToken the service never issued is ignored.+ again = signer.list_profile_permissions(profileName=name, nextToken="garbage")+ assert again["permissions"] == listed["permissions"] and "nextToken" not in again++ removed = signer.remove_profile_permission(+ profileName=name, statementId="s1", revisionId=listed["revisionId"])+ assert removed["revisionId"] != listed["revisionId"]+ assert [p["statementId"] for p in+ signer.list_profile_permissions(profileName=name)["permissions"]] == ["s3"]+ signer.remove_profile_permission(+ profileName=name, statementId="s3", revisionId=removed["revisionId"])+ with pytest.raises(ClientError) as exc:+ signer.list_profile_permissions(profileName=name)+ assert _signer_error(exc)[2] == "PolicyNotFound"+ # With the policy gone the next add needs no revisionId again.+ signer.add_profile_permission(+ profileName=name, action="signer:GetSigningProfile", principal=account, statementId="again")+++def test_signer_profile_permissions_revision_id_rules(signer):+ name, _put, account = _permissions_profile(signer)++ def add(**kw):+ params = {"profileName": name, "action": "signer:StartSigningJob",+ "principal": account, "statementId": "s1"}+ params.update(kw)+ return signer.add_profile_permission(**params)++ with pytest.raises(ClientError) as exc:+ add(revisionId="whatever")+ assert _signer_error(exc) == (+ 400, "ValidationException", "ValidationException",+ "Resource Policy does not exist but revisionId was specified in the request")+ first = add()["revisionId"]+ with pytest.raises(ClientError) as exc:+ add(statementId="s2")+ assert _signer_error(exc) == (+ 400, "ValidationException", "ValidationException",+ f"Resource Policy exists for Profile Name {name}. But no revisionId was provided "+ "in the request")+ second = add(statementId="s2", action="signer:GetSigningProfile", revisionId=first)["revisionId"]+ with pytest.raises(ClientError) as exc:+ add(statementId="s3", revisionId=first)+ assert _signer_error(exc) == (+ 409, "ConflictException", "PolicyRevisionIdMismatch",+ f"Specified revisionId ({first}) does not match the revisionId of the existing "+ f"policy ({second})")+ # Repeating a statement exactly answers the current revision, before+ # any revisionId check.+ assert add()["revisionId"] == second+ assert add(revisionId="stale")["revisionId"] == second+ with pytest.raises(ClientError) as exc:+ add(action="signer:GetSigningProfile", revisionId=second)+ assert _signer_error(exc) == (400, "ValidationException", "InvalidPermissionStatement",+ "Statement with statementId s1 is already in the policy")+ with pytest.raises(ClientError) as exc:+ signer.remove_profile_permission(profileName=name, statementId="s1", revisionId=first)+ assert _signer_error(exc)[:3] == (409, "ConflictException", "PolicyRevisionIdMismatch")+ with pytest.raises(ClientError) as exc:+ signer.remove_profile_permission(profileName=name, statementId="zz", revisionId=second)+ assert _signer_error(exc) == (404, "ResourceNotFoundException", "PolicyNotFound",+ f"No policy named zz associated with {name} profile")+++def test_signer_profile_permissions_refuse_malformed_statements(signer):+ name, _put, account = _permissions_profile(signer)+ base = {"profileName": name, "action": "signer:StartSigningJob",+ "principal": account, "statementId": "s1"}+ cases = [+ ({"statementId": ""}, (400, "ValidationException", "ValidationException",+ "statementId cannot be empty.")),+ ({"statementId": "a b"}, (400, "ValidationException", "InvalidPermissionStatement",+ "Statement ID must contain only alphanumeric characters, "+ "underscores, and dashes")),+ ({"statementId": "y" * 101}, (400, "ValidationException", "InvalidPermissionStatement",+ "Statement ID must be less than 64 characters length")),+ ({"principal": "*"}, (400, "ValidationException", "InvalidPrincipal",+ "Principal is not a valid AWS account id or IAM Role Arn")),+ ({"principal": f"arn:aws:iam::{account}:root"}, (+ 400, "ValidationException", "InvalidPrincipal",+ "Principal is not a valid AWS account id or IAM Role Arn")),+ ({"action": "signer:Foo"}, (+ 400, "ValidationException", "ValidationException",+ f"Action signer:Foo not supported for platform {_LAMBDA_PLATFORM}. Action must be "+ "one of [signer:StartSigningJob, signer:GetSigningProfile, signer:RevokeSignature]")),+ ({"profileVersion": "ABCDEFGHIJ"}, (+ 404, "ResourceNotFoundException", "ProfileVersionNotFound",+ f"Version ABCDEFGHIJ does not exist for SigningProfile {name}.")),+ ]+ for override, expected in cases:+ with pytest.raises(ClientError) as exc:+ signer.add_profile_permission(**{**base, **override})+ assert _signer_error(exc) == expected, override+ with pytest.raises(ClientError) as exc:+ signer.list_profile_permissions(profileName=name)+ assert _signer_error(exc)[2] == "PolicyNotFound"++ # A 64-character id and an IAM role ARN are accepted.+ signer.add_profile_permission(**{**base, "statementId": "x" * 64})+ role = make_client("iam").create_role(+ RoleName=f"signer-perm-{_uid()}",+ AssumeRolePolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": []}),+ )["Role"]["Arn"]+ signer.add_profile_permission(+ **{**base, "statementId": "role", "principal": role},+ revisionId=signer.list_profile_permissions(profileName=name)["revisionId"])++ ghost = f"ghost_{_uid()}"+ for call in (+ lambda: signer.add_profile_permission(**{**base, "profileName": ghost}),+ lambda: signer.list_profile_permissions(profileName=ghost),+ lambda: signer.remove_profile_permission(profileName=ghost, statementId="s1",+ revisionId="x"),+ ):+ with pytest.raises(ClientError) as exc:+ call()+ assert _signer_error(exc) == (404, "ResourceNotFoundException", "ProfileNotFound",+ f"SigningProfile with name {ghost} does not exist")+++def test_signer_profile_permissions_policy_size_limit(signer):+ """The 2000-byte limit counts the compact statement list with the+ principal as given: 2000 bytes are accepted, 2001 are refused."""+ name, put, account = _permissions_profile(signer)++ def size(sids):+ return len(json.dumps([+ {"Sid": sid, "Effect": "Allow", "Principal": {"AWS": account},+ "Action": "signer:GetSigningProfile", "Resource": put["arn"]}+ for sid in sids], separators=(",", ":")))++ # N ids of 2 to 64 characters whose list is exactly 2000 bytes.+ for count in range(1, 20):+ need = 2000 - size([f"{i:02d}" for i in range(count)])+ if 0 <= need <= 62 * count:+ break+ sids = []+ for i in range(count):+ pad = min(62, need)+ need -= pad+ sids.append(f"{i:02d}" + "a" * pad)+ assert size(sids) == 2000 and len(sids[-1]) < 64+ revision = None+ for sid in sids:+ revision = signer.add_profile_permission(+ profileName=name, action="signer:GetSigningProfile", principal=account,+ statementId=sid, **({"revisionId": revision} if revision else {}))["revisionId"]+ revision = signer.remove_profile_permission(+ profileName=name, statementId=sids[-1], revisionId=revision)["revisionId"]+ with pytest.raises(ClientError) as exc:+ signer.add_profile_permission(+ profileName=name, action="signer:GetSigningProfile", principal=account,+ statementId=sids[-1] + "c", revisionId=revision)+ assert _signer_error(exc) == (402, "ServiceLimitExceededException", "ServiceLimitExceeded",+ "Policy cannot exceed maximum size of 2000 bytes")+++def test_signer_cancel_profile_keeps_the_name_and_freezes_permissions(signer):+ name, _put, account = _permissions_profile(signer)+ revision = signer.add_profile_permission(+ profileName=name, action="signer:StartSigningJob", principal=account,+ statementId="s1")["revisionId"]+ signer.cancel_signing_profile(profileName=name)+ assert signer.get_signing_profile(profileName=name)["status"] == "Canceled"++ listed = signer.list_profile_permissions(profileName=name)+ assert [p["statementId"] for p in listed["permissions"]] == ["s1"]+ assert listed["revisionId"] != revision+ with pytest.raises(ClientError) as exc:+ signer.add_profile_permission(+ profileName=name, action="signer:StartSigningJob", principal=account,+ statementId="late", revisionId=listed["revisionId"])+ assert _signer_error(exc) == (400, "ValidationException", "ProfileNotActive",+ "Cannot add permission to a profile in Canceled state")+ with pytest.raises(ClientError) as exc:+ signer.remove_profile_permission(+ profileName=name, statementId="s1", revisionId=listed["revisionId"])+ assert _signer_error(exc) == (400, "ValidationException", "ProfileNotActive",+ "Cannot remove permission from a profile in Canceled state")++ signer.cancel_signing_profile(profileName=name)+ assert signer.get_signing_profile(profileName=name)["status"] == "Canceled"+ ghost = f"ghost_{_uid()}"+ with pytest.raises(ClientError) as exc:+ signer.cancel_signing_profile(profileName=ghost)+ assert _signer_error(exc) == (404, "ResourceNotFoundException", "ProfileNotFound",+ f"Signing Profile with name {ghost} does not exist.")++@pytest.mark.parametrize("name", ["fw-profile", "p" * 65])def test_signer_profile_name_outside_documented_pattern_is_refused(signer, s3, buckets, name