guardrail-middleware 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niraj Sanjay Karnawat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: guardrail-middleware
3
+ Version: 0.1.0
4
+ Summary: Runtime authorization middleware for AI agent tool calls — policy checks, injection/taint detectors, and a hash-chained audit log, before any action executes.
5
+ Author: Niraj Sanjay Karnawat
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Niraj21-star/guardrail-middleware
8
+ Project-URL: Source, https://github.com/Niraj21-star/guardrail-middleware
9
+ Keywords: ai-agents,guardrails,llm-security,middleware,fastapi,authorization
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: fastapi
20
+ Requires-Dist: starlette>=0.27; extra == "fastapi"
21
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
22
+ Provides-Extra: yaml
23
+ Requires-Dist: pyyaml>=6; extra == "yaml"
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7; extra == "dev"
26
+ Requires-Dist: fastapi>=0.100; extra == "dev"
27
+ Requires-Dist: httpx>=0.24; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # guardrail-middleware
31
+
32
+ **Runtime authorization for AI agent tool calls.** GuardRail sits between an AI agent and its tools: every proposed action is checked against a policy *before* it executes — and every decision is written to a tamper-evident audit log.
33
+
34
+ An agent that can call tools can also be talked into misusing them — by a prompt injection in an email, a poisoned webpage, or its own overconfidence. GuardRail is the checkpoint that asks, deterministically and in under a millisecond: *is this role allowed to do this, to this resource, with these parameters, on the say-so of this source?*
35
+
36
+ ```
37
+ pip install guardrail-middleware # core, zero dependencies
38
+ pip install guardrail-middleware[fastapi] # + FastAPI/Starlette middleware
39
+ ```
40
+
41
+ ## Quick start — framework-agnostic
42
+
43
+ ```python
44
+ from guardrail_middleware import Guardrail
45
+
46
+ guard = Guardrail() # built-in default policy
47
+
48
+ decision = guard.evaluate({
49
+ "tool": "payments",
50
+ "operation": "payment",
51
+ "target_resource": "vendor/acme",
52
+ "parameters": {"amount": 42000},
53
+ "agent_role": "support",
54
+ })
55
+
56
+ decision.verdict # Verdict.BLOCK — role 'support' may not run payments
57
+ decision.allowed # False
58
+ decision.explanation
59
+ ```
60
+
61
+ Works anywhere an agent proposes an action: LangChain/LangGraph tool wrappers, MCP servers, custom agent loops, job queues.
62
+
63
+ ## Quick start — FastAPI / Starlette middleware
64
+
65
+ ```python
66
+ from fastapi import FastAPI
67
+ from guardrail_middleware import Guardrail, AuditLog
68
+ from guardrail_middleware.fastapi import GuardrailMiddleware
69
+
70
+ app = FastAPI()
71
+ app.add_middleware(
72
+ GuardrailMiddleware,
73
+ guard=Guardrail(audit_log=AuditLog("audit.jsonl")),
74
+ paths=["/tools/execute"],
75
+ )
76
+ ```
77
+
78
+ Requests to guarded paths are read as actions. **Blocked or escalated actions never reach your handler** — the client gets HTTP 403 with the full decision as JSON. Allowed actions pass through with `X-Guardrail-Verdict` and `X-Guardrail-Risk` headers set.
79
+
80
+ ## Quick start — decorator
81
+
82
+ ```python
83
+ from guardrail_middleware.fastapi import guard_tool, GuardrailBlocked
84
+
85
+ @guard_tool(guard, tool="payments", operation="payment", agent_role="support")
86
+ def send_payment(amount: int, to: str):
87
+ ... # only runs if GuardRail approves
88
+
89
+ try:
90
+ send_payment(amount=42_000, to="vendor/acme")
91
+ except GuardrailBlocked as stopped:
92
+ print(stopped.decision.explanation)
93
+ ```
94
+
95
+ ## Verdicts
96
+
97
+ | Verdict | Meaning |
98
+ |---|---|
99
+ | `APPROVE` | No policy issues — execute. |
100
+ | `APPROVE_WITH_CONDITIONS` | Execute only with the attached conditions (batch it, back up first, dry-run). |
101
+ | `ESCALATE_TO_HUMAN` | A person must approve first (over-limit payment, untrusted source, unbounded delete). |
102
+ | `BLOCK` | Never execute (injection, unauthorized role, PII exfiltration, hard money ceiling). |
103
+
104
+ Priority is fail-safe: any `block` finding wins, then `escalate`, then `conditions`.
105
+
106
+ ## What it checks — 7 deterministic detectors
107
+
108
+ No LLM in the decision path: the same action under the same policy always gets the same verdict, reproducibly and fast.
109
+
110
+ 1. **Injection** — instruction-override / role-hijack / secret-extraction / policy-bypass patterns in untrusted content (email, webpage, tool output). Untrusted content is data, never instructions.
111
+ 2. **Authorization** — role × operation-class permissions (an `intern` role cannot delete, a `support` role cannot pay).
112
+ 3. **Financial limits** — per-class auto-approve and block thresholds, plus a hard ceiling no role can exceed; a payment with no verifiable amount escalates.
113
+ 4. **Bulk operations** — record-count thresholds: conditions (batch + dry-run) above the auto-approve max, escalation above the bulk ceiling.
114
+ 5. **Taint / exfiltration** — PII or secret fields flowing to an external destination is blocked; secrets inside tool-call parameters are blocked outright.
115
+ 6. **Destructive actions** — irreversible operations without a backup/confirmation marker get conditions; a delete with no target escalates.
116
+ 7. **Untrusted source** — money movement, deletion, or external sends *triggered by* email/webpage/tool-output content escalate to a human.
117
+
118
+ ## Policy
119
+
120
+ Every threshold lives in one policy dict — tune it without touching code, or load it from YAML:
121
+
122
+ ```python
123
+ from guardrail_middleware import Guardrail, Policy
124
+
125
+ policy = Policy.from_yaml("policy.yaml") # see policy.example.yaml
126
+ guard = Guardrail(policy=policy)
127
+
128
+ # …or inline
129
+ guard = Guardrail(policy={"approval_limits": {"payment": {"auto_approve_max": 500}}})
130
+ ```
131
+
132
+ ## Audit log
133
+
134
+ Pass an `AuditLog` and every decision is appended as one JSON line, hash-chained with SHA-256: each entry commits to the previous entry's hash, so editing, deleting, or reordering history breaks the chain.
135
+
136
+ ```python
137
+ from guardrail_middleware import AuditLog
138
+ AuditLog("audit.jsonl").verify() # {'ok': True, 'entries': 128, 'broken_at': None}
139
+ ```
140
+
141
+ ## Demo & tests
142
+
143
+ ```bash
144
+ python examples/demo.py # 5 scenarios, all four verdicts, audit verification
145
+ pytest # 18 tests: engine, detectors, middleware, decorator, audit tampering
146
+ ```
147
+
148
+ ## Where this comes from
149
+
150
+ `guardrail-middleware` is the reusable enforcement core extracted from **[GuardRail](https://github.com/Niraj21-star/guard_ai)** — a runtime action-authorization and behavioral-safety layer for agentic AI built at Infosys Ignite EngNext 2026 (special recognition), where the full system adds multi-step plan validation, an action-passport execution gateway, and a 42-scenario adversarial red-team benchmark. This package packages the single-action checkpoint from that system so any agent stack can adopt it in minutes.
151
+
152
+ ## Status & honesty notes
153
+
154
+ - v0.1.0, alpha. The API may still move.
155
+ - Detectors are deterministic heuristics, not a proof of safety — pair them with least-privilege credentials and human review for high-impact tools.
156
+ - Plan-level (multi-step) validation lives in the main GuardRail project, not in this package yet.
157
+
158
+ ## License
159
+
160
+ MIT © Niraj Sanjay Karnawat
@@ -0,0 +1,131 @@
1
+ # guardrail-middleware
2
+
3
+ **Runtime authorization for AI agent tool calls.** GuardRail sits between an AI agent and its tools: every proposed action is checked against a policy *before* it executes — and every decision is written to a tamper-evident audit log.
4
+
5
+ An agent that can call tools can also be talked into misusing them — by a prompt injection in an email, a poisoned webpage, or its own overconfidence. GuardRail is the checkpoint that asks, deterministically and in under a millisecond: *is this role allowed to do this, to this resource, with these parameters, on the say-so of this source?*
6
+
7
+ ```
8
+ pip install guardrail-middleware # core, zero dependencies
9
+ pip install guardrail-middleware[fastapi] # + FastAPI/Starlette middleware
10
+ ```
11
+
12
+ ## Quick start — framework-agnostic
13
+
14
+ ```python
15
+ from guardrail_middleware import Guardrail
16
+
17
+ guard = Guardrail() # built-in default policy
18
+
19
+ decision = guard.evaluate({
20
+ "tool": "payments",
21
+ "operation": "payment",
22
+ "target_resource": "vendor/acme",
23
+ "parameters": {"amount": 42000},
24
+ "agent_role": "support",
25
+ })
26
+
27
+ decision.verdict # Verdict.BLOCK — role 'support' may not run payments
28
+ decision.allowed # False
29
+ decision.explanation
30
+ ```
31
+
32
+ Works anywhere an agent proposes an action: LangChain/LangGraph tool wrappers, MCP servers, custom agent loops, job queues.
33
+
34
+ ## Quick start — FastAPI / Starlette middleware
35
+
36
+ ```python
37
+ from fastapi import FastAPI
38
+ from guardrail_middleware import Guardrail, AuditLog
39
+ from guardrail_middleware.fastapi import GuardrailMiddleware
40
+
41
+ app = FastAPI()
42
+ app.add_middleware(
43
+ GuardrailMiddleware,
44
+ guard=Guardrail(audit_log=AuditLog("audit.jsonl")),
45
+ paths=["/tools/execute"],
46
+ )
47
+ ```
48
+
49
+ Requests to guarded paths are read as actions. **Blocked or escalated actions never reach your handler** — the client gets HTTP 403 with the full decision as JSON. Allowed actions pass through with `X-Guardrail-Verdict` and `X-Guardrail-Risk` headers set.
50
+
51
+ ## Quick start — decorator
52
+
53
+ ```python
54
+ from guardrail_middleware.fastapi import guard_tool, GuardrailBlocked
55
+
56
+ @guard_tool(guard, tool="payments", operation="payment", agent_role="support")
57
+ def send_payment(amount: int, to: str):
58
+ ... # only runs if GuardRail approves
59
+
60
+ try:
61
+ send_payment(amount=42_000, to="vendor/acme")
62
+ except GuardrailBlocked as stopped:
63
+ print(stopped.decision.explanation)
64
+ ```
65
+
66
+ ## Verdicts
67
+
68
+ | Verdict | Meaning |
69
+ |---|---|
70
+ | `APPROVE` | No policy issues — execute. |
71
+ | `APPROVE_WITH_CONDITIONS` | Execute only with the attached conditions (batch it, back up first, dry-run). |
72
+ | `ESCALATE_TO_HUMAN` | A person must approve first (over-limit payment, untrusted source, unbounded delete). |
73
+ | `BLOCK` | Never execute (injection, unauthorized role, PII exfiltration, hard money ceiling). |
74
+
75
+ Priority is fail-safe: any `block` finding wins, then `escalate`, then `conditions`.
76
+
77
+ ## What it checks — 7 deterministic detectors
78
+
79
+ No LLM in the decision path: the same action under the same policy always gets the same verdict, reproducibly and fast.
80
+
81
+ 1. **Injection** — instruction-override / role-hijack / secret-extraction / policy-bypass patterns in untrusted content (email, webpage, tool output). Untrusted content is data, never instructions.
82
+ 2. **Authorization** — role × operation-class permissions (an `intern` role cannot delete, a `support` role cannot pay).
83
+ 3. **Financial limits** — per-class auto-approve and block thresholds, plus a hard ceiling no role can exceed; a payment with no verifiable amount escalates.
84
+ 4. **Bulk operations** — record-count thresholds: conditions (batch + dry-run) above the auto-approve max, escalation above the bulk ceiling.
85
+ 5. **Taint / exfiltration** — PII or secret fields flowing to an external destination is blocked; secrets inside tool-call parameters are blocked outright.
86
+ 6. **Destructive actions** — irreversible operations without a backup/confirmation marker get conditions; a delete with no target escalates.
87
+ 7. **Untrusted source** — money movement, deletion, or external sends *triggered by* email/webpage/tool-output content escalate to a human.
88
+
89
+ ## Policy
90
+
91
+ Every threshold lives in one policy dict — tune it without touching code, or load it from YAML:
92
+
93
+ ```python
94
+ from guardrail_middleware import Guardrail, Policy
95
+
96
+ policy = Policy.from_yaml("policy.yaml") # see policy.example.yaml
97
+ guard = Guardrail(policy=policy)
98
+
99
+ # …or inline
100
+ guard = Guardrail(policy={"approval_limits": {"payment": {"auto_approve_max": 500}}})
101
+ ```
102
+
103
+ ## Audit log
104
+
105
+ Pass an `AuditLog` and every decision is appended as one JSON line, hash-chained with SHA-256: each entry commits to the previous entry's hash, so editing, deleting, or reordering history breaks the chain.
106
+
107
+ ```python
108
+ from guardrail_middleware import AuditLog
109
+ AuditLog("audit.jsonl").verify() # {'ok': True, 'entries': 128, 'broken_at': None}
110
+ ```
111
+
112
+ ## Demo & tests
113
+
114
+ ```bash
115
+ python examples/demo.py # 5 scenarios, all four verdicts, audit verification
116
+ pytest # 18 tests: engine, detectors, middleware, decorator, audit tampering
117
+ ```
118
+
119
+ ## Where this comes from
120
+
121
+ `guardrail-middleware` is the reusable enforcement core extracted from **[GuardRail](https://github.com/Niraj21-star/guard_ai)** — a runtime action-authorization and behavioral-safety layer for agentic AI built at Infosys Ignite EngNext 2026 (special recognition), where the full system adds multi-step plan validation, an action-passport execution gateway, and a 42-scenario adversarial red-team benchmark. This package packages the single-action checkpoint from that system so any agent stack can adopt it in minutes.
122
+
123
+ ## Status & honesty notes
124
+
125
+ - v0.1.0, alpha. The API may still move.
126
+ - Detectors are deterministic heuristics, not a proof of safety — pair them with least-privilege credentials and human review for high-impact tools.
127
+ - Plan-level (multi-step) validation lives in the main GuardRail project, not in this package yet.
128
+
129
+ ## License
130
+
131
+ MIT © Niraj Sanjay Karnawat
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "guardrail-middleware"
7
+ version = "0.1.0"
8
+ description = "Runtime authorization middleware for AI agent tool calls — policy checks, injection/taint detectors, and a hash-chained audit log, before any action executes."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Niraj Sanjay Karnawat" }]
13
+ keywords = ["ai-agents", "guardrails", "llm-security", "middleware", "fastapi", "authorization"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Security",
20
+ "Topic :: Software Development :: Libraries",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ fastapi = ["starlette>=0.27", "fastapi>=0.100"]
25
+ yaml = ["pyyaml>=6"]
26
+ dev = ["pytest>=7", "fastapi>=0.100", "httpx>=0.24"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Niraj21-star/guardrail-middleware"
30
+ Source = "https://github.com/Niraj21-star/guardrail-middleware"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ """guardrail-middleware — runtime authorization for AI agent tool calls.
2
+
3
+ GuardRail sits between an AI agent and its tools. Every proposed action is
4
+ checked against a policy — authorization, prompt-injection and taint
5
+ detectors, financial and bulk limits — *before* it executes, and every
6
+ decision is written to a tamper-evident, hash-chained audit log.
7
+
8
+ Quick start::
9
+
10
+ from guardrail_middleware import Guardrail
11
+
12
+ guard = Guardrail()
13
+ decision = guard.evaluate({
14
+ "tool": "payments", "operation": "payment",
15
+ "target_resource": "vendor/acme",
16
+ "parameters": {"amount": 42000},
17
+ "agent_role": "support",
18
+ })
19
+ print(decision.verdict) # ESCALATE_TO_HUMAN
20
+
21
+ Extracted from the GuardRail project (Infosys Ignite EngNext 2026, special
22
+ recognition) so any agent stack can use the same enforcement core.
23
+ """
24
+
25
+ from .audit import AuditLog
26
+ from .engine import Guardrail
27
+ from .models import ActionRequest, Decision, Finding, TriggeredBy, Verdict
28
+ from .policy import DEFAULT_POLICY, Policy
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ __all__ = [
33
+ "Guardrail",
34
+ "Policy",
35
+ "DEFAULT_POLICY",
36
+ "AuditLog",
37
+ "ActionRequest",
38
+ "Decision",
39
+ "Finding",
40
+ "Verdict",
41
+ "TriggeredBy",
42
+ "__version__",
43
+ ]
@@ -0,0 +1,88 @@
1
+ """Append-only, hash-chained audit log.
2
+
3
+ Every decision GuardRail makes is recorded as one JSON line. Each entry
4
+ carries the SHA-256 hash of the previous entry, so any later edit, deletion,
5
+ or reordering of the log breaks the chain and is detectable with
6
+ :meth:`AuditLog.verify`.
7
+
8
+ The log is deliberately boring: a file on disk, one line per decision, no
9
+ database required. Point it at shared storage if several processes write.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import threading
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any, Optional, Union
20
+
21
+ _GENESIS = "0" * 64
22
+
23
+
24
+ def _entry_hash(payload: dict[str, Any]) -> str:
25
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
26
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
27
+
28
+
29
+ class AuditLog:
30
+ """Thread-safe append-only audit log with a SHA-256 hash chain."""
31
+
32
+ def __init__(self, path: Union[str, Path]) -> None:
33
+ self._path = Path(path)
34
+ self._lock = threading.Lock()
35
+ self._last_hash = self._read_last_hash()
36
+
37
+ def _read_last_hash(self) -> str:
38
+ if not self._path.exists():
39
+ return _GENESIS
40
+ last = _GENESIS
41
+ with open(self._path, "r", encoding="utf-8") as fh:
42
+ for line in fh:
43
+ line = line.strip()
44
+ if line:
45
+ try:
46
+ last = json.loads(line)["entry_hash"]
47
+ except (json.JSONDecodeError, KeyError):
48
+ continue
49
+ return last
50
+
51
+ def record(self, *, action: dict[str, Any], decision: dict[str, Any]) -> str:
52
+ """Append one decision; returns the new entry's hash."""
53
+ with self._lock:
54
+ payload = {
55
+ "ts": datetime.now(timezone.utc).isoformat(),
56
+ "prev_hash": self._last_hash,
57
+ "action": action,
58
+ "decision": decision,
59
+ }
60
+ entry_hash = _entry_hash(payload)
61
+ entry = {**payload, "entry_hash": entry_hash}
62
+ self._path.parent.mkdir(parents=True, exist_ok=True)
63
+ with open(self._path, "a", encoding="utf-8") as fh:
64
+ fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
65
+ self._last_hash = entry_hash
66
+ return entry_hash
67
+
68
+ def verify(self) -> dict[str, Any]:
69
+ """Recompute the whole chain. Returns {ok, entries, broken_at}."""
70
+ prev = _GENESIS
71
+ count = 0
72
+ if not self._path.exists():
73
+ return {"ok": True, "entries": 0, "broken_at": None}
74
+ with open(self._path, "r", encoding="utf-8") as fh:
75
+ for idx, line in enumerate(fh):
76
+ line = line.strip()
77
+ if not line:
78
+ continue
79
+ try:
80
+ entry = json.loads(line)
81
+ except json.JSONDecodeError:
82
+ return {"ok": False, "entries": count, "broken_at": idx}
83
+ payload = {k: v for k, v in entry.items() if k != "entry_hash"}
84
+ if entry.get("prev_hash") != prev or _entry_hash(payload) != entry.get("entry_hash"):
85
+ return {"ok": False, "entries": count, "broken_at": idx}
86
+ prev = entry["entry_hash"]
87
+ count += 1
88
+ return {"ok": True, "entries": count, "broken_at": None}