201 lines
8.6 KiB
Python
201 lines
8.6 KiB
Python
"""Current management authorization; customer-facing retrieval opts out by default."""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import json
|
|
import os
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
import group_sso
|
|
import zyt_auth
|
|
|
|
import rbac
|
|
|
|
OWN_CODE = 'knowledge:scope:own'
|
|
BRIDGE_ENV = 'ZYT_KNOWLEDGE_ACCOUNT_BRIDGE'
|
|
REVIEWER_PERMISSIONS = ('knowledge:read', 'knowledge:review', 'im:content:read')
|
|
TASKS_READ = 'knowledge:tasks:read'
|
|
TASK_ARCHIVE = (TASKS_READ, 'im:content:read')
|
|
TASK_CREATE = (*TASK_ARCHIVE, 'knowledge:run')
|
|
TASK_CONTROL = (*TASK_ARCHIVE, 'knowledge:run:control')
|
|
TASK_WATCH = (*TASK_ARCHIVE, 'knowledge:watch')
|
|
|
|
|
|
def _endpoint(value):
|
|
# Compare the complete registered API base, including any path. No network,
|
|
# aliases, display names or coincidentally equal numeric IDs establish trust.
|
|
if (not isinstance(value, str) or not value or len(value) > 2048
|
|
or any(ord(c) <= 32 or ord(c) == 127 for c in value)
|
|
or any(c in value for c in '\\%?#')):
|
|
raise ValueError('Invalid account bridge endpoint')
|
|
parsed = urlsplit(value)
|
|
if (parsed.scheme not in {'https', 'http'} or not parsed.hostname
|
|
or parsed.username is not None or parsed.password is not None
|
|
or any(part in {'.', '..'} for part in parsed.path.split('/'))):
|
|
raise ValueError('Invalid account bridge endpoint')
|
|
port = parsed.port
|
|
host = parsed.hostname.lower()
|
|
if ':' in host:
|
|
host = '[' + host + ']'
|
|
if port is not None and port != (443 if parsed.scheme == 'https' else 80):
|
|
host += ':' + str(port)
|
|
return urlunsplit((parsed.scheme, host, parsed.path.rstrip('/'), '', ''))
|
|
|
|
|
|
def _bridge_object(pairs):
|
|
result = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
raise ValueError('Duplicate account bridge field')
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def account_bridge_ready(db):
|
|
"""Explicit operator attestation of the Group and desktop Admin namespace."""
|
|
try:
|
|
raw = os.environ.get(BRIDGE_ENV, '')
|
|
if not raw or len(raw) > 8192:
|
|
return False
|
|
bridge = json.loads(raw, object_pairs_hook=_bridge_object)
|
|
if (not isinstance(bridge, dict)
|
|
or set(bridge) != {'group_api_url', 'desktop_api_url', 'namespace'}
|
|
or bridge['namespace'] != 'admin'):
|
|
return False
|
|
group = group_sso.GroupPasswordConfig.from_env()
|
|
if group is None or _endpoint(group.group_api_url) != _endpoint(bridge['group_api_url']):
|
|
return False
|
|
# This is the same priority as admin_api.desktop_login_api_url(). Read
|
|
# only this setting; never infer provenance from account names or IDs.
|
|
row = db.execute('SELECT config_json FROM model_config WHERE id=1').fetchone()
|
|
configured = json.loads(row[0]).get('ZYT_LOGIN_API_URL') if row is not None else ''
|
|
desktop = str(configured or '').strip().rstrip('/') or zyt_auth.api_base_url()
|
|
return _endpoint(desktop) == _endpoint(bridge['desktop_api_url'])
|
|
except (ValueError, TypeError, AttributeError, RecursionError, zyt_auth.ZytAuthError):
|
|
return False
|
|
|
|
|
|
def own_account_key(db, actor):
|
|
"""Return the validated Group account's desktop identity key."""
|
|
if not account_bridge_ready(db):
|
|
return None
|
|
row = db.execute('SELECT provider,gid,source_admin_id FROM group_sso_bindings WHERE user_id=?',
|
|
(actor,)).fetchone()
|
|
if (row is None or row['provider'] != group_sso.PROVIDER
|
|
or not isinstance(row['gid'], str) or not group_sso.GID_PATTERN.fullmatch(row['gid'])
|
|
or type(row['source_admin_id']) is not int or row['source_admin_id'] <= 0):
|
|
return None
|
|
return 'admin:' + str(row['source_admin_id'])
|
|
|
|
|
|
def own_account_tenants(db, actor, *, include_inactive=False):
|
|
"""A valid Group binding plus the registered Admin namespace, or nothing."""
|
|
key = own_account_key(db, actor)
|
|
if key is None:
|
|
return frozenset()
|
|
query = 'SELECT tenant_id FROM desktop_accounts WHERE zyt_user_id=?'
|
|
if not include_inactive:
|
|
query += " AND status='active'"
|
|
return frozenset(row[0] for row in db.execute(query, (key,)))
|
|
|
|
|
|
|
|
class KnowledgeAccessDenied(PermissionError):
|
|
pass
|
|
|
|
|
|
class KnowledgeProcessingDenied(ValueError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class KnowledgeAccess:
|
|
actor: int
|
|
permissions: frozenset[str]
|
|
tenants: frozenset[str] | None
|
|
|
|
@property
|
|
def own(self):
|
|
return OWN_CODE in self.permissions
|
|
|
|
def tenant_sql(self, alias=''):
|
|
prefix = alias + '.' if alias else ''
|
|
if self.tenants is None:
|
|
return '1=1', []
|
|
values = sorted(self.tenants)
|
|
return (f"{prefix}tenant_id IN ({','.join('?' for _ in values)})" if values else '0=1', values)
|
|
|
|
def item_sql(self, alias='knowledge_item'):
|
|
return self.tenant_sql(alias)
|
|
|
|
def job_sql(self, alias=''):
|
|
return self.tenant_sql(alias)
|
|
|
|
def check_item(self, db, tenant, item_id):
|
|
clause, args = self.item_sql('k')
|
|
if db.execute(f'SELECT 1 FROM knowledge_item k WHERE k.id=? AND k.tenant_id=? AND {clause}',
|
|
[item_id, tenant, *args]).fetchone() is None:
|
|
raise KeyError('知识不存在或不在你的授权范围内')
|
|
|
|
def check_job(self, db, tenant, job_id):
|
|
clause, args = self.job_sql('j')
|
|
if db.execute(f'SELECT 1 FROM knowledge_job j WHERE j.id=? AND j.tenant_id=? AND {clause}',
|
|
[job_id, tenant, *args]).fetchone() is None:
|
|
raise KeyError('任务不存在或不在你的授权范围内')
|
|
|
|
def check_tenants(self, tenants):
|
|
if self.tenants is not None and not set(tenants) <= self.tenants:
|
|
raise KeyError('账号不存在或不在你的授权范围内')
|
|
|
|
|
|
def current_access(db, actor, required=()):
|
|
"""Never reuse the request/session's cached permissions across a wait or a write."""
|
|
user = db.execute('SELECT role,active FROM users WHERE id=?', (actor,)).fetchone()
|
|
permissions = rbac.permissions_of(db, user['role']) if user and user['active'] else set()
|
|
if user is None or not user['active'] or not set(required) <= permissions:
|
|
raise KnowledgeAccessDenied('权限已变化或账号已停用,请刷新后重试')
|
|
scoped = db.execute('SELECT desktop_account_id FROM admin_account_scope WHERE admin_user_id=?', (actor,)).fetchall()
|
|
tenants = None
|
|
if 'desktop-account:all' not in permissions and scoped:
|
|
tenants = frozenset(row[0] for row in db.execute('SELECT d.tenant_id FROM desktop_accounts d '
|
|
'JOIN admin_account_scope a ON a.desktop_account_id=d.id WHERE a.admin_user_id=?', (actor,)))
|
|
if OWN_CODE in permissions:
|
|
own_tenants = own_account_tenants(db, actor)
|
|
tenants = own_tenants if tenants is None else tenants & own_tenants
|
|
return KnowledgeAccess(int(actor), frozenset(permissions), tenants)
|
|
|
|
|
|
def processing_principal_access(db, actor, tenant, *, automatic=False):
|
|
"""Scheduled work follows its human creator, including changes after queuing."""
|
|
required = ('knowledge:watch' if automatic else 'knowledge:run', 'im:content:read')
|
|
if not actor or int(actor) <= 0 or db.execute('SELECT 1 FROM users WHERE id=?', (actor,)).fetchone() is None:
|
|
raise KnowledgeProcessingDenied('无法确认整理任务创建者;进度已保留')
|
|
try:
|
|
access = current_access(db, actor, required)
|
|
access.check_tenants([tenant])
|
|
return access
|
|
except (KnowledgeAccessDenied, KeyError) as exc:
|
|
raise KnowledgeProcessingDenied('整理任务创建者权限已变化、账号已停用或账号授权已收回;进度已保留') from exc
|
|
|
|
|
|
def processing_access(db, job_id, tenant):
|
|
job = db.execute('SELECT * FROM knowledge_job WHERE id=? AND tenant_id=?', (job_id, tenant)).fetchone()
|
|
if job is None:
|
|
raise KnowledgeProcessingDenied('整理来源任务不存在,无法确认创建者;进度已保留')
|
|
options = json.loads(job['options_json'])
|
|
automatic = job['run_id'] == 'auto' or options.get('incremental') == 1 or options.get('run_id') == 'auto'
|
|
return processing_principal_access(db, job['created_by'], tenant, automatic=automatic)
|
|
|
|
|
|
def management_where(db, actor, scope, *, alias='knowledge_item', required=('knowledge:read',), jobs=False):
|
|
from archive_store import tenant_scope
|
|
|
|
scoped = tenant_scope(scope)
|
|
clause, args = scoped.clause(alias), list(scoped.params)
|
|
if actor is not None:
|
|
access = current_access(db, actor, required)
|
|
extra, params = access.job_sql(alias) if jobs else access.item_sql(alias)
|
|
clause += ' AND ' + extra
|
|
args.extend(params)
|
|
return clause, args
|