From 544c64efa9bc0d2c05a27ce8dd61784da8f31bbb Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 13:03:27 +0000 Subject: [PATCH 1/2] fix(agent): route annotated Blueprint Cedar rules by tier Every repo cedar_policies entry went to PolicyEngine's legacy extra_policies path, which rejects @tier/@rule_id. Following the Cedar policy guide (annotated hard/soft rules) therefore failed every task on that repo at start; blueprint_soft_policies/blueprint_hard_policies were only ever used in unit tests. Registry Cedar modules share the field. - split_blueprint_policies routes @tier("hard") entries to the hard input, @tier("soft") to the soft input, and leaves unannotated entries on the legacy path. An entry declaring both tiers, or @rule_id without a tier, fails with a clear error instead of being guessed. - Tests: the guide's verbatim example rules build an engine through the runner's bootstrap and enforce as documented (hard deny, soft gate with min-wins timeout); fails with the original ValueError on the old wiring. - CEDAR_POLICY_GUIDE described a blueprint.yaml {hard, soft, disable} format and maxPreApprovalScope that do not exist; it now documents the Blueprint construct's array form and says which options are not implemented yet. --- agent/src/runner.py | 42 ++++++++- agent/tests/test_blueprint_cedar_routing.py | 89 +++++++++++++++++++ agent/tests/test_runner.py | 27 ++++++ docs/guides/CEDAR_POLICY_GUIDE.md | 60 +++++++------ .../docs/customizing/Cedar-policies.md | 60 +++++++------ 5 files changed, 221 insertions(+), 57 deletions(-) create mode 100644 agent/tests/test_blueprint_cedar_routing.py diff --git a/agent/src/runner.py b/agent/src/runner.py index d4d83c8d3..9eb68c7f6 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -241,6 +241,43 @@ def _setup_agent_env(config: TaskConfig) -> tuple[str | None, str | None]: return otlp_endpoint, otlp_protocol +_TIER_HARD = '@tier("hard")' +_TIER_SOFT = '@tier("soft")' + + +def split_blueprint_policies(policies: list[str]) -> tuple[list[str], list[str], list[str]]: + """Route Blueprint ``cedar_policies`` strings to the engine input their tier needs. + + Annotated rules (``@tier("hard")`` / ``@tier("soft")``, as documented in the + Cedar policy guide) go to ``blueprint_hard_policies`` / ``blueprint_soft_policies``. + Unannotated rules keep the legacy ``extra_policies`` path, which wraps each one + as a soft rule. A string that declares both tiers, or ``@rule_id`` without a + tier, is rejected: guessing would silently change what a rule enforces. + """ + legacy: list[str] = [] + hard: list[str] = [] + soft: list[str] = [] + for idx, text in enumerate(policies): + is_hard, is_soft = _TIER_HARD in text, _TIER_SOFT in text + if is_hard and is_soft: + raise ValueError( + f'cedar_policies[{idx}] declares both @tier("hard") and @tier("soft"); ' + "put hard and soft rules in separate entries" + ) + if is_hard: + hard.append(text) + elif is_soft: + soft.append(text) + elif "@rule_id(" in text or "@tier(" in text: + raise ValueError( + f"cedar_policies[{idx}] has Cedar HITL annotations but no " + '@tier("hard") or @tier("soft"); declare the tier explicitly' + ) + else: + legacy.append(text) + return legacy, hard, soft + + def _initialize_policy_engine_and_hooks( *, config: TaskConfig, @@ -283,11 +320,14 @@ def _initialize_policy_engine_and_hooks( # DEFAULT_APPROVAL_GATE_CAP. if config.approval_gate_cap is not None: engine_kwargs["approval_gate_cap"] = config.approval_gate_cap + legacy, hard, soft = split_blueprint_policies(cedar_policies or []) policy_engine = PolicyEngine( task_type=config.policy_principal, repo=config.repo_url, read_only=config.read_only, - extra_policies=cedar_policies if cedar_policies else None, + extra_policies=legacy or None, + blueprint_hard_policies="\n".join(hard) or None, + blueprint_soft_policies="\n".join(soft) or None, **engine_kwargs, ) # Surface the resolved cap + its source so operators can distinguish a diff --git a/agent/tests/test_blueprint_cedar_routing.py b/agent/tests/test_blueprint_cedar_routing.py new file mode 100644 index 000000000..9dfe7733e --- /dev/null +++ b/agent/tests/test_blueprint_cedar_routing.py @@ -0,0 +1,89 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""Blueprint ``cedar_policies`` reach the engine input their declared tier needs. + +The Cedar policy guide documents fully annotated hard and soft rules. Before this +routing, every annotated rule went down the legacy ``extra_policies`` path, which +rejects annotations, so following the guide failed every task at start. +""" + +from __future__ import annotations + +import pytest + +from policy import PolicyEngine +from runner import split_blueprint_policies + +# Verbatim from docs/guides/CEDAR_POLICY_GUIDE.md "Where rules live". +GUIDE_HARD = """@tier("hard") +@rule_id("block_prod_writes") +forbid (principal, action == Agent::Action::"write_file", resource) + when { context.file_path like "prod/**" };""" +GUIDE_SOFT = """@tier("soft") +@rule_id("deploy_staging") +@severity("high") +@approval_timeout_s("900") +@category("destructive") +forbid (principal, action == Agent::Action::"execute_bash", resource) + when { context.command like "*terraform apply*" };""" +LEGACY = """forbid (principal, action == Agent::Action::"execute_bash", resource) + when { context.command like "*legacy-danger*" };""" + + +def engine_for(policies: list[str], **kwargs) -> PolicyEngine: + legacy, hard, soft = split_blueprint_policies(policies) + return PolicyEngine( + task_type="new_task", + repo="owner/repo", + extra_policies=legacy or None, + blueprint_hard_policies="\n".join(hard) or None, + blueprint_soft_policies="\n".join(soft) or None, + **kwargs, + ) + + +def test_routes_each_string_by_its_declared_tier(): + assert split_blueprint_policies([GUIDE_HARD, GUIDE_SOFT, LEGACY]) == ( + [LEGACY], + [GUIDE_HARD], + [GUIDE_SOFT], + ) + + +def test_guide_rules_build_an_engine_and_enforce_as_documented(): + engine = engine_for([GUIDE_HARD, GUIDE_SOFT]) + + hard = engine.evaluate_tool_use("Write", {"file_path": "prod/config.yaml", "content": "x"}) + assert hard.outcome == "deny" + + soft = engine.evaluate_tool_use( + "Bash", {"command": "cd infra && terraform apply -auto-approve"} + ) + assert soft.outcome == "require_approval" + assert "deploy_staging" in soft.matching_rule_ids + # Min-wins: the task's default window (300 s) caps the rule's 900 s ... + assert soft.timeout_s == 300 + # ... and a task submitted with a longer window gets the rule's full 900 s. + longer = engine_for([GUIDE_SOFT], task_default_timeout_s=3600) + assert longer.evaluate_tool_use("Bash", {"command": "terraform apply"}).timeout_s == 900 + + assert engine.evaluate_tool_use("Bash", {"command": "terraform plan"}).outcome == "allow" + + +def test_unannotated_rules_keep_the_legacy_soft_wrapping(): + decision = engine_for([LEGACY]).evaluate_tool_use("Bash", {"command": "run legacy-danger now"}) + assert decision.outcome == "require_approval" + assert tuple(decision.matching_rule_ids) == ("legacy_extra_0",) + + +@pytest.mark.parametrize( + ("text", "message"), + [ + (GUIDE_HARD + "\n" + GUIDE_SOFT, "both"), + ('@rule_id("orphan")\nforbid (principal, action, resource);', "declare the tier"), + ], +) +def test_ambiguous_annotations_fail_instead_of_guessing(text, message): + with pytest.raises(ValueError, match=message): + split_blueprint_policies([text]) diff --git a/agent/tests/test_runner.py b/agent/tests/test_runner.py index ffeeb87c4..e63516d94 100644 --- a/agent/tests/test_runner.py +++ b/agent/tests/test_runner.py @@ -48,6 +48,33 @@ def _config(**overrides: Any) -> TaskConfig: return TaskConfig(**base) +class TestBlueprintCedarPolicyBootstrap: + """A Blueprint's annotated rules must build a real engine, not fail task start.""" + + @patch("hooks.build_hook_matchers") + def test_annotated_blueprint_rules_reach_the_engine(self, _mock_build_hooks): + soft = ( + '@tier("soft")\n@rule_id("deploy_staging")\n@approval_timeout_s("900")\n' + 'forbid (principal, action == Agent::Action::"execute_bash", resource)\n' + ' when { context.command like "*terraform apply*" };' + ) + hard = ( + '@tier("hard")\n@rule_id("block_prod_writes")\n' + 'forbid (principal, action == Agent::Action::"write_file", resource)\n' + ' when { context.file_path like "prod/**" };' + ) + engine, _ = _initialize_policy_engine_and_hooks( + config=_config(cedar_policies=[soft, hard]), trajectory=None, progress=MagicMock() + ) + assert engine.evaluate_tool_use("Bash", {"command": "terraform apply"}).outcome == ( + "require_approval" + ) + assert ( + engine.evaluate_tool_use("Write", {"file_path": "prod/x", "content": "y"}).outcome + == "deny" + ) + + class TestInitializePolicyEngineAndHooks: """Bootstrap the per-task PolicyEngine + hooks without the SDK loop. diff --git a/docs/guides/CEDAR_POLICY_GUIDE.md b/docs/guides/CEDAR_POLICY_GUIDE.md index 15fd92322..98903f5e3 100644 --- a/docs/guides/CEDAR_POLICY_GUIDE.md +++ b/docs/guides/CEDAR_POLICY_GUIDE.md @@ -17,32 +17,37 @@ Both tiers use the same Cedar syntax. The annotation is all that differs. ## Where rules live -A blueprint's `security.cedarPolicies` field in `blueprint.yaml` is concatenated with the platform's built-in rules: - -```yaml -security: - cedarPolicies: - hard: | - @tier("hard") - @rule_id("block_prod_writes") - forbid (principal, action == Agent::Action::"write_file", resource) - when { context.file_path like "prod/**" }; - soft: | - @tier("soft") - @rule_id("deploy_staging") - @severity("high") - @approval_timeout_s("900") - @category("destructive") - forbid (principal, action == Agent::Action::"execute_bash", resource) - when { context.command like "*terraform apply*" }; - disable: - # Opt-out of built-in soft-deny rules you don't want. - # You CANNOT disable built-in hard-deny rules — the platform rejects that at task start. - - write_env_files - maxPreApprovalScope: "tool_type_session" # optional cap on what --pre-approve can grant - approvalGateCap: 50 # optional per-task gate budget (1–500, default 50) +A repository's rules come from its `Blueprint` construct (`security.cedarPolicies`, an array of Cedar policy strings) and from any registry Cedar policy modules attached to it. They are appended to the platform's built-in rules. Each string declares its own tier: + +```ts +new Blueprint(this, 'PaymentsBlueprint', { + repo: 'acme/payments-api', + repoTable, + security: { + cedarPolicies: [ + `@tier("hard") + @rule_id("block_prod_writes") + forbid (principal, action == Agent::Action::"write_file", resource) + when { context.file_path like "prod/**" };`, + `@tier("soft") + @rule_id("deploy_staging") + @severity("high") + @approval_timeout_s("900") + @category("destructive") + forbid (principal, action == Agent::Action::"execute_bash", resource) + when { context.command like "*terraform apply*" };`, + ], + approvalGateCap: 50, // optional per-task gate budget (1–500, default 50) + }, +}); ``` +- **`@tier("hard")`** rules always deny. **`@tier("soft")`** rules pause for approval. +- Keep hard and soft rules in **separate entries**. An entry that declares both tiers, or `@rule_id` without a tier, fails task start rather than being guessed. +- An entry with no annotations at all is treated as a legacy soft rule with a generated rule ID (`legacy_extra_`). +- `@approval_timeout_s` is **min-wins** with the task's own approval window (default 300 s; set `--approval-timeout` up to 3600 s on submit). The rule above therefore waits 300 s unless the task asks for 900 s or more. +- Disabling built-in soft rules and capping `--pre-approve` scopes per repository are not supported yet. + The built-in rule set is documented in [`agent/policies/hard_deny.cedar`](../../agent/policies/hard_deny.cedar) and [`agent/policies/soft_deny.cedar`](../../agent/policies/soft_deny.cedar). Run `bgagent policies list --repo owner/repo` against a deployed stack to see the effective rules for a repo. ## Vocabulary @@ -140,18 +145,17 @@ The blueprint loader runs a probe Cedar evaluation before the task is admitted. - Malformed Cedar syntax. - Duplicate `@rule_id` across hard + soft tiers. -- `@tier` value that doesn't match the file section it was written in. +- An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. - Missing `@rule_id` on a soft-deny rule. - `@approval_timeout_s` below the 30 s floor or non-integer. -- `disable:` entry that names a built-in hard-deny rule (absolute by design) or a nonexistent rule ID. - Combined hard + soft Cedar text exceeding 64 KB. -Fix the blueprint, redeploy (or update the `blueprint.yaml` if you're using a pulled blueprint), resubmit. +Fix the Blueprint, redeploy, resubmit. ## Capacity and UX budgets - **`approvalGateCap`** (1–500, default 50) — per-task ceiling on how many gates can fire before the task is force-terminated. It's a circuit breaker for runaway policy matches, not a rate limit for humans. Raise it for long migrations; lower it for high-risk blueprints. -- **`maxPreApprovalScope`** — optional upper bound on what `--pre-approve` is allowed to seed. If set to `tool_type_session`, a user can't pre-approve `all_session` from the CLI. +- A per-repository cap on what `--pre-approve` may seed (`maxPreApprovalScope`) is designed but not implemented yet. ## Testing policies before shipping diff --git a/docs/src/content/docs/customizing/Cedar-policies.md b/docs/src/content/docs/customizing/Cedar-policies.md index 6fe17e11a..a1342f532 100644 --- a/docs/src/content/docs/customizing/Cedar-policies.md +++ b/docs/src/content/docs/customizing/Cedar-policies.md @@ -21,32 +21,37 @@ Both tiers use the same Cedar syntax. The annotation is all that differs. ## Where rules live -A blueprint's `security.cedarPolicies` field in `blueprint.yaml` is concatenated with the platform's built-in rules: - -```yaml -security: - cedarPolicies: - hard: | - @tier("hard") - @rule_id("block_prod_writes") - forbid (principal, action == Agent::Action::"write_file", resource) - when { context.file_path like "prod/**" }; - soft: | - @tier("soft") - @rule_id("deploy_staging") - @severity("high") - @approval_timeout_s("900") - @category("destructive") - forbid (principal, action == Agent::Action::"execute_bash", resource) - when { context.command like "*terraform apply*" }; - disable: - # Opt-out of built-in soft-deny rules you don't want. - # You CANNOT disable built-in hard-deny rules — the platform rejects that at task start. - - write_env_files - maxPreApprovalScope: "tool_type_session" # optional cap on what --pre-approve can grant - approvalGateCap: 50 # optional per-task gate budget (1–500, default 50) +A repository's rules come from its `Blueprint` construct (`security.cedarPolicies`, an array of Cedar policy strings) and from any registry Cedar policy modules attached to it. They are appended to the platform's built-in rules. Each string declares its own tier: + +```ts +new Blueprint(this, 'PaymentsBlueprint', { + repo: 'acme/payments-api', + repoTable, + security: { + cedarPolicies: [ + `@tier("hard") + @rule_id("block_prod_writes") + forbid (principal, action == Agent::Action::"write_file", resource) + when { context.file_path like "prod/**" };`, + `@tier("soft") + @rule_id("deploy_staging") + @severity("high") + @approval_timeout_s("900") + @category("destructive") + forbid (principal, action == Agent::Action::"execute_bash", resource) + when { context.command like "*terraform apply*" };`, + ], + approvalGateCap: 50, // optional per-task gate budget (1–500, default 50) + }, +}); ``` +- **`@tier("hard")`** rules always deny. **`@tier("soft")`** rules pause for approval. +- Keep hard and soft rules in **separate entries**. An entry that declares both tiers, or `@rule_id` without a tier, fails task start rather than being guessed. +- An entry with no annotations at all is treated as a legacy soft rule with a generated rule ID (`legacy_extra_`). +- `@approval_timeout_s` is **min-wins** with the task's own approval window (default 300 s; set `--approval-timeout` up to 3600 s on submit). The rule above therefore waits 300 s unless the task asks for 900 s or more. +- Disabling built-in soft rules and capping `--pre-approve` scopes per repository are not supported yet. + The built-in rule set is documented in [`agent/policies/hard_deny.cedar`](../../agent/policies/hard_deny.cedar) and [`agent/policies/soft_deny.cedar`](../../agent/policies/soft_deny.cedar). Run `bgagent policies list --repo owner/repo` against a deployed stack to see the effective rules for a repo. ## Vocabulary @@ -144,18 +149,17 @@ The blueprint loader runs a probe Cedar evaluation before the task is admitted. - Malformed Cedar syntax. - Duplicate `@rule_id` across hard + soft tiers. -- `@tier` value that doesn't match the file section it was written in. +- An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. - Missing `@rule_id` on a soft-deny rule. - `@approval_timeout_s` below the 30 s floor or non-integer. -- `disable:` entry that names a built-in hard-deny rule (absolute by design) or a nonexistent rule ID. - Combined hard + soft Cedar text exceeding 64 KB. -Fix the blueprint, redeploy (or update the `blueprint.yaml` if you're using a pulled blueprint), resubmit. +Fix the Blueprint, redeploy, resubmit. ## Capacity and UX budgets - **`approvalGateCap`** (1–500, default 50) — per-task ceiling on how many gates can fire before the task is force-terminated. It's a circuit breaker for runaway policy matches, not a rate limit for humans. Raise it for long migrations; lower it for high-risk blueprints. -- **`maxPreApprovalScope`** — optional upper bound on what `--pre-approve` is allowed to seed. If set to `tool_type_session`, a user can't pre-approve `all_session` from the CLI. +- A per-repository cap on what `--pre-approve` may seed (`maxPreApprovalScope`) is designed but not implemented yet. ## Testing policies before shipping From 7e78a50a8369f3eeb5732badf0cc9c0684daedec Mon Sep 17 00:00:00 2001 From: bgagent Date: Fri, 20 Nov 2026 17:01:47 -0600 Subject: [PATCH 2/2] fix: read Blueprint rule tiers from parsed Cedar policies --- agent/src/policy.py | 133 +++++++++------- agent/src/runner.py | 42 +---- agent/tests/test_blueprint_cedar_routing.py | 146 ++++++++++-------- agent/tests/test_runner.py | 36 ++--- cdk/src/handlers/get-policies.ts | 29 +--- cdk/src/handlers/shared/cedar-policy.ts | 26 +++- cdk/test/handlers/get-policies.test.ts | 27 ++++ docs/guides/CEDAR_POLICY_GUIDE.md | 18 +-- .../docs/customizing/Cedar-policies.md | 18 +-- 9 files changed, 244 insertions(+), 231 deletions(-) diff --git a/agent/src/policy.py b/agent/src/policy.py index b21bf8146..d00ce353d 100644 --- a/agent/src/policy.py +++ b/agent/src/policy.py @@ -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 {} @@ -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. @@ -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, @@ -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) diff --git a/agent/src/runner.py b/agent/src/runner.py index 28ec85c42..061dc287e 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -199,43 +199,6 @@ def _setup_agent_env(config: TaskConfig) -> None: os.environ.update(cleaned) -_TIER_HARD = '@tier("hard")' -_TIER_SOFT = '@tier("soft")' - - -def split_blueprint_policies(policies: list[str]) -> tuple[list[str], list[str], list[str]]: - """Route Blueprint ``cedar_policies`` strings to the engine input their tier needs. - - Annotated rules (``@tier("hard")`` / ``@tier("soft")``, as documented in the - Cedar policy guide) go to ``blueprint_hard_policies`` / ``blueprint_soft_policies``. - Unannotated rules keep the legacy ``extra_policies`` path, which wraps each one - as a soft rule. A string that declares both tiers, or ``@rule_id`` without a - tier, is rejected: guessing would silently change what a rule enforces. - """ - legacy: list[str] = [] - hard: list[str] = [] - soft: list[str] = [] - for idx, text in enumerate(policies): - is_hard, is_soft = _TIER_HARD in text, _TIER_SOFT in text - if is_hard and is_soft: - raise ValueError( - f'cedar_policies[{idx}] declares both @tier("hard") and @tier("soft"); ' - "put hard and soft rules in separate entries" - ) - if is_hard: - hard.append(text) - elif is_soft: - soft.append(text) - elif "@rule_id(" in text or "@tier(" in text: - raise ValueError( - f"cedar_policies[{idx}] has Cedar HITL annotations but no " - '@tier("hard") or @tier("soft"); declare the tier explicitly' - ) - else: - legacy.append(text) - return legacy, hard, soft - - def _initialize_policy_engine_and_hooks( *, config: TaskConfig, @@ -278,14 +241,11 @@ def _initialize_policy_engine_and_hooks( # DEFAULT_APPROVAL_GATE_CAP. if config.approval_gate_cap is not None: engine_kwargs["approval_gate_cap"] = config.approval_gate_cap - legacy, hard, soft = split_blueprint_policies(cedar_policies or []) policy_engine = PolicyEngine( task_type=config.policy_principal, repo=config.repo_url, read_only=config.read_only, - extra_policies=legacy or None, - blueprint_hard_policies="\n".join(hard) or None, - blueprint_soft_policies="\n".join(soft) or None, + blueprint_policies=cedar_policies or None, **engine_kwargs, ) # Surface the resolved cap + its source so operators can distinguish a diff --git a/agent/tests/test_blueprint_cedar_routing.py b/agent/tests/test_blueprint_cedar_routing.py index 9dfe7733e..f63990007 100644 --- a/agent/tests/test_blueprint_cedar_routing.py +++ b/agent/tests/test_blueprint_cedar_routing.py @@ -1,89 +1,103 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 -"""Blueprint ``cedar_policies`` reach the engine input their declared tier needs. - -The Cedar policy guide documents fully annotated hard and soft rules. Before this -routing, every annotated rule went down the legacy ``extra_policies`` path, which -rejects annotations, so following the guide failed every task at start. -""" +"""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 policy import PolicyEngine -from runner import split_blueprint_policies - -# Verbatim from docs/guides/CEDAR_POLICY_GUIDE.md "Where rules live". -GUIDE_HARD = """@tier("hard") -@rule_id("block_prod_writes") -forbid (principal, action == Agent::Action::"write_file", resource) - when { context.file_path like "prod/**" };""" -GUIDE_SOFT = """@tier("soft") -@rule_id("deploy_staging") -@severity("high") -@approval_timeout_s("900") -@category("destructive") -forbid (principal, action == Agent::Action::"execute_bash", resource) - when { context.command like "*terraform apply*" };""" +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 like "*legacy-danger*" };""" - - -def engine_for(policies: list[str], **kwargs) -> PolicyEngine: - legacy, hard, soft = split_blueprint_policies(policies) - return PolicyEngine( - task_type="new_task", - repo="owner/repo", - extra_policies=legacy or None, - blueprint_hard_policies="\n".join(hard) or None, - blueprint_soft_policies="\n".join(soft) or None, - **kwargs, - ) + when { context.command == "echo legacy" };""" -def test_routes_each_string_by_its_declared_tier(): - assert split_blueprint_policies([GUIDE_HARD, GUIDE_SOFT, LEGACY]) == ( - [LEGACY], - [GUIDE_HARD], - [GUIDE_SOFT], +@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 test_guide_rules_build_an_engine_and_enforce_as_documented(): - engine = engine_for([GUIDE_HARD, GUIDE_SOFT]) - - hard = engine.evaluate_tool_use("Write", {"file_path": "prod/config.yaml", "content": "x"}) - assert hard.outcome == "deny" - - soft = engine.evaluate_tool_use( - "Bash", {"command": "cd infra && terraform apply -auto-approve"} +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() ) - assert soft.outcome == "require_approval" - assert "deploy_staging" in soft.matching_rule_ids - # Min-wins: the task's default window (300 s) caps the rule's 900 s ... - assert soft.timeout_s == 300 - # ... and a task submitted with a longer window gets the rule's full 900 s. - longer = engine_for([GUIDE_SOFT], task_default_timeout_s=3600) - assert longer.evaluate_tool_use("Bash", {"command": "terraform apply"}).timeout_s == 900 + return engine - assert engine.evaluate_tool_use("Bash", {"command": "terraform plan"}).outcome == "allow" + +@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 -def test_unannotated_rules_keep_the_legacy_soft_wrapping(): - decision = engine_for([LEGACY]).evaluate_tool_use("Bash", {"command": "run legacy-danger now"}) +@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 tuple(decision.matching_rule_ids) == ("legacy_extra_0",) + 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( - ("text", "message"), - [ - (GUIDE_HARD + "\n" + GUIDE_SOFT, "both"), - ('@rule_id("orphan")\nforbid (principal, action, resource);', "declare the tier"), - ], + "comment", ["", '// Older versions used @tier("hard") and @rule_id("old").\n'] ) -def test_ambiguous_annotations_fail_instead_of_guessing(text, message): - with pytest.raises(ValueError, match=message): - split_blueprint_policies([text]) +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"]) diff --git a/agent/tests/test_runner.py b/agent/tests/test_runner.py index 84850d6e3..ef61d3cc7 100644 --- a/agent/tests/test_runner.py +++ b/agent/tests/test_runner.py @@ -56,30 +56,28 @@ def _config(**overrides: Any) -> TaskConfig: class TestBlueprintCedarPolicyBootstrap: - """A Blueprint's annotated rules must build a real engine, not fail task start.""" - + @pytest.mark.parametrize( + "annotation", + [ + '@tier ( "soft" )', + '// Previously used @tier("hard").\n@tier("soft")', + ], + ) @patch("hooks.build_hook_matchers") - def test_annotated_blueprint_rules_reach_the_engine(self, _mock_build_hooks): - soft = ( - '@tier("soft")\n@rule_id("deploy_staging")\n@approval_timeout_s("900")\n' + 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 like "*terraform apply*" };' - ) - hard = ( - '@tier("hard")\n@rule_id("block_prod_writes")\n' - 'forbid (principal, action == Agent::Action::"write_file", resource)\n' - ' when { context.file_path like "prod/**" };' + ' when { context.command == "echo report" };' ) engine, _ = _initialize_policy_engine_and_hooks( - config=_config(cedar_policies=[soft, hard]), trajectory=None, progress=MagicMock() - ) - assert engine.evaluate_tool_use("Bash", {"command": "terraform apply"}).outcome == ( - "require_approval" - ) - assert ( - engine.evaluate_tool_use("Write", {"file_path": "prod/x", "content": "y"}).outcome - == "deny" + 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: diff --git a/cdk/src/handlers/get-policies.ts b/cdk/src/handlers/get-policies.ts index 62bdcb675..e34150b7c 100644 --- a/cdk/src/handlers/get-policies.ts +++ b/cdk/src/handlers/get-policies.ts @@ -150,25 +150,15 @@ export async function handler(event: APIGatewayProxyEvent): Promise``, 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:`` 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', { @@ -185,9 +175,6 @@ export async function handler(event: APIGatewayProxyEvent): Promise string): ParsedRule[] { + if (!policiesText.trim() && !nextLegacyRuleId) { return []; } const parts = cedar.policySetTextToParts(policiesText) as CedarPolicySetParts; @@ -126,9 +128,13 @@ export function parseRules(policiesText: string): ParsedRule[] { parts.errors ?? [], ); } + const policies = parts.policies; + if (nextLegacyRuleId && (!policies.length || parts.policy_templates?.length)) { + throw new CedarPolicyParseError('Blueprint entry must contain static Cedar policies', []); + } const out: ParsedRule[] = []; - parts.policies.forEach((policyText, index) => { + policies.forEach((policyText, index) => { const parsed = cedar.policyToJson(policyText) as CedarPolicyJson; if (parsed.type !== 'success' || !parsed.json) { throw new CedarPolicyParseError( @@ -137,6 +143,11 @@ export function parseRules(policiesText: string): ParsedRule[] { ); } const annotations = parsed.json.annotations ?? {}; + if (nextLegacyRuleId && policies.length === 1 + && annotations.tier === undefined && annotations.rule_id === undefined) { + annotations.tier = 'soft'; + annotations.rule_id = nextLegacyRuleId(); + } const tier = annotations.tier; const rule_id = annotations.rule_id; @@ -145,7 +156,7 @@ export function parseRules(policiesText: string): ParsedRule[] { // it to return ALLOW for non-matching requests rather than // default-deny. We skip it from ParsedRule[] so callers only see // user-facing rule entries. - if (rule_id === 'base_permit' && tier === undefined) { + if (!nextLegacyRuleId && rule_id === 'base_permit' && tier === undefined) { return; } @@ -161,6 +172,9 @@ export function parseRules(policiesText: string): ParsedRule[] { [], ); } + if (nextLegacyRuleId && out.length > 0 && out[0]!.tier !== tier) { + throw new CedarPolicyParseError('Put hard and soft rules in separate Blueprint entries', []); + } const rule: ParsedRule = { policy_id: `policy${index}`, diff --git a/cdk/test/handlers/get-policies.test.ts b/cdk/test/handlers/get-policies.test.ts index 1327f9513..2d9dd59f3 100644 --- a/cdk/test/handlers/get-policies.test.ts +++ b/cdk/test/handlers/get-policies.test.ts @@ -246,6 +246,33 @@ describe('get-policies', () => { expect(soft.map((r: { rule_id: string }) => r.rule_id)).not.toContain('block_prod_writes'); }); + test('uses Cedar annotations to list inline rules and number legacy entries', async () => { + mockLookupRepo.mockResolvedValue(onboardedWith([ + `// Previously @tier("hard")\n${UNANNOTATED_RULE}`, + `@tier ( "hard" ) @rule_id ( "publish_freeze" ) ${UNANNOTATED_RULE}`, + OTHER_UNANNOTATED_RULE, + ])); + + const res = await handler(makeEvent()); + + expect(res.statusCode).toBe(200); + const { hard, soft } = JSON.parse(res.body).data.policies; + expect(hard).toContainEqual(expect.objectContaining({ rule_id: 'publish_freeze' })); + expect(soft.slice(-2).map((r: { rule_id: string }) => r.rule_id)).toEqual([ + 'legacy_extra_0', 'legacy_extra_1', + ]); + }); + + test.each([ + ['both tiers', `${CUSTOM_SOFT_RULE}\n@tier("hard") @rule_id("freeze") ${UNANNOTATED_RULE}`], + ['a comment alone', '// no policies'], + ['an unbound template', 'forbid (principal == ?principal, action, resource);'], + ])('reports an invalid Blueprint entry containing %s', async (_description, entry) => { + mockLookupRepo.mockResolvedValue(onboardedWith([entry])); + const res = await handler(makeEvent()); + expect(res.statusCode).toBe(503); + }); + test('caches per-repo response across calls', async () => { mockSend.mockResolvedValue({}); diff --git a/docs/guides/CEDAR_POLICY_GUIDE.md b/docs/guides/CEDAR_POLICY_GUIDE.md index 98903f5e3..de2877543 100644 --- a/docs/guides/CEDAR_POLICY_GUIDE.md +++ b/docs/guides/CEDAR_POLICY_GUIDE.md @@ -28,7 +28,7 @@ new Blueprint(this, 'PaymentsBlueprint', { `@tier("hard") @rule_id("block_prod_writes") forbid (principal, action == Agent::Action::"write_file", resource) - when { context.file_path like "prod/**" };`, + when { context.file_path like "prod/*" || context.file_path like "*/prod/*" };`, `@tier("soft") @rule_id("deploy_staging") @severity("high") @@ -42,13 +42,13 @@ new Blueprint(this, 'PaymentsBlueprint', { }); ``` -- **`@tier("hard")`** rules always deny. **`@tier("soft")`** rules pause for approval. +- The hard rule blocks Write and Edit for files under any directory named `prod`, including nested directories. It matches both relative and absolute paths as supplied by the tool. - Keep hard and soft rules in **separate entries**. An entry that declares both tiers, or `@rule_id` without a tier, fails task start rather than being guessed. - An entry with no annotations at all is treated as a legacy soft rule with a generated rule ID (`legacy_extra_`). -- `@approval_timeout_s` is **min-wins** with the task's own approval window (default 300 s; set `--approval-timeout` up to 3600 s on submit). The rule above therefore waits 300 s unless the task asks for 900 s or more. +- The soft rule asks for approval with a 900-second limit. The task's approval window can shorten it. The default gives 300 seconds, `--approval-timeout 600` gives 600, and `--approval-timeout 3600` gives 900. The remaining task lifetime can shorten the window further. - Disabling built-in soft rules and capping `--pre-approve` scopes per repository are not supported yet. -The built-in rule set is documented in [`agent/policies/hard_deny.cedar`](../../agent/policies/hard_deny.cedar) and [`agent/policies/soft_deny.cedar`](../../agent/policies/soft_deny.cedar). Run `bgagent policies list --repo owner/repo` against a deployed stack to see the effective rules for a repo. +`bgagent policies list --repo owner/repo` lists the built-in rules and the repository's inline Blueprint rules. To see the additional rules the agent loads at task start, inspect the registry modules referenced by `assets.cedarPolicyModules`. The built-in rules are in [`hard_deny.cedar`](../../agent/policies/hard_deny.cedar) and [`soft_deny.cedar`](../../agent/policies/soft_deny.cedar). ## Vocabulary @@ -66,9 +66,9 @@ Every tool call the agent makes is evaluated as a Cedar `(principal, action, res | Annotation | Required? | Values | Purpose | |---|---|---|---| -| `@rule_id("...")` | **Yes on soft-deny** (recommended on hard-deny) | Unique kebab/snake-case identifier | Stable ID for `--pre-approve rule:X`, for audit events, and for `bgagent policies show --rule X`. Engine rejects duplicates at task start. | -| `@tier("hard"\|"soft")` | **Yes** | Exactly one of `"hard"` or `"soft"` | Must match the file section. Mismatches fail task start. | -| `@approval_timeout_s("N")` | No | Integer seconds ≥ 30 | Per-rule timeout. Defaults to 300 s (overridable per-task via `--approval-timeout`). When multiple soft rules match, the engine picks the minimum. Values < 120 s emit a load-time warning; values < 30 s are rejected. Ignored on hard-deny. | +| `@rule_id("...")` | **Yes on tiered rules** | Unique kebab/snake-case identifier | Names a rule in approval requests, audit events, and `bgagent policies show --rule X`. The engine rejects duplicate IDs at task start. | +| `@tier("hard"\|"soft")` | **Yes on named rules** | Exactly one of `"hard"` or `"soft"` | Selects the tier. All rules in one Blueprint entry must use the same tier. | +| `@approval_timeout_s("N")` | No | Integer seconds ≥ 30 | Caps the task's approval window when this soft rule matches. The task default is 300 seconds and `--approval-timeout` can set it to at most 3600 seconds. Values below 120 seconds trigger a warning and values below 30 seconds fail validation. | | `@severity("low"\|"medium"\|"high")` | No | One of three | Displayed in the approval prompt. Default: `medium`. | | `@category("...")` | No | `destructive`, `network`, `filesystem`, `auth`, or free-form | Optional UX grouping. Not enforced. | @@ -133,7 +133,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) A single tool call can match several rules. When that happens the engine merges them: -- **Timeout** — the minimum of all matching rules' `@approval_timeout_s` values (smallest window wins). +- **Timeout** — the shortest of the task's approval window and the `@approval_timeout_s` limits on the matching rules. - **Severity** — the maximum across matches (`high` > `medium` > `low`). - **`matching_rule_ids`** — the full set, so the CLI can show the user every rule that fired. @@ -146,7 +146,7 @@ The blueprint loader runs a probe Cedar evaluation before the task is admitted. - Malformed Cedar syntax. - Duplicate `@rule_id` across hard + soft tiers. - An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. -- Missing `@rule_id` on a soft-deny rule. +- Missing `@rule_id` on a rule that declares a tier. - `@approval_timeout_s` below the 30 s floor or non-integer. - Combined hard + soft Cedar text exceeding 64 KB. diff --git a/docs/src/content/docs/customizing/Cedar-policies.md b/docs/src/content/docs/customizing/Cedar-policies.md index 2dc8126ab..97c3329e6 100644 --- a/docs/src/content/docs/customizing/Cedar-policies.md +++ b/docs/src/content/docs/customizing/Cedar-policies.md @@ -30,7 +30,7 @@ new Blueprint(this, 'PaymentsBlueprint', { `@tier("hard") @rule_id("block_prod_writes") forbid (principal, action == Agent::Action::"write_file", resource) - when { context.file_path like "prod/**" };`, + when { context.file_path like "prod/*" || context.file_path like "*/prod/*" };`, `@tier("soft") @rule_id("deploy_staging") @severity("high") @@ -44,13 +44,13 @@ new Blueprint(this, 'PaymentsBlueprint', { }); ``` -- **`@tier("hard")`** rules always deny. **`@tier("soft")`** rules pause for approval. +- The hard rule blocks Write and Edit for files under any directory named `prod`, including nested directories. It matches both relative and absolute paths as supplied by the tool. - Keep hard and soft rules in **separate entries**. An entry that declares both tiers, or `@rule_id` without a tier, fails task start rather than being guessed. - An entry with no annotations at all is treated as a legacy soft rule with a generated rule ID (`legacy_extra_`). -- `@approval_timeout_s` is **min-wins** with the task's own approval window (default 300 s; set `--approval-timeout` up to 3600 s on submit). The rule above therefore waits 300 s unless the task asks for 900 s or more. +- The soft rule asks for approval with a 900-second limit. The task's approval window can shorten it. The default gives 300 seconds, `--approval-timeout 600` gives 600, and `--approval-timeout 3600` gives 900. The remaining task lifetime can shorten the window further. - Disabling built-in soft rules and capping `--pre-approve` scopes per repository are not supported yet. -The built-in rule set is documented in [`agent/policies/hard_deny.cedar`](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/agent/policies/hard_deny.cedar) and [`agent/policies/soft_deny.cedar`](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/agent/policies/soft_deny.cedar). Run `bgagent policies list --repo owner/repo` against a deployed stack to see the effective rules for a repo. +`bgagent policies list --repo owner/repo` lists the built-in rules and the repository's inline Blueprint rules. To see the additional rules the agent loads at task start, inspect the registry modules referenced by `assets.cedarPolicyModules`. The built-in rules are in [`hard_deny.cedar`](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/agent/policies/hard_deny.cedar) and [`soft_deny.cedar`](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/blob/main/agent/policies/soft_deny.cedar). ## Vocabulary @@ -68,9 +68,9 @@ Every tool call the agent makes is evaluated as a Cedar `(principal, action, res | Annotation | Required? | Values | Purpose | |---|---|---|---| -| `@rule_id("...")` | **Yes on soft-deny** (recommended on hard-deny) | Unique kebab/snake-case identifier | Stable ID for `--pre-approve rule:X`, for audit events, and for `bgagent policies show --rule X`. Engine rejects duplicates at task start. | -| `@tier("hard"\|"soft")` | **Yes** | Exactly one of `"hard"` or `"soft"` | Must match the file section. Mismatches fail task start. | -| `@approval_timeout_s("N")` | No | Integer seconds ≥ 30 | Per-rule timeout. Defaults to 300 s (overridable per-task via `--approval-timeout`). When multiple soft rules match, the engine picks the minimum. Values < 120 s emit a load-time warning; values < 30 s are rejected. Ignored on hard-deny. | +| `@rule_id("...")` | **Yes on tiered rules** | Unique kebab/snake-case identifier | Names a rule in approval requests, audit events, and `bgagent policies show --rule X`. The engine rejects duplicate IDs at task start. | +| `@tier("hard"\|"soft")` | **Yes on named rules** | Exactly one of `"hard"` or `"soft"` | Selects the tier. All rules in one Blueprint entry must use the same tier. | +| `@approval_timeout_s("N")` | No | Integer seconds ≥ 30 | Caps the task's approval window when this soft rule matches. The task default is 300 seconds and `--approval-timeout` can set it to at most 3600 seconds. Values below 120 seconds trigger a warning and values below 30 seconds fail validation. | | `@severity("low"\|"medium"\|"high")` | No | One of three | Displayed in the approval prompt. Default: `medium`. | | `@category("...")` | No | `destructive`, `network`, `filesystem`, `auth`, or free-form | Optional UX grouping. Not enforced. | @@ -135,7 +135,7 @@ forbid (principal, action == Agent::Action::"execute_bash", resource) A single tool call can match several rules. When that happens the engine merges them: -- **Timeout** — the minimum of all matching rules' `@approval_timeout_s` values (smallest window wins). +- **Timeout** — the shortest of the task's approval window and the `@approval_timeout_s` limits on the matching rules. - **Severity** — the maximum across matches (`high` > `medium` > `low`). - **`matching_rule_ids`** — the full set, so the CLI can show the user every rule that fired. @@ -148,7 +148,7 @@ The blueprint loader runs a probe Cedar evaluation before the task is admitted. - Malformed Cedar syntax. - Duplicate `@rule_id` across hard + soft tiers. - An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. -- Missing `@rule_id` on a soft-deny rule. +- Missing `@rule_id` on a rule that declares a tier. - `@approval_timeout_s` below the 30 s floor or non-integer. - Combined hard + soft Cedar text exceeding 64 KB.