Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions openhands/automation/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,25 @@ def _extract_credential(request: Request) -> tuple[str, AuthMethod]:
)


def _upstream_headers(
credential: str, auth_method: AuthMethod, x_org_id: str | None
) -> dict[str, str]:
headers = (
{"Authorization": f"Bearer {credential}"}
if auth_method == AuthMethod.API_KEY
else {"Cookie": f"{SESSION_COOKIE_NAME}={credential}"}
)
if x_org_id:
headers[X_ORG_ID_HEADER] = x_org_id
return headers


def upstream_auth_headers(request: Request) -> dict[str, str]:
"""Headers that carry the caller's own credential to the OpenHands API."""
credential, auth_method = _extract_credential(request)
return _upstream_headers(credential, auth_method, _extract_x_org_id(request))


def _parse_users_me(
data: dict[str, Any], auth_method: AuthMethod, credential: str
) -> AuthenticatedUser:
Expand Down Expand Up @@ -477,13 +496,7 @@ async def authenticate_request(

# --- Validate against OpenHands API ---
logger.debug("Auth cache miss, validating with OpenHands API")
outbound_headers = (
{"Authorization": f"Bearer {credential}"}
if auth_method == AuthMethod.API_KEY
else {"Cookie": f"{SESSION_COOKIE_NAME}={credential}"}
)
if x_org_id:
outbound_headers[X_ORG_ID_HEADER] = x_org_id
outbound_headers = _upstream_headers(credential, auth_method, x_org_id)

try:
resp = await _make_auth_request_with_retry(
Expand Down
56 changes: 42 additions & 14 deletions openhands/automation/capabilities_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import uuid
from zoneinfo import available_timezones

from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import ValidationError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
Expand Down Expand Up @@ -47,7 +47,8 @@
from openhands.automation.trigger_matcher import matches_trigger
from openhands.automation.utils.cron import min_interval_seconds
from openhands.automation.utils.model_profiles import (
validate_agent_profile_selection,
ensure_agent_profile_exists,
validate_agent_profile_combination,
validate_model_profile_for_user,
)
from openhands.automation.utils.webhook import get_webhook_config
Expand Down Expand Up @@ -105,9 +106,11 @@ async def get_capabilities(
builtin = builtin_sources() if config.service.webhook_secret else []
event_sources = sorted({*builtin, *await _custom_sources(user.org_id, session)})

features = [*_STATIC_FEATURES]
if config.service.is_local_mode:
features.append("agentProfiles")
# Not a packaged-code feature: the id is passed through to the run, whose
# conversation server resolves it - the Agent Server locally, the OpenHands
# app server in cloud, which has to be a version that serves
# /api/agent-profiles.
features = [*_STATIC_FEATURES, "agentProfiles"]
if event_sources:
features.append("webhookDelivery")
if config.kv.enabled:
Expand Down Expand Up @@ -139,6 +142,7 @@ async def get_capabilities(
@router.post("/validate")
async def validate_draft(
body: ValidateDraftRequest,
request: Request,
user: AuthenticatedUser = Depends(_require_view_automations),
session: AsyncSession = Depends(get_session),
) -> ValidateDraftResponse:
Expand All @@ -152,12 +156,31 @@ async def validate_draft(
"Validating draft for %s (automation_id=%s)", body.endpoint, body.automation_id
)

# A saved draft has no agent profile, so the draft shape does not know the
# field. Creation does, and preflight answers for creation: the profile
# skips the shape and is checked by the model creation itself uses.
shape = {k: v for k, v in body.draft.items() if k != "agent_profile_id"}
try:
normalized_draft = normalize_draft_body(body.endpoint, body.draft)
normalized_draft = normalize_draft_body(body.endpoint, shape)
if "agent_profile_id" in body.draft:
normalized_draft["agent_profile_id"] = body.draft["agent_profile_id"]
draft = FINAL_DRAFT_MODELS[body.endpoint].model_validate(normalized_draft)
except ValidationError as e:
return ValidateDraftResponse(valid=False, errors=_schema_errors(e))

# Asked first, before this request touches the database, and reported last.
# A failure to ask must not cost the caller the verdicts below: preflight is
# advisory and creation repeats the check, so the profile is left unjudged.
profile_error: DraftValidationError | None = None
if isinstance(draft, CreateAutomationRequest):
try:
await ensure_agent_profile_exists(draft.agent_profile_id, request, user)
except HTTPException as e:
if e.status_code == 422:
profile_error = _agent_profile_error(e)
else:
logger.warning("Preflight could not check the agent profile: %s", e)

errors: list[DraftValidationError] = []
sample_event_matched: bool | None = None

Expand All @@ -174,15 +197,9 @@ async def validate_draft(

if isinstance(draft, CreateAutomationRequest):
try:
validate_agent_profile_selection(draft.agent_profile_id, draft.model)
validate_agent_profile_combination(draft.agent_profile_id, draft.model)
except HTTPException as e:
errors.append(
DraftValidationError(
field="agent_profile_id",
code="invalid_agent_profile",
message=str(e.detail),
)
)
errors.append(_agent_profile_error(e))

trigger = draft.trigger
if isinstance(trigger, CronTrigger):
Expand Down Expand Up @@ -222,13 +239,24 @@ async def validate_draft(
trigger, trigger.source, event.event_key, body.sample_event
)

if profile_error is not None:
errors.append(profile_error)

return ValidateDraftResponse(
valid=not errors,
errors=errors,
sample_event_matched=sample_event_matched,
)


def _agent_profile_error(error: HTTPException) -> DraftValidationError:
return DraftValidationError(
field="agent_profile_id",
code="invalid_agent_profile",
message=str(error.detail),
)


async def _custom_sources(org_id: uuid.UUID, session: AsyncSession) -> list[str]:
"""Custom webhook sources this organization has enabled.

Expand Down
17 changes: 14 additions & 3 deletions openhands/automation/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@
fetch_latest_finish_tool_response_for_run,
)
from openhands.automation.utils.model_profiles import (
ensure_agent_profile_exists,
resolve_model_profile_for_user,
validate_agent_profile_selection,
validate_agent_profile_combination,
)
from openhands.automation.utils.run import (
create_pending_run,
Expand Down Expand Up @@ -214,6 +215,8 @@ async def create_automation(
An entry shipping its own tarball creates here rather than through a
preset, so it may carry the same ``template`` provenance those accept.
"""
validate_agent_profile_combination(body.agent_profile_id, body.model)

# Enabling the same template twice returns the existing automation rather
# than a duplicate. Before tarball validation, so a repeat enable costs one
# query and leaves the new upload unreferenced rather than adopting it.
Expand All @@ -225,14 +228,17 @@ async def create_automation(
response.status_code = status.HTTP_200_OK
return AutomationResponse.model_validate(existing)

# After the template lookup, so a repeat enable stays one query and does
# not depend on the OpenHands API, and before the rest of the transaction.
await ensure_agent_profile_exists(body.agent_profile_id, request, user)

# Validate tarball_path (checks ownership for internal uploads)
await validate_tarball_path(
tarball_path=body.tarball_path,
user_id=user.user_id,
org_id=user.org_id,
session=session,
)
validate_agent_profile_selection(body.agent_profile_id, body.model)
model = (
None
if body.agent_profile_id
Expand Down Expand Up @@ -423,7 +429,12 @@ async def update_automation(

if "agent_profile_id" in update_data or "model" in update_data:
selected_profile = update_data.get("agent_profile_id", auto.agent_profile_id)
validate_agent_profile_selection(selected_profile, body.model)
validate_agent_profile_combination(selected_profile, body.model)
if selected_profile != auto.agent_profile_id:
# Only a newly selected profile is looked up: an update that sends
# the current one back must not start failing because the profile
# was deleted since, or the OpenHands API is down.
await ensure_agent_profile_exists(selected_profile, request, user)
if selected_profile:
update_data["model"] = None
elif "model" in update_data:
Expand Down
110 changes: 104 additions & 6 deletions openhands/automation/utils/model_profiles.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
"""Helpers for resolving and validating model profile selections."""

import logging
import uuid

from fastapi import HTTPException, status
import httpx
from cachetools import TTLCache
from fastapi import HTTPException, Request, status

from openhands.automation.auth import AuthenticatedUser
from openhands.automation.auth import (
X_ORG_ID_HEADER,
AuthenticatedUser,
get_http_client,
upstream_auth_headers,
)


logger = logging.getLogger(__name__)

# The profile ids an organization was last seen to have. A setup form validates
# the same selection over and over, and only a hit is trusted: an id that is
# not here is always looked up, so a profile created a moment ago is found.
_known_profiles: TTLCache[uuid.UUID, frozenset[str]] = TTLCache(maxsize=1024, ttl=60)


def validate_model_profile_for_user(
Expand Down Expand Up @@ -41,15 +57,97 @@ def resolve_model_profile_for_user(
return model_profile


def validate_agent_profile_combination(
agent_profile_id: uuid.UUID | None, model: str | None
) -> None:
"""An agent profile owns its model, so the two cannot be selected together."""
if agent_profile_id is not None and model:
raise HTTPException(422, "An agent profile already specifies the model")


def validate_agent_profile_selection(
agent_profile_id: uuid.UUID | None, model: str | None
) -> None:
"""An agent profile owns its model and is resolved by the configured server."""
"""Validate a profile selected where no caller is present, as in git sync.

Without a caller there is no credential to check the profile against the
OpenHands app server with, so in cloud mode the selection is refused. A
caller's own selection goes through `ensure_agent_profile_exists` instead.
"""
if agent_profile_id is None:
return
from openhands.automation.config import get_config

if not get_config().service.is_local_mode:
raise HTTPException(422, "Agent profiles require a configured Agent Server")
if model:
raise HTTPException(422, "An agent profile already specifies the model")
raise HTTPException(
422,
"Agent profiles can only be selected through the API on this deployment",
)
validate_agent_profile_combination(agent_profile_id, model)


async def ensure_agent_profile_exists(
agent_profile_id: uuid.UUID | None, request: Request, user: AuthenticatedUser
) -> None:
"""Check a profile the caller selected against their organization.

A local deployment hands the id to its Agent Server, which resolves it. In
cloud mode the profiles belong to the caller's organization in the
OpenHands app server, which starts a conversation with default settings
rather than fail on an id it does not know, so an unknown id is refused
here. A profile deleted after this check still falls back at run time.

A miss asks the app server, so a caller that has a database transaction
open holds its connection for that long.
"""
if agent_profile_id is None:
return
from openhands.automation.config import get_config

settings = get_config().service
if settings.is_local_mode:
return
if str(agent_profile_id) in _known_profiles.get(user.org_id, ()):
return

# The organization the automation is stored under, not whichever one the
# caller's session happens to resolve to by now.
headers = {**upstream_auth_headers(request), X_ORG_ID_HEADER: str(user.org_id)}
try:
resp = await get_http_client(request).get(
f"{settings.openhands_api_base_url}/api/agent-profiles", headers=headers
)
except httpx.RequestError as exc:
raise HTTPException(
status.HTTP_502_BAD_GATEWAY,
"Failed to reach OpenHands API for agent profiles",
) from exc
if resp.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN):
# The credential was accepted from the auth cache but the app server no
# longer honours it; say so rather than report a gateway fault.
raise HTTPException(
resp.status_code, "OpenHands API refused the request for agent profiles"
)
try:
if resp.status_code != status.HTTP_200_OK:
raise ValueError(f"status {resp.status_code}")
profiles = resp.json()["profiles"]
known = frozenset(
str(profile["id"])
for profile in profiles
if isinstance(profile, dict) and profile.get("id")
)
except (ValueError, KeyError, TypeError) as exc:
logger.warning("Agent profile lookup failed: %s", exc)
raise HTTPException(
status.HTTP_502_BAD_GATEWAY,
"Unexpected response from OpenHands API for agent profiles",
) from exc
_known_profiles[user.org_id] = known
if str(agent_profile_id) not in known:
raise HTTPException(422, f"Agent profile `{agent_profile_id}` not found")


def clear_agent_profile_cache() -> None:
"""Forget the profiles seen so far. Tests use it to start clean."""
_known_profiles.clear()
Loading
Loading