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.
refactor(backend): move the user-settings routes into features/user and delete v1.py (#14480)
Reinier van der Leereea6d26190fb
diff --git a/autogpt_platform/backend/backend/api/features/chat/share.py b/autogpt_platform/backend/backend/api/features/chat/share.pyindex 6337a7e624..60f7c5dfcc 100644--- a/autogpt_platform/backend/backend/api/features/chat/share.py+++ b/autogpt_platform/backend/backend/api/features/chat/share.py@@ -4,7 +4,7 @@ Three groups of routes:- **Owner-only** — list linked-execution candidates, enable share withopt-ins, disable share. Mirrors the ``/graphs/.../share`` shape on- :mod:`backend.api.features.v1` for execution sharing.+ :mod:`backend.api.features.graph_executions.routes` for execution sharing.- **Public-by-token** — the public viewer reads through theseunauthenticated routes; the share token is the bearer credential.Same enumeration defenses as execution sharing (strict UUID pathdiff --git a/autogpt_platform/backend/backend/api/features/user/__init__.py b/autogpt_platform/backend/backend/api/features/user/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/user/routes.pysimilarity index 93%rename from autogpt_platform/backend/backend/api/features/v1.pyrename to autogpt_platform/backend/backend/api/features/user/routes.pyindex 6d8c71f588..2cf4879902 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/user/routes.py@@ -24,21 +24,18 @@ from backend.util.settings import Settingssettings = Settings()logger = logging.getLogger(__name__)--# Define the API routes-v1_router = APIRouter()---########################################################-##################### Auth #############################-########################################################+# Nothing is hoisted onto this router, tags included. Six of the seven routes+# take Security(requires_user); POST /auth/user/preferences/from-email takes+# none — it is reached from an email link and verifies its own signed token —+# so a router-level dependency would silently authenticate it.+router = APIRouter()_tally_background_tasks: set[asyncio.Task] = set()USER_CREATED_HEADER = "X-AutoGPT-User-Created"-@v1_router.post("/auth/user",summary="Get or create user",tags=["auth"],@@ -79,7 +76,7 @@ async def get_or_create_user_route(return user.model_dump()-@v1_router.post("/auth/user/email",summary="Update user email",tags=["auth"],@@ -93,7 +90,7 @@ async def update_user_email_route(return {"email": email}-@v1_router.get("/auth/user/timezone",summary="Get user timezone",tags=["auth"],@@ -107,7 +104,7 @@ async def get_user_timezone_route(return TimezoneResponse(timezone=user.timezone)-@v1_router.post("/auth/user/timezone",summary="Update user timezone",tags=["auth"],@@ -121,7 +118,7 @@ async def update_user_timezone_route(return TimezoneResponse(timezone=user.timezone)-@v1_router.get("/auth/user/preferences",summary="Get notification preferences",tags=["auth"],@@ -134,7 +131,7 @@ async def get_preferences(return preferences-@v1_router.post("/auth/user/preferences",summary="Update notification preferences",tags=["auth"],@@ -148,7 +145,7 @@ async def update_preferences(return output-@v1_router.post("/auth/user/preferences/from-email",summary="Apply a volume-knob choice from a Briefing footer link",tags=["auth"],diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/user/routes_test.pysimilarity index 64%rename from autogpt_platform/backend/backend/api/features/v1_test.pyrename to autogpt_platform/backend/backend/api/features/user/routes_test.pyindex bf35487652..4d6805f5dd 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/user/routes_test.py@@ -7,13 +7,14 @@ import fastapi.testclientimport pytestimport pytest_mockfrom autogpt_libs.auth.models import RequestContext+from fastapi.routing import APIRoutefrom pytest_snapshot.plugin import Snapshot+from backend.api.rest_api import app as real_appfrom backend.api.rest_api import handle_internal_http_errorfrom backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError-from backend.util.exceptions import ConflictError-from .v1 import v1_router+from .routes import routerdef _test_ctx(user_id: str) -> RequestContext:@@ -31,14 +32,10 @@ def _test_ctx(user_id: str) -> RequestContext:app = fastapi.FastAPI()-app.include_router(v1_router)+app.include_router(router)# Mirror rest_api.py's GraphActivationError → 400 mapping so the atomicity# tests below verify the same behaviour the real app exposes.app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))-# Same reason: ConflictError is mapped app-wide, never on the route, so without-# this a conflict reads here as an unhandled error rather than the 409 a client-# actually gets.-app.add_exception_handler(ConflictError, handle_internal_http_error(409))client = fastapi.testclient.TestClient(app)@@ -93,7 +90,7 @@ def test_get_or_create_user_route(mock_result = Mock(user=mock_user, was_created=False)mocker.patch(- "backend.api.features.v1.get_or_create_user_with_status",+ "backend.api.features.user.routes.get_or_create_user_with_status",return_value=mock_result,)@@ -121,7 +118,7 @@ def test_get_or_create_user_route_reports_creation(}mocker.patch(- "backend.api.features.v1.get_or_create_user_with_status",+ "backend.api.features.user.routes.get_or_create_user_with_status",return_value=Mock(user=mock_user, was_created=True),)@@ -146,7 +143,7 @@ def test_update_user_email_route() -> None:"""Test update user email endpoint"""mocker.patch(- "backend.api.features.v1.update_user_email",+ "backend.api.features.user.routes.update_user_email",return_value=None,)@@ -172,3 +169,63 @@ def test_invalid_json_request() -> None:headers={"Content-Type": "application/json"},)assert response.status_code == 422+++# The login surface: six routes authenticate, one deliberately does not.+# Nothing is hoisted onto this router — a router-level dependency would+# silently authenticate the email-link route.+AUTHENTICATED = {+ ("post", "/api/auth/user"),+ ("post", "/api/auth/user/email"),+ ("get", "/api/auth/user/timezone"),+ ("post", "/api/auth/user/timezone"),+ ("get", "/api/auth/user/preferences"),+ ("post", "/api/auth/user/preferences"),+}+UNAUTHENTICATED = {("post", "/api/auth/user/preferences/from-email")}++[email protected]("method,path", sorted(AUTHENTICATED))+def test_auth_route_requires_a_user(method: str, path: str):+ """Asserted on the dependency chain, not on `security` in the schema: each+ handler's own Security(get_user_id) or get_jwt_payload puts `security`+ there regardless, so the schema cannot tell requires_user apart."""+ route = next(+ r+ for r in real_app.routes+ if isinstance(r, APIRoute) and r.path == path and method.upper() in r.methods+ )+ assert "requires_user" in {+ d.call.__name__ for d in route.dependant.dependencies if d.call+ }++[email protected]("method,path", sorted(UNAUTHENTICATED))+def test_email_preference_route_stays_unauthenticated(method: str, path: str):+ """Reached from a link in an email, so it carries no user credential and+ verifies its own signed token instead. If a dependency ever appears here,+ every unsubscribe link in the wild breaks."""+ route = next(+ r+ for r in real_app.routes+ if isinstance(r, APIRoute) and r.path == path and method.upper() in r.methods+ )+ assert route.dependant.dependencies == []+ assert "security" not in real_app.openapi()["paths"][path][method]+++def test_auth_surface_has_no_other_operations():+ served = {+ (method.lower(), route.path)+ for route in real_app.routes+ if isinstance(route, APIRoute)+ and route.endpoint.__module__ == "backend.api.features.user.routes"+ for method in route.methods+ if method != "HEAD"+ }+ assert served == AUTHENTICATED | UNAUTHENTICATED++[email protected]("method,path", sorted(AUTHENTICATED | UNAUTHENTICATED))+def test_auth_operation_keeps_its_tags(method: str, path: str):+ assert real_app.openapi()["paths"][path][method]["tags"] == ["v1", "auth"]diff --git a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.pyindex b72346776c..0c1b35aa3e 100644--- a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -1,4 +1,4 @@-"""Authorization tests for the org-scoped credits routes in v1.py.+"""Authorization tests for the org-scoped credits routes.SECRT-2449: the credits balance/transaction/invoice/top-up routes resolvetheir credit model through the request's org context, so for a real (pooled)@@ -41,15 +41,11 @@ from backend.data.org_credit import OrgCreditModelfrom .billing.credits import routes as credits_routesfrom .billing.subscriptions import routes as subscriptions_routes-from .v1 import v1_routerapp = fastapi.FastAPI()-# Both halves of /credits now live in their own modules. v1_router stays mounted-# because this suite's role matrix still reaches routes left behind in it; every-# further layer that moves a /credits route has to add its router here too, and-# the durable fix is to give the request-level tests the real app as the two-# introspection tests already use.-app.include_router(v1_router)+# Every /credits route this matrix exercises now lives in one of these two+# modules; the durable fix is to give the request-level tests the real app as+# the two introspection tests already use.app.include_router(credits_routes.router)app.include_router(subscriptions_routes.router)client = fastapi.testclient.TestClient(app)@@ -109,7 +105,7 @@ class GatedRoute(pydantic.BaseModel):body: dict | None = None-# Every route in v1.py carrying+# Every route carrying# ``Security(requires_org_permission(OrgAction.MANAGE_BILLING))`` (via the# ``BillingManagerContext`` alias). Kept in sync with the app by# ``test_every_credits_route_is_gated_or_explicitly_exempt``; ``name`` is the@@ -388,9 +384,9 @@ def test_every_credits_route_is_gated_or_explicitly_exempt():table instead: every ``/credits*`` route must either carry the MANAGE_BILLINGdependency or be an explicit, documented exemption.- It walks ``real_app``, not a locally-mounted router: this layer moves the- credits routes out of ``v1_router``, so a ``v1_router``-only mount would see- nothing at all here and pass vacuously. (#14475's docstring asked for a+ It walks ``real_app``, not a locally-mounted router: a local mount only sees+ the routers this file happens to mount, so a ``/credits`` route served by any+ other one would pass vacuously. (#14475's docstring asked for a``PENDING_AUDIT`` set of names; T250.2's audit then found none of the eightneeds a gate, so they are asserted by what makes them safe instead — seeADMIN_CREDITS_ROUTES and TRIAL_CREDITS_ROUTES above, SECRT-2650.)diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 2ea3361102..0bc0a93f7c 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -69,7 +69,7 @@ import backend.api.features.store.routesimport backend.api.features.store.skill_routesimport backend.api.features.subscription_trial_routes as subscription_trial_routesimport backend.api.features.transfers.routes as transfer_routes-import backend.api.features.v1+import backend.api.features.user.routes as user_routesimport backend.api.features.workspace.folder_routes as workspace_folder_routesimport backend.api.features.workspace.routes as team_routesimport backend.data.autopilot_migrate@@ -393,7 +393,6 @@ app.add_exception_handler(app.add_exception_handler(PreconditionFailed, handle_internal_http_error(428))app.add_exception_handler(Exception, handle_internal_http_error(500))-app.include_router(backend.api.features.v1.v1_router, tags=["v1"], prefix="/api")app.include_router(backend.api.features.desktop_preview.router, tags=["v1"], prefix="/api")@@ -443,6 +442,11 @@ app.include_router(tags=["v1"],prefix="/api",)+app.include_router(+ user_routes.router,+ tags=["v1"],+ prefix="/api",+)app.include_router(auth_email_routes.auth_email_router,prefix="/api/auth/email",