mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-29 16:35:19 -05:00
refac
This commit is contained in:
1 parent
2d4a3f622f
commit
c456a6dbfd
5 files changed
+144
-3
No files matched your search
@@ -15,6 +15,7 @@ import re
|
||||
from contextlib import suppress
|
||||
from html import escape
|
||||
import posixpath
|
||||
from typing import Literal
|
||||
from urllib.parse import quote, unquote, urljoin, urlsplit
|
||||
|
||||
import aiohttp
|
||||
@@ -35,6 +36,7 @@ from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.machines import MachineError, managed, local as local_machines, ssh as ssh_machines
|
||||
from open_webui.utils.machines.managed import describe
|
||||
from open_webui.utils.machines import (
|
||||
has_machine_access,
|
||||
get_machine_client,
|
||||
find_machine_connection,
|
||||
machine_headers,
|
||||
@@ -555,6 +557,32 @@ async def list_machines(request: Request, user=Depends(get_verified_user)):
|
||||
]
|
||||
|
||||
|
||||
class AccessPrincipal(BaseModel):
|
||||
principal_type: Literal['user', 'group']
|
||||
principal_id: str
|
||||
|
||||
|
||||
class AccessCheckForm(BaseModel):
|
||||
machine_id: str
|
||||
principals: list[AccessPrincipal] = Field(max_length=256)
|
||||
|
||||
|
||||
@router.post('/access/check')
|
||||
async def check_machine_access(request: Request, form_data: AccessCheckForm, user=Depends(get_verified_user)):
|
||||
"""Return the given users and groups that cannot use a machine the caller can use."""
|
||||
if form_data.machine_id not in {machine['id'] for machine in await list_machines(request, user)}:
|
||||
raise HTTPException(404, 'Machine not found')
|
||||
return {
|
||||
'principals_without_access': [
|
||||
principal
|
||||
for principal in form_data.principals
|
||||
if not await has_machine_access(
|
||||
principal.principal_type, principal.principal_id, form_data.machine_id, user.id
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
PROXY_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
|
||||
|
||||
|
||||
|
||||
@@ -204,6 +204,53 @@ async def has_machine_write_access(user, machine_id):
|
||||
return await has_connection_write_access(user, await get_connection(user, connection_id))
|
||||
|
||||
|
||||
async def has_machine_access(principal_type: str, principal_id: str, machine_id: str, owner_id: str) -> bool:
|
||||
"""Whether a user, or every member of a group through the group itself, can use the machine."""
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.utils.access_control import has_access
|
||||
|
||||
# A personal machine is only ever its owner's.
|
||||
if machine_id.startswith('tether:'):
|
||||
return principal_type == 'user' and principal_id == owner_id
|
||||
|
||||
is_admin = False
|
||||
if principal_type == 'user':
|
||||
target = await Users.get_user_by_id(principal_id)
|
||||
if not target:
|
||||
return False
|
||||
if target.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
return True
|
||||
is_admin = target.role == 'admin'
|
||||
user_id = target.id
|
||||
group_ids = {group.id for group in await Groups.get_groups_by_member_id(target.id, include_inherited=True)}
|
||||
else:
|
||||
user_id, group_ids = '', {principal_id}
|
||||
|
||||
template = machine_id.startswith('template:')
|
||||
connection_id = split_template_id(machine_id)[0] if template else machine_id
|
||||
connections = await Config.get('machines.connections', []) or []
|
||||
connection = next((c for c in connections if c.get('id') == connection_id and c.get('enabled', True)), None)
|
||||
if not connection:
|
||||
return False
|
||||
grants = (connection.get('config') or {}).get('access_grants', [])
|
||||
# Connections without grants are admin-only, as in has_connection_access.
|
||||
if not grants:
|
||||
return is_admin
|
||||
if not template:
|
||||
return await has_access(user_id, 'read', grants, group_ids)
|
||||
if await has_access(user_id, 'write', grants, group_ids):
|
||||
return True
|
||||
if not await has_access(user_id, 'read', grants, group_ids):
|
||||
return False
|
||||
return machine_id in await AccessGrants.get_accessible_resource_ids(
|
||||
user_id=user_id, resource_type='machine', resource_ids=[machine_id], user_group_ids=group_ids
|
||||
)
|
||||
|
||||
|
||||
def split_template_id(machine_id):
|
||||
if not machine_id.startswith('template:'):
|
||||
raise HTTPException(400, 'Invalid template machine ID')
|
||||
|
||||
@@ -292,6 +292,23 @@ export const getMachines = async (token: string): Promise<MachineServer[]> => {
|
||||
return res.json().catch(() => []);
|
||||
};
|
||||
|
||||
export type AccessPrincipal = { principal_type: 'user' | 'group'; principal_id: string };
|
||||
|
||||
/** The given users and groups that cannot use a machine. */
|
||||
export const checkMachineAccess = async (
|
||||
token: string,
|
||||
machineId: string,
|
||||
principals: AccessPrincipal[]
|
||||
): Promise<AccessPrincipal[]> => {
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/machines/access/check`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ machine_id: machineId, principals })
|
||||
});
|
||||
if (!res.ok) throw (await res.json().catch(() => null))?.detail ?? res.statusText;
|
||||
return (await res.json()).principals_without_access ?? [];
|
||||
};
|
||||
|
||||
export const getCwd = async (target: MachineTarget): Promise<MachineCwd | null> => {
|
||||
const url = `${target.baseUrl.replace(/\/$/, '')}/files/cwd`;
|
||||
const headers: Record<string, string> = machineHeaders(target);
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import ChatBubbleOval from '$lib/components/icons/ChatBubbleOval.svelte';
|
||||
import Keyframes from '$lib/components/icons/Keyframes.svelte';
|
||||
import Cog6 from '$lib/components/icons/Cog6.svelte';
|
||||
import TagSelector from '$lib/components/workspace/common/TagSelector.svelte';
|
||||
|
||||
import ModelItem from './ModelItem.svelte';
|
||||
@@ -998,8 +999,8 @@
|
||||
}}
|
||||
/>
|
||||
|
||||
{#if modelFilterItems.length > 0 || (multipleEnabled && items.length > 0)}
|
||||
<div class="flex min-w-0 shrink-0 items-center gap-0.5">
|
||||
{#if modelFilterItems.length > 0 || (multipleEnabled && items.length > 0) || $user?.role === 'admin'}
|
||||
<div class="flex min-w-0 shrink-0 items-center">
|
||||
{#if multipleEnabled && items.length > 0}
|
||||
<Tooltip content={$i18n.t('Compare')}>
|
||||
<button
|
||||
@@ -1040,6 +1041,25 @@
|
||||
onChange={setModelFilter}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if $user?.role === 'admin'}
|
||||
<Tooltip content={$i18n.t('Settings')}>
|
||||
<button
|
||||
type="button"
|
||||
class="focus-ring flex h-[1.375rem] w-5 shrink-0 items-center justify-center rounded-lg transition-colors duration-100 {($settings?.highContrastMode ??
|
||||
false)
|
||||
? 'text-base-700 hover:bg-base-200 hover:text-base-900 dark:text-base-300 dark:hover:bg-base-800 dark:hover:text-base-100'
|
||||
: 'text-base-500 hover:bg-base-50/40 hover:text-base-900 dark:text-base-400 dark:hover:bg-base-800/40 dark:hover:text-base-100'}"
|
||||
aria-label={$i18n.t('Settings')}
|
||||
on:click={() => {
|
||||
show = false;
|
||||
showSettings.set('admin:connections');
|
||||
}}
|
||||
>
|
||||
<Cog6 className="size-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
import AccessControl from '$lib/components/workspace/common/AccessControl.svelte';
|
||||
import XMark from '../icons/XMark.svelte';
|
||||
import { updateFolderAccessById } from '$lib/apis/folders';
|
||||
import { user } from '$lib/stores';
|
||||
import { checkMachineAccess } from '$lib/apis/machines';
|
||||
import { machines, user } from '$lib/stores';
|
||||
import { machineIdOf } from '$lib/utils/machines';
|
||||
import {
|
||||
loadFolderDetails,
|
||||
updateFolderDetails,
|
||||
@@ -30,6 +32,25 @@
|
||||
let loading = false;
|
||||
let shareMode: 'continue' | null = null;
|
||||
|
||||
// Sharing a folder does not share the machine its directory is on.
|
||||
$: machineId = machineIdOf(folder?.data) ?? folder?.machine_id;
|
||||
$: machineName = ($machines ?? []).find(({ id }) => id === machineId)?.name || $i18n.t('Machine');
|
||||
let withoutMachine = 0;
|
||||
let accessCheck = 0;
|
||||
const checkAccess = async (id: string | undefined, grants: AccessGrant[]) => {
|
||||
const check = ++accessCheck;
|
||||
const principals = grants.map(({ principal_type, principal_id }) => ({
|
||||
principal_type,
|
||||
principal_id
|
||||
}));
|
||||
const missing =
|
||||
id && principals.length
|
||||
? await checkMachineAccess(localStorage.token, id, principals).catch(() => [])
|
||||
: [];
|
||||
if (check === accessCheck) withoutMachine = missing.length;
|
||||
};
|
||||
$: if (show) checkAccess(machineId, accessGrants);
|
||||
|
||||
// Fetch fresh folder data (with access_grants) when modal opens
|
||||
$: if (show && folder?.id) {
|
||||
loadAccessGrants();
|
||||
@@ -129,6 +150,14 @@
|
||||
</select>
|
||||
</label>
|
||||
</AccessControl>
|
||||
{#if withoutMachine}
|
||||
<p class="mt-2 text-xs text-base-500 dark:text-base-400">
|
||||
{$i18n.t(
|
||||
"Some people you've shared with can't use {{MACHINE}}. They'll see this folder's chats, not its files.",
|
||||
{ MACHINE: machineName }
|
||||
)}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
Reference in new issue
Block a user