Skip to content

Self-improving AI Employees for everyone

fix(identity): one principal resolver, cron identity + routing, drop dead route

trohitg9f2dff7c553d
diff --git a/server/nodes/scheduler/cron_scheduler/_workflow.py b/server/nodes/scheduler/cron_scheduler/_workflow.py
index bad3f446..6d462371 100644
--- a/server/nodes/scheduler/cron_scheduler/_workflow.py
+++ b/server/nodes/scheduler/cron_scheduler/_workflow.py
@@ -125,6 +125,7 @@ class CronTriggerWorkflow:
from services.temporal.trigger_listener_workflow import (
event_workflow_search_attributes,
)
+ from services.temporal.workflow import TEMPORAL_ROUTING_INPUT_KEY
# A spawned run may execute — or stay cooperatively paused — for
# months, and Temporal's timeout timer keeps ticking through a
@@ -152,6 +153,24 @@ class CronTriggerWorkflow:
"workflow_id": deployment_workflow_id,
"workflow_slug": workflow_slug,
"tenant_id": tenant_id,
+ # Forward the deployer's identity and the frozen routing
+ # snapshot. Omitting them made every cron firing run as
+ # the anonymous owner AND fall back to the safe routing
+ # default, silently bypassing per-queue rate limits.
+ **{
+ key: listener_data[key]
+ for key in ("user_id", "graphVersion", "generation")
+ if key in listener_data
+ },
+ **(
+ {
+ TEMPORAL_ROUTING_INPUT_KEY: listener_data[
+ TEMPORAL_ROUTING_INPUT_KEY
+ ]
+ }
+ if TEMPORAL_ROUTING_INPUT_KEY in listener_data
+ else {}
+ ),
}
],
**child_options,
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index e7cff52e..e2bc8c8d 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -463,15 +463,7 @@ async def handle_execute_node(data: Dict[str, Any], websocket: WebSocket) -> Dic
)
if key in data
}
- socket_path = str((getattr(websocket, "scope", {}) or {}).get("path") or "")
- user_id = str(
- (
- data.get("user_id")
- if socket_path == "/ws/internal"
- else getattr(getattr(websocket, "state", None), "user_id", None)
- )
- or "owner"
- )
+ user_id = execution_principal(data, websocket)
await broadcaster.update_node_status(
node_id,
@@ -962,10 +954,7 @@ async def handle_execute_workflow(data: Dict[str, Any], websocket: WebSocket) ->
session_id=session_id,
status_callback=status_callback,
workflow_id=workflow_id,
- user_id=str(
- getattr(getattr(websocket, "state", None), "user_id", None)
- or "owner"
- ),
+ user_id=execution_principal(data, websocket),
)
finally:
# Always release the active-run counter so the button never gets stuck
@@ -1007,15 +996,7 @@ async def handle_execute_ai_node(data: Dict[str, Any], websocket: WebSocket) ->
node_id, node_type = data["node_id"], data["node_type"]
workflow_id = data.get("workflow_id") # Per-workflow isolation for tool node glowing
execution_id = str(data.get("execution_id") or uuid.uuid4().hex)
- socket_path = str((getattr(websocket, "scope", {}) or {}).get("path") or "")
- user_id = str(
- (
- data.get("user_id")
- if socket_path == "/ws/internal"
- else getattr(getattr(websocket, "state", None), "user_id", None)
- )
- or "owner"
- )
+ user_id = execution_principal(data, websocket)
await broadcaster.update_node_status(node_id, "executing", {"execution_id": execution_id}, workflow_id=workflow_id)
await broadcaster.workflow_run_started(workflow_id)
@@ -1451,7 +1432,7 @@ async def handle_refresh_model_registry(data: Dict[str, Any], websocket: WebSock
from services.ws_handler_registry import get_ws_handlers
-from services.authz import resolve_internal_handler # noqa: E402
+from services.authz import execution_principal, resolve_internal_handler # noqa: E402
def _resolve_handler(msg_type: str):
diff --git a/server/routers/workflow.py b/server/routers/workflow.py
index 77b7c55c..1b62dded 100644
--- a/server/routers/workflow.py
+++ b/server/routers/workflow.py
@@ -2,9 +2,9 @@
from fastapi import APIRouter, Depends
from pydantic import BaseModel
-from typing import Dict, Any, List, Optional
-from uuid import uuid4
+from typing import Dict, Any
+from constants import OWNER_PRINCIPAL_ID
from core.container import container
from services.workflow import WorkflowService
from services.status_broadcaster import get_status_broadcaster
@@ -14,103 +14,6 @@ logger = get_logger(__name__)
router = APIRouter(prefix="/api/workflow", tags=["workflow"])
-class WorkflowExecutionRequest(BaseModel):
- node_id: str
- node_type: str
- parameters: Dict[str, Any] = {}
- nodes: List[Dict[str, Any]] = []
- edges: List[Dict[str, Any]] = []
- session_id: str = "default"
- workflow_id: Optional[str] = None
- execution_id: Optional[str] = None
-
-
[email protected]("/execute-node")
-async def execute_workflow_node(
- request: WorkflowExecutionRequest, workflow_service: WorkflowService = Depends(lambda: container.workflow_service())
-):
- """Execute a single node in a workflow with parameter resolution."""
- logger.debug(f"[DEBUG ROUTER] Received execution request: node_id={request.node_id}, node_type={request.node_type}")
- execution_id = request.execution_id or uuid4().hex
-
- # Get broadcaster and send "executing" status
- broadcaster = get_status_broadcaster()
- await broadcaster.update_node_status(
- node_id=request.node_id,
- status="executing",
- data={"node_type": request.node_type, "execution_id": execution_id},
- workflow_id=request.workflow_id,
- )
-
- try:
- result = await workflow_service.execute_node(
- node_id=request.node_id,
- node_type=request.node_type,
- parameters=request.parameters,
- nodes=request.nodes,
- edges=request.edges,
- session_id=request.session_id,
- execution_id=execution_id,
- workflow_id=request.workflow_id,
- )
- result.setdefault("execution_id", execution_id)
-
- # Broadcast completion status based on result
- if result.get("success"):
- success_data = {
- "node_type": request.node_type,
- "execution_id": execution_id,
- "execution_time": result.get("execution_time"),
- "result": result.get("result"),
- }
- await broadcaster.update_node_status(
- node_id=request.node_id,
- status="success",
- data=success_data,
- workflow_id=request.workflow_id,
- )
- # Also broadcast the output
- if result.get("result"):
- raw_result = result.get("result")
- correlated_output = (
- {**raw_result, "execution_id": execution_id}
- if isinstance(raw_result, dict)
- else {"result": raw_result, "execution_id": execution_id}
- )
- await broadcaster.update_node_output(
- node_id=request.node_id,
- output=correlated_output,
- workflow_id=request.workflow_id,
- )
- else:
- await broadcaster.update_node_status(
- node_id=request.node_id,
- status="error",
- data={
- "node_type": request.node_type,
- "execution_id": execution_id,
- "error": result.get("error"),
- },
- workflow_id=request.workflow_id,
- )
-
- return result
-
- except Exception as e:
- # Broadcast error status
- await broadcaster.update_node_status(
- node_id=request.node_id,
- status="error",
- data={
- "node_type": request.node_type,
- "execution_id": execution_id,
- "error": str(e),
- },
- workflow_id=request.workflow_id,
- )
- raise
-
-
@router.get("/node-output/{node_id}")
async def get_workflow_node_output(
node_id: str,
@@ -212,6 +115,10 @@ async def execute_node_for_temporal(
session_id=context.get("session_id", "temporal"),
execution_id=context.get("execution_id"),
workflow_id=context.get("workflow_id"),
+ # The caller is a Temporal activity relaying an identity minted
+ # server-side at deploy time. Without this the node executes as
+ # the anonymous owner regardless of who deployed the workflow.
+ user_id=str(context.get("user_id") or OWNER_PRINCIPAL_ID),
extras=invocation_extras or None,
)
logger.info(
diff --git a/server/services/authz/__init__.py b/server/services/authz/__init__.py
index ab09d84a..c27733ba 100644
--- a/server/services/authz/__init__.py
+++ b/server/services/authz/__init__.py
@@ -6,10 +6,12 @@ directly and the boundary stays greppable.
from services.authz.ws_surface import (
INTERNAL_SOCKET_HANDLERS,
+ execution_principal,
resolve_internal_handler,
)
__all__ = [
"INTERNAL_SOCKET_HANDLERS",
+ "execution_principal",
"resolve_internal_handler",
]
diff --git a/server/services/authz/ws_surface.py b/server/services/authz/ws_surface.py
index 223b8cd5..bfa71ae9 100644
--- a/server/services/authz/ws_surface.py
+++ b/server/services/authz/ws_surface.py
@@ -22,7 +22,7 @@ being a silent privilege grant.
from __future__ import annotations
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Mapping, Optional
#: Everything the activity worker legitimately needs. Both execute
#: handlers already carry their own ``/ws/internal`` identity branch.
@@ -51,4 +51,32 @@ def resolve_internal_handler(
return resolver(msg_type)
-__all__ = ["INTERNAL_SOCKET_HANDLERS", "resolve_internal_handler"]
+def execution_principal(data: Mapping[str, Any], websocket: Any) -> str:
+ """Resolve the identity an execution runs as.
+
+ One implementation for every execute handler. They previously had three
+ slightly different copies: two honoured a payload-supplied ``user_id``
+ on the internal worker socket and one did not, so the same request
+ executed as a different principal depending on which handler received
+ it.
+
+ A payload-supplied ``user_id`` is trusted ONLY on ``/ws/internal``,
+ where the sender is a Temporal activity relaying identity that was
+ minted server-side at deploy time. On any authenticated socket the
+ handshake identity wins and the payload is ignored.
+ """
+ from constants import OWNER_PRINCIPAL_ID
+
+ scope = getattr(websocket, "scope", {}) or {}
+ if str(scope.get("path") or "") == "/ws/internal":
+ candidate = data.get("user_id")
+ else:
+ candidate = getattr(getattr(websocket, "state", None), "user_id", None)
+ return str(candidate or OWNER_PRINCIPAL_ID)
+
+
+__all__ = [
+ "INTERNAL_SOCKET_HANDLERS",
+ "execution_principal",
+ "resolve_internal_handler",
+]
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 07f3c72c..9688af3e 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -778,6 +778,9 @@ class DeploymentManager:
workflow_type_name = _POLLING_LISTENER_WORKFLOW_TYPE if is_polling else _PUSH_LISTENER_WORKFLOW_TYPE
trigger_kind = "polling" if is_polling else self._trigger_kind_for(node_type)
+ from services.temporal.executor import (
+ capture_temporal_routing_input,
+ )
from services.workflow_naming import node_label_slug
trigger_label = node_label_slug(node)
@@ -785,9 +788,6 @@ class DeploymentManager:
# workflow_id for tests / direct-call paths that bypass deploy.
slug = state.workflow_slug or workflow_id
listener_id = self._listener_workflow_id(slug, trigger_label)
- from services.temporal.executor import (
- capture_temporal_routing_input,
- )
# ``trigger_label`` flows into the per-firing run id
# (``<slug>-<label>-<event_id>``) inside both child workflows so
@@ -972,6 +972,7 @@ class DeploymentManager:
if state is None:
raise RuntimeError(f"No deployment state for workflow {workflow_id}")
+ from services.temporal.executor import capture_temporal_routing_input
from services.workflow_naming import node_label_slug
trigger_label = node_label_slug(node)
@@ -991,6 +992,14 @@ class DeploymentManager:
"nodes": state.nodes,
"edges": state.edges,
"session_id": state.session_id,
+ # Without this every cron-fired run executes as the anonymous
+ # owner, regardless of who deployed it. The sibling push/poll
+ # listener path has always carried it.
+ "user_id": state.user_id,
+ # Cron was the only one of four start sites not freezing the
+ # routing snapshot, so its runs fell back to the safe default
+ # (worker pool OFF) and silently bypassed per-queue rate limits.
+ **capture_temporal_routing_input(),
}
schedule_id = await create_cron_schedule(