Skip to content

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

prerelease v1.5.29 (#2237)

Nahuel Nucera180da4ca11e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2366bee..b722550e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,9 +9,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
-- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys.
-- **Managed Service for Apache Flink — job execution** — with Docker available, starting a `FLINK-1_19` or `FLINK-1_20` application runs its jar from MiniStack S3 in the official Apache Flink image (1.19.1 or 1.20.5, Java 11) with a JobManager and a TaskManager, its runtime properties at `/etc/flink/application_properties.json`, its configured parallelism and checkpointing, and its AWS calls pointed at MiniStack in the application's account. Snapshots are Flink savepoints, restores resume the job's state, and a job that fails to start returns the application to `READY`. Jars in `/opt/ministack/flink-lib` (for example a mounted `aws-kinesisanalytics-runtime`) are added to every cluster. Without Docker the control plane behaves as before.
-- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys. The Flink job itself does not run (control plane only).
+- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys. Contributed by @Jolley71717.
+- **Managed Service for Apache Flink — job execution** — with Docker available, starting a `FLINK-1_19` or `FLINK-1_20` application runs its jar from MiniStack S3 in the official Apache Flink image (1.19.1 or 1.20.5, Java 11) with a JobManager and a TaskManager, its runtime properties at `/etc/flink/application_properties.json`, its configured parallelism and checkpointing, and its AWS calls pointed at MiniStack in the application's account. Snapshots are Flink savepoints, restores resume the job's state, and a job that fails to start returns the application to `READY`. Jars in `/opt/ministack/flink-lib` (for example a mounted `aws-kinesisanalytics-runtime`) are added to every cluster. Without Docker the control plane behaves as before. Contributed by @Jolley71717.
+- **S3 Access Points** — S3 Control `CreateAccessPoint`, `GetAccessPoint`, `ListAccessPoints`, `DeleteAccessPoint` and `Put`/`Get`/`DeleteAccessPointPolicy`. The bucket must be in the request's region, names are unique per account and region, and errors follow AWS (`AccessPointAlreadyOwnedByYou`, `NoSuchAccessPoint`). Requests through an access point ARN (`<name>-<account>.<host>`) or its `-s3alias` alias reach the bucket, including as a `CopyObject` source; signing for another region gets the bucket-region redirect with the access point's region. `DeleteBucket` refuses a bucket with access points. CloudFormation provisions `AWS::S3::AccessPoint`, and under `AUTH=true` each operation needs its `s3:` action. Contributed by @fabio-andre-rodrigues.
+- **S3 Object Lambda** — S3 Control `Create`/`Get`/`List`/`DeleteAccessPointForObjectLambda`, `Get`/`PutAccessPointConfigurationForObjectLambda` and the policy operations, with the supporting access point and Lambda in the same account and region. `GetObject` through an Object Lambda ARN or `--ol-s3` alias invokes the Lambda with the documented `getObjectContext` (a presigned `inputS3Url` through the supporting access point, `outputRoute`, `outputToken`) and returns what it writes with `WriteGetObjectResponse`. `HeadObject`, `ListObjects` and `ListObjectsV2` transformations return the Lambda's JSON result; operations without a transformation pass through; `Range` and `partNumber` need `AllowedFeatures`; Lambda failures map to `LambdaRuntimeError`, `LambdaResponseNotReceived`, `LambdaTimeout` and `LambdaNotFound`. CloudFormation provisions `AWS::S3ObjectLambda::AccessPoint` and `AccessPointPolicy`. AWS no longer onboards new Object Lambda customers, so the data plane follows the S3 user guide. Contributed by @fabio-andre-rodrigues.
+- **Lambda — `AWS_DISABLE_HOST_PREFIX_INJECTION=true` by default** — Lambda environments set it unless the function does, so boto3 in a handler reaches `WriteGetObjectResponse` without the `<route>.<host>` prefix, which doesn't resolve locally. SDKs that ignore the variable need their host-prefix injection turned off in client config. Contributed by @fabio-andre-rodrigues.
+
## [1.5.28] — 2026-10-16
### Added
diff --git a/README.md b/README.md
index ab07016c..769ea37b 100644
--- a/README.md
+++ b/README.md
@@ -402,7 +402,7 @@ subnet = ec2.create_subnet(
| Service | Operations | Notes |
|---------|-----------|-------|
-| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation, CreateMultiRegionAccessPoint, DeleteMultiRegionAccessPoint, PutMultiRegionAccessPointPolicy, DescribeMultiRegionAccessPointOperation, GetMultiRegionAccessPoint, GetMultiRegionAccessPointPolicy, ListMultiRegionAccessPoints, GetMultiRegionAccessPointRoutes, SubmitMultiRegionAccessPointRoutes | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete, and on annotation writes under `AUTH=true` (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); requests signed for another region than the bucket's home get `301 PermanentRedirect` with `x-amz-bucket-region`, and `CreateBucket` applies the location-constraint rules; Multi-Region Access Points are managed through S3 Control (create, delete, get, list, policy, routes) or CloudFormation (`AWS::S3::MultiRegionAccessPoint`), and `<alias>.accesspoint.s3-global.amazonaws.com` serves the active member homed in `MINISTACK_REGION` (traffic dials fail over) through the regular S3 path |
+| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication, GetObjectTagging, PutObjectTagging, DeleteObjectTagging, PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation, CreateMultiRegionAccessPoint, DeleteMultiRegionAccessPoint, PutMultiRegionAccessPointPolicy, DescribeMultiRegionAccessPointOperation, GetMultiRegionAccessPoint, GetMultiRegionAccessPointPolicy, ListMultiRegionAccessPoints, GetMultiRegionAccessPointRoutes, SubmitMultiRegionAccessPointRoutes, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, PutAccessPointPolicy, GetAccessPointPolicy, DeleteAccessPointPolicy, CreateAccessPointForObjectLambda, GetAccessPointForObjectLambda, ListAccessPointsForObjectLambda, DeleteAccessPointForObjectLambda, GetAccessPointConfigurationForObjectLambda, PutAccessPointConfigurationForObjectLambda, PutAccessPointPolicyForObjectLambda, GetAccessPointPolicyForObjectLambda, DeleteAccessPointPolicyForObjectLambda, WriteGetObjectResponse | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete, and on annotation writes under `AUTH=true` (governance mode yields to `x-amz-bypass-governance-retention`); object annotations are per version (up to 1,000, 1 byte–1 MiB each), carried by `CopyObject` and removed with their version; object tags are versioned (`?tagging&versionId=…` reads, writes, and deletes the per-version tag set); requests signed for another region than the bucket's home get `301 PermanentRedirect` with `x-amz-bucket-region`, and `CreateBucket` applies the location-constraint rules; Multi-Region Access Points are managed through S3 Control (create, delete, get, list, policy, routes) or CloudFormation (`AWS::S3::MultiRegionAccessPoint`), and `<alias>.accesspoint.s3-global.amazonaws.com` serves the active member homed in `MINISTACK_REGION` (traffic dials fail over) through the regular S3 path; S3 Access Points (S3 Control, ARN host and `-s3alias` alias, `AWS::S3::AccessPoint`) and S3 Object Lambda (S3 Control, `GetObject`/`HeadObject`/`ListObjects` transformations through a Lambda calling `WriteGetObjectResponse`, `AWS::S3ObjectLambda::*`) |
| **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support, with moved messages carrying `DeadLetterQueueSourceArn`; messages expire after `MessageRetentionPeriod`; the batch actions apply AWS's request-level validation (empty batch, more than ten entries, repeated or malformed entry ids) before any entry is processed |
| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, AddPermission, RemovePermission, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); subscription filter policies on message attributes or, with `FilterPolicyScope` `MessageBody`, the message body (`prefix`, `suffix`, `equals-ignore-case`, `wildcard`, `anything-but`, `numeric`, `cidr`, `exists`); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` |
| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on every write that changes an item, respects `StreamViewType`; `Query` and `Scan` pages stop at 1 MB of data read; GSIs accept multi-attribute keys (up to four `HASH` and four `RANGE` attributes); Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE; global tables (version 2019.11.21) through `UpdateTable` `ReplicaUpdates`: a replica is a copy of the table in the other region, and writes replicate between them |
diff --git a/ministack/app.py b/ministack/app.py
index a4d686da..30d9ac33 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -24,7 +24,7 @@ import sys
import tempfile
import time
import uuid
-from urllib.parse import parse_qs, quote, unquote
+from urllib.parse import parse_qs, quote, unquote, urlencode
_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", "4566")
@@ -1573,27 +1573,54 @@ def _s3control_mrap_arn(s3, path: str) -> str:
return f"arn:aws:s3::{account}:accesspoint/{record['Alias'] if record else '*'}"
+def _s3control_access_point_arn(s3, path: str) -> str:
+ """IAM resource for an access point request: its regional ARN, or the
+ account's wildcard for ListAccessPoints."""
+ name = unquote(path).rstrip("/").removeprefix("/v20180820/accesspoint").strip("/").removesuffix("/policy")
+ return s3.access_point_arn(name or "*")
+
+
+def _s3control_object_lambda_arn(s3, path: str) -> str:
+ """IAM resource for an Object Lambda Access Point request."""
+ name = unquote(path).rstrip("/").removeprefix("/v20180820/accesspointforobjectlambda").strip("/")
+ return s3.object_lambda_arn(name.split("/", 1)[0] or "*")
+
+
async def _handle_s3_control_request(path: str, method: str, body: bytes, query_params: dict, request_id: str,
headers: dict | None = None):
"""Handle S3 Control operations addressed via the /v20180820 path prefix."""
if not path.startswith(_S3_CONTROL_PREFIX):
return None
- if path.startswith(_S3_CONTROL_MRAP_PREFIXES) or path.rstrip("/") == "/v20180820/mrap/instances":
- s3 = _get_module("s3")
+ is_mrap = path.startswith(_S3_CONTROL_MRAP_PREFIXES) or path.rstrip("/") == "/v20180820/mrap/instances"
+ s3 = _get_module("s3")
+ is_object_lambda = s3.is_object_lambda_control_path(path)
+ if is_mrap or is_object_lambda or s3.is_access_point_control_path(path):
headers = headers or {}
if AUTH:
from ministack.core.iam_actions import s3control_action
action = s3control_action(method, path)
if action:
+ if is_mrap:
+ resource = _s3control_mrap_arn(s3, path)
+ elif is_object_lambda:
+ resource = _s3control_object_lambda_arn(s3, path)
+ else:
+ resource = _s3control_access_point_arn(s3, path)
denied = _enforce_data_plane("s3", action, headers, query_params, request_id,
- resource_arn=_s3control_mrap_arn(s3, path))
+ resource_arn=resource)
if denied:
return denied
+ if is_mrap:
+ handler = s3.handle_mrap_control
+ elif is_object_lambda:
+ handler = s3.handle_object_lambda_control
+ else:
+ handler = s3.handle_access_point_control
status, resp_headers, resp_body = (
(AUTH and s3.s3control_account_error(headers))
- or s3.handle_mrap_control(method, path, headers, body, query_params)
+ or handler(method, path, headers, body, query_params)
)
return status, {**resp_headers, "x-amzn-requestid": request_id}, resp_body
@@ -2102,6 +2129,7 @@ async def _handle_alb_request(host: str, path: str, method: str, headers: dict,
return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()
+_ACCESS_POINT_HOST_RE = re.compile(r"^(?P<name>[a-z0-9-]+)-(?P<account>\d{12})$")
_MRAP_HOST_RE = re.compile(
r"^([a-z0-9]+\.mrap)\.accesspoint\.s3-global\.amazonaws\.com$", re.IGNORECASE
)
@@ -2156,6 +2184,39 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
bucket = _extract_s3_vhost_bucket(host)
if not bucket or _S3_VHOST_EXCLUDE_RE.search(host) or bucket in _NON_S3_VHOST_NAMES:
return None
+ # An access point ARN is addressed as `<name>-<account>.<host>`, signed `s3`.
+ access_point_region = None
+ ap_match = _ACCESS_POINT_HOST_RE.match(bucket)
+ s3 = _get_module("s3")
+ if ap_match and s3.signed_service(headers, query_params) == "s3-object-lambda":
+ # An Object Lambda Access Point ARN, same host shape, signed for Object Lambda.
+ from ministack.services import s3_object_lambda
+
+ record, olap_region, olap_error = s3_object_lambda.resolve_host(
+ ap_match.group("name"), ap_match.group("account"), headers, query_params)
+ if olap_error:
+ return olap_error
+ if AUTH:
+ from ministack.core.iam_actions import s3_object_lambda_action
+
+ action = s3_object_lambda_action(method, path.lstrip("/"), query_params)
+ if action:
+ denied = _enforce_data_plane("s3-object-lambda", action, headers, query_params, "",
+ resource_arn=s3.object_lambda_arn(record["Name"], region=olap_region))
+ if denied:
+ return denied
+ query = urlencode(query_params, doseq=True)
+ url = f"http://{host}{path}" + (f"?{query}" if query else "")
+ return await s3_object_lambda.handle_request(record, olap_region, method, path.lstrip("/"), headers, body,
+ query_params, url)
+ if ap_match and s3.signed_service(headers, query_params) == "s3":
+ target = s3.resolve_access_point_host(ap_match.group("name"), ap_match.group("account"),
+ s3._signed_region(headers, query_params))
+ if target is not None:
+ ap_bucket, ap_region, ap_error = target
+ if ap_error:
+ return ap_error
+ bucket, access_point_region = ap_bucket, ap_region
# CloudFront KVS data-plane clients (boto3 cloudfront-keyvaluestore with
# inject_host_prefix=False) hit ministack with host=localhost and path
# prefixed by /key-value-stores/. Host-name exclusion above doesn't fire,
@@ -2209,7 +2270,8 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
# Pass the original (pre-rewrite) URI as signed_path so a presigned
# virtual-hosted URL, which signed the canonical URI without the bucket,
# verifies against what the client actually signed.
- return await _get_module("s3").handle_request(method, vhost_path, headers, body, query_params, signed_path=path)
+ return await _get_module("s3").handle_request(method, vhost_path, headers, body, query_params, signed_path=path,
+ access_point_region=access_point_region)
except Exception as e:
logger.exception("Error handling virtual-hosted S3 request: %s", e)
from xml.sax.saxutils import escape as _xml_esc
@@ -2314,6 +2376,16 @@ async def _handle_special_data_plane_request(
client_ip: str = "127.0.0.1",
):
"""Handle special-case service entrypoints before the generic router."""
+ # S3 Object Lambda's WriteGetObjectResponse, on any host: its modeled host
+ # prefix `<route>.<host>` doesn't resolve locally, so the route header decides.
+ if method == "POST" and path == "/WriteGetObjectResponse" and headers.get("x-amz-request-route"):
+ from ministack.services import s3_object_lambda
+
+ denied = _enforce_data_plane("s3-object-lambda", "s3-object-lambda:WriteGetObjectResponse",
+ headers, query_params, request_id)
+ if denied:
+ return denied
+ return s3_object_lambda.write_get_object_response(headers, body)
# Iceberg REST catalog — /iceberg/* is served by two catalogs that share the
# prefix: the Glue Data Catalog (the lakehouse a Glue job and Firehose both
# write) and S3 Tables. Dispatch between them so a table one writer commits,
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index c153246c..c5ba6c00 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -273,11 +273,44 @@ _S3CONTROL_MRAP_ASYNC_ACTIONS = {
}
+_S3CONTROL_ACCESS_POINT_ACTIONS = {
+ ("PUT", False): "s3:CreateAccessPoint",
+ ("GET", False): "s3:GetAccessPoint",
+ ("DELETE", False): "s3:DeleteAccessPoint",
+ ("PUT", True): "s3:PutAccessPointPolicy",
+ ("GET", True): "s3:GetAccessPointPolicy",
+ ("DELETE", True): "s3:DeleteAccessPointPolicy",
+}
+
+
+_S3CONTROL_OBJECT_LAMBDA_ACTIONS = {
+ ("PUT", ""): "s3:CreateAccessPointForObjectLambda",
+ ("GET", ""): "s3:GetAccessPointForObjectLambda",
+ ("DELETE", ""): "s3:DeleteAccessPointForObjectLambda",
+ ("PUT", "configuration"): "s3:PutAccessPointConfigurationForObjectLambda",
+ ("GET", "configuration"): "s3:GetAccessPointConfigurationForObjectLambda",
+ ("PUT", "policy"): "s3:PutAccessPointPolicyForObjectLambda",
+ ("GET", "policy"): "s3:GetAccessPointPolicyForObjectLambda",
+ ("DELETE", "policy"): "s3:DeleteAccessPointPolicyForObjectLambda",
+}
+
+
def s3control_action(method: str, path: str) -> str | None:
- """IAM action for an S3 Control Multi-Region Access Point request, or None."""
+ """IAM action for an S3 Control Multi-Region Access Point or access point request, or None."""
from urllib.parse import unquote
path = unquote(path).rstrip("/")
+ object_lambda = "/v20180820/accesspointforobjectlambda"
+ if path == object_lambda:
+ return "s3:ListAccessPointsForObjectLambda" if method == "GET" else None
+ if path.startswith(object_lambda + "/"):
+ sub = path[len(object_lambda) + 1:].partition("/")[2]
+ return _S3CONTROL_OBJECT_LAMBDA_ACTIONS.get((method, sub))
+ access_points = "/v20180820/accesspoint"
+ if path == access_points:
+ return "s3:ListAccessPoints" if method == "GET" else None
+ if path.startswith(access_points + "/"):
+ return _S3CONTROL_ACCESS_POINT_ACTIONS.get((method, path.endswith("/policy")))
async_prefix = "/v20180820/async-requests/mrap/"
instances = "/v20180820/mrap/instances"
if path.startswith(async_prefix):
@@ -297,6 +330,13 @@ def s3control_action(method: str, path: str) -> str | None:
return None
+def s3_object_lambda_action(method: str, key: str, query_params: dict) -> str | None:
+ """The ``s3-object-lambda:`` action for a request through an Object Lambda
+ Access Point: the S3 action the same request names, in that service."""
+ action = _s3_action(method, f"/olap/{key}" if key else "/olap", query_params or {})
+ return f"s3-object-lambda:{action}" if action else None
+
+
def _s3_action(method: str, path: str, query_params: dict) -> str | None:
parts = [p for p in path.split("/") if p]
depth = min(len(parts), 2)
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 6c645c65..7b2946f0 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -26,6 +26,12 @@ from ministack.core.responses import _12_DIGIT_RE
logger = logging.getLogger("lambda_runtime")
+# S3 Object Lambda handlers call WriteGetObjectResponse, whose modeled host
+# prefix (`<route>.<host>`) doesn't resolve against MiniStack's endpoint.
+# botocore reads this variable and skips the prefix; MiniStack routes the call
+# by its x-amz-request-route header instead. A function's own value wins.
+HOST_PREFIX_ENV = "AWS_DISABLE_HOST_PREFIX_INJECTION"
+
_RESERVED_RUNTIME_ENV_VARS = {
"AWS_REGION",
"AWS_DEFAULT_REGION",
@@ -1192,6 +1198,7 @@ class Worker:
spawn_env["AWS_ENDPOINT_URL"] = f"http://127.0.0.1:{port}"
if "LOCALSTACK_HOSTNAME" in os.environ:
spawn_env["LOCALSTACK_HOSTNAME"] = os.environ["LOCALSTACK_HOSTNAME"]
+ spawn_env.setdefault(HOST_PREFIX_ENV, "true")
spawn_env.setdefault("LAMBDA_TASK_ROOT", code_dir)
spawn_env.setdefault("AWS_LAMBDA_FUNCTION_NAME", self.config.get("FunctionName", ""))
spawn_env.setdefault("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", str(self.config.get("MemorySize", 128)))
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 98adf366..b181bc20 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -711,6 +711,7 @@ _CUSTOM_NAME_REPLACEMENT = {
),
},
"AWS::IoT::DomainConfiguration": {"name": "DomainConfigurationName"},
+ "AWS::KinesisAnalyticsV2::Application": {"name": "ApplicationName"},
# BackupVaultName is required, so every vault is custom-named. Measured on
# an account: adding EncryptionKeyArn fails with the refusal sentence.
"AWS::Backup::BackupVault": {
@@ -733,6 +734,11 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "LaunchConfigurationName",
"requires_replacement": lambda old, new: old != new,
},
+ "AWS::S3::AccessPoint": {
+ "name": "Name",
+ "requires_replacement": lambda old, new: any(
+ old.get(p) != new.get(p) for p in ("Bucket", "BucketAccountId", "Name", "VpcConfiguration")),
+ },
"AWS::IAM::InstanceProfile": {
"name": "InstanceProfileName",
"requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
@@ -1436,6 +1442,127 @@ def _s3_mrap_delete(physical_id, props):
_s3.delete_mrap(physical_id)
+def _s3_access_point_policy(props) -> str | None:
+ policy = props.get("Policy")
+ if policy is None:
+ return None
+ return policy if isinstance(policy, str) else json.dumps(policy)
+
+
+def _s3_access_point_attrs(record: dict) -> dict:
+ return {"Arn": _s3.access_point_arn(record["Name"]), "Alias": record["Alias"],
+ "Name": record["Name"], "NetworkOrigin": record["NetworkOrigin"]}
+
+
+def _s3_access_point_create(logical_id, props, stack_name):
+ """Provision an AWS::S3::AccessPoint through the same checks as the S3
+ Control API. The physical id (and Ref) is the name."""
+ name = props.get("Name") or _physical_name(stack_name, logical_id, lowercase=True, max_len=50)
+ try:
+ record = _s3.create_access_point(
+ name, props.get("Bucket", ""), props.get("VpcConfiguration"),
+ props.get("PublicAccessBlockConfiguration"), _s3_access_point_policy(props),
+ {t["Key"]: t["Value"] for t in props.get("Tags") or []},
+ )
+ except _s3.AccessPointError as exc:
+ raise ValueError(f"{exc.code}: {exc.message}") from exc
+ return name, _s3_access_point_attrs(record)
+
+
+def _s3_access_point_update(physical_id, old_props, new_props, stack_name):
+ """Policy, PublicAccessBlockConfiguration and Tags update in place."""
+ record = _s3._access_points.get(physical_id)
+ if record is None:
+ return _s3_access_point_create(physical_id, new_props, stack_name)
+ record["Policy"] = _s3_access_point_policy(new_props)
+ pab = {field: True for field in _s3._PAB_FIELDS}
+ pab.update({k: bool(v) for k, v in (new_props.get("PublicAccessBlockConfiguration") or {}).items()
+ if k in _s3._PAB_FIELDS})
+ record["PublicAccessBlockConfiguration"] = pab
+ record["Tags"] = {t["Key"]: t["Value"] for t in new_props.get("Tags") or []}
+ return physical_id, _s3_access_point_attrs(record)
+
+
+def _s3_access_point_delete(physical_id, props):
+ _s3._access_points.pop(physical_id, None)
+
+
+def _object_lambda_configuration(props) -> dict:
+ """``ObjectLambdaConfiguration`` in the S3 Control record's shape."""
+ config = props.get("ObjectLambdaConfiguration") or {}
+ transformations = []
+ for tc in config.get("TransformationConfigurations") or []:
+ aws_lambda = (tc.get("ContentTransformation") or {}).get("AwsLambda") or {}
+ transformation = {"Actions": list(tc.get("Actions") or []), "FunctionArn": aws_lambda.get("FunctionArn", "")}
+ if "FunctionPayload" in aws_lambda:
+ transformation["FunctionPayload"] = aws_lambda["FunctionPayload"]
+ transformations.append(transformation)
+ return {
+ "SupportingAccessPoint": config.get("SupportingAccessPoint", ""),
+ "CloudWatchMetricsEnabled": bool(config.get("CloudWatchMetricsEnabled", False)),
+ "AllowedFeatures": list(config.get("AllowedFeatures") or []),
+ "TransformationConfigurations": transformations,
+ }
+
+
+def _object_lambda_attrs(record: dict) -> dict:
+ return {"Arn": _s3.object_lambda_arn(record["Name"]), "Alias.Value": record["Alias"]["Value"],
+ "Alias.Status": record["Alias"]["Status"], "CreationDate": record["CreationDate"]}
+
+
+def _object_lambda_create(logical_id, props, stack_name):
+ """AWS::S3ObjectLambda::AccessPoint, through the S3 Control checks."""
+ name = props.get("Name") or _physical_name(stack_name, logical_id, lowercase=True, max_len=45)
+ try:
+ record = _s3.create_object_lambda_access_point(name, _object_lambda_configuration(props))
+ except _s3.AccessPointError as exc:
+ raise ValueError(f"{exc.code}: {exc.message}") from exc
+ return name, _object_lambda_attrs(record)
+
+
+def _object_lambda_update(physical_id, old_props, new_props, stack_name):
+ """Name replaces the access point; the configuration updates in place."""
+ record = _s3._object_lambda_access_points.get(physical_id)
+ if record is None:
+ return _object_lambda_create(physical_id, new_props, stack_name)
+ config = _object_lambda_configuration(new_props)
+ try:
+ _s3.validate_object_lambda_configuration(config)
+ except _s3.AccessPointError as exc:
+ raise ValueError(f"{exc.code}: {exc.message}") from exc
+ record["Configuration"] = config
+ return physical_id, _object_lambda_attrs(record)
+
+
+def _object_lambda_delete(physical_id, props):
+ _s3._object_lambda_access_points.pop(physical_id, None)
+
+
+def _object_lambda_policy_create(logical_id, props, stack_name):
+ """AWS::S3ObjectLambda::AccessPointPolicy; its physical id is the access point name."""
+ name = props.get("ObjectLambdaAccessPoint", "")
+ record = _s3._object_lambda_access_points.get(name)
+ if record is None:
+ raise ValueError(f"NoSuchAccessPoint: The specified accesspoint does not exist: {name}")
+ document = props.get("PolicyDocument")
+ record["Policy"] = document if isinstance(document, str) else json.dumps(document)
+ return name, {}
+
+
+def _object_lambda_policy_update(physical_id, old_props, new_props, stack_name):
+ if new_props.get("ObjectLambdaAccessPoint") != old_props.get("ObjectLambdaAccessPoint"):
+ result = _object_lambda_policy_create(physical_id, new_props, stack_name)
+ _delete_predecessor(_object_lambda_policy_delete, physical_id, old_props)
+ return result
+ return _object_lambda_policy_create(physical_id, new_props, stack_name)
+
+
+def _object_lambda_policy_delete(physical_id, props):
+ record = _s3._object_lambda_access_points.get(physical_id)
+ if record is not None:
+ record["Policy"] = None
+
+
def _s3_attrs(name):
return {
"Arn": f"arn:aws:s3:::{name}",
@@ -3468,15 +3595,6 @@ def _kda_application_create(logical_id, props, stack_name):
def _kda_application_update(physical_id, old_props, new_props, stack_name, logical_id=None):
- """ApplicationName replaces; the rest updates in place."""
- replaced = _rename_replacement(
- physical_id, old_props, new_props, stack_name, logical_id,
- new_props.get("ApplicationName") or physical_id,
- physical_id if physical_id in _kda._applications else None,
- _kda_application_create, _kda_application_delete,
- )
- if replaced is not None:
- return replaced
_kda.replace_from_template(physical_id, new_props)
arn = _kda._applications[physical_id]["ApplicationARN"]
tags = _tag_map(new_props.get("Tags"))
@@ -3505,11 +3623,14 @@ def _kda_logging_option_create(logical_id, props, stack_name):
def _kda_logging_option_update(physical_id, old_props, new_props, stack_name, logical_id=None):
- """Both properties are create-only, so any change replaces the option."""
- if old_props == new_props:
- return physical_id, {}
- _kda_logging_option_delete(physical_id, old_props)
- return _kda_logging_option_create(logical_id or physical_id, new_props, stack_name)
+ stream = (new_props.get("CloudWatchLoggingOption") or {}).get("LogStreamARN")
+ if stream != (old_props.get("CloudWatchLoggingOption") or {}).get("LogStreamARN"):
+ _kda_call(_kda.update_application, {
+ "ApplicationName": new_props.get("ApplicationName"),
+ "CloudWatchLoggingOptionUpdates": [
+ {"CloudWatchLoggingOptionId": physical_id, "LogStreamARNUpdate": stream}],
+ }, "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption")
+ return physical_id, {}
def _kda_logging_option_delete(physical_id, props):
@@ -3533,13 +3654,7 @@ def _cwlogs_stream_create(logical_id, props, stack_name):
def _cwlogs_stream_update(physical_id, old_props, new_props, stack_name, logical_id=None):
- """LogGroupName and LogStreamName are create-only: a change replaces the stream."""
- if (old_props.get("LogGroupName") == new_props.get("LogGroupName")
- and (new_props.get("LogStreamName") or physical_id) == physical_id):
- return physical_id, {}
- created = _cwlogs_stream_create(logical_id or physical_id, new_props, stack_name)
- _delete_predecessor(_cwlogs_stream_delete, physical_id, old_props)
- return created
+ return physical_id, {}
def _cwlogs_stream_delete(physical_id, props):
@@ -14503,6 +14618,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::Backup::BackupVault": ("BackupVaultName", "EncryptionKeyArn"),
"AWS::Location::Tracker": ("TrackerName", "KmsKeyId"),
"AWS::S3::MultiRegionAccessPoint": ("Name", "PublicAccessBlockConfiguration", "Regions"),
+ "AWS::S3::AccessPoint": ("Bucket", "BucketAccountId", "Name", "VpcConfiguration"),
+ "AWS::S3ObjectLambda::AccessPoint": ("Name",),
"AWS::AutoScaling::LaunchConfiguration": (
"AssociatePublicIpAddress", "BlockDeviceMappings", "ClassicLinkVPCId",
"ClassicLinkVPCSecurityGroups", "EbsOptimized", "IamInstanceProfile", "ImageId",
@@ -14579,6 +14696,9 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"FileSystemId", "IpAddress", "IpAddressType", "Ipv6Address", "SubnetId",
),
"AWS::EFS::AccessPoint": ("ClientToken", "FileSystemId", "PosixUser", "RootDirectory"),
+ "AWS::KinesisAnalyticsV2::Application": ("ApplicationName", "ApplicationMode"),
+ "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption": ("ApplicationName",),
+ "AWS::Logs::LogStream": ("LogGroupName", "LogStreamName"),
}
@@ -14625,6 +14745,21 @@ _RESOURCE_HANDLERS = {
"create": _s3_mrap_create,
"delete": _s3_mrap_delete,
},
+ "AWS::S3::AccessPoint": {
+ "create": _s3_access_point_create,
+ "update": _s3_access_point_update,
+ "delete": _s3_access_point_delete,
+ },
+ "AWS::S3ObjectLambda::AccessPoint": {
+ "create": _object_lambda_create,
+ "update": _object_lambda_update,
+ "delete": _object_lambda_delete,
+ },
+ "AWS::S3ObjectLambda::AccessPointPolicy": {
+ "create": _object_lambda_policy_create,
+ "update": _object_lambda_policy_update,
+ "delete": _object_lambda_policy_delete,
+ },
"AWS::S3::BucketPolicy": {
"create": _s3_bucket_policy_create,
"update": _s3_bucket_policy_update,
diff --git a/ministack/services/kinesisanalyticsv2.py b/ministack/services/kinesisanalyticsv2.py
index d27387f8..fb3ae2aa 100644
--- a/ministack/services/kinesisanalyticsv2.py
+++ b/ministack/services/kinesisanalyticsv2.py
@@ -1,30 +1,6 @@
# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
-"""
-Amazon Managed Service for Apache Flink (kinesisanalyticsv2) control plane.
-JSON 1.1 via X-Amz-Target (prefix: KinesisAnalytics_20180523).
-
-Verified against botocore kinesisanalyticsv2/2018-05-23/service-2.json:
- metadata.targetPrefix = "KinesisAnalytics_20180523"
- metadata.signingName = "kinesisanalytics"
- metadata.protocol = "json", jsonVersion "1.1"
-
-Supports the operations a CDK deploy and a lifecycle script use:
- CreateApplication, DescribeApplication, UpdateApplication, DeleteApplication,
- StartApplication, StopApplication,
- CreateApplicationSnapshot, ListApplicationSnapshots,
- DescribeApplicationSnapshot, DeleteApplicationSnapshot,
- AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption,
- TagResource, UntagResource, ListTagsForResource.
-
-Running the job is the job of the optional data plane module
-(``kinesisanalyticsv2_flink``), which starts Flink containers when Docker is
-available. Without it, applications move through the same statuses and keep
-snapshot records, but no job runs.
-
-Records keep the request shape of ApplicationConfiguration; DescribeApplication
-renders the Description shape from it. Stores are per account and region.
-"""
+"""Amazon Managed Service for Apache Flink (kinesisanalyticsv2) control plane; jobs run in kinesisanalyticsv2_flink."""
import base64
import contextvars
@@ -43,13 +19,10 @@ from ministack.core.responses import (
json_response,
new_uuid,
)
+from ministack.services import kinesisanalyticsv2_flink as _dataplane
logger = logging.getLogger("kinesisanalyticsv2")
-try: # The Docker-backed data plane is optional.
- from ministack.services import kinesisanalyticsv2_flink as _dataplane
-except ImportError: # pragma: no cover - present once the data plane lands
- _dataplane = None
_applications = AccountRegionScopedDict() # ApplicationName -> record
_snapshots = AccountRegionScopedDict() # ApplicationName -> {SnapshotName -> snapshot}
@@ -100,11 +73,10 @@ def load_persisted_state(data):
def reset():
- if _dataplane is not None:
- try:
- _dataplane.reset()
- except Exception: # never let cleanup break a reset
- logger.exception("kinesisanalyticsv2 data plane reset failed")
+ try:
+ _dataplane.reset()
+ except Exception:
+ logger.exception("kinesisanalyticsv2 data plane reset failed")
_applications.clear()
_snapshots.clear()
_tags.clear()
@@ -133,7 +105,7 @@ def _new_token():
def _bump_version(record):
record["ApplicationVersionId"] += 1
record["ConditionalToken"] = _new_token()
- record["LastUpdateTimestamp"] = time.time()
+ record["LastUpdateTimestamp"] = int(time.time())
def _check_concurrency(record, data):
@@ -313,7 +285,7 @@ def create_application(data):
"(SQL and Studio applications) is not implemented.")
if name in _applications:
return _error("ResourceInUseException", f"Application '{name}' already exists.")
- now = time.time()
+ now = int(time.time())
record = {
"ApplicationARN": _arn(name),
"ApplicationName": name,
@@ -444,7 +416,7 @@ def delete_application(data, check_timestamp=True):
if record["ApplicationStatus"] in _TRANSITIONAL:
return _error("ResourceInUseException",
f"Application {name} is in {record['ApplicationStatus']} status and cannot be deleted.")
- if _dataplane is not None and record.get("_driven"):
+ if record.get("_driven"):
_in_background(_dataplane_call, "delete", _dataplane_view(record))
del _applications[name]
_snapshots.pop(name, None)
@@ -503,7 +475,7 @@ def _restore_path(record, restore):
def _runs_jobs(record):
"""Docker is available and the data plane has an image for the runtime."""
- return (_dataplane is not None and _dataplane.available()
+ return (_dataplane.available()
and _dataplane.supports(record["RuntimeEnvironment"]))
@@ -616,7 +588,7 @@ def _add_snapshot(record, snapshot_name, savepoint_path, status="READY"):
"SnapshotName": snapshot_name,
"SnapshotStatus": status,
"ApplicationVersionId": record["ApplicationVersionId"],
- "SnapshotCreationTimestamp": time.time(),
+ "SnapshotCreationTimestamp": int(time.time()),
"RuntimeEnvironment": record["RuntimeEnvironment"],
"ApplicationEncryptionConfigurationDescription": _encryption_description(record),
}
@@ -834,6 +806,5 @@ async def handle_request(method, path, headers, body, query_params):
return _error("SerializationException", "Invalid JSON")
handler = _HANDLERS.get(action)
if handler is None:
- return _error("UnsupportedOperationException",
- f"MiniStack does not implement kinesisanalyticsv2 {action or 'request'}.")
+ return _error("UnknownOperationException", f"Unknown operation: {action}")
return handler(data)
diff --git a/ministack/services/kinesisanalyticsv2_flink.py b/ministack/services/kinesisanalyticsv2_flink.py
index d90b8d27..3c208565 100644
--- a/ministack/services/kinesisanalyticsv2_flink.py
+++ b/ministack/services/kinesisanalyticsv2_flink.py
@@ -1,41 +1,7 @@
# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
-"""
-Managed Service for Apache Flink data plane: Docker-backed job execution.
-
-The control plane (``kinesisanalyticsv2``) owns application records and status;
-this module owns the containers. When Docker is available, starting an
-application launches a JobManager and a TaskManager from the official Apache
-Flink image for the application's runtime, fetches the application jar from
-MiniStack S3 and submits it through the Flink REST API. Stop, snapshot and
-restore map to Flink savepoints.
-
-Interface used by the control plane (all synchronous; none raise):
-
-- ``available()``: Docker is reachable.
-- ``supports(runtime)``: this data plane can run jobs for the runtime
- (``FLINK-1_19`` and ``FLINK-1_20``); other runtimes stay control plane only.
-- ``start(app, savepoint_path, on_status)``: launch the cluster and submit the
- job in a background thread; ``on_status("RUNNING")`` or
- ``on_status("FAILED", message)`` reports the outcome.
-- ``snapshot(app, snapshot_name)``: take a savepoint; returns its path, or
- ``None`` if it failed.
-- ``stop(app, force, take_snapshot)``: stop the job and remove the containers;
- returns the savepoint path when one was taken.
-- ``delete(app)``: remove containers, network and savepoint volume.
-- ``reset()``: remove everything this MiniStack instance created.
-
-``app`` is the stored record in the DescribeApplication shape plus
-``AccountId`` and ``Region``.
-
-Savepoints live in a per-application Docker volume mounted at the same path in
-both containers, so they survive a stop (which removes the containers) and a
-MiniStack restart, and need no S3 filesystem configuration.
-
-Runtime images match the Flink patch version and Java version AWS documents for
-each runtime (Managed Flink developer guide, "Amazon Managed Service for Apache
-Flink 1.19" and "1.20" pages: Flink 1.19.1 and 1.20.5, Java 11).
-"""
+"""Managed Service for Apache Flink data plane: each application runs as a JobManager and a TaskManager
+from the official Flink image, and snapshots are Flink savepoints in a per-application volume."""
import hashlib
import io
@@ -68,15 +34,8 @@ _RUNTIME_IMAGES = {
_LABEL = "kinesisanalyticsv2"
_REST_PORT = 8081
_SAVEPOINT_DIR = "/flink-savepoints"
-# Path the aws-kinesisanalytics-runtime library reads runtime properties from
-# (com.amazonaws:aws-kinesisanalytics-runtime 1.2.0, config.properties).
_PROPERTIES_PATH = "/etc/flink/application_properties.json"
-# Jars added to every cluster's /opt/flink/lib, like the libraries Managed Flink
-# provides on its classpath. Managed Flink provides
-# com.amazonaws:aws-kinesisanalytics-runtime ("Provided dependencies",
-# Managed Flink developer guide, best practices), and AWS documents building
-# jobs with it in provided scope, so it must come from here: mount a
-# directory holding it. Same pattern as the RDS IAM plugin's artifact root.
+# Jars mounted here join every cluster's classpath, as Managed Flink provides aws-kinesisanalytics-runtime.
_FLINK_LIB_DIR = "/opt/ministack/flink-lib"
# UID of the ``flink`` user in the official image; the savepoint volume must be
# writable by it.
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 09da5345..11534f63 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -54,6 +54,7 @@ from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.concurrency import esm_wake, run_reentrant, spawn_background
from ministack.core.lambda_runtime import (
DURABLE_ENV_VARS,
+ HOST_PREFIX_ENV,
INVOKE_DEPTH_BOOTSTRAP,
INVOKE_DEPTH_ENV,
INVOKE_DEPTH_HEADER,
@@ -4498,6 +4499,7 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
# /opt/bin) — no _LAMBDA_LAYERS_DIRS shim here (the official RIE bootstrap
# ignores it anyway).
container_env.update(env_vars)
+ container_env.setdefault(HOST_PREFIX_ENV, "true")
# Per-invocation durable-execution overlay (no-op when the call isn't
# inside a durable function).
container_env.update(_durable_env_overlay())
@@ -5391,6 +5393,7 @@ def _provided_worker_env(config: dict, code_dir: str, port: int) -> dict:
})
proc_env.update(execution_credentials(config))
proc_env.update(env_vars)
+ proc_env.setdefault(HOST_PREFIX_ENV, "true")
proc_env.update(_durable_env_overlay())
# Override AWS_ENDPOINT_URL *after* function env vars so Lambda binaries
# always call back to this MiniStack instance.
@@ -5736,6 +5739,7 @@ def _execute_function_local(func: dict, event: dict, request_id: str) -> dict:
if endpoint:
env["AWS_ENDPOINT_URL"] = endpoint
env.update(env_vars)
+ env.setdefault(HOST_PREFIX_ENV, "true")
env.update(_durable_env_overlay())
# X-Ray active tracing — one-shot subprocess, env is per-invocation
# so a fresh trace ID per call is safe (unlike the pooled RIE).
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 482cb89f..b624a938 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -63,6 +63,7 @@ from ministack.core.iam_evaluator import (
resolve_credential,
)
from ministack.core.responses import (
+ AccountRegionScopedDict,
AccountScopedDict,
get_account_id,
get_region,
@@ -106,6 +107,130 @@ _bucket_cors = AccountScopedDict()
_mraps = AccountScopedDict()
# S3 Control async request token -> the AsyncOperation DescribeMultiRegionAccessPointOperation reports.
_mrap_operations = AccountScopedDict()
+# Regional access points, by name within an account and region:
+# {Name, Bucket, BucketAccountId, Alias, CreationDate, NetworkOrigin, VpcConfiguration,
+# PublicAccessBlockConfiguration, Policy, Tags}
+_access_points = AccountRegionScopedDict()
+
+# Object Lambda Access Points, by name within an account and region:
+# {Name, Alias: {Value, Status}, CreationDate, Configuration, Policy, PublicAccessBlockConfiguration}
+_object_lambda_access_points = AccountRegionScopedDict()
+# GetObject requests waiting on the Lambda's WriteGetObjectResponse, keyed by
+# (route, token). In flight only: never persisted, cleared on reset.
+_olap_requests: dict[tuple[str, str], dict] = {}
+_olap_requests_lock = threading.Lock()
+_OBJECT_LAMBDA_ALIAS_SUFFIX = "--ol-s3"
+
+
+def object_lambda_arn(name: str, account_id: str | None = None, region: str | None = None) -> str:
+ return f"arn:aws:s3-object-lambda:{region or get_region()}:{account_id or get_account_id()}:accesspoint/{name}"
+
+
+def new_object_lambda_alias(name: str, region: str) -> str:
+ """Shape of the documented example ``myolap-1a4n8yjrb3kda96f67zwrwiiuse1a--ol-s3``."""
+ alphabet = string.ascii_lowercase + string.digits
+ return f"{name[:20]}-{''.join(random.choices(alphabet, k=24))}{_region_code(region)}a{_OBJECT_LAMBDA_ALIAS_SUFFIX}"
+
+
+def resolve_object_lambda_alias(alias: str):
+ """``(account, region, record)`` for an Object Lambda alias in any tenant, or None."""
+ for (account, region, _name), record in list(_object_lambda_access_points._data.items()):
+ if (record.get("Alias") or {}).get("Value") == alias:
+ return account, region, record
+ return None
+
+
+_ACCESS_POINT_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])$")
+_OBJECT_LAMBDA_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{1,43}[a-z0-9])$")
+_COMPASS_CODES = {"northeast": "ne", "southeast": "se", "northwest": "nw", "southwest": "sw"}
+
+
+def _region_code(region: str) -> str:
+ """AWS's short region code in access point aliases: ``use1``, ``euw1``…"""
+ parts = region.split("-")
+ if len(parts) < 3:
+ return region.replace("-", "")
+ middle = "".join(_COMPASS_CODES.get(p, p[:1]) for p in parts[1:-1])
+ return f"{parts[0]}{middle}{parts[-1]}"
+
+
+def new_access_point_alias(name: str, region: str) -> str:
+ """The alias S3 mints for an access point (observed shape):
+ ``<first 20 chars of name>-<29 lowercase alnum><region code>b-s3alias``."""
+ alphabet = string.ascii_lowercase + string.digits
+ return f"{name[:20]}-{''.join(random.choices(alphabet, k=29))}{_region_code(region)}b-s3alias"
+
+
+def access_point_arn(name: str, account_id: str | None = None, region: str | None = None) -> str:
+ return f"arn:aws:s3:{region or get_region()}:{account_id or get_account_id()}:accesspoint/{name}"
+
+
+def resolve_access_point(name: str, account_id: str, region: str) -> dict | None:
+ return _access_points.get_scoped(account_id, region, name)
+
+
+def access_point_regions(name: str, account_id: str) -> list[str]:
+ """Regions in which an account has an access point of this name."""
+ return [region for (account, region, ap_name) in _access_points._data
+ if account == account_id and ap_name == name]
+
+
+def resolve_access_point_alias(alias: str):
+ """``(account, region, record)`` for an access point alias in any tenant, or None."""
+ for (account, region, _name), record in list(_access_points._data.items()):
+ if record.get("Alias") == alias:
+ return account, region, record
+ return None
+
+
+_ACCESS_POINT_ALIAS_SUFFIX = "-s3alias"
+
+
+def _resolve_copy_source_alias(headers: dict) -> tuple:
+ """``(headers, denied)``: an ``x-amz-copy-source`` access point alias rewritten to its bucket."""
+ source = headers.get("x-amz-copy-source", "")
+ src_bucket, sep, rest = source.lstrip("/").partition("/")
+ if not sep or not src_bucket.endswith(_ACCESS_POINT_ALIAS_SUFFIX):
+ return headers, None
+ resolved = resolve_access_point_alias(src_bucket)
+ if resolved is None:
+ return headers, None
+ if resolved[0] != get_account_id():
+ return headers, _error("AccessDenied", "Access Denied", 403, f"/{src_bucket}")
+ return {**headers, "x-amz-copy-source": f"{resolved[2]['Bucket']}/{rest}"}, None
+
+
+def resolve_access_point_host(name: str, account_id: str, signed_region: str | None):
+ """The target of an access point host ``<name>-<account>.<host>`` as
+ ``(bucket, access point region, error)``, or None when no such access
+ point exists (the host then names a bucket). An access point in another
+ region than the signing one still resolves, so the region check answers
+ with the access point's region."""
+ regions = access_point_regions(name, account_id)
+ if not regions:
+ return None
+ if account_id != get_account_id():
+ # Access point policies aren't evaluated; another account is refused.
+ return None, None, _error("AccessDenied", "Access Denied", 403, f"/{name}")
+ region = signed_region if signed_region in regions else regions[0]
+ return resolve_access_point(name, account_id, region)["Bucket"], region, None
+
+
+def signed_service(headers: dict, query_params: dict) -> str | None:
+ """The service a SigV4 request was signed for, from its credential scope."""
+ auth = headers.get("authorization", "")
+ if auth.startswith("AWS4-HMAC-SHA256"):
+ m = _SIGV4_SCOPE_SERVICE_RE.search(auth)
+ return m.group(1) if m else None
+ parts = (_qp(query_params, "X-Amz-Credential", "") or _qp(query_params, "x-amz-credential", "")).split("/")
+ return parts[3] if len(parts) == 5 else None
+
+
+def bucket_access_points_attached(bucket: str) -> bool:
+ """Whether a bucket in the current account fronts an MRAP or an access point."""
+ account = get_account_id()
+ return mrap_member(bucket) or any(
+ a == account and r.get("Bucket") == bucket for (a, _region, _n), r in list(_access_points._data.items()))
def new_mrap_alias() -> str:
@@ -272,6 +397,8 @@ _PERSISTED_BUCKET_DICTS = {
# alias fronting them fails where a missing bucket would not.
"mraps": _mraps,
"mrap_operations": _mrap_operations,
+ "access_points": _access_points,
+ "object_lambda_access_points": _object_lambda_access_points,
}
@@ -1079,7 +1206,12 @@ def _check_bucket_region(method: str, bucket: str, key: str, headers: dict, quer
home = home or bucket_region(bucket)
if home is None or home == signed:
return None
+ return region_mismatch_error(method, bucket, key, headers, query_params, signed, home)
+
+def region_mismatch_error(method: str, bucket: str, key: str, headers: dict, query_params: dict,
+ signed: str, home: str) -> tuple:
+ """The response to a request signed for ``signed`` that belongs to ``home``."""
resource = f"/{bucket}/{key}" if key else f"/{bucket}"
presigned = bool(_qp(query_params, "X-Amz-Algorithm", "") or _qp(query_params, "x-amz-algorithm", ""))
if _host_region(headers) == home:
@@ -2104,7 +2236,10 @@ async def handle_request(
signed_path: str | None = None,
enforce_bucket_region: bool = True,
internal: bool = False,
+ access_point_region: str | None = None,
) -> tuple:
+ """``access_point_region`` is set for a request that came through an access
+ point host; the region check then compares against the access point."""
bucket, key = _parse_bucket_key(path, headers)
# A virtual-hosted request is rewritten to path-style before it reaches here
@@ -2124,10 +2259,34 @@ async def handle_request(
# reach the handlers exactly as a header-signed request delivers them.
headers = _merge_hoisted_amz_headers(headers, query_params)
+ # An Object Lambda Access Point alias goes to the Object Lambda flow.
+ if bucket.endswith(_OBJECT_LAMBDA_ALIAS_SUFFIX):
+ resolved = resolve_object_lambda_alias(bucket)
+ if resolved is not None:
+ from ministack.services import s3_object_lambda
+
+ account, olap_region, record = resolved
+ if account != get_account_id():
+ return _error("AccessDenied", "Access Denied", 403, f"/{bucket}")
+ return await s3_object_lambda.handle_request(record, olap_region, method, key, headers, body,
+ query_params, path)
+
+ # An access point alias works wherever a bucket name does on the S3 API.
+ if bucket.endswith(_ACCESS_POINT_ALIAS_SUFFIX):
+ resolved = resolve_access_point_alias(bucket)
+ if resolved is not None:
+ account, access_point_region, record = resolved
+ if account != get_account_id():
+ return _error("AccessDenied", "Access Denied", 403, f"/{bucket}")
+ bucket = record["Bucket"]
+ headers, denied = _resolve_copy_source_alias(headers)
+ if denied is not None:
+ return denied
+
denied = _apply_bucket_scope(method, bucket, key, headers, query_params, body, internal)
if denied is None and enforce_bucket_region:
# After the scope is pinned, so the owner's record names the home region.
- denied = _check_bucket_region(method, bucket, key, headers, query_params)
+ denied = _check_bucket_region(method, bucket, key, headers, query_params, home=access_point_region)
if denied is not None:
status, resp_headers, resp_body = denied
resp_headers.setdefault("x-amz-request-id", new_uuid())
@@ -2546,7 +2705,7 @@ def _delete_bucket(name: str):
bucket = _ensure_bucket(name)
if bucket is None:
return _no_such_bucket(name)
- if mrap_member(name):
+ if bucket_access_points_attached(name):
return _error("BucketHasAccessPointsAttached",
"Bucket has access points attached and cannot be deleted.", 400, f"/{name}")
if bucket["objects"] or _bucket_has_versions(name):
@@ -8573,6 +8732,386 @@ def handle_mrap_control(method: str, path: str, headers: dict, body: bytes, quer
return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)
+# ---------------------------------------------------------------------------
+# S3 Control: regional access points
+# ---------------------------------------------------------------------------
+
+_ACCESS_POINT_PREFIX = "/v20180820/accesspoint"
+_PAB_FIELDS = ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets")
+
+
+class AccessPointError(Exception):
+ def __init__(self, code: str, message: str, status: int, extra: dict[str, str] | None = None):
+ super().__init__(message)
+ self.code, self.message, self.status, self.extra = code, message, status, extra
+
+ def response(self) -> tuple:
+ return s3control_error(self.code, self.message, self.status, self.extra)
+
+
+def _no_such_access_point(name: str) -> AccessPointError:
+ return AccessPointError("NoSuchAccessPoint", "The specified accesspoint does not exist", 404,
+ {"AccessPointName": name})
+
+
+def create_access_point(name: str, bucket: str, vpc_configuration: dict | None = None,
+ public_access_block: dict | None = None, policy: str | None = None,
+ tags: dict | None = None) -> dict:
+ """Create an access point in the current account and region (observed
+ rules: the bucket must be in that region, the name unique there)."""
+ if not _ACCESS_POINT_NAME_RE.match(name or "") or "--" in name:
+ raise AccessPointError("InvalidAccessPoint", "The specified access point name or account is not valid.", 400)
+ region = bucket_region(bucket)
+ if region is None:
+ raise AccessPointError("NoSuchBucket", "The specified bucket does not exist", 404, {"BucketName": bucket})
+ if region != get_region():
+ raise AccessPointError("InvalidRequest",
+ "Amazon S3 AccessPoint can only be created for bucket in the same region", 400)
+ if _access_points.get(name) is not None:
+ raise AccessPointError("AccessPointAlreadyOwnedByYou",
+ "Your previous request to create the named accesspoint succeeded and you already "
+ "own it.", 409)
+ pab = {field: True for field in _PAB_FIELDS}
+ pab.update({k: bool(v) for k, v in (public_access_block or {}).items() if k in _PAB_FIELDS})
+ record = {
+ "Name": name,
+ "Bucket": bucket,
+ "BucketAccountId": get_account_id(),
+ "Alias": new_access_point_alias(name, region),
+ "CreationDate": now_iso(),
+ "NetworkOrigin": "VPC" if (vpc_configuration or {}).get("VpcId") else "Internet",
+ "VpcConfiguration": vpc_configuration or None,
+ "PublicAccessBlockConfiguration": pab,
+ "Policy": policy,
+ "Tags": tags or {},
+ }
+ _access_points[name] = record
+ return record
+
+
+def delete_access_point(name: str) -> None:
+ if _access_points.pop(name, None) is None:
+ raise _no_such_access_point(name)
+
+
+def _access_point_xml(parent, record: dict, full: bool) -> None:
+ SubElement(parent, "Name").text = record["Name"]
+ SubElement(parent, "NetworkOrigin").text = record["NetworkOrigin"]
+ if record.get("VpcConfiguration"):
+ SubElement(SubElement(parent, "VpcConfiguration"), "VpcId").text = record["VpcConfiguration"]["VpcId"]
+ SubElement(parent, "Bucket").text = record["Bucket"]
+ if full:
+ pab = SubElement(parent, "PublicAccessBlockConfiguration")
+ for field in _PAB_FIELDS:
+ SubElement(pab, field).text = str(record["PublicAccessBlockConfiguration"].get(field, True)).lower()
+ SubElement(parent, "CreationDate").text = record["CreationDate"]
+ SubElement(parent, "AccessPointArn").text = access_point_arn(record["Name"])
+ SubElement(parent, "Alias").text = record["Alias"]
+ if full:
+ region = get_region()
+ endpoints = SubElement(parent, "Endpoints")
+ for key, host in (("ipv4", f"s3-accesspoint.{region}.amazonaws.com"),
+ ("fips", f"s3-accesspoint-fips.{region}.amazonaws.com"),
+ ("dualstack", f"s3-accesspoint.dualstack.{region}.amazonaws.com"),
+ ("fips_dualstack", f"s3-accesspoint-fips.dualstack.{region}.amazonaws.com")):
+ entry = SubElement(endpoints, "entry")
+ SubElement(entry, "key").text = key
+ SubElement(entry, "value").text = host
+ SubElement(parent, "BucketAccountId").text = record["BucketAccountId"]
+
+
+def _access_point_create_request(name: str, body: bytes) -> tuple:
+ try:
+ root = fromstring(body) if body else Element("CreateAccessPointRequest")
+ except Exception:
+ return s3control_error("MalformedXML", "The XML you provided was not well-formed", 400)
+ vpc_el = _child(root, "VpcConfiguration")
+ tags_el = _child(root, "Tags")
+ try:
+ record = create_access_point(
+ name, _child_text(root, "Bucket"),
+ vpc_configuration={"VpcId": _child_text(vpc_el, "VpcId")} if vpc_el is not None else None,
+ public_access_block=_parse_pab(_child(root, "PublicAccessBlockConfiguration")),
+ tags={_child_text(t, "Key"): _child_text(t, "Value") for t in tags_el} if tags_el is not None else None,
+ )
+ except AccessPointError as exc:
+ return exc.response()
+ out = Element("CreateAccessPointResult", xmlns=S3CONTROL_NS)
+ SubElement(out, "AccessPointArn").text = access_point_arn(name)
+ SubElement(out, "Alias").text = record["Alias"]
+ return _s3control_response(out)
+
+
+def _access_point_list(query_params: dict) -> tuple:
+ bucket = _qp(query_params, "bucket", "")
+ records = sorted((r for r in _access_points.values() if not bucket or r["Bucket"] == bucket),
+ key=lambda r: r["Name"])
+ start = int(_qp(query_params, "nextToken", "0") or "0")
+ max_results = int(_qp(query_params, "maxResults", "1000") or "1000")
+ out = Element("ListAccessPointsResult", xmlns=S3CONTROL_NS)
+ aps = SubElement(out, "AccessPointList")
+ for record in records[start:start + max_results]:
+ _access_point_xml(SubElement(aps, "AccessPoint"), record, full=False)
+ if start + max_results < len(records):
+ SubElement(out, "NextToken").text = str(start + max_results)
+ return _s3control_response(out)
+
+
+def _access_point_policy(name: str, method: str, body: bytes) -> tuple:
+ record = _access_points.get(name)
+ if record is None:
+ return _no_such_access_point(name).response()
+ if method == "PUT":
+ try:
+ record["Policy"] = _child_text(fromstring(body), "Policy")
+ except Exception:
+ return s3control_error("MalformedXML", "The XML you provided was not well-formed", 400)
+ return 200, {"Content-Type": "application/xml"}, b""
+ if method == "DELETE":
+ record["Policy"] = None
+ return 204, {}, b""
+ if not record.get("Policy"):
+ # The code and message are inferred from the other S3 policy errors.
+ return s3control_error("NoSuchAccessPointPolicy", "The specified accesspoint policy does not exist", 404,
+ {"AccessPointName": name})
+ out = Element("GetAccessPointPolicyResult", xmlns=S3CONTROL_NS)
+ SubElement(out, "Policy").text = record["Policy"]
+ return _s3control_response(out)
+
+
+def is_access_point_control_path(path: str) -> bool:
+ return path.rstrip("/") == _ACCESS_POINT_PREFIX or path.startswith(_ACCESS_POINT_PREFIX + "/")
+
+
+def handle_access_point_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
+ """S3 Control access point operations in the request's region."""
+ tail = url_unquote(path).rstrip("/")[len(_ACCESS_POINT_PREFIX):].strip("/")
+ if not tail:
+ if method == "GET":
+ return _access_point_list(query_params)
+ elif tail.endswith("/policy"):
+ return _access_point_policy(tail[: -len("/policy")], method, body)
+ elif method == "PUT":
+ return _access_point_create_request(tail, body)
+ elif method == "GET":
+ record = _access_points.get(tail)
+ if record is None:
+ return _no_such_access_point(tail).response()
+ out = Element("GetAccessPointResult", xmlns=S3CONTROL_NS)
+ _access_point_xml(out, record, full=True)
+ return _s3control_response(out)
+ elif method == "DELETE":
+ try:
+ delete_access_point(tail)
+ except AccessPointError as exc:
+ return exc.response()
+ return 204, {}, b""
+ return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.", 405)
+
+
+# ---------------------------------------------------------------------------
+# S3 Control: Object Lambda Access Points
+# ---------------------------------------------------------------------------
+
+_OBJECT_LAMBDA_PREFIX = "/v20180820/accesspointforobjectlambda"
+OBJECT_LAMBDA_ACTIONS = ("GetObject", "HeadObject", "ListObjects", "ListObjectsV2")
+OBJECT_LAMBDA_FEATURES = ("GetObject-Range", "GetObject-PartNumber", "HeadObject-Range", "HeadObject-PartNumber")
+
+
+def _no_such_object_lambda(name: str) -> AccessPointError:
+ # Object Lambda shares the access point error (inference).
+ return _no_such_access_point(name)
+
+
+def _parse_object_lambda_configuration(el) -> dict:
+ transformations = []
+ for tc in _child(el, "TransformationConfigurations") or []:
+ actions_el = _child(tc, "Actions")
+ aws_lambda = _child(_child(tc, "ContentTransformation"), "AwsLambda")
+ transformation = {
+ "Actions": [a.text or "" for a in actions_el] if actions_el is not None else [],
+ "FunctionArn": _child_text(aws_lambda, "FunctionArn"),
+ }
+ if _child(aws_lambda, "FunctionPayload") is not None:
+ transformation["FunctionPayload"] = _child_text(aws_lambda, "FunctionPayload")
+ transformations.append(transformation)
+ features_el = _child(el, "AllowedFeatures")
+ return {
+ "SupportingAccessPoint": _child_text(el, "SupportingAccessPoint"),
+ "CloudWatchMetricsEnabled": _child_text(el, "CloudWatchMetricsEnabled").lower() == "true",
+ "AllowedFeatures": [f.text or "" for f in features_el] if features_el is not None else [],
+ "TransformationConfigurations": transformations,
+ }
+
+
+def _object_lambda_configuration_xml(parent, config: dict) -> None:
+ el = SubElement(parent, "Configuration")
+ SubElement(el, "SupportingAccessPoint").text = config["SupportingAccessPoint"]
+ SubElement(el, "CloudWatchMetricsEnabled").text = str(config.get("CloudWatchMetricsEnabled", False)).lower()
+ features = SubElement(el, "AllowedFeatures")
+ for feature in config.get("AllowedFeatures") or []:
+ SubElement(features, "AllowedFeature").text = feature
+ tcs = SubElement(el, "TransformationConfigurations")
+ for transformation in config.get("TransformationConfigurations") or []:
+ tc = SubElement(tcs, "TransformationConfiguration")
+ actions = SubElement(tc, "Actions")
+ for action in transformation["Actions"]:
+ SubElement(actions, "Action").text = action
+ aws_lambda = SubElement(SubElement(tc, "ContentTransformation"), "AwsLambda")
+ SubElement(aws_lambda, "FunctionArn").text = transformation["FunctionArn"]
+ if "FunctionPayload" in transformation:
+ SubElement(aws_lambda, "FunctionPayload").text = transformation["FunctionPayload"]
+
+
+def supporting_access_point(config: dict, region: str | None = None):
+ """``(name, record)`` of the access point an Object Lambda Access Point in
+ ``region`` (default: the request's) sits on, or None."""
+ region = region or get_region()
+ try:
+ arn = parse_arn(config.get("SupportingAccessPoint", ""))
+ except ArnParseError:
+ return None
+ if (arn.service, arn.account_id, arn.region) != ("s3", get_account_id(), region):
+ return None
+ name = arn.resource.split("/", 1)[-1]
+ record = _access_points.get_scoped(get_account_id(), region, name)
+ return (name, record) if record is not None else None
+
+
+def validate_object_lambda_configuration(config: dict) -> None:
+ """The supporting access point and every Lambda share the access point's
+ account and region (S3 user guide); actions and features come from the
+ documented sets. The error code and messages are inferred."""
+ def invalid(message):
+ raise AccessPointError("InvalidRequest", message, 400)
+
+ if supporting_access_point(config) is None:
+ invalid("The supporting access point must be an existing access point in the same account and Region.")
+ for feature in config.get("AllowedFeatures") or []:
+ if feature not in OBJECT_LAMBDA_FEATURES:
+ invalid(f"Invalid AllowedFeature: {feature}")
+ if not config.get("TransformationConfigurations"):
+ invalid("At least one TransformationConfiguration is required.")
+ for transformation in config["TransformationConfigurations"]:
+ if not transformation["Actions"] or any(a not in OBJECT_LAMBDA_ACTIONS for a in transformation["Actions"]):
+ invalid("Invalid transformation configuration action.")
+ try:
+ fn = parse_arn(transformation["FunctionArn"])
+ except ArnParseError:
+ invalid("The Lambda function ARN is invalid.")
+ if (fn.service, fn.account_id, fn.region) != ("lambda", get_account_id(), get_region()):
+ invalid("The Lambda function must be in the same account and Region as the Object Lambda Access Point.")
+
+
+def create_object_lambda_access_point(name: str, config: dict, policy: str | None = None) -> dict:
+ if not _OBJECT_LAMBDA_NAME_RE.match(name or ""):
+ raise AccessPointError("InvalidAccessPoint", "The specified access point name or account is not valid.", 400)
+ validate_object_lambda_configuration(config)
+ if _object_lambda_access_points.get(name) is not None:
+ raise AccessPointError("AccessPointAlreadyOwnedByYou",
+ "Your previous request to create the named accesspoint succeeded and you already "
+ "own it.", 409)
+ record = {
+ "Name": name,
+ "Alias": {"Value": new_object_lambda_alias(name, get_region()), "Status": "READY"},
+ "CreationDate": now_iso(),
+ "Configuration": config,
+ "Policy": policy,
+ "PublicAccessBlockConfiguration": {field: True for field in _PAB_FIELDS},
+ }
+ _object_lambda_access_points[name] = record
+ return record
+
+
+def _object_lambda_alias_xml(parent, record: dict) -> None:
+ alias = SubElement(parent, "Alias")
+ SubElement(alias, "Value").text = record["Alias"]["Value"]
+ SubElement(alias, "Status").text = record["Alias"]["Status"]
+
+
+def is_object_lambda_control_path(path: str) -> bool:
+ return path.rstrip("/") == _OBJECT_LAMBDA_PREFIX or path.startswith(_OBJECT_LAMBDA_PREFIX + "/")
+
+
+def _object_lambda_request(name: str, method: str, body: bytes, sub: str) -> tuple:
+ record = _object_lambda_access_points.get(name)
+ if method == "PUT" and not sub:
+ try:
+ root = fromstring(body)
+ config = _parse_object_lambda_configuration(_child(root, "Configuration"))
+ record = create_object_lambda_access_point(name, config)
+ except AccessPointError as exc:
+ return exc.response()
+ except Exception:
+ return s3control_error("MalformedXML", "The XML you provided was not well-formed", 400)
+ out = Element("CreateAccessPointForObjectLambdaResult", xmlns=S3CONTROL_NS)
+ SubElement(out, "ObjectLambdaAccessPointArn").text = object_lambda_arn(name)
+ _object_lambda_alias_xml(out, record)
+ return _s3control_response(out)
+ if record is None:
+ return _no_such_object_lambda(name).response()
+ if sub == "configuration":
+ if method == "PUT":
+ try:
+ config = _parse_object_lambda_configuration(_child(fromstring(body), "Configuration"))
+ validate_object_lambda_configuration(config)
+ except AccessPointError as exc:
+ return exc.response()
+ record["Configuration"] = config
+ return 200, {"Content-Type": "application/xml"}, b""
+ out = Element("GetAccessPointConfigurationForObjectLambdaResult", xmlns=S3CONTROL_NS)
+ _object_lambda_configuration_xml(out, record["Configuration"])
+ return _s3control_response(out)
+ if sub == "policy":
+ if method == "PUT":
+ record["Policy"] = _child_text(fromstring(body), "Policy")
+ return 200, {"Content-Type": "application/xml"}, b""
+ if method == "DELETE":
+ record["Policy"] = None
+ return 204, {}, b""
+ if not record.get("Policy"):
+ return s3control_error("NoSuchAccessPointPolicy", "The specified accesspoint policy does not exist",
+ 404, {"AccessPointName": name})
+ out = Element("GetAccessPointPolicyForObjectLambdaResult", xmlns=S3CONTROL_NS)
+ SubElement(out, "Policy").text = record["Policy"]
+ return _s3control_response(out)
+ if method == "DELETE":
+ _object_lambda_access_points.pop(name, None)
+ return 204, {}, b""
+ out = Element("GetAccessPointForObjectLambdaResult", xmlns=S3CONTROL_NS)
+ SubElement(out, "Name").text = name
+ pab = SubElement(out, "PublicAccessBlockConfiguration")
+ for field in _PAB_FIELDS:
+ SubElement(pab, field).text = "true"
+ SubElement(out, "CreationDate").text = record["CreationDate"]
+ _object_lambda_alias_xml(out, record)
+ return _s3control_response(out)
+
+
+def handle_object_lambda_control(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
+ """S3 Control Object Lambda Access Point operations in the request's region."""
+ tail = url_unquote(path).rstrip("/")[len(_OBJECT_LAMBDA_PREFIX):].strip("/")
+ if not tail:
+ if method != "GET":
+ return s3control_error("MethodNotAllowed", "The specified method is not allowed against this resource.",
+ 405)
+ records = sorted(_object_lambda_access_points.values(), key=lambda r: r["Name"])
+ start = int(_qp(query_params, "nextToken", "0") or "0")
+ max_results = int(_qp(query_params, "maxResults", "1000") or "1000")
+ out = Element("ListAccessPointsForObjectLambdaResult", xmlns=S3CONTROL_NS)
+ listed = SubElement(out, "ObjectLambdaAccessPointList")
+ for record in records[start:start + max_results]:
+ entry = SubElement(listed, "ObjectLambdaAccessPoint")
+ SubElement(entry, "Name").text = record["Name"]
+ SubElement(entry, "ObjectLambdaAccessPointArn").text = object_lambda_arn(record["Name"])
+ _object_lambda_alias_xml(entry, record)
+ if start + max_results < len(records):
+ SubElement(out, "NextToken").text = str(start + max_results)
+ return _s3control_response(out)
+ name, _, sub = tail.partition("/")
+ return _object_lambda_request(name, method, body, sub)
+
+
def reset():
"""Wipe all in-memory state (used by /_ministack/reset)."""
global _buckets, _bucket_policies, _bucket_notifications, _bucket_tags
@@ -8607,6 +9146,9 @@ def reset():
_object_versions,
_mraps,
_mrap_operations,
+ _access_points,
+ _object_lambda_access_points,
+ _olap_requests,
):
d.clear()
diff --git a/ministack/services/s3_object_lambda.py b/ministack/services/s3_object_lambda.py
new file mode 100644
index 00000000..484e86d1
--- /dev/null
+++ b/ministack/services/s3_object_lambda.py
@@ -0,0 +1,390 @@
+"""S3 Object Lambda data plane: requests through an Object Lambda Access Point (records live in s3.py)."""
+
+import asyncio
+import datetime as _dt
+import json
+import logging
+import os
+import random
+import string
+from urllib.parse import quote
+from xml.etree.ElementTree import Element, SubElement
+
+from ministack.core.iam_evaluator import CredentialResolutionError, resolve_credential
+from ministack.core.responses import get_account_id, new_uuid
+from ministack.core.router import extract_access_key_id, extract_signed_region
+from ministack.core.sigv4 import (
+ build_canonical_query_string,
+ build_canonical_request,
+ build_string_to_sign,
+ calculate_signature,
+)
+from ministack.services import s3
+
+logger = logging.getLogger("s3")
+
+PROTOCOL_VERSION = "1.00"
+_PRESIGN_EXPIRES = 3600
+_SUBRESOURCES = frozenset({
+ "acl", "tagging", "attributes", "legal-hold", "retention", "torrent", "uploadId", "uploads",
+ "restore", "select", "versioning", "location", "policy", "cors", "lifecycle", "versions",
+})
+
+
+def _qp(query_params: dict, name: str, default: str = "") -> str:
+ value = query_params.get(name, default)
+ if isinstance(value, list):
+ return value[0] if value else default
+ return value
+
+
+def _error(code: str, message: str, status: int, resource: str = "") -> tuple:
+ return s3._error(code, message, status, resource)
+
+
+# ---------------------------------------------------------------------------
+# Which operation, and which transformation
+# ---------------------------------------------------------------------------
+
+def _operation(method: str, key: str, query_params: dict) -> str | None:
+ """The transformable operation a request is, or None for everything else."""
+ if any(name in query_params for name in _SUBRESOURCES):
+ return None
+ if key:
+ return {"GET": "GetObject", "HEAD": "HeadObject"}.get(method)
+ if method == "GET":
+ return "ListObjectsV2" if _qp(query_params, "list-type") == "2" else "ListObjects"
+ return None
+
+
+def _transformation(record: dict, operation: str) -> dict | None:
+ for transformation in record["Configuration"].get("TransformationConfigurations") or []:
+ if operation in transformation["Actions"]:
+ return transformation
+ return None
+
+
+def _feature_error(record: dict, operation: str, headers: dict, query_params: dict) -> tuple | None:
+ """Range and partNumber reach a transformation only when AllowedFeatures
+ lists them (S3 user guide); the 501 refusal is inferred."""
+ allowed = record["Configuration"].get("AllowedFeatures") or []
+ for present, feature in ((bool(headers.get("range")), f"{operation}-Range"),
+ ("partNumber" in query_params, f"{operation}-PartNumber")):
+ if present and feature not in allowed:
+ return _error("NotImplemented", "A header you provided implies functionality that is not implemented",
+ 501)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# The presigned inputS3Url
+# ---------------------------------------------------------------------------
+
+def _runs_in_container(func_config: dict) -> bool:
+ from ministack.services import lambda_svc
+
+ return bool(
+ lambda_svc.LAMBDA_STRICT
+ or lambda_svc.LAMBDA_EXECUTOR == "docker"
+ or (func_config.get("PackageType") == "Image" and func_config.get("ImageUri"))
+ or lambda_svc._proxy_url_for(func_config)
+ )
+
+
+def _endpoint_for(func_config: dict) -> str:
+ """The MiniStack endpoint as the function's executor reaches it."""
+ from ministack.core import tls
+ from ministack.services import lambda_svc
+
+ endpoint = os.environ.get("AWS_ENDPOINT_URL", "").rstrip("/")
+ if not endpoint:
+ port = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))
+ endpoint = f"{'https' if tls.use_ssl_enabled() else 'http'}://127.0.0.1:{port}"
+ return lambda_svc._rewrite_host_for_container(endpoint) if _runs_in_container(func_config) else endpoint
+
+
+def _presign(method: str, endpoint: str, path: str, query: dict[str, str], credential, region: str,
+ session_token: str = "") -> str:
+ """A SigV4 presigned URL MiniStack's own verification accepts."""
+ now = _dt.datetime.now(_dt.timezone.utc)
+ amz_date, date_stamp = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d")
+ params = {
+ **query,
+ "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
+ "X-Amz-Credential": f"{credential.access_key_id}/{date_stamp}/{region}/s3/aws4_request",
+ "X-Amz-Date": amz_date,
+ "X-Amz-Expires": str(_PRESIGN_EXPIRES),
+ "X-Amz-SignedHeaders": "host",
+ }
+ if session_token:
+ params["X-Amz-Security-Token"] = session_token
+ host = endpoint.split("://", 1)[1]
+ query_lists = {k: [v] for k, v in params.items()}
+ canonical = build_canonical_request(method, path, {"host": host}, query_lists, "host")
+ signature = calculate_signature(credential.secret_access_key, date_stamp, region, "s3",
+ build_string_to_sign(amz_date, date_stamp, region, "s3", canonical))
+ return f"{endpoint}{quote(path, safe='/-_.~')}?{build_canonical_query_string(query_lists)}" \
+ f"&X-Amz-Signature={signature}"
+
+
+def _caller_credential(headers: dict, query_params: dict):
+ """The caller's credential, which signs the presigned inputS3Url as AWS does."""
+ access_key = extract_access_key_id(headers, query_params) or os.environ.get("AWS_ACCESS_KEY_ID", "test")
+ token = headers.get("x-amz-security-token") or _qp(query_params, "X-Amz-Security-Token")
+ credential = resolve_credential(access_key, get_account_id(), token or None)
+ if isinstance(credential, CredentialResolutionError):
+ credential = resolve_credential(access_key, get_account_id())
+ return credential, token
+
+
+# ---------------------------------------------------------------------------
+# WriteGetObjectResponse
+# ---------------------------------------------------------------------------
+
+def _new_route(region: str) -> str:
+ alphabet = string.ascii_lowercase + string.digits
+ return f"io-{s3._region_code(region)}-{''.join(random.choices(alphabet, k=12))}"
+
+
+def _register(route: str, token: str) -> dict:
+ pending = {"status": 200, "headers": {}, "body": b"", "error": None, "done": False}
+ with s3._olap_requests_lock:
+ s3._olap_requests[(route, token)] = pending
+ return pending
+
+
+def _response_header_name(name: str) -> str:
+ """``x-amz-fwd-header-content-type`` names ``Content-Type``."""
+ if name.startswith("x-amz-"):
+ return name
+ return "-".join(part.capitalize() for part in name.split("-"))
+
+
+def write_get_object_response(headers: dict, body: bytes) -> tuple:
+ """``POST /WriteGetObjectResponse``, matched by its ``x-amz-request-route``
+ header on any host. An unknown route gets AWS's 400 InvalidHostHeader
+ (observed); a known route with a wrong or spent token the same (inferred)."""
+ key = (headers.get("x-amz-request-route", ""), headers.get("x-amz-request-token", ""))
+ with s3._olap_requests_lock:
+ pending = s3._olap_requests.get(key)
+ if pending is None or pending["done"]:
+ return _error("InvalidHostHeader", "Invalid Host header.", 400)
+ pending["status"] = int(headers.get("x-amz-fwd-status") or 200)
+ pending["headers"] = {
+ _response_header_name(name[len("x-amz-fwd-header-"):]): value
+ for name, value in headers.items() if name.startswith("x-amz-fwd-header-")
+ }
+ pending["headers"].update({name: value for name, value in headers.items() if name.startswith("x-amz-meta-")})
+ if headers.get("x-amz-fwd-error-code"):
+ pending["error"] = (headers["x-amz-fwd-error-code"], headers.get("x-amz-fwd-error-message", ""))
+ pending["body"] = body or b""
+ pending["done"] = True
+ return 200, {"Content-Type": "application/xml"}, b""
+
+
+# ---------------------------------------------------------------------------
+# Lambda invocation
+# ---------------------------------------------------------------------------
+
+def _function(arn: str):
+ from ministack.services import lambda_svc
+
+ try:
+ name, qualifier = lambda_svc._resolve_name_and_qualifier(arn)
+ record, _ = lambda_svc._get_func_record_for_qualifier(name, qualifier)
+ except Exception:
+ return None
+ return record
+
+
+def _lambda_failure(result: dict) -> tuple | None:
+ """The error for a failed invocation, or None when the function returned."""
+ if not result.get("error"):
+ return None
+ body = result.get("body")
+ error_type = body.get("errorType", "") if isinstance(body, dict) else ""
+ message = body.get("errorMessage", "") if isinstance(body, dict) else str(body or "")
+ if error_type == "Sandbox.Timedout" or message.startswith("Task timed out"):
+ return _error("LambdaTimeout", "The Lambda function timed out.", 500)
+ if result.get("throttle") or error_type == "TooManyRequestsException":
+ return _error("LambdaInvocationFailed", "The Lambda function could not be invoked.", 400)
+ return _error("LambdaRuntimeError", message or "The Lambda function failed.", 500)
+
+
+def _event(record: dict, transformation: dict, context_name: str, context: dict, url: str, headers: dict,
+ access_key: str) -> dict:
+ account = get_account_id()
+ configuration = {
+ "accessPointArn": s3.object_lambda_arn(record["Name"]),
+ "supportingAccessPointArn": record["Configuration"]["SupportingAccessPoint"],
+ }
+ if "FunctionPayload" in transformation:
+ configuration["payload"] = transformation["FunctionPayload"]
+ return {
+ "xAmzRequestId": new_uuid(),
+ context_name: context,
+ "configuration": configuration,
+ "userRequest": {
+ "url": url,
+ "headers": {_response_header_name(k): v for k, v in headers.items() if k != "authorization"},
+ },
+ "userIdentity": {
+ "type": "IAMUser",
+ "principalId": access_key,
+ "arn": f"arn:aws:iam::{account}:root",
+ "accountId": account,
+ "accessKeyId": access_key,
+ },
+ "protocolVersion": PROTOCOL_VERSION,
+ }
+
+
+async def _invoke(func_record: dict, event: dict) -> dict:
+ from ministack.services import lambda_svc
+
+ # On a worker thread, so the event loop serves the Lambda's
+ # WriteGetObjectResponse call while the GET waits.
+ return await asyncio.to_thread(lambda_svc._execute_function, func_record, event)
+
+
+# ---------------------------------------------------------------------------
+# Request flow
+# ---------------------------------------------------------------------------
+
+def _list_result_xml(result: dict) -> bytes | None:
+ """``listResultXml`` as is, or ``listBucketResult`` JSON as S3's XML. The
+ JSON uses camelCase keys (``contents``, ``key``, ``eTag``) and ``null`` for
+ absent values, per the S3 user guide."""
+ if isinstance(result.get("listResultXml"), str):
+ return result["listResultXml"].encode()
+ data = result.get("listBucketResult")
+ if not isinstance(data, dict):
+ return None
+ root = Element("ListBucketResult", xmlns=s3.S3_NS)
+
+ def xml_tag(name: str) -> str:
+ return "ETag" if name.lower() == "etag" else name[:1].upper() + name[1:]
+
+ def add(parent, name, value):
+ if value is None:
+ return
+ tag = xml_tag(name)
+ if isinstance(value, list):
+ for item in value:
+ add(parent, name, item)
+ elif isinstance(value, dict):
+ child = SubElement(parent, tag)
+ for k, v in value.items():
+ add(child, k, v)
+ else:
+ SubElement(parent, tag).text = str(value).lower() if isinstance(value, bool) else str(value)
+
+ for tag, value in data.items():
+ add(root, tag, value)
+ return s3._xml_body(root)
+
+
+def resolve_host(name: str, account_id: str, headers: dict, query_params: dict):
+ """``(record, region, error)`` for an Object Lambda host ``<name>-<account>``
+ signed ``s3-object-lambda``. An unknown name answers NoSuchAccessPoint (inferred)."""
+ regions = [r for (a, r, n) in list(s3._object_lambda_access_points._data) if a == account_id and n == name]
+ if not regions:
+ return None, None, _error("NoSuchAccessPoint", "The specified accesspoint does not exist", 404)
+ if account_id != get_account_id():
+ return None, None, _error("AccessDenied", "Access Denied", 403)
+ signed = extract_signed_region(headers, query_params)
+ region = signed if signed in regions else regions[0]
+ return s3._object_lambda_access_points.get_scoped(account_id, region, name), region, None
+
+
+async def handle_request(record: dict, region: str, method: str, key: str, headers: dict, body: bytes,
+ query_params: dict, url: str) -> tuple:
+ """A request through the Object Lambda Access Point ``record`` in ``region``."""
+ signed = extract_signed_region(headers, query_params)
+ if signed is not None and signed != region:
+ return s3.region_mismatch_error(method, record["Name"], key, headers, query_params, signed, region)
+ supporting = s3.supporting_access_point(record["Configuration"], region)
+ if supporting is None:
+ return _error("NoSuchAccessPoint", "The specified accesspoint does not exist", 404)
+ _supporting_name, supporting_record = supporting
+
+ operation = _operation(method, key, query_params)
+ transformation = _transformation(record, operation) if operation else None
+ if transformation is None:
+ # No transformation for this operation: the supporting access point serves it.
+ path = f"/{supporting_record['Bucket']}/{key}" if key else f"/{supporting_record['Bucket']}"
+ return await s3.handle_request(method, path, headers, body, query_params, enforce_bucket_region=False)
+
+ refused = _feature_error(record, operation, headers, query_params)
+ if refused:
+ return refused
+ func_record = _function(transformation["FunctionArn"])
+ if func_record is None:
+ return _error("LambdaNotFound", "The Lambda function could not be found.", 404)
+
+ credential, token = _caller_credential(headers, query_params)
+ if isinstance(credential, CredentialResolutionError):
+ return _error("InvalidAccessKeyId", "The AWS Access Key Id you provided does not exist in our records.", 403)
+ endpoint = _endpoint_for(func_record.get("config") or func_record)
+ alias = supporting_record["Alias"]
+ if operation in ("GetObject", "HeadObject"):
+ query = {name: _qp(query_params, name) for name in ("versionId", "partNumber") if name in query_params}
+ input_url = _presign("GET" if operation == "GetObject" else "HEAD", endpoint, f"/{alias}/{key}", query,
+ credential, region, token)
+ else:
+ query = {name: _qp(query_params, name) for name in query_params if not name.lower().startswith("x-amz-")}
+ input_url = _presign("GET", endpoint, f"/{alias}", query, credential, region, token)
+
+ if operation != "GetObject":
+ context_name = {"HeadObject": "headObjectContext", "ListObjects": "listObjectsContext",
+ "ListObjectsV2": "listObjectsV2Context"}[operation]
+ event = _event(record, transformation, context_name, {"inputS3Url": input_url}, url, headers,
+ credential.access_key_id)
+ result = await _invoke(func_record, event)
+ failed = _lambda_failure(result)
+ if failed:
+ return failed
+ return _structured_response(operation, result.get("body"))
+
+ route, request_token = _new_route(region), new_uuid()
+ pending = _register(route, request_token)
+ event = _event(record, transformation, "getObjectContext",
+ {"inputS3Url": input_url, "outputRoute": route, "outputToken": request_token},
+ url, headers, credential.access_key_id)
+ try:
+ result = await _invoke(func_record, event)
+ finally:
+ with s3._olap_requests_lock:
+ s3._olap_requests.pop((route, request_token), None)
+ if not pending["done"]:
+ return _lambda_failure(result) or _error(
+ "LambdaResponseNotReceived", "The Lambda function exited without calling WriteGetObjectResponse.", 500)
+ if pending["error"]:
+ code, message = pending["error"]
+ status = pending["status"] if pending["status"] >= 400 else 500
+ return _error(code, message, status)
+ return pending["status"], {"Content-Type": "application/octet-stream", **pending["headers"]}, pending["body"]
+
+
+def _structured_response(operation: str, returned) -> tuple:
+ """HeadObject and list transformations return JSON instead of calling
+ WriteGetObjectResponse (S3 user guide)."""
+ if isinstance(returned, str):
+ try:
+ returned = json.loads(returned)
+ except ValueError:
+ returned = None
+ if not isinstance(returned, dict):
+ return _error("LambdaRuntimeError", "The Lambda function returned a malformed response.", 500)
+ status = int(returned.get("statusCode") or 200)
+ if operation == "HeadObject":
+ headers = {_response_header_name(k.lower()): str(v) for k, v in (returned.get("headers") or {}).items()}
+ headers.update({f"x-amz-meta-{k}": str(v) for k, v in (returned.get("metadata") or {}).items()})
+ return status, headers, b""
+ if status >= 300:
+ return _error(returned.get("errorCode") or "LambdaRuntimeError",
+ returned.get("errorMessage") or "The Lambda function failed.", status)
+ xml = _list_result_xml(returned)
+ if xml is None:
+ return _error("LambdaRuntimeError", "The Lambda function returned a malformed response.", 500)
+ return status, {"Content-Type": "application/xml"}, xml
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index d7750b93..5cf405da 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -36535,6 +36535,114 @@ def test_cfn_s3_name_conflict_with_validation_disabled_fails_the_resource(cfn, s
s3.delete_bucket(Bucket=name)
+def test_cfn_s3_access_point_provisions_updates_and_deletes(cfn, s3):
+ """AWS::S3::AccessPoint (#2159): Ref is the name; Arn, Alias, Name and
+ NetworkOrigin resolve; Policy updates in place; delete removes it."""
+ from conftest import patch_endpoint_dns
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ bucket, stack_name, ap_name = f"cfn-ap-data-{uid}", f"cfn-ap-{uid}", f"cfn-ap-{uid}"
+ s3.create_bucket(Bucket=bucket)
+
+ def template(policy_action, block_acls=True):
+ return json.dumps({
+ "Resources": {"Ap": {"Type": "AWS::S3::AccessPoint", "Properties": {
+ "Name": ap_name, "Bucket": bucket,
+ "PublicAccessBlockConfiguration": {"BlockPublicAcls": block_acls},
+ "Policy": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::000000000000:root"},
+ "Action": policy_action,
+ "Resource": f"arn:aws:s3:us-east-1:000000000000:accesspoint/{ap_name}/object/*"}]}}}},
+ "Outputs": {k: {"Value": v} for k, v in {
+ "Ref": {"Ref": "Ap"}, "Arn": {"Fn::GetAtt": ["Ap", "Arn"]},
+ "Alias": {"Fn::GetAtt": ["Ap", "Alias"]}, "Name": {"Fn::GetAtt": ["Ap", "Name"]},
+ "NetworkOrigin": {"Fn::GetAtt": ["Ap", "NetworkOrigin"]}}.items()},
+ })
+
+ ctl = boto3.client("s3control", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name="us-east-1", aws_access_key_id="test", aws_secret_access_key="test")
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("s3:GetObject"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ assert _output(stack, "Ref") == _output(stack, "Name") == ap_name
+ assert _output(stack, "Arn") == f"arn:aws:s3:us-east-1:000000000000:accesspoint/{ap_name}"
+ assert _output(stack, "Alias").endswith("use1b-s3alias")
+ assert _output(stack, "NetworkOrigin") == "Internet"
+ with patch_endpoint_dns():
+ assert ctl.get_access_point(AccountId="000000000000", Name=ap_name)["Bucket"] == bucket
+ assert "s3:GetObject" in ctl.get_access_point_policy(AccountId="000000000000", Name=ap_name)["Policy"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("s3:PutObject", block_acls=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ with patch_endpoint_dns():
+ assert "s3:PutObject" in ctl.get_access_point_policy(AccountId="000000000000", Name=ap_name)["Policy"]
+ pab = ctl.get_access_point(AccountId="000000000000", Name=ap_name)["PublicAccessBlockConfiguration"]
+ assert pab["BlockPublicAcls"] is False and pab["BlockPublicPolicy"] is True
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ with patch_endpoint_dns(), pytest.raises(ClientError):
+ ctl.get_access_point(AccountId="000000000000", Name=ap_name)
+ s3.delete_bucket(Bucket=bucket)
+
+
+def test_cfn_s3_object_lambda_access_point_and_policy(cfn, s3, lam):
+ """AWS::S3ObjectLambda::AccessPoint and AccessPointPolicy (#2159)."""
+ from conftest import patch_endpoint_dns
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ bucket, stack_name = f"cfn-olap-data-{uid}", f"cfn-olap-{uid}"
+ s3.create_bucket(Bucket=bucket)
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e, c):\n return 1\n")
+ fn_arn = lam.create_function(FunctionName=f"cfn-olap-fn-{uid}", Runtime="python3.12", Role=_CR_LAMBDA_ROLE,
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})["FunctionArn"]
+ template = {
+ "Resources": {
+ "Ap": {"Type": "AWS::S3::AccessPoint", "Properties": {"Bucket": bucket, "Name": f"cfn-sup-{uid}"}},
+ "Olap": {"Type": "AWS::S3ObjectLambda::AccessPoint", "Properties": {
+ "Name": f"cfn-olap-{uid}",
+ "ObjectLambdaConfiguration": {
+ "SupportingAccessPoint": {"Fn::GetAtt": ["Ap", "Arn"]},
+ "TransformationConfigurations": [{
+ "Actions": ["GetObject"],
+ "ContentTransformation": {"AwsLambda": {"FunctionArn": fn_arn}}}]}}},
+ "OlapPolicy": {"Type": "AWS::S3ObjectLambda::AccessPointPolicy", "Properties": {
+ "ObjectLambdaAccessPoint": {"Ref": "Olap"},
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::000000000000:root"},
+ "Action": "s3-object-lambda:GetObject", "Resource": {"Fn::GetAtt": ["Olap", "Arn"]}}]}}},
+ },
+ "Outputs": {k: {"Value": v} for k, v in {
+ "Ref": {"Ref": "Olap"}, "Arn": {"Fn::GetAtt": ["Olap", "Arn"]},
+ "AliasValue": {"Fn::GetAtt": ["Olap", "Alias.Value"]},
+ "AliasStatus": {"Fn::GetAtt": ["Olap", "Alias.Status"]},
+ "Created": {"Fn::GetAtt": ["Olap", "CreationDate"]}}.items()},
+ }
+ ctl = boto3.client("s3control", endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name="us-east-1", aws_access_key_id="test", aws_secret_access_key="test")
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)
+ assert _output(stack, "Ref") == f"cfn-olap-{uid}"
+ assert _output(stack, "Arn") == f"arn:aws:s3-object-lambda:us-east-1:000000000000:accesspoint/cfn-olap-{uid}"
+ assert _output(stack, "AliasValue").endswith("--ol-s3")
+ assert _output(stack, "AliasStatus") == "READY"
+ assert _output(stack, "Created")
+ with patch_endpoint_dns():
+ policy = ctl.get_access_point_policy_for_object_lambda(AccountId="000000000000", Name=f"cfn-olap-{uid}")
+ assert "s3-object-lambda:GetObject" in policy["Policy"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=f"cfn-olap-fn-{uid}")
+ with patch_endpoint_dns(), pytest.raises(ClientError):
+ ctl.get_access_point_for_object_lambda(AccountId="000000000000", Name=f"cfn-olap-{uid}")
+ s3.delete_bucket(Bucket=bucket)
+
+
@pytest.mark.parametrize("custom_bus", [True, False])
def test_cfn_events_rule_bus_arn_delivery_and_lifecycle(cfn, eb, sqs, custom_bus):
"""ARN/name aliases share a rule on create, update, delivery, drift and delete."""
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 861c14ac..0f396523 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -5770,3 +5770,79 @@ def test_s3_list_grants_scoped_by_prefix_condition(monkeypatch, addressing):
iam.delete_user_policy(UserName=name, PolicyName="home")
iam.delete_user(UserName=name)
root_s3.delete_bucket(Bucket=bucket)
+
+
[email protected]("method,path,action", [
+ ("PUT", "/v20180820/accesspoint/ap1", "s3:CreateAccessPoint"),
+ ("GET", "/v20180820/accesspoint/ap1", "s3:GetAccessPoint"),
+ ("DELETE", "/v20180820/accesspoint/ap1", "s3:DeleteAccessPoint"),
+ ("GET", "/v20180820/accesspoint", "s3:ListAccessPoints"),
+ ("PUT", "/v20180820/accesspoint/ap1/policy", "s3:PutAccessPointPolicy"),
+ ("GET", "/v20180820/accesspoint/ap1/policy", "s3:GetAccessPointPolicy"),
+ ("DELETE", "/v20180820/accesspoint/ap1/policy", "s3:DeleteAccessPointPolicy"),
+])
+def test_s3control_access_point_iam_action(method, path, action):
+ from ministack.core.iam_actions import s3control_action
+
+ assert s3control_action(method, path) == action
+
+
+def test_s3control_access_point_denied_without_the_action(monkeypatch):
+ """Under AUTH=true access point calls need their own action, on the access
+ point's regional ARN."""
+ import ministack.app as app
+
+ seen = _capture_enforced_arn(monkeypatch)
+ headers = {
+ "authorization": "AWS4-HMAC-SHA256 Credential=test/20261013/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=deadbeef",
+ "x-amz-account-id": "000000000000",
+ }
+ monkeypatch.setattr(app, "AUTH", True)
+ asyncio.run(app._handle_s3_control_request("/v20180820/accesspoint/ap1/policy", "GET", b"", {}, "rid", headers))
+ assert seen["action"] == "s3:GetAccessPointPolicy"
+ assert seen["arn"].endswith(":000000000000:accesspoint/ap1")
+
+
[email protected]("method,path,action", [
+ ("PUT", "/v20180820/accesspointforobjectlambda/ol", "s3:CreateAccessPointForObjectLambda"),
+ ("GET", "/v20180820/accesspointforobjectlambda/ol", "s3:GetAccessPointForObjectLambda"),
+ ("DELETE", "/v20180820/accesspointforobjectlambda/ol", "s3:DeleteAccessPointForObjectLambda"),
+ ("GET", "/v20180820/accesspointforobjectlambda", "s3:ListAccessPointsForObjectLambda"),
+ ("PUT", "/v20180820/accesspointforobjectlambda/ol/configuration", "s3:PutAccessPointConfigurationForObjectLambda"),
+ ("GET", "/v20180820/accesspointforobjectlambda/ol/configuration", "s3:GetAccessPointConfigurationForObjectLambda"),
+ ("PUT", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:PutAccessPointPolicyForObjectLambda"),
+ ("GET", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:GetAccessPointPolicyForObjectLambda"),
+ ("DELETE", "/v20180820/accesspointforobjectlambda/ol/policy", "s3:DeleteAccessPointPolicyForObjectLambda"),
+])
+def test_s3control_object_lambda_iam_action(method, path, action):
+ from ministack.core.iam_actions import s3control_action
+
+ assert s3control_action(method, path) == action
+
+
[email protected]("method,key,query,action", [
+ ("GET", "k.txt", {}, "s3-object-lambda:GetObject"),
+ ("HEAD", "k.txt", {}, "s3-object-lambda:GetObject"),
+ ("PUT", "k.txt", {}, "s3-object-lambda:PutObject"),
+ ("DELETE", "k.txt", {}, "s3-object-lambda:DeleteObject"),
+ ("GET", "", {"list-type": ["2"]}, "s3-object-lambda:ListBucket"),
+])
+def test_s3_object_lambda_data_plane_iam_action(method, key, query, action):
+ from ministack.core.iam_actions import s3_object_lambda_action
+
+ assert s3_object_lambda_action(method, key, query) == action
+
+
+def test_write_get_object_response_needs_its_iam_action(monkeypatch):
+ import ministack.app as app
+
+ seen = _capture_enforced_arn(monkeypatch)
+ monkeypatch.setattr(app, "AUTH", True)
+ headers = {"x-amz-request-route": "io-use1-unknown", "x-amz-request-token": "t",
+ "authorization": "AWS4-HMAC-SHA256 Credential=test/20261013/us-east-1/s3-object-lambda/"
+ "aws4_request, SignedHeaders=host, Signature=x"}
+ status = asyncio.run(app._handle_special_data_plane_request(
+ "POST", "/WriteGetObjectResponse", headers, b"", {}, "rid"))[0]
+ assert seen["action"] == "s3-object-lambda:WriteGetObjectResponse"
+ assert status == 400
diff --git a/tests/test_kinesisanalyticsv2.py b/tests/test_kinesisanalyticsv2.py
index 06fe0837..1e0c5c35 100644
--- a/tests/test_kinesisanalyticsv2.py
+++ b/tests/test_kinesisanalyticsv2.py
@@ -634,3 +634,55 @@ def test_runtime_without_an_image_stays_control_plane_only(local_state, monkeypa
assert described() == "READY"
[snap] = kda._snapshots["dp"].values()
assert snap["SnapshotStatus"] == "READY"
+
+
+def test_unknown_action_and_int_timestamps(local_state):
+ status, body = _call("ListApplications", {})
+ assert (status, body["__type"]) == (400, "UnknownOperationException")
+ kda.create_application({"ApplicationName": "ts", "RuntimeEnvironment": RUNTIME, "ServiceExecutionRole": ROLE})
+ detail = _call("DescribeApplication", {"ApplicationName": "ts"})[1]["ApplicationDetail"]
+ assert isinstance(detail["CreateTimestamp"], int)
+ assert isinstance(detail["LastUpdateTimestamp"], int)
+
+
+def _logging_stack(app_name, group, stream, mode="STREAMING"):
+ import json
+
+ return json.dumps({"Resources": {
+ "Logs": {"Type": "AWS::Logs::LogGroup", "Properties": {"LogGroupName": group}},
+ "StreamA": {"Type": "AWS::Logs::LogStream", "Properties": {"LogGroupName": {"Ref": "Logs"},
+ "LogStreamName": "a"}},
+ "StreamB": {"Type": "AWS::Logs::LogStream", "Properties": {"LogGroupName": {"Ref": "Logs"},
+ "LogStreamName": "b"}},
+ "App": {"Type": "AWS::KinesisAnalyticsV2::Application", "Properties": {
+ "ApplicationName": app_name, "RuntimeEnvironment": RUNTIME, "ServiceExecutionRole": ROLE,
+ "ApplicationMode": mode, "ApplicationConfiguration": CODE}},
+ "AppLogging": {"Type": "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption",
+ "DependsOn": ["StreamA", "StreamB"],
+ "Properties": {"ApplicationName": {"Ref": "App"}, "CloudWatchLoggingOption": {
+ "LogStreamARN": {"Fn::Sub": "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:"
+ f"log-group:{group}:log-stream:{stream}"}}}},
+ }})
+
+
+def test_cloudformation_logging_option_updates_in_place_and_mode_change_is_refused(cfn, kinesisanalyticsv2):
+ stack, app, group = _name("flink-log"), _name("cfn-app"), f"/flink/{_name()}"
+ cfn.create_stack(StackName=stack, TemplateBody=_logging_stack(app, group, "a"))
+ try:
+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"
+ [before] = _detail(kinesisanalyticsv2, app)["CloudWatchLoggingOptionDescriptions"]
+
+ cfn.update_stack(StackName=stack, TemplateBody=_logging_stack(app, group, "b"))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"
+ [after] = _detail(kinesisanalyticsv2, app)["CloudWatchLoggingOptionDescriptions"]
+ assert after["CloudWatchLoggingOptionId"] == before["CloudWatchLoggingOptionId"]
+ assert after["LogStreamARN"].endswith(":log-stream:b")
+
+ cfn.update_stack(StackName=stack, TemplateBody=_logging_stack(app, group, "b", mode="INTERACTIVE"))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ events = cfn.describe_stack_events(StackName=stack)["StackEvents"]
+ failed = next(e for e in events if e["LogicalResourceId"] == "App" and e["ResourceStatus"] == "UPDATE_FAILED")
+ assert "custom-named resource requires replacing" in failed["ResourceStatusReason"]
+ finally:
+ cfn.delete_stack(StackName=stack)
+ _wait_stack(cfn, stack)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index dc49f87a..a541f787 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -14972,3 +14972,23 @@ def test_lambda_s3_code_region_publish_layer_version(use1_code_bucket):
published = euw1.publish_layer_version(LayerName=layer, Content={"ZipFile": _make_zip("x = 1\n")})
assert published["Version"] == 1
euw1.delete_layer_version(LayerName=layer, VersionNumber=1)
+
+
+def test_lambda_env_disables_host_prefix_injection_by_default(lam):
+ """WriteGetObjectResponse's host prefix (<route>.<host>) doesn't resolve
+ from inside a Lambda, so boto3 in a handler is told not to inject it
+ unless the function sets the variable itself (#2159)."""
+ code = _make_zip("import os\ndef handler(e, c):\n return os.environ.get('AWS_DISABLE_HOST_PREFIX_INJECTION')\n")
+ name = f"host-prefix-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(FunctionName=name, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": code})
+ own = f"{name}-own"
+ lam.create_function(FunctionName=own, Runtime="python3.12", Role=_LAMBDA_ROLE, Handler="index.handler",
+ Code={"ZipFile": code},
+ Environment={"Variables": {"AWS_DISABLE_HOST_PREFIX_INJECTION": "false"}})
+ try:
+ assert json.loads(lam.invoke(FunctionName=name)["Payload"].read()) == "true"
+ assert json.loads(lam.invoke(FunctionName=own)["Payload"].read()) == "false"
+ finally:
+ lam.delete_function(FunctionName=name)
+ lam.delete_function(FunctionName=own)
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 19b8de5f..569b0353 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -659,6 +659,38 @@ def test_s3_mrap_round_trip():
_round_trip("s3", "s3", populate, observe)
+def test_s3_access_points_round_trip_every_tenant():
+ """Access points are scoped by account and region; a restart keeps all of
+ them, not only the tenant that saved."""
+ record = {"Name": "ap", "Bucket": "data", "Alias": "ap-abc-s3alias", "NetworkOrigin": "Internet"}
+
+ def populate(mod):
+ mod._access_points.set_scoped("111111111111", "us-east-1", "ap", dict(record))
+ mod._access_points.set_scoped("222222222222", "eu-west-1", "ap", {**record, "Bucket": "other"})
+
+ def observe(mod):
+ assert mod._access_points.get_scoped("111111111111", "us-east-1", "ap")["Bucket"] == "data"
+ assert mod._access_points.get_scoped("222222222222", "eu-west-1", "ap")["Bucket"] == "other"
+
+ _round_trip("s3", "s3", populate, observe)
+
+
+def test_s3_object_lambda_access_points_round_trip_without_pending_requests():
+ """Object Lambda Access Points outlive a restart; requests waiting for a
+ WriteGetObjectResponse are in flight only and are never saved."""
+ def populate(mod):
+ mod._object_lambda_access_points.set_scoped("111111111111", "us-east-1", "olap", {
+ "Name": "olap", "Alias": {"Value": "olap-abc--ol-s3", "Status": "READY"}})
+ mod._olap_requests[("route", "token")] = {"done": False}
+
+ def observe(mod):
+ assert mod._object_lambda_access_points.get_scoped(
+ "111111111111", "us-east-1", "olap")["Alias"]["Value"] == "olap-abc--ol-s3"
+ assert "olap_requests" not in mod.get_state()
+
+ _round_trip("s3", "s3", populate, observe)
+
+
def test_transcribe_round_trip():
import time as _time
diff --git a/tests/test_s3_access_points.py b/tests/test_s3_access_points.py
new file mode 100644
index 00000000..b1636bc6
--- /dev/null
+++ b/tests/test_s3_access_points.py
@@ -0,0 +1,254 @@
+"""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 uuid
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+from conftest import 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
+
+
+# --- Data plane --------------------------------------------------------------
+
+def _raw(method, host, path, region, body=b""):
+ """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)
+ req.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()
+ S3SigV4Auth(Credentials("test", "test"), "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")
+
+
+def test_access_point_arn_shaped_bucket_without_access_point_is_a_bucket():
+ """`<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]}"
+ assert _raw("GET", host, "/b.txt", "us-east-1")[2] == b"bucket"
+ 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"
+
+
+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 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_object_lambda.py b/tests/test_s3_object_lambda.py
new file mode 100644
index 00000000..f4faa8ae
--- /dev/null
+++ b/tests/test_s3_object_lambda.py
@@ -0,0 +1,407 @@
+"""S3 Object Lambda (#2159): Object Lambda Access Points in S3 Control, and
+GetObject / HeadObject / List transformations through a Lambda that answers
+with WriteGetObjectResponse.
+
+The data plane follows the S3 user guide; AWS no longer onboards new Object
+Lambda customers, so it could not be observed (see the plan's evidence table).
+"""
+import io
+import json
+import os
+import re
+import uuid
+import zipfile
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+from conftest import patch_endpoint_dns
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+ACCOUNT = "000000000000"
+ROLE = f"arn:aws:iam::{ACCOUNT}:role/lambda-role"
+
+
+def _client(service, region="us-east-1", **config):
+ return boto3.client(
+ service, endpoint_url=ENDPOINT, region_name=region,
+ aws_access_key_id="test", aws_secret_access_key="test",
+ config=Config(region_name=region, retries={"mode": "standard"}, **config),
+ )
+
+
[email protected](autouse=True)
+def _host_dns():
+ """boto3 prefixes S3 Control and access point hosts."""
+ with patch_endpoint_dns():
+ yield
+
+
+def _uid():
+ return uuid.uuid4().hex[:8]
+
+
+def _zip(source: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", source)
+ return buf.getvalue()
+
+
+# Fetches the original through the presigned inputS3Url and writes it back
+# upper-cased, with a status, a header and metadata of its own.
+_UPPER_HANDLER = """
+import urllib.request
+import boto3
+
+def handler(event, context):
+ ctx = event["getObjectContext"]
+ original = urllib.request.urlopen(ctx["inputS3Url"]).read()
+ boto3.client("s3").write_get_object_response(
+ RequestRoute=ctx["outputRoute"], RequestToken=ctx["outputToken"],
+ Body=original.upper(), StatusCode=200, ContentType="text/x-upper",
+ Metadata={"transformed": "yes"})
+ return {"status_code": 200}
+"""
+
+
+def supporting_access_point():
+ """A bucket holding k.txt and an access point on it, both in us-east-1."""
+ s3, ctl = _client("s3"), _client("s3control")
+ bucket, name = f"olap-data-{_uid()}", f"olap-sup-{_uid()}"
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="k.txt", Body=b"hello object lambda")
+ arn = ctl.create_access_point(AccountId=ACCOUNT, Name=name, Bucket=bucket)["AccessPointArn"]
+ yield bucket, arn
+ ctl.delete_access_point(AccountId=ACCOUNT, Name=name)
+ for obj in s3.list_objects_v2(Bucket=bucket).get("Contents", []):
+ s3.delete_object(Bucket=bucket, Key=obj["Key"])
+ s3.delete_bucket(Bucket=bucket)
+
+
+def _function(source, region="us-east-1"):
+ lam = _client("lambda", region)
+ name = f"olap-fn-{_uid()}"
+ arn = lam.create_function(FunctionName=name, Runtime="python3.12", Role=ROLE, Handler="index.handler",
+ Code={"ZipFile": _zip(source)}, Timeout=30)["FunctionArn"]
+ return lam, name, arn
+
+
+def upper_function():
+ lam, name, arn = _function(_UPPER_HANDLER)
+ yield arn
+ lam.delete_function(FunctionName=name)
+
+
+def _configuration(supporting_arn, function_arn, actions=("GetObject",), allowed=()):
+ return {
+ "SupportingAccessPoint": supporting_arn,
+ "AllowedFeatures": list(allowed),
+ "TransformationConfigurations": [{
+ "Actions": list(actions),
+ "ContentTransformation": {"AwsLambda": {"FunctionArn": function_arn, "FunctionPayload": "p"}},
+ }],
+ }
+
+
+def olap(supporting_access_point, upper_function):
+ bucket, supporting_arn = supporting_access_point
+ ctl = _client("s3control")
+ name = f"olap-{_uid()}"
+ created = ctl.create_access_point_for_object_lambda(
+ AccountId=ACCOUNT, Name=name, Configuration=_configuration(supporting_arn, upper_function))
+ yield name, created, bucket
+ try:
+ ctl.delete_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+ except ClientError:
+ pass
+
+
+# --- Control plane ---------------------------------------------------------
+
+def test_object_lambda_control_create_get_list_delete(supporting_access_point, upper_function):
+ _, supporting_arn = supporting_access_point
+ ctl = _client("s3control")
+ name = f"olap-{_uid()}"
+ config = _configuration(supporting_arn, upper_function, actions=("GetObject", "HeadObject"),
+ allowed=("GetObject-Range",))
+ created = ctl.create_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name, Configuration=config)
+ assert created["ObjectLambdaAccessPointArn"] == f"arn:aws:s3-object-lambda:us-east-1:{ACCOUNT}:accesspoint/{name}"
+ assert re.fullmatch(rf"{name[:20]}-[a-z0-9]{{24}}use1a--ol-s3", created["Alias"]["Value"])
+ assert created["Alias"]["Status"] == "READY"
+
+ got = ctl.get_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+ assert got["Name"] == name and got["Alias"] == created["Alias"] and "CreationDate" in got
+ assert all(got["PublicAccessBlockConfiguration"].values())
+
+ stored = ctl.get_access_point_configuration_for_object_lambda(AccountId=ACCOUNT, Name=name)["Configuration"]
+ assert stored["SupportingAccessPoint"] == supporting_arn
+ assert stored["AllowedFeatures"] == ["GetObject-Range"]
+ assert stored["TransformationConfigurations"][0]["Actions"] == ["GetObject", "HeadObject"]
+ assert stored["TransformationConfigurations"][0]["ContentTransformation"]["AwsLambda"] == {
+ "FunctionArn": upper_function, "FunctionPayload": "p"}
+
+ ctl.put_access_point_configuration_for_object_lambda(
+ AccountId=ACCOUNT, Name=name, Configuration=_configuration(supporting_arn, upper_function))
+ stored = ctl.get_access_point_configuration_for_object_lambda(AccountId=ACCOUNT, Name=name)["Configuration"]
+ assert stored["TransformationConfigurations"][0]["Actions"] == ["GetObject"]
+
+ listed = ctl.list_access_points_for_object_lambda(AccountId=ACCOUNT)["ObjectLambdaAccessPointList"]
+ assert name in [a["Name"] for a in listed]
+
+ policy = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"},
+ "Action": "s3-object-lambda:GetObject", "Resource": created["ObjectLambdaAccessPointArn"]}]})
+ ctl.put_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name, Policy=policy)
+ assert ctl.get_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name)["Policy"] == policy
+ ctl.delete_access_point_policy_for_object_lambda(AccountId=ACCOUNT, Name=name)
+
+ ctl.delete_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+ with pytest.raises(ClientError) as exc:
+ ctl.get_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
[email protected]("change", ["supporting-region", "supporting-missing", "lambda-region", "feature", "action"])
+def test_object_lambda_control_validation(supporting_access_point, upper_function, change):
+ """The supporting access point and Lambda share the access point's account
+ and region; actions and allowed features come from the documented sets."""
+ _, supporting_arn = supporting_access_point
+ config = _configuration(supporting_arn, upper_function)
+ if change == "supporting-region":
+ config["SupportingAccessPoint"] = supporting_arn.replace(":us-east-1:", ":eu-west-1:")
+ elif change == "supporting-missing":
+ config["SupportingAccessPoint"] = supporting_arn + "-missing"
+ elif change == "lambda-region":
+ config["TransformationConfigurations"][0]["ContentTransformation"]["AwsLambda"]["FunctionArn"] = (
+ upper_function.replace(":us-east-1:", ":eu-west-1:"))
+ elif change == "feature":
+ config["AllowedFeatures"] = ["GetObject-Everything"]
+ else:
+ config["TransformationConfigurations"][0]["Actions"] = ["PutObject"]
+ with pytest.raises(ClientError) as exc:
+ _client("s3control").create_access_point_for_object_lambda(
+ AccountId=ACCOUNT, Name=f"olap-{_uid()}", Configuration=config)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "InvalidRequest"
+
+
+# --- Routing and WriteGetObjectResponse ------------------------------------
+
+def test_object_lambda_routing_unknown_name():
+ arn = f"arn:aws:s3-object-lambda:us-east-1:{ACCOUNT}:accesspoint/nope-{_uid()}"
+ with pytest.raises(ClientError) as exc:
+ _client("s3").get_object(Bucket=arn, Key="k.txt")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NoSuchAccessPoint"
+
+
[email protected]("inject_host_prefix", [False, True])
+def test_object_lambda_write_get_object_response_unknown_route(inject_host_prefix):
+ """An unknown route is refused as AWS does (observed: 400 InvalidHostHeader),
+ with or without the modeled host prefix."""
+ s3 = _client("s3", inject_host_prefix=inject_host_prefix)
+ with pytest.raises(ClientError) as exc:
+ s3.write_get_object_response(RequestRoute=f"io-use1-{_uid()}", RequestToken="t", Body=b"x")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "InvalidHostHeader"
+ assert exc.value.response["Error"]["Message"] == "Invalid Host header."
+
+
+# --- GetObject transformation ----------------------------------------------
+
+def test_object_lambda_get_object_through_arn_and_alias(olap):
+ name, created, _ = olap
+ s3 = _client("s3")
+ for target in (created["ObjectLambdaAccessPointArn"], created["Alias"]["Value"]):
+ obj = s3.get_object(Bucket=target, Key="k.txt")
+ assert obj["Body"].read() == b"HELLO OBJECT LAMBDA"
+ assert obj["ContentType"] == "text/x-upper"
+ assert obj["Metadata"] == {"transformed": "yes"}
+
+
+def _olap_with(supporting_arn, source, actions=("GetObject",), allowed=()):
+ lam, fn_name, fn_arn = _function(source)
+ ctl = _client("s3control")
+ name = f"olap-{_uid()}"
+ created = ctl.create_access_point_for_object_lambda(
+ AccountId=ACCOUNT, Name=name, Configuration=_configuration(supporting_arn, fn_arn, actions, allowed))
+
+ def cleanup():
+ ctl.delete_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+ lam.delete_function(FunctionName=fn_name)
+
+ return created["ObjectLambdaAccessPointArn"], cleanup
+
+
[email protected]("source,code,status", [
+ ("def handler(e, c):\n raise RuntimeError('boom')\n", "LambdaRuntimeError", 500),
+ ("def handler(e, c):\n return {'status_code': 200}\n", "LambdaResponseNotReceived", 500),
+ ("import boto3\ndef handler(e, c):\n ctx = e['getObjectContext']\n"
+ " boto3.client('s3').write_get_object_response(RequestRoute=ctx['outputRoute'], "
+ "RequestToken=ctx['outputToken'], StatusCode=403, ErrorCode='NotAllowed', ErrorMessage='nope')\n",
+ "NotAllowed", 403),
+], ids=["raises", "no-write", "forwarded-error"])
+def test_object_lambda_get_object_errors(supporting_access_point, source, code, status):
+ _, supporting_arn = supporting_access_point
+ arn, cleanup = _olap_with(supporting_arn, source)
+ try:
+ with pytest.raises(ClientError) as exc:
+ _client("s3").get_object(Bucket=arn, Key="k.txt")
+ assert exc.value.response["Error"]["Code"] == code
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == status
+ finally:
+ cleanup()
+
+
+def test_object_lambda_get_object_missing_function(supporting_access_point, upper_function):
+ _, supporting_arn = supporting_access_point
+ lam, fn_name, fn_arn = _function("def handler(e, c):\n return 1\n")
+ ctl = _client("s3control")
+ name = f"olap-{_uid()}"
+ created = ctl.create_access_point_for_object_lambda(
+ AccountId=ACCOUNT, Name=name, Configuration=_configuration(supporting_arn, fn_arn))
+ lam.delete_function(FunctionName=fn_name)
+ try:
+ with pytest.raises(ClientError) as exc:
+ _client("s3").get_object(Bucket=created["ObjectLambdaAccessPointArn"], Key="k.txt")
+ assert exc.value.response["Error"]["Code"] == "LambdaNotFound"
+ finally:
+ ctl.delete_access_point_for_object_lambda(AccountId=ACCOUNT, Name=name)
+
+
+def test_object_lambda_wrong_region_signing(olap):
+ """Signed for another region than the Object Lambda Access Point's: the
+ AC1 redirect with the access point's region."""
+ import http.client
+
+ from botocore.auth import S3SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ name, _, _ = olap
+ netloc = ENDPOINT.split("://", 1)[1]
+ host = f"{name}-{ACCOUNT}.{netloc}"
+ req = AWSRequest(method="GET", url=f"http://{host}/k.txt")
+ req.headers["x-amz-content-sha256"] = "UNSIGNED-PAYLOAD"
+ S3SigV4Auth(Credentials("test", "test"), "s3-object-lambda", "eu-west-1").add_auth(req)
+ hostname, port = netloc.rsplit(":", 1)
+ conn = http.client.HTTPConnection(hostname, int(port), timeout=30)
+ conn.request("GET", "/k.txt", headers={**dict(req.headers.items()), "Host": host})
+ resp = conn.getresponse()
+ resp.read()
+ assert resp.status == 301
+ assert resp.getheader("x-amz-bucket-region") == "us-east-1"
+
+
+# --- AllowedFeatures and pass-through --------------------------------------
+
+_RANGE_ECHO = """
+import boto3
+
+def handler(event, context):
+ ctx = event["getObjectContext"]
+ boto3.client("s3").write_get_object_response(
+ RequestRoute=ctx["outputRoute"], RequestToken=ctx["outputToken"],
+ Body=(event["userRequest"]["headers"].get("Range") or "none").encode())
+ return {"status_code": 200}
+"""
+
+
+def test_object_lambda_allowed_features(supporting_access_point):
+ _, supporting_arn = supporting_access_point
+ refused_arn, refused_cleanup = _olap_with(supporting_arn, _RANGE_ECHO)
+ allowed_arn, allowed_cleanup = _olap_with(supporting_arn, _RANGE_ECHO, allowed=("GetObject-Range",))
+ s3 = _client("s3")
+ try:
+ with pytest.raises(ClientError) as exc:
+ s3.get_object(Bucket=refused_arn, Key="k.txt", Range="bytes=0-4")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 501
+ assert s3.get_object(Bucket=allowed_arn, Key="k.txt", Range="bytes=0-4")["Body"].read() == b"bytes=0-4"
+ finally:
+ refused_cleanup()
+ allowed_cleanup()
+
+
+def test_object_lambda_pass_through(olap):
+ """Operations without a transformation go to the supporting access point."""
+ _, created, bucket = olap
+ s3 = _client("s3")
+ arn = created["ObjectLambdaAccessPointArn"]
+ s3.put_object(Bucket=arn, Key="put.txt", Body=b"plain")
+ assert s3.get_object(Bucket=bucket, Key="put.txt")["Body"].read() == b"plain"
+ assert s3.head_object(Bucket=arn, Key="put.txt")["ContentLength"] == 5
+ s3.delete_object(Bucket=arn, Key="put.txt")
+ assert "Contents" not in s3.list_objects_v2(Bucket=bucket, Prefix="put.txt")
+
+
+# --- HeadObject and list transformations -----------------------------------
+
+_HEAD_AND_LIST = """
+def handler(event, context):
+ if "headObjectContext" in event:
+ return {"statusCode": 200, "headers": {"Content-Type": "text/x-head", "Content-Length": "7"},
+ "metadata": {"seen": "head"}}
+ if "listObjectsV2Context" in event:
+ return {"statusCode": 200, "listResultXml":
+ "<?xml version='1.0' encoding='UTF-8'?><ListBucketResult><Name>b</Name><KeyCount>1</KeyCount>"
+ "<IsTruncated>false</IsTruncated><Contents><Key>only-v2.txt</Key><Size>1</Size></Contents>"
+ "</ListBucketResult>"}
+ return {"statusCode": 200, "listBucketResult": {
+ "name": "b", "isTruncated": False, "contents": [{"key": "only-v1.txt", "size": 1}]}}
+"""
+
+
+def test_object_lambda_head_object_and_list_objects(supporting_access_point):
+ _, supporting_arn = supporting_access_point
+ arn, cleanup = _olap_with(supporting_arn, _HEAD_AND_LIST, actions=("HeadObject", "ListObjects", "ListObjectsV2"))
+ s3 = _client("s3")
+ try:
+ head = s3.head_object(Bucket=arn, Key="k.txt")
+ assert (head["ContentType"], head["Metadata"]) == ("text/x-head", {"seen": "head"})
+ assert [o["Key"] for o in s3.list_objects_v2(Bucket=arn)["Contents"]] == ["only-v2.txt"]
+ # A transformation without GetObject passes GetObject through.
+ assert s3.get_object(Bucket=arn, Key="k.txt")["Body"].read() == b"hello object lambda"
+ finally:
+ cleanup()
+
+
+def test_object_lambda_list_objects_json_result(supporting_access_point):
+ _, supporting_arn = supporting_access_point
+ arn, cleanup = _olap_with(supporting_arn, _HEAD_AND_LIST, actions=("ListObjects",))
+ try:
+ listed = _client("s3").list_objects(Bucket=arn)
+ assert [o["Key"] for o in listed["Contents"]] == ["only-v1.txt"]
+ finally:
+ cleanup()
+
+
+# --- Executors ---------------------------------------------------------------
+
[email protected](os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",
+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon")
+def test_object_lambda_get_object_docker_executor(olap):
+ """The same transformation from the Docker executor: boto3 in the Lambda
+ image must honour AWS_DISABLE_HOST_PREFIX_INJECTION, and the inputS3Url
+ must use a host the container reaches."""
+ _, created, _ = olap
+ obj = _client("s3").get_object(Bucket=created["ObjectLambdaAccessPointArn"], Key="k.txt")
+ assert obj["Body"].read() == b"HELLO OBJECT LAMBDA"
+
+
+def test_object_lambda_input_url_host_follows_executor(monkeypatch):
+ """In-process: a container executor gets host.docker.internal, the
+ subprocess executors 127.0.0.1."""
+ from ministack.services import lambda_svc, s3_object_lambda
+
+ monkeypatch.delenv("AWS_ENDPOINT_URL", raising=False)
+ monkeypatch.setattr(lambda_svc, "LAMBDA_EXECUTOR", "local")
+ monkeypatch.setattr(lambda_svc, "LAMBDA_STRICT", False)
+ config = {"FunctionName": "f", "Runtime": "python3.12"}
+ assert s3_object_lambda._endpoint_for(config).startswith(("http://127.0.0.1:", "https://127.0.0.1:"))
+ monkeypatch.setattr(lambda_svc, "LAMBDA_EXECUTOR", "docker")
+ assert "://host.docker.internal:" in s3_object_lambda._endpoint_for(config)