fastapi-apcore 0.4.0__tar.gz → 0.6.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.
- {fastapi_apcore-0.4.0/src/fastapi_apcore.egg-info → fastapi_apcore-0.6.0}/PKG-INFO +35 -8
- fastapi_apcore-0.4.0/PKG-INFO → fastapi_apcore-0.6.0/README.md +29 -32
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/pyproject.toml +13 -6
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/cli.py +16 -4
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/client.py +48 -3
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/extensions.py +8 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/shortcuts.py +12 -4
- fastapi_apcore-0.6.0/src/fastapi_apcore/governance.py +105 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/output/registry_writer.py +17 -28
- fastapi_apcore-0.6.0/src/fastapi_apcore/scanners/base.py +202 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/scanners/native.py +34 -24
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/scanners/openapi.py +58 -11
- fastapi_apcore-0.4.0/README.md → fastapi_apcore-0.6.0/src/fastapi_apcore.egg-info/PKG-INFO +59 -2
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore.egg-info/SOURCES.txt +4 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore.egg-info/requires.txt +5 -5
- fastapi_apcore-0.6.0/tests/test_acl_demo.py +58 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_extensions.py +46 -0
- fastapi_apcore-0.6.0/tests/test_governance.py +85 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_integration.py +25 -0
- fastapi_apcore-0.6.0/tests/test_proxy_preflight.py +118 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_scanner.py +110 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_writers.py +68 -0
- fastapi_apcore-0.4.0/src/fastapi_apcore/scanners/base.py +0 -114
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/setup.cfg +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/__init__.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/__init__.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/config.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/context.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/observability.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/registry.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/serializers.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/engine/tasks.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/output/__init__.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/output/yaml_writer.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/py.typed +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore/scanners/__init__.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore.egg-info/dependency_links.txt +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore.egg-info/entry_points.txt +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/src/fastapi_apcore.egg-info/top_level.txt +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_client.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_config.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_context.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_observability.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_public_api.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_registry.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_serializers.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_shortcuts.py +0 -0
- {fastapi_apcore-0.4.0 → fastapi_apcore-0.6.0}/tests/test_tasks.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastapi-apcore
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: FastAPI integration for apcore AI-Perceivable Core — exposes FastAPI routes as apcore modules with auto-discovery, schema extraction from Pydantic models, and OpenAPI-based scanning.
|
|
5
5
|
Author-email: aiperceivable <team@aiperceivable.com>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -10,17 +10,17 @@ Keywords: fastapi,apcore,mcp,llm,ai,tools,pydantic,schema,module,cli,auto-discov
|
|
|
10
10
|
Requires-Python: >=3.11
|
|
11
11
|
Description-Content-Type: text/markdown
|
|
12
12
|
Requires-Dist: fastapi>=0.100
|
|
13
|
-
Requires-Dist: apcore>=0.
|
|
14
|
-
Requires-Dist: apcore-toolkit>=0.
|
|
13
|
+
Requires-Dist: apcore>=0.33.0
|
|
14
|
+
Requires-Dist: apcore-toolkit>=0.15.0
|
|
15
15
|
Provides-Extra: mcp
|
|
16
|
-
Requires-Dist: apcore-mcp>=0.
|
|
16
|
+
Requires-Dist: apcore-mcp>=0.23.4; extra == "mcp"
|
|
17
17
|
Provides-Extra: cli
|
|
18
|
-
Requires-Dist: apcore-cli>=0.
|
|
18
|
+
Requires-Dist: apcore-cli>=0.14.1; extra == "cli"
|
|
19
19
|
Requires-Dist: click>=8.0; extra == "cli"
|
|
20
20
|
Provides-Extra: all
|
|
21
21
|
Requires-Dist: fastapi-apcore[cli,mcp]; extra == "all"
|
|
22
22
|
Provides-Extra: dev
|
|
23
|
-
Requires-Dist: apdev[dev]>=0.2.
|
|
23
|
+
Requires-Dist: apdev[dev]>=0.2.7; extra == "dev"
|
|
24
24
|
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
25
25
|
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
26
26
|
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
@@ -59,8 +59,10 @@ FastAPI integration for [apcore](https://github.com/aiperceivable/apcore-python)
|
|
|
59
59
|
|
|
60
60
|
- Python >= 3.11
|
|
61
61
|
- FastAPI >= 0.100
|
|
62
|
-
- apcore >= 0.
|
|
63
|
-
- apcore-toolkit >= 0.
|
|
62
|
+
- apcore >= 0.33.0
|
|
63
|
+
- apcore-toolkit >= 0.15.0
|
|
64
|
+
- apcore-mcp >= 0.23.4 (optional, `[mcp]` extra)
|
|
65
|
+
- apcore-cli >= 0.14.1 (optional, `[cli]` extra)
|
|
64
66
|
|
|
65
67
|
## Installation
|
|
66
68
|
|
|
@@ -331,6 +333,8 @@ if __name__ == "__main__":
|
|
|
331
333
|
|
|
332
334
|
Each scanned route becomes a CLI command named after `display.cli.alias` from the binding overlay (or the module_id if no overlay is set). The commands forward HTTP requests to the running API using `HTTPProxyRegistryWriter`. Built-in subcommands include `list`, `describe`, `completion`, and `man`.
|
|
333
335
|
|
|
336
|
+
`create_cli()` runs a proxy preflight by default (`validate_proxy=True`). It resolves inherited and referenced OpenAPI parameters through apcore-toolkit's effective-parameter scanner, then refuses to register any operation the HTTP proxy cannot forward losslessly — for example a query parameter on a JSON-body `POST`, a body on a query-method route, or conflicting path/query/body names. The error names every offending module. Pass `validate_proxy=False` to keep the legacy best-effort behaviour. Native scanning (`scan_source="native"`) skips this check because it has no OpenAPI document to resolve against.
|
|
337
|
+
|
|
334
338
|
`commands_dir` points to a directory of plain Python function files. When set, `ConventionScanner` from `apcore-toolkit` scans for public functions and registers them as additional modules alongside the scanned API routes (§5.14).
|
|
335
339
|
|
|
336
340
|
### Display Overlay (`binding_path`)
|
|
@@ -394,6 +398,29 @@ All settings are read from environment variables with the `APCORE_` prefix:
|
|
|
394
398
|
| `APCORE_ACL_PATH` | — | Path to ACL YAML rules file |
|
|
395
399
|
| `APCORE_MIDDLEWARES` | — | Comma-separated middleware dotted paths |
|
|
396
400
|
|
|
401
|
+
#### Access control (ACL)
|
|
402
|
+
|
|
403
|
+
Set `APCORE_ACL_PATH` to a YAML rules file and apcore enforces role-based
|
|
404
|
+
`allow`/`deny` on every module call. Roles come from the request's
|
|
405
|
+
authenticated user: `FastAPIContextFactory` reads `request.state.user`
|
|
406
|
+
(`roles` / `groups` / `scopes`) into the apcore `Identity` that ACL conditions
|
|
407
|
+
match against. A denied call raises `ACLDeniedError`, which your route maps to
|
|
408
|
+
HTTP 403.
|
|
409
|
+
|
|
410
|
+
```yaml
|
|
411
|
+
# acl.yaml
|
|
412
|
+
default_effect: deny
|
|
413
|
+
rules:
|
|
414
|
+
- description: Admins may call any module
|
|
415
|
+
callers: ["*"]
|
|
416
|
+
targets: ["*"]
|
|
417
|
+
effect: allow
|
|
418
|
+
conditions: { roles: ["admin"] }
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
See **[`examples/acl_demo/`](examples/acl_demo/)** for a runnable FastAPI app
|
|
422
|
+
plus integration tests (`tests/test_acl_demo.py`).
|
|
423
|
+
|
|
397
424
|
### Observability
|
|
398
425
|
|
|
399
426
|
| Variable | Default | Description |
|
|
@@ -1,33 +1,3 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: fastapi-apcore
|
|
3
|
-
Version: 0.4.0
|
|
4
|
-
Summary: FastAPI integration for apcore AI-Perceivable Core — exposes FastAPI routes as apcore modules with auto-discovery, schema extraction from Pydantic models, and OpenAPI-based scanning.
|
|
5
|
-
Author-email: aiperceivable <team@aiperceivable.com>
|
|
6
|
-
License-Expression: Apache-2.0
|
|
7
|
-
Project-URL: Homepage, https://github.com/aiperceivable/
|
|
8
|
-
Project-URL: Repository, https://github.com/aiperceivable/fastapi-apcore
|
|
9
|
-
Keywords: fastapi,apcore,mcp,llm,ai,tools,pydantic,schema,module,cli,auto-discovery,integration
|
|
10
|
-
Requires-Python: >=3.11
|
|
11
|
-
Description-Content-Type: text/markdown
|
|
12
|
-
Requires-Dist: fastapi>=0.100
|
|
13
|
-
Requires-Dist: apcore>=0.14.0
|
|
14
|
-
Requires-Dist: apcore-toolkit>=0.4.1
|
|
15
|
-
Provides-Extra: mcp
|
|
16
|
-
Requires-Dist: apcore-mcp>=0.11.0; extra == "mcp"
|
|
17
|
-
Provides-Extra: cli
|
|
18
|
-
Requires-Dist: apcore-cli>=0.4.0; extra == "cli"
|
|
19
|
-
Requires-Dist: click>=8.0; extra == "cli"
|
|
20
|
-
Provides-Extra: all
|
|
21
|
-
Requires-Dist: fastapi-apcore[cli,mcp]; extra == "all"
|
|
22
|
-
Provides-Extra: dev
|
|
23
|
-
Requires-Dist: apdev[dev]>=0.2.3; extra == "dev"
|
|
24
|
-
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
25
|
-
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
26
|
-
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
27
|
-
Requires-Dist: ruff>=0.1; extra == "dev"
|
|
28
|
-
Requires-Dist: mypy>=1.0; extra == "dev"
|
|
29
|
-
Requires-Dist: coverage>=7.0; extra == "dev"
|
|
30
|
-
|
|
31
1
|
# fastapi-apcore
|
|
32
2
|
|
|
33
3
|
FastAPI integration for [apcore](https://github.com/aiperceivable/apcore-python) (AI-Perceivable Core). Expose your FastAPI routes as MCP tools with auto-discovery, Pydantic schema extraction, and built-in observability.
|
|
@@ -59,8 +29,10 @@ FastAPI integration for [apcore](https://github.com/aiperceivable/apcore-python)
|
|
|
59
29
|
|
|
60
30
|
- Python >= 3.11
|
|
61
31
|
- FastAPI >= 0.100
|
|
62
|
-
- apcore >= 0.
|
|
63
|
-
- apcore-toolkit >= 0.
|
|
32
|
+
- apcore >= 0.33.0
|
|
33
|
+
- apcore-toolkit >= 0.15.0
|
|
34
|
+
- apcore-mcp >= 0.23.4 (optional, `[mcp]` extra)
|
|
35
|
+
- apcore-cli >= 0.14.1 (optional, `[cli]` extra)
|
|
64
36
|
|
|
65
37
|
## Installation
|
|
66
38
|
|
|
@@ -331,6 +303,8 @@ if __name__ == "__main__":
|
|
|
331
303
|
|
|
332
304
|
Each scanned route becomes a CLI command named after `display.cli.alias` from the binding overlay (or the module_id if no overlay is set). The commands forward HTTP requests to the running API using `HTTPProxyRegistryWriter`. Built-in subcommands include `list`, `describe`, `completion`, and `man`.
|
|
333
305
|
|
|
306
|
+
`create_cli()` runs a proxy preflight by default (`validate_proxy=True`). It resolves inherited and referenced OpenAPI parameters through apcore-toolkit's effective-parameter scanner, then refuses to register any operation the HTTP proxy cannot forward losslessly — for example a query parameter on a JSON-body `POST`, a body on a query-method route, or conflicting path/query/body names. The error names every offending module. Pass `validate_proxy=False` to keep the legacy best-effort behaviour. Native scanning (`scan_source="native"`) skips this check because it has no OpenAPI document to resolve against.
|
|
307
|
+
|
|
334
308
|
`commands_dir` points to a directory of plain Python function files. When set, `ConventionScanner` from `apcore-toolkit` scans for public functions and registers them as additional modules alongside the scanned API routes (§5.14).
|
|
335
309
|
|
|
336
310
|
### Display Overlay (`binding_path`)
|
|
@@ -394,6 +368,29 @@ All settings are read from environment variables with the `APCORE_` prefix:
|
|
|
394
368
|
| `APCORE_ACL_PATH` | — | Path to ACL YAML rules file |
|
|
395
369
|
| `APCORE_MIDDLEWARES` | — | Comma-separated middleware dotted paths |
|
|
396
370
|
|
|
371
|
+
#### Access control (ACL)
|
|
372
|
+
|
|
373
|
+
Set `APCORE_ACL_PATH` to a YAML rules file and apcore enforces role-based
|
|
374
|
+
`allow`/`deny` on every module call. Roles come from the request's
|
|
375
|
+
authenticated user: `FastAPIContextFactory` reads `request.state.user`
|
|
376
|
+
(`roles` / `groups` / `scopes`) into the apcore `Identity` that ACL conditions
|
|
377
|
+
match against. A denied call raises `ACLDeniedError`, which your route maps to
|
|
378
|
+
HTTP 403.
|
|
379
|
+
|
|
380
|
+
```yaml
|
|
381
|
+
# acl.yaml
|
|
382
|
+
default_effect: deny
|
|
383
|
+
rules:
|
|
384
|
+
- description: Admins may call any module
|
|
385
|
+
callers: ["*"]
|
|
386
|
+
targets: ["*"]
|
|
387
|
+
effect: allow
|
|
388
|
+
conditions: { roles: ["admin"] }
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
See **[`examples/acl_demo/`](examples/acl_demo/)** for a runnable FastAPI app
|
|
392
|
+
plus integration tests (`tests/test_acl_demo.py`).
|
|
393
|
+
|
|
397
394
|
### Observability
|
|
398
395
|
|
|
399
396
|
| Variable | Default | Description |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "fastapi-apcore"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.6.0"
|
|
8
8
|
description = "FastAPI integration for apcore AI-Perceivable Core — exposes FastAPI routes as apcore modules with auto-discovery, schema extraction from Pydantic models, and OpenAPI-based scanning."
|
|
9
9
|
requires-python = ">=3.11"
|
|
10
10
|
readme = "README.md"
|
|
@@ -28,16 +28,16 @@ keywords = [
|
|
|
28
28
|
]
|
|
29
29
|
dependencies = [
|
|
30
30
|
"fastapi>=0.100",
|
|
31
|
-
"apcore>=0.
|
|
32
|
-
"apcore-toolkit>=0.
|
|
31
|
+
"apcore>=0.33.0",
|
|
32
|
+
"apcore-toolkit>=0.15.0",
|
|
33
33
|
]
|
|
34
34
|
|
|
35
35
|
[project.optional-dependencies]
|
|
36
|
-
mcp = ["apcore-mcp>=0.
|
|
37
|
-
cli = ["apcore-cli>=0.
|
|
36
|
+
mcp = ["apcore-mcp>=0.23.4"]
|
|
37
|
+
cli = ["apcore-cli>=0.14.1", "click>=8.0"]
|
|
38
38
|
all = ["fastapi-apcore[mcp,cli]"]
|
|
39
39
|
dev = [
|
|
40
|
-
"apdev[dev]>=0.2.
|
|
40
|
+
"apdev[dev]>=0.2.7",
|
|
41
41
|
"pytest>=7.0",
|
|
42
42
|
"pytest-asyncio>=0.21",
|
|
43
43
|
"httpx>=0.24",
|
|
@@ -64,6 +64,13 @@ src = ["src"]
|
|
|
64
64
|
target-version = "py311"
|
|
65
65
|
line-length = 120
|
|
66
66
|
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
# Pin the rule set explicitly. Ruff's implicit default selection changes between
|
|
69
|
+
# releases (0.16 widened it from E4/E7/E9/F to a much larger set), which made CI
|
|
70
|
+
# fail on a newer ruff while an older local ruff passed. Widening the selection
|
|
71
|
+
# is a deliberate change, not a side effect of upgrading the linter.
|
|
72
|
+
select = ["E4", "E7", "E9", "F"]
|
|
73
|
+
|
|
67
74
|
[tool.mypy]
|
|
68
75
|
python_version = "3.11"
|
|
69
76
|
strict = true
|
|
@@ -136,6 +136,12 @@ def create_cli() -> Any:
|
|
|
136
136
|
tags: str = typer.Option(None, "--tags", help="Comma-separated tags filter."),
|
|
137
137
|
prefix: str = typer.Option(None, "--prefix", help="Module ID prefix filter."),
|
|
138
138
|
log_level: str = typer.Option(None, "--log-level", help="Log level: DEBUG, INFO, WARNING, ERROR."),
|
|
139
|
+
policy: str = typer.Option(
|
|
140
|
+
None,
|
|
141
|
+
"--policy",
|
|
142
|
+
help="Path to an external governance policy YAML (marks requires_approval / destructive "
|
|
143
|
+
"on matching modules without touching the app's source).",
|
|
144
|
+
),
|
|
139
145
|
) -> None:
|
|
140
146
|
"""Start an MCP server exposing registered apcore modules as tools."""
|
|
141
147
|
app = _load_app(app_path)
|
|
@@ -144,7 +150,7 @@ def create_cli() -> Any:
|
|
|
144
150
|
from fastapi_apcore.client import FastAPIApcore
|
|
145
151
|
|
|
146
152
|
apcore = FastAPIApcore.get_instance()
|
|
147
|
-
apcore.init_app(app)
|
|
153
|
+
apcore.init_app(app, policy_path=policy)
|
|
148
154
|
|
|
149
155
|
from fastapi_apcore.engine.config import get_apcore_settings
|
|
150
156
|
from fastapi_apcore.engine.registry import get_executor, get_registry, get_metrics_collector
|
|
@@ -217,8 +223,11 @@ def create_cli() -> Any:
|
|
|
217
223
|
use_executor = bool(settings.middlewares or settings.acl_path or settings.executor_config)
|
|
218
224
|
registry_or_executor = get_executor() if use_executor else registry
|
|
219
225
|
|
|
220
|
-
|
|
221
|
-
|
|
226
|
+
# Diagnostics MUST go to stderr: under the stdio transport, stdout is the
|
|
227
|
+
# MCP JSON-RPC stream and any stray text corrupts it (strict clients like
|
|
228
|
+
# Claude Desktop reject the whole stream).
|
|
229
|
+
typer.echo(f"[fastapi-apcore] Starting MCP server '{name}' via {transport}...", err=True)
|
|
230
|
+
typer.echo(f"[fastapi-apcore] {registry.count} modules registered.", err=True)
|
|
222
231
|
|
|
223
232
|
try:
|
|
224
233
|
from apcore_mcp import serve as mcp_serve
|
|
@@ -339,6 +348,8 @@ def create_cli() -> Any:
|
|
|
339
348
|
max_age: int = typer.Option(None, "--max-age", help="Max age in seconds for completed tasks."),
|
|
340
349
|
) -> None:
|
|
341
350
|
"""Clean up old completed tasks."""
|
|
351
|
+
import asyncio
|
|
352
|
+
|
|
342
353
|
from fastapi_apcore.engine.config import get_apcore_settings
|
|
343
354
|
from fastapi_apcore.engine.tasks import get_task_manager
|
|
344
355
|
|
|
@@ -346,7 +357,8 @@ def create_cli() -> Any:
|
|
|
346
357
|
max_age = get_apcore_settings().task_cleanup_age
|
|
347
358
|
|
|
348
359
|
tm = get_task_manager()
|
|
349
|
-
|
|
360
|
+
# apcore >= 0.22 made AsyncTaskManager.cleanup() a coroutine.
|
|
361
|
+
count = asyncio.run(tm.cleanup(max_age_seconds=max_age))
|
|
350
362
|
typer.echo(f"Cleaned up {count} tasks.")
|
|
351
363
|
|
|
352
364
|
return cli
|
|
@@ -73,6 +73,7 @@ class FastAPIApcore:
|
|
|
73
73
|
simplify_ids: bool = False,
|
|
74
74
|
include: str | None = None,
|
|
75
75
|
exclude: str | None = None,
|
|
76
|
+
policy_path: str | None = None,
|
|
76
77
|
) -> None:
|
|
77
78
|
"""Initialize fastapi-apcore with a FastAPI application.
|
|
78
79
|
|
|
@@ -117,6 +118,14 @@ class FastAPIApcore:
|
|
|
117
118
|
from fastapi_apcore.output import get_writer
|
|
118
119
|
|
|
119
120
|
scanned = self.scan(app, source=scan_source, simplify_ids=simplify_ids, include=include, exclude=exclude)
|
|
121
|
+
# Apply external governance policy (marks requires_approval /
|
|
122
|
+
# destructive) before registration so approval gating reflects the
|
|
123
|
+
# operator's decision — without modifying the target app's source.
|
|
124
|
+
effective_policy = policy_path or getattr(settings, "policy_path", None)
|
|
125
|
+
if scanned and effective_policy:
|
|
126
|
+
from fastapi_apcore.governance import apply_policy, load_policy
|
|
127
|
+
|
|
128
|
+
scanned = apply_policy(scanned, load_policy(effective_policy))
|
|
120
129
|
if scanned:
|
|
121
130
|
writer = get_writer(None) # RegistryWriter
|
|
122
131
|
writer.write(scanned, registry)
|
|
@@ -594,6 +603,7 @@ class FastAPIApcore:
|
|
|
594
603
|
max_content_width: int | None = None,
|
|
595
604
|
docs_url: str | None = None,
|
|
596
605
|
verbose_help: bool = False,
|
|
606
|
+
validate_proxy: bool = True,
|
|
597
607
|
) -> Any:
|
|
598
608
|
"""Create an apcore-cli Click group with all API routes as commands.
|
|
599
609
|
|
|
@@ -634,6 +644,13 @@ class FastAPIApcore:
|
|
|
634
644
|
(``--input``, ``--yes``, ``--large-input``, ``--format``) in
|
|
635
645
|
``--help`` output. Defaults to ``False`` (hidden). Users can
|
|
636
646
|
also toggle this at runtime with the ``--verbose`` flag.
|
|
647
|
+
validate_proxy: When ``True`` (default) and ``scan_source="openapi"``,
|
|
648
|
+
resolve inherited OpenAPI parameters through apcore-toolkit's
|
|
649
|
+
effective-parameter scanner and refuse to register operations
|
|
650
|
+
that cannot be forwarded losslessly (for example a query
|
|
651
|
+
parameter on a JSON-body method). Set ``False`` to keep the
|
|
652
|
+
legacy best-effort proxy. Native scanning skips this check
|
|
653
|
+
because it has no OpenAPI document to resolve against.
|
|
637
654
|
|
|
638
655
|
Returns:
|
|
639
656
|
A Click Group that can be invoked with ``cli(standalone_mode=True)``.
|
|
@@ -656,7 +673,7 @@ class FastAPIApcore:
|
|
|
656
673
|
import click
|
|
657
674
|
from apcore_cli.cli import GroupedModuleGroup, set_docs_url, set_verbose_help
|
|
658
675
|
from apcore_cli.discovery import register_discovery_commands
|
|
659
|
-
from apcore_cli.shell import configure_man_help,
|
|
676
|
+
from apcore_cli.shell import configure_man_help, register_completion_command
|
|
660
677
|
except ImportError:
|
|
661
678
|
raise ImportError(
|
|
662
679
|
"apcore-cli is required for create_cli(). " "Install with: pip install fastapi-apcore[cli]"
|
|
@@ -696,6 +713,27 @@ class FastAPIApcore:
|
|
|
696
713
|
|
|
697
714
|
modules = DisplayResolver().resolve(modules, binding_path=binding_path)
|
|
698
715
|
|
|
716
|
+
# 1c. Resolve effective OpenAPI inputs and reject operations the HTTP
|
|
717
|
+
# proxy cannot forward losslessly. The writer switches to effective
|
|
718
|
+
# forwarding only when ``proxy_inputs`` metadata is present.
|
|
719
|
+
if validate_proxy and scan_source == "openapi" and modules:
|
|
720
|
+
from apcore_toolkit import validate_effective_proxy_modules
|
|
721
|
+
|
|
722
|
+
from fastapi_apcore.scanners.openapi import apply_effective_proxy_inputs
|
|
723
|
+
|
|
724
|
+
spec = app.openapi()
|
|
725
|
+
if not isinstance(spec, dict):
|
|
726
|
+
logger.warning(
|
|
727
|
+
"create_cli: app.openapi() did not return an OpenAPI document; "
|
|
728
|
+
"skipping proxy preflight"
|
|
729
|
+
)
|
|
730
|
+
else:
|
|
731
|
+
modules = apply_effective_proxy_inputs(modules, spec)
|
|
732
|
+
try:
|
|
733
|
+
validate_effective_proxy_modules(modules)
|
|
734
|
+
except ValueError as exc:
|
|
735
|
+
raise ValueError(f"create_cli() proxy preflight failed: {exc}") from exc
|
|
736
|
+
|
|
699
737
|
# 2. Register as HTTP proxy modules
|
|
700
738
|
registry = Registry()
|
|
701
739
|
writer = HTTPProxyRegistryWriter(
|
|
@@ -724,7 +762,14 @@ class FastAPIApcore:
|
|
|
724
762
|
ctx_settings["max_content_width"] = max_content_width
|
|
725
763
|
|
|
726
764
|
effective_width = max_content_width
|
|
727
|
-
_cli_description =
|
|
765
|
+
_cli_description = (
|
|
766
|
+
f"{prog_name} — CLI for {app.title or 'FastAPI'} API.\n\n"
|
|
767
|
+
"Tips:\n"
|
|
768
|
+
f" {prog_name} --help --verbose Show all options including built-in apcore flags\n"
|
|
769
|
+
f" {prog_name} --help --man Generate a full roff man page for all commands\n"
|
|
770
|
+
f" {prog_name} list List all available commands\n"
|
|
771
|
+
f" {prog_name} describe MODULE_ID Show schema and annotations for a command"
|
|
772
|
+
)
|
|
728
773
|
|
|
729
774
|
@click.group(
|
|
730
775
|
cls=GroupedModuleGroup,
|
|
@@ -764,7 +809,7 @@ class FastAPIApcore:
|
|
|
764
809
|
set_verbose_help(True)
|
|
765
810
|
|
|
766
811
|
register_discovery_commands(cli, registry)
|
|
767
|
-
|
|
812
|
+
register_completion_command(cli, prog_name=prog_name)
|
|
768
813
|
|
|
769
814
|
# Enable --help --man to generate a full roff man page covering all commands.
|
|
770
815
|
configure_man_help(
|
|
@@ -80,10 +80,18 @@ class FastAPIDiscoverer:
|
|
|
80
80
|
func=flattened,
|
|
81
81
|
module_id=fm.module_id,
|
|
82
82
|
description=fm.description,
|
|
83
|
+
documentation=getattr(fm, "documentation", None),
|
|
83
84
|
tags=fm.tags,
|
|
84
85
|
version=fm.version,
|
|
86
|
+
annotations=getattr(fm, "annotations", None),
|
|
87
|
+
metadata=getattr(fm, "metadata", None),
|
|
88
|
+
display=getattr(fm, "display", None),
|
|
89
|
+
examples=getattr(fm, "examples", None),
|
|
85
90
|
input_schema=fm.input_schema,
|
|
86
91
|
output_schema=fm.output_schema,
|
|
92
|
+
# apcore 0.33.0 added resources (e.g. a per-module
|
|
93
|
+
# timeout); rebuilding the module must not drop it.
|
|
94
|
+
resources=getattr(fm, "resources", None),
|
|
87
95
|
)
|
|
88
96
|
except (ImportError, AttributeError):
|
|
89
97
|
pass
|
|
@@ -116,9 +116,13 @@ def cancellable_call(
|
|
|
116
116
|
if context is None:
|
|
117
117
|
if request is not None:
|
|
118
118
|
context = get_context_factory().create_context(request)
|
|
119
|
+
context.cancel_token = token
|
|
119
120
|
else:
|
|
120
|
-
|
|
121
|
-
|
|
121
|
+
# apcore >= 0.22 exposes cancel_token as a first-class Context.create()
|
|
122
|
+
# parameter, replacing the post-hoc `context.cancel_token = token` anti-pattern.
|
|
123
|
+
context = Context.create(cancel_token=token)
|
|
124
|
+
else:
|
|
125
|
+
context.cancel_token = token
|
|
122
126
|
|
|
123
127
|
if timeout is None:
|
|
124
128
|
timeout = get_apcore_settings().cancel_default_timeout
|
|
@@ -158,9 +162,13 @@ async def cancellable_call_async(
|
|
|
158
162
|
if context is None:
|
|
159
163
|
if request is not None:
|
|
160
164
|
context = get_context_factory().create_context(request)
|
|
165
|
+
context.cancel_token = token
|
|
161
166
|
else:
|
|
162
|
-
|
|
163
|
-
|
|
167
|
+
# apcore >= 0.22 exposes cancel_token as a first-class Context.create()
|
|
168
|
+
# parameter, replacing the post-hoc `context.cancel_token = token` anti-pattern.
|
|
169
|
+
context = Context.create(cancel_token=token)
|
|
170
|
+
else:
|
|
171
|
+
context.cancel_token = token
|
|
164
172
|
|
|
165
173
|
if timeout is None:
|
|
166
174
|
timeout = get_apcore_settings().cancel_default_timeout
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""External governance policy for scanned modules.
|
|
2
|
+
|
|
3
|
+
Behavioral annotations inferred from HTTP method (``GET`` -> readonly,
|
|
4
|
+
``DELETE`` -> destructive) never set ``requires_approval`` -- and a money-moving
|
|
5
|
+
``POST`` (e.g. ``/refund``) is not even flagged destructive. Deciding *what needs
|
|
6
|
+
human approval* is a governance choice, not something a heuristic can infer.
|
|
7
|
+
|
|
8
|
+
This module lets an operator declare that choice in an **external policy file**,
|
|
9
|
+
applied to scanned modules **without touching the target application's source**
|
|
10
|
+
(the outside-in governance model). A policy is a mapping::
|
|
11
|
+
|
|
12
|
+
# governance.yaml
|
|
13
|
+
require_approval: # module_id glob patterns -> requires_approval=True
|
|
14
|
+
- "*delete*"
|
|
15
|
+
- "*refund*"
|
|
16
|
+
mark_destructive: # module_id glob patterns -> destructive=True (optional)
|
|
17
|
+
- "*refund*"
|
|
18
|
+
|
|
19
|
+
Patterns are matched against each module's ``module_id`` with :func:`fnmatch.fnmatch`.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import dataclasses
|
|
25
|
+
import logging
|
|
26
|
+
from fnmatch import fnmatch
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from apcore import ModuleAnnotations
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger("fastapi_apcore")
|
|
33
|
+
|
|
34
|
+
# Modules are typed ``Any``: fastapi-apcore's local ``scanners.base.ScannedModule``
|
|
35
|
+
# and the canonical ``apcore_toolkit.types.ScannedModule`` have drifted into two
|
|
36
|
+
# distinct dataclasses. Policy application is duck-typed on the ``module_id`` and
|
|
37
|
+
# ``annotations`` fields, which both variants share.
|
|
38
|
+
|
|
39
|
+
_PATTERN_KEYS = ("require_approval", "mark_destructive")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_policy(path: str | Path) -> dict[str, Any]:
|
|
43
|
+
"""Load a governance policy from a YAML file.
|
|
44
|
+
|
|
45
|
+
Returns an empty policy (no-op) if the path does not exist so callers can
|
|
46
|
+
pass a conventional default path unconditionally.
|
|
47
|
+
"""
|
|
48
|
+
p = Path(path)
|
|
49
|
+
if not p.exists():
|
|
50
|
+
logger.warning("Governance policy not found at %s; no rules applied.", p)
|
|
51
|
+
return {}
|
|
52
|
+
import yaml
|
|
53
|
+
|
|
54
|
+
data = yaml.safe_load(p.read_text()) or {}
|
|
55
|
+
if not isinstance(data, dict):
|
|
56
|
+
raise ValueError(f"Governance policy at {p} must be a mapping, got {type(data).__name__}.")
|
|
57
|
+
return data
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _matches(module_id: str, patterns: Any) -> bool:
|
|
61
|
+
if not isinstance(patterns, (list, tuple)):
|
|
62
|
+
return False
|
|
63
|
+
return any(isinstance(pat, str) and fnmatch(module_id, pat) for pat in patterns)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def apply_policy(modules: list[Any], policy: dict[str, Any]) -> list[Any]:
|
|
67
|
+
"""Return ``modules`` with annotations updated per ``policy``.
|
|
68
|
+
|
|
69
|
+
Sets ``requires_approval=True`` on modules whose ``module_id`` matches any
|
|
70
|
+
``require_approval`` pattern, and ``destructive=True`` for ``mark_destructive``.
|
|
71
|
+
Modules that match nothing are returned unchanged. Emits an INFO line per
|
|
72
|
+
change so the governance decision is auditable at startup.
|
|
73
|
+
"""
|
|
74
|
+
if not policy:
|
|
75
|
+
return modules
|
|
76
|
+
|
|
77
|
+
require_approval = policy.get("require_approval")
|
|
78
|
+
mark_destructive = policy.get("mark_destructive")
|
|
79
|
+
unknown = [k for k in policy if k not in _PATTERN_KEYS]
|
|
80
|
+
if unknown:
|
|
81
|
+
logger.warning("Governance policy: ignoring unknown keys %s", unknown)
|
|
82
|
+
|
|
83
|
+
result: list[Any] = []
|
|
84
|
+
for mod in modules:
|
|
85
|
+
needs_approval = _matches(mod.module_id, require_approval)
|
|
86
|
+
make_destructive = _matches(mod.module_id, mark_destructive)
|
|
87
|
+
if not (needs_approval or make_destructive):
|
|
88
|
+
result.append(mod)
|
|
89
|
+
continue
|
|
90
|
+
|
|
91
|
+
base = mod.annotations if isinstance(mod.annotations, ModuleAnnotations) else ModuleAnnotations()
|
|
92
|
+
changes: dict[str, bool] = {}
|
|
93
|
+
if needs_approval and not base.requires_approval:
|
|
94
|
+
changes["requires_approval"] = True
|
|
95
|
+
if make_destructive and not base.destructive:
|
|
96
|
+
changes["destructive"] = True
|
|
97
|
+
if not changes:
|
|
98
|
+
result.append(mod)
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
new_ann = dataclasses.replace(base, **changes)
|
|
102
|
+
result.append(dataclasses.replace(mod, annotations=new_ann))
|
|
103
|
+
logger.info("Governance: %s -> %s", mod.module_id, ", ".join(f"{k}=True" for k in changes))
|
|
104
|
+
|
|
105
|
+
return result
|
|
@@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any
|
|
|
13
13
|
from apcore_toolkit.output.registry_writer import RegistryWriter
|
|
14
14
|
|
|
15
15
|
if TYPE_CHECKING:
|
|
16
|
-
from apcore import FunctionModule
|
|
17
16
|
from apcore_toolkit.types import ScannedModule
|
|
18
17
|
|
|
19
18
|
logger = logging.getLogger("fastapi_apcore")
|
|
@@ -36,6 +35,7 @@ class FastAPIRegistryWriter(RegistryWriter):
|
|
|
36
35
|
dry_run: bool = False,
|
|
37
36
|
verify: bool = False,
|
|
38
37
|
verifiers: Any = None,
|
|
38
|
+
allowed_prefixes: list[str] | None = None,
|
|
39
39
|
) -> list[Any]:
|
|
40
40
|
from apcore_toolkit.output.types import WriteResult
|
|
41
41
|
from apcore_toolkit.output.verifiers import RegistryVerifier, run_verifier_chain
|
|
@@ -46,7 +46,7 @@ class FastAPIRegistryWriter(RegistryWriter):
|
|
|
46
46
|
results.append(WriteResult(module_id=mod.module_id))
|
|
47
47
|
continue
|
|
48
48
|
|
|
49
|
-
fm = self._to_function_module(mod)
|
|
49
|
+
fm = self._to_function_module(mod, allowed_prefixes=allowed_prefixes)
|
|
50
50
|
with contextlib.suppress(KeyError, ValueError):
|
|
51
51
|
registry.unregister(mod.module_id)
|
|
52
52
|
registry.register(mod.module_id, fm)
|
|
@@ -73,32 +73,21 @@ class FastAPIRegistryWriter(RegistryWriter):
|
|
|
73
73
|
results.append(result)
|
|
74
74
|
return results
|
|
75
75
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
output_model = _schema_to_pydantic(f"{mod.module_id}_Output", mod.output_schema)
|
|
92
|
-
|
|
93
|
-
return FuncModule(
|
|
94
|
-
func=func,
|
|
95
|
-
module_id=mod.module_id,
|
|
96
|
-
description=mod.description,
|
|
97
|
-
tags=mod.tags,
|
|
98
|
-
version=mod.version,
|
|
99
|
-
input_schema=input_model,
|
|
100
|
-
output_schema=output_model,
|
|
101
|
-
)
|
|
76
|
+
# NOTE: this writer no longer overrides ``_to_function_module``. Doing so
|
|
77
|
+
# previously dropped ``annotations``, silently disabling approval/ACL gating
|
|
78
|
+
# (that keys on ``requires_approval``) for scanned routes. Field mapping —
|
|
79
|
+
# including annotations — is now centralized in the toolkit base writer's
|
|
80
|
+
# ``_build_function_module``; here we override only the narrow schema hooks.
|
|
81
|
+
|
|
82
|
+
def _build_input_schema(self, mod: ScannedModule) -> Any:
|
|
83
|
+
"""Build an explicit input model from the scanned OpenAPI/Pydantic schema
|
|
84
|
+
so ``FunctionModule`` skips function introspection."""
|
|
85
|
+
return _schema_to_pydantic(f"{mod.module_id}_Input", mod.input_schema)
|
|
86
|
+
|
|
87
|
+
def _build_output_schema(self, mod: ScannedModule) -> Any:
|
|
88
|
+
"""Build an explicit output model from the scanned schema. See
|
|
89
|
+
:meth:`_build_input_schema`."""
|
|
90
|
+
return _schema_to_pydantic(f"{mod.module_id}_Output", mod.output_schema)
|
|
102
91
|
|
|
103
92
|
|
|
104
93
|
_JSON_TYPE_MAP: dict[str, type] = {
|