Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-3358 [FIX] List only S3 buckets the connector credentials can browse (#1925)

Kirtiman Mishra846fad543a06
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/minio/exceptions.py b/unstract/connectors/src/unstract/connectors/filesystems/minio/exceptions.py
index 05e7ed67d..2a4149eca 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/minio/exceptions.py
+++ b/unstract/connectors/src/unstract/connectors/filesystems/minio/exceptions.py
@@ -1,5 +1,51 @@
+from enum import Enum
+
+from botocore.exceptions import ClientError
+
from unstract.connectors.exceptions import ConnectorError
+
+class BucketProbeDisposition(Enum):
+ """Action for a `list_objects_v2` probe failure, per S3 error code."""
+
+ DROP = "drop" # Hide the bucket (no access, or bucket gone).
+ FAIL_OPEN = "fail_open" # Region mismatch — keep bucket visible.
+ RETRY_FAIL_OPEN = "retry_fail_open" # Throttled — retry once, then keep.
+
+
+# S3 `Error.Code` → probe disposition. Unlisted codes propagate.
+# `RequestTimeTooSkewed` is omitted deliberately: it's a system-wide clock
+# issue, not a bucket outcome — let it surface via `handle_s3fs_exception`.
+BUCKET_PROBE_DISPOSITION: dict[str, BucketProbeDisposition] = {
+ "AccessDenied": BucketProbeDisposition.DROP,
+ "AllAccessDisabled": BucketProbeDisposition.DROP,
+ "NoSuchBucket": BucketProbeDisposition.DROP,
+ "PermanentRedirect": BucketProbeDisposition.FAIL_OPEN,
+ "IllegalLocationConstraintException": BucketProbeDisposition.FAIL_OPEN,
+ "SlowDown": BucketProbeDisposition.RETRY_FAIL_OPEN,
+ "Throttling": BucketProbeDisposition.RETRY_FAIL_OPEN,
+ "ThrottlingException": BucketProbeDisposition.RETRY_FAIL_OPEN,
+}
+
+
+def s3_error_code(exc: BaseException) -> str:
+ """Return the S3 `Error.Code` from a `ClientError` or its s3fs-translated
+ wrapper (`PermissionError` / `FileNotFoundError` / `OSError`).
+
+ Walks `__cause__` first (explicit `raise X from original`), then falls
+ back to `__context__` (implicit chaining inside an `except` block). A
+ `seen` set guards against pathological cycles.
+ """
+ seen: set[int] = set()
+ target: BaseException | None = exc
+ while target is not None and id(target) not in seen:
+ seen.add(id(target))
+ if isinstance(target, ClientError):
+ return str(target.response.get("Error", {}).get("Code", "") or "")
+ target = target.__cause__ or target.__context__
+ return ""
+
+
S3FS_EXC_TO_UNSTRACT_EXC: dict[str, str] = {
# Auth errors
"The AWS Access Key Id you provided does not exist in our records": (
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
index d6253348a..04063e19f 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
+++ b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
@@ -1,19 +1,144 @@
+import asyncio
import logging
import os
+import random
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from typing import Any
+from botocore.exceptions import ClientError
from s3fs.core import S3FileSystem
from unstract.connectors.filesystems.unstract_file_system import UnstractFileSystem
-from .exceptions import handle_s3fs_exception
+from .exceptions import (
+ BUCKET_PROBE_DISPOSITION,
+ BucketProbeDisposition,
+ handle_s3fs_exception,
+ s3_error_code,
+)
logger = logging.getLogger(__name__)
+# Cap concurrent per-bucket probes to avoid S3 503 SlowDown on large accounts.
+_MAX_CONCURRENT_BUCKET_PROBES = 16
+_BUCKET_PROBE_RETRY_DELAY_SECONDS = 0.5
+
+
+class _AccessFilteredS3FileSystem(S3FileSystem): # type: ignore[misc]
+ """Lists only buckets the credentials can browse.
+
+ Probes each bucket and looks up the S3 `Error.Code` in
+ `BUCKET_PROBE_DISPOSITION`. Unlisted codes propagate.
+ """
+
+ async def _lsbuckets(self, refresh: bool = False) -> list[dict[str, Any]]:
+ buckets: list[dict[str, Any]] = await super()._lsbuckets(refresh=refresh)
+ if not buckets:
+ return buckets
+ return await self._filter_accessible_buckets(buckets)
+
+ async def _filter_accessible_buckets(
+ self, buckets: list[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
+ sem = asyncio.Semaphore(_MAX_CONCURRENT_BUCKET_PROBES)
+
+ async def _probe(name: str) -> bool:
+ async with sem:
+ return await self._is_bucket_accessible(name)
+
+ results = await asyncio.gather(*(_probe(b["name"]) for b in buckets))
+ accessible = [b for b, ok in zip(buckets, results, strict=True) if ok]
+ dropped = len(buckets) - len(accessible)
+ if dropped:
+ logger.info(
+ "[S3/MinIO] Bucket filter: kept %d of %d; "
+ "dropped %d on DROP dispositions.",
+ len(accessible),
+ len(buckets),
+ dropped,
+ )
+ return accessible
+
+ async def _is_bucket_accessible(self, name: str) -> bool:
+ try:
+ await self._call_s3("list_objects_v2", Bucket=name, MaxKeys=1)
+ return True
+ except (ClientError, OSError) as exc:
+ code = s3_error_code(exc)
+ disposition = BUCKET_PROBE_DISPOSITION.get(code)
+ if disposition is BucketProbeDisposition.DROP:
+ return False
+ if disposition is BucketProbeDisposition.FAIL_OPEN:
+ logger.warning(
+ "[S3/MinIO] Bucket %r probe returned %s; keeping in listing.",
+ name,
+ code,
+ )
+ return True
+ if disposition is BucketProbeDisposition.RETRY_FAIL_OPEN:
+ return await self._retry_probe_fail_open(name, code)
+ # Unclassified code: log which bucket before propagating so the
+ # gather-cancellation has a breadcrumb.
+ logger.exception(
+ "[S3/MinIO] Unclassified probe failure for bucket %r "
+ "(code=%r); propagating.",
+ name,
+ code,
+ )
+ raise
+
+ async def _retry_probe_fail_open(self, name: str, first_code: str) -> bool:
+ # Full jitter avoids correlated retries under SlowDown thundering herd.
+ await asyncio.sleep(
+ _BUCKET_PROBE_RETRY_DELAY_SECONDS
+ + random.uniform(0, _BUCKET_PROBE_RETRY_DELAY_SECONDS)
+ )
+ try:
+ await self._call_s3("list_objects_v2", Bucket=name, MaxKeys=1)
+ return True
+ except (ClientError, OSError) as retry_exc:
+ retry_code = s3_error_code(retry_exc)
+ disposition = BUCKET_PROBE_DISPOSITION.get(retry_code)
+ if disposition is BucketProbeDisposition.DROP:
+ return False
+ if disposition is BucketProbeDisposition.FAIL_OPEN:
+ logger.warning(
+ "[S3/MinIO] Bucket %r fail-open on retry "
+ "(first=%s, retry=%s); keeping in listing.",
+ name,
+ first_code,
+ retry_code,
+ )
+ return True
+ if disposition is BucketProbeDisposition.RETRY_FAIL_OPEN:
+ # Still transient after one retry — keep to avoid flapping.
+ logger.info(
+ "[S3/MinIO] Bucket %r still transient after retry "
+ "(first=%s, retry=%s); keeping in listing.",
+ name,
+ first_code,
+ retry_code,
+ )
+ return True
+ # Unclassified retry failure (e.g. credentials expired mid-probe):
+ # log the bucket, then re-raise so the real error surfaces.
+ logger.exception(
+ "[S3/MinIO] Unclassified retry probe failure for bucket %r "
+ "(first=%s, retry=%s); propagating.",
+ name,
+ first_code,
+ retry_code,
+ )
+ raise
+
class MinioFS(UnstractFileSystem):
+ # Override with plain S3FileSystem in a subclass when the credentials are
+ # known to have full access to every bucket they list, so the per-bucket
+ # access probe in _AccessFilteredS3FileSystem can be skipped.
+ _FS_CLASS: type[S3FileSystem] = _AccessFilteredS3FileSystem
+
def __init__(self, settings: dict[str, Any]):
super().__init__("MinioFS/S3")
key = (settings.get("key") or "").strip()
@@ -30,7 +155,7 @@ class MinioFS(UnstractFileSystem):
if endpoint_url:
creds["endpoint_url"] = endpoint_url
- self.s3 = S3FileSystem(
+ self.s3 = self._FS_CLASS(
anon=False,
use_listings_cache=False,
default_fill_cache=False,
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py b/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
index 9c8ab3f33..82521a12a 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
+++ b/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
@@ -1,5 +1,7 @@
import os
+from s3fs.core import S3FileSystem
+
from unstract.connectors.filesystems.minio.minio import MinioFS
@@ -9,6 +11,11 @@ class UnstractCloudStorage(MinioFS):
Implemented with Google Cloud Storage through Minio.
"""
+ # UCS credentials always have full access to UCS buckets, so skip the
+ # per-bucket access probe that MinioFS runs on its fsspec filesystem.
+ # The probe adds latency and could hide a bucket on a transient S3 error.
+ _FS_CLASS = S3FileSystem
+
@staticmethod
def get_id() -> str:
return "pcs|b8cd25cd-4452-4d54-bd5e-e7d71459b702"
diff --git a/unstract/connectors/tests/filesystems/test_miniofs.py b/unstract/connectors/tests/filesystems/test_miniofs.py
index 28dd00b13..3cf9ade1f 100644
--- a/unstract/connectors/tests/filesystems/test_miniofs.py
+++ b/unstract/connectors/tests/filesystems/test_miniofs.py
@@ -1,7 +1,18 @@
+import asyncio
import os
import unittest
+from unittest.mock import AsyncMock, patch
-from unstract.connectors.filesystems.minio.minio import MinioFS
+from botocore.exceptions import ClientError
+from s3fs.core import S3FileSystem
+from s3fs.errors import translate_boto_error
+
+from unstract.connectors.filesystems.minio.exceptions import s3_error_code
+from unstract.connectors.filesystems.minio.minio import (
+ MinioFS,
+ _AccessFilteredS3FileSystem,
+)
+from unstract.connectors.filesystems.ucs.ucs import UnstractCloudStorage
class TestMinoFS(unittest.TestCase):
@@ -36,7 +47,189 @@ class TestMinoFS(unittest.TestCase):
}
)
- print(s3.get_fsspec_fs().ls("/minio-test")) # type:ignore
+ print(s3.get_fsspec_fs().ls("/minio-test"))
+
+
+def _translated_error(code: str) -> BaseException:
+ """Mirror what s3fs `_call_s3` actually raises in production.
+
+ s3fs routes every raise through `translate_boto_error`, which converts
+ `ClientError` into `PermissionError` / `FileNotFoundError` / `OSError`
+ with the original `ClientError` preserved as `__cause__`. Tests must
+ raise the translated form or they won't exercise the real catch path.
+ """
+ ce = ClientError({"Error": {"Code": code, "Message": code}}, "ListObjectsV2")
+ translated: BaseException = translate_boto_error(ce)
+ return translated
+
+
+class TestAccessFilteredS3FileSystem(unittest.TestCase):
+ """Unit tests for the per-bucket access filter in _AccessFilteredS3FileSystem.
+
+ These tests don't need a live MinIO/S3. They bypass
+ `_AccessFilteredS3FileSystem.__init__` and monkey-patch `_call_s3` /
+ `S3FileSystem._lsbuckets` to exercise the override end-to-end. If s3fs
+ renames or re-signatures either internal, these tests fail loudly in
+ CI instead of silently reverting to the unfiltered parent behavior.
+ """
+
+ def _make_fs(self) -> _AccessFilteredS3FileSystem:
+ # Bypass __init__ to avoid touching the network / event loop.
+ return _AccessFilteredS3FileSystem.__new__(_AccessFilteredS3FileSystem)
+
+ def test_accessible_bucket_is_kept(self) -> None:
+ fs = self._make_fs()
+ with patch.object(fs, "_call_s3", new=AsyncMock(return_value={})):
+ self.assertTrue(asyncio.run(fs._is_bucket_accessible("allowed")))
+
+ def test_access_denied_bucket_is_dropped(self) -> None:
+ # s3fs translates `AccessDenied` → `PermissionError`; the filter
+ # must still drop the bucket by recovering the code from `__cause__`.
+ fs = self._make_fs()
+ with patch.object(
+ fs,
+ "_call_s3",
+ new=AsyncMock(side_effect=_translated_error("AccessDenied")),
+ ):
+ self.assertFalse(asyncio.run(fs._is_bucket_accessible("denied")))
+
+ def test_no_such_bucket_is_dropped(self) -> None:
+ # Race: bucket deleted between `list_buckets` and probe → `NoSuchBucket`
+ # (translated to `FileNotFoundError`). Drop it rather than surface.
+ fs = self._make_fs()
+ with patch.object(
+ fs,
+ "_call_s3",
+ new=AsyncMock(side_effect=_translated_error("NoSuchBucket")),
+ ):
+ self.assertFalse(asyncio.run(fs._is_bucket_accessible("deleted")))
+
+ def test_permanent_redirect_bucket_is_kept(self) -> None:
+ # Fail-open: region mismatch keeps the bucket listed.
+ fs = self._make_fs()
+ with patch.object(
+ fs,
+ "_call_s3",
+ new=AsyncMock(side_effect=_translated_error("PermanentRedirect")),
+ ):
+ self.assertTrue(asyncio.run(fs._is_bucket_accessible("other-region")))
+
+ def test_throttling_retries_then_fails_open(self) -> None:
+ fs = self._make_fs()
+
+ async def fake_call(_action: str, **_kwargs: object) -> dict[str, object]:
+ raise _translated_error("SlowDown")
+
+ call = AsyncMock(side_effect=fake_call)
+ with (
+ patch.object(fs, "_call_s3", new=call),
+ patch("asyncio.sleep", new=AsyncMock(return_value=None)),
+ ):
+ self.assertTrue(asyncio.run(fs._is_bucket_accessible("throttled")))
+ self.assertEqual(call.await_count, 2) # initial + one retry
+
+ def test_throttling_then_denied_on_retry_is_dropped(self) -> None:
+ fs = self._make_fs()
+ codes = ["SlowDown", "AccessDenied"]
+
+ async def fake_call(_action: str, **_kwargs: object) -> dict[str, object]:
+ raise _translated_error(codes.pop(0))
+
+ with (
+ patch.object(fs, "_call_s3", new=AsyncMock(side_effect=fake_call)),
+ patch("asyncio.sleep", new=AsyncMock(return_value=None)),
+ ):
+ self.assertFalse(asyncio.run(fs._is_bucket_accessible("slow-then-denied")))
+
+ def test_throttling_then_unknown_on_retry_propagates(self) -> None:
+ # Unknown error on retry (e.g. credentials expire mid-probe) must NOT
+ # be silently swallowed — it has to surface as a real failure.
+ fs = self._make_fs()
+ codes = ["SlowDown", "SomeWeirdUnknownCode"]
+
+ async def fake_call(_action: str, **_kwargs: object) -> dict[str, object]:
+ raise _translated_error(codes.pop(0))
+
+ with (
+ patch.object(fs, "_call_s3", new=AsyncMock(side_effect=fake_call)),
+ patch("asyncio.sleep", new=AsyncMock(return_value=None)),
+ ):
+ with self.assertRaises(OSError):
+ asyncio.run(fs._is_bucket_accessible("slow-then-mystery"))
+
+ def test_unknown_error_propagates(self) -> None:
+ # Unknown codes must NOT be silently hidden on first probe either.
+ fs = self._make_fs()
+ with patch.object(
+ fs,
+ "_call_s3",
+ new=AsyncMock(side_effect=_translated_error("SomeWeirdUnknownCode")),
+ ):
+ with self.assertRaises(OSError):
+ asyncio.run(fs._is_bucket_accessible("mystery"))
+
+ def test_request_time_too_skewed_propagates(self) -> None:
+ # Clock skew is system-wide, not bucket-level; it must surface so
+ # `handle_s3fs_exception` can show the clock-skew message.
+ fs = self._make_fs()
+ with patch.object(
+ fs,
+ "_call_s3",
+ new=AsyncMock(side_effect=_translated_error("RequestTimeTooSkewed")),
+ ):
+ with self.assertRaises(PermissionError):
+ asyncio.run(fs._is_bucket_accessible("any-bucket"))
+
+ def test_lsbuckets_override_wires_to_filter(self) -> None:
+ # Regression guard for s3fs signature drift on `_lsbuckets`/`_call_s3`.
+ fs = self._make_fs()
+ parent_buckets = [{"name": "allowed"}, {"name": "denied"}]
+
+ async def fake_call(_action: str, **kwargs: object) -> dict[str, object]:
+ if kwargs.get("Bucket") == "denied":
+ raise _translated_error("AccessDenied")
+ return {}
+
+ with (
+ patch(
+ "unstract.connectors.filesystems.minio.minio."
+ "S3FileSystem._lsbuckets",
+ new=AsyncMock(return_value=parent_buckets),
+ ),
+ patch.object(fs, "_call_s3", new=AsyncMock(side_effect=fake_call)),
+ ):
+ result = asyncio.run(fs._lsbuckets(refresh=True))
+ self.assertEqual([b["name"] for b in result], ["allowed"])
+
+ def test_default_fs_class_is_filtered(self) -> None:
+ # MinioFS defaults to the access-filtered filesystem; subclasses can opt out.
+ self.assertIs(MinioFS._FS_CLASS, _AccessFilteredS3FileSystem)
+
+ def test_ucs_opts_out_of_access_filter(self) -> None:
+ # UCS credentials are expected to have full access, so the per-bucket
+ # probe must be skipped. Guards against a future refactor dropping
+ # the `_FS_CLASS = S3FileSystem` override in ucs.py.
+ self.assertIs(UnstractCloudStorage._FS_CLASS, S3FileSystem)
+ self.assertIsNot(UnstractCloudStorage._FS_CLASS, _AccessFilteredS3FileSystem)
+
+ def test_error_code_walks_context_when_cause_absent(self) -> None:
+ # Guards against future wrapper layers that use implicit exception
+ # chaining (`raise X` inside an `except`). The original `ClientError`
+ # lands on `__context__`, not `__cause__` — the helper must still
+ # recover the disposition code or we silently propagate AccessDenied.
+ client_exc = ClientError(
+ {"Error": {"Code": "AccessDenied", "Message": "AccessDenied"}},
+ "ListObjectsV2",
+ )
+ try:
+ try:
+ raise client_exc
+ except ClientError:
+ # Implicit chaining: no `from` clause, so ClientError lands
+ # on __context__ of the OSError below.
+ raise OSError("translated") # noqa: B904
+ except OSError as outer:
+ self.assertEqual(s3_error_code(outer), "AccessDenied")
if __name__ == "__main__":