Skip to content

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

prerelease (#2436)

Nahuel Nucera3e918c469663
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66e638b9..78a5655d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **S3 — persisted keys that a file path can't hold survive a restart** — with `S3_PERSIST=1` a key ending in `/` (a folder marker such as `project/Incoming/`) came back without its slash, and keys under it, a key under another key's object (`a/b` beside `a`), or one with doubled or dot segments (`x//y`) were lost or rewritten on restart. Such keys are now stored by an encoded name under the bucket's `.ministack-keys` directory, with the key in their sidecar, and every other key keeps its own path, so data saved by earlier versions still loads. Reported by @jasonthagerty.
- **S3 — HEAD identifiers and Iceberg REST routing** — ordinary HEAD responses retain an existing AWS-format request ID and HostId, normalizing only a missing or legacy request ID and filling a missing HostId. Iceberg REST HEAD requests signed with the `s3` scope retain the catalog's JSON error format instead of being rewritten as S3 XML.
-- **S3 — GET/HEAD/DELETE error precedence and responses** — ordinary header-signed downloads under `AUTH=true` check the endpoint/signing region before the bucket's home region, then credentials and missing buckets, matching real AWS observations from Osaka. Authentication errors include S3 signature diagnostics, missing keys include `Key`, and these errors carry matching XML/header request identifiers. HeadObject, HeadBucket and DeleteObject check the bucket's home region first, like PUT; a DELETE sent to another regional endpoint no longer succeeds merely because it was signed for the bucket's home. HEAD returns empty error responses without a Content-Length header, and HeadBucket reports an existing bucket's region even on a denial and its ARN on success. IAM still gates existing objects and buckets, and deleting an absent key remains idempotent. Presigned and subresource requests keep their existing paths.
+- **S3 — GET/HEAD/DELETE error precedence and responses** — ordinary header-signed downloads under `AUTH=true` check the endpoint/signing region before the bucket's home region, then credentials and missing buckets, matching real AWS observations from Osaka. Authentication errors include S3 signature diagnostics, missing keys include `Key`, and these errors carry matching XML/header request identifiers. HeadObject, HeadBucket and DeleteObject check the bucket's home region first, like PUT; a DELETE sent to another regional endpoint no longer succeeds merely because it was signed for the bucket's home. HEAD returns empty error responses without a Content-Length header, and HeadBucket reports an existing bucket's region even on a denial and its ARN on success. These response shapes (the `Key` in `NoSuchKey`, empty HEAD errors, the HeadBucket region and ARN) apply with `AUTH` unset too; only the region and credential order needs `AUTH=true`. IAM still gates existing objects and buckets, and deleting an absent key remains idempotent. Presigned and subresource requests keep their existing paths.
- **Glue — a job's own botocore loads from where the script asks** — the Spark boot shim imported `botocore` before the job script ran, so a `--py-files` deps zip that holds botocore gave the zipped copy, and a script that then swapped the zip for its extracted folder failed with `DataNotFoundError: Unable to load data for: endpoints`; the shim now patches `Session.create_client` when the script first imports `botocore.session`, and still adds `endpoint_url` only when the caller sets none.
- **Glue — Spark job scripts get `--JOB_NAME` and `--JOB_RUN_ID`** — a Spark job run passed only the job's `DefaultArguments` and the run's `Arguments`, so a script that reads `JOB_NAME` or `JOB_RUN_ID` with `getResolvedOptions` failed; both now reach the script, as on AWS. They replace a value in `DefaultArguments`, and a value in the run's `Arguments` replaces them. `pythonshell` scripts don't get them, as on AWS. `GetJobRun` still shows only the arguments the caller gave.
- **Step Functions — JSONata fields on an inline `Map`** — `Items`, `ItemSelector`, `MaxConcurrency`, `Output` and `Assign` were ignored or read as JSONPath, so the Map iterated over the whole input, iterations got literal `{% ... %}` text, a `MaxConcurrency` expression failed with `States.Runtime`, and `Assign` variables were never set; all five are now evaluated, as on AWS. `Items` that is not an array fails with `States.QueryEvaluationError`.
@@ -18,11 +19,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Lambda — Kinesis event source mapping filters** — a `FilterCriteria` pattern on a Kinesis record's `data` or on its metadata (`partitionKey`, `sequenceNumber`, ...) never matched, so a mapping with filters dropped every record. Patterns are now matched as AWS documents them: metadata fields next to the event fields, and `data` decoded from base64 as JSON. Data that isn't JSON can't match a `data` pattern but still matches metadata patterns.
- **Lambda — two MiniStacks on one host no longer remove each other's function code** — the provided-runtime and Docker-executor extraction caches lived at fixed paths in the shared temp directory, so a second instance on the same host deleted a tree the first was still running from ("leftover from a previous process") and its `reset()` removed the first one's caches; an invocation then failed with `No such file or directory: .../bootstrap`. Both caches are now named for the instance's `GATEWAY_PORT`. Contributed by @skialpine.
### Added
-- **OpenSearch — `OPENSEARCH_JAVA_OPTS`** — a small machine could not cap the heap of the engine containers MiniStack starts; the setting is now passed to each of them (per-domain and Serverless collection), and unset passes nothing. Contributed by @skialpine.
+- **CloudFormation — `AWS::Athena::WorkGroup`** — a template with a workgroup failed with "Unrecognized resource types"; the workgroup is now created with its `Description`, `State`, `Tags` and `WorkGroupConfiguration`, updated in place when they change, replaced when `Name` changes, and deleted with the stack. `Ref` returns the name and `Fn::GetAtt` `CreationTime` and the effective engine version, as the template reference describes. Reported by @mishukdutta-cz.
+- **Kinesis — stream and consumer resource policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` answered `InvalidAction`; they now store a policy per stream or consumer, persisted and dropped with it, with AWS's checks in AWS's order: the ARN's region (`InvalidArgumentException` "The region specified in the ARN '<arn>' does not match the endpoint region"), the policy ("Policy validation error: This policy contains invalid Json", "Missing required field Version" or "Statement", and per statement the actions a stream or consumer can share and a `Resource` equal to the ARN, with the statement's line and column), then the resource ("Stream <name> under account <id> not found."). `GetResourcePolicy` without a policy answers `{"Policy": "{}"}` and `DeleteResourcePolicy` "No resource policy found for resource ARN <arn>.". Cross-account event source mappings are not covered yet. Reported by @Jolley71717.
+- **OpenSearch — engine containers run with a 512 MB heap** — every container MiniStack starts for a domain or Serverless collection used the image's 1 GB heap, too much for a small machine with several of them; each now runs with `-Xms512m -Xmx512m`, the heap OpenSearch's sample docker-compose uses. Contributed by @skialpine.
### Fixed
+- **Lambda — two MiniStacks on one host no longer remove each other's function code** — the provided-runtime and Docker-executor extraction caches lived at fixed paths in the shared temp directory, so a second instance on the same host deleted a tree the first was still running from ("leftover from a previous process") and its `reset()` removed the first one's caches; an invocation then failed with `No such file or directory: .../bootstrap`. Both caches are now named for the instance's `GATEWAY_PORT`. Contributed by @skialpine.
- **OpenSearch — the container reaper no longer removes a live domain's exited engine** — the reaper read a container id key that only the deferred create path set, so it took a domain's stopped engine for abandoned and removed it after two minutes; it now reads the key every domain record keeps. Contributed by @skialpine.
-### Fixed
- **Lambda — restoring persisted state shares code between versions** — each function version got its own copy of its zip at boot, although versions share one blob file, so a state with many versions took gigabytes before the first request. Records that share a blob now share its bytes. Contributed by @skialpine.
- **Lambda — a package that is not a zip is refused** — `CreateFunction`, `UpdateFunctionCode` and `PublishLayerVersion` accepted a package that is not a zip (an empty file included) and answered success, `UpdateFunctionCode` keeping the previous code. They now answer `InvalidParameterValueException` `Could not unzip uploaded file. Please check your file, then try to upload again.` Contributed by @skialpine.
- **DynamoDB — `TransactWriteItems` follows DynamoDB's check order** — an `Update` whose `ConditionExpression` failed was cancelled with `ValidationError` when its `UpdateExpression` could not be applied to the item (for example `SET #c = #c + :one` on a missing item); it now cancels with `ConditionalCheckFailed`, as `UpdateItem` answers `ConditionalCheckFailedException` for the same request. Such an update-expression error on one member no longer hides a failed condition on another: both reasons are returned, while wrong-typed keys and index keys still cancel before any condition. A missing table answers `ResourceNotFoundException` even when another member has a `ValidationError`, and a `begins_with` condition with a number operand answers `ValidationException` instead of an internal error, as on AWS. Contributed by @jun-ut.
@@ -33,14 +36,15 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **HTTP/1.1 status lines carry their reason phrase** — final responses were written as `HTTP/1.1 200 `, so a CloudFront Function saw an empty `statusDescription`. They now read `HTTP/1.1 200 OK`, `404 Not Found`. Contributed by @skialpine.
- **Responses carry one `Date`** — a proxied response carried the target's `Date` and a second one from Hypercorn. The app now adds `Date` to a response that has none, including a WebSocket handshake, and Hypercorn adds none; an ALB writes its own `Date` in place of an instance or IP target's, as AWS does, and CloudFront keeps the origin's. Hypercorn's own error responses, such as a malformed request's 400 and a WebSocket handshake refused with `websocket.close`, carry one `Date` too. Contributed by @skialpine.
- **CloudFront — `X-Amz-Cf-Id` and `Via` have CloudFront's shape** — the data plane sent 56 characters of standard base64 without padding as `X-Amz-Cf-Id` and a 13-character token in `Via`. It now sends URL-safe base64 of 40 bytes with its `==` padding, and `Via: 1.1 <32 hex>.cloudfront.net (CloudFront)`. Contributed by @skialpine.
-- **ALB — the listener's CORS response headers are applied** — `routing.http.response.access_control_*.header_value` set with `ModifyListenerAttributes` had no effect. Each non-empty value is now added to the listener's responses, replacing the target's header of that name. Contributed by @skialpine.
-- **ALB and CloudFront responses carry only their own headers** — the gateway added `x-amzn-requestid` and `x-amz-request-id` to both and `Access-Control-Allow-Origin: *` to ALB responses. They now carry what the target or origin sent, plus the load balancer's or CloudFront's own: `Server: awselb/2.0` on a response the load balancer makes itself (a Lambda target's, fixed-response, redirect, authentication, its own errors), and `Server: CloudFront` when the origin sends none. Contributed by @skialpine.
+- **ALB — the listener's response-header attributes are applied** — `routing.http.response.access_control_*`, `strict_transport_security`, `content_security_policy`, `x_content_type_options` and `x_frame_options` `.header_value` set with `ModifyListenerAttributes` had no effect. Each non-empty value is now added to the listener's responses, replacing the target's header of that name, and `routing.http.response.server.enabled` `false` drops the load balancer's `Server: awselb/2.0`. Contributed by @skialpine.
+- **ALB and CloudFront responses carry only their own headers** — the gateway added `x-amzn-requestid` and `x-amz-request-id` to both and `Access-Control-Allow-Origin: *` to ALB responses. They now carry what the target or origin sent, plus the load balancer's or CloudFront's own: `Server: awselb/2.0` on a response the load balancer makes itself (a Lambda target's, fixed-response, redirect, authentication, its own errors), and `Server: CloudFront` when the origin sends none and a viewer-response function ran. Lambda Function URL responses carry only their own `x-amzn-RequestId`, no second request id or `x-amz-request-id`. Contributed by @skialpine.
- **Responses carry no Hypercorn `Server` header** — every response carried `Server: hypercorn-h11`, which no AWS endpoint sends. Hypercorn no longer adds it; services that send their own `Server` are unchanged. Contributed by @skialpine.
- **ALB — `Accept-Encoding` reaches HTTP targets** — the data plane dropped the client's `Accept-Encoding`, so a target never compressed its response. It is now forwarded, and the target's encoded response is passed through unchanged. Contributed by @skialpine.
- **API Gateway — an HTTP API's `rawQueryString` is the query string as the client sent it** — a bare key gained an `=` (`?flag` reached the function as `flag=`). Both the Lambda proxy event and the REQUEST authorizer event now carry the request's own query string. Contributed by @skialpine.
- **ALB — an OPTIONS request reaches the target** — the gateway answered every preflight to a load balancer address with its own wildcard CORS response. The request is now forwarded to the target like any other method. Contributed by @skialpine.
- **ALB — the query string reaches HTTP targets unchanged** — it was rebuilt from the first value of each key, so `?page=1&page=2` arrived as `?page=1`. The request's own query string is now forwarded, including from a CloudFront distribution whose origin is the load balancer. Contributed by @skialpine.
- **ALB — instance and IP targets receive the client's `Host`** — they got their own address as `Host`. They now get the client's, as an Application Load Balancer sends it: on a listener on port 80 or 443 without a port, on any other listener with the listener's port in place of any port the client sent; `routing.http.preserve_host_header.enabled` sends it unmodified. Lambda targets keep the `Host` exactly as sent, and authentication uses the client's `Host`. Contributed by @skialpine.
+- **Lambda — a Kinesis event source mapping in another region or account answers as AWS does** — `CreateEventSourceMapping` now refuses another region's stream with "Event source region must match Lambda region <region>" and another account's with "Received Exception while reading from provided stream. No account found for the given parameters". Reported by @Jolley71717.
## [1.5.32] — 2026-10-23
diff --git a/README.md b/README.md
index 2f6d40bb..68810808 100644
--- a/README.md
+++ b/README.md
@@ -422,7 +422,7 @@ subnet = ec2.create_subnet(
|---------|-----------|-------|
| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource, GetServiceSetting, UpdateServiceSetting, ResetServiceSetting | Supports String, SecureString, StringList; `name:version` and `name:label` selectors on `GetParameter` / `GetParameters` |
| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path parameter values resolved from the untransformed event, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
-| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, SubscribeToShard, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key); SubscribeToShard pushes `SubscribeToShardEvent`s over HTTP/1.1 or HTTP/2 (h2c) for up to 5 minutes, JSON or CBOR |
+| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, SubscribeToShard, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key); SubscribeToShard pushes `SubscribeToShardEvent`s over HTTP/1.1 or HTTP/2 (h2c) for up to 5 minutes, JSON or CBOR |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates, CreateReceiptRuleSet, DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet, SetActiveReceiptRuleSet, DescribeActiveReceiptRuleSet, CreateReceiptRule, DescribeReceiptRule, DeleteReceiptRule | Emails stored in-memory, not sent; the sender must be a verified identity (`MessageRejected` otherwise), and a sandboxed account sends only to verified or `@simulator.amazonses.com` recipients; receipt rule sets and ordered rules, with every action type, are stored and persisted; inbound email receiving is not emulated; a send publishes a `Delivery`, `Bounce` or `Complaint` notification per recipient to the identity's `SetIdentityNotificationTopic` SNS topic, following the mailbox simulator |
| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, PutConfigurationSetTrackingOptions, PutConfigurationSetDeliveryOptions, PutConfigurationSetReputationOptions, PutConfigurationSetSendingOptions, PutConfigurationSetSuppressionOptions, PutConfigurationSetVdmOptions, PutConfigurationSetArchivingOptions, CreateConfigurationSetEventDestination, GetConfigurationSetEventDestinations, UpdateConfigurationSetEventDestination, DeleteConfigurationSetEventDestination, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountDetails, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource, CreateTenant, GetTenant, ListTenants, DeleteTenant, CreateTenantResourceAssociation, DeleteTenantResourceAssociation, ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes, CreateDedicatedIpPool, GetDedicatedIpPool, ListDedicatedIpPools, DeleteDedicatedIpPool | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent; `PutAccountDetails` with `ProductionAccessEnabled=false` puts the account in the sandbox; email templates share the v1 store, so `SendEmail` with `Content.Template` renders a template created through either API version; a configuration set, identity or template associated with a tenant cannot be deleted until the association is removed; dedicated IP pools are records only, with no IP addresses behind them |
@@ -509,6 +509,7 @@ subnet = ec2.create_subnet(
| `AWS::ElastiCache::ReplicationGroup` | Replication group id | PrimaryEndPoint.Address, PrimaryEndPoint.Port, ReaderEndPoint.Address, ReaderEndPoint.Port, ReadEndPoint.Addresses, ReadEndPoint.Ports, ReadEndPoint.AddressesList, ReadEndPoint.PortsList (cluster mode disabled); ConfigurationEndPoint.Address, ConfigurationEndPoint.Port (cluster mode enabled) |
| `AWS::ElastiCache::User` | User id | Arn, Status |
| `AWS::ElastiCache::UserGroup` | User group id | Arn, Status |
+| `AWS::Athena::WorkGroup` | Workgroup name | CreationTime, WorkGroupConfiguration.EngineVersion.EffectiveEngineVersion |
| `AWS::Glue::Database` | Database name | — |
| `AWS::Glue::Table` | Table name | — |
| `AWS::Glue::Partition` | `<catalog id>\|<database>\|<table>\|<values hash>` | IdentifierPartitionInputValues |
@@ -921,7 +922,6 @@ When Docker is available, `StartApplication` for a `FLINK-1_19` or `FLINK-1_20`
| `OPENSEARCH_DATAPLANE` | `0` | Set `1` to spawn a real `opensearchproject/opensearch` container per `CreateDomain` and per OpenSearch Serverless `CreateCollection`. Default `0` returns a stub endpoint (`<domain>.ministack.local:9200`) — management plane only |
| `OPENSEARCH_BASE_PORT` | `14571` | Starting host port for per-domain OpenSearch containers when `OPENSEARCH_DATAPLANE=1` |
| `OPENSEARCH_IMAGE` | `opensearchproject/opensearch:2.15.0` | Image used when spawning per-domain OpenSearch containers |
-| `OPENSEARCH_JAVA_OPTS` | _(unset)_ | JVM options (for example `-Xms512m -Xmx512m`) passed as `OPENSEARCH_JAVA_OPTS` to every OpenSearch container, per-domain and OpenSearch Serverless collection; unset, nothing is passed and the image keeps its default heap (`jvm.options`, 1 GB) |
| `OPENSEARCH_DASHBOARDS` | `0` | Set `1` (together with `OPENSEARCH_DATAPLANE=1`) to also spawn a per-domain `opensearchproject/opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated |
| `OPENSEARCH_DASHBOARDS_BASE_PORT` | `15601` | Starting host port for per-domain Dashboards containers |
| `OPENSEARCH_DASHBOARDS_IMAGE` | `opensearchproject/opensearch-dashboards:2.15.0` | Image used when spawning per-domain Dashboards containers |
diff --git a/ministack/app.py b/ministack/app.py
index 8c47b99d..ca5a9255 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2695,7 +2695,11 @@ async def _handle_special_data_plane_request(
):
return _with_data_plane_headers(response, request_id, wildcard_cors=False)
if response := await _handle_lambda_url_request(host, path, method, headers, body, query_params):
- return _with_data_plane_headers(response, request_id, wildcard_cors=False)
+ # A Function URL names its own x-amzn-RequestId and X-Amzn-Trace-Id; it sends no other request ids.
+ status, resp_headers, resp_body = response
+ if not any(k.lower() == "x-amzn-requestid" for k in resp_headers):
+ resp_headers["x-amzn-RequestId"] = request_id
+ return status, resp_headers, resp_body
if response := await _handle_s3_vhost_request(host, path, method, headers, body, query_params):
if AUTH and (target := _s3_cors_target(host, path, path_style=False)):
response[1].update(_get_module("s3").cors_response_headers(target[0], method, headers))
@@ -3404,7 +3408,7 @@ async def app(scope, receive, send):
# IAM denials. Presigns, access points and subresources keep their handlers.
head_path = None
# Iceberg routes are selected before S3, even when signed with scope s3.
- if (AUTH and method == "HEAD" and not path.startswith("/iceberg")
+ if (method == "HEAD" and not path.startswith("/iceberg")
and detect_service(method, path, headers, query_params) == "s3"):
host = headers.get("host", "")
bucket = _extract_s3_vhost_bucket(host)
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 5f7452c3..5931ddfc 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -1250,7 +1250,8 @@ def extract_resource_arn(service: str, method: str, path: str,
return "*"
if service == "kinesis":
- arn = _safe_json_field(body, "StreamARN")
+ # The resource-policy operations name their stream or consumer as ResourceARN.
+ arn = _safe_json_field(body, "ResourceARN") or _safe_json_field(body, "StreamARN")
if arn:
return arn
name = _safe_json_field(body, "StreamName")
diff --git a/ministack/services/alb.py b/ministack/services/alb.py
index 44d9c9ea..95e5b7c4 100644
--- a/ministack/services/alb.py
+++ b/ministack/services/alb.py
@@ -2376,6 +2376,10 @@ _LISTENER_RESPONSE_HEADERS = {
("access_control_allow_credentials", "Access-Control-Allow-Credentials"),
("access_control_expose_headers", "Access-Control-Expose-Headers"),
("access_control_max_age", "Access-Control-Max-Age"),
+ ("strict_transport_security", "Strict-Transport-Security"),
+ ("content_security_policy", "Content-Security-Policy"),
+ ("x_content_type_options", "X-Content-Type-Options"),
+ ("x_frame_options", "X-Frame-Options"),
)
}
@@ -2392,14 +2396,18 @@ def _with_listener_response_headers(listener_arn, response):
return status, {**{k: v for k, v in headers.items() if k.lower() not in replaced}, **added}, body
-def _with_alb_server(response):
+def _with_alb_server(response, listener_arn=None):
"""A response the load balancer makes itself (Lambda target, fixed-response, redirect, authentication, its own
- errors) carries its Server header; an instance or IP target's response keeps the target's own, or none."""
+ errors) carries its Server header unless the listener's routing.http.response.server.enabled is false; an
+ instance or IP target's response keeps the target's own, or none."""
from ministack.core.responses import StreamingResponse
status, headers, body = response
if isinstance(body, StreamingResponse) or any(k.lower() == "server" for k in headers):
return response
+ if listener_arn and any(a.get("Key") == "routing.http.response.server.enabled" and a.get("Value") == "false"
+ for a in _listener_attrs.get(listener_arn, [])):
+ return response
return status, {**headers, "Server": "awselb/2.0"}, body
@@ -2441,10 +2449,10 @@ async def dispatch_request(lb, method, path, headers, body, query_params, port=8
target_headers, body, query_params, port,
lb_arn=lb.get("LoadBalancerArn", ""), target_host=target_host,
raw_query_string=raw_query_string, raw_path=raw_path)
- return _with_listener_response_headers(l_arn, _with_alb_server(response))
+ return _with_listener_response_headers(l_arn, _with_alb_server(response, l_arn))
return _with_alb_server((502, {"Content-Type": "application/json"},
- json.dumps({"message": "No matching ALB rule found"}).encode()))
+ json.dumps({"message": "No matching ALB rule found"}).encode()), l_arn)
def reset():
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 6230740c..afc385e1 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -25,6 +25,7 @@ import ministack.services.apigateway as _apigw_v2
import ministack.services.apigateway_v1 as _apigw_v1
import ministack.services.appconfig as _appconfig
import ministack.services.appsync as _appsync
+import ministack.services.athena as _athena
import ministack.services.autoscaling as _asg
import ministack.services.backup as _backup
import ministack.services.cloudfront as _cf
@@ -13498,6 +13499,56 @@ def _glue_reset_dropped(old_props, new_props, defaults):
return {k: v for k, v in defaults.items() if k in old_props and k not in new_props}
+def _athena_workgroup_attributes(name):
+ workgroup = _athena._workgroups[name]
+ engine = (workgroup.get("Configuration") or {}).get("EngineVersion") or {}
+ selected = engine.get("SelectedEngineVersion")
+ effective = engine.get("EffectiveEngineVersion") or (
+ selected if selected and selected != "AUTO" else "Athena engine version 3")
+ return {
+ "CreationTime": str(workgroup["CreationTime"]),
+ "WorkGroupConfiguration.EngineVersion.EffectiveEngineVersion": effective,
+ "WorkGroupConfigurationUpdates.EngineVersion.EffectiveEngineVersion": effective,
+ }
+
+
+def _athena_workgroup_apply(name, props):
+ """The properties AWS updates in place (template reference: Update requires No interruption)."""
+ workgroup = _athena._workgroups[name]
+ workgroup["Description"] = props.get("Description", "")
+ workgroup["State"] = props.get("State") or "ENABLED"
+ workgroup["Configuration"] = copy.deepcopy(props.get("WorkGroupConfiguration") or {})
+ arn = _athena._arn_workgroup(name)
+ tags = _tag_map(props.get("Tags"))
+ if tags:
+ _athena._tags[arn] = tags
+ else:
+ _athena._tags.pop(arn, None)
+
+
+def _athena_workgroup_create(logical_id, props, stack_name):
+ name = props.get("Name")
+ if not name:
+ raise ValueError("Property validation failure: [The property {/Name} is required]")
+ _glue_call(_athena._create_workgroup, {"Name": name}, "AWS::Athena::WorkGroup", "create")
+ _athena_workgroup_apply(name, props)
+ return name, _athena_workgroup_attributes(name)
+
+
+def _athena_workgroup_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ if new_props.get("Name") != physical_id or physical_id not in _athena._workgroups:
+ created = _athena_workgroup_create(logical_id or physical_id, new_props, stack_name)
+ if physical_id in _athena._workgroups and created[0] != physical_id:
+ _delete_predecessor(_athena_workgroup_delete, physical_id, old_props)
+ return created
+ _athena_workgroup_apply(physical_id, new_props)
+ return physical_id, _athena_workgroup_attributes(physical_id)
+
+
+def _athena_workgroup_delete(physical_id, props):
+ _athena._delete_workgroup({"WorkGroup": physical_id, "RecursiveDeleteOption": bool(props.get("RecursiveDeleteOption"))})
+
+
def _glue_database_name(logical_id, props, stack_name):
# DatabaseName is the schema's primary identifier, so it wins over
# DatabaseInput.Name when both are given.
@@ -15029,6 +15080,7 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::RDS::DBInstance": _RDS_DB_INSTANCE_CREATE_ONLY,
# Table, Partition and Connection replace on nested members
# (TableInput.Name, PartitionInput.Values, ConnectionInput.Name).
+ "AWS::Athena::WorkGroup": ("Name",),
"AWS::Glue::Database": ("DatabaseName",),
"AWS::Glue::Crawler": ("Name",),
"AWS::Glue::Job": ("Name",),
@@ -15145,6 +15197,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _ec_user_group_delete,
},
+ "AWS::Athena::WorkGroup": {
+ "create": _athena_workgroup_create,
+ "update": _athena_workgroup_update,
+ "update_with_logical_id": True,
+ "delete": _athena_workgroup_delete,
+ },
"AWS::Glue::Database": {
"create": _glue_database_create,
"update": _glue_database_update,
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 3a2e3a7c..e3028634 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -5861,13 +5861,13 @@ def _cf_via_hash() -> str:
return os.urandom(16).hex()
-def _add_cloudfront_headers(headers: dict, x_cache: str, request_id: str | None = None) -> dict:
+def _add_cloudfront_headers(headers: dict, x_cache: str, request_id: str | None = None, edge_server: bool = True) -> dict:
result = dict(headers)
result["via"] = f"1.1 {_cf_via_hash()}.cloudfront.net (CloudFront)"
result["x-cache"] = x_cache
result["x-amz-cf-pop"] = "LOC50-C1"
result["x-amz-cf-id"] = request_id or _cf_request_id()
- if not any(k.lower() == "server" for k in result):
+ if edge_server and not any(k.lower() == "server" for k in result):
result["server"] = "CloudFront"
return result
@@ -6451,5 +6451,7 @@ async def handle_viewer_request(dist: dict, method: str, path: str, raw_uri: str
response_headers["set-cookie"] = set_cookie_values if len(set_cookie_values) > 1 else set_cookie_values[0]
response_body = _body_from_response_event(response, origin_body)
- final_headers = _add_cloudfront_headers(response_headers, "Miss from cloudfront")
+ # An origin response without Server gets CloudFront's only when a viewer-response function ran (observed on AWS).
+ ran_response_function = bool(response_function_arn) and origin_status < 400
+ final_headers = _add_cloudfront_headers(response_headers, "Miss from cloudfront", edge_server=ran_response_function)
return status, _render_headers(final_headers, title_case=True), response_body
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index d87b05f8..6d51fdbc 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -47,6 +47,7 @@ ITERATOR_EXPIRY_SECONDS = 300
_streams = AccountRegionScopedDict()
_shard_iterators = AccountRegionScopedDict()
_consumers = AccountRegionScopedDict()
+_resource_policies = AccountRegionScopedDict() # stream or consumer ARN -> policy document as sent
# (ConsumerARN, ShardId) -> {"id", "started"} of the live SubscribeToShard
_subscriptions = {}
SUBSCRIPTION_SECONDS = 300
@@ -63,6 +64,7 @@ def get_state():
"streams": copy.deepcopy(_streams),
"shard_iterators": copy.deepcopy(_shard_iterators),
"consumers": copy.deepcopy(_consumers),
+ "resource_policies": copy.deepcopy(_resource_policies),
}
@@ -75,6 +77,9 @@ def _restore_state(data):
_restore_stream_store(data.get("streams", {}))
_restore_shard_iterator_store(data.get("shard_iterators", {}))
_restore_consumer_store(data.get("consumers", {}))
+ policies = data.get("resource_policies", {})
+ if isinstance(policies, AccountRegionScopedDict):
+ _resource_policies.update(policies)
def _kinesis_arn_scope(value, default_account_id: str | None = None) -> tuple[str, str]:
@@ -401,6 +406,9 @@ async def handle_request(method, path, headers, body, query_params):
"StopStreamEncryption": _stop_stream_encryption,
"EnableEnhancedMonitoring": _enable_enhanced_monitoring,
"DisableEnhancedMonitoring": _disable_enhanced_monitoring,
+ "PutResourcePolicy": _put_resource_policy,
+ "GetResourcePolicy": _get_resource_policy,
+ "DeleteResourcePolicy": _delete_resource_policy,
}
handler = handlers.get(action)
@@ -464,6 +472,8 @@ def _delete_stream(data):
del _shard_iterators[tok]
for carn in [a for a, c in _consumers.items() if c["StreamARN"] == stream["StreamARN"]]:
del _consumers[carn]
+ _resource_policies.pop(carn, None)
+ _resource_policies.pop(stream["StreamARN"], None)
del _streams[name]
return json_response({})
@@ -1077,11 +1087,13 @@ def _deregister_consumer(data):
if not consumer:
return error_response_json("ResourceNotFoundException", "Consumer not found", 400)
del _consumers[consumer["ConsumerARN"]]
+ _resource_policies.pop(consumer["ConsumerARN"], None)
elif stream_arn and consumer_name:
consumer = _consumer_by_stream_and_name(stream_arn, consumer_name)
if not consumer:
return error_response_json("ResourceNotFoundException", "Consumer not found", 400)
del _consumers[consumer["ConsumerARN"]]
+ _resource_policies.pop(consumer["ConsumerARN"], None)
else:
return error_response_json("ValidationException",
"ConsumerARN or StreamARN+ConsumerName required", 400)
@@ -1404,8 +1416,147 @@ def _cbor_response(data: dict, status: int = 200):
return status, {"Content-Type": "application/x-amz-cbor-1.1"}, body
+# ---------------------------------------------------------------------------
+# Resource policies (codes and messages as AWS answered them, us-east-1, 2026-10-26)
+# ---------------------------------------------------------------------------
+
+# The actions a policy may share (Kinesis Data Streams developer guide, "Controlling access").
+_POLICY_ACTIONS = {
+ "stream": {"kinesis:DescribeStreamSummary", "kinesis:GetRecords", "kinesis:GetShardIterator",
+ "kinesis:ListShards", "kinesis:PutRecord", "kinesis:PutRecords"},
+ "consumer": {"kinesis:DescribeStreamConsumer", "kinesis:SubscribeToShard"},
+}
+
+
+def _statement_positions(text):
+ """(line, column) of each Statement entry's opening brace, 1-based, in document order."""
+ decoder = json.JSONDecoder()
+ depth, i, n = 0, 0, len(text)
+ while i < n:
+ ch = text[i]
+ if ch == '"':
+ key, end = json.decoder.scanstring(text, i + 1)
+ j = end
+ while j < n and text[j] in " \t\r\n":
+ j += 1
+ if depth == 1 and key == "Statement" and j < n and text[j] == ":":
+ j += 1
+ while j < n and text[j] in " \t\r\n":
+ j += 1
+ starts = []
+ if j < n and text[j] == "[":
+ j += 1
+ while j < n:
+ while j < n and text[j] in " \t\r\n,":
+ j += 1
+ if j >= n or text[j] == "]":
+ break
+ starts.append(j)
+ _value, j = decoder.raw_decode(text, j)
+ else:
+ starts.append(j)
+ return [(text.count("\n", 0, k) + 1, k - (text.rfind("\n", 0, k) + 1) + 1) for k in starts]
+ i = end
+ continue
+ if ch in "{[":
+ depth += 1
+ elif ch in "}]":
+ depth -= 1
+ i += 1
+ return []
+
+
+def _policy_error(text, resource_arn, kind):
+ """The validation message AWS gives a policy for this resource, or None."""
+ try:
+ document = json.loads(text)
+ except (TypeError, ValueError):
+ return "This policy contains invalid Json"
+ if not isinstance(document, dict):
+ return "This policy contains invalid Json"
+ for field in ("Version", "Statement"):
+ if field not in document:
+ return f"Missing required field {field}"
+ statements = document["Statement"]
+ statements = statements if isinstance(statements, list) else [statements]
+ positions = _statement_positions(text)
+ for index, statement in enumerate(statements):
+ if not isinstance(statement, dict):
+ continue
+ line, column = positions[index] if index < len(positions) else (1, 1)
+ where = f"Resource policy contains invalid statement at line {line}, column {column}: "
+ actions = statement.get("Action", [])
+ actions = actions if isinstance(actions, list) else [actions]
+ invalid = [a for a in actions if a not in _POLICY_ACTIONS[kind]]
+ if invalid:
+ return where + "The following action names are invalid: " + ", ".join(f'"{a}"' for a in invalid)
+ resources = statement.get("Resource", [])
+ resources = resources if isinstance(resources, list) else [resources]
+ if any(r != resource_arn for r in resources):
+ return where + "The resource policy's resource must be the same as the resource ARN."
+ return None
+
+
+def _policy_resource(resource_arn, policy=None):
+ """(kind, error): checks the ARN's region and account, then the policy, then that the resource exists."""
+ try:
+ spec = parse_arn(resource_arn or "")
+ except ArnParseError:
+ spec = None
+ if spec is None or spec.service != "kinesis" or not spec.resource.startswith("stream/"):
+ return None, error_response_json("InvalidArgumentException", f"Invalid ARN: {resource_arn}", 400)
+ if spec.region != get_region():
+ return None, error_response_json(
+ "InvalidArgumentException",
+ f"The region specified in the ARN '{resource_arn}' does not match the endpoint region", 400)
+ if spec.account_id != get_account_id():
+ return None, error_response_json("UnrecognizedClientException", "No account found for the given parameters", 400)
+ kind = "consumer" if "/consumer/" in spec.resource else "stream"
+ if policy is not None:
+ message = _policy_error(policy, resource_arn, kind)
+ if message:
+ return None, error_response_json("InvalidArgumentException", f"Policy validation error: {message}", 400)
+ if kind == "stream" and not _resolve_stream_by_arn(resource_arn):
+ name = spec.resource.split("/", 1)[1]
+ return None, error_response_json(
+ "ResourceNotFoundException", f"Stream {name} under account {get_account_id()} not found.", 400)
+ if kind == "consumer" and not _consumer_from_arn(resource_arn):
+ return None, error_response_json("ResourceNotFoundException", f"Consumer {resource_arn} not found", 400)
+ return kind, None
+
+
+def _put_resource_policy(data):
+ resource_arn, policy = data.get("ResourceARN"), data.get("Policy")
+ _kind, err = _policy_resource(resource_arn, policy if isinstance(policy, str) else "")
+ if err:
+ return err
+ _resource_policies[resource_arn] = policy
+ return json_response({})
+
+
+def _get_resource_policy(data):
+ resource_arn = data.get("ResourceARN")
+ _kind, err = _policy_resource(resource_arn)
+ if err:
+ return err
+ return json_response({"Policy": _resource_policies.get(resource_arn) or "{}"})
+
+
+def _delete_resource_policy(data):
+ resource_arn = data.get("ResourceARN")
+ _kind, err = _policy_resource(resource_arn)
+ if err:
+ return err
+ if resource_arn not in _resource_policies:
+ return error_response_json(
+ "ResourceNotFoundException", f"No resource policy found for resource ARN {resource_arn}.", 400)
+ del _resource_policies[resource_arn]
+ return json_response({})
+
+
def reset():
_streams.clear()
_shard_iterators.clear()
_consumers.clear()
+ _resource_policies.clear()
_subscriptions.clear()
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index ffe9ce2c..e5367bd6 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -1147,6 +1147,12 @@ def _validate_event_source_arn(event_source_arn: str):
return None, err
if spec.service not in {"sqs", "kinesis", "dynamodb"}:
return None, _invalid_parameter_value(f"Unsupported event source ARN: {event_source_arn}")
+ if spec.service == "kinesis" and spec.region != get_region():
+ return None, _invalid_parameter_value(f"Event source region must match Lambda region {get_region()}")
+ if spec.service == "kinesis" and spec.account_id != get_account_id():
+ # Another account's stream is not readable here; this is what AWS answers when it cannot read it.
+ return None, _invalid_parameter_value(
+ "Received Exception while reading from provided stream. No account found for the given parameters")
scope_err = _require_same_account_region_arn(spec, event_source_arn, "event source")
if scope_err:
return None, scope_err
diff --git a/ministack/services/opensearch.py b/ministack/services/opensearch.py
index 25fede3b..99b0dfe1 100644
--- a/ministack/services/opensearch.py
+++ b/ministack/services/opensearch.py
@@ -58,7 +58,6 @@ DASHBOARDS_ENABLED = os.environ.get("OPENSEARCH_DASHBOARDS", "0") == "1"
BASE_PORT = int(os.environ.get("OPENSEARCH_BASE_PORT", "14571"))
DASHBOARDS_BASE_PORT = int(os.environ.get("OPENSEARCH_DASHBOARDS_BASE_PORT", "15601"))
DEFAULT_IMAGE = os.environ.get("OPENSEARCH_IMAGE", "opensearchproject/opensearch:2.15.0")
-JAVA_OPTS = os.environ.get("OPENSEARCH_JAVA_OPTS", "")
DASHBOARDS_IMAGE = os.environ.get(
"OPENSEARCH_DASHBOARDS_IMAGE", "opensearchproject/opensearch-dashboards:2.15.0"
)
@@ -398,11 +397,11 @@ def start_engine_container(docker, name: str, labels: dict, host_port=None, volu
# matching that here would block every smoke test.
"DISABLE_SECURITY_PLUGIN": "true",
"OPENSEARCH_INITIAL_ADMIN_PASSWORD": "MinIstack-Admin-1!",
+ # The heap OpenSearch's own sample docker-compose uses, instead of the image's 1 GB per container.
+ "OPENSEARCH_JAVA_OPTS": "-Xms512m -Xmx512m",
},
ulimits=[{"Name": "memlock", "Soft": -1, "Hard": -1}],
)
- if JAVA_OPTS:
- run_kwargs["environment"]["OPENSEARCH_JAVA_OPTS"] = JAVA_OPTS
if volumes is not None:
run_kwargs["volumes"] = volumes
if DOCKER_NETWORK:
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 36fd057e..7f8b3794 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -5431,9 +5431,8 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =
return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")
if key not in bucket["objects"]:
- from ministack.app import AUTH
-
- if (AUTH and not query_params.keys() - {"x-id"}
+ # The response shape AWS gives a header-signed GET, whatever MiniStack's AUTH setting.
+ if (not query_params.keys() - {"x-id"}
and headers.get("authorization", "").startswith("AWS4-HMAC-SHA256")):
status, err_headers, err_body = _object_error(
"NoSuchKey", "The specified key does not exist.", 404, Key=key,
@@ -9055,25 +9054,79 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):
# ---------------------------------------------------------------------------
-def _object_disk_path(bucket: str, key: str, account_id: str = None) -> str | None:
- """Resolve the on-disk path for an object and verify it lives under DATA_DIR.
+# A key is stored at its own path (so Athena and Glue can read the bytes) when a
+# file can hold it there; otherwise under this reserved directory, by an encoded
+# name. Keys a path cannot hold: a trailing or doubled slash, "." or ".."
+# segments, a key under another key's file or a file over another key's folder.
+_ENCODED_KEYS_DIR = ".ministack-keys"
- Returns None if the resolved path escapes DATA_DIR (e.g. key contains `..`
- or absolute path). Callers must treat None as "skip operation".
- """
- if account_id is None:
- account_id = get_account_id()
- root = os.path.realpath(DATA_DIR)
- candidate = os.path.realpath(os.path.join(DATA_DIR, account_id, bucket, key))
+
+def _plain_path_key(key: str) -> bool:
+ if not key or "\x00" in key:
+ return False
+ parts = key.split("/")
+ return (parts[0] != _ENCODED_KEYS_DIR
+ and all(p not in ("", ".", "..") and len(p.encode()) <= 200
+ and not p.endswith((".meta.json", ".tmp")) for p in parts))
+
+
+def _encoded_key_name(key: str) -> str:
+ # No "/" or "." survives, so the name is one path component and never a sidecar or temp name.
+ name = url_quote(key, safe="").replace(".", "%2E")
+ return name if len(name) <= 200 else "sha256-" + hashlib.sha256(key.encode()).hexdigest()
+
+
+def _under(root: str, candidate: str) -> bool:
try:
- if os.path.commonpath([root, candidate]) != root:
- logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)
- return None
+ return candidate != root and os.path.commonpath([root, candidate]) == root
except ValueError:
# commonpath raises on mixed drives / unrelated paths — treat as escape.
- logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)
- return None
- return candidate
+ return False
+
+
+def _key_disk_path(base: str, key: str) -> str | None:
+ """Where ``key`` lives under ``base``: its own path, or its encoded name when
+ a file cannot hold it there (or it is already stored that way)."""
+ root = os.path.realpath(base)
+ encoded = os.path.join(root, _ENCODED_KEYS_DIR, _encoded_key_name(key))
+ if not _plain_path_key(key):
+ return encoded
+ plain = os.path.join(root, key)
+ if not _under(root, os.path.realpath(plain)):
+ return encoded
+ if os.path.isfile(plain) or os.path.isfile(plain + ".meta.json"):
+ return plain
+ if os.path.isfile(encoded) or os.path.isfile(encoded + ".meta.json"):
+ return encoded
+ parent = os.path.dirname(plain)
+ while parent != root:
+ if os.path.isfile(parent):
+ return encoded
+ parent = os.path.dirname(parent)
+ return encoded if os.path.isdir(plain) else plain
+
+
+def _other_key_disk_path(base: str, key: str, fpath: str) -> str | None:
+ """The key's other possible location, so a write to one clears a stale copy in the other."""
+ root = os.path.realpath(base)
+ encoded = os.path.join(root, _ENCODED_KEYS_DIR, _encoded_key_name(key))
+ if fpath != encoded:
+ return encoded
+ plain = os.path.join(root, key)
+ return plain if _plain_path_key(key) and _under(root, os.path.realpath(plain)) else None
+
+
+def _remove_key_files(fpath: str | None):
+ for path in (fpath, fpath and fpath + ".meta.json"):
+ if path and os.path.isfile(path):
+ os.remove(path)
+
+
+def _object_disk_path(bucket: str, key: str, account_id: str = None) -> str | None:
+ """The on-disk path of an object, always under DATA_DIR."""
+ if account_id is None:
+ account_id = get_account_id()
+ return _key_disk_path(os.path.join(DATA_DIR, account_id, bucket), key)
def _atomic_write(fpath: str, data: bytes, *, text: bool = False):
@@ -9122,12 +9175,14 @@ def _persist_object(bucket: str, key: str, obj):
data = obj.get("body")
if data is not None:
_atomic_write(fpath, data)
- meta = {**_object_meta_from_record(obj), **_key_history_meta(bucket, key)}
+ meta = {**_object_meta_from_record(obj), **_key_history_meta(bucket, key), "key": key}
_atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)
# Drop body from in-memory record to save RAM
obj["body"] = None
else:
_atomic_write(fpath, obj)
+ _atomic_write(fpath + ".meta.json", json.dumps({"key": key}), text=True)
+ _remove_key_files(_other_key_disk_path(os.path.join(DATA_DIR, get_account_id(), bucket), key, fpath))
except Exception as e:
logger.warning("Failed to persist S3 object %s/%s: %s", bucket, key, e)
@@ -9151,6 +9206,7 @@ def _persist_delete_marker(bucket_name: str, key: str, marker: dict):
"version_id": marker.get("version_id"),
"last_modified": marker.get("last_modified", ""),
**_key_history_meta(bucket_name, key),
+ "key": key,
}
_atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)
except Exception as e:
@@ -9195,16 +9251,10 @@ _VERSIONS_DIR = ".versions"
def _version_disk_path(bucket: str, key: str, version_id: str, account_id: str = None) -> str | None:
if account_id is None:
account_id = get_account_id()
- root = os.path.realpath(os.path.join(DATA_DIR, _VERSIONS_DIR, account_id, bucket, version_id))
- candidate = os.path.realpath(os.path.join(root, key))
- try:
- if candidate == root or os.path.commonpath([root, candidate]) != root:
- logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)
- return None
- except ValueError:
- logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)
+ base = os.path.join(DATA_DIR, _VERSIONS_DIR, account_id, bucket, version_id)
+ if not _under(os.path.realpath(os.path.join(DATA_DIR, _VERSIONS_DIR, account_id, bucket)), os.path.realpath(base)):
return None
- return candidate
+ return _key_disk_path(base, key)
def _version_file_exists(bucket_name: str, key: str, version_id: str, account_id: str = None) -> bool:
@@ -9284,11 +9334,8 @@ def _delete_persisted_object(bucket_name: str, key: str):
fpath = _object_disk_path(bucket_name, key)
if fpath is None:
return
- if os.path.exists(fpath):
- os.remove(fpath)
- meta_path = fpath + ".meta.json"
- if os.path.exists(meta_path):
- os.remove(meta_path)
+ _remove_key_files(fpath)
+ _remove_key_files(_other_key_disk_path(os.path.join(DATA_DIR, get_account_id(), bucket_name), key, fpath))
except Exception as e:
logger.warning("Failed to delete persisted S3 object %s/%s: %s", bucket_name, key, e)
@@ -9372,92 +9419,106 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):
"region": None,
}
bucket = _buckets._data[scoped_key]
- for dirpath, _dirnames, filenames in os.walk(bucket_path):
- for fname in filenames:
- if fname.endswith(".meta.json"):
- continue
- abs_path = os.path.join(dirpath, fname)
- key = os.path.relpath(abs_path, bucket_path)
- meta_path = abs_path + ".meta.json"
- meta = {}
- if os.path.exists(meta_path):
- try:
- with open(meta_path) as mf:
- meta = json.load(mf)
- except Exception:
- pass
- # A delete marker's sidecar stands in for the object it hides: the
- # data file belongs to the version underneath, not to the current
- # key. Rebuild the marker (and the version it covers) instead of
- # resurrecting the object as current.
- if meta.get("is_delete_marker"):
- _load_persisted_delete_marker(account_id, bucket, bucket_name, key, meta)
- continue
- # Body stays on disk — only load metadata into memory.
- # Compute size/etag from meta sidecar; fall back to reading
- # the file only when the sidecar is missing or incomplete.
- size = meta.get("size")
- etag = meta.get("etag")
- if size is None or not etag:
- with open(abs_path, "rb") as f:
- data = f.read()
- size = len(data)
- etag = etag or f'"{md5_hash(data)}"'
- bucket["objects"][key] = {
- "body": None,
- "content_type": meta.get("content_type", "application/octet-stream"),
- "content_encoding": meta.get("content_encoding"),
- "etag": etag,
- "last_modified": meta.get("last_modified") or now_iso(),
- "size": size,
- "metadata": meta.get("metadata", {}),
- "preserved_headers": meta.get("preserved_headers", {}),
- "storage_class": meta.get("storage_class", "STANDARD"),
- "checksums": meta.get("checksums", {}),
- }
- if meta.get("version_id"):
- bucket["objects"][key]["version_id"] = meta["version_id"]
- if "versions" in meta or "tags" in meta or "acl" in meta:
- _load_persisted_history(account_id, bucket, bucket_name, key, meta)
- elif meta.get("version_id"):
- vkey = (bucket_name, key)
- scoped_vkey = (account_id, vkey)
- if scoped_vkey not in _object_versions._data:
- _object_versions._data[scoped_vkey] = []
- _object_versions._data[scoped_vkey].append(
- {
- "version_id": meta["version_id"],
- "last_modified": meta.get("last_modified") or now_iso(),
- "etag": etag,
- "size": size,
- "is_latest": True,
- "data": None,
- "content_type": meta.get("content_type", "application/octet-stream"),
- "content_encoding": meta.get("content_encoding"),
- "metadata": meta.get("metadata", {}),
- "preserved_headers": meta.get("preserved_headers", {}),
- "storage_class": meta.get("storage_class", "STANDARD"),
- "checksums": meta.get("checksums", {}),
- }
- )
- # Delete markers whose data file is gone (a key that never held a body, or
- # whose version was purged) live on as a lone sidecar.
- for dirpath, _dirnames, filenames in os.walk(bucket_path):
- for fname in filenames:
- if not fname.endswith(".meta.json"):
- continue
- meta_path = os.path.join(dirpath, fname)
- data_path = meta_path[: -len(".meta.json")]
- if os.path.exists(data_path):
- continue # handled with its data file above
+ for abs_path, key in _persisted_key_files(bucket_path, sidecars=False):
+ meta_path = abs_path + ".meta.json"
+ meta = {}
+ if os.path.exists(meta_path):
try:
with open(meta_path) as mf:
meta = json.load(mf)
except Exception:
- continue
- if meta.get("is_delete_marker"):
- key = os.path.relpath(data_path, bucket_path)
- _load_persisted_delete_marker(account_id, bucket, bucket_name, key, meta)
+ pass
+ # A delete marker's sidecar stands in for the object it hides: the
+ # data file belongs to the version underneath, not to the current
+ # key. Rebuild the marker (and the version it covers) instead of
+ # resurrecting the object as current.
+ if meta.get("is_delete_marker"):
+ _load_persisted_delete_marker(account_id, bucket, bucket_name, key, meta)
+ continue
+ # Body stays on disk — only load metadata into memory.
+ # Compute size/etag from meta sidecar; fall back to reading
+ # the file only when the sidecar is missing or incomplete.
+ size = meta.get("size")
+ etag = meta.get("etag")
+ if size is None or not etag:
+ with open(abs_path, "rb") as f:
+ data = f.read()
+ size = len(data)
+ etag = etag or f'"{md5_hash(data)}"'
+ bucket["objects"][key] = {
+ "body": None,
+ "content_type": meta.get("content_type", "application/octet-stream"),
+ "content_encoding": meta.get("content_encoding"),
+ "etag": etag,
+ "last_modified": meta.get("last_modified") or now_iso(),
+ "size": size,
+ "metadata": meta.get("metadata", {}),
+ "preserved_headers": meta.get("preserved_headers", {}),
+ "storage_class": meta.get("storage_class", "STANDARD"),
+ "checksums": meta.get("checksums", {}),
+ }
+ if meta.get("version_id"):
+ bucket["objects"][key]["version_id"] = meta["version_id"]
+ if "versions" in meta or "tags" in meta or "acl" in meta:
+ _load_persisted_history(account_id, bucket, bucket_name, key, meta)
+ elif meta.get("version_id"):
+ vkey = (bucket_name, key)
+ scoped_vkey = (account_id, vkey)
+ if scoped_vkey not in _object_versions._data:
+ _object_versions._data[scoped_vkey] = []
+ _object_versions._data[scoped_vkey].append(
+ {
+ "version_id": meta["version_id"],
+ "last_modified": meta.get("last_modified") or now_iso(),
+ "etag": etag,
+ "size": size,
+ "is_latest": True,
+ "data": None,
+ "content_type": meta.get("content_type", "application/octet-stream"),
+ "content_encoding": meta.get("content_encoding"),
+ "metadata": meta.get("metadata", {}),
+ "preserved_headers": meta.get("preserved_headers", {}),
+ "storage_class": meta.get("storage_class", "STANDARD"),
+ "checksums": meta.get("checksums", {}),
+ }
+ )
+ # Delete markers whose data file is gone (a key that never held a body, or
+ # whose version was purged) live on as a lone sidecar.
+ for meta_path, key in _persisted_key_files(bucket_path, sidecars=True):
+ data_path = meta_path[: -len(".meta.json")]
+ if os.path.exists(data_path):
+ continue # handled with its data file above
+ try:
+ with open(meta_path) as mf:
+ meta = json.load(mf)
+ except Exception:
+ continue
+ if meta.get("is_delete_marker"):
+ _load_persisted_delete_marker(account_id, bucket, bucket_name, meta.get("key") or key, meta)
+
+
+def _persisted_key_files(bucket_path, sidecars):
+ """(file, key) for a bucket's data files, or sidecars: plain paths first, then encoded names."""
+ for dirpath, dirnames, filenames in os.walk(bucket_path):
+ if dirpath == bucket_path and _ENCODED_KEYS_DIR in dirnames:
+ dirnames.remove(_ENCODED_KEYS_DIR)
+ for fname in filenames:
+ if fname.endswith(".meta.json") == sidecars and not fname.endswith(".tmp"):
+ path = os.path.join(dirpath, fname)
+ key = os.path.relpath(path[: -len(".meta.json")] if sidecars else path, bucket_path)
+ yield path, key
+ encoded_dir = os.path.join(bucket_path, _ENCODED_KEYS_DIR)
+ for fname in sorted(os.listdir(encoded_dir)) if os.path.isdir(encoded_dir) else []:
+ if fname.endswith(".meta.json") != sidecars or fname.endswith(".tmp"):
+ continue
+ path = os.path.join(encoded_dir, fname)
+ meta_path = path if sidecars else path + ".meta.json"
+ try:
+ with open(meta_path) as mf:
+ key = json.load(mf).get("key")
+ except Exception:
+ key = None
+ yield path, key or url_unquote(fname[: -len(".meta.json")] if sidecars else fname)
def _load_persisted_delete_marker(account_id, bucket, bucket_name, key, meta):
diff --git a/tests/test_alb.py b/tests/test_alb.py
index ab9fe90f..12bc5710 100644
--- a/tests/test_alb.py
+++ b/tests/test_alb.py
@@ -616,6 +616,9 @@ def test_elbv2_dataplane_fixed_response(elbv2, lam):
assert resp.status == 200
assert resp.read() == b"maintenance"
assert resp.headers["Server"] == "awselb/2.0"
+ elbv2.modify_listener_attributes(ListenerArn=l_arn, Attributes=[
+ {"Key": "routing.http.response.server.enabled", "Value": "false"}])
+ assert _req.urlopen(_req.Request(url, method="GET")).headers.get("Server") is None
finally:
elbv2.delete_listener(ListenerArn=l_arn)
elbv2.delete_target_group(TargetGroupArn=tg_arn)
@@ -3160,6 +3163,17 @@ def test_elbv2_dataplane_applies_the_listeners_cors_response_headers(elbv2):
{"Key": prefix + "access_control_allow_origin.header_value", "Value": ""},
])
assert fetch().get_all("Access-Control-Allow-Origin") == ["https://target.example.test"]
+ # The other insert headers on the same page behave the same way.
+ elbv2.modify_listener_attributes(ListenerArn=l_arn, Attributes=[
+ {"Key": prefix + "strict_transport_security.header_value", "Value": "max-age=31536000"},
+ {"Key": prefix + "content_security_policy.header_value", "Value": "default-src 'self'"},
+ {"Key": prefix + "x_content_type_options.header_value", "Value": "nosniff"},
+ {"Key": prefix + "x_frame_options.header_value", "Value": "DENY"},
+ ])
+ headers = fetch()
+ assert (headers.get("Strict-Transport-Security"), headers.get("Content-Security-Policy"),
+ headers.get("X-Content-Type-Options"), headers.get("X-Frame-Options")) == (
+ "max-age=31536000", "default-src 'self'", "nosniff", "DENY")
finally:
_alb_http_target_teardown(elbv2, lb_arn, tg_arn, l_arn)
_stop_server(server)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 2395ecd0..0c4b56d6 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -26432,7 +26432,6 @@ def test_cfn_iam_policy_is_inline_not_managed(cfn, iam):
role = f"cfn-pol-inl-role-{uid}"
policy_name = f"cfn-pol-inl-{uid}"
_cfn_policy_test_roles(iam, [role])
- before = {p["Arn"] for p in iam.list_policies(Scope="Local")["Policies"]}
template = json.dumps({
"Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
"PolicyName": policy_name,
@@ -26453,10 +26452,11 @@ def test_cfn_iam_policy_is_inline_not_managed(cfn, iam):
document = _inline_role_document(iam, role, policy_name)
assert document["Statement"][0]["Action"] == "s3:GetObject"
- # Nothing managed: no attachment on the role and no new Local policy.
+ # Nothing managed: no attachment on the role and no Local policy of this name or stack. Other tests
+ # running in parallel create and delete Local policies, so the whole list can't be compared.
assert iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"] == []
- after = {p["Arn"] for p in iam.list_policies(Scope="Local")["Policies"]}
- assert after == before
+ local = iam.list_policies(Scope="Local")["Policies"]
+ assert not [p["Arn"] for p in local if p["PolicyName"] == policy_name or uid in p["Arn"]]
assert _output(stack, "Ref") == _output(stack, "Id")
assert _output(stack, "Ref") != policy_name
@@ -37679,3 +37679,44 @@ def test_cfn_state_machine_refused_encryption_update_rolls_back(cfn, sfn, kms_cl
finally:
_delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_athena_workgroup_create_update_replace_delete(cfn):
+ """AWS::Athena::WorkGroup (template reference): Ref is the name, GetAtt CreationTime; Description,
+ State, Tags and WorkGroupConfiguration update in place, a new Name replaces the workgroup."""
+ athena = make_client("athena")
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name, first, second = f"cfn-athena-wg-{uid}", f"wg-{uid}", f"wg2-{uid}"
+
+ def template(name, description, state):
+ return json.dumps({
+ "Resources": {"WG": {"Type": "AWS::Athena::WorkGroup", "Properties": {
+ "Name": name, "Description": description, "State": state,
+ "Tags": [{"Key": "team", "Value": "data"}],
+ "WorkGroupConfiguration": {"ResultConfiguration": {"OutputLocation": f"s3://results-{uid}/"}},
+ }}},
+ "Outputs": {"Ref": {"Value": {"Ref": "WG"}}, "Created": {"Value": {"Fn::GetAtt": ["WG", "CreationTime"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(first, "one", "ENABLED"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Ref") == first and _output(stack, "Created").isdigit()
+ wg = athena.get_work_group(WorkGroup=first)["WorkGroup"]
+ assert (wg["Description"], wg["State"]) == ("one", "ENABLED")
+ assert wg["Configuration"]["ResultConfiguration"]["OutputLocation"] == f"s3://results-{uid}/"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(first, "two", "DISABLED"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ wg = athena.get_work_group(WorkGroup=first)["WorkGroup"]
+ assert (wg["Description"], wg["State"]) == ("two", "DISABLED")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(second, "two", "ENABLED"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE" and _output(stack, "Ref") == second
+ names = {w["Name"] for w in athena.list_work_groups()["WorkGroups"]}
+ assert second in names and first not in names
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert second not in {w["Name"] for w in athena.list_work_groups()["WorkGroups"]}
diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.py
index 2f6e4e83..5dc0582f 100644
--- a/tests/test_cloudfront.py
+++ b/tests/test_cloudfront.py
@@ -6299,7 +6299,7 @@ def test_streamed_alb_body_idle_past_the_read_timeout_is_an_origin_timeout():
def _function_url_dist(cloudfront, url_host: str, protocol_policy: str = "https-only",
- origin_request_policy: str = _ALL_VIEWER_EXCEPT_HOST) -> str:
+ origin_request_policy: str = _ALL_VIEWER_EXCEPT_HOST, response_function_arn: str = "") -> str:
origin = {
"Id": "url-origin", "DomainName": url_host,
"CustomHeaders": {"Quantity": 1, "Items": [{"HeaderName": "X-Origin-Verify", "HeaderValue": "origin-token"}]},
@@ -6319,6 +6319,9 @@ def _function_url_dist(cloudfront, url_host: str, protocol_policy: str = "https-
"CachePolicyId": _CACHING_DISABLED, "OriginRequestPolicyId": origin_request_policy,
},
}
+ if response_function_arn:
+ dist_config["DefaultCacheBehavior"]["FunctionAssociations"] = {
+ "Quantity": 1, "Items": [{"FunctionARN": response_function_arn, "EventType": "viewer-response"}]}
return cloudfront.create_distribution(DistributionConfig=dist_config)["Distribution"]["DomainName"]
@@ -6398,3 +6401,22 @@ def test_request_id_has_cloudfronts_shape(cf_raw_origin_stack):
lowered = {name.lower(): value for name, value in headers.items()}
assert re.fullmatch(r"[A-Za-z0-9_-]{54}==", lowered["x-amz-cf-id"]), lowered["x-amz-cf-id"]
assert re.fullmatch(r"1\.1 [0-9a-f]{32}\.cloudfront\.net \(CloudFront\)", lowered["via"]), lowered["via"]
+
+
+def test_function_url_origin_response_headers_follow_aws(cloudfront, function_url_origin):
+ """Captured on AWS: no Server from an origin that sends none, and one request id, the Function URL's own."""
+ status, headers, _body = _get(_function_url_dist(cloudfront, function_url_origin["open"]), "/hello")
+ assert status == 200
+ names = [k.lower() for k in headers]
+ assert "server" not in names
+ assert names.count("x-amzn-requestid") == 1 and "x-amz-request-id" not in names
+
+
+def test_viewer_response_function_adds_cloudfront_server_when_the_origin_sends_none(cloudfront, function_url_origin):
+ _skip_without_node()
+ fn_arn = _create_function(cloudfront, f"cf-dp-server-{_uuid_mod.uuid4().hex[:8]}",
+ b"function handler(event) { return event.response; }")
+ dist_host = _function_url_dist(cloudfront, function_url_origin["open"], response_function_arn=fn_arn)
+ status, headers, _body = _get(dist_host, "/hello")
+ assert status == 200
+ assert {k.lower(): v for k, v in headers.items()}["server"] == "CloudFront"
diff --git a/tests/test_kinesis.py b/tests/test_kinesis.py
index 93efde10..0589fd9b 100644
--- a/tests/test_kinesis.py
+++ b/tests/test_kinesis.py
@@ -942,6 +942,80 @@ def test_subscription_captures_selection_before_runner_and_pruning(subscription_
asyncio.run(exercise())
+def _kin_error(exc):
+ err = exc.value.response["Error"]
+ return exc.value.response["ResponseMetadata"]["HTTPStatusCode"], err["Code"], err["Message"]
+
+
+def test_kinesis_resource_policy_follows_aws(kin):
+ """Captured on AWS (us-east-1, 2026-10-26): codes, messages and check order of the resource-policy calls."""
+ name = f"rp-{_uuid_mod.uuid4().hex[:8]}"
+ kin.create_stream(StreamName=name, ShardCount=1)
+ arn = kin.describe_stream_summary(StreamName=name)["StreamDescriptionSummary"]["StreamARN"]
+ account = arn.split(":")[4]
+ consumer = kin.register_stream_consumer(StreamARN=arn, ConsumerName="c")["Consumer"]["ConsumerARN"]
+
+ def policy(resource, actions):
+ return json.dumps({"Version": "2012-10-17", "Statement": [{"Sid": "x", "Effect": "Allow",
+ "Principal": {"AWS": f"arn:aws:iam::{account}:root"}, "Action": actions, "Resource": resource}]})
+
+ try:
+ assert kin.get_resource_policy(ResourceARN=arn)["Policy"] == "{}"
+ with pytest.raises(ClientError) as exc:
+ kin.delete_resource_policy(ResourceARN=arn)
+ assert _kin_error(exc) == (400, "ResourceNotFoundException", f"No resource policy found for resource ARN {arn}.")
+ for document, message in (
+ ("not json", "Policy validation error: This policy contains invalid Json"),
+ ("{}", "Policy validation error: Missing required field Version"),
+ ('{"Version":"2012-10-17"}', "Policy validation error: Missing required field Statement"),
+ (policy(consumer, ["kinesis:GetRecords"]), "Policy validation error: Resource policy contains invalid statement"
+ " at line 1, column 41: The resource policy's resource must be the same as the resource ARN."),
+ ):
+ with pytest.raises(ClientError) as exc:
+ kin.put_resource_policy(ResourceARN=arn, Policy=document)
+ assert _kin_error(exc) == (400, "InvalidArgumentException", message)
+ with pytest.raises(ClientError) as exc:
+ kin.put_resource_policy(ResourceARN=consumer, Policy=policy(consumer, ["kinesis:GetRecords"]))
+ assert _kin_error(exc) == (400, "InvalidArgumentException", "Policy validation error: Resource policy contains invalid"
+ ' statement at line 1, column 41: The following action names are invalid: "kinesis:GetRecords"')
+
+ stream_policy = policy(arn, ["kinesis:GetRecords", "kinesis:GetShardIterator"])
+ kin.put_resource_policy(ResourceARN=arn, Policy=stream_policy)
+ assert kin.get_resource_policy(ResourceARN=arn)["Policy"] == stream_policy
+ kin.put_resource_policy(ResourceARN=consumer, Policy=policy(consumer, ["kinesis:SubscribeToShard"]))
+ kin.delete_resource_policy(ResourceARN=arn)
+ assert kin.get_resource_policy(ResourceARN=arn)["Policy"] == "{}"
+
+ missing = arn.rsplit("/", 1)[0] + "/no-such-stream"
+ with pytest.raises(ClientError) as exc:
+ kin.get_resource_policy(ResourceARN=missing)
+ assert _kin_error(exc) == (400, "ResourceNotFoundException", f"Stream no-such-stream under account {account} not found.")
+ with pytest.raises(ClientError) as exc:
+ kin.get_resource_policy(ResourceARN=arn.replace(f":{account}:", ":111111111111:"))
+ assert _kin_error(exc) == (400, "UnrecognizedClientException", "No account found for the given parameters")
+ west = arn.replace(":us-east-1:", ":us-west-2:")
+ with pytest.raises(ClientError) as exc:
+ kin.get_resource_policy(ResourceARN=west)
+ assert _kin_error(exc) == (400, "InvalidArgumentException",
+ f"The region specified in the ARN '{west}' does not match the endpoint region")
+ finally:
+ kin.delete_stream(StreamName=name, EnforceConsumerDeletion=True)
+
+
+def test_kinesis_resource_policy_goes_with_its_stream(kin):
+ name = f"rp-del-{_uuid_mod.uuid4().hex[:8]}"
+ kin.create_stream(StreamName=name, ShardCount=1)
+ arn = kin.describe_stream_summary(StreamName=name)["StreamDescriptionSummary"]["StreamARN"]
+ account = arn.split(":")[4]
+ kin.put_resource_policy(ResourceARN=arn, Policy=json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{account}:root"}, "Action": "kinesis:GetRecords",
+ "Resource": arn}]}))
+ kin.delete_stream(StreamName=name)
+ kin.create_stream(StreamName=name, ShardCount=1)
+ try:
+ assert kin.get_resource_policy(ResourceARN=arn)["Policy"] == "{}"
+ finally:
+ kin.delete_stream(StreamName=name)
_FILTER_HANDLER = """
import base64
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 00370bbd..f92722cb 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -4184,7 +4184,7 @@ def test_lambda_provided_runtime_docker_invoke(lam):
lam.delete_function(FunctionName=func_name)
-def test_lambda_provided_runtime_env_has_function_vars():
+def test_lambda_provided_runtime_env_has_function_vars(monkeypatch, tmp_path):
"""_execute_function_provided re-injects AWS_LAMBDA_FUNCTION_MEMORY_SIZE /
_VERSION / LOG_STREAM_NAME from the function config (#1060).
@@ -4229,6 +4229,9 @@ def test_lambda_provided_runtime_env_has_function_vars():
},
"code_zip": buf.getvalue(),
}
+ # This process shares the server's cache directory, which a reset on the server removes; use a private one.
+ monkeypatch.setattr(lmod, "_PROVIDED_CODE_CACHE", str(tmp_path / "provided"))
+ monkeypatch.setattr(lmod, "_provided_code_dirs", {})
result = lmod._execute_function_provided(func, {"ping": "pong"}, request_id="request-1")
assert not result.get("error"), result
body = result["body"]
@@ -4237,7 +4240,7 @@ def test_lambda_provided_runtime_env_has_function_vars():
assert body["log_stream"]
-def test_lambda_provided_runtime_parallel_invocations():
+def test_lambda_provided_runtime_parallel_invocations(monkeypatch, tmp_path):
"""Concurrent provided.* invocations must not fail with ETXTBSY (#1051).
Pre-fix, every invocation extracted the code zip into its own tempdir;
@@ -4278,6 +4281,9 @@ def test_lambda_provided_runtime_parallel_invocations():
"code_zip": buf.getvalue(),
}
+ # This process shares the server's cache directory, which a reset on the server removes; use a private one.
+ monkeypatch.setattr(lmod, "_PROVIDED_CODE_CACHE", str(tmp_path / "provided"))
+ monkeypatch.setattr(lmod, "_provided_code_dirs", {})
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(
lambda i: lmod._execute_function_provided(func, {"n": i}, request_id=f"request-{i}"), range(8)))
@@ -15751,6 +15757,7 @@ def test_lambda_function_url_event_and_response_follow_aws(lam):
assert event["requestContext"]["accountId"] == "anonymous"
assert event["requestContext"]["requestId"] == request_id
assert trace.startswith(headers["x-amzn-trace-id"] + ";Parent=")
+ assert len(resp.headers.get_all("x-amzn-RequestId")) == 1 and resp.headers.get("x-amz-request-id") is None
assert re.fullmatch(r"Root=1-[0-9a-f]{8}-[0-9a-f]{24};Parent=[0-9a-f]{16};Sampled=0;Lineage=1:[0-9a-f]{8}:0", trace)
finally:
lam.delete_function(FunctionName=name)
@@ -15763,3 +15770,23 @@ def test_lambda_code_caches_belong_to_this_instance():
port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
assert os.path.basename(lsvc._PROVIDED_CODE_CACHE) == f"ministack-provided-code-{port}"
assert os.path.basename(lsvc._DOCKER_EXTRACT_CACHE) == f"ministack-lambda-extract-{port}"
+
+
[email protected]("event_source_arn, message", [
+ ("arn:aws:kinesis:us-west-2:000000000000:stream/esm-kinesis-source",
+ "Event source region must match Lambda region us-east-1"),
+ ("arn:aws:kinesis:us-east-1:111111111111:stream/esm-kinesis-source",
+ "Received Exception while reading from provided stream. No account found for the given parameters"),
+])
+def test_lambda_create_esm_kinesis_scope_messages_follow_aws(lam, event_source_arn, message):
+ """Captured on AWS (us-east-1, 2026-10-26)."""
+ name = f"esm-scope-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(FunctionName=name, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": _make_zip("def handler(e, c): return None")})
+ try:
+ with pytest.raises(ClientError) as exc:
+ lam.create_event_source_mapping(EventSourceArn=event_source_arn, FunctionName=name, StartingPosition="LATEST")
+ err = exc.value.response["Error"]
+ assert (err["Code"], err["Message"]) == ("InvalidParameterValueException", message)
+ finally:
+ lam.delete_function(FunctionName=name)
diff --git a/tests/test_opensearch.py b/tests/test_opensearch.py
index 17d69ac5..5b67d510 100644
--- a/tests/test_opensearch.py
+++ b/tests/test_opensearch.py
@@ -724,9 +724,8 @@ def test_opensearch_cold_image_publishes_the_real_endpoint(fake_docker, monkeypa
assert rec["Endpoint"] == "localhost:19200"
[email protected]("value", ["-Xms512m -Xmx512m", ""])
-def test_opensearch_engine_container_passes_java_opts(fake_docker, monkeypatch, value):
- """OPENSEARCH_JAVA_OPTS reaches the engine container when set; unset or empty adds nothing."""
+def test_opensearch_engine_container_has_a_512m_heap(fake_docker, monkeypatch):
+ """Every engine container runs with a 512 MB heap rather than the image's 1 GB."""
from ministack.services import opensearch as os_
runs = []
@@ -734,12 +733,10 @@ def test_opensearch_engine_container_passes_java_opts(fake_docker, monkeypatch,
monkeypatch.setattr(
fake_docker.containers, "run", lambda **kw: (runs.append(kw), run(**kw))[1]
)
- monkeypatch.setattr(os_, "JAVA_OPTS", value)
- os_.start_engine_container(fake_docker, f"java-opts-{_uid()}", {}, 19203)
+ os_.start_engine_container(fake_docker, f"heap-{_uid()}", {}, 19203)
- env = runs[0]["environment"]
- assert env.get("OPENSEARCH_JAVA_OPTS") == (value or None)
+ assert runs[0]["environment"]["OPENSEARCH_JAVA_OPTS"] == "-Xms512m -Xmx512m"
@pytest.mark.serial
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 5e146d1d..a0804617 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -2,21 +2,29 @@ import asyncio
import base64
import contextlib
import hashlib
+import http.client
import json
import os
import re
import struct
import time
+import urllib.error
+import urllib.request
import uuid
import uuid as _uuid_mod
from datetime import datetime
-from urllib.parse import urlparse
+from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlsplit
from xml.etree import ElementTree
+from xml.etree.ElementTree import fromstring
import boto3
import pytest
import requests
+from botocore import UNSIGNED
+from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth
+from botocore.awsrequest import AWSRequest
from botocore.config import Config
+from botocore.credentials import Credentials
from botocore.exceptions import ClientError
from conftest import (
inprocess_iam_user,
@@ -11048,3 +11056,1522 @@ def test_s3_copy_source_in_the_query_string_is_authorized_contract(auth_enabled,
for item in s3.list_objects_v2(Bucket=bucket).get("Contents", []):
s3.delete_object(Bucket=bucket, Key=item["Key"])
s3.delete_bucket(Bucket=bucket)
+
+
+# ---------------------------------------------------------------------------
+# S3 Access Points: the S3 Control API and the data plane through an access point ARN or alias.
+# ---------------------------------------------------------------------------
+
+
+ACCOUNT = "000000000000"
+
+
+def _client(service, region, account_key="test"):
+ return boto3.client(
+ service, endpoint_url=ENDPOINT, region_name=region,
+ aws_access_key_id=account_key, aws_secret_access_key="test",
+ config=Config(region_name=region, retries={"mode": "standard"}),
+ )
+
+
[email protected](autouse=True)
+def _s3control_dns():
+ """boto3 prefixes S3 Control and access point hosts with the account id."""
+ with patch_endpoint_dns():
+ yield
+
+
+def _uid():
+ return uuid.uuid4().hex[:8]
+
+
+def bucket():
+ """A bucket in us-east-1 holding k.txt."""
+ s3 = _client("s3", "us-east-1")
+ name = f"ap-data-{_uid()}"
+ s3.create_bucket(Bucket=name)
+ s3.put_object(Bucket=name, Key="k.txt", Body=b"hello")
+ yield name
+ for obj in s3.list_objects_v2(Bucket=name).get("Contents", []):
+ s3.delete_object(Bucket=name, Key=obj["Key"])
+ try:
+ s3.delete_bucket(Bucket=name)
+ except ClientError:
+ pass
+
+
+def access_point(bucket):
+ ctl = _client("s3control", "us-east-1")
+ name = f"ap-{_uid()}"
+ created = ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
+ yield name, created
+ try:
+ ctl.delete_access_point(AccountId=ACCOUNT, Name=name)
+ except ClientError:
+ pass
+
+
+# --- Control plane ---------------------------------------------------------
+
+def test_access_point_control_create_get_list_delete(bucket):
+ ctl = _client("s3control", "us-east-1")
+ name = f"ap-{_uid()}"
+ created = ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
+ arn = f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}"
+ assert created["AccessPointArn"] == arn
+ assert re.fullmatch(rf"{name[:20]}-[a-z0-9]{{29}}use1b-s3alias", created["Alias"])
+
+ ap = ctl.get_access_point(AccountId=ACCOUNT, Name=name)
+ assert (ap["Name"], ap["Bucket"], ap["BucketAccountId"], ap["NetworkOrigin"]) == (
+ name, bucket, ACCOUNT, "Internet")
+ assert ap["AccessPointArn"] == arn and ap["Alias"] == created["Alias"]
+ assert ap["PublicAccessBlockConfiguration"] == {
+ "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True}
+ assert ap["Endpoints"]["ipv4"] == "s3-accesspoint.us-east-1.amazonaws.com"
+ assert set(ap["Endpoints"]) == {"ipv4", "fips", "dualstack", "fips_dualstack"}
+ assert "CreationDate" in ap
+
+ second = f"ap-{_uid()}"
+ ctl.create_access_point(AccountId=ACCOUNT, Name=second, Bucket=bucket,
+ VpcConfiguration={"VpcId": "vpc-0123456789abcdef0"})
+ try:
+ listed = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket)["AccessPointList"]
+ assert sorted(a["Name"] for a in listed) == sorted([name, second])
+ assert {a["Name"]: a["NetworkOrigin"] for a in listed}[second] == "VPC"
+ page = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket, MaxResults=1)
+ assert len(page["AccessPointList"]) == 1 and page["NextToken"]
+ rest = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket, NextToken=page["NextToken"])
+ assert len(rest["AccessPointList"]) == 1
+ finally:
+ ctl.delete_access_point(AccountId=ACCOUNT, Name=second)
+
+ with pytest.raises(ClientError) as exc:
+ ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ assert exc.value.response["Error"]["Code"] == "AccessPointAlreadyOwnedByYou"
+ assert exc.value.response["Error"]["Message"] == (
+ "Your previous request to create the named accesspoint succeeded and you already own it.")
+
+ with pytest.raises(ClientError) as exc:
+ _client("s3", "us-east-1").delete_bucket(Bucket=bucket)
+ assert exc.value.response["Error"]["Code"] == "BucketHasAccessPointsAttached"
+
+ ctl.delete_access_point(AccountId=ACCOUNT, Name=name)
+ with pytest.raises(ClientError) as exc:
+ ctl.get_access_point(AccountId=ACCOUNT, Name=name)
+ err = exc.value.response["Error"]
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert (err["Code"], err["Message"], err["AccessPointName"]) == (
+ "NoSuchAccessPoint", "The specified accesspoint does not exist", name)
+
+
+def test_access_point_control_bucket_must_be_in_request_region(bucket):
+ with pytest.raises(ClientError) as exc:
+ _client("s3control", "eu-west-1").create_access_point(AccountId=ACCOUNT, Name=f"ap-{_uid()}", Bucket=bucket)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "InvalidRequest"
+ assert exc.value.response["Error"]["Message"] == (
+ "Amazon S3 AccessPoint can only be created for bucket in the same region")
+
+
+def test_access_point_control_same_name_in_another_region(bucket):
+ """Access point names are unique per account and region (observed)."""
+ euw1_s3 = _client("s3", "eu-west-1")
+ euw1_bucket = f"ap-euw1-{_uid()}"
+ euw1_s3.create_bucket(Bucket=euw1_bucket, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
+ name = f"ap-{_uid()}"
+ use1, euw1 = _client("s3control", "us-east-1"), _client("s3control", "eu-west-1")
+ use1.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
+ try:
+ alias = euw1.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=euw1_bucket)["Alias"]
+ assert alias.endswith("euw1b-s3alias")
+ assert euw1.get_access_point(AccountId=ACCOUNT, Name=name)["Bucket"] == euw1_bucket
+ assert use1.get_access_point(AccountId=ACCOUNT, Name=name)["Bucket"] == bucket
+ euw1.delete_access_point(AccountId=ACCOUNT, Name=name)
+ finally:
+ use1.delete_access_point(AccountId=ACCOUNT, Name=name)
+ euw1_s3.delete_bucket(Bucket=euw1_bucket)
+
+
+def test_access_point_control_policy_round_trip(access_point):
+ name, _ = access_point
+ ctl = _client("s3control", "us-east-1")
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]})
+ ctl.put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=policy)
+ assert ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)["Policy"] == policy
+ ctl.delete_access_point_policy(AccountId=ACCOUNT, Name=name)
+ with pytest.raises(ClientError) as exc:
+ ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
[email protected]("method,path,status,fields", [
+ ("POST", "/{ap}/policy", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTPOLICY"}),
+ ("PATCH", "/{ap}/policy", 405, {"Method": "PATCH", "ResourceType": "ACCESSPOINTPOLICY"}),
+ ("POST", "/{ap}", 405, {"Method": "POST", "ResourceType": "ACCESSPOINT"}),
+ ("POST", "", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTS"}),
+ ("GET", "/{ap}/x", 400, {"URI": "accesspoint/{ap}/x"}),
+ ("DELETE", "/{ap}/x", 400, {}),
+ ("DELETE", "/{ap}/policy/x", 400, {}),
+ ("GET", "/{ap}/", 400, {}),
+ ("GET", "//{ap}", 400, {}),
+ ("PUT", "//{ap}/policy", 400, {}),
+ ("GET", "/", 400, {}), ("GET", "/{ap}/policyStatus", 404, {"AccessPointName": "{ap}/policyStatus"}),
+ ("GET", "/{ap}/scope", 404, {}),
+])
+def test_access_point_control_unserved_requests(access_point, method, path, status, fields):
+ """Unserved methods answer 405, unparsed paths 400, unemulated routes 404; none changes the access point."""
+ name, _ = access_point
+ ctl = _client("s3control", "us-east-1")
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]})
+ ctl.put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=policy)
+ body = b"<PutAccessPointPolicyRequest><Policy>{}</Policy></PutAccessPointPolicyRequest>"
+ got, _, data = _raw(method, ENDPOINT.split("://", 1)[1], "/v20180820/accesspoint" + path.format(ap=name),
+ "us-east-1", body if method == "PUT" else b"", headers={"x-amz-account-id": ACCOUNT})
+ code = {405: "MethodNotAllowed", 400: "InvalidURI", 404: "NoSuchAccessPoint"}[status]
+ assert (got, re.search(rb"<Code>(\w+)</Code>", data).group(1).decode()) == (status, code)
+ for tag, value in fields.items():
+ assert f"<{tag}>{value.format(ap=name)}</{tag}>".encode() in data
+ assert ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)["Policy"] == policy
+
+
+def test_access_point_named_policy_needs_the_access_point_action(auth_enabled, iam_user, bucket):
+ """/v20180820/accesspoint/policy names an access point called "policy"."""
+ ctl = _client("s3control", "us-east-1")
+ ctl.create_access_point(AccountId=ACCOUNT, Name="policy", Bucket=bucket)
+ try:
+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": ["s3:GetAccessPointPolicy", "s3:DeleteAccessPointPolicy"],
+ "Resource": "*"}]}).client("s3control", region="us-east-1")
+ user.delete_access_point_policy(AccountId=ACCOUNT, Name="policy")
+ if auth_enabled:
+ for call in (user.get_access_point, user.delete_access_point):
+ with pytest.raises(ClientError) as exc:
+ call(AccountId=ACCOUNT, Name="policy")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+ assert ctl.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket
+ else:
+ assert user.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket
+ user.delete_access_point(AccountId=ACCOUNT, Name="policy")
+ finally:
+ try:
+ ctl.delete_access_point(AccountId=ACCOUNT, Name="policy")
+ except ClientError:
+ pass
+
+
+def test_access_point_policy_unserved_method_is_refused_before_authorization(auth_enabled, iam_user, access_point):
+ """POST on an access point policy answers 405 to any caller and returns no policy."""
+ name, _ = access_point
+ _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({
+ "Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]}))
+ user = iam_user()
+ iam = make_client("iam")
+ key = iam.create_access_key(UserName=user.name)["AccessKey"]
+ try:
+ signed = {"key": (key["AccessKeyId"], key["SecretAccessKey"]), "headers": {"x-amz-account-id": ACCOUNT}}
+ host, path = ENDPOINT.split("://", 1)[1], f"/v20180820/accesspoint/{name}/policy"
+ status, _, data = _raw("POST", host, path, "us-east-1", **signed)
+ assert status == 405 and b"<ResourceType>ACCESSPOINTPOLICY</ResourceType>" in data
+ assert b"<Policy>" not in data
+ assert _raw("GET", host, path, "us-east-1", **signed)[0] == (403 if auth_enabled else 200)
+ finally:
+ iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
+
+
+# --- Data plane --------------------------------------------------------------
+
+def _raw(method, host, path, region, body=b"", key=("test", "test"), headers=None):
+ """A SigV4-signed request with an explicit Host, no redirect handling."""
+ import hashlib
+ import http.client
+ from urllib.parse import urlparse
+
+ from botocore.auth import S3SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ req = AWSRequest(method=method, url=f"http://{host}{path}", data=body, headers=headers)
+ req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()
+ S3SigV4Auth(Credentials(*key), "s3", region).add_auth(req)
+ parsed = urlparse(ENDPOINT)
+ conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)
+ conn.request(method, path, body=body or None, headers={**dict(req.headers.items()), "Host": host})
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data
+
+
+def test_access_point_arn_reaches_the_bucket(bucket, access_point):
+ name, created = access_point
+ s3 = _client("s3", "us-east-1")
+ arn = created["AccessPointArn"]
+ assert s3.get_object(Bucket=arn, Key="k.txt")["Body"].read() == b"hello"
+ s3.put_object(Bucket=arn, Key="through-ap.txt", Body=b"via ap")
+ assert s3.get_object(Bucket=bucket, Key="through-ap.txt")["Body"].read() == b"via ap"
+ keys = [o["Key"] for o in s3.list_objects_v2(Bucket=arn)["Contents"]]
+ assert keys == ["k.txt", "through-ap.txt"]
+ # A client configured for another region still signs for the ARN's region.
+ assert _client("s3", "eu-west-1").get_object(Bucket=arn, Key="k.txt")["Body"].read() == b"hello"
+
+
+def test_access_point_arn_wrong_region_signing_gets_the_redirect(access_point):
+ name, _ = access_point
+ host = f"{name}-{ACCOUNT}.{ENDPOINT.split('://', 1)[1]}"
+ status, headers, _ = _raw("GET", host, "/k.txt", "eu-west-1")
+ assert status == 301
+ assert headers["x-amz-bucket-region"] == "us-east-1"
+ assert _raw("GET", host, "/k.txt", "us-east-1")[0] == 200
+
+
+def test_access_point_arn_other_account_is_denied(access_point):
+ _, created = access_point
+ other = _client("s3", "us-east-1", account_key="111122223333")
+ with pytest.raises(ClientError) as exc:
+ other.get_object(Bucket=created["AccessPointArn"], Key="k.txt")
+ assert exc.value.response["Error"]["Code"] in ("AccessDenied", "NoSuchAccessPoint")
+
+
[email protected]("method", ["GET", "HEAD"])
+def test_access_point_arn_shaped_bucket_without_access_point_is_a_bucket(auth_enabled, method):
+ """`<name>-<12 digits>` is a valid bucket name; with no access point of
+ that name it is served as the bucket."""
+ s3 = _client("s3", "us-east-1")
+ name = f"plain-{_uid()}-123456789012"
+ s3.create_bucket(Bucket=name)
+ try:
+ s3.put_object(Bucket=name, Key="b.txt", Body=b"bucket")
+ host = f"{name}.{ENDPOINT.split('://', 1)[1]}"
+ status, headers, body = _raw(method, host, "/b.txt", "us-east-1")
+ assert status == 200
+ assert body == (b"bucket" if method == "GET" else b"")
+ if auth_enabled and method == "HEAD":
+ assert re.fullmatch(r"[A-Z0-9]{16}", headers["x-amz-request-id"])
+ finally:
+ s3.delete_object(Bucket=name, Key="b.txt")
+ s3.delete_bucket(Bucket=name)
+
+
+def test_access_point_alias_works_as_a_bucket_name(bucket, access_point):
+ _, created = access_point
+ s3 = _client("s3", "us-east-1")
+ alias = created["Alias"]
+ assert s3.get_object(Bucket=alias, Key="k.txt")["Body"].read() == b"hello"
+ s3.put_object(Bucket=alias, Key="alias.txt", Body=b"via alias")
+ assert s3.get_object(Bucket=bucket, Key="alias.txt")["Body"].read() == b"via alias"
+ s3.copy_object(Bucket=bucket, Key="copied.txt", CopySource={"Bucket": alias, "Key": "k.txt"})
+ assert s3.get_object(Bucket=bucket, Key="copied.txt")["Body"].read() == b"hello"
+
+
[email protected]("addressing_style", ["path", "virtual"])
[email protected]("allow_upload", [False, True], ids=["no-permission", "allow"])
+def test_access_point_alias_upload_permission_contract(
+ bucket, access_point, auth_enabled, iam_user, addressing_style, allow_upload,
+):
+ _, created = access_point
+ policy = {"Statement": [{"Effect": "Allow", "Action": "s3:PutObject", "Resource": "*"}]}
+ client = iam_user(policy=policy if allow_upload else None).client(
+ "s3", config=Config(s3={"addressing_style": addressing_style}),
+ )
+ root = _client("s3", "us-east-1")
+ if auth_enabled and not allow_upload:
+ with pytest.raises(ClientError) as exc:
+ client.put_object(Bucket=created["Alias"], Key="contract-upload", Body=b"via alias")
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+ assert root.list_objects_v2(Bucket=bucket, Prefix="contract-upload")["KeyCount"] == 0
+ else:
+ assert client.put_object(
+ Bucket=created["Alias"], Key="contract-upload", Body=b"via alias",
+ )["ResponseMetadata"]["HTTPStatusCode"] == 200
+ with root.get_object(Bucket=bucket, Key="contract-upload")["Body"] as body:
+ assert body.read() == b"via alias"
+
+
[email protected]("target,addressing_style", [("Alias", "path"), ("Alias", "virtual"), ("AccessPointArn", "virtual")])
[email protected]("allow_head", [False, True], ids=["no-permission", "allow"])
+def test_access_point_head_permission_contract(access_point, auth_enabled, iam_user, target, addressing_style, allow_head):
+ _, created = access_point
+ policy = {"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}
+ client = iam_user(policy=policy if allow_head else None).client(
+ "s3", region="us-east-1", config=Config(s3={"addressing_style": addressing_style}))
+ if auth_enabled and not allow_head:
+ with pytest.raises(ClientError) as exc:
+ client.head_object(Bucket=created[target], Key="k.txt")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ else:
+ response = client.head_object(Bucket=created[target], Key="k.txt")
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert response["ContentLength"] == 5
+
+
[email protected]("target", ["Alias", "AccessPointArn"])
[email protected]("allow_delete", [False, True], ids=["no-permission", "allow"])
+def test_access_point_delete_permission_contract(bucket, access_point, auth_enabled, iam_user, target, allow_delete):
+ _, created = access_point
+ policy = {"Statement": [{"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "*"}]}
+ client = iam_user(policy=policy if allow_delete else None).client("s3", region="us-east-1")
+ root = _client("s3", "us-east-1")
+ if auth_enabled and not allow_delete:
+ with pytest.raises(ClientError) as exc:
+ client.delete_object(Bucket=created[target], Key="k.txt")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
+ with root.get_object(Bucket=bucket, Key="k.txt")["Body"] as body:
+ assert body.read() == b"hello"
+ else:
+ assert client.delete_object(Bucket=created[target], Key="k.txt")["ResponseMetadata"]["HTTPStatusCode"] == 204
+ with pytest.raises(ClientError) as exc:
+ root.head_object(Bucket=bucket, Key="k.txt")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def _ap_status(call):
+ try:
+ return call()["ResponseMetadata"]["HTTPStatusCode"]
+ except ClientError as exc:
+ return exc.response["ResponseMetadata"]["HTTPStatusCode"], exc.response["Error"]["Code"]
+
+
+def test_access_point_block_public_acls_refuses_public_acl_writes():
+ """An access point's BlockPublicAcls refuses public ACLs sent through it, whatever the bucket's settings."""
+ s3, ctl = _client("s3", "us-east-1"), _client("s3control", "us-east-1")
+ name = f"ap-acl-{_uid()}"
+ all_off = {k: False for k in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")}
+ s3.create_bucket(Bucket=name, ObjectOwnership="BucketOwnerPreferred")
+ s3.put_public_access_block(Bucket=name, PublicAccessBlockConfiguration=all_off)
+ s3.put_object(Bucket=name, Key="k.txt", Body=b"hello")
+ blocking = ctl.create_access_point(AccountId=ACCOUNT, Name=f"ap-on-{_uid()}", Bucket=name)
+ open_ap = ctl.create_access_point(
+ AccountId=ACCOUNT, Name=f"ap-off-{_uid()}", Bucket=name, PublicAccessBlockConfiguration=all_off)
+ try:
+ denied = (403, "AccessDenied")
+ for target in (blocking["Alias"], blocking["AccessPointArn"]):
+ assert _ap_status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == denied
+ assert _ap_status(lambda: s3.put_object_acl(Bucket=target, Key="k.txt", ACL="public-read")) == denied
+ assert _ap_status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="private")) == 200
+ for target in (open_ap["Alias"], open_ap["AccessPointArn"], name):
+ assert _ap_status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == 200
+ finally:
+ for ap in (blocking, open_ap):
+ ctl.delete_access_point(AccountId=ACCOUNT, Name=ap["AccessPointArn"].rsplit("/", 1)[1])
+ for obj in s3.list_objects_v2(Bucket=name).get("Contents", []):
+ s3.delete_object(Bucket=name, Key=obj["Key"])
+ s3.delete_bucket(Bucket=name)
+
+
+def test_access_point_alias_from_another_account_is_denied(access_point):
+ _name, created = access_point
+ other = _client("s3", "us-east-1", account_key="111122223333")
+ with pytest.raises(ClientError) as exc:
+ other.get_object(Bucket=created["Alias"], Key="k.txt")
+ assert exc.value.response["Error"]["Code"] == "AccessDenied"
+
+
+def _access_point_policy(bucket, access_point_arn, grant, deny=None, condition=None):
+ """An identity policy allowing reads and copies on ``grant`` ("bucket", "access point" or "both")."""
+ arns = {"bucket": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],
+ "access point": [access_point_arn, f"{access_point_arn}/object/*"]}
+ resources = arns["bucket"] + arns["access point"] if grant == "both" else arns[grant]
+ statements = [{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
+ "Resource": resources}]
+ if deny or condition:
+ statements.append({"Effect": "Deny", "Action": ["s3:GetObject", "s3:ListBucket"],
+ "Resource": arns[deny] if deny else "*", **({"Condition": condition} if condition else {})})
+ return {"Version": "2012-10-17", "Statement": statements}
+
+
+def _assert_access(auth_enabled, allowed, call):
+ """Under AUTH a refused call answers 403 AccessDenied; anything else succeeds."""
+ if auth_enabled and not allowed:
+ with pytest.raises(ClientError) as exc:
+ call()
+ error = exc.value.response
+ assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("AccessDenied", 403)
+ else:
+ call()
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("grant, deny, allowed", [
+ ("both", None, True),
+ ("bucket", None, False),
+ ("access point", None, False),
+ ("both", "access point", False),
+ ("both", "bucket", False),
+], ids=["both", "bucket-only", "access-point-only", "deny-access-point", "deny-bucket"])
+def test_access_point_request_needs_access_point_and_bucket_contract(auth_enabled, iam_user, bucket, access_point,
+ via, grant, deny, allowed):
+ """Through an access point a read and a listing are checked on the access point and on its bucket."""
+ _name, created = access_point
+ client = iam_user(policy=_access_point_policy(bucket, created["AccessPointArn"], grant, deny)).client("s3")
+ target = created[via]
+ _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=target, Key="k.txt"))
+ _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=target))
+ _assert_access(auth_enabled, grant != "access point" and deny != "bucket",
+ lambda: client.get_object(Bucket=bucket, Key="k.txt"))
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("key, condition_value, through_access_point, through_bucket", [
+ ("s3:DataAccessPointArn", "arn", False, True),
+ ("s3:DataAccessPointAccount", ACCOUNT, False, True),
+ ("s3:AccessPointNetworkOrigin", "Internet", False, True),
+ ("s3:ExistingObjectTag/class", "secret", False, False),
+ ("s3:DataAccessPointArn", None, True, False),
+], ids=["arn", "account", "network-origin", "object-tag", "arn-absent"])
+def test_access_point_condition_keys_contract(auth_enabled, iam_user, bucket, access_point, via, key,
+ condition_value, through_access_point, through_bucket):
+ """A request through an access point carries its ARN, account and network origin, and the object's tags."""
+ _name, created = access_point
+ _client("s3", "us-east-1").put_object_tagging(Bucket=bucket, Key="k.txt",
+ Tagging={"TagSet": [{"Key": "class", "Value": "secret"}]})
+ arn = created["AccessPointArn"]
+ condition = ({"Null": {key: "true"}} if condition_value is None
+ else {"StringEquals": {key: arn if condition_value == "arn" else condition_value}})
+ client = iam_user(policy=_access_point_policy(bucket, arn, "both", condition=condition)).client("s3")
+ _assert_access(auth_enabled, through_access_point, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
+ _assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("condition, through_bucket", [(False, False), (True, True)], ids=["deny", "deny-on-arn-key"])
+def test_access_point_request_meets_the_bucket_policy_contract(auth_enabled, iam_user, bucket, access_point, via,
+ condition, through_bucket):
+ """The bucket policy applies through an access point and sees its ARN."""
+ _name, created = access_point
+ arn = created["AccessPointArn"]
+ user = iam_user(policy=_access_point_policy(bucket, arn, "both"))
+ statement = {"Effect": "Deny", "Principal": {"AWS": user.arn}, "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:::{bucket}/*"}
+ if condition:
+ statement["Condition"] = {"StringEquals": {"s3:DataAccessPointArn": arn}}
+ _client("s3", "us-east-1").put_bucket_policy(
+ Bucket=bucket, Policy=json.dumps({"Version": "2012-10-17", "Statement": [statement]}))
+ client = user.client("s3")
+ _assert_access(auth_enabled, False, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
+ _assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("grant, effect, delegate, allowed", [
+ ("bucket", "Allow", False, True),
+ (None, "Allow", True, True),
+ ("access point", None, True, True),
+ ("access point", "Allow", False, False),
+ ("both", "Deny", True, False),
+], ids=["allow-identity-on-bucket", "allow-delegated", "delegated-identity-on-access-point",
+ "allow-not-delegated", "deny"])
+def test_access_point_policy_contract(auth_enabled, iam_user, bucket, access_point, via, grant, effect, delegate,
+ allowed):
+ """The access point policy answers for the access point, the bucket policy or identity for the bucket."""
+ name, created = access_point
+ arn = created["AccessPointArn"]
+ user = iam_user(policy=_access_point_policy(bucket, arn, grant) if grant else None)
+ if delegate:
+ _client("s3", "us-east-1").put_bucket_policy(Bucket=bucket, Policy=json.dumps({
+ "Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "*",
+ "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],
+ "Condition": {"StringEquals": {"s3:DataAccessPointAccount": ACCOUNT}}}]}))
+ if effect:
+ _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({
+ "Version": "2012-10-17", "Statement": [{
+ "Effect": effect, "Principal": {"AWS": user.arn}, "Action": ["s3:GetObject", "s3:ListBucket"],
+ "Resource": [arn, f"{arn}/object/*"]}]}))
+ client = user.client("s3")
+ _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
+ _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=created[via]))
+ _assert_access(auth_enabled, grant in ("bucket", "both"), lambda: client.get_object(Bucket=bucket, Key="k.txt"))
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
+def test_access_point_refuses_bucket_policy_writes_contract(auth_enabled, iam_user, bucket, access_point, via):
+ """Under AUTH an access point refuses PutBucketPolicy and DeleteBucketPolicy and serves GetBucketPolicy."""
+ _name, created = access_point
+ arn = created["AccessPointArn"]
+ client = iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": ["s3:PutBucketPolicy", "s3:GetBucketPolicy", "s3:DeleteBucketPolicy"],
+ "Resource": [f"arn:aws:s3:::{bucket}", arn]}]}).client("s3", region="us-east-1")
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
+ "Resource": f"arn:aws:s3:::{bucket}/*"}]})
+ client.put_bucket_policy(Bucket=bucket, Policy=policy)
+ assert client.get_bucket_policy(Bucket=created[via])["Policy"] == policy
+ for write in (lambda: client.delete_bucket_policy(Bucket=created[via]),
+ lambda: client.put_bucket_policy(Bucket=created[via], Policy=policy)):
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ write()
+ error = exc.value.response["Error"]
+ assert error["Code"] == "AccessDenied"
+ assert error["Message"].endswith(f'on resource: "{arn}" with an explicit deny in a resource-based policy')
+ assert client.get_bucket_policy(Bucket=bucket)["Policy"] == policy
+ else:
+ write()
+ client.delete_bucket_policy(Bucket=bucket)
+
+
+def test_access_point_refuses_unsigned_requests_contract(auth_enabled, bucket, access_point):
+ """Under AUTH an unsigned request through an access point is refused; the bucket still serves it."""
+ _name, created = access_point
+ s3 = _client("s3", "us-east-1")
+ s3.put_bucket_ownership_controls(Bucket=bucket, OwnershipControls={
+ "Rules": [{"ObjectOwnership": "BucketOwnerPreferred"}]})
+ s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration={k: False for k in (
+ "BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")})
+ s3.put_object(Bucket=bucket, Key="pub.txt", Body=b"public", ACL="public-read")
+ anon = boto3.client("s3", endpoint_url=ENDPOINT, region_name="us-east-1",
+ config=Config(signature_version=UNSIGNED, retries={"mode": "standard"}))
+ assert anon.get_object(Bucket=bucket, Key="pub.txt")["Body"].read() == b"public"
+ for target in (created["Alias"], created["AccessPointArn"]):
+ if auth_enabled:
+ with pytest.raises(ClientError) as exc:
+ anon.get_object(Bucket=target, Key="pub.txt")
+ error = exc.value.response
+ assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidRequest", 400)
+ else:
+ assert anon.get_object(Bucket=target, Key="pub.txt")["Body"].read() == b"public"
+
+
[email protected]("via", ["AccessPointArn", "Alias"])
+def test_access_point_sigv2_requests_contract(auth_enabled, iam_user, bucket, access_point, via):
+ """Through an access point a SigV2 presigned URL is served, a SigV2 Authorization header is refused under AUTH."""
+ _name, created = access_point
+ user = iam_user(policy=_access_point_policy(bucket, created["AccessPointArn"], "both"))
+ client = user.client("s3", region="us-east-1", config=Config(signature_version="s3"))
+ url = client.generate_presigned_url("get_object", Params={"Bucket": created[via], "Key": "k.txt"})
+ assert "AWSAccessKeyId=" in url
+ with urllib.request.urlopen(url, timeout=10) as resp:
+ assert resp.read() == b"hello"
+ tampered = re.sub(r"Signature=[^&]+", "Signature=AAAA", url)
+ if auth_enabled:
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(tampered, timeout=10)
+ assert exc.value.code == 403
+ assert b"<Code>SignatureDoesNotMatch</Code>" in exc.value.read()
+ with pytest.raises(ClientError) as exc:
+ client.get_object(Bucket=created[via], Key="k.txt")
+ error = exc.value.response
+ assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidRequest", 400)
+ else:
+ with urllib.request.urlopen(tampered, timeout=10) as resp:
+ assert resp.read() == b"hello"
+ assert client.get_object(Bucket=created[via], Key="k.txt")["Body"].read() == b"hello"
+ assert client.get_object(Bucket=bucket, Key="k.txt")["Body"].read() == b"hello"
+
+
[email protected]("grant, deny, condition, allowed", [
+ ("both", None, False, True),
+ ("bucket", None, False, False),
+ ("both", "access point", False, False),
+ ("both", None, True, False),
+], ids=["both", "bucket-only", "deny-access-point", "deny-on-arn-key"])
+def test_access_point_alias_copy_source_contract(auth_enabled, iam_user, bucket, access_point, grant, deny,
+ condition, allowed):
+ """A copy source named by an alias is read through its access point."""
+ _name, created = access_point
+ arn = created["AccessPointArn"]
+ policy = _access_point_policy(bucket, arn, grant, deny,
+ {"StringEquals": {"s3:DataAccessPointArn": arn}} if condition else None)
+ client = iam_user(policy=policy).client("s3")
+ _assert_access(auth_enabled, allowed, lambda: client.copy_object(
+ Bucket=bucket, Key="copy.txt", CopySource={"Bucket": created["Alias"], "Key": "k.txt"}))
+ _assert_access(auth_enabled, True, lambda: client.copy_object(
+ Bucket=bucket, Key="copy.txt", CopySource={"Bucket": bucket, "Key": "k.txt"}))
+
+
+def test_access_point_control_invalid_name(bucket):
+ ctl = _client("s3control", "us-east-1")
+ with pytest.raises(ClientError) as exc:
+ ctl.create_access_point(AccountId=ACCOUNT, Name="Bad_Name", Bucket=bucket)
+ err = exc.value.response
+ assert (err["Error"]["Code"], err["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidAccessPoint", 400)
+
+
+# ---------------------------------------------------------------------------
+# GetObject error order, as observed on AWS (Osaka and Tokyo, 2026-10-18), replayed locally.
+# ---------------------------------------------------------------------------
+
+
+HOME, TOKYO = "ap-northeast-3", "ap-northeast-1"
+_DOWNLOAD_PAYLOAD = b"download error validation"
+
+
+def download_bucket(s3):
+ name = f"download-errors-{uuid.uuid4().hex}"
+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
+ s3.put_object(Bucket=name, Key="probe.txt", Body=_DOWNLOAD_PAYLOAD)
+ yield name
+ s3.delete_object(Bucket=name, Key="probe.txt")
+ s3.delete_bucket(Bucket=name)
+
+
+def download_client(download_bucket, iam_user):
+ return iam_user(policy={"Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{download_bucket}/*"},
+ {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": f"arn:aws:s3:::{download_bucket}"},
+ ]}).client("s3", region=HOME)
+
+
+def _download(bucket, client, *, credential="valid", endpoint_region=HOME, region=HOME,
+ virtual=False, key="probe.txt", query="", root=False):
+ frozen = client._request_signer._credentials.get_frozen_credentials()
+ access_key, secret = frozen.access_key, frozen.secret_key
+ if credential == "unknown":
+ access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
+ elif credential == "wrong-secret":
+ secret = "wrong"
+ if root:
+ access_key, secret = "test", "any-secret"
+ target = urlsplit(ENDPOINT)
+ host = f"s3.{endpoint_region}.{target.netloc}"
+ path = f"/{quote(bucket)}/{quote(key, safe='/')}"
+ if virtual:
+ host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
+ request = AWSRequest(method="GET", url=f"http://{host}{path}{query}")
+ S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
+ connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
+ try:
+ connection.request("GET", path + query, headers={**dict(request.headers), "Host": host})
+ response = connection.getresponse()
+ return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
+ finally:
+ connection.close()
+
+
+def _assert_download_error(response, code, *, bucket, key="probe.txt", region=HOME, access_key=None):
+ _, headers, body = response
+ error = fromstring(body)
+ messages = {
+ "InvalidBucketName": "The specified bucket is not valid.",
+ "InvalidAccessKeyId": "The AWS Access Key Id you provided does not exist in our records.",
+ "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. "
+ "Check your key and signing method.",
+ "AuthorizationHeaderMalformed": f"The authorization header is malformed; the region '{region}' is wrong; "
+ f"expecting '{HOME if region == TOKYO else TOKYO}'",
+ "PermanentRedirect": "The bucket you are attempting to access must be addressed using the specified "
+ "endpoint. Please send all future requests to this endpoint.",
+ "NoSuchBucket": "The specified bucket does not exist",
+ "NoSuchKey": "The specified key does not exist.",
+ }
+ details = {
+ "InvalidBucketName": ["BucketName"], "InvalidAccessKeyId": ["AWSAccessKeyId"],
+ "AuthorizationHeaderMalformed": ["Region"], "PermanentRedirect": ["Bucket", "Endpoint"],
+ "NoSuchBucket": ["BucketName"], "NoSuchKey": ["Key"],
+ "SignatureDoesNotMatch": ["AWSAccessKeyId", "StringToSign", "SignatureProvided", "StringToSignBytes",
+ "CanonicalRequest", "CanonicalRequestBytes"],
+ }
+ expected = ["Code", "Message", *details[code], "RequestId", "HostId"]
+ assert error.findtext("Code") == code
+ assert error.findtext("Message") == messages[code]
+ if code == "SignatureDoesNotMatch":
+ # Real GET responses varied the order of the signature diagnostics.
+ assert sorted(child.tag for child in error) == sorted(expected)
+ for name in ("CanonicalRequest", "StringToSign"):
+ assert bytes.fromhex(error.findtext(name + "Bytes")).decode() == error.findtext(name)
+ assert error.findtext("CanonicalRequest").startswith("GET\n")
+ assert error.findtext("StringToSign").splitlines()[-1] == hashlib.sha256(
+ error.findtext("CanonicalRequest").encode()).hexdigest()
+ assert re.fullmatch(r"[a-f0-9]{64}", error.findtext("SignatureProvided"))
+ signed = AWSRequest()
+ document = error.findtext("StringToSign")
+ signed.context["timestamp"] = document.splitlines()[1]
+ signer = S3SigV4Auth(Credentials(error.findtext("AWSAccessKeyId"), "wrong"), "s3", region)
+ assert signer.signature(document, signed) == error.findtext("SignatureProvided")
+ else:
+ assert [child.tag for child in error] == expected
+ assert headers["content-type"] == "application/xml"
+ assert error.findtext("RequestId") == headers["x-amz-request-id"]
+ assert re.fullmatch(r"[A-Z0-9]{16}", error.findtext("RequestId"))
+ assert error.findtext("HostId") == headers["x-amz-id-2"]
+ assert len(base64.b64decode(error.findtext("HostId"), validate=True)) >= 48
+ assert "location" not in headers
+ if code == "PermanentRedirect":
+ assert error.findtext("Endpoint") == f"{bucket}.s3.{HOME}.{urlsplit(ENDPOINT).netloc}"
+ assert error.findtext("Bucket") == bucket
+ assert headers["x-amz-bucket-region"] == HOME
+ else:
+ assert "x-amz-bucket-region" not in headers
+ if code in {"InvalidBucketName", "NoSuchBucket"}:
+ assert error.findtext("BucketName") == bucket
+ if code == "NoSuchKey":
+ assert error.findtext("Key") == key
+ if code == "AuthorizationHeaderMalformed":
+ assert error.findtext("Region") == (HOME if region == TOKYO else TOKYO)
+ if access_key is not None:
+ assert error.findtext("AWSAccessKeyId") == access_key
+
+
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
+ # Fixed first-response observations; AUTH=false is a separate local contract.
+ (False, "valid", HOME, HOME, (200, None), (200, None)),
+ (False, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (200, None)),
+ (False, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (200, None)),
+ (True, "valid", HOME, HOME, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
+ (True, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
+ (False, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (False, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (False, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (True, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
+ # test_download_signing_region_precedes_home_and_credentials, including wire checks.
+ (False, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (200, None)),
+ (True, "valid", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "unknown", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (False, "valid", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (False, "unknown", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (False, "wrong-secret", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (True, "valid", TOKYO, TOKYO, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
+ (True, "unknown", TOKYO, TOKYO, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", TOKYO, TOKYO, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
+])
+def test_download_combined_errors(download_bucket, download_client, auth_enabled,
+ virtual, missing, credential, endpoint_region, region, expected, compat_expected):
+ bucket = f"missing-{download_bucket}" if missing else download_bucket
+ expected = expected if auth_enabled else compat_expected
+ response = _download(bucket, download_client, credential=credential, endpoint_region=endpoint_region,
+ region=region, virtual=virtual)
+ code = fromstring(response[2]).findtext("Code") if response[0] != 200 else None
+ assert (response[0], code) == expected
+ if response[0] == 200:
+ assert response[2] == _DOWNLOAD_PAYLOAD
+ elif auth_enabled:
+ access_key = ("AKIAUNKNOWNKEY000001" if credential == "unknown"
+ else download_client._request_signer._credentials.access_key)
+ _assert_download_error(response, code, bucket=bucket, region=region,
+ access_key=access_key if code in {"InvalidAccessKeyId", "SignatureDoesNotMatch"} else None)
+
+
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
+def test_download_signing_region_precedes_home_and_credentials(download_bucket, download_client, s3,
+ auth_enabled, virtual, credential):
+ # Fixed AWS observation: Osaka bucket + Tokyo endpoint + Osaka signature.
+ # Kept separately as the regression for GET's different priority from HEAD/DELETE.
+ response = _download(download_bucket, download_client, virtual=virtual, credential=credential,
+ endpoint_region=TOKYO, region=HOME)
+ assert response[0] == (400 if auth_enabled else 200)
+ if auth_enabled:
+ _assert_download_error(response, "AuthorizationHeaderMalformed", bucket=download_bucket, region=HOME)
+ else:
+ assert response[2] == _DOWNLOAD_PAYLOAD
+ with s3.get_object(Bucket=download_bucket, Key="probe.txt")["Body"] as body:
+ assert body.read() == _DOWNLOAD_PAYLOAD
+
+
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
+def test_download_missing_key(download_bucket, download_client, auth_enabled, virtual, credential, region):
+ response = _download(download_bucket, download_client, virtual=virtual, credential=credential,
+ region=region, key="missing.txt")
+ code = ("AuthorizationHeaderMalformed" if region != HOME else
+ "InvalidAccessKeyId" if credential == "unknown" else
+ "SignatureDoesNotMatch" if credential == "wrong-secret" else "NoSuchKey")
+ if not auth_enabled:
+ code = "AuthorizationHeaderMalformed" if region != HOME else "NoSuchKey"
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (
+ 400 if code == "AuthorizationHeaderMalformed" else 404 if code == "NoSuchKey" else 403, code,
+ )
+ if auth_enabled:
+ _assert_download_error(response, code, bucket=download_bucket, key="missing.txt", region=region)
+
+
+def test_download_invalid_name_precedes_credentials(download_client, auth_enabled):
+ response = _download("invalid bucket", download_client, credential="unknown")
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (
+ (400, "InvalidBucketName") if auth_enabled else (404, "NoSuchBucket")
+ )
+ if auth_enabled:
+ _assert_download_error(response, "InvalidBucketName", bucket="invalid bucket")
+
+
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
+def test_download_still_enforces_iam(download_bucket, iam_user, auth_enabled, virtual, denial):
+ policy = {"Statement": [{"Effect": "Deny", "Action": "s3:GetObject", "Resource": "*"}]}
+ client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
+ response = _download(download_bucket, client, virtual=virtual)
+ if auth_enabled:
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (403, "AccessDenied")
+ else:
+ assert (response[0], response[2]) == (200, _DOWNLOAD_PAYLOAD)
+
+
[email protected]("virtual", [False, True])
+def test_download_reserved_root_compatibility(download_bucket, s3, virtual):
+ response = _download(download_bucket, s3, virtual=virtual, root=True)
+ assert (response[0], response[2]) == (200, _DOWNLOAD_PAYLOAD)
+
+
[email protected]("virtual", [False, True])
[email protected]("query", ["?versionId=null", "?tagging"])
+def test_download_subresources_keep_their_iam_path(download_bucket, iam_user, auth_enabled, virtual, query):
+ client = iam_user().client("s3", region=HOME)
+ response = _download(f"missing-{download_bucket}", client, virtual=virtual, query=query)
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (
+ (403, "AccessDenied") if auth_enabled else (404, "NoSuchBucket")
+ )
+
+
[email protected]("virtual", [False, True])
+def test_download_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, virtual):
+ owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
+ aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
+ bucket = f"foreign-download-{uuid.uuid4().hex}"
+ owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
+ owner.put_object(Bucket=bucket, Key="probe.txt", Body=b"private")
+ client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}).client("s3")
+ try:
+ response = _download(bucket, client, virtual=virtual)
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (403, "AccessDenied")
+ finally:
+ owner.delete_object(Bucket=bucket, Key="probe.txt")
+ owner.delete_bucket(Bucket=bucket)
+ owner.close()
+
+
+# ---------------------------------------------------------------------------
+# HeadObject and HeadBucket error order, as observed on AWS (Osaka and Tokyo, 2026-10-23), replayed locally.
+# ---------------------------------------------------------------------------
+
+
+_HEAD_PAYLOAD = b"head error validation"
+
+
[email protected]("source", ["region", "authentication", "normal", "iam", "missing-request", "missing-host"])
+def test_head_finalizer_preserves_valid_identifiers(source):
+ """Pure formatting contract: no AUTH/IAM patch, no live AWS request."""
+ from ministack.core.iam_actions import access_denied_response
+ from ministack.services import s3
+
+ host_id = base64.b64encode(b"existing-host-id" * 4).decode()
+ if source in {"region", "authentication", "missing-host"}:
+ code, status = ("PermanentRedirect", 301) if source == "region" else ("InvalidAccessKeyId", 403)
+ response = s3._object_error(code, "formatting probe", status)
+ if source == "missing-host":
+ response[1].pop("x-amz-id-2")
+ elif source == "iam":
+ response = access_denied_response("s3", "s3:GetObject", "arn:aws:iam::000000000000:user/probe", "legacy-id")
+ else:
+ response = 200, {"Content-Type": "text/plain", "Content-Length": "4", "x-amz-id-2": host_id}, b""
+ if source == "normal":
+ response[1]["x-amz-request-id"] = "12345678-1234-1234-1234-123456789abc"
+ original_headers = dict(response[1])
+ result = s3.format_head_response("/id-format-probe/key", {}, response)
+ request_id = result[1]["x-amz-request-id"]
+ assert re.fullmatch(r"[A-Z0-9]{16}", request_id)
+ if re.fullmatch(r"[A-Z0-9]{16}", original_headers.get("x-amz-request-id", "")):
+ assert request_id == original_headers["x-amz-request-id"]
+ if original_headers.get("x-amz-id-2"):
+ assert result[1]["x-amz-id-2"] == original_headers["x-amz-id-2"]
+ assert len(base64.b64decode(result[1]["x-amz-id-2"], validate=True)) >= 48
+ assert result[2] == b""
+ assert s3.format_head_response("/id-format-probe/key", {}, result) == result
+ assert response[1] == original_headers
+
+
+def head_bucket(s3):
+ name = f"head-errors-{uuid.uuid4().hex}"
+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
+ s3.put_object(Bucket=name, Key="probe.txt", Body=_HEAD_PAYLOAD, ContentType="text/plain")
+ yield name
+ s3.delete_object(Bucket=name, Key="probe.txt")
+ s3.delete_bucket(Bucket=name)
+
+
+def head_client(head_bucket, iam_user):
+ return iam_user(policy={"Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{head_bucket}/*"},
+ {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": f"arn:aws:s3:::{head_bucket}"},
+ ]}).client("s3", region=HOME)
+
+
+def _head(bucket, client, *, key="probe.txt", virtual=False, credential="valid",
+ endpoint_region=HOME, region=HOME, root=False, query="", extra_headers=None, presigned=False):
+ frozen = client._request_signer._credentials.get_frozen_credentials()
+ access_key, secret = frozen.access_key, frozen.secret_key
+ if credential == "unknown":
+ access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
+ elif credential == "wrong-secret":
+ secret = "wrong"
+ if root:
+ access_key, secret = "test", "any-secret"
+ target = urlsplit(ENDPOINT)
+ host = f"s3.{endpoint_region}.{target.netloc}"
+ path = f"/{quote(bucket)}" + (f"/{quote(key, safe='/')}" if key else "")
+ if virtual:
+ host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
+ request = AWSRequest(method="HEAD", url=f"http://{host}{path}{query}", headers=extra_headers)
+ if presigned:
+ S3SigV4QueryAuth(Credentials(access_key, secret), "s3", region, expires=300).add_auth(request)
+ signed_url = urlsplit(request.url)
+ path, query = signed_url.path, "?" + signed_url.query
+ else:
+ S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
+ connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
+ try:
+ connection.request("HEAD", path + query, headers={**dict(request.headers), "Host": host})
+ response = connection.getresponse()
+ return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
+ finally:
+ connection.close()
+
+
+def _assert_wire(response, *, bucket, key, expected_region=None):
+ status, headers, body = response
+ assert body == b""
+ assert headers.get("x-amz-bucket-region") == expected_region
+ assert "x-amz-error-code" not in headers
+ assert "x-amz-error-message" not in headers
+ assert re.fullmatch(r"[A-Z0-9]{16}", headers["x-amz-request-id"])
+ assert len(base64.b64decode(headers["x-amz-id-2"], validate=True)) >= 48
+ if key and status == 200:
+ assert headers["content-length"] == str(len(_HEAD_PAYLOAD))
+ assert headers["content-type"] == "text/plain"
+ else:
+ assert "content-length" not in headers
+ assert headers["content-type"] == "application/xml"
+ assert headers.get("x-amz-bucket-arn") == (f"arn:aws:s3:::{bucket}" if not key and status == 200 else None)
+
+
[email protected]("key", ["probe.txt", ""], ids=["HeadObject", "HeadBucket"])
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
+ # Fixed first-response observations, separately for HeadObject and HeadBucket.
+ # Unlike GET, HEAD checks the bucket's home before the signing scope.
+ (False, "valid", HOME, HOME, 200, 200),
+ (False, "unknown", HOME, HOME, 403, 200),
+ (False, "wrong-secret", HOME, HOME, 403, 200),
+ (True, "valid", HOME, HOME, 404, 404),
+ (True, "unknown", HOME, HOME, 403, 404),
+ (True, "wrong-secret", HOME, HOME, 403, 404),
+ (False, "valid", HOME, TOKYO, 400, 400),
+ (False, "unknown", HOME, TOKYO, 400, 400),
+ (False, "wrong-secret", HOME, TOKYO, 400, 400),
+ (True, "valid", HOME, TOKYO, 400, 404),
+ (True, "unknown", HOME, TOKYO, 400, 404),
+ (True, "wrong-secret", HOME, TOKYO, 400, 404),
+ # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
+ # test_head_home_precedes_signing_region_and_credentials, including wire checks.
+ (False, "wrong-secret", TOKYO, HOME, 301, 200),
+ (True, "valid", TOKYO, HOME, 400, 404),
+ (True, "unknown", TOKYO, HOME, 400, 404),
+ (True, "wrong-secret", TOKYO, HOME, 400, 404),
+ (False, "valid", TOKYO, TOKYO, 301, 301),
+ (False, "unknown", TOKYO, TOKYO, 301, 301),
+ (False, "wrong-secret", TOKYO, TOKYO, 301, 301),
+ (True, "valid", TOKYO, TOKYO, 404, 404),
+ (True, "unknown", TOKYO, TOKYO, 403, 404),
+ (True, "wrong-secret", TOKYO, TOKYO, 403, 404),
+])
+def test_head_combined_errors(head_bucket, head_client, auth_enabled,
+ key, virtual, missing, credential, endpoint_region, region, expected, compat_expected):
+ bucket = f"missing-{head_bucket}" if missing else head_bucket
+ expected = expected if auth_enabled else compat_expected
+ response = _head(bucket, head_client, key=key, virtual=virtual, credential=credential,
+ endpoint_region=endpoint_region, region=region)
+ assert response[0] == expected
+ assert response[2] == b""
+ if auth_enabled:
+ _assert_wire(response, bucket=bucket, key=key,
+ expected_region=HOME if not missing and (not key or expected == 301) else None)
+
+
[email protected]("key", ["probe.txt", ""], ids=["HeadObject", "HeadBucket"])
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
+def test_head_home_precedes_signing_region_and_credentials(head_bucket, head_client, s3,
+ auth_enabled, key, virtual, credential):
+ # Fixed AWS regression: home-region redirect wins over signing/authentication errors.
+ response = _head(head_bucket, head_client, key=key, virtual=virtual, credential=credential,
+ endpoint_region=TOKYO, region=HOME)
+ assert response[0] == (301 if auth_enabled else 200)
+ assert response[2] == b""
+ if auth_enabled:
+ _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME)
+ with s3.get_object(Bucket=head_bucket, Key="probe.txt")["Body"] as body:
+ assert body.read() == _HEAD_PAYLOAD
+
+
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
+def test_head_missing_key(head_bucket, head_client, auth_enabled, virtual, credential, region):
+ response = _head(head_bucket, head_client, key="missing.txt", virtual=virtual, credential=credential, region=region)
+ expected = 400 if region != HOME else 403 if auth_enabled and credential != "valid" else 404
+ assert response[0] == expected
+ if auth_enabled:
+ _assert_wire(response, bucket=head_bucket, key="missing.txt")
+
+
[email protected]("key", ["probe.txt", ""])
+def test_head_invalid_name_precedes_credentials(head_client, auth_enabled, key):
+ response = _head("invalid bucket", head_client, key=key, credential="unknown")
+ assert response[0] == (400 if auth_enabled else 404)
+ if auth_enabled:
+ _assert_wire(response, bucket="invalid bucket", key=key)
+
+
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
+def test_head_still_enforces_iam(head_bucket, iam_user, auth_enabled, key, virtual, denial):
+ policy = {"Statement": [{"Effect": "Deny", "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": "*"}]}
+ client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
+ response = _head(head_bucket, client, key=key, virtual=virtual)
+ assert response[0] == (403 if auth_enabled else 200)
+ if auth_enabled:
+ _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME if not key else None)
+
+
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
+def test_head_reserved_root_compatibility(head_bucket, s3, auth_enabled, key, virtual):
+ response = _head(head_bucket, s3, key=key, virtual=virtual, root=True)
+ assert response[0] == 200
+ if auth_enabled:
+ _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME if not key else None)
+
+
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
+def test_head_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, key, virtual):
+ owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
+ aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
+ bucket = f"foreign-head-{uuid.uuid4().hex}"
+ owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
+ owner.put_object(Bucket=bucket, Key="probe.txt", Body=_HEAD_PAYLOAD)
+ client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}).client("s3")
+ try:
+ response = _head(bucket, client, key=key, virtual=virtual)
+ assert response[0] == 403
+ if auth_enabled:
+ _assert_wire(response, bucket=bucket, key=key, expected_region=HOME if not key else None)
+ finally:
+ owner.delete_object(Bucket=bucket, Key="probe.txt")
+ owner.delete_bucket(Bucket=bucket)
+ owner.close()
+
+
[email protected]("virtual", [False, True])
+def test_head_version_query_keeps_iam_path(head_bucket, iam_user, auth_enabled, virtual):
+ client = iam_user().client("s3", region=HOME)
+ response = _head(f"missing-{head_bucket}", client, virtual=virtual, query="?versionId=null")
+ assert response[0] == (403 if auth_enabled else 404)
+
+
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "wrong-secret"])
+def test_head_presigned_validation_is_preserved(head_bucket, head_client, s3, virtual, credential):
+ response = _head(head_bucket, head_client, virtual=virtual, credential=credential, presigned=True)
+ assert response[0] == (200 if credential == "valid" else 403)
+ assert response[2] == b""
+ if credential == "valid":
+ assert response[1]["content-length"] == str(len(_HEAD_PAYLOAD))
+ assert response[1]["content-type"] == "text/plain"
+ with s3.get_object(Bucket=head_bucket, Key="probe.txt")["Body"] as body:
+ assert body.read() == _HEAD_PAYLOAD
+
+
[email protected]("virtual", [False, True])
+def test_head_conditional_metadata(head_bucket, head_client, auth_enabled, virtual):
+ response = _head(head_bucket, head_client, virtual=virtual)
+ assert response[0] == 200
+ assert response[1]["content-length"] == str(len(_HEAD_PAYLOAD))
+ assert response[2] == b""
+ etag = response[1]["etag"]
+ response = _head(head_bucket, head_client, virtual=virtual, extra_headers={"If-None-Match": etag})
+ assert response[0] == 304
+ assert response[2] == b""
+ if auth_enabled:
+ assert "content-length" not in response[1]
+ assert "content-type" not in response[1]
+ response = _head(head_bucket, head_client, virtual=virtual, extra_headers={"If-Match": '"incorrect"'})
+ assert response[0] == 412
+ if auth_enabled:
+ _assert_wire(response, bucket=head_bucket, key="probe.txt")
+
+
+# ---------------------------------------------------------------------------
+# DeleteObject error order, as observed on AWS (Osaka and Tokyo, 2026-10-23), replayed locally.
+# ---------------------------------------------------------------------------
+
+
+_DELETE_PAYLOAD = b"delete error validation"
+
+
+def delete_bucket(s3):
+ name = f"delete-errors-{uuid.uuid4().hex}"
+ s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
+ s3.put_object(Bucket=name, Key="probe.txt", Body=_DELETE_PAYLOAD)
+ yield name
+ s3.delete_object(Bucket=name, Key="probe.txt")
+ s3.delete_bucket(Bucket=name)
+
+
+def delete_client(delete_bucket, iam_user):
+ return iam_user(policy={"Statement": [
+ {"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": f"arn:aws:s3:::{delete_bucket}/*"},
+ ]}).client("s3", region=HOME)
+
+
+def _send(host, path, headers):
+ target = urlsplit(ENDPOINT)
+ connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
+ try:
+ connection.request("DELETE", path, headers={**headers, "Host": host})
+ response = connection.getresponse()
+ return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
+ finally:
+ connection.close()
+
+
+def _delete(bucket, client, *, credential="valid", endpoint_region=HOME, region=HOME,
+ virtual=False, key="probe.txt", query="", root=False, extra_headers=None):
+ frozen = client._request_signer._credentials.get_frozen_credentials()
+ access_key, secret = frozen.access_key, frozen.secret_key
+ if credential == "unknown":
+ access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
+ elif credential == "wrong-secret":
+ secret = "wrong"
+ if root:
+ access_key, secret = "test", "any-secret"
+ host = f"s3.{endpoint_region}.{urlsplit(ENDPOINT).netloc}"
+ path = f"/{quote(bucket)}/{quote(key, safe='/')}"
+ if virtual:
+ host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
+ request = AWSRequest(method="DELETE", url=f"http://{host}{path}{query}", headers=extra_headers)
+ S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
+ return _send(host, path + query, dict(request.headers))
+
+
+def _assert_state(client, bucket, *, deleted):
+ if deleted:
+ with pytest.raises(ClientError) as exc:
+ client.get_object(Bucket=bucket, Key="probe.txt")
+ assert exc.value.response["Error"]["Code"] == "NoSuchKey"
+ else:
+ with client.get_object(Bucket=bucket, Key="probe.txt")["Body"] as body:
+ assert body.read() == _DELETE_PAYLOAD
+
+
+def _assert_delete_error(response, code, *, bucket, region=HOME, endpoint_region=HOME, access_key=None):
+ _, headers, body = response
+ error = fromstring(body)
+ messages = {
+ "InvalidBucketName": "The specified bucket is not valid.",
+ "InvalidAccessKeyId": "The AWS Access Key Id you provided does not exist in our records.",
+ "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. "
+ "Check your key and signing method.",
+ "AuthorizationHeaderMalformed": f"The authorization header is malformed; the region '{region}' is wrong; "
+ f"expecting '{endpoint_region}'",
+ "PermanentRedirect": "The bucket you are attempting to access must be addressed using the specified "
+ "endpoint. Please send all future requests to this endpoint.",
+ "NoSuchBucket": "The specified bucket does not exist",
+ }
+ details = {
+ "InvalidBucketName": ["BucketName"], "InvalidAccessKeyId": ["AWSAccessKeyId"],
+ "AuthorizationHeaderMalformed": ["Region"], "PermanentRedirect": ["Endpoint", "Bucket"],
+ "NoSuchBucket": ["BucketName"],
+ "SignatureDoesNotMatch": ["AWSAccessKeyId", "StringToSign", "SignatureProvided", "StringToSignBytes",
+ "CanonicalRequest", "CanonicalRequestBytes"],
+ }
+ expected = ["Code", "Message", *details[code], "RequestId", "HostId"]
+ assert error.findtext("Code") == code
+ assert error.findtext("Message") == messages[code]
+ if code == "SignatureDoesNotMatch":
+ # Diagnostic membership and consistency matter even if AWS varies field order.
+ assert sorted(child.tag for child in error) == sorted(expected)
+ for name in ("CanonicalRequest", "StringToSign"):
+ assert bytes.fromhex(error.findtext(name + "Bytes")).decode() == error.findtext(name)
+ assert error.findtext("CanonicalRequest").startswith("DELETE\n")
+ document = error.findtext("StringToSign")
+ assert document.splitlines()[-1] == hashlib.sha256(error.findtext("CanonicalRequest").encode()).hexdigest()
+ signed = AWSRequest()
+ signed.context["timestamp"] = document.splitlines()[1]
+ signer = S3SigV4Auth(Credentials(error.findtext("AWSAccessKeyId"), "wrong"), "s3", region)
+ assert signer.signature(document, signed) == error.findtext("SignatureProvided")
+ else:
+ assert [child.tag for child in error] == expected
+ assert headers["content-type"] == "application/xml"
+ assert error.findtext("RequestId") == headers["x-amz-request-id"]
+ assert re.fullmatch(r"[A-Z0-9]{16}", error.findtext("RequestId"))
+ assert error.findtext("HostId") == headers["x-amz-id-2"]
+ assert len(base64.b64decode(error.findtext("HostId"), validate=True)) >= 48
+ assert "location" not in headers
+ if code == "PermanentRedirect":
+ assert error.findtext("Endpoint") == f"{bucket}.s3.{HOME}.{urlsplit(ENDPOINT).netloc}"
+ assert error.findtext("Bucket") == bucket
+ assert headers["x-amz-bucket-region"] == HOME
+ else:
+ assert "x-amz-bucket-region" not in headers
+ if code in {"InvalidBucketName", "NoSuchBucket"}:
+ assert error.findtext("BucketName") == bucket
+ if code == "AuthorizationHeaderMalformed":
+ assert error.findtext("Region") == endpoint_region
+ if access_key is not None:
+ assert error.findtext("AWSAccessKeyId") == access_key
+
+
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
+ # Fixed first-response observations; DELETE success must also remove the object.
+ (False, "valid", HOME, HOME, (204, None), (204, None)),
+ (False, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (204, None)),
+ (False, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (204, None)),
+ (True, "valid", HOME, HOME, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
+ (True, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
+ (False, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (False, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (False, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
+ (True, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
+ # test_delete_home_precedes_signing_region_and_credentials, including state checks.
+ (False, "wrong-secret", TOKYO, HOME, (301, "PermanentRedirect"), (204, None)),
+ (True, "valid", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "unknown", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
+ (False, "valid", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (False, "unknown", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (False, "wrong-secret", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
+ (True, "valid", TOKYO, TOKYO, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
+ (True, "unknown", TOKYO, TOKYO, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
+ (True, "wrong-secret", TOKYO, TOKYO, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
+])
+def test_delete_combined_errors(delete_bucket, delete_client, s3, auth_enabled,
+ virtual, missing, credential, endpoint_region, region, expected, compat_expected):
+ bucket = f"missing-{delete_bucket}" if missing else delete_bucket
+ expected = expected if auth_enabled else compat_expected
+ response = _delete(bucket, delete_client, virtual=virtual, credential=credential,
+ endpoint_region=endpoint_region, region=region)
+ assert (response[0], fromstring(response[2]).findtext("Code") if response[2] else None) == expected
+ _assert_state(s3, delete_bucket, deleted=not missing and response[0] == 204)
+ if response[0] == 204:
+ assert response[2] == b""
+ elif auth_enabled:
+ access_key = "AKIAUNKNOWNKEY000001" if credential == "unknown" else delete_client._request_signer._credentials.access_key
+ _assert_delete_error(response, expected[1], bucket=bucket, region=region, endpoint_region=endpoint_region,
+ access_key=access_key if expected[1] in {"InvalidAccessKeyId", "SignatureDoesNotMatch"} else None)
+
+
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
+def test_delete_home_precedes_signing_region_and_credentials(delete_bucket, delete_client, s3,
+ auth_enabled, virtual, credential):
+ # Fixed AWS observation: redirect, including with an unknown access key.
+ response = _delete(delete_bucket, delete_client, virtual=virtual, credential=credential,
+ endpoint_region=TOKYO, region=HOME)
+ assert response[0] == (301 if auth_enabled else 204)
+ if auth_enabled:
+ _assert_delete_error(response, "PermanentRedirect", bucket=delete_bucket, endpoint_region=TOKYO)
+ else:
+ assert response[2] == b""
+ _assert_state(s3, delete_bucket, deleted=not auth_enabled)
+
+
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
+def test_delete_missing_key_is_idempotent(delete_bucket, delete_client, s3, auth_enabled, virtual, credential, region):
+ response = _delete(delete_bucket, delete_client, virtual=virtual, credential=credential, region=region, key="missing.txt")
+ code = ("AuthorizationHeaderMalformed" if region != HOME else
+ "InvalidAccessKeyId" if auth_enabled and credential == "unknown" else
+ "SignatureDoesNotMatch" if auth_enabled and credential == "wrong-secret" else None)
+ assert (response[0], fromstring(response[2]).findtext("Code") if response[2] else None) == (
+ 400 if region != HOME else 403 if code else 204, code)
+ if code and auth_enabled:
+ _assert_delete_error(response, code, bucket=delete_bucket, region=region)
+ if not code:
+ assert response[2] == b""
+ assert _delete(delete_bucket, delete_client, virtual=virtual, key="missing.txt")[0] == 204
+ _assert_state(s3, delete_bucket, deleted=False)
+
+
+def test_delete_invalid_name_precedes_credentials(delete_client, auth_enabled):
+ response = _delete("invalid bucket", delete_client, credential="unknown")
+ assert response[0] == (400 if auth_enabled else 404)
+ if auth_enabled:
+ _assert_delete_error(response, "InvalidBucketName", bucket="invalid bucket")
+
+
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
+def test_delete_still_enforces_iam(delete_bucket, iam_user, s3, auth_enabled, virtual, denial):
+ policy = {"Statement": [{"Effect": "Deny", "Action": "s3:DeleteObject", "Resource": "*"}]}
+ client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
+ response = _delete(delete_bucket, client, virtual=virtual)
+ assert response[0] == (403 if auth_enabled else 204)
+ _assert_state(s3, delete_bucket, deleted=not auth_enabled)
+ assert _delete(delete_bucket, client, virtual=virtual, key="missing.txt")[0] == (403 if auth_enabled else 204)
+
+
[email protected]("virtual", [False, True])
+def test_delete_reserved_root_compatibility(delete_bucket, s3, virtual):
+ assert _delete(delete_bucket, s3, virtual=virtual, root=True)[0] == 204
+ _assert_state(s3, delete_bucket, deleted=True)
+
+
[email protected]("virtual", [False, True])
+def test_delete_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, virtual):
+ owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
+ aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
+ bucket = f"foreign-delete-{uuid.uuid4().hex}"
+ owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
+ owner.put_object(Bucket=bucket, Key="probe.txt", Body=_DELETE_PAYLOAD)
+ client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "*"}]}).client("s3")
+ try:
+ assert _delete(bucket, client, virtual=virtual)[0] == 403
+ _assert_state(owner, bucket, deleted=False)
+ finally:
+ owner.delete_object(Bucket=bucket, Key="probe.txt")
+ owner.delete_bucket(Bucket=bucket)
+ owner.close()
+
+
[email protected]("virtual", [False, True])
[email protected]("query", ["?versionId=null", "?tagging"])
+def test_delete_subresources_keep_their_iam_path(delete_bucket, iam_user, auth_enabled, virtual, query):
+ client = iam_user().client("s3", region=HOME)
+ response = _delete(f"missing-{delete_bucket}", client, virtual=virtual, query=query)
+ assert response[0] == (403 if auth_enabled else 404)
+
+
[email protected]("virtual", [False, True])
+def test_delete_version_needs_its_own_permission(delete_bucket, delete_client, s3, auth_enabled, virtual):
+ response = _delete(delete_bucket, delete_client, virtual=virtual, query="?versionId=null")
+ assert response[0] == (403 if auth_enabled else 204)
+ _assert_state(s3, delete_bucket, deleted=not auth_enabled)
+
+
[email protected]("virtual", [False, True])
+def test_delete_failed_precondition_preserves_object(delete_bucket, delete_client, s3, virtual):
+ response = _delete(delete_bucket, delete_client, virtual=virtual, extra_headers={"If-Match": '"incorrect"'})
+ assert (response[0], fromstring(response[2]).findtext("Code")) == (412, "PreconditionFailed")
+ _assert_state(s3, delete_bucket, deleted=False)
+
+
[email protected]("virtual", [False, True])
[email protected]("invalid", [False, True], ids=["valid", "bad-signature"])
+def test_delete_presigned_validation_is_preserved(delete_bucket, iam_user, s3, virtual, invalid):
+ client = iam_user(policy={"Statement": [
+ {"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": f"arn:aws:s3:::{delete_bucket}/*"},
+ ]}).client("s3", region=HOME, config=Config(signature_version="s3v4", s3={"addressing_style": "virtual" if virtual else "path"}))
+ target = urlsplit(client.generate_presigned_url("delete_object", Params={"Bucket": delete_bucket, "Key": "probe.txt"}))
+ query = dict(parse_qsl(target.query))
+ if invalid:
+ signature = query["X-Amz-Signature"]
+ query["X-Amz-Signature"] = ("0" if signature[0] != "0" else "1") + signature[1:]
+ response = _send(target.netloc, target.path + "?" + urlencode(query), {})
+ assert response[0] == (403 if invalid else 204)
+ _assert_state(s3, delete_bucket, deleted=not invalid)
+
+
+def test_s3_missing_key_shapes_do_not_depend_on_auth(download_bucket, head_bucket, s3):
+ """The NoSuchKey body and the HEAD error shape are AWS's whether or not MiniStack checks auth."""
+ status, _headers, body = _download(download_bucket, s3, key="no-such-key")
+ error = fromstring(body)
+ assert (status, error.findtext("Code"), error.findtext("Key")) == (404, "NoSuchKey", "no-such-key")
+ assert error.find("Resource") is None
+ status, headers, body = _head(head_bucket, s3, key="no-such-key")
+ assert (status, body) == (404, b"")
+ assert "content-length" not in headers
+ status, headers, _body = _head(head_bucket, s3, key=None)
+ assert status == 200
+ assert (headers["x-amz-bucket-region"], headers["x-amz-bucket-arn"]) == (HOME, f"arn:aws:s3:::{head_bucket}")
+
+
+def test_s3_persisted_keys_a_path_cannot_hold_survive_a_restart(tmp_path, monkeypatch):
+ """Keys a file layout can't hold (a folder marker, a key under another key, doubled or dot
+ segments, a sidecar-like name) are saved, read back and reloaded as written."""
+ from ministack.services import s3 as s3mod
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")
+ keys = ["dir/", "dir/child.txt", "dir/deeper/x.txt", "a", "a/b", "x//y", "p/./q", "../up", "n.meta.json",
+ "c/d/e", "c/d", "k" * 300]
+ for key in keys:
+ s3mod._persist_object("keys-bucket", key, {"body": key.encode(), "etag": '"e"', "size": len(key.encode()),
+ "last_modified": s3mod.now_iso()})
+ for key in keys:
+ assert s3mod._read_body("keys-bucket", key, {"body": None}) == key.encode(), key
+ # Athena and Glue read ordinary keys at their own path.
+ assert open(tmp_path / "000000000000" / "keys-bucket" / "dir" / "child.txt", "rb").read() == b"dir/child.txt"
+
+ s3mod._buckets._data.pop(("000000000000", "keys-bucket"), None)
+ s3mod._load_persisted_bucket("000000000000", "keys-bucket", str(tmp_path / "000000000000" / "keys-bucket"))
+ restored = s3mod._buckets._data[("000000000000", "keys-bucket")]["objects"]
+ assert sorted(restored) == sorted(keys)
+ assert all(restored[key]["size"] == len(key.encode()) for key in keys)
+
+ # Once the key above it is gone, a rewrite moves the key back to its own path.
+ s3mod._delete_persisted_object("keys-bucket", "a/b")
+ s3mod._delete_persisted_object("keys-bucket", "a")
+ s3mod._persist_object("keys-bucket", "a/b", {"body": b"moved", "etag": '"e"', "size": 5,
+ "last_modified": s3mod.now_iso()})
+ assert open(tmp_path / "000000000000" / "keys-bucket" / "a" / "b", "rb").read() == b"moved"
+ s3mod._buckets._data.pop(("000000000000", "keys-bucket"), None)
diff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.py
deleted file mode 100644
index 3d8b91e7..00000000
--- a/tests/test_s3_access_points.py
+++ /dev/null
@@ -1,663 +0,0 @@
-"""S3 Access Points (#2159): the S3 Control API and the data plane through an
-access point ARN or alias."""
-import json
-import os
-import re
-import urllib.error
-import urllib.request
-import uuid
-
-import boto3
-import pytest
-from botocore import UNSIGNED
-from botocore.config import Config
-from botocore.exceptions import ClientError
-from conftest import make_client, patch_endpoint_dns
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
-ACCOUNT = "000000000000"
-
-
-def _client(service, region, account_key="test"):
- return boto3.client(
- service, endpoint_url=ENDPOINT, region_name=region,
- aws_access_key_id=account_key, aws_secret_access_key="test",
- config=Config(region_name=region, retries={"mode": "standard"}),
- )
-
-
[email protected](autouse=True)
-def _s3control_dns():
- """boto3 prefixes S3 Control and access point hosts with the account id."""
- with patch_endpoint_dns():
- yield
-
-
-def _uid():
- return uuid.uuid4().hex[:8]
-
-
-def bucket():
- """A bucket in us-east-1 holding k.txt."""
- s3 = _client("s3", "us-east-1")
- name = f"ap-data-{_uid()}"
- s3.create_bucket(Bucket=name)
- s3.put_object(Bucket=name, Key="k.txt", Body=b"hello")
- yield name
- for obj in s3.list_objects_v2(Bucket=name).get("Contents", []):
- s3.delete_object(Bucket=name, Key=obj["Key"])
- try:
- s3.delete_bucket(Bucket=name)
- except ClientError:
- pass
-
-
-def access_point(bucket):
- ctl = _client("s3control", "us-east-1")
- name = f"ap-{_uid()}"
- created = ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
- yield name, created
- try:
- ctl.delete_access_point(AccountId=ACCOUNT, Name=name)
- except ClientError:
- pass
-
-
-# --- Control plane ---------------------------------------------------------
-
-def test_access_point_control_create_get_list_delete(bucket):
- ctl = _client("s3control", "us-east-1")
- name = f"ap-{_uid()}"
- created = ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
- arn = f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}"
- assert created["AccessPointArn"] == arn
- assert re.fullmatch(rf"{name[:20]}-[a-z0-9]{{29}}use1b-s3alias", created["Alias"])
-
- ap = ctl.get_access_point(AccountId=ACCOUNT, Name=name)
- assert (ap["Name"], ap["Bucket"], ap["BucketAccountId"], ap["NetworkOrigin"]) == (
- name, bucket, ACCOUNT, "Internet")
- assert ap["AccessPointArn"] == arn and ap["Alias"] == created["Alias"]
- assert ap["PublicAccessBlockConfiguration"] == {
- "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True}
- assert ap["Endpoints"]["ipv4"] == "s3-accesspoint.us-east-1.amazonaws.com"
- assert set(ap["Endpoints"]) == {"ipv4", "fips", "dualstack", "fips_dualstack"}
- assert "CreationDate" in ap
-
- second = f"ap-{_uid()}"
- ctl.create_access_point(AccountId=ACCOUNT, Name=second, Bucket=bucket,
- VpcConfiguration={"VpcId": "vpc-0123456789abcdef0"})
- try:
- listed = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket)["AccessPointList"]
- assert sorted(a["Name"] for a in listed) == sorted([name, second])
- assert {a["Name"]: a["NetworkOrigin"] for a in listed}[second] == "VPC"
- page = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket, MaxResults=1)
- assert len(page["AccessPointList"]) == 1 and page["NextToken"]
- rest = ctl.list_access_points(AccountId=ACCOUNT, Bucket=bucket, NextToken=page["NextToken"])
- assert len(rest["AccessPointList"]) == 1
- finally:
- ctl.delete_access_point(AccountId=ACCOUNT, Name=second)
-
- with pytest.raises(ClientError) as exc:
- ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
- assert exc.value.response["Error"]["Code"] == "AccessPointAlreadyOwnedByYou"
- assert exc.value.response["Error"]["Message"] == (
- "Your previous request to create the named accesspoint succeeded and you already own it.")
-
- with pytest.raises(ClientError) as exc:
- _client("s3", "us-east-1").delete_bucket(Bucket=bucket)
- assert exc.value.response["Error"]["Code"] == "BucketHasAccessPointsAttached"
-
- ctl.delete_access_point(AccountId=ACCOUNT, Name=name)
- with pytest.raises(ClientError) as exc:
- ctl.get_access_point(AccountId=ACCOUNT, Name=name)
- err = exc.value.response["Error"]
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
- assert (err["Code"], err["Message"], err["AccessPointName"]) == (
- "NoSuchAccessPoint", "The specified accesspoint does not exist", name)
-
-
-def test_access_point_control_bucket_must_be_in_request_region(bucket):
- with pytest.raises(ClientError) as exc:
- _client("s3control", "eu-west-1").create_access_point(AccountId=ACCOUNT, Name=f"ap-{_uid()}", Bucket=bucket)
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
- assert exc.value.response["Error"]["Code"] == "InvalidRequest"
- assert exc.value.response["Error"]["Message"] == (
- "Amazon S3 AccessPoint can only be created for bucket in the same region")
-
-
-def test_access_point_control_same_name_in_another_region(bucket):
- """Access point names are unique per account and region (observed)."""
- euw1_s3 = _client("s3", "eu-west-1")
- euw1_bucket = f"ap-euw1-{_uid()}"
- euw1_s3.create_bucket(Bucket=euw1_bucket, CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
- name = f"ap-{_uid()}"
- use1, euw1 = _client("s3control", "us-east-1"), _client("s3control", "eu-west-1")
- use1.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)
- try:
- alias = euw1.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=euw1_bucket)["Alias"]
- assert alias.endswith("euw1b-s3alias")
- assert euw1.get_access_point(AccountId=ACCOUNT, Name=name)["Bucket"] == euw1_bucket
- assert use1.get_access_point(AccountId=ACCOUNT, Name=name)["Bucket"] == bucket
- euw1.delete_access_point(AccountId=ACCOUNT, Name=name)
- finally:
- use1.delete_access_point(AccountId=ACCOUNT, Name=name)
- euw1_s3.delete_bucket(Bucket=euw1_bucket)
-
-
-def test_access_point_control_policy_round_trip(access_point):
- name, _ = access_point
- ctl = _client("s3control", "us-east-1")
- policy = json.dumps({"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
- "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]})
- ctl.put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=policy)
- assert ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)["Policy"] == policy
- ctl.delete_access_point_policy(AccountId=ACCOUNT, Name=name)
- with pytest.raises(ClientError) as exc:
- ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
-
-
[email protected]("method,path,status,fields", [
- ("POST", "/{ap}/policy", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTPOLICY"}),
- ("PATCH", "/{ap}/policy", 405, {"Method": "PATCH", "ResourceType": "ACCESSPOINTPOLICY"}),
- ("POST", "/{ap}", 405, {"Method": "POST", "ResourceType": "ACCESSPOINT"}),
- ("POST", "", 405, {"Method": "POST", "ResourceType": "ACCESSPOINTS"}),
- ("GET", "/{ap}/x", 400, {"URI": "accesspoint/{ap}/x"}),
- ("DELETE", "/{ap}/x", 400, {}),
- ("DELETE", "/{ap}/policy/x", 400, {}),
- ("GET", "/{ap}/", 400, {}),
- ("GET", "//{ap}", 400, {}),
- ("PUT", "//{ap}/policy", 400, {}),
- ("GET", "/", 400, {}), ("GET", "/{ap}/policyStatus", 404, {"AccessPointName": "{ap}/policyStatus"}),
- ("GET", "/{ap}/scope", 404, {}),
-])
-def test_access_point_control_unserved_requests(access_point, method, path, status, fields):
- """Unserved methods answer 405, unparsed paths 400, unemulated routes 404; none changes the access point."""
- name, _ = access_point
- ctl = _client("s3control", "us-east-1")
- policy = json.dumps({"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
- "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]})
- ctl.put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=policy)
- body = b"<PutAccessPointPolicyRequest><Policy>{}</Policy></PutAccessPointPolicyRequest>"
- got, _, data = _raw(method, ENDPOINT.split("://", 1)[1], "/v20180820/accesspoint" + path.format(ap=name),
- "us-east-1", body if method == "PUT" else b"", headers={"x-amz-account-id": ACCOUNT})
- code = {405: "MethodNotAllowed", 400: "InvalidURI", 404: "NoSuchAccessPoint"}[status]
- assert (got, re.search(rb"<Code>(\w+)</Code>", data).group(1).decode()) == (status, code)
- for tag, value in fields.items():
- assert f"<{tag}>{value.format(ap=name)}</{tag}>".encode() in data
- assert ctl.get_access_point_policy(AccountId=ACCOUNT, Name=name)["Policy"] == policy
-
-
-def test_access_point_named_policy_needs_the_access_point_action(auth_enabled, iam_user, bucket):
- """/v20180820/accesspoint/policy names an access point called "policy"."""
- ctl = _client("s3control", "us-east-1")
- ctl.create_access_point(AccountId=ACCOUNT, Name="policy", Bucket=bucket)
- try:
- user = iam_user(policy={"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Action": ["s3:GetAccessPointPolicy", "s3:DeleteAccessPointPolicy"],
- "Resource": "*"}]}).client("s3control", region="us-east-1")
- user.delete_access_point_policy(AccountId=ACCOUNT, Name="policy")
- if auth_enabled:
- for call in (user.get_access_point, user.delete_access_point):
- with pytest.raises(ClientError) as exc:
- call(AccountId=ACCOUNT, Name="policy")
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
- assert exc.value.response["Error"]["Code"] == "AccessDenied"
- assert ctl.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket
- else:
- assert user.get_access_point(AccountId=ACCOUNT, Name="policy")["Bucket"] == bucket
- user.delete_access_point(AccountId=ACCOUNT, Name="policy")
- finally:
- try:
- ctl.delete_access_point(AccountId=ACCOUNT, Name="policy")
- except ClientError:
- pass
-
-
-def test_access_point_policy_unserved_method_is_refused_before_authorization(auth_enabled, iam_user, access_point):
- """POST on an access point policy answers 405 to any caller and returns no policy."""
- name, _ = access_point
- _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({
- "Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
- "Resource": f"arn:aws:s3:us-east-1:{ACCOUNT}:accesspoint/{name}/object/*"}]}))
- user = iam_user()
- iam = make_client("iam")
- key = iam.create_access_key(UserName=user.name)["AccessKey"]
- try:
- signed = {"key": (key["AccessKeyId"], key["SecretAccessKey"]), "headers": {"x-amz-account-id": ACCOUNT}}
- host, path = ENDPOINT.split("://", 1)[1], f"/v20180820/accesspoint/{name}/policy"
- status, _, data = _raw("POST", host, path, "us-east-1", **signed)
- assert status == 405 and b"<ResourceType>ACCESSPOINTPOLICY</ResourceType>" in data
- assert b"<Policy>" not in data
- assert _raw("GET", host, path, "us-east-1", **signed)[0] == (403 if auth_enabled else 200)
- finally:
- iam.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
-
-
-# --- Data plane --------------------------------------------------------------
-
-def _raw(method, host, path, region, body=b"", key=("test", "test"), headers=None):
- """A SigV4-signed request with an explicit Host, no redirect handling."""
- import hashlib
- import http.client
- from urllib.parse import urlparse
-
- from botocore.auth import S3SigV4Auth
- from botocore.awsrequest import AWSRequest
- from botocore.credentials import Credentials
-
- req = AWSRequest(method=method, url=f"http://{host}{path}", data=body, headers=headers)
- req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()
- S3SigV4Auth(Credentials(*key), "s3", region).add_auth(req)
- parsed = urlparse(ENDPOINT)
- conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=30)
- conn.request(method, path, body=body or None, headers={**dict(req.headers.items()), "Host": host})
- resp = conn.getresponse()
- data = resp.read()
- conn.close()
- return resp.status, {k.lower(): v for k, v in resp.getheaders()}, data
-
-
-def test_access_point_arn_reaches_the_bucket(bucket, access_point):
- name, created = access_point
- s3 = _client("s3", "us-east-1")
- arn = created["AccessPointArn"]
- assert s3.get_object(Bucket=arn, Key="k.txt")["Body"].read() == b"hello"
- s3.put_object(Bucket=arn, Key="through-ap.txt", Body=b"via ap")
- assert s3.get_object(Bucket=bucket, Key="through-ap.txt")["Body"].read() == b"via ap"
- keys = [o["Key"] for o in s3.list_objects_v2(Bucket=arn)["Contents"]]
- assert keys == ["k.txt", "through-ap.txt"]
- # A client configured for another region still signs for the ARN's region.
- assert _client("s3", "eu-west-1").get_object(Bucket=arn, Key="k.txt")["Body"].read() == b"hello"
-
-
-def test_access_point_arn_wrong_region_signing_gets_the_redirect(access_point):
- name, _ = access_point
- host = f"{name}-{ACCOUNT}.{ENDPOINT.split('://', 1)[1]}"
- status, headers, _ = _raw("GET", host, "/k.txt", "eu-west-1")
- assert status == 301
- assert headers["x-amz-bucket-region"] == "us-east-1"
- assert _raw("GET", host, "/k.txt", "us-east-1")[0] == 200
-
-
-def test_access_point_arn_other_account_is_denied(access_point):
- _, created = access_point
- other = _client("s3", "us-east-1", account_key="111122223333")
- with pytest.raises(ClientError) as exc:
- other.get_object(Bucket=created["AccessPointArn"], Key="k.txt")
- assert exc.value.response["Error"]["Code"] in ("AccessDenied", "NoSuchAccessPoint")
-
-
[email protected]("method", ["GET", "HEAD"])
-def test_access_point_arn_shaped_bucket_without_access_point_is_a_bucket(auth_enabled, method):
- """`<name>-<12 digits>` is a valid bucket name; with no access point of
- that name it is served as the bucket."""
- s3 = _client("s3", "us-east-1")
- name = f"plain-{_uid()}-123456789012"
- s3.create_bucket(Bucket=name)
- try:
- s3.put_object(Bucket=name, Key="b.txt", Body=b"bucket")
- host = f"{name}.{ENDPOINT.split('://', 1)[1]}"
- status, headers, body = _raw(method, host, "/b.txt", "us-east-1")
- assert status == 200
- assert body == (b"bucket" if method == "GET" else b"")
- if auth_enabled and method == "HEAD":
- assert re.fullmatch(r"[A-Z0-9]{16}", headers["x-amz-request-id"])
- finally:
- s3.delete_object(Bucket=name, Key="b.txt")
- s3.delete_bucket(Bucket=name)
-
-
-def test_access_point_alias_works_as_a_bucket_name(bucket, access_point):
- _, created = access_point
- s3 = _client("s3", "us-east-1")
- alias = created["Alias"]
- assert s3.get_object(Bucket=alias, Key="k.txt")["Body"].read() == b"hello"
- s3.put_object(Bucket=alias, Key="alias.txt", Body=b"via alias")
- assert s3.get_object(Bucket=bucket, Key="alias.txt")["Body"].read() == b"via alias"
- s3.copy_object(Bucket=bucket, Key="copied.txt", CopySource={"Bucket": alias, "Key": "k.txt"})
- assert s3.get_object(Bucket=bucket, Key="copied.txt")["Body"].read() == b"hello"
-
-
[email protected]("addressing_style", ["path", "virtual"])
[email protected]("allow_upload", [False, True], ids=["no-permission", "allow"])
-def test_access_point_alias_upload_permission_contract(
- bucket, access_point, auth_enabled, iam_user, addressing_style, allow_upload,
-):
- _, created = access_point
- policy = {"Statement": [{"Effect": "Allow", "Action": "s3:PutObject", "Resource": "*"}]}
- client = iam_user(policy=policy if allow_upload else None).client(
- "s3", config=Config(s3={"addressing_style": addressing_style}),
- )
- root = _client("s3", "us-east-1")
- if auth_enabled and not allow_upload:
- with pytest.raises(ClientError) as exc:
- client.put_object(Bucket=created["Alias"], Key="contract-upload", Body=b"via alias")
- assert exc.value.response["Error"]["Code"] == "AccessDenied"
- assert root.list_objects_v2(Bucket=bucket, Prefix="contract-upload")["KeyCount"] == 0
- else:
- assert client.put_object(
- Bucket=created["Alias"], Key="contract-upload", Body=b"via alias",
- )["ResponseMetadata"]["HTTPStatusCode"] == 200
- with root.get_object(Bucket=bucket, Key="contract-upload")["Body"] as body:
- assert body.read() == b"via alias"
-
-
[email protected]("target,addressing_style", [("Alias", "path"), ("Alias", "virtual"), ("AccessPointArn", "virtual")])
[email protected]("allow_head", [False, True], ids=["no-permission", "allow"])
-def test_access_point_head_permission_contract(access_point, auth_enabled, iam_user, target, addressing_style, allow_head):
- _, created = access_point
- policy = {"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}
- client = iam_user(policy=policy if allow_head else None).client(
- "s3", region="us-east-1", config=Config(s3={"addressing_style": addressing_style}))
- if auth_enabled and not allow_head:
- with pytest.raises(ClientError) as exc:
- client.head_object(Bucket=created[target], Key="k.txt")
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
- else:
- response = client.head_object(Bucket=created[target], Key="k.txt")
- assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
- assert response["ContentLength"] == 5
-
-
[email protected]("target", ["Alias", "AccessPointArn"])
[email protected]("allow_delete", [False, True], ids=["no-permission", "allow"])
-def test_access_point_delete_permission_contract(bucket, access_point, auth_enabled, iam_user, target, allow_delete):
- _, created = access_point
- policy = {"Statement": [{"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "*"}]}
- client = iam_user(policy=policy if allow_delete else None).client("s3", region="us-east-1")
- root = _client("s3", "us-east-1")
- if auth_enabled and not allow_delete:
- with pytest.raises(ClientError) as exc:
- client.delete_object(Bucket=created[target], Key="k.txt")
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403
- with root.get_object(Bucket=bucket, Key="k.txt")["Body"] as body:
- assert body.read() == b"hello"
- else:
- assert client.delete_object(Bucket=created[target], Key="k.txt")["ResponseMetadata"]["HTTPStatusCode"] == 204
- with pytest.raises(ClientError) as exc:
- root.head_object(Bucket=bucket, Key="k.txt")
- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
-
-
-def _status(call):
- try:
- return call()["ResponseMetadata"]["HTTPStatusCode"]
- except ClientError as exc:
- return exc.response["ResponseMetadata"]["HTTPStatusCode"], exc.response["Error"]["Code"]
-
-
-def test_access_point_block_public_acls_refuses_public_acl_writes():
- """An access point's BlockPublicAcls refuses public ACLs sent through it, whatever the bucket's settings."""
- s3, ctl = _client("s3", "us-east-1"), _client("s3control", "us-east-1")
- name = f"ap-acl-{_uid()}"
- all_off = {k: False for k in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")}
- s3.create_bucket(Bucket=name, ObjectOwnership="BucketOwnerPreferred")
- s3.put_public_access_block(Bucket=name, PublicAccessBlockConfiguration=all_off)
- s3.put_object(Bucket=name, Key="k.txt", Body=b"hello")
- blocking = ctl.create_access_point(AccountId=ACCOUNT, Name=f"ap-on-{_uid()}", Bucket=name)
- open_ap = ctl.create_access_point(
- AccountId=ACCOUNT, Name=f"ap-off-{_uid()}", Bucket=name, PublicAccessBlockConfiguration=all_off)
- try:
- denied = (403, "AccessDenied")
- for target in (blocking["Alias"], blocking["AccessPointArn"]):
- assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == denied
- assert _status(lambda: s3.put_object_acl(Bucket=target, Key="k.txt", ACL="public-read")) == denied
- assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="private")) == 200
- for target in (open_ap["Alias"], open_ap["AccessPointArn"], name):
- assert _status(lambda: s3.put_object(Bucket=target, Key="w", Body=b"x", ACL="public-read")) == 200
- finally:
- for ap in (blocking, open_ap):
- ctl.delete_access_point(AccountId=ACCOUNT, Name=ap["AccessPointArn"].rsplit("/", 1)[1])
- for obj in s3.list_objects_v2(Bucket=name).get("Contents", []):
- s3.delete_object(Bucket=name, Key=obj["Key"])
- s3.delete_bucket(Bucket=name)
-
-
-def test_access_point_alias_from_another_account_is_denied(access_point):
- _name, created = access_point
- other = _client("s3", "us-east-1", account_key="111122223333")
- with pytest.raises(ClientError) as exc:
- other.get_object(Bucket=created["Alias"], Key="k.txt")
- assert exc.value.response["Error"]["Code"] == "AccessDenied"
-
-
-def _access_point_policy(bucket, access_point_arn, grant, deny=None, condition=None):
- """An identity policy allowing reads and copies on ``grant`` ("bucket", "access point" or "both")."""
- arns = {"bucket": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],
- "access point": [access_point_arn, f"{access_point_arn}/object/*"]}
- resources = arns["bucket"] + arns["access point"] if grant == "both" else arns[grant]
- statements = [{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
- "Resource": resources}]
- if deny or condition:
- statements.append({"Effect": "Deny", "Action": ["s3:GetObject", "s3:ListBucket"],
- "Resource": arns[deny] if deny else "*", **({"Condition": condition} if condition else {})})
- return {"Version": "2012-10-17", "Statement": statements}
-
-
-def _assert_access(auth_enabled, allowed, call):
- """Under AUTH a refused call answers 403 AccessDenied; anything else succeeds."""
- if auth_enabled and not allowed:
- with pytest.raises(ClientError) as exc:
- call()
- error = exc.value.response
- assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("AccessDenied", 403)
- else:
- call()
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("grant, deny, allowed", [
- ("both", None, True),
- ("bucket", None, False),
- ("access point", None, False),
- ("both", "access point", False),
- ("both", "bucket", False),
-], ids=["both", "bucket-only", "access-point-only", "deny-access-point", "deny-bucket"])
-def test_access_point_request_needs_access_point_and_bucket_contract(auth_enabled, iam_user, bucket, access_point,
- via, grant, deny, allowed):
- """Through an access point a read and a listing are checked on the access point and on its bucket."""
- _name, created = access_point
- client = iam_user(policy=_access_point_policy(bucket, created["AccessPointArn"], grant, deny)).client("s3")
- target = created[via]
- _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=target, Key="k.txt"))
- _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=target))
- _assert_access(auth_enabled, grant != "access point" and deny != "bucket",
- lambda: client.get_object(Bucket=bucket, Key="k.txt"))
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("key, condition_value, through_access_point, through_bucket", [
- ("s3:DataAccessPointArn", "arn", False, True),
- ("s3:DataAccessPointAccount", ACCOUNT, False, True),
- ("s3:AccessPointNetworkOrigin", "Internet", False, True),
- ("s3:ExistingObjectTag/class", "secret", False, False),
- ("s3:DataAccessPointArn", None, True, False),
-], ids=["arn", "account", "network-origin", "object-tag", "arn-absent"])
-def test_access_point_condition_keys_contract(auth_enabled, iam_user, bucket, access_point, via, key,
- condition_value, through_access_point, through_bucket):
- """A request through an access point carries its ARN, account and network origin, and the object's tags."""
- _name, created = access_point
- _client("s3", "us-east-1").put_object_tagging(Bucket=bucket, Key="k.txt",
- Tagging={"TagSet": [{"Key": "class", "Value": "secret"}]})
- arn = created["AccessPointArn"]
- condition = ({"Null": {key: "true"}} if condition_value is None
- else {"StringEquals": {key: arn if condition_value == "arn" else condition_value}})
- client = iam_user(policy=_access_point_policy(bucket, arn, "both", condition=condition)).client("s3")
- _assert_access(auth_enabled, through_access_point, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
- _assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("condition, through_bucket", [(False, False), (True, True)], ids=["deny", "deny-on-arn-key"])
-def test_access_point_request_meets_the_bucket_policy_contract(auth_enabled, iam_user, bucket, access_point, via,
- condition, through_bucket):
- """The bucket policy applies through an access point and sees its ARN."""
- _name, created = access_point
- arn = created["AccessPointArn"]
- user = iam_user(policy=_access_point_policy(bucket, arn, "both"))
- statement = {"Effect": "Deny", "Principal": {"AWS": user.arn}, "Action": "s3:GetObject",
- "Resource": f"arn:aws:s3:::{bucket}/*"}
- if condition:
- statement["Condition"] = {"StringEquals": {"s3:DataAccessPointArn": arn}}
- _client("s3", "us-east-1").put_bucket_policy(
- Bucket=bucket, Policy=json.dumps({"Version": "2012-10-17", "Statement": [statement]}))
- client = user.client("s3")
- _assert_access(auth_enabled, False, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
- _assert_access(auth_enabled, through_bucket, lambda: client.get_object(Bucket=bucket, Key="k.txt"))
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
[email protected]("grant, effect, delegate, allowed", [
- ("bucket", "Allow", False, True),
- (None, "Allow", True, True),
- ("access point", None, True, True),
- ("access point", "Allow", False, False),
- ("both", "Deny", True, False),
-], ids=["allow-identity-on-bucket", "allow-delegated", "delegated-identity-on-access-point",
- "allow-not-delegated", "deny"])
-def test_access_point_policy_contract(auth_enabled, iam_user, bucket, access_point, via, grant, effect, delegate,
- allowed):
- """The access point policy answers for the access point, the bucket policy or identity for the bucket."""
- name, created = access_point
- arn = created["AccessPointArn"]
- user = iam_user(policy=_access_point_policy(bucket, arn, grant) if grant else None)
- if delegate:
- _client("s3", "us-east-1").put_bucket_policy(Bucket=bucket, Policy=json.dumps({
- "Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "*",
- "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"],
- "Condition": {"StringEquals": {"s3:DataAccessPointAccount": ACCOUNT}}}]}))
- if effect:
- _client("s3control", "us-east-1").put_access_point_policy(AccountId=ACCOUNT, Name=name, Policy=json.dumps({
- "Version": "2012-10-17", "Statement": [{
- "Effect": effect, "Principal": {"AWS": user.arn}, "Action": ["s3:GetObject", "s3:ListBucket"],
- "Resource": [arn, f"{arn}/object/*"]}]}))
- client = user.client("s3")
- _assert_access(auth_enabled, allowed, lambda: client.get_object(Bucket=created[via], Key="k.txt"))
- _assert_access(auth_enabled, allowed, lambda: client.list_objects_v2(Bucket=created[via]))
- _assert_access(auth_enabled, grant in ("bucket", "both"), lambda: client.get_object(Bucket=bucket, Key="k.txt"))
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
-def test_access_point_refuses_bucket_policy_writes_contract(auth_enabled, iam_user, bucket, access_point, via):
- """Under AUTH an access point refuses PutBucketPolicy and DeleteBucketPolicy and serves GetBucketPolicy."""
- _name, created = access_point
- arn = created["AccessPointArn"]
- client = iam_user(policy={"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Action": ["s3:PutBucketPolicy", "s3:GetBucketPolicy", "s3:DeleteBucketPolicy"],
- "Resource": [f"arn:aws:s3:::{bucket}", arn]}]}).client("s3", region="us-east-1")
- policy = json.dumps({"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, "Action": "s3:GetObject",
- "Resource": f"arn:aws:s3:::{bucket}/*"}]})
- client.put_bucket_policy(Bucket=bucket, Policy=policy)
- assert client.get_bucket_policy(Bucket=created[via])["Policy"] == policy
- for write in (lambda: client.delete_bucket_policy(Bucket=created[via]),
- lambda: client.put_bucket_policy(Bucket=created[via], Policy=policy)):
- if auth_enabled:
- with pytest.raises(ClientError) as exc:
- write()
- error = exc.value.response["Error"]
- assert error["Code"] == "AccessDenied"
- assert error["Message"].endswith(f'on resource: "{arn}" with an explicit deny in a resource-based policy')
- assert client.get_bucket_policy(Bucket=bucket)["Policy"] == policy
- else:
- write()
- client.delete_bucket_policy(Bucket=bucket)
-
-
-def test_access_point_refuses_unsigned_requests_contract(auth_enabled, bucket, access_point):
- """Under AUTH an unsigned request through an access point is refused; the bucket still serves it."""
- _name, created = access_point
- s3 = _client("s3", "us-east-1")
- s3.put_bucket_ownership_controls(Bucket=bucket, OwnershipControls={
- "Rules": [{"ObjectOwnership": "BucketOwnerPreferred"}]})
- s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration={k: False for k in (
- "BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")})
- s3.put_object(Bucket=bucket, Key="pub.txt", Body=b"public", ACL="public-read")
- anon = boto3.client("s3", endpoint_url=ENDPOINT, region_name="us-east-1",
- config=Config(signature_version=UNSIGNED, retries={"mode": "standard"}))
- assert anon.get_object(Bucket=bucket, Key="pub.txt")["Body"].read() == b"public"
- for target in (created["Alias"], created["AccessPointArn"]):
- if auth_enabled:
- with pytest.raises(ClientError) as exc:
- anon.get_object(Bucket=target, Key="pub.txt")
- error = exc.value.response
- assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidRequest", 400)
- else:
- assert anon.get_object(Bucket=target, Key="pub.txt")["Body"].read() == b"public"
-
-
[email protected]("via", ["AccessPointArn", "Alias"])
-def test_access_point_sigv2_requests_contract(auth_enabled, iam_user, bucket, access_point, via):
- """Through an access point a SigV2 presigned URL is served, a SigV2 Authorization header is refused under AUTH."""
- _name, created = access_point
- user = iam_user(policy=_access_point_policy(bucket, created["AccessPointArn"], "both"))
- client = user.client("s3", region="us-east-1", config=Config(signature_version="s3"))
- url = client.generate_presigned_url("get_object", Params={"Bucket": created[via], "Key": "k.txt"})
- assert "AWSAccessKeyId=" in url
- with urllib.request.urlopen(url, timeout=10) as resp:
- assert resp.read() == b"hello"
- tampered = re.sub(r"Signature=[^&]+", "Signature=AAAA", url)
- if auth_enabled:
- with pytest.raises(urllib.error.HTTPError) as exc:
- urllib.request.urlopen(tampered, timeout=10)
- assert exc.value.code == 403
- assert b"<Code>SignatureDoesNotMatch</Code>" in exc.value.read()
- with pytest.raises(ClientError) as exc:
- client.get_object(Bucket=created[via], Key="k.txt")
- error = exc.value.response
- assert (error["Error"]["Code"], error["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidRequest", 400)
- else:
- with urllib.request.urlopen(tampered, timeout=10) as resp:
- assert resp.read() == b"hello"
- assert client.get_object(Bucket=created[via], Key="k.txt")["Body"].read() == b"hello"
- assert client.get_object(Bucket=bucket, Key="k.txt")["Body"].read() == b"hello"
-
-
[email protected]("grant, deny, condition, allowed", [
- ("both", None, False, True),
- ("bucket", None, False, False),
- ("both", "access point", False, False),
- ("both", None, True, False),
-], ids=["both", "bucket-only", "deny-access-point", "deny-on-arn-key"])
-def test_access_point_alias_copy_source_contract(auth_enabled, iam_user, bucket, access_point, grant, deny,
- condition, allowed):
- """A copy source named by an alias is read through its access point."""
- _name, created = access_point
- arn = created["AccessPointArn"]
- policy = _access_point_policy(bucket, arn, grant, deny,
- {"StringEquals": {"s3:DataAccessPointArn": arn}} if condition else None)
- client = iam_user(policy=policy).client("s3")
- _assert_access(auth_enabled, allowed, lambda: client.copy_object(
- Bucket=bucket, Key="copy.txt", CopySource={"Bucket": created["Alias"], "Key": "k.txt"}))
- _assert_access(auth_enabled, True, lambda: client.copy_object(
- Bucket=bucket, Key="copy.txt", CopySource={"Bucket": bucket, "Key": "k.txt"}))
-
-
-def test_access_point_control_invalid_name(bucket):
- ctl = _client("s3control", "us-east-1")
- with pytest.raises(ClientError) as exc:
- ctl.create_access_point(AccountId=ACCOUNT, Name="Bad_Name", Bucket=bucket)
- err = exc.value.response
- assert (err["Error"]["Code"], err["ResponseMetadata"]["HTTPStatusCode"]) == ("InvalidAccessPoint", 400)
diff --git a/tests/test_s3_delete_errors.py b/tests/test_s3_delete_errors.py
deleted file mode 100644
index 695e154e..00000000
--- a/tests/test_s3_delete_errors.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""DeleteObject observations from real AWS, Osaka, 2026-10-23.
-
-AWS.Tools.S3 5.0.318 / AWS CLI 2.38.1 used explicit Osaka/Tokyo endpoints
-and bucket-scoped DeleteObject grants. These tests replay the first HTTP
-response locally, before SDK correction. No real AWS requests are made.
-"""
-import base64
-import hashlib
-import http.client
-import os
-import re
-import uuid
-from urllib.parse import parse_qsl, quote, urlencode, urlsplit
-from xml.etree.ElementTree import fromstring
-
-import boto3
-import pytest
-from botocore.auth import S3SigV4Auth
-from botocore.awsrequest import AWSRequest
-from botocore.config import Config
-from botocore.credentials import Credentials
-from botocore.exceptions import ClientError
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
-HOME, TOKYO = "ap-northeast-3", "ap-northeast-1"
-PAYLOAD = b"delete error validation"
-pytestmark = pytest.mark.auth_contract
-
-
-def delete_bucket(s3):
- name = f"delete-errors-{uuid.uuid4().hex}"
- s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
- s3.put_object(Bucket=name, Key="probe.txt", Body=PAYLOAD)
- yield name
- s3.delete_object(Bucket=name, Key="probe.txt")
- s3.delete_bucket(Bucket=name)
-
-
-def delete_client(delete_bucket, iam_user):
- return iam_user(policy={"Statement": [
- {"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": f"arn:aws:s3:::{delete_bucket}/*"},
- ]}).client("s3", region=HOME)
-
-
-def _send(host, path, headers):
- target = urlsplit(ENDPOINT)
- connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
- try:
- connection.request("DELETE", path, headers={**headers, "Host": host})
- response = connection.getresponse()
- return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
- finally:
- connection.close()
-
-
-def _delete(bucket, client, *, credential="valid", endpoint_region=HOME, region=HOME,
- virtual=False, key="probe.txt", query="", root=False, extra_headers=None):
- frozen = client._request_signer._credentials.get_frozen_credentials()
- access_key, secret = frozen.access_key, frozen.secret_key
- if credential == "unknown":
- access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
- elif credential == "wrong-secret":
- secret = "wrong"
- if root:
- access_key, secret = "test", "any-secret"
- host = f"s3.{endpoint_region}.{urlsplit(ENDPOINT).netloc}"
- path = f"/{quote(bucket)}/{quote(key, safe='/')}"
- if virtual:
- host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
- request = AWSRequest(method="DELETE", url=f"http://{host}{path}{query}", headers=extra_headers)
- S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
- return _send(host, path + query, dict(request.headers))
-
-
-def _assert_state(client, bucket, *, deleted):
- if deleted:
- with pytest.raises(ClientError) as exc:
- client.get_object(Bucket=bucket, Key="probe.txt")
- assert exc.value.response["Error"]["Code"] == "NoSuchKey"
- else:
- with client.get_object(Bucket=bucket, Key="probe.txt")["Body"] as body:
- assert body.read() == PAYLOAD
-
-
-def _assert_error(response, code, *, bucket, region=HOME, endpoint_region=HOME, access_key=None):
- _, headers, body = response
- error = fromstring(body)
- messages = {
- "InvalidBucketName": "The specified bucket is not valid.",
- "InvalidAccessKeyId": "The AWS Access Key Id you provided does not exist in our records.",
- "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. "
- "Check your key and signing method.",
- "AuthorizationHeaderMalformed": f"The authorization header is malformed; the region '{region}' is wrong; "
- f"expecting '{endpoint_region}'",
- "PermanentRedirect": "The bucket you are attempting to access must be addressed using the specified "
- "endpoint. Please send all future requests to this endpoint.",
- "NoSuchBucket": "The specified bucket does not exist",
- }
- details = {
- "InvalidBucketName": ["BucketName"], "InvalidAccessKeyId": ["AWSAccessKeyId"],
- "AuthorizationHeaderMalformed": ["Region"], "PermanentRedirect": ["Endpoint", "Bucket"],
- "NoSuchBucket": ["BucketName"],
- "SignatureDoesNotMatch": ["AWSAccessKeyId", "StringToSign", "SignatureProvided", "StringToSignBytes",
- "CanonicalRequest", "CanonicalRequestBytes"],
- }
- expected = ["Code", "Message", *details[code], "RequestId", "HostId"]
- assert error.findtext("Code") == code
- assert error.findtext("Message") == messages[code]
- if code == "SignatureDoesNotMatch":
- # Diagnostic membership and consistency matter even if AWS varies field order.
- assert sorted(child.tag for child in error) == sorted(expected)
- for name in ("CanonicalRequest", "StringToSign"):
- assert bytes.fromhex(error.findtext(name + "Bytes")).decode() == error.findtext(name)
- assert error.findtext("CanonicalRequest").startswith("DELETE\n")
- document = error.findtext("StringToSign")
- assert document.splitlines()[-1] == hashlib.sha256(error.findtext("CanonicalRequest").encode()).hexdigest()
- signed = AWSRequest()
- signed.context["timestamp"] = document.splitlines()[1]
- signer = S3SigV4Auth(Credentials(error.findtext("AWSAccessKeyId"), "wrong"), "s3", region)
- assert signer.signature(document, signed) == error.findtext("SignatureProvided")
- else:
- assert [child.tag for child in error] == expected
- assert headers["content-type"] == "application/xml"
- assert error.findtext("RequestId") == headers["x-amz-request-id"]
- assert re.fullmatch(r"[A-Z0-9]{16}", error.findtext("RequestId"))
- assert error.findtext("HostId") == headers["x-amz-id-2"]
- assert len(base64.b64decode(error.findtext("HostId"), validate=True)) >= 48
- assert "location" not in headers
- if code == "PermanentRedirect":
- assert error.findtext("Endpoint") == f"{bucket}.s3.{HOME}.{urlsplit(ENDPOINT).netloc}"
- assert error.findtext("Bucket") == bucket
- assert headers["x-amz-bucket-region"] == HOME
- else:
- assert "x-amz-bucket-region" not in headers
- if code in {"InvalidBucketName", "NoSuchBucket"}:
- assert error.findtext("BucketName") == bucket
- if code == "AuthorizationHeaderMalformed":
- assert error.findtext("Region") == endpoint_region
- if access_key is not None:
- assert error.findtext("AWSAccessKeyId") == access_key
-
-
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
- # Fixed first-response observations; DELETE success must also remove the object.
- (False, "valid", HOME, HOME, (204, None), (204, None)),
- (False, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (204, None)),
- (False, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (204, None)),
- (True, "valid", HOME, HOME, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
- (True, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
- (True, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
- (False, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (False, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (False, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (True, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
- # test_delete_home_precedes_signing_region_and_credentials, including state checks.
- (False, "wrong-secret", TOKYO, HOME, (301, "PermanentRedirect"), (204, None)),
- (True, "valid", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "unknown", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (False, "valid", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (False, "unknown", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (False, "wrong-secret", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (True, "valid", TOKYO, TOKYO, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
- (True, "unknown", TOKYO, TOKYO, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
- (True, "wrong-secret", TOKYO, TOKYO, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
-])
-def test_delete_combined_errors(delete_bucket, delete_client, s3, auth_enabled,
- virtual, missing, credential, endpoint_region, region, expected, compat_expected):
- bucket = f"missing-{delete_bucket}" if missing else delete_bucket
- expected = expected if auth_enabled else compat_expected
- response = _delete(bucket, delete_client, virtual=virtual, credential=credential,
- endpoint_region=endpoint_region, region=region)
- assert (response[0], fromstring(response[2]).findtext("Code") if response[2] else None) == expected
- _assert_state(s3, delete_bucket, deleted=not missing and response[0] == 204)
- if response[0] == 204:
- assert response[2] == b""
- elif auth_enabled:
- access_key = "AKIAUNKNOWNKEY000001" if credential == "unknown" else delete_client._request_signer._credentials.access_key
- _assert_error(response, expected[1], bucket=bucket, region=region, endpoint_region=endpoint_region,
- access_key=access_key if expected[1] in {"InvalidAccessKeyId", "SignatureDoesNotMatch"} else None)
-
-
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
-def test_delete_home_precedes_signing_region_and_credentials(delete_bucket, delete_client, s3,
- auth_enabled, virtual, credential):
- # Fixed AWS observation: redirect, including with an unknown access key.
- response = _delete(delete_bucket, delete_client, virtual=virtual, credential=credential,
- endpoint_region=TOKYO, region=HOME)
- assert response[0] == (301 if auth_enabled else 204)
- if auth_enabled:
- _assert_error(response, "PermanentRedirect", bucket=delete_bucket, endpoint_region=TOKYO)
- else:
- assert response[2] == b""
- _assert_state(s3, delete_bucket, deleted=not auth_enabled)
-
-
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
-def test_delete_missing_key_is_idempotent(delete_bucket, delete_client, s3, auth_enabled, virtual, credential, region):
- response = _delete(delete_bucket, delete_client, virtual=virtual, credential=credential, region=region, key="missing.txt")
- code = ("AuthorizationHeaderMalformed" if region != HOME else
- "InvalidAccessKeyId" if auth_enabled and credential == "unknown" else
- "SignatureDoesNotMatch" if auth_enabled and credential == "wrong-secret" else None)
- assert (response[0], fromstring(response[2]).findtext("Code") if response[2] else None) == (
- 400 if region != HOME else 403 if code else 204, code)
- if code and auth_enabled:
- _assert_error(response, code, bucket=delete_bucket, region=region)
- if not code:
- assert response[2] == b""
- assert _delete(delete_bucket, delete_client, virtual=virtual, key="missing.txt")[0] == 204
- _assert_state(s3, delete_bucket, deleted=False)
-
-
-def test_delete_invalid_name_precedes_credentials(delete_client, auth_enabled):
- response = _delete("invalid bucket", delete_client, credential="unknown")
- assert response[0] == (400 if auth_enabled else 404)
- if auth_enabled:
- _assert_error(response, "InvalidBucketName", bucket="invalid bucket")
-
-
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
-def test_delete_still_enforces_iam(delete_bucket, iam_user, s3, auth_enabled, virtual, denial):
- policy = {"Statement": [{"Effect": "Deny", "Action": "s3:DeleteObject", "Resource": "*"}]}
- client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
- response = _delete(delete_bucket, client, virtual=virtual)
- assert response[0] == (403 if auth_enabled else 204)
- _assert_state(s3, delete_bucket, deleted=not auth_enabled)
- assert _delete(delete_bucket, client, virtual=virtual, key="missing.txt")[0] == (403 if auth_enabled else 204)
-
-
[email protected]("virtual", [False, True])
-def test_delete_reserved_root_compatibility(delete_bucket, s3, virtual):
- assert _delete(delete_bucket, s3, virtual=virtual, root=True)[0] == 204
- _assert_state(s3, delete_bucket, deleted=True)
-
-
[email protected]("virtual", [False, True])
-def test_delete_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, virtual):
- owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
- aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
- bucket = f"foreign-delete-{uuid.uuid4().hex}"
- owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
- owner.put_object(Bucket=bucket, Key="probe.txt", Body=PAYLOAD)
- client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "*"}]}).client("s3")
- try:
- assert _delete(bucket, client, virtual=virtual)[0] == 403
- _assert_state(owner, bucket, deleted=False)
- finally:
- owner.delete_object(Bucket=bucket, Key="probe.txt")
- owner.delete_bucket(Bucket=bucket)
- owner.close()
-
-
[email protected]("virtual", [False, True])
[email protected]("query", ["?versionId=null", "?tagging"])
-def test_delete_subresources_keep_their_iam_path(delete_bucket, iam_user, auth_enabled, virtual, query):
- client = iam_user().client("s3", region=HOME)
- response = _delete(f"missing-{delete_bucket}", client, virtual=virtual, query=query)
- assert response[0] == (403 if auth_enabled else 404)
-
-
[email protected]("virtual", [False, True])
-def test_delete_version_needs_its_own_permission(delete_bucket, delete_client, s3, auth_enabled, virtual):
- response = _delete(delete_bucket, delete_client, virtual=virtual, query="?versionId=null")
- assert response[0] == (403 if auth_enabled else 204)
- _assert_state(s3, delete_bucket, deleted=not auth_enabled)
-
-
[email protected]("virtual", [False, True])
-def test_delete_failed_precondition_preserves_object(delete_bucket, delete_client, s3, virtual):
- response = _delete(delete_bucket, delete_client, virtual=virtual, extra_headers={"If-Match": '"incorrect"'})
- assert (response[0], fromstring(response[2]).findtext("Code")) == (412, "PreconditionFailed")
- _assert_state(s3, delete_bucket, deleted=False)
-
-
[email protected]("virtual", [False, True])
[email protected]("invalid", [False, True], ids=["valid", "bad-signature"])
-def test_delete_presigned_validation_is_preserved(delete_bucket, iam_user, s3, virtual, invalid):
- client = iam_user(policy={"Statement": [
- {"Effect": "Allow", "Action": "s3:DeleteObject", "Resource": f"arn:aws:s3:::{delete_bucket}/*"},
- ]}).client("s3", region=HOME, config=Config(signature_version="s3v4", s3={"addressing_style": "virtual" if virtual else "path"}))
- target = urlsplit(client.generate_presigned_url("delete_object", Params={"Bucket": delete_bucket, "Key": "probe.txt"}))
- query = dict(parse_qsl(target.query))
- if invalid:
- signature = query["X-Amz-Signature"]
- query["X-Amz-Signature"] = ("0" if signature[0] != "0" else "1") + signature[1:]
- response = _send(target.netloc, target.path + "?" + urlencode(query), {})
- assert response[0] == (403 if invalid else 204)
- _assert_state(s3, delete_bucket, deleted=not invalid)
diff --git a/tests/test_s3_download_errors.py b/tests/test_s3_download_errors.py
deleted file mode 100644
index 55bd8088..00000000
--- a/tests/test_s3_download_errors.py
+++ /dev/null
@@ -1,266 +0,0 @@
-"""GetObject observations from real AWS, Osaka, 2026-10-18.
-
-AWS CLI 2.38.1 / AWS.Tools.S3 5.0.318 used explicit Osaka/Tokyo endpoints
-and a bucket-scoped GetObject/ListBucket grant. These tests replay HTTP
-observations locally, before client region correction; they never call AWS.
-AUTH=false assertions preserve MiniStack's permissive compatibility.
-"""
-import base64
-import hashlib
-import http.client
-import os
-import re
-import uuid
-from urllib.parse import quote, urlsplit
-from xml.etree.ElementTree import fromstring
-
-import boto3
-import pytest
-from botocore.auth import S3SigV4Auth
-from botocore.awsrequest import AWSRequest
-from botocore.credentials import Credentials
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
-HOME, TOKYO = "ap-northeast-3", "ap-northeast-1"
-PAYLOAD = b"download error validation"
-pytestmark = pytest.mark.auth_contract
-
-
-def download_bucket(s3):
- name = f"download-errors-{uuid.uuid4().hex}"
- s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
- s3.put_object(Bucket=name, Key="probe.txt", Body=PAYLOAD)
- yield name
- s3.delete_object(Bucket=name, Key="probe.txt")
- s3.delete_bucket(Bucket=name)
-
-
-def download_client(download_bucket, iam_user):
- return iam_user(policy={"Statement": [
- {"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{download_bucket}/*"},
- {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": f"arn:aws:s3:::{download_bucket}"},
- ]}).client("s3", region=HOME)
-
-
-def _download(bucket, client, *, credential="valid", endpoint_region=HOME, region=HOME,
- virtual=False, key="probe.txt", query="", root=False):
- frozen = client._request_signer._credentials.get_frozen_credentials()
- access_key, secret = frozen.access_key, frozen.secret_key
- if credential == "unknown":
- access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
- elif credential == "wrong-secret":
- secret = "wrong"
- if root:
- access_key, secret = "test", "any-secret"
- target = urlsplit(ENDPOINT)
- host = f"s3.{endpoint_region}.{target.netloc}"
- path = f"/{quote(bucket)}/{quote(key, safe='/')}"
- if virtual:
- host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
- request = AWSRequest(method="GET", url=f"http://{host}{path}{query}")
- S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
- connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
- try:
- connection.request("GET", path + query, headers={**dict(request.headers), "Host": host})
- response = connection.getresponse()
- return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
- finally:
- connection.close()
-
-
-def _assert_error(response, code, *, bucket, key="probe.txt", region=HOME, access_key=None):
- _, headers, body = response
- error = fromstring(body)
- messages = {
- "InvalidBucketName": "The specified bucket is not valid.",
- "InvalidAccessKeyId": "The AWS Access Key Id you provided does not exist in our records.",
- "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. "
- "Check your key and signing method.",
- "AuthorizationHeaderMalformed": f"The authorization header is malformed; the region '{region}' is wrong; "
- f"expecting '{HOME if region == TOKYO else TOKYO}'",
- "PermanentRedirect": "The bucket you are attempting to access must be addressed using the specified "
- "endpoint. Please send all future requests to this endpoint.",
- "NoSuchBucket": "The specified bucket does not exist",
- "NoSuchKey": "The specified key does not exist.",
- }
- details = {
- "InvalidBucketName": ["BucketName"], "InvalidAccessKeyId": ["AWSAccessKeyId"],
- "AuthorizationHeaderMalformed": ["Region"], "PermanentRedirect": ["Bucket", "Endpoint"],
- "NoSuchBucket": ["BucketName"], "NoSuchKey": ["Key"],
- "SignatureDoesNotMatch": ["AWSAccessKeyId", "StringToSign", "SignatureProvided", "StringToSignBytes",
- "CanonicalRequest", "CanonicalRequestBytes"],
- }
- expected = ["Code", "Message", *details[code], "RequestId", "HostId"]
- assert error.findtext("Code") == code
- assert error.findtext("Message") == messages[code]
- if code == "SignatureDoesNotMatch":
- # Real GET responses varied the order of the signature diagnostics.
- assert sorted(child.tag for child in error) == sorted(expected)
- for name in ("CanonicalRequest", "StringToSign"):
- assert bytes.fromhex(error.findtext(name + "Bytes")).decode() == error.findtext(name)
- assert error.findtext("CanonicalRequest").startswith("GET\n")
- assert error.findtext("StringToSign").splitlines()[-1] == hashlib.sha256(
- error.findtext("CanonicalRequest").encode()).hexdigest()
- assert re.fullmatch(r"[a-f0-9]{64}", error.findtext("SignatureProvided"))
- signed = AWSRequest()
- document = error.findtext("StringToSign")
- signed.context["timestamp"] = document.splitlines()[1]
- signer = S3SigV4Auth(Credentials(error.findtext("AWSAccessKeyId"), "wrong"), "s3", region)
- assert signer.signature(document, signed) == error.findtext("SignatureProvided")
- else:
- assert [child.tag for child in error] == expected
- assert headers["content-type"] == "application/xml"
- assert error.findtext("RequestId") == headers["x-amz-request-id"]
- assert re.fullmatch(r"[A-Z0-9]{16}", error.findtext("RequestId"))
- assert error.findtext("HostId") == headers["x-amz-id-2"]
- assert len(base64.b64decode(error.findtext("HostId"), validate=True)) >= 48
- assert "location" not in headers
- if code == "PermanentRedirect":
- assert error.findtext("Endpoint") == f"{bucket}.s3.{HOME}.{urlsplit(ENDPOINT).netloc}"
- assert error.findtext("Bucket") == bucket
- assert headers["x-amz-bucket-region"] == HOME
- else:
- assert "x-amz-bucket-region" not in headers
- if code in {"InvalidBucketName", "NoSuchBucket"}:
- assert error.findtext("BucketName") == bucket
- if code == "NoSuchKey":
- assert error.findtext("Key") == key
- if code == "AuthorizationHeaderMalformed":
- assert error.findtext("Region") == (HOME if region == TOKYO else TOKYO)
- if access_key is not None:
- assert error.findtext("AWSAccessKeyId") == access_key
-
-
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
- # Fixed first-response observations; AUTH=false is a separate local contract.
- (False, "valid", HOME, HOME, (200, None), (200, None)),
- (False, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (200, None)),
- (False, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (200, None)),
- (True, "valid", HOME, HOME, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
- (True, "unknown", HOME, HOME, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
- (True, "wrong-secret", HOME, HOME, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
- (False, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (False, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (False, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (400, "AuthorizationHeaderMalformed")),
- (True, "valid", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "unknown", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "wrong-secret", HOME, TOKYO, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
- # test_download_signing_region_precedes_home_and_credentials, including wire checks.
- (False, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (200, None)),
- (True, "valid", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "unknown", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (True, "wrong-secret", TOKYO, HOME, (400, "AuthorizationHeaderMalformed"), (404, "NoSuchBucket")),
- (False, "valid", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (False, "unknown", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (False, "wrong-secret", TOKYO, TOKYO, (301, "PermanentRedirect"), (301, "PermanentRedirect")),
- (True, "valid", TOKYO, TOKYO, (404, "NoSuchBucket"), (404, "NoSuchBucket")),
- (True, "unknown", TOKYO, TOKYO, (403, "InvalidAccessKeyId"), (404, "NoSuchBucket")),
- (True, "wrong-secret", TOKYO, TOKYO, (403, "SignatureDoesNotMatch"), (404, "NoSuchBucket")),
-])
-def test_download_combined_errors(download_bucket, download_client, auth_enabled,
- virtual, missing, credential, endpoint_region, region, expected, compat_expected):
- bucket = f"missing-{download_bucket}" if missing else download_bucket
- expected = expected if auth_enabled else compat_expected
- response = _download(bucket, download_client, credential=credential, endpoint_region=endpoint_region,
- region=region, virtual=virtual)
- code = fromstring(response[2]).findtext("Code") if response[0] != 200 else None
- assert (response[0], code) == expected
- if response[0] == 200:
- assert response[2] == PAYLOAD
- elif auth_enabled:
- access_key = ("AKIAUNKNOWNKEY000001" if credential == "unknown"
- else download_client._request_signer._credentials.access_key)
- _assert_error(response, code, bucket=bucket, region=region,
- access_key=access_key if code in {"InvalidAccessKeyId", "SignatureDoesNotMatch"} else None)
-
-
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
-def test_download_signing_region_precedes_home_and_credentials(download_bucket, download_client, s3,
- auth_enabled, virtual, credential):
- # Fixed AWS observation: Osaka bucket + Tokyo endpoint + Osaka signature.
- # Kept separately as the regression for GET's different priority from HEAD/DELETE.
- response = _download(download_bucket, download_client, virtual=virtual, credential=credential,
- endpoint_region=TOKYO, region=HOME)
- assert response[0] == (400 if auth_enabled else 200)
- if auth_enabled:
- _assert_error(response, "AuthorizationHeaderMalformed", bucket=download_bucket, region=HOME)
- else:
- assert response[2] == PAYLOAD
- with s3.get_object(Bucket=download_bucket, Key="probe.txt")["Body"] as body:
- assert body.read() == PAYLOAD
-
-
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
-def test_download_missing_key(download_bucket, download_client, auth_enabled, virtual, credential, region):
- response = _download(download_bucket, download_client, virtual=virtual, credential=credential,
- region=region, key="missing.txt")
- code = ("AuthorizationHeaderMalformed" if region != HOME else
- "InvalidAccessKeyId" if credential == "unknown" else
- "SignatureDoesNotMatch" if credential == "wrong-secret" else "NoSuchKey")
- if not auth_enabled:
- code = "AuthorizationHeaderMalformed" if region != HOME else "NoSuchKey"
- assert (response[0], fromstring(response[2]).findtext("Code")) == (
- 400 if code == "AuthorizationHeaderMalformed" else 404 if code == "NoSuchKey" else 403, code,
- )
- if auth_enabled:
- _assert_error(response, code, bucket=download_bucket, key="missing.txt", region=region)
-
-
-def test_download_invalid_name_precedes_credentials(download_client, auth_enabled):
- response = _download("invalid bucket", download_client, credential="unknown")
- assert (response[0], fromstring(response[2]).findtext("Code")) == (
- (400, "InvalidBucketName") if auth_enabled else (404, "NoSuchBucket")
- )
- if auth_enabled:
- _assert_error(response, "InvalidBucketName", bucket="invalid bucket")
-
-
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
-def test_download_still_enforces_iam(download_bucket, iam_user, auth_enabled, virtual, denial):
- policy = {"Statement": [{"Effect": "Deny", "Action": "s3:GetObject", "Resource": "*"}]}
- client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
- response = _download(download_bucket, client, virtual=virtual)
- if auth_enabled:
- assert (response[0], fromstring(response[2]).findtext("Code")) == (403, "AccessDenied")
- else:
- assert (response[0], response[2]) == (200, PAYLOAD)
-
-
[email protected]("virtual", [False, True])
-def test_download_reserved_root_compatibility(download_bucket, s3, virtual):
- response = _download(download_bucket, s3, virtual=virtual, root=True)
- assert (response[0], response[2]) == (200, PAYLOAD)
-
-
[email protected]("virtual", [False, True])
[email protected]("query", ["?versionId=null", "?tagging"])
-def test_download_subresources_keep_their_iam_path(download_bucket, iam_user, auth_enabled, virtual, query):
- client = iam_user().client("s3", region=HOME)
- response = _download(f"missing-{download_bucket}", client, virtual=virtual, query=query)
- assert (response[0], fromstring(response[2]).findtext("Code")) == (
- (403, "AccessDenied") if auth_enabled else (404, "NoSuchBucket")
- )
-
-
[email protected]("virtual", [False, True])
-def test_download_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, virtual):
- owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
- aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
- bucket = f"foreign-download-{uuid.uuid4().hex}"
- owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
- owner.put_object(Bucket=bucket, Key="probe.txt", Body=b"private")
- client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}).client("s3")
- try:
- response = _download(bucket, client, virtual=virtual)
- assert (response[0], fromstring(response[2]).findtext("Code")) == (403, "AccessDenied")
- finally:
- owner.delete_object(Bucket=bucket, Key="probe.txt")
- owner.delete_bucket(Bucket=bucket)
- owner.close()
diff --git a/tests/test_s3_head_errors.py b/tests/test_s3_head_errors.py
deleted file mode 100644
index d21ff52b..00000000
--- a/tests/test_s3_head_errors.py
+++ /dev/null
@@ -1,278 +0,0 @@
-"""Real AWS HEAD observations (Osaka, 2026-10-23), replayed only against MiniStack.
-
-AWS.Tools.S3 5.0.318 and AWS CLI 2.38.1 used a bucket-scoped GetObject/ListBucket
-grant and explicit Osaka/Tokyo endpoints. Assertions describe the first HTTP
-response, before SDK region correction. HEAD has no XML error diagnostics.
-"""
-import base64
-import http.client
-import os
-import re
-import uuid
-from urllib.parse import quote, urlsplit
-
-import boto3
-import pytest
-from botocore.auth import S3SigV4Auth, S3SigV4QueryAuth
-from botocore.awsrequest import AWSRequest
-from botocore.credentials import Credentials
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
-HOME, TOKYO = "ap-northeast-3", "ap-northeast-1"
-PAYLOAD = b"head error validation"
-pytestmark = pytest.mark.auth_contract
-
-
[email protected]("source", ["region", "authentication", "normal", "iam", "missing-request", "missing-host"])
-def test_head_finalizer_preserves_valid_identifiers(source):
- """Pure formatting contract: no AUTH/IAM patch, no live AWS request."""
- from ministack.core.iam_actions import access_denied_response
- from ministack.services import s3
-
- host_id = base64.b64encode(b"existing-host-id" * 4).decode()
- if source in {"region", "authentication", "missing-host"}:
- code, status = ("PermanentRedirect", 301) if source == "region" else ("InvalidAccessKeyId", 403)
- response = s3._object_error(code, "formatting probe", status)
- if source == "missing-host":
- response[1].pop("x-amz-id-2")
- elif source == "iam":
- response = access_denied_response("s3", "s3:GetObject", "arn:aws:iam::000000000000:user/probe", "legacy-id")
- else:
- response = 200, {"Content-Type": "text/plain", "Content-Length": "4", "x-amz-id-2": host_id}, b""
- if source == "normal":
- response[1]["x-amz-request-id"] = "12345678-1234-1234-1234-123456789abc"
- original_headers = dict(response[1])
- result = s3.format_head_response("/id-format-probe/key", {}, response)
- request_id = result[1]["x-amz-request-id"]
- assert re.fullmatch(r"[A-Z0-9]{16}", request_id)
- if re.fullmatch(r"[A-Z0-9]{16}", original_headers.get("x-amz-request-id", "")):
- assert request_id == original_headers["x-amz-request-id"]
- if original_headers.get("x-amz-id-2"):
- assert result[1]["x-amz-id-2"] == original_headers["x-amz-id-2"]
- assert len(base64.b64decode(result[1]["x-amz-id-2"], validate=True)) >= 48
- assert result[2] == b""
- assert s3.format_head_response("/id-format-probe/key", {}, result) == result
- assert response[1] == original_headers
-
-
-def head_bucket(s3):
- name = f"head-errors-{uuid.uuid4().hex}"
- s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": HOME})
- s3.put_object(Bucket=name, Key="probe.txt", Body=PAYLOAD, ContentType="text/plain")
- yield name
- s3.delete_object(Bucket=name, Key="probe.txt")
- s3.delete_bucket(Bucket=name)
-
-
-def head_client(head_bucket, iam_user):
- return iam_user(policy={"Statement": [
- {"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::{head_bucket}/*"},
- {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": f"arn:aws:s3:::{head_bucket}"},
- ]}).client("s3", region=HOME)
-
-
-def _head(bucket, client, *, key="probe.txt", virtual=False, credential="valid",
- endpoint_region=HOME, region=HOME, root=False, query="", extra_headers=None, presigned=False):
- frozen = client._request_signer._credentials.get_frozen_credentials()
- access_key, secret = frozen.access_key, frozen.secret_key
- if credential == "unknown":
- access_key, secret = "AKIAUNKNOWNKEY000001", "wrong"
- elif credential == "wrong-secret":
- secret = "wrong"
- if root:
- access_key, secret = "test", "any-secret"
- target = urlsplit(ENDPOINT)
- host = f"s3.{endpoint_region}.{target.netloc}"
- path = f"/{quote(bucket)}" + (f"/{quote(key, safe='/')}" if key else "")
- if virtual:
- host, path = f"{bucket}.{host}", f"/{quote(key, safe='/')}"
- request = AWSRequest(method="HEAD", url=f"http://{host}{path}{query}", headers=extra_headers)
- if presigned:
- S3SigV4QueryAuth(Credentials(access_key, secret), "s3", region, expires=300).add_auth(request)
- signed_url = urlsplit(request.url)
- path, query = signed_url.path, "?" + signed_url.query
- else:
- S3SigV4Auth(Credentials(access_key, secret), "s3", region).add_auth(request)
- connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=10)
- try:
- connection.request("HEAD", path + query, headers={**dict(request.headers), "Host": host})
- response = connection.getresponse()
- return response.status, {k.lower(): v for k, v in response.getheaders()}, response.read()
- finally:
- connection.close()
-
-
-def _assert_wire(response, *, bucket, key, expected_region=None):
- status, headers, body = response
- assert body == b""
- assert headers.get("x-amz-bucket-region") == expected_region
- assert "x-amz-error-code" not in headers
- assert "x-amz-error-message" not in headers
- assert re.fullmatch(r"[A-Z0-9]{16}", headers["x-amz-request-id"])
- assert len(base64.b64decode(headers["x-amz-id-2"], validate=True)) >= 48
- if key and status == 200:
- assert headers["content-length"] == str(len(PAYLOAD))
- assert headers["content-type"] == "text/plain"
- else:
- assert "content-length" not in headers
- assert headers["content-type"] == "application/xml"
- assert headers.get("x-amz-bucket-arn") == (f"arn:aws:s3:::{bucket}" if not key and status == 200 else None)
-
-
[email protected]("key", ["probe.txt", ""], ids=["HeadObject", "HeadBucket"])
[email protected]("virtual", [False, True], ids=["path", "virtual"])
[email protected]("missing,credential,endpoint_region,region,expected,compat_expected", [
- # Fixed first-response observations, separately for HeadObject and HeadBucket.
- # Unlike GET, HEAD checks the bucket's home before the signing scope.
- (False, "valid", HOME, HOME, 200, 200),
- (False, "unknown", HOME, HOME, 403, 200),
- (False, "wrong-secret", HOME, HOME, 403, 200),
- (True, "valid", HOME, HOME, 404, 404),
- (True, "unknown", HOME, HOME, 403, 404),
- (True, "wrong-secret", HOME, HOME, 403, 404),
- (False, "valid", HOME, TOKYO, 400, 400),
- (False, "unknown", HOME, TOKYO, 400, 400),
- (False, "wrong-secret", HOME, TOKYO, 400, 400),
- (True, "valid", HOME, TOKYO, 400, 404),
- (True, "unknown", HOME, TOKYO, 400, 404),
- (True, "wrong-secret", HOME, TOKYO, 400, 404),
- # Existing-bucket valid/unknown + Tokyo endpoint/Osaka signature live in
- # test_head_home_precedes_signing_region_and_credentials, including wire checks.
- (False, "wrong-secret", TOKYO, HOME, 301, 200),
- (True, "valid", TOKYO, HOME, 400, 404),
- (True, "unknown", TOKYO, HOME, 400, 404),
- (True, "wrong-secret", TOKYO, HOME, 400, 404),
- (False, "valid", TOKYO, TOKYO, 301, 301),
- (False, "unknown", TOKYO, TOKYO, 301, 301),
- (False, "wrong-secret", TOKYO, TOKYO, 301, 301),
- (True, "valid", TOKYO, TOKYO, 404, 404),
- (True, "unknown", TOKYO, TOKYO, 403, 404),
- (True, "wrong-secret", TOKYO, TOKYO, 403, 404),
-])
-def test_head_combined_errors(head_bucket, head_client, auth_enabled,
- key, virtual, missing, credential, endpoint_region, region, expected, compat_expected):
- bucket = f"missing-{head_bucket}" if missing else head_bucket
- expected = expected if auth_enabled else compat_expected
- response = _head(bucket, head_client, key=key, virtual=virtual, credential=credential,
- endpoint_region=endpoint_region, region=region)
- assert response[0] == expected
- assert response[2] == b""
- if auth_enabled:
- _assert_wire(response, bucket=bucket, key=key,
- expected_region=HOME if not missing and (not key or expected == 301) else None)
-
-
[email protected]("key", ["probe.txt", ""], ids=["HeadObject", "HeadBucket"])
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "unknown"])
-def test_head_home_precedes_signing_region_and_credentials(head_bucket, head_client, s3,
- auth_enabled, key, virtual, credential):
- # Fixed AWS regression: home-region redirect wins over signing/authentication errors.
- response = _head(head_bucket, head_client, key=key, virtual=virtual, credential=credential,
- endpoint_region=TOKYO, region=HOME)
- assert response[0] == (301 if auth_enabled else 200)
- assert response[2] == b""
- if auth_enabled:
- _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME)
- with s3.get_object(Bucket=head_bucket, Key="probe.txt")["Body"] as body:
- assert body.read() == PAYLOAD
-
-
[email protected]("virtual", [False, True])
[email protected]("credential,region", [("valid", HOME), ("unknown", HOME), ("wrong-secret", HOME), ("valid", TOKYO)])
-def test_head_missing_key(head_bucket, head_client, auth_enabled, virtual, credential, region):
- response = _head(head_bucket, head_client, key="missing.txt", virtual=virtual, credential=credential, region=region)
- expected = 400 if region != HOME else 403 if auth_enabled and credential != "valid" else 404
- assert response[0] == expected
- if auth_enabled:
- _assert_wire(response, bucket=head_bucket, key="missing.txt")
-
-
[email protected]("key", ["probe.txt", ""])
-def test_head_invalid_name_precedes_credentials(head_client, auth_enabled, key):
- response = _head("invalid bucket", head_client, key=key, credential="unknown")
- assert response[0] == (400 if auth_enabled else 404)
- if auth_enabled:
- _assert_wire(response, bucket="invalid bucket", key=key)
-
-
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
[email protected]("denial", ["implicit", "explicit"])
-def test_head_still_enforces_iam(head_bucket, iam_user, auth_enabled, key, virtual, denial):
- policy = {"Statement": [{"Effect": "Deny", "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": "*"}]}
- client = iam_user(policy=policy if denial == "explicit" else None).client("s3", region=HOME)
- response = _head(head_bucket, client, key=key, virtual=virtual)
- assert response[0] == (403 if auth_enabled else 200)
- if auth_enabled:
- _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME if not key else None)
-
-
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
-def test_head_reserved_root_compatibility(head_bucket, s3, auth_enabled, key, virtual):
- response = _head(head_bucket, s3, key=key, virtual=virtual, root=True)
- assert response[0] == 200
- if auth_enabled:
- _assert_wire(response, bucket=head_bucket, key=key, expected_region=HOME if not key else None)
-
-
[email protected]("key", ["probe.txt", ""])
[email protected]("virtual", [False, True])
-def test_head_does_not_grant_foreign_bucket_access(iam_user, auth_enabled, key, virtual):
- owner = boto3.client("s3", endpoint_url=ENDPOINT, region_name=HOME,
- aws_access_key_id="333333333333", aws_secret_access_key="root-secret")
- bucket = f"foreign-head-{uuid.uuid4().hex}"
- owner.create_bucket(Bucket=bucket, CreateBucketConfiguration={"LocationConstraint": HOME})
- owner.put_object(Bucket=bucket, Key="probe.txt", Body=PAYLOAD)
- client = iam_user(policy={"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}).client("s3")
- try:
- response = _head(bucket, client, key=key, virtual=virtual)
- assert response[0] == 403
- if auth_enabled:
- _assert_wire(response, bucket=bucket, key=key, expected_region=HOME if not key else None)
- finally:
- owner.delete_object(Bucket=bucket, Key="probe.txt")
- owner.delete_bucket(Bucket=bucket)
- owner.close()
-
-
[email protected]("virtual", [False, True])
-def test_head_version_query_keeps_iam_path(head_bucket, iam_user, auth_enabled, virtual):
- client = iam_user().client("s3", region=HOME)
- response = _head(f"missing-{head_bucket}", client, virtual=virtual, query="?versionId=null")
- assert response[0] == (403 if auth_enabled else 404)
-
-
[email protected]("virtual", [False, True])
[email protected]("credential", ["valid", "wrong-secret"])
-def test_head_presigned_validation_is_preserved(head_bucket, head_client, s3, virtual, credential):
- response = _head(head_bucket, head_client, virtual=virtual, credential=credential, presigned=True)
- assert response[0] == (200 if credential == "valid" else 403)
- assert response[2] == b""
- if credential == "valid":
- assert response[1]["content-length"] == str(len(PAYLOAD))
- assert response[1]["content-type"] == "text/plain"
- with s3.get_object(Bucket=head_bucket, Key="probe.txt")["Body"] as body:
- assert body.read() == PAYLOAD
-
-
[email protected]("virtual", [False, True])
-def test_head_conditional_metadata(head_bucket, head_client, auth_enabled, virtual):
- response = _head(head_bucket, head_client, virtual=virtual)
- assert response[0] == 200
- assert response[1]["content-length"] == str(len(PAYLOAD))
- assert response[2] == b""
- etag = response[1]["etag"]
- response = _head(head_bucket, head_client, virtual=virtual, extra_headers={"If-None-Match": etag})
- assert response[0] == 304
- assert response[2] == b""
- if auth_enabled:
- assert "content-length" not in response[1]
- assert "content-type" not in response[1]
- response = _head(head_bucket, head_client, virtual=virtual, extra_headers={"If-Match": '"incorrect"'})
- assert response[0] == 412
- if auth_enabled:
- _assert_wire(response, bucket=head_bucket, key="probe.txt")
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 1cb370f6..4abf6c33 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -8035,6 +8035,38 @@ def test_sfn_jsonata_undefined_variable_raises_query_eval_error(sfn_sync):
sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+def test_sfn_jsonata_assign_null_variable_reads_back_as_null(sfn_sync):
+ """A variable with the value `null` reads back as `null`, not as undefined.
+ AWS keeps the two apart: only an unset variable fails."""
+ import uuid as _uuid_local
+ sm_name = f"jsonata-assign-null-{_uuid_local.uuid4().hex[:8]}"
+ sm_arn = sfn_sync.create_state_machine(
+ name=sm_name,
+ roleArn="arn:aws:iam::000000000000:role/test-role",
+ definition=json.dumps({
+ "QueryLanguage": "JSONata",
+ "StartAt": "SetNull",
+ "States": {
+ "SetNull": {
+ "Type": "Pass",
+ "Assign": {"v": None},
+ "Next": "ReadNull",
+ },
+ "ReadNull": {
+ "Type": "Pass",
+ "Output": {"v": "{% $v %}"},
+ "End": True,
+ },
+ },
+ }),
+ )["stateMachineArn"]
+ try:
+ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")
+ assert resp["status"] == "SUCCEEDED"
+ assert json.loads(resp["output"]) == {"v": None}
+ finally:
+ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)
+
_SFN_ECHO_PROCESSOR = {"ProcessorConfig": {"Mode": "INLINE"}, "StartAt": "Echo",
"States": {"Echo": {"Type": "Pass", "End": True}}}
@@ -8044,11 +8076,6 @@ def test_sfn_jsonata_inline_map_evaluates_its_fields(sfn_sync):
reads the current item and variables from the outer scope."""
import uuid as _uuid_local
sm_name = f"jsonata-map-fields-{_uuid_local.uuid4().hex[:8]}"
-def test_sfn_jsonata_assign_null_variable_reads_back_as_null(sfn_sync):
- """A variable with the value `null` reads back as `null`, not as undefined.
- AWS keeps the two apart: only an unset variable fails."""
- import uuid as _uuid_local
- sm_name = f"jsonata-assign-null-{_uuid_local.uuid4().hex[:8]}"
sm_arn = sfn_sync.create_state_machine(
name=sm_name,
roleArn="arn:aws:iam::000000000000:role/test-role",
@@ -8094,18 +8121,6 @@ def test_sfn_jsonata_inline_map_items_not_an_array_fails(sfn_sync):
"StartAt": "M",
"States": {
"M": {"Type": "Map", "Items": "{% 'x' %}", "ItemProcessor": _SFN_ECHO_PROCESSOR, "End": True},
- "StartAt": "SetNull",
- "States": {
- "SetNull": {
- "Type": "Pass",
- "Assign": {"v": None},
- "Next": "ReadNull",
- },
- "ReadNull": {
- "Type": "Pass",
- "Output": {"v": "{% $v %}"},
- "End": True,
- },
},
}),
)["stateMachineArn"]