Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix/lambda-validation-250Mb-S3 persist 10Mb (#496)
Nahuel Nucera2beba80b37c5
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 919eed3e..7f238431 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -413,6 +413,26 @@ def _fetch_code_from_s3(bucket: str, key: str) -> bytes | None:return None+_UNZIPPED_LIMIT_BYTES = 262144000 # 250 MiB — AWS hard limit+++def _validate_unzipped_size(zip_data: bytes | None):+ if not zip_data:+ return None+ try:+ with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:+ unzipped_size = sum(info.file_size for info in zf.infolist())+ except zipfile.BadZipFile:+ return None+ if unzipped_size > _UNZIPPED_LIMIT_BYTES:+ return error_response_json(+ "InvalidParameterValueException",+ f"Unzipped size must be smaller than {_UNZIPPED_LIMIT_BYTES} bytes",+ 400,+ )+ return None++def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:code_size = len(code_zip) if code_zip else 0code_sha = base64.b64encode(hashlib.sha256(code_zip).digest()).decode() if code_zip else ""@@ -804,6 +824,10 @@ def _create_function(data: dict):elif "S3Bucket" in code_data and "S3Key" in code_data:code_zip = _fetch_code_from_s3(code_data["S3Bucket"], code_data["S3Key"])+ err = _validate_unzipped_size(code_zip)+ if err is not None:+ return err+if image_uri:data.setdefault("PackageType", "Image")@@ -1163,6 +1187,9 @@ def _update_code(name: str, data: dict):f"Failed to fetch code from s3://{data['S3Bucket']}/{data['S3Key']}",400,)+ err = _validate_unzipped_size(code_zip)+ if err is not None:+ return errif code_zip:func["code_zip"] = code_zipfunc["config"]["CodeSize"] = len(code_zip)@@ -3348,6 +3375,10 @@ def _publish_layer_version(layer_name: str, data: dict):elif "S3Bucket" in content and "S3Key" in content:zip_data = _fetch_code_from_s3(content["S3Bucket"], content["S3Key"])+ err = _validate_unzipped_size(zip_data)+ if err is not None:+ return err+ver_config: dict = {"LayerArn": _layer_arn(layer_name),"LayerVersionArn": f"{_layer_arn(layer_name)}:{ver}",diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex c1b474f4..e0a9a587 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -151,7 +151,7 @@ except Exception:DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")-PERSIST = os.environ.get("S3_PERSIST", "0") == "1"+S3_PERSIST = os.environ.get("S3_PERSIST", "0") == "1"# Headers preserved from PUT requests and returned on GET/HEAD._PRESERVED_HEADERS = (@@ -197,7 +197,7 @@ def _get_object_data(bucket_name: str, key: str) -> bytes | None:obj = bucket["objects"].get(key)if obj is None:return None- return obj["body"]+ return _read_body(bucket_name, key, obj)def _ensure_bucket(name: str):@@ -620,7 +620,7 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):_bucket_object_lock[name] = {"enabled": True, "default_retention": None}_bucket_versioning[name] = "Enabled"- if PERSIST:+ if S3_PERSIST:os.makedirs(os.path.join(DATA_DIR, name), exist_ok=True)return 200, {"Location": f"/{name}"}, b""@@ -1636,7 +1636,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):return _error("BadRequest", "Object tags cannot be greater than 10", 400)_object_tags[(bucket_name, key)] = tags- if PERSIST:+ if S3_PERSIST:_persist_object(bucket_name, key, obj)_fire_s3_event_async(@@ -1657,7 +1657,7 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):"etag": obj["etag"],"size": obj["size"],"is_latest": True,- "data": obj.get("data", body if len(body) < 10_000_000 else None),+ "data": body,})# Mark all previous versions as not latestfor v in _object_versions[vkey][:-1]:@@ -1717,7 +1717,7 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict ="Last-Modified": v["last_modified"],"x-amz-version-id": v["version_id"],}- return 200, resp_headers, v.get("data", b"")+ return 200, resp_headers, v["data"]return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")if key not in bucket["objects"]:@@ -1732,6 +1732,7 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =resp_headers = _object_response_headers(obj, bucket_name, key)range_header = headers.get("range", "")+ body = _read_body(bucket_name, key, obj)if range_header:rng = _parse_range(range_header, obj["size"])if rng is None:@@ -1744,12 +1745,12 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =_xml_body(_range_error_xml(bucket_name, key)),)start, end = rng- slice_body = obj["body"][start : end + 1]+ slice_body = body[start : end + 1]resp_headers["Content-Length"] = str(len(slice_body))resp_headers["Content-Range"] = f"bytes {start}-{end}/{obj['size']}"return 206, resp_headers, slice_body- return 200, resp_headers, obj["body"]+ return 200, resp_headers, bodydef _range_error_xml(bucket_name: str, key: str) -> Element:@@ -1817,6 +1818,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None):_object_tags.pop((bucket_name, key), None)_object_retention.pop((bucket_name, key), None)_object_legal_hold.pop((bucket_name, key), None)+ _delete_persisted_object(bucket_name, key)if existed:_fire_s3_event_async(bucket_name, key, "s3:ObjectRemoved:Delete")@@ -1920,8 +1922,9 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):new_etag = src_obj["etag"]last_modified = now_iso()+ src_body = _read_body(src_bucket_name, src_key, src_obj)dest_obj = {- "body": src_obj["body"],+ "body": src_body,"content_type": content_type,"content_encoding": content_encoding,"etag": new_etag,@@ -1962,7 +1965,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):else:_object_legal_hold.pop((bucket_name, dest_key), None)- if PERSIST:+ if S3_PERSIST:_persist_object(bucket_name, dest_key, dest_obj)_fire_s3_event_async(@@ -1987,7 +1990,7 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):"etag": dest_obj["etag"],"size": dest_obj["size"],"is_latest": True,- "data": dest_obj.get("data", src_obj["body"] if src_obj["size"] < 10_000_000 else None),+ "data": src_body,})for v in _object_versions[vkey][:-1]:v["is_latest"] = False@@ -2801,7 +2804,7 @@ def _upload_part_copy(bucket_name: str, dest_key: str, query_params: dict, headereturn _error("NoSuchKey", "The specified key does not exist.", 404)src_obj = src_bucket["objects"][src_key]- src_body = src_obj["body"]+ src_body = _read_body(src_bucket_name, src_key, src_obj)# Handle x-amz-copy-source-rangecopy_range = headers.get("x-amz-copy-source-range", "")@@ -2903,7 +2906,7 @@ def _complete_multipart_upload(}bucket["objects"][key] = obj- if PERSIST:+ if S3_PERSIST:_persist_object(bucket_name, key, obj)del _multipart_uploads[upload_id]@@ -2930,7 +2933,7 @@ def _complete_multipart_upload("etag": obj["etag"],"size": obj["size"],"is_latest": True,- "data": obj.get("data", combined if len(combined) < 10_000_000 else None),+ "data": combined,})for v in _object_versions[vkey][:-1]:v["is_latest"] = False@@ -3099,17 +3102,52 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):# ----------------------------------------------------------------------------def _persist_object(bucket: str, key: str, obj):- try:+def _object_disk_path(bucket: str, key: str, account_id: str = None) -> str | None:+ """Resolve the on-disk path for an object and verify it lives under DATA_DIR.++ Returns None if the resolved path escapes DATA_DIR (e.g. key contains `..`+ or absolute path). Callers must treat None as "skip operation".+ """+ if account_id is None:account_id = get_account_id()- fpath = os.path.realpath(os.path.join(DATA_DIR, account_id, bucket, key))- if not fpath.startswith(os.path.realpath(DATA_DIR)):+ root = os.path.realpath(DATA_DIR)+ candidate = os.path.realpath(os.path.join(DATA_DIR, account_id, bucket, key))+ try:+ if os.path.commonpath([root, candidate]) != root:logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)+ return None+ except ValueError:+ # commonpath raises on mixed drives / unrelated paths — treat as escape.+ logger.warning("S3 persist: path traversal blocked for %s/%s", bucket, key)+ return None+ return candidate+++def _atomic_write(fpath: str, data: bytes, *, text: bool = False):+ """Write `data` to `fpath` atomically with mode 0o600."""+ tmp = fpath + ".tmp"+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ fd = os.open(tmp, flags, 0o600)+ try:+ with os.fdopen(fd, "w" if text else "wb") as f:+ f.write(data)+ except Exception:+ try:+ os.remove(tmp)+ except OSError:+ pass+ raise+ os.replace(tmp, fpath)+++def _persist_object(bucket: str, key: str, obj):+ try:+ fpath = _object_disk_path(bucket, key)+ if fpath is None:return- os.makedirs(os.path.dirname(fpath), exist_ok=True)+ os.makedirs(os.path.dirname(fpath), mode=0o700, exist_ok=True)data = obj["body"] if isinstance(obj, dict) else obj- with open(fpath, "wb") as f:- f.write(data)+ _atomic_write(fpath, data)if isinstance(obj, dict):meta = {"content_type": obj.get("content_type", "application/octet-stream"),@@ -3120,14 +3158,51 @@ def _persist_object(bucket: str, key: str, obj):"metadata": obj.get("metadata", {}),"preserved_headers": obj.get("preserved_headers", {}),}- with open(fpath + ".meta.json", "w") as mf:- json.dump(meta, mf)+ _atomic_write(fpath + ".meta.json", json.dumps(meta), text=True)+ # Drop body from in-memory record to save RAM+ if isinstance(obj, dict):+ obj["body"] = Noneexcept Exception as e:logger.warning("Failed to persist S3 object %s/%s: %s", bucket, key, e)+def _read_body(bucket_name: str, key: str, obj: dict) -> bytes:+ """Return object body — from memory if available, else from disk."""+ body = obj.get("body")+ if body is not None:+ return body+ if not S3_PERSIST:+ return b""+ try:+ fpath = _object_disk_path(bucket_name, key)+ if fpath is None:+ return b""+ with open(fpath, "rb") as f:+ return f.read()+ except Exception as e:+ logger.warning("Failed to read persisted S3 object %s/%s: %s", bucket_name, key, e)+ return b""+++def _delete_persisted_object(bucket_name: str, key: str):+ """Remove an object's data and metadata files from disk."""+ if not S3_PERSIST:+ return+ try:+ fpath = _object_disk_path(bucket_name, key)+ if fpath is None:+ return+ if os.path.exists(fpath):+ os.remove(fpath)+ meta_path = fpath + ".meta.json"+ if os.path.exists(meta_path):+ os.remove(meta_path)+ except Exception as e:+ logger.warning("Failed to delete persisted S3 object %s/%s: %s", bucket_name, key, e)++def _load_persisted_data():- if not PERSIST or not os.path.isdir(DATA_DIR):+ if not S3_PERSIST or not os.path.isdir(DATA_DIR):returntry:# Support both layouts:@@ -3180,8 +3255,6 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):abs_path = os.path.join(dirpath, fname)key = os.path.relpath(abs_path, bucket_path)meta_path = abs_path + ".meta.json"- with open(abs_path, "rb") as f:- data = f.read()meta = {}if os.path.exists(meta_path):try:@@ -3189,13 +3262,23 @@ def _load_persisted_bucket(account_id, bucket_name, bucket_path):meta = json.load(mf)except Exception:pass+ # Body stays on disk — only load metadata into memory.+ # Compute size/etag from meta sidecar; fall back to reading+ # the file only when the sidecar is missing or incomplete.+ size = meta.get("size")+ etag = meta.get("etag")+ if size is None or not etag:+ with open(abs_path, "rb") as f:+ data = f.read()+ size = len(data)+ etag = etag or f'"{md5_hash(data)}"'bucket["objects"][key] = {- "body": data,+ "body": None,"content_type": meta.get("content_type", "application/octet-stream"),"content_encoding": meta.get("content_encoding"),- "etag": meta.get("etag") or f'"{md5_hash(data)}"',+ "etag": etag,"last_modified": meta.get("last_modified") or now_iso(),- "size": len(data),+ "size": size,"metadata": meta.get("metadata", {}),"preserved_headers": meta.get("preserved_headers", {}),}