sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

feat(interventions): add Cedar authorization handler for Python

Open lizradway opened this issue 5 months ago • 1 comments

Description

Port of the TypeScript CedarAuthorization vended intervention handler (strands-agents/harness-sdk#2365) to Python.

This adds a Cedar-based authorization intervention handler that evaluates Cedar policies before every tool call, enforcing fine-grained, identity-aware access control over agent tool invocations.

Key features:

  • Evaluates Cedar policies via cedarpy (Rust-backed Python bindings)
  • Auto-generates Cedar schemas from MCP tool definitions via cedar-mcp-schema-generator (PyPI)
  • Static or dynamic principal resolution from invocation_state
  • Rate limiting via per-tool call counts persisted to agent.state
  • Context enrichment (forward environment, roles, etc. into Cedar context)
  • File-based or inline policy/entity/schema loading
  • Hot reload (reload()) with atomic swap and validation-before-commit
  • Configurable error handling (throw/deny/proceed) for user callback errors
  • Thread-safe call count tracking and reload
  • Fail-closed by design (missing principal or evaluation errors → deny)
  • Distinct error messages for Cedar engine failures vs policy denials

API

from strands.vended_interventions.cedar import CedarAuthorization, ToolDefinition

Constructor:

CedarAuthorization(
    *,
    policies: str,                          # Required. Inline Cedar text or path to .cedar file
    tools: list[ToolDefinition] | None,     # MCP tool defs for auto schema generation
    entities: list[dict] | str | None,      # Inline list, JSON string, or path to .json file
    schema: str | None,                     # Inline Cedar schema or path to .cedarschema file
    principal: dict | None,                 # Static principal: {"type": "User", "id": "alice"}
    principal_resolver: Callable | None,    # Dynamic: (invocation_state) -> {"type", "id"} | None
    context_enricher: Callable | None,      # ({"tool_name", "tool_input", "invocation_state"}) -> dict
    on_error: "throw" | "deny" | "proceed", # Error mode for user callback exceptions (default: "throw")
)

Methods:

  • reload() — Re-read policies/entities/schema from disk, validate, then commit atomically
  • reset_call_counts(agent=None) — Clear rate-limit counters (and agent.state if agent provided)

Cedar context structure passed to every evaluation:

{
  "input": { ...tool_arguments },
  "session": {
    "hour_utc": 14,
    "call_count": 3,
    ...context_enricher_fields
  }
}

Cedar request mapping:

  • Principal: static {"type", "id"} or resolved from invocation_state
  • Action: Action::"<tool_name>" (auto-derived)
  • Resource: Resource::"agent" (fixed)

Usage Examples

Minimal — single policy:

from strands import Agent
from strands.vended_interventions.cedar import CedarAuthorization

cedar = CedarAuthorization(
    policies='permit(principal, action == Action::"search", resource);'
)
agent = Agent(interventions=[cedar], tools=[search_tool])

Multi-tenant with dynamic principal:

cedar = CedarAuthorization(
    policies='path/to/policies.cedar',
    entities='path/to/entities.json',
    principal_resolver=lambda state: {"type": "User", "id": state["user_id"]},
    context_enricher=lambda ctx: {
        "environment": ctx["invocation_state"].get("env"),
        "role": ctx["invocation_state"].get("role"),
    },
)
agent = Agent(interventions=[cedar], tools=[...])
agent("do something", invocation_state={"user_id": "alice", "role": "admin", "env": "staging"})

Rate limiting:

permit(principal, action == Action::"send_email", resource)
when { context.session.call_count < 3 };

Argument-level gating:

permit(principal, action == Action::"query_database", resource)
when { context.input.database == "analytics" };

Dependencies: Added cedar optional dependency group (pip install strands-agents[cedar]). Both cedarpy and cedar-mcp-schema-generator are imported lazily — the main package doesn't hard-fail without them.

  • Blocked on Cedar MCP Schema Generator export to PyPI:
    • https://github.com/cedar-policy/cedar-for-agents/pull/139: creates python bindings for mcp schema generator

Related Issues

https://github.com/strands-agents/harness-sdk/pull/2365 https://github.com/cedar-policy/cedar-for-agents/pull/139

Documentation PR

No documentation changes included. An example/guide can be added once cedar-mcp-schema-generator is published to PyPI.

Type of Change

New feature

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.

  • 63 unit/integration tests passing, 5 skipped (schema generator package not yet on PyPI)
  • Integration tests use full Agent loop via MockedModelProvider (model → tool use → intervention → tool execution)
  • Tests cover: basic permit/deny, role-based access, rate limiting, principal resolution, context enrichment, file loading (policies/entities/schema), schema validation, hot reload, thread safety, agent state persistence, evaluation failure types
  • Existing intervention system tests (74) still pass
  • [x] I ran hatch run prepare

Checklist

  • [x] I have read the CONTRIBUTING document
  • [x] I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • [x] My change is focused and reasonably small; I have split unrelated work into separate PRs
  • [x] I have added any necessary tests that prove my fix is effective or my feature works
  • [x] I have updated the documentation accordingly
  • [x] I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • [x] My changes generate no new warnings
  • [x] Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

lizradway avatar Jun 15 '26 18:06 lizradway

Assessment: Comment (draft PR — not blocking, but a few items to resolve before it's merge-ready)

This is a clean, well-tested port of the TS CedarAuthorization handler. The fail-closed design, distinct error messaging, thread-safe call counting, and the end-to-end integration tests through the real agent loop are all solid. The PR description is exemplary for API bar-raising — use cases, full signatures, and module exports are all documented.

Review themes
  • Dependencies: The [cedar] extra uses exact == pins (repo convention is bounded ranges) and references a package not yet on PyPI, so the extra is currently uninstallable. This is the main thing blocking the draft.
  • Fail-closed consistency: The principal is sanitized against quote-injection but the action (tool_name) and the auto-generated-schema validation path have small gaps worth closing.
  • State ownership: The call-count restore-from-agent.state logic is one-shot and memory-authoritative, which is a footgun if a handler instance is shared across agents — needs either guarding or an explicit single-agent contract in the docs.
  • Test coverage: Strong overall, but the NoDecision/engine-failure fail-closed branches (the security-critical paths) aren't directly exercised. Plus minor dead code.
API review process

This introduces a new public class and module (strands.vended_interventions.cedar). Per the team's API bar-raising process, that's a new customer-facing abstraction and should carry the api/needs-review label before merge — I don't see it on the PR. The description already contains everything an API reviewer needs.

Nice work — the structure and test depth here make this easy to review.

github-actions[bot] avatar Jun 15 '26 19:06 github-actions[bot]

Assessment: Comment (draft — one release blocker remains)

Thanks for the quick turnaround — the last round of commits resolved nearly all of my earlier feedback: tool_name is now quote-sanitized, the single-agent state ownership is documented, the schema-validation suppression has a clear rationale, cedarpy is imported once at module level, the dead _shared_state is gone, and the NoDecision/exception fail-closed branches now have direct test coverage (including call-count rollback). The new real-model integration tests in tests_integ/ are a nice addition.

Remaining items
  • Dependency (blocker for merge/release): the cedar-mcp-schema-generator git @main reference can't be published to PyPI and isn't reproducible. Fine to keep in draft for now; needs a published, version-ranged dep before this can ship. (inline)
  • Minor: cedarpy==4.8.0 exact pin vs. the bounded-range convention used by the other extras. (inline)
  • Minor/forward-looking: lock removal is safe under the current single-event-loop model; left a note in case a future change introduces an await mid-mutation. (inline)

Once the schema-generator dependency is published and pinned to a range, I'd consider this ready to come out of draft. Solid work.

github-actions[bot] avatar Jun 15 '26 21:06 github-actions[bot]

Assessment: Comment (draft — dependency still not installable)

Latest commit (4b4f7e1) switched cedar-mcp-schema-generator from the git @main URL to a PyPI pin ==0.6.0 and removed the allow-direct-references metadata — good cleanup. However, the package isn't published to PyPI yet (pip download returns "No matching distribution found"), so the [cedar] extra remains uninstallable. I've left details on the existing dependency thread.

Status of earlier feedback
  • ✅ tool_name quote sanitization, single-agent state docs, schema-validation rationale, top-level cedarpy import, removed _shared_state, NoDecision/exception fail-closed tests, integ tests — all resolved in prior rounds.
  • 🔄 Dependency: moved off the git URL (good) but the PyPI package doesn't exist yet — extra can't be installed. Needs the package published (and ideally a bounded range) before merge.
  • 🔵 Minor: cedarpy==4.8.0 / cedar-mcp-schema-generator==0.6.0 exact pins vs. the bounded-range convention.

Everything code-side is in good shape; the only thing standing between this and merge-ready is the upstream package actually being available on PyPI.

github-actions[bot] avatar Jun 15 '26 22:06 github-actions[bot]

Assessment: Comment

Most of my earlier-round feedback is already resolved (quote sanitization, state-ownership docs, fail-closed test coverage, top-level import, dead code, lock rationale). This round I found two new code-side items on top of the still-open dependency blocker.

Review themes
  • Rate-limit reset bug: reset_call_counts() with no agent argument is silently undone by the restore-from-agent.state path on the next call. The existing test passes only because it uses a fresh mock state per event, masking the real-world single-agent path. (inline)
  • API extensibility: PrincipalResolver/ContextEnricher use fixed Callable aliases, which the repo style guide specifically advises against for public, customer-implemented callbacks — prefer Protocol + **kwargs. (inline)
  • Dependency (still blocking): cedar-mcp-schema-generator==0.6.0 isn't on PyPI yet, so the [cedar] extra remains uninstallable. Already tracked on the existing thread; noting here for completeness.

The core design, fail-closed posture, and end-to-end test depth remain strong — these are targeted refinements, not structural concerns.

github-actions[bot] avatar Jun 16 '26 14:06 github-actions[bot]

Assessment: Comment

Most of my earlier feedback (quote sanitization, NoDecision/exception fail-closed test coverage, single-agent state docs, top-level cedarpy import, dead-code removal) was already resolved in prior rounds — nice turnaround. This pass surfaced two new items plus the still-open dependency thread.

Review themes
  • Call-count reset (Important): reset_call_counts() without an agent arg is silently undone by the restore-from-agent.state path on the next tool call. The happy-path call is the broken one, and the existing test masks it by using fresh mock state per event. Inline.
  • Extensibility (Important): PrincipalResolver/ContextEnricher are public Callable aliases — the STYLE_GUIDE calls for Protocol + **kwargs so these customer-facing callbacks can gain parameters without breaking existing implementations. Inline.
  • Dependency (blocker, already tracked): [cedar] extra still references a package not yet on PyPI and uses exact == pins vs. the bounded-range convention. Covered on the open threads with pgrayy.
  • API process: This adds a new public module (strands.vended_interventions.cedar). Per the team's API bar-raising process it should carry the api/needs-review label before merge — still not present.

The fail-closed design and end-to-end integration coverage through the real agent loop remain the strongest parts of this PR.

github-actions[bot] avatar Jun 16 '26 14:06 github-actions[bot]

Assessment: Comment

Notable state change this round: the cedar-policy-mcp-schema-generator==0.6.0 dependency is now published on PyPI, which clears the blocker that was gating this PR out of draft. The latest commit also folds cedar into the all extra (per pgrayy's suggestion) and removes the now-unneeded importorskip guards from the test modules.

Status
  • ✅ Dependency blocker resolved — both cedarpy==4.8.0 and cedar-policy-mcp-schema-generator==0.6.0 are installable from PyPI; the [cedar]/[all] extras and the 5 previously-skipped schema-generator tests should now work.
  • 🟡 Pin ranges (Important) — now that cedar is in all, the exact == pins ride in the full install + default test matrix; recommend bounded ranges to match the repo convention. Details on the dependency thread with pgrayy.
  • 🔄 Still open (unchanged code) — the no-arg reset_call_counts() restore-from-state bug and the Callable→Protocol extensibility item remain on their existing inline threads; cedar_authorization.py wasn't touched this round.

With the upstream package now published, the main thing left before this comes out of draft is switching the two exact pins to bounded ranges and addressing the two open code threads.

github-actions[bot] avatar Jun 16 '26 15:06 github-actions[bot]