actiongate-fastapi 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,4 @@
1
+ .DS_Store
2
+ __pycache__/
3
+ dist/
4
+ *.egg-info/
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 ActionGate OSS
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: actiongate-fastapi
3
+ Version: 0.1.0
4
+ Summary: Gate FastAPI routes through ActionGate primitives.
5
+ Project-URL: Homepage, https://github.com/actiongate-oss/actiongate-fastapi
6
+ Project-URL: Documentation, https://github.com/actiongate-oss/actiongate-fastapi#readme
7
+ Project-URL: Repository, https://github.com/actiongate-oss/actiongate-fastapi
8
+ Author-email: ActionGate OSS <actiongate-oss@users.noreply.github.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: actiongate,ai-agents,fastapi,middleware,rate-limiting
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: actiongate>=0.2.0
21
+ Requires-Dist: fastapi>=0.100.0
22
+ Provides-Extra: all
23
+ Requires-Dist: auditgate>=0.1.0; extra == 'all'
24
+ Requires-Dist: budgetgate>=0.2.0; extra == 'all'
25
+ Requires-Dist: rulegate>=0.2.0; extra == 'all'
26
+ Provides-Extra: audit
27
+ Requires-Dist: auditgate>=0.1.0; extra == 'audit'
28
+ Provides-Extra: budget
29
+ Requires-Dist: budgetgate>=0.2.0; extra == 'budget'
30
+ Provides-Extra: dev
31
+ Requires-Dist: httpx>=0.24.0; extra == 'dev'
32
+ Requires-Dist: pytest>=8.0; extra == 'dev'
33
+ Provides-Extra: rules
34
+ Requires-Dist: rulegate>=0.2.0; extra == 'rules'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # actiongate-fastapi
38
+
39
+ Gate FastAPI routes through [ActionGate](https://github.com/actiongate-oss/actiongate) primitives.
40
+
41
+ ```
42
+ pip install actiongate-fastapi
43
+ ```
44
+
45
+ ## Route decorator
46
+
47
+ ```python
48
+ from fastapi import FastAPI
49
+ from actiongate import Engine, Gate, Policy
50
+ from actiongate_fastapi import gated_route
51
+
52
+ app = FastAPI()
53
+ ag = Engine()
54
+
55
+ @app.post("/search")
56
+ @gated_route(
57
+ actiongate=ag,
58
+ gate=Gate("api", "search", "global"),
59
+ policy=Policy(max_calls=100, window=60),
60
+ )
61
+ async def search(query: str):
62
+ return {"results": do_search(query)}
63
+ ```
64
+
65
+ Returns 429 for rate limit and budget blocks. Returns 403 for policy violations.
66
+
67
+ ## Dependency injection
68
+
69
+ ```python
70
+ from fastapi import Depends
71
+ from actiongate_fastapi import gate_dependency
72
+
73
+ require_gate = gate_dependency(actiongate=ag)
74
+
75
+ @app.post("/search")
76
+ async def search(
77
+ query: str,
78
+ _=Depends(require_gate(
79
+ gate=Gate("api", "search"),
80
+ policy=Policy(max_calls=100, window=60),
81
+ )),
82
+ ):
83
+ return {"results": do_search(query)}
84
+ ```
85
+
86
+ ## Add more gates
87
+
88
+ ```
89
+ pip install actiongate-fastapi[all]
90
+ ```
91
+
92
+ ```python
93
+ from actiongate import Engine as AG, Gate, Policy
94
+ from budgetgate import Engine as BG, Ledger, Budget
95
+ from rulegate import Engine as RG, Rule, Ruleset, Context
96
+ from actiongate_fastapi import gated_route
97
+ from decimal import Decimal
98
+
99
+ ag, bg, rg = AG(), BG(), RG()
100
+
101
+ def no_pii(ctx: Context) -> bool:
102
+ return "ssn" not in str(ctx.kwargs).lower()
103
+
104
+ @app.post("/search")
105
+ @gated_route(
106
+ actiongate=ag,
107
+ gate=Gate("api", "search", "global"),
108
+ policy=Policy(max_calls=100, window=60),
109
+ budgetgate=bg,
110
+ ledger=Ledger("api", "search", "global"),
111
+ budget=Budget(max_spend=Decimal("50.00"), window=3600),
112
+ cost=Decimal("0.01"),
113
+ rulegate=rg,
114
+ rule=Rule("api", "search"),
115
+ ruleset=Ruleset(predicates=(no_pii,)),
116
+ )
117
+ async def search(query: str):
118
+ return {"results": do_search(query)}
119
+ ```
120
+
121
+ Gates evaluate in order: ActionGate → BudgetGate → RuleGate → execute → AuditGate.
122
+
123
+ ## License
124
+
125
+ Apache-2.0. ActionGate and BudgetGate are Apache-2.0. RuleGate and AuditGate are BSL-1.1.
@@ -0,0 +1,89 @@
1
+ # actiongate-fastapi
2
+
3
+ Gate FastAPI routes through [ActionGate](https://github.com/actiongate-oss/actiongate) primitives.
4
+
5
+ ```
6
+ pip install actiongate-fastapi
7
+ ```
8
+
9
+ ## Route decorator
10
+
11
+ ```python
12
+ from fastapi import FastAPI
13
+ from actiongate import Engine, Gate, Policy
14
+ from actiongate_fastapi import gated_route
15
+
16
+ app = FastAPI()
17
+ ag = Engine()
18
+
19
+ @app.post("/search")
20
+ @gated_route(
21
+ actiongate=ag,
22
+ gate=Gate("api", "search", "global"),
23
+ policy=Policy(max_calls=100, window=60),
24
+ )
25
+ async def search(query: str):
26
+ return {"results": do_search(query)}
27
+ ```
28
+
29
+ Returns 429 for rate limit and budget blocks. Returns 403 for policy violations.
30
+
31
+ ## Dependency injection
32
+
33
+ ```python
34
+ from fastapi import Depends
35
+ from actiongate_fastapi import gate_dependency
36
+
37
+ require_gate = gate_dependency(actiongate=ag)
38
+
39
+ @app.post("/search")
40
+ async def search(
41
+ query: str,
42
+ _=Depends(require_gate(
43
+ gate=Gate("api", "search"),
44
+ policy=Policy(max_calls=100, window=60),
45
+ )),
46
+ ):
47
+ return {"results": do_search(query)}
48
+ ```
49
+
50
+ ## Add more gates
51
+
52
+ ```
53
+ pip install actiongate-fastapi[all]
54
+ ```
55
+
56
+ ```python
57
+ from actiongate import Engine as AG, Gate, Policy
58
+ from budgetgate import Engine as BG, Ledger, Budget
59
+ from rulegate import Engine as RG, Rule, Ruleset, Context
60
+ from actiongate_fastapi import gated_route
61
+ from decimal import Decimal
62
+
63
+ ag, bg, rg = AG(), BG(), RG()
64
+
65
+ def no_pii(ctx: Context) -> bool:
66
+ return "ssn" not in str(ctx.kwargs).lower()
67
+
68
+ @app.post("/search")
69
+ @gated_route(
70
+ actiongate=ag,
71
+ gate=Gate("api", "search", "global"),
72
+ policy=Policy(max_calls=100, window=60),
73
+ budgetgate=bg,
74
+ ledger=Ledger("api", "search", "global"),
75
+ budget=Budget(max_spend=Decimal("50.00"), window=3600),
76
+ cost=Decimal("0.01"),
77
+ rulegate=rg,
78
+ rule=Rule("api", "search"),
79
+ ruleset=Ruleset(predicates=(no_pii,)),
80
+ )
81
+ async def search(query: str):
82
+ return {"results": do_search(query)}
83
+ ```
84
+
85
+ Gates evaluate in order: ActionGate → BudgetGate → RuleGate → execute → AuditGate.
86
+
87
+ ## License
88
+
89
+ Apache-2.0. ActionGate and BudgetGate are Apache-2.0. RuleGate and AuditGate are BSL-1.1.
@@ -0,0 +1,6 @@
1
+ """ActionGate FastAPI Integration — gate API routes with ActionGate primitives."""
2
+
3
+ from .actiongate_fastapi import gated_route, gate_dependency
4
+
5
+ __all__ = ["gated_route", "gate_dependency"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,217 @@
1
+ """ActionGate FastAPI Integration — gate API routes with ActionGate primitives.
2
+
3
+ Two integration patterns:
4
+
5
+ 1. Dependency injection (idiomatic FastAPI):
6
+
7
+ from actiongate_fastapi import gate_dependency
8
+ from actiongate import Engine, Gate, Policy
9
+ from fastapi import Depends
10
+
11
+ ag = Engine()
12
+ require_gate = gate_dependency(actiongate=ag)
13
+
14
+ @app.post("/search")
15
+ async def search(query: str, _=Depends(require_gate(
16
+ gate=Gate("api", "search", "global"),
17
+ policy=Policy(max_calls=100, window=60),
18
+ ))):
19
+ return {"results": do_search(query)}
20
+
21
+ 2. Route decorator (simpler):
22
+
23
+ from actiongate_fastapi import gated_route
24
+
25
+ @app.post("/search")
26
+ @gated_route(
27
+ actiongate=ag,
28
+ gate=Gate("api", "search", "global"),
29
+ policy=Policy(max_calls=100, window=60),
30
+ )
31
+ async def search(query: str):
32
+ return {"results": do_search(query)}
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import asyncio
38
+ from decimal import Decimal
39
+ from functools import wraps
40
+ from typing import Any, Callable, TYPE_CHECKING
41
+
42
+ from fastapi import HTTPException
43
+
44
+ if TYPE_CHECKING:
45
+ from actiongate import Engine as ActionEngine, Gate, Policy
46
+ from budgetgate import Engine as BudgetEngine, Ledger, Budget
47
+ from rulegate import Engine as RuleEngine, Rule, Ruleset
48
+ from auditgate import Engine as AuditEngine, Trail, AuditPolicy
49
+
50
+
51
+ def _run_gates(
52
+ *,
53
+ ag: "ActionEngine | None",
54
+ gate: "Gate | None",
55
+ policy: "Policy | None",
56
+ bg: "BudgetEngine | None",
57
+ ledger: "Ledger | None",
58
+ budget: "Budget | None",
59
+ cost: Decimal | None,
60
+ rg: "RuleEngine | None",
61
+ rule: "Rule | None",
62
+ ruleset: "Ruleset | None",
63
+ audit: "AuditEngine | None",
64
+ trail: "Trail | None",
65
+ audit_policy: "AuditPolicy | None",
66
+ context_kwargs: dict[str, Any] | None = None,
67
+ ) -> None:
68
+ """Run gate pipeline. Raises HTTPException(429 or 403) on block."""
69
+ decisions: dict[str, Any] = {}
70
+
71
+ if ag and gate:
72
+ decision = ag.check(gate, policy)
73
+ decisions["actiongate"] = decision.to_dict()
74
+ if decision.blocked:
75
+ _audit_log(audit, trail, audit_policy, "BLOCK", "actiongate", decisions)
76
+ raise HTTPException(status_code=429, detail=decision.message)
77
+
78
+ if bg and ledger and cost is not None:
79
+ decision = bg.check(ledger, cost, budget)
80
+ decisions["budgetgate"] = decision.to_dict()
81
+ if decision.blocked:
82
+ _audit_log(audit, trail, audit_policy, "BLOCK", "budgetgate", decisions)
83
+ raise HTTPException(status_code=429, detail=decision.message)
84
+
85
+ if rg and rule and ruleset:
86
+ decision = rg.check(rule, ruleset, kwargs=context_kwargs or {})
87
+ decisions["rulegate"] = decision.to_dict()
88
+ if decision.blocked:
89
+ _audit_log(audit, trail, audit_policy, "BLOCK", "rulegate", decisions)
90
+ raise HTTPException(status_code=403, detail=decision.message)
91
+
92
+ _audit_log(audit, trail, audit_policy, "ALLOW", "pipeline", decisions)
93
+
94
+
95
+ def _audit_log(
96
+ audit: Any, trail: Any, audit_policy: Any,
97
+ verdict_str: str, gate_type: str, decisions: dict[str, Any],
98
+ ) -> None:
99
+ if audit is None or trail is None:
100
+ return
101
+ try:
102
+ from auditgate import Verdict, Severity
103
+ verdict_map = {"ALLOW": Verdict.ALLOW, "BLOCK": Verdict.BLOCK}
104
+ severity_map = {"ALLOW": Severity.INFO, "BLOCK": Severity.WARN}
105
+ audit.record(
106
+ trail,
107
+ verdict=verdict_map.get(verdict_str, Verdict.ERROR),
108
+ severity=severity_map.get(verdict_str, Severity.ERROR),
109
+ gate_type=gate_type,
110
+ gate_identity=str(trail),
111
+ reason=f"{verdict_str} by {gate_type}",
112
+ detail=decisions,
113
+ policy=audit_policy,
114
+ )
115
+ except Exception:
116
+ pass
117
+
118
+
119
+ def gated_route(
120
+ *,
121
+ actiongate: "ActionEngine | None" = None,
122
+ gate: "Gate | None" = None,
123
+ policy: "Policy | None" = None,
124
+ budgetgate: "BudgetEngine | None" = None,
125
+ ledger: "Ledger | None" = None,
126
+ budget: "Budget | None" = None,
127
+ cost: Decimal | None = None,
128
+ rulegate: "RuleEngine | None" = None,
129
+ rule: "Rule | None" = None,
130
+ ruleset: "Ruleset | None" = None,
131
+ auditgate: "AuditEngine | None" = None,
132
+ trail: "Trail | None" = None,
133
+ audit_policy: "AuditPolicy | None" = None,
134
+ ) -> Callable:
135
+ """Decorator that gates a FastAPI route.
136
+
137
+ Returns 429 for rate/budget blocks, 403 for policy violations.
138
+
139
+ Example:
140
+ @app.post("/search")
141
+ @gated_route(
142
+ actiongate=ag,
143
+ gate=Gate("api", "search", "global"),
144
+ policy=Policy(max_calls=100, window=60),
145
+ )
146
+ async def search(query: str):
147
+ return {"results": do_search(query)}
148
+ """
149
+ gate_kwargs = dict(
150
+ ag=actiongate, gate=gate, policy=policy,
151
+ bg=budgetgate, ledger=ledger, budget=budget, cost=cost,
152
+ rg=rulegate, rule=rule, ruleset=ruleset,
153
+ audit=auditgate, trail=trail, audit_policy=audit_policy,
154
+ )
155
+
156
+ def decorator(fn: Callable) -> Callable:
157
+ if asyncio.iscoroutinefunction(fn):
158
+ @wraps(fn)
159
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
160
+ _run_gates(**gate_kwargs, context_kwargs=kwargs)
161
+ return await fn(*args, **kwargs)
162
+ return async_wrapper
163
+ else:
164
+ @wraps(fn)
165
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
166
+ _run_gates(**gate_kwargs, context_kwargs=kwargs)
167
+ return fn(*args, **kwargs)
168
+ return sync_wrapper
169
+
170
+ return decorator
171
+
172
+
173
+ def gate_dependency(
174
+ *,
175
+ actiongate: "ActionEngine | None" = None,
176
+ budgetgate: "BudgetEngine | None" = None,
177
+ rulegate: "RuleEngine | None" = None,
178
+ auditgate: "AuditEngine | None" = None,
179
+ ) -> Callable:
180
+ """Create a FastAPI dependency factory for gate checks.
181
+
182
+ Returns a function that produces Depends()-compatible callables.
183
+
184
+ Example:
185
+ require_gate = gate_dependency(actiongate=ag, budgetgate=bg)
186
+
187
+ @app.post("/search")
188
+ async def search(
189
+ query: str,
190
+ _=Depends(require_gate(
191
+ gate=Gate("api", "search"),
192
+ policy=Policy(max_calls=100, window=60),
193
+ )),
194
+ ):
195
+ return {"results": do_search(query)}
196
+ """
197
+ def make_dependency(
198
+ *,
199
+ gate: "Gate | None" = None,
200
+ policy: "Policy | None" = None,
201
+ ledger: "Ledger | None" = None,
202
+ budget: "Budget | None" = None,
203
+ cost: Decimal | None = None,
204
+ rule: "Rule | None" = None,
205
+ ruleset: "Ruleset | None" = None,
206
+ trail: "Trail | None" = None,
207
+ audit_policy: "AuditPolicy | None" = None,
208
+ ) -> Callable:
209
+ async def dependency() -> None:
210
+ _run_gates(
211
+ ag=actiongate, gate=gate, policy=policy,
212
+ bg=budgetgate, ledger=ledger, budget=budget, cost=cost,
213
+ rg=rulegate, rule=rule, ruleset=ruleset,
214
+ audit=auditgate, trail=trail, audit_policy=audit_policy,
215
+ )
216
+ return dependency
217
+ return make_dependency
@@ -0,0 +1,77 @@
1
+ """ActionGate FastAPI demo — run with: uvicorn demo:app
2
+
3
+ pip install actiongate-fastapi[all] uvicorn
4
+ python demo.py
5
+
6
+ Or for live server: uvicorn demo:app --reload
7
+ Then: curl http://localhost:8000/search?query=hello
8
+ """
9
+
10
+ from decimal import Decimal
11
+ from fastapi import FastAPI
12
+ from actiongate import Engine as AG, Gate, Policy
13
+ from budgetgate import Engine as BG, Ledger, Budget
14
+ from rulegate import Engine as RG, Rule, Ruleset, Context
15
+ from actiongate_fastapi import gated_route
16
+
17
+ app = FastAPI(title="ActionGate FastAPI Demo")
18
+ ag, bg, rg = AG(), BG(), RG()
19
+
20
+ def no_pii(ctx: Context) -> bool:
21
+ return "ssn" not in str(ctx.kwargs).lower()
22
+
23
+ def no_drop(ctx: Context) -> bool:
24
+ return "drop" not in str(ctx.kwargs.get("sql", "")).lower()
25
+
26
+ @app.get("/search")
27
+ @gated_route(
28
+ actiongate=ag,
29
+ gate=Gate("api", "search", "global"),
30
+ policy=Policy(max_calls=5, window=60),
31
+ budgetgate=bg,
32
+ ledger=Ledger("api", "search", "global"),
33
+ budget=Budget(max_spend=Decimal("0.05"), window=3600),
34
+ cost=Decimal("0.01"),
35
+ rulegate=rg,
36
+ rule=Rule("api", "search"),
37
+ ruleset=Ruleset(predicates=(no_pii,)),
38
+ )
39
+ async def search(query: str = "hello"):
40
+ return {"results": f"Found: {query}"}
41
+
42
+ @app.get("/db")
43
+ @gated_route(
44
+ actiongate=ag,
45
+ gate=Gate("api", "db", "global"),
46
+ policy=Policy(max_calls=10, window=60),
47
+ rulegate=rg,
48
+ rule=Rule("api", "db"),
49
+ ruleset=Ruleset(predicates=(no_drop,)),
50
+ )
51
+ async def query_db(sql: str = "SELECT 1"):
52
+ return {"rows": 3, "sql": sql}
53
+
54
+ # ── Self-test when run directly ──
55
+ if __name__ == "__main__":
56
+ from fastapi.testclient import TestClient
57
+
58
+ client = TestClient(app)
59
+ calls = [
60
+ ("Search", "/search?query=AI+news"),
61
+ ("PII blocked", "/search?query=find+SSN"),
62
+ ("Search again", "/search?query=Python"),
63
+ ("Search again", "/search?query=weather"),
64
+ ("Search again", "/search?query=recipes"),
65
+ ("Rate limited", "/search?query=too+many"),
66
+ ("Safe SQL", "/db?sql=SELECT+1"),
67
+ ("DROP blocked", "/db?sql=DROP+TABLE"),
68
+ ]
69
+
70
+ print("ActionGate FastAPI Demo")
71
+ print("─" * 50)
72
+ for label, url in calls:
73
+ r = client.get(url)
74
+ status = r.status_code
75
+ body = r.json()
76
+ detail = body.get("detail", body)
77
+ print(f" {label:20s} {status} {detail}")
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "actiongate-fastapi"
7
+ version = "0.1.0"
8
+ description = "Gate FastAPI routes through ActionGate primitives."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.12"
12
+ authors = [
13
+ { name = "ActionGate OSS", email = "actiongate-oss@users.noreply.github.com" }
14
+ ]
15
+ keywords = [
16
+ "actiongate",
17
+ "fastapi",
18
+ "rate-limiting",
19
+ "middleware",
20
+ "ai-agents",
21
+ ]
22
+ classifiers = [
23
+ "Development Status :: 3 - Alpha",
24
+ "Intended Audience :: Developers",
25
+ "License :: OSI Approved :: Apache Software License",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = [
32
+ "actiongate>=0.2.0",
33
+ "fastapi>=0.100.0",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ budget = ["budgetgate>=0.2.0"]
38
+ rules = ["rulegate>=0.2.0"]
39
+ audit = ["auditgate>=0.1.0"]
40
+ all = [
41
+ "budgetgate>=0.2.0",
42
+ "rulegate>=0.2.0",
43
+ "auditgate>=0.1.0",
44
+ ]
45
+ dev = [
46
+ "pytest>=8.0",
47
+ "httpx>=0.24.0",
48
+ ]
49
+
50
+ [project.urls]
51
+ Homepage = "https://github.com/actiongate-oss/actiongate-fastapi"
52
+ Documentation = "https://github.com/actiongate-oss/actiongate-fastapi#readme"
53
+ Repository = "https://github.com/actiongate-oss/actiongate-fastapi"
54
+
55
+ [tool.hatch.build.targets.wheel]
56
+ packages = ["actiongate_fastapi"]
@@ -0,0 +1,228 @@
1
+ """Tests for actiongate-fastapi integration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import traceback
7
+ from decimal import Decimal
8
+
9
+ sys.path.insert(0, ".")
10
+
11
+ passed = 0
12
+ failed = 0
13
+ errors: list[str] = []
14
+
15
+ def test(name):
16
+ def decorator(fn):
17
+ global passed, failed
18
+ try:
19
+ fn()
20
+ passed += 1
21
+ print(f" PASS {name}")
22
+ except Exception as e:
23
+ failed += 1
24
+ errors.append(f" FAIL {name}: {e}\n{traceback.format_exc()}")
25
+ print(f" FAIL {name}: {e}")
26
+ return fn
27
+ return decorator
28
+
29
+ _clk = 1.0
30
+ def fake_clock():
31
+ return _clk
32
+
33
+
34
+ print("── @gated_route decorator ──")
35
+
36
+ @test("allowed request returns 200")
37
+ def _():
38
+ from fastapi import FastAPI
39
+ from fastapi.testclient import TestClient
40
+ from actiongate import Engine, Gate, Policy
41
+ from actiongate_fastapi import gated_route
42
+
43
+ app = FastAPI()
44
+ ag = Engine(clock=fake_clock)
45
+
46
+ @app.get("/ping")
47
+ @gated_route(actiongate=ag, gate=Gate("test", "ping"), policy=Policy(max_calls=5, window=60))
48
+ async def ping():
49
+ return {"msg": "pong"}
50
+
51
+ client = TestClient(app)
52
+ resp = client.get("/ping")
53
+ assert resp.status_code == 200
54
+ assert resp.json() == {"msg": "pong"}
55
+
56
+
57
+ @test("rate limited returns 429")
58
+ def _():
59
+ global _clk; _clk = 1.0
60
+ from fastapi import FastAPI
61
+ from fastapi.testclient import TestClient
62
+ from actiongate import Engine, Gate, Policy
63
+ from actiongate_fastapi import gated_route
64
+
65
+ app = FastAPI()
66
+ ag = Engine(clock=fake_clock)
67
+
68
+ @app.get("/ping")
69
+ @gated_route(actiongate=ag, gate=Gate("test", "p2"), policy=Policy(max_calls=1, window=60))
70
+ async def ping():
71
+ return {"msg": "pong"}
72
+
73
+ client = TestClient(app)
74
+ r1 = client.get("/ping")
75
+ assert r1.status_code == 200
76
+
77
+ _clk = 2.0
78
+ r2 = client.get("/ping")
79
+ assert r2.status_code == 429
80
+
81
+
82
+ @test("budget exceeded returns 429")
83
+ def _():
84
+ global _clk; _clk = 1.0
85
+ from fastapi import FastAPI
86
+ from fastapi.testclient import TestClient
87
+ from actiongate import Engine as AG, Gate, Policy
88
+ from budgetgate import Engine as BG, Ledger, Budget
89
+ from actiongate_fastapi import gated_route
90
+
91
+ app = FastAPI()
92
+ ag = AG(clock=fake_clock)
93
+ bg = BG(clock=fake_clock)
94
+
95
+ @app.get("/expensive")
96
+ @gated_route(
97
+ actiongate=ag, gate=Gate("test", "exp"), policy=Policy(max_calls=100, window=60),
98
+ budgetgate=bg, ledger=Ledger("test", "api", "u:1"),
99
+ budget=Budget(max_spend=Decimal("1.00"), window=60), cost=Decimal("0.60"),
100
+ )
101
+ async def expensive():
102
+ return {"ok": True}
103
+
104
+ client = TestClient(app)
105
+ r1 = client.get("/expensive")
106
+ assert r1.status_code == 200
107
+
108
+ _clk = 2.0
109
+ r2 = client.get("/expensive")
110
+ assert r2.status_code == 429
111
+
112
+
113
+ @test("policy violation returns 403")
114
+ def _():
115
+ global _clk; _clk = 1.0
116
+ from fastapi import FastAPI
117
+ from fastapi.testclient import TestClient
118
+ from actiongate import Engine as AG, Gate, Policy
119
+ from rulegate import Engine as RG, Rule, Ruleset, Context
120
+ from actiongate_fastapi import gated_route
121
+
122
+ def no_bad(ctx: Context) -> bool:
123
+ return "bad" not in str(ctx.kwargs).lower()
124
+
125
+ app = FastAPI()
126
+ ag = AG(clock=fake_clock)
127
+ rg = RG(clock=fake_clock)
128
+
129
+ @app.get("/search")
130
+ @gated_route(
131
+ actiongate=ag, gate=Gate("test", "s2"), policy=Policy(max_calls=100, window=60),
132
+ rulegate=rg, rule=Rule("test", "search"), ruleset=Ruleset(predicates=(no_bad,)),
133
+ )
134
+ async def search(query: str = "good"):
135
+ return {"results": query}
136
+
137
+ client = TestClient(app)
138
+ r1 = client.get("/search?query=good")
139
+ assert r1.status_code == 200
140
+
141
+ r2 = client.get("/search?query=bad")
142
+ assert r2.status_code == 403
143
+
144
+
145
+ @test("sync route works")
146
+ def _():
147
+ global _clk; _clk = 1.0
148
+ from fastapi import FastAPI
149
+ from fastapi.testclient import TestClient
150
+ from actiongate import Engine, Gate, Policy
151
+ from actiongate_fastapi import gated_route
152
+
153
+ app = FastAPI()
154
+ ag = Engine(clock=fake_clock)
155
+
156
+ @app.get("/sync")
157
+ @gated_route(actiongate=ag, gate=Gate("test", "sync"), policy=Policy(max_calls=5, window=60))
158
+ def sync_route():
159
+ return {"sync": True}
160
+
161
+ client = TestClient(app)
162
+ resp = client.get("/sync")
163
+ assert resp.status_code == 200
164
+ assert resp.json() == {"sync": True}
165
+
166
+
167
+ print("\n── gate_dependency ──")
168
+
169
+ @test("dependency injection blocks on rate limit")
170
+ def _():
171
+ global _clk; _clk = 1.0
172
+ from fastapi import FastAPI, Depends
173
+ from fastapi.testclient import TestClient
174
+ from actiongate import Engine, Gate, Policy
175
+ from actiongate_fastapi import gate_dependency
176
+
177
+ app = FastAPI()
178
+ ag = Engine(clock=fake_clock)
179
+ require_gate = gate_dependency(actiongate=ag)
180
+
181
+ @app.get("/dep")
182
+ async def dep_route(_=Depends(require_gate(
183
+ gate=Gate("test", "dep"), policy=Policy(max_calls=1, window=60),
184
+ ))):
185
+ return {"ok": True}
186
+
187
+ client = TestClient(app)
188
+ r1 = client.get("/dep")
189
+ assert r1.status_code == 200
190
+
191
+ _clk = 2.0
192
+ r2 = client.get("/dep")
193
+ assert r2.status_code == 429
194
+
195
+
196
+ @test("429 response includes detail message")
197
+ def _():
198
+ global _clk; _clk = 1.0
199
+ from fastapi import FastAPI
200
+ from fastapi.testclient import TestClient
201
+ from actiongate import Engine, Gate, Policy
202
+ from actiongate_fastapi import gated_route
203
+
204
+ app = FastAPI()
205
+ ag = Engine(clock=fake_clock)
206
+
207
+ @app.get("/msg")
208
+ @gated_route(actiongate=ag, gate=Gate("test", "msg"), policy=Policy(max_calls=1, window=60))
209
+ async def msg():
210
+ return {"ok": True}
211
+
212
+ client = TestClient(app)
213
+ client.get("/msg")
214
+ _clk = 2.0
215
+ r = client.get("/msg")
216
+ assert r.status_code == 429
217
+ assert "detail" in r.json()
218
+ assert "Rate limit" in r.json()["detail"]
219
+
220
+
221
+ print(f"\n{'═' * 50}")
222
+ print(f"Results: {passed} passed, {failed} failed")
223
+ if errors:
224
+ print("\nFailures:")
225
+ for e in errors:
226
+ print(e)
227
+ print(f"{'═' * 50}")
228
+ sys.exit(1 if failed else 0)