diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index e000bb7f92..6b2608ff92 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -1870,6 +1870,10 @@ USER_PERMISSIONS_NOTES_ALLOW_PUBLIC_SHARING = ( USER_PERMISSIONS_FOLDERS_ALLOW_SHARING = os.getenv('USER_PERMISSIONS_FOLDERS_ALLOW_SHARING', 'False').lower() == 'true' +USER_PERMISSIONS_AUTOMATIONS_ALLOW_SHARING = ( + os.getenv('USER_PERMISSIONS_AUTOMATIONS_ALLOW_SHARING', 'False').lower() == 'true' +) + USER_PERMISSIONS_CALENDAR_ALLOW_PUBLIC_SHARING = ( os.getenv('USER_PERMISSIONS_CALENDAR_ALLOW_PUBLIC_SHARING', 'False').lower() == 'true' @@ -2014,6 +2018,7 @@ DEFAULT_USER_PERMISSIONS = { 'notes': USER_PERMISSIONS_NOTES_ALLOW_SHARING, 'public_notes': USER_PERMISSIONS_NOTES_ALLOW_PUBLIC_SHARING, 'folders': USER_PERMISSIONS_FOLDERS_ALLOW_SHARING, + 'automations': USER_PERMISSIONS_AUTOMATIONS_ALLOW_SHARING, 'public_chats': USER_PERMISSIONS_CHAT_ALLOW_PUBLIC_SHARING, 'open_chats': USER_PERMISSIONS_CHAT_ALLOW_OPEN_SHARING, 'public_calendars': USER_PERMISSIONS_CALENDAR_ALLOW_PUBLIC_SHARING, diff --git a/backend/open_webui/events.py b/backend/open_webui/events.py index 38d3ff71c2..1ca1757b78 100644 --- a/backend/open_webui/events.py +++ b/backend/open_webui/events.py @@ -668,6 +668,11 @@ class EventDefinitions(BaseModel): AUTOMATION_DELETED: EventDefinition = EventDefinition( name='automation.deleted', description='An automation was deleted.', message='Automation deleted' ) + AUTOMATION_ACCESS_UPDATED: EventDefinition = EventDefinition( + name='automation.access_updated', + description='Automation access was updated.', + message='Automation access updated', + ) AUTOMATION_RUN_STARTED: EventDefinition = EventDefinition( name='automation.run_started', description='An automation run started.', message='Automation run started' ) diff --git a/backend/open_webui/models/automations.py b/backend/open_webui/models/automations.py index b51f6c37d7..391cfb0006 100644 --- a/backend/open_webui/models/automations.py +++ b/backend/open_webui/models/automations.py @@ -5,6 +5,8 @@ from typing import Literal, Optional from uuid import uuid4 from open_webui.models.notifications import emit_changes +from open_webui.models.access_grants import AccessGrant, AccessGrantResponse, AccessGrants +from open_webui.models.users import UserResponse from open_webui.internal.db import Base, get_async_db_context from open_webui.utils.misc import json_text_variants from pydantic import BaseModel, ConfigDict @@ -166,6 +168,10 @@ class AutomationForm(BaseModel): class AutomationResponse(AutomationModel): last_run: Optional[AutomationRunModel] = None next_runs: Optional[list[int]] = None + user: Optional[UserResponse] = None # the owner, shown like on workspace items + # Rename, reschedule, pause and run. What a run does stays the owner's: it runs as them. + write_access: Optional[bool] = None + access_grants: Optional[list[AccessGrantResponse]] = None # for the owner or an admin class AutomationListResponse(BaseModel): @@ -238,10 +244,25 @@ class AutomationTable: folder_id: Optional[str] = None, skip: int = 0, limit: int = 30, + view: Literal['all', 'mine', 'shared'] = 'mine', + group_ids: Optional[list[str]] = None, db: Optional[AsyncSession] = None, ) -> 'AutomationListResponse': async with get_async_db_context(db) as db: - stmt = select(Automation).filter_by(user_id=user_id) + if view == 'mine': + stmt = select(Automation).filter_by(user_id=user_id) + else: + # Owned plus shared directly; folder-shared ones are listed in their folder. + stmt = AccessGrants.has_permission_filter( + select(Automation), + Automation, + {'user_id': user_id, 'group_ids': group_ids or []}, + 'automation', + 'read', + db=db, + ) + if view == 'shared': + stmt = stmt.filter(Automation.user_id != user_id) if folder_id: stmt = stmt.filter(Automation.folder_id == folder_id) @@ -377,6 +398,7 @@ class AutomationTable: from open_webui.models.notifications import delete_notifications recipients = await delete_notifications(resource_type='automation', resource_ids=[id], db=db) + await db.execute(delete(AccessGrant).filter_by(resource_type='automation', resource_id=id)) await db.delete(row) await db.commit() await emit_changes(recipients) diff --git a/backend/open_webui/models/chats.py b/backend/open_webui/models/chats.py index 9866bf07a3..72c1075579 100644 --- a/backend/open_webui/models/chats.py +++ b/backend/open_webui/models/chats.py @@ -2110,6 +2110,19 @@ class ChatTable: and await has_folder_access(user.id, folder, 'read', db) ): return True + # A run chat is readable by anyone the automation is shared with. + automation_id = (chat.meta or {}).get('automation_id') + if automation_id and permission == 'read': + from open_webui.models.automations import Automations + from open_webui.utils.access_control.automations import has_automation_access + + automation = await Automations.get_by_id(automation_id, db=db) + if ( + automation + and automation.user_id == chat.user_id + and await has_automation_access(user, automation, 'read', db=db) + ): + return True return False async def filter_task_ids_by_user_id(self, chat, user_id: str, task_ids: list[str]) -> list[str]: diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py index 4fe8224cf4..1e754d0834 100644 --- a/backend/open_webui/routers/automations.py +++ b/backend/open_webui/routers/automations.py @@ -10,6 +10,7 @@ from open_webui.constants import ERROR_MESSAGES from open_webui.events import EVENTS, publish_event from open_webui.internal.db import get_async_session from open_webui.models.automations import ( + AutomationData, AutomationForm, AutomationListResponse, AutomationModel, @@ -19,13 +20,15 @@ from open_webui.models.automations import ( Automations, hide_webhook_token, ) -from open_webui.models.users import Users -from open_webui.models.access_grants import AccessGrants, has_public_write_access_grant +from open_webui.models.users import UserResponse, Users +from open_webui.models.access_grants import AccessGrantResponse, AccessGrants, has_public_write_access_grant from open_webui.models.channels import Channels from open_webui.models.config import Config from open_webui.models.folders import Folders +from open_webui.models.groups import Groups +from open_webui.utils.access_control.automations import can_manage_automation, has_automation_access from open_webui.utils.access_control.folders import has_folder_write_access -from open_webui.utils.access_control import has_permission +from open_webui.utils.access_control import has_permission, validate_access_grants from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.agents.discovery import get_models as get_agent_models from open_webui.utils.automations import ( @@ -91,6 +94,7 @@ async def check_automation_triggers(form_data: AutomationForm, user, db, is_crea def check_automation_access(automation, user): + """The owner only: what a run does, since every run uses the owner's account.""" if not automation or user.id != automation.user_id: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -98,6 +102,25 @@ def check_automation_access(automation, user): ) +async def get_accessible_automation(id: str, user, permission: str, db: AsyncSession) -> AutomationModel: + """Read: view it and its runs. Write: rename, reschedule, pause and run it.""" + automation = await Automations.get_by_id(id, db=db) + if not await has_automation_access(user, automation, permission, db=db): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + return automation + + +async def get_owner_timezone(automation, user) -> Optional[str]: + """Schedules follow the owner's timezone, like the scheduler does when it reschedules.""" + if automation.user_id == user.id: + return user.timezone + owner = await Users.get_user_by_id(automation.user_id) + return owner.timezone if owner else None + + async def check_automation_limits(request, user, rrule_str: Optional[str], db, is_create: bool = False): """Enforce global automation limits. Admins bypass all checks.""" if user.role == 'admin': @@ -139,22 +162,6 @@ async def check_automation_folder_access(folder_id: Optional[str], user, db: Asy ) -async def check_automation_manage_access(automation, user, db: AsyncSession): - """Pausing, running and run history: the creator, or anyone who can write to its folder.""" - if automation and automation.user_id == user.id: - return - if ( - automation - and automation.folder_id - and (user.role == 'admin' or await has_folder_write_access(user.id, automation.folder_id, db=db)) - ): - return - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=ERROR_MESSAGES.NOT_FOUND, - ) - - async def check_automation_channel_access(form_data: AutomationForm, user, db: AsyncSession): target = form_data.data.target if not target or target.type != 'channel': @@ -193,16 +200,24 @@ async def check_automation_channel_access(form_data: AutomationForm, user, db: A ) -async def enrich_automation( - automation: AutomationModel, db: AsyncSession, tz: str = None, viewer=None -) -> AutomationResponse: +async def enrich_automation(automation: AutomationModel, db: AsyncSession, viewer) -> AutomationResponse: """Full enrichment for single-item views (includes next_runs computation).""" last_run = await AutomationRuns.get_latest(automation.id, db=db) - data = automation.data if viewer is None or viewer.id == automation.user_id else hide_webhook_token(automation.data) + is_owner = viewer.id == automation.user_id + owner = viewer if is_owner else await Users.get_user_by_id(automation.user_id, db=db) + grants = ( + await AccessGrants.get_grants_by_resource('automation', automation.id, db=db) + if can_manage_automation(viewer, automation) + else None + ) return AutomationResponse( - **{**automation.model_dump(), 'data': data}, + # The webhook URL starts runs as the owner, so only the owner sees its token. + **{**automation.model_dump(), 'data': automation.data if is_owner else hide_webhook_token(automation.data)}, last_run=last_run, - next_runs=await schedule_next_runs(automation.data, tz=tz), + next_runs=await schedule_next_runs(automation.data, tz=owner.timezone if owner else None), + user=UserResponse(**owner.model_dump()) if owner else None, + write_access=await has_automation_access(viewer, automation, 'write', db=db), + access_grants=[AccessGrantResponse.from_grant(g) for g in grants] if grants is not None else None, ) @@ -216,6 +231,7 @@ async def get_automation_items( status: Optional[str] = None, folder_id: Optional[str] = None, page: Optional[int] = 1, + view: Literal['all', 'mine', 'shared'] = 'all', user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session), ): @@ -224,6 +240,7 @@ async def get_automation_items( page = max(1, page) skip = (page - 1) * limit + group_ids = [group.id for group in await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)] result = await Automations.search_automations( user_id=user.id, query=query, @@ -231,23 +248,44 @@ async def get_automation_items( folder_id=folder_id, skip=skip, limit=limit, + view=view, + group_ids=group_ids, db=db, ) # Batch-fetch latest runs in a single query instead of N+1 ids = [item.id for item in result.items] latest_runs = await AutomationRuns.get_latest_batch(ids, db=db) if ids else {} - - return { - 'items': [ - AutomationResponse( - **item.model_dump(), - last_run=latest_runs.get(item.id), - ) - for item in result.items - ], - 'total': result.total, + shared = [item for item in result.items if item.user_id != user.id] + owners = { + u.id: UserResponse(**u.model_dump()) + for u in await Users.get_users_by_user_ids(list({item.user_id for item in result.items}), db=db) } + writable = ( + {item.id for item in shared} + if user.role == 'admin' + else await AccessGrants.get_accessible_resource_ids( + user_id=user.id, + resource_type='automation', + resource_ids=[item.id for item in shared], + permission='write', + user_group_ids=set(group_ids), + db=db, + ) + ) + + items = [] + for item in result.items: + is_owner = item.user_id == user.id + items.append( + AutomationResponse( + **{**item.model_dump(), 'data': item.data if is_owner else hide_webhook_token(item.data)}, + last_run=latest_runs.get(item.id), + user=owners.get(item.user_id), + write_access=is_owner or item.id in writable, + ) + ) + return {'items': items, 'total': result.total} @router.get('/models') @@ -262,8 +300,10 @@ async def get_automation_models( await check_automations_permission(request, user) automation = None if automation_id: - automation = await Automations.get_by_id(automation_id, db=db) - check_automation_access(automation, user) + automation = await get_accessible_automation(automation_id, user, 'read', db) + # Only the owner picks the model, so the automation's terminal context is the owner's. + if automation.user_id != user.id: + automation = None metadata = {'terminal_id': terminal_id} if automation: metadata.update(model_id=automation.data.get('model_id'), automation_id=automation.id) @@ -293,7 +333,7 @@ async def create_new_automation( tz = user.timezone next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=tz) automation = await Automations.insert(user.id, form_data, next_run_at, db=db) - response = await enrich_automation(automation, db, tz=tz) + response = await enrich_automation(automation, db, viewer=user) await publish_event( request, EVENTS.AUTOMATION_CREATED, @@ -315,9 +355,8 @@ async def get_automation_by_id( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) - return await enrich_automation(automation, db, tz=user.timezone) + automation = await get_accessible_automation(id, user, 'read', db) + return await enrich_automation(automation, db, viewer=user) # Update Automation By Id @@ -332,17 +371,34 @@ async def update_automation_by_id( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) - await check_automation_folder_access(form_data.folder_id, user, db) - await check_automation_channel_access(form_data, user, db) - await validate_automation_terminal(request, user, form_data.data.model_dump(), id) - await check_automation_triggers(form_data, user, db) + automation = await get_accessible_automation(id, user, 'write', db) + if automation.user_id == user.id: + await check_automation_folder_access(form_data.folder_id, user, db) + await check_automation_channel_access(form_data, user, db) + await validate_automation_terminal(request, user, form_data.data.model_dump(), id) + await check_automation_triggers(form_data, user, db) + else: + # Runs use the owner's account, so others only change when it runs: the name, + # the schedule and whether it's on. Everything else stays as the owner set it. + form_data = AutomationForm( + name=form_data.name, + folder_id=automation.folder_id, + data=AutomationData(**{**automation.data, 'rrule': form_data.data.rrule}), + meta=automation.meta, + is_active=form_data.is_active, + ) + if not form_data.data.rrule and not form_data.data.webhook: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Add a schedule or a webhook') + if form_data.data.rrule: + try: + await validate_rrule(form_data.data.rrule, tz=await get_owner_timezone(automation, user)) + except ValueError as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + await check_automation_limits(None, user, form_data.data.rrule or None, db) - tz = user.timezone - next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=tz) + next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=await get_owner_timezone(automation, user)) updated = await Automations.update_by_id(id, form_data, next_run_at, db=db) - response = await enrich_automation(updated, db, tz=tz) + response = await enrich_automation(updated, db, viewer=user) await publish_event( request, EVENTS.AUTOMATION_UPDATED, @@ -364,10 +420,11 @@ async def toggle_automation_by_id( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - await check_automation_manage_access(automation, user, db) - toggled = await Automations.toggle(id, await schedule_next_run(automation.data, tz=user.timezone), db=db) - response = await enrich_automation(toggled, db, tz=user.timezone, viewer=user) + automation = await get_accessible_automation(id, user, 'write', db) + toggled = await Automations.toggle( + id, await schedule_next_run(automation.data, tz=await get_owner_timezone(automation, user)), db=db + ) + response = await enrich_automation(toggled, db, viewer=user) await publish_event( request, EVENTS.AUTOMATION_ENABLED if toggled.is_active else EVENTS.AUTOMATION_DISABLED, @@ -402,9 +459,11 @@ async def run_automation_by_id( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - await check_automation_manage_access(automation, user, db) + automation = await get_accessible_automation(id, user, 'write', db) variables = form_data.variables if form_data else None + # Variables are written into the owner's prompt, so only the owner fills them in. + if variables and automation.user_id != user.id: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) check_variables(automation, variables) automation = await Automations.update_last_run_at(automation.id, db=db) asyncio.create_task(execute_automation(request.app, automation, variables)) @@ -415,7 +474,7 @@ async def run_automation_by_id( subject_id=automation.id, data={'name': automation.name}, ) - return await enrich_automation(automation, db, tz=user.timezone, viewer=user) + return await enrich_automation(automation, db, viewer=user) # Webhook Trigger @@ -436,7 +495,7 @@ async def regenerate_automation_token( updated = await Automations.regenerate_webhook_token(id, db=db) if not updated: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()) - return await enrich_automation(updated, db, tz=user.timezone) + return await enrich_automation(updated, db, viewer=user) async def read_hook_variables(request: Request) -> dict: @@ -512,8 +571,9 @@ async def delete_automation_by_id( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - check_automation_access(automation, user) + automation = await get_accessible_automation(id, user, 'read', db) + if not can_manage_automation(user, automation): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) await AutomationRuns.delete_by_automation(id, db=db) result = await Automations.delete(id, db=db) if result: @@ -527,6 +587,46 @@ async def delete_automation_by_id( return result +# Update Automation Access By Id + + +class AutomationAccessGrantsForm(BaseModel): + access_grants: list[dict] + + +@router.post('/{id}/access/update', response_model=AutomationResponse) +async def update_automation_access_by_id( + request: Request, + id: str, + form_data: AutomationAccessGrantsForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + await check_automations_permission(request, user) + automation = await get_accessible_automation(id, user, 'read', db) + # Editing an automation does not grant permission to manage its sharing. + if not can_manage_automation(user, automation): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + + access_grants = await validate_access_grants( + await Config.get('user.permissions'), + user.id, + user.role, + form_data.access_grants, + resource_type='automation', + db=db, + ) + await AccessGrants.set_access_grants('automation', id, access_grants, db=db) + await publish_event( + request, + EVENTS.AUTOMATION_ACCESS_UPDATED, + actor=user, + subject_id=id, + data={'grant_count': len(access_grants)}, + ) + return await enrich_automation(automation, db, viewer=user) + + # Get Automation Runs @@ -541,8 +641,7 @@ async def get_automation_runs( db: AsyncSession = Depends(get_async_session), ): await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - await check_automation_manage_access(automation, user, db) + await get_accessible_automation(id, user, 'read', db) return await AutomationRuns.get_by_automation(id, skip=skip, limit=limit, direction=direction, db=db) @@ -557,8 +656,7 @@ async def get_automation_run( from open_webui.models.automations import AutomationRun await check_automations_permission(request, user) - automation = await Automations.get_by_id(id, db=db) - await check_automation_manage_access(automation, user, db) + await get_accessible_automation(id, user, 'read', db) run = await db.get(AutomationRun, run_id) if not run or run.automation_id != id: raise HTTPException(404, 'Run not found') diff --git a/backend/open_webui/routers/folders.py b/backend/open_webui/routers/folders.py index e8e9a770cb..b328a27e7b 100644 --- a/backend/open_webui/routers/folders.py +++ b/backend/open_webui/routers/folders.py @@ -750,7 +750,8 @@ async def check_folder_read_access(request: Request, id: str, user, db: AsyncSes async def get_folder_automations( request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session) ): - """The folder's automations, whoever made them. Only creators edit; folder editors may pause and run.""" + """The folder's automations, whoever made them. Only creators edit; folder editors, and anyone + an automation is shared with for editing, may rename, reschedule, pause and run it.""" folder = await check_folder_read_access(request, id, user, db) automations = await Automations.get_by_folder(id, db=db) if not automations: @@ -760,6 +761,17 @@ async def get_folder_automations( has_write = ( user.role == 'admin' or folder.user_id == user.id or await _has_folder_access(user.id, folder, 'write', db) ) + shared_write = ( + set() + if has_write + else await AccessGrants.get_accessible_resource_ids( + user_id=user.id, + resource_type='automation', + resource_ids=[item.id for item in automations], + permission='write', + db=db, + ) + ) return [ { **AutomationResponse( @@ -771,7 +783,7 @@ async def get_folder_automations( ).model_dump(), 'user_name': creators.get(item.user_id) or 'Unknown', 'can_edit': item.user_id == user.id, - 'can_manage': item.user_id == user.id or has_write, + 'can_manage': item.user_id == user.id or has_write or item.id in shared_write, } for item in automations ] diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index 3053931310..9dc3fdcdc2 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -4743,15 +4743,19 @@ async def toggle_automation( user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) + from open_webui.utils.access_control.automations import has_automation_access + automation = await Automations.get_by_id(automation_id) if not automation: return JSONCodec.dumps({'error': 'Automation not found'}) - if automation.user_id != user_id: + # Anyone it's shared with for editing may pause it; it keeps the owner's schedule timezone. + if not await has_automation_access(user, automation, 'write'): return JSONCodec.dumps({'error': 'Access denied'}) + owner = user if automation.user_id == user_id else await Users.get_user_by_id(automation.user_id) toggled = await Automations.toggle( automation_id, - await schedule_next_run(automation.data, tz=user.timezone if user else None), + await schedule_next_run(automation.data, tz=owner.timezone if owner else None), ) return JSONCodec.dumps( diff --git a/backend/open_webui/utils/access_control/__init__.py b/backend/open_webui/utils/access_control/__init__.py index cc57a76101..48f079f822 100644 --- a/backend/open_webui/utils/access_control/__init__.py +++ b/backend/open_webui/utils/access_control/__init__.py @@ -224,6 +224,7 @@ _SHARING_PERMISSION_KEYS = { 'skill': ('sharing.skills', 'sharing.public_skills', None), 'note': ('sharing.notes', 'sharing.public_notes', None), 'folder': ('sharing.folders', None, None), + 'automation': ('sharing.automations', None, None), 'channel': (None, 'sharing.public_channels', None), 'calendar': (None, 'sharing.public_calendars', None), 'shared_chat': (None, 'sharing.public_chats', 'sharing.open_chats'), diff --git a/backend/open_webui/utils/access_control/automations.py b/backend/open_webui/utils/access_control/automations.py new file mode 100644 index 0000000000..b4f028a4ff --- /dev/null +++ b/backend/open_webui/utils/access_control/automations.py @@ -0,0 +1,29 @@ +from open_webui.models.access_grants import AccessGrants +from open_webui.models.folders import Folders +from open_webui.utils.access_control.folders import has_folder_access +from sqlalchemy.ext.asyncio import AsyncSession + + +async def has_automation_access(user, automation, permission: str = 'read', db: AsyncSession | None = None) -> bool: + """Owner, admin, a direct grant, or the same permission on the automation's folder. + + Every run uses the owner's account, so write access only covers changes that can't + misuse it: the name, the schedule, pausing and running now (see the update route). + """ + if not automation or not user: + return False + if user.role == 'admin' or automation.user_id == user.id: + return True + if await AccessGrants.has_access( + user_id=user.id, resource_type='automation', resource_id=automation.id, permission=permission, db=db + ): + return True + if automation.folder_id: + folder = await Folders.get_folder_by_id(automation.folder_id, db=db) + return bool(folder) and await has_folder_access(user.id, folder, permission, db) + return False + + +def can_manage_automation(user, automation) -> bool: + """Sharing and deleting.""" + return bool(automation) and (user.role == 'admin' or automation.user_id == user.id) diff --git a/src/lib/apis/automations/index.ts b/src/lib/apis/automations/index.ts index 011e0ba053..e07b7bbd38 100644 --- a/src/lib/apis/automations/index.ts +++ b/src/lib/apis/automations/index.ts @@ -95,6 +95,33 @@ export type AutomationResponse = { updated_at: number; last_run: AutomationRunModel | null; next_runs: number[] | null; + + /** The owner, as on workspace items. */ + user?: { id: string; name: string; role: string; email: string } | null; + /** Rename, reschedule, pause and run. What a run does stays the owner's: it runs as them. */ + write_access?: boolean | null; + /** For the owner or an admin. */ + access_grants?: + | { id?: string; principal_type: string; principal_id: string; permission: string }[] + | null; +}; + +export const updateAutomationAccessGrants = async ( + token: string, + id: string, + accessGrants: any[] +): Promise => { + const res = await fetch(`${WEBUI_API_BASE_URL}/automations/${id}/access/update`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + authorization: `Bearer ${token}` + }, + body: JSON.stringify({ access_grants: accessGrants }) + }); + if (!res.ok) throw (await res.json())?.detail ?? res.statusText; + return res.json(); }; export const getAutomationModels = async ( @@ -118,7 +145,9 @@ export const getAutomationItems = async ( query: string | null, status: string | null, page: number, - folder_id?: string | null + folder_id?: string | null, + /** 'all' is yours plus those shared with you directly. */ + view: 'all' | 'mine' | 'shared' = 'all' ): Promise<{ items: AutomationResponse[]; total: number }> => { let error = null; @@ -126,6 +155,9 @@ export const getAutomationItems = async ( if (query) { searchParams.append('query', query); } + if (view !== 'all') { + searchParams.append('view', view); + } if (status && status !== 'all') { searchParams.append('status', status); } diff --git a/src/lib/components/admin/Users/Groups/Permissions.svelte b/src/lib/components/admin/Users/Groups/Permissions.svelte index 1a9873494e..43eb8f8a5f 100644 --- a/src/lib/components/admin/Users/Groups/Permissions.svelte +++ b/src/lib/components/admin/Users/Groups/Permissions.svelte @@ -490,6 +490,27 @@ {/if} + {#if $config?.features?.enable_automations} +
+
+
+ {$i18n.t('Automations Sharing')} +
+ +
+ {#if defaultPermissions?.sharing?.automations && !permissions.sharing.automations} +
+
+ {$i18n.t('This is a default user permission and will remain enabled.')} +
+
+ {/if} +
+ {/if} + {#if permissions.chat.share}
diff --git a/src/lib/components/automations/AutomationEditor.svelte b/src/lib/components/automations/AutomationEditor.svelte index 9b3819acbd..6a3d846827 100644 --- a/src/lib/components/automations/AutomationEditor.svelte +++ b/src/lib/components/automations/AutomationEditor.svelte @@ -24,6 +24,7 @@ folders, mobile, showSidebar, + user, type AgentModel } from '$lib/stores'; import { getTerminalServers, type TerminalServer } from '$lib/apis/machines'; @@ -32,6 +33,7 @@ import { getAutomationById, + updateAutomationAccessGrants, toggleAutomationById, runAutomationById, deleteAutomationById, @@ -70,6 +72,7 @@ import LinkIcon from '$lib/components/icons/Link.svelte'; import WebhookDropdown from '$lib/components/automations/WebhookDropdown.svelte'; import InputVariablesModal from '$lib/components/chat/MessageInput/InputVariablesModal.svelte'; + import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte'; dayjs.extend(localizedFormat); @@ -80,6 +83,15 @@ let is_active = automation.is_active; + // Every run uses the owner's account, so only the owner changes what it does. Anyone it's + // shared with for editing renames, reschedules, pauses and runs it; viewers only look. + $: canEdit = automation.user_id === $user?.id; + $: canManage = canEdit || !!automation.write_access; + $: canShare = canEdit || $user?.role === 'admin'; + let showAccessControlModal = false; + let accessGrants: any[] = []; + $: accessGrants = automation.access_grants ?? []; + let loading = false; let showDeleteConfirm = false; let showCloneModal = false; @@ -170,7 +182,8 @@ async function loadAgentModels(terminalId: string, cwd: string, target: string) { const request = ++modelRequest; agentModels = []; - if (!terminalId || target !== 'chat') return; + // Only the owner picks the model, through the owner's terminal. + if (!terminalId || target !== 'chat' || automation.user_id !== $user?.id) return; try { const available = await getAutomationModels( localStorage.token, @@ -350,7 +363,8 @@ const runNowHandler = async () => { if (loading) return; runVariables = getRunVariables(automation.data.prompt); - if (Object.keys(runVariables).length > 0) { + // Variables are written into the owner's prompt; others run it with the defaults. + if (Object.keys(runVariables).length > 0 && canEdit) { showVariablesModal = true; return; } @@ -497,6 +511,32 @@ onSave={(values) => run(values)} /> +{#if canShare} + { + try { + automation = await updateAutomationAccessGrants( + localStorage.token, + automation.id, + accessGrants + ); + toast.success($i18n.t('Saved')); + } catch (error) { + accessGrants = automation.access_grants ?? []; + toast.error(`${error}`); + } + }} + /> +{/if} + @@ -535,13 +576,22 @@ {loading} {dirty} {saving} - {runNowHandler} + runNowHandler={canManage ? runNowHandler : null} {copyLinkHandler} {saveHandler} duplicateHandler={() => (showCloneModal = true)} - deleteHandler={() => (showDeleteConfirm = true)} + shareHandler={canShare ? () => (showAccessControlModal = true) : null} + deleteHandler={canShare ? () => (showDeleteConfirm = true) : null} />
+ {#if !canEdit} +
+ {$i18n.t('Shared by {{name}}', { + name: automation.user?.name ?? $i18n.t('Deleted User') + })} + · {canManage ? $i18n.t('Write') : $i18n.t('Read')} +
+ {/if}
@@ -612,7 +664,7 @@ {$i18n.t('Schedule')} -
+
{$i18n.t('Webhook')} -
+
{$i18n.t('Model')} -
+
{$i18n.t('Destination')} -
+
{$i18n.t('Machine')} -
+
{}; + export let runNowHandler: (() => void) | null = () => {}; export let copyLinkHandler = () => {}; export let saveHandler = () => {}; export let duplicateHandler = () => {}; - export let deleteHandler = () => {}; + // Null hides the action: sharing and deleting are the owner's (or an admin's). + export let shareHandler: (() => void) | null = null; + export let deleteHandler: (() => void) | null = () => {}; // Same soft round buttons as the folder view's top bar. const iconButton = @@ -41,21 +44,36 @@ {/if} - - - + {#if runNowHandler} + + + + {/if} + + {#if shareHandler} + + + + {/if} - + {#if deleteHandler} + + {/if}
diff --git a/src/lib/components/automations/AutomationMenu.svelte b/src/lib/components/automations/AutomationMenu.svelte index fd8c24e4c5..41bc872d19 100644 --- a/src/lib/components/automations/AutomationMenu.svelte +++ b/src/lib/components/automations/AutomationMenu.svelte @@ -11,8 +11,9 @@ export let editHandler: Function; export let cloneHandler: Function; - export let runHandler: Function = () => {}; - export let deleteHandler: Function; + // Null hides the item: a shared automation may be view-only, and only its owner (or an admin) deletes it. + export let runHandler: Function | null = () => {}; + export let deleteHandler: Function | null; export let onClose: Function = () => {}; export let show = false; @@ -70,45 +71,49 @@
{$i18n.t('Clone')}
- +
{$i18n.t('Run Now')}
+ + {/if} -
+ {#if deleteHandler} +
- + + {/if}
diff --git a/src/lib/components/automations/Automations.svelte b/src/lib/components/automations/Automations.svelte index 733c7201b3..42764aba7b 100644 --- a/src/lib/components/automations/Automations.svelte +++ b/src/lib/components/automations/Automations.svelte @@ -48,6 +48,7 @@ import Plus from '$lib/components/icons/Plus.svelte'; import SidebarIcon from '$lib/components/icons/Sidebar.svelte'; import Icon from '$lib/components/chat/FileNav/Icon.svelte'; + import ChatParticipants from '$lib/components/common/ChatParticipants.svelte'; dayjs.extend(relativeTime); @@ -70,6 +71,10 @@ let query = ''; let statusFilter = 'all'; + let ownerFilter: 'all' | 'mine' | 'shared' = 'all'; + // Sharing and deleting are the owner's or an admin's. + const canShare = (automation: AutomationResponse) => + automation.user_id === $user?.id || $user?.role === 'admin'; let searchDebounceTimer: ReturnType; let page = 1; @@ -102,7 +107,7 @@ }; // Immediate response to page/filter changes (gate behind loaded) - $: if (loaded && $active && page && statusFilter !== undefined) { + $: if (loaded && $active && page && statusFilter !== undefined && ownerFilter) { getAutomationList(); } @@ -115,12 +120,17 @@ loading = true; try { - const res = await getAutomationItems(localStorage.token, query, statusFilter, page).catch( - (error) => { - toast.error(`${error}`); - return null; - } - ); + const res = await getAutomationItems( + localStorage.token, + query, + statusFilter, + page, + null, + ownerFilter + ).catch((error) => { + toast.error(`${error}`); + return null; + }); if (res) { automations = res.items; @@ -164,7 +174,10 @@ }); if (!allAutomations) return; - const targets = allAutomations.filter((a) => a.is_active !== enable); + // Shared automations you can only view are left as they are. + const targets = allAutomations.filter( + (a) => a.is_active !== enable && a.write_access !== false + ); if (targets.length === 0) return; try { @@ -250,7 +263,14 @@ let totalAutomations = 0; do { - const res = await getAutomationItems(localStorage.token, query, status, currentPage); + const res = await getAutomationItems( + localStorage.token, + query, + status, + currentPage, + null, + ownerFilter + ); const pageItems = res?.items ?? []; totalAutomations = res?.total ?? pageItems.length; allAutomations = [...allAutomations, ...pageItems]; @@ -487,7 +507,7 @@ {/each} +
{$i18n.t('Owner')}
+ {#each [['all', 'All'], ['mine', 'Mine'], ['shared', 'Shared with me']] as const as [value, label]} + + {/each}
@@ -613,16 +648,13 @@
- {formatLastRun(automation)} + {formatTrigger(automation.data, $i18n)} · {formatDestination(automation)}
@@ -630,21 +662,33 @@
-