Repository navigation
Expand file tree
/
Copy pathiam_policy_canary.py
More file actions
executable file
·442 lines (389 loc) · 15.7 KB
/
Copy pathiam_policy_canary.py
File metadata and controls
executable file
·442 lines (389 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env python3
"""Scheduled IAM allow/deny canary.
The production AWS account governance posture requires that the
least-privilege execution roles provisioned by ``terraform/iam/`` and the
Organization-level deny boundaries from ``terraform/organizations/`` keep
enforcing the same allow/deny matrix over time. The validation strategy:
* ``scripts/iam_policy_canary.py`` runs on a schedule against a sandbox
AWS account and reports allow/deny diffs to the runbook channel.
This script is that canary. It asks IAM's
``iam:SimulatePrincipalPolicy`` to evaluate a set of
expectations declared in a YAML config file, and fails (exit code = 1,
JSON-formatted report on stdout) the first time the simulated
``EvalDecision`` disagrees with the declared expectation.
YAML config schema
------------------
.. code-block:: yaml
expectations:
- principal: arn:aws:iam::111122223333:role/agent-runtime-role
actions: [bedrock:InvokeModel]
resources:
- "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-*"
expected: allowed
- principal: arn:aws:iam::111122223333:role/agent-runtime-role
actions: [iam:CreateUser]
resources: ["*"]
expected: denied
Each expectation maps 1:1 to a single ``SimulatePrincipalPolicy`` call.
``expected`` MUST be one of the literals ``allowed`` or ``denied``. The
script normalizes boto3's ``EvalDecision`` (which may be e.g.
``"allowed"`` / ``"implicitDeny"`` / ``"explicitDeny"``) into the same
binary vocabulary before comparison.
Invocation
----------
.. code-block:: bash
python scripts/iam_policy_canary.py \\
--role-arn arn:aws:iam::111122223333:role/canary-invoker \\
--region us-east-1 \\
--config ops/iam_canary.yaml
The ``--role-arn`` flag is threaded through as
``CallerArn`` on every ``simulate_principal_policy`` call so CloudTrail
audit logs attribute the simulation to a specific, dedicated role.
Coverage note
-------------
This script lives **outside** ``src/agent/`` and is therefore NOT subject
to the 100 % line+branch coverage gate that applies to the agent package.
Terraform- / ops-only code paths are validated by their own CI jobs.
Design constraints
------------------
* Python 3.10+. No dependencies beyond stdlib, ``boto3`` (lazy-imported —
``boto3`` is already a transitive dependency of ``bedrock-agentcore``
per ``pyproject.toml``), and ``PyYAML`` (lazy-imported — standard
transitive dep).
* Lazy imports keep ``python -m py_compile`` / ``--help`` working in any
venv, including the 100 %-coverage unit-test venv which does not carry
``boto3`` / ``PyYAML`` directly.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
EXIT_OK = 0
EXIT_MISMATCH = 1
EXIT_USAGE = 2
_EXPECTED_LITERALS: frozenset[str] = frozenset({"allowed", "denied"})
_SCP_POLICY_RESOURCE = "aws_organizations_policy.scp_boundary"
_SCP_ATTACHMENT_RESOURCE_PREFIX = "aws_organizations_policy_attachment.scp_boundary"
def _parse_args(argv: list[str]) -> argparse.Namespace:
"""Parse CLI flags."""
parser = argparse.ArgumentParser(
prog="iam_policy_canary",
description=(
"Scheduled IAM allow/deny canary for the production AWS "
"account governance posture. Reads a YAML config of "
"allow/deny expectations and asserts each one via "
"iam:SimulatePrincipalPolicy. Exit code 0 on "
"success, 1 on any mismatch (with a JSON report on stdout). "
"Also exposes a `--scp-plan` subcommand that asserts the "
"Organizations SCP attachment is present in a terraform plan "
"JSON dump."
),
)
parser.add_argument(
"--role-arn",
required=False,
help=(
"IAM role ARN used as CallerArn on every "
"SimulatePrincipalPolicy call (for CloudTrail attribution). "
"Required for the IAM-canary mode; ignored for `--scp-plan`."
),
)
parser.add_argument(
"--region",
default="us-east-1",
help="AWS region for the IAM client (default: us-east-1).",
)
parser.add_argument(
"--config",
required=False,
type=Path,
help=(
"Path to the YAML config of allow/deny expectations (schema "
"in module docstring). Required for the IAM-canary mode; "
"ignored for `--scp-plan`."
),
)
parser.add_argument(
"--scp-plan",
required=False,
type=Path,
default=None,
help=(
"Path to a `terraform show -json plan.out` JSON dump of the "
"`terraform/organizations/` module. When supplied, the "
"script switches to SCP-plan smoke mode and asserts the SCP "
"policy resource (and, when the plan sets `attach_scp = "
"true`, the SCP attachment) are present in the plan. "
"Mutually exclusive with `--config` / `--role-arn`."
),
)
parser.add_argument(
"--expect-attachment",
action="store_true",
help=(
"When used with `--scp-plan`, also assert at least one "
"`aws_organizations_policy_attachment.scp_boundary` entry "
"is present in the plan (i.e. operator has flipped "
"`attach_scp = true`)."
),
)
args = parser.parse_args(argv)
# Mode-specific argument validation: argparse cannot express the
# mutually exclusive groupings cleanly because both modes share the
# `--region` flag.
if args.scp_plan is None:
if not args.role_arn or not args.config:
parser.error(
"IAM-canary mode requires both --role-arn and --config; "
"use --scp-plan <path> for SCP plan-smoke mode instead."
)
else:
if args.role_arn is not None or args.config is not None:
parser.error(
"--scp-plan is mutually exclusive with --role-arn / --config."
)
return args
def _load_config(path: Path) -> list[dict[str, Any]]:
"""Load and shallow-validate the YAML config."""
# Lazy-import so ``--help`` works in a venv without PyYAML installed.
try:
import yaml # type: ignore[import-untyped]
except ImportError as exc: # pragma: no cover - defensive
raise SystemExit(
"PyYAML is required to parse the config file. "
"Install with: pip install pyyaml"
) from exc
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict) or "expectations" not in raw:
raise SystemExit(
f"config {path}: top-level must be a mapping with an 'expectations' key"
)
expectations = raw["expectations"]
if not isinstance(expectations, list) or not expectations:
raise SystemExit(
f"config {path}: 'expectations' must be a non-empty list"
)
for idx, exp in enumerate(expectations):
if not isinstance(exp, dict):
raise SystemExit(f"config {path}: expectation #{idx} must be a mapping")
for key in ("principal", "actions", "resources", "expected"):
if key not in exp:
raise SystemExit(
f"config {path}: expectation #{idx} missing required key '{key}'"
)
if not isinstance(exp["actions"], list) or not exp["actions"]:
raise SystemExit(
f"config {path}: expectation #{idx} 'actions' must be a non-empty list"
)
if not isinstance(exp["resources"], list) or not exp["resources"]:
raise SystemExit(
f"config {path}: expectation #{idx} 'resources' must be a non-empty list"
)
if exp["expected"] not in _EXPECTED_LITERALS:
raise SystemExit(
f"config {path}: expectation #{idx} 'expected' must be one of "
f"{sorted(_EXPECTED_LITERALS)}, got {exp['expected']!r}"
)
return list(expectations)
def _normalize_decision(eval_decision: str) -> str:
"""Map boto3's ``EvalDecision`` (allowed / implicitDeny / explicitDeny) to the binary vocabulary used in the config."""
return "allowed" if eval_decision == "allowed" else "denied"
def _evaluate(
iam_client: Any,
caller_arn: str,
expectation: dict[str, Any],
) -> dict[str, Any]:
"""Evaluate a single expectation against ``simulate_principal_policy``.
Returns a dict describing the result:
{
"principal": str,
"actions": list[str],
"resources": list[str],
"expected": "allowed" | "denied",
"observed": "allowed" | "denied",
"eval_decision_raw": str, # verbatim boto3 EvalDecision
"match": bool,
}
"""
response = iam_client.simulate_principal_policy(
PolicySourceArn=expectation["principal"],
ActionNames=list(expectation["actions"]),
ResourceArns=list(expectation["resources"]),
CallerArn=caller_arn,
)
results = response.get("EvaluationResults", [])
# If IAM returns multiple EvaluationResults (one per action), we fail
# the whole expectation if ANY of them disagrees. This matches the
# "any mismatch -> fail" rule in the module docstring.
match = True
observed = "allowed"
raw_decisions: list[str] = []
for result in results:
raw = result.get("EvalDecisionDetails", {}).get(
"DecisionDetail",
result.get("EvalDecision", ""),
)
decision_raw = result.get("EvalDecision", "")
raw_decisions.append(decision_raw)
observed_one = _normalize_decision(decision_raw)
if observed_one != expectation["expected"]:
match = False
# Aggregate the worst-case observation: if any action is denied we
# report "denied" so the report is unambiguous.
if observed_one == "denied":
observed = "denied"
# Keep `raw` referenced so linters don't complain about the unused
# DecisionDetail fetch above (some providers populate only one of
# the two keys — both are surfaced for completeness).
_ = raw
return {
"principal": expectation["principal"],
"actions": list(expectation["actions"]),
"resources": list(expectation["resources"]),
"expected": expectation["expected"],
"observed": observed,
"eval_decision_raw": raw_decisions,
"match": match,
}
def _scp_plan_smoke(plan_path: Path, *, expect_attachment: bool) -> int:
"""Assert the Organizations SCP exists in a `terraform show -json` plan.
The operator runs ``terraform plan -out plan.out`` and ``terraform
show -json plan.out > plan.json`` against
``terraform/organizations/``, then runs ``python
scripts/iam_policy_canary.py --scp-plan plan.json
[--expect-attachment]`` to assert the SCP resource (and, when the
security review has lifted ``attach_scp`` to ``true``, at least one
matching attachment) is present in the plan.
The script uses only stdlib JSON parsing — no boto3 or AWS calls —
so it can run in any CI shell without AWS credentials.
"""
try:
raw = json.loads(plan_path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
sys.stdout.write(
json.dumps(
{"status": "error", "error": "plan-not-found", "path": str(plan_path)},
indent=2,
sort_keys=True,
)
+ "\n"
)
del exc
return EXIT_MISMATCH
except json.JSONDecodeError as exc:
sys.stdout.write(
json.dumps(
{
"status": "error",
"error": "plan-not-json",
"path": str(plan_path),
"detail": str(exc),
},
indent=2,
sort_keys=True,
)
+ "\n"
)
return EXIT_MISMATCH
addresses: set[str] = set()
# `terraform show -json` records resource changes under either the
# top-level `resource_changes` array (the canonical post-1.0 shape)
# or — for the no-changes case — under `planned_values.root_module`.
# We accept either to keep the smoke step useful in both situations.
for change in raw.get("resource_changes", []):
addr = change.get("address")
if isinstance(addr, str):
addresses.add(addr)
planned = raw.get("planned_values", {}).get("root_module", {})
for resource in planned.get("resources", []):
addr = resource.get("address")
if isinstance(addr, str):
addresses.add(addr)
has_policy = any(
addr == _SCP_POLICY_RESOURCE or addr.startswith(f"{_SCP_POLICY_RESOURCE}[")
for addr in addresses
)
has_attachment = any(
addr.startswith(_SCP_ATTACHMENT_RESOURCE_PREFIX) for addr in addresses
)
failures: list[str] = []
if not has_policy:
failures.append(
f"missing required resource '{_SCP_POLICY_RESOURCE}' in plan"
)
if expect_attachment and not has_attachment:
failures.append(
f"--expect-attachment set but no '{_SCP_ATTACHMENT_RESOURCE_PREFIX}'"
" entries found in plan (set var.attach_scp = true)"
)
if failures:
sys.stdout.write(
json.dumps(
{
"status": "mismatch",
"plan_path": str(plan_path),
"expect_attachment": expect_attachment,
"failures": failures,
"addresses_seen": sorted(addresses),
},
indent=2,
sort_keys=True,
)
+ "\n"
)
return EXIT_MISMATCH
sys.stdout.write(
f"iam_policy_canary --scp-plan: OK (policy={'present' if has_policy else 'absent'},"
f" attachment={'present' if has_attachment else 'absent'})\n"
)
return EXIT_OK
def _run(args: argparse.Namespace) -> int:
"""Core entrypoint. Returns the process exit code."""
if args.scp_plan is not None:
return _scp_plan_smoke(
args.scp_plan, expect_attachment=args.expect_attachment
)
expectations = _load_config(args.config)
# Lazy-import so ``--help`` works in a venv without boto3 installed.
try:
import boto3 # type: ignore[import-untyped]
except ImportError as exc: # pragma: no cover - defensive
raise SystemExit(
"boto3 is required to call iam:SimulatePrincipalPolicy. "
"Install with: pip install boto3"
) from exc
iam_client = boto3.client("iam", region_name=args.region)
report: list[dict[str, Any]] = []
for expectation in expectations:
report.append(_evaluate(iam_client, args.role_arn, expectation))
mismatches = [entry for entry in report if not entry["match"]]
if mismatches:
sys.stdout.write(
json.dumps(
{
"status": "mismatch",
"mismatches": mismatches,
"evaluated": report,
},
indent=2,
sort_keys=True,
)
)
sys.stdout.write("\n")
return EXIT_MISMATCH
sys.stdout.write(
f"iam_policy_canary: OK ({len(report)} expectation(s) matched)\n"
)
return EXIT_OK
def main(argv: list[str] | None = None) -> int:
"""CLI entrypoint. Returns the process exit code."""
try:
args = _parse_args(sys.argv[1:] if argv is None else argv)
except SystemExit as exc:
# argparse exits with 2 on usage errors; preserve that contract.
return int(exc.code) if isinstance(exc.code, int) else EXIT_USAGE
return _run(args)
if __name__ == "__main__":
raise SystemExit(main())