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

This commit is contained in:
Swifty
2024-09-25 13:06:47 +02:00
committed by GitHub
parent 46b8f9af0a
commit 9f79e70b0f
11 changed files with 60 additions and 18 deletions

View File

@@ -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

View File

@@ -1,4 +1,5 @@
import inspect
import logging
from collections import defaultdict
from contextlib import asynccontextmanager
from functools import wraps
@@ -27,6 +28,7 @@ from backend.util.settings import Config, Settings
from .utils import get_user_id
settings = Settings()
logger = logging.getLogger(__name__)
class AgentServer(AppService):
@@ -65,9 +67,13 @@ class AgentServer(AppService):
if self._test_dependency_overrides:
app.dependency_overrides.update(self._test_dependency_overrides)
logger.debug(
f"FastAPI CORS allow origins: {Config().backend_cors_allow_origins}"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_origins=Config().backend_cors_allow_origins,
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers

View File

@@ -20,13 +20,10 @@ app = FastAPI()
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=["*"],

View File

@@ -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,
@@ -115,6 +115,35 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The port for agent server API to run on",
)
backend_cors_allow_origins: List[str] = Field(default_factory=list)
@field_validator("backend_cors_allow_origins")
@classmethod
def validate_cors_allow_origins(cls, v: List[str]) -> List[str]:
out = []
port = None
has_localhost = False
has_127_0_0_1 = False
for url in v:
url = url.strip()
if url.startswith(("http://", "https://")):
if "localhost" in url:
port = url.split(":")[2]
has_localhost = True
if "127.0.0.1" in url:
port = url.split(":")[2]
has_127_0_0_1 = True
out.append(url)
else:
raise ValueError(f"Invalid URL: {url}")
if has_127_0_0_1 and not has_localhost:
out.append(f"http://localhost:{port}")
if has_localhost and not has_127_0_0_1:
out.append(f"http://127.0.0.1:{port}")
return out
@classmethod
def settings_customise_sources(
cls,

View File

@@ -66,6 +66,7 @@ services:
- ENABLE_AUTH=true
- PYRO_HOST=0.0.0.0
- EXECUTIONMANAGER_HOST=executor
- BACKEND_CORS_ALLOW_ORIGINS=["http://localhost:3000"]
ports:
- "8006:8006"
- "8003:8003" # execution scheduler
@@ -134,6 +135,8 @@ services:
- REDIS_PASSWORD=password
- ENABLE_AUTH=true
- PYRO_HOST=0.0.0.0
- BACKEND_CORS_ALLOW_ORIGINS=["http://localhost:3000"]
ports:
- "8001:8001"
networks:
@@ -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:

View File

@@ -14,6 +14,9 @@
"test-ui": "playwright test --ui",
"gentests": "playwright codegen http://localhost:3000"
},
"browserslist": [
"defaults"
],
"dependencies": {
"@hookform/resolvers": "^3.9.0",
"@next/third-parties": "^14.2.5",

View File

@@ -56,7 +56,7 @@ domain: "dev-builder.agpt.co"
env:
APP_ENV: "dev"
NEXT_PUBLIC_AGPT_SERVER_URL: "http://agpt-server:8000/api"
NEXT_PUBLIC_AGPT_SERVER_URL: ["http://agpt-server:8000/api"]
GOOGLE_CLIENT_ID: ""
GOOGLE_CLIENT_SECRET: ""
NEXT_PUBLIC_SUPABASE_URL: ""

View File

@@ -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"

View File

@@ -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"]

View File

@@ -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"
BACKEND_CORS_ALLOW_ORIGINS: "https://dev-builder.agpt.co"

View File

@@ -16,9 +16,9 @@ import sentry_sdk.integrations.starlette
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()
@@ -62,12 +62,9 @@ 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",
"https://dev-builder.agpt.co",
],
allow_origins=os.environ.get(
"BACKEND_CORS_ALLOW_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000"
).split(","),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
@@ -87,6 +84,7 @@ def health():
content="<h1>Marketplace API</h1>", status_code=200
)
@app.get("/")
def default():
return fastapi.responses.HTMLResponse(