mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
AI task generation permissions (#185004)
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
"""Permission checks for AI tasks."""
|
||||
|
||||
from homeassistant.auth.permissions.const import POLICY_CONTROL, POLICY_READ
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import Unauthorized, UnknownUser
|
||||
|
||||
|
||||
async def async_check_permissions(
|
||||
hass: HomeAssistant,
|
||||
entity_id: str | None,
|
||||
attachments: list[dict] | None,
|
||||
context: Context | None,
|
||||
) -> None:
|
||||
"""Check access to explicitly selected entities and entity attachments."""
|
||||
if context is None or context.user_id is None:
|
||||
return
|
||||
|
||||
if (user := await hass.auth.async_get_user(context.user_id)) is None:
|
||||
raise UnknownUser(context=context)
|
||||
|
||||
if entity_id is not None and not user.permissions.check_entity(
|
||||
entity_id, POLICY_CONTROL
|
||||
):
|
||||
raise Unauthorized(
|
||||
context=context, entity_id=entity_id, permission=POLICY_CONTROL
|
||||
)
|
||||
|
||||
for attachment in attachments or []:
|
||||
media_content_id = attachment["media_content_id"]
|
||||
for domain in ("camera", "image"):
|
||||
prefix = f"media-source://{domain}/"
|
||||
if not media_content_id.startswith(prefix):
|
||||
continue
|
||||
attachment_entity_id = media_content_id.removeprefix(prefix)
|
||||
if not user.permissions.check_entity(attachment_entity_id, POLICY_READ):
|
||||
raise Unauthorized(
|
||||
context=context,
|
||||
entity_id=attachment_entity_id,
|
||||
permission=POLICY_READ,
|
||||
)
|
||||
break
|
||||
@@ -27,6 +27,7 @@ from .const import (
|
||||
IMAGE_EXPIRY_TIME,
|
||||
AITaskEntityFeature,
|
||||
)
|
||||
from .permissions import async_check_permissions
|
||||
|
||||
|
||||
def _save_media_image(image_data: media_source.MediaImage) -> Path:
|
||||
@@ -110,6 +111,8 @@ async def async_generate_data(
|
||||
context: Context | None = None,
|
||||
) -> GenDataTaskResult:
|
||||
"""Run a data generation task in the AI Task integration."""
|
||||
await async_check_permissions(hass, entity_id, attachments, context)
|
||||
|
||||
if entity_id is None:
|
||||
entity_id = hass.data[DATA_PREFERENCES].gen_data_entity_id
|
||||
|
||||
@@ -159,6 +162,8 @@ async def async_generate_image(
|
||||
context: Context | None = None,
|
||||
) -> ServiceResponse:
|
||||
"""Run an image generation task in the AI Task integration."""
|
||||
await async_check_permissions(hass, entity_id, attachments, context)
|
||||
|
||||
if entity_id is None:
|
||||
entity_id = hass.data[DATA_PREFERENCES].gen_image_entity_id
|
||||
|
||||
|
||||
@@ -16,12 +16,12 @@ from homeassistant.components.ai_task.const import (
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.exceptions import HomeAssistantError, Unauthorized
|
||||
from homeassistant.helpers import selector
|
||||
|
||||
from .conftest import TEST_ENTITY_ID, MockAITaskEntity
|
||||
|
||||
from tests.common import flush_store
|
||||
from tests.common import MockUser, flush_store
|
||||
|
||||
|
||||
async def test_preferences_storage_load(
|
||||
@@ -380,3 +380,111 @@ async def test_generate_image_service_no_entity(
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_components")
|
||||
@pytest.mark.parametrize("service", ["generate_data", "generate_image"])
|
||||
async def test_generate_service_explicit_entity_permission(
|
||||
hass: HomeAssistant,
|
||||
hass_read_only_user: MockUser,
|
||||
mock_ai_task_entity: MockAITaskEntity,
|
||||
service: str,
|
||||
) -> None:
|
||||
"""Reject an explicit entity before resolving attachments or calling a provider."""
|
||||
with (
|
||||
patch("homeassistant.components.ai_task.task._resolve_attachments") as resolve,
|
||||
pytest.raises(Unauthorized) as err,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
service,
|
||||
{
|
||||
"task_name": "Test",
|
||||
"instructions": "Test prompt",
|
||||
"entity_id": TEST_ENTITY_ID,
|
||||
},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
context=Context(user_id=hass_read_only_user.id),
|
||||
)
|
||||
assert err.value.entity_id == TEST_ENTITY_ID
|
||||
resolve.assert_not_called()
|
||||
assert not mock_ai_task_entity.mock_generate_data_tasks
|
||||
assert not mock_ai_task_entity.mock_generate_image_tasks
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_components")
|
||||
@pytest.mark.parametrize("service", ["generate_data", "generate_image"])
|
||||
@pytest.mark.parametrize("domain", ["camera", "image"])
|
||||
@pytest.mark.parametrize("entity_selection", [{}, {"entity_id": TEST_ENTITY_ID}])
|
||||
async def test_generate_service_attachment_permission(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
mock_ai_task_entity: MockAITaskEntity,
|
||||
service: str,
|
||||
domain: str,
|
||||
entity_selection: dict[str, str],
|
||||
) -> None:
|
||||
"""Camera and image attachments require read permission for either task choice."""
|
||||
hass.data[DATA_PREFERENCES].async_set_preferences(
|
||||
gen_data_entity_id=TEST_ENTITY_ID, gen_image_entity_id=TEST_ENTITY_ID
|
||||
)
|
||||
hass_admin_user.mock_policy(
|
||||
{"entities": {"entity_ids": {TEST_ENTITY_ID: {"control": True}}}}
|
||||
)
|
||||
attachment_entity_id = f"{domain}.test"
|
||||
with (
|
||||
patch("homeassistant.components.ai_task.task._resolve_attachments") as resolve,
|
||||
pytest.raises(Unauthorized) as err,
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
service,
|
||||
{
|
||||
"task_name": "Test",
|
||||
"instructions": "Test prompt",
|
||||
"attachments": [
|
||||
{
|
||||
"media_content_id": f"media-source://{domain}/{attachment_entity_id}",
|
||||
"media_content_type": "image/jpeg",
|
||||
}
|
||||
],
|
||||
}
|
||||
| entity_selection,
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
context=Context(user_id=hass_admin_user.id),
|
||||
)
|
||||
assert err.value.entity_id == attachment_entity_id
|
||||
resolve.assert_not_called()
|
||||
assert not mock_ai_task_entity.mock_generate_data_tasks
|
||||
assert not mock_ai_task_entity.mock_generate_image_tasks
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_components")
|
||||
@pytest.mark.parametrize("service", ["generate_data", "generate_image"])
|
||||
async def test_generate_service_default_permission(
|
||||
hass: HomeAssistant,
|
||||
hass_read_only_user: MockUser,
|
||||
service: str,
|
||||
) -> None:
|
||||
"""Read-only users can use the configured default task entity."""
|
||||
hass.data[DATA_PREFERENCES].async_set_preferences(
|
||||
gen_data_entity_id=TEST_ENTITY_ID, gen_image_entity_id=TEST_ENTITY_ID
|
||||
)
|
||||
context = Context(user_id=hass_read_only_user.id)
|
||||
with patch.object(
|
||||
hass.data[DATA_MEDIA_SOURCE],
|
||||
"async_upload_media",
|
||||
return_value="media-source://ai_task/image/test.png",
|
||||
):
|
||||
result = await hass.services.async_call(
|
||||
DOMAIN,
|
||||
service,
|
||||
{"task_name": "Test", "instructions": "Test prompt"},
|
||||
blocking=True,
|
||||
return_response=True,
|
||||
context=context,
|
||||
)
|
||||
assert result
|
||||
assert hass.states.get(TEST_ENTITY_ID).context is context
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Test AI task permissions."""
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.auth.permissions.const import POLICY_CONTROL, POLICY_READ
|
||||
from homeassistant.components.ai_task.permissions import async_check_permissions
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import Unauthorized, UnknownUser
|
||||
|
||||
from .conftest import TEST_ENTITY_ID
|
||||
|
||||
from tests.common import MockUser
|
||||
|
||||
|
||||
@pytest.mark.parametrize("context", [None, Context()])
|
||||
async def test_system_context(hass: HomeAssistant, context: Context | None) -> None:
|
||||
"""System tasks can use entities without a user permission check."""
|
||||
await async_check_permissions(
|
||||
hass,
|
||||
TEST_ENTITY_ID,
|
||||
[{"media_content_id": "media-source://camera/camera.test"}],
|
||||
context,
|
||||
)
|
||||
|
||||
|
||||
async def test_unknown_user(hass: HomeAssistant) -> None:
|
||||
"""An unknown user cannot use even the default task entity."""
|
||||
context = Context(user_id="unknown")
|
||||
with pytest.raises(UnknownUser) as err:
|
||||
await async_check_permissions(hass, None, None, context)
|
||||
assert err.value.context is context
|
||||
|
||||
|
||||
async def test_explicit_entity_denied(
|
||||
hass: HomeAssistant, hass_read_only_user: MockUser
|
||||
) -> None:
|
||||
"""Explicitly selected task entities require control permission."""
|
||||
context = Context(user_id=hass_read_only_user.id)
|
||||
with pytest.raises(Unauthorized) as err:
|
||||
await async_check_permissions(hass, TEST_ENTITY_ID, None, context)
|
||||
assert err.value.context is context
|
||||
assert err.value.entity_id == TEST_ENTITY_ID
|
||||
assert err.value.permission == POLICY_CONTROL
|
||||
|
||||
|
||||
async def test_explicit_entity_allowed(
|
||||
hass: HomeAssistant, hass_admin_user: MockUser
|
||||
) -> None:
|
||||
"""Users with control permission can select a task entity."""
|
||||
await async_check_permissions(
|
||||
hass, TEST_ENTITY_ID, None, Context(user_id=hass_admin_user.id)
|
||||
)
|
||||
|
||||
|
||||
async def test_default_entity(
|
||||
hass: HomeAssistant, hass_read_only_user: MockUser
|
||||
) -> None:
|
||||
"""Using the default task entity does not require control permission."""
|
||||
await async_check_permissions(
|
||||
hass, None, None, Context(user_id=hass_read_only_user.id)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain", ["camera", "image"])
|
||||
@pytest.mark.parametrize("entity_id", [None, TEST_ENTITY_ID])
|
||||
async def test_attachment_denied(
|
||||
hass: HomeAssistant,
|
||||
hass_admin_user: MockUser,
|
||||
domain: str,
|
||||
entity_id: str | None,
|
||||
) -> None:
|
||||
"""Entity attachments need read permission even with a default task entity."""
|
||||
hass_admin_user.mock_policy(
|
||||
{"entities": {"entity_ids": {TEST_ENTITY_ID: {"control": True}}}}
|
||||
)
|
||||
context = Context(user_id=hass_admin_user.id)
|
||||
attachment_entity_id = f"{domain}.test"
|
||||
with pytest.raises(Unauthorized) as err:
|
||||
await async_check_permissions(
|
||||
hass,
|
||||
entity_id,
|
||||
[{"media_content_id": f"media-source://{domain}/{attachment_entity_id}"}],
|
||||
context,
|
||||
)
|
||||
assert err.value.context is context
|
||||
assert err.value.entity_id == attachment_entity_id
|
||||
assert err.value.permission == POLICY_READ
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain", ["camera", "image"])
|
||||
async def test_attachment_allowed(
|
||||
hass: HomeAssistant, hass_read_only_user: MockUser, domain: str
|
||||
) -> None:
|
||||
"""Read permission is sufficient for an entity attachment."""
|
||||
await async_check_permissions(
|
||||
hass,
|
||||
None,
|
||||
[{"media_content_id": f"media-source://{domain}/{domain}.test"}],
|
||||
Context(user_id=hass_read_only_user.id),
|
||||
)
|
||||
|
||||
|
||||
async def test_local_media(hass: HomeAssistant, hass_read_only_user: MockUser) -> None:
|
||||
"""Local media attachments do not have entity permissions."""
|
||||
hass_read_only_user.mock_policy({})
|
||||
await async_check_permissions(
|
||||
hass,
|
||||
None,
|
||||
[{"media_content_id": "media-source://media_source/local/test.png"}],
|
||||
Context(user_id=hass_read_only_user.id),
|
||||
)
|
||||
Reference in New Issue
Block a user