Skip to content

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

UN-3487 [FIX] Restrict the S3/MinIO connector to one bucket (#2295)

Kirtiman Mishra89a4434434ba
diff --git a/backend/connector_v2/tests/test_connector_register.py b/backend/connector_v2/tests/test_connector_register.py
index 889a961ec..b1f6e7e7b 100644
--- a/backend/connector_v2/tests/test_connector_register.py
+++ b/backend/connector_v2/tests/test_connector_register.py
@@ -24,6 +24,7 @@ from utils.user_context import UserContext
from connector_v2.models import ConnectorInstance
MINIO_CONNECTOR_ID = "minio|c799f6e3-2b57-434e-aaac-b5daa415da19"
+_BUCKET = "connector-register-test"
pytestmark = pytest.mark.skipif(
not all(
@@ -45,12 +46,28 @@ def _credentials(secret: str | None = None) -> dict:
"secret": secret or os.environ["MINIO_SECRET_ACCESS_KEY"],
"endpoint_url": os.environ["MINIO_ENDPOINT_URL"],
"region_name": "",
+ "bucket": _BUCKET,
"path": "/",
}
+def _ensure_bucket_exists() -> None:
+ # UN-3487: MinioFS now requires a bucket, and `test_credentials` probes
+ # it directly — it must actually exist in the rig's MinIO.
+ from s3fs.core import S3FileSystem
+
+ fs = S3FileSystem(
+ key=os.environ["MINIO_ACCESS_KEY_ID"],
+ secret=os.environ["MINIO_SECRET_ACCESS_KEY"],
+ client_kwargs={"endpoint_url": os.environ["MINIO_ENDPOINT_URL"]},
+ )
+ if not fs.exists(_BUCKET):
+ fs.mkdir(_BUCKET)
+
+
class ConnectorRegisterTest(TestCase):
def setUp(self) -> None:
+ _ensure_bucket_exists()
self.org = Organization.objects.create(
name="org-conn", display_name="Org Conn", organization_id="org-conn"
)
diff --git a/backend/file_management/file_management_helper.py b/backend/file_management/file_management_helper.py
index 51cc14180..9ec3b587a 100644
--- a/backend/file_management/file_management_helper.py
+++ b/backend/file_management/file_management_helper.py
@@ -11,6 +11,7 @@ from deprecated import deprecated
from django.conf import settings
from django.http import StreamingHttpResponse
from fsspec import AbstractFileSystem
+from fsspec.implementations.dirfs import DirFileSystem
from pydrive2.files import ApiRequestError
from file_management.exceptions import (
@@ -31,6 +32,27 @@ from unstract.connectors.filesystems.unstract_file_system import UnstractFileSys
logger = logging.getLogger(__name__)
+def _default_root_path(
+ file_system: UnstractFileSystem, fs: AbstractFileSystem, path: str
+) -> str | None:
+ """Some connectors restrict browsing to their own default root (e.g. a
+ configured `path`) when the caller didn't ask for a specific one.
+
+ `DirFileSystem.path` (used by a bucket-scoped MinioFS) is excluded: it's
+ the wrapped bucket prefix, not a default root, and every operation
+ already resolves relative to it — applying it again here would
+ double-prefix the path (UN-3487).
+ """
+ if not path or path == "/":
+ try:
+ if file_system.path:
+ return file_system.path
+ except AttributeError:
+ if hasattr(fs, "path") and fs.path and not isinstance(fs, DirFileSystem):
+ return fs.path
+ return None
+
+
class FileManagerHelper:
@staticmethod
def get_file_system(connector: ConnectorInstance) -> UnstractFileSystem:
@@ -47,14 +69,8 @@ class FileManagerHelper:
@staticmethod
def list_files(file_system: UnstractFileSystem, path: str) -> list[FileInformation]:
fs = file_system.get_fsspec_fs()
- file_path = f"{path}"
- # TODO: Add below logic by checking each connector?
try:
- if file_system.path and (not path or path == "/"):
- file_path = file_system.path
- except AttributeError:
- if hasattr(fs, "path") and fs.path and (not path or path == "/"):
- file_path = fs.path
+ file_path = _default_root_path(file_system, fs, path) or path
except Exception:
logger.error(f"Missing path Atribute in {fs}")
raise MissingConnectorParams()
@@ -135,13 +151,8 @@ class FileManagerHelper:
) -> None:
fs = file_system.get_fsspec_fs()
- file_path = f"{path}"
- try:
- if file_system.path and (not path or path == "/"):
- file_path = f"{file_system.path}/"
- except AttributeError:
- if fs.path and (not path or path == "/"):
- file_path = f"{fs.path}/"
+ root = _default_root_path(file_system, fs, path)
+ file_path = f"{root}/" if root else path
file_path = file_path + "/" if not file_path.endswith("/") else file_path
diff --git a/backend/file_management/tests.py b/backend/file_management/tests.py
index a39b155ac..bc2c1d1cd 100644
--- a/backend/file_management/tests.py
+++ b/backend/file_management/tests.py
@@ -1 +1,101 @@
-# Create your tests here.
+"""UN-3487: `file/`, `file/download` and `file/upload` are scoped to the
+caller, not just the org.
+
+Before this fix, `FileManagementViewSet` resolved a connector by a raw
+`ConnectorInstance.objects.get(pk=id)` — any authenticated org member who
+knew (or guessed) another user's connector id could browse, download from,
+or upload to it, sharing settings aside. These drive the real views through
+DRF's request factory, so a gate that exists only in the queryset — and
+never reaches the route — is still caught.
+"""
+
+import unittest
+from unittest.mock import mock_open, patch
+
+from connector_v2.models import ConnectorInstance
+from django.test import TestCase
+from permissions.roles import ResourceRole
+from permissions.tests.base import CoOwnerOrgTestMixin
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.test import APIRequestFactory, force_authenticate
+
+from file_management.file_management_helper import FileManagerHelper
+from file_management.views import FileManagementViewSet
+from unstract.connectors.filesystems.minio.minio import MinioFS
+
+
+class FileManagementAccessScopeTest(CoOwnerOrgTestMixin, TestCase):
+ def setUp(self) -> None:
+ self._seed_org()
+ self.connector = ConnectorInstance.objects.create(
+ connector_name="team-a-s3",
+ connector_id="minio|c799f6e3-2b57-434e-aaac-b5daa415da19",
+ connector_metadata={"bucket": "team-a-data"},
+ organization=self.org,
+ created_by=self.owner,
+ )
+ # `created_by` is audit-only — access runs through the membership
+ # table, same as every other shareable resource in this codebase.
+ self.connector.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.connector.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _list(self, actor) -> Response:
+ view = FileManagementViewSet.as_view({"get": "list"})
+ request = self.factory.get(
+ "/file", {"connector_id": str(self.connector.pk), "path": "/"}
+ )
+ force_authenticate(request, user=actor)
+ with (
+ patch(
+ "file_management.views.FileManagerHelper.get_file_system",
+ return_value=None,
+ ),
+ patch("file_management.views.FileManagerHelper.list_files", return_value=[]),
+ ):
+ return view(request)
+
+ def test_owner_can_list_their_own_connector(self) -> None:
+ self.assertEqual(self._list(self.owner).status_code, status.HTTP_200_OK)
+
+ def test_org_admin_can_list_any_connector(self) -> None:
+ self.assertEqual(self._list(self.admin).status_code, status.HTTP_200_OK)
+
+ def test_shared_viewer_can_list_the_connector(self) -> None:
+ self.assertEqual(self._list(self.viewer).status_code, status.HTTP_200_OK)
+
+ def test_outsider_org_member_cannot_list_an_unshared_connector(self) -> None:
+ # In scope (org member), but the connector was never shared with them.
+ self.assertEqual(self._list(self.outsider).status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_non_org_member_cannot_list_the_connector(self) -> None:
+ self.assertEqual(self._list(self.stranger).status_code, status.HTTP_404_NOT_FOUND)
+
+
+class BucketScopedRootPathTest(unittest.TestCase):
+ """Regression for a Greptile finding on this PR: a bucket-scoped
+ connector's own `DirFileSystem.path` is its wrapped bucket prefix, not a
+ connector-level default root. Treating it as one double-prefixes every
+ root-level operation (`<bucket>/<bucket>/...`) instead of resolving
+ within the bucket.
+ """
+
+ def _minio_fs(self) -> MinioFS:
+ return MinioFS({"bucket": "team-a-data", "key": "k", "secret": "s"})
+
+ def test_list_files_at_root_is_not_double_prefixed(self) -> None:
+ minio_fs = self._minio_fs()
+ with patch.object(minio_fs.s3, "ls", return_value=[]) as mock_ls:
+ FileManagerHelper.list_files(minio_fs, "/")
+ mock_ls.assert_called_once_with("team-a-data/", detail=True)
+
+ def test_upload_file_at_root_is_not_double_prefixed(self) -> None:
+ minio_fs = self._minio_fs()
+ with patch.object(minio_fs.s3, "open", mock_open()) as mock_open_call:
+ FileManagerHelper.upload_file(minio_fs, "/", b"data", "report.pdf")
+ (called_path,), kwargs = mock_open_call.call_args
+ self.assertEqual(kwargs, {"mode": "wb"})
+ self.assertNotIn("team-a-data/team-a-data", called_path)
+ self.assertTrue(called_path.startswith("team-a-data/"))
+ self.assertTrue(called_path.endswith("report.pdf"))
diff --git a/backend/file_management/views.py b/backend/file_management/views.py
index ea39cb1d2..6ed28d7d2 100644
--- a/backend/file_management/views.py
+++ b/backend/file_management/views.py
@@ -2,6 +2,7 @@ import logging
from typing import Any
from connector_v2.models import ConnectorInstance
+from django.db.models import QuerySet
from django.http import HttpRequest
from oauth2client.client import HttpAccessTokenRefreshError
from rest_framework import serializers, viewsets
@@ -30,8 +31,22 @@ class FileManagementViewSet(viewsets.ModelViewSet):
versioning_class = URLPathVersioning
- def get_queryset(self):
- return ConnectorInstance.objects.all()
+ def get_queryset(self) -> QuerySet[ConnectorInstance]:
+ # Org-scoped alone isn't enough: this must also respect ownership /
+ # sharing, or any org member could browse another user's connector
+ # by guessing its id.
+ return ConnectorInstance.objects.for_user(self.request.user)
+
+ def _get_connector_or_404(self, id: str) -> ConnectorInstance:
+ """Resolve a connector within the caller's own access scope.
+
+ Raises the same not-found error whether the id is unknown or simply
+ outside `get_queryset()` — the caller can't tell those apart.
+ """
+ try:
+ return self.get_queryset().get(pk=id)
+ except ConnectorInstance.DoesNotExist:
+ raise ConnectorInstanceNotFound()
def get_serializer_class(self) -> serializers.Serializer:
if self.action == "upload":
@@ -50,13 +65,11 @@ class FileManagementViewSet(viewsets.ModelViewSet):
id: str = serializer.validated_data.get("connector_id")
path: str = serializer.validated_data.get("path")
try:
- connector_instance: ConnectorInstance = ConnectorInstance.objects.get(pk=id)
+ connector_instance = self._get_connector_or_404(id)
file_system = FileManagerHelper.get_file_system(connector_instance)
files = FileManagerHelper.list_files(file_system, path)
serializer = FileInfoSerializer(files, many=True)
return Response(serializer.data)
- except ConnectorInstance.DoesNotExist:
- raise ConnectorInstanceNotFound()
except HttpAccessTokenRefreshError as error:
logger.error(
f"HttpAccessTokenRefreshError thrown from file list, error {error}"
@@ -72,7 +85,7 @@ class FileManagementViewSet(viewsets.ModelViewSet):
serializer.is_valid(raise_exception=True)
id: str = serializer.validated_data.get("connector_id")
path: str = serializer.validated_data.get("path")
- connector_instance: ConnectorInstance = ConnectorInstance.objects.get(pk=id)
+ connector_instance = self._get_connector_or_404(id)
file_system = FileManagerHelper.get_file_system(connector_instance)
return FileManagerHelper.download_file(file_system, path)
@@ -84,7 +97,7 @@ class FileManagementViewSet(viewsets.ModelViewSet):
path: str = serializer.validated_data.get("path")
uploaded_files: Any = serializer.validated_data.get("file")
- connector_instance: ConnectorInstance = ConnectorInstance.objects.get(pk=id)
+ connector_instance = self._get_connector_or_404(id)
file_system = FileManagerHelper.get_file_system(connector_instance)
for uploaded_file in uploaded_files:
diff --git a/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx b/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx
index b9a639adc..f02f69ef3 100644
--- a/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx
+++ b/frontend/src/components/helpers/custom-markdown/CustomMarkdown.jsx
@@ -37,7 +37,15 @@ const CustomMarkdown = ({
case "tripleCode":
return (
<Paragraph style={{ margin: 0 }}>
- <pre style={{ margin: 0 }}>{content}</pre>
+ <pre
+ style={{
+ margin: 0,
+ whiteSpace: "pre-wrap",
+ overflowWrap: "anywhere",
+ }}
+ >
+ {content}
+ </pre>
</Paragraph>
);
case "inlineCode":
diff --git a/tests/e2e/etl/conftest.py b/tests/e2e/etl/conftest.py
index 7cff0c692..2a07245a1 100644
--- a/tests/e2e/etl/conftest.py
+++ b/tests/e2e/etl/conftest.py
@@ -133,6 +133,7 @@ def etl_workflow(
"secret": minio_store.secret_key,
"endpoint_url": minio_store.internal_url,
"region_name": "us-east-1",
+ "bucket": minio_store.bucket,
},
},
)
@@ -164,7 +165,9 @@ def etl_workflow(
"connection_type": "FILESYSTEM",
"connector_instance_id": source_id,
"configuration": {
- "folders": [f"/{minio_store.bucket}/{input_prefix}"],
+ # UN-3487: the connector is now scoped to its own bucket, so
+ # paths resolve relative to it — no bucket prefix here.
+ "folders": [f"/{input_prefix}"],
"processSubDirectories": False,
"maxFiles": 1,
"fileProcessingOrder": "unordered",
@@ -179,7 +182,8 @@ def etl_workflow(
json={
"connection_type": "FILESYSTEM",
"connector_instance_id": destination_id,
- "configuration": {"outputFolder": f"{minio_store.bucket}/{output_prefix}"},
+ # UN-3487: same as the source — no bucket prefix, it's implicit.
+ "configuration": {"outputFolder": output_prefix},
},
)
assert resp.status_code == 200, f"destination endpoint: {resp.text}"
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
index 04063e19f..bba3e7d18 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
+++ b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py
@@ -7,8 +7,11 @@ from email.utils import parsedate_to_datetime
from typing import Any
from botocore.exceptions import ClientError
+from fsspec import AbstractFileSystem
+from fsspec.implementations.dirfs import DirFileSystem
from s3fs.core import S3FileSystem
+from unstract.connectors.exceptions import ConnectorError
from unstract.connectors.filesystems.unstract_file_system import UnstractFileSystem
from .exceptions import (
@@ -20,6 +23,37 @@ from .exceptions import (
logger = logging.getLogger(__name__)
+
+class _BucketScopedFileSystem(DirFileSystem):
+ """`DirFileSystem.walk()` relpaths the directory string it yields, but
+ not the `name` field inside each file/dir entry's own metadata dict —
+ those still carry the wrapped fs's raw, bucket-prefixed key. `ls()`
+ already fixes every entry; `walk()` doesn't. Fix it here so discovery
+ (which walks) and browsing (which lists) agree (UN-3487).
+ """
+
+ def _relpath_entries(
+ self, entries: dict[str, Any] | list[str]
+ ) -> dict[str, Any] | list[str]:
+ # detail=False (fsspec's own default) yields bare basenames with
+ # nothing to fix. detail=True yields a dict already keyed by bare
+ # basename — only each entry's own `name` field is bucket-qualified.
+ if not isinstance(entries, dict):
+ return entries
+ return {
+ name: {**info, "name": self._relpath(info["name"])}
+ for name, info in entries.items()
+ }
+
+ def walk(self, path: str, *args: Any, **kwargs: Any) -> Any:
+ for root, dirs, files in super().walk(path, *args, **kwargs):
+ yield root, self._relpath_entries(dirs), self._relpath_entries(files)
+
+ async def _walk(self, path: str, *args: Any, **kwargs: Any) -> Any:
+ async for root, dirs, files in super()._walk(path, *args, **kwargs):
+ yield root, self._relpath_entries(dirs), self._relpath_entries(files)
+
+
# 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
@@ -138,12 +172,21 @@ class MinioFS(UnstractFileSystem):
# 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
+ # Override to False in a subclass whose settings restrict access some
+ # other way (e.g. UCS, which uses its own `path` setting instead).
+ _REQUIRES_BUCKET: bool = True
def __init__(self, settings: dict[str, Any]):
super().__init__("MinioFS/S3")
key = (settings.get("key") or "").strip()
secret = (settings.get("secret") or "").strip()
endpoint_url = (settings.get("endpoint_url") or "").strip()
+ self.bucket = (settings.get("bucket") or "").strip()
+ if self._REQUIRES_BUCKET and not self.bucket:
+ raise ConnectorError(
+ "A bucket must be configured for this connector.",
+ treat_as_user_message=True,
+ )
client_kwargs = {}
if "region_name" in settings and settings["region_name"] != "":
client_kwargs = {"region_name": settings["region_name"]}
@@ -324,7 +367,16 @@ class MinioFS(UnstractFileSystem):
)
return None
- def get_fsspec_fs(self) -> S3FileSystem:
+ def get_fsspec_fs(self) -> AbstractFileSystem:
+ """Return the filesystem scoped to this connector's bucket.
+
+ When a bucket is configured, every operation (list, read, write,
+ `test_credentials`) is confined to it via `_BucketScopedFileSystem` —
+ the underlying credentials may see more, but this connector never
+ will.
+ """
+ if self.bucket:
+ return _BucketScopedFileSystem(path=self.bucket, fs=self.s3)
return self.s3
def test_credentials(self) -> bool:
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/minio/static/json_schema.json b/unstract/connectors/src/unstract/connectors/filesystems/minio/static/json_schema.json
index d0ba5ed91..d99c6d232 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/minio/static/json_schema.json
+++ b/unstract/connectors/src/unstract/connectors/filesystems/minio/static/json_schema.json
@@ -5,7 +5,8 @@
"required": [
"connectorName",
"endpoint_url",
- "region_name"
+ "region_name",
+ "bucket"
],
"properties": {
"connectorName": {
@@ -36,6 +37,11 @@
"title": "Region Name",
"default": "ap-south",
"description": "Region of the AWS S3 account (leave blank for Minio)"
+ },
+ "bucket": {
+ "type": "string",
+ "title": "Bucket Name",
+ "description": "Name of the bucket to be restricted to."
}
}
}
diff --git a/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py b/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
index 82521a12a..927b2b1ed 100644
--- a/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
+++ b/unstract/connectors/src/unstract/connectors/filesystems/ucs/ucs.py
@@ -15,6 +15,10 @@ class UnstractCloudStorage(MinioFS):
# 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
+ # UCS restricts access via its own `path` setting, not `bucket` — its
+ # schema never carries `bucket`, so MinioFS's required-bucket check
+ # doesn't apply here.
+ _REQUIRES_BUCKET = False
@staticmethod
def get_id() -> str:
diff --git a/unstract/connectors/tests/filesystems/test_miniofs.py b/unstract/connectors/tests/filesystems/test_miniofs.py
index 9c8c4b6e2..104669b26 100644
--- a/unstract/connectors/tests/filesystems/test_miniofs.py
+++ b/unstract/connectors/tests/filesystems/test_miniofs.py
@@ -5,8 +5,10 @@ from unittest.mock import AsyncMock, patch
import pytest
from botocore.exceptions import ClientError
+from fsspec.implementations.dirfs import DirFileSystem
from s3fs.core import S3FileSystem
from s3fs.errors import translate_boto_error
+from unstract.connectors.exceptions import ConnectorError
from unstract.connectors.filesystems.minio.exceptions import s3_error_code
from unstract.connectors.filesystems.minio.minio import (
MinioFS,
@@ -26,21 +28,30 @@ class TestMinoFS(unittest.TestCase):
# Endpoint from the rig's testcontainers MinIO via MINIO_ENDPOINT_URL;
# falls back to the local platform MinIO for manual runs.
self.assertEqual(MinioFS.requires_oauth(), False)
+ endpoint_url = os.environ.get("MINIO_ENDPOINT_URL", "http://localhost:9000")
+ bucket = "rig-minio-test"
+
+ # UN-3487: bucket is now required, so the connector can no longer
+ # discover it via a root bucket listing — bootstrap it directly.
+ bootstrap_fs = S3FileSystem(
+ key=os.environ["MINIO_ACCESS_KEY_ID"],
+ secret=os.environ["MINIO_SECRET_ACCESS_KEY"],
+ client_kwargs={"endpoint_url": endpoint_url},
+ )
+ if not bootstrap_fs.exists(bucket):
+ bootstrap_fs.mkdir(bucket)
+
fs = MinioFS(
{
"key": os.environ["MINIO_ACCESS_KEY_ID"],
"secret": os.environ["MINIO_SECRET_ACCESS_KEY"],
- "endpoint_url": os.environ.get(
- "MINIO_ENDPOINT_URL", "http://localhost:9000"
- ),
- "path": "/",
+ "endpoint_url": endpoint_url,
+ "bucket": bucket,
}
).get_fsspec_fs()
- bucket = "rig-minio-test"
- if not fs.exists(bucket):
- fs.mkdir(bucket)
- listed = [b.rstrip("/").split("/")[-1] for b in fs.ls("")]
- self.assertIn(bucket, listed)
+ # A live connection to the bucket-scoped root must succeed, without
+ # needing (or being able) to see any other bucket.
+ fs.ls("")
def _translated_error(code: str) -> BaseException:
@@ -201,8 +212,7 @@ class TestAccessFilteredS3FileSystem(unittest.TestCase):
with (
patch(
- "unstract.connectors.filesystems.minio.minio."
- "S3FileSystem._lsbuckets",
+ "unstract.connectors.filesystems.minio.minio.S3FileSystem._lsbuckets",
new=AsyncMock(return_value=parent_buckets),
),
patch.object(fs, "_call_s3", new=AsyncMock(side_effect=fake_call)),
@@ -241,5 +251,90 @@ class TestAccessFilteredS3FileSystem(unittest.TestCase):
self.assertEqual(s3_error_code(outer), "AccessDenied")
+class TestMinioFSBucketRestriction(unittest.TestCase):
+ """Unit tests for UN-3487: `bucket` is required and enforced on MinioFS.
+
+ All tests construct `MinioFS`/`UnstractCloudStorage` directly — no
+ network calls happen until an actual fsspec method is invoked.
+ """
+
+ def test_missing_bucket_raises(self) -> None:
+ with self.assertRaises(ConnectorError):
+ MinioFS({"key": "k", "secret": "s", "endpoint_url": "http://x"})
+
+ def test_blank_bucket_raises(self) -> None:
+ with self.assertRaises(ConnectorError):
+ MinioFS({"bucket": " ", "key": "k", "secret": "s"})
+
+ def test_bucket_is_stored(self) -> None:
+ fs = MinioFS({"bucket": "team-a-data", "key": "k", "secret": "s"})
+ self.assertEqual(fs.bucket, "team-a-data")
+
+ def test_get_fsspec_fs_scopes_to_bucket(self) -> None:
+ fs = MinioFS({"bucket": "team-a-data", "key": "k", "secret": "s"})
+ scoped = fs.get_fsspec_fs()
+ self.assertIsInstance(scoped, DirFileSystem)
+ self.assertEqual(scoped.path, "team-a-data")
+ self.assertIs(scoped.fs, fs.s3)
+
+ def test_walk_results_are_relative_to_the_bucket(self) -> None:
+ # `DirFileSystem.walk()` relpaths the directory string it yields,
+ # but not the `name` field inside each entry's own metadata dict —
+ # those still carry the wrapped fs's raw, bucket-prefixed key. This
+ # is what workflow-execution file discovery reads (it walks, the
+ # UI browser lists) — a name still carrying the bucket here is what
+ # doubles the prefix at the point a discovered file gets opened.
+ #
+ # Matches fsspec's real shape (verified against AbstractFileSystem.
+ # walk): the dict is keyed by bare basename already; only each
+ # entry's own `name` field carries the full, bucket-qualified path.
+ fs = MinioFS({"bucket": "unstract", "key": "k", "secret": "s"})
+
+ def fake_walk(path: str, detail: bool = True, **kwargs: object):
+ yield (
+ "unstract/e2e-in",
+ {},
+ {"probe.txt": {"name": "unstract/e2e-in/probe.txt", "type": "file"}},
+ )
+
+ with patch.object(fs.s3, "walk", side_effect=fake_walk):
+ root, dirs, files = next(fs.get_fsspec_fs().walk("e2e-in", detail=True))
+ self.assertEqual(root, "e2e-in")
+ self.assertEqual(list(files.keys()), ["probe.txt"])
+ self.assertEqual(files["probe.txt"]["name"], "e2e-in/probe.txt")
+
+ def test_walk_default_detail_false_is_untouched(self) -> None:
+ # fsspec's own default is detail=False, which yields bare basename
+ # lists, not dicts. The relpath fix must not assume dict shape, or
+ # any caller using the plain walk() contract gets an AttributeError.
+ fs = MinioFS({"bucket": "unstract", "key": "k", "secret": "s"})
+
+ def fake_walk(path: str, **kwargs: object):
+ yield ("unstract/e2e-in", [], ["probe.txt"])
+
+ with patch.object(fs.s3, "walk", side_effect=fake_walk):
+ root, dirs, files = next(fs.get_fsspec_fs().walk("e2e-in"))
+ self.assertEqual(root, "e2e-in")
+ self.assertEqual(files, ["probe.txt"])
+
+ def test_scoped_root_listing_never_reaches_lsbuckets(self) -> None:
+ # The security-relevant assertion: ls("") on a bucket-scoped
+ # connector must resolve to listing that one bucket's contents,
+ # never the account-wide bucket enumeration `_lsbuckets` performs.
+ fs = MinioFS({"bucket": "team-a-data", "key": "k", "secret": "s"})
+ with patch.object(fs.s3, "ls", return_value=[]) as mock_ls:
+ fs.get_fsspec_fs().ls("")
+ mock_ls.assert_called_once_with("team-a-data", detail=True)
+
+ def test_ucs_does_not_require_bucket(self) -> None:
+ # UCS restricts access via its own `path` setting instead.
+ ucs = UnstractCloudStorage({"key": "k", "secret": "s", "path": "some/path"})
+ self.assertEqual(ucs.bucket, "")
+
+ def test_ucs_get_fsspec_fs_is_unscoped(self) -> None:
+ ucs = UnstractCloudStorage({"key": "k", "secret": "s", "path": "some/path"})
+ self.assertIs(ucs.get_fsspec_fs(), ucs.s3)
+
+
if __name__ == "__main__":
unittest.main()