Skip to content

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

feat(cfn): support OpenSearch domains (#1135)

robert-pitt-foodhub0e949ce2fc12
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 2d48c406..5b8bcc97 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -242,6 +242,190 @@ fs.write = function(fd, ...args) {
return { Lambda, LambdaClient, InvokeCommand, waitUntilFunctionActiveV2 };
}
+ // ── OpenSearch stub (REST-JSON, not JSON-RPC) ─────────────────────────
+ function _openSearchRequest(opName, params) {
+ const ep = new URL(process.env.AWS_ENDPOINT_URL || "http://127.0.0.1:4566");
+ const input = Object.assign({}, params || {});
+ const domainName = input.DomainName;
+ const encodedName = encodeURIComponent(domainName || "");
+ let method = "GET";
+ let requestPath;
+ let body;
+
+ switch (opName) {
+ case "CreateDomain":
+ method = "POST";
+ requestPath = "/2021-01-01/opensearch/domain";
+ body = input;
+ break;
+ case "DescribeDomain":
+ requestPath = "/2021-01-01/opensearch/domain/" + encodedName;
+ break;
+ case "DescribeDomains":
+ method = "POST";
+ requestPath = "/2021-01-01/opensearch/domain-info";
+ body = input;
+ break;
+ case "DeleteDomain":
+ method = "DELETE";
+ requestPath = "/2021-01-01/opensearch/domain/" + encodedName;
+ break;
+ case "ListDomainNames":
+ requestPath = "/2021-01-01/opensearch/domain";
+ if (input.EngineType) {
+ requestPath += "?engineType=" + encodeURIComponent(input.EngineType);
+ }
+ break;
+ case "UpdateDomainConfig":
+ method = "POST";
+ requestPath = "/2021-01-01/opensearch/domain/" + encodedName + "/config";
+ delete input.DomainName;
+ body = input;
+ break;
+ case "DescribeDomainConfig":
+ requestPath = "/2021-01-01/opensearch/domain/" + encodedName + "/config";
+ break;
+ case "DescribeDomainChangeProgress":
+ requestPath = "/2021-01-01/opensearch/domain/" + encodedName + "/progress";
+ if (input.ChangeId) {
+ requestPath += "?changeId=" + encodeURIComponent(input.ChangeId);
+ }
+ break;
+ case "ListVersions": {
+ requestPath = "/2021-01-01/opensearch/versions";
+ const query = new URLSearchParams();
+ if (input.MaxResults !== undefined) query.set("maxResults", input.MaxResults);
+ if (input.NextToken) query.set("nextToken", input.NextToken);
+ const suffix = query.toString();
+ if (suffix) requestPath += "?" + suffix;
+ break;
+ }
+ case "GetCompatibleVersions":
+ requestPath = "/2021-01-01/opensearch/compatibleVersions";
+ if (input.DomainName) {
+ requestPath += "?domainName=" + encodeURIComponent(input.DomainName);
+ }
+ break;
+ case "AddTags":
+ method = "POST";
+ requestPath = "/2021-01-01/tags";
+ body = input;
+ break;
+ case "ListTags":
+ requestPath = "/2021-01-01/tags?arn=" + encodeURIComponent(input.ARN || "");
+ break;
+ case "RemoveTags":
+ method = "POST";
+ requestPath = "/2021-01-01/tags-removal";
+ body = input;
+ break;
+ default:
+ return Promise.reject(new Error("Unsupported OpenSearch operation: " + opName));
+ }
+
+ const encodedBody = body === undefined ? "" : JSON.stringify(body);
+ return new Promise((resolve, reject) => {
+ // REST-JSON requests do not carry X-Amz-Target. The lightweight shim
+ // does not cryptographically sign them, but supplies the credential
+ // scope MiniStack's router uses to select OpenSearch. Let Node set Host
+ // from the endpoint: a synthetic ``opensearch.localhost`` host is
+ // indistinguishable from a virtual-hosted S3 bucket at the edge.
+ const headers = {
+ "Accept": "application/json",
+ };
+ const region = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1";
+ const accessKey = process.env.AWS_ACCESS_KEY_ID || "test";
+ headers["Authorization"] =
+ "AWS4-HMAC-SHA256 Credential=" + accessKey + "/19700101/" + region
+ + "/es/aws4_request, SignedHeaders=host, Signature=ministack";
+ if (encodedBody) {
+ headers["Content-Type"] = "application/json";
+ headers["Content-Length"] = Buffer.byteLength(encodedBody);
+ }
+ const req = http.request(
+ {
+ hostname: ep.hostname,
+ port: parseInt(ep.port || "4566", 10),
+ method: method,
+ path: requestPath,
+ headers: headers,
+ },
+ (res) => {
+ const chunks = [];
+ res.on("data", (c) => chunks.push(c));
+ res.on("end", () => {
+ const text = Buffer.concat(chunks).toString();
+ let parsed;
+ try { parsed = text ? JSON.parse(text) : {}; } catch (_) { parsed = {}; }
+ if (res.statusCode >= 400) {
+ const type = parsed.__type || parsed.Code || "OpenSearchServiceError";
+ const code = String(type).split("#").pop();
+ const err = new Error(
+ parsed.Message || parsed.message || text || "OpenSearch service error"
+ );
+ err.statusCode = res.statusCode;
+ err.code = code;
+ err.name = code;
+ reject(err);
+ } else {
+ resolve(parsed);
+ }
+ });
+ }
+ );
+ req.on("error", reject);
+ if (encodedBody) req.write(encodedBody);
+ req.end();
+ });
+ }
+
+ function _makeOpenSearchClientModule() {
+ class OpenSearchClient {
+ constructor(cfg) {
+ const clientConfig = cfg || {};
+ this.config = {
+ apiVersion: clientConfig.apiVersion,
+ region: async () => clientConfig.region
+ || process.env.AWS_REGION
+ || process.env.AWS_DEFAULT_REGION
+ || "us-east-1",
+ };
+ }
+ send(cmd) { return cmd._run(); }
+ }
+
+ class OpenSearch {
+ constructor(_cfg) {}
+ }
+
+ const operations = [
+ "CreateDomain",
+ "DescribeDomain",
+ "DescribeDomains",
+ "DeleteDomain",
+ "ListDomainNames",
+ "UpdateDomainConfig",
+ "DescribeDomainConfig",
+ "DescribeDomainChangeProgress",
+ "ListVersions",
+ "GetCompatibleVersions",
+ "AddTags",
+ "ListTags",
+ "RemoveTags",
+ ];
+ const exports = { OpenSearch, OpenSearchClient };
+ for (const opName of operations) {
+ OpenSearch.prototype[opName[0].toLowerCase() + opName.slice(1)] = function(params) {
+ return _openSearchRequest(opName, params);
+ };
+ exports[opName + "Command"] = class {
+ constructor(params) { this._params = params; }
+ _run() { return _openSearchRequest(opName, this._params); }
+ };
+ }
+ return exports;
+ }
+
// ── Generic JSON-RPC stub (covers SSM, SFN, STS, CloudWatch, Logs, etc.) ─
// Most AWS SDK v3 packages use awsJson1.x: POST / with X-Amz-Target header.
// Ministack's router maps target prefixes to service modules.
@@ -377,6 +561,7 @@ fs.write = function(fd, ...args) {
// ── require() intercept ────────────────────────────────────────────────
const _SPECIFIC_STUBS = {
"@aws-sdk/client-lambda": _makeLambdaClientModule(),
+ "@aws-sdk/client-opensearch": _makeOpenSearchClientModule(),
};
const _SDK_CLIENT_RE = /^@aws-sdk\/client-(.+)$/;
diff --git a/ministack/core/router.py b/ministack/core/router.py
index b8a4f0ed..5e7f8517 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -425,6 +425,11 @@ SERVICE_PATTERNS = {
}
+_OPENSEARCH_PATH_PREFIXES = tuple(
+ prefix.lower() for prefix in SERVICE_PATTERNS["opensearch"]["path_prefixes"]
+)
+
+
def detect_service(method: str, path: str, headers: dict, query_params: dict) -> str:
"""Detect which AWS service a request is targeting."""
host = headers.get("host", "")
@@ -946,6 +951,12 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
return "cloudfront"
if path_lower.startswith("/2013-04-01/"):
return "route53"
+ # OpenSearch's REST-JSON management API may arrive without a usable
+ # SigV4 Authorization header when invoked from Lambda custom-resource
+ # providers. Route its versioned paths before the generic S3 fallback;
+ # otherwise POST UpdateDomainConfig returns S3's XML MethodNotAllowed.
+ if path_lower.startswith(_OPENSEARCH_PATH_PREFIXES):
+ return "opensearch"
if (path_lower.startswith("/v2/apis") or path_lower.startswith("/v2/tags")) and (
re.search(r"appsync-api\.", host) or re.search(r"appsync-realtime-api\.", host)
):
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index ccb7857e..04a871e2 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3,12 +3,14 @@ CloudFormation provisioners — resource create/delete handlers for each AWS res
"""
import base64
+import copy
import hashlib
import io
import json
import logging
import os
import random
+import re
import string
import time
import zipfile
@@ -37,6 +39,7 @@ import ministack.services.iot as _iot
import ministack.services.kinesis as _kinesis
import ministack.services.kms as _kms
import ministack.services.lambda_svc as _lambda_svc
+import ministack.services.opensearch as _opensearch
import ministack.services.pipes as _pipes
import ministack.services.rds as _rds
import ministack.services.route53 as _r53
@@ -124,6 +127,10 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
"""
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "update" in handler:
+ if handler.get("update_with_logical_id"):
+ return handler["update"](
+ physical_id, old_props, new_props, stack_name, logical_id
+ )
return handler["update"](physical_id, old_props, new_props, stack_name)
# Custom resource types
if resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource":
@@ -141,6 +148,116 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
# Resource Provisioners
# ===========================================================================
+# --- OpenSearch Domain ---
+
+_OPENSEARCH_MODELED_PROPERTIES = {
+ "EngineVersion",
+ "ClusterConfig",
+ "EBSOptions",
+ "AccessPolicies",
+ "SnapshotOptions",
+ "CognitoOptions",
+ "EncryptionAtRestOptions",
+ "NodeToNodeEncryptionOptions",
+ "AdvancedOptions",
+ "DomainEndpointOptions",
+ "AdvancedSecurityOptions",
+ "VPCOptions",
+ "AutoTuneOptions",
+ "OffPeakWindowOptions",
+ "SoftwareUpdateOptions",
+}
+
+
+def _opensearch_physical_name(stack_name, logical_id):
+ """Generate a valid 28-character OpenSearch name without losing its suffix."""
+ source = f"{stack_name}-{logical_id}".lower()
+ prefix = re.sub(r"[^a-z0-9-]", "-", source).strip("-")
+ if not prefix or not prefix[0].isalpha():
+ prefix = f"d-{prefix}"
+ suffix = new_uuid().replace("-", "")[:8]
+ prefix = prefix[:19].rstrip("-") or "domain"
+ return f"{prefix}-{suffix}"
+
+
+def _opensearch_create_payload(props, domain_name):
+ desired = copy.deepcopy(props or {})
+ tags = desired.pop("Tags", [])
+ desired["DomainName"] = domain_name
+ desired["TagList"] = copy.deepcopy(tags)
+ if isinstance(desired.get("AccessPolicies"), (dict, list)):
+ desired["AccessPolicies"] = json.dumps(
+ desired["AccessPolicies"], sort_keys=True, separators=(",", ":")
+ )
+ compatibility = {
+ key: copy.deepcopy(value)
+ for key, value in (props or {}).items()
+ if key not in _OPENSEARCH_MODELED_PROPERTIES
+ and key not in {"DomainName", "Tags"}
+ }
+ return desired, compatibility
+
+
+def _opensearch_attributes(rec):
+ endpoint = rec.get("Endpoint") or (rec.get("Endpoints") or {}).get("vpc")
+ if not endpoint:
+ raise ValueError(f"OpenSearch domain {rec.get('DomainName', '')} has no endpoint")
+ arn = rec["ARN"]
+ return {
+ "Arn": arn,
+ "DomainArn": arn,
+ "DomainEndpoint": endpoint,
+ "Id": rec["DomainId"],
+ }
+
+
+def _opensearch_domain_create(logical_id, props, stack_name):
+ name = props.get("DomainName") or _opensearch_physical_name(stack_name, logical_id)
+ payload, compatibility = _opensearch_create_payload(props, name)
+ rec = None
+ try:
+ rec = _opensearch.create_domain_record(payload, compatibility)
+ return name, _opensearch_attributes(rec)
+ except Exception:
+ # Only delete if this call actually allocated the record. In
+ # particular, a duplicate-name error must not delete the pre-existing
+ # domain that caused it.
+ if rec is not None:
+ _opensearch.delete_domain_record(name, missing_ok=True)
+ raise
+
+
+def _opensearch_domain_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ old_was_explicit = "DomainName" in old_props
+ new_is_explicit = "DomainName" in new_props
+ replacement_required = (
+ (new_is_explicit and new_props.get("DomainName") != physical_id)
+ or (old_was_explicit and not new_is_explicit)
+ )
+
+ if replacement_required:
+ replacement_logical_id = logical_id or physical_id
+ new_id, attrs = _opensearch_domain_create(
+ replacement_logical_id, new_props, stack_name
+ )
+ try:
+ _opensearch.delete_domain_record(physical_id, missing_ok=True)
+ except Exception:
+ _opensearch.delete_domain_record(new_id, missing_ok=True)
+ raise
+ return new_id, attrs
+
+ payload, compatibility = _opensearch_create_payload(new_props, physical_id)
+ rec = _opensearch.update_domain_from_cloudformation(
+ physical_id, payload, compatibility
+ )
+ return physical_id, _opensearch_attributes(rec)
+
+
+def _opensearch_domain_delete(physical_id, props):
+ _opensearch.delete_domain_record(physical_id, missing_ok=True)
+
# --- S3 Bucket ---
def _s3_create(logical_id, props, stack_name):
@@ -4422,6 +4539,12 @@ def _s3tables_table_delete(physical_id, props):
_RESOURCE_HANDLERS = {
+ "AWS::OpenSearchService::Domain": {
+ "create": _opensearch_domain_create,
+ "update": _opensearch_domain_update,
+ "update_with_logical_id": True,
+ "delete": _opensearch_domain_delete,
+ },
"AWS::S3::Bucket": {"create": _s3_create, "update": _s3_update, "delete": _s3_delete},
"AWS::S3::BucketPolicy": {"create": _s3_bucket_policy_create, "delete": _s3_bucket_policy_delete},
"AWS::S3Tables::TableBucket": {"create": _s3tables_bucket_create, "delete": _s3tables_bucket_delete},
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 3e529756..87f89de8 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -135,7 +135,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
)
else:
physical_id, attrs = _update_resource(
- resource_type, old_pid, old_props, resolved_props, stack_name
+ resource_type, old_pid, old_props, resolved_props,
+ stack_name, logical_id
)
else:
if _is_custom_resource(resource_type):
diff --git a/ministack/services/opensearch.py b/ministack/services/opensearch.py
index ff64ec1b..8e2cc5a3 100644
--- a/ministack/services/opensearch.py
+++ b/ministack/services/opensearch.py
@@ -74,6 +74,24 @@ _SUPPORTED_VERSIONS = [
_DEFAULT_VERSION = "OpenSearch_3.5"
+_MODELED_DOMAIN_PROPERTIES = (
+ "EngineVersion",
+ "ClusterConfig",
+ "EBSOptions",
+ "AccessPolicies",
+ "SnapshotOptions",
+ "CognitoOptions",
+ "EncryptionAtRestOptions",
+ "NodeToNodeEncryptionOptions",
+ "AdvancedOptions",
+ "DomainEndpointOptions",
+ "AdvancedSecurityOptions",
+ "VPCOptions",
+ "AutoTuneOptions",
+ "OffPeakWindowOptions",
+ "SoftwareUpdateOptions",
+)
+
# AWS allows lowercase letters, digits, hyphens; first character must be
# lowercase letter; 3-28 chars.
_NAME_RE = re.compile(r"^[a-z][a-z0-9\-]{2,27}$")
@@ -93,6 +111,16 @@ _state_lock = threading.Lock()
_docker_client = None
+class OpenSearchServiceError(ValueError):
+ """Actionable service error shared by HTTP and internal callers."""
+
+ def __init__(self, status, code, message):
+ super().__init__(message)
+ self.status = status
+ self.code = code
+ self.message = message
+
+
def reset():
_domains.clear()
_tags.clear()
@@ -181,7 +209,13 @@ def _engine_type(version: str) -> str:
def _public(d: dict) -> dict:
"""Strip internal _-prefixed bookkeeping fields before serialising."""
- out = {k: v for k, v in d.items() if not k.startswith("_")}
+ out = copy.deepcopy({k: v for k, v in d.items() if not k.startswith("_")})
+ # MasterUserOptions is an input-only shape and may contain a plaintext
+ # password. AWS does not return it from DescribeDomain, and neither should
+ # MiniStack's raw JSON response.
+ advanced_security = out.get("AdvancedSecurityOptions")
+ if isinstance(advanced_security, dict):
+ advanced_security.pop("MasterUserOptions", None)
if not out.get("VPCOptions"):
out.pop("VPCOptions", None)
return out
@@ -333,6 +367,20 @@ def _teardown_dataplane(rec: dict) -> None:
pass
+def _teardown_named_dataplane(domain_name: str) -> None:
+ """Best-effort cleanup for a create that failed before returning a record."""
+ docker = _get_docker()
+ if docker is None:
+ return
+ for name in (_container_name(domain_name), _dashboards_container_name(domain_name)):
+ try:
+ c = docker.containers.get(name)
+ c.stop(timeout=2)
+ c.remove(force=True)
+ except Exception:
+ pass
+
+
# ---------------------------------------------------------------------------
# DomainStatus / DomainConfig builders
# ---------------------------------------------------------------------------
@@ -421,7 +469,9 @@ def _new_domain_record(name, payload):
"ClusterConfig": cluster_cfg,
"EBSOptions": ebs_opts,
"AccessPolicies": access_policies,
- "SnapshotOptions": {"AutomatedSnapshotStartHour": 0},
+ "SnapshotOptions": payload.get(
+ "SnapshotOptions", {"AutomatedSnapshotStartHour": 0}
+ ),
"CognitoOptions": payload.get("CognitoOptions", {"Enabled": False}),
"EncryptionAtRestOptions": payload.get(
"EncryptionAtRestOptions", {"Enabled": False}
@@ -448,10 +498,14 @@ def _new_domain_record(name, payload):
"AdvancedSecurityOptions",
{"Enabled": False, "InternalUserDatabaseEnabled": False},
),
- "AutoTuneOptions": {"State": "DISABLED"},
+ "AutoTuneOptions": payload.get("AutoTuneOptions", {"State": "DISABLED"}),
"ChangeProgressDetails": {},
- "OffPeakWindowOptions": {"Enabled": False},
- "SoftwareUpdateOptions": {"AutoSoftwareUpdateEnabled": False},
+ "OffPeakWindowOptions": payload.get(
+ "OffPeakWindowOptions", {"Enabled": False}
+ ),
+ "SoftwareUpdateOptions": payload.get(
+ "SoftwareUpdateOptions", {"AutoSoftwareUpdateEnabled": False}
+ ),
"_Endpoint": endpoint,
"_CreatedTime": _now(),
"_UpdatedTime": _now(),
@@ -494,7 +548,11 @@ def _domain_config(rec: dict) -> dict:
"NodeToNodeEncryptionOptions": wrap(rec["NodeToNodeEncryptionOptions"]),
"AdvancedOptions": wrap(rec["AdvancedOptions"]),
"DomainEndpointOptions": wrap(rec["DomainEndpointOptions"]),
- "AdvancedSecurityOptions": wrap(rec["AdvancedSecurityOptions"]),
+ "AdvancedSecurityOptions": wrap({
+ k: copy.deepcopy(v)
+ for k, v in rec["AdvancedSecurityOptions"].items()
+ if k != "MasterUserOptions"
+ }),
"AutoTuneOptions": wrap(rec["AutoTuneOptions"]),
"ChangeProgressDetails": rec.get("ChangeProgressDetails", {}),
"OffPeakWindowOptions": wrap(rec["OffPeakWindowOptions"]),
@@ -505,6 +563,169 @@ def _domain_config(rec: dict) -> dict:
return config
+def _normalise_tags(tag_list):
+ """Return an exact, detached tag set with the last value winning by key."""
+ by_key = {}
+ for tag in tag_list or []:
+ detached = copy.deepcopy(tag)
+ by_key[detached.get("Key", "")] = detached
+ return list(by_key.values())
+
+
+def _desired_modeled_configuration(payload):
+ """Expand a full create-shaped payload into the desired domain state."""
+ return {
+ "EngineVersion": copy.deepcopy(payload.get("EngineVersion", _DEFAULT_VERSION)),
+ "ClusterConfig": _default_cluster_config(copy.deepcopy(payload.get("ClusterConfig"))),
+ "EBSOptions": _default_ebs_options(copy.deepcopy(payload.get("EBSOptions"))),
+ "AccessPolicies": copy.deepcopy(payload.get("AccessPolicies", "")),
+ "SnapshotOptions": copy.deepcopy(payload.get(
+ "SnapshotOptions", {"AutomatedSnapshotStartHour": 0}
+ )),
+ "CognitoOptions": copy.deepcopy(payload.get("CognitoOptions", {"Enabled": False})),
+ "EncryptionAtRestOptions": copy.deepcopy(payload.get(
+ "EncryptionAtRestOptions", {"Enabled": False}
+ )),
+ "NodeToNodeEncryptionOptions": copy.deepcopy(payload.get(
+ "NodeToNodeEncryptionOptions", {"Enabled": False}
+ )),
+ "AdvancedOptions": copy.deepcopy(payload.get("AdvancedOptions", {})),
+ "DomainEndpointOptions": copy.deepcopy(payload.get(
+ "DomainEndpointOptions",
+ {"EnforceHTTPS": True, "TLSSecurityPolicy": "Policy-Min-TLS-1-2-2019-07"},
+ )),
+ "AdvancedSecurityOptions": copy.deepcopy(payload.get(
+ "AdvancedSecurityOptions",
+ {"Enabled": False, "InternalUserDatabaseEnabled": False},
+ )),
+ "VPCOptions": _normalise_vpc_options(copy.deepcopy(payload.get("VPCOptions"))),
+ "AutoTuneOptions": copy.deepcopy(payload.get("AutoTuneOptions", {"State": "DISABLED"})),
+ "OffPeakWindowOptions": copy.deepcopy(payload.get(
+ "OffPeakWindowOptions", {"Enabled": False}
+ )),
+ "SoftwareUpdateOptions": copy.deepcopy(payload.get(
+ "SoftwareUpdateOptions", {"AutoSoftwareUpdateEnabled": False}
+ )),
+ }
+
+
+def create_domain_record(payload, compatibility_properties=None):
+ """Create a domain through the shared management-plane lifecycle.
+
+ Internal callers receive the live private record. HTTP handlers pass it
+ through ``_public`` before serialising it.
+ """
+ detached_payload = copy.deepcopy(payload or {})
+ name = detached_payload.get("DomainName")
+ if not name:
+ raise OpenSearchServiceError(400, "ValidationException", "DomainName is required")
+ if not _NAME_RE.match(name):
+ raise OpenSearchServiceError(
+ 400,
+ "ValidationException",
+ "DomainName must start with a lowercase letter, contain only "
+ "lowercase letters, digits, and hyphens, and be 3-28 characters",
+ )
+ if name in _domains:
+ raise OpenSearchServiceError(
+ 409, "ResourceAlreadyExistsException", f"Domain already exists: {name}"
+ )
+
+ rec = None
+ try:
+ rec = _new_domain_record(name, detached_payload)
+ if compatibility_properties is not None:
+ rec["_CloudFormationCompatibility"] = copy.deepcopy(
+ compatibility_properties
+ )
+ _domains[name] = rec
+ tags = _normalise_tags(detached_payload.get("TagList"))
+ if tags:
+ _tags[rec["ARN"]] = tags
+ else:
+ _tags.pop(rec["ARN"], None)
+ return rec
+ except Exception:
+ if rec is not None:
+ _teardown_dataplane(rec)
+ _teardown_named_dataplane(name)
+ _domains.pop(name, None)
+ _tags.pop(_arn(name), None)
+ _change_progress.pop(name, None)
+ raise
+
+
+def update_domain_from_cloudformation(name, payload, compatibility_properties):
+ """Apply a complete CloudFormation desired state to an existing domain."""
+ rec = _domains.get(name)
+ if not rec:
+ raise OpenSearchServiceError(
+ 404, "ResourceNotFoundException", f"Domain not found: {name}"
+ )
+
+ detached_payload = copy.deepcopy(payload or {})
+ desired = _desired_modeled_configuration(detached_payload)
+ detached_compatibility = copy.deepcopy(compatibility_properties or {})
+ desired_tags = _normalise_tags(detached_payload.get("TagList"))
+ current_tags = _normalise_tags(_tags.get(rec["ARN"]) or [])
+
+ changed_properties = []
+ for key in _MODELED_DOMAIN_PROPERTIES:
+ wanted = desired[key]
+ current = rec.get(key)
+ if key == "VPCOptions":
+ current = rec.get("VPCOptions")
+ if current != wanted:
+ changed_properties.append(key)
+ if key == "VPCOptions":
+ _set_vpc_options(rec, wanted)
+ else:
+ rec[key] = copy.deepcopy(wanted)
+ if key == "EngineVersion":
+ rec["ServiceSoftwareOptions"]["CurrentVersion"] = wanted
+
+ if rec.get("_CloudFormationCompatibility", {}) != detached_compatibility:
+ rec["_CloudFormationCompatibility"] = detached_compatibility
+ changed_properties.append("CompatibilityProperties")
+
+ if current_tags != desired_tags:
+ if desired_tags:
+ _tags[rec["ARN"]] = desired_tags
+ else:
+ _tags.pop(rec["ARN"], None)
+
+ if changed_properties:
+ rec["_UpdatedTime"] = _now()
+ _change_progress[name] = {
+ "ChangeId": new_uuid(),
+ "StartTime": _now(),
+ "Status": "COMPLETED",
+ "PendingProperties": [],
+ "CompletedProperties": changed_properties,
+ "TotalNumberOfStages": 0,
+ "ConfigChangeStatus": "Completed",
+ }
+ return rec
+
+
+def delete_domain_record(name, missing_ok=False):
+ """Delete all domain-owned state and containers, optionally idempotently."""
+ rec = _domains.pop(name, None)
+ if not rec and not missing_ok:
+ raise OpenSearchServiceError(
+ 404, "ResourceNotFoundException", f"Domain not found: {name}"
+ )
+ if rec:
+ _teardown_dataplane(rec)
+ arn = rec.get("ARN", _arn(name))
+ else:
+ arn = _arn(name)
+ _teardown_named_dataplane(name)
+ _tags.pop(arn, None)
+ _change_progress.pop(name, None)
+ return rec
+
+
# ---------------------------------------------------------------------------
# Path matching
# ---------------------------------------------------------------------------
@@ -533,21 +754,10 @@ def _qp(query_params, key) -> str:
# ---------------------------------------------------------------------------
def _create_domain(payload):
- name = payload.get("DomainName")
- if not name:
- return _error(400, "ValidationException", "DomainName is required")
- if not _NAME_RE.match(name):
- return _error(400, "ValidationException",
- "DomainName must start with a lowercase letter, contain only "
- "lowercase letters, digits, and hyphens, and be 3-28 characters")
- if name in _domains:
- return _error(409, "ResourceAlreadyExistsException",
- f"Domain already exists: {name}")
- rec = _new_domain_record(name, payload)
- _domains[name] = rec
- tag_list = payload.get("TagList") or []
- if tag_list:
- _tags[_arn(name)] = list(tag_list)
+ try:
+ rec = create_domain_record(payload)
+ except OpenSearchServiceError as exc:
+ return _error(exc.status, exc.code, exc.message)
return _json(200, {"DomainStatus": _public(rec)})
@@ -559,12 +769,10 @@ def _describe_domain(name):
def _delete_domain(name):
- rec = _domains.pop(name, None)
- if not rec:
- return _error(404, "ResourceNotFoundException", f"Domain not found: {name}")
- _teardown_dataplane(rec)
- _tags.pop(_arn(name), None)
- _change_progress.pop(name, None)
+ try:
+ rec = delete_domain_record(name)
+ except OpenSearchServiceError as exc:
+ return _error(exc.status, exc.code, exc.message)
out = dict(rec)
out["Deleted"] = True
return _json(200, {"DomainStatus": _public(out)})
@@ -607,7 +815,7 @@ def _update_domain_config(name, payload):
if k == "VPCOptions":
_set_vpc_options(rec, v)
else:
- rec[k] = v
+ rec[k] = copy.deepcopy(v)
rec["_UpdatedTime"] = _now()
# Real AWS marks the domain Processing while config rollout happens; we
@@ -684,7 +892,7 @@ def _add_tags(payload):
by_key = {t["Key"]: t for t in existing}
for t in tag_list:
by_key[t["Key"]] = t
- _tags[arn] = list(by_key.values())
+ _tags[arn] = copy.deepcopy(list(by_key.values()))
return _json(200, {})
@@ -695,7 +903,7 @@ def _list_tags(query_params):
arn, err = _resolve_taggable_opensearch_arn(arn)
if err:
return err
- return _json(200, {"TagList": list(_tags.get(arn) or [])})
+ return _json(200, {"TagList": copy.deepcopy(list(_tags.get(arn) or []))})
def _remove_tags(payload):
diff --git a/tests/conftest.py b/tests/conftest.py
index 806efa6b..4621bc61 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -419,6 +419,11 @@ def cfn():
return make_client("cloudformation")
[email protected](scope="session")
+def opensearch():
+ return make_client("opensearch")
+
+
@pytest.fixture(scope="session")
def kms_client():
return make_client("kms")
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index a736fa14..3b1fbbf7 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -4644,6 +4644,513 @@ def test_cfn_sam_transform_missing_translator_falls_back(monkeypatch):
assert _apply_sam_transform_if_applicable(plain) is plain
+# AWS::OpenSearchService::Domain
+
+
+def _opensearch_stack_template(domain_props):
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "SearchDomain": {
+ "Type": "AWS::OpenSearchService::Domain",
+ "Properties": domain_props,
+ },
+ },
+ "Outputs": {
+ "Ref": {"Value": {"Ref": "SearchDomain"}},
+ "Arn": {"Value": {"Fn::GetAtt": ["SearchDomain", "Arn"]}},
+ "DomainArn": {
+ "Value": {"Fn::GetAtt": ["SearchDomain", "DomainArn"]}
+ },
+ "Endpoint": {
+ "Value": {"Fn::GetAtt": ["SearchDomain", "DomainEndpoint"]}
+ },
+ "Id": {"Value": {"Fn::GetAtt": ["SearchDomain", "Id"]},},
+ },
+ }
+
+
+def _stack_resource(cfn, stack_name, logical_id="SearchDomain"):
+ return cfn.describe_stack_resource(
+ StackName=stack_name, LogicalResourceId=logical_id
+ )["StackResourceDetail"]
+
+
+def test_cfn_opensearch_domain_create_update_replace_and_idempotent_delete(
+ cfn, opensearch):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-{suffix}"
+ domain_name = f"search-{suffix}"
+ sentinel = f"NeverLog-{suffix}"
+ all_properties = {
+ "AccessPolicies": {
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "es:*", "Resource": "*"}],
+ },
+ "AdvancedOptions": {"indices.fielddata.cache.size": "20"},
+ "AdvancedSecurityOptions": {
+ "Enabled": True,
+ "InternalUserDatabaseEnabled": True,
+ "MasterUserOptions": {
+ "MasterUserName": "admin",
+ "MasterUserPassword": sentinel,
+ },
+ },
+ "AIMLOptions": {"NaturalLanguageQueryGenerationOptions": {"DesiredState": "ENABLED"}},
+ "AutomatedSnapshotPauseOptions": {"Enabled": True},
+ "ClusterConfig": {"InstanceCount": 1, "InstanceType": "t3.small.search"},
+ "CognitoOptions": {"Enabled": False},
+ "DeploymentStrategyOptions": {"DeploymentStrategy": "BLUE_GREEN"},
+ "DomainEndpointOptions": {"EnforceHTTPS": False},
+ "DomainName": domain_name,
+ "EBSOptions": {"EBSEnabled": True, "VolumeSize": 20, "VolumeType": "gp3"},
+ "EncryptionAtRestOptions": {"Enabled": True},
+ "EngineVersion": "OpenSearch_2.15",
+ "IdentityCenterOptions": {"EnabledAPIAccess": False},
+ "IPAddressType": "ipv4",
+ "LogPublishingOptions": {},
+ "NodeToNodeEncryptionOptions": {"Enabled": True},
+ "OffPeakWindowOptions": {"Enabled": True},
+ "SkipShardMigrationWait": True,
+ "SnapshotOptions": {"AutomatedSnapshotStartHour": 7},
+ "SoftwareUpdateOptions": {"AutoSoftwareUpdateEnabled": True},
+ "Tags": [
+ {"Key": "Environment", "Value": "test"},
+ {"Key": "Changing", "Value": "old"},
+ ],
+ "VPCOptions": {},
+ }
+
+ cfn.create_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template(all_properties)),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ resource = _stack_resource(cfn, stack_name)
+ assert resource["PhysicalResourceId"] == domain_name
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+ expected_arn = f"arn:aws:es:us-east-1:000000000000:domain/{domain_name}"
+ assert outputs == {
+ "Ref": domain_name,
+ "Arn": expected_arn,
+ "DomainArn": expected_arn,
+ "Endpoint": f"{domain_name}.ministack.local:9200",
+ "Id": f"000000000000/{domain_name}",
+ }
+
+ status = opensearch.describe_domain(DomainName=domain_name)["DomainStatus"]
+ assert status["EngineVersion"] == "OpenSearch_2.15"
+ assert status["ClusterConfig"]["InstanceType"] == "t3.small.search"
+ assert status["SnapshotOptions"]["AutomatedSnapshotStartHour"] == 7
+ assert status["OffPeakWindowOptions"]["Enabled"] is True
+ assert status["SoftwareUpdateOptions"]["AutoSoftwareUpdateEnabled"] is True
+ assert sentinel not in json.dumps(status, default=str)
+ tags = opensearch.list_tags(ARN=expected_arn)["TagList"]
+ assert {t["Key"]: t["Value"] for t in tags} == {
+ "Environment": "test", "Changing": "old"
+ }
+ assert domain_name in {
+ item["DomainName"] for item in opensearch.list_domain_names()["DomainNames"]
+ }
+
+ updated_properties = {
+ "DomainName": domain_name,
+ "EngineVersion": "OpenSearch_2.17",
+ "ClusterConfig": {"InstanceCount": 2},
+ "AIMLOptions": {"NaturalLanguageQueryGenerationOptions": {"DesiredState": "DISABLED"}},
+ "Tags": [
+ {"Key": "Changing", "Value": "new"},
+ {"Key": "Added", "Value": "yes"},
+ ],
+ }
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template(updated_properties)),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _stack_resource(cfn, stack_name)["PhysicalResourceId"] == domain_name
+ status = opensearch.describe_domain(DomainName=domain_name)["DomainStatus"]
+ assert status["EngineVersion"] == "OpenSearch_2.17"
+ assert status["ClusterConfig"]["InstanceCount"] == 2
+ assert status["EBSOptions"]["VolumeSize"] == 10
+ assert status["AdvancedOptions"] == {}
+ assert status["OffPeakWindowOptions"] == {"Enabled": False}
+ tags = opensearch.list_tags(ARN=expected_arn)["TagList"]
+ assert {t["Key"]: t["Value"] for t in tags} == {
+ "Changing": "new", "Added": "yes"
+ }
+ progress = opensearch.describe_domain_change_progress(DomainName=domain_name)[
+ "ChangeProgressStatus"
+ ]
+ assert progress["Status"] == "COMPLETED"
+ assert progress["ConfigChangeStatus"] == "Completed"
+
+ replacement_name = f"replace-{suffix}"
+ replacement_props = {
+ "DomainName": replacement_name,
+ "Tags": [{"Key": "Replacement", "Value": "true"}],
+ }
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template(replacement_props)),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _stack_resource(cfn, stack_name)["PhysicalResourceId"] == replacement_name
+ with pytest.raises(ClientError) as exc:
+ opensearch.describe_domain(DomainName=domain_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ opensearch.describe_domain(DomainName=replacement_name)
+
+ # Removing an explicit DomainName is also a replacement, with a newly
+ # generated physical name derived from the stack and logical ID.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template({"Tags": []})),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ generated_name = _stack_resource(cfn, stack_name)["PhysicalResourceId"]
+ assert generated_name != replacement_name
+ assert len(generated_name) <= 28
+ with pytest.raises(ClientError):
+ opensearch.describe_domain(DomainName=replacement_name)
+
+ # Manual removal must not make CloudFormation deletion fail.
+ opensearch.delete_domain(DomainName=generated_name)
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+
+def test_cfn_opensearch_auto_name_is_stable_across_update(cfn, opensearch):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-auto-{suffix}"
+ template = _opensearch_stack_template({"EngineVersion": "OpenSearch_2.15"})
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ physical_id = _stack_resource(cfn, stack_name)["PhysicalResourceId"]
+ assert len(physical_id) <= 28
+ assert len(physical_id) >= 3
+ assert physical_id[0].islower()
+ assert all(c.islower() or c.isdigit() or c == "-" for c in physical_id)
+
+ template = _opensearch_stack_template({
+ "EngineVersion": "OpenSearch_2.17",
+ "VPCOptions": {
+ "SubnetIds": ["subnet-control-plane"],
+ "SecurityGroupIds": ["sg-control-plane"],
+ },
+ })
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _stack_resource(cfn, stack_name)["PhysicalResourceId"] == physical_id
+ status = opensearch.describe_domain(DomainName=physical_id)["DomainStatus"]
+ assert status["EngineVersion"] == "OpenSearch_2.17"
+ assert status["Endpoints"]["vpc"] == f"{physical_id}.ministack.local:9200"
+
+ # Removing VPCOptions is an in-place control-plane update and restores the
+ # public endpoint response shape.
+ template = _opensearch_stack_template({"EngineVersion": "OpenSearch_2.17"})
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _stack_resource(cfn, stack_name)["PhysicalResourceId"] == physical_id
+ status = opensearch.describe_domain(DomainName=physical_id)["DomainStatus"]
+ assert status["Endpoint"] == f"{physical_id}.ministack.local:9200"
+ assert "Endpoints" not in status
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+
+def test_cfn_opensearch_vpc_refs_use_vpc_endpoint(cfn, opensearch):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-vpc-{suffix}"
+ domain_name = f"vpc-{suffix}"
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}},
+ "Subnet": {
+ "Type": "AWS::EC2::Subnet",
+ "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.1.0/24"},
+ },
+ "SecurityGroup": {
+ "Type": "AWS::EC2::SecurityGroup",
+ "Properties": {"VpcId": {"Ref": "Vpc"}, "GroupDescription": "search"},
+ },
+ "SearchDomain": {
+ "Type": "AWS::OpenSearchService::Domain",
+ "Properties": {
+ "DomainName": domain_name,
+ "VPCOptions": {
+ "SubnetIds": [{"Ref": "Subnet"}],
+ "SecurityGroupIds": [{"Ref": "SecurityGroup"}],
+ },
+ },
+ },
+ },
+ "Outputs": {
+ "Endpoint": {"Value": {"Fn::GetAtt": ["SearchDomain", "DomainEndpoint"]}}
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ status = opensearch.describe_domain(DomainName=domain_name)["DomainStatus"]
+ endpoint = status["Endpoints"]["vpc"]
+ assert {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]} == {
+ "Endpoint": endpoint
+ }
+ resources = {
+ r["LogicalResourceId"]: r
+ for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]
+ }
+ assert status["VPCOptions"]["SubnetIds"] == [resources["Subnet"]["PhysicalResourceId"]]
+ assert status["VPCOptions"]["SecurityGroupIds"] == [
+ resources["SecurityGroup"]["PhysicalResourceId"]
+ ]
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+
+def test_cfn_opensearch_failed_replacement_preserves_original(cfn, opensearch):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-failure-{suffix}"
+ original = f"original-{suffix}"
+ duplicate = f"duplicate-{suffix}"
+ opensearch.create_domain(DomainName=duplicate)
+ cfn.create_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template({"DomainName": original})),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(_opensearch_stack_template({"DomainName": duplicate})),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert opensearch.describe_domain(DomainName=original)["DomainStatus"]["DomainName"] == original
+ assert opensearch.describe_domain(DomainName=duplicate)["DomainStatus"]["DomainName"] == duplicate
+ assert _stack_resource(cfn, stack_name)["PhysicalResourceId"] == original
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ opensearch.delete_domain(DomainName=duplicate)
+
+
+def test_cfn_opensearch_invalid_create_redacts_secret_and_rolls_back(cfn, opensearch):
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-invalid-{suffix}"
+ sentinel = f"SentinelPassword-{suffix}"
+ invalid_name = f"INVALID-{suffix}"
+ template = _opensearch_stack_template({
+ "DomainName": invalid_name,
+ "AdvancedSecurityOptions": {
+ "Enabled": True,
+ "MasterUserOptions": {
+ "MasterUserName": "admin",
+ "MasterUserPassword": sentinel,
+ },
+ },
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE"
+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ assert sentinel not in json.dumps(events, default=str)
+ assert sentinel not in json.dumps(stack, default=str)
+ with pytest.raises(ClientError) as exc:
+ opensearch.describe_domain(DomainName=invalid_name)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_cfn_opensearch_private_compatibility_state_is_detached_and_replaced():
+ from ministack.services import opensearch as service
+ from ministack.services.cloudformation.provisioners import (
+ _opensearch_domain_create,
+ _opensearch_domain_delete,
+ _opensearch_domain_update,
+ )
+
+ suffix = _uuid_mod.uuid4().hex[:8]
+ name = f"private-{suffix}"
+ compatibility = {"AIMLOptions": {"Nested": ["original"]}}
+ props = {
+ "DomainName": name,
+ **compatibility,
+ "Tags": [{"Key": "Original", "Value": "yes"}],
+ }
+ physical_id, _ = _opensearch_domain_create("SearchDomain", props, "unit-stack")
+ try:
+ props["AIMLOptions"]["Nested"].append("mutated")
+ props["Tags"][0]["Value"] = "mutated"
+ rec = service._domains[physical_id]
+ assert rec["_CloudFormationCompatibility"] == {
+ "AIMLOptions": {"Nested": ["original"]}
+ }
+ assert service._tags[rec["ARN"]] == [{"Key": "Original", "Value": "yes"}]
+
+ same_id, _ = _opensearch_domain_update(
+ physical_id,
+ {"DomainName": name, "AIMLOptions": compatibility["AIMLOptions"]},
+ {"DomainName": name},
+ "unit-stack",
+ "SearchDomain",
+ )
+ assert same_id == physical_id
+ assert service._domains[physical_id]["_CloudFormationCompatibility"] == {}
+ assert service._tags.get(rec["ARN"]) is None
+ finally:
+ _opensearch_domain_delete(physical_id, {})
+ _opensearch_domain_delete(physical_id, {})
+ assert service._domains.get(physical_id) is None
+ assert service._change_progress.get(physical_id) is None
+
+
+def test_cfn_cdk_opensearch_access_policy_custom_resource(cfn, opensearch):
+ """CDK's provider Lambda can load the OpenSearch SDK v3 package.
+
+ The OpenSearch Domain L2 emits Custom::OpenSearchAccessPolicy with
+ InstallLatestAwsSdk=false. Its shared provider dynamically loads
+ @aws-sdk/client-opensearch and sends UpdateDomainConfigCommand.
+ """
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-os-access-{suffix}"
+ domain_name = f"access-{suffix}"
+ function_name = f"cfn-os-provider-{suffix}"
+ access_policy = json.dumps({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": "*",
+ "Action": "es:*",
+ "Resource": "*",
+ }],
+ }, separators=(",", ":"))
+ provider_code = r"""
+const http = require("http");
+
+function respond(event, status, reason, physicalId, data) {
+ const body = JSON.stringify({
+ Status: status,
+ Reason: reason,
+ PhysicalResourceId: physicalId,
+ StackId: event.StackId,
+ RequestId: event.RequestId,
+ LogicalResourceId: event.LogicalResourceId,
+ NoEcho: false,
+ Data: data || {},
+ });
+ const target = new URL(event.ResponseURL);
+ return new Promise((resolve, reject) => {
+ const req = http.request({
+ hostname: target.hostname,
+ port: target.port,
+ path: target.pathname + target.search,
+ method: "PUT",
+ headers: {
+ "Content-Type": "",
+ "Content-Length": Buffer.byteLength(body),
+ },
+ }, (res) => {
+ res.resume();
+ res.on("end", resolve);
+ });
+ req.on("error", reject);
+ req.write(body);
+ req.end();
+ });
+}
+
+exports.handler = async (event) => {
+ let physicalId = event.PhysicalResourceId || event.LogicalResourceId;
+ try {
+ const raw = event.ResourceProperties[event.RequestType];
+ if (raw) {
+ const call = typeof raw === "string" ? JSON.parse(raw) : raw;
+ physicalId = call.physicalResourceId?.id || physicalId;
+ const sdk = require("@aws-sdk/client-opensearch");
+ const clientClass = Object.entries(sdk).find(([name]) => name === "OpenSearchClient")?.[1];
+ const commandName = call.action[0].toUpperCase() + call.action.slice(1) + "Command";
+ const commandClass = Object.entries(sdk).find(([name]) => name === commandName)?.[1];
+ if (!clientClass || !commandClass) throw new Error("OpenSearch SDK exports not found");
+ const client = new clientClass({ apiVersion: "2021-01-01" });
+ const result = await client.send(new commandClass(call.parameters));
+ result.apiVersion = client.config.apiVersion;
+ result.region = await client.config.region().catch(() => undefined);
+ await respond(event, "SUCCESS", "OK", physicalId, result);
+ } else {
+ await respond(event, "SUCCESS", "OK", physicalId, {});
+ }
+ } catch (err) {
+ await respond(event, "FAILED", err.message || String(err), physicalId, {});
+ }
+};
+"""
+ call_prefix = (
+ '{"action":"updateDomainConfig","service":"OpenSearch",'
+ f'"parameters":{{"DomainName":"{domain_name}",'
+ f'"AccessPolicies":{json.dumps(access_policy)}}},'
+ f'"physicalResourceId":{{"id":"{domain_name}AccessPolicy"}}}}'
+ )
+ template = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "SearchDomain": {
+ "Type": "AWS::OpenSearchService::Domain",
+ "Properties": {"DomainName": domain_name},
+ },
+ "Provider": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": function_name,
+ "Runtime": "nodejs18.x",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/custom-resource",
+ "Timeout": 10,
+ "Code": {"ZipFile": provider_code},
+ # CDK local tooling sets this exact hostname. The SDK shim
+ # must not turn it into the S3-shaped
+ # ``opensearch.localhost`` virtual host.
+ "Environment": {
+ "Variables": {"AWS_ENDPOINT_URL": "http://localhost:4566"},
+ },
+ },
+ },
+ "AccessPolicy": {
+ "Type": "Custom::OpenSearchAccessPolicy",
+ "Properties": {
+ "ServiceToken": {"Fn::GetAtt": ["Provider", "Arn"]},
+ "Create": call_prefix,
+ "Update": call_prefix,
+ "InstallLatestAwsSdk": False,
+ "ServiceTimeout": 5,
+ },
+ "DependsOn": ["SearchDomain", "Provider"],
+ },
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ config = opensearch.describe_domain_config(DomainName=domain_name)["DomainConfig"]
+ assert config["AccessPolicies"]["Options"] == access_policy
+ resource = _stack_resource(cfn, stack_name, "AccessPolicy")
+ assert resource["PhysicalResourceId"] == f"{domain_name}AccessPolicy"
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+
+
def test_cfn_s3tables_resources(cfn, s3tables):
"""CloudFormation can provision AWS::S3Tables::TableBucket, Namespace, and Table."""
template = {
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 982c048c..f5fea779 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -6712,7 +6712,7 @@ exports.handler = async () => {
def test_nodejs_worker_aws_sdk_v3_stub_resolves():
- """@aws-sdk/client-lambda, @aws-sdk/client-sfn, @aws-sdk/client-ssm resolve.
+ """Lambda, OpenSearch, SFN, and SSM SDK v3 packages resolve.
Real AWS Lambda (Node.js 18+) ships these built-in. Ministack injects
stubs: Lambda uses a dedicated REST stub; sfn/ssm use the generic JSON-RPC
@@ -6720,6 +6720,7 @@ def test_nodejs_worker_aws_sdk_v3_stub_resolves():
"""
handler_js = """\
const { Lambda, LambdaClient, InvokeCommand, waitUntilFunctionActiveV2 } = require("@aws-sdk/client-lambda");
+const { OpenSearch, OpenSearchClient, UpdateDomainConfigCommand } = require("@aws-sdk/client-opensearch");
const { SFN, SFNClient } = require("@aws-sdk/client-sfn");
const { SSM, SSMClient, PutParameterCommand, GetParameterCommand } = require("@aws-sdk/client-ssm");
exports.handler = async (_event, _ctx) => ({
@@ -6727,6 +6728,9 @@ exports.handler = async (_event, _ctx) => ({
hasLambdaClient: typeof LambdaClient === "function",
hasInvokeCommand: typeof InvokeCommand === "function",
hasWaiter: typeof waitUntilFunctionActiveV2 === "function",
+ hasOpenSearch: typeof OpenSearch === "function",
+ hasOpenSearchClient: typeof OpenSearchClient === "function",
+ hasUpdateDomainConfigCommand: typeof UpdateDomainConfigCommand === "function",
hasSFN: typeof SFN === "function",
hasSFNClient: typeof SFNClient === "function",
hasSSM: typeof SSM === "function",
@@ -6742,6 +6746,9 @@ exports.handler = async (_event, _ctx) => ({
assert r["hasLambdaClient"] is True
assert r["hasInvokeCommand"] is True
assert r["hasWaiter"] is True
+ assert r["hasOpenSearch"] is True
+ assert r["hasOpenSearchClient"] is True
+ assert r["hasUpdateDomainConfigCommand"] is True
assert r["hasSFN"] is True
assert r["hasSFNClient"] is True
assert r["hasSSM"] is True
@@ -6750,6 +6757,70 @@ exports.handler = async (_event, _ctx) => ({
assert r["hasGetParameterCommand"] is True
+def test_nodejs_worker_opensearch_sdk_v3_stub_uses_rest_json():
+ """The OpenSearch shim serializes UpdateDomainConfig like the real SDK."""
+ handler_js = """\
+const http = require("http");
+
+exports.handler = async () => {
+ let received;
+ const srv = http.createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk) => body += chunk);
+ req.on("end", () => {
+ received = {
+ method: req.method,
+ path: req.url,
+ host: req.headers.host,
+ body: JSON.parse(body),
+ };
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({
+ DomainConfig: {
+ AccessPolicies: {
+ Options: body && JSON.parse(body).AccessPolicies,
+ Status: { State: "Active", UpdateVersion: 2 },
+ },
+ },
+ }));
+ });
+ });
+ await new Promise((resolve) => srv.listen(0, "127.0.0.1", resolve));
+ process.env.AWS_ENDPOINT_URL = "http://localhost:" + srv.address().port;
+
+ const {
+ OpenSearchClient,
+ UpdateDomainConfigCommand,
+ } = require("@aws-sdk/client-opensearch");
+ const client = new OpenSearchClient({ apiVersion: "2021-01-01", region: "eu-west-2" });
+ const result = await client.send(new UpdateDomainConfigCommand({
+ DomainName: "domain with spaces",
+ AccessPolicies: "policy-json",
+ }));
+ const config = {
+ apiVersion: client.config.apiVersion,
+ region: await client.config.region(),
+ };
+ await new Promise((resolve) => srv.close(resolve));
+ return { received, result, config };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ received = result["result"]["received"]
+ assert received["method"] == "POST"
+ assert received["path"] == "/2021-01-01/opensearch/domain/domain%20with%20spaces/config"
+ assert received["host"].startswith("localhost:")
+ assert received["body"] == {"AccessPolicies": "policy-json"}
+ access_policies = result["result"]["result"]["DomainConfig"]["AccessPolicies"]
+ assert access_policies["Options"] == "policy-json"
+ assert access_policies["Status"]["State"] == "Active"
+ assert result["result"]["config"] == {
+ "apiVersion": "2021-01-01",
+ "region": "eu-west-2",
+ }
+
+
def test_nodejs_worker_json_rpc_error_has_name():
"""Service errors from the JSON-RPC stub expose err.name (not just err.code).
diff --git a/tests/test_opensearch.py b/tests/test_opensearch.py
index 1ed0f525..f2291724 100644
--- a/tests/test_opensearch.py
+++ b/tests/test_opensearch.py
@@ -6,15 +6,16 @@ by ``OPENSEARCH_DATAPLANE=1`` and exercised separately when that env var
is set.
"""
+import json
import os
import time
+import urllib.request
import uuid
import boto3
import pytest
from botocore.exceptions import ClientError
-
ENDPOINT = "http://localhost:4566"
REGION = "us-east-1"
@@ -227,6 +228,26 @@ def test_opensearch_update_domain_config_persists(os_client):
os_client.delete_domain(DomainName=name)
+def test_opensearch_unsigned_update_domain_config_does_not_route_to_s3(os_client):
+ """CDK custom-resource REST requests route by path when SigV4 is unavailable."""
+ name = f"raw-{_uid()}"
+ os_client.create_domain(DomainName=name)
+ try:
+ policy = '{"Version":"2012-10-17","Statement":[]}'
+ request = urllib.request.Request(
+ f"{ENDPOINT}/2021-01-01/opensearch/domain/{name}/config",
+ data=json.dumps({"AccessPolicies": policy}).encode(),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ with urllib.request.urlopen(request) as response:
+ assert response.headers.get_content_type() == "application/json"
+ result = json.load(response)
+ assert result["DomainConfig"]["AccessPolicies"]["Options"] == policy
+ finally:
+ os_client.delete_domain(DomainName=name)
+
+
def test_opensearch_describe_domain_change_progress(os_client):
name = f"prog-{_uid()}"
os_client.create_domain(DomainName=name)
@@ -387,8 +408,8 @@ def test_opensearch_dataplane_cluster_health():
"""When OPENSEARCH_DATAPLANE=1 is set on the ministack server, CreateDomain
spawns a real opensearchproject/opensearch container and DescribeDomain
returns its endpoint. Verify cluster health responds."""
- import urllib.request
import json as _json
+ import urllib.request
o = _client()
name = f"dp-{_uid()}"
diff --git a/tests/test_router.py b/tests/test_router.py
index 9112e66b..79dd8969 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -82,3 +82,24 @@ def test_lambda_credential_scope_still_routes_when_path_unknown():
),
}
assert detect_service("GET", "/2099-01-01/something-new", headers, {}) == "lambda"
+
+
[email protected](("method", "path"), [
+ ("POST", "/2021-01-01/opensearch/domain/example/config"),
+ ("GET", "/2021-01-01/opensearch/domain/example"),
+ ("POST", "/2021-01-01/opensearch/domain-info"),
+ ("GET", "/2021-01-01/domain/example"),
+ ("GET", "/2021-01-01/versions"),
+ ("GET", "/2021-01-01/compatibleVersions"),
+ ("POST", "/2021-01-01/tags"),
+ ("POST", "/2021-01-01/tags-removal"),
+])
+def test_opensearch_management_paths_route_without_sigv4(method, path):
+ """OpenSearch custom-resource calls must not fall through to S3."""
+ assert detect_service(method, path, _HEADERS, {}) == "opensearch"
+
+
+def test_unknown_opensearch_version_path_still_falls_back_to_s3():
+ assert detect_service(
+ "POST", "/2021-01-01/not-opensearch/domain/example/config", _HEADERS, {}
+ ) == "s3"