Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 73 additions & 60 deletions agent/src/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,16 +524,16 @@ class _ParsedRule:
severity: str | None


def _parse_policy_annotations(cedarpy_module, policies_text: str) -> list[_ParsedRule]:
"""Parse every static policy's annotations via cedarpy.policies_to_json_str.

Returns a list in cedarpy's positional order. Raises on malformed input.
"""
def _parse_policy_set(cedarpy_module, policies_text: str) -> dict:
try:
parsed = json.loads(cedarpy_module.policies_to_json_str(policies_text))
return json.loads(cedarpy_module.policies_to_json_str(policies_text))
except Exception as exc:
raise ValueError(f"Cedar policy parse failed: {type(exc).__name__}: {exc}") from exc


def _parse_policy_annotations(cedarpy_module, policies_text: str) -> list[_ParsedRule]:
"""Read every static policy's annotations in cedarpy's positional order."""
parsed = _parse_policy_set(cedarpy_module, policies_text)
rules: list[_ParsedRule] = []
for pid, body in parsed.get("staticPolicies", {}).items():
ann = body.get("annotations", {}) or {}
Expand All @@ -559,6 +559,53 @@ def _parse_policy_annotations(cedarpy_module, policies_text: str) -> list[_Parse
return rules


def _route_operator_policies(
cedarpy_module, extra_policies: list[str], blueprint_policies: list[str]
) -> tuple[list[str], list[str]]:
"""Keep each entry intact. Only entries without a tier or rule ID get a generated ID."""
hard: list[str] = []
soft: list[str] = []
legacy_count = 0
for field_name, entries in (
("extra_policies", extra_policies),
("cedar_policies", blueprint_policies),
):
for idx, text in enumerate(entries):
source = f"{field_name}[{idx}]"
try:
parsed = _parse_policy_set(cedarpy_module, text)
except ValueError as exc:
raise ValueError(f"{source}: {exc}") from exc
templates = parsed.get("templates", {}).values()
if templates and field_name == "cedar_policies":
raise ValueError(
f"{source} contains an unbound Cedar template; use a static policy"
)
bodies = (*parsed.get("staticPolicies", {}).values(), *templates)
if not bodies:
raise ValueError(f"{source} must contain a Cedar policy")
annotations = [body.get("annotations", {}) for body in bodies]
tiers = {ann.get("tier") for ann in annotations}
if tiers == {None} and all("rule_id" not in ann for ann in annotations):
soft.append(f'@tier("soft")\n@rule_id("legacy_extra_{legacy_count}")\n{text}')
legacy_count += 1
elif field_name == "extra_policies":
raise ValueError(
f"{source} already declares @tier or @rule_id; use blueprint_policies"
)
elif tiers == {"hard"}:
hard.append(text)
elif tiers == {"soft"}:
soft.append(text)
elif {"hard", "soft"} <= tiers:
raise ValueError(
f"{source} declares both hard and soft tiers; use separate entries"
)
else:
raise ValueError(f'{source}: declare the tier ("hard" or "soft") on each rule')
return hard, soft


def _validate_tier(rules: list[_ParsedRule], expected_tier: str, source: str) -> None:
"""Every rule in a tier file MUST declare matching @tier + @rule_id.

Expand Down Expand Up @@ -696,20 +743,18 @@ class PolicyEngine:
disable-list validation), probes a test authorization to catch syntax
errors early, and seeds the approval allowlist from ``initial_approvals``.

Legacy callers that pass ``extra_policies=[...]`` (Phase 1 shape) are
supported in backward-compat mode: the extra text is appended to the
soft-deny tier WITHOUT strict annotation validation. New callers in
Chunks 3+ should use ``blueprint_hard_policies`` / ``blueprint_soft_policies``
/ ``blueprint_disable`` / ``initial_approvals`` / ``approval_gate_cap``.
Each ``blueprint_policies`` entry declares its tier in Cedar. Unannotated
entries and legacy ``extra_policies`` get generated soft rule IDs.
"""

def __init__( # noqa: C901 -- 18 when the ceiling of 15 was set; must not grow
def __init__(
self,
task_type: str,
repo: str,
*,
read_only: bool = False,
extra_policies: list[str] | None = None,
blueprint_policies: list[str] | None = None,
blueprint_hard_policies: str | None = None,
blueprint_soft_policies: str | None = None,
blueprint_disable: list[str] | None = None,
Expand Down Expand Up @@ -789,60 +834,28 @@ def __init__( # noqa: C901 -- 18 when the ceiling of 15 was set; must not grow
# (rm -rf /, .git writes, DROP TABLE) are missing.
raise RuntimeError(str(exc)) from exc

# Blueprint customization: append blueprint rules into the tiers.
hard_text = builtin_hard
if blueprint_hard_policies:
hard_text = f"{hard_text}\n{blueprint_hard_policies}"
soft_text = builtin_soft

# Legacy ``extra_policies`` goes into soft tier with a synthetic
# wrapper (@tier("soft") + @rule_id("legacy_extra_N")). Cedar's
# annotation semantics on duplicate keys within a single policy
# are implementation-defined (parse error in most versions), so
# we REJECT legacy text that already declares @tier or @rule_id
# (finding #2 from Chunk 2 review) instead of silently picking
# one interpretation. Callers should migrate to
# blueprint_soft_policies / blueprint_hard_policies with fully
# annotated rules.
legacy_extra: list[str] = []
if extra_policies:
for idx, policy_text in enumerate(extra_policies):
if "@tier(" in policy_text or "@rule_id(" in policy_text:
raise ValueError(
f"extra_policies[{idx}] already declares @tier or "
f"@rule_id; the legacy extra_policies kwarg is for "
f"UNANNOTATED rules only. Migrate annotated rules "
f"to blueprint_soft_policies / blueprint_hard_policies."
)
legacy_rule_id = f"legacy_extra_{idx}"
legacy_extra.append(f'@tier("soft")\n@rule_id("{legacy_rule_id}")\n{policy_text}')
if blueprint_soft_policies:
soft_text = f"{soft_text}\n{blueprint_soft_policies}"
if legacy_extra:
soft_text = soft_text + "\n" + "\n".join(legacy_extra)

# 64 KB cap on combined operator-supplied policy text (finding #12).
# Built-ins do not count — they are trusted platform content. Registry
# cedar_policy_module assets arrive via the legacy ``extra_policies``
# path, so they MUST be counted here too; otherwise a large registry
# policy bypasses the cap entirely (#246 review). Count the raw operator
# text (pre-synthetic-wrapper) so the bound reflects authored bytes.
operator_text = "".join(
filter(
None,
[
blueprint_hard_policies,
blueprint_soft_policies,
*(extra_policies or []),
],
# Cap all operator-authored bytes before asking Cedar to parse any of them.
operator_bytes = sum(
len(text.encode("utf-8"))
for text in (
blueprint_hard_policies or "",
blueprint_soft_policies or "",
*(extra_policies or []),
*(blueprint_policies or []),
)
)
if len(operator_text.encode("utf-8")) > POLICIES_MAX_BYTES:
if operator_bytes > POLICIES_MAX_BYTES:
raise ValueError(
f"cedar_policies exceeds {POLICIES_MAX_BYTES // 1024} KB cap "
f"({len(operator_text.encode('utf-8'))} bytes)"
f"({operator_bytes} bytes)"
)

hard, soft = _route_operator_policies(
self._cedarpy, extra_policies or [], blueprint_policies or []
)
hard_text = "\n".join(filter(None, [builtin_hard, blueprint_hard_policies, *hard]))
soft_text = "\n".join(filter(None, [builtin_soft, blueprint_soft_policies, *soft]))

# Parse + validate annotations on each tier.
try:
self._hard_rules = _parse_policy_annotations(self._cedarpy, hard_text)
Expand Down
2 changes: 1 addition & 1 deletion agent/src/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def _initialize_policy_engine_and_hooks(
task_type=config.policy_principal,
repo=config.repo_url,
read_only=config.read_only,
extra_policies=cedar_policies or None,
blueprint_policies=cedar_policies or None,
**engine_kwargs,
)
# Surface the resolved cap + its source so operators can distinguish a
Expand Down
103 changes: 103 additions & 0 deletions agent/tests/test_blueprint_cedar_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

"""Exercise Blueprint Cedar policies through the runner's normal bootstrap."""

from __future__ import annotations

import re
from pathlib import Path
from unittest.mock import MagicMock

import pytest

from models import TaskConfig
from policy import POLICIES_MAX_BYTES, PolicyEngine
from runner import _initialize_policy_engine_and_hooks

LEGACY = """forbid (principal, action == Agent::Action::"execute_bash", resource)
when { context.command == "echo legacy" };"""


@pytest.fixture(scope="module")
def guide_policies() -> list[str]:
guide = Path(__file__).resolve().parents[2] / "docs/guides/CEDAR_POLICY_GUIDE.md"
array = re.search(
r"cedarPolicies:\s*\[(.*?)^\s*\]", guide.read_text(), re.DOTALL | re.MULTILINE
)
assert array, "The guide must include the Blueprint's cedarPolicies array"
return re.findall(r"`([^`]+)`", array[1])


def engine_for(policies: list[str], *, timeout_s: int | None = None) -> PolicyEngine:
config = TaskConfig(
repo_url="owner/repo",
aws_region="us-east-1",
cedar_policies=policies,
approval_timeout_s=timeout_s,
)
engine, _ = _initialize_policy_engine_and_hooks(
config=config, trajectory=None, progress=MagicMock()
)
return engine


@pytest.mark.parametrize("tool", ["Write", "Edit"])
@pytest.mark.parametrize(
("path", "outcome"),
[
("prod/config.yaml", "deny"),
("/workspace/repo/prod/config.yaml", "deny"),
("services/prod/nested/config.yaml", "deny"),
("/workspace/repo/prod/nested/config.yaml", "deny"),
("production/config.yaml", "allow"),
("/workspace/repo/nonprod/config.yaml", "allow"),
],
)
def test_guide_hard_rule_matches_the_prod_directory(guide_policies, tool, path, outcome):
decision = engine_for(guide_policies).evaluate_tool_use(tool, {"file_path": path})
assert decision.outcome == outcome
if outcome == "deny":
assert "block_prod_writes" in decision.reason


@pytest.mark.parametrize(("task_timeout", "expected"), [(None, 300), (600, 600), (3600, 900)])
def test_guide_soft_rule_uses_shorter_approval_window(guide_policies, task_timeout, expected):
engine = engine_for(guide_policies, timeout_s=task_timeout)
decision = engine.evaluate_tool_use("Bash", {"command": "terraform apply"})
assert decision.outcome == "require_approval"
assert decision.matching_rule_ids == ("deploy_staging",)
assert decision.timeout_s == expected
assert engine.evaluate_tool_use("Bash", {"command": "terraform plan"}).outcome == "allow"


@pytest.mark.parametrize(
"comment", ["", '// Older versions used @tier("hard") and @rule_id("old").\n']
)
def test_legacy_rule_keeps_its_generated_id(guide_policies, comment):
engine = engine_for([*guide_policies, comment + LEGACY])
decision = engine.evaluate_tool_use("Bash", {"command": "echo legacy"})
assert decision.outcome == "require_approval"
assert decision.matching_rule_ids == ("legacy_extra_0",)


def test_mixed_tiers_in_one_entry_fail_task_start(guide_policies):
with pytest.raises(ValueError, match="both"):
engine_for(["\n".join(guide_policies)])


def test_rule_id_without_a_tier_fails_task_start():
with pytest.raises(ValueError, match="declare the tier"):
engine_for(['@rule_id("orphan")\nforbid (principal, action, resource);'])


def test_unbound_template_in_a_blueprint_entry_fails_task_start(guide_policies):
with pytest.raises(ValueError, match=r"cedar_policies\[1\].*template"):
engine_for(
[LEGACY, guide_policies[0] + "\npermit (principal == ?principal, action, resource);"]
)


def test_oversized_blueprint_is_rejected_before_parsing():
with pytest.raises(ValueError, match="64 KB cap"):
engine_for([" " * POLICIES_MAX_BYTES, "malformed"])
25 changes: 25 additions & 0 deletions agent/tests/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,31 @@ def _config(**overrides: Any) -> TaskConfig:
return TaskConfig(**base)


class TestBlueprintCedarPolicyBootstrap:
@pytest.mark.parametrize(
"annotation",
[
'@tier ( "soft" )',
'// Previously used @tier("hard").\n@tier("soft")',
],
)
@patch("hooks.build_hook_matchers")
def test_cedar_recognizes_the_tier_despite_formatting_or_comments(
self, _mock_build_hooks, annotation
):
policy = (
f'{annotation}\n@rule_id("review_report")\n'
'forbid (principal, action == Agent::Action::"execute_bash", resource)\n'
' when { context.command == "echo report" };'
)
engine, _ = _initialize_policy_engine_and_hooks(
config=_config(cedar_policies=[policy]), trajectory=None, progress=MagicMock()
)
decision = engine.evaluate_tool_use("Bash", {"command": "echo report"})
assert decision.outcome == "require_approval"
assert decision.matching_rule_ids == ("review_report",)


class TestClaudeSessionOwnership:
@pytest.mark.parametrize("microvm", [False, True])
@pytest.mark.parametrize(
Expand Down
29 changes: 8 additions & 21 deletions cdk/src/handlers/get-policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,25 +150,15 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
return successResponse(200, cached.response, requestId);
}

// Repos without custom policies still get the built-in set. A
// Blueprint entry that carries no annotations runs in the agent as
// a soft rule named ``legacy_extra_<n>``, n counting such entries
// (``agent/src/policy.py``). List it the same way: that id is what
// an approval request shows and what a ``rule:<id>`` scope takes.
let legacyCount = 0;
const blueprintText = (config?.cedar_policies ?? [])
.map((p) => (p.includes('@tier(') || p.includes('@rule_id(')
? p
: `@tier("soft")\n@rule_id("legacy_extra_${legacyCount++}")\n${p}`))
.join('\n');
const hardText = BUILTIN_HARD_DENY_POLICIES;
const softText = concatPolicies(BUILTIN_SOFT_DENY_POLICIES, blueprintText);

let hardRules;
let softRules;
let rules;
try {
hardRules = parseRules(hardText);
softRules = parseRules(softText);
rules = parseRules(concatPolicies(BUILTIN_HARD_DENY_POLICIES, BUILTIN_SOFT_DENY_POLICIES));
// Approval requests use these same IDs, counting only legacy entries.
let legacyCount = 0;
const nextLegacyRuleId = () => `legacy_extra_${legacyCount++}`;
for (const entry of config?.cedar_policies ?? []) {
rules.push(...parseRules(entry, nextLegacyRuleId));
}
} catch (err) {
if (err instanceof CedarPolicyParseError) {
logger.error('Cedar parse failure for repo policies', {
Expand All @@ -185,9 +175,6 @@ export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayPr
throw err;
}

// A rule's own @tier decides where it is listed: a Blueprint entry
// annotated @tier("hard") was parsed with the soft text above.
const rules = [...hardRules, ...softRules];
const response: GetPoliciesResponse = {
repo_id: repoId,
policies: {
Expand Down
Loading
Loading