Skip to content

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

fix(s3): account-scope the on-disk bucket directory (#824) (#826)

Akhil Adiga7209b5470e20
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 21c1ecab..a5d4321d 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -30,6 +30,7 @@ import json
import logging
import os
import re
+import shutil
import threading
import time
from urllib.parse import parse_qs as _parse_qs
@@ -833,7 +834,10 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):
_bucket_versioning[name] = "Enabled"
if S3_PERSIST:
- os.makedirs(os.path.join(DATA_DIR, name), exist_ok=True)
+ # Account-scope the on-disk dir to match where objects are actually
+ # written (_object_disk_path / _persist_object). Omitting the account id
+ # here created a spurious empty folder at DATA_DIR/<bucket> (#824).
+ os.makedirs(os.path.join(DATA_DIR, get_account_id(), name), exist_ok=True)
logger.info("S3 bucket created: %s%s", name, f" (region={region})" if region else "")
return 200, {"Location": f"/{name}"}, b""
@@ -870,6 +874,8 @@ def _delete_bucket(name: str):
del _object_retention[k]
for k in [k for k in _object_legal_hold if k[0] == name]:
del _object_legal_hold[k]
+ if S3_PERSIST:
+ _delete_persisted_bucket(name)
return 204, {}, b""
@@ -3872,6 +3878,41 @@ def _delete_persisted_object(bucket_name: str, key: str):
logger.warning("Failed to delete persisted S3 object %s/%s: %s", bucket_name, key, e)
+def _delete_persisted_bucket(name: str):
+ """Remove a bucket's account-scoped on-disk directory when the bucket is deleted.
+
+ Mirrors the account scoping in _object_disk_path so we clean up exactly the
+ directory _create_bucket / _persist_object create. Without this the bucket
+ folder is orphaned on disk after DeleteBucket (#824).
+
+ Only the new account-scoped layout (DATA_DIR/<account>/<bucket>) is removed;
+ legacy unscoped data (DATA_DIR/<bucket>) from pre-account-scoping versions is
+ left in place — same as _delete_persisted_object, which only touches the
+ account-scoped path."""
+ if not S3_PERSIST or not name:
+ return
+ try:
+ account_id = get_account_id()
+ root = os.path.realpath(DATA_DIR)
+ account_root = os.path.realpath(os.path.join(DATA_DIR, account_id))
+ bucket_dir = os.path.realpath(os.path.join(DATA_DIR, account_id, name))
+ # Never remove DATA_DIR, the account directory itself, or anything that
+ # escapes DATA_DIR — only the one bucket's subtree. rmtree is destructive,
+ # so guard the primitive rather than relying solely on the validated caller.
+ if (
+ bucket_dir in (root, account_root)
+ or os.path.commonpath([root, bucket_dir]) != root
+ ):
+ logger.warning("S3 persist: refusing to delete bucket dir %s (outside its bucket scope)", name)
+ return
+ if os.path.isdir(bucket_dir):
+ # No ignore_errors: let a partial-failure OSError reach the except
+ # below so cleanup failures are logged instead of silently leaking.
+ shutil.rmtree(bucket_dir)
+ except (ValueError, OSError) as e:
+ logger.warning("Failed to delete persisted S3 bucket dir %s: %s", name, e)
+
+
def _load_persisted_data():
if not S3_PERSIST or not os.path.isdir(DATA_DIR):
return
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 28a0f05d..8ffab220 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -1987,6 +1987,80 @@ def test_s3_storage_class_persisted_to_disk(tmp_path, monkeypatch):
assert restored["storage_class"] == "GLACIER"
+def test_s3_create_bucket_persists_account_scoped(tmp_path, monkeypatch):
+ """CreateBucket persists under DATA_DIR/<account>/<bucket>, never DATA_DIR/<bucket> (#824)."""
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")
+ monkeypatch.setattr(respmod, "get_account_id", lambda: "000000000000")
+ try:
+ status, _, _ = s3mod._create_bucket("issue824-create", b"")
+ assert status == 200
+ # The on-disk dir is account-scoped...
+ assert os.path.isdir(os.path.join(str(tmp_path), "000000000000", "issue824-create"))
+ # ...and there is NO spurious folder at the data-dir root.
+ assert not os.path.exists(os.path.join(str(tmp_path), "issue824-create"))
+ finally:
+ s3mod._buckets._data.pop(("000000000000", "issue824-create"), None)
+
+
+def test_s3_put_object_no_spurious_root_folder(tmp_path, monkeypatch):
+ """PutBucket + PutObject must not leave an empty folder at the data-dir root (#824).
+
+ Mirrors the issue's repro: create 'my-bucket', put 'my-file', and assert the
+ data-dir root contains only the account dir (no DATA_DIR/my-bucket)."""
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")
+ monkeypatch.setattr(respmod, "get_account_id", lambda: "000000000000")
+ try:
+ s3mod._create_bucket("my-bucket", b"")
+ obj = {
+ "body": b"hello",
+ "content_type": "text/plain",
+ "content_encoding": None,
+ "etag": '"abc"',
+ "last_modified": s3mod.now_iso(),
+ "size": 5,
+ "metadata": {},
+ "preserved_headers": {},
+ "storage_class": "STANDARD",
+ }
+ s3mod._persist_object("my-bucket", "my-file", obj)
+ # Object data lands under the account-scoped path...
+ assert os.path.isfile(
+ os.path.join(str(tmp_path), "000000000000", "my-bucket", "my-file")
+ )
+ # ...and the only top-level entry is the account dir — no spurious 'my-bucket'.
+ assert sorted(os.listdir(str(tmp_path))) == ["000000000000"]
+ finally:
+ s3mod._buckets._data.pop(("000000000000", "my-bucket"), None)
+
+
+def test_s3_delete_bucket_removes_persisted_dir(tmp_path, monkeypatch):
+ """DeleteBucket removes the account-scoped on-disk directory (#824 cleanup gap)."""
+ from ministack.core import responses as respmod
+ from ministack.services import s3 as s3mod
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ monkeypatch.setattr(s3mod, "get_account_id", lambda: "000000000000")
+ monkeypatch.setattr(respmod, "get_account_id", lambda: "000000000000")
+ try:
+ s3mod._create_bucket("issue824-delete", b"")
+ bucket_dir = os.path.join(str(tmp_path), "000000000000", "issue824-delete")
+ assert os.path.isdir(bucket_dir)
+ status, _, _ = s3mod._delete_bucket("issue824-delete")
+ assert status == 204
+ # The on-disk directory is cleaned up, not orphaned.
+ assert not os.path.exists(bucket_dir)
+ finally:
+ s3mod._buckets._data.pop(("000000000000", "issue824-delete"), None)
+
+
def test_s3_copy_object_propagates_storage_class(s3):
"""CopyObject with explicit StorageClass overrides the source's class (#534)."""
s3.create_bucket(Bucket="qa-s3-sc-copy")