Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(platform): Fix REST API CORS issue + UI build for Firefox #8140

Merged
merged 13 commits into from
Sep 25, 2024
Merged
2 changes: 2 additions & 0 deletions autogpt_platform/backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ DB_PORT=5432
DATABASE_URL="postgresql://${DB_USER}:${DB_PASS}@localhost:${DB_PORT}/${DB_NAME}?connect_timeout=60&schema=platform"
PRISMA_SCHEMA="postgres/schema.prisma"

BACKEND_CORS_ALLOW_ORIGINS="http://localhost:3000"

REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=password
Expand Down
8 changes: 7 additions & 1 deletion autogpt_platform/backend/backend/server/rest_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import inspect
import logging
from collections import defaultdict
from contextlib import asynccontextmanager
from functools import wraps
Expand Down Expand Up @@ -27,6 +28,7 @@
from .utils import get_user_id

settings = Settings()
logger = logging.getLogger(__name__)


class AgentServer(AppService):
Expand Down Expand Up @@ -65,9 +67,13 @@ def run_service(self):
if self._test_dependency_overrides:
app.dependency_overrides.update(self._test_dependency_overrides)

logger.info(
f"FastAPI CORS allow origins: {Config().backend_cors_allow_origins}"
)
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved

app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_origins=Config().backend_cors_allow_origins,
allow_credentials=True,
allow_methods=["*"], # Allows all methods
aarushik93 marked this conversation as resolved.
Show resolved Hide resolved
allow_headers=["*"], # Allows all headers
Expand Down
7 changes: 2 additions & 5 deletions autogpt_platform/backend/backend/server/ws_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@
event_queue = AsyncRedisEventQueue()
_connection_manager = None

logger.info(f"CORS allow origins: {settings.config.backend_cors_allow_origins}")
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://127.0.0.1:3000",
"https://dev-builder.agpt.co",
],
allow_origins=settings.config.backend_cors_allow_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand Down
31 changes: 29 additions & 2 deletions autogpt_platform/backend/backend/util/settings.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
import os
from typing import Any, Dict, Generic, Set, Tuple, Type, TypeVar
from typing import Any, Dict, Generic, List, Set, Tuple, Type, TypeVar

from pydantic import BaseModel, Field, PrivateAttr
from pydantic import BaseModel, Field, PrivateAttr, field_validator
from pydantic_settings import (
BaseSettings,
JsonConfigSettingsSource,
Expand Down Expand Up @@ -105,6 +105,33 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The port for agent server API to run on",
)

backend_cors_allow_origins: List[str] = []
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved

@field_validator("backend_cors_allow_origins")
@classmethod
def validate_cors_allow_origins(cls, v):
out = []
if isinstance(v, list):
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
for url in v:
url = url.strip()
if url.startswith(("http://", "https://")):
out.append(url)
else:
raise ValueError(f"Invalid URL: {url}")
else:
raise ValueError("backend_cors_allow_origins must be a valid url")

# If using local callback add both localhost and 127.0.0.1
# NOTE: Localhost does not use ssl
has_localhost = any(["localhost" in url for url in out])
has_127_0_0_1 = any(["127.0.0.1" in url for url in out])
if has_127_0_0_1 and not has_localhost:
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
out.append("http://localhost:3000")
if has_localhost and not has_127_0_0_1:
out.append("http://127.0.0.1:3000")

return out

@classmethod
def settings_customise_sources(
cls,
Expand Down
4 changes: 4 additions & 0 deletions autogpt_platform/docker-compose.platform.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ services:
- ENABLE_AUTH=true
- PYRO_HOST=0.0.0.0
- EXECUTIONMANAGER_HOST=executor
- BACKEND_CORS_ALLOW_ORIGINS=["http://localhost:3000"]
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
ports:
- "8006:8006"
- "8003:8003" # execution scheduler
Expand Down Expand Up @@ -134,6 +135,8 @@ services:
- REDIS_PASSWORD=password
- ENABLE_AUTH=true
- PYRO_HOST=0.0.0.0
- BACKEND_CORS_ALLOW_ORIGINS=["http://localhost:3000"]
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved

ports:
- "8001:8001"
networks:
Expand All @@ -158,6 +161,7 @@ services:
- SUPABASE_JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters-long
- SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
- DATABASE_URL=postgresql://postgres:your-super-secret-and-long-postgres-password@db:5432/postgres?connect_timeout=60&schema=market
- BACKEND_CORS_ALLOW_ORIGINS="http://localhost:3000,http://127.0.0.1:3000"
ports:
- "8015:8015"
networks:
Expand Down
3 changes: 3 additions & 0 deletions autogpt_platform/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"lint": "next lint",
"format": "prettier --write ."
},
"browserslist": [
"defaults"
],
"dependencies": {
"@hookform/resolvers": "^3.9.0",
"@next/third-parties": "^14.2.5",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,5 @@ env:
SUPABASE_JWT_SECRET: ""
SUPABASE_ANON_KEY: ""
SUPABASE_URL: ""
DATABASE_URL: ""
DATABASE_URL: ""
BACKEND_CORS_ALLOW_ORIGINS: "https://dev-builder.agpt.co"
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,4 @@ env:
NUM_NODE_WORKERS: 5
REDIS_HOST: "redis-dev-master.redis-dev.svc.cluster.local"
REDIS_PORT: "6379"
BACKEND_CORS_ALLOW_ORIGINS: "https://dev-builder.agpt.co"
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,5 @@ livenessProbe:
env:
REDIS_HOST: "redis-dev-master.redis-dev.svc.cluster.local"
REDIS_PORT: "6379"
REDIS_PASSWORD: "password"
REDIS_PASSWORD: "password"
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
BACKEND_CORS_ALLOW_ORIGINS: "https://dev-builder.agpt.co"
12 changes: 5 additions & 7 deletions autogpt_platform/market/market/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
import market.config
import market.routes.admin
import market.routes.agents
import market.routes.analytics
import market.routes.search
import market.routes.submissions
import market.routes.analytics

dotenv.load_dotenv()

Expand Down Expand Up @@ -62,12 +62,9 @@ async def lifespan(app: fastapi.FastAPI):
app.add_middleware(fastapi.middleware.gzip.GZipMiddleware, minimum_size=1000)
app.add_middleware(
middleware_class=fastapi.middleware.cors.CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://127.0.0.1:3000",
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
"https://dev-builder.agpt.co",
],
allow_origins=os.environ.get(
"BACKEND_CORS_ALLOW_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000"
Swiftyos marked this conversation as resolved.
Show resolved Hide resolved
).split(","),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand All @@ -87,6 +84,7 @@ def health():
content="<h1>Marketplace API</h1>", status_code=200
)


@app.get("/")
def default():
return fastapi.responses.HTMLResponse(
Expand Down
Loading