fix: project policy update compares against Volcengine actual state

Was comparing against local DB which could be stale.
Now queries Volcengine for actual project-level policies before diffing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
seaislee1209 2026-03-28 23:10:13 +08:00
parent c4c6a03f61
commit 765c80a47a

View File

@ -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)