Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

refactor: Move cos (#1654)

Mike Fortmanad2fe5f12995
diff --git a/Dockerfile.backend b/Dockerfile.backend
index 513f6c37b..aa9ddebc1 100644
--- a/Dockerfile.backend
+++ b/Dockerfile.backend
@@ -38,6 +38,7 @@ RUN --mount=type=cache,target=/root/.cache/uv,uid=0,gid=0 \
# Application (invalidates after deps only when src/flows change)
COPY src/ ./src/
+COPY enhancements/ ./enhancements/
COPY flows/ ./flows/
COPY securityconfig/ ./securityconfig/
COPY cloud_securityconfig/ ./cloud_securityconfig/
diff --git a/enhancements/__init__.py b/enhancements/__init__.py
new file mode 100644
index 000000000..b590503c4
--- /dev/null
+++ b/enhancements/__init__.py
@@ -0,0 +1,13 @@
+"""OpenRAG enhancements package.
+
+This directory is populated by enterprise / SaaS overlays via the
+`git checkout --ours enhancements/ frontend/enhancements/` merge strategy.
+In OSS it ships with a minimal set of additional connectors (IBM COS).
+Strip the imports below to ship a bare OSS build.
+"""
+
+from connectors.base import BaseConnector
+
+from .connectors.ibm_cos import IBMCOSConnector
+
+ADDITIONAL_CONNECTORS: list[type[BaseConnector]] = [IBMCOSConnector]
diff --git a/enhancements/connectors/__init__.py b/enhancements/connectors/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/connectors/ibm_cos/__init__.py b/enhancements/connectors/ibm_cos/__init__.py
similarity index 100%
rename from src/connectors/ibm_cos/__init__.py
rename to enhancements/connectors/ibm_cos/__init__.py
index 5bf01ad43..f202f477f 100644
--- a/src/connectors/ibm_cos/__init__.py
+++ b/enhancements/connectors/ibm_cos/__init__.py
@@ -1,11 +1,11 @@
-from .connector import IBMCOSConnector
-from .models import IBMCOSConfigureBody
from .api import (
- ibm_cos_defaults,
+ ibm_cos_bucket_status,
ibm_cos_configure,
+ ibm_cos_defaults,
ibm_cos_list_buckets,
- ibm_cos_bucket_status,
)
+from .connector import IBMCOSConnector
+from .models import IBMCOSConfigureBody
__all__ = [
"IBMCOSConnector",
diff --git a/src/connectors/ibm_cos/api.py b/enhancements/connectors/ibm_cos/api.py
similarity index 87%
rename from src/connectors/ibm_cos/api.py
rename to enhancements/connectors/ibm_cos/api.py
index ee4ef97b8..c58e0fb67 100644
--- a/src/connectors/ibm_cos/api.py
+++ b/enhancements/connectors/ibm_cos/api.py
@@ -6,7 +6,7 @@ from fastapi import Depends
from fastapi.responses import JSONResponse
from config.settings import get_index_name
-from dependencies import get_connector_service, get_session_manager, get_current_user
+from dependencies import get_connector_service, get_current_user, get_session_manager
from session_manager import User
from utils.logging_config import get_logger
@@ -42,20 +42,22 @@ async def ibm_cos_defaults(
"""Prefer connection config value over env var."""
return conn_config.get(conn_key) or env_val
- return JSONResponse({
- "api_key_set": bool(api_key or conn_config.get("api_key")),
- "service_instance_id": _pick("service_instance_id", service_instance_id),
- "endpoint": _pick("endpoint_url", endpoint),
- "hmac_access_key_set": bool(hmac_access_key or conn_config.get("hmac_access_key")),
- "hmac_secret_key_set": bool(hmac_secret_key or conn_config.get("hmac_secret_key")),
- "auth_mode": conn_config.get(
- "auth_mode",
- "hmac" if (disable_iam or not (api_key or conn_config.get("api_key"))) else "iam",
- ),
- "disable_iam": disable_iam,
- "bucket_names": conn_config.get("bucket_names", []),
- "connection_id": connections[0].connection_id if connections else None,
- })
+ return JSONResponse(
+ {
+ "api_key_set": bool(api_key or conn_config.get("api_key")),
+ "service_instance_id": _pick("service_instance_id", service_instance_id),
+ "endpoint": _pick("endpoint_url", endpoint),
+ "hmac_access_key_set": bool(hmac_access_key or conn_config.get("hmac_access_key")),
+ "hmac_secret_key_set": bool(hmac_secret_key or conn_config.get("hmac_secret_key")),
+ "auth_mode": conn_config.get(
+ "auth_mode",
+ "hmac" if (disable_iam or not (api_key or conn_config.get("api_key"))) else "iam",
+ ),
+ "disable_iam": disable_iam,
+ "bucket_names": conn_config.get("bucket_names", []),
+ "connection_id": connections[0].connection_id if connections else None,
+ }
+ )
async def ibm_cos_configure(
@@ -169,17 +171,11 @@ async def ibm_cos_bucket_status(
# 2. Count indexed documents per bucket from OpenSearch
ingested_counts: dict = {}
try:
- opensearch_client = session_manager.get_user_opensearch_client(
- user.user_id, user.jwt_token
- )
+ opensearch_client = session_manager.get_user_opensearch_client(user.user_id, user.jwt_token)
query_body = {
"size": 0,
"query": {"term": {"connector_type": "ibm_cos"}},
- "aggs": {
- "doc_ids": {
- "terms": {"field": "document_id", "size": 50000}
- }
- },
+ "aggs": {"doc_ids": {"terms": {"field": "document_id", "size": 50000}}},
}
index_name = get_index_name()
os_resp = opensearch_client.search(index=index_name, body=query_body)
diff --git a/src/connectors/ibm_cos/auth.py b/enhancements/connectors/ibm_cos/auth.py
similarity index 75%
rename from src/connectors/ibm_cos/auth.py
rename to enhancements/connectors/ibm_cos/auth.py
index 54012d724..7505ecda6 100644
--- a/src/connectors/ibm_cos/auth.py
+++ b/enhancements/connectors/ibm_cos/auth.py
@@ -1,7 +1,7 @@
"""IBM Cloud Object Storage authentication and client factory."""
import os
-from typing import Dict, Any
+from typing import Any
from utils.logging_config import get_logger
@@ -11,7 +11,7 @@ logger = get_logger(__name__)
_DEFAULT_AUTH_ENDPOINT = "https://iam.cloud.ibm.com/identity/token"
-def _resolve_credentials(config: Dict[str, Any]):
+def _resolve_credentials(config: dict[str, Any]):
"""Resolve IBM COS credentials from config dict → environment variable fallback.
Returns a dict with the resolved values needed to build a boto3 client/resource.
@@ -25,19 +25,13 @@ def _resolve_credentials(config: Dict[str, Any]):
)
api_key = config.get("api_key") or os.getenv("IBM_COS_API_KEY")
- service_instance_id = (
- config.get("service_instance_id") or os.getenv("IBM_COS_SERVICE_INSTANCE_ID")
- )
- hmac_access_key = (
- config.get("hmac_access_key") or os.getenv("IBM_COS_HMAC_ACCESS_KEY_ID")
- )
- hmac_secret_key = (
- config.get("hmac_secret_key") or os.getenv("IBM_COS_HMAC_SECRET_ACCESS_KEY")
+ service_instance_id = config.get("service_instance_id") or os.getenv(
+ "IBM_COS_SERVICE_INSTANCE_ID"
)
+ hmac_access_key = config.get("hmac_access_key") or os.getenv("IBM_COS_HMAC_ACCESS_KEY_ID")
+ hmac_secret_key = config.get("hmac_secret_key") or os.getenv("IBM_COS_HMAC_SECRET_ACCESS_KEY")
auth_endpoint = (
- config.get("auth_endpoint")
- or os.getenv("IBM_COS_AUTH_ENDPOINT")
- or _DEFAULT_AUTH_ENDPOINT
+ config.get("auth_endpoint") or os.getenv("IBM_COS_AUTH_ENDPOINT") or _DEFAULT_AUTH_ENDPOINT
)
return {
@@ -50,7 +44,7 @@ def _resolve_credentials(config: Dict[str, Any]):
}
-def _build_resource(config: Dict[str, Any], creds: Dict[str, Any]):
+def _build_resource(config: dict[str, Any], creds: dict[str, Any]):
"""Build an S3-compatible resource using resolved credentials.
HMAC mode uses standard boto3 (no IBM-specific calls, pure S3 protocol).
@@ -60,15 +54,12 @@ def _build_resource(config: Dict[str, Any], creds: Dict[str, Any]):
if auth_mode == "hmac":
if not (creds["hmac_access_key"] and creds["hmac_secret_key"]):
- raise ValueError(
- "HMAC mode requires hmac_access_key and hmac_secret_key."
- )
+ raise ValueError("HMAC mode requires hmac_access_key and hmac_secret_key.")
try:
import boto3
except ImportError as exc:
raise ImportError(
- "boto3 is required for IBM COS HMAC mode. "
- "Install it with: pip install boto3"
+ "boto3 is required for IBM COS HMAC mode. Install it with: pip install boto3"
) from exc
logger.debug("Creating IBM COS resource with HMAC authentication (boto3)")
return boto3.resource(
@@ -84,13 +75,10 @@ def _build_resource(config: Dict[str, Any], creds: Dict[str, Any]):
from ibm_botocore.client import Config
except ImportError as exc:
raise ImportError(
- "ibm-cos-sdk is required for IBM COS IAM mode. "
- "Install it with: pip install ibm-cos-sdk"
+ "ibm-cos-sdk is required for IBM COS IAM mode. Install it with: pip install ibm-cos-sdk"
) from exc
if not (creds["api_key"] and creds["service_instance_id"]):
- raise ValueError(
- "IAM mode requires api_key and service_instance_id."
- )
+ raise ValueError("IAM mode requires api_key and service_instance_id.")
logger.debug("Creating IBM COS resource with IAM authentication (ibm_boto3)")
return ibm_boto3.resource(
"s3",
@@ -102,7 +90,7 @@ def _build_resource(config: Dict[str, Any], creds: Dict[str, Any]):
)
-def _build_client(config: Dict[str, Any], creds: Dict[str, Any]):
+def _build_client(config: dict[str, Any], creds: dict[str, Any]):
"""Build an S3-compatible client using resolved credentials.
HMAC mode uses standard boto3 (no IBM-specific calls, pure S3 protocol).
@@ -112,15 +100,12 @@ def _build_client(config: Dict[str, Any], creds: Dict[str, Any]):
if auth_mode == "hmac":
if not (creds["hmac_access_key"] and creds["hmac_secret_key"]):
- raise ValueError(
- "HMAC mode requires hmac_access_key and hmac_secret_key."
- )
+ raise ValueError("HMAC mode requires hmac_access_key and hmac_secret_key.")
try:
import boto3
except ImportError as exc:
raise ImportError(
- "boto3 is required for IBM COS HMAC mode. "
- "Install it with: pip install boto3"
+ "boto3 is required for IBM COS HMAC mode. Install it with: pip install boto3"
) from exc
logger.debug("Creating IBM COS client with HMAC authentication (boto3)")
return boto3.client(
@@ -136,13 +121,10 @@ def _build_client(config: Dict[str, Any], creds: Dict[str, Any]):
from ibm_botocore.client import Config
except ImportError as exc:
raise ImportError(
- "ibm-cos-sdk is required for IBM COS IAM mode. "
- "Install it with: pip install ibm-cos-sdk"
+ "ibm-cos-sdk is required for IBM COS IAM mode. Install it with: pip install ibm-cos-sdk"
) from exc
if not (creds["api_key"] and creds["service_instance_id"]):
- raise ValueError(
- "IAM mode requires api_key and service_instance_id."
- )
+ raise ValueError("IAM mode requires api_key and service_instance_id.")
logger.debug("Creating IBM COS client with IAM authentication (ibm_boto3)")
return ibm_boto3.client(
"s3",
@@ -154,7 +136,7 @@ def _build_client(config: Dict[str, Any], creds: Dict[str, Any]):
)
-def create_ibm_cos_resource(config: Dict[str, Any]):
+def create_ibm_cos_resource(config: dict[str, Any]):
"""Return an S3 resource handle (high-level API).
HMAC mode returns a standard boto3.resource (pure S3, no IBM discovery calls).
@@ -170,7 +152,7 @@ def create_ibm_cos_resource(config: Dict[str, Any]):
return _build_resource(config, creds)
-def create_ibm_cos_client(config: Dict[str, Any]):
+def create_ibm_cos_client(config: dict[str, Any]):
"""Return an S3 low-level client.
HMAC mode returns a standard boto3.client (pure S3, no IBM discovery calls).
diff --git a/src/connectors/ibm_cos/connector.py b/enhancements/connectors/ibm_cos/connector.py
similarity index 85%
rename from src/connectors/ibm_cos/connector.py
rename to enhancements/connectors/ibm_cos/connector.py
index 24f346d8c..dd2d1279a 100644
--- a/src/connectors/ibm_cos/connector.py
+++ b/enhancements/connectors/ibm_cos/connector.py
@@ -2,10 +2,11 @@
import mimetypes
import os
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from posixpath import basename
-from typing import Any, Dict, List, Optional
+from typing import Any
+from config.settings import IBM_AUTH_ENABLED
from connectors.base import BaseConnector, ConnectorDocument, DocumentACL
from utils.logging_config import get_logger
@@ -46,9 +47,14 @@ class IBMCOSConnector(BaseConnector):
connection_id (str): Connection identifier used for logging.
"""
+ CONNECTOR_TYPE = "ibm_cos"
+ CONNECTOR_KIND = "bucket"
CONNECTOR_NAME = "IBM Cloud Object Storage"
CONNECTOR_DESCRIPTION = "Add knowledge from IBM Cloud Object Storage"
CONNECTOR_ICON = "ibm-cos"
+ # api_key/hmac_access_key/hmac_secret_key are already in GENERAL_SECRET_KEYS;
+ # only service_instance_id is IBM-specific.
+ SECRET_CONFIG_KEYS = ("service_instance_id",)
# BaseConnector uses these to check env-var availability for IAM mode.
# HMAC-only setups will show as "unavailable" in the UI but can still be
@@ -56,6 +62,39 @@ class IBMCOSConnector(BaseConnector):
CLIENT_ID_ENV_VAR = "IBM_COS_API_KEY"
CLIENT_SECRET_ENV_VAR = "IBM_COS_SERVICE_INSTANCE_ID"
+ @classmethod
+ def is_available(cls, manager, user_id=None) -> bool:
+ return IBM_AUTH_ENABLED
+
+ @classmethod
+ def register_routes(cls, app) -> None:
+ from .api import (
+ ibm_cos_bucket_status,
+ ibm_cos_configure,
+ ibm_cos_defaults,
+ ibm_cos_list_buckets,
+ )
+
+ # Registered before generic /{connector_type}/... to avoid shadowing.
+ app.add_api_route(
+ "/connectors/ibm_cos/defaults", ibm_cos_defaults, methods=["GET"], tags=["internal"]
+ )
+ app.add_api_route(
+ "/connectors/ibm_cos/configure", ibm_cos_configure, methods=["POST"], tags=["internal"]
+ )
+ app.add_api_route(
+ "/connectors/ibm_cos/{connection_id}/buckets",
+ ibm_cos_list_buckets,
+ methods=["GET"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/connectors/ibm_cos/{connection_id}/bucket-status",
+ ibm_cos_bucket_status,
+ methods=["GET"],
+ tags=["internal"],
+ )
+
def get_client_id(self) -> str:
"""Return IAM API key, or HMAC access key ID as fallback."""
val = (
@@ -86,26 +125,25 @@ class IBMCOSConnector(BaseConnector):
"or IBM_COS_HMAC_SECRET_ACCESS_KEY (HMAC)."
)
- def __init__(self, config: Dict[str, Any]):
+ def __init__(self, config: dict[str, Any]):
if config is None:
config = {}
super().__init__(config)
- self.bucket_names: List[str] = config.get("bucket_names") or []
+ self.bucket_names: list[str] = config.get("bucket_names") or []
self.prefix: str = config.get("prefix", "")
self.connection_id: str = config.get("connection_id", "default")
# Resolved service instance ID used as ACL owner fallback
- self._service_instance_id: str = (
- config.get("service_instance_id")
- or os.getenv("IBM_COS_SERVICE_INSTANCE_ID", "")
+ self._service_instance_id: str = config.get("service_instance_id") or os.getenv(
+ "IBM_COS_SERVICE_INSTANCE_ID", ""
)
self._handle = None # Lazy-initialised on first use
# IAM mode uses ibm_boto3.client to avoid internal service-instance
# discovery calls that cause XML-parse errors against the real IBM COS API.
# HMAC mode uses ibm_boto3.resource (confirmed working with MinIO and S3).
- self._is_hmac: bool = (config.get("auth_mode", "iam") == "hmac")
+ self._is_hmac: bool = config.get("auth_mode", "iam") == "hmac"
def _get_handle(self):
"""Return (and cache) the appropriate boto3 handle for the configured auth mode.
@@ -130,9 +168,9 @@ class IBMCOSConnector(BaseConnector):
try:
handle = self._get_handle()
if self._is_hmac:
- list(handle.buckets.all()) # resource API
+ list(handle.buckets.all()) # resource API
else:
- handle.list_buckets() # client API
+ handle.list_buckets() # client API
self._authenticated = True
logger.debug(f"IBM COS authenticated for connection {self.connection_id}")
return True
@@ -141,7 +179,7 @@ class IBMCOSConnector(BaseConnector):
self._authenticated = False
return False
- def _resolve_bucket_names(self) -> List[str]:
+ def _resolve_bucket_names(self) -> list[str]:
"""Return configured bucket names, or auto-discover all accessible buckets."""
if self.bucket_names:
return self.bucket_names
@@ -160,10 +198,10 @@ class IBMCOSConnector(BaseConnector):
async def list_files(
self,
- page_token: Optional[str] = None,
- max_files: Optional[int] = None,
+ page_token: str | None = None,
+ max_files: int | None = None,
**kwargs,
- ) -> Dict[str, Any]:
+ ) -> dict[str, Any]:
"""List objects across all configured (or auto-discovered) buckets.
Uses the ibm_boto3 resource API: Bucket.objects.all() handles pagination
@@ -177,7 +215,7 @@ class IBMCOSConnector(BaseConnector):
"next_page_token": always None (SDK handles pagination internally)
"""
handle = self._get_handle()
- files: List[Dict[str, Any]] = []
+ files: list[dict[str, Any]] = []
bucket_names = self._resolve_bucket_names()
for bucket_name in bucket_names:
@@ -209,7 +247,7 @@ class IBMCOSConnector(BaseConnector):
return {"files": files, "next_page_token": None}
else:
# client API: list_objects_v2 with manual pagination
- kwargs: Dict[str, Any] = {"Bucket": bucket_name}
+ kwargs: dict[str, Any] = {"Bucket": bucket_name}
if self.prefix:
kwargs["Prefix"] = self.prefix
while True:
@@ -261,12 +299,12 @@ class IBMCOSConnector(BaseConnector):
# Both client.get_object() and resource.Object().get() return the same
# response dict: Body stream + ContentType, ContentLength, LastModified.
if self._is_hmac:
- response = handle.Object(bucket_name, key).get() # resource
+ response = handle.Object(bucket_name, key).get() # resource
else:
response = handle.get_object(Bucket=bucket_name, Key=key) # client
content: bytes = response["Body"].read()
- last_modified: datetime = response.get("LastModified") or datetime.now(timezone.utc)
+ last_modified: datetime = response.get("LastModified") or datetime.now(UTC)
size: int = response.get("ContentLength", len(content))
# MIME type detection: prefer filename extension over generic S3 content-type.
@@ -317,7 +355,7 @@ class IBMCOSConnector(BaseConnector):
or self._service_instance_id
)
- allowed_users: List[str] = []
+ allowed_users: list[str] = []
for grant in acl_response.get("Grants", []):
grantee = grant.get("Grantee", {})
permission = grant.get("Permission", "")
@@ -352,19 +390,15 @@ class IBMCOSConnector(BaseConnector):
"""No-op: IBM COS event notifications are out of scope for this connector."""
return ""
- async def handle_webhook(self, payload: Dict[str, Any]) -> List[str]:
+ async def handle_webhook(self, payload: dict[str, Any]) -> list[str]:
"""No-op: webhooks are not supported in this connector version."""
return []
def extract_webhook_channel_id(
- self, payload: Dict[str, Any], headers: Dict[str, str]
- ) -> Optional[str]:
+ self, payload: dict[str, Any], headers: dict[str, str]
+ ) -> str | None:
return None
async def cleanup_subscription(self, subscription_id: str) -> bool:
"""No-op: no subscription to clean up."""
return True
-
-
-
-
diff --git a/enhancements/connectors/ibm_cos/models.py b/enhancements/connectors/ibm_cos/models.py
new file mode 100644
index 000000000..145df871b
--- /dev/null
+++ b/enhancements/connectors/ibm_cos/models.py
@@ -0,0 +1,19 @@
+"""Pydantic request/response models for IBM COS API endpoints."""
+
+from pydantic import BaseModel
+
+
+class IBMCOSConfigureBody(BaseModel):
+ auth_mode: str # "iam" or "hmac"
+ endpoint: str
+ # IAM fields
+ api_key: str | None = None
+ service_instance_id: str | None = None
+ auth_endpoint: str | None = None
+ # HMAC fields
+ hmac_access_key: str | None = None
+ hmac_secret_key: str | None = None
+ # Optional bucket selection
+ bucket_names: list[str] | None = None
+ # Optional: update an existing connection
+ connection_id: str | None = None
diff --git a/src/connectors/ibm_cos/support.py b/enhancements/connectors/ibm_cos/support.py
similarity index 87%
rename from src/connectors/ibm_cos/support.py
rename to enhancements/connectors/ibm_cos/support.py
index 25e5e5bcb..f6992fc3c 100644
--- a/src/connectors/ibm_cos/support.py
+++ b/enhancements/connectors/ibm_cos/support.py
@@ -5,15 +5,14 @@ config dict construction, keeping the route handlers thin.
"""
import os
-from typing import Dict, Optional, Tuple
from .models import IBMCOSConfigureBody
def build_ibm_cos_config(
body: IBMCOSConfigureBody,
- existing_config: Dict,
-) -> Tuple[Dict, Optional[str]]:
+ existing_config: dict,
+) -> tuple[dict, str | None]:
"""Resolve IBM COS credentials and build the connection config dict.
Resolution order for each credential: request body → environment variable
@@ -23,17 +22,13 @@ def build_ibm_cos_config(
(conn_config, None) on success
({}, error_message) on validation failure
"""
- conn_config: Dict = {
+ conn_config: dict = {
"auth_mode": body.auth_mode,
"endpoint_url": body.endpoint,
}
if body.auth_mode == "iam":
- api_key = (
- body.api_key
- or os.getenv("IBM_COS_API_KEY")
- or existing_config.get("api_key")
- )
+ api_key = body.api_key or os.getenv("IBM_COS_API_KEY") or existing_config.get("api_key")
svc_id = (
body.service_instance_id
or os.getenv("IBM_COS_SERVICE_INSTANCE_ID")
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.ts
index 735c7c7ba..8a7f5c94c 100644
--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts
@@ -91,7 +91,7 @@ export const useConnectConnectorMutation = () => {
window.location.href = authUrl;
} else {
- // Direct-auth connector (e.g. IBM COS) — credentials already verified,
+ // Direct-auth connector (bucket-kind) — credentials already verified,
// no OAuth redirect needed. Refresh connector status.
queryClient.invalidateQueries({ queryKey: ["connectors"] });
toast.success(`${connector.name} connected successfully`);
diff --git a/frontend/app/api/mutations/useSyncConnector.ts b/frontend/app/api/mutations/useSyncConnector.ts
index 26566131f..25426e32b 100644
--- a/frontend/app/api/mutations/useSyncConnector.ts
+++ b/frontend/app/api/mutations/useSyncConnector.ts
@@ -2,6 +2,8 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { IngestSettings } from "@/components/cloud-picker/types";
+
// Response types
interface SyncResponse {
task_ids?: string[];
@@ -68,10 +70,10 @@ const syncConnector = async ({
downloadUrl?: string;
size?: number;
}>;
- settings?: any;
+ settings?: IngestSettings;
/** When true, ingest all files from the connector (bypasses the re-sync gate). */
sync_all?: boolean;
- /** Restrict ingest to these bucket names (IBM COS). */
+ /** Restrict ingest to these bucket names (bucket connectors). */
bucket_filter?: string[];
/** When true, replace any indexed document with the same filename. */
replace_duplicates?: boolean;
diff --git a/frontend/app/knowledge/page.tsx b/frontend/app/knowledge/page.tsx
index b03e2f492..f70811f1d 100644
--- a/frontend/app/knowledge/page.tsx
+++ b/frontend/app/knowledge/page.tsx
@@ -40,6 +40,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useIsCloudBrand } from "@/contexts/brand-context";
+import { getConnectorDescriptor } from "@/lib/connectors/registry";
import {
buildKnowledgeTableRows,
getKnowledgeFileIdentity,
@@ -50,11 +51,6 @@ import {
DeleteConfirmationDialog,
formatFilesToDelete,
} from "../../components/delete-confirmation-dialog";
-import AwsLogo from "../../components/icons/aws-logo";
-import GoogleDriveIcon from "../../components/icons/google-drive-logo";
-import IBMCOSIcon from "../../components/icons/ibm-cos-icon";
-import OneDriveIcon from "../../components/icons/one-drive-logo";
-import SharePointIcon from "../../components/icons/share-point-logo";
import { SyncConfirmDialog } from "../../components/sync-confirm-dialog";
import { useDeleteDocument } from "../api/mutations/useDeleteDocument";
import { useRefreshOpenragDocs } from "../api/mutations/useRefreshOpenragDocs";
@@ -111,26 +107,16 @@ function listFilesFilterParam(values?: string[]): string | undefined {
// Function to get the appropriate icon for a connector type
function getSourceIcon(connectorType?: string) {
+ if (connectorType) {
+ const Icon = getConnectorDescriptor(connectorType)?.Icon;
+ if (Icon) return <Icon className="h-4 w-4 text-foreground flex-shrink-0" />;
+ }
switch (connectorType) {
- case "google_drive":
- return (
- <GoogleDriveIcon className="h-4 w-4 text-foreground flex-shrink-0" />
- );
- case "onedrive":
- return <OneDriveIcon className="h-4 w-4 text-foreground flex-shrink-0" />;
- case "sharepoint":
- return (
- <SharePointIcon className="h-4 w-4 text-foreground flex-shrink-0" />
- );
case "openrag_docs":
case "url":
return <Globe className="h-4 w-4 text-muted-foreground flex-shrink-0" />;
case "s3":
return <Cloud className="h-4 w-4 text-foreground flex-shrink-0" />;
- case "ibm_cos":
- return <IBMCOSIcon className="h-4 w-4 flex-shrink-0" />;
- case "aws_s3":
- return <AwsLogo className="h-4 w-4 flex-shrink-0" />;
default:
return (
<FileIcon className="h-4 w-4 text-muted-foreground flex-shrink-0" />
diff --git a/frontend/app/settings/_components/connector-cards.tsx b/frontend/app/settings/_components/connector-cards.tsx
index 5f0880e53..f4471b686 100644
--- a/frontend/app/settings/_components/connector-cards.tsx
+++ b/frontend/app/settings/_components/connector-cards.tsx
@@ -8,24 +8,20 @@ import {
type Connector as QueryConnector,
useGetConnectorsQuery,
} from "@/app/api/queries/useGetConnectorsQuery";
-import AwsLogo from "@/components/icons/aws-logo";
-import GoogleDriveIcon from "@/components/icons/google-drive-logo";
-import IBMCOSIcon from "@/components/icons/ibm-cos-icon";
-import OneDriveIcon from "@/components/icons/one-drive-logo";
-import SharePointIcon from "@/components/icons/share-point-logo";
import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
+import {
+ getConnectorDescriptor,
+ getConnectorDescriptors,
+} from "@/lib/connectors/registry";
import ConnectorCard, { type Connector } from "./connector-card";
import ConnectorsSkeleton from "./connectors-skeleton";
-import IBMCOSSettingsDialog from "./ibm-cos-settings-dialog";
-import S3SettingsDialog from "./s3-settings-dialog";
export default function ConnectorCards() {
const { isAuthenticated, isNoAuthMode, isIbmAuthMode } = useAuth();
const isCloudBrand = useIsCloudBrand();
const router = useRouter();
- const [ibmCOSDialogOpen, setIBMCOSDialogOpen] = useState(false);
- const [s3DialogOpen, setS3DialogOpen] = useState(false);
+ const [openDialog, setOpenDialog] = useState<string | null>(null);
const { data: queryConnectors = [], isLoading: connectorsLoading } =
useGetConnectorsQuery({
@@ -35,21 +31,16 @@ export default function ConnectorCards() {
const connectMutation = useConnectConnectorMutation();
const disconnectMutation = useDisconnectConnectorMutation();
- const getConnectorIcon = useCallback((iconName: string) => {
- const iconMap: { [key: string]: React.ReactElement } = {
- "google-drive": <GoogleDriveIcon />,
- sharepoint: <SharePointIcon />,
- onedrive: <OneDriveIcon />,
- "ibm-cos": <IBMCOSIcon />,
- "aws-s3": <AwsLogo />,
- };
- return (
- iconMap[iconName] || (
+ const getConnectorIcon = useCallback((connectorType: string) => {
+ const Icon = getConnectorDescriptor(connectorType)?.Icon;
+ if (!Icon) {
+ return (
<div className="w-8 h-8 bg-gray-500 rounded flex items-center justify-center text-white font-bold leading-none shrink-0">
?
</div>
- )
- );
+ );
+ }
+ return <Icon />;
}, []);
const connectors = queryConnectors
@@ -60,7 +51,7 @@ export default function ConnectorCards() {
})
.map((c) => ({
...c,
- icon: getConnectorIcon(c.icon),
+ icon: getConnectorIcon(c.type),
})) as Connector[];
const handleConnect = async (connector: Connector) => {
@@ -79,13 +70,10 @@ export default function ConnectorCards() {
router.push(`/upload/${provider}`);
};
- // Connectors that use a settings dialog instead of OAuth for configuration
const getConfigureHandler = (connector: Connector) => {
- if (connector.type === "ibm_cos") {
- return () => setIBMCOSDialogOpen(true);
- }
- if (connector.type === "aws_s3") {
- return () => setS3DialogOpen(true);
+ const descriptor = getConnectorDescriptor(connector.type);
+ if (descriptor?.SettingsDialog) {
+ return () => setOpenDialog(connector.type);
}
return undefined;
};
@@ -94,6 +82,10 @@ export default function ConnectorCards() {
return null;
}
+ const dialogDescriptors = getConnectorDescriptors().filter(
+ (d) => d.SettingsDialog,
+ );
+
return (
<>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
@@ -125,11 +117,18 @@ export default function ConnectorCards() {
)}
</div>
- <IBMCOSSettingsDialog
- open={ibmCOSDialogOpen}
- setOpen={setIBMCOSDialogOpen}
- />
- <S3SettingsDialog open={s3DialogOpen} setOpen={setS3DialogOpen} />
+ {dialogDescriptors.map((descriptor) => {
+ const Dialog = descriptor.SettingsDialog!;
+ return (
+ <Dialog
+ key={descriptor.connectorType}
+ open={openDialog === descriptor.connectorType}
+ setOpen={(open: boolean) =>
+ setOpenDialog(open ? descriptor.connectorType : null)
+ }
+ />
+ );
+ })}
</>
);
}
diff --git a/frontend/app/upload/[provider]/page.tsx b/frontend/app/upload/[provider]/page.tsx
index c964fef9c..480776377 100644
--- a/frontend/app/upload/[provider]/page.tsx
+++ b/frontend/app/upload/[provider]/page.tsx
@@ -1,26 +1,15 @@
"use client";
-import { useQueryClient } from "@tanstack/react-query";
-import {
- AlertCircle,
- ArrowLeft,
- FileSearch,
- FolderOpen,
- RefreshCw,
-} from "lucide-react";
+import { AlertCircle, ArrowLeft } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
import { useGetConnectorsQuery } from "@/app/api/queries/useGetConnectorsQuery";
import { useGetConnectorTokenQuery } from "@/app/api/queries/useGetConnectorTokenQuery";
-import { useIBMCOSBucketStatusQuery } from "@/app/api/queries/useIBMCOSBucketStatusQuery";
-import { useS3BucketStatusQuery } from "@/app/api/queries/useS3BucketStatusQuery";
import { type CloudFile, UnifiedCloudPicker } from "@/components/cloud-picker";
-import { IngestSettings } from "@/components/cloud-picker/ingest-settings";
import { getIngestChunkSettingsError } from "@/components/cloud-picker/types";
import { DuplicateHandlingDialog } from "@/components/duplicate-handling-dialog";
-import { FileBrowserDialog } from "@/components/file-browser-dialog";
import { Button } from "@/components/ui/button";
import {
Tooltip,
@@ -29,348 +18,7 @@ import {
} from "@/components/ui/tooltip";
import { useTask } from "@/contexts/task-context";
import { useSessionIngestSettings } from "@/hooks/useSessionIngestSettings";
-import { duplicateCheck } from "@/lib/upload-utils";
-
-// Connectors that sync entire buckets/repositories without a file picker
-const DIRECT_SYNC_PROVIDERS = ["ibm_cos", "aws_s3"];
-
-// ---------------------------------------------------------------------------
-// Shared bucket view — used by both IBM COS and S3
-// ---------------------------------------------------------------------------
-
-function BucketView({
- connector,
- buckets,
- isLoading,
- bucketsError,
- onRefetch,
- invalidateQueryKey,
- syncMutation,
- addTask,
- onBack,
- onDone,
-}: {
- connector: any;
- buckets: Array<{ name: string; ingested_count: number }> | undefined;
- isLoading: boolean;
- bucketsError?: Error | null;
- onRefetch: () => void;
- invalidateQueryKey: readonly unknown[];
- syncMutation: ReturnType<typeof useSyncConnector>;
- addTask: (id: string) => void;
- onBack: () => void;
- onDone: () => void;
-}) {
- const queryClient = useQueryClient();
- const [selectedBuckets, setSelectedBuckets] = useState<Set<string>>(
- new Set(),
- );
- const [ingestSettings, setIngestSettings] = useSessionIngestSettings();
- const [isSettingsOpen, setIsSettingsOpen] = useState(false);
- const [browseDialogBucket, setBrowseDialogBucket] = useState<string | null>(
- null,
- );
-
- const invalidate = () => {
- queryClient.invalidateQueries({ queryKey: invalidateQueryKey });
- };
-
- const toggleBucket = (bucketName: string) => {
- setSelectedBuckets((prev) => {
- const next = new Set(prev);
- if (next.has(bucketName)) {
- next.delete(bucketName);
- } else {
- next.add(bucketName);
- }
- return next;
- });
- };
-
- const ingestSelected = () => {
- const chunkErr = getIngestChunkSettingsError(ingestSettings);
- if (chunkErr) {
- toast.error("Could not start ingest", { description: chunkErr });
- return;
- }
- syncMutation.mutate(
- {
- connectorType: connector.type,
- body: {
- connection_id: connector.connectionId!,
- selected_files: [],
- bucket_filter: Array.from(selectedBuckets),
- settings: ingestSettings,
- },
- },
- {
- onSuccess: (result) => {
- invalidate();
- if (result.task_ids?.length) {
- addTask(result.task_ids[0]);
- onDone();
- } else {
- toast.info("No files found in the selected buckets.");
- }
- },
- onError: (err) => {
- toast.error(err instanceof Error ? err.message : "Sync failed");
- },
- },
- );
- };
-
- return (
- <>
- <div className="mb-8 flex gap-2 items-center">
- <Button variant="ghost" onClick={onBack} size="icon">
- <ArrowLeft size={18} />
- </Button>
- <h2 className="text-xl text-[18px] font-semibold">
- Add from {connector.name}
- </h2>
- </div>
-
- <div className="max-w-3xl mx-auto space-y-4">
- <div className="flex items-center justify-between">
- <p className="text-sm text-muted-foreground">
- Select buckets to ingest.
- </p>
- <div className="flex items-center gap-2">
- {selectedBuckets.size > 0 && (
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSelectedBuckets(new Set())}
- >
- Deselect All
- </Button>
- )}
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- setSelectedBuckets(new Set(buckets?.map((b) => b.name) ?? []))
- }
- disabled={isLoading || !buckets?.length}
- >
- Select All
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={onRefetch}
- disabled={isLoading}
- >
- <RefreshCw
- size={14}
- className={isLoading ? "animate-spin" : ""}
- />
- Refresh Buckets
- </Button>
- </div>
- </div>
-
- {isLoading ? (
- <div className="flex justify-center py-8">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
- </div>
- ) : bucketsError ? (
- <div className="rounded-lg border border-destructive/50 p-6 text-center text-destructive text-sm">
- {bucketsError.message ||
- "Failed to load buckets. Check your credentials and endpoint."}
- </div>
- ) : !buckets?.length ? (
- <div className="rounded-lg border p-6 text-center text-muted-foreground text-sm">
- No buckets found. Check your credentials and endpoint.
- </div>
- ) : (
- <div className="rounded-lg border divide-y">
- {buckets.map((bucket) => {
- const isSelected = selectedBuckets.has(bucket.name);
- return (
- <div
- key={bucket.name}
- className="flex items-center gap-[18px] px-4 py-3 cursor-pointer"
- onClick={() => toggleBucket(bucket.name)}
- >
- <div
- className={`shrink-0 size-5 rounded-[6px] border-2 flex items-center justify-center transition-colors ${
- isSelected
- ? "bg-foreground border-foreground"
- : "border-muted-foreground/60"
- }`}
- >
- {isSelected && (
- <svg
- viewBox="0 0 12 12"
- fill="none"
- className="size-3 text-background"
- stroke="currentColor"
- strokeWidth={2}
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <polyline points="2,6 5,9 10,3" />
- </svg>
- )}
- </div>
- <div className="flex items-center gap-4 flex-1 min-w-0">
- <div className="bg-white/5 rounded-[10px] shrink-0 size-10 flex items-center justify-center">
- <FolderOpen size={20} className="text-muted-foreground" />
- </div>
- <div className="flex flex-col gap-1 min-w-0">
- <p className="font-medium text-sm leading-6">
- {bucket.name}
- </p>
- {bucket.ingested_count > 0 && (
- <p className="text-xs text-muted-foreground">
- {bucket.ingested_count} document
- {bucket.ingested_count !== 1 ? "s" : ""} ingested
- </p>
- )}
- </div>
- <Button
- variant="outline"
- size="sm"
- className="shrink-0"
- onClick={(e) => {
- e.stopPropagation();
- setBrowseDialogBucket(bucket.name);
- }}
- >
- <FileSearch size={14} className="mr-1.5" />
- Browse Files
- </Button>
- </div>
- </div>
- );
- })}
- </div>
- )}
-
- <IngestSettings
- isOpen={isSettingsOpen}
- onOpenChange={setIsSettingsOpen}
- settings={ingestSettings}
- onSettingsChange={setIngestSettings}
- />
- </div>
-
- <div className="max-w-3xl mx-auto mt-6 sticky bottom-0 left-0 right-0 pb-6 bg-background pt-4">
- <div className="flex justify-between gap-3">
- <Button
- variant="ghost"
- className="border bg-transparent border-border rounded-lg text-secondary-foreground"
- onClick={onBack}
- >
- Back
- </Button>
- <Button
- className="bg-foreground text-background hover:bg-foreground/90 font-semibold"
- onClick={ingestSelected}
- disabled={syncMutation.isPending || selectedBuckets.size === 0}
- loading={syncMutation.isPending}
- >
- {syncMutation.isPending
- ? "Ingesting…"
- : selectedBuckets.size > 0
- ? `Ingest ${selectedBuckets.size} Bucket${selectedBuckets.size !== 1 ? "s" : ""}`
- : "Select Buckets to Ingest"}
- </Button>
- </div>
- </div>
-
- {connector.connectionId && browseDialogBucket && (
- <FileBrowserDialog
- open
- onOpenChange={(open) => {
- if (!open) setBrowseDialogBucket(null);
- }}
- connectorType={connector.type}
- connectionId={connector.connectionId}
- buckets={[browseDialogBucket]}
- />
- )}
- </>
- );
-}
-
-// ---------------------------------------------------------------------------
-// IBM COS wrapper
-// ---------------------------------------------------------------------------
-
-function IBMCOSBucketView({
- connector,
- syncMutation,
- addTask,
- onBack,
- onDone,
-}: {
- connector: any;
- syncMutation: ReturnType<typeof useSyncConnector>;
- addTask: (id: string) => void;
- onBack: () => void;
- onDone: () => void;
-}) {
- const {
- data: buckets,
- isLoading,
- refetch,
- } = useIBMCOSBucketStatusQuery(connector.connectionId, { enabled: true });
- return (
- <BucketView
- connector={connector}
- buckets={buckets}
- isLoading={isLoading}
- onRefetch={refetch}
- invalidateQueryKey={["ibm-cos-bucket-status", connector.connectionId]}
- syncMutation={syncMutation}
- addTask={addTask}
- onBack={onBack}
- onDone={onDone}
- />
- );
-}
-
-// ---------------------------------------------------------------------------
-// Amazon S3 wrapper
-// ---------------------------------------------------------------------------
-
-function S3BucketView({
- connector,
- syncMutation,
- addTask,
- onBack,
- onDone,
-}: {
- connector: any;
- syncMutation: ReturnType<typeof useSyncConnector>;
- addTask: (id: string) => void;
- onBack: () => void;
- onDone: () => void;
-}) {
- const {
- data: buckets,
- isLoading,
- error: bucketsError,
- refetch,
- } = useS3BucketStatusQuery(connector.connectionId, { enabled: true });
- return (
- <BucketView
- connector={connector}
- buckets={buckets}
- isLoading={isLoading}
- bucketsError={bucketsError as Error | null}
- onRefetch={refetch}
- invalidateQueryKey={["s3-bucket-status", connector.connectionId]}
- syncMutation={syncMutation}
- addTask={addTask}
- onBack={onBack}
- onDone={onDone}
- />
- );
-}
+import { getConnectorDescriptor } from "@/lib/connectors/registry";
// CloudFile interface is now imported from the unified cloud picker
@@ -386,8 +34,8 @@ export default function UploadProviderPage() {
error: connectorsError,
} = useGetConnectorsQuery();
const connector = connectors.find((c) => c.type === provider);
-
- const isDirectSyncProvider = DIRECT_SYNC_PROVIDERS.includes(provider);
+ const descriptor = getConnectorDescriptor(provider);
+ const isDirectSyncProvider = descriptor?.kind === "bucket";
const { data: tokenData, isLoading: tokenLoading } =
useGetConnectorTokenQuery(
@@ -400,7 +48,7 @@ export default function UploadProviderPage() {
: undefined,
},
{
- // Direct-sync providers (e.g. IBM COS) don't use OAuth tokens
+ // Bucket-kind connectors sync entire buckets and don't use OAuth tokens.
enabled:
!!connector &&
connector.status === "connected" &&
@@ -475,6 +123,8 @@ export default function UploadProviderPage() {
);
};
+ const getProviderDisplayName = () => descriptor?.name ?? provider;
+
const handleSync = async (connector: {
connectionId?: string;
type: string;
@@ -573,15 +223,6 @@ export default function UploadProviderPage() {
setDuplicateDialogOpen(open);
};
- const getProviderDisplayName = () => {
- const nameMap: { [key: string]: string } = {
- google_drive: "Google Drive",
- onedrive: "OneDrive",
- sharepoint: "SharePoint",
- };
- return nameMap[provider] || provider;
- };
-
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
@@ -656,21 +297,15 @@ export default function UploadProviderPage() {
);
}
- // Direct-sync providers show a bucket list with sync status.
- if (isDirectSyncProvider && connector.status === "connected") {
- if (provider === "aws_s3") {
- return (
- <S3BucketView
- connector={connector}
- syncMutation={syncMutation}
- addTask={addTask}
- onBack={() => router.back()}
- onDone={() => router.push("/knowledge")}
- />
- );
- }
+ // Bucket-kind connectors render their own bucket list view.
+ if (
+ isDirectSyncProvider &&
+ connector.status === "connected" &&
+ descriptor?.BucketView
+ ) {
+ const BucketView = descriptor.BucketView;
return (
- <IBMCOSBucketView
+ <BucketView
connector={connector}
syncMutation={syncMutation}
addTask={addTask}
diff --git a/frontend/components/cloud-picker/file-item.tsx b/frontend/components/cloud-picker/file-item.tsx
index f4d7d4257..2011ea60d 100644
--- a/frontend/components/cloud-picker/file-item.tsx
+++ b/frontend/components/cloud-picker/file-item.tsx
@@ -1,12 +1,8 @@
"use client";
import { FileText, Folder, Trash2 } from "lucide-react";
-import AwsLogo from "@/components/icons/aws-logo";
-import GoogleDriveIcon from "@/components/icons/google-drive-logo";
-import IBMCOSIcon from "@/components/icons/ibm-cos-icon";
-import OneDriveIcon from "@/components/icons/one-drive-logo";
-import SharePointIcon from "@/components/icons/share-point-logo";
import { Button } from "@/components/ui/button";
+import { getConnectorDescriptor } from "@/lib/connectors/registry";
import type { CloudFile } from "./types";
interface FileItemProps {
@@ -63,20 +59,9 @@ const formatFileSize = (bytes?: number) => {
};
const getProviderIcon = (provider: string) => {
- switch (provider) {
- case "google_drive":
- return <GoogleDriveIcon />;
- case "onedrive":
- return <OneDriveIcon />;
- case "sharepoint":
- return <SharePointIcon />;
- case "ibm_cos":
- return <IBMCOSIcon />;
- case "aws_s3":
- return <AwsLogo />;
- default:
- return <FileText className="h-6 w-6" />;
- }
+ const Icon = getConnectorDescriptor(provider)?.Icon;
+ if (Icon) return <Icon />;
+ return <FileText className="h-6 w-6" />;
};
export const FileItem = ({ file, onRemove, provider }: FileItemProps) => (
diff --git a/frontend/components/connectors/aws-s3/bucket-view.tsx b/frontend/components/connectors/aws-s3/bucket-view.tsx
new file mode 100644
index 000000000..148145856
--- /dev/null
+++ b/frontend/components/connectors/aws-s3/bucket-view.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+import type { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
+import { useS3BucketStatusQuery } from "@/app/api/queries/useS3BucketStatusQuery";
+import { SharedBucketView } from "../shared-bucket-view";
+
+export interface S3BucketViewProps {
+ connector: any;
+ syncMutation: ReturnType<typeof useSyncConnector>;
+ addTask: (id: string) => void;
+ onBack: () => void;
+ onDone: () => void;
+}
+
+export function S3BucketView({
+ connector,
+ syncMutation,
+ addTask,
+ onBack,
+ onDone,
+}: S3BucketViewProps) {
+ const {
+ data: buckets,
+ isLoading,
+ error: bucketsError,
+ refetch,
+ } = useS3BucketStatusQuery(connector.connectionId, { enabled: true });
+ return (
+ <SharedBucketView
+ connector={connector}
+ buckets={buckets}
+ isLoading={isLoading}
+ bucketsError={bucketsError as Error | null}
+ onRefetch={refetch}
+ invalidateQueryKey={["s3-bucket-status", connector.connectionId]}
+ syncMutation={syncMutation}
+ addTask={addTask}
+ onBack={onBack}
+ onDone={onDone}
+ />
+ );
+}
diff --git a/frontend/components/connectors/shared-bucket-view.tsx b/frontend/components/connectors/shared-bucket-view.tsx
new file mode 100644
index 000000000..86d5f23b0
--- /dev/null
+++ b/frontend/components/connectors/shared-bucket-view.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { ArrowLeft, FileSearch, FolderOpen, RefreshCw } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import type { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
+import { IngestSettings } from "@/components/cloud-picker/ingest-settings";
+import { getIngestChunkSettingsError } from "@/components/cloud-picker/types";
+import { FileBrowserDialog } from "@/components/file-browser-dialog";
+import { Button } from "@/components/ui/button";
+import { useSessionIngestSettings } from "@/hooks/useSessionIngestSettings";
+
+export interface SharedBucketViewProps {
+ connector: any;
+ buckets: Array<{ name: string; ingested_count: number }> | undefined;
+ isLoading: boolean;
+ bucketsError?: Error | null;
+ onRefetch: () => void;
+ invalidateQueryKey: readonly unknown[];
+ syncMutation: ReturnType<typeof useSyncConnector>;
+ addTask: (id: string) => void;
+ onBack: () => void;
+ onDone: () => void;
+}
+
+export function SharedBucketView({
+ connector,
+ buckets,
+ isLoading,
+ bucketsError,
+ onRefetch,
+ invalidateQueryKey,
+ syncMutation,
+ addTask,
+ onBack,
+ onDone,
+}: SharedBucketViewProps) {
+ const queryClient = useQueryClient();
+ const [selectedBuckets, setSelectedBuckets] = useState<Set<string>>(
+ new Set(),
+ );
+ const [ingestSettings, setIngestSettings] = useSessionIngestSettings();
+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
+ const [browseDialogBucket, setBrowseDialogBucket] = useState<string | null>(
+ null,
+ );
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: invalidateQueryKey });
+ };
+
+ const toggleBucket = (bucketName: string) => {
+ setSelectedBuckets((prev) => {
+ const next = new Set(prev);
+ if (next.has(bucketName)) {
+ next.delete(bucketName);
+ } else {
+ next.add(bucketName);
+ }
+ return next;
+ });
+ };
+
+ const ingestSelected = () => {
+ const chunkErr = getIngestChunkSettingsError(ingestSettings);
+ if (chunkErr) {
+ toast.error("Could not start ingest", { description: chunkErr });
+ return;
+ }
+ syncMutation.mutate(
+ {
+ connectorType: connector.type,
+ body: {
+ connection_id: connector.connectionId!,
+ selected_files: [],
+ bucket_filter: Array.from(selectedBuckets),
+ settings: ingestSettings,
+ },
+ },
+ {
+ onSuccess: (result) => {
+ invalidate();
+ if (result.task_ids?.length) {
+ addTask(result.task_ids[0]);
+ onDone();
+ } else {
+ toast.info("No files found in the selected buckets.");
+ }
+ },
+ onError: (err) => {
+ toast.error(err instanceof Error ? err.message : "Sync failed");
+ },
+ },
+ );
+ };
+
+ return (
+ <>
+ <div className="mb-8 flex gap-2 items-center">
+ <Button variant="ghost" onClick={onBack} size="icon">
+ <ArrowLeft size={18} />
+ </Button>
+ <h2 className="text-xl text-[18px] font-semibold">
+ Add from {connector.name}
+ </h2>
+ </div>
+
+ <div className="max-w-3xl mx-auto space-y-4">
+ <div className="flex items-center justify-between">
+ <p className="text-sm text-muted-foreground">
+ Select buckets to ingest.
+ </p>
+ <div className="flex items-center gap-2">
+ {selectedBuckets.size > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setSelectedBuckets(new Set())}
+ >
+ Deselect All
+ </Button>
+ )}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setSelectedBuckets(new Set(buckets?.map((b) => b.name) ?? []))
+ }
+ disabled={isLoading || !buckets?.length}
+ >
+ Select All
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onRefetch}
+ disabled={isLoading}
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? "animate-spin" : ""}
+ />
+ Refresh Buckets
+ </Button>
+ </div>
+ </div>
+
+ {isLoading ? (
+ <div className="flex justify-center py-8">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
+ </div>
+ ) : bucketsError ? (
+ <div className="rounded-lg border border-destructive/50 p-6 text-center text-destructive text-sm">
+ {bucketsError.message ||
+ "Failed to load buckets. Check your credentials and endpoint."}
+ </div>
+ ) : !buckets?.length ? (
+ <div className="rounded-lg border p-6 text-center text-muted-foreground text-sm">
+ No buckets found. Check your credentials and endpoint.
+ </div>
+ ) : (
+ <div className="rounded-lg border divide-y">
+ {buckets.map((bucket) => {
+ const isSelected = selectedBuckets.has(bucket.name);
+ return (
+ <div
+ key={bucket.name}
+ role="checkbox"
+ aria-checked={isSelected}
+ aria-label={bucket.name}
+ tabIndex={0}
+ className="flex items-center gap-[18px] px-4 py-3 cursor-pointer"
+ onClick={() => toggleBucket(bucket.name)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ toggleBucket(bucket.name);
+ }
+ }}
+ >
+ <div
+ className={`shrink-0 size-5 rounded-[6px] border-2 flex items-center justify-center transition-colors ${
+ isSelected
+ ? "bg-foreground border-foreground"
+ : "border-muted-foreground/60"
+ }`}
+ >
+ {isSelected && (
+ <svg
+ viewBox="0 0 12 12"
+ fill="none"
+ className="size-3 text-background"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="2,6 5,9 10,3" />
+ </svg>
+ )}
+ </div>
+ <div className="flex items-center gap-4 flex-1 min-w-0">
+ <div className="bg-white/5 rounded-[10px] shrink-0 size-10 flex items-center justify-center">
+ <FolderOpen size={20} className="text-muted-foreground" />
+ </div>
+ <div className="flex flex-col gap-1 min-w-0">
+ <p className="font-medium text-sm leading-6">
+ {bucket.name}
+ </p>
+ {bucket.ingested_count > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {bucket.ingested_count} document
+ {bucket.ingested_count !== 1 ? "s" : ""} ingested
+ </p>
+ )}
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ setBrowseDialogBucket(bucket.name);
+ }}
+ >
+ <FileSearch size={14} className="mr-1.5" />
+ Browse Files
+ </Button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ <IngestSettings
+ isOpen={isSettingsOpen}
+ onOpenChange={setIsSettingsOpen}
+ settings={ingestSettings}
+ onSettingsChange={setIngestSettings}
+ />
+ </div>
+
+ <div className="max-w-3xl mx-auto mt-6 sticky bottom-0 left-0 right-0 pb-6 bg-background pt-4">
+ <div className="flex justify-between gap-3">
+ <Button
+ variant="ghost"
+ className="border bg-transparent border-border rounded-lg text-secondary-foreground"
+ onClick={onBack}
+ >
+ Back
+ </Button>
+ <Button
+ className="bg-foreground text-background hover:bg-foreground/90 font-semibold"
+ onClick={ingestSelected}
+ disabled={syncMutation.isPending || selectedBuckets.size === 0}
+ loading={syncMutation.isPending}
+ >
+ {syncMutation.isPending
+ ? "Ingesting…"
+ : selectedBuckets.size > 0
+ ? `Ingest ${selectedBuckets.size} Bucket${selectedBuckets.size !== 1 ? "s" : ""}`
+ : "Select Buckets to Ingest"}
+ </Button>
+ </div>
+ </div>
+
+ {connector.connectionId && browseDialogBucket && (
+ <FileBrowserDialog
+ open
+ onOpenChange={(open) => {
+ if (!open) setBrowseDialogBucket(null);
+ }}
+ connectorType={connector.type}
+ connectionId={connector.connectionId}
+ buckets={[browseDialogBucket]}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsx
index 687c8eef5..c8338e8de 100644
--- a/frontend/components/knowledge-dropdown.tsx
+++ b/frontend/components/knowledge-dropdown.tsx
@@ -15,11 +15,6 @@ import { toast } from "sonner";
import type { File as SearchFile } from "@/app/api/queries/useGetSearchQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
import { DuplicateHandlingDialog } from "@/components/duplicate-handling-dialog";
-import AwsIcon from "@/components/icons/aws-logo";
-import GoogleDriveIcon from "@/components/icons/google-drive-logo";
-import IBMCOSIcon from "@/components/icons/ibm-cos-icon";
-import OneDriveIcon from "@/components/icons/one-drive-logo";
-import SharePointIcon from "@/components/icons/share-point-logo";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -40,6 +35,10 @@ import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useTask } from "@/contexts/task-context";
import { usePermissions } from "@/hooks/use-permissions";
+import {
+ getConnectorDescriptor,
+ getConnectorDescriptors,
+} from "@/lib/connectors/registry";
import {
duplicateCheck,
uploadFiles,
@@ -135,8 +134,9 @@ export function KnowledgeDropdown() {
const [folderLoading, setFolderLoading] = useState(false);
const [fileUploading, setFileUploading] = useState(false);
const [isNavigatingToCloud, setIsNavigatingToCloud] = useState(false);
- const [ibmCosConfigured, setIbmCosConfigured] = useState(false);
- const [s3Configured, setS3Configured] = useState(false);
+ const [bucketConnectorConfigured, setBucketConnectorConfigured] = useState<
+ Record<string, boolean>
+ >({});
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [duplicateFilename, setDuplicateFilename] = useState<string>("");
const [pendingFolderUpload, setPendingFolderUpload] = useState<{
@@ -167,11 +167,16 @@ export function KnowledgeDropdown() {
useEffect(() => {
const checkAvailability = async () => {
try {
+ const bucketDescriptors = getConnectorDescriptors().filter(
+ (d) => d.kind === "bucket",
+ );
+
// Check upload batch size and bucket connector availability in parallel
- const [uploadOptionsRes, ibmCosRes, s3Res] = await Promise.all([
+ const [uploadOptionsRes, ...bucketResponses] = await Promise.all([
fetch("/api/upload_options"),
- fetch("/api/connectors/ibm_cos/defaults"),
- fetch("/api/connectors/aws_s3/defaults"),
+ ...bucketDescriptors.map((d) =>
+ fetch(`/api/connectors/${d.connectorType}/defaults`),
+ ),
]);
if (uploadOptionsRes.ok) {
@@ -184,23 +189,22 @@ export function KnowledgeDropdown() {
}
}
- if (ibmCosRes.ok) {
- const ibmCosData = await ibmCosRes.json();
- setIbmCosConfigured(
- Boolean(
- ibmCosData.connection_id ||
- ibmCosData.api_key_set ||
- ibmCosData.hmac_access_key_set,
- ),
- );
- }
-
- if (s3Res.ok) {
- const s3Data = await s3Res.json();
- setS3Configured(
- Boolean(s3Data.connection_id || s3Data.access_key_set),
- );
- }
+ const configured: Record<string, boolean> = {};
+ await Promise.all(
+ bucketResponses.map(async (res, i) => {
+ const descriptor = bucketDescriptors[i];
+ if (!res.ok) return;
+ const data = await res.json();
+ // Generic predicate: connection_id set OR any *_set boolean is true.
+ const anySetFlag = Object.entries(data).some(
+ ([k, v]) => k.endsWith("_set") && v === true,
+ );
+ configured[descriptor.connectorType] = Boolean(
+ data.connection_id || anySetFlag,
+ );
+ }),
+ );
+ setBucketConnectorConfigured(configured);
// Check cloud connectors
const connectorsRes = await fetch("/api/connectors");
@@ -615,38 +619,48 @@ export function KnowledgeDropdown() {
}
};
- // Icon mapping for cloud connectors
- const connectorIconMap = {
- google_drive: GoogleDriveIcon,
- onedrive: OneDriveIcon,
- sharepoint: SharePointIcon,
- };
-
const cloudConnectorItems = Object.entries(cloudConnectors)
.filter(([type, info]) => {
if (!info.available) return false;
if (isCloudBrand && type === "onedrive") return false;
return true;
})
- .map(([type, info]) => ({
- label: info.name,
- icon: connectorIconMap[type as keyof typeof connectorIconMap] || PlugZap,
- onClick: async () => {
- if (info.connected && info.hasToken) {
- setIsNavigatingToCloud(true);
- try {
- router.push(`/upload/${type}`);
- // Keep loading state for a short time to show feedback
- setTimeout(() => setIsNavigatingToCloud(false), 1000);
- } catch {
- setIsNavigatingToCloud(false);
+ .map(([type, info]) => {
+ const descriptor = getConnectorDescriptor(type);
+ return {
+ label: info.name,
+ icon: descriptor?.Icon ?? PlugZap,
+ onClick: async () => {
+ if (info.connected && info.hasToken) {
+ setIsNavigatingToCloud(true);
+ try {
+ router.push(`/upload/${type}`);
+ setTimeout(() => setIsNavigatingToCloud(false), 1000);
+ } catch {
+ setIsNavigatingToCloud(false);
+ }
+ } else {
+ router.push("/settings");
}
- } else {
- router.push("/settings");
- }
- },
- disabled: !info.connected || !info.hasToken,
- }));
+ },
+ disabled: !info.connected || !info.hasToken,
+ };
+ });
+
+ const bucketConnectorItems = isIbmAuthMode
+ ? getConnectorDescriptors()
+ .filter(
+ (d) =>
+ d.kind === "bucket" &&
+ d.menuItem &&
+ bucketConnectorConfigured[d.connectorType],
+ )
+ .map((d) => ({
+ label: d.menuItem!.label,
+ icon: d.Icon,
+ onClick: () => router.push(d.menuItem!.route),
+ }))
+ : [];
const menuItems = [
{
@@ -659,24 +673,7 @@ export function KnowledgeDropdown() {
icon: FolderIconWithColor,
onClick: () => folderInputRef.current?.click(),
},
- ...(isIbmAuthMode && s3Configured
- ? [
- {
- label: "Amazon S3",
- icon: AwsIcon,
- onClick: () => router.push("/upload/aws_s3"),
- },
- ]
- : []),
- ...(isIbmAuthMode && ibmCosConfigured
- ? [
- {
- label: "IBM Cloud Object Storage",
- icon: IBMCOSIcon,
- onClick: () => router.push("/upload/ibm_cos"),
- },
- ]
- : []),
+ ...bucketConnectorItems,
...cloudConnectorItems,
];
diff --git a/frontend/components/sync-confirm-dialog.tsx b/frontend/components/sync-confirm-dialog.tsx
index b3124d65b..fa36c229d 100644
--- a/frontend/components/sync-confirm-dialog.tsx
+++ b/frontend/components/sync-confirm-dialog.tsx
@@ -3,7 +3,9 @@
import { AlertTriangle, Check, Loader2, RefreshCw, Trash2 } from "lucide-react";
import type React from "react";
import type { OrphanFile } from "@/app/api/mutations/useSyncConnector";
+import { getConnectorLabel } from "@/lib/connectors/registry";
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
+import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import {
Dialog,
@@ -16,16 +18,8 @@ import {
import { ScrollArea } from "./ui/scroll-area";
import { Separator } from "./ui/separator";
-const CONNECTOR_DISPLAY_NAMES: Record<string, string> = {
- google_drive: "Google Drive",
- onedrive: "OneDrive",
- sharepoint: "SharePoint",
- ibm_cos: "IBM Cloud Object Storage",
- aws_s3: "Amazon S3",
-};
-
const formatConnectorLabel = (type: string): string =>
- CONNECTOR_DISPLAY_NAMES[type] ?? type;
+ getConnectorLabel(type) ?? type;
const pluralize = (n: number, singular: string, plural?: string): string =>
`${n} ${n === 1 ? singular : (plural ?? `${singular}s`)}`;
diff --git a/frontend/enhancements/connectors/ibm-cos/components/bucket-view.tsx b/frontend/enhancements/connectors/ibm-cos/components/bucket-view.tsx
new file mode 100644
index 000000000..11b3922fc
--- /dev/null
+++ b/frontend/enhancements/connectors/ibm-cos/components/bucket-view.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+import type { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
+import { SharedBucketView } from "@/components/connectors/shared-bucket-view";
+import { useIBMCOSBucketStatusQuery } from "../useIBMCOSBucketStatusQuery";
+
+export interface IBMCOSBucketViewProps {
+ connector: any;
+ syncMutation: ReturnType<typeof useSyncConnector>;
+ addTask: (id: string) => void;
+ onBack: () => void;
+ onDone: () => void;
+}
+
+export function IBMCOSBucketView({
+ connector,
+ syncMutation,
+ addTask,
+ onBack,
+ onDone,
+}: IBMCOSBucketViewProps) {
+ const {
+ data: buckets,
+ isLoading,
+ error: bucketsError,
+ refetch,
+ } = useIBMCOSBucketStatusQuery(connector.connectionId, { enabled: true });
+ return (
+ <SharedBucketView
+ connector={connector}
+ buckets={buckets}
+ isLoading={isLoading}
+ bucketsError={bucketsError as Error | null}
+ onRefetch={refetch}
+ invalidateQueryKey={["ibm-cos-bucket-status", connector.connectionId]}
+ syncMutation={syncMutation}
+ addTask={addTask}
+ onBack={onBack}
+ onDone={onDone}
+ />
+ );
+}
diff --git a/frontend/components/icons/ibm-cos-icon.tsx b/frontend/enhancements/connectors/ibm-cos/icon.tsx
similarity index 100%
rename from frontend/components/icons/ibm-cos-icon.tsx
rename to frontend/enhancements/connectors/ibm-cos/icon.tsx
diff --git a/frontend/app/settings/_components/ibm-cos-settings-dialog.tsx b/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
similarity index 95%
rename from frontend/app/settings/_components/ibm-cos-settings-dialog.tsx
rename to frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
index fcae96f5d..2dd31dcf9 100644
--- a/frontend/app/settings/_components/ibm-cos-settings-dialog.tsx
+++ b/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
@@ -4,9 +4,6 @@ import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
-import { useIBMCOSConfigureMutation } from "@/app/api/mutations/useIBMCOSConfigureMutation";
-import { useIBMCOSDefaultsQuery } from "@/app/api/queries/useIBMCOSDefaultsQuery";
-import IBMCOSIcon from "@/components/icons/ibm-cos-icon";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -15,10 +12,10 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import {
- type IBMCOSFormData,
- IBMCOSSettingsForm,
-} from "./ibm-cos-settings-form";
+import IBMCOSIcon from "./icon";
+import { type IBMCOSFormData, IBMCOSSettingsForm } from "./settings-form";
+import { useIBMCOSConfigureMutation } from "./useIBMCOSConfigureMutation";
+import { useIBMCOSDefaultsQuery } from "./useIBMCOSDefaultsQuery";
interface IBMCOSSettingsDialogProps {
open: boolean;
diff --git a/frontend/app/settings/_components/ibm-cos-settings-form.tsx b/frontend/enhancements/connectors/ibm-cos/settings-form.tsx
similarity index 100%
rename from frontend/app/settings/_components/ibm-cos-settings-form.tsx
rename to frontend/enhancements/connectors/ibm-cos/settings-form.tsx
diff --git a/frontend/app/api/queries/useIBMCOSBucketStatusQuery.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts
similarity index 100%
rename from frontend/app/api/queries/useIBMCOSBucketStatusQuery.ts
rename to frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts
diff --git a/frontend/app/api/queries/useIBMCOSBucketsQuery.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketsQuery.ts
similarity index 100%
rename from frontend/app/api/queries/useIBMCOSBucketsQuery.ts
rename to frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketsQuery.ts
diff --git a/frontend/app/api/mutations/useIBMCOSConfigureMutation.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts
similarity index 100%
rename from frontend/app/api/mutations/useIBMCOSConfigureMutation.ts
rename to frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts
diff --git a/frontend/app/api/queries/useIBMCOSDefaultsQuery.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts
similarity index 100%
rename from frontend/app/api/queries/useIBMCOSDefaultsQuery.ts
rename to frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts
diff --git a/frontend/enhancements/index.ts b/frontend/enhancements/index.ts
new file mode 100644
index 000000000..80e637626
--- /dev/null
+++ b/frontend/enhancements/index.ts
@@ -0,0 +1,26 @@
+import type { ConnectorUIDescriptor } from "@/lib/connectors/types";
+import { IBMCOSBucketView } from "./connectors/ibm-cos/components/bucket-view";
+import IBMCOSIcon from "./connectors/ibm-cos/icon";
+import IBMCOSSettingsDialog from "./connectors/ibm-cos/settings-dialog";
+import { useIBMCOSDefaultsQuery } from "./connectors/ibm-cos/useIBMCOSDefaultsQuery";
+
+/**
+ * Connector descriptors layered on top of the OSS builtins.
+ *
+ * Downstream builds (e.g. SaaS) overlay this file via the
+ * `git checkout --ours enhancements/ frontend/enhancements/` merge strategy.
+ * The OSS variant of this file ships with IBM COS registered; strip the
+ * imports and reset the array to `[]` for a bare OSS build.
+ */
+export const ADDITIONAL_CONNECTORS: ConnectorUIDescriptor[] = [
+ {
+ connectorType: "ibm_cos",
+ name: "IBM Cloud Object Storage",
+ Icon: IBMCOSIcon,
+ kind: "bucket",
+ SettingsDialog: IBMCOSSettingsDialog,
+ BucketView: IBMCOSBucketView,
+ useDefaultsQuery: useIBMCOSDefaultsQuery,
+ menuItem: { label: "IBM Cloud Object Storage", route: "/upload/ibm_cos" },
+ },
+];
diff --git a/frontend/lib/connectors/registry.ts b/frontend/lib/connectors/registry.ts
new file mode 100644
index 000000000..facc29144
--- /dev/null
+++ b/frontend/lib/connectors/registry.ts
@@ -0,0 +1,62 @@
+import { useS3DefaultsQuery } from "@/app/api/queries/useS3DefaultsQuery";
+import S3SettingsDialog from "@/app/settings/_components/s3-settings-dialog";
+import { S3BucketView } from "@/components/connectors/aws-s3/bucket-view";
+import AwsLogo from "@/components/icons/aws-logo";
+import GoogleDriveLogo from "@/components/icons/google-drive-logo";
+import OneDriveLogo from "@/components/icons/one-drive-logo";
+import SharePointLogo from "@/components/icons/share-point-logo";
+import { ADDITIONAL_CONNECTORS } from "@/enhancements";
+import type { ConnectorUIDescriptor } from "./types";
+
+const BUILTIN_CONNECTORS: ConnectorUIDescriptor[] = [
+ {
+ connectorType: "google_drive",
+ name: "Google Drive",
+ Icon: GoogleDriveLogo,
+ kind: "oauth",
+ menuItem: { label: "Google Drive", route: "/upload/google_drive" },
+ },
+ {
+ connectorType: "onedrive",
+ name: "OneDrive",
+ Icon: OneDriveLogo,
+ kind: "oauth",
+ menuItem: { label: "OneDrive", route: "/upload/onedrive" },
+ },
+ {
+ connectorType: "sharepoint",
+ name: "SharePoint",
+ Icon: SharePointLogo,
+ kind: "oauth",
+ menuItem: { label: "SharePoint", route: "/upload/sharepoint" },
+ },
+ {
+ connectorType: "aws_s3",
+ name: "Amazon S3",
+ Icon: AwsLogo,
+ kind: "bucket",
+ SettingsDialog: S3SettingsDialog,
+ BucketView: S3BucketView,
+ useDefaultsQuery: useS3DefaultsQuery,
+ menuItem: { label: "Amazon S3", route: "/upload/aws_s3" },
+ },
+];
+
+const ALL_CONNECTORS: ConnectorUIDescriptor[] = [
+ ...BUILTIN_CONNECTORS,
+ ...ADDITIONAL_CONNECTORS,
+];
+
+export function getConnectorDescriptors(): ConnectorUIDescriptor[] {
+ return ALL_CONNECTORS;
+}
+
+export function getConnectorDescriptor(
+ connectorType: string,
+): ConnectorUIDescriptor | undefined {
+ return ALL_CONNECTORS.find((d) => d.connectorType === connectorType);
+}
+
+export function getConnectorLabel(connectorType: string): string | undefined {
+ return getConnectorDescriptor(connectorType)?.name;
+}
diff --git a/frontend/lib/connectors/types.ts b/frontend/lib/connectors/types.ts
new file mode 100644
index 000000000..fe639b580
--- /dev/null
+++ b/frontend/lib/connectors/types.ts
@@ -0,0 +1,61 @@
+import type { UseQueryResult } from "@tanstack/react-query";
+import type { ComponentType } from "react";
+import type { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
+
+export type ConnectorKind = "oauth" | "bucket";
+
+export interface ConnectorIconProps {
+ className?: string;
+}
+
+export interface ConnectorSettingsDialogProps {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+}
+
+export interface ConnectorBucketViewProps {
+ // Loosely typed to match the existing connector shape from useGetConnectorsQuery.
+ connector: any;
+ syncMutation: ReturnType<typeof useSyncConnector>;
+ addTask: (id: string) => void;
+ onBack: () => void;
+ onDone: () => void;
+}
+
+export interface ConnectorMenuItem {
+ label: string;
+ route: string;
+}
+
+/**
+ * Static description of a connector's UI surface. The registry combines
+ * builtin descriptors with whatever lives in `frontend/enhancements/`, and
+ * shared components consume the merged list instead of hard-coding per-type
+ * branches.
+ *
+ * The optional fields are hook points: a connector only fills in the ones
+ * it actually needs (e.g. only bucket connectors set `BucketView`).
+ */
+export interface ConnectorUIDescriptor {
+ /** Matches the backend connector_type string (e.g. "google_drive"). */
+ connectorType: string;
+ /** Human-readable label used in dialogs, dropdowns, etc. */
+ name: string;
+ /** Icon component rendered next to the name. */
+ Icon: ComponentType<ConnectorIconProps>;
+ /**
+ * Configure-flow shape. "oauth" connectors trigger the OAuth mutation;
+ * "bucket" connectors open a settings dialog and sync entire buckets.
+ */
+ kind: ConnectorKind;
+ /** Modal used to enter credentials for bucket-kind connectors. */
+ SettingsDialog?: ComponentType<ConnectorSettingsDialogProps>;
+ /** Page-level view rendered on /upload/[provider] for bucket connectors. */
+ BucketView?: ComponentType<ConnectorBucketViewProps>;
+ /** Hook returning connector-specific defaults (server-side env presence, etc). */
+ useDefaultsQuery?: (options?: {
+ enabled?: boolean;
+ }) => UseQueryResult<unknown>;
+ /** Entry in the "add knowledge" dropdown. */
+ menuItem?: ConnectorMenuItem;
+}
diff --git a/src/api/connectors.py b/src/api/connectors.py
index 665962d87..3babd660c 100644
--- a/src/api/connectors.py
+++ b/src/api/connectors.py
@@ -335,9 +335,9 @@ class ConnectorSyncBody(BaseModel):
max_files: int | None = None
selected_files: list[Any] | None = None
# When True, ingest ALL files from the connector (bypasses the existing-files gate).
- # Used by direct-sync providers on initial ingest.
+ # Used by bucket-kind connectors on initial ingest.
sync_all: bool = False
- # When set, only ingest files from these buckets.
+ # When set, only ingest files from these buckets (bucket-kind connectors).
bucket_filter: list[str] | None = None
# Per-request ingest options from the connector upload UI (overrides saved Knowledge for this sync).
settings: dict[str, Any] | None = None
@@ -1108,7 +1108,7 @@ async def sync_all_connectors(
jwt_token = user.jwt_token
# Cloud connector types to sync
- cloud_connector_types = ["google_drive", "onedrive", "sharepoint", "ibm_cos", "aws_s3"]
+ cloud_connector_types = _cloud_connector_types()
all_task_ids = []
synced_connectors = []
@@ -1292,7 +1292,10 @@ async def sync_all_connectors(
return JSONResponse({"error": f"Sync failed: {str(e)}"}, status_code=500)
-CLOUD_CONNECTOR_TYPES = ["google_drive", "onedrive", "sharepoint", "ibm_cos", "aws_s3"]
+def _cloud_connector_types() -> list[str]:
+ from connectors.registry import get_connector_classes
+
+ return [cls.CONNECTOR_TYPE for cls in get_connector_classes()]
async def _preview_orphans_for_connector_type(
@@ -1387,7 +1390,7 @@ async def connectors_sync_all_preview(
synced_count_by_type: dict[str, int] = {}
orphans_available_by_type: dict[str, bool] = {}
- for connector_type in CLOUD_CONNECTOR_TYPES:
+ for connector_type in _cloud_connector_types():
try:
orphans, synced_count = await _preview_orphans_for_connector_type(
connector_type=connector_type,
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index 1605f88a1..a9557eafc 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -32,18 +32,7 @@ from api import (
from api import keys as api_keys
from api.health import health_check, opensearch_health_ready
from api.schemas.tasks import ErrorResponse, TaskRetryResponse
-from connectors.aws_s3.api import (
- s3_bucket_status,
- s3_configure,
- s3_defaults,
- s3_list_buckets,
-)
-from connectors.ibm_cos.api import (
- ibm_cos_bucket_status,
- ibm_cos_configure,
- ibm_cos_defaults,
- ibm_cos_list_buckets,
-)
+from connectors.registry import get_connector_classes
def register_internal_routes(app: FastAPI):
@@ -219,53 +208,10 @@ def register_internal_routes(app: FastAPI):
# Connector endpoints
app.add_api_route("/connectors", connectors.list_connectors, methods=["GET"], tags=["internal"])
- # IBM COS-specific routes (registered before generic /{connector_type}/... to avoid shadowing)
- app.add_api_route(
- "/connectors/ibm_cos/defaults",
- ibm_cos_defaults,
- methods=["GET"],
- tags=["internal"],
- )
- app.add_api_route(
- "/connectors/ibm_cos/configure",
- ibm_cos_configure,
- methods=["POST"],
- tags=["internal"],
- )
- app.add_api_route(
- "/connectors/ibm_cos/{connection_id}/buckets",
- ibm_cos_list_buckets,
- methods=["GET"],
- tags=["internal"],
- )
- app.add_api_route(
- "/connectors/ibm_cos/{connection_id}/bucket-status",
- ibm_cos_bucket_status,
- methods=["GET"],
- tags=["internal"],
- )
- # AWS S3-specific routes (registered before generic /{connector_type}/... to avoid shadowing)
- app.add_api_route(
- "/connectors/aws_s3/defaults", s3_defaults, methods=["GET"], tags=["internal"]
- )
- app.add_api_route(
- "/connectors/aws_s3/configure",
- s3_configure,
- methods=["POST"],
- tags=["internal"],
- )
- app.add_api_route(
- "/connectors/aws_s3/{connection_id}/buckets",
- s3_list_buckets,
- methods=["GET"],
- tags=["internal"],
- )
- app.add_api_route(
- "/connectors/aws_s3/{connection_id}/bucket-status",
- s3_bucket_status,
- methods=["GET"],
- tags=["internal"],
- )
+ # Per-connector routes (defaults, configure, bucket listing, etc.) — registered before
+ # the generic /{connector_type}/... routes to avoid path shadowing.
+ for cls in get_connector_classes():
+ cls.register_routes(app)
app.add_api_route(
"/connectors/{connector_type}/sync",
connectors.connector_sync,
diff --git a/src/bootstrap.py b/src/bootstrap.py
index 0e6644fdb..a0e4a7842 100644
--- a/src/bootstrap.py
+++ b/src/bootstrap.py
@@ -1,9 +1,18 @@
+import sys
from pathlib import Path
+
from dotenv import load_dotenv
# This module is intended to be imported as the first line in entry points
# to ensure environment variables and logging are available to all subsequent imports.
+# Make the repo root importable so the top-level `enhancements/` package is
+# discoverable alongside `src/`. Safe to no-op when the path is already present.
+_REPO_ROOT = str(Path(__file__).parent.parent)
+if _REPO_ROOT not in sys.path:
+ sys.path.insert(0, _REPO_ROOT)
+
+
def load_env():
"""Load .env then immediately configure structured logging so all subsequent
module-level log calls use the correct formatter and processors."""
@@ -13,11 +22,14 @@ def load_env():
# Configure logging immediately after env vars are available so every
# subsequent import gets a properly configured logger.
from utils.logging_config import configure_from_env
+
configure_from_env()
+
# Execute immediately on import
load_env()
from utils.logging_config import get_logger # noqa: E402 — after configure_from_env
+
logger = get_logger(__name__)
logger.info("Application startup span: environment loaded")
diff --git a/src/connectors/__init__.py b/src/connectors/__init__.py
index 323a76285..da461e1e2 100644
--- a/src/connectors/__init__.py
+++ b/src/connectors/__init__.py
@@ -1,15 +1,13 @@
+from .aws_s3 import S3Connector
from .base import BaseConnector
from .google_drive import GoogleDriveConnector
-from .sharepoint import SharePointConnector
from .onedrive import OneDriveConnector
-from .ibm_cos import IBMCOSConnector
-from .aws_s3 import S3Connector
+from .sharepoint import SharePointConnector
__all__ = [
"BaseConnector",
"GoogleDriveConnector",
"SharePointConnector",
"OneDriveConnector",
- "IBMCOSConnector",
"S3Connector",
]
diff --git a/src/connectors/aws_s3/connector.py b/src/connectors/aws_s3/connector.py
index 13929e41b..12377d2b5 100644
--- a/src/connectors/aws_s3/connector.py
+++ b/src/connectors/aws_s3/connector.py
@@ -2,10 +2,11 @@
import mimetypes
import os
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from posixpath import basename
-from typing import Any, Dict, List, Optional
+from typing import Any
+from config.settings import IBM_AUTH_ENABLED
from connectors.base import BaseConnector, ConnectorDocument, DocumentACL
from utils.logging_config import get_logger
@@ -44,13 +45,45 @@ class S3Connector(BaseConnector):
connection_id (str): Connection identifier used for logging.
"""
+ CONNECTOR_TYPE = "aws_s3"
+ CONNECTOR_KIND = "bucket"
CONNECTOR_NAME = "Amazon S3"
CONNECTOR_DESCRIPTION = "Add knowledge from Amazon S3 or any S3-compatible storage"
CONNECTOR_ICON = "aws-s3"
+ SECRET_CONFIG_KEYS = ("aws_secret_access_key",)
CLIENT_ID_ENV_VAR = "AWS_ACCESS_KEY_ID"
CLIENT_SECRET_ENV_VAR = "AWS_SECRET_ACCESS_KEY"
+ @classmethod
+ def is_available(cls, manager, user_id=None) -> bool:
+ # Gated by feature flag in OSS; SaaS / enterprise can flip it on.
+ return IBM_AUTH_ENABLED
+
+ @classmethod
+ def register_routes(cls, app) -> None:
+ from .api import s3_bucket_status, s3_configure, s3_defaults, s3_list_buckets
+
+ # Registered before generic /{connector_type}/... to avoid shadowing.
+ app.add_api_route(
+ "/connectors/aws_s3/defaults", s3_defaults, methods=["GET"], tags=["internal"]
+ )
+ app.add_api_route(
+ "/connectors/aws_s3/configure", s3_configure, methods=["POST"], tags=["internal"]
+ )
+ app.add_api_route(
+ "/connectors/aws_s3/{connection_id}/buckets",
+ s3_list_buckets,
+ methods=["GET"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/connectors/aws_s3/{connection_id}/bucket-status",
+ s3_bucket_status,
+ methods=["GET"],
+ tags=["internal"],
+ )
+
def get_client_id(self) -> str:
"""Return access key from config dict, or AWS_ACCESS_KEY_ID env var as fallback."""
val = self.config.get("access_key") or os.getenv("AWS_ACCESS_KEY_ID")
@@ -71,12 +104,12 @@ class S3Connector(BaseConnector):
"or set the AWS_SECRET_ACCESS_KEY environment variable."
)
- def __init__(self, config: Dict[str, Any]):
+ def __init__(self, config: dict[str, Any]):
if config is None:
config = {}
super().__init__(config)
- self.bucket_names: List[str] = config.get("bucket_names") or []
+ self.bucket_names: list[str] = config.get("bucket_names") or []
self.prefix: str = config.get("prefix", "")
self.connection_id: str = config.get("connection_id", "default")
@@ -110,7 +143,7 @@ class S3Connector(BaseConnector):
self._authenticated = False
return False
- def _resolve_bucket_names(self) -> List[str]:
+ def _resolve_bucket_names(self) -> list[str]:
"""Return configured bucket names, or auto-discover all accessible buckets."""
if self.bucket_names:
return self.bucket_names
@@ -125,10 +158,10 @@ class S3Connector(BaseConnector):
async def list_files(
self,
- page_token: Optional[str] = None,
- max_files: Optional[int] = None,
+ page_token: str | None = None,
+ max_files: int | None = None,
**kwargs,
- ) -> Dict[str, Any]:
+ ) -> dict[str, Any]:
"""List objects across all configured (or auto-discovered) buckets.
Uses the boto3 resource API: Bucket.objects.all() handles pagination
@@ -140,7 +173,7 @@ class S3Connector(BaseConnector):
"next_page_token": always None (SDK handles pagination internally)
"""
resource = self._get_resource()
- files: List[Dict[str, Any]] = []
+ files: list[dict[str, Any]] = []
bucket_names = self._resolve_bucket_names()
for bucket_name in bucket_names:
@@ -189,7 +222,7 @@ class S3Connector(BaseConnector):
response = resource.Object(bucket_name, key).get()
content: bytes = response["Body"].read()
- last_modified: datetime = response.get("LastModified") or datetime.now(timezone.utc)
+ last_modified: datetime = response.get("LastModified") or datetime.now(UTC)
size: int = response.get("ContentLength", len(content))
# Prefer filename extension over generic S3 content-type (often application/octet-stream)
@@ -233,7 +266,7 @@ class S3Connector(BaseConnector):
or ""
)
- allowed_users: List[str] = []
+ allowed_users: list[str] = []
for grant in acl_response.get("Grants", []):
grantee = grant.get("Grantee", {})
permission = grant.get("Permission", "")
@@ -263,13 +296,13 @@ class S3Connector(BaseConnector):
"""No-op: S3 event notifications are out of scope for this connector."""
return ""
- async def handle_webhook(self, payload: Dict[str, Any]) -> List[str]:
+ async def handle_webhook(self, payload: dict[str, Any]) -> list[str]:
"""No-op: webhooks are not supported in this connector version."""
return []
def extract_webhook_channel_id(
- self, payload: Dict[str, Any], headers: Dict[str, str]
- ) -> Optional[str]:
+ self, payload: dict[str, Any], headers: dict[str, str]
+ ) -> str | None:
return None
async def cleanup_subscription(self, subscription_id: str) -> bool:
diff --git a/src/connectors/base.py b/src/connectors/base.py
index 492dd6208..4fb79f19a 100644
--- a/src/connectors/base.py
+++ b/src/connectors/base.py
@@ -52,6 +52,14 @@ class BaseConnector(ABC):
CLIENT_ID_ENV_VAR: str = None
CLIENT_SECRET_ENV_VAR: str = None
+ # Stable identifier used in connections.json and on the wire (e.g. "google_drive").
+ CONNECTOR_TYPE: str = None
+ # "oauth" connectors authenticate per-user via OAuth env-var credentials.
+ # "bucket" connectors authenticate via per-connection config dict (HMAC, API key, etc).
+ CONNECTOR_KIND: str = "oauth"
+ # Connector-specific keys in the config dict that must be encrypted at rest.
+ SECRET_CONFIG_KEYS: tuple = ()
+
# Connector metadata for UI
CONNECTOR_NAME: str = None
CONNECTOR_DESCRIPTION: str = None
@@ -61,6 +69,31 @@ class BaseConnector(ABC):
self.config = config
self._authenticated = False
+ @classmethod
+ def register_routes(cls, app) -> None:
+ """Register connector-specific FastAPI routes on the given app.
+
+ Default: no-op. Connectors with extra endpoints (bucket listing,
+ credential configuration, etc.) should override this and add their
+ own `app.add_api_route(...)` calls.
+ """
+ return None
+
+ @classmethod
+ def is_available(cls, manager, user_id: str | None = None) -> bool:
+ """Whether this connector should be offered to the given user.
+
+ Default (oauth-kind): env credentials present OR user has a saved connection.
+ Bucket-kind connectors should override to gate on their own feature flag.
+ """
+ try:
+ instance = cls({})
+ instance.get_client_id()
+ instance.get_client_secret()
+ return True
+ except (ValueError, NotImplementedError, RuntimeError):
+ return manager._has_saved_credentials_for_user(cls.CONNECTOR_TYPE, user_id)
+
def get_client_id(self) -> str:
"""Get the OAuth client ID from environment variable"""
if not self.CLIENT_ID_ENV_VAR:
diff --git a/src/connectors/connection_manager.py b/src/connectors/connection_manager.py
index fcc127bcb..a087eb1e6 100644
--- a/src/connectors/connection_manager.py
+++ b/src/connectors/connection_manager.py
@@ -10,12 +10,8 @@ import aiofiles
from utils.logging_config import get_logger
-from .aws_s3 import S3Connector
from .base import BaseConnector
-from .google_drive import GoogleDriveConnector
-from .ibm_cos import IBMCOSConnector
-from .onedrive import OneDriveConnector
-from .sharepoint import SharePointConnector
+from .registry import get_all_secret_keys, get_connector_class, get_connector_classes
logger = get_logger(__name__)
@@ -58,20 +54,7 @@ class ConnectionManager:
needs_encryption_upgrade = False
decryption_failed = False
- secret_keys = {
- "api_key",
- "hmac_secret_key",
- "secret_key",
- "client_secret",
- "aws_secret_access_key",
- "ibm_api_key",
- "access_token",
- "refresh_token",
- "access_key",
- "hmac_access_key",
- "service_instance_id",
- "basic_credentials",
- }
+ secret_keys = get_all_secret_keys()
if self.connections_file.exists():
async with aiofiles.open(self.connections_file) as f:
@@ -124,20 +107,7 @@ class ConnectionManager:
"""Save connections to persistent storage"""
from utils.encryption import encrypt_secret
- secret_keys = {
- "api_key",
- "hmac_secret_key",
- "secret_key",
- "client_secret",
- "aws_secret_access_key",
- "ibm_api_key",
- "access_token",
- "refresh_token",
- "access_key",
- "hmac_access_key",
- "service_instance_id",
- "basic_credentials",
- }
+ secret_keys = get_all_secret_keys()
data = {"connections": []}
@@ -447,56 +417,26 @@ class ConnectionManager:
) -> dict[str, dict[str, Any]]:
"""Get available connector types with their metadata.
- Availability is user-scoped when ``user_id`` is provided:
- a connector is considered available if either:
- 1) its required env credentials are present, or
- 2) the user has an active saved connection with usable credentials.
+ Each connector class decides its own availability via `is_available`.
+ OAuth connectors default to "env credentials present OR user has a saved
+ connection"; bucket-kind connectors gate on their own feature flag.
"""
- return {
- "google_drive": {
- "name": GoogleDriveConnector.CONNECTOR_NAME,
- "description": GoogleDriveConnector.CONNECTOR_DESCRIPTION,
- "icon": GoogleDriveConnector.CONNECTOR_ICON,
- "available": self._is_connector_available("google_drive", user_id),
- },
- "sharepoint": {
- "name": SharePointConnector.CONNECTOR_NAME,
- "description": SharePointConnector.CONNECTOR_DESCRIPTION,
- "icon": SharePointConnector.CONNECTOR_ICON,
- "available": self._is_connector_available("sharepoint", user_id),
- },
- "onedrive": {
- "name": OneDriveConnector.CONNECTOR_NAME,
- "description": OneDriveConnector.CONNECTOR_DESCRIPTION,
- "icon": OneDriveConnector.CONNECTOR_ICON,
- "available": self._is_connector_available("onedrive", user_id),
- },
- "ibm_cos": {
- "name": IBMCOSConnector.CONNECTOR_NAME,
- "description": IBMCOSConnector.CONNECTOR_DESCRIPTION,
- "icon": IBMCOSConnector.CONNECTOR_ICON,
- "available": os.environ.get("IBM_AUTH_ENABLED", "").lower() in ("1", "true", "yes"),
- },
- "aws_s3": {
- "name": S3Connector.CONNECTOR_NAME,
- "description": S3Connector.CONNECTOR_DESCRIPTION,
- "icon": S3Connector.CONNECTOR_ICON,
- "available": os.environ.get("IBM_AUTH_ENABLED", "").lower() in ("1", "true", "yes"),
- },
- }
+ result: dict[str, dict[str, Any]] = {}
+ for cls in get_connector_classes():
+ result[cls.CONNECTOR_TYPE] = {
+ "name": cls.CONNECTOR_NAME,
+ "description": cls.CONNECTOR_DESCRIPTION,
+ "icon": cls.CONNECTOR_ICON,
+ "available": cls.is_available(self, user_id),
+ }
+ return result
def get_auth_user_principals(self, user: Any) -> list[str]:
"""Return connector ACL principals derivable from the OpenRAG auth user."""
from utils.group_acl import unique_acl_principals
principals: list[str] = []
- for connector_cls in (
- GoogleDriveConnector,
- SharePointConnector,
- OneDriveConnector,
- IBMCOSConnector,
- S3Connector,
- ):
+ for connector_cls in get_connector_classes():
try:
principals.extend(connector_cls.get_auth_user_principals(user) or [])
except Exception as e:
@@ -523,46 +463,15 @@ class ConnectionManager:
continue
return False
- def _is_connector_available(self, connector_type: str, user_id: str | None = None) -> bool:
- """Check whether connector is available for use by the given user."""
- try:
- temp_config = ConnectionConfig(
- connection_id="temp",
- connector_type=connector_type,
- name="temp",
- config={},
- )
- connector = self._create_connector(temp_config)
- # Try to get credentials to check if env vars are set
- connector.get_client_id()
- connector.get_client_secret()
- return True
- except (ValueError, NotImplementedError, RuntimeError):
- # Fallback: saved per-user connection config (e.g. aws_s3 / ibm_cos)
- return self._has_saved_credentials_for_user(connector_type, user_id)
-
def _create_connector(self, config: ConnectionConfig) -> BaseConnector:
- """Factory method to create connector instances"""
+ """Factory method to create connector instances via the registry."""
try:
- if config.connector_type == "google_drive":
- return GoogleDriveConnector(config.config)
- elif config.connector_type == "sharepoint":
- return SharePointConnector(config.config)
- elif config.connector_type == "onedrive":
- return OneDriveConnector(config.config)
- elif config.connector_type == "ibm_cos":
- return IBMCOSConnector(config.config)
- elif config.connector_type == "aws_s3":
- return S3Connector(config.config)
- elif config.connector_type == "box":
- raise NotImplementedError("Box connector not implemented yet")
- elif config.connector_type == "dropbox":
- raise NotImplementedError("Dropbox connector not implemented yet")
- else:
+ cls = get_connector_class(config.connector_type)
+ if cls is None:
raise ValueError(f"Unknown connector type: {config.connector_type}")
+ return cls(config.config)
except Exception as e:
logger.error(f"Failed to create {config.connector_type} connector: {e}")
- # Re-raise the exception so caller can handle appropriately
raise
async def update_last_sync(self, connection_id: str):
diff --git a/src/connectors/google_drive/connector.py b/src/connectors/google_drive/connector.py
index a438558d3..75126ff89 100644
--- a/src/connectors/google_drive/connector.py
+++ b/src/connectors/google_drive/connector.py
@@ -83,10 +83,18 @@ class GoogleDriveConnector(BaseConnector):
CLIENT_SECRET_ENV_VAR: str = "GOOGLE_OAUTH_CLIENT_SECRET"
# Connector metadata
+ CONNECTOR_TYPE = "google_drive"
+ CONNECTOR_KIND = "oauth"
CONNECTOR_NAME = "Google Drive"
CONNECTOR_DESCRIPTION = "Add knowledge from Google Drive"
CONNECTOR_ICON = "google-drive"
+ @classmethod
+ def get_oauth_class(cls):
+ from .oauth import GoogleDriveOAuth
+
+ return GoogleDriveOAuth
+
# Supported alias keys coming from various frontends / pickers
_FILE_ID_ALIASES = ("file_ids", "selected_file_ids", "selected_files")
_FOLDER_ID_ALIASES = ("folder_ids", "selected_folder_ids", "selected_folders")
@@ -395,7 +403,7 @@ class GoogleDriveConnector(BaseConnector):
)
for fid in self.cfg.file_ids:
meta = self._get_file_meta_by_id(fid)
- if not meta or meta.get("trashed"):
+ if not meta:
logger.debug(
"[GoogleDrive] _iter_selected_items: no metadata for file_id=%s", fid
)
diff --git a/src/connectors/ibm_cos/models.py b/src/connectors/ibm_cos/models.py
deleted file mode 100644
index 59f2324f9..000000000
--- a/src/connectors/ibm_cos/models.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""Pydantic request/response models for IBM COS API endpoints."""
-
-from typing import List, Optional
-from pydantic import BaseModel
-
-
-class IBMCOSConfigureBody(BaseModel):
- auth_mode: str # "iam" or "hmac"
- endpoint: str
- # IAM fields
- api_key: Optional[str] = None
- service_instance_id: Optional[str] = None
- auth_endpoint: Optional[str] = None
- # HMAC fields
- hmac_access_key: Optional[str] = None
- hmac_secret_key: Optional[str] = None
- # Optional bucket selection
- bucket_names: Optional[List[str]] = None
- # Optional: update an existing connection
- connection_id: Optional[str] = None
diff --git a/src/connectors/onedrive/connector.py b/src/connectors/onedrive/connector.py
index 82652b0cf..e563fa406 100644
--- a/src/connectors/onedrive/connector.py
+++ b/src/connectors/onedrive/connector.py
@@ -32,10 +32,18 @@ class OneDriveConnector(BaseConnector):
CLIENT_SECRET_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET" # pragma: allowlist secret
# Connector metadata
+ CONNECTOR_TYPE = "onedrive"
+ CONNECTOR_KIND = "oauth"
CONNECTOR_NAME = "OneDrive"
CONNECTOR_DESCRIPTION = "Add knowledge from OneDrive"
CONNECTOR_ICON = "onedrive"
+ @classmethod
+ def get_oauth_class(cls):
+ from .oauth import OneDriveOAuth
+
+ return OneDriveOAuth
+
def __init__(self, config: dict[str, Any]):
super().__init__(config)
diff --git a/src/connectors/registry.py b/src/connectors/registry.py
new file mode 100644
index 000000000..58cf2eff1
--- /dev/null
+++ b/src/connectors/registry.py
@@ -0,0 +1,73 @@
+"""Registry of available connector classes.
+
+Combines the builtin OSS connectors with any extras contributed by the
+top-level `enhancements/` package (loaded best-effort — absence is fine).
+
+Shared code (`connection_manager`, settings endpoints, etc.) should look up
+connector classes via this module instead of hard-coding imports/branches.
+"""
+
+from .aws_s3 import S3Connector
+from .base import BaseConnector
+from .google_drive import GoogleDriveConnector
+from .onedrive import OneDriveConnector
+from .sharepoint import SharePointConnector
+
+# Connector classes shipped with OSS. Anything outside this list is contributed
+# by the top-level `enhancements/` package (loaded best-effort).
+BUILTIN_CONNECTORS: list[type[BaseConnector]] = [
+ GoogleDriveConnector,
+ OneDriveConnector,
+ SharePointConnector,
+ S3Connector,
+]
+
+
+# Config-dict secret keys that are not connector-specific (OAuth tokens, generic
+# credentials shared across multiple connectors). Per-connector secret keys come
+# from each class's SECRET_CONFIG_KEYS.
+GENERAL_SECRET_KEYS = frozenset(
+ {
+ "api_key",
+ "hmac_secret_key",
+ "secret_key",
+ "client_secret",
+ "access_token",
+ "refresh_token",
+ "access_key",
+ "hmac_access_key",
+ "basic_credentials",
+ }
+)
+
+
+def _load_additional() -> list[type[BaseConnector]]:
+ try:
+ from enhancements import ADDITIONAL_CONNECTORS
+ except ModuleNotFoundError:
+ # No enhancements package installed — bare OSS build.
+ return []
+ except Exception:
+ import logging
+
+ logging.getLogger(__name__).exception("ADDITIONAL_CONNECTORS import failed")
+ raise
+ return list(ADDITIONAL_CONNECTORS)
+
+
+def get_connector_classes() -> list[type[BaseConnector]]:
+ return BUILTIN_CONNECTORS + _load_additional()
+
+
+def get_connector_class(connector_type: str) -> type[BaseConnector] | None:
+ for cls in get_connector_classes():
+ if cls.CONNECTOR_TYPE == connector_type:
+ return cls
+ return None
+
+
+def get_all_secret_keys() -> set:
+ keys = set(GENERAL_SECRET_KEYS)
+ for cls in get_connector_classes():
+ keys.update(cls.SECRET_CONFIG_KEYS)
+ return keys
diff --git a/src/connectors/sharepoint/connector.py b/src/connectors/sharepoint/connector.py
index 0a2a78f86..ec4836376 100644
--- a/src/connectors/sharepoint/connector.py
+++ b/src/connectors/sharepoint/connector.py
@@ -32,10 +32,18 @@ class SharePointConnector(BaseConnector):
CLIENT_SECRET_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET" # pragma: allowlist secret
# Connector metadata
+ CONNECTOR_TYPE = "sharepoint"
+ CONNECTOR_KIND = "oauth"
CONNECTOR_NAME = "SharePoint"
CONNECTOR_DESCRIPTION = "Add knowledge from SharePoint"
CONNECTOR_ICON = "sharepoint"
+ @classmethod
+ def get_oauth_class(cls):
+ from .oauth import SharePointOAuth
+
+ return SharePointOAuth
+
def __init__(self, config: dict[str, Any]):
super().__init__(config)
diff --git a/src/services/auth_service.py b/src/services/auth_service.py
index c14e0a73c..8fae9bd49 100644
--- a/src/services/auth_service.py
+++ b/src/services/auth_service.py
@@ -8,19 +8,21 @@ import httpx
from fastapi import HTTPException
from config.settings import OAUTH_BROKER_URL, WEBHOOK_BASE_URL, is_no_auth_mode
-from connectors.google_drive import GoogleDriveConnector
-from connectors.google_drive.oauth import GoogleDriveOAuth
-from connectors.onedrive import OneDriveConnector
-from connectors.onedrive.oauth import OneDriveOAuth
-from connectors.sharepoint import SharePointConnector
-from connectors.sharepoint.oauth import SharePointOAuth
+from connectors.registry import get_connector_class, get_connector_classes
from services.langflow_mcp_service import LangflowMCPService
from session_manager import SessionManager
logger = logging.getLogger(__name__)
-# Connectors that authenticate directly (no OAuth redirect required)
-_DIRECT_AUTH_CONNECTORS = {"ibm_cos"}
+
+def _direct_auth_connector_types() -> set:
+ """Bucket-kind connectors authenticate directly (no OAuth redirect)."""
+ return {cls.CONNECTOR_TYPE for cls in get_connector_classes() if cls.CONNECTOR_KIND == "bucket"}
+
+
+def _data_source_connector_types() -> set:
+ """All connector types that can be configured as data sources."""
+ return {cls.CONNECTOR_TYPE for cls in get_connector_classes()}
class AuthService:
@@ -69,12 +71,7 @@ class AuthService:
# Validate connector_type based on purpose
if purpose == "app_auth" and connector_type != "google_drive":
raise ValueError("Only Google login supported for app authentication")
- elif purpose == "data_source" and connector_type not in [
- "google_drive",
- "onedrive",
- "sharepoint",
- "ibm_cos",
- ]:
+ elif purpose == "data_source" and connector_type not in _data_source_connector_types():
raise ValueError(f"Unsupported connector type: {connector_type}")
elif purpose not in ["app_auth", "data_source"]:
raise ValueError(f"Unsupported purpose: {purpose}")
@@ -109,19 +106,16 @@ class AuthService:
)
# Direct-auth connectors (HMAC/API-key based, no OAuth redirect)
- if connector_type in _DIRECT_AUTH_CONNECTORS:
+ if connector_type in _direct_auth_connector_types():
return await self._init_direct_connection(connector_type, connection_id)
- # Get OAuth configuration from connector and OAuth classes
-
- # Map connector types to their connector and OAuth classes
- connector_class_map = {
- "google_drive": (GoogleDriveConnector, GoogleDriveOAuth),
- "onedrive": (OneDriveConnector, OneDriveOAuth),
- "sharepoint": (SharePointConnector, SharePointOAuth),
- }
-
- connector_class, oauth_class = connector_class_map.get(connector_type, (None, None))
+ # Look up connector + OAuth class pair via the registry.
+ connector_class = get_connector_class(connector_type)
+ oauth_class = (
+ connector_class.get_oauth_class()
+ if connector_class and hasattr(connector_class, "get_oauth_class")
+ else None
+ )
if not connector_class or not oauth_class:
raise ValueError(f"No classes found for connector type: {connector_type}")
@@ -254,13 +248,12 @@ class AuthService:
# Get token endpoint from connector type
connector_type = connection_config.connector_type
- connector_class_map = {
- "google_drive": (GoogleDriveConnector, GoogleDriveOAuth),
- "onedrive": (OneDriveConnector, OneDriveOAuth),
- "sharepoint": (SharePointConnector, SharePointOAuth),
- }
-
- connector_class, oauth_class = connector_class_map.get(connector_type, (None, None))
+ connector_class = get_connector_class(connector_type)
+ oauth_class = (
+ connector_class.get_oauth_class()
+ if connector_class and hasattr(connector_class, "get_oauth_class")
+ else None
+ )
if not connector_class or not oauth_class:
raise ValueError(f"No classes found for connector type: {connector_type}")