Self-hosted AI workspace.
Python
refactor(auth): centralize the internal-tool pseudo-username into a constant (#4333)
Kenny Van de Maele7eaa8957447f
diff --git a/app.py b/app.pyindex 7ccf57f4f..1950c1b2f 100644--- a/app.py+++ b/app.py@@ -318,7 +318,7 @@ if AUTH_ENABLED:# (no admin cookie available in that context). Restricted to# loopback clients + matching token to keep it locked down.try:- from core.middleware import INTERNAL_TOOL_HEADER, INTERNAL_TOOL_TOKEN as _ITT+ from core.middleware import INTERNAL_TOOL_HEADER, INTERNAL_TOOL_TOKEN as _ITT, INTERNAL_TOOL_USER_hdr = request.headers.get(INTERNAL_TOOL_HEADER)if _hdr and secrets.compare_digest(_hdr, _ITT) and _is_trusted_loopback(request):# Impersonation: when the agent's loopback call sets@@ -330,7 +330,7 @@ if AUTH_ENABLED:if _impersonate and _impersonate in getattr(_auth_mgr, "users", {}):request.state.current_user = _impersonateelse:- request.state.current_user = "internal-tool"+ request.state.current_user = INTERNAL_TOOL_USERrequest.state.api_token = Falsereturn await call_next(request)except Exception as _e:diff --git a/core/auth.py b/core/auth.pyindex adad33b80..3bdf0f390 100644--- a/core/auth.py+++ b/core/auth.py@@ -20,6 +20,7 @@ logger = logging.getLogger(__name__)from core.atomic_io import atomic_write_json as _atomic_write_json # noqa: E402+from core.middleware import INTERNAL_TOOL_USER # noqa: E402DEFAULT_PRIVILEGES = {"can_use_agent": True,@@ -65,7 +66,7 @@ TOKEN_TTL = 60 * 60 * 24 * 7 # 7 days# of those names would be denied an assistant and inconsistently owner-scoped.# Refuse to create or rename into any of them so the sentinels can't be# impersonated. (Keep this in sync with that synthetic-owner set.)-RESERVED_USERNAMES = frozenset({"internal-tool", "api", "demo", "system"})+RESERVED_USERNAMES = frozenset({INTERNAL_TOOL_USER, "api", "demo", "system"})def normalize_known_username(users: Dict[str, Any], username: str | None) -> Optional[str]:diff --git a/core/middleware.py b/core/middleware.pyindex 550ee3bd7..92c62a08b 100644--- a/core/middleware.py+++ b/core/middleware.py@@ -15,6 +15,8 @@ from starlette.responses import Response# same value from this module. Never persisted or exposed externally.INTERNAL_TOOL_TOKEN = os.environ.get("ODYSSEUS_INTERNAL_TOKEN") or secrets.token_hex(32)INTERNAL_TOOL_HEADER = "X-Odysseus-Internal-Token"+# Pseudo-username on in-process tool-loopback requests; require_admin trusts it and it is reserved.+INTERNAL_TOOL_USER = "internal-tool"def is_cors_preflight(method: str, headers) -> bool:@@ -39,7 +41,7 @@ def require_admin(request: Request):hdr = request.headers.get(INTERNAL_TOOL_HEADER)if hdr and secrets.compare_digest(hdr, INTERNAL_TOOL_TOKEN):return- if getattr(request.state, "current_user", None) == "internal-tool":+ if getattr(request.state, "current_user", None) == INTERNAL_TOOL_USER:returnexcept Exception:passdiff --git a/routes/note_routes.py b/routes/note_routes.pyindex b7c064137..c4674e489 100644--- a/routes/note_routes.py+++ b/routes/note_routes.py@@ -10,6 +10,7 @@ from fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModelfrom core.database import SessionLocal, Note+from core.middleware import INTERNAL_TOOL_USERfrom src.auth_helpers import require_userfrom src.constants import DATA_DIRfrom sqlalchemy.orm.attributes import flag_modified@@ -582,7 +583,7 @@ def setup_note_routes(task_scheduler=None):return require_user(request) or Nonedef _is_admin_or_single_user(request: Request, user: str | None) -> bool:- if user == "internal-tool":+ if user == INTERNAL_TOOL_USER:return Trueif not user:# require_user() already admitted this request, which only happensdiff --git a/routes/research_routes.py b/routes/research_routes.pyindex 947789e5c..889298f7d 100644--- a/routes/research_routes.py+++ b/routes/research_routes.py@@ -12,6 +12,7 @@ from typing import Optionalfrom fastapi import APIRouter, HTTPException, Query, Requestfrom fastapi.responses import HTMLResponse, StreamingResponsefrom pydantic import BaseModel, Field+from core.middleware import INTERNAL_TOOL_USERfrom src.endpoint_resolver import resolve_endpointfrom src.auth_helpers import _auth_disabled, get_current_userfrom core.auth import RESERVED_USERNAMES@@ -386,7 +387,7 @@ def setup_research_routes(research_handler, session_manager=None) -> APIRouter:"""Launch a research job from the dedicated panel."""from src.auth_helpers import require_privilegeuser = require_privilege(request, "can_use_research")- if user == "internal-tool":+ if user == INTERNAL_TOOL_USER:tool_owner = (request.headers.get("X-Odysseus-Owner") or "").strip()if tool_owner and tool_owner not in RESERVED_USERNAMES:auth_mgr = getattr(request.app.state, "auth_manager", None)diff --git a/routes/shell_routes.py b/routes/shell_routes.pyindex b4e52325d..112b9fbca 100644--- a/routes/shell_routes.py+++ b/routes/shell_routes.py@@ -15,6 +15,7 @@ from collections import namedtuplefrom pathlib import Pathfrom typing import Dict, Anyfrom core.platform_compat import IS_APPLE_SILICON, which_tool+from core.middleware import INTERNAL_TOOL_USERfrom src.optional_deps import prepare_optional_dependency_import# POSIX-only: `pty`/`fcntl` transitively import `termios`, which does NOT exist@@ -55,7 +56,7 @@ def _require_admin(request: Request):# In-process tool loopback. The AuthMiddleware already validated the# internal token + loopback client before setting this marker, so# honour it here as admin-equivalent.- if user == "internal-tool":+ if user == INTERNAL_TOOL_USER:returnif not user or user == "api":raise HTTPException(403, "Admin only")diff --git a/routes/task_routes.py b/routes/task_routes.pyindex 5698353bf..d38040fde 100644--- a/routes/task_routes.py+++ b/routes/task_routes.py@@ -11,6 +11,7 @@ from fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModelfrom core.database import SessionLocal, ScheduledTask, TaskRun+from core.middleware import INTERNAL_TOOL_USERfrom core.constants import internal_api_basefrom src.auth_helpers import get_current_userfrom src.constants import DATA_DIR, EMAIL_URGENCY_CACHE_DIR@@ -427,7 +428,7 @@ def setup_task_routes(task_scheduler) -> APIRouter:# In-process tool-loopback marker — AuthMiddleware validated# the internal token + loopback client before stamping this,# so treat as admin-equivalent.- if user == "internal-tool":+ if user == INTERNAL_TOOL_USER:return Truetry:from core.auth import AuthManager