Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
3390 lines (2959 loc) · 142 KB
/
Copy pathapp.py
File metadata and controls
3390 lines (2959 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
"""
MiniStack — Local AWS Service Emulator.
Single-port ASGI application on port 4566 (configurable via GATEWAY_PORT).
Routes requests to service handlers based on AWS headers, paths, and query parameters.
Compatible with AWS CLI, boto3, and any AWS SDK via --endpoint-url.
"""
import argparse
import asyncio
import base64
import gzip
import json
import logging
import math
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import uuid
from urllib.parse import parse_qs, unquote
_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
_MINISTACK_PORT = os.environ.get("GATEWAY_PORT", "4566")
AUTH = os.environ.get("AUTH", "false").lower() == "true"
_VERSION = os.environ.get("MINISTACK_VERSION") or ""
def _version() -> str:
"""The reported version, resolved on first ask and cached."""
global _VERSION
if not _VERSION:
try:
from importlib.metadata import version as _pkg_version
_VERSION = _pkg_version("ministack")
except Exception:
_VERSION = "dev"
return _VERSION
# Matches host headers like "{apiId}.execute-api.<host>" or "{apiId}.execute-api.<host>:4566"
_EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$")
# A distribution's DomainName: <label>.cloudfront.net, or <label>.cloudfront.<MINISTACK_HOST>.
_CLOUDFRONT_HOST_RE = re.compile(
r"^([a-z0-9]+)\.cloudfront\.(?:net|" + re.escape(_MINISTACK_HOST) + r")(?::\d+)?$"
)
# Lambda Function URL: {urlId}.lambda-url.{region}.<anything>[:port]. The stored
# FunctionUrl carries AWS's own `.on.aws` suffix, so we match any suffix rather
# than only _MINISTACK_HOST — pointing a proxy or an /etc/hosts entry at the
# AWS-shaped hostname is the whole point of addressing a function this way.
_LAMBDA_URL_RE = re.compile(r"^([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\.lambda-url\.[a-z0-9-]+\.")
# OpenSearch Serverless collection endpoint: {collectionId}.{region}.aoss.<anything>[:port].
_AOSS_COLLECTION_HOST_RE = re.compile(r"^[a-z0-9]{3,40}\.[a-z0-9-]+\.aoss\.", re.IGNORECASE)
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
# IoT data plane WebSocket: anything containing ".iot." in the host header.
# Match AWS-shaped IoT hosts only — `iot.<region>.<host>`,
# `data-ats.iot.<region>.<host>`, `data.iot.<region>.<host>`, and the
# account-prefixed endpoint returned by DescribeEndpoint
# (`<prefix>.iot.<region>.<host>`). Anchored at a host-segment boundary
# (start-of-host or after a dot) so custom domains that happen to contain
# `.iot.` as a substring (e.g. an S3 bucket `mybucket.iot.example.com`) are
# not misrouted into the MQTT WebSocket handler.
_IOT_DATA_WS_RE = re.compile(r"(^|\.)iot\.[a-z0-9-]+\.")
def _ws_has_mqtt_subprotocol(ws_headers: dict) -> bool:
"""Check whether the upgrade request advertises an ``mqtt`` subprotocol."""
raw = ws_headers.get("sec-websocket-protocol", "")
for proto in (p.strip().lower() for p in raw.split(",") if p.strip()):
if proto in ("mqtt", "mqttv3.1", "mqttv5"):
return True
return False
def _ws_resolve_iot_account_id(scope: dict, ws_headers: dict) -> str:
"""Pick the account ID for an inbound IoT WebSocket upgrade.
Resolution order:
1. ``X-Amz-Credential`` query parameter (SigV4-signed WS) — extract the
access key portion. If it's a 12-digit number, use it as the account.
2. ``Authorization: AWS4-HMAC-SHA256`` header — same extraction.
3. Fall back to ``MINISTACK_ACCOUNT_ID`` / ``000000000000``.
SigV4 signature *verification* is intentionally lax (any
well-formed credential is accepted); IoT policy enforcement is not yet
feature. The point here is multi-tenancy isolation, not auth.
"""
qs = scope.get("query_string", b"").decode("utf-8", errors="replace")
qp = parse_qs(qs, keep_blank_values=True) if qs else {}
cred = ""
raw = qp.get("X-Amz-Credential") or qp.get("x-amz-credential")
if raw:
cred = raw[0] if isinstance(raw, list) else raw
if not cred:
auth = ws_headers.get("authorization", "")
m = re.search(r"Credential=([^,/]+)/", auth)
if m:
cred = m.group(1)
access_key = cred.split("/", 1)[0] if cred else ""
if access_key and re.match(r"^\d{12}$", access_key):
return access_key
return os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
# Virtual-hosted S3 bucket extraction. AWS-aligned per
# docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html and
# bucketnamingrules.html (HTTP vhost — ministack is HTTP). Works for any
# endpoint hostname (localhost, ministack, custom Docker DNS, real AWS
# domains) without hardcoding _MINISTACK_HOST.
_IPV4_RE = re.compile(r"^(?:\d{1,3}\.){3}\d{1,3}$")
_BUCKET_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.\-]{1,61}[a-z0-9])$")
def _extract_s3_vhost_bucket(host: str):
"""Return the bucket if Host is virtual-hosted-style S3, else None.
AWS virtual-hosted patterns (all must resolve to a bucket):
<bucket>.<base-host> — SDK default
<bucket>.s3.<base-host> — explicit S3 endpoint
<bucket>.s3.<region>.<base-host> — region-qualified
<bucket>.s3-website.<region>.<base-host> — static website
<bucket>.s3-accelerate.<base-host> — transfer acceleration
A bare ``<base-host>`` (no leading bucket label) is path-style → None.
"""
if not host:
return None
host = host.strip()
if not host or host.startswith("["):
return None
host = host.lower()
if ":" in host:
host = host.rsplit(":", 1)[0]
if not host or _IPV4_RE.match(host) or "." not in host:
return None
candidate, tail = host.split(".", 1)
if not tail or tail.startswith("."):
return None
if not _BUCKET_LABEL_RE.match(candidate):
return None
if ".." in candidate or _IPV4_RE.match(candidate):
return None
if tail == _MINISTACK_HOST or tail.endswith("." + _MINISTACK_HOST):
return candidate
first_tail_segment = tail.split(".", 1)[0]
if first_tail_segment == "s3" or first_tail_segment.startswith(("s3-", "s3express-")):
return candidate
return None
_S3_VHOST_EXCLUDE_RE = re.compile(
r"\.(execute-api|lambda-url|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api|iot|cloudfront)\."
)
_HEALTH_PATHS = ("/_ministack/health", "/_localstack/health", "/health")
_BODY_METHODS = ("POST", "PUT", "PATCH")
_COGNITO_USERINFO_PATHS = ("/oauth2/userInfo", "/oauth2/userinfo")
_RDS_DATA_PATHS = ("/Execute", "/BeginTransaction", "/CommitTransaction", "/RollbackTransaction", "/BatchExecute")
_S3_CONTROL_PREFIX = "/v20180820/"
_SES_V2_PREFIX = "/v2/email"
_ALB_PATH_PREFIX = "/_alb/"
_NON_S3_VHOST_NAMES = frozenset(
{
"s3",
"s3-control",
"sqs",
"sns",
"dynamodb",
"lambda",
"iam",
"sts",
"secretsmanager",
"logs",
"ssm",
"events",
"kinesis",
"monitoring",
"ses",
"states",
"ecs",
"rds",
"rds-data",
"elasticache",
"glue",
"athena",
"airflow",
"apigateway",
"cloudformation",
"autoscaling",
"codebuild",
"transfer",
"cur",
"cloudfront-kvs",
"appsync-api",
"appsync-realtime-api",
"inspector2",
"dsql",
}
)
from ministack.core import container_reaper
from ministack.core.concurrency import spawn_background
from ministack.core.hypercorn_compat import install as _install_hypercorn_compat
from ministack.core.iam_evaluator import (
AmbiguousAccessKeyError,
find_iam_access_key_account,
)
from ministack.core.persistence import PERSIST_STATE, load_state, save_all
from ministack.core.responses import (
_12_DIGIT_RE,
set_request_account_id,
set_request_region,
)
from ministack.core.router import detect_service, extract_access_key_id, extract_region
# Must run before hypercorn emits its first Expect: 100-continue reply.
# See ministack/core/hypercorn_compat.py for the rationale (issue #389).
_install_hypercorn_compat()
# ---------------------------------------------------------------------------
# Lazy service loader — modules are imported on first request, not at startup.
# This saves ~20 MB of idle RAM and speeds up boot.
# ---------------------------------------------------------------------------
_loaded_modules: dict = {}
def _request_account_scope(access_key_id: str) -> str:
"""Return the tenant selector for an AWS access key."""
return find_iam_access_key_account(access_key_id) or access_key_id
# Execution state of ready.d scripts — surfaced via /_ministack/health and /_ministack/ready.
# status: "pending" (not started) | "running" | "completed" (all scripts finished, errors included)
_ready_scripts_state: dict = {
"status": "pending",
"total": 0,
"completed": 0,
"failed": 0,
}
class _ErrorModule:
"""Stub returned when a service module fails to import."""
def __init__(self, name: str, error: str):
self._name = name
self._error = error
async def handle_request(self, method, path, headers, body, query_params):
return (
500,
{"Content-Type": "application/json"},
json.dumps(
{
"__type": "ServiceUnavailable",
"message": f"Service module '{self._name}' failed to load: {self._error}",
}
).encode(),
)
def get_state(self):
# None, not {}. This module never loaded, so it has no state — and
# writing an empty dict here would overwrite whatever the last working
# run persisted, losing every resource the service held.
return None
def _restore_state(self, data):
pass
def load_persisted_state(self, data):
pass
def reset(self):
pass
def _get_module(name: str):
"""Import and cache a service module by short name (e.g. 's3', 'lambda_svc')."""
mod = _loaded_modules.get(name)
if mod is None:
try:
mod = __import__(f"ministack.services.{name}", fromlist=["handle_request"])
except (ModuleNotFoundError, ImportError) as e:
logger.warning("Service module failed to load: %s - %s", name, e)
mod = _ErrorModule(name, str(e))
_loaded_modules[name] = mod
return mod
# The loop serving HTTP requests, captured at lifespan startup. Worker threads
# (Step Functions executions, CloudFormation provisioners) need it to call a
# service handler, because a handler may genuinely await now.
_MAIN_LOOP = None
def call_service_handler_sync(handler, method, path, headers, body, query_params, timeout: float | None = None):
"""Call an async service handler from a worker thread and return its result.
In-process callers used to drive handlers with ``coro.send(None)``, relying
on an unwritten invariant that service handlers never actually await. That
held only while every handler was synchronous underneath. The moment one
awaits — offloading Docker work, for instance — the first step runs with no
running event loop and raises ``RuntimeError: no running event loop``, which
escapes past the caller's ``except StopIteration``.
So the coroutine is scheduled on the loop that is actually running and this
thread waits for the result. Callers must be on a worker thread: waiting on
the loop from the loop itself would deadlock, so that is refused loudly
rather than hanging.
"""
loop = _MAIN_LOOP
if loop is None or loop.is_closed():
# No server running (unit tests, CLI use): drive it on a private loop.
return asyncio.run(handler(method, path, headers, body, query_params))
try:
running = asyncio.get_running_loop()
except RuntimeError:
running = None
if running is loop:
raise RuntimeError(
"call_service_handler_sync must be called from a worker thread, "
"not from the event loop — await the handler directly instead"
)
future = asyncio.run_coroutine_threadsafe(handler(method, path, headers, body, query_params), loop)
return future.result(timeout)
def _lazy_handler(module_name: str):
"""Return a callable that lazily imports module_name and delegates to handle_request."""
async def _handler(method, path, headers, body, query_params):
mod = _get_module(module_name)
return await mod.handle_request(method, path, headers, body, query_params)
return _handler
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("ministack")
# Single source of truth for routable services, their backing modules, and aliases.
SERVICE_REGISTRY = {
"account": {"module": "account"},
"acm": {"module": "acm"},
"backup": {"module": "backup"},
"batch": {"module": "batch"},
"apigateway": {
"module": "apigateway",
"aliases": ("execute-api", "apigatewayv2"),
"sub_modules": ("apigateway_v1",),
},
"appconfig": {"module": "appconfig"},
"appconfigdata": {"module": "appconfig"},
"appsync": {"module": "appsync"},
"appsync-events": {"module": "appsync_events"},
"athena": {"module": "athena"},
"autoscaling": {"module": "autoscaling"},
"cloudformation": {"module": "cloudformation"},
"cloudcontrol": {"module": "cloudcontrol"},
"cloudfront": {"module": "cloudfront"},
"cloudfront-keyvaluestore": {"module": "cloudfront_keyvaluestore"},
"codebuild": {"module": "codebuild"},
"cognito-identity": {"module": "cognito"},
"cognito-idp": {"module": "cognito"},
"config": {"module": "config"},
"dynamodb": {"module": "dynamodb"},
"dynamodbstreams": {"module": "dynamodb_streams"},
"dsql": {"module": "dsql"},
"ec2": {"module": "ec2"},
"ecr": {"module": "ecr"},
"ecs": {"module": "ecs"},
"ecs-metadata": {"module": "ecs_metadata"},
"eks": {"module": "eks"},
"elasticache": {"module": "elasticache"},
"elasticfilesystem": {"module": "efs"},
"elasticloadbalancing": {"module": "alb", "aliases": ("elbv2", "elb")},
"elasticmapreduce": {"module": "emr"},
"events": {"module": "eventbridge", "aliases": ("eventbridge",)},
"firehose": {"module": "firehose", "aliases": ("kinesis-firehose",)},
"glue": {"module": "glue"},
"airflow": {"module": "mwaa", "aliases": ("mwaa",)},
"iam": {"module": "iam"},
"imds": {"module": "imds"},
"iot": {"module": "iot"},
"iot-data": {"module": "iot_data"},
"iot-jobs-data": {"module": "iot_jobs_data"},
"iotwireless": {"module": "iotwireless"},
"kinesis": {"module": "kinesis"},
"kms": {"module": "kms"},
# ``lambda`` is a Python keyword, so the implementation module is named
# ``lambda_svc``. Keep ``lambda`` as the persistence key to preserve the
# long-standing ``lambda.json`` state-file contract across warm boots.
"lambda": {
"module": "lambda_svc",
"state_key": "lambda",
"sub_modules": ("lambda_durable",),
},
"lambda-core": {"module": "lambda_core"},
"lambda-microvms": {"module": "lambda_microvms"},
"location": {"module": "location"},
"logs": {"module": "cloudwatch_logs", "aliases": ("cloudwatch-logs",)},
"mediaconnect": {"module": "mediaconnect"},
"opensearch": {"module": "opensearch", "aliases": ("es", "elasticsearch")},
"opensearchserverless": {"module": "opensearchserverless", "aliases": ("aoss",)},
"organizations": {"module": "organizations"},
"monitoring": {"module": "cloudwatch", "aliases": ("cloudwatch",)},
"pipes": {"module": "pipes"},
"rds-data": {"module": "rds_data"},
"rds": {"module": "rds"},
"resource-groups": {"module": "resource_groups"},
"route53": {"module": "route53"},
"s3": {"module": "s3"},
"s3files": {"module": "s3files"},
"scheduler": {"module": "scheduler"},
"secretsmanager": {"module": "secretsmanager"},
"servicediscovery": {"module": "servicediscovery"},
"ses": {"module": "ses", "sub_modules": ("ses_v2",)},
"signer": {"module": "signer"},
"sns": {"module": "sns"},
"sqs": {"module": "sqs"},
"ssm": {"module": "ssm"},
"states": {"module": "stepfunctions", "aliases": ("step-functions", "stepfunctions")},
"sts": {"module": "sts"},
"tagging": {"module": "tagging"},
"transcribe": {"module": "transcribe"},
"translate": {"module": "translate"},
"transfer": {"module": "transfer"},
"waf": {"module": "waf_v1"},
"waf-regional": {"module": "waf_v1"},
"wafv2": {"module": "waf"},
"cloudtrail": {"module": "cloudtrail"},
"cur": {"module": "cur"},
"inspector2": {"module": "inspector2"},
"mq": {"module": "mq"},
"s3tables": {"module": "s3tables"},
"bedrock": {"module": "bedrock"},
"bedrock-runtime": {"module": "bedrock_runtime"},
"bedrock-agent": {"module": "bedrock_agent"},
"bedrock-agent-runtime": {"module": "bedrock_agent_runtime"},
"bedrock-agentcore": {"module": "bedrock_agentcore"},
"kafka": {"module": "msk"},
}
SERVICE_HANDLERS = {
service_name: _lazy_handler(service_config["module"]) for service_name, service_config in SERVICE_REGISTRY.items()
}
def _registry_module_names():
"""Return every primary and dispatched module declared by the registry."""
return {
module
for config in SERVICE_REGISTRY.values()
for module in (config["module"], *config.get("sub_modules", ()))
}
def _registry_state_map():
"""Map persistence-file keys to modules declared by ``SERVICE_REGISTRY``.
A primary module normally uses its module name for the filename. Lambda
retains its long-standing ``lambda.json`` filename through ``state_key``;
sub-modules always use their own names.
"""
state_map = {}
for config in SERVICE_REGISTRY.values():
module = config["module"]
state_map[config.get("state_key", module)] = module
state_map.update({sub_module: sub_module for sub_module in config.get("sub_modules", ())})
return state_map
# Maps on-disk persistence keys to service modules. The registry is the sole
# declaration point, including modules reached through a service's dispatcher.
_state_map = _registry_state_map()
SERVICE_NAME_ALIASES = {
alias: service_name
for service_name, service_config in SERVICE_REGISTRY.items()
for alias in service_config.get("aliases", ())
}
def _resolve_port():
"""Resolve gateway port: GATEWAY_PORT > EDGE_PORT > 4566."""
return os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
def _port_is_bindable(host: str, port: int) -> bool:
"""Whether `port` can be opened here: free, and permitted to this process."""
import socket as _socket
with _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) as probe:
probe.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
try:
probe.bind(("" if host == "0.0.0.0" else host, port))
except OSError:
return False
return True
if os.environ.get("LOCALSTACK_PERSISTENCE") == "1" and os.environ.get("S3_PERSIST") != "1":
os.environ["S3_PERSIST"] = "1"
logger.info("LOCALSTACK_PERSISTENCE=1 detected — enabling S3_PERSIST")
_services_env = os.environ.get("SERVICES", "").strip()
if _services_env:
_requested = {s.strip() for s in _services_env.split(",") if s.strip()}
_resolved = set()
for _name in _requested:
_key = SERVICE_NAME_ALIASES.get(_name, _name)
if _key in SERVICE_HANDLERS:
_resolved.add(_key)
else:
logger.warning("SERVICES: unknown service '%s' (resolved as '%s') — skipping", _name, _key)
SERVICE_HANDLERS = {k: v for k, v in SERVICE_HANDLERS.items() if k in _resolved}
logger.info("SERVICES filter active — enabled: %s", sorted(SERVICE_HANDLERS.keys()))
BANNER = r"""
__ __ _ _ ____ _ _
| \/ (_)_ __ (_) ___|| |_ __ _ ___| | __
| |\/| | | '_ \| \___ \| __/ _` |/ __| |/ /
| | | | | | | | |___) | || (_| | (__| <
|_| |_|_|_| |_|_|____/ \__\__,_|\___|_|\_\
Local AWS Service Emulator — Port {port}
Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,
SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,
ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,
Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront,
AppSync, Cloud Map, S3 Files, RDS Data API, CodeBuild, AppConfig, Transfer, EKS,
Inspector2, IoT Core, Aurora DSQL
"""
_reset_lock: "asyncio.Lock | None" = None
def _get_reset_lock() -> asyncio.Lock:
global _reset_lock
if _reset_lock is None:
_reset_lock = asyncio.Lock()
return _reset_lock
# ---------------------------------------------------------------------------
# Request I/O helpers
# ---------------------------------------------------------------------------
def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:
"""Decode AWS chunked request bodies and normalize content-encoding headers."""
sha256_header = headers.get("x-amz-content-sha256", "")
content_encoding = headers.get("content-encoding", "")
if not (
sha256_header.startswith("STREAMING-")
or "aws-chunked" in content_encoding
or headers.get("x-amz-decoded-content-length")
):
return body
# Walked by index with the chunks collected for one join. Both the
# decoded += chunk append and re-slicing the unparsed tail copy an
# amount proportional to the whole body on every chunk, which made this
# decode quadratic twice over -- and aws-chunked is what the AWS CLI
# sends for a large streaming PutObject.
chunks = []
pos = 0
trailer = b""
while pos < len(body):
crlf = body.find(b"\r\n", pos)
if crlf == -1:
break
chunk_header = body[pos:crlf].decode("ascii", errors="replace")
size_hex = chunk_header.split(";")[0].strip()
try:
chunk_size = int(size_hex, 16)
except ValueError:
break
if chunk_size == 0:
# Whatever follows the final chunk is the trailing header
# section the request announced in x-amz-trailer.
trailer = body[crlf + 2 :]
break
data_start = crlf + 2
chunks.append(body[data_start : data_start + chunk_size])
pos = data_start + chunk_size + 2 # skip trailing \r\n
decoded = b"".join(chunks)
# A checksum computed while the body streamed arrives here rather than
# among the request headers, and the rest of the request has no way to
# tell the two apart -- so lift it into the headers, where every
# checksum reader already looks. An explicit header wins: the trailer
# is the late copy of the same field, not an override.
for line in trailer.split(b"\r\n"):
name, sep, value = line.partition(b":")
if not sep:
continue
name = name.decode("ascii", errors="replace").strip().lower()
if name:
headers.setdefault(
name, value.decode("utf-8", errors="replace").strip())
body = decoded
if "aws-chunked" in content_encoding:
encodings = [p.strip() for p in content_encoding.split(",") if p.strip() != "aws-chunked"]
if encodings:
headers["content-encoding"] = ", ".join(encodings)
else:
headers.pop("content-encoding", None)
return body
def _decompress_request_body(body: bytes, headers: dict) -> bytes:
"""Inflate a gzip-compressed request body and drop the gzip token.
Smithy's ``@requestCompression`` trait makes AWS SDKs gzip a request body
once it passes ``REQUEST_MIN_COMPRESSION_SIZE_BYTES`` (default 10240) and
send ``Content-Encoding: gzip``. CloudWatch ``PutMetricData`` carries the
trait today; any client may compress a body it is allowed to compress.
Returns ``body`` unchanged when the header does not ask for gzip.
"""
content_encoding = headers.get("content-encoding", "")
if "gzip" not in content_encoding.lower():
return body
try:
inflated = gzip.decompress(body)
except (OSError, EOFError) as e:
# A body flagged gzip that will not inflate is a real bug. Log it and
# pass the raw bytes on, so the handler's own error surfaces.
logger.warning("gzip request body failed to inflate: %s", e)
return body
encodings = [p.strip() for p in content_encoding.split(",") if p.strip().lower() != "gzip"]
if encodings:
headers["content-encoding"] = ", ".join(encodings)
else:
headers.pop("content-encoding", None)
return inflated
async def _read_request_body(receive, method: str, headers: dict) -> bytes:
"""Read and decode the request body only for methods or headers that can carry one."""
body = b""
if headers.get("content-length") or headers.get("transfer-encoding") or method in _BODY_METHODS:
# Chunks are collected and joined once. Appending to a bytes object
# re-copies everything received so far on every 64 KB chunk, which made
# assembling a 95 MB PutObject copy ~76 GB of memory.
chunks = []
while True:
message = await receive()
chunk = message.get("body", b"")
if chunk:
chunks.append(chunk)
if not message.get("more_body", False):
break
body = b"".join(chunks)
return _decode_aws_chunked_body(body, headers)
def _encode_header_value(v: str) -> bytes:
try:
return v.encode("latin-1")
except UnicodeEncodeError:
return v.encode("utf-8")
def _asgi_header_list(headers: dict) -> list:
# A list/tuple header value expands to one header line per item. This is
# required for Set-Cookie, which RFC 6265 §3 forbids folding into a single
# comma-joined header; APIGW Lambda-proxy responses surface multiple
# cookies this way. Scalar values keep their existing single-line behavior.
header_list = []
for k, v in headers.items():
if isinstance(v, (list, tuple)):
for item in v:
header_list.append((k.encode("latin-1"), _encode_header_value(str(item))))
else:
header_list.append((k.encode("latin-1"), _encode_header_value(str(v))))
return header_list
async def _send_response(send, status, headers, body):
"""Send ASGI HTTP response."""
from ministack.core.responses import StreamingResponse
if isinstance(body, StreamingResponse):
raise TypeError("StreamingResponse requires _send_streaming_response(send, receive, ...)")
body_bytes = body if isinstance(body, bytes) else body.encode("utf-8")
if "content-length" not in {k.lower() for k in headers}:
headers["Content-Length"] = str(len(body_bytes))
await send(
{
"type": "http.response.start",
"status": status,
"headers": _asgi_header_list(headers),
}
)
await send(
{
"type": "http.response.body",
"body": body_bytes,
"more_body": False,
}
)
async def _send_streaming_response(send, receive, status, headers, streaming):
"""Hold an HTTP response open and stream body chunks until the runner ends.
Used by CloudWatch Logs ``StartLiveTail`` and by the ALB data plane. A
handler that knows the length keeps ``Content-Length``, so a proxied
response keeps the framing its target chose; long-lived eventstreams set
none and the ASGI server chunks those.
"""
await send(
{
"type": "http.response.start",
"status": status,
"headers": _asgi_header_list(headers),
}
)
try:
await streaming.runner(send, receive)
except Exception:
logger.exception("Streaming response failed")
try:
await send({"type": "http.response.body", "body": b"", "more_body": False})
except Exception:
pass
async def _send_if_handled(send, response, receive=None) -> bool:
"""Send a response tuple and report whether the request was handled."""
if response is None:
return False
from ministack.core.responses import StreamingResponse
status, headers, body = response
if isinstance(body, StreamingResponse):
if receive is None:
raise TypeError("StreamingResponse requires the ASGI receive channel")
await _send_streaming_response(send, receive, status, headers, body)
else:
await _send_response(send, status, headers, body)
return True
# ---------------------------------------------------------------------------
# Tier 1 — Pre-body handlers (no request body needed)
# ---------------------------------------------------------------------------
def _handle_options_request(method: str, request_id: str):
"""Return the standard CORS preflight response when applicable."""
if method != "OPTIONS":
return None
return (
200,
{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH",
"Access-Control-Allow-Headers": "*",
"Access-Control-Expose-Headers": "*",
"Access-Control-Max-Age": "86400",
"Content-Length": "0",
"x-amzn-requestid": request_id,
},
b"",
)
def _handle_health_request(path: str, request_id: str):
"""Return health responses for MiniStack and LocalStack-compatible endpoints."""
if path not in _HEALTH_PATHS:
return None
return (
200,
{
"Content-Type": "application/json",
"x-amzn-requestid": request_id,
},
json.dumps(
{
"services": {s: "available" for s in SERVICE_HANDLERS},
"edition": os.environ.get("MINISTACK_EDITION", "light"),
"version": _version(),
"iot_mtls": _iot_mtls_state,
"ready_scripts": dict(_ready_scripts_state),
}
).encode(),
)
def _handle_ready_request(path: str, request_id: str):
"""Return readiness state once ready.d scripts have completed."""
if path != "/_ministack/ready":
return None
# The mTLS listener binds after the HTTP port, so readiness covers it: a
# consumer polling one endpoint does not race the MQTT port.
ready = (_ready_scripts_state["status"] == "completed"
and _iot_mtls_state != "starting")
status = 200 if ready else 503
body = dict(_ready_scripts_state)
body["iot_mtls"] = _iot_mtls_state
return (
status,
{
"Content-Type": "application/json",
"x-amzn-requestid": request_id,
},
json.dumps(body).encode(),
)
def _handle_unknown_localstack_request(path: str, request_id: str):
"""Return a clear 404 JSON for unrecognised /_localstack/* paths.
/_localstack/health is already matched by _handle_health_request (included in
_HEALTH_PATHS), so only unknown paths reach here. This prevents them from
falling through to the S3 handler and returning confusing NoSuchBucket XML.
"""
if not path.startswith("/_localstack/"):
return None
return (
404,
{
"Content-Type": "application/json",
"x-amzn-requestid": request_id,
},
json.dumps(
{
"error": (
f"Unknown LocalStack endpoint: {path}. "
"Ministack exposes /_ministack/health, /_ministack/ready, and /_ministack/reset. "
"See https://github.com/ministackorg/ministack for the full API."
)
}
).encode(),
)
def _handle_lambda_download_request(path: str, method: str):
"""Serve MiniStack's Lambda layer and function-code download endpoints."""
if path.startswith("/_ministack/lambda-layers/") and method == "GET":
path_parts = path.split("/")
if len(path_parts) >= 8 and path_parts[7] == "content" and path_parts[6].isdigit():
return _get_module("lambda_svc").serve_layer_content(
path_parts[5],
int(path_parts[6]),
account_id=path_parts[3],
region=path_parts[4],
)
if len(path_parts) >= 6 and path_parts[5] == "content" and path_parts[4].isdigit():
return _get_module("lambda_svc").serve_layer_content(path_parts[3], int(path_parts[4]))
if path.startswith("/_ministack/lambda-code/") and method == "GET":
path_parts = path.split("/")
if len(path_parts) >= 6:
return _get_module("lambda_svc").serve_function_code(
path_parts[5],
account_id=path_parts[3],
region=path_parts[4],
)
if len(path_parts) >= 4:
return _get_module("lambda_svc").serve_function_code(path_parts[3])
return None
async def _handle_cognito_get_request(method: str, path: str, headers: dict, query_params: dict):
"""Handle Cognito GET endpoints that do not require request body parsing."""
if "/.well-known/" in path and method == "GET":
# Real AWS serves /<poolId>/.well-known/jwks.json only for actual user
# pools — any other pool prefix errors. Fall through to S3 when the
# pool isn't registered so an S3 object stored under a .well-known/
# key isn't shadowed by a fake Cognito JWKS body.
if path.endswith("/.well-known/jwks.json"):
pool_id = path.rsplit("/.well-known/jwks.json", 1)[0].lstrip("/")
if pool_id:
cognito = _get_module("cognito")
if cognito._get_pool_unscoped(pool_id) is not None:
return cognito.well_known_jwks(pool_id)
elif path.endswith("/.well-known/openid-configuration"):
pool_id = path.rsplit("/.well-known/openid-configuration", 1)[0].lstrip("/")
if pool_id:
cognito = _get_module("cognito")
if cognito._get_pool_unscoped(pool_id) is not None:
region = extract_region(headers) or "us-east-1"
host = headers.get("host") or headers.get("Host")
scheme = headers.get("x-forwarded-proto") or "http"
return cognito.well_known_openid_configuration(
pool_id, region, host, scheme)
if path == "/oauth2/authorize" and method == "GET":
return _get_module("cognito").handle_oauth2_authorize(method, path, headers, query_params)
if path in _COGNITO_USERINFO_PATHS and method == "GET":
return _get_module("cognito").handle_oauth2_userinfo(method, path, headers, b"", query_params)
if path == "/logout" and method == "GET":
return _get_module("cognito").handle_logout(method, path, headers, query_params)
return None
async def _handle_admin_reset(path: str, method: str, query_params: dict):
"""Handle reset requests before request body parsing."""
if path != "/_ministack/reset" or method != "POST":
return None
async with _get_reset_lock():
await asyncio.to_thread(_reset_all_state)
run_init = query_params.get("init", [""])[0] == "1"
if run_init:
_run_init_scripts()
_ready_scripts_state.update({"status": "pending", "total": 0, "completed": 0, "failed": 0})
asyncio.create_task(_run_ready_scripts())
return 200, {"Content-Type": "application/json"}, json.dumps({"reset": "ok"}).encode()
async def _handle_ses_messages_request(method: str, path: str, headers: dict, query_params: dict):
"""Handle SES messages inspection endpoint.
Supports filtering by account via the 'account' query parameter. When provided,
returns messages grouped by account across the service's regional stores.
"""
if path != "/_ministack/ses/messages" or method != "GET":
return None
account_id = None
if "account" in query_params:
raw_account = query_params["account"]
account_id = raw_account[0] if isinstance(raw_account, (list, tuple)) else raw_account
if not _12_DIGIT_RE.match(account_id):
return (
400,
{"Content-Type": "application/json"},
json.dumps(
{
"__type": "InvalidAccountID",
"message": f"Account ID must be 12 digits, got: {account_id}",
}
).encode(),
)
try:
mod = _get_module("ses")
sent_emails_dict = {}
try:
all_data = mod._sent_emails.to_dict()
for scoped_key, val in all_data.items():
if len(scoped_key) == 2:
acct, key = scoped_key
elif len(scoped_key) == 3:
acct, _region, key = scoped_key
else:
continue
if key == "entries" and isinstance(val, list):
sent_emails_dict.setdefault(acct, []).extend(val)
except Exception:
# Fallback: empty dict on any unexpected shape
sent_emails_dict = {}
response = {
"messages": {
acct: [
{
"MessageId": rec["MessageId"],
"Source": rec["Source"],
"To": rec.get("To", []),
"CC": rec.get("CC", []),
"BCC": rec.get("BCC", []),
"Subject": rec.get("RenderedSubject") or rec.get("Subject", ""),
"BodyText": rec.get("RenderedBodyText") or rec.get("BodyText", ""),
"BodyHtml": rec.get("RenderedBodyHtml") or rec.get("BodyHtml"),
"Timestamp": rec["Timestamp"],
"Type": rec["Type"],
}
for rec in (recs if isinstance(recs, list) else [])
]
for acct, recs in sent_emails_dict.items()
if account_id is None or acct == account_id
}
}
except Exception as e:
logger.exception("Error retrieving SES messages: %s", e)
return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()