Merge branch 'pam' of github.com:jumpserver/jumpserver into pam

pull/14774/head^2
ibuler 2024-12-16 18:10:43 +08:00
commit 69d2a23861
4 changed files with 76 additions and 29 deletions

View File

@ -77,10 +77,12 @@ class GatheredAccountViewSet(OrgBulkModelViewSet):
serializer_classes = {
"default": serializers.GatheredAccountSerializer,
"status": serializers.GatheredAccountActionSerializer,
"details": serializers.GatheredAccountDetailsSerializer
}
rbac_perms = {
"sync_accounts": "assets.add_gatheredaccount",
"status": "assets.change_gatheredaccount",
"details": "assets.view_gatheredaccount"
}
@action(methods=["put"], detail=True, url_path="status")
@ -102,3 +104,10 @@ class GatheredAccountViewSet(OrgBulkModelViewSet):
handler = RiskHandler(asset, username, request=self.request)
handler.handle_delete_remote()
return Response(status=status.HTTP_200_OK)
@action(methods=["get"], detail=True, url_path="details")
def details(self, request, *args, **kwargs):
pk = kwargs.get('pk')
account = get_object_or_404(GatheredAccount, pk=pk)
serializer = self.get_serializer(account.detail)
return Response(data=serializer.data)

View File

@ -16,17 +16,24 @@ from ..base.manager import AccountBasePlaybookManager
logger = get_logger(__name__)
risk_items = [
# "authorized_keys",
# "sudoers",
# "groups",
"authorized_keys",
"sudoers",
"groups",
]
diff_items = risk_items + [
common_risk_items = [
"address_last_login",
"date_last_login",
"date_password_change",
"date_password_expired",
"detail"
]
diff_items = risk_items + common_risk_items
def format_datetime(value):
if isinstance(value, timezone.datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return value
def get_items_diff(ori_account, d):
@ -35,24 +42,26 @@ def get_items_diff(ori_account, d):
diff = {}
for item in diff_items:
ori = getattr(ori_account, item)
new = d.get(item, "")
if not ori and not new:
continue
if isinstance(ori, timezone.datetime):
ori = ori.strftime("%Y-%m-%d %H:%M:%S")
if isinstance(new, timezone.datetime):
new = new.strftime("%Y-%m-%d %H:%M:%S")
if new != ori:
diff[item] = get_text_diff(str(ori), str(new))
get_item_diff(item, ori_account, d, diff)
ori_account._diff = diff
return diff
def get_item_diff(item, ori_account, d, diff):
detail = getattr(ori_account, 'detail', {})
new_detail = d.get('detail', {})
ori = getattr(ori_account, item, None) or detail.get(item)
new = d.get(item, "") or new_detail.get(item)
if not ori and not new:
return
ori = format_datetime(ori)
new = format_datetime(new)
if new != ori:
diff[item] = get_text_diff(str(ori), str(new))
class AnalyseAccountRisk:
long_time = timezone.timedelta(days=90)
datetime_check_items = [
@ -81,8 +90,8 @@ class AnalyseAccountRisk:
risks = []
for k, v in diff.items():
# if k not in risk_items:
# continue
if k not in risk_items:
continue
risks.append(
dict(
asset=ori_account.asset,
@ -330,12 +339,14 @@ class GatherAccountsManager(AccountBasePlaybookManager):
return ga
@bulk_update_decorator(GatheredAccount, update_fields=diff_items)
@bulk_update_decorator(GatheredAccount, update_fields=common_risk_items)
def update_gathered_account(self, ori_account, d):
diff = get_items_diff(ori_account, d)
if not diff:
return
for k in diff:
if k not in common_risk_items:
continue
setattr(ori_account, k, d[k])
return ori_account
@ -353,7 +364,6 @@ class GatherAccountsManager(AccountBasePlaybookManager):
ori_account = self.ori_gathered_accounts_mapper.get(
"{}_{}".format(asset.id, username)
)
if not ori_account:
self.create_gathered_account(d)
else:

View File

@ -1,4 +1,6 @@
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from accounts.const import AutomationTypes
from accounts.models import GatherAccountsAutomation
@ -12,6 +14,7 @@ __all__ = [
'GatheredAccountSerializer',
'GatheredAccountActionSerializer',
'GatherAccountAutomationSerializer',
'GatheredAccountDetailsSerializer'
]
@ -20,8 +23,8 @@ class GatherAccountAutomationSerializer(BaseAutomationSerializer):
model = GatherAccountsAutomation
read_only_fields = BaseAutomationSerializer.Meta.read_only_fields
fields = (BaseAutomationSerializer.Meta.fields
+ ['is_sync_account', 'check_risk', 'recipients']
+ read_only_fields)
+ ['is_sync_account', 'check_risk', 'recipients']
+ read_only_fields)
extra_kwargs = {
'check_risk': {
'help_text': _('Whether to check the risk of the gathered accounts.'),
@ -36,6 +39,7 @@ class GatherAccountAutomationSerializer(BaseAutomationSerializer):
class AccountAssetSerializer(_AccountAssetSerializer):
class Meta(_AccountAssetSerializer.Meta):
ref_name = "GatheredAccountAssetSerializer"
fields = [f for f in _AccountAssetSerializer.Meta.fields if f != 'auto_config']
@ -48,7 +52,7 @@ class GatheredAccountSerializer(BulkOrgResourceModelSerializer):
'id', 'asset', 'username',
'date_last_login', 'address_last_login',
'remote_present', 'present',
'date_updated', 'status',
'date_updated', 'status', 'detail'
]
read_only_fields = fields
@ -62,3 +66,23 @@ class GatheredAccountSerializer(BulkOrgResourceModelSerializer):
class GatheredAccountActionSerializer(GatheredAccountSerializer):
class Meta(GatheredAccountSerializer.Meta):
read_only_fields = list(set(GatheredAccountSerializer.Meta.read_only_fields) - {'status'})
class GatheredAccountDetailsSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
request = self.context.get('request')
if not request:
return
params = request.query_params
if params.get('format') == 'openapi':
return
pk = request.parser_context['kwargs'].get('pk')
obj = get_object_or_404(GatheredAccount, pk=pk)
details = obj.detail
for key, value in details.items():
if isinstance(value, bool):
self.fields[key] = serializers.BooleanField(label=key, read_only=True)
else:
self.fields[key] = serializers.CharField(label=key, read_only=True)

View File

@ -187,9 +187,13 @@ class ResourceActivityAPIView(generics.ListAPIView):
'id', 'datetime', 'r_detail', 'r_detail_id',
'r_user', 'r_action', 'r_type'
)
org_q = Q(org_id=Organization.SYSTEM_ID) | Q(org_id=current_org.id)
if resource_id:
org_q |= Q(org_id='') | Q(org_id=Organization.ROOT_ID)
org_q = Q()
if not current_org.is_root():
org_q = Q(org_id=Organization.SYSTEM_ID) | Q(org_id=current_org.id)
if resource_id:
org_q |= Q(org_id='') | Q(org_id=Organization.ROOT_ID)
with tmp_to_root_org():
qs1 = self.get_operate_log_qs(fields, limit, org_q, resource_id=resource_id)
qs2 = self.get_activity_log_qs(fields, limit, org_q, resource_id=resource_id)