AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(server): Add OAuth handlers for GitHub, Notion, Google & amend store data structure (#7868)
Reinier van der Leer8f1c63a7ea35
diff --git a/rnd/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py b/rnd/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.pyindex ec16d19988..fa698d140d 100644--- a/rnd/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py+++ b/rnd/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py@@ -19,16 +19,17 @@ class _BaseCredentials(BaseModel):class OAuth2Credentials(_BaseCredentials):type: Literal["oauth2"] = "oauth2"access_token: SecretStr- access_token_expires_at: int- refresh_token: SecretStr- refresh_token_expires_at: Optional[int]+ access_token_expires_at: Optional[int] # seconds+ refresh_token: Optional[SecretStr]+ refresh_token_expires_at: Optional[int] # secondsscopes: list[str]+ metadata: dict[str, Any] = Field(default_factory=dict)class APIKeyCredentials(_BaseCredentials):type: Literal["api_key"] = "api_key"api_key: SecretStr- expires_at: Optional[int]+ expires_at: Optional[int] # secondsCredentials = Annotated[diff --git a/rnd/autogpt_server/autogpt_server/integrations/github.py b/rnd/autogpt_server/autogpt_server/integrations/github.pynew file mode 100644index 0000000000..af24830461--- /dev/null+++ b/rnd/autogpt_server/autogpt_server/integrations/github.py@@ -0,0 +1,99 @@+import time+from typing import Optional+from urllib.parse import urlencode++import requests+from autogpt_libs.supabase_integration_credentials_store import OAuth2Credentials++from autogpt_server.integrations.oauth import BaseOAuthHandler+++class GitHubOAuthHandler(BaseOAuthHandler):+ """+ Based on the documentation at:+ - [Authorizing OAuth apps - GitHub Docs](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps)+ - [Refreshing user access tokens - GitHub Docs](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/refreshing-user-access-tokens)++ Notes:+ - By default, token expiration is disabled on GitHub Apps. This means the access+ token doesn't expire and no refresh token is returned by the authorization flow.+ - When token expiration gets enabled, any existing tokens will remain non-expiring.+ - When token expiration gets disabled, token refreshes will return a non-expiring+ access token *with no refresh token*.+ """ # noqa++ PROVIDER_NAME = "github"++ def __init__(self, client_id: str, client_secret: str, redirect_uri: str):+ self.client_id = client_id+ self.client_secret = client_secret+ self.redirect_uri = redirect_uri+ self.auth_base_url = "https://github.com/login/oauth/authorize"+ self.token_url = "https://github.com/login/oauth/access_token"++ def get_login_url(self, scopes: list[str], state: str) -> str:+ params = {+ "client_id": self.client_id,+ "redirect_uri": self.redirect_uri,+ "scope": " ".join(scopes),+ "state": state,+ }+ return f"{self.auth_base_url}?{urlencode(params)}"++ def exchange_code_for_tokens(self, code: str) -> OAuth2Credentials:+ return self._request_tokens({"code": code, "redirect_uri": self.redirect_uri})++ def _refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:+ if not credentials.refresh_token:+ return credentials++ return self._request_tokens(+ {+ "refresh_token": credentials.refresh_token.get_secret_value(),+ "grant_type": "refresh_token",+ }+ )++ def _request_tokens(+ self,+ params: dict[str, str],+ current_credentials: Optional[OAuth2Credentials] = None,+ ) -> OAuth2Credentials:+ request_body = {+ "client_id": self.client_id,+ "client_secret": self.client_secret,+ **params,+ }+ headers = {"Accept": "application/json"}+ response = requests.post(self.token_url, data=request_body, headers=headers)+ response.raise_for_status()+ token_data: dict = response.json()++ now = int(time.time())+ new_credentials = OAuth2Credentials(+ provider=self.PROVIDER_NAME,+ title=current_credentials.title if current_credentials else "GitHub",+ access_token=token_data["access_token"],+ # Token refresh responses have an empty `scope` property (see docs),+ # so we have to get the scope from the existing credentials object.+ scopes=(+ token_data.get("scope", "").split(",")+ or (current_credentials.scopes if current_credentials else [])+ ),+ # Refresh token and expiration intervals are only given if token expiration+ # is enabled in the GitHub App's settings.+ refresh_token=token_data.get("refresh_token"),+ access_token_expires_at=(+ now + expires_in+ if (expires_in := token_data.get("expires_in", None))+ else None+ ),+ refresh_token_expires_at=(+ now + expires_in+ if (expires_in := token_data.get("refresh_token_expires_in", None))+ else None+ ),+ )+ if current_credentials:+ new_credentials.id = current_credentials.id+ return new_credentialsdiff --git a/rnd/autogpt_server/autogpt_server/integrations/google.py b/rnd/autogpt_server/autogpt_server/integrations/google.pynew file mode 100644index 0000000000..edcba32df8--- /dev/null+++ b/rnd/autogpt_server/autogpt_server/integrations/google.py@@ -0,0 +1,96 @@+from autogpt_libs.supabase_integration_credentials_store import OAuth2Credentials+from google.auth.transport.requests import Request+from google.oauth2.credentials import Credentials+from google_auth_oauthlib.flow import Flow+from pydantic import SecretStr++from .oauth import BaseOAuthHandler+++class GoogleOAuthHandler(BaseOAuthHandler):+ """+ Based on the documentation at https://developers.google.com/identity/protocols/oauth2/web-server+ """ # noqa++ PROVIDER_NAME = "google"++ def __init__(self, client_id: str, client_secret: str, redirect_uri: str):+ self.client_id = client_id+ self.client_secret = client_secret+ self.redirect_uri = redirect_uri+ self.token_uri = "https://oauth2.googleapis.com/token"++ def get_login_url(self, scopes: list[str], state: str) -> str:+ flow = self._setup_oauth_flow(scopes)+ flow.redirect_uri = self.redirect_uri+ authorization_url, _ = flow.authorization_url(+ access_type="offline",+ include_granted_scopes="true",+ state=state,+ prompt="consent",+ )+ return authorization_url++ def exchange_code_for_tokens(self, code: str) -> OAuth2Credentials:+ flow = self._setup_oauth_flow(None)+ flow.redirect_uri = self.redirect_uri+ flow.fetch_token(code=code)++ google_creds = flow.credentials+ # Google's OAuth library is poorly typed so we need some of these:+ assert google_creds.token+ assert google_creds.refresh_token+ assert google_creds.expiry+ assert google_creds.scopes+ return OAuth2Credentials(+ provider=self.PROVIDER_NAME,+ title="Google",+ access_token=SecretStr(google_creds.token),+ refresh_token=SecretStr(google_creds.refresh_token),+ access_token_expires_at=int(google_creds.expiry.timestamp()),+ refresh_token_expires_at=None,+ scopes=google_creds.scopes,+ )++ def _refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:+ # Google credentials should ALWAYS have a refresh token+ assert credentials.refresh_token++ google_creds = Credentials(+ token=credentials.access_token.get_secret_value(),+ refresh_token=credentials.refresh_token.get_secret_value(),+ token_uri=self.token_uri,+ client_id=self.client_id,+ client_secret=self.client_secret,+ scopes=credentials.scopes,+ )+ # Google's OAuth library is poorly typed so we need some of these:+ assert google_creds.refresh_token+ assert google_creds.scopes++ google_creds.refresh(Request())+ assert google_creds.expiry++ return OAuth2Credentials(+ id=credentials.id,+ provider=self.PROVIDER_NAME,+ title=credentials.title,+ access_token=SecretStr(google_creds.token),+ refresh_token=SecretStr(google_creds.refresh_token),+ access_token_expires_at=int(google_creds.expiry.timestamp()),+ refresh_token_expires_at=None,+ scopes=google_creds.scopes,+ )++ def _setup_oauth_flow(self, scopes: list[str] | None) -> Flow:+ return Flow.from_client_config(+ {+ "web": {+ "client_id": self.client_id,+ "client_secret": self.client_secret,+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",+ "token_uri": self.token_uri,+ }+ },+ scopes=scopes,+ )diff --git a/rnd/autogpt_server/autogpt_server/integrations/notion.py b/rnd/autogpt_server/autogpt_server/integrations/notion.pynew file mode 100644index 0000000000..aed2ccba43--- /dev/null+++ b/rnd/autogpt_server/autogpt_server/integrations/notion.py@@ -0,0 +1,76 @@+from base64 import b64encode+from urllib.parse import urlencode++import requests+from autogpt_libs.supabase_integration_credentials_store import OAuth2Credentials++from autogpt_server.integrations.oauth import BaseOAuthHandler+++class NotionOAuthHandler(BaseOAuthHandler):+ """+ Based on the documentation at https://developers.notion.com/docs/authorization++ Notes:+ - Notion uses non-expiring access tokens and therefore doesn't have a refresh flow+ - Notion doesn't use scopes+ """++ PROVIDER_NAME = "notion"++ def __init__(self, client_id: str, client_secret: str, redirect_uri: str):+ self.client_id = client_id+ self.client_secret = client_secret+ self.redirect_uri = redirect_uri+ self.auth_base_url = "https://api.notion.com/v1/oauth/authorize"+ self.token_url = "https://api.notion.com/v1/oauth/token"++ def get_login_url(self, scopes: list[str], state: str) -> str:+ params = {+ "client_id": self.client_id,+ "redirect_uri": self.redirect_uri,+ "response_type": "code",+ "owner": "user",+ "state": state,+ }+ return f"{self.auth_base_url}?{urlencode(params)}"++ def exchange_code_for_tokens(self, code: str) -> OAuth2Credentials:+ request_body = {+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": self.redirect_uri,+ }+ auth_str = b64encode(f"{self.client_id}:{self.client_secret}".encode()).decode()+ headers = {+ "Authorization": f"Basic {auth_str}",+ "Accept": "application/json",+ }+ response = requests.post(self.token_url, json=request_body, headers=headers)+ response.raise_for_status()+ token_data = response.json()++ return OAuth2Credentials(+ provider=self.PROVIDER_NAME,+ title=token_data.get("workspace_name", "Notion"),+ access_token=token_data["access_token"],+ refresh_token=None,+ access_token_expires_at=None, # Notion tokens don't expire+ refresh_token_expires_at=None,+ scopes=[],+ metadata={+ "owner": token_data["owner"],+ "bot_id": token_data["bot_id"],+ "workspace_id": token_data["workspace_id"],+ "workspace_name": token_data.get("workspace_name"),+ "workspace_icon": token_data.get("workspace_icon"),+ },+ )++ def _refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:+ # Notion doesn't support token refresh+ return credentials++ def needs_refresh(self, credentials: OAuth2Credentials) -> bool:+ # Notion access tokens don't expire+ return Falsediff --git a/rnd/autogpt_server/autogpt_server/integrations/oauth.py b/rnd/autogpt_server/autogpt_server/integrations/oauth.pynew file mode 100644index 0000000000..5fefe5b54d--- /dev/null+++ b/rnd/autogpt_server/autogpt_server/integrations/oauth.py@@ -0,0 +1,48 @@+import time+from abc import ABC, abstractmethod+from typing import ClassVar++from autogpt_libs.supabase_integration_credentials_store import OAuth2Credentials+++class BaseOAuthHandler(ABC):+ PROVIDER_NAME: ClassVar[str]++ @abstractmethod+ def __init__(self, client_id: str, client_secret: str, redirect_uri: str): ...++ @abstractmethod+ def get_login_url(self, scopes: list[str], state: str) -> str:+ """Constructs a login URL that the user can be redirected to"""+ ...++ @abstractmethod+ def exchange_code_for_tokens(self, code: str) -> OAuth2Credentials:+ """Exchanges the acquired authorization code from login for a set of tokens"""+ ...++ @abstractmethod+ def _refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:+ """Implements the token refresh mechanism"""+ ...++ def refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:+ if credentials.provider != self.PROVIDER_NAME:+ raise ValueError(+ f"{self.__class__.__name__} can not refresh tokens "+ f"for other provider '{credentials.provider}'"+ )+ return self._refresh_tokens(credentials)++ def get_access_token(self, credentials: OAuth2Credentials) -> str:+ """Returns a valid access token, refreshing it first if needed"""+ if self.needs_refresh(credentials):+ credentials = self.refresh_tokens(credentials)+ return credentials.access_token.get_secret_value()++ def needs_refresh(self, credentials: OAuth2Credentials) -> bool:+ """Indicates whether the given tokens need to be refreshed"""+ return (+ credentials.access_token_expires_at is not None+ and credentials.access_token_expires_at < int(time.time()) + 300+ )diff --git a/rnd/autogpt_server/poetry.lock b/rnd/autogpt_server/poetry.lockindex 3c70aff5b6..21c2adc646 100644--- a/rnd/autogpt_server/poetry.lock+++ b/rnd/autogpt_server/poetry.lock@@ -25,7 +25,7 @@ requests = "*"sentry-sdk = "^1.40.4"[package.extras]-benchmark = ["agbenchmark @ file:///Users/majdyz/Code/AutoGPT/benchmark"]+benchmark = ["agbenchmark"][package.source]type = "directory"@@ -356,7 +356,7 @@ watchdog = "4.0.0"webdriver-manager = "^4.0.1"[package.extras]-benchmark = ["agbenchmark @ file:///Users/majdyz/Code/AutoGPT/benchmark"]+benchmark = ["agbenchmark"][package.source]type = "directory"@@ -1606,6 +1606,24 @@ files = [google-auth = "*"httplib2 = ">=0.19.0"+[[package]]+name = "google-auth-oauthlib"+version = "1.2.1"+description = "Google Authentication Library"+optional = false+python-versions = ">=3.6"+files = [+ {file = "google_auth_oauthlib-1.2.1-py2.py3-none-any.whl", hash = "sha256:2d58a27262d55aa1b87678c3ba7142a080098cbc2024f903c62355deb235d91f"},+ {file = "google_auth_oauthlib-1.2.1.tar.gz", hash = "sha256:afd0cad092a2eaa53cd8e8298557d6de1034c6cb4a740500b5357b648af97263"},+]++[package.dependencies]+google-auth = ">=2.15.0"+requests-oauthlib = ">=0.7.0"++[package.extras]+tool = ["click (>=6.0.0)"]+[[package]]name = "google-cloud-appengine-logging"version = "1.4.5"@@ -6644,4 +6662,4 @@ test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools",[metadata]lock-version = "2.0"python-versions = "^3.10"-content-hash = "cd891465378f91d1141723cda0229dcea4a230f426942bb578d767a9e956b14a"+content-hash = "c61b384425319c7c9d51344d351ecba735481ef5dc4582701c13cbd027d0690a"diff --git a/rnd/autogpt_server/pyproject.toml b/rnd/autogpt_server/pyproject.tomlindex 2909abe9bd..cfd6061f5b 100644--- a/rnd/autogpt_server/pyproject.toml+++ b/rnd/autogpt_server/pyproject.toml@@ -11,38 +11,39 @@ readme = "README.md"[tool.poetry.dependencies]python = "^3.10"agpt = { path = "../../autogpt", develop = true }-click = "^8.1.7"+anthropic = "^0.25.1"+apscheduler = "^3.10.4"autogpt-forge = { path = "../../forge", develop = true }-prisma = "^0.13.1"-pydantic = "^2.7.2"-pytest = "^8.2.1"-uvicorn = { extras = ["standard"], version = "^0.30.1" }+autogpt-libs = { path = "../autogpt_libs" }+click = "^8.1.7"+croniter = "^2.0.5"+discord-py = "^2.4.0"+expiringdict = "^1.2.2"fastapi = "^0.109.0"+feedparser = "^6.0.11"flake8 = "^7.0.0"+google-api-python-client = "^2.142.0"+google-auth-oauthlib = "^1.2.1"+groq = "^0.8.0"+jinja2 = "^3.1.4"+jsonref = "^1.1.0"jsonschema = "^4.22.0"+ollama = "^0.3.0"+openai = "^1.35.7"+praw = "^7.7.1"+prisma = "^0.13.1"psutil = "^5.9.8"+pydantic = "^2.7.2"+pydantic-settings = "^2.3.4"pyro5 = "^5.15"-tenacity = "^8.3.0"-apscheduler = "^3.10.4"-croniter = "^2.0.5"+pytest = "^8.2.1"pytest-asyncio = "^0.23.7"+python-dotenv = "^1.0.1"+tenacity = "^8.3.0"+uvicorn = { extras = ["standard"], version = "^0.30.1" }websockets = "^12.0"-pydantic-settings = "^2.3.4"-praw = "^7.7.1"-openai = "^1.35.7"-jsonref = "^1.1.0"-groq = "^0.8.0"-anthropic = "^0.25.1"youtube-transcript-api = "^0.6.2"-ollama = "^0.3.0"-feedparser = "^6.0.11"-python-dotenv = "^1.0.1"-expiringdict = "^1.2.2"-discord-py = "^2.4.0"--autogpt-libs = {path = "../autogpt_libs"}-jinja2 = "^3.1.4"[tool.poetry.group.dev.dependencies]cx-freeze = { git = "https://github.com/ntindle/cx_Freeze.git", rev = "main", develop = true }poethepoet = "^0.26.1"