diff --git a/backend/apps/monitor/views.py b/backend/apps/monitor/views.py index 4de3956..56d6134 100644 --- a/backend/apps/monitor/views.py +++ b/backend/apps/monitor/views.py @@ -994,19 +994,35 @@ def iam_user_project_policies_view(request, pk, pid): return Response({'error': 'not_found'}, status=status.HTTP_404_NOT_FOUND) new_policies = request.data.get('policies', []) - old_policies = project.attached_policies or [] account, ak, sk = _get_volc_account(user.volc_account_id) if not ak: return Response({'error': 'no_credentials'}, status=status.HTTP_400_BAD_REQUEST) svc = IAMService(ak, sk) + + # Get actual current policies from Volcengine (not local DB) + actual_old = [] + try: + resp = svc.client.call('ListAttachedUserPolicies', { + 'UserName': user.username, + 'ProjectName': project.project_name, + }) + for p in resp.get('Result', {}).get('AttachedPolicyMetadata', []): + scopes = p.get('PolicyScope', []) + for s in scopes: + if s.get('PolicyScopeType') == 'Project' and s.get('ProjectName') == project.project_name: + actual_old.append(p.get('PolicyName', '')) + break + except Exception: + actual_old = project.attached_policies or [] + attached = [] detached = [] errors = [] # Remove policies that were removed - to_remove = [p for p in old_policies if p not in new_policies] + to_remove = [p for p in actual_old if p not in new_policies] for policy_name in to_remove: try: svc.detach_policy_in_project(user.username, policy_name, project.project_name) @@ -1015,7 +1031,7 @@ def iam_user_project_policies_view(request, pk, pid): errors.append(f"移除 {policy_name}: {e}") # Add policies that are new - to_add = [p for p in new_policies if p not in old_policies] + to_add = [p for p in new_policies if p not in actual_old] for policy_name in to_add: try: svc.attach_policy_in_project(user.username, policy_name, project.project_name)