mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-04 18:13:03 +00:00
Migration 0038 moves every stored secret (OAuth tokens, MCP OAuth tokens and client registrations, API keys) into the connection's encrypted envelope, links API-key tools to one connection per distinct credential, allows several accounts per provider, and adds credential_mode to sources and tools. OAuth MCP tools keep resolving each member's own token, as they did before. docsgpt.connectors.service is now the only reader of OAuth tokens: get_valid_token_info refreshes under a row lock and persists rotated refresh tokens, and a revoked grant flags the connection, pauses its sources and notifies the owner. Loaders build from a connection (BaseConnectorLoader.from_connection), so scheduled sync covers Drive, SharePoint and Confluence sources with no browser. S3 and Reddit keys stay on the connection instead of in remote_data. New endpoints: POST /api/connections, /setup, /reconnect, /picker-token, /claim, DELETE /api/connections/<id>, per-action permissions and MCP refresh-tools. Upload, file listing, sync and validate-session take a connection_id; session tokens keep working for this release. The tool executor reads credentials from the resolved connection (owner or member mode) and pauses on a Connect card when a connection needs signing in. docsgpt connectors reencrypt rewrites stored credentials after a key rotation.
118 lines
4.3 KiB
Python
118 lines
4.3 KiB
Python
import datetime
|
|
import logging
|
|
from typing import Optional, Dict, Any
|
|
|
|
from msal import ConfidentialClientApplication
|
|
|
|
from docsgpt.core.settings import settings
|
|
from docsgpt.parser.connectors.base import BaseConnectorAuth
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class SharePointAuth(BaseConnectorAuth):
|
|
"""
|
|
Handles Microsoft OAuth 2.0 authentication for SharePoint/OneDrive.
|
|
|
|
Note: Files.Read scope allows access to files the user has granted access to,
|
|
similar to Google Drive's drive.file scope.
|
|
"""
|
|
|
|
SCOPES = [
|
|
"Files.Read",
|
|
"Sites.Read.All",
|
|
"User.Read",
|
|
]
|
|
|
|
def __init__(self):
|
|
self.client_id = settings.MICROSOFT_CLIENT_ID
|
|
self.client_secret = settings.MICROSOFT_CLIENT_SECRET
|
|
|
|
if not self.client_id:
|
|
raise ValueError(
|
|
"Microsoft OAuth credentials not configured. Please set MICROSOFT_CLIENT_ID in settings."
|
|
)
|
|
|
|
if not self.client_secret:
|
|
raise ValueError(
|
|
"Microsoft OAuth credentials not configured. Please set MICROSOFT_CLIENT_SECRET in settings."
|
|
)
|
|
|
|
self.redirect_uri = settings.CONNECTOR_REDIRECT_BASE_URI
|
|
self.tenant_id = settings.MICROSOFT_TENANT_ID
|
|
self.authority = settings.MICROSOFT_AUTHORITY or f"https://login.microsoftonline.com/{self.tenant_id}"
|
|
|
|
self.auth_app = ConfidentialClientApplication(
|
|
client_id=self.client_id,
|
|
client_credential=self.client_secret,
|
|
authority=self.authority
|
|
)
|
|
|
|
def get_authorization_url(self, state: Optional[str] = None) -> str:
|
|
return self.auth_app.get_authorization_request_url(
|
|
scopes=self.SCOPES, state=state, redirect_uri=self.redirect_uri
|
|
)
|
|
|
|
def exchange_code_for_tokens(self, authorization_code: str) -> Dict[str, Any]:
|
|
result = self.auth_app.acquire_token_by_authorization_code(
|
|
code=authorization_code,
|
|
scopes=self.SCOPES,
|
|
redirect_uri=self.redirect_uri
|
|
)
|
|
|
|
if "error" in result:
|
|
logger.error("Token exchange failed: %s", result.get("error_description"))
|
|
raise ValueError(f"Error acquiring token: {result.get('error_description')}")
|
|
|
|
return self.map_token_response(result)
|
|
|
|
def refresh_access_token(self, refresh_token: str) -> Dict[str, Any]:
|
|
result = self.auth_app.acquire_token_by_refresh_token(refresh_token=refresh_token, scopes=self.SCOPES)
|
|
|
|
if "error" in result:
|
|
logger.error("Token refresh failed: %s", result.get("error_description"))
|
|
raise ValueError(f"Error refreshing token: {result.get('error_description')}")
|
|
|
|
return self.map_token_response(result)
|
|
|
|
def is_token_expired(self, token_info: Dict[str, Any]) -> bool:
|
|
if not token_info:
|
|
return True
|
|
|
|
expiry_timestamp = token_info.get("expiry")
|
|
|
|
if expiry_timestamp is None:
|
|
return True
|
|
|
|
current_timestamp = int(datetime.datetime.now().timestamp())
|
|
return (expiry_timestamp - current_timestamp) < 60
|
|
|
|
def sanitize_token_info(self, token_info: Dict[str, Any], **extra_fields) -> Dict[str, Any]:
|
|
return super().sanitize_token_info(
|
|
token_info,
|
|
allows_shared_content=token_info.get("allows_shared_content", False),
|
|
**extra_fields,
|
|
)
|
|
|
|
PERSONAL_ACCOUNT_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad"
|
|
|
|
def _allows_shared_content(self, id_token_claims: Dict[str, Any]) -> bool:
|
|
"""Return True when the account is a work/school tenant that can access SharePoint shared content."""
|
|
tid = id_token_claims.get("tid", "")
|
|
return bool(tid) and tid != self.PERSONAL_ACCOUNT_TENANT_ID
|
|
|
|
def map_token_response(self, result) -> Dict[str, Any]:
|
|
claims = result.get("id_token_claims", {})
|
|
return {
|
|
"access_token": result.get("access_token"),
|
|
"refresh_token": result.get("refresh_token"),
|
|
"token_uri": claims.get("iss"),
|
|
"scopes": result.get("scope"),
|
|
"expiry": claims.get("exp"),
|
|
"allows_shared_content": self._allows_shared_content(claims),
|
|
"user_info": {
|
|
"name": claims.get("name"),
|
|
"email": claims.get("preferred_username"),
|
|
},
|
|
}
|