amv-sentinel 2.7.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.
- amv_sentinel-2.7.0/PKG-INFO +166 -0
- amv_sentinel-2.7.0/README.md +116 -0
- amv_sentinel-2.7.0/pyproject.toml +92 -0
- amv_sentinel-2.7.0/setup.cfg +4 -0
- amv_sentinel-2.7.0/src/amv_sentinel/__init__.py +399 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/admin_api.py +212 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/admin_ui.py +228 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/asgi.py +136 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/dashboard.py +622 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/enforcement.py +266 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/fastapi.py +26 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/risk_asgi.py +228 -0
- amv_sentinel-2.7.0/src/amv_sentinel/adapters/wsgi.py +124 -0
- amv_sentinel-2.7.0/src/amv_sentinel/admin_access.py +87 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/aggregator.py +51 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/bot_classifier.py +207 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/bot_inventory.py +748 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/budget_types.py +355 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/canonical.py +139 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/confidence.py +50 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/crawler_policy.py +373 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/evaluator.py +589 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/geo_registry.py +181 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/geo_resolver.py +177 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/guards.py +224 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/local_store.py +161 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/policy_registry.py +78 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/protocols.py +34 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/redaction.py +44 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/risk_guard.py +326 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/risk_options.py +322 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/rules.py +260 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/sentinel_counter.py +98 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/sentinel_engine.py +167 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/sentinel_policy.py +53 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/sentinel_types.py +147 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/shared_counter.py +241 -0
- amv_sentinel-2.7.0/src/amv_sentinel/core/verified_bot.py +775 -0
- amv_sentinel-2.7.0/src/amv_sentinel/data/verified_bots.json +119 -0
- amv_sentinel-2.7.0/src/amv_sentinel/integrations/sqlalchemy_postgres.py +56 -0
- amv_sentinel-2.7.0/src/amv_sentinel/observability.py +91 -0
- amv_sentinel-2.7.0/src/amv_sentinel/privacy.py +33 -0
- amv_sentinel-2.7.0/src/amv_sentinel/providers.py +50 -0
- amv_sentinel-2.7.0/src/amv_sentinel/py.typed +1 -0
- amv_sentinel-2.7.0/src/amv_sentinel/trusted_proxy.py +318 -0
- amv_sentinel-2.7.0/src/amv_sentinel.egg-info/PKG-INFO +166 -0
- amv_sentinel-2.7.0/src/amv_sentinel.egg-info/SOURCES.txt +50 -0
- amv_sentinel-2.7.0/src/amv_sentinel.egg-info/dependency_links.txt +1 -0
- amv_sentinel-2.7.0/src/amv_sentinel.egg-info/requires.txt +36 -0
- amv_sentinel-2.7.0/src/amv_sentinel.egg-info/top_level.txt +1 -0
- amv_sentinel-2.7.0/tests/test_core.py +54 -0
- amv_sentinel-2.7.0/tests/test_engine.py +239 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: amv-sentinel
|
|
3
|
+
Version: 2.7.0
|
|
4
|
+
Summary: Deterministic Cost-Aware Policy Guardrails and Risk Observation SDK for Python
|
|
5
|
+
Author: AMEVA Engineering Team
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://ameva.pro/lib/sentinel/
|
|
8
|
+
Project-URL: Documentation, https://ameva.pro/lib/sentinel/
|
|
9
|
+
Project-URL: Repository, https://github.com/uno-km/ameva-sentinel
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Security
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: pydantic<3,>=2.7
|
|
22
|
+
Requires-Dist: typing-extensions>=4.6.0
|
|
23
|
+
Provides-Extra: redis
|
|
24
|
+
Requires-Dist: redis<6.0.0,>=5.0.0; extra == "redis"
|
|
25
|
+
Provides-Extra: fastapi
|
|
26
|
+
Requires-Dist: fastapi<1.0.0,>=0.110.0; extra == "fastapi"
|
|
27
|
+
Requires-Dist: starlette<1.0.0,>=0.36.0; extra == "fastapi"
|
|
28
|
+
Provides-Extra: flask
|
|
29
|
+
Requires-Dist: flask<4.0.0,>=2.3.0; extra == "flask"
|
|
30
|
+
Provides-Extra: sqlalchemy
|
|
31
|
+
Requires-Dist: sqlalchemy<3.0.0,>=2.0.0; extra == "sqlalchemy"
|
|
32
|
+
Provides-Extra: yaml
|
|
33
|
+
Requires-Dist: pyyaml<7.0.0,>=6.0.1; extra == "yaml"
|
|
34
|
+
Provides-Extra: all
|
|
35
|
+
Requires-Dist: redis<6.0.0,>=5.0.0; extra == "all"
|
|
36
|
+
Requires-Dist: fastapi<1.0.0,>=0.110.0; extra == "all"
|
|
37
|
+
Requires-Dist: starlette<1.0.0,>=0.36.0; extra == "all"
|
|
38
|
+
Requires-Dist: flask<4.0.0,>=2.3.0; extra == "all"
|
|
39
|
+
Requires-Dist: sqlalchemy<3.0.0,>=2.0.0; extra == "all"
|
|
40
|
+
Requires-Dist: pyyaml<7.0.0,>=6.0.1; extra == "all"
|
|
41
|
+
Provides-Extra: test
|
|
42
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
43
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
44
|
+
Requires-Dist: httpx>=0.27.0; extra == "test"
|
|
45
|
+
Requires-Dist: redis>=5.0.0; extra == "test"
|
|
46
|
+
Requires-Dist: fastapi>=0.110.0; extra == "test"
|
|
47
|
+
Requires-Dist: flask>=2.3.0; extra == "test"
|
|
48
|
+
Requires-Dist: sqlalchemy>=2.0.0; extra == "test"
|
|
49
|
+
Requires-Dist: pyyaml>=6.0.1; extra == "test"
|
|
50
|
+
|
|
51
|
+
# amv-sentinel (Python)
|
|
52
|
+
|
|
53
|
+
**Bot classification and risk scoring for Python backends — engine parity with the TypeScript SDK.**
|
|
54
|
+
|
|
55
|
+
This is a from-scratch Python port of `amv-sentinel-risk-core`'s engine: the same 8-rule risk scoring pipeline, the same `SentinelAction` values (`ALLOW`/`OBSERVE`/`RATE_LIMIT`/`REQUIRE_APP_VERIFICATION`/`TEMPORARY_DENY`/`REDIRECT`/`DEGRADED_ALLOW`, confirmed character-for-character identical strings to the TypeScript enum for cross-language JSON compatibility), and the same 43-signature bot classifier that correctly identifies `GPTBot` as `OpenAI`, `ClaudeBot` as `Anthropic`, and 41 more search engines, AI agents, social-preview bots, monitors, feed fetchers, and scripting clients — backed by 58 passing tests.
|
|
56
|
+
|
|
57
|
+
## Install
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install amv-sentinel
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Quickstart
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from amv_sentinel import evaluate_risk, classify_bot, TelemetrySignals
|
|
67
|
+
|
|
68
|
+
# Direct classification
|
|
69
|
+
classification = classify_bot("GPTBot/1.1 (+https://openai.com/gptbot)")
|
|
70
|
+
# -> category='AI_AGENT', vendor_group='OpenAI', name='GPTBot'
|
|
71
|
+
|
|
72
|
+
# Full risk evaluation
|
|
73
|
+
signals = TelemetrySignals(user_agent=request.headers.get("user-agent"))
|
|
74
|
+
report = evaluate_risk(signals, enforcement_mode="ENFORCE")
|
|
75
|
+
|
|
76
|
+
if report.action == "TEMPORARY_DENY":
|
|
77
|
+
return Response(status_code=403)
|
|
78
|
+
if report.action == "RATE_LIMIT":
|
|
79
|
+
return Response(status_code=429)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## What's in the box
|
|
83
|
+
|
|
84
|
+
- `evaluate_risk()` / `evaluate_risk_now()` — the main entry point. Classifies the UA, runs the policy's rules, clamps the score 0–100, applies the threshold ladder, returns a `SentinelRiskReport`.
|
|
85
|
+
- `classify_bot()` — standalone bot classification, no scoring, if that's all you need.
|
|
86
|
+
- `rules` — the 8 built-in rules (`webdriver`, `burst`, `trusted_input_absent`, `touch_mismatch`, `suspicious_ua`, `bot_classification`, `headless_deep`, `http_missing_headers`), usable individually or via `create_policy()`.
|
|
87
|
+
- `MemoryFixedWindowCounterStore` — bounded in-memory burst counter (capacity-limited, evicts oldest entries rather than growing unbounded).
|
|
88
|
+
- `resolve_admin_access()` — view-only-by-default admin dashboard access gating (no token configured → viewable, read-only; matching token → full access).
|
|
89
|
+
|
|
90
|
+
## Honest status
|
|
91
|
+
|
|
92
|
+
This engine was built to close a real gap: an earlier version of this package only had a 90-line stub with three hardcoded `if`/`elif` branches, not a real rules/policy pipeline. What ships now is a complete, independently-tested port — but it does not yet include the `sv1.*` collector-token verification scheme or `GeoDeliveryEngine`/forensic-analytics aggregation that the TypeScript side has; those are still TypeScript-only as of this release.
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
Apache-2.0 © 2026 AMEVA Open Source Ecosystem.
|
|
96
|
+
|
|
97
|
+
## Request risk guard (FastAPI / ASGI)
|
|
98
|
+
|
|
99
|
+
`SentinelRiskMiddleware` classifies every HTTP request (User-Agent + request rate), scores it with the sentinel rules and either records
|
|
100
|
+
the verdict (`mode="observe"`, default) or blocks automated traffic (`mode="enforce"`: 403 / 429). Search engines, AI crawlers, link previews
|
|
101
|
+
and monitors are exempt from blocking by default (`allow_categories`).
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from amv_sentinel import SentinelRiskMiddleware
|
|
105
|
+
|
|
106
|
+
app.add_middleware(
|
|
107
|
+
SentinelRiskMiddleware,
|
|
108
|
+
options_provider=load_options, # async () -> dict | None (None = defaults); validated with validate_risk_options
|
|
109
|
+
recorder=record_decision, # optional async (decision, request_info, options)
|
|
110
|
+
scope_filter=lambda p: p.startswith("/api/"),
|
|
111
|
+
)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Never takes the host down: option, evaluation and recording failures pass the request through and call `on_error`.
|
|
115
|
+
Limits: the User-Agent can be forged; the rate counter is per process unless you pass a shared counter to `RiskGuard` (see below).
|
|
116
|
+
|
|
117
|
+
### 2.6 additions
|
|
118
|
+
|
|
119
|
+
**Shared counter with a local pre-filter.** `RedisFixedWindowCounterStore` takes any `redis.asyncio`-compatible client (duck typed;
|
|
120
|
+
`redis` stays an optional dependency) and increments with one Lua script (`INCRBY`, `PEXPIRE` on the first increment of a window).
|
|
121
|
+
`PrefilteredAsyncCounter` counts in local memory first and only pushes to Redis once a client's local count reaches
|
|
122
|
+
`prefilter_ratio` (default 0.25) of the burst threshold, or immediately for automated-tool / unknown-bot UAs. Each request is pushed
|
|
123
|
+
once, so counts from several instances add up without double counting. A client spread over K instances can still send up to
|
|
124
|
+
K x (pre-filter point - 1) requests per window unnoticed; `prefilter_ratio=0` consults Redis on every request.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from amv_sentinel import PrefilteredAsyncCounter, RedisFixedWindowCounterStore, RiskGuard
|
|
128
|
+
|
|
129
|
+
guard = RiskGuard(async_counter=PrefilteredAsyncCounter(RedisFixedWindowCounterStore(redis_client), prefilter_ratio=0.25))
|
|
130
|
+
app.add_middleware(SentinelRiskMiddleware, options_provider=load_options, guard=guard, on_error=log_error)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
If Redis fails the request is evaluated with the local count, the decision carries `counter_degraded=True` /
|
|
134
|
+
`counter_error="AMU_WARN_SENTINEL_COUNTER: <type>"` and `on_error("counter", exc)` is called - the failure is reported, not hidden.
|
|
135
|
+
The synchronous `RiskGuard.evaluate` is unchanged; the middleware uses `RiskGuard.evaluate_async`.
|
|
136
|
+
|
|
137
|
+
**Recording.** Blocked, suspect (score >= `rate_limit_score` x `suspect_ratio`, default 0.5) and SPOOFED requests are recorded before
|
|
138
|
+
the response. Ordinary requests are sampled 1 in `sample_every` (default 20) and recorded with `RiskRequestInfo.weight = sample_every`;
|
|
139
|
+
estimate totals as the sum of weights. The decision is available to the app as `scope["state"]["sentinel"]` (`request.state.sentinel`).
|
|
140
|
+
|
|
141
|
+
**Per-path policies.** `policies` maps a path prefix to overrides of `mode`, the score thresholds, `burst_threshold`, the weights,
|
|
142
|
+
`allow_categories`, `allowed_bot_rate_limit_multiplier`, `spoofed_weight` and `suspect_ratio`; the longest prefix wins (max 20
|
|
143
|
+
entries; unknown or nested keys are rejected with `AMU_ERR_RISK_OPTIONS`). Example: `{"/api/v1/rag/chat": {"mode": "enforce"}}`
|
|
144
|
+
enforces on the chat prefix only.
|
|
145
|
+
|
|
146
|
+
**Allowed crawlers.** `allowed_bot_rate_limit_multiplier` = N >= 2 gives the `allow_categories` their own burst cap of
|
|
147
|
+
`burst_threshold` x N; above it they get 429 with `Retry-After` (never 403). The default 1 keeps the previous behaviour (never blocked).
|
|
148
|
+
|
|
149
|
+
**Verified-bot verdict.** `evaluate` / `evaluate_async` accept `bot_verification` (`NA` / `VERIFIED` / `SPOOFED` / `UNVERIFIED`);
|
|
150
|
+
the middleware takes it from an optional `bot_verifier(scope, headers)`. `SPOOFED` adds `spoofed_weight` (default 40, rule
|
|
151
|
+
`bot.spoofed_bot`) and removes the allow-category exemption; the other values do not change the score. A verifier error is reported
|
|
152
|
+
as `on_error("verify", exc)` and evaluated as `NA`.
|
|
153
|
+
|
|
154
|
+
### 2.7 additions: bot inventory, per-bot rules, SEO/GEO files, admin UI
|
|
155
|
+
|
|
156
|
+
Know which bots visit, decide per bot, publish the same policy to crawlers, and manage it from a page you can mount in minutes.
|
|
157
|
+
|
|
158
|
+
- [Quickstart](docs/quickstart.md) - observe bots in ten lines, then move to blocking safely
|
|
159
|
+
- [Serverless and Redis](docs/serverless-redis.md) - shared counter, inventory and identity cache on multi-instance hosts, with command-count estimates
|
|
160
|
+
- [Storage and extension points](docs/storage.md) - every protocol, and how to back them with PostgreSQL or anything else
|
|
161
|
+
- [Bots, identity checks and rules](docs/bots-and-rules.md) - inventory, verified vs spoofed identity, rule precedence
|
|
162
|
+
- [SEO and GEO](docs/seo-geo.md) - generate robots.txt and llms.txt from your rules
|
|
163
|
+
- [Admin API and UI](docs/admin-ui.md) - ready-made router and single-file page; you provide authentication
|
|
164
|
+
- [Operations checklist](docs/operations.md) - what to check before enforcing, failure behaviour, known limits
|
|
165
|
+
|
|
166
|
+
The code blocks in these manuals are executed by the test-suite.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# amv-sentinel (Python)
|
|
2
|
+
|
|
3
|
+
**Bot classification and risk scoring for Python backends — engine parity with the TypeScript SDK.**
|
|
4
|
+
|
|
5
|
+
This is a from-scratch Python port of `amv-sentinel-risk-core`'s engine: the same 8-rule risk scoring pipeline, the same `SentinelAction` values (`ALLOW`/`OBSERVE`/`RATE_LIMIT`/`REQUIRE_APP_VERIFICATION`/`TEMPORARY_DENY`/`REDIRECT`/`DEGRADED_ALLOW`, confirmed character-for-character identical strings to the TypeScript enum for cross-language JSON compatibility), and the same 43-signature bot classifier that correctly identifies `GPTBot` as `OpenAI`, `ClaudeBot` as `Anthropic`, and 41 more search engines, AI agents, social-preview bots, monitors, feed fetchers, and scripting clients — backed by 58 passing tests.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install amv-sentinel
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quickstart
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from amv_sentinel import evaluate_risk, classify_bot, TelemetrySignals
|
|
17
|
+
|
|
18
|
+
# Direct classification
|
|
19
|
+
classification = classify_bot("GPTBot/1.1 (+https://openai.com/gptbot)")
|
|
20
|
+
# -> category='AI_AGENT', vendor_group='OpenAI', name='GPTBot'
|
|
21
|
+
|
|
22
|
+
# Full risk evaluation
|
|
23
|
+
signals = TelemetrySignals(user_agent=request.headers.get("user-agent"))
|
|
24
|
+
report = evaluate_risk(signals, enforcement_mode="ENFORCE")
|
|
25
|
+
|
|
26
|
+
if report.action == "TEMPORARY_DENY":
|
|
27
|
+
return Response(status_code=403)
|
|
28
|
+
if report.action == "RATE_LIMIT":
|
|
29
|
+
return Response(status_code=429)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## What's in the box
|
|
33
|
+
|
|
34
|
+
- `evaluate_risk()` / `evaluate_risk_now()` — the main entry point. Classifies the UA, runs the policy's rules, clamps the score 0–100, applies the threshold ladder, returns a `SentinelRiskReport`.
|
|
35
|
+
- `classify_bot()` — standalone bot classification, no scoring, if that's all you need.
|
|
36
|
+
- `rules` — the 8 built-in rules (`webdriver`, `burst`, `trusted_input_absent`, `touch_mismatch`, `suspicious_ua`, `bot_classification`, `headless_deep`, `http_missing_headers`), usable individually or via `create_policy()`.
|
|
37
|
+
- `MemoryFixedWindowCounterStore` — bounded in-memory burst counter (capacity-limited, evicts oldest entries rather than growing unbounded).
|
|
38
|
+
- `resolve_admin_access()` — view-only-by-default admin dashboard access gating (no token configured → viewable, read-only; matching token → full access).
|
|
39
|
+
|
|
40
|
+
## Honest status
|
|
41
|
+
|
|
42
|
+
This engine was built to close a real gap: an earlier version of this package only had a 90-line stub with three hardcoded `if`/`elif` branches, not a real rules/policy pipeline. What ships now is a complete, independently-tested port — but it does not yet include the `sv1.*` collector-token verification scheme or `GeoDeliveryEngine`/forensic-analytics aggregation that the TypeScript side has; those are still TypeScript-only as of this release.
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
Apache-2.0 © 2026 AMEVA Open Source Ecosystem.
|
|
46
|
+
|
|
47
|
+
## Request risk guard (FastAPI / ASGI)
|
|
48
|
+
|
|
49
|
+
`SentinelRiskMiddleware` classifies every HTTP request (User-Agent + request rate), scores it with the sentinel rules and either records
|
|
50
|
+
the verdict (`mode="observe"`, default) or blocks automated traffic (`mode="enforce"`: 403 / 429). Search engines, AI crawlers, link previews
|
|
51
|
+
and monitors are exempt from blocking by default (`allow_categories`).
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from amv_sentinel import SentinelRiskMiddleware
|
|
55
|
+
|
|
56
|
+
app.add_middleware(
|
|
57
|
+
SentinelRiskMiddleware,
|
|
58
|
+
options_provider=load_options, # async () -> dict | None (None = defaults); validated with validate_risk_options
|
|
59
|
+
recorder=record_decision, # optional async (decision, request_info, options)
|
|
60
|
+
scope_filter=lambda p: p.startswith("/api/"),
|
|
61
|
+
)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Never takes the host down: option, evaluation and recording failures pass the request through and call `on_error`.
|
|
65
|
+
Limits: the User-Agent can be forged; the rate counter is per process unless you pass a shared counter to `RiskGuard` (see below).
|
|
66
|
+
|
|
67
|
+
### 2.6 additions
|
|
68
|
+
|
|
69
|
+
**Shared counter with a local pre-filter.** `RedisFixedWindowCounterStore` takes any `redis.asyncio`-compatible client (duck typed;
|
|
70
|
+
`redis` stays an optional dependency) and increments with one Lua script (`INCRBY`, `PEXPIRE` on the first increment of a window).
|
|
71
|
+
`PrefilteredAsyncCounter` counts in local memory first and only pushes to Redis once a client's local count reaches
|
|
72
|
+
`prefilter_ratio` (default 0.25) of the burst threshold, or immediately for automated-tool / unknown-bot UAs. Each request is pushed
|
|
73
|
+
once, so counts from several instances add up without double counting. A client spread over K instances can still send up to
|
|
74
|
+
K x (pre-filter point - 1) requests per window unnoticed; `prefilter_ratio=0` consults Redis on every request.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from amv_sentinel import PrefilteredAsyncCounter, RedisFixedWindowCounterStore, RiskGuard
|
|
78
|
+
|
|
79
|
+
guard = RiskGuard(async_counter=PrefilteredAsyncCounter(RedisFixedWindowCounterStore(redis_client), prefilter_ratio=0.25))
|
|
80
|
+
app.add_middleware(SentinelRiskMiddleware, options_provider=load_options, guard=guard, on_error=log_error)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
If Redis fails the request is evaluated with the local count, the decision carries `counter_degraded=True` /
|
|
84
|
+
`counter_error="AMU_WARN_SENTINEL_COUNTER: <type>"` and `on_error("counter", exc)` is called - the failure is reported, not hidden.
|
|
85
|
+
The synchronous `RiskGuard.evaluate` is unchanged; the middleware uses `RiskGuard.evaluate_async`.
|
|
86
|
+
|
|
87
|
+
**Recording.** Blocked, suspect (score >= `rate_limit_score` x `suspect_ratio`, default 0.5) and SPOOFED requests are recorded before
|
|
88
|
+
the response. Ordinary requests are sampled 1 in `sample_every` (default 20) and recorded with `RiskRequestInfo.weight = sample_every`;
|
|
89
|
+
estimate totals as the sum of weights. The decision is available to the app as `scope["state"]["sentinel"]` (`request.state.sentinel`).
|
|
90
|
+
|
|
91
|
+
**Per-path policies.** `policies` maps a path prefix to overrides of `mode`, the score thresholds, `burst_threshold`, the weights,
|
|
92
|
+
`allow_categories`, `allowed_bot_rate_limit_multiplier`, `spoofed_weight` and `suspect_ratio`; the longest prefix wins (max 20
|
|
93
|
+
entries; unknown or nested keys are rejected with `AMU_ERR_RISK_OPTIONS`). Example: `{"/api/v1/rag/chat": {"mode": "enforce"}}`
|
|
94
|
+
enforces on the chat prefix only.
|
|
95
|
+
|
|
96
|
+
**Allowed crawlers.** `allowed_bot_rate_limit_multiplier` = N >= 2 gives the `allow_categories` their own burst cap of
|
|
97
|
+
`burst_threshold` x N; above it they get 429 with `Retry-After` (never 403). The default 1 keeps the previous behaviour (never blocked).
|
|
98
|
+
|
|
99
|
+
**Verified-bot verdict.** `evaluate` / `evaluate_async` accept `bot_verification` (`NA` / `VERIFIED` / `SPOOFED` / `UNVERIFIED`);
|
|
100
|
+
the middleware takes it from an optional `bot_verifier(scope, headers)`. `SPOOFED` adds `spoofed_weight` (default 40, rule
|
|
101
|
+
`bot.spoofed_bot`) and removes the allow-category exemption; the other values do not change the score. A verifier error is reported
|
|
102
|
+
as `on_error("verify", exc)` and evaluated as `NA`.
|
|
103
|
+
|
|
104
|
+
### 2.7 additions: bot inventory, per-bot rules, SEO/GEO files, admin UI
|
|
105
|
+
|
|
106
|
+
Know which bots visit, decide per bot, publish the same policy to crawlers, and manage it from a page you can mount in minutes.
|
|
107
|
+
|
|
108
|
+
- [Quickstart](docs/quickstart.md) - observe bots in ten lines, then move to blocking safely
|
|
109
|
+
- [Serverless and Redis](docs/serverless-redis.md) - shared counter, inventory and identity cache on multi-instance hosts, with command-count estimates
|
|
110
|
+
- [Storage and extension points](docs/storage.md) - every protocol, and how to back them with PostgreSQL or anything else
|
|
111
|
+
- [Bots, identity checks and rules](docs/bots-and-rules.md) - inventory, verified vs spoofed identity, rule precedence
|
|
112
|
+
- [SEO and GEO](docs/seo-geo.md) - generate robots.txt and llms.txt from your rules
|
|
113
|
+
- [Admin API and UI](docs/admin-ui.md) - ready-made router and single-file page; you provide authentication
|
|
114
|
+
- [Operations checklist](docs/operations.md) - what to check before enforcing, failure behaviour, known limits
|
|
115
|
+
|
|
116
|
+
The code blocks in these manuals are executed by the test-suite.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "amv-sentinel"
|
|
7
|
+
version = "2.7.0"
|
|
8
|
+
description = "Deterministic Cost-Aware Policy Guardrails and Risk Observation SDK for Python"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "AMEVA Engineering Team" }
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Topic :: Security",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"pydantic>=2.7,<3",
|
|
28
|
+
"typing-extensions>=4.6.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
redis = [
|
|
33
|
+
"redis>=5.0.0,<6.0.0",
|
|
34
|
+
]
|
|
35
|
+
fastapi = [
|
|
36
|
+
"fastapi>=0.110.0,<1.0.0",
|
|
37
|
+
"starlette>=0.36.0,<1.0.0",
|
|
38
|
+
]
|
|
39
|
+
flask = [
|
|
40
|
+
"flask>=2.3.0,<4.0.0",
|
|
41
|
+
]
|
|
42
|
+
sqlalchemy = [
|
|
43
|
+
"sqlalchemy>=2.0.0,<3.0.0",
|
|
44
|
+
]
|
|
45
|
+
yaml = [
|
|
46
|
+
"pyyaml>=6.0.1,<7.0.0",
|
|
47
|
+
]
|
|
48
|
+
all = [
|
|
49
|
+
"redis>=5.0.0,<6.0.0",
|
|
50
|
+
"fastapi>=0.110.0,<1.0.0",
|
|
51
|
+
"starlette>=0.36.0,<1.0.0",
|
|
52
|
+
"flask>=2.3.0,<4.0.0",
|
|
53
|
+
"sqlalchemy>=2.0.0,<3.0.0",
|
|
54
|
+
"pyyaml>=6.0.1,<7.0.0",
|
|
55
|
+
]
|
|
56
|
+
test = [
|
|
57
|
+
"pytest>=8.0.0",
|
|
58
|
+
"pytest-asyncio>=0.23.0",
|
|
59
|
+
"httpx>=0.27.0",
|
|
60
|
+
"redis>=5.0.0",
|
|
61
|
+
"fastapi>=0.110.0",
|
|
62
|
+
"flask>=2.3.0",
|
|
63
|
+
"sqlalchemy>=2.0.0",
|
|
64
|
+
"pyyaml>=6.0.1",
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
[tool.setuptools.packages.find]
|
|
68
|
+
where = ["src"]
|
|
69
|
+
|
|
70
|
+
[tool.setuptools.package-data]
|
|
71
|
+
"amv_sentinel" = ["py.typed", "data/*.json"]
|
|
72
|
+
|
|
73
|
+
[tool.pytest.ini_options]
|
|
74
|
+
testpaths = ["tests"]
|
|
75
|
+
pythonpath = ["src"]
|
|
76
|
+
asyncio_mode = "strict"
|
|
77
|
+
filterwarnings = [
|
|
78
|
+
"ignore:.*Using .*httpx.* with .*starlette.*",
|
|
79
|
+
"ignore:.*starlette\\.testclient.*",
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
[project.urls]
|
|
90
|
+
Homepage = "https://ameva.pro/lib/sentinel/"
|
|
91
|
+
Documentation = "https://ameva.pro/lib/sentinel/"
|
|
92
|
+
Repository = "https://github.com/uno-km/ameva-sentinel"
|