Skip to content

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

Add Amazon OpenSearch Serverless (aoss) (#1966)

Jeff Heller3f039fb06e19
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e97573cf..7a91c58b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **OpenSearch Serverless — collections, security and access policies, and a proxied data plane** — `CreateCollection`, `BatchGetCollection`, `ListCollections`, `UpdateCollection`, `DeleteCollection`, `Create`/`Get`/`Update`/`Delete`/`ListSecurityPolicy` (`encryption`, `network`), `Create`/`Get`/`Update`/`Delete`/`ListAccessPolicy` (`data`), `GetPoliciesStats` and `TagResource` / `UntagResource` / `ListTagsForResource`, enough for Terraform's `aws_opensearchserverless_collection`, `_security_policy` and `_access_policy` to apply, plan clean and destroy. A collection needs a matching encryption policy (exact name or `prefix*`, most specific wins) unless `encryptionConfig` is given, and answers `kmsKeyArn: auto` for an AWS-owned key; policy documents are validated, a resource pattern may sit in only one encryption policy, a data policy refuses empty or wildcard principals, and an update must name the current `policyVersion` (`base64("<lastModifiedDate>_<n>")`). Its `collectionEndpoint`, `http://<id>.<region>.aoss.<host>:<port>`, is served through the gateway and requests must be SigV4-signed for `aoss` and carry `x-amz-content-sha256` (403 otherwise); with `OPENSEARCH_DATAPLANE=1` it is backed by its own `opensearchproject/opensearch` container, persisted on a named Docker volume across a restart under `PERSIST_STATE` and removed on `DeleteCollection`, otherwise it answers 503. APIs AOSS does not support answer 404, as `_refresh`, `_cluster/*` and scroll do on AWS, and `TIMESERIES` collections refuse custom document ids and updates. Data access and network policies are stored, not enforced. Checked against the botocore model and the OpenSearch Serverless developer guide and API reference.
### Fixed
- **ElastiCache — serverless caches run in cluster mode** — AWS serves a serverless cache as a cluster-mode cache, so a multi-key command whose keys hash to different slots fails with `CROSSSLOT`; MiniStack's container ran without cluster mode and accepted it, so such code passed locally and failed on AWS. The container now runs as one cluster-mode shard holding every slot, and `CLUSTER SLOTS` reports the cache's endpoint, as AWS's single virtual shard does. Contributed by @skialpine.
diff --git a/README.md b/README.md
index 3c03e4e0..4b89bf50 100644
--- a/README.md
+++ b/README.md
@@ -636,6 +636,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
| **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |
+| **OpenSearch Serverless** | CreateCollection, BatchGetCollection, ListCollections, UpdateCollection, DeleteCollection, CreateSecurityPolicy, GetSecurityPolicy, UpdateSecurityPolicy, DeleteSecurityPolicy, ListSecurityPolicies, CreateAccessPolicy, GetAccessPolicy, UpdateAccessPolicy, DeleteAccessPolicy, ListAccessPolicies, GetPoliciesStats, TagResource, UntagResource, ListTagsForResource | JSON 1.0 control plane (`boto3.client("opensearchserverless")`, SigV4 scope `aoss`); Terraform `aws_opensearchserverless_collection` / `_security_policy` / `_access_policy` compatible. `CreateCollection` requires a matching encryption policy (or `encryptionConfig`), as AWS does; policies carry `policyVersion` and updates must name the current one. The collection is `CREATING` until its data plane is ready, then `ACTIVE`. `collectionEndpoint` is `http://<collection-id>.<region>.aoss.localhost:<port>`, served through the gateway: with `OPENSEARCH_DATAPLANE=1` each collection gets an `opensearchproject/opensearch` container, and requests signed for `aoss` (with `x-amz-content-sha256`) are proxied to it. APIs AWS documents as unsupported answer 404 (`_refresh`, `_cluster/*`, `_cat/nodes`, scroll, ...), `TIMESERIES` collections refuse custom document ids and updates, and the engine's own response — including its own `Content-Encoding` negotiation — passes through unchanged. Data access and network policies are stored but not enforced. |
| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateAccount, DescribeCreateAccountStatus, MoveAccount, CloseAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, CreatePolicy, DescribePolicy, UpdatePolicy, DeletePolicy, ListPolicies, AttachPolicy, DetachPolicy, ListPoliciesForTarget, ListTargetsForPolicy, EnablePolicyType, DisablePolicyType, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; `aws_organizations_account`, `aws_organizations_policy` and `aws_organizations_policy_attachment` apply — `CreateAccount` answers with a `CreateAccountStatus` read back through `DescribeCreateAccountStatus`, the root carries `SERVICE_CONTROL_POLICY` enabled plus the AWS-managed `p-FullAWSAccess`, attaching a policy whose type the root has disabled is `PolicyTypeNotEnabledException` and deleting an attached one is `PolicyInUseException`; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` |
| **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix |
| **WAF (Classic + Regional)** | List* (17 ops), Get*, GetChangeToken, GetChangeTokenStatus, GetPermissionPolicy, Create*/Update*/Delete* (stubbed) | Minimal v1 stub — empty lists for all `List*`, valid ChangeToken on Create/Update/Delete; for full features use **wafv2** (also supported) |
@@ -884,7 +885,7 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret
| `DOCKER_NETWORK` | _(unset)_ | Docker network for all container-backed services (RDS, DSQL, EKS, ElastiCache, Lambda). Set to your Docker Compose network name so containers can reach each other. Replaces `LAMBDA_DOCKER_NETWORK` |
| `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |
| `ELASTICACHE_CLUSTER_MODE_REAL` | `0` | Set `1` (requires `DOCKER_NETWORK`) to provision real Redis Cluster replication groups: `NumNodeGroups × (1+ReplicasPerNodeGroup)` cluster-enabled nodes wired with `redis-cli --cluster create`, serving real `CLUSTER SLOTS` / `MOVED` redirects for cluster-aware clients |
-| `OPENSEARCH_DATAPLANE` | `0` | Set `1` to spawn a real `opensearchproject/opensearch` container per `CreateDomain`. Default `0` returns a stub endpoint (`<domain>.ministack.local:9200`) — management plane only |
+| `OPENSEARCH_DATAPLANE` | `0` | Set `1` to spawn a real `opensearchproject/opensearch` container per `CreateDomain` and per OpenSearch Serverless `CreateCollection`. Default `0` returns a stub endpoint (`<domain>.ministack.local:9200`) — management plane only |
| `OPENSEARCH_BASE_PORT` | `14571` | Starting host port for per-domain OpenSearch containers when `OPENSEARCH_DATAPLANE=1` |
| `OPENSEARCH_IMAGE` | `opensearchproject/opensearch:2.15.0` | Image used when spawning per-domain OpenSearch containers |
| `OPENSEARCH_DASHBOARDS` | `0` | Set `1` (together with `OPENSEARCH_DATAPLANE=1`) to also spawn a per-domain `opensearchproject/opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated |
diff --git a/ministack/app.py b/ministack/app.py
index 16315090..95bf9930 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -56,6 +56,8 @@ _CLOUDFRONT_HOST_RE = re.compile(
# than only _MINISTACK_HOST — pointing a proxy or an /etc/hosts entry at the
# AWS-shaped hostname is the whole point of addressing a function this way.
_LAMBDA_URL_RE = re.compile(r"^([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\.lambda-url\.[a-z0-9-]+\.")
+# OpenSearch Serverless collection endpoint: {collectionId}.{region}.aoss.<anything>[:port].
+_AOSS_COLLECTION_HOST_RE = re.compile(r"^[a-z0-9]{3,40}\.[a-z0-9-]+\.aoss\.", re.IGNORECASE)
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
# IoT data plane WebSocket: anything containing ".iot." in the host header.
@@ -415,6 +417,7 @@ SERVICE_REGISTRY = {
"logs": {"module": "cloudwatch_logs", "aliases": ("cloudwatch-logs",)},
"mediaconnect": {"module": "mediaconnect"},
"opensearch": {"module": "opensearch", "aliases": ("es", "elasticsearch")},
+ "opensearchserverless": {"module": "opensearchserverless", "aliases": ("aoss",)},
"organizations": {"module": "organizations"},
"monitoring": {"module": "cloudwatch", "aliases": ("cloudwatch",)},
"pipes": {"module": "pipes"},
@@ -2194,6 +2197,13 @@ async def _handle_special_data_plane_request(
headers, body, query_params, client_ip,
):
return _with_data_plane_headers(response, request_id, wildcard_cors=False)
+ # Before S3 virtual hosting, which would read the collection id as a bucket.
+ if _AOSS_COLLECTION_HOST_RE.match(host) and (
+ response := await _get_module("opensearchserverless").handle_dataplane(
+ method, host, raw_path or path, raw_query_string, headers, body, query_params
+ )
+ ):
+ return _with_data_plane_headers(response, request_id)
if response := await _handle_execute_api_request(
host, path, method, headers, body, query_params, raw_path=raw_path
):
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 8dad6b56..afda753a 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -90,6 +90,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {
"monitoring": "cloudwatch",
"mq": "mq",
"opensearch": "es",
+ "opensearchserverless": "aoss",
"organizations": "organizations",
"pipes": "pipes",
"rds": "rds",
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 46652ee7..22d31842 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -264,6 +264,11 @@ SERVICE_PATTERNS = {
],
"credential_scope": "es",
},
+ "opensearchserverless": {
+ "target_prefixes": ["OpenSearchServerless."],
+ "host_patterns": [r"^aoss\."],
+ "credential_scope": "aoss",
+ },
"organizations": {
"target_prefixes": ["AWSOrganizationsV20161128"],
"host_patterns": [r"^organizations\."],
@@ -764,6 +769,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"waf-regional": "waf-regional",
"es": "opensearch",
"opensearch": "opensearch",
+ "aoss": "opensearchserverless",
"organizations": "organizations",
"account": "account",
"batch": "batch",
diff --git a/ministack/services/opensearch.py b/ministack/services/opensearch.py
index 00940b57..babdf2ac 100644
--- a/ministack/services/opensearch.py
+++ b/ministack/services/opensearch.py
@@ -369,6 +369,53 @@ def _remove_container_by_id(cid: str) -> None:
pass
+def start_engine_container(docker, name: str, labels: dict, host_port=None, volumes=None):
+ """Run one single-node OpenSearch engine container.
+
+ Returns ``(container_id, host, port)`` for reaching its HTTP API. With
+ ``host_port=None`` Docker picks the published port. ``volumes``, if given,
+ is passed through to ``containers.run`` unchanged (a named volume bound to
+ the data dir, so data survives a container restart). Raises on failure.
+ Shared with the OpenSearch Serverless data plane.
+ """
+ run_kwargs = dict(
+ image=apply_image_prefix(DEFAULT_IMAGE), detach=True,
+ ports={"9200/tcp": host_port},
+ name=name,
+ labels=labels,
+ environment={
+ "discovery.type": "single-node",
+ # Disable security plugin so test code can talk to the cluster
+ # without bootstrapping a CA chain. Real AWS requires HTTPS+IAM;
+ # matching that here would block every smoke test.
+ "DISABLE_SECURITY_PLUGIN": "true",
+ "OPENSEARCH_INITIAL_ADMIN_PASSWORD": "MinIstack-Admin-1!",
+ },
+ ulimits=[{"Name": "memlock", "Soft": -1, "Hard": -1}],
+ )
+ if volumes is not None:
+ run_kwargs["volumes"] = volumes
+ if DOCKER_NETWORK:
+ run_kwargs["network"] = DOCKER_NETWORK
+ container = docker.containers.run(**run_kwargs)
+ try:
+ host, port = _MINISTACK_HOST, host_port
+ if DOCKER_NETWORK or host_port is None:
+ container.reload()
+ settings = container.attrs.get("NetworkSettings", {})
+ if DOCKER_NETWORK:
+ ip = settings.get("Networks", {}).get(DOCKER_NETWORK, {}).get("IPAddress", "")
+ if ip:
+ host, port = ip, 9200
+ if port is None:
+ bindings = (settings.get("Ports") or {}).get("9200/tcp") or []
+ port = int(bindings[0]["HostPort"])
+ except Exception:
+ _remove_container_by_id(container.id)
+ raise
+ return container.id, host, port
+
+
def _spawn_dataplane(domain_name: str, engine_version: str):
"""Spawn an OpenSearch container.
@@ -399,7 +446,6 @@ def _spawn_dataplane(domain_name: str, engine_version: str):
dash_host_port = _dashboards_port_counter[0]
_dashboards_port_counter[0] += 1
- image = apply_image_prefix(DEFAULT_IMAGE)
labels = {
# Standard label so the boot/shutdown orphan reap finds these; the
# com.ministack.* keys below are what the service's own lookups use.
@@ -409,40 +455,13 @@ def _spawn_dataplane(domain_name: str, engine_version: str):
"com.ministack.region": get_region(),
"com.docker.compose.project": "ministack",
}
- env_vars = {
- "discovery.type": "single-node",
- # Disable security plugin so test code can talk to the cluster
- # without bootstrapping a CA chain. Real AWS requires HTTPS+IAM;
- # matching that here would block every smoke test.
- "DISABLE_SECURITY_PLUGIN": "true",
- "OPENSEARCH_INITIAL_ADMIN_PASSWORD": "MinIstack-Admin-1!",
- }
- run_kwargs = dict(
- image=image, detach=True,
- ports={"9200/tcp": host_port},
- name=_container_name(domain_name),
- labels=labels,
- environment=env_vars,
- ulimits=[{"Name": "memlock", "Soft": -1, "Hard": -1}],
- )
- if DOCKER_NETWORK:
- run_kwargs["network"] = DOCKER_NETWORK
-
- cid = None
- endpoint_host, endpoint_port = _MINISTACK_HOST, host_port
try:
- container = docker.containers.run(**run_kwargs)
- cid = container.id
- if DOCKER_NETWORK:
- container.reload()
- networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
- ip = networks.get(DOCKER_NETWORK, {}).get("IPAddress", "")
- if ip:
- endpoint_host = ip
- endpoint_port = 9200
+ cid, endpoint_host, endpoint_port = start_engine_container(
+ docker, _container_name(domain_name), labels, host_port
+ )
logger.info(
- "OpenSearch: started container %s at %s:%s (image=%s)",
- domain_name, endpoint_host, endpoint_port, image,
+ "OpenSearch: started container %s at %s:%s",
+ domain_name, endpoint_host, endpoint_port,
)
except Exception as e:
logger.warning("OpenSearch: Docker failed for %s: %s", domain_name, e)
diff --git a/ministack/services/opensearchserverless.py b/ministack/services/opensearchserverless.py
new file mode 100644
index 00000000..ac618215
--- /dev/null
+++ b/ministack/services/opensearchserverless.py
@@ -0,0 +1,988 @@
+# 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 OpenSearch Serverless (AOSS) emulator.
+
+Control plane: JSON 1.0 via ``X-Amz-Target: OpenSearchServerless.<Op>``
+(botocore ``opensearchserverless`` 2021-11-01, signing name ``aoss``).
+Data plane: each collection's ``collectionEndpoint`` is served through the
+gateway (``<id>.<region>.aoss.<MINISTACK_HOST>:<port>``) and proxied to a real
+``opensearchproject/opensearch`` container when ``OPENSEARCH_DATAPLANE=1``.
+
+Operations:
+- CreateCollection, BatchGetCollection, ListCollections, UpdateCollection, DeleteCollection
+- Create/Get/Update/Delete/ListSecurityPolicy (encryption, network)
+- Create/Get/Update/Delete/ListAccessPolicy (data)
+- GetPoliciesStats
+- TagResource, UntagResource, ListTagsForResource
+"""
+
+import base64
+import copy
+import fnmatch
+import http.client
+import json
+import logging
+import os
+import random
+import re
+import string
+import time
+
+from ministack.core import container_reaper, persistence
+from ministack.core.arn import ArnParseError, parse_arn
+from ministack.core.concurrency import resource_lock, run_offloop, spawn_background
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ AccountScopedDict,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+ new_uuid,
+ set_request_account_id,
+ set_request_region,
+)
+
+logger = logging.getLogger("opensearchserverless")
+
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+_ENGINE_READY_TIMEOUT = 300.0
+_PROXY_TIMEOUT = 120.0
+_CONTAINER_LABEL = "opensearchserverless"
+# OpenSearch's default data path (opensearchproject/opensearch image).
+_ENGINE_DATA_DIR = "/usr/share/opensearch/data"
+
+_NAME_RE = re.compile(r"^[a-z][a-z0-9-]+$")
+_COLLECTION_TYPES = ("SEARCH", "TIMESERIES", "VECTORSEARCH")
+_SECURITY_POLICY_TYPES = ("encryption", "network")
+_ACCESS_POLICY_TYPES = ("data",)
+
+# Data access policy permissions (AWS docs: "Data access control for Amazon
+# OpenSearch Serverless", supported policy permissions).
+_DATA_PERMISSIONS = {
+ "collection": {
+ "aoss:*", "aoss:CreateCollectionItems", "aoss:DeleteCollectionItems",
+ "aoss:UpdateCollectionItems", "aoss:DescribeCollectionItems",
+ },
+ "index": {
+ "aoss:*", "aoss:ReadDocument", "aoss:WriteDocument", "aoss:CreateIndex",
+ "aoss:DeleteIndex", "aoss:UpdateIndex", "aoss:DescribeIndex",
+ },
+ "model": {
+ "aoss:*", "aoss:CreateMLResource", "aoss:DeleteMLResource",
+ "aoss:UpdateMLResource", "aoss:DescribeMLResource", "aoss:ExecuteMLResource",
+ },
+}
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+_collections = AccountRegionScopedDict() # id -> record (+ private _* fields)
+_security_policies = AccountRegionScopedDict() # "<type>/<name>" -> record
+_access_policies = AccountRegionScopedDict() # "<type>/<name>" -> record
+_tags = AccountScopedDict() # collection ARN -> [{key, value}]
+_docker_client = None
+
+
+def reset():
+ _collections.clear()
+ _security_policies.clear()
+ _access_policies.clear()
+ _tags.clear()
+ docker = _get_docker()
+ if docker is None:
+ return
+ try:
+ containers = docker.containers.list(
+ all=True, filters={"label": f"com.ministack.service={_CONTAINER_LABEL}"}
+ )
+ except Exception:
+ return
+ container_reaper.drop_containers(containers, force=True)
+
+
+def get_state():
+ return {
+ "collections": copy.deepcopy(_collections),
+ "security_policies": copy.deepcopy(_security_policies),
+ "access_policies": copy.deepcopy(_access_policies),
+ "tags": copy.deepcopy(_tags),
+ }
+
+
+def load_persisted_state(data):
+ if not data:
+ return
+ _collections.update(data.get("collections", {}))
+ _security_policies.update(data.get("security_policies", {}))
+ _access_policies.update(data.get("access_policies", {}))
+ _tags.update(data.get("tags", {}))
+ original_account, original_region = get_account_id(), get_region()
+ try:
+ for (account_id, region, _cid), rec in list(_collections.all_items()):
+ set_request_account_id(account_id)
+ set_request_region(region)
+ # Engine containers do not survive a restart; provision afresh.
+ # _VolumeName is kept: PERSIST_STATE gives the fresh container the
+ # same named volume, so its data survives the restart.
+ rec.pop("_ContainerId", None)
+ rec.pop("_Engine", None)
+ rec["status"] = "CREATING"
+ _start_provisioning(rec)
+ finally:
+ set_request_account_id(original_account)
+ set_request_region(original_region)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def _error(code, message, status=400):
+ return error_response_json(code, message, status)
+
+
+class _Invalid(Exception):
+ def __init__(self, message, code="ValidationException"):
+ super().__init__(message)
+ self.code = code
+ self.message = message
+
+
+def _validate_name(value, field, max_len):
+ if not isinstance(value, str) or not value:
+ raise _Invalid(f"1 validation error detected: Value null at '{field}' failed to satisfy constraint: Member must not be null")
+ if not (3 <= len(value) <= max_len) or not _NAME_RE.match(value):
+ raise _Invalid(
+ f"1 validation error detected: Value '{value}' at '{field}' failed to satisfy constraint: "
+ f"Member must satisfy regular expression pattern: [a-z][a-z0-9-]+ and length {3}-{max_len}"
+ )
+
+
+def _validate_enum(value, field, allowed):
+ if value not in allowed:
+ raise _Invalid(
+ f"1 validation error detected: Value '{value}' at '{field}' failed to satisfy constraint: "
+ f"Member must satisfy enum value set: [{', '.join(allowed)}]"
+ )
+
+
+def _policy_version(modified_ms, revision):
+ # AWS docs example: "MTY2MzY5MzIxNzgyNl8x" = base64("1663693217826_1").
+ return base64.b64encode(f"{modified_ms}_{revision}".encode()).decode()
+
+
+def _collection_arn(collection_id):
+ return f"arn:aws:aoss:{get_region()}:{get_account_id()}:collection/{collection_id}"
+
+
+def _new_collection_id():
+ alphabet = string.ascii_lowercase + string.digits
+ while True:
+ cid = "".join(random.choices(alphabet, k=20))
+ if not any(key[2] == cid for key, _ in _collections.all_items()):
+ return cid
+
+
+def _collection_endpoint(collection_id):
+ from ministack.core import tls
+
+ scheme = "https" if tls.use_ssl_enabled() else "http"
+ port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
+ return f"{scheme}://{collection_id}.{get_region()}.aoss.{_MINISTACK_HOST}:{port}"
+
+
+def _pattern_matches(pattern, value):
+ """AOSS resource patterns support a trailing ``*`` wildcard."""
+ return fnmatch.fnmatchcase(value, pattern)
+
+
+def _page(items, data, max_default=100):
+ try:
+ start = int(data.get("nextToken") or 0)
+ except (TypeError, ValueError):
+ raise _Invalid("Invalid nextToken")
+ limit = data.get("maxResults") or max_default
+ page = items[start:start + limit]
+ token = str(start + limit) if start + limit < len(items) else None
+ return page, token
+
+
+# ---------------------------------------------------------------------------
+# Policy documents
+# ---------------------------------------------------------------------------
+
+def _parse_policy_document(raw):
+ if not isinstance(raw, str) or not raw.strip():
+ raise _Invalid("Policy document must not be empty")
+ try:
+ return json.loads(raw)
+ except json.JSONDecodeError as e:
+ raise _Invalid(f"Policy json is invalid, error: [{e.msg}]")
+
+
+def _validate_rules(rules, allowed_types, need_permission):
+ if not isinstance(rules, list) or not rules:
+ raise _Invalid("Policy json is invalid, error: [Rules must be a non-empty list]")
+ for rule in rules:
+ if not isinstance(rule, dict):
+ raise _Invalid("Policy json is invalid, error: [Rule must be an object]")
+ rtype = rule.get("ResourceType")
+ if rtype not in allowed_types:
+ raise _Invalid(f"Policy json is invalid, error: [ResourceType {rtype!r} is not supported]")
+ resources = rule.get("Resource")
+ if not isinstance(resources, list) or not resources:
+ raise _Invalid("Policy json is invalid, error: [Resource must be a non-empty list]")
+ for resource in resources:
+ if not isinstance(resource, str) or not resource.startswith(f"{rtype}/") or resource == f"{rtype}/":
+ raise _Invalid(f"Policy json is invalid, error: [Resource {resource!r} must start with '{rtype}/']")
+ if need_permission:
+ perms = rule.get("Permission")
+ if not isinstance(perms, list) or not perms:
+ raise _Invalid("Policy json is invalid, error: [Permission must be a non-empty list]")
+ for perm in perms:
+ if perm not in _DATA_PERMISSIONS[rtype]:
+ raise _Invalid(f"Policy json is invalid, error: [Permission {perm!r} is not valid for ResourceType {rtype}]")
+
+
+def _validate_encryption_policy(doc, own_name):
+ if not isinstance(doc, dict):
+ raise _Invalid("Policy json is invalid, error: [Encryption policy must be a JSON object]")
+ _validate_rules(doc.get("Rules"), ("collection",), False)
+ if not doc.get("AWSOwnedKey") and not doc.get("KmsARN"):
+ raise _Invalid("Policy json is invalid, error: [Either AWSOwnedKey must be true or KmsARN must be specified]")
+ # AWS docs: identical resource patterns may not appear in two encryption policies.
+ patterns = {r for rule in doc["Rules"] for r in rule["Resource"]}
+ for key, rec in _security_policies.items():
+ if not key.startswith("encryption/") or rec["name"] == own_name:
+ continue
+ for rule in rec["policy"].get("Rules", []):
+ clash = patterns.intersection(rule.get("Resource", []))
+ if clash:
+ raise _Invalid(
+ f"Policy json is invalid, error: [Resource {sorted(clash)[0]} is already used in "
+ f"encryption policy {rec['name']}]"
+ )
+
+
+def _validate_network_policy(doc):
+ if not isinstance(doc, list) or not doc:
+ raise _Invalid("Policy json is invalid, error: [Network policy must be a non-empty JSON array]")
+ for statement in doc:
+ if not isinstance(statement, dict):
+ raise _Invalid("Policy json is invalid, error: [Network policy rule must be an object]")
+ _validate_rules(statement.get("Rules"), ("collection", "dashboard"), False)
+ public = statement.get("AllowFromPublic")
+ if not public and not statement.get("SourceVPCEs") and not statement.get("SourceServices"):
+ raise _Invalid(
+ "Policy json is invalid, error: [AllowFromPublic must be true or SourceVPCEs/SourceServices specified]"
+ )
+
+
+def _validate_data_policy(doc):
+ if not isinstance(doc, list) or not doc:
+ raise _Invalid("Policy json is invalid, error: [Data access policy must be a non-empty JSON array]")
+ for statement in doc:
+ if not isinstance(statement, dict):
+ raise _Invalid("Policy json is invalid, error: [Data access policy rule must be an object]")
+ _validate_rules(statement.get("Rules"), tuple(_DATA_PERMISSIONS), True)
+ principals = statement.get("Principal")
+ if not isinstance(principals, list) or not principals:
+ raise _Invalid("Policy json is invalid, error: [Principal must be a non-empty list]")
+ for principal in principals:
+ if not isinstance(principal, str) or "*" in principal:
+ raise _Invalid(f"Policy json is invalid, error: [Principal {principal!r} is invalid; wildcards are not supported]")
+
+
+def _policy_detail(rec, include_policy=True):
+ out = {k: copy.deepcopy(v) for k, v in rec.items() if not k.startswith("_")}
+ if not include_policy:
+ out.pop("policy", None)
+ return out
+
+
+def _put_policy(store, kind, data, validate):
+ ptype, name = data.get("type"), data.get("name")
+ _validate_enum(ptype, "type", _SECURITY_POLICY_TYPES if kind == "security" else _ACCESS_POLICY_TYPES)
+ _validate_name(name, "name", 32)
+ key = f"{ptype}/{name}"
+ if key in store:
+ raise _Invalid(f"Policy with name {name} and type {ptype} already exists", "ConflictException")
+ doc = _parse_policy_document(data.get("policy"))
+ validate(ptype, name, doc)
+ now = _now_ms()
+ rec = {
+ "type": ptype,
+ "name": name,
+ "policyVersion": _policy_version(now, 1),
+ "description": data.get("description", ""),
+ "policy": doc,
+ "createdDate": now,
+ "lastModifiedDate": now,
+ "_revision": 1,
+ }
+ store[key] = rec
+ return rec
+
+
+def _update_policy(store, kind, data, validate):
+ ptype, name = data.get("type"), data.get("name")
+ _validate_enum(ptype, "type", _SECURITY_POLICY_TYPES if kind == "security" else _ACCESS_POLICY_TYPES)
+ _validate_name(name, "name", 32)
+ rec = store.get(f"{ptype}/{name}")
+ if rec is None:
+ raise _Invalid(f"Policy with name {name} and type {ptype} is not found", "ResourceNotFoundException")
+ if data.get("policyVersion") != rec["policyVersion"]:
+ raise _Invalid(
+ "Policy version specified in the request refers to an older version and policy has since changed"
+ )
+ changed = False
+ if "policy" in data and data["policy"] is not None:
+ doc = _parse_policy_document(data["policy"])
+ validate(ptype, name, doc)
+ if doc != rec["policy"]:
+ rec["policy"] = doc
+ changed = True
+ if "description" in data and data["description"] != rec["description"]:
+ rec["description"] = data["description"]
+ changed = True
+ if changed:
+ now = _now_ms()
+ rec["_revision"] += 1
+ rec["lastModifiedDate"] = now
+ rec["policyVersion"] = _policy_version(now, rec["_revision"])
+ return rec
+
+
+def _list_policies(store, data, detail_key):
+ ptype = data.get("type")
+ filters = data.get("resource") or []
+ items = []
+ for key in sorted(store.keys()):
+ rec = store[key]
+ if rec["type"] != ptype:
+ continue
+ if filters:
+ rules = rec["policy"] if isinstance(rec["policy"], list) else [rec["policy"]]
+ resources = [r for st in rules for rule in st.get("Rules", []) for r in rule.get("Resource", [])]
+ if not any(_pattern_matches(f, r) or _pattern_matches(r, f) for f in filters for r in resources):
+ continue
+ items.append(_policy_detail(rec, include_policy=False))
+ page, token = _page(items, data)
+ out = {detail_key: page}
+ if token:
+ out["nextToken"] = token
+ return out
+
+
+def _security_validator(ptype, name, doc):
+ if ptype == "encryption":
+ _validate_encryption_policy(doc, name)
+ else:
+ _validate_network_policy(doc)
+
+
+def _access_validator(_ptype, _name, doc):
+ _validate_data_policy(doc)
+
+
+def _create_security_policy(data):
+ return json_response({"securityPolicyDetail": _policy_detail(
+ _put_policy(_security_policies, "security", data, _security_validator))})
+
+
+def _get_security_policy(data):
+ _validate_enum(data.get("type"), "type", _SECURITY_POLICY_TYPES)
+ rec = _security_policies.get(f"{data.get('type')}/{data.get('name')}")
+ if rec is None:
+ raise _Invalid(f"Policy with name {data.get('name')} and type {data.get('type')} is not found",
+ "ResourceNotFoundException")
+ return json_response({"securityPolicyDetail": _policy_detail(rec)})
+
+
+def _update_security_policy(data):
+ return json_response({"securityPolicyDetail": _policy_detail(
+ _update_policy(_security_policies, "security", data, _security_validator))})
+
+
+def _delete_security_policy(data):
+ _validate_enum(data.get("type"), "type", _SECURITY_POLICY_TYPES)
+ if _security_policies.pop(f"{data.get('type')}/{data.get('name')}", None) is None:
+ raise _Invalid(f"Policy with name {data.get('name')} and type {data.get('type')} is not found",
+ "ResourceNotFoundException")
+ return json_response({})
+
+
+def _list_security_policies(data):
+ _validate_enum(data.get("type"), "type", _SECURITY_POLICY_TYPES)
+ return json_response(_list_policies(_security_policies, data, "securityPolicySummaries"))
+
+
+def _create_access_policy(data):
+ return json_response({"accessPolicyDetail": _policy_detail(
+ _put_policy(_access_policies, "access", data, _access_validator))})
+
+
+def _get_access_policy(data):
+ _validate_enum(data.get("type"), "type", _ACCESS_POLICY_TYPES)
+ rec = _access_policies.get(f"{data.get('type')}/{data.get('name')}")
+ if rec is None:
+ raise _Invalid(f"Policy with name {data.get('name')} and type {data.get('type')} is not found",
+ "ResourceNotFoundException")
+ return json_response({"accessPolicyDetail": _policy_detail(rec)})
+
+
+def _update_access_policy(data):
+ return json_response({"accessPolicyDetail": _policy_detail(
+ _update_policy(_access_policies, "access", data, _access_validator))})
+
+
+def _delete_access_policy(data):
+ _validate_enum(data.get("type"), "type", _ACCESS_POLICY_TYPES)
+ if _access_policies.pop(f"{data.get('type')}/{data.get('name')}", None) is None:
+ raise _Invalid(f"Policy with name {data.get('name')} and type {data.get('type')} is not found",
+ "ResourceNotFoundException")
+ return json_response({})
+
+
+def _list_access_policies(data):
+ _validate_enum(data.get("type"), "type", _ACCESS_POLICY_TYPES)
+ return json_response(_list_policies(_access_policies, data, "accessPolicySummaries"))
+
+
+def _get_policies_stats(_data):
+ enc = sum(1 for k in _security_policies.keys() if k.startswith("encryption/"))
+ net = sum(1 for k in _security_policies.keys() if k.startswith("network/"))
+ dat = len(_access_policies)
+ return json_response({
+ "AccessPolicyStats": {"DataPolicyCount": dat},
+ "SecurityPolicyStats": {"EncryptionPolicyCount": enc, "NetworkPolicyCount": net},
+ "SecurityConfigStats": {"SamlConfigCount": 0},
+ "LifecyclePolicyStats": {"RetentionPolicyCount": 0},
+ "TotalPolicyCount": enc + net + dat,
+ })
+
+
+# ---------------------------------------------------------------------------
+# Collections
+# ---------------------------------------------------------------------------
+
+def _matching_encryption_key(name):
+ """The KMS key of the most specific encryption policy rule matching ``name``."""
+ best = None
+ for key, rec in _security_policies.items():
+ if not key.startswith("encryption/"):
+ continue
+ for rule in rec["policy"].get("Rules", []):
+ for resource in rule.get("Resource", []):
+ pattern = resource[len("collection/"):]
+ if not _pattern_matches(pattern, name):
+ continue
+ exact = "*" not in pattern
+ rank = (exact, len(pattern))
+ if best is None or rank > best[0]:
+ doc = rec["policy"]
+ best = (rank, doc.get("KmsARN") or "auto")
+ return best[1] if best else None
+
+
+def _collection_detail(rec, fields):
+ return {k: copy.deepcopy(rec[k]) for k in fields if rec.get(k) is not None}
+
+
+_DETAIL_FIELDS = (
+ "id", "name", "status", "type", "description", "arn", "kmsKeyArn", "standbyReplicas",
+ "deletionProtection", "vectorOptions", "createdDate", "lastModifiedDate",
+ "collectionEndpoint", "dashboardEndpoint", "failureCode", "failureMessage",
+)
+_CREATE_FIELDS = (
+ "id", "name", "status", "type", "description", "arn", "kmsKeyArn", "standbyReplicas",
+ "deletionProtection", "vectorOptions", "createdDate", "lastModifiedDate",
+)
+_SUMMARY_FIELDS = ("id", "name", "status", "arn", "kmsKeyArn")
+
+
+def _find_by_name(name):
+ for rec in _collections.values():
+ if rec["name"] == name:
+ return rec
+ return None
+
+
+def _create_collection(data):
+ name = data.get("name")
+ _validate_name(name, "name", 64)
+ ctype = data.get("type", "TIMESERIES")
+ _validate_enum(ctype, "type", _COLLECTION_TYPES)
+ standby = data.get("standbyReplicas", "ENABLED")
+ _validate_enum(standby, "standbyReplicas", ("ENABLED", "DISABLED"))
+ deletion = data.get("deletionProtection", "DISABLED")
+ _validate_enum(deletion, "deletionProtection", ("ENABLED", "DISABLED"))
+ if data.get("collectionGroupName"):
+ raise _Invalid("Collection groups are not supported by MiniStack")
+ if len(data.get("description") or "") > 1000:
+ raise _Invalid("Description must be at most 1000 characters")
+ tags = data.get("tags") or []
+ _validate_tags(tags)
+ if _find_by_name(name):
+ raise _Invalid(f"A collection with name {name} already exists", "ConflictException")
+
+ encryption = data.get("encryptionConfig") or {}
+ kms = encryption.get("kmsKeyArn") or ("auto" if encryption.get("aWSOwnedKey") else None)
+ if kms is None:
+ kms = _matching_encryption_key(name)
+ if kms is None:
+ raise _Invalid(
+ f"No matching security policy of encryption type found for collection name: {name}. "
+ "Please create security policy of encryption type for this collection."
+ )
+
+ now = _now_ms()
+ cid = _new_collection_id()
+ endpoint = _collection_endpoint(cid)
+ rec = {
+ "id": cid,
+ "name": name,
+ "status": "CREATING",
+ "type": ctype,
+ "description": data.get("description", ""),
+ "arn": _collection_arn(cid),
+ "kmsKeyArn": kms,
+ "standbyReplicas": standby,
+ "deletionProtection": deletion,
+ "vectorOptions": copy.deepcopy(data.get("vectorOptions")),
+ "createdDate": now,
+ "lastModifiedDate": now,
+ "collectionEndpoint": endpoint,
+ "dashboardEndpoint": f"{endpoint}/_dashboards",
+ }
+ _collections[cid] = rec
+ if tags:
+ _tags[rec["arn"]] = _merge_tags([], tags)
+ _start_provisioning(rec)
+ return json_response({"createCollectionDetail": _collection_detail(rec, _CREATE_FIELDS)})
+
+
+def _batch_get_collection(data):
+ ids, names = data.get("ids"), data.get("names")
+ if bool(ids) == bool(names):
+ raise _Invalid("You must provide either ids or names, but not both")
+ details, errors = [], []
+ for value in ids or names:
+ rec = _collections.get(value) if ids else _find_by_name(value)
+ if rec is None:
+ err = {"id": value} if ids else {"name": value}
+ err.update({"errorCode": "NOT_FOUND", "errorMessage": "The specified Collection is not found."})
+ errors.append(err)
+ else:
+ details.append(_collection_detail(rec, _DETAIL_FIELDS))
+ return json_response({"collectionDetails": details, "collectionErrorDetails": errors})
+
+
+def _list_collections(data):
+ filters = data.get("collectionFilters") or {}
+ items = []
+ for rec in sorted(_collections.values(), key=lambda r: r["createdDate"]):
+ if filters.get("name") and rec["name"] != filters["name"]:
+ continue
+ if filters.get("status") and rec["status"] != filters["status"]:
+ continue
+ items.append(_collection_detail(rec, _SUMMARY_FIELDS))
+ page, token = _page(items, data)
+ out = {"collectionSummaries": page}
+ if token:
+ out["nextToken"] = token
+ return json_response(out)
+
+
+def _update_collection(data):
+ cid = data.get("id")
+ rec = _collections.get(cid)
+ if rec is None:
+ raise _Invalid(f"Collection with id {cid} is not found", "ResourceNotFoundException")
+ if rec["status"] != "ACTIVE":
+ raise _Invalid(f"Collection with id {cid} is not in ACTIVE state", "ConflictException")
+ if "description" in data:
+ rec["description"] = data["description"]
+ if "deletionProtection" in data:
+ _validate_enum(data["deletionProtection"], "deletionProtection", ("ENABLED", "DISABLED"))
+ rec["deletionProtection"] = data["deletionProtection"]
+ if "vectorOptions" in data:
+ rec["vectorOptions"] = copy.deepcopy(data["vectorOptions"])
+ rec["lastModifiedDate"] = _now_ms()
+ return json_response({"updateCollectionDetail": _collection_detail(rec, (
+ "id", "name", "status", "type", "description", "vectorOptions", "arn",
+ "createdDate", "lastModifiedDate", "deletionProtection",
+ ))})
+
+
+def _delete_collection(data):
+ cid = data.get("id")
+ with resource_lock("opensearchserverless", cid or ""):
+ rec = _collections.get(cid)
+ if rec is None:
+ raise _Invalid(f"Collection with id {cid} is not found", "ResourceNotFoundException")
+ if rec["status"] not in ("ACTIVE", "FAILED", "UPDATE_FAILED"):
+ raise _Invalid(f"Collection with id {cid} is in {rec['status']} state", "ConflictException")
+ if rec.get("deletionProtection") == "ENABLED":
+ raise _Invalid(f"Collection with id {cid} has deletion protection enabled")
+ _collections.pop(cid, None)
+ rec["_deleting"] = True
+ _tags.pop(rec["arn"], None)
+ _remove_container(rec.get("_ContainerId"))
+ _remove_volume(rec.get("_VolumeName"))
+ return json_response({"deleteCollectionDetail": {
+ "id": rec["id"], "name": rec["name"], "status": "DELETING",
+ "deletionProtection": rec.get("deletionProtection", "DISABLED"),
+ }})
+
+
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def _validate_tags(tags):
+ if not isinstance(tags, list) or len(tags) > 50:
+ raise _Invalid("Tags must be a list of at most 50 items")
+ for tag in tags:
+ if not isinstance(tag, dict) or not tag.get("key") or "value" not in tag:
+ raise _Invalid("Each tag must have a key and a value")
+
+
+def _merge_tags(existing, new):
+ by_key = {t["key"]: t for t in existing}
+ for tag in new:
+ by_key[tag["key"]] = {"key": tag["key"], "value": tag["value"]}
+ return list(by_key.values())
+
+
+def _resolve_tag_arn(arn):
+ try:
+ spec = parse_arn(arn or "")
+ except ArnParseError:
+ raise _Invalid(f"Invalid resource ARN: {arn}")
+ if spec.service != "aoss" or spec.account_id != get_account_id() or spec.region != get_region():
+ raise _Invalid(f"Invalid resource ARN: {arn}")
+ if not spec.resource.startswith("collection/"):
+ raise _Invalid(f"Invalid resource ARN: {arn}")
+ rec = _collections.get(spec.resource[len("collection/"):])
+ if rec is None or rec["arn"] != arn:
+ raise _Invalid(f"Resource {arn} is not found", "ResourceNotFoundException")
+ return arn
+
+
+def _tag_resource(data):
+ arn = _resolve_tag_arn(data.get("resourceArn"))
+ tags = data.get("tags") or []
+ _validate_tags(tags)
+ merged = _merge_tags(_tags.get(arn) or [], tags)
+ if len(merged) > 50:
+ raise _Invalid("A resource can have at most 50 tags", "ServiceQuotaExceededException")
+ _tags[arn] = merged
+ return json_response({})
+
+
+def _untag_resource(data):
+ arn = _resolve_tag_arn(data.get("resourceArn"))
+ keys = set(data.get("tagKeys") or [])
+ _tags[arn] = [t for t in _tags.get(arn) or [] if t["key"] not in keys]
+ return json_response({})
+
+
+def _list_tags_for_resource(data):
+ arn = _resolve_tag_arn(data.get("resourceArn"))
+ return json_response({"tags": copy.deepcopy(_tags.get(arn) or [])})
+
+
+# ---------------------------------------------------------------------------
+# Engine containers
+# ---------------------------------------------------------------------------
+
+def _get_docker():
+ global _docker_client
+ if _docker_client is None:
+ from ministack.services import opensearch
+
+ _docker_client = opensearch._get_docker()
+ return _docker_client
+
+
+def _dataplane_enabled():
+ from ministack.services import opensearch
+
+ return opensearch.DATAPLANE_ENABLED
+
+
+def _remove_container(container_id):
+ if container_id:
+ from ministack.services import opensearch
+
+ opensearch._remove_container_by_id(container_id)
+
+
+def _volume_name(cid):
+ return f"ministack-aoss-{get_region()}-{cid}-data"
+
+
+def _remove_volume(volume_name):
+ """Best-effort teardown of a collection's persisted data volume."""
+ if not volume_name:
+ return
+ docker = _get_docker()
+ if docker is None:
+ return
+ try:
+ docker.volumes.get(volume_name).remove()
+ except Exception as e:
+ logger.warning("OpenSearch Serverless: failed to remove volume %s: %s", volume_name, e)
+
+
+def _wait_for_engine(host, port, deadline):
+ while time.monotonic() < deadline:
+ try:
+ conn = http.client.HTTPConnection(host, port, timeout=2)
+ conn.request("GET", "/")
+ ok = conn.getresponse().status == 200
+ conn.close()
+ if ok:
+ return True
+ except (OSError, http.client.HTTPException):
+ pass
+ time.sleep(1)
+ return False
+
+
+def _start_provisioning(rec):
+ spawn_background(_provision, rec, thread_name=f"ministack-aoss-start-{rec['id']}")
+
+
+def _provision(rec):
+ """Bring a collection to ACTIVE, starting its engine container when enabled."""
+ cid = rec["id"]
+ container_id, engine, failure = None, None, None
+ volume_name = None
+ if _dataplane_enabled():
+ docker = _get_docker()
+ if docker is None:
+ failure = "Docker is not available to run the collection's OpenSearch engine"
+ else:
+ from ministack.services import opensearch
+
+ labels = {
+ **container_reaper.own_labels(_CONTAINER_LABEL),
+ "com.ministack.service": _CONTAINER_LABEL,
+ "com.ministack.collection": cid,
+ "com.ministack.region": get_region(),
+ }
+ name = f"ministack-aoss-{get_region()}-{cid}"
+ try:
+ if persistence.PERSIST_STATE:
+ # Same collection id survives a restart (persisted state
+ # is keyed by it), so the volume it names is the one a
+ # prior boot already created — a warm boot reattaches it.
+ volume_name = rec.get("_VolumeName") or _volume_name(cid)
+ container_id, host, port = opensearch.start_engine_container(
+ docker, name, labels,
+ volumes={volume_name: {"bind": _ENGINE_DATA_DIR, "mode": "rw"}},
+ )
+ else:
+ container_id, host, port = opensearch.start_engine_container(docker, name, labels)
+ if _wait_for_engine(host, port, time.monotonic() + _ENGINE_READY_TIMEOUT):
+ engine = f"{host}:{port}"
+ else:
+ failure = "The collection's OpenSearch engine did not become ready"
+ except Exception as e:
+ logger.warning("OpenSearch Serverless: engine start failed for %s: %s", cid, e)
+ failure = f"The collection's OpenSearch engine failed to start: {e}"
+ with resource_lock("opensearchserverless", cid):
+ live = _collections.get(cid)
+ orphaned = live is not rec or rec.get("_deleting")
+ if not orphaned:
+ rec["_ContainerId"] = container_id
+ rec["_Engine"] = engine
+ if volume_name:
+ rec["_VolumeName"] = volume_name
+ if failure:
+ rec["status"] = "FAILED"
+ rec["failureCode"] = "INTERNAL_ERROR"
+ rec["failureMessage"] = failure
+ else:
+ rec["status"] = "ACTIVE"
+ rec["lastModifiedDate"] = _now_ms()
+ if orphaned or failure:
+ _remove_container(container_id)
+
+
+def _live_container_ids():
+ return {rec.get("_ContainerId") for _k, rec in _collections.all_items() if rec.get("_ContainerId")}
+
+
+container_reaper.register_live_ids(_CONTAINER_LABEL, _live_container_ids)
+
+
+# ---------------------------------------------------------------------------
+# Data plane
+# ---------------------------------------------------------------------------
+
+# Host of a collection endpoint: <collection-id>.<region>.aoss.<suffix>[:port]
+_DATAPLANE_HOST_RE = re.compile(r"^(?P<id>[a-z0-9]{3,40})\.[a-z0-9-]+\.aoss\.")
+
+# AWS docs "Supported operations and plugins in Amazon OpenSearch Serverless" (serverless-genref.html):
+# everything else is proxied, these answer 404 as they do on real AOSS.
+_DENIED_FIRST_SEGMENTS = {"_refresh", "_cluster", "_nodes", "_reindex", "_snapshot"}
+
+# Write operations that carry a caller-chosen document id; AWS docs "Choosing
+# a collection type" refuse these on a TIMESERIES collection.
+_TIMESERIES_RESTRICTED = {("POST", "_create"), ("PUT", "_create"), ("POST", "_update"), ("POST", "_doc"), ("PUT", "_doc")}
+
+
+def _dataplane_denied(path, segments, query_params):
+ if path == "":
+ return True
+ if segments[0] in _DENIED_FIRST_SEGMENTS:
+ return True
+ if path == "_cat/nodes":
+ return True
+ if len(segments) == 2 and segments[1] == "_refresh":
+ return True
+ if path == "_search/scroll" or "scroll" in (query_params or {}):
+ return True
+ return False
+
+
+def _operation_supported(method, raw_path, collection_type, query_params=None):
+ path = raw_path.strip("/")
+ segments = path.split("/") if path else [""]
+ if _dataplane_denied(path, segments, query_params):
+ return False
+ if (
+ collection_type == "TIMESERIES" and len(segments) == 3
+ and not segments[0].startswith("_") and segments[2]
+ ):
+ return (method, segments[1]) not in _TIMESERIES_RESTRICTED
+ return True
+
+
+def _aoss_error(status, reason, error_type):
+ body = {"status": status, "request-id": new_uuid(), "error": {"reason": reason, "type": error_type}}
+ return status, {"Content-Type": "application/json"}, json.dumps(body).encode()
+
+
+def _signed_for_aoss(headers, query_params):
+ auth = headers.get("authorization", "")
+ credential = auth if auth else " ".join(query_params.get("X-Amz-Credential", []))
+ match = re.search(r"[^/\s=]+/\d{8}/[^/]+/([^/]+)/aws4_request", credential)
+ return bool(match) and match.group(1) == "aoss"
+
+
+_HOP_BY_HOP = {
+ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
+ "transfer-encoding", "upgrade", "content-length",
+}
+
+
+def _proxy(engine, method, target, headers, body):
+ host, _, port = engine.rpartition(":")
+ forward = {
+ k: v for k, v in headers.items()
+ if k not in _HOP_BY_HOP and k != "host" and k != "authorization" and not k.startswith("x-amz-")
+ }
+ conn = http.client.HTTPConnection(host, int(port), timeout=_PROXY_TIMEOUT)
+ try:
+ conn.request(method, target, body=body if body else None, headers=forward)
+ resp = conn.getresponse()
+ data = resp.read()
+ out_headers = {
+ k: v for k, v in resp.getheaders() if k.lower() not in _HOP_BY_HOP
+ }
+ return resp.status, out_headers, data
+ finally:
+ conn.close()
+
+
+def _find_collection_anywhere(collection_id):
+ """Collection ids are globally unique, like the endpoint hostnames built from them."""
+ return next((rec for (_a, _r, cid), rec in _collections.all_items() if cid == collection_id), None)
+
+
+async def handle_dataplane(method, host, raw_path, query_string, headers, body, query_params):
+ """Serve a request addressed to a collection endpoint, or None if ``host`` is not one."""
+ match = _DATAPLANE_HOST_RE.match((host or "").split(":")[0].lower())
+ if not match:
+ return None
+ rec = _find_collection_anywhere(match.group("id"))
+ if rec is None:
+ return _aoss_error(404, "404 Not Found", "NotFound")
+ # AWS docs "Troubleshooting Amazon OpenSearch Serverless": every request must be
+ # SigV4-signed for service `aoss` and carry x-amz-content-sha256, else 403.
+ if not _signed_for_aoss(headers, query_params) or not headers.get("x-amz-content-sha256"):
+ return _aoss_error(403, "403 Forbidden", "Forbidden")
+ # 404 for unsupported APIs such as _refresh: langchain-ai/langchainjs#2302 quoting AWS.
+ if not _operation_supported(method, raw_path, rec["type"], query_params):
+ return _aoss_error(404, "404 Not Found", "NotFound")
+ engine = rec.get("_Engine")
+ if rec["status"] != "ACTIVE" or not engine:
+ return _aoss_error(503, "503 Service Unavailable", "ServiceUnavailable")
+ target = raw_path + (f"?{query_string}" if query_string else "")
+ try:
+ status, resp_headers, data = await run_offloop(_proxy, engine, method, target, headers, body)
+ except (OSError, http.client.HTTPException) as e:
+ logger.warning("OpenSearch Serverless: engine for %s unreachable: %s", rec["id"], e)
+ return _aoss_error(503, "503 Service Unavailable", "ServiceUnavailable")
+ return status, resp_headers, data
+
+
+# ---------------------------------------------------------------------------
+# Control-plane dispatcher
+# ---------------------------------------------------------------------------
+
+_HANDLERS = {
+ "CreateCollection": _create_collection,
+ "BatchGetCollection": _batch_get_collection,
+ "ListCollections": _list_collections,
+ "UpdateCollection": _update_collection,
+ "DeleteCollection": _delete_collection,
+ "CreateSecurityPolicy": _create_security_policy,
+ "GetSecurityPolicy": _get_security_policy,
+ "UpdateSecurityPolicy": _update_security_policy,
+ "DeleteSecurityPolicy": _delete_security_policy,
+ "ListSecurityPolicies": _list_security_policies,
+ "CreateAccessPolicy": _create_access_policy,
+ "GetAccessPolicy": _get_access_policy,
+ "UpdateAccessPolicy": _update_access_policy,
+ "DeleteAccessPolicy": _delete_access_policy,
+ "ListAccessPolicies": _list_access_policies,
+ "GetPoliciesStats": _get_policies_stats,
+ "TagResource": _tag_resource,
+ "UntagResource": _untag_resource,
+ "ListTagsForResource": _list_tags_for_resource,
+}
+
+# Container teardown talks to Docker; run those off the event loop.
+_OFFLOOP = {"DeleteCollection"}
+
+
+async def handle_request(method, path, headers, body, query_params):
+ target = headers.get("x-amz-target", "")
+ action = target.split(".", 1)[1] if target.startswith("OpenSearchServerless.") else ""
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _error("SerializationException", "Invalid JSON in request body")
+ if not isinstance(data, dict):
+ return _error("SerializationException", "Request body must be a JSON object")
+ handler = _HANDLERS.get(action)
+ if handler is None:
+ return _error("UnknownOperationException", f"Unknown operation: {action or target}")
+ try:
+ if action in _OFFLOOP:
+ return await run_offloop(handler, data)
+ return handler(data)
+ except _Invalid as e:
+ return _error(e.code, e.message)
diff --git a/tests/conftest.py b/tests/conftest.py
index f8042d8b..1a69eb00 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -664,6 +664,11 @@ def opensearch():
return make_client("opensearch")
[email protected](scope="session")
+def aoss():
+ return make_client("opensearchserverless")
+
+
@pytest.fixture(scope="session")
def kms_client():
return make_client("kms")
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 0e933afc..ea0717b6 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2334,6 +2334,12 @@ class TestActionExtraction:
assert extract_iam_action("dynamodb", "POST", "/", {"x-amz-target": "DynamoDB_20120810.PutItem"}, b"", {}) == "dynamodb:PutItem"
assert extract_iam_action("kms", "POST", "/", {"x-amz-target": "TrentService.Encrypt"}, b"", {}) == "kms:Encrypt"
+ def test_opensearchserverless_target_protocol(self):
+ from ministack.core.iam_actions import extract_iam_action
+ assert extract_iam_action(
+ "opensearchserverless", "POST", "/", {"x-amz-target": "OpenSearchServerless.CreateCollection"}, b"", {}
+ ) == "aoss:CreateCollection"
+
def test_s3_rest(self):
from ministack.core.iam_actions import extract_iam_action
assert extract_iam_action("s3", "GET", "/", {}, b"", {}) == "s3:ListAllMyBuckets"
diff --git a/tests/test_opensearchserverless.py b/tests/test_opensearchserverless.py
new file mode 100644
index 00000000..64a96c14
--- /dev/null
+++ b/tests/test_opensearchserverless.py
@@ -0,0 +1,595 @@
+"""OpenSearch Serverless (AOSS) tests.
+
+Control plane: collections, encryption/network security policies, data access
+policies, tags. Data plane: the collection endpoint is served through the
+gateway and proxied to a real OpenSearch container when the server runs with
+``OPENSEARCH_DATAPLANE=1`` (``data_plane`` lane).
+"""
+
+import base64
+import hashlib
+import http.client
+import json
+import os
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+
+import boto3
+import pytest
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from botocore.exceptions import ClientError
+
+from ministack.services import opensearchserverless as aoss_module
+
+from conftest import ENDPOINT, GATEWAY_PORT
+
+REGION = "us-east-1"
+
+
+def _uid():
+ return uuid.uuid4().hex[:8]
+
+
+def _enc_policy(*resources):
+ return json.dumps({
+ "Rules": [{"ResourceType": "collection", "Resource": [f"collection/{r}" for r in resources]}],
+ "AWSOwnedKey": True,
+ })
+
+
+def _net_policy(name):
+ return json.dumps([{
+ "Rules": [{"ResourceType": "collection", "Resource": [f"collection/{name}"]}],
+ "AllowFromPublic": True,
+ }])
+
+
+def _data_policy(name, principal="arn:aws:iam::000000000000:role/reader"):
+ return json.dumps([{
+ "Rules": [
+ {"ResourceType": "collection", "Resource": [f"collection/{name}"], "Permission": ["aoss:*"]},
+ {"ResourceType": "index", "Resource": [f"index/{name}/*"],
+ "Permission": ["aoss:DescribeIndex", "aoss:ReadDocument"]},
+ ],
+ "Principal": [principal],
+ }])
+
+
+def _wait_status(aoss, cid, timeout=240):
+ deadline = time.time() + timeout
+ while True:
+ detail = aoss.batch_get_collection(ids=[cid])["collectionDetails"][0]
+ if detail["status"] != "CREATING" or time.time() > deadline:
+ return detail
+ time.sleep(1)
+
+
+def collection(aoss):
+ """A collection with its encryption policy; deleted afterwards."""
+ name = f"c-{_uid()}"
+ aoss.create_security_policy(name=f"{name}-enc", type="encryption", policy=_enc_policy(name))
+ created = aoss.create_collection(name=name, type="SEARCH")["createCollectionDetail"]
+ yield _wait_status(aoss, created["id"])
+ try:
+ aoss.delete_collection(id=created["id"])
+ except ClientError:
+ pass
+ aoss.delete_security_policy(name=f"{name}-enc", type="encryption")
+
+
+# ---------------------------------------------------------------------------
+# Security policies
+# ---------------------------------------------------------------------------
+
+def test_aoss_security_policy_lifecycle(aoss):
+ name = f"p-{_uid()}"
+ created = aoss.create_security_policy(
+ name=name, type="encryption", policy=_enc_policy(name), description="enc"
+ )["securityPolicyDetail"]
+ try:
+ assert created["type"] == "encryption"
+ assert created["policy"] == json.loads(_enc_policy(name))
+ # AWS docs example: policyVersion is base64("<lastModifiedDate>_<n>").
+ assert base64.b64decode(created["policyVersion"]).decode() == f"{created['lastModifiedDate']}_1"
+
+ got = aoss.get_security_policy(name=name, type="encryption")["securityPolicyDetail"]
+ assert got == created
+
+ with pytest.raises(ClientError) as exc:
+ aoss.update_security_policy(
+ name=name, type="encryption", policyVersion="MTY2MzY5MzIxNzgyNl8x",
+ policy=_enc_policy(name, f"{name}x"),
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+ time.sleep(0.01)
+ updated = aoss.update_security_policy(
+ name=name, type="encryption", policyVersion=created["policyVersion"],
+ policy=_enc_policy(name, f"{name}x"),
+ )["securityPolicyDetail"]
+ assert updated["policyVersion"] != created["policyVersion"]
+ assert updated["policy"]["Rules"][0]["Resource"] == [f"collection/{name}", f"collection/{name}x"]
+
+ summaries = aoss.list_security_policies(type="encryption")["securityPolicySummaries"]
+ summary = next(s for s in summaries if s["name"] == name)
+ assert "policy" not in summary
+ assert summary["policyVersion"] == updated["policyVersion"]
+ assert not any(s["name"] == name for s in aoss.list_security_policies(type="network")["securityPolicySummaries"])
+ finally:
+ aoss.delete_security_policy(name=name, type="encryption")
+ with pytest.raises(ClientError) as exc:
+ aoss.get_security_policy(name=name, type="encryption")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_aoss_security_policy_duplicate_conflict(aoss):
+ name = f"p-{_uid()}"
+ aoss.create_security_policy(name=name, type="network", policy=_net_policy(name))
+ try:
+ with pytest.raises(ClientError) as exc:
+ aoss.create_security_policy(name=name, type="network", policy=_net_policy(name))
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+ # Names are per type: an encryption policy may reuse it.
+ aoss.create_security_policy(name=name, type="encryption", policy=_enc_policy(f"{name}-other"))
+ aoss.delete_security_policy(name=name, type="encryption")
+ finally:
+ aoss.delete_security_policy(name=name, type="network")
+
+
[email protected]("policy", [
+ "not json",
+ json.dumps({"Rules": [], "AWSOwnedKey": True}),
+ json.dumps({"Rules": [{"ResourceType": "index", "Resource": ["index/x/*"]}], "AWSOwnedKey": True}),
+ json.dumps({"Rules": [{"ResourceType": "collection", "Resource": ["collection/x"]}]}),
+])
+def test_aoss_encryption_policy_validation(aoss, policy):
+ with pytest.raises(ClientError) as exc:
+ aoss.create_security_policy(name=f"p-{_uid()}", type="encryption", policy=policy)
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+
+def test_aoss_encryption_policy_rejects_resource_in_another_policy(aoss):
+ name = f"p-{_uid()}"
+ aoss.create_security_policy(name=name, type="encryption", policy=_enc_policy(name))
+ try:
+ with pytest.raises(ClientError) as exc:
+ aoss.create_security_policy(name=f"{name}-2", type="encryption", policy=_enc_policy(name))
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ aoss.delete_security_policy(name=name, type="encryption")
+
+
+# ---------------------------------------------------------------------------
+# Access policies
+# ---------------------------------------------------------------------------
+
+def test_aoss_access_policy_lifecycle(aoss):
+ name = f"a-{_uid()}"
+ created = aoss.create_access_policy(name=name, type="data", policy=_data_policy(name))["accessPolicyDetail"]
+ try:
+ assert created["policy"] == json.loads(_data_policy(name))
+ got = aoss.get_access_policy(name=name, type="data")["accessPolicyDetail"]
+ assert got["policyVersion"] == created["policyVersion"]
+
+ time.sleep(0.01)
+ updated = aoss.update_access_policy(
+ name=name, type="data", policyVersion=created["policyVersion"],
+ policy=_data_policy(name, "arn:aws:iam::000000000000:role/writer"),
+ )["accessPolicyDetail"]
+ assert updated["policy"][0]["Principal"] == ["arn:aws:iam::000000000000:role/writer"]
+ # The superseded version can no longer update.
+ with pytest.raises(ClientError) as exc:
+ aoss.update_access_policy(
+ name=name, type="data", policyVersion=created["policyVersion"], description="x",
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+ listed = aoss.list_access_policies(type="data", resource=[f"collection/{name}"])["accessPolicySummaries"]
+ assert [p["name"] for p in listed] == [name]
+ assert aoss.list_access_policies(type="data", resource=["collection/nothing-here"])["accessPolicySummaries"] == []
+
+ stats = aoss.get_policies_stats()
+ assert stats["AccessPolicyStats"]["DataPolicyCount"] >= 1
+ finally:
+ aoss.delete_access_policy(name=name, type="data")
+ with pytest.raises(ClientError) as exc:
+ aoss.delete_access_policy(name=name, type="data")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
[email protected]("statement", [
+ {"Rules": [{"ResourceType": "index", "Resource": ["index/x/*"], "Permission": ["aoss:ReadDocument"]}],
+ "Principal": []},
+ {"Rules": [{"ResourceType": "index", "Resource": ["index/x/*"], "Permission": ["aoss:ReadDocument"]}],
+ "Principal": ["arn:aws:iam::000000000000:role/*"]},
+ {"Rules": [{"ResourceType": "index", "Resource": ["index/x/*"], "Permission": ["aoss:CreateCollectionItems"]}],
+ "Principal": ["arn:aws:iam::000000000000:role/r"]},
+])
+def test_aoss_data_policy_validation(aoss, statement):
+ with pytest.raises(ClientError) as exc:
+ aoss.create_access_policy(name=f"a-{_uid()}", type="data", policy=json.dumps([statement]))
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+
+# ---------------------------------------------------------------------------
+# Collections
+# ---------------------------------------------------------------------------
+
+def test_aoss_collection_requires_matching_encryption_policy(aoss):
+ name = f"c-{_uid()}"
+ with pytest.raises(ClientError) as exc:
+ aoss.create_collection(name=name, type="SEARCH")
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ assert "No matching security policy of encryption type" in exc.value.response["Error"]["Message"]
+
+
+def test_aoss_collection_prefix_encryption_policy_matches(aoss):
+ prefix = f"pre{_uid()}"
+ aoss.create_security_policy(name=f"{prefix}-enc", type="encryption", policy=_enc_policy(f"{prefix}*"))
+ try:
+ created = aoss.create_collection(name=f"{prefix}-logs", type="TIMESERIES")["createCollectionDetail"]
+ assert created["kmsKeyArn"] == "auto"
+ _wait_status(aoss, created["id"])
+ aoss.delete_collection(id=created["id"])
+ finally:
+ aoss.delete_security_policy(name=f"{prefix}-enc", type="encryption")
+
+
+def test_aoss_collection_lifecycle(aoss, collection):
+ cid, name = collection["id"], collection["name"]
+ assert collection["status"] == "ACTIVE"
+ assert collection["arn"] == f"arn:aws:aoss:{REGION}:{collection['arn'].split(':')[4]}:collection/{cid}"
+ assert len(cid) == 20 and cid.isalnum() and cid.islower()
+ assert collection["collectionEndpoint"].endswith(f"://{cid}.{REGION}.aoss.localhost:{GATEWAY_PORT}")
+ assert collection["dashboardEndpoint"] == f"{collection['collectionEndpoint']}/_dashboards"
+ assert collection["kmsKeyArn"] == "auto"
+
+ by_name = aoss.batch_get_collection(names=[name, "missing-coll"])
+ assert [d["id"] for d in by_name["collectionDetails"]] == [cid]
+ assert by_name["collectionErrorDetails"] == [
+ {"name": "missing-coll", "errorCode": "NOT_FOUND", "errorMessage": "The specified Collection is not found."}
+ ]
+
+ summaries = aoss.list_collections(collectionFilters={"name": name})["collectionSummaries"]
+ assert summaries == [{"id": cid, "name": name, "status": "ACTIVE", "arn": collection["arn"], "kmsKeyArn": "auto"}]
+
+ updated = aoss.update_collection(id=cid, description="new description")["updateCollectionDetail"]
+ assert updated["description"] == "new description"
+
+ with pytest.raises(ClientError) as exc:
+ aoss.create_collection(name=name, type="SEARCH")
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+
+ deleted = aoss.delete_collection(id=cid)["deleteCollectionDetail"]
+ assert deleted["status"] == "DELETING"
+ assert aoss.batch_get_collection(ids=[cid])["collectionDetails"] == []
+ with pytest.raises(ClientError) as exc:
+ aoss.delete_collection(id=cid)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_aoss_collection_deletion_protection(aoss, collection):
+ aoss.update_collection(id=collection["id"], deletionProtection="ENABLED")
+ with pytest.raises(ClientError) as exc:
+ aoss.delete_collection(id=collection["id"])
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ aoss.update_collection(id=collection["id"], deletionProtection="DISABLED")
+
+
+def test_aoss_tags(aoss, collection):
+ arn = collection["arn"]
+ aoss.tag_resource(resourceArn=arn, tags=[{"key": "a", "value": "1"}, {"key": "b", "value": "2"}])
+ aoss.tag_resource(resourceArn=arn, tags=[{"key": "a", "value": "3"}])
+ aoss.untag_resource(resourceArn=arn, tagKeys=["b"])
+ assert aoss.list_tags_for_resource(resourceArn=arn)["tags"] == [{"key": "a", "value": "3"}]
+ with pytest.raises(ClientError) as exc:
+ aoss.list_tags_for_resource(resourceArn=arn.replace(collection["id"], "zzzzzzzzzzzzzzzzzzzz"))
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# PERSIST_STATE volume persistence
+# ---------------------------------------------------------------------------
+
+def _fake_docker_with_volumes():
+ """Minimal docker double recording `containers.run()` kwargs and `volumes.get(name).remove()` calls."""
+ runs = []
+ containers = {}
+ removed_volumes = []
+
+ class FakeContainer:
+ def __init__(self, name):
+ self.id = f"cid-{name}"
+ self.name = name
+ self.attrs = {"NetworkSettings": {"Networks": {}, "Ports": {"9200/tcp": [{"HostPort": "19200"}]}}}
+
+ def reload(self):
+ pass
+
+ def stop(self, timeout=None):
+ pass
+
+ def remove(self, force=False, v=False):
+ pass
+
+ class FakeContainers:
+ def run(self, **kwargs):
+ runs.append(kwargs)
+ container = FakeContainer(kwargs["name"])
+ containers[container.id] = container
+ containers[container.name] = container
+ return container
+
+ def get(self, identifier):
+ return containers[identifier]
+
+ def list(self, all=False, filters=None):
+ return []
+
+ class FakeVolume:
+ def __init__(self, name):
+ self.name = name
+
+ def remove(self):
+ removed_volumes.append(self.name)
+
+ class FakeVolumes:
+ def get(self, name):
+ return FakeVolume(name)
+
+ class FakeDocker:
+ def __init__(self):
+ self.containers = FakeContainers()
+ self.volumes = FakeVolumes()
+
+ return FakeDocker(), runs, removed_volumes
+
+
+def test_aoss_persist_state_volume_lifecycle(monkeypatch):
+ """PERSIST_STATE=1: the collection engine's data dir binds to a named Docker volume,
+ recorded on the collection, reused by a warm-boot re-provision (`load_persisted_state`),
+ and removed by DeleteCollection."""
+ from ministack.core import persistence
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import opensearchserverless as m
+
+ fake_docker, runs, removed_volumes = _fake_docker_with_volumes()
+
+ set_request_account_id("000000000000")
+ set_request_region("us-east-1")
+ monkeypatch.setattr(m, "_get_docker", lambda: fake_docker)
+ monkeypatch.setattr(m, "_dataplane_enabled", lambda: True)
+ monkeypatch.setattr(m, "_wait_for_engine", lambda *a, **k: True)
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ # Run provisioning synchronously so assertions can follow create/restore
+ # without a join/poll loop.
+ monkeypatch.setattr(m, "spawn_background", lambda fn, *a, **kw: fn(*a))
+
+ m.reset()
+ try:
+ created = json.loads(m._create_collection({
+ "name": "vol-test", "type": "SEARCH", "encryptionConfig": {"aWSOwnedKey": True},
+ })[2])["createCollectionDetail"]
+ cid = created["id"]
+
+ # (1) create requests a named volume mount.
+ assert len(runs) == 1
+ volume_name = m._volume_name(cid)
+ assert runs[0]["volumes"] == {volume_name: {"bind": m._ENGINE_DATA_DIR, "mode": "rw"}}
+
+ # (2) the persisted record carries the volume.
+ rec = m._collections.get(cid)
+ assert rec["status"] == "ACTIVE", rec
+ assert rec["_VolumeName"] == volume_name
+ state = m.get_state()
+
+ # (3) restore (warm boot) reattaches the same volume.
+ m.load_persisted_state(state)
+ assert len(runs) == 2
+ assert runs[1]["name"] == runs[0]["name"]
+ assert runs[1]["volumes"] == {volume_name: {"bind": m._ENGINE_DATA_DIR, "mode": "rw"}}
+ assert m._collections.get(cid)["_VolumeName"] == volume_name
+
+ # (4) delete removes it.
+ m._delete_collection({"id": cid})
+ assert removed_volumes == [volume_name]
+ finally:
+ m.reset()
+
+
+def test_aoss_provision_no_volume_when_not_persisting(monkeypatch):
+ """PERSIST_STATE=0 keeps today's behaviour: no volume is mounted."""
+ from ministack.core import persistence
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import opensearchserverless as m
+
+ fake_docker, runs, removed_volumes = _fake_docker_with_volumes()
+
+ set_request_account_id("000000000000")
+ set_request_region("us-east-1")
+ monkeypatch.setattr(m, "_get_docker", lambda: fake_docker)
+ monkeypatch.setattr(m, "_dataplane_enabled", lambda: True)
+ monkeypatch.setattr(m, "_wait_for_engine", lambda *a, **k: True)
+ monkeypatch.setattr(persistence, "PERSIST_STATE", False)
+ monkeypatch.setattr(m, "spawn_background", lambda fn, *a, **kw: fn(*a))
+
+ m.reset()
+ try:
+ created = json.loads(m._create_collection({
+ "name": "vol-off-test", "type": "SEARCH", "encryptionConfig": {"aWSOwnedKey": True},
+ })[2])["createCollectionDetail"]
+ cid = created["id"]
+ assert len(runs) == 1
+ assert "volumes" not in runs[0]
+ assert "_VolumeName" not in m._collections.get(cid)
+
+ m._delete_collection({"id": cid})
+ assert removed_volumes == []
+ finally:
+ m.reset()
+
+
+def test_aoss_account_isolation():
+ def client(account):
+ return boto3.client("opensearchserverless", endpoint_url=ENDPOINT, region_name=REGION,
+ aws_access_key_id=account, aws_secret_access_key="test")
+ a, b = client("111111111111"), client("222222222222")
+ name = f"iso-{_uid()}"
+ a.create_security_policy(name=name, type="encryption", policy=_enc_policy(name))
+ try:
+ assert not any(p["name"] == name for p in b.list_security_policies(type="encryption")["securityPolicySummaries"])
+ with pytest.raises(ClientError):
+ b.create_collection(name=name, type="SEARCH")
+ finally:
+ a.delete_security_policy(name=name, type="encryption")
+
+
+# ---------------------------------------------------------------------------
+# Data-plane rules (no server needed)
+# ---------------------------------------------------------------------------
+
[email protected]("method,path,query,ctype,supported", [
+ # AWS docs "Supported operations and plugins in Amazon OpenSearch Serverless": denied, answer 404.
+ ("GET", "/", {}, "SEARCH", False),
+ ("HEAD", "/", {}, "SEARCH", False),
+ ("GET", "/_refresh", {}, "SEARCH", False),
+ ("POST", "/_cluster/health", {}, "SEARCH", False),
+ ("GET", "/_nodes", {}, "SEARCH", False),
+ ("POST", "/_reindex", {}, "SEARCH", False),
+ ("PUT", "/_snapshot/repo", {}, "SEARCH", False),
+ ("GET", "/_cat/nodes", {}, "SEARCH", False),
+ ("POST", "/events/_refresh", {}, "SEARCH", False),
+ ("POST", "/_search/scroll", {}, "SEARCH", False),
+ ("GET", "/_search/scroll", {}, "SEARCH", False),
+ ("GET", "/events/_search", {"scroll": ["1m"]}, "SEARCH", False),
+ # Proxied.
+ ("POST", "/_msearch", {}, "SEARCH", True),
+ ("POST", "/events/_msearch", {}, "SEARCH", True),
+ ("POST", "/_mget", {}, "SEARCH", True),
+ ("POST", "/events/_mget", {}, "SEARCH", True),
+ ("POST", "/events/_search", {}, "SEARCH", True),
+ ("PUT", "/events", {}, "SEARCH", True),
+ ("DELETE", "/events", {}, "SEARCH", True),
+ # TIMESERIES: no custom document ids or upserts.
+ ("PUT", "/events/_doc/abc", {}, "SEARCH", True),
+ ("PUT", "/events/_doc/abc", {}, "TIMESERIES", False),
+ ("POST", "/events/_doc/abc", {}, "TIMESERIES", False),
+ ("POST", "/events/_doc", {}, "TIMESERIES", True),
+ ("POST", "/events/_update/abc", {}, "TIMESERIES", False),
+])
+def test_aoss_data_plane_denylist(method, path, query, ctype, supported):
+ assert aoss_module._operation_supported(method, path, ctype, query) is supported
+
+
+# ---------------------------------------------------------------------------
+# Data plane through the gateway (no Docker)
+# ---------------------------------------------------------------------------
+
+def _gateway_request(host_header, method, path, headers=None, body=b""):
+ """Connect to the gateway's own address, sending ``host_header`` as Host —
+ the way test_cloudfront_dataplane.py's ``_get`` reaches a virtual host
+ that doesn't resolve locally."""
+ conn = http.client.HTTPConnection(urllib.parse.urlparse(ENDPOINT).hostname, int(GATEWAY_PORT), timeout=10)
+ try:
+ hdrs = {"Host": host_header}
+ hdrs.update(headers or {})
+ conn.request(method, path, body=body or None, headers=hdrs)
+ resp = conn.getresponse()
+ return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read()
+ finally:
+ conn.close()
+
+
+def _aoss_signed_headers(body=b""):
+ """Satisfies `_signed_for_aoss`'s credential-scope check and the
+ x-amz-content-sha256 requirement without a virtual host DNS can resolve."""
+ return {
+ "authorization": f"AWS4-HMAC-SHA256 Credential=test/20260101/{REGION}/aoss/aws4_request, "
+ "SignedHeaders=host, Signature=" + "0" * 64,
+ "x-amz-content-sha256": hashlib.sha256(body).hexdigest(),
+ }
+
+
+def test_aoss_dataplane_routed_through_gateway(collection):
+ """The collection endpoint's host is routed through the gateway to
+ handle_dataplane (app.py's `_AOSS_COLLECTION_HOST_RE` branch of
+ `_handle_special_data_plane_request`), without Docker or a running engine.
+ """
+ cid = collection["id"]
+ known_host = f"{cid}.{REGION}.aoss.localhost:{GATEWAY_PORT}"
+ unknown_host = f"{'z' * 20}.{REGION}.aoss.localhost:{GATEWAY_PORT}"
+
+ # Unsigned request to a real collection: 403.
+ assert _gateway_request(known_host, "GET", "/events/_search")[0] == 403
+
+ # Unknown collection id host: 404.
+ assert _gateway_request(unknown_host, "GET", "/events/_search", _aoss_signed_headers())[0] == 404
+
+ # Denylisted path, correctly signed for aoss: 404.
+ assert _gateway_request(known_host, "GET", "/_cat/nodes", _aoss_signed_headers())[0] == 404
+
+ # No engine behind it: a supported, signed request answers 503.
+ if os.environ.get("OPENSEARCH_DATAPLANE") != "1":
+ assert _gateway_request(known_host, "GET", "/events/_search", _aoss_signed_headers())[0] == 503
+
+
+# ---------------------------------------------------------------------------
+# Data plane (real engine container)
+# ---------------------------------------------------------------------------
+
+def _signed(endpoint, method, path, body=None, headers=None, service="aoss", content_sha=True):
+ data = json.dumps(body).encode() if body is not None else b""
+ hdrs = {"content-type": "application/json"}
+ if content_sha:
+ hdrs["x-amz-content-sha256"] = hashlib.sha256(data).hexdigest()
+ hdrs.update(headers or {})
+ req = AWSRequest(method=method, url=endpoint + path, data=data, headers=hdrs)
+ SigV4Auth(Credentials("test", "test"), service, REGION).add_auth(req)
+ request = urllib.request.Request(endpoint + path, data=data or None, method=method, headers=dict(req.headers))
+ try:
+ resp = urllib.request.urlopen(request, timeout=60)
+ except urllib.error.HTTPError as e:
+ resp = e
+ return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read()
+
+
+ os.environ.get("OPENSEARCH_DATAPLANE") != "1",
+ reason="set OPENSEARCH_DATAPLANE=1 to run the collection engine smoke",
+)
+def test_aoss_dataplane_index_search_and_aoss_behaviour(aoss, collection):
+ if collection["status"] != "ACTIVE":
+ pytest.skip(f"collection engine unavailable: {collection.get('failureMessage')}")
+ ep = collection["collectionEndpoint"]
+
+ status, _, body = _signed(ep, "PUT", "/docs", {"mappings": {"properties": {"title": {"type": "text"}}}})
+ assert status == 200, body
+ status, _, body = _signed(ep, "PUT", "/docs/_doc/1", {"title": "front door unlocked"})
+ assert status == 201, body
+
+ hits = []
+ for _ in range(30):
+ status, headers, body = _signed(ep, "POST", "/docs/_search", {"query": {"match": {"title": "unlocked"}}})
+ assert status == 200 and "content-encoding" not in headers
+ hits = json.loads(body)["hits"]["hits"]
+ if hits:
+ break
+ time.sleep(0.5)
+ assert [h["_id"] for h in hits] == ["1"]
+
+ # Unsupported APIs answer 404; unsigned / wrongly scoped requests 403.
+ assert _signed(ep, "POST", "/docs/_refresh")[0] == 404
+ assert _signed(ep, "GET", "/_cluster/health")[0] == 404
+ assert _signed(ep, "GET", "/docs", service="es")[0] == 403
+ assert _signed(ep, "GET", "/docs", content_sha=False)[0] == 403
+ req = urllib.request.Request(ep + "/docs", method="GET")
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req, timeout=30)
+ assert exc.value.code == 403