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
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ Routes: `GET /api/automation/v1/kv`, `GET /api/automation/v1/kv/{key}`,
`--automation-id` for a missing claim).
- Users, Agent Canvas and spawned conversations: the normal API key
(`X-Session-API-Key` or `Authorization: Bearer <key>`) plus
`?automation_id=`; membership in the automation's org is the check.
`?automation_id=` of an automation in the caller's org. Reads need
`view_automations`; writes also need the right to edit that automation
(`manage_automations`, or being the user it runs as, never a service
account), 403 otherwise. The local key has both permissions.
- Capability discovery: `GET /v1/capabilities` lists `kvStore` in
`features` only while the secret is set.
- Config: `AUTOMATION_KV_SECRET` (required; signs tokens, encrypts values),
Expand Down
1 change: 1 addition & 0 deletions docs/kv-store-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ prefix, never on the reason text.
| 400 | `automation_id query parameter is required for user-authenticated KV access` | User credentials without `?automation_id=` |
| 400 | `{"error": "operation_failed", "message", "operation_index", "operation"}` | A batch operation failed; nothing in the batch was applied |
| 401 | `Missing token`, `Invalid authorization header format`, `Invalid or expired KV token`, `Authentication required: ...` | No usable KV token or user credentials (an expired token is a 401 too) |
| 403 | `Requires view_automations permission`, `Only admins, owners, or the automation creator can modify it` | User credentials without `view_automations`, or a write to an automation the user may not modify |
| 404 | `key_not_found` | Key does not exist |
| 404 | `invalid_path` | GET `?path=` is well formed but names a field the value does not have |
| 404 | `Automation not found` | The token's (or `?automation_id=`'s) automation does not exist or is not accessible |
Expand Down
33 changes: 24 additions & 9 deletions openhands/automation/kv_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
KVSetResponse,
)
from openhands.automation.models import Automation, AutomationKV, AutomationKVMeta
from openhands.automation.router import _assert_can_manage
from openhands.automation.utils.kv import KVTokenClaims, KVTokenError, verify_kv_token


Expand Down Expand Up @@ -120,8 +121,8 @@ class KVAuthContext:

2. User authentication (API key / X-Session-API-Key / cookie) — used by
humans and spawned conversations acting on a user's behalf. Requires
an ``automation_id`` query parameter; the user must be a member of the
automation's org.
an ``automation_id`` query parameter; ``_verify_automation_access``
decides what the user may do with that automation's data.
"""

automation_id: uuid.UUID
Expand Down Expand Up @@ -185,13 +186,21 @@ async def _verify_automation_access(
session: AsyncSession,
user: AuthenticatedUser,
automation_id: uuid.UUID,
*,
write: bool,
) -> None:
"""Verify that the user has access to the given automation's KV data.
"""Verify that the user may read, or also write, the automation's KV data.

The user must be a member of the automation's org (view_automations).
Unlike management endpoints, we do not require manage_automations for KV
reads — a member who can see the automation can inspect its state.
Every request needs ``view_automations`` and an automation in the user's
org: a member who can see the automation can inspect its state. A write
must also pass ``_assert_can_manage``, the rule for modifying the
automation itself. A run needs neither: it uses its KV token.
"""
if "view_automations" not in user.permissions:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Requires view_automations permission",
)
result = await session.execute(
select(Automation).where(Automation.id == automation_id)
)
Expand All @@ -201,6 +210,8 @@ async def _verify_automation_access(
if automation.org_id != user.org_id:
# Don't leak existence — return 404 rather than 403
raise _automation_not_found()
if write:
await _assert_can_manage(automation, user)


async def _try_resolve_user(
Expand Down Expand Up @@ -231,6 +242,7 @@ async def _try_resolve_user(


async def get_kv_auth_context(
request: Request,
authorization: Annotated[str | None, Header()] = None,
user: Annotated[AuthenticatedUser | None, Depends(_try_resolve_user)] = None,
automation_id: Annotated[
Expand All @@ -254,8 +266,8 @@ async def get_kv_auth_context(

2. **User auth** (humans / spawned conversations): Standard OpenHands
authentication (API key, X-Session-API-Key, or cookie). Requires an
``automation_id`` query parameter; the user must be in the automation's
org.
``automation_id`` query parameter; reads need ``view_automations``,
and writes also the right to modify that automation.

The KV JWT path is checked first so existing automation scripts continue
to work without changes. If the Bearer token is not a JWT (or is absent),
Expand Down Expand Up @@ -302,7 +314,10 @@ async def get_kv_auth_context(
),
)

await _verify_automation_access(session, user, automation_id)
# Every KV route that changes data uses a method other than GET.
await _verify_automation_access(
session, user, automation_id, write=request.method != "GET"
)

return KVAuthContext(
automation_id=automation_id,
Expand Down
155 changes: 149 additions & 6 deletions tests/test_kv_user_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

These tests verify that KV endpoints accept user authentication (API key /
X-Session-API-Key) in addition to the existing per-run KV JWT tokens. User
auth requires an ``automation_id`` query parameter and checks org membership.
auth requires an ``automation_id`` query parameter and checks org membership,
``view_automations`` for reads and the right to modify the automation for
writes.

Uses SQLite (no Docker required) and overrides ``authenticate_request`` to
mock user identity.
Expand All @@ -26,8 +28,17 @@
from openhands.automation.config import clear_config_cache, get_config
from openhands.automation.db import get_session, set_sqlite_mode
from openhands.automation.kv_router import _try_resolve_user
from openhands.automation.models import Automation, AutomationKV, Base
from openhands.automation.utils.kv import create_kv_token, encrypt_value
from openhands.automation.models import (
Automation,
AutomationKV,
AutomationRunAsKind,
Base,
)
from openhands.automation.utils.kv import (
create_kv_token,
decrypt_value,
encrypt_value,
)


TEST_USER_ID = uuid.UUID("12345678-1234-5678-1234-567812345678")
Expand All @@ -36,6 +47,8 @@
TEST_AUTOMATION_ID = uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
OTHER_AUTOMATION_ID = uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
TEST_RUN_ID = uuid.UUID("cccccccc-cccc-cccc-cccc-cccccccccccc")
TEAMMATE_USER_ID = uuid.UUID("dddddddd-dddd-dddd-dddd-dddddddddddd")
TEAMMATE_AUTOMATION_ID = uuid.UUID("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee")
TEST_KV_SECRET = "test-kv-secret-key-for-testing-only"

# Base path prefix for all KV endpoints (matches app configuration)
Expand Down Expand Up @@ -234,16 +247,32 @@ async def test_automation(sqlite_session):
entrypoint="uv run script.py",
)
sqlite_session.add(other)

# And one in the same org that runs as another member
teammate = Automation(
id=TEAMMATE_AUTOMATION_ID,
user_id=TEAMMATE_USER_ID,
org_id=TEST_ORG_ID,
name="Teammate Automation",
trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"},
tarball_path="s3://bucket/code.tar.gz",
entrypoint="uv run script.py",
)
sqlite_session.add(teammate)
await sqlite_session.commit()
return automation


def seed_keys(session: AsyncSession, mapping: dict) -> None:
"""Seed per-key rows for TEST_AUTOMATION_ID."""
def seed_keys(
session: AsyncSession,
mapping: dict,
automation_id: uuid.UUID = TEST_AUTOMATION_ID,
) -> None:
"""Seed per-key rows for an automation (TEST_AUTOMATION_ID by default)."""
for key, value in mapping.items():
session.add(
AutomationKV(
automation_id=TEST_AUTOMATION_ID,
automation_id=automation_id,
key=key,
value_encrypted=encrypt_value(TEST_KV_SECRET, value),
)
Expand Down Expand Up @@ -383,6 +412,120 @@ async def test_x_session_api_key_header_works(
assert resp.status_code == 200


# ---------------------------------------------------------------------------
# User auth: permissions
# ---------------------------------------------------------------------------


class TestUserAuthPermissions:
"""Reads need view_automations; writes need the right to modify the automation."""

async def test_member_can_read_a_teammates_automation(
self, kv_user_client, test_automation, sqlite_session
):
"""A member reads the KV data of an automation that runs as someone else."""
seed_keys(sqlite_session, {"cursor": 42}, TEAMMATE_AUTOMATION_ID)
await sqlite_session.commit()

resp = await kv_user_client.get(
f"{_KV}/cursor",
params={"automation_id": str(TEAMMATE_AUTOMATION_ID)},
headers={"Authorization": "Bearer test-api-key"},
)

assert resp.status_code == 200
assert resp.json()["value"] == 42

@pytest.mark.parametrize(
("method", "path", "body"),
[
("PUT", "/count", 2),
("PATCH", "/config", {"path": "a", "value": 2}),
("DELETE", "/count", None),
("POST", "/count/incr", None),
("POST", "/count/decr", None),
("POST", "/items/lpush", {"value": "b"}),
("POST", "/items/rpush", {"value": "b"}),
("POST", "/items/lpop", None),
("POST", "/items/rpop", None),
(
"POST",
"/batch",
{"operations": [{"op": "set", "key": "count", "value": 2}]},
),
],
)
async def test_member_cannot_change_a_teammates_automation(
self, kv_user_client, test_automation, sqlite_session, method, path, body
):
"""Every write route refuses a member who may not modify the automation."""
seeded = {"count": 1, "items": ["a"], "config": {"a": 1}}
seed_keys(sqlite_session, seeded, TEAMMATE_AUTOMATION_ID)
await sqlite_session.commit()

resp = await kv_user_client.request(
method,
f"{_KV}{path}",
params={"automation_id": str(TEAMMATE_AUTOMATION_ID)},
headers={"Authorization": "Bearer test-api-key"},
json=body,
)

assert resp.status_code == 403
stored = await sqlite_session.execute(
select(AutomationKV.key, AutomationKV.value_encrypted).where(
AutomationKV.automation_id == TEAMMATE_AUTOMATION_ID
)
)
assert {
key: decrypt_value(TEST_KV_SECRET, value) for key, value in stored
} == seeded

async def test_admin_can_write_a_teammates_automation(
self, kv_admin_client, test_automation
):
"""A holder of manage_automations writes any automation's KV in the org."""
resp = await kv_admin_client.put(
f"{_KV}/cursor",
params={"automation_id": str(TEAMMATE_AUTOMATION_ID)},
headers={"Authorization": "Bearer test-api-key"},
json=43,
)

assert resp.status_code == 201

async def test_caller_without_view_permission_cannot_read(
self, kv_user_client, mock_user, test_automation
):
"""Without view_automations even the caller's own automation is refused."""
mock_user.permissions = ["view_org_settings"]

resp = await kv_user_client.get(
_KV,
params={"automation_id": str(TEST_AUTOMATION_ID)},
headers={"Authorization": "Bearer test-api-key"},
)

assert resp.status_code == 403

async def test_service_account_cannot_write_the_automation_it_runs(
self, kv_user_client, mock_user, test_automation, sqlite_session
):
"""A service account's key gets no write; its runs use the KV token."""
mock_user.role = "service_account"
test_automation.run_as_kind = AutomationRunAsKind.SERVICE
await sqlite_session.commit()

resp = await kv_user_client.put(
f"{_KV}/cursor",
params={"automation_id": str(TEST_AUTOMATION_ID)},
headers={"Authorization": "Bearer test-api-key"},
json=1,
)

assert resp.status_code == 403


# ---------------------------------------------------------------------------
# KV token auth still works
# ---------------------------------------------------------------------------
Expand Down
Loading