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): synchronous StartSigningJob with the S3 side effect (#1663)
iot-rocket00000d08b45b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7f3cfb75..c4e5e120 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added- **CloudFormation — the `Rules` section is evaluated** — a template's rules were ignored; they now run after the parameters resolve and before any resource is touched, on `CreateStack`, `UpdateStack` and `CreateChangeSet`: a rule whose `RuleCondition` is false is skipped, a false `Assert` refuses the operation with its `AssertDescription` as a `ValidationError`, and the CDK's `CheckBootstrapVersion` rule therefore refuses an outdated bootstrap version instead of passing silently. `Fn::And`, `Fn::Or`, `Fn::Not`, `Fn::Equals`, `Fn::If`, `Fn::Contains`, `Fn::EachMemberEquals`, `Fn::EachMemberIn` and `Ref` are evaluated; `Fn::RefAll`, `Fn::ValueOf` and `Fn::ValueOfAll` are served from the EC2 store for the VPC, subnet and security-group id types, and a rule over any other type is skipped with a warning. A function outside the rule set is refused as a template format error. Contributed by @iot-rocket.- **CloudFormation — the `AWS::Include` transform** — an embedded `Fn::Transform` naming `AWS::Include` was carried into the stack as a literal key; it is now replaced by the contents of the S3 object its `Location` points to (JSON or plain YAML, a key-value object) before the template is validated: next to a sibling resource inside `Resources`, as a whole `Properties` map, inside one next to other properties, in `Mappings`, or in `Outputs`. A location that is not an `s3://` URI, a snippet with a YAML shorthand tag, a missing object, a snippet that is not an object and a nested include are refused before a stack exists, with the sentence a real account answers where one is known. `UsePreviousTemplate` and a change set without a body reuse the stored processed template, so a snippet edited in S3 since the deploy is not picked up, as on AWS. Contributed by @iot-rocket.+- **AWS Signer — synchronous `StartSigningJob` with the S3 side effect** — the `signer` API did not exist. `StartSigningJob`, `DescribeSigningJob`, `ListSigningJobs`, `PutSigningProfile` and `GetSigningProfile` are served natively (REST-JSON). Signing is synchronous and synthetic: Start validates the source object against the local S3 store, writes a JSON marker (source reference + SHA-256 of the source bytes) to `destination.prefix + jobId` (`.zip` appended for a `.zip` source on the Lambda platform, as measured) and returns the job already `Succeeded`; a missing source, destination bucket or profile is `ResourceNotFoundException` at Start with no job recorded. `clientRequestToken` replays the first response. Jobs carry the profile's signing material and a `signatureExpiresAt`; list filters and the documented input constraints are enforced, and `ListSigningJobs` pages with a `nextToken` that is bound to the filters it was minted with. The unsigned path rules leave path-style S3 traffic for a bucket named `signing-jobs` alone unless the request looks like signer's own surface, and a job records the IAM principal that started it rather than the account root. `signatureValidityPeriod` follows the model, where both members are optional, and the documented constraints on `overrides`, `signingMaterial`, `tags`, `jobInvoker` and `profileOwner` are enforced instead of stored as sent. State persists with `PERSIST_STATE=1`. Contributed by @iot-rocket.- **IoT Wireless — `GetPositionEstimate`** — the service was absent. `POST /position-estimate` now answers the way the API is shaped: the output structure declares a `payload` blob, so the HTTP body is the raw GeoJSON `Point` and boto3 hands the caller a `StreamingBody`, not a JSON envelope. The estimate is synthetic and deterministic (the canonical `Ip.IpAddress` hashes onto lon [-180, 180) / lat [-60, 60)); `properties` carry the two accuracy fields plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the time the position is resolved and the receive time as its substitute when the caller sends none, so a request that carries a `Timestamp` answers byte-identical bytes. `WiFiAccessPoints`, `CellTowers` and `Gnss` are accepted and ignored, while `AdvancedConfiguration.WiFiCellular.ConfidencePercent` drives the reported `horizontalConfidenceLevel` over 100, within the 50 to 99 the model allows. Refusals carry the live service's wording: no measurement, an unparseable address, a `Timestamp` that is not a Unix timestamp or a `ConfidencePercent` out of range is `ValidationException`; an address that is not globally routable, or is multicast, is `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, as is a well-formed request whose only measurements are WLAN/cell/GNSS, which AWS documents that class for. Stateless. Contributed by @iot-rocket.### Fixeddiff --git a/README.md b/README.mdindex 834979aa..2efecc66 100644--- a/README.md+++ b/README.md@@ -604,6 +604,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` || **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix || **WAF (Classic + Regional)** | List* (17 ops), Get*, GetChangeToken, GetChangeTokenStatus, GetPermissionPolicy, Create*/Update*/Delete* (stubbed) | Minimal v1 stub — empty lists for all `List*`, valid ChangeToken on Create/Update/Delete; for full features use **wafv2** (also supported) |+| **Signer** | StartSigningJob, DescribeSigningJob, ListSigningJobs, PutSigningProfile, GetSigningProfile | **Signing is synchronous and synthetic**: `StartSigningJob` validates the source object against the local S3 store and writes a JSON signature marker (source reference + SHA-256 of the source bytes — not real cryptography) to `destination.s3.bucketName` at key `prefix + jobId` **before returning**, so the job is already `Succeeded` and a caller whose contract is the signed object at `prefix + jobId` never polls `DescribeSigningJob` (`.zip` is appended for a `.zip` source on `AWSLambda-SHA384-ECDSA`, as measured on AWS). A missing source object or destination bucket is `ResourceNotFoundException` at Start with **no job recorded** (there is no async pipeline, so nothing ever lists as `Failed`); an unknown `profileName` is `ResourceNotFoundException` like on AWS, so create profiles with `PutSigningProfile` first. `clientRequestToken` replays the first response. `source.s3.version` is required by the service model, but an absent value (what `head_object` reports on an unversioned bucket) reads the current object and records the version id S3 holds for it, which is `"null"` only on a bucket without versioning; a literal `"null"` reads the stored `"null"` version when one exists, falling back to the current object. The job carries the profile's `signingMaterial`, `overrides`, `signingParameters` and a `signatureExpiresAt` from its validity period (default 135 months). `ListSigningJobs` filters on `status`, `isRevoked`, `platformId`, `requestedBy` and `jobInvoker`, and pages: `maxResults` (1..25) limits the page and a `nextToken` carries the sort position of the last job, so a paginator reaches every job; without `maxResults` the whole list comes back in one page || **Batch** | CreateComputeEnvironment, UpdateComputeEnvironment, DescribeComputeEnvironments, CreateJobQueue, DescribeJobQueues, RegisterJobDefinition, DescribeJobDefinitions, SubmitJob, DescribeJobs, ListJobs | Control-plane stub — submitted jobs immediately transition to `SUCCEEDED`; multi-revision job definitions; `jobQueue` lookup by name or ARN; account-scoped state |---diff --git a/ministack/app.py b/ministack/app.pyindex d73202f8..27f0f2d6 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -392,6 +392,7 @@ SERVICE_REGISTRY = {"secretsmanager": {"module": "secretsmanager"},"servicediscovery": {"module": "servicediscovery"},"ses": {"module": "ses"},+ "signer": {"module": "signer"},"sns": {"module": "sns"},"sqs": {"module": "sqs"},"ssm": {"module": "ssm"},@@ -486,6 +487,7 @@ _state_map = {"dsql": "dsql","mediaconnect": "mediaconnect","mq": "mq",+ "signer": "signer","opensearch": "opensearch","s3tables": "s3tables","lambda_durable": "lambda_durable",diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 6c757b0e..7106b0c0 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -97,6 +97,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {"secretsmanager": "secretsmanager","servicediscovery": "servicediscovery","ses": "ses",+ "signer": "signer","sns": "sns","sqs": "sqs","ssm": "ssm",@@ -453,6 +454,7 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {"s3files": [], # uses S3 namespace but different paths"s3tables": ["s3tables"],"scheduler": ["scheduler"],+ "signer": ["signer"],}# Compiled route: (http_method, compiled_regex, operation_name, specificity)@@ -1149,6 +1151,23 @@ def extract_resource_arn(service: str, method: str, path: str,return f"arn:aws:ses:{region}:{account_id}:identity/{identity}"return "*"+ if service == "signer":+ # StartSigningJob and GetSigningProfile 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/n+ parts = [p for p in path.split("/") if p]+ if parts and parts[0] == "signing-profiles" and len(parts) > 1 and method == "GET":+ return f"arn:aws:signer:{region}:{account_id}:/signing-profiles/{parts[1]}"+ if parts and parts[0] == "signing-jobs":+ if len(parts) > 1:+ return f"arn:aws:signer:{region}:{account_id}:/signing-jobs/{parts[1]}"+ if method == "POST":+ profile = _safe_json_field(body, "profileName")+ if profile:+ return f"arn:aws:signer:{region}:{account_id}:/signing-profiles/{profile}"+ return "*"+if service == "ssm":name = _param(body, query_params, "Name")if name:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 25057017..2ca1996e 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -461,6 +461,14 @@ SERVICE_PATTERNS = {"host_patterns": [r"inspector2\."],"credential_scope": "inspector2",},+ # AWS Signer (REST-JSON, signing name `signer`). No other pattern+ # contains "signer.", so placement in this dict is not order-sensitive;+ # SDK requests resolve via the credential-scope early return, unsigned+ # clients via the /signing-jobs + /signing-profiles path rules.+ "signer": {+ "host_patterns": [r"signer\."],+ "credential_scope": "signer",+ },"dsql": {"host_patterns": [r"dsql\."],"credential_scope": "dsql",@@ -592,6 +600,16 @@ def _anchored_host_pattern(pattern: str) -> "re.Pattern":return compiled+# The closed query-parameter set of ListSigningJobs, and the shape of a signing+# job id. Both are used to keep the unsigned /signing-jobs path rules off+# path-style S3 traffic for a bucket of that name.+_LIST_SIGNING_JOBS_PARAMS = frozenset({+ "status", "isRevoked", "platformId", "requestedBy", "jobInvoker",+ "maxResults", "nextToken", "signatureExpiresBefore", "signatureExpiresAfter",+})+_UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")++def detect_service(method: str, path: str, headers: dict, query_params: dict) -> str:"""Detect which AWS service a request is targeting."""host = headers.get("host", "")@@ -1163,6 +1181,29 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) -># rule below.if path_lower.startswith("/oidc/"):return "eks"+ # AWS Signer REST-JSON paths for unsigned clients (SigV4 requests route+ # via the `signer` credential scope above). Segment-anchored, limited to+ # the methods the signer surface serves, and further narrowed by the+ # ListSigningJobs parameter set and the uuid shape of a job id, so+ # path-style S3 traffic for a bucket like "signing-jobs-archive", and all+ # but a bare unsigned GET or POST on a bucket named exactly+ # "signing-jobs", still falls through to S3.+ if path_lower == "/signing-jobs" and method in ("POST", "GET"):+ # S3 marks its own listings and multipart/delete POSTs in the query,+ # and ListSigningJobs has a closed parameter set, so a path-style S3+ # request for a bucket named "signing-jobs" keeps its verbs.+ if not (set(query_params) - _LIST_SIGNING_JOBS_PARAMS):+ return "signer"+ if method == "GET" and path_lower.startswith("/signing-jobs/"):+ rest = path_lower[len("/signing-jobs/"):]+ # A signing job id is a uuid, so an S3 object key that is not one+ # falls through rather than being read as a DescribeSigningJob.+ if rest and "/" not in rest and _UUID_RE.fullmatch(rest):+ return "signer"+ if method in ("PUT", "GET") and path_lower.startswith("/signing-profiles/"):+ rest = path_lower[len("/signing-profiles/"):]+ if rest and "/" not in rest:+ return "signer"if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):return "ecs"# smithy-rpc-v2-cbor path: /service/ServiceName/operation/ActionNamediff --git a/ministack/services/signer.py b/ministack/services/signer.pynew file mode 100644index 00000000..0213f801--- /dev/null+++ b/ministack/services/signer.py@@ -0,0 +1,760 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""+AWS Signer service emulator.+REST-JSON protocol — /signing-jobs and /signing-profiles paths (signing+name `signer`). URIs/methods verified against botocore's signer 2017-08-25+service model (StartSigningJob is POST /signing-jobs, DescribeSigningJob is+GET /signing-jobs/{jobId}, the profile pair lives on+/signing-profiles/{profileName}).++Supports:+ Jobs: StartSigningJob, DescribeSigningJob, ListSigningJobs+ Profiles: PutSigningProfile, GetSigningProfile++Behaviour that follows the live service (measured 2026-08-26 unless noted):++ * An unknown `profileName` on StartSigningJob is ResourceNotFoundException+ "profile with name <name> does not exist"; nothing is written and no job+ is recorded. PutSigningProfile is the way to create a profile.+ * `clientRequestToken` is an idempotency token: a repeat with a known+ token answers the first call's `{jobId, jobOwner}` again and writes+ nothing (API reference: "All calls after the first that use this token+ return the same response as the first call"). A raw-wire request+ without one (the model requires it; SDKs autofill it) is still accepted.+ * The signed-object key is `prefix + jobId`, with `.zip` appended when the+ profile's platform is AWSLambda-SHA384-ECDSA and the source key ends in+ `.zip` (both measured: the IoT platform wrote exactly `prefix + jobId`,+ the Lambda platform wrote `prefix + jobId + ".zip"` for a `.zip`+ source). Other platforms and extensions are unmeasured and get the+ plain key.+ * `source.s3.version` is required by the model, but a caller on an+ unversioned bucket forwards what `head_object` gave it: no VersionId at+ all, or S3's literal `"null"` sentinel (the live service accepts+ `"null"` on a suspended-versioning bucket). An absent version reads the+ current object and records the version id S3 stores for it, which is+ `"null"` only when the bucket never had versioning enabled (S3 user+ guide: "Objects that are stored in your bucket before you set the+ versioning state have a version ID of null"). `"null"` reads the stored+ literal-`"null"` version when one exists (suspended-bucket writes,+ pre-versioning objects), falls back to the current object otherwise,+ and records `"null"`. Either way the required member is always present+ on Describe/List.+ * A job carries the profile's `signingMaterial`, `overrides` and+ `signingParameters`, and `signatureExpiresAt` = createdAt plus the+ profile's `signatureValidityPeriod` (default 135 months, per the+ PutSigningProfile reference).++Deliberate divergences from AWS, each pinned by a test:++ * Signing is SYNCHRONOUS and SYNTHETIC. Real Signer queues an async job;+ here StartSigningJob validates the source object against MiniStack's own+ S3 store in-process, writes a JSON signature marker (source reference ++ SHA-256 of the source bytes, not real cryptography) to+ `destination.s3.bucketName`, and returns with the job already+ `Succeeded`. Callers whose contract is the S3 side effect work without+ polling DescribeSigningJob; the signature BYTES are not a real signature.+ * A missing source object or destination bucket fails at Start with+ ResourceNotFoundException and records NO job — there is no async+ pipeline that could fail later, so nothing ever lists as `Failed`.+ * ListSigningJobs pages: `maxResults` (1..25) limits the page and a+ `nextToken` carries the sort position of the last job returned, so a+ paginator walks the whole list. `status`, `isRevoked`,+ `platformId`, `requestedBy` and `jobInvoker` filter; nothing is ever+ revoked, so `isRevoked=true` is an empty page. `signatureExpiresBefore`+ / `signatureExpiresAfter` are ignored.+ * `destination.s3.bucketName` is optional in the model but required here+ (the live behaviour without it is unmeasured).++Documented input constraints that are enforced (the live refusal wording+was not measured, so the messages are MiniStack's own): `profileName` is 2+to 64 characters and the reference gives the pattern `^[a-zA-Z0-9_]{2,}`.+That pattern is start-anchored; MiniStack applies it to the whole name, as+the Terraform provider does (`^[0-9A-Za-z_]{0,64}$`), so a hyphen anywhere+is refused. `ListSigningJobs.maxResults` is 1 to 25, `status` is one of+`InProgress | Failed | Succeeded`, and `signatureValidityPeriod.type` is one+of `DAYS | MONTHS | YEARS`.+"""++import base64+import calendar+import copy+import hashlib+import json+import logging+import re+import time+import urllib.parse+import uuid+from datetime import datetime, timedelta, timezone++import ministack.services.s3 as s3_svc+from ministack.core.persistence import load_state+from ministack.core.responses import (+ AccountRegionScopedDict,+ error_response_json,+ get_account_id,+ get_region,+ json_response,+)++logger = logging.getLogger("signer")++# ---------------------------------------------------------------------------+# State+# ---------------------------------------------------------------------------++_jobs = AccountRegionScopedDict() # jobId -> job record (camelCase fields)+_profiles = AccountRegionScopedDict() # profileName -> profile record+_tokens = AccountRegionScopedDict() # clientRequestToken -> first StartSigningJob response+++def reset():+ _jobs.clear()+ _profiles.clear()+ _tokens.clear()+++def get_state():+ return {+ "jobs": copy.deepcopy(_jobs),+ "profiles": copy.deepcopy(_profiles),+ "tokens": copy.deepcopy(_tokens),+ }+++def restore_state(data):+ if not data:+ return+ _jobs.update(data.get("jobs", {}))+ _profiles.update(data.get("profiles", {}))+ _tokens.update(data.get("tokens", {}))+++try:+ _restored = load_state("signer")+ if _restored:+ restore_state(_restored)+except Exception:+ logger.exception("Failed to restore persisted signer state; continuing fresh")+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++# ProfileName shape: length 2..64, pattern ^[a-zA-Z0-9_]{2,} in the API+# reference (StartSigningJob / PutSigningProfile / GetSigningProfile). The+# reference pattern is start-anchored only; it is applied to the whole name+# here, as the Terraform provider does, so a hyphen anywhere is refused.+_PROFILE_NAME_RE = re.compile(r"[a-zA-Z0-9_]{2,64}")++_JOB_STATUSES = ("InProgress", "Failed", "Succeeded")+_VALIDITY_UNITS = ("DAYS", "MONTHS", "YEARS")+# SigningPlatformOverrides / SigningConfigurationOverrides valid values, and+# the tags map constraints PutSigningProfile documents.+_IMAGE_FORMATS = ("JSON", "JSONEmbedded", "JSONDetached")+_ENCRYPTION_ALGORITHMS = ("RSA", "ECDSA")+_HASH_ALGORITHMS = ("SHA1", "SHA256")+_MAX_TAGS = 200+_TAG_KEY_RE = re.compile(r"[a-zA-Z+\-=._:/]+")+_ACCOUNT_ID_RE = re.compile(r"[0-9]{12}")+# PutSigningProfile reference: "If unspecified, the default is 135 months."+_DEFAULT_VALIDITY = {"type": "MONTHS", "value": 135}+# The one platform whose signed-object key was measured to differ.+_LAMBDA_PLATFORM_ID = "AWSLambda-SHA384-ECDSA"+++def _now():+ return int(time.time())+++def _error(status, code, message):+ return error_response_json(code, message, status)+++def _profile_arn(name):+ # Signer profile ARNs carry a `/` before the resource type:+ # arn:aws:signer:<region>:<account>:/signing-profiles/<name>[/<version>]+ return (+ f"arn:aws:signer:{get_region()}:{get_account_id()}:"+ f"/signing-profiles/{name}"+ )+++def _new_profile_version():+ # ProfileVersion is a 10-char alphanumeric token on AWS.+ return uuid.uuid4().hex[:10]+++def _requested_by(headers):+ """The caller's IAM principal, which is what AWS reports on the job.++ The access key in the request is resolved the way the IAM layer resolves+ it, so a job started under an assumed role or an IAM user records that+ principal and the requestedBy filter can find it again. Without AUTH+ there is nothing to resolve, and an unknown or unresolvable key is not an+ error here, so the account root stands in as it did before.+ """+ from ministack.core.iam_evaluator import PrincipalInfo, resolve_principal+ from ministack.core.router import extract_access_key_id++ account = get_account_id()+ access_key = extract_access_key_id(headers or {})+ if access_key:+ principal = resolve_principal(access_key, account)+ if isinstance(principal, PrincipalInfo) and principal.arn:+ return principal.arn+ return f"arn:aws:iam::{account}:root"+++def _drop_none(record):+ return {k: v for k, v in record.items() if v is not None}+++def _validate_profile_name(name):+ """Return an error tuple when `name` is outside the documented+ ProfileName constraints, else None (wording not measured, see module+ docstring)."""+ if not isinstance(name, str) or not _PROFILE_NAME_RE.fullmatch(name):+ return _error(400, "ValidationException",+ f"profileName {name!r} must be 2 to 64 characters "+ "matching ^[a-zA-Z0-9_]{2,}.")+ return None+++def _validate_overrides(overrides):+ """The two enums SigningPlatformOverrides documents, plus the pair on the+ SigningConfigurationOverrides it nests. botocore does not check enums+ client-side, so an unknown value reaches the service, which refuses it."""+ if overrides is None:+ return None+ if not isinstance(overrides, dict):+ return _error(400, "ValidationException", "overrides must be a structure.")+ image_format = overrides.get("signingImageFormat")+ if image_format is not None and image_format not in _IMAGE_FORMATS:+ return _error(400, "ValidationException",+ f"Invalid value for overrides.signingImageFormat: "+ f"{image_format!r}; expected one of "+ f"{', '.join(_IMAGE_FORMATS)}.")+ config = overrides.get("signingConfiguration")+ if config is None:+ return None+ if not isinstance(config, dict):+ return _error(400, "ValidationException",+ "overrides.signingConfiguration must be a structure.")+ for member, allowed in (("encryptionAlgorithm", _ENCRYPTION_ALGORITHMS),+ ("hashAlgorithm", _HASH_ALGORITHMS)):+ value = config.get(member)+ if value is not None and value not in allowed:+ return _error(400, "ValidationException",+ f"Invalid value for overrides.signingConfiguration."+ f"{member}: {value!r}; expected one of "+ f"{', '.join(allowed)}.")+ return None+++def _validate_signing_material(material):+ """certificateArn is the shape's one member and is Required: Yes. The+ certificate itself is not resolved: nothing signs for real here, so there+ is no ACM lookup to make."""+ if material is None:+ return None+ if not isinstance(material, dict):+ return _error(400, "ValidationException",+ "signingMaterial must be a structure.")+ if not isinstance(material.get("certificateArn"), str) or not material["certificateArn"]:+ return _error(400, "ValidationException",+ "signingMaterial.certificateArn is required.")+ return None+++def _validate_tags(tags):+ """The map constraints PutSigningProfile documents: at most 200 entries,+ keys 1..128 matching `^(?!aws:)[a-zA-Z+-=._:/]+$`, values at most 256."""+ if tags is None:+ return None+ if not isinstance(tags, dict):+ return _error(400, "ValidationException", "tags must be a map.")+ if len(tags) > _MAX_TAGS:+ return _error(400, "ValidationException",+ f"tags must have at most {_MAX_TAGS} entries, got {len(tags)}.")+ for key, value in tags.items():+ if not isinstance(key, str) or not 1 <= len(key) <= 128:+ return _error(400, "ValidationException",+ f"Invalid tag key: {key!r}; keys are 1 to 128 characters.")+ if key.startswith("aws:") or not _TAG_KEY_RE.fullmatch(key):+ return _error(400, "ValidationException",+ f"Invalid tag key: {key!r}; keys match "+ "^(?!aws:)[a-zA-Z+-=._:/]+$.")+ if not isinstance(value, str) or len(value) > 256:+ return _error(400, "ValidationException",+ f"Invalid tag value for {key!r}; values are at most "+ "256 characters.")+ return None+++def _validate_account_id(value, field):+ """jobInvoker and profileOwner are both a fixed length of 12 digits."""+ if value is None:+ return None+ if not isinstance(value, str) or not _ACCOUNT_ID_RE.fullmatch(value):+ return _error(400, "ValidationException",+ f"Invalid value for {field}: {value!r}; expected 12 digits.")+ return None+++def _signature_expires_at(created_at, period):+ """createdAt plus the profile's signatureValidityPeriod (DAYS / MONTHS /+ YEARS), default 135 months. Month arithmetic clamps the day to the+ target month's length."""+ if not isinstance(period, dict) or not period.get("value"):+ period = _DEFAULT_VALIDITY+ unit = period.get("type") or "MONTHS"+ value = int(period["value"])+ start = datetime.fromtimestamp(created_at, tz=timezone.utc)+ if unit == "DAYS":+ return int((start + timedelta(days=value)).timestamp())+ months = value * (12 if unit == "YEARS" else 1)+ total = start.month - 1 + months+ year = start.year + total // 12+ month = total % 12 + 1+ day = min(start.day, calendar.monthrange(year, month)[1])+ return int(start.replace(year=year, month=month, day=day).timestamp())+++def _register_profile(name, body):+ version = _new_profile_version()+ arn = _profile_arn(name)+ profile = {+ "profileName": name,+ "profileVersion": version,+ "profileVersionArn": f"{arn}/{version}",+ "arn": arn,+ "platformId": body.get("platformId"),+ "signingMaterial": body.get("signingMaterial"),+ "signatureValidityPeriod": body.get("signatureValidityPeriod"),+ "overrides": body.get("overrides"),+ "signingParameters": body.get("signingParameters"),+ "tags": body.get("tags"),+ "status": "Active",+ }+ _profiles[name] = profile+ return profile+++def _current_version_id(bucket, key):+ """The version id S3 holds for the CURRENT object at `key`, or `"null"`.++ MiniStack's S3 puts `version_id` on the object record only for a write+ that landed while versioning was Enabled (services/s3.py+ `_record_object_version`), and `_object_response_headers` emits+ `x-amz-version-id` from that same field — so this is the id a GetObject+ on the current object reports. AWS uses the literal `null` as the+ version id of an object stored before versioning was set (S3 user+ guide, "Unversioned, versioning-enabled, and versioning-suspended+ buckets")."""+ bucket_record = s3_svc._ensure_bucket(bucket)+ if bucket_record is None:+ return "null"+ obj = bucket_record["objects"].get(key)+ return (obj or {}).get("version_id") or "null"+++def _resolve_source(bucket, key, version):+ """Return `(data, version_id)` for the source object, or `(None, None)`+ when it doesn't exist.++ The model requires `source.s3.version`, but a caller on an unversioned+ bucket sends what `head_object` reported: nothing, or S3's literal+ `"null"` sentinel. Absent/None/"" reads the current object and records+ the version id that object really carries, so a job on a versioned+ bucket names the version it signed; `"null"` is recorded only when the+ bucket has no versioning. `"null"` as the request value is trickier:+ MiniStack's S3 stores an addressable literal-`"null"` version+ (suspended-bucket writes, pre-versioning objects), and on a bucket whose+ versioning was enabled later that version can hold DIFFERENT bytes than+ the current object — so try the `"null"` version first and fall back to+ the current object only when no such version exists; both record+ `"null"`. Anything else is a real version id and reads exactly that+ version."""+ if version in (None, ""):+ data = s3_svc._get_object_data(bucket, key)+ if data is None:+ return None, None+ return data, _current_version_id(bucket, key)+ if version == "null":+ data = s3_svc._get_object_data(bucket, key, version_id="null")+ if data is not None:+ return data, "null"+ return s3_svc._get_object_data(bucket, key), "null"+ return s3_svc._get_object_data(bucket, key, version_id=version), version+++def _signed_key(prefix, job_id, platform_id, src_key):+ key = f"{prefix}{job_id}"+ if platform_id == _LAMBDA_PLATFORM_ID and src_key.endswith(".zip"):+ key += ".zip"+ return key+++# ---------------------------------------------------------------------------+# Handlers+# ---------------------------------------------------------------------------++def _start_signing_job(body, headers=None):+ s3_source = (body.get("source") or {}).get("s3") or {}+ s3_dest = (body.get("destination") or {}).get("s3") or {}+ profile_name = body.get("profileName")++ # profileOwner is accepted without effect, but its shape is documented and+ # a malformed value is a 400 on AWS rather than a silently ignored member.+ owner_problem = _validate_account_id(body.get("profileOwner"), "profileOwner")+ if owner_problem is not None:+ return owner_problem++ src_bucket = s3_source.get("bucketName")+ src_key = s3_source.get("key")+ src_version = s3_source.get("version")+ if not (isinstance(src_bucket, str) and src_bucket+ and isinstance(src_key, str) and src_key):+ return _error(400, "ValidationException",+ "source.s3.bucketName and source.s3.key are required strings.")+ if src_version is not None and not isinstance(src_version, str):+ return _error(400, "ValidationException",+ "source.s3.version must be a string.")+ dst_bucket = s3_dest.get("bucketName")+ if not (isinstance(dst_bucket, str) and dst_bucket):+ return _error(400, "ValidationException",+ "destination.s3.bucketName is required.")+ prefix = s3_dest.get("prefix") or ""+ if not isinstance(prefix, str):+ return _error(400, "ValidationException",+ "destination.s3.prefix must be a string.")+ if not profile_name:+ return _error(400, "ValidationException", "profileName is required.")+ name_err = _validate_profile_name(profile_name)+ if name_err:+ return name_err+ token = body.get("clientRequestToken")+ if token is not None and not isinstance(token, str):+ return _error(400, "ValidationException",+ "clientRequestToken must be a string.")++ if token:+ replay = _tokens.get(token)+ if replay is not None:+ # Idempotent replay: the first call's response, nothing written.+ return json_response(dict(replay))++ profile = _profiles.get(profile_name)+ if profile is None:+ # Live-measured wording.+ return _error(404, "ResourceNotFoundException",+ f"profile with name {profile_name} does not exist")++ data, version_id = _resolve_source(src_bucket, src_key, src_version)+ if data is None:+ # Synchronous divergence: the real service would accept the job and+ # fail it later; there is no later here, so the missing source fails+ # the Start itself and no job is recorded.+ return _error(404, "ResourceNotFoundException",+ f"Source object s3://{src_bucket}/{src_key} not found.")++ if s3_svc._ensure_bucket(dst_bucket) is None:+ # Same synchronous divergence for the destination bucket.+ return _error(404, "ResourceNotFoundException",+ f"Destination bucket {dst_bucket} not found.")++ job_id = str(uuid.uuid4())+ platform_id = profile.get("platformId")+ signed_key = _signed_key(prefix, job_id, platform_id, src_key)+ now = _now()++ marker = {+ "jobId": job_id,+ "profileName": profile_name,+ "platformId": platform_id,+ "source": {+ "bucketName": src_bucket,+ "key": src_key,+ "version": version_id,+ },+ "sourceSha256": hashlib.sha256(data).hexdigest(),+ "signedAt": now,+ "signedBy": "ministack-signer",+ }+ marker_bytes = json.dumps(marker, ensure_ascii=False).encode("utf-8")+ status, _headers, resp_body = s3_svc._put_object(+ dst_bucket, signed_key, marker_bytes,+ {"content-type": "application/json",+ "content-length": str(len(marker_bytes))},+ )+ if status >= 300:+ # Bucket existence was checked above, so this is some other S3+ # rejection (Object Lock, SSE config, ...) — surface it as the+ # service-side failure it is instead of mislabeling it "not found".+ logger.error(+ "Signed-object write to s3://%s/%s failed with S3 status %s: %s",+ dst_bucket, signed_key, status, resp_body,+ )+ return _error(500, "InternalServiceErrorException",+ f"Writing the signed object to s3://{dst_bucket}/"+ f"{signed_key} failed with S3 status {status}.")++ account = get_account_id()+ _jobs[job_id] = {+ "jobId": job_id,+ "source": {"s3": {+ "bucketName": src_bucket,+ "key": src_key,+ "version": version_id,+ }},+ "signedObject": {"s3": {"bucketName": dst_bucket, "key": signed_key}},+ "profileName": profile_name,+ "profileVersion": profile.get("profileVersion"),+ "platformId": platform_id,+ "signingMaterial": profile.get("signingMaterial"),+ "overrides": profile.get("overrides"),+ "signingParameters": profile.get("signingParameters"),+ "signatureExpiresAt": _signature_expires_at(+ now, profile.get("signatureValidityPeriod")+ ),+ "status": "Succeeded",+ "statusReason": "Signing Succeeded", # live-measured Describe wording+ "createdAt": now,+ "completedAt": now,+ "requestedBy": _requested_by(headers),+ "jobOwner": account,+ "jobInvoker": account,+ }+ response = {"jobId": job_id, "jobOwner": account}+ if token:+ _tokens[token] = dict(response)+ return json_response(response)+++def _describe_signing_job(job_id):+ job = _jobs.get(job_id)+ if job is None:+ return _error(404, "ResourceNotFoundException",+ f"Signing job {job_id} not found.")+ return json_response(_drop_none(job))+++# Real AWS ListSigningJobs returns SigningJob summaries, not the Describe+# shape (no requestedBy, statusReason, completedAt). Keep in sync with the+# AWS SigningJob shape.+_LISTED_JOB_FIELDS = (+ "jobId", "source", "signedObject", "createdAt", "status",+ "profileName", "profileVersion", "platformId", "jobOwner", "jobInvoker",+ "signingMaterial", "signatureExpiresAt",+)+++def _job_sort_key(job):+ """Jobs are ordered by creation, with the job id breaking a tie: two jobs+ started in the same second must still have a total order, or a nextToken+ pointing at one of them cannot say where the next page starts."""+ return (job.get("createdAt") or 0, job.get("jobId") or "")+++_TOKEN_FILTERS = ("status", "isRevoked", "platformId", "requestedBy", "jobInvoker")+++def _token_filter_digest(query):+ """A fingerprint of the filters a listing was made with. A token is only+ meaningful for the list it was minted from, so it carries the fingerprint+ and a call that changes a filter mid-walk is refused rather than resumed+ at a position that means nothing for the new list."""+ filters = [(name, query.get(name)) for name in _TOKEN_FILTERS]+ raw = json.dumps(filters, sort_keys=True).encode("utf-8")+ return hashlib.sha256(raw).hexdigest()[:16]+++def _encode_job_token(job, query):+ """A token carries the sort position of the last job on the page, not an+ offset: an offset would skip a job whenever one was created between two+ calls."""+ raw = json.dumps(list(_job_sort_key(job)) + [_token_filter_digest(query)])+ return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii")+++def _decode_job_token(token, query):+ """The sort key a token carries, or None when the token is not ours or was+ minted for a different filter set."""+ try:+ raw = json.loads(base64.urlsafe_b64decode(token.encode("ascii")).decode("utf-8"))+ if not isinstance(raw, list) or len(raw) != 3:+ return None+ if raw[2] != _token_filter_digest(query):+ return None+ return (float(raw[0]), str(raw[1]))+ except Exception:+ return None+++def _list_signing_jobs(query):+ """`maxResults` (1..25) limits the page; when jobs remain, the response+ carries a `nextToken` that a following call resumes from, as the API+ documents ("If additional jobs remain to be listed, AWS Signer returns a+ nextToken value"). Without `maxResults` the whole list is returned in one+ page: the service's own default page size is not documented and was not+ measured. The order (createdAt, then jobId) is MiniStack's own; the+ reference does not document one. `status`, `isRevoked`, `platformId`,+ `requestedBy` and `jobInvoker` filter (nothing is ever revoked, so+ isRevoked=true is empty); signatureExpiresBefore/-After are ignored.+ `maxResults` must be 1..25 and `status` one of the documented values; the+ refusal wording is MiniStack's own."""+ status_filter = query.get("status")+ if status_filter is not None and status_filter not in _JOB_STATUSES:+ return _error(400, "ValidationException",+ f"Invalid value for status: {status_filter!r}; expected "+ f"one of {', '.join(_JOB_STATUSES)}.")+ raw_max = query.get("maxResults")+ max_results = None+ if raw_max is not None:+ try:+ max_results = int(raw_max)+ except (TypeError, ValueError):+ return _error(400, "ValidationException",+ f"Invalid value for maxResults: {raw_max!r}.")+ if not 1 <= max_results <= 25:+ return _error(400, "ValidationException",+ f"maxResults must be between 1 and 25, got "+ f"{max_results}.")+ is_revoked = query.get("isRevoked")+ if is_revoked is not None:+ if str(is_revoked).lower() not in ("true", "false"):+ return _error(400, "ValidationException",+ f"Invalid value for isRevoked: {is_revoked!r}.")+ token = query.get("nextToken")+ cursor = None+ if token is not None:+ cursor = _decode_job_token(token, query)+ if cursor is None:+ return _error(400, "ValidationException",+ f"Invalid value for nextToken: {token!r}.")+ # Nothing is ever revoked, so the revoked listing is empty whatever the+ # rest of the query says. The token is still validated first, or the same+ # bad token would be a 400 alone and a 200 next to isRevoked=true.+ if is_revoked is not None and str(is_revoked).lower() == "true":+ return json_response({"jobs": []})+ invoker_problem = _validate_account_id(query.get("jobInvoker"), "jobInvoker")+ if invoker_problem is not None:+ return invoker_problem+ equality = {+ field: query[field]+ for field in ("platformId", "requestedBy", "jobInvoker")+ if query.get(field) is not None+ }+ matched = []+ for job in _jobs.values():+ if status_filter and job.get("status") != status_filter:+ continue+ if any(job.get(field) != value for field, value in equality.items()):+ continue+ matched.append(job)+ matched.sort(key=_job_sort_key)+ if cursor is not None:+ matched = [job for job in matched if _job_sort_key(job) > cursor]+ page, remaining = matched, []+ if max_results is not None:+ page, remaining = matched[:max_results], matched[max_results:]+ jobs = []+ for job in page:+ summary = _drop_none({k: job.get(k) for k in _LISTED_JOB_FIELDS})+ summary["isRevoked"] = False+ jobs.append(summary)+ result = {"jobs": jobs}+ if remaining:+ result["nextToken"] = _encode_job_token(page[-1], query)+ return json_response(result)+++def _put_signing_profile(name, body):+ name_err = _validate_profile_name(name)+ if name_err:+ return name_err+ if not body.get("platformId"):+ return _error(400, "ValidationException", "platformId is required.")+ period = body.get("signatureValidityPeriod")+ if period is not None:+ # Both members are documented Required: No, so a period carrying only+ # one of them is a valid request; _signature_expires_at falls back to+ # MONTHS for a missing type and to the 135-month default for a missing+ # value. Only the shapes the model cannot express are refused.+ if not isinstance(period, dict):+ return _error(400, "ValidationException",+ "signatureValidityPeriod must be a structure.")+ unit = period.get("type")+ if unit is not None and unit not in _VALIDITY_UNITS:+ return _error(400, "ValidationException",+ f"Invalid value for signatureValidityPeriod.type: {unit!r}; "+ f"expected one of {', '.join(_VALIDITY_UNITS)}.")+ value = period.get("value")+ if value is not None and (isinstance(value, bool) or not isinstance(value, int)):+ return _error(400, "ValidationException",+ "signatureValidityPeriod.value must be an integer.")+ for problem in (_validate_overrides(body.get("overrides")),+ _validate_signing_material(body.get("signingMaterial")),+ _validate_tags(body.get("tags"))):+ if problem is not None:+ return problem+ profile = _register_profile(name, body)+ return json_response({+ "arn": profile["arn"],+ "profileVersion": profile["profileVersion"],+ "profileVersionArn": profile["profileVersionArn"],+ })+++def _get_signing_profile(name):+ name_err = _validate_profile_name(name)+ if name_err:+ return name_err+ profile = _profiles.get(name)+ if profile is None:+ return _error(404, "ResourceNotFoundException",+ f"Signing profile {name} not found.")+ return json_response(_drop_none(profile))+++# ---------------------------------------------------------------------------+# Request Router+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body_bytes, query_params):+ try:+ body = json.loads(body_bytes) if body_bytes else {}+ except json.JSONDecodeError:+ body = {}+ if not isinstance(body, dict):+ body = {}++ query = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}++ # POST /signing-jobs -- StartSigningJob+ if path == "/signing-jobs" and method == "POST":+ return _start_signing_job(body, headers)++ # GET /signing-jobs -- ListSigningJobs+ if path == "/signing-jobs" and method == "GET":+ return _list_signing_jobs(query)++ # GET /signing-jobs/{jobId} -- DescribeSigningJob+ if path.startswith("/signing-jobs/") and method == "GET":+ job_id = urllib.parse.unquote(path[len("/signing-jobs/"):])+ if job_id and "/" not in job_id:+ return _describe_signing_job(job_id)++ # PUT/GET /signing-profiles/{profileName} -- PutSigningProfile / GetSigningProfile+ if path.startswith("/signing-profiles/"):+ name = urllib.parse.unquote(path[len("/signing-profiles/"):])+ if name and "/" not in name:+ if method == "PUT":+ return _put_signing_profile(name, body)+ if method == "GET":+ return _get_signing_profile(name)++ return _error(400, "ValidationException", f"No route for {method} {path}")diff --git a/tests/conftest.py b/tests/conftest.pyindex ece36eee..69c02fdb 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -445,6 +445,11 @@ def ses():return make_client("ses")[email protected](scope="session")+def signer():+ return make_client("signer")++@pytest.fixture(scope="session")def sfn():return make_client("stepfunctions")diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 9caeba26..a92bdd61 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -998,6 +998,16 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("ssm", "POST", "/", {}, b"", {"Name": ["/app/config"]}, "us-east-1", "123") == "arn:aws:ssm:us-east-1:123:parameter/app/config"+ def test_signer_profile_and_job(self):+ from ministack.core.iam_actions import extract_resource_arn+ job_body = b'{"profileName": "fleet", "source": {"s3": {}}}'+ assert extract_resource_arn("signer", "POST", "/signing-jobs", {}, job_body, {}, "us-east-1", "123") == "arn:aws:signer:us-east-1:123:/signing-profiles/fleet"+ assert extract_resource_arn("signer", "GET", "/signing-profiles/fleet", {}, b"", {}, "us-east-1", "123") == "arn:aws:signer:us-east-1:123:/signing-profiles/fleet"+ assert extract_resource_arn("signer", "GET", "/signing-jobs/9a1f", {}, b"", {}, "us-east-1", "123") == "arn:aws:signer:us-east-1:123:/signing-jobs/9a1f"+ assert extract_resource_arn("signer", "PUT", "/signing-profiles/fleet", {}, b"{}", {}, "us-east-1", "123") == "*"+ 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_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_persistence.py b/tests/test_persistence.pyindex 41a25a12..0e080db3 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -5632,3 +5632,66 @@ def test_batch_persistence_lifecycle_restores_regional_state(monkeypatch, tmp_paassert service._jobs.get_scoped(account_id, boot_region, job_id) is Nonefinally:service.reset()+++# ── signer._jobs / signer._profiles / signer._tokens ───────────────────++def test_signer_jobs_profiles_and_tokens_survive_warm_boot():+ """A restored signer job must keep its signedObject reference: a caller+ whose contract is the signed object at `prefix + jobId` reads that key,+ and a job record that forgets where its marker lives can no longer+ answer DescribeSigningJob for it after a restart. The idempotency map+ must survive too, or a retried Start after a restart would sign twice."""+ mod = _get_module("signer")+ mod.reset()+ job_id = "persisted-signing-job"+ now = 1700000000+ try:+ mod._profiles["persisted_profile"] = {+ "profileName": "persisted_profile",+ "profileVersion": "abc123def4",+ "profileVersionArn": (+ "arn:aws:signer:us-east-1:000000000000:"+ "/signing-profiles/persisted_profile/abc123def4"+ ),+ "arn": (+ "arn:aws:signer:us-east-1:000000000000:"+ "/signing-profiles/persisted_profile"+ ),+ "platformId": "AWSIoTDeviceManagement-SHA256-ECDSA",+ "status": "Active",+ }+ mod._jobs[job_id] = {+ "jobId": job_id,+ "source": {"s3": {"bucketName": "src-bkt", "key": "fw.bin",+ "version": "null"}},+ "signedObject": {"s3": {"bucketName": "dst-bkt",+ "key": f"signed/{job_id}"}},+ "profileName": "persisted_profile",+ "profileVersion": "abc123def4",+ "platformId": "AWSIoTDeviceManagement-SHA256-ECDSA",+ "status": "Succeeded",+ "createdAt": now,+ "completedAt": now,+ "requestedBy": "arn:aws:iam::000000000000:root",+ "jobOwner": "000000000000",+ "jobInvoker": "000000000000",+ }+ mod._tokens["token-1"] = {"jobId": job_id, "jobOwner": "000000000000"}++ _round_trip_dict(mod, "signer")++ job = mod._jobs.get(job_id)+ assert job is not None, "_jobs lost across save_state -> load_state"+ assert job["status"] == "Succeeded"+ assert job["signedObject"]["s3"]["key"] == f"signed/{job_id}"+ profile = mod._profiles.get("persisted_profile")+ assert profile is not None, (+ "_profiles lost across save_state -> load_state"+ )+ assert profile["profileVersion"] == "abc123def4"+ assert mod._tokens.get("token-1") == {+ "jobId": job_id, "jobOwner": "000000000000",+ }+ finally:+ mod.reset()diff --git a/tests/test_router.py b/tests/test_router.pyindex 13513bf4..5045842f 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -353,6 +353,80 @@ def test_served_host_prefers_the_multi_label_token():) == "appconfig"+def test_signer_credential_scope_routes():+ """boto3 signs signer requests with credential scope `signer` (botocore+ signingName) — the scope early-return must resolve it."""+ assert detect_service(+ "POST", "/signing-jobs", _sigv4_headers("signer"), {}+ ) == "signer"+ assert detect_service(+ "GET", "/signing-profiles/prof1", _sigv4_headers("signer"), {}+ ) == "signer"+++def test_signer_host_routes():+ headers = {"host": "signer.us-east-1.localhost:4566"}+ assert detect_service("GET", "/signing-jobs/9d2c58d6-4a1b-4c3d-8e5f-0a1b2c3d4e5f", headers, {}) == "signer"+++ "method,path",+ [+ ("POST", "/signing-jobs"),+ ("GET", "/signing-jobs"),+ ("GET", "/signing-jobs/9d2c58d6-4a1b-4c3d-8e5f-0a1b2c3d4e5f"),+ ("PUT", "/signing-profiles/prof1"),+ ("GET", "/signing-profiles/prof1"),+ ],+)+def test_signer_unsigned_paths_route_by_prefix(method, path):+ """Without SigV4 the default is S3 — the /signing-jobs and+ /signing-profiles path rules must claim signer's REST-JSON surface+ before that fallback."""+ assert detect_service(method, path, _HEADERS, {}) == "signer"++[email protected](("method", "path", "query"), [+ # A key that is not a job id: DescribeSigningJob takes a uuid.+ ("GET", "/signing-jobs/report.json", {}),+ ("GET", "/signing-jobs/2026-09-09", {}),+ # S3 marks its own listing and its multipart/delete POSTs in the query,+ # and ListSigningJobs has none of those parameters.+ ("GET", "/signing-jobs", {"list-type": "2"}),+ ("GET", "/signing-jobs", {"prefix": "signed/"}),+ ("POST", "/signing-jobs", {"delete": ""}),+ ("POST", "/signing-jobs", {"uploads": ""}),+])+def test_signer_paths_leave_s3_traffic_alone(method, path, query):+ """A bucket named exactly "signing-jobs" keeps the requests that carry an+ S3 marker; only the shapes signer's own surface uses are claimed."""+ assert detect_service(method, path, _HEADERS, query) == "s3"++[email protected](("method", "path"), [+ # Buckets that merely share the prefix.+ ("GET", "/signing-jobs-archive"),+ ("GET", "/signing-jobs-archive/report.json"),+ ("PUT", "/signing-profiles-backup/dump.bin"),+ # Verbs signer's surface doesn't serve, on the exact-named bucket.+ ("PUT", "/signing-jobs/new-object"),+ ("DELETE", "/signing-jobs/old-object"),+ ("DELETE", "/signing-profiles/prof1"),+ # Multi-segment object keys inside the exact-named bucket, and the+ # bare list-bucket GET on "signing-profiles" (ListSigningProfiles is+ # not implemented, so S3 keeps it).+ ("GET", "/signing-jobs/path/to/object"),+ ("GET", "/signing-profiles/nested/key"),+ ("GET", "/signing-profiles"),+])+def test_signer_lookalike_s3_paths_stay_on_s3(method, path):+ """Regression: `startswith("/signing-jobs")` hijacked unsigned path-style+ S3 traffic for any bucket whose name starts with that prefix. The rules+ are segment-anchored and method-limited now, so this traffic falls+ through to the S3 default."""+ assert detect_service(method, path, _HEADERS, {}) == "s3"++@pytest.mark.parametrize("host", ["ministack","ministack-core:4566",diff --git a/tests/test_signer.py b/tests/test_signer.pynew file mode 100644index 00000000..5192afde--- /dev/null+++ b/tests/test_signer.py@@ -0,0 +1,841 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""+Integration tests for the AWS Signer emulator (synchronous, synthetic signing).++The contract under test is the S3 side effect: StartSigningJob validates the+source object against the local S3 store and synchronously writes a JSON+signature marker to `destination.prefix + jobId`, so a caller whose contract+is the signed object at `prefix + jobId` never has to poll+DescribeSigningJob.+"""+import hashlib+import json+import re+import urllib.error+import urllib.request+import uuid++import pytest+from botocore.exceptions import ClientError+from conftest import ENDPOINT, make_client++_IOT_PLATFORM = "AWSIoTDeviceManagement-SHA256-ECDSA"+_LAMBDA_PLATFORM = "AWSLambda-SHA384-ECDSA"++_SIGNER_AUTH = (+ "AWS4-HMAC-SHA256 "+ "Credential=test/20260811/us-east-1/signer/aws4_request, "+ "SignedHeaders=host, Signature=fake"+)+++def _uid():+ return uuid.uuid4().hex[:8]+++def _raw(method, path, payload):+ """Raw HTTP with the signer credential scope; returns (status, body)."""+ req = urllib.request.Request(+ f"{ENDPOINT}{path}",+ data=json.dumps(payload).encode(),+ method=method,+ headers={"Authorization": _SIGNER_AUTH, "content-type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=5) as resp:+ return resp.status, json.loads(resp.read() or b"{}")+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read() or b"{}")+++def buckets(s3):+ """A fresh (source, destination) bucket pair, both unversioned."""+ src = f"signer-src-{_uid()}"+ dst = f"signer-dst-{_uid()}"+ s3.create_bucket(Bucket=src)+ s3.create_bucket(Bucket=dst)+ return src, dst+++def profile(signer):+ """A signing profile on the IoT platform (the one whose signed-object+ key is exactly prefix + jobId)."""+ name = f"profile_{_uid()}"+ signer.put_signing_profile(profileName=name, platformId=_IOT_PLATFORM)+ return name+++def _start(signer, src, dst, *, key, profile, prefix="signed/", version="null"):+ return signer.start_signing_job(+ source={"s3": {"bucketName": src, "key": key, "version": version}},+ destination={"s3": {"bucketName": dst, "prefix": prefix}},+ profileName=profile,+ )+++def _keys(s3, bucket):+ return [o["Key"] for o in s3.list_objects_v2(Bucket=bucket).get("Contents", [])]+++# ---------------------------------------------------------------------------+# StartSigningJob — the S3 side effect+# ---------------------------------------------------------------------------++def test_signer_start_writes_marker_at_prefix_plus_job_id(signer, s3, buckets, profile):+ src, dst = buckets+ payload = b"firmware-image-bytes " + uuid.uuid4().bytes+ s3.put_object(Bucket=src, Key="fw/image.bin", Body=payload)++ resp = _start(signer, src, dst, key="fw/image.bin", profile=profile)+ job_id = resp["jobId"]+ assert job_id+ assert re.fullmatch(r"\d{12}", resp["jobOwner"])++ # Cross-API: the marker object must be readable through the S3 API at+ # exactly destination.prefix + jobId.+ obj = s3.get_object(Bucket=dst, Key=f"signed/{job_id}")+ marker = json.loads(obj["Body"].read())+ assert marker["jobId"] == job_id+ assert marker["profileName"] == profile+ assert marker["source"]["bucketName"] == src+ assert marker["source"]["key"] == "fw/image.bin"+ assert marker["sourceSha256"] == hashlib.sha256(payload).hexdigest()+++def test_signer_empty_prefix_lands_marker_at_job_id(signer, s3, buckets, profile):+ src, dst = buckets+ s3.put_object(Bucket=src, Key="cfg.json", Body=b"{}")++ resp = _start(signer, src, dst, key="cfg.json", profile=profile, prefix="")+ s3.head_object(Bucket=dst, Key=resp["jobId"]) # raises if absent+++def test_signer_lambda_platform_appends_zip_for_a_zip_source(signer, s3, buckets):+ """Measured on the live service: a `.zip` source signed on+ AWSLambda-SHA384-ECDSA lands at prefix + jobId + ".zip", while the IoT+ platform writes exactly prefix + jobId."""+ src, dst = buckets+ name = f"lambda_{_uid()}"+ signer.put_signing_profile(profileName=name, platformId=_LAMBDA_PLATFORM)+ s3.put_object(Bucket=src, Key="source/src.zip", Body=b"PK-zip-bytes")+ s3.put_object(Bucket=src, Key="source/src.bin", Body=b"bin-bytes")++ zipped = _start(signer, src, dst, key="source/src.zip", profile=name)["jobId"]+ plain = _start(signer, src, dst, key="source/src.bin", profile=name)["jobId"]++ assert f"signed/{zipped}.zip" in _keys(s3, dst)+ assert f"signed/{plain}" in _keys(s3, dst)+ described = signer.describe_signing_job(jobId=zipped)+ assert described["signedObject"]["s3"]["key"] == f"signed/{zipped}.zip"+ assert described["platformId"] == _LAMBDA_PLATFORM+++def test_signer_iot_platform_keeps_the_plain_key_for_a_zip_source(signer, s3, buckets, profile):+ """The `.zip` suffix rides on the PLATFORM, not on the source extension:+ the same `.zip` source that gets `prefix + jobId + ".zip"` on+ AWSLambda-SHA384-ECDSA lands at exactly `prefix + jobId` on+ AWSIoTDeviceManagement-SHA256-ECDSA. The measurement (2026-08-26)+ attributes the suffix to the Lambda platform; a `.zip` source on the IoT+ platform was not itself measured live, so this pins the emulator's rule."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="fw/firmware.zip", Body=b"PK-firmware")++ job_id = _start(signer, src, dst, key="fw/firmware.zip", profile=profile)["jobId"]++ assert _keys(s3, dst) == [f"signed/{job_id}"]+ described = signer.describe_signing_job(jobId=job_id)+ assert described["platformId"] == _IOT_PLATFORM+ assert described["signedObject"]["s3"]["key"] == f"signed/{job_id}"+++def test_signer_unversioned_source_with_version_omitted(s3, signer, buckets, profile):+ """A caller on an unversioned bucket may send NO `version` at all (the+ model requires it, so boto3's client-side validation has to be off — the+ wire request simply lacks the member, like a non-Python SDK's optional+ struct field). The job then records S3's "null" id so the required+ member is always present on Describe."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="plain.bin", Body=b"unversioned-bytes")+ raw_signer = make_client("signer", {"parameter_validation": False})++ resp = raw_signer.start_signing_job(+ source={"s3": {"bucketName": src, "key": "plain.bin"}},+ destination={"s3": {"bucketName": dst, "prefix": "out/"}},+ profileName=profile,+ )+ marker = json.loads(+ s3.get_object(Bucket=dst, Key=f"out/{resp['jobId']}")["Body"].read()+ )+ assert marker["sourceSha256"] == hashlib.sha256(b"unversioned-bytes").hexdigest()+ job = signer.describe_signing_job(jobId=resp["jobId"])+ assert job["source"]["s3"]["version"] == "null"+++def test_signer_omitted_version_records_the_stored_version_id(s3, signer, buckets, profile):+ """With no `version` on the wire the current object is signed, and the+ job names the version id S3 really holds for it. "null" is only correct+ for a bucket without versioning (S3 user guide: objects stored before+ the versioning state is set have a version ID of null)."""+ src, dst = buckets+ s3.put_bucket_versioning(+ Bucket=src, VersioningConfiguration={"Status": "Enabled"}+ )+ s3.put_object(Bucket=src, Key="fw.bin", Body=b"older-bytes")+ current = s3.put_object(Bucket=src, Key="fw.bin", Body=b"current-bytes")["VersionId"]+ assert current != "null"+ raw_signer = make_client("signer", {"parameter_validation": False})++ resp = raw_signer.start_signing_job(+ source={"s3": {"bucketName": src, "key": "fw.bin"}},+ destination={"s3": {"bucketName": dst, "prefix": "out/"}},+ profileName=profile,+ )++ marker = json.loads(+ s3.get_object(Bucket=dst, Key=f"out/{resp['jobId']}")["Body"].read()+ )+ assert marker["sourceSha256"] == hashlib.sha256(b"current-bytes").hexdigest()+ assert marker["source"]["version"] == current+ job = signer.describe_signing_job(jobId=resp["jobId"])+ assert job["source"]["s3"]["version"] == current+++def test_signer_versioned_source_signs_the_named_version(signer, s3, buckets, profile):+ src, dst = buckets+ s3.put_bucket_versioning(+ Bucket=src, VersioningConfiguration={"Status": "Enabled"}+ )+ v1 = s3.put_object(Bucket=src, Key="fw.bin", Body=b"version-one")["VersionId"]+ s3.put_object(Bucket=src, Key="fw.bin", Body=b"version-two")++ resp = _start(signer, src, dst, key="fw.bin", profile=profile, version=v1)+ marker = json.loads(+ s3.get_object(Bucket=dst, Key=f"signed/{resp['jobId']}")["Body"].read()+ )+ assert marker["sourceSha256"] == hashlib.sha256(b"version-one").hexdigest()+ assert signer.describe_signing_job(jobId=resp["jobId"])["source"]["s3"]["version"] == v1+++def test_signer_null_version_reads_the_literal_null_version(signer, s3, buckets, profile):+ """`version="null"` must read the stored literal-"null" version, not the+ current object. A pre-versioning write stays addressable as VersionId+ "null" once versioning is enabled on top of it, so on such a bucket the+ two hold DIFFERENT bytes — remapping "null" to "current" signs the wrong+ ones."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="fw.bin", Body=b"pre-versioning-bytes")+ s3.put_bucket_versioning(+ Bucket=src, VersioningConfiguration={"Status": "Enabled"}+ )+ s3.put_object(Bucket=src, Key="fw.bin", Body=b"current-bytes")+ # Sanity: S3 itself serves the two differently.+ null_body = s3.get_object(Bucket=src, Key="fw.bin", VersionId="null")+ assert null_body["Body"].read() == b"pre-versioning-bytes"++ resp = _start(signer, src, dst, key="fw.bin", profile=profile, version="null")+ marker = json.loads(+ s3.get_object(Bucket=dst, Key=f"signed/{resp['jobId']}")["Body"].read()+ )+ assert marker["sourceSha256"] == hashlib.sha256(b"pre-versioning-bytes").hexdigest()+ assert marker["source"]["version"] == "null"+++def test_signer_marker_write_fires_s3_object_created_notification(+ signer, s3, sqs, buckets, profile+):+ """The marker write goes through the same S3 write path as a caller's own+ PutObject, so a bucket notification on the destination must fire for the+ signed-object key."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="notify.bin", Body=b"notify")+ queue_url = sqs.create_queue(QueueName=f"signer-evt-{_uid()}")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]+ s3.put_bucket_notification_configuration(+ Bucket=dst,+ NotificationConfiguration={+ "QueueConfigurations": [+ {"QueueArn": queue_arn, "Events": ["s3:ObjectCreated:*"]}+ ],+ },+ )++ job_id = _start(signer, src, dst, key="notify.bin", profile=profile)["jobId"]++ msgs = sqs.receive_message(+ QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=2+ )+ bodies = [json.loads(m["Body"]) for m in msgs.get("Messages", [])]+ keys = [+ r["s3"]["object"]["key"]+ for b in bodies if "Records" in b+ for r in b["Records"] if r.get("eventSource") == "aws:s3"+ ]+ assert f"signed/{job_id}" in keys+++def test_signer_client_request_token_replays_the_first_response(signer, s3, buckets, profile):+ """API reference: "All calls after the first that use this token return+ the same response as the first call." A retry with the same token must+ not write a second marker."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="idem.bin", Body=b"idem")+ token = str(uuid.uuid4())+ kwargs = dict(+ source={"s3": {"bucketName": src, "key": "idem.bin", "version": "null"}},+ destination={"s3": {"bucketName": dst, "prefix": "signed/"}},+ profileName=profile,+ clientRequestToken=token,+ )+ first = signer.start_signing_job(**kwargs)+ second = signer.start_signing_job(**kwargs)+ assert second["jobId"] == first["jobId"]+ assert second["jobOwner"] == first["jobOwner"]+ assert _keys(s3, dst) == [f"signed/{first['jobId']}"]+ assert [j["jobId"] for j in signer.list_signing_jobs()["jobs"]].count(first["jobId"]) == 1+++def test_signer_raw_wire_start_without_client_request_token(s3, signer, buckets, profile):+ """The model requires clientRequestToken and SDKs autofill it; a raw+ request without one is still accepted (nothing to replay against)."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="raw.bin", Body=b"raw")+ status, body = _raw("POST", "/signing-jobs", {+ "source": {"s3": {"bucketName": src, "key": "raw.bin", "version": "null"}},+ "destination": {"s3": {"bucketName": dst, "prefix": "raw/"}},+ "profileName": profile,+ })+ assert status == 200, body+ assert re.fullmatch(r"\d{12}", body["jobOwner"])+ s3.head_object(Bucket=dst, Key=f"raw/{body['jobId']}")++[email protected]("source_s3", [+ {"bucketName": ["not", "a", "string"], "key": "k", "version": "null"},+ {"bucketName": "bkt", "key": {"nested": True}, "version": "null"},+ {"bucketName": "bkt", "key": "k", "version": 7},+])+def test_signer_raw_wire_non_string_source_members_are_refused(source_s3, buckets, profile):+ """A raw body with a non-string bucketName / key / version is a 400,+ not a server error from the S3 lookup."""+ _src, dst = buckets+ status, body = _raw("POST", "/signing-jobs", {+ "source": {"s3": source_s3},+ "destination": {"s3": {"bucketName": dst}},+ "profileName": profile,+ "clientRequestToken": str(uuid.uuid4()),+ })+ assert status == 400+ assert body["__type"] == "ValidationException"++[email protected]("field, value", [+ ("prefix", ["signed/"]),+ ("clientRequestToken", 12345),+])+def test_signer_raw_wire_non_string_scalars_are_refused(field, value, s3, buckets, profile):+ """A raw body with a non-string destination.s3.prefix or+ clientRequestToken is a 400, not a TypeError deeper in the handler."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="scalar.bin", Body=b"scalar")+ destination = {"bucketName": dst, "prefix": "signed/"}+ payload = {+ "source": {"s3": {"bucketName": src, "key": "scalar.bin", "version": "null"}},+ "destination": {"s3": destination},+ "profileName": profile,+ "clientRequestToken": str(uuid.uuid4()),+ }+ if field == "prefix":+ destination["prefix"] = value+ else:+ payload[field] = value++ status, body = _raw("POST", "/signing-jobs", payload)++ assert status == 400, body+ assert body["__type"] == "ValidationException"+ assert _keys(s3, dst) == []+++def test_signer_missing_source_404_and_no_job_recorded(signer, buckets, profile):+ src, dst = buckets+ missing_key = f"never-uploaded-{_uid()}.bin"+ with pytest.raises(ClientError) as exc:+ _start(signer, src, dst, key=missing_key, profile=profile)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ # Synchronous divergence: the failed Start records nothing, so no job in+ # any status references the missing source.+ jobs = signer.list_signing_jobs()["jobs"]+ assert not any(+ j["source"]["s3"]["key"] == missing_key for j in jobs if "source" in j+ )+++def test_signer_missing_destination_bucket_404_and_no_job_recorded(+ signer, s3, buckets, profile+):+ src, _dst = buckets+ key = f"orphan-{_uid()}.bin"+ s3.put_object(Bucket=src, Key=key, Body=b"data")+ with pytest.raises(ClientError) as exc:+ _start(signer, src, f"no-such-bucket-{_uid()}", key=key, profile=profile)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ jobs = signer.list_signing_jobs()["jobs"]+ assert not any(+ j["source"]["s3"]["key"] == key for j in jobs if "source" in j+ )+++def test_signer_start_with_unknown_profile_is_resource_not_found(signer, s3, buckets):+ """Live-measured: an unknown profileName is refused with+ ResourceNotFoundException "profile with name <name> does not exist".+ Nothing is written and no job is recorded."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="auto.bin", Body=b"auto")+ name = f"ghost_{_uid()}"+ with pytest.raises(ClientError) as exc:+ _start(signer, src, dst, key="auto.bin", profile=name)+ error = exc.value.response["Error"]+ assert error["Code"] == "ResourceNotFoundException"+ assert error["Message"] == f"profile with name {name} does not exist"+ assert _keys(s3, dst) == []+ assert not any(j["profileName"] == name for j in signer.list_signing_jobs()["jobs"])+++# ---------------------------------------------------------------------------+# DescribeSigningJob / ListSigningJobs+# ---------------------------------------------------------------------------++def test_signer_describe_job_succeeded_with_signed_object(signer, s3, buckets, profile):+ src, dst = buckets+ s3.put_object(Bucket=src, Key="app.bin", Body=b"app")+ resp = _start(signer, src, dst, key="app.bin", profile=profile)+ job_id = resp["jobId"]++ job = signer.describe_signing_job(jobId=job_id)+ assert job["jobId"] == job_id+ assert job["status"] == "Succeeded"+ # Live-measured Describe wording on real AWS for a succeeded job.+ assert job["statusReason"] == "Signing Succeeded"+ assert job["profileName"] == profile+ assert job["platformId"] == _IOT_PLATFORM+ assert job["signedObject"]["s3"] == {+ "bucketName": dst, "key": f"signed/{job_id}",+ }+ assert job["source"]["s3"]["bucketName"] == src+ # Timestamp shapes (epoch seconds on the wire) — boto3 parses datetimes.+ assert job["completedAt"] >= job["createdAt"]+ assert job["jobOwner"] == resp["jobOwner"]+ assert job["requestedBy"]+++def test_signer_describe_job_carries_the_profile_material_and_expiry(signer, s3, buckets):+ """signingMaterial, overrides and signingParameters come from the+ profile; signatureExpiresAt is createdAt plus the profile's+ signatureValidityPeriod."""+ src, dst = buckets+ name = f"material_{_uid()}"+ cert = "arn:aws:acm:us-east-1:000000000000:certificate/9ec626ca-0bbb-4be5-83a2-ee563f8386ca"+ signer.put_signing_profile(+ profileName=name,+ platformId=_IOT_PLATFORM,+ signingMaterial={"certificateArn": cert},+ overrides={"signingConfiguration": {"hashAlgorithm": "SHA256"}},+ signingParameters={"build": "42"},+ signatureValidityPeriod={"type": "DAYS", "value": 10},+ )+ s3.put_object(Bucket=src, Key="m.bin", Body=b"m")+ job_id = _start(signer, src, dst, key="m.bin", profile=name)["jobId"]++ job = signer.describe_signing_job(jobId=job_id)+ assert job["signingMaterial"] == {"certificateArn": cert}+ assert job["overrides"] == {"signingConfiguration": {"hashAlgorithm": "SHA256"}}+ assert job["signingParameters"] == {"build": "42"}+ assert (job["signatureExpiresAt"] - job["createdAt"]).days == 10+ listed = next(j for j in signer.list_signing_jobs()["jobs"] if j["jobId"] == job_id)+ assert listed["signingMaterial"] == {"certificateArn": cert}+ assert listed["signatureExpiresAt"] == job["signatureExpiresAt"]+++def test_signer_default_signature_validity_is_135_months(signer, s3, buckets, profile):+ """PutSigningProfile reference: "If unspecified, the default is 135+ months." """+ src, dst = buckets+ s3.put_object(Bucket=src, Key="d.bin", Body=b"d")+ job_id = _start(signer, src, dst, key="d.bin", profile=profile)["jobId"]+ job = signer.describe_signing_job(jobId=job_id)+ created, expires = job["createdAt"], job["signatureExpiresAt"]+ months = (expires.year - created.year) * 12 + expires.month - created.month+ assert months == 135+++def test_signer_describe_unknown_job_404(signer):+ with pytest.raises(ClientError) as exc:+ signer.describe_signing_job(jobId=str(uuid.uuid4()))+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_signer_list_jobs_filters_by_status(signer, s3, buckets, profile):+ src, dst = buckets+ s3.put_object(Bucket=src, Key="list.bin", Body=b"list")+ job_id = _start(signer, src, dst, key="list.bin", profile=profile)["jobId"]++ succeeded = signer.list_signing_jobs(status="Succeeded")["jobs"]+ assert any(j["jobId"] == job_id for j in succeeded)+ assert all(j["status"] == "Succeeded" for j in succeeded)++ # Nothing ever fails asynchronously here, so the Failed page is empty.+ failed = signer.list_signing_jobs(status="Failed")["jobs"]+ assert not any(j["jobId"] == job_id for j in failed)+++def test_signer_list_jobs_status_outside_documented_values_is_refused(signer):+ """Valid Values: InProgress | Failed | Succeeded; botocore does not check+ enums client-side, so a typo reaches the server."""+ with pytest.raises(ClientError) as exc:+ signer.list_signing_jobs(status="Bogus")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_list_jobs_is_revoked_filter(signer, s3, buckets, profile):+ """Nothing is ever revoked here: isRevoked=true is an empty page,+ isRevoked=false lists the job with isRevoked False."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="rev.bin", Body=b"rev")+ job_id = _start(signer, src, dst, key="rev.bin", profile=profile)["jobId"]++ assert signer.list_signing_jobs(isRevoked=True)["jobs"] == []+ not_revoked = signer.list_signing_jobs(isRevoked=False)["jobs"]+ match = next(j for j in not_revoked if j["jobId"] == job_id)+ assert match["isRevoked"] is False+++def test_signer_list_jobs_platform_id_filter(signer, s3, buckets, profile):+ src, dst = buckets+ lam = f"lam_{_uid()}"+ signer.put_signing_profile(profileName=lam, platformId=_LAMBDA_PLATFORM)+ s3.put_object(Bucket=src, Key="p.bin", Body=b"p")+ iot_job = _start(signer, src, dst, key="p.bin", profile=profile)["jobId"]+ lam_job = _start(signer, src, dst, key="p.bin", profile=lam)["jobId"]++ lam_ids = [j["jobId"] for j in signer.list_signing_jobs(platformId=_LAMBDA_PLATFORM)["jobs"]]+ assert lam_job in lam_ids and iot_job not in lam_ids+ assert signer.list_signing_jobs(platformId="NoSuchPlatform")["jobs"] == []+++def test_signer_list_jobs_requested_by_and_job_invoker_filters(signer, s3, buckets, profile):+ src, dst = buckets+ s3.put_object(Bucket=src, Key="who.bin", Body=b"who")+ job_id = _start(signer, src, dst, key="who.bin", profile=profile)["jobId"]+ job = signer.describe_signing_job(jobId=job_id)++ by_requester = signer.list_signing_jobs(requestedBy=job["requestedBy"])["jobs"]+ assert any(j["jobId"] == job_id for j in by_requester)+ assert signer.list_signing_jobs(requestedBy="arn:aws:iam::000000000000:user/nobody")["jobs"] == []++ by_invoker = signer.list_signing_jobs(jobInvoker=job["jobInvoker"])["jobs"]+ assert any(j["jobId"] == job_id for j in by_invoker)+ assert signer.list_signing_jobs(jobInvoker="999999999999")["jobs"] == []+++def test_signer_list_jobs_max_results_pages_with_a_next_token(signer, s3, buckets, profile):+ """maxResults limits the page and the response carries a nextToken while+ jobs remain, so a paginator reaches all of them."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="t.bin", Body=b"t")+ started = {_start(signer, src, dst, key="t.bin", profile=profile)["jobId"]+ for _ in range(3)}++ page = signer.list_signing_jobs(maxResults=1)+ assert len(page["jobs"]) == 1+ assert page.get("nextToken")++ # Walk to the end: the suite shares one store, so the three jobs of this+ # test are somewhere in a longer list.+ seen = [page["jobs"][0]["jobId"]]+ token = page["nextToken"]+ for _ in range(200):+ page = signer.list_signing_jobs(maxResults=1, nextToken=token)+ seen.extend(job["jobId"] for job in page["jobs"])+ token = page.get("nextToken")+ if not token:+ break+ assert not token, "the walk never reached the last page"+ assert started.issubset(set(seen))+ assert len(seen) == len(set(seen)), seen++ # The paginator boto3 builds from the model walks the same list.+ paginated = [job["jobId"] for page in+ signer.get_paginator("list_signing_jobs").paginate(+ PaginationConfig={"PageSize": 1})+ for job in page["jobs"]]+ assert started.issubset(set(paginated))+++def test_signer_list_jobs_last_page_has_no_next_token(signer, s3, buckets, profile):+ """A page that exhausts the list carries no token, which is what stops a+ paginator."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="t.bin", Body=b"t")+ _start(signer, src, dst, key="t.bin", profile=profile)++ page = signer.list_signing_jobs(maxResults=25)+ assert page["jobs"]+ assert "nextToken" not in page+++def test_signer_job_records_the_calling_principal(signer, s3, buckets, profile):+ """AWS reports the IAM principal that requested the job. A job started+ with an IAM user's access key records that user, not the account root,+ so the requestedBy filter can find it again."""+ import boto3++ iam = make_client("iam")+ user_name = f"signer-caller-{_uid()}"+ user_arn = iam.create_user(UserName=user_name)["User"]["Arn"]+ key = iam.create_access_key(UserName=user_name)["AccessKey"]+ src, dst = buckets+ s3.put_object(Bucket=src, Key="who.bin", Body=b"w")+ try:+ as_user = boto3.client(+ "signer",+ endpoint_url=signer.meta.endpoint_url,+ region_name=signer.meta.region_name,+ aws_access_key_id=key["AccessKeyId"],+ aws_secret_access_key=key["SecretAccessKey"],+ )+ job = _start(as_user, src, dst, key="who.bin", profile=profile)+ described = signer.describe_signing_job(jobId=job["jobId"])+ assert described["requestedBy"] == user_arn+ assert signer.list_signing_jobs(requestedBy=user_arn)["jobs"]+ finally:+ iam.delete_access_key(UserName=user_name, AccessKeyId=key["AccessKeyId"])+ iam.delete_user(UserName=user_name)+++def test_signer_list_jobs_token_is_bound_to_its_filter_set(signer, s3, buckets, profile):+ """A token is only meaningful for the list it came from, so resuming with+ a different filter is refused rather than served from a position that+ means nothing for the new list."""+ src, dst = buckets+ s3.put_object(Bucket=src, Key="bound.bin", Body=b"b")+ for _ in range(2):+ _start(signer, src, dst, key="bound.bin", profile=profile)++ page = signer.list_signing_jobs(maxResults=1, status="Succeeded")+ assert page.get("nextToken")+ with pytest.raises(ClientError) as exc:+ signer.list_signing_jobs(maxResults=1, nextToken=page["nextToken"])+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ # The same token resumes fine under the filter set it was minted with.+ assert "jobs" in signer.list_signing_jobs(+ maxResults=1, status="Succeeded", nextToken=page["nextToken"])+++def test_signer_list_jobs_revoked_filter_still_refuses_a_foreign_token(signer):+ """isRevoked=true short-circuits to an empty page, but a token that is not+ ours is a 400 there too: the same value cannot be a 400 alone and a 200+ next to another filter."""+ with pytest.raises(ClientError) as exc:+ signer.list_signing_jobs(isRevoked=True, nextToken="not-a-real-token")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert signer.list_signing_jobs(isRevoked=True)["jobs"] == []+++def test_signer_list_jobs_foreign_next_token_is_refused(signer):+ """A token MiniStack did not mint is a 400, not a silent full listing."""+ with pytest.raises(ClientError) as exc:+ signer.list_signing_jobs(nextToken="not-a-real-token")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_list_jobs_malformed_max_results_is_validation_error(signer):+ """A non-numeric maxResults is a 400 ValidationException, not a 500."""+ raw_signer = make_client("signer", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ raw_signer.list_signing_jobs(maxResults="not-a-number")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_list_jobs_max_results_above_documented_maximum_is_refused(signer):+ """The API reference documents maxResults as 1 to 25; botocore checks+ only the minimum client-side, so the server has to refuse 26."""+ with pytest.raises(ClientError) as exc:+ signer.list_signing_jobs(maxResults=26)+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ assert isinstance(signer.list_signing_jobs(maxResults=25)["jobs"], list)+++# ---------------------------------------------------------------------------+# Signing profiles+# ---------------------------------------------------------------------------++def test_signer_profile_put_get_round_trip(signer):+ name = f"explicit_profile_{_uid()}"+ put = signer.put_signing_profile(+ profileName=name, platformId=_LAMBDA_PLATFORM+ )+ assert put["arn"].endswith(f":/signing-profiles/{name}")+ assert put["profileVersionArn"] == f"{put['arn']}/{put['profileVersion']}"++ got = signer.get_signing_profile(profileName=name)+ assert got["profileName"] == name+ assert got["platformId"] == _LAMBDA_PLATFORM+ assert got["profileVersion"] == put["profileVersion"]+ assert got["status"] == "Active"+++def test_signer_get_unknown_profile_404(signer):+ with pytest.raises(ClientError) as exc:+ signer.get_signing_profile(profileName=f"ghost_{_uid()}")+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++[email protected]("name", ["fw-profile", "p" * 65])+def test_signer_profile_name_outside_documented_pattern_is_refused(+ signer, s3, buckets, name+):+ """ProfileName is 2 to 64 characters; the reference pattern+ ^[a-zA-Z0-9_]{2,} is applied to the whole name. botocore checks only the+ minimum length client-side, so the hyphen and the 65-character name+ reach the server and must be refused on every operation that takes the+ name."""+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(profileName=name, platformId=_LAMBDA_PLATFORM)+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ with pytest.raises(ClientError) as exc:+ signer.get_signing_profile(profileName=name)+ assert exc.value.response["Error"]["Code"] == "ValidationException"++ src, dst = buckets+ s3.put_object(Bucket=src, Key="named.bin", Body=b"named")+ with pytest.raises(ClientError) as exc:+ _start(signer, src, dst, key="named.bin", profile=name)+ assert exc.value.response["Error"]["Code"] == "ValidationException"+ # Refused before anything is written: no marker, no job.+ assert _keys(s3, dst) == []+++def test_signer_put_profile_requires_platform_id(signer):+ raw_signer = make_client("signer", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ raw_signer.put_signing_profile(profileName=f"no_platform_{_uid()}")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_put_profile_accepts_a_partial_validity_period(signer):+ """Both members of SignatureValidityPeriod are documented Required: No, so+ a period carrying only one of them is a valid request."""+ for period in ({"type": "DAYS"}, {"value": 12}, {}):+ name = f"partial_{_uid()}"+ signer.put_signing_profile(+ profileName=name,+ platformId=_IOT_PLATFORM,+ signatureValidityPeriod=period,+ )+ assert signer.get_signing_profile(profileName=name)["profileName"] == name+++def test_signer_put_profile_rejects_an_unknown_override_enum(signer):+ """SigningPlatformOverrides.signingImageFormat is JSON | JSONEmbedded |+ JSONDetached, and the nested configuration overrides are RSA | ECDSA and+ SHA1 | SHA256. botocore does not check enums client-side."""+ for overrides in (+ {"signingImageFormat": "PNG"},+ {"signingConfiguration": {"encryptionAlgorithm": "DSA"}},+ {"signingConfiguration": {"hashAlgorithm": "MD5"}},+ ):+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(+ profileName=f"ovr_{_uid()}",+ platformId=_IOT_PLATFORM,+ overrides=overrides,+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"++ # The documented values are accepted.+ name = f"ovr_{_uid()}"+ signer.put_signing_profile(+ profileName=name,+ platformId=_IOT_PLATFORM,+ overrides={+ "signingImageFormat": "JSONDetached",+ "signingConfiguration": {"encryptionAlgorithm": "ECDSA",+ "hashAlgorithm": "SHA256"},+ },+ )+ profile = signer.get_signing_profile(profileName=name)+ assert profile["overrides"]["signingImageFormat"] == "JSONDetached"+++def test_signer_put_profile_requires_the_signing_material_certificate(signer):+ """SigningMaterial.certificateArn is the shape's one member and is+ Required: Yes."""+ # botocore enforces the required member client-side, so the server-side+ # check is reachable only from a client that does not validate.+ raw_signer = make_client("signer", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ raw_signer.put_signing_profile(+ profileName=f"mat_{_uid()}",+ platformId=_IOT_PLATFORM,+ signingMaterial={},+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_put_profile_enforces_the_tag_constraints(signer):+ """Keys are 1..128 and match ^(?!aws:)[a-zA-Z+-=._:/]+$, values are at+ most 256 characters, and the map takes at most 200 entries."""+ for tags in (+ {"aws:reserved": "x"},+ {"has space": "x"},+ {"k" * 129: "x"},+ {"k": "v" * 257},+ {f"k{i}": "v" for i in range(201)},+ ):+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(+ profileName=f"tag_{_uid()}", platformId=_IOT_PLATFORM, tags=tags)+ assert exc.value.response["Error"]["Code"] == "ValidationException", tags++ name = f"tag_{_uid()}"+ signer.put_signing_profile(+ profileName=name, platformId=_IOT_PLATFORM, tags={"team.name": "iot"})+ assert signer.get_signing_profile(profileName=name)["tags"] == {"team.name": "iot"}+++def test_signer_rejects_malformed_account_id_members(signer, s3, buckets, profile):+ """jobInvoker on ListSigningJobs and profileOwner on StartSigningJob are+ both a fixed length of 12 digits."""+ raw_signer = make_client("signer", {"parameter_validation": False})+ with pytest.raises(ClientError) as exc:+ raw_signer.list_signing_jobs(jobInvoker="not-an-account")+ assert exc.value.response["Error"]["Code"] == "ValidationException"++ src, dst = buckets+ s3.put_object(Bucket=src, Key="owner.bin", Body=b"x")+ with pytest.raises(ClientError) as exc:+ raw_signer.start_signing_job(+ source={"s3": {"bucketName": src, "key": "owner.bin"}},+ destination={"s3": {"bucketName": dst}},+ profileName=profile,+ profileOwner="12345",+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_signer_put_profile_rejects_unknown_validity_unit(signer):+ """SignatureValidityPeriod.type: DAYS | MONTHS | YEARS."""+ with pytest.raises(ClientError) as exc:+ signer.put_signing_profile(+ profileName=f"unit_{_uid()}",+ platformId=_IOT_PLATFORM,+ signatureValidityPeriod={"type": "WEEKS", "value": 2},+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"