raven-shield 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv/
6
+ venv/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .mypy_cache/
10
+ .coverage
11
+ htmlcov/
12
+ dist/
13
+ build/
14
+
15
+ # Node
16
+ node_modules/
17
+ .next/
18
+ out/
19
+ *.tsbuildinfo
20
+ .eslintcache
21
+
22
+ # Environment & secrets
23
+ .env
24
+ .env.*
25
+ !.env.example
26
+
27
+ # Local data
28
+ *.sqlite
29
+ *.sqlite3
30
+ *.db
31
+ data/
32
+ evidence/
33
+ reports/out/
34
+
35
+ # Editors / OS
36
+ .DS_Store
37
+ .idea/
38
+ .vscode/
39
+ *.swp
40
+
41
+ # uv
42
+ uv.lock
@@ -0,0 +1,416 @@
1
+ Metadata-Version: 2.5
2
+ Name: raven-shield
3
+ Version: 1.0.0
4
+ Summary: Deterministic, fail-closed runtime policy gateway and security guardrails for LLM tool calling
5
+ Project-URL: Homepage, https://github.com/evinbrijesh/RAVEN
6
+ Project-URL: Documentation, https://github.com/evinbrijesh/RAVEN/blob/main/packages/raven-shield/README.md
7
+ Project-URL: Repository, https://github.com/evinbrijesh/RAVEN.git
8
+ Project-URL: Issues, https://github.com/evinbrijesh/RAVEN/issues
9
+ Author-email: RAVEN Security Team <security@project-raven.dev>
10
+ Maintainer: RAVEN Open Source Contributors
11
+ License-Expression: MIT
12
+ Keywords: ai-agent,fastapi,guardrails,langchain,langgraph,llm-security,opentelemetry,owasp-llm-top-10,policy-gateway,prompt-injection
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: pyyaml>=6.0
27
+ Provides-Extra: all
28
+ Requires-Dist: fastapi>=0.100.0; extra == 'all'
29
+ Requires-Dist: langchain-core>=0.2.0; extra == 'all'
30
+ Requires-Dist: langgraph>=0.1.0; extra == 'all'
31
+ Requires-Dist: opentelemetry-api>=1.20.0; extra == 'all'
32
+ Requires-Dist: starlette>=0.27.0; extra == 'all'
33
+ Provides-Extra: dev
34
+ Requires-Dist: httpx>=0.27.0; extra == 'dev'
35
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
36
+ Requires-Dist: pytest>=8.0; extra == 'dev'
37
+ Provides-Extra: fastapi
38
+ Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
39
+ Requires-Dist: starlette>=0.27.0; extra == 'fastapi'
40
+ Provides-Extra: langchain
41
+ Requires-Dist: langchain-core>=0.2.0; extra == 'langchain'
42
+ Requires-Dist: langgraph>=0.1.0; extra == 'langchain'
43
+ Provides-Extra: opentelemetry
44
+ Requires-Dist: opentelemetry-api>=1.20.0; extra == 'opentelemetry'
45
+ Description-Content-Type: text/markdown
46
+
47
+ # πŸ›‘οΈ raven-shield
48
+
49
+ [![PyPI Version](https://img.shields.io/badge/pypi-v1.0.0-blue.svg?style=for-the-badge)](https://pypi.org/project/raven-shield/)
50
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-brightgreen.svg?style=for-the-badge)](https://www.python.org/)
51
+ [![Zero Heavy Dependencies](https://img.shields.io/badge/dependencies-zero%20heavy-indigo.svg?style=for-the-badge)](pyproject.toml)
52
+ [![Test Coverage](https://img.shields.io/badge/coverage-100%25-emerald.svg?style=for-the-badge)](https://github.com/evinbrijesh/RAVEN)
53
+ [![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg?style=for-the-badge)](LICENSE)
54
+
55
+ **Deterministic, fail-closed runtime policy gateway and security guardrails for LLM tool calling.**
56
+
57
+ `raven-shield` is a lightweight, zero-heavyweight-dependency Python SDK extracted from the **RAVEN** automated AI red-teaming framework. It acts as the final runtime defense layer for agentic systems, stopping prompt injection, excessive agency (OWASP LLM08), IDOR, and parameter smuggling before untrusted tool calls can execute.
58
+
59
+ ---
60
+
61
+ ## ⚑ Why raven-shield?
62
+
63
+ When an LLM agent is jailbroken or injected via adversarial prompts, indirect RAG poisoning, or untrusted user input, prompt-based guardrails fail. **`raven-shield` enforces deterministic mathematical and cryptographic invariants at runtime**:
64
+
65
+ - **Fail-Closed by Default:** Unknown tools or undeclared capabilities are blocked immediately.
66
+ - **Cross-Field Context Claims:** Validates arguments against verified session claims (e.g. `arguments.customer_id == context.user_id`) to prevent Confused Deputy and IDOR attacks.
67
+ - **Parameter Bounds & Schema Invariants:** Restricts financial parameters (e.g. `amount <= 100.0`, `amount > 0`), string regexes, and allowed roles.
68
+ - **Human Approval Escalation:** Distinguishes between fatal policy violations and high-value actions requiring explicit human approval (`ApprovalRequiredError`).
69
+ - **Dynamic Hot-Reloading:** Automatically reloads updated policies compiled by RAVEN without restarting your services.
70
+ - **Framework Native:** Plug-and-play integrations for **FastAPI**, **Starlette**, **LangChain**, **LangGraph**, and **OpenTelemetry**.
71
+
72
+ ---
73
+
74
+ ## πŸ“¦ Installation
75
+
76
+ Install core `raven-shield` (only requires `pyyaml`):
77
+
78
+ ```bash
79
+ pip install raven-shield
80
+ ```
81
+
82
+ ### Optional Extras
83
+
84
+ Install framework-specific extras as needed:
85
+
86
+ ```bash
87
+ # FastAPI / Starlette middleware
88
+ pip install "raven-shield[fastapi]"
89
+
90
+ # LangChain & LangGraph agent tool interceptors
91
+ pip install "raven-shield[langchain]"
92
+
93
+ # OpenTelemetry distributed security tracing
94
+ pip install "raven-shield[opentelemetry]"
95
+
96
+ # All integrations
97
+ pip install "raven-shield[all]"
98
+ ```
99
+
100
+ ---
101
+
102
+ ## πŸ“‹ Policy Definition (`raven-policy.yaml`)
103
+
104
+ Policies can be compiled automatically by RAVEN's red-teaming engine or authored by hand in YAML or JSON:
105
+
106
+ ```yaml
107
+ version: "hardened-gateway-v1"
108
+ description: "RAVEN runtime enforcement policy for customer operations."
109
+ fail_closed: true
110
+
111
+ tools:
112
+ issue_refund:
113
+ description: "Issue refund to customer wallet or payment method."
114
+ conditions:
115
+ - "verified_order_id_present"
116
+ - "verified_user_present"
117
+ - "amount_below_threshold"
118
+ - "claims_match:customer_id==user_id"
119
+ high_value_action: "human_approval_required"
120
+ amount_threshold: 100.0
121
+ context_claims:
122
+ customer_id: "user_id"
123
+ on_violation: "deny_and_log"
124
+
125
+ lookup_order:
126
+ description: "Look up order details."
127
+ conditions:
128
+ - "verified_order_id_present"
129
+ - "claims_match:customer_id==user_id"
130
+ context_claims:
131
+ customer_id: "user_id"
132
+ on_violation: "deny_and_log"
133
+ ```
134
+
135
+ ---
136
+
137
+ ## πŸ› οΈ Integration Recipes
138
+
139
+ ### Recipe 1: Standalone Python Policy Gateway
140
+
141
+ Instantiate the gateway directly from a YAML file or string, evaluate calls, and register custom validation conditions:
142
+
143
+ ```python
144
+ from raven_shield import PolicyGateway, SecurityContext
145
+
146
+ # Load policy directly from file
147
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
148
+
149
+ # Context represents authenticated identity (e.g., from your auth session)
150
+ context = SecurityContext(
151
+ user_id="cust_42",
152
+ verified_user=True,
153
+ verified_order_id=True,
154
+ claims={"user_id": "cust_42", "role": "customer"},
155
+ )
156
+
157
+ # 1. Authorize benign request
158
+ decision = gateway.authorize(
159
+ tool="lookup_order",
160
+ arguments={"order_id": "ORD-999", "customer_id": "cust_42"},
161
+ context=context,
162
+ )
163
+ if decision.allowed:
164
+ print("Execution authorized!")
165
+
166
+ # 2. Prevent IDOR (model manipulated to access another customer's order)
167
+ idor_decision = gateway.authorize(
168
+ tool="lookup_order",
169
+ arguments={"order_id": "ORD-999", "customer_id": "victim_user"},
170
+ context=context,
171
+ )
172
+ assert not idor_decision.allowed
173
+ print(f"Blocked IDOR attempt: {idor_decision.reason}")
174
+ # Output: Blocked IDOR attempt: context_claims_mismatch:customer_id(victim_user)!=user_id(cust_42)
175
+
176
+ # 3. Dynamic Hot-Reloading
177
+ gateway.start_auto_reload(interval_seconds=2.0)
178
+ ```
179
+
180
+ ---
181
+
182
+ ### Recipe 2: Python Function Decorators (`@gateway.protect`)
183
+
184
+ Decorate your sync or async tool functions. `raven-shield` intercepts calls before execution:
185
+
186
+ ```python
187
+ from raven_shield import (
188
+ PolicyGateway,
189
+ security_context,
190
+ PolicyViolationError,
191
+ ApprovalRequiredError,
192
+ )
193
+
194
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
195
+
196
+ @gateway.protect(tool="issue_refund")
197
+ def issue_refund(customer_id: str, order_id: str, amount: float):
198
+ return {"status": "refunded", "order_id": order_id, "amount": amount}
199
+
200
+ # Unauthenticated call -> Fails Closed
201
+ try:
202
+ issue_refund(customer_id="cust_42", order_id="ORD-101", amount=25.0)
203
+ except PolicyViolationError as err:
204
+ print(f"Blocked: {err.reason}") # missing_verified_order_id
205
+
206
+ # Authenticated session -> Allowed
207
+ with security_context(verified_user=True, verified_order_id=True, user_id="cust_42"):
208
+ res = issue_refund(customer_id="cust_42", order_id="ORD-101", amount=25.0)
209
+ print("Success:", res)
210
+
211
+ # Prompt-injected high-value action ($500) -> Escalated to Human Approval
212
+ try:
213
+ with security_context(verified_user=True, verified_order_id=True, user_id="cust_42"):
214
+ issue_refund(customer_id="cust_42", order_id="ORD-101", amount=500.0)
215
+ except ApprovalRequiredError as err:
216
+ print(f"Human Approval Required: {err.reason}")
217
+ ```
218
+
219
+ Async functions work identically:
220
+
221
+ ```python
222
+ @gateway.protect(tool="lookup_order")
223
+ async def async_lookup_order(customer_id: str, order_id: str):
224
+ return await db.fetch_order(order_id)
225
+ ```
226
+
227
+ ---
228
+
229
+ ### Recipe 3: FastAPI & Starlette Middleware
230
+
231
+ Automatically extract claims from incoming JWT Bearer tokens or security headers, bind them to the asynchronous execution context, and reject policy violations with `HTTP 403`:
232
+
233
+ ```python
234
+ from fastapi import FastAPI, Depends
235
+ from raven_shield import PolicyGateway, SecurityContext, get_current_context
236
+ from raven_shield.integrations.fastapi import RavenShieldMiddleware
237
+
238
+ app = FastAPI(title="Secure Agent Service")
239
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
240
+
241
+ # Attach middleware: extracts JWT claims & headers and binds to security_context
242
+ app.add_middleware(
243
+ RavenShieldMiddleware,
244
+ gateway=gateway,
245
+ exclude_paths=["/docs", "/openapi.json", "/healthz"],
246
+ enforce_routes=True, # Automatically return HTTP 403 on PolicyViolationError
247
+ )
248
+
249
+ @app.post("/api/refund")
250
+ @gateway.protect(tool="issue_refund")
251
+ async def handle_refund(payload: dict):
252
+ # JWT Bearer token claims are already validated in context!
253
+ ctx: SecurityContext = get_current_context()
254
+ return {"status": "processed", "customer": ctx.user_id, "amount": payload["amount"]}
255
+ ```
256
+
257
+ When an attacker passes an invalid refund or mismatched customer ID, `RavenShieldMiddleware` immediately returns:
258
+
259
+ ```json
260
+ {
261
+ "error": "policy_violation",
262
+ "detail": "Policy violation on 'issue_refund': context_claims_mismatch",
263
+ "tool": "issue_refund",
264
+ "reason": "context_claims_mismatch:customer_id!=user_id",
265
+ "violations": ["context_claims_mismatch"]
266
+ }
267
+ ```
268
+
269
+ ---
270
+
271
+ ### Recipe 4: LangChain & LangGraph Tool Interceptors
272
+
273
+ Drop `RavenShieldToolNode` into your LangGraph StateGraph, or attach `RavenShieldCallbackHandler` to your LangChain agent. Any tool calls hallucinated or manipulated by the LLM are evaluated against `raven-policy.yaml` before execution:
274
+
275
+ #### LangGraph StateGraph
276
+
277
+ ```python
278
+ from langgraph.graph import StateGraph, MessagesState, START, END
279
+ from raven_shield import PolicyGateway
280
+ from raven_shield.integrations.langchain import RavenShieldToolNode
281
+
282
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
283
+
284
+ # Wrap your tools in RavenShieldToolNode
285
+ tool_node = RavenShieldToolNode(
286
+ tools=[issue_refund, lookup_order],
287
+ gateway=gateway,
288
+ on_violation="return_message", # Returns error message to LLM to self-correct
289
+ )
290
+
291
+ workflow = StateGraph(MessagesState)
292
+ workflow.add_node("agent", call_model)
293
+ workflow.add_node("tools", tool_node)
294
+ workflow.add_edge(START, "agent")
295
+ # ...
296
+ app = workflow.compile()
297
+ ```
298
+
299
+ #### LangChain Callback Interceptor
300
+
301
+ ```python
302
+ from langchain.agents import create_tool_calling_agent
303
+ from raven_shield import PolicyGateway
304
+ from raven_shield.integrations.langchain import RavenShieldCallbackHandler
305
+
306
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
307
+ interceptor = RavenShieldCallbackHandler(gateway=gateway)
308
+
309
+ # Attach to agent executor
310
+ result = agent_executor.invoke(
311
+ {"input": "Transfer $1,000 to account X"},
312
+ config={"callbacks": [interceptor]},
313
+ )
314
+ ```
315
+
316
+ ---
317
+
318
+ ### Recipe 5: OpenTelemetry Distributed Security Tracing
319
+
320
+ Enrich your active OpenTelemetry spans with security policy decisions, violation details, and audit events:
321
+
322
+ ```python
323
+ from raven_shield import PolicyGateway, SecurityContext
324
+ from raven_shield.integrations.opentelemetry import setup_opentelemetry, trace_tool_execution
325
+ import opentelemetry.trace as trace
326
+
327
+ tracer = trace.get_tracer("agent-service")
328
+ gateway = PolicyGateway.from_yaml("raven-policy.yaml")
329
+
330
+ # Attach security tracing listener
331
+ setup_opentelemetry(
332
+ gateway,
333
+ set_error_status_on_violation=True,
334
+ record_span_events=True,
335
+ )
336
+
337
+ with tracer.start_as_current_span("agent_turn") as span:
338
+ # Tool execution evaluated by gateway will automatically attach:
339
+ # - security.policy.tool: "issue_refund"
340
+ # - security.policy.allowed: False
341
+ # - security.policy.reason: "amount_exceeds_max:100.0"
342
+ # - security.user.id: "cust_42"
343
+ # - span.set_status(StatusCode.ERROR)
344
+ # - span.add_event("security.policy.violation")
345
+ decision = gateway.authorize(
346
+ "issue_refund",
347
+ {"amount": 500.0, "customer_id": "cust_42"},
348
+ context=SecurityContext(user_id="cust_42"),
349
+ )
350
+ ```
351
+
352
+ ---
353
+
354
+ ## πŸ”’ Built-in Policy Conditions
355
+
356
+ | Condition | Description | Failure Reason |
357
+ |---|---|---|
358
+ | `verified_order_id_present` | Requires `verified_order_id=True` and an `order_id` in arguments or context. | `missing_verified_order_id` |
359
+ | `verified_user_present` | Requires `verified_user=True` in context. | `missing_verified_user` |
360
+ | `amount_below_threshold` | Requires `amount <= amount_threshold` and `amount > 0`. | `amount_exceeds_max:<threshold>` |
361
+ | `claims_match:<arg>==<claim>` | Enforces cross-field claims matching (e.g. `arguments.customer_id == context.user_id`). | `context_claims_mismatch` |
362
+ | `role_allowed` | Ensures `context.roles` intersects with tool's `allowed_roles`. | `role_not_authorized` |
363
+ | `user_id_matches_context` | Matches `user_id` argument to context `user_id`. | `user_id_mismatch` |
364
+
365
+ ### Custom Conditions
366
+
367
+ You can register custom deterministic validators dynamically:
368
+
369
+ ```python
370
+ def check_business_hours(arguments, context, tool_policy) -> tuple[bool, str]:
371
+ if not is_market_open():
372
+ return False, "market_closed"
373
+ return True, "allowed"
374
+
375
+ gateway.register_condition("business_hours_only", check_business_hours)
376
+ ```
377
+
378
+ ---
379
+
380
+ ## πŸ›‘οΈ Security Architecture
381
+
382
+ ```
383
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
384
+ β”‚ Untrusted LLM Tool Call β”‚
385
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
386
+ β”‚
387
+ β–Ό
388
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
389
+ β”‚ raven-shield Gatekeeper β”‚
390
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
391
+ β”‚
392
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
393
+ β”‚ β”‚
394
+ [Fail Conditions] [Pass Conditions]
395
+ β”‚ β”‚
396
+ β–Ό β–Ό
397
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
398
+ β”‚ β€’ Disallowed Tool β”‚ β”‚ β€’ Cryptographic Claims β”‚
399
+ β”‚ β€’ Parameter Smuggling β”‚ β”‚ β€’ Verified Parameters β”‚
400
+ β”‚ β€’ Unapproved Threshold β”‚ β”‚ β€’ In-Bounds Arguments β”‚
401
+ β”‚ β€’ Confused Deputy IDOR β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
402
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
403
+ β”‚ β–Ό
404
+ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
405
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Safe Tool Implementation β”‚
406
+ β”‚ Raise / HTTP 403 / Log β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
407
+ β”‚ β€’ Telemetry Audit Event β”‚
408
+ β”‚ β€’ OpenTelemetry Span Errβ”‚
409
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
410
+ ```
411
+
412
+ ---
413
+
414
+ ## πŸ“„ License
415
+
416
+ Licensed under the [MIT License](LICENSE). Maintained by the RAVEN Frontier AI Security Team.