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 6b81d7276..061dc287e 100644 --- a/agent/src/runner.py +++ b/agent/src/runner.py @@ -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 diff --git a/agent/tests/test_blueprint_cedar_routing.py b/agent/tests/test_blueprint_cedar_routing.py new file mode 100644 index 000000000..f63990007 --- /dev/null +++ b/agent/tests/test_blueprint_cedar_routing.py @@ -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"]) diff --git a/agent/tests/test_runner.py b/agent/tests/test_runner.py index ed932fdbf..ef61d3cc7 100644 --- a/agent/tests/test_runner.py +++ b/agent/tests/test_runner.py @@ -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( 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 15fd92322..de2877543 100644 --- a/docs/guides/CEDAR_POLICY_GUIDE.md +++ b/docs/guides/CEDAR_POLICY_GUIDE.md @@ -17,33 +17,38 @@ 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/*" || 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) + }, +}); ``` -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. +- 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_`). +- 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. + +`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 @@ -61,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. | @@ -128,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. @@ -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. -- Missing `@rule_id` on a soft-deny rule. +- An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. +- Missing `@rule_id` on a rule that declares a tier. - `@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 d4afa894a..97c3329e6 100644 --- a/docs/src/content/docs/customizing/Cedar-policies.md +++ b/docs/src/content/docs/customizing/Cedar-policies.md @@ -19,33 +19,38 @@ 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/*" || 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) + }, +}); ``` -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. +- 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_`). +- 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. + +`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 @@ -63,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. | @@ -130,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. @@ -142,18 +147,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. -- Missing `@rule_id` on a soft-deny rule. +- An entry that declares both `@tier("hard")` and `@tier("soft")`, or `@rule_id` without a `@tier`. +- Missing `@rule_id` on a rule that declares a tier. - `@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