ic-code 1.6.1__py3-none-any.whl → 1.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ic/__init__.py CHANGED
@@ -4,8 +4,8 @@ IC (Infra Resource Management CLI) - A comprehensive tool for managing cloud inf
4
4
  This package provides CLI tools and libraries for managing AWS, GCP, OCI, CloudFlare, and SSH resources.
5
5
  """
6
6
 
7
- __version__ = "1.6.1"
8
- __author__ = "SangYun"
7
+ __version__ = "1.7.2"
8
+ __author__ = "sykim"
9
9
  __email__ = "cruiser594@gmail.com"
10
10
 
11
11
  # Core components
ic/cli.py CHANGED
@@ -159,6 +159,9 @@ def execute_multi_service_command(platform_name, services, command, args):
159
159
  """Execute a command across multiple services in parallel."""
160
160
  import concurrent.futures
161
161
  from threading import Lock
162
+
163
+ if platform_name == 'cf':
164
+ platform_name = 'cloudflare'
162
165
 
163
166
  discovery = get_platform_discovery()
164
167
  output_lock = Lock()
@@ -270,6 +273,8 @@ def execute_multi_service_command(platform_name, services, command, args):
270
273
 
271
274
  def execute_single_command(args):
272
275
  """Execute a single command using the platform discovery system."""
276
+ if getattr(args, 'platform', None) == 'cf':
277
+ args.platform = 'cloudflare'
273
278
  discovery = get_platform_discovery()
274
279
 
275
280
  # Validate platform availability
@@ -360,14 +365,20 @@ def setup_platform_parsers(platform_subparsers):
360
365
  if platform_name in dev_platforms:
361
366
  help_text += " (개발 중 - 버그 가능성 있음)"
362
367
 
368
+ platform_aliases = ['cf'] if platform_name == 'cloudflare' else []
363
369
  if platform_name in dev_platforms:
364
370
  platform_parser = platform_subparsers.add_parser(
365
371
  platform_name,
372
+ aliases=platform_aliases,
366
373
  help=help_text,
367
374
  formatter_class=lambda prog, p=platform_name: DevelopmentStatusHelpFormatter(p.upper(), prog)
368
375
  )
369
376
  else:
370
- platform_parser = platform_subparsers.add_parser(platform_name, help=help_text)
377
+ platform_parser = platform_subparsers.add_parser(
378
+ platform_name,
379
+ aliases=platform_aliases,
380
+ help=help_text
381
+ )
371
382
 
372
383
  # Create service subparsers
373
384
  service_subparsers = platform_parser.add_subparsers(
@@ -396,8 +407,13 @@ def setup_platform_parsers(platform_subparsers):
396
407
  # Add commands for this service
397
408
  commands = discovery.get_service_commands(platform_name, service_name)
398
409
  for command_name, command_module in commands.items():
410
+ try:
411
+ aliases = getattr(command_module, 'ALIASES', []) or []
412
+ except Exception:
413
+ aliases = []
399
414
  command_parser = command_subparsers.add_parser(
400
415
  command_name,
416
+ aliases=aliases,
401
417
  help=f"{command_name} 명령어"
402
418
  )
403
419
 
@@ -11,8 +11,9 @@ import subprocess
11
11
  from typing import Dict, List, Tuple, Optional
12
12
  from dataclasses import dataclass
13
13
  from pathlib import Path
14
- import pkg_resources
14
+ import importlib.metadata
15
15
  from packaging import version
16
+ from packaging.requirements import Requirement
16
17
  import logging
17
18
 
18
19
  logger = logging.getLogger(__name__)
@@ -159,19 +160,19 @@ class DependencyValidator:
159
160
 
160
161
  # Check version if available
161
162
  try:
162
- installed_version = pkg_resources.get_distribution(package_name).version
163
+ installed_version = importlib.metadata.version(package_name)
163
164
  dep_info.installed_version = installed_version
164
-
165
+
165
166
  # Parse version requirement
166
- req = pkg_resources.Requirement.parse(f"{package_name}{required_version}")
167
- if installed_version in req:
167
+ req = Requirement(f"{package_name}{required_version}")
168
+ if req.specifier.contains(installed_version, prereleases=True):
168
169
  dep_info.is_compatible = True
169
170
  else:
170
171
  dep_info.is_compatible = False
171
172
  dep_info.error_message = (
172
173
  f"Version {installed_version} does not meet requirement {required_version}"
173
174
  )
174
-
175
+
175
176
  except Exception as e:
176
177
  dep_info.error_message = f"Could not determine version: {e}"
177
178
 
@@ -403,7 +403,7 @@ class PlatformDiscovery:
403
403
 
404
404
  def get_command_module(self, platform_name: str, service_name: str, command_name: str) -> Optional[Any]:
405
405
  """
406
- Get a specific command module.
406
+ Get a specific command module (including matching command aliases).
407
407
 
408
408
  Args:
409
409
  platform_name: Name of the platform
@@ -414,7 +414,16 @@ class PlatformDiscovery:
414
414
  Command module or None if not found
415
415
  """
416
416
  commands = self.get_service_commands(platform_name, service_name)
417
- return commands.get(command_name)
417
+ if command_name in commands:
418
+ return commands[command_name]
419
+ for mod in commands.values():
420
+ try:
421
+ aliases = getattr(mod, "ALIASES", None)
422
+ if aliases and command_name in aliases:
423
+ return mod
424
+ except Exception:
425
+ continue
426
+ return None
418
427
 
419
428
  def validate_platform_availability(self, platform_name: str) -> Tuple[bool, Optional[str]]:
420
429
  """
@@ -0,0 +1,531 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ AWS IAM 공통 헬퍼 모듈
4
+
5
+ 계정 조회, 날짜/다중 패턴 필터링, 정책 문서(PolicyDocument)의
6
+ Resource / Condition(IP 제한 등) 및 신뢰 정책(AssumeRolePolicyDocument) 파싱 유틸리티를 제공합니다.
7
+ """
8
+
9
+ import json
10
+ import urllib.parse
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ import boto3
15
+ from common.utils import get_valid_accounts, get_profiles
16
+
17
+
18
+ def parse_iso_datetime(dt_str: Optional[str]) -> Optional[datetime]:
19
+ """
20
+ AWS IAM 날짜 문자열(ISO 8601 등) 또는 datetime 객체를 UTC datetime으로 변환합니다.
21
+ 'N/A', 'no_information', 'not_supported', 빈 문자열 등은 None을 반환합니다.
22
+ """
23
+ if not dt_str:
24
+ return None
25
+ if isinstance(dt_str, datetime):
26
+ return dt_str if dt_str.tzinfo else dt_str.replace(tzinfo=timezone.utc)
27
+ if not isinstance(dt_str, str) or dt_str.strip() in (
28
+ "N/A",
29
+ "no_information",
30
+ "not_supported",
31
+ "-",
32
+ "None",
33
+ ):
34
+ return None
35
+ try:
36
+ cleaned = dt_str.strip().replace("Z", "+00:00")
37
+ dt = datetime.fromisoformat(cleaned)
38
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
39
+ except Exception:
40
+ return None
41
+
42
+
43
+ def format_date_str(val: Any) -> str:
44
+ """datetime 객체나 문자열을 YYYY-MM-DD 형식으로 반환합니다."""
45
+ if not val:
46
+ return "-"
47
+ if isinstance(val, datetime):
48
+ return val.strftime("%Y-%m-%d")
49
+ if isinstance(val, str):
50
+ cleaned = val.strip()
51
+ if cleaned in ("N/A", "no_information", "not_supported", "-", "None"):
52
+ return "-"
53
+ return cleaned[:10]
54
+ return "-"
55
+
56
+
57
+ def calculate_days_ago(dt: Optional[datetime]) -> Tuple[Optional[int], Optional[str]]:
58
+ """
59
+ datetime 객체로부터 현재(UTC) 기준 경과 일수와 날짜 문자열(YYYY-MM-DD)을 계산합니다.
60
+ """
61
+ if not dt:
62
+ return None, None
63
+ if isinstance(dt, str):
64
+ dt = parse_iso_datetime(dt)
65
+ if not dt:
66
+ return None, None
67
+ if dt.tzinfo is None:
68
+ dt = dt.replace(tzinfo=timezone.utc)
69
+ now = datetime.now(timezone.utc)
70
+ delta = now - dt
71
+ days = max(0, delta.days)
72
+ date_str = dt.strftime("%Y-%m-%d")
73
+ return days, date_str
74
+
75
+
76
+ def color_days_badge(
77
+ days: Optional[int], date_str: Optional[str] = None, empty_val: str = "-"
78
+ ) -> str:
79
+ """
80
+ 경과 일수에 따라 색상을 부여합니다:
81
+ - 90일 이상: [bold red]빨강[/bold red]
82
+ - 60~89일: [bold yellow]노랑[/bold yellow]
83
+ - 60일 미만: [bold green]초록[/bold green]
84
+ - 없음: [dim]empty_val[/dim]
85
+ """
86
+ if days is None:
87
+ return f"[dim]{empty_val}[/dim]"
88
+
89
+ text = f"{days}일\n({date_str})" if date_str else f"{days}일"
90
+ if days >= 90:
91
+ return f"[bold red]{text}[/bold red]"
92
+ elif days >= 60:
93
+ return f"[bold yellow]{text}[/bold yellow]"
94
+ else:
95
+ return f"[bold green]{text}[/bold green]"
96
+
97
+
98
+ def match_created_filter(
99
+ created_time_str: Optional[str], created_filter: Optional[str]
100
+ ) -> bool:
101
+ """
102
+ 생성 날짜(created_time_str)가 created_filter 조건에 맞는지 확인합니다.
103
+
104
+ 지원 형식:
105
+ 1. 부분 일치 / 복수 검색 (콤마 구분): 'YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-01,YYYY-MM-15'
106
+ 2. 기간 범위 검색 (~ 또는 ..): 'YYYY-MM-01~YYYY-MM-31'
107
+ 3. 비교 연산자: '>=YYYY-MM-DD', '>YYYY-MM-DD', '<=YYYY-MM-DD', '<YYYY-MM-DD'
108
+ """
109
+ if not created_filter:
110
+ return True
111
+ if not created_time_str or created_time_str == "-":
112
+ return False
113
+
114
+ date_part = str(created_time_str)[:10].strip()
115
+ filter_terms = [t.strip() for t in created_filter.split(",") if t.strip()]
116
+ if not filter_terms:
117
+ return True
118
+
119
+ for term in filter_terms:
120
+ if "~" in term or ".." in term:
121
+ sep = "~" if "~" in term else ".."
122
+ parts = term.split(sep, 1)
123
+ start_date = parts[0].strip()
124
+ end_date = parts[1].strip()
125
+ if (not start_date or date_part >= start_date) and (
126
+ not end_date or date_part <= end_date
127
+ ):
128
+ return True
129
+ continue
130
+
131
+ if term.startswith(">="):
132
+ target = term[2:].strip()
133
+ if date_part >= target:
134
+ return True
135
+ continue
136
+ elif term.startswith(">"):
137
+ target = term[1:].strip()
138
+ if date_part > target:
139
+ return True
140
+ continue
141
+ elif term.startswith("<="):
142
+ target = term[2:].strip()
143
+ if date_part <= target:
144
+ return True
145
+ continue
146
+ elif term.startswith("<"):
147
+ target = term[1:].strip()
148
+ if date_part < target:
149
+ return True
150
+ continue
151
+
152
+ if term in date_part or term in str(created_time_str):
153
+ return True
154
+
155
+ return False
156
+
157
+
158
+ def match_multi_filter(targets: Any, filter_str: Optional[str]) -> bool:
159
+ """
160
+ 콤마(,)로 구분된 복수 검색어(대소문자 무시 부분 일치 및 !제외 패턴)가
161
+ 대상 문자열 또는 문자열 리스트(targets)에 매칭되는지 확인합니다.
162
+ """
163
+ if not filter_str:
164
+ return True
165
+
166
+ if targets is None:
167
+ target_list: List[str] = []
168
+ elif isinstance(targets, (list, tuple, set)):
169
+ target_list = [str(x).lower() for x in targets if x is not None]
170
+ else:
171
+ target_list = [str(targets).lower()]
172
+
173
+ terms = [t.strip().lower() for t in filter_str.split(",") if t.strip()]
174
+ if not terms:
175
+ return True
176
+
177
+ pos_terms = [t for t in terms if not t.startswith("!")]
178
+ neg_terms = [t[1:].strip() for t in terms if t.startswith("!") and t[1:].strip()]
179
+
180
+ for neg in neg_terms:
181
+ if any(neg in item for item in target_list):
182
+ return False
183
+
184
+ if not pos_terms:
185
+ return True
186
+
187
+ if not target_list:
188
+ return False
189
+
190
+ return any(any(pos in item for item in target_list) for pos in pos_terms)
191
+
192
+
193
+ def resolve_aws_accounts(account_input: Optional[str]) -> List[Tuple[str, Optional[str]]]:
194
+ """
195
+ CLI 인자(-a) 또는 로컬 프로필 설정에서 유효한 (account_id, profile_name) 목록을 반환합니다.
196
+ """
197
+ profiles_map = get_profiles()
198
+ valid_accounts = get_valid_accounts(account_input)
199
+
200
+ if not account_input:
201
+ matched = [
202
+ item
203
+ for item in valid_accounts
204
+ if item[1] in profiles_map.values() and item[1] != "default"
205
+ ]
206
+ if not matched and profiles_map:
207
+ valid_accounts = [
208
+ (acct_id, prof_name)
209
+ for acct_id, prof_name in profiles_map.items()
210
+ if prof_name != "default"
211
+ ]
212
+
213
+ if not valid_accounts:
214
+ try:
215
+ sts = boto3.client("sts")
216
+ cid = sts.get_caller_identity()
217
+ acct = cid.get("Account", "default")
218
+ prof = profiles_map.get(acct)
219
+ valid_accounts = [(acct, prof)]
220
+ except Exception:
221
+ valid_accounts = [("default", None)]
222
+
223
+ return valid_accounts
224
+
225
+
226
+ def get_account_display_name(account_id: str, profile_name: Optional[str]) -> str:
227
+ """프로필명 우선으로 표시할 계정 이름을 반환합니다."""
228
+ profiles_map = get_profiles()
229
+ account_display = profile_name or profiles_map.get(account_id, account_id)
230
+ if account_display == "default" and account_id != "default":
231
+ account_display = account_id
232
+ return account_display
233
+
234
+
235
+ def normalize_policy_document(doc: Any) -> Dict[str, Any]:
236
+ """AWS 정책 문서(dict 또는 URL-encoded JSON 문자열)를 dict로 정규화합니다."""
237
+ if not doc:
238
+ return {}
239
+ if isinstance(doc, dict):
240
+ return doc
241
+ if isinstance(doc, str):
242
+ try:
243
+ unquoted = urllib.parse.unquote(doc)
244
+ parsed = json.loads(unquoted)
245
+ return parsed if isinstance(parsed, dict) else {}
246
+ except Exception:
247
+ return {}
248
+ return {}
249
+
250
+
251
+ def format_condition_map(
252
+ cond_map: Any, effect: str = "Allow", include_effect: bool = True
253
+ ) -> List[str]:
254
+ """
255
+ IAM Statement의 Condition 블록을 사람이 읽기 쉬운 문자열 리스트로 변환합니다.
256
+ 예: [Deny] NotIpAddress: aws:SourceIp = 1.2.3.4/32, 5.6.7.8/32
257
+ """
258
+ if not cond_map or not isinstance(cond_map, dict):
259
+ return []
260
+
261
+ eff_prefix = ""
262
+ if include_effect:
263
+ if effect.lower() == "deny":
264
+ eff_prefix = "[bold red][Deny][/bold red] "
265
+ else:
266
+ eff_prefix = "[bold green][Allow][/bold green] "
267
+
268
+ results: List[str] = []
269
+ for op, kv in cond_map.items():
270
+ if isinstance(kv, dict):
271
+ for k, v in kv.items():
272
+ v_list = [v] if isinstance(v, (str, int, float, bool)) else list(v or [])
273
+ v_str = ", ".join(str(x) for x in v_list)
274
+ results.append(f"{eff_prefix}{op}: {k} = {v_str}")
275
+ else:
276
+ results.append(f"{eff_prefix}{op}: {kv}")
277
+ return results
278
+
279
+
280
+ def extract_policy_restrictions(
281
+ doc: Any,
282
+ ) -> Tuple[List[str], List[str], List[str]]:
283
+ """
284
+ IAM PolicyDocument에서:
285
+ 1) resources: 제한된 특정 리소스 목록 (전체 와일드카드만 있으면 ['*'])
286
+ 2) conditions: IP 제한(aws:SourceIp), MFA, 리전 등 Condition 표현식 목록
287
+ 3) statements_summary: 각 Statement 요약 ([Effect] Action -> Resource [Condition])
288
+ 을 추출하여 반환합니다.
289
+ """
290
+ parsed = normalize_policy_document(doc)
291
+ statements = parsed.get("Statement", [])
292
+ if isinstance(statements, dict):
293
+ statements = [statements]
294
+
295
+ scoped_resources: List[str] = []
296
+ has_wildcard_resource = False
297
+ conditions: List[str] = []
298
+ summaries: List[str] = []
299
+
300
+ for stmt in statements:
301
+ if not isinstance(stmt, dict):
302
+ continue
303
+
304
+ effect = str(stmt.get("Effect", "Allow"))
305
+ actions = stmt.get("Action", stmt.get("NotAction", []))
306
+ if isinstance(actions, str):
307
+ actions = [actions]
308
+ has_not_action = "NotAction" in stmt
309
+
310
+ resources = stmt.get("Resource", stmt.get("NotResource", []))
311
+ if isinstance(resources, str):
312
+ resources = [resources]
313
+ has_not_resource = "NotResource" in stmt
314
+
315
+ for r in resources:
316
+ r_str = str(r)
317
+ if r_str == "*":
318
+ has_wildcard_resource = True
319
+ else:
320
+ label = f"NotResource: {r_str}" if has_not_resource else r_str
321
+ if effect.lower() == "deny":
322
+ label = f"[bold red][Deny][/bold red] {label}"
323
+ if label not in scoped_resources:
324
+ scoped_resources.append(label)
325
+
326
+ stmt_conds = format_condition_map(
327
+ stmt.get("Condition"), effect=effect, include_effect=True
328
+ )
329
+ for c in stmt_conds:
330
+ if c not in conditions:
331
+ conditions.append(c)
332
+
333
+ act_str = ", ".join(str(a) for a in actions[:4])
334
+ if len(actions) > 4:
335
+ act_str += f" (+{len(actions) - 4})"
336
+ if has_not_action:
337
+ act_str = f"NotAction({act_str})"
338
+
339
+ res_str = ", ".join(str(r) for r in resources[:3])
340
+ if len(resources) > 3:
341
+ res_str += f" (+{len(resources) - 3})"
342
+ if has_not_resource:
343
+ res_str = f"NotResource({res_str})"
344
+
345
+ effect_tag = (
346
+ f"[bold green]{effect}[/bold green]"
347
+ if effect.lower() == "allow"
348
+ else f"[bold red]{effect}[/bold red]"
349
+ )
350
+ cond_plain = format_condition_map(
351
+ stmt.get("Condition"), effect=effect, include_effect=False
352
+ )
353
+ cond_suffix = f" [yellow](When: {'; '.join(cond_plain)})[/yellow]" if cond_plain else ""
354
+ summaries.append(f"[{effect_tag}] {act_str} -> {res_str}{cond_suffix}")
355
+
356
+ if scoped_resources:
357
+ final_resources = scoped_resources
358
+ elif has_wildcard_resource:
359
+ final_resources = ["*"]
360
+ else:
361
+ final_resources = []
362
+
363
+ return final_resources, conditions, summaries
364
+
365
+
366
+ def summarize_policy_document(doc: Any, max_statements: int = 8) -> List[str]:
367
+ """
368
+ Policy Document의 Statement를 읽기 쉬운 요약 문자열 리스트로 변환합니다.
369
+ """
370
+ _, _, summaries = extract_policy_restrictions(doc)
371
+ if len(summaries) > max_statements:
372
+ return summaries[:max_statements] + [
373
+ f"... (+{len(summaries) - max_statements} more statements)"
374
+ ]
375
+ return summaries
376
+
377
+
378
+ def parse_aws_role_trust(
379
+ role_dict: Dict[str, Any], account_id: str = ""
380
+ ) -> Tuple[str, List[str], List[str], List[str]]:
381
+ """
382
+ IAM Role 객체에서:
383
+ 1) role_type ('service-linked', 'service', 'federated', 'user')
384
+ 2) trusted_entities (신뢰 주체 표시 목록)
385
+ 3) trusted_users (신뢰된 IAM User 이름 목록)
386
+ 4) trust_conditions (AssumeRolePolicy에 걸린 Condition 제한 조건 목록)
387
+ 을 추출합니다.
388
+ """
389
+ path = role_dict.get("Path", "/") or "/"
390
+ doc = normalize_policy_document(role_dict.get("AssumeRolePolicyDocument"))
391
+ statements = doc.get("Statement", [])
392
+ if isinstance(statements, dict):
393
+ statements = [statements]
394
+
395
+ trusted_entities: List[str] = []
396
+ trusted_users: List[str] = []
397
+ trust_conditions: List[str] = []
398
+ has_service = False
399
+ has_federated = False
400
+ has_aws = False
401
+
402
+ for stmt in statements:
403
+ if not isinstance(stmt, dict):
404
+ continue
405
+ effect = str(stmt.get("Effect", "Allow"))
406
+ if effect.lower() != "allow":
407
+ continue
408
+ principal = stmt.get("Principal", {})
409
+ if principal == "*":
410
+ trusted_entities.append("*")
411
+ has_aws = True
412
+ elif isinstance(principal, dict):
413
+ # Service principals
414
+ svc = principal.get("Service")
415
+ if svc:
416
+ has_service = True
417
+ svc_list = [svc] if isinstance(svc, str) else list(svc)
418
+ for s in svc_list:
419
+ entry = f"Service: {s}"
420
+ if entry not in trusted_entities:
421
+ trusted_entities.append(entry)
422
+
423
+ # Federated principals (SAML / OIDC)
424
+ fed = principal.get("Federated")
425
+ if fed:
426
+ has_federated = True
427
+ fed_list = [fed] if isinstance(fed, str) else list(fed)
428
+ for f in fed_list:
429
+ short_f = f.split(":", 5)[-1] if f.startswith("arn:aws:") else f
430
+ entry = f"Federated: {short_f}"
431
+ if entry not in trusted_entities:
432
+ trusted_entities.append(entry)
433
+
434
+ # AWS principals (Accounts, Users, Roles)
435
+ aws_p = principal.get("AWS")
436
+ if aws_p:
437
+ has_aws = True
438
+ aws_list = [aws_p] if isinstance(aws_p, str) else list(aws_p)
439
+ for a in aws_list:
440
+ a_str = str(a)
441
+ if ":user/" in a_str:
442
+ u_name = a_str.split(":user/")[-1].split("/")[-1]
443
+ if u_name and u_name not in trusted_users:
444
+ trusted_users.append(u_name)
445
+ elif a_str == f"arn:aws:iam::{account_id}:root" or a_str == account_id:
446
+ if ":root" not in trusted_users:
447
+ trusted_users.append(":root")
448
+
449
+ if a_str.startswith("arn:aws:iam::"):
450
+ parts = a_str.split(":")
451
+ acct_part = parts[4] if len(parts) > 4 else ""
452
+ res_part = parts[5] if len(parts) > 5 else a_str
453
+ entry = (
454
+ f"AWS: {acct_part}:{res_part}"
455
+ if acct_part
456
+ else f"AWS: {a_str}"
457
+ )
458
+ else:
459
+ entry = f"AWS: {a_str}"
460
+ if entry not in trusted_entities:
461
+ trusted_entities.append(entry)
462
+
463
+ stmt_conds = format_condition_map(
464
+ stmt.get("Condition"), effect=effect, include_effect=False
465
+ )
466
+ for c in stmt_conds:
467
+ label = f"[Trust] {c}"
468
+ if label not in trust_conditions:
469
+ trust_conditions.append(label)
470
+
471
+ if path.startswith("/aws-service-role/"):
472
+ role_type = "service-linked"
473
+ elif has_federated and not has_aws:
474
+ role_type = "federated"
475
+ elif has_service and not has_aws:
476
+ role_type = "service"
477
+ elif has_aws:
478
+ role_type = "user"
479
+ elif has_federated:
480
+ role_type = "federated"
481
+ else:
482
+ role_type = "service"
483
+
484
+ return role_type, trusted_entities, trusted_users, trust_conditions
485
+
486
+
487
+ def extract_assume_role_targets_from_doc(doc: Any) -> List[str]:
488
+ """
489
+ IAM Policy Document에서 sts:AssumeRole 액션이 허용된 대상 Role 이름 목록을 추출합니다.
490
+ """
491
+ parsed = normalize_policy_document(doc)
492
+ statements = parsed.get("Statement", [])
493
+ if isinstance(statements, dict):
494
+ statements = [statements]
495
+
496
+ target_roles: List[str] = []
497
+ for stmt in statements:
498
+ if not isinstance(stmt, dict):
499
+ continue
500
+ if str(stmt.get("Effect", "")).lower() != "allow":
501
+ continue
502
+
503
+ actions = stmt.get("Action", [])
504
+ if isinstance(actions, str):
505
+ actions = [actions]
506
+ actions_lower = [str(a).lower() for a in actions]
507
+
508
+ allows_assume = any(
509
+ a in ("*", "sts:*", "sts:assumerole") or a.startswith("sts:assumerole")
510
+ for a in actions_lower
511
+ )
512
+ if not allows_assume:
513
+ continue
514
+
515
+ resources = stmt.get("Resource", [])
516
+ if isinstance(resources, str):
517
+ resources = [resources]
518
+
519
+ for res in resources:
520
+ res_str = str(res)
521
+ if ":role/" in res_str:
522
+ role_name = res_str.split(":role/")[-1]
523
+ if role_name and role_name not in target_roles:
524
+ target_roles.append(role_name)
525
+ elif res_str == "*" and any(
526
+ a.startswith("sts:assumerole") for a in actions_lower
527
+ ):
528
+ if "*" not in target_roles:
529
+ target_roles.append("*")
530
+
531
+ return target_roles