Skip to content

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

Fix/lambda cognito eks (#368)

Nahuel Nucera479a68306c32
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6300f43..abb7f062 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,45 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.2.21] — 2026-04-17
+
+### Added
+- **`/_ministack/ready` endpoint** — exposes ready.d script completion status, enabling Docker healthchecks and orchestrators to gate on init script completion. Contributed by @kjdev (#360)
+- **ECS `command` passed to Docker containers** — task definition `containerDefinitions[].command` is now forwarded to `docker run`, overriding the image's default CMD. Previously the command field was ignored. Contributed by @s0rbus (#366)
+- **CloudFormation `AWS::Events::EventBus` provisioner** — CDK/Terraform stacks declaring EventBridge custom event buses now provision correctly. Supports Name, Tags, and Fn::GetAtt Arn/Name. Contributed by @AdigaAkhil (#365)
+- **Lambda Java, .NET, and Ruby runtime support** — `LAMBDA_EXECUTOR=docker` now supports `java21`, `java17`, `java11`, `java8.al2`, `dotnet8`, `dotnet6`, `ruby3.4`, `ruby3.3`, `ruby3.2` using official AWS Lambda RIE images. Fallback resolvers added for future versions.
+
+### Fixed
+
+#### Lambda
+- **Lambda Docker-in-Docker (DinD)** — `LAMBDA_EXECUTOR=docker` now works when ministack itself runs inside Docker. Code is copied into Lambda containers via `docker cp` instead of bind mounts (which fail because the host Docker daemon can't see the ministack container's filesystem). Lambda containers are reached via container IP instead of host-mapped ports. Container detection uses `/.dockerenv`, `/run/.containerenv`, and `/proc/1/cgroup` fallback. Fixes #367. Reported by @HackJack-101
+- **Lambda timeout enforcement** — warm workers now enforce the configured `Timeout` value via `thread.join(timeout)` + `proc.kill()`. Previously, functions ran indefinitely regardless of the timeout setting. Timeout errors return `Runtime.ExitError` matching AWS behavior.
+- **Lambda published version isolation** — `PublishVersion` now creates immutable code snapshots. Invoking a specific version returns the code from when it was published, not the current `$LATEST`. Workers are keyed by `function_name:qualifier` to prevent version cross-contamination.
+- **Lambda `UpdateFunctionCode` worker invalidation** — only invalidates the `$LATEST` worker, leaving published version workers alive. Previously killed all workers for the function.
+- **Lambda warm container tmpdir cleanup** — warm container cache now tracks and cleans up temp directories when containers are evicted or on `reset()`. Previously leaked `/tmp/ministack-lambda-docker-*` directories.
+- **Lambda `_execute_function_image` deduplicated** — Image-based Lambda execution now reuses `_invoke_rie()` instead of duplicating the HTTP polling logic.
+- **Lambda `_invoke_rie` faster polling** — reduced polling interval from 500ms to 100ms for faster cold starts when using `LAMBDA_EXECUTOR=docker`.
+- **Lambda `Invoke` qualifier from query params** — `Qualifier` query parameter now correctly parsed for Lambda invocations, matching AWS SDK behavior.
+- **Lambda worker error on exception** — worker invalidation on exception now only kills the specific qualifier's worker, not all workers for the function.
+
+#### Cognito
+- **Cognito password validation** — `SignUp`, `AdminCreateUser`, `AdminSetUserPassword`, `ConfirmForgotPassword`, and `ChangePassword` now validate passwords against the pool's `PasswordPolicy` (min length, uppercase, lowercase, numbers, symbols). Previously any password was accepted.
+- **Cognito `_generate_temp_password` policy-compliant** — generated temporary passwords now guarantee at least one character from each required class (upper, lower, digit, symbol), ensuring they pass the pool's own password policy.
+
+#### EKS
+- **EKS non-blocking cluster creation** — `CreateCluster` now returns immediately with `status: CREATING` while k3s starts in a background thread. Previously blocked the ASGI event loop for up to 30 seconds.
+- **EKS failure status** — if k3s fails to start, the cluster status is set to `FAILED` instead of silently going `ACTIVE` with a broken endpoint.
+- **EKS k3s image pinned** — default k3s image pinned to `rancher/k3s:v1.31.4-k3s1` instead of `:latest` for reproducible builds.
+
+#### Performance & Infrastructure
+- **Docker client cached** — Lambda Docker executor reuses a single Docker client instead of creating one per invocation.
+- **EC2 terminated instance cleanup throttled** — `DescribeInstances` no longer scans and cleans up terminated instances on every call; cleanup runs at most once per 10 seconds.
+- **S3 ETag single-compute** — `PutObject` now computes the MD5 hash once instead of twice, reducing CPU per write.
+- **CloudFormation deploy/delete speed** — removed artificial 1.5s async delays from stack deploy and delete operations.
+- **`/_ministack/reset` no longer blocks event loop** — `_reset_all_state()` now runs via `asyncio.to_thread()` so Docker container cleanup (ECS, EKS, Lambda) doesn't starve the ASGI event loop. ECS `reset()` also fixed to stop containers by label filter (`ministack=ecs`) instead of individually fetching stale container IDs.
+
+---
+
## [1.2.20] — 2026-04-17
### Added
diff --git a/ministack/app.py b/ministack/app.py
index ddd8ece3..0fec07c1 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -342,7 +342,7 @@ async def app(scope, receive, send):
# Admin endpoints — no wildcard CORS headers (return early, before CORS block)
if path == "/_ministack/reset" and method == "POST":
- _reset_all_state()
+ await asyncio.to_thread(_reset_all_state)
run_init = query_params.get("init", [""])[0] == "1"
if run_init:
_run_init_scripts()
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index efdc165c..e347d835 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -527,32 +527,60 @@ class Worker:
else:
cold = False
+ timeout = self.config.get("Timeout", 30)
event["_request_id"] = request_id
- try:
- self._proc.stdin.write(json.dumps(event) + "\n")
- self._proc.stdin.flush()
- # Read lines until we get a valid JSON protocol message.
- # Non-JSON lines (e.g. stray console.log to stdout) are treated as log noise.
- for _ in range(200):
- response_line = self._proc.stdout.readline()
- if not response_line:
- raise RuntimeError("Worker process died")
- response_line = response_line.strip()
- if not response_line:
- continue
- if response_line.startswith("{"):
- try:
- response = json.loads(response_line)
- response["cold_start"] = cold
- response["log"] = self._drain_stderr()
- return response
- except json.JSONDecodeError:
+ result_box: list = []
+
+ def _read_response():
+ try:
+ self._proc.stdin.write(json.dumps(event) + "\n")
+ self._proc.stdin.flush()
+ for _ in range(200):
+ response_line = self._proc.stdout.readline()
+ if not response_line:
+ result_box.append({"status": "error", "error": "Worker process died"})
+ return
+ response_line = response_line.strip()
+ if not response_line:
continue
- # Non-JSON line -- skip it
- raise RuntimeError("No JSON response from worker after 200 lines")
- except Exception as e:
+ if response_line.startswith("{"):
+ try:
+ response = json.loads(response_line)
+ result_box.append(response)
+ return
+ except json.JSONDecodeError:
+ continue
+ result_box.append({"status": "error", "error": "No JSON response from worker after 200 lines"})
+ except Exception as e:
+ result_box.append({"status": "error", "error": str(e)})
+
+ reader = threading.Thread(target=_read_response, daemon=True)
+ reader.start()
+ reader.join(timeout=timeout)
+
+ if reader.is_alive():
+ # Timeout — kill the worker process
+ logger.warning("Lambda %s timed out after %ds — killing worker", self.func_name, timeout)
+ if self._proc:
+ self._proc.kill()
+ self._proc = None
+ return {
+ "status": "error",
+ "error": f"Task timed out after {timeout}.00 seconds",
+ "cold_start": cold,
+ "log": self._drain_stderr(),
+ }
+
+ if not result_box:
self._proc = None
- return {"status": "error", "error": str(e), "cold_start": cold}
+ return {"status": "error", "error": "Worker returned no response", "cold_start": cold}
+
+ response = result_box[0]
+ if response.get("status") == "error":
+ self._proc = None
+ response["cold_start"] = cold
+ response["log"] = self._drain_stderr()
+ return response
def kill(self):
if self._proc and self._proc.poll() is None:
@@ -562,21 +590,36 @@ class Worker:
shutil.rmtree(self._tmpdir, ignore_errors=True)
-def get_or_create_worker(func_name: str, config: dict, code_zip: bytes) -> Worker:
+def get_or_create_worker(func_name: str, config: dict, code_zip: bytes,
+ qualifier: str = "$LATEST") -> Worker:
+ key = f"{func_name}:{qualifier}"
with _lock:
- worker = _workers.get(func_name)
- if worker is None:
- worker = Worker(func_name, config, code_zip)
- _workers[func_name] = worker
+ worker = _workers.get(key)
+ if worker is not None:
+ return worker
+ worker = Worker(func_name, config, code_zip)
+ _workers[key] = worker
return worker
-def invalidate_worker(func_name: str):
- """Kill and remove worker when function is updated or deleted."""
+def invalidate_worker(func_name: str, qualifier: str = None):
+ """Kill and remove workers for a function.
+
+ If qualifier is provided, only kill that specific version/alias worker.
+ Otherwise kill all workers for the function (used on delete).
+ """
with _lock:
- worker = _workers.pop(func_name, None)
- if worker:
- worker.kill()
+ if qualifier is not None:
+ key = f"{func_name}:{qualifier}"
+ worker = _workers.pop(key, None)
+ if worker:
+ worker.kill()
+ else:
+ to_remove = [k for k in _workers if k.startswith(f"{func_name}:")]
+ for k in to_remove:
+ worker = _workers.pop(k, None)
+ if worker:
+ worker.kill()
def reset():
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index edb582b0..eeb4ee18 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -151,8 +151,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
logical_id, exc)
provisioned_resources.pop(logical_id, None)
- # Delay for realistic async behavior
- await asyncio.sleep(1.5)
+ await asyncio.sleep(0)
if failed:
if disable_rollback:
@@ -290,7 +289,7 @@ async def _delete_stack_async(stack_name: str, stack_id: str):
if export_name:
_exports.pop(export_name, None)
- await asyncio.sleep(1.5)
+ await asyncio.sleep(0)
stack["StackStatus"] = "DELETE_COMPLETE"
_add_event(stack_id, stack_name, stack_name,
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index d31a542f..294b640b 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -908,6 +908,30 @@ def _update_user_pool_client(data):
return json_response({"UserPoolClient": {k: v for k, v in client.items() if v is not None}})
+def _validate_password(pool, password):
+ """Validate password against the pool's PasswordPolicy. Returns error response or None."""
+ policy = pool.get("Policies", {}).get("PasswordPolicy", {})
+ min_len = policy.get("MinimumLength", 8)
+ errors = []
+ if len(password) < min_len:
+ errors.append(f"Password must have length greater than or equal to {min_len}")
+ if policy.get("RequireUppercase", True) and not any(c.isupper() for c in password):
+ errors.append("Password must have uppercase characters")
+ if policy.get("RequireLowercase", True) and not any(c.islower() for c in password):
+ errors.append("Password must have lowercase characters")
+ if policy.get("RequireNumbers", True) and not any(c.isdigit() for c in password):
+ errors.append("Password must have numeric characters")
+ if policy.get("RequireSymbols", True) and not any(c in "^$*.[]{}()?-\"!@#%&/\\,><':;|_~`+=" for c in password):
+ errors.append("Password must have symbol characters")
+ if errors:
+ return error_response_json(
+ "InvalidPasswordException",
+ "Password did not conform with policy: " + "; ".join(errors),
+ 400,
+ )
+ return None
+
+
# ===========================================================================
# USER MANAGEMENT
# ===========================================================================
@@ -929,6 +953,9 @@ def _admin_create_user(data):
now = _now_epoch()
temp_password = data.get("TemporaryPassword") or _generate_temp_password()
+ pw_err = _validate_password(pool, temp_password)
+ if pw_err:
+ return pw_err
attrs = data.get("UserAttributes", [])
# Ensure sub attribute
attr_dict = _attr_list_to_dict(attrs)
@@ -1022,7 +1049,11 @@ def _admin_set_user_password(data):
user, err = _resolve_user(pool, username)
if err:
return err
- user["_password"] = data.get("Password", "")
+ new_pw = data.get("Password", "")
+ pw_err = _validate_password(pool, new_pw)
+ if pw_err:
+ return pw_err
+ user["_password"] = new_pw
permanent = data.get("Permanent", False)
if permanent:
user["UserStatus"] = "CONFIRMED"
@@ -1474,6 +1505,10 @@ def _sign_up(data):
if username in pool["_users"]:
return error_response_json("UsernameExistsException", "User already exists.", 400)
+ pw_err = _validate_password(pool, password)
+ if pw_err:
+ return pw_err
+
now = _now_epoch()
attrs = data.get("UserAttributes", [])
attr_dict = _attr_list_to_dict(attrs)
@@ -1583,6 +1618,9 @@ def _confirm_forgot_password(data):
return error_response_json("UserNotFoundException", "User does not exist.", 400)
# Accept any confirmation code in emulation (real AWS validates against issued code)
+ pw_err = _validate_password(pool, new_password)
+ if pw_err:
+ return pw_err
user["_password"] = new_password
user["UserStatus"] = "CONFIRMED"
user["UserLastModifiedDate"] = _now_epoch()
@@ -1598,6 +1636,9 @@ def _change_password(data):
for pool in _user_pools.values():
user = _user_from_token(access_token, pool)
if user:
+ pw_err = _validate_password(pool, proposed)
+ if pw_err:
+ return pw_err
user["_password"] = proposed
user["UserLastModifiedDate"] = _now_epoch()
return json_response({})
@@ -2971,8 +3012,18 @@ def _identity_pool_out(pool: dict) -> dict:
# ===========================================================================
def _generate_temp_password() -> str:
- chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + "!@#$%"
- return "".join(secrets.choice(chars) for _ in range(12))
+ # Ensure at least one char from each required class to satisfy default policy
+ required = [
+ secrets.choice(string.ascii_uppercase),
+ secrets.choice(string.ascii_lowercase),
+ secrets.choice(string.digits),
+ secrets.choice("!@#$%^&*"),
+ ]
+ chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + "!@#$%^&*"
+ remaining = [secrets.choice(chars) for _ in range(8)]
+ password = required + remaining
+ secrets.SystemRandom().shuffle(password)
+ return "".join(password)
def _apply_user_filter(users: list, filter_str: str) -> list:
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 870a0bd4..95c69c67 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -356,17 +356,27 @@ def _run_instances(p):
return _xml(200, "RunInstancesResponse", inner)
-def _describe_instances(p):
- filter_ids = _parse_member_list(p, "InstanceId")
- filters = _parse_filters(p)
-
- # Clean up instances terminated more than 60s ago (AWS removes after ~1 hour)
+_last_cleanup = [0.0]
+
+def _cleanup_terminated():
+ """Remove instances terminated >60s ago. Called at most once per 10 seconds."""
+ now = time.time()
+ if now - _last_cleanup[0] < 10:
+ return
+ _last_cleanup[0] = now
stale = [k for k, v in _instances.items()
if v["State"]["Name"] == "terminated"
- and time.time() - v.get("_terminated_at", 0) > 60]
+ and now - v.get("_terminated_at", 0) > 60]
for k in stale:
_instances.pop(k, None)
+
+def _describe_instances(p):
+ filter_ids = _parse_member_list(p, "InstanceId")
+ filters = _parse_filters(p)
+
+ _cleanup_terminated()
+
if filter_ids:
for iid in filter_ids:
if iid not in _instances:
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 4f8a9a7c..c1d91373 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -1617,14 +1617,17 @@ _ACTION_MAP = {
def reset():
docker_client = _get_docker()
if docker_client:
- for task in _tasks.values():
- for cid in task.get("_docker_ids", []):
+ # Stop containers by label instead of chasing individual IDs —
+ # avoids slow 404s for containers that were already removed.
+ try:
+ for c in docker_client.containers.list(filters={"label": "ministack=ecs"}):
try:
- c = docker_client.containers.get(cid)
c.stop(timeout=2)
c.remove(v=True)
- except Exception as e:
- logger.warning("reset: failed to stop/remove container %s: %s", cid, e)
+ except Exception:
+ pass
+ except Exception:
+ pass
_clusters.clear()
_task_defs.clear()
_task_def_latest.clear()
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index efdb8332..3c51d9db 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -26,7 +26,7 @@ from ministack.core.responses import AccountScopedDict, get_account_id, json_res
logger = logging.getLogger("eks")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
-EKS_K3S_IMAGE = os.environ.get("EKS_K3S_IMAGE", "rancher/k3s:latest")
+EKS_K3S_IMAGE = os.environ.get("EKS_K3S_IMAGE", "rancher/k3s:v1.31.4-k3s1")
EKS_BASE_PORT = int(os.environ.get("EKS_BASE_PORT", "16443"))
try:
@@ -211,57 +211,9 @@ def _create_cluster(body):
container_id = None
port = _next_port()
- client = _get_docker()
- if client:
- try:
- ms_network = _get_ministack_network(client)
- run_kwargs = dict(
- image=EKS_K3S_IMAGE,
- command=["server",
- "--disable=traefik,metrics-server,servicelb",
- "--tls-san=0.0.0.0",
- f"--https-listen-port=6443"],
- detach=True,
- privileged=True,
- ports={"6443/tcp": port},
- name=f"ministack-eks-{name}",
- labels={"ministack": "eks", "cluster_name": name},
- environment={
- "K3S_KUBECONFIG_MODE": "644",
- },
- tmpfs={"/run": "", "/var/run": ""},
- )
- if ms_network:
- run_kwargs["network"] = ms_network
-
- container = client.containers.run(**run_kwargs)
- container_id = container.id
-
- # Wait for API server
- if ms_network:
- container.reload()
- networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
- container_ip = networks.get(ms_network, {}).get("IPAddress", "")
- if container_ip and _wait_for_port(container_ip, 6443):
- endpoint = f"https://{container_ip}:6443"
- logger.info("EKS: k3s for %s ready at %s (network %s)", name, endpoint, ms_network)
- if not endpoint:
- if _wait_for_port("127.0.0.1", port):
- endpoint = f"https://localhost:{port}"
- logger.info("EKS: k3s for %s ready at %s", name, endpoint)
- else:
- logger.warning("EKS: k3s for %s did not become ready on port %d", name, port)
- endpoint = f"https://localhost:{port}"
-
- ca_data = _extract_ca_cert(container)
-
- except Exception as e:
- logger.warning("EKS: failed to start k3s for %s: %s", name, e)
- endpoint = f"https://localhost:{port}"
- else:
- endpoint = f"https://localhost:{port}"
- logger.info("EKS: Docker unavailable — cluster %s created without k3s backend", name)
-
+ # Build cluster record immediately (status CREATING) and return fast.
+ # k3s startup happens in background thread to avoid blocking the event loop.
+ endpoint = f"https://localhost:{port}"
cluster = {
"name": name,
"arn": arn,
@@ -286,13 +238,13 @@ def _create_cluster(body):
"identity": {
"oidc": {"issuer": f"https://oidc.eks.{REGION}.amazonaws.com/id/{new_uuid()[:32].replace('-', '').upper()}"}
},
- "status": "ACTIVE",
- "certificateAuthority": {"data": ca_data},
+ "status": "CREATING",
+ "certificateAuthority": {"data": ""},
"platformVersion": f"eks.{int(time.time()) % 100}",
"tags": body.get("tags", {}),
"encryptionConfig": body.get("encryptionConfig", []),
"accessConfig": body.get("accessConfig", {}),
- "_docker_id": container_id,
+ "_docker_id": None,
"_port": port,
}
@@ -300,6 +252,58 @@ def _create_cluster(body):
if cluster["tags"]:
_tags[arn] = dict(cluster["tags"])
+ def _bg_start():
+ client = _get_docker()
+ if not client:
+ cluster["status"] = "ACTIVE"
+ logger.info("EKS: Docker unavailable — cluster %s created without k3s backend", name)
+ return
+ try:
+ ms_network = _get_ministack_network(client)
+ run_kwargs = dict(
+ image=EKS_K3S_IMAGE,
+ command=["server",
+ "--disable=traefik,metrics-server,servicelb",
+ "--tls-san=0.0.0.0",
+ f"--https-listen-port=6443"],
+ detach=True,
+ privileged=True,
+ ports={"6443/tcp": port},
+ name=f"ministack-eks-{name}",
+ labels={"ministack": "eks", "cluster_name": name},
+ environment={"K3S_KUBECONFIG_MODE": "644"},
+ tmpfs={"/run": "", "/var/run": ""},
+ )
+ if ms_network:
+ run_kwargs["network"] = ms_network
+
+ container = client.containers.run(**run_kwargs)
+ cluster["_docker_id"] = container.id
+
+ ep = ""
+ if ms_network:
+ container.reload()
+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
+ container_ip = networks.get(ms_network, {}).get("IPAddress", "")
+ if container_ip and _wait_for_port(container_ip, 6443):
+ ep = f"https://{container_ip}:6443"
+ logger.info("EKS: k3s for %s ready at %s (network %s)", name, ep, ms_network)
+ if not ep:
+ if _wait_for_port("127.0.0.1", port):
+ ep = f"https://localhost:{port}"
+ logger.info("EKS: k3s for %s ready at %s", name, ep)
+ else:
+ logger.warning("EKS: k3s for %s did not become ready on port %d", name, port)
+ ep = f"https://localhost:{port}"
+
+ cluster["endpoint"] = ep
+ cluster["certificateAuthority"]["data"] = _extract_ca_cert(container)
+ cluster["status"] = "ACTIVE"
+ except Exception as e:
+ logger.warning("EKS: failed to start k3s for %s: %s", name, e)
+ cluster["status"] = "FAILED"
+
+ threading.Thread(target=_bg_start, daemon=True, name=f"eks-{name}").start()
return _json_resp(200, {"cluster": _sanitize(cluster)})
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index b724e7ef..e05df392 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -29,6 +29,7 @@ import base64
import copy
import hashlib
import importlib
+import io
import json
import logging
import os
@@ -60,6 +61,45 @@ except ImportError:
docker_lib = None
_docker_available = False
+_cached_docker_client = None
+_is_in_container: bool | None = None
+
+
+def _running_in_container() -> bool:
+ """Detect if we're running inside a Docker/Podman container."""
+ global _is_in_container
+ if _is_in_container is not None:
+ return _is_in_container
+ # /.dockerenv is created by Docker; /run/.containerenv by Podman
+ if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
+ _is_in_container = True
+ return True
+ # Fall back to checking cgroup (works on most Linux container runtimes)
+ try:
+ with open("/proc/1/cgroup", "r") as f:
+ content = f.read()
+ if "docker" in content or "containerd" in content or "lxc" in content:
+ _is_in_container = True
+ return True
+ except (OSError, IOError):
+ pass
+ _is_in_container = False
+ return False
+
+
+def _get_docker_client():
+ """Return a cached Docker client, or create one on first call."""
+ global _cached_docker_client
+ if _cached_docker_client is not None:
+ return _cached_docker_client
+ if not _docker_available:
+ return None
+ try:
+ _cached_docker_client = docker_lib.from_env()
+ return _cached_docker_client
+ except Exception:
+ return None
+
_functions = AccountScopedDict() # function_name -> FunctionRecord
_layers = AccountScopedDict() # layer_name -> {"versions": [...], "next_version": int}
_esms = AccountScopedDict() # uuid -> esm dict
@@ -611,7 +651,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
# Invoke
if method == "POST" and sub == "invocations":
- return await _invoke(func_name, data, headers, path_qualifier)
+ return await _invoke(func_name, data, headers, path_qualifier, query_params)
# PublishVersion
if method == "POST" and sub == "versions":
@@ -872,8 +912,8 @@ def _update_code(name: str, data: dict):
func["config"]["LastUpdateStatus"] = "Successful"
func["config"]["RevisionId"] = new_uuid()
- # Invalidate warm worker so next invocation picks up the new code
- invalidate_worker(name)
+ # Invalidate only the old $LATEST worker �� published version workers stay alive
+ invalidate_worker(name, qualifier="$LATEST")
if data.get("Publish"):
ver_num = func["next_version"]
@@ -939,7 +979,8 @@ def _update_config(name: str, data: dict):
# ---------------------------------------------------------------------------
-async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | None = None):
+async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | None = None,
+ query_params: dict | None = None):
if name not in _functions:
return error_response_json(
"ResourceNotFoundException",
@@ -949,7 +990,7 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N
func = _functions[name]
invocation_type = headers.get("x-amz-invocation-type") or headers.get("X-Amz-Invocation-Type") or "RequestResponse"
- qualifier = path_qualifier or _qp_first(headers, "x-amz-qualifier") or None
+ qualifier = path_qualifier or _qp_first(query_params or {}, "Qualifier") or _qp_first(headers, "x-amz-qualifier") or None
executed_version = "$LATEST"
exec_record = func
@@ -1025,6 +1066,15 @@ _RUNTIME_IMAGE_MAP: dict[str, str] = {
"nodejs20.x": "public.ecr.aws/lambda/nodejs:20",
"nodejs22.x": "public.ecr.aws/lambda/nodejs:22",
"nodejs24.x": "public.ecr.aws/lambda/nodejs:24",
+ "java21": "public.ecr.aws/lambda/java:21",
+ "java17": "public.ecr.aws/lambda/java:17",
+ "java11": "public.ecr.aws/lambda/java:11",
+ "java8.al2": "public.ecr.aws/lambda/java:8.al2",
+ "dotnet8": "public.ecr.aws/lambda/dotnet:8",
+ "dotnet6": "public.ecr.aws/lambda/dotnet:6",
+ "ruby3.4": "public.ecr.aws/lambda/ruby:3.4",
+ "ruby3.3": "public.ecr.aws/lambda/ruby:3.3",
+ "ruby3.2": "public.ecr.aws/lambda/ruby:3.2",
"provided.al2023": "public.ecr.aws/lambda/provided:al2023",
"provided.al2": "public.ecr.aws/lambda/provided:al2",
"provided": "public.ecr.aws/lambda/provided:latest",
@@ -1040,6 +1090,15 @@ def _docker_image_for_runtime(runtime: str) -> str | None:
if runtime.startswith("nodejs"):
ver = runtime.replace("nodejs", "").rstrip(".x")
return f"public.ecr.aws/lambda/nodejs:{ver}"
+ if runtime.startswith("java"):
+ ver = runtime.replace("java", "")
+ return f"public.ecr.aws/lambda/java:{ver}"
+ if runtime.startswith("dotnet"):
+ ver = runtime.replace("dotnet", "")
+ return f"public.ecr.aws/lambda/dotnet:{ver}"
+ if runtime.startswith("ruby"):
+ ver = runtime.replace("ruby", "")
+ return f"public.ecr.aws/lambda/ruby:{ver}"
if runtime.startswith("provided"):
return "public.ecr.aws/lambda/provided:al2023"
return None
@@ -1079,7 +1138,7 @@ def _get_warm_container(key: str):
return None
-def _cache_warm_container(key: str, container):
+def _cache_warm_container(key: str, container, tmpdir: str = None):
"""Store a running container in the warm cache."""
with _warm_containers_lock:
# Evict old entry if exists
@@ -1090,11 +1149,16 @@ def _cache_warm_container(key: str, container):
old["container"].remove(force=True)
except Exception:
pass
- _warm_containers[key] = {"container": container, "last_used": time.time()}
+ old_tmpdir = old.get("tmpdir")
+ if old_tmpdir and os.path.exists(old_tmpdir):
+ import shutil
+ shutil.rmtree(old_tmpdir, ignore_errors=True)
+ _warm_containers[key] = {"container": container, "last_used": time.time(), "tmpdir": tmpdir}
def _cleanup_warm_containers():
- """Remove all warm containers. Called on reset() and shutdown."""
+ """Remove all warm containers and their tmpdirs. Called on reset() and shutdown."""
+ import shutil
with _warm_containers_lock:
for key, entry in list(_warm_containers.items()):
try:
@@ -1105,15 +1169,28 @@ def _cleanup_warm_containers():
entry["container"].remove(force=True)
except Exception:
pass
+ tmpdir = entry.get("tmpdir")
+ if tmpdir and os.path.exists(tmpdir):
+ shutil.rmtree(tmpdir, ignore_errors=True)
_warm_containers.clear()
+def _docker_cp_dir(container, src_dir: str, dest_dir: str):
+ """Copy a local directory into a Docker container using a tar archive."""
+ import tarfile
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as tar:
+ tar.add(src_dir, arcname=".")
+ buf.seek(0)
+ container.put_archive(dest_dir, buf)
+
+
def _invoke_rie(container, event: dict, timeout: int) -> dict:
"""POST event to a running RIE container's HTTP endpoint."""
import urllib.request
- max_attempts = int(timeout * 2) + 10
+ max_attempts = int(timeout * 10) + 20
for _attempt in range(max_attempts):
- time.sleep(0.5)
+ time.sleep(0.1)
container.reload()
if container.status != "running":
break
@@ -1123,6 +1200,14 @@ def _invoke_rie(container, event: dict, timeout: int) -> dict:
container_ip = None
if LAMBDA_DOCKER_NETWORK:
container_ip = networks.get(LAMBDA_DOCKER_NETWORK, {}).get("IPAddress", "")
+ if not container_ip and _running_in_container():
+ # DinD: host-mapped ports aren't reachable from inside this container.
+ # Use the Lambda container's IP on any available Docker network.
+ for net_info in networks.values():
+ ip = net_info.get("IPAddress", "")
+ if ip:
+ container_ip = ip
+ break
if container_ip:
rie_url = f"http://{container_ip}:8080/2015-03-31/functions/function/invocations"
else:
@@ -1208,10 +1293,9 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
pass
# Cold start — create new container
- try:
- client = docker_lib.from_env()
- except Exception as exc:
- logger.warning("Cannot connect to Docker daemon (%s) – falling back to local subprocess", exc)
+ client = _get_docker_client()
+ if not client:
+ logger.warning("Cannot connect to Docker daemon – falling back to local subprocess")
return _execute_function_local(func, event)
# Code and layers are extracted to a persistent temp dir (not cleaned up
@@ -1248,14 +1332,29 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
layers_dirs.append(layer_dir)
# Build mounts — RIE expects code at /var/task, layers at /opt
+ # Detect Docker-in-Docker: if running inside a container, bind mount
+ # paths from /tmp won't exist on the host. Use LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT
+ # if set, otherwise fall back to docker cp after container creation.
+ _use_docker_cp = False
host_code_dir = LAMBDA_DOCKER_VOLUME_MOUNT or code_dir
- mounts = [
- docker_lib.types.Mount("/var/task", host_code_dir, type="bind", read_only=True),
- ]
- if is_provided:
- mounts.append(docker_lib.types.Mount("/var/runtime", host_code_dir, type="bind", read_only=True))
- for idx, ld in enumerate(layers_dirs):
- mounts.append(docker_lib.types.Mount(f"/opt/layer_{idx}", ld, type="bind", read_only=True))
+ mounts = []
+ if LAMBDA_DOCKER_VOLUME_MOUNT:
+ mounts.append(docker_lib.types.Mount("/var/task", host_code_dir, type="bind", read_only=True))
+ if is_provided:
+ mounts.append(docker_lib.types.Mount("/var/runtime", host_code_dir, type="bind", read_only=True))
+ for idx, ld in enumerate(layers_dirs):
+ mounts.append(docker_lib.types.Mount(f"/opt/layer_{idx}", ld, type="bind", read_only=True))
+ elif _running_in_container():
+ # Running inside Docker — bind mounts from tmpdir won't work
+ # because the host Docker daemon can't see our container's filesystem.
+ # We'll use docker cp after container creation instead.
+ _use_docker_cp = True
+ else:
+ mounts.append(docker_lib.types.Mount("/var/task", host_code_dir, type="bind", read_only=True))
+ if is_provided:
+ mounts.append(docker_lib.types.Mount("/var/runtime", host_code_dir, type="bind", read_only=True))
+ for idx, ld in enumerate(layers_dirs):
+ mounts.append(docker_lib.types.Mount(f"/opt/layer_{idx}", ld, type="bind", read_only=True))
# Build environment
container_env: dict[str, str] = {
@@ -1293,22 +1392,35 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
"image": image,
"command": cmd,
"environment": container_env,
- "mounts": mounts,
"ports": {"8080/tcp": None},
"detach": True,
"stdin_open": False,
"labels": {"ministack": "lambda"},
}
+ if mounts:
+ run_kwargs["mounts"] = mounts
if LAMBDA_DOCKER_NETWORK:
run_kwargs["network"] = LAMBDA_DOCKER_NETWORK
- container = client.containers.run(**run_kwargs)
+ if _use_docker_cp:
+ # Docker-in-Docker: create container first, copy code in, then start
+ create_kwargs = {k: v for k, v in run_kwargs.items() if k not in ("detach", "stdin_open")}
+ container = client.containers.create(**create_kwargs)
+ _docker_cp_dir(container, code_dir, "/var/task")
+ if is_provided:
+ _docker_cp_dir(container, code_dir, "/var/runtime")
+ for idx, ld in enumerate(layers_dirs):
+ _docker_cp_dir(container, ld, f"/opt/layer_{idx}")
+ container.start()
+ else:
+ container = client.containers.run(**run_kwargs)
result = _invoke_rie(container, event, timeout)
if not result.get("error"):
# Success — cache the warm container for reuse
- _cache_warm_container(cache_key, container)
+ _cache_warm_container(cache_key, container, tmpdir=tmpdir)
container = None # prevent finally from killing it
+ tmpdir = None # prevent finally from cleaning it
logger.info("Lambda %s: cold start RIE container cached for reuse", config["FunctionName"])
return result
@@ -1331,6 +1443,9 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
container.remove(force=True)
except Exception:
pass
+ if tmpdir is not None and os.path.exists(tmpdir):
+ import shutil
+ shutil.rmtree(tmpdir, ignore_errors=True)
# ---------------------------------------------------------------------------
@@ -1369,23 +1484,28 @@ def _execute_function_warm(func: dict, event: dict) -> dict:
return {"body": {"statusCode": 200, "body": "Mock response - no code deployed"}}
func_name = config.get("FunctionName", "unknown")
+ qualifier = config.get("Version", "$LATEST")
try:
- worker = get_or_create_worker(func_name, config, code_zip)
+ worker = get_or_create_worker(func_name, config, code_zip, qualifier=qualifier)
result = worker.invoke(event, new_uuid())
if result.get("status") == "ok":
return {"body": result.get("result"), "log": result.get("log", "")}
else:
+ error_msg = result.get("error", "Unknown error")
+ error_type = "Runtime.HandlerError"
+ if "timed out" in error_msg.lower():
+ error_type = "Runtime.ExitError"
return {
"body": {
- "errorMessage": result.get("error", "Unknown error"),
- "errorType": "Runtime.HandlerError",
+ "errorMessage": error_msg,
+ "errorType": error_type,
},
"error": True,
"log": result.get("trace", result.get("error", "")),
}
except Exception as e:
logger.error("Warm worker execution error for %s: %s", func_name, e)
- invalidate_worker(func_name)
+ invalidate_worker(func_name, qualifier=qualifier)
return {
"body": {"errorMessage": str(e), "errorType": type(e).__name__},
"error": True,
@@ -1412,10 +1532,9 @@ def _execute_function_image(func: dict, event: dict) -> dict:
timeout = config.get("Timeout", 30)
env_vars = config.get("Environment", {}).get("Variables", {})
- try:
- client = docker_lib.from_env()
- except Exception as exc:
- return {"body": {"errorMessage": f"Cannot connect to Docker: {exc}", "errorType": "Runtime.DockerError"}, "error": True}
+ client = _get_docker_client()
+ if not client:
+ return {"body": {"errorMessage": "Cannot connect to Docker", "errorType": "Runtime.DockerError"}, "error": True}
# Use image locally if available, otherwise pull
try:
@@ -1458,40 +1577,8 @@ def _execute_function_image(func: dict, event: dict) -> dict:
container = client.containers.run(**run_kwargs)
try:
- import time as _time
- import urllib.request
- for _attempt in range(int(timeout * 2) + 10):
- _time.sleep(0.5)
- container.reload()
- if container.status != "running":
- break
- try:
- if LAMBDA_DOCKER_NETWORK:
- networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
- container_ip = networks.get(LAMBDA_DOCKER_NETWORK, {}).get("IPAddress", "")
- if container_ip:
- rie_url = f"http://{container_ip}:8080/2015-03-31/functions/function/invocations"
- else:
- continue
- else:
- ports = container.ports.get("8080/tcp") or []
- if not ports:
- continue
- rie_url = f"http://127.0.0.1:{ports[0]['HostPort']}/2015-03-31/functions/function/invocations"
- req = urllib.request.Request(rie_url, data=json.dumps(event).encode(),
- headers={"Content-Type": "application/json"})
- resp = urllib.request.urlopen(req, timeout=timeout)
- body = resp.read().decode("utf-8", errors="replace")
- try:
- parsed = json.loads(body)
- except json.JSONDecodeError:
- parsed = body
- logs = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace").strip()
- return {"body": parsed, "log": logs}
- except (urllib.error.URLError, ConnectionRefusedError, OSError):
- continue
- stdout = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace").strip()
- return {"body": {"errorMessage": f"Image Lambda failed: {stdout[:500]}", "errorType": "Runtime.ExitError"}, "error": True, "log": stdout}
+ result = _invoke_rie(container, event, timeout)
+ return result
finally:
try:
container.stop(timeout=2)
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 1256ee76..b000ecfc 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -304,7 +304,7 @@ def _extract_user_metadata(headers: dict) -> dict:
return meta
-def _build_object_record(body: bytes, headers: dict) -> dict:
+def _build_object_record(body: bytes, headers: dict, etag: str = None) -> dict:
content_type = headers.get("content-type", "application/octet-stream")
content_encoding = headers.get("content-encoding")
preserved = {}
@@ -317,7 +317,7 @@ def _build_object_record(body: bytes, headers: dict) -> dict:
"body": body,
"content_type": content_type,
"content_encoding": content_encoding,
- "etag": f'"{md5_hash(body)}"',
+ "etag": etag or f'"{md5_hash(body)}"',
"last_modified": now_iso(),
"size": len(body),
"metadata": _extract_user_metadata(headers),
@@ -1562,7 +1562,8 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
if md5_err:
return md5_err
- obj = _build_object_record(body, headers)
+ etag = f'"{md5_hash(body)}"'
+ obj = _build_object_record(body, headers, etag=etag)
bucket["objects"][key] = obj
# --- Object Lock headers on PutObject ---
diff --git a/pyproject.toml b/pyproject.toml
index 19a29325..e5fa03ed 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.2.20"
+version = "1.2.21"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
@@ -65,6 +65,9 @@ include = ["ministack*"]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
+markers = [
+ "serial: tests that mutate global server state and must run alone",
+]
[tool.ruff]
line-length = 120
diff --git a/tests/conftest.py b/tests/conftest.py
index 89d6c14f..63c73d48 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -37,6 +37,7 @@ _SERIAL_TESTS = {
"tests/test_sfn.py::test_sfn_mock_config_throw",
"tests/test_ec2.py::test_ec2_create_default_vpc",
"tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait",
+ "tests/test_sfn.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",
}
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index a43a22c5..1097cf1e 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -548,7 +548,7 @@ def test_cognito_refresh_token_auth_correct_user(cognito_idp):
ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
)["UserPoolClient"]["ClientId"]
- for name, pw in [("first", "First1!"), ("second", "Second1!")]:
+ for name, pw in [("first", "FirstPass1!"), ("second", "SecondPass1!")]:
cognito_idp.admin_create_user(UserPoolId=pid, Username=name)
cognito_idp.admin_set_user_password(UserPoolId=pid, Username=name, Password=pw, Permanent=True)
@@ -557,7 +557,7 @@ def test_cognito_refresh_token_auth_correct_user(cognito_idp):
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "second", "PASSWORD": "Second1!"},
+ AuthParameters={"USERNAME": "second", "PASSWORD": "SecondPass1!"},
)
refresh_token = auth["AuthenticationResult"]["RefreshToken"]
@@ -700,7 +700,7 @@ def test_cognito_update_user_pool_client(cognito_idp):
def test_cognito_admin_reset_user_password(cognito_idp):
pid = cognito_idp.create_user_pool(PoolName="ResetPwdPool")["UserPool"]["Id"]
cognito_idp.admin_create_user(UserPoolId=pid, Username="resetuser")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="resetuser", Password="Pass1!", Permanent=True)
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="resetuser", Password="PassWord1!", Permanent=True)
cognito_idp.admin_reset_user_password(UserPoolId=pid, Username="resetuser")
user = cognito_idp.admin_get_user(UserPoolId=pid, Username="resetuser")
assert user["UserStatus"] == "RESET_REQUIRED"
@@ -808,14 +808,14 @@ def test_cognito_refresh_token_returns_correct_user(cognito_idp):
ClientName="qa-refresh-app",
ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
)["UserPoolClient"]["ClientId"]
- for name, pw in [("qa-first", "First1!"), ("qa-second", "Second1!")]:
+ for name, pw in [("qa-first", "FirstPass1!"), ("qa-second", "SecondPass1!")]:
cognito_idp.admin_create_user(UserPoolId=pid, Username=name)
cognito_idp.admin_set_user_password(UserPoolId=pid, Username=name, Password=pw, Permanent=True)
auth = cognito_idp.admin_initiate_auth(
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "qa-second", "PASSWORD": "Second1!"},
+ AuthParameters={"USERNAME": "qa-second", "PASSWORD": "SecondPass1!"},
)
refresh_token = auth["AuthenticationResult"]["RefreshToken"]
refresh = cognito_idp.admin_initiate_auth(
@@ -853,14 +853,14 @@ def test_cognito_disabled_user_auth_fails(cognito_idp):
ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
)["UserPoolClient"]["ClientId"]
cognito_idp.admin_create_user(UserPoolId=pid, Username="qa-disabled")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="qa-disabled", Password="Dis1!", Permanent=True)
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="qa-disabled", Password="DisableP1!", Permanent=True)
cognito_idp.admin_disable_user(UserPoolId=pid, Username="qa-disabled")
with pytest.raises(ClientError) as exc:
cognito_idp.admin_initiate_auth(
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "qa-disabled", "PASSWORD": "Dis1!"},
+ AuthParameters={"USERNAME": "qa-disabled", "PASSWORD": "DisableP1!"},
)
assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
@@ -936,8 +936,8 @@ def test_cognito_totp_full_flow(cognito_idp):
assert cfg["SoftwareTokenMfaConfiguration"]["Enabled"] is True
# Create and confirm user
- cognito_idp.admin_create_user(UserPoolId=pid, Username="totp-user", TemporaryPassword="Tmp1!")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="totp-user", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="totp-user", TemporaryPassword="TmpPass1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="totp-user", Password="PermPass1!", Permanent=True)
# Enroll TOTP: associate → get tokens first (MFA not yet enrolled, pool is ON but no enrollment)
# Pool ON with no enrollment → auth succeeds so user can enroll
@@ -945,7 +945,7 @@ def test_cognito_totp_full_flow(cognito_idp):
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "totp-user", "PASSWORD": "Perm1!"},
+ AuthParameters={"USERNAME": "totp-user", "PASSWORD": "PermPass1!"},
)
access_token = auth["AuthenticationResult"]["AccessToken"]
@@ -963,7 +963,7 @@ def test_cognito_totp_full_flow(cognito_idp):
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "totp-user", "PASSWORD": "Perm1!"},
+ AuthParameters={"USERNAME": "totp-user", "PASSWORD": "PermPass1!"},
)
assert auth2.get("ChallengeName") == "SOFTWARE_TOKEN_MFA"
assert "Session" in auth2
@@ -995,19 +995,19 @@ def test_cognito_totp_optional_mfa(cognito_idp):
)
# User without MFA enrolled
- cognito_idp.admin_create_user(UserPoolId=pid, Username="no-mfa-user", TemporaryPassword="Tmp1!")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="no-mfa-user", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="no-mfa-user", TemporaryPassword="TmpPass1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="no-mfa-user", Password="PermPass1!", Permanent=True)
auth = cognito_idp.admin_initiate_auth(
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "no-mfa-user", "PASSWORD": "Perm1!"},
+ AuthParameters={"USERNAME": "no-mfa-user", "PASSWORD": "PermPass1!"},
)
assert "AuthenticationResult" in auth # no challenge — not enrolled
# User with MFA enrolled via AdminSetUserMFAPreference
- cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-user", TemporaryPassword="Tmp1!")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-user", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-user", TemporaryPassword="TmpPass1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-user", Password="PermPass1!", Permanent=True)
cognito_idp.admin_set_user_mfa_preference(
UserPoolId=pid,
Username="mfa-user",
@@ -1017,15 +1017,15 @@ def test_cognito_totp_optional_mfa(cognito_idp):
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "mfa-user", "PASSWORD": "Perm1!"},
+ AuthParameters={"USERNAME": "mfa-user", "PASSWORD": "PermPass1!"},
)
assert auth2.get("ChallengeName") == "SOFTWARE_TOKEN_MFA"
def test_cognito_admin_get_user_mfa_fields(cognito_idp):
"""AdminGetUser returns correct UserMFASettingList and PreferredMfaSetting."""
pid = cognito_idp.create_user_pool(PoolName="qa-totp-getuser")["UserPool"]["Id"]
- cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-check-user", TemporaryPassword="Tmp1!")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-check-user", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="mfa-check-user", TemporaryPassword="TmpPass1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="mfa-check-user", Password="PermPass1!", Permanent=True)
# Before enrollment
u = cognito_idp.admin_get_user(UserPoolId=pid, Username="mfa-check-user")
@@ -1050,14 +1050,14 @@ def test_cognito_set_user_mfa_preference_via_token(cognito_idp):
ClientName="qa-totp-self-app",
ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
)["UserPoolClient"]["ClientId"]
- cognito_idp.admin_create_user(UserPoolId=pid, Username="self-enroll", TemporaryPassword="Tmp1!")
- cognito_idp.admin_set_user_password(UserPoolId=pid, Username="self-enroll", Password="Perm1!", Permanent=True)
+ cognito_idp.admin_create_user(UserPoolId=pid, Username="self-enroll", TemporaryPassword="TmpPass1!")
+ cognito_idp.admin_set_user_password(UserPoolId=pid, Username="self-enroll", Password="PermPass1!", Permanent=True)
auth = cognito_idp.admin_initiate_auth(
UserPoolId=pid,
ClientId=cid,
AuthFlow="ADMIN_USER_PASSWORD_AUTH",
- AuthParameters={"USERNAME": "self-enroll", "PASSWORD": "Perm1!"},
+ AuthParameters={"USERNAME": "self-enroll", "PASSWORD": "PermPass1!"},
)
access_token = auth["AuthenticationResult"]["AccessToken"]
diff --git a/tests/test_ecs.py b/tests/test_ecs.py
index 5f3d534b..a4d9dee1 100644
--- a/tests/test_ecs.py
+++ b/tests/test_ecs.py
@@ -72,9 +72,17 @@ def test_ecs_run_task_stops_after_exit(ecs):
def test_ecs_run_task_network_connectivity(ecs):
"""ECS container can reach Ministack (proves network detection works)."""
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
- # When Ministack runs on the host (CI), containers need host.docker.internal.
- # When Ministack runs in Docker (compose), network detection handles it.
- host = os.environ.get("MINISTACK_HOST_FROM_CONTAINER", "host.docker.internal")
+ # Determine how a container can reach the host where Ministack runs.
+ # Docker Desktop (macOS/Windows): host.docker.internal works.
+ # Linux: use the Docker bridge gateway IP (typically 172.17.0.1).
+ host = os.environ.get("MINISTACK_HOST_FROM_CONTAINER", "")
+ if not host:
+ import platform
+ if platform.system() == "Linux":
+ # Docker bridge gateway — how containers reach the host on Linux
+ host = "172.17.0.1"
+ else:
+ host = "host.docker.internal"
parsed = urlparse(endpoint)
container_endpoint = f"{parsed.scheme}://{host}:{parsed.port}"
diff --git a/tests/test_eks.py b/tests/test_eks.py
index 2ea624bc..f101b24b 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -46,7 +46,7 @@ def test_eks_create_describe_delete_cluster(eks):
)
cluster = resp["cluster"]
assert cluster["name"] == name
- assert cluster["status"] == "ACTIVE"
+ assert cluster["status"] in ("CREATING", "ACTIVE")
assert cluster["version"] == "1.30"
assert "arn" in cluster
assert f"cluster/{name}" in cluster["arn"]
@@ -55,11 +55,14 @@ def test_eks_create_describe_delete_cluster(eks):
assert "identity" in cluster
assert "oidc" in cluster["identity"]
- # Describe
- resp = eks.describe_cluster(name=name)
+ # Describe — poll until background k3s startup completes
+ for _ in range(30):
+ resp = eks.describe_cluster(name=name)
+ if resp["cluster"]["status"] == "ACTIVE":
+ break
+ time.sleep(1)
assert resp["cluster"]["name"] == name
assert resp["cluster"]["status"] == "ACTIVE"
- assert resp["cluster"]["endpoint"] == cluster["endpoint"]
# Delete
resp = eks.delete_cluster(name=name)