Skip to content
Closed
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
4 changes: 2 additions & 2 deletions dev_config/python/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ repos:
types-redis,
pydantic,
lxml,
"openhands-sdk==1.39.1",
"openhands-tools==1.39.1",
"openhands-sdk==1.50.1",
"openhands-tools==1.50.1",
"sqlalchemy==2.0.48",
"stripe==11.6.0",
"pygithub==2.6.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,38 @@ def _to_sdk_marketplace_registrations(
]


def _apply_profile_secret_scope(
secrets: dict[str, Any],
user: UserInfo,
) -> dict[str, Any]:
"""Narrow a conversation's secrets to the active agent profile's scope.

Mirrors the local agent-server, which filters ``request.secrets`` inside its
``agent_profile_id`` branch — a branch cloud never takes, because it resolves
the profile itself and sends a resolved agent. Without this the field would
persist and display while restricting nothing (OpenHands/enterprise#344).

Strict, matching ``openhands.sdk.profiles.resolver.filter_profile_secrets``:
nothing is added back for either agent kind, so a profile that omits its own
ACP provider credential — or a git provider token — does not receive it. A
ref matching no supplied secret is a harmless no-op; this is an allow-list
over what a launch assembles, so unlike ``mcp_server_refs`` it cannot dangle.

``None`` (the default, and every non-profile launch) leaves the set untouched.
"""
refs = getattr(user, 'active_agent_profile_secret_refs', None)
if refs is None:
return secrets
allowed = set(refs)
dropped = sorted(set(secrets) - allowed)
if dropped:
_logger.info(
'agent_profile_secret_scope:filtered',
extra={'dropped_secret_names': dropped},
)
return {name: value for name, value in secrets.items() if name in allowed}


@dataclass
class LiveStatusAppConversationService(AppConversationServiceBase):
"""AppConversationService which combines live status info from the sandbox with stored data."""
Expand Down Expand Up @@ -2249,6 +2281,10 @@ async def _build_start_conversation_request_for_user(
)
secrets[name] = StaticSecret(value=value)

# After the API merge, so a caller sending extra secrets cannot
# widen what the profile allows.
secrets = _apply_profile_secret_scope(secrets, user)

system_message_suffix = self._maybe_append_shallow_clone_context(
user, selected_repository, system_message_suffix
)
Expand Down Expand Up @@ -2622,6 +2658,10 @@ async def _build_acp_start_conversation_request(
)
secrets[name] = StaticSecret(value=value)

# After the API merge, so a caller sending extra secrets cannot
# widen what the profile allows.
secrets = _apply_profile_secret_scope(secrets, user)

system_message_suffix = self._maybe_append_shallow_clone_context(
user, selected_repository, system_message_suffix
)
Expand Down
6 changes: 6 additions & 0 deletions openhands/app_server/settings/settings_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,12 @@ class Settings(BaseModel):
# None and ``store()`` refuses instances that carry them (no backing column).
active_agent_profile_id: str | None = None
active_agent_profile_revision: int | None = None
# The resolved profile's ``secret_refs`` allow-list, carried alongside the
# provenance above for the same reason: resolution replaces
# ``agent_settings`` with an ``AgentSettings`` dump, which has no field for
# it, and conversation-start needs it to scope the conversation's secrets.
# ``None`` = unrestricted, matching the SDK's tri-state.
active_agent_profile_secret_refs: list[str] | None = None

# True when this instance came from a resolve-requested load: its
# agent_settings are the *effective* launch view (possibly an Agent
Expand Down
15 changes: 12 additions & 3 deletions storage/saas_settings_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def _resolve_active_agent_profile(
effective_llm_api_key: SecretStr | None,
override_agent_profile_id: str | None = None,
llm_profiles: LLMProfiles | None = None,
) -> tuple[dict[str, Any], str, int] | None:
) -> tuple[dict[str, Any], str, int, list[str] | None] | None:
"""Resolve an agent profile into an ``agent_settings`` dump.

Resolves ``override_agent_profile_id`` when given (a one-off,
Expand Down Expand Up @@ -390,7 +390,10 @@ def _resolve_active_agent_profile(
exc,
)
return None
return resolved_dump, str(profile.id), profile.revision
# ``secret_refs`` rides out alongside the provenance: the resolved dump
# is an ``AgentSettings``, which has no field for it, and conversation
# start needs it to scope the conversation's secrets.
return resolved_dump, str(profile.id), profile.revision, profile.secret_refs

async def load(
self,
Expand Down Expand Up @@ -656,10 +659,16 @@ async def load(
live_llm_profiles,
)
if resolved is not None:
resolved_dump, resolved_id, resolved_revision = resolved
(
resolved_dump,
resolved_id,
resolved_revision,
resolved_secret_refs,
) = resolved
kwargs['agent_settings'] = resolved_dump
kwargs['active_agent_profile_id'] = resolved_id
kwargs['active_agent_profile_revision'] = resolved_revision
kwargs['active_agent_profile_secret_refs'] = resolved_secret_refs

settings = Settings(**kwargs)
settings._mcp_config_updated = False
Expand Down
132 changes: 127 additions & 5 deletions tests/unit/test_agent_profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@
from fastapi.testclient import TestClient
from sqlalchemy import select, update

from openhands.app_server.app_conversation.live_status_app_conversation_service import (
_apply_profile_secret_scope,
)
from openhands.app_server.settings.agent_profiles import (
MAX_AGENT_PROFILES,
AgentProfiles,
)
from openhands.app_server.settings.settings_models import Settings
from openhands.app_server.user.user_models import UserInfo
from openhands.app_server.user_auth import get_user_id
from openhands.sdk.profiles import (
ACPAgentProfile,
Expand Down Expand Up @@ -721,7 +726,7 @@ def test_falls_back_to_org_wide_active_pointer_when_member_pointer_unset(self):

result = store._resolve_active_agent_profile(org, member, {}, None)
assert result is not None
_dump, resolved_id, _revision = result
_dump, resolved_id, _revision, _refs = result
assert resolved_id == pid

def test_stale_pointer_falls_back_to_none(self):
Expand All @@ -744,7 +749,7 @@ def test_resolves_openhands_profile_and_returns_provenance(self):

result = store._resolve_active_agent_profile(org, member, {}, None)
assert result is not None
dump, resolved_id, revision = result
dump, resolved_id, revision, _refs = result
assert resolved_id == pid
assert revision == 0
assert dump['agent_kind'] == 'openhands'
Expand Down Expand Up @@ -778,7 +783,7 @@ def test_resolves_profile_with_legacy_mcp_config(self):
)

assert result is not None
dump, _resolved_id, _revision = result
dump, _resolved_id, _revision, _refs = result
assert set(dump['mcp_config']) == {'shttp'}
assert dump['mcp_config']['shttp']['auth'] == {
'strategy': 'bearer',
Expand Down Expand Up @@ -819,7 +824,7 @@ def test_resolve_canonicalizes_legacy_litellm_proxy_llm(self):

result = store._resolve_active_agent_profile(org, member, {}, None)
assert result is not None
dump, _resolved_id, _revision = result
dump, _resolved_id, _revision, _refs = result
assert dump['llm']['model'] == 'openhands/claude-opus-5'
assert dump['llm'].get('base_url') is None

Expand All @@ -835,7 +840,7 @@ def test_override_id_wins_over_member_pointer(self):
org, member, {}, None, override_agent_profile_id=pid
)
assert result is not None
_dump, resolved_id, _revision = result
_dump, resolved_id, _revision, _refs = result
assert resolved_id == pid

def test_override_id_does_not_mutate_member_pointer(self):
Expand Down Expand Up @@ -1382,3 +1387,120 @@ async def test_admin_can_save_profile_201(
)

assert response.status_code == status.HTTP_201_CREATED


class TestProfileSecretScope:
"""``secret_refs`` must reach the launch, and narrow its secrets there.

The local agent-server filters ``request.secrets`` inside its
``agent_profile_id`` branch — a branch cloud never takes, since it resolves
the profile itself and sends a resolved agent. These cover the cloud-side
equivalent (OpenHands/enterprise#344).
"""

def _user(self, refs):
return UserInfo(active_agent_profile_secret_refs=refs)

SENT = {
'DATADOG_API_KEY': 'dd',
'GITHUB_TOKEN': 'gh',
'ANTHROPIC_API_KEY': 'ak',
}

def test_an_unscoped_profile_leaves_the_secrets_untouched(self):
assert (
_apply_profile_secret_scope(dict(self.SENT), self._user(None)) == self.SENT
)

def test_a_scoped_profile_keeps_only_the_named_secrets(self):
got = _apply_profile_secret_scope(
dict(self.SENT), self._user(['DATADOG_API_KEY'])
)
assert got == {'DATADOG_API_KEY': 'dd'}

def test_an_empty_scope_keeps_nothing(self):
assert _apply_profile_secret_scope(dict(self.SENT), self._user([])) == {}

def test_a_git_provider_token_is_not_exempt(self):
# Strict: GITHUB_TOKEN rides the same channel and is dropped when the
# profile does not list it. Intended, and the reason the editor shows
# what a scope excludes.
got = _apply_profile_secret_scope(
dict(self.SENT), self._user(['DATADOG_API_KEY'])
)
assert 'GITHUB_TOKEN' not in got

def test_an_acp_provider_credential_is_not_exempt(self):
got = _apply_profile_secret_scope(
dict(self.SENT), self._user(['DATADOG_API_KEY'])
)
assert 'ANTHROPIC_API_KEY' not in got

def test_a_ref_matching_no_supplied_secret_is_a_no_op(self):
got = _apply_profile_secret_scope(
dict(self.SENT), self._user(['DATADOG_API_KEY', 'NEVER_SUPPLIED'])
)
assert got == {'DATADOG_API_KEY': 'dd'}

def test_secret_refs_survive_the_settings_to_user_info_projection(self):
"""The seam that would silently disable the scope if it regressed.

``AuthUserContext._user_info_from_settings`` rebuilds ``UserInfo`` from
``settings.model_dump()``. If that ever became a field-by-field copy,
the refs would be dropped, the filter would read ``None``, and every
scoped profile would quietly launch unrestricted.
"""
settings = Settings(
active_agent_profile_id='pid',
active_agent_profile_secret_refs=['DATADOG_API_KEY'],
)
user = UserInfo(
id='u1', **settings.model_dump(context={'expose_secrets': True})
)
assert user.active_agent_profile_secret_refs == ['DATADOG_API_KEY']
assert _apply_profile_secret_scope(
{'DATADOG_API_KEY': 'dd', 'GITHUB_TOKEN': 'gh'}, user
) == {'DATADOG_API_KEY': 'dd'}

def test_a_deployment_without_agent_profiles_is_unrestricted(self):
"""The file-backed store resolves no profile, so nothing is scoped.

``FileSettingsStore.load`` discards the resolve flags outright, so the
refs stay ``None`` there and the filter must be a pass-through rather
than an empty allow-list.
"""
user = UserInfo(id='u1')
sent = {'GITHUB_TOKEN': 'gh', 'DATADOG_API_KEY': 'dd'}
assert _apply_profile_secret_scope(dict(sent), user) == sent

def test_resolution_carries_secret_refs_out_of_the_store(self):
"""Without this the filter above would silently never fire."""
with patch('storage.database.a_session_maker'):
from storage.saas_settings_store import SaasSettingsStore
store = SaasSettingsStore(str(USER_ID))

org = MagicMock(spec=Org)
org.id = ORG_ID
ap = AgentProfiles()
save_profile_preserving_identity(
ap,
OpenHandsAgentProfile(
name='scoped',
llm_profile_ref='Default',
secret_refs=['DATADOG_API_KEY'],
),
)
org.agent_profiles = ap.model_dump(
mode='json', context={'expose_secrets': True}
)
org.llm_profiles = {
'profiles': {'Default': {'model': 'gpt-4o', 'api_key': 'orgkey'}},
'active': 'Default',
}
member = MagicMock(spec=OrgMember)
member.active_agent_profile_id = next(iter(ap.profiles.values())).id

result = store._resolve_active_agent_profile(org, member, {}, None)
assert result is not None
_dump, _id, _revision, refs = result
assert refs == ['DATADOG_API_KEY']
Loading