236 lines
11 KiB
Python
236 lines
11 KiB
Python
"""Request-side access policy enforcement, using existing settings and audit tables."""
|
|
import ipaddress
|
|
import os
|
|
from datetime import timedelta
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from django.db import transaction
|
|
from django.utils import timezone
|
|
from rest_framework.exceptions import ValidationError
|
|
from common.exception.app_exception import AppUnauthorizedFailed
|
|
from system_manage.models import AccessControlPolicy, AccessControlPolicyApplicationRecord, SystemSetting
|
|
from system_manage.models.log_management import Log
|
|
|
|
# A separate settings row; no schema change or automatic migration is needed.
|
|
SETTING_ID = 20
|
|
POLICY_TIMEZONE = ZoneInfo('Asia/Shanghai')
|
|
DEVICE_TYPES = ('桌面端', '移动终端', '平板', '服务器')
|
|
|
|
|
|
def configuration(lock=False):
|
|
query = SystemSetting.objects
|
|
if lock:
|
|
query.get_or_create(type=SETTING_ID, defaults={'meta': {'bindings': [], 'region_networks': []}})
|
|
query = query.select_for_update()
|
|
row = query.filter(type=SETTING_ID).first()
|
|
return row, dict(row.meta or {}) if row else {'bindings': [], 'region_networks': []}
|
|
|
|
|
|
def network(value):
|
|
try:
|
|
return str(ipaddress.ip_network(value.strip(), strict=False))
|
|
except (ValueError, AttributeError):
|
|
raise ValidationError('请输入有效的 IP 或网段')
|
|
|
|
|
|
def client_ip(request):
|
|
"""Only consume forwarded addresses from explicitly trusted proxy chains."""
|
|
try:
|
|
peer = ipaddress.ip_address(request.META.get('REMOTE_ADDR', ''))
|
|
except ValueError:
|
|
return ''
|
|
trusted = []
|
|
for value in os.environ.get('MAXKB_ACCESS_TRUSTED_PROXIES', '').split(','):
|
|
if value.strip():
|
|
trusted.append(ipaddress.ip_network(value.strip(), strict=False))
|
|
forwarded = request.META.get('HTTP_X_FORWARDED_FOR', '')
|
|
if any(peer in block for block in trusted) and forwarded:
|
|
for value in reversed(forwarded.split(',')):
|
|
if not any(peer in block for block in trusted):
|
|
break
|
|
try:
|
|
peer = ipaddress.ip_address(value.strip())
|
|
except ValueError:
|
|
raise AppUnauthorizedFailed(403, '接入受限:来源 IP 无效')
|
|
return str(peer)
|
|
|
|
|
|
def device_type(request):
|
|
agent = request.META.get('HTTP_USER_AGENT', '').lower()
|
|
if any(token in agent for token in ('ipad', 'tablet')) or ('android' in agent and 'mobile' not in agent):
|
|
return '平板'
|
|
if any(token in agent for token in ('mobile', 'iphone', 'android')):
|
|
return '移动终端'
|
|
if any(token in agent for token in ('mozilla', 'windows', 'macintosh', 'x11')):
|
|
return '桌面端'
|
|
if any(token in agent for token in ('curl', 'python', 'java/', 'go-http', 'postman', 'wget', 'node')):
|
|
return '服务器'
|
|
return '未知'
|
|
|
|
|
|
def contains(address, block):
|
|
try:
|
|
return ipaddress.ip_address(address) in ipaddress.ip_network(block, strict=False)
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def policy_reason(policy, now, device, regions):
|
|
"""Empty reason means allowed. Disabled / out-of-effect policies do not restrict."""
|
|
if not policy.enabled or (policy.effect_start_time and now < policy.effect_start_time) or (
|
|
policy.effect_end_time and now >= policy.effect_end_time):
|
|
return ''
|
|
local = now.astimezone(POLICY_TIMEZONE)
|
|
if policy.access_time_enabled:
|
|
start, end = policy.access_start_time, policy.access_end_time
|
|
if start is None or end is None or start == end:
|
|
return '访问时段配置无效'
|
|
current = local.time().replace(tzinfo=None)
|
|
if start < end:
|
|
in_period = start <= current < end
|
|
day = local.isoweekday()
|
|
else:
|
|
in_period = current >= start or current < end
|
|
day = (local - timedelta(days=1)).isoweekday() if current < end else local.isoweekday()
|
|
if not in_period or (policy.allowed_weekdays and day not in policy.allowed_weekdays):
|
|
return '不在允许访问时段'
|
|
if policy.allowed_device_types and device not in policy.allowed_device_types:
|
|
return '设备类型不允许'
|
|
if policy.allowed_regions and not set(policy.allowed_regions).intersection(regions):
|
|
return '来源区域不允许或无法识别'
|
|
return ''
|
|
|
|
|
|
def enforce(request, kind, identifier):
|
|
if request is None:
|
|
return
|
|
target = f'{kind}:{identifier}'
|
|
checked = getattr(request, '_access_policy_checked', set())
|
|
if target in checked:
|
|
return
|
|
_, config = configuration()
|
|
if not config.get('bindings'):
|
|
return
|
|
try:
|
|
address = client_ip(request)
|
|
except AppUnauthorizedFailed:
|
|
Log.objects.create(menu='接入控制', operate='拒绝访问', status=403,
|
|
operation_object={'target': target}, user={}, ip_address=request.META.get('REMOTE_ADDR', '')[:128],
|
|
details={'path': request.path, 'reason': '来源 IP 无效', 'device_type': device_type(request)})
|
|
raise
|
|
bindings = [b for b in config.get('bindings', []) if (
|
|
b['target_type'] == 'SERVICE' and b['target_identifier'] == target) or (
|
|
b['target_type'] == 'DEVICE' and contains(address, b['target_identifier']))]
|
|
if not bindings:
|
|
return
|
|
device = device_type(request)
|
|
regions = {item['name'] for item in config.get('region_networks', []) if contains(address, item['network'])}
|
|
policies = list(AccessControlPolicy.objects.filter(id__in={b['policy_id'] for b in bindings}).order_by('id'))
|
|
reason, denied_policy = '', None
|
|
now = timezone.now()
|
|
for policy in policies:
|
|
reason = policy_reason(policy, now, device, regions)
|
|
if reason:
|
|
denied_policy = policy
|
|
break
|
|
# DRF has not assigned request.user while an authentication handler runs.
|
|
user = request.__dict__.get('_user')
|
|
Log.objects.create(menu='接入控制', operate='拒绝访问' if reason else '允许访问',
|
|
operation_object={'target': target, 'policy_id': str(denied_policy.id) if denied_policy else ''},
|
|
user={'id': str(user.id)} if getattr(user, 'id', None) else {}, status=403 if reason else 200,
|
|
ip_address=address, workspace_id='default',
|
|
details={'path': request.path, 'device_type': device, 'regions': sorted(regions),
|
|
'policies': [p.name for p in policies], 'reason': reason})
|
|
if reason:
|
|
raise AppUnauthorizedFailed(403, f'接入受限:{reason}')
|
|
request._access_policy_checked = checked | {target}
|
|
|
|
|
|
def targets():
|
|
from application.models import Application
|
|
from system_manage.models.ai_hub import AIService, AIParserResource
|
|
return [{'id': f'{kind}:{obj.id}', 'name': obj.name, 'kind': kind,
|
|
'label': f'{label} · {obj.name}'}
|
|
for kind, label, model in (('application', '问答助手', Application),
|
|
('mindmap', '导图服务', AIService), ('parser', '解析服务', AIParserResource))
|
|
for obj in model.objects.all().order_by('name')]
|
|
|
|
|
|
def enforce_task(request, service_id=None, nodes=None):
|
|
"""Call before task transactions so denied-call audit survives their rollback."""
|
|
enforce(request, 'mindmap', service_id or 'workbench')
|
|
for node in nodes if isinstance(nodes, list) else []:
|
|
if isinstance(node, dict) and node.get('type') == 'parse' and node.get('resource_id'):
|
|
enforce(request, 'parser', node['resource_id'])
|
|
|
|
|
|
@transaction.atomic
|
|
def bind(policy_id, operator, data):
|
|
policy = AccessControlPolicy.objects.select_for_update().get(pk=policy_id)
|
|
kind = data['target_type']
|
|
target = data['target_identifier'].strip()
|
|
if kind == 'DEVICE':
|
|
target = network(target)
|
|
name = data.get('target_name', '').strip() or target
|
|
else:
|
|
obj = next((item for item in targets() if item['id'] == target), None)
|
|
if obj is None:
|
|
raise ValidationError('请选择有效服务')
|
|
name = obj['label'][:128]
|
|
row, config = configuration(lock=True)
|
|
item = {'policy_id': str(policy.id), 'target_type': kind, 'target_identifier': target,
|
|
'target_name': name, 'operator_name': operator.nick_name or operator.username,
|
|
'apply_time': timezone.now().isoformat()}
|
|
bindings = config.setdefault('bindings', [])
|
|
if any(all(b[key] == item[key] for key in ('policy_id', 'target_type', 'target_identifier')) for b in bindings):
|
|
raise ValidationError('该对象已绑定此策略')
|
|
bindings.append(item)
|
|
row.meta = config
|
|
row.save(update_fields=['meta', 'update_time'])
|
|
AccessControlPolicyApplicationRecord.objects.create(policy=policy, policy_name=policy.name,
|
|
target_type=kind, target_identifier=target, target_name=name,
|
|
operator=operator, operator_name=item['operator_name'], remark='绑定策略;' + data.get('remark', ''))
|
|
policy.application_count += 1
|
|
policy.last_applied_time = timezone.now()
|
|
policy.save(update_fields=['application_count', 'last_applied_time', 'update_time'])
|
|
return item
|
|
|
|
|
|
@transaction.atomic
|
|
def unbind(policy_id, operator, data):
|
|
policy = AccessControlPolicy.objects.select_for_update().get(pk=policy_id)
|
|
row, config = configuration(lock=True)
|
|
items = config.get('bindings', [])
|
|
removed = [b for b in items if b['policy_id'] == str(policy.id)
|
|
and b['target_type'] == data.get('target_type') and b['target_identifier'] == data.get('target_identifier')]
|
|
if not removed:
|
|
raise ValidationError('绑定不存在')
|
|
config['bindings'] = [b for b in items if b not in removed]
|
|
row.meta = config
|
|
row.save(update_fields=['meta', 'update_time'])
|
|
item = removed[0]
|
|
AccessControlPolicyApplicationRecord.objects.create(policy=policy, policy_name=policy.name,
|
|
target_type=item['target_type'], target_identifier=item['target_identifier'], target_name=item['target_name'],
|
|
operator=operator, operator_name=operator.nick_name or operator.username, remark='解除绑定')
|
|
|
|
|
|
@transaction.atomic
|
|
def save_regions(data):
|
|
if not isinstance(data, list) or len(data) > 500:
|
|
raise ValidationError('区域网段最多500项')
|
|
clean = []
|
|
for item in data:
|
|
if not isinstance(item, dict) or not isinstance(item.get('name'), str) or not 1 <= len(item['name'].strip()) <= 64:
|
|
raise ValidationError('请输入有效区域名称')
|
|
block = network(item.get('network'))
|
|
for prior in clean:
|
|
left, right = ipaddress.ip_network(prior['network']), ipaddress.ip_network(block)
|
|
if left.version == right.version and left.overlaps(right):
|
|
raise ValidationError('区域网段不能重叠')
|
|
clean.append({'name': item['name'].strip(), 'network': block})
|
|
row, config = configuration(lock=True)
|
|
config['region_networks'] = clean
|
|
row.meta = config
|
|
row.save(update_fields=['meta', 'update_time'])
|
|
return clean
|