amv-sentinel 2.7.0__py3-none-any.whl
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/__init__.py +399 -0
- amv_sentinel/adapters/admin_api.py +212 -0
- amv_sentinel/adapters/admin_ui.py +228 -0
- amv_sentinel/adapters/asgi.py +136 -0
- amv_sentinel/adapters/dashboard.py +622 -0
- amv_sentinel/adapters/enforcement.py +266 -0
- amv_sentinel/adapters/fastapi.py +26 -0
- amv_sentinel/adapters/risk_asgi.py +228 -0
- amv_sentinel/adapters/wsgi.py +124 -0
- amv_sentinel/admin_access.py +87 -0
- amv_sentinel/core/aggregator.py +51 -0
- amv_sentinel/core/bot_classifier.py +207 -0
- amv_sentinel/core/bot_inventory.py +748 -0
- amv_sentinel/core/budget_types.py +355 -0
- amv_sentinel/core/canonical.py +139 -0
- amv_sentinel/core/confidence.py +50 -0
- amv_sentinel/core/crawler_policy.py +373 -0
- amv_sentinel/core/evaluator.py +589 -0
- amv_sentinel/core/geo_registry.py +181 -0
- amv_sentinel/core/geo_resolver.py +177 -0
- amv_sentinel/core/guards.py +224 -0
- amv_sentinel/core/local_store.py +161 -0
- amv_sentinel/core/policy_registry.py +78 -0
- amv_sentinel/core/protocols.py +34 -0
- amv_sentinel/core/redaction.py +44 -0
- amv_sentinel/core/risk_guard.py +326 -0
- amv_sentinel/core/risk_options.py +322 -0
- amv_sentinel/core/rules.py +260 -0
- amv_sentinel/core/sentinel_counter.py +98 -0
- amv_sentinel/core/sentinel_engine.py +167 -0
- amv_sentinel/core/sentinel_policy.py +53 -0
- amv_sentinel/core/sentinel_types.py +147 -0
- amv_sentinel/core/shared_counter.py +241 -0
- amv_sentinel/core/verified_bot.py +775 -0
- amv_sentinel/data/verified_bots.json +119 -0
- amv_sentinel/integrations/sqlalchemy_postgres.py +56 -0
- amv_sentinel/observability.py +91 -0
- amv_sentinel/privacy.py +33 -0
- amv_sentinel/providers.py +50 -0
- amv_sentinel/py.typed +1 -0
- amv_sentinel/trusted_proxy.py +318 -0
- amv_sentinel-2.7.0.dist-info/METADATA +166 -0
- amv_sentinel-2.7.0.dist-info/RECORD +45 -0
- amv_sentinel-2.7.0.dist-info/WHEEL +5 -0
- amv_sentinel-2.7.0.dist-info/top_level.txt +1 -0
amv_sentinel/__init__.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
# Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0 OR Commercial-License
|
|
3
|
+
"""
|
|
4
|
+
AMEVA-Sentinel Python SDK.
|
|
5
|
+
Privacy-first Automation Risk Observation & Multi-Axis Cost Guardrails.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "2.7.0"
|
|
9
|
+
|
|
10
|
+
from .core.budget_types import (
|
|
11
|
+
RouteCostPolicy,
|
|
12
|
+
RateLimitTier,
|
|
13
|
+
CostPolicyDefaults,
|
|
14
|
+
CostPolicyConfig,
|
|
15
|
+
PolicyIdentity,
|
|
16
|
+
VerifiedPrincipal,
|
|
17
|
+
RequestCostContext,
|
|
18
|
+
CostGuardDecision,
|
|
19
|
+
CostGuardBudgetInfo,
|
|
20
|
+
BudgetConsumeRequest,
|
|
21
|
+
BudgetConsumeResult,
|
|
22
|
+
RedactedThreatEvent,
|
|
23
|
+
ThreatAggregateRecord,
|
|
24
|
+
EvaluationContext,
|
|
25
|
+
BUDGET_SCOPES,
|
|
26
|
+
LEGACY_DEFAULT_BUDGET_SCOPES,
|
|
27
|
+
)
|
|
28
|
+
from .core.canonical import (
|
|
29
|
+
canonicalize_policy_json,
|
|
30
|
+
compute_policy_checksum,
|
|
31
|
+
hash_key_identifier,
|
|
32
|
+
validate_cost_policy,
|
|
33
|
+
SAFE_FALLBACK_COST_POLICY,
|
|
34
|
+
)
|
|
35
|
+
from .core.policy_registry import CostPolicyRegistry
|
|
36
|
+
from .core.guards import RequestShapeGuard, ResponseBudgetGuard, GuardValidationResult
|
|
37
|
+
from .core.local_store import LocalEmergencyBudgetStore, compute_emergency_capacity
|
|
38
|
+
from .core.redaction import sanitize_threat_event, ALLOWED_EVIDENCE_CODES
|
|
39
|
+
from .core.aggregator import BoundedThreatAggregator
|
|
40
|
+
from .core.evaluator import SentinelCostGuardEvaluator
|
|
41
|
+
from .core.protocols import AsyncBudgetStore, SyncBudgetStore, ThreatAggregateStore
|
|
42
|
+
from .core.geo_registry import (
|
|
43
|
+
GeoCountryInfo,
|
|
44
|
+
RegionViewport,
|
|
45
|
+
REGION_VIEWPORTS,
|
|
46
|
+
ISO_COUNTRIES,
|
|
47
|
+
resolve_country,
|
|
48
|
+
resolve_geo_coordinates,
|
|
49
|
+
)
|
|
50
|
+
from .core.geo_resolver import (
|
|
51
|
+
GeoBotPattern,
|
|
52
|
+
AI_BOT_PATTERNS,
|
|
53
|
+
GeoBaselineOptions,
|
|
54
|
+
GeoResolutionResult,
|
|
55
|
+
measure_utf8_bytes,
|
|
56
|
+
calculate_bandwidth_savings,
|
|
57
|
+
match_route_baseline,
|
|
58
|
+
match_bot_pattern,
|
|
59
|
+
resolve_geo_payload,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
from .core.bot_classifier import (
|
|
63
|
+
BotSignature,
|
|
64
|
+
BotCategory,
|
|
65
|
+
TriageCategory,
|
|
66
|
+
BotClassification,
|
|
67
|
+
BOT_SIGNATURES,
|
|
68
|
+
classify_bot,
|
|
69
|
+
)
|
|
70
|
+
from .admin_access import (
|
|
71
|
+
AdminAccessMode,
|
|
72
|
+
AdminAccessReason,
|
|
73
|
+
AdminAccessResult,
|
|
74
|
+
resolve_admin_access,
|
|
75
|
+
)
|
|
76
|
+
from .core.sentinel_types import (
|
|
77
|
+
SentinelAction,
|
|
78
|
+
TelemetrySignals,
|
|
79
|
+
EvidenceItem,
|
|
80
|
+
EvaluationContext as SentinelEvaluationContext,
|
|
81
|
+
SentinelRiskReport,
|
|
82
|
+
create_trace_id,
|
|
83
|
+
create_degraded_report,
|
|
84
|
+
)
|
|
85
|
+
from .core.rules import RuleDefinition, RuleEvaluationResult, rules
|
|
86
|
+
from .core.sentinel_policy import SentinelThresholds, SentinelPolicy, create_policy, default_policy
|
|
87
|
+
from .core.sentinel_counter import (
|
|
88
|
+
CounterIncrementResult,
|
|
89
|
+
CounterStore,
|
|
90
|
+
MemoryFixedWindowCounterStore,
|
|
91
|
+
MemoryCounterStore,
|
|
92
|
+
)
|
|
93
|
+
from .core.confidence import calculate_confidence
|
|
94
|
+
from .core.sentinel_engine import evaluate_risk, evaluate_risk_now, BurstRateLimiter
|
|
95
|
+
from .privacy import mask_ip_address, normalize_target_type
|
|
96
|
+
from .trusted_proxy import (
|
|
97
|
+
TrustedProxyPolicy,
|
|
98
|
+
DEFAULT_TRUSTED_PROXY_POLICY,
|
|
99
|
+
extract_client_ip,
|
|
100
|
+
inspect_client_address,
|
|
101
|
+
is_ip_in_cidr,
|
|
102
|
+
is_ip_in_any_cidr,
|
|
103
|
+
)
|
|
104
|
+
from .providers import resolve_provider_adapter, EdgeClientInfo
|
|
105
|
+
from .observability import Sentinel, ActorClaim, Assessment, create_degraded_assessment
|
|
106
|
+
from .adapters.asgi import SentinelASGIMiddleware, SentinelASGIObserver
|
|
107
|
+
from .adapters.wsgi import SentinelWSGIMiddleware, SentinelWSGIObserver
|
|
108
|
+
from .adapters.fastapi import create_fastapi_cost_guard, create_fastapi_observer
|
|
109
|
+
from .adapters.enforcement import SentinelASGIEnforcer, SentinelWSGIEnforcer
|
|
110
|
+
from .core.risk_options import (
|
|
111
|
+
DEFAULT_RISK_OPTIONS,
|
|
112
|
+
RISK_OPTION_SPEC,
|
|
113
|
+
RiskOptionError,
|
|
114
|
+
validate_risk_options,
|
|
115
|
+
)
|
|
116
|
+
from .core.risk_guard import RiskDecision, RiskGuard, path_applies as risk_path_applies
|
|
117
|
+
from .adapters.risk_asgi import SentinelRiskMiddleware, RiskRequestInfo
|
|
118
|
+
from .adapters.dashboard import (
|
|
119
|
+
get_sentinel_dashboard_html,
|
|
120
|
+
mount_fastapi_dashboard,
|
|
121
|
+
mount_flask_dashboard,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
__all__ = [
|
|
125
|
+
"__version__",
|
|
126
|
+
"Sentinel",
|
|
127
|
+
"ActorClaim",
|
|
128
|
+
"Assessment",
|
|
129
|
+
"TrustedProxyPolicy",
|
|
130
|
+
"DEFAULT_TRUSTED_PROXY_POLICY",
|
|
131
|
+
"extract_client_ip",
|
|
132
|
+
"is_ip_in_cidr",
|
|
133
|
+
"is_ip_in_any_cidr",
|
|
134
|
+
"RouteCostPolicy",
|
|
135
|
+
"RateLimitTier",
|
|
136
|
+
"CostPolicyDefaults",
|
|
137
|
+
"CostPolicyConfig",
|
|
138
|
+
"PolicyIdentity",
|
|
139
|
+
"VerifiedPrincipal",
|
|
140
|
+
"RequestCostContext",
|
|
141
|
+
"CostGuardDecision",
|
|
142
|
+
"CostGuardBudgetInfo",
|
|
143
|
+
"BudgetConsumeRequest",
|
|
144
|
+
"BudgetConsumeResult",
|
|
145
|
+
"RedactedThreatEvent",
|
|
146
|
+
"ThreatAggregateRecord",
|
|
147
|
+
"EvaluationContext",
|
|
148
|
+
"BUDGET_SCOPES",
|
|
149
|
+
"LEGACY_DEFAULT_BUDGET_SCOPES",
|
|
150
|
+
"canonicalize_policy_json",
|
|
151
|
+
"compute_policy_checksum",
|
|
152
|
+
"hash_key_identifier",
|
|
153
|
+
"validate_cost_policy",
|
|
154
|
+
"SAFE_FALLBACK_COST_POLICY",
|
|
155
|
+
"CostPolicyRegistry",
|
|
156
|
+
"RequestShapeGuard",
|
|
157
|
+
"ResponseBudgetGuard",
|
|
158
|
+
"GuardValidationResult",
|
|
159
|
+
"LocalEmergencyBudgetStore",
|
|
160
|
+
"compute_emergency_capacity",
|
|
161
|
+
"sanitize_threat_event",
|
|
162
|
+
"ALLOWED_EVIDENCE_CODES",
|
|
163
|
+
"BoundedThreatAggregator",
|
|
164
|
+
"SentinelCostGuardEvaluator",
|
|
165
|
+
"AsyncBudgetStore",
|
|
166
|
+
"SyncBudgetStore",
|
|
167
|
+
"ThreatAggregateStore",
|
|
168
|
+
"GeoCountryInfo",
|
|
169
|
+
"RegionViewport",
|
|
170
|
+
"REGION_VIEWPORTS",
|
|
171
|
+
"ISO_COUNTRIES",
|
|
172
|
+
"resolve_country",
|
|
173
|
+
"resolve_geo_coordinates",
|
|
174
|
+
"GeoBotPattern",
|
|
175
|
+
"AI_BOT_PATTERNS",
|
|
176
|
+
"GeoBaselineOptions",
|
|
177
|
+
"GeoResolutionResult",
|
|
178
|
+
"measure_utf8_bytes",
|
|
179
|
+
"calculate_bandwidth_savings",
|
|
180
|
+
"match_route_baseline",
|
|
181
|
+
"match_bot_pattern",
|
|
182
|
+
"resolve_geo_payload",
|
|
183
|
+
"mask_ip_address",
|
|
184
|
+
"normalize_target_type",
|
|
185
|
+
"resolve_provider_adapter",
|
|
186
|
+
"EdgeClientInfo",
|
|
187
|
+
"get_sentinel_dashboard_html",
|
|
188
|
+
"mount_fastapi_dashboard",
|
|
189
|
+
"mount_flask_dashboard",
|
|
190
|
+
"create_degraded_assessment",
|
|
191
|
+
"BotSignature",
|
|
192
|
+
"BotCategory",
|
|
193
|
+
"TriageCategory",
|
|
194
|
+
"BotClassification",
|
|
195
|
+
"BOT_SIGNATURES",
|
|
196
|
+
"classify_bot",
|
|
197
|
+
"AdminAccessMode",
|
|
198
|
+
"AdminAccessReason",
|
|
199
|
+
"AdminAccessResult",
|
|
200
|
+
"resolve_admin_access",
|
|
201
|
+
"SentinelAction",
|
|
202
|
+
"TelemetrySignals",
|
|
203
|
+
"EvidenceItem",
|
|
204
|
+
"SentinelEvaluationContext",
|
|
205
|
+
"SentinelRiskReport",
|
|
206
|
+
"create_trace_id",
|
|
207
|
+
"create_degraded_report",
|
|
208
|
+
"RuleDefinition",
|
|
209
|
+
"RuleEvaluationResult",
|
|
210
|
+
"rules",
|
|
211
|
+
"SentinelThresholds",
|
|
212
|
+
"SentinelPolicy",
|
|
213
|
+
"create_policy",
|
|
214
|
+
"default_policy",
|
|
215
|
+
"CounterIncrementResult",
|
|
216
|
+
"CounterStore",
|
|
217
|
+
"MemoryFixedWindowCounterStore",
|
|
218
|
+
"MemoryCounterStore",
|
|
219
|
+
"calculate_confidence",
|
|
220
|
+
"evaluate_risk",
|
|
221
|
+
"evaluate_risk_now",
|
|
222
|
+
"BurstRateLimiter",
|
|
223
|
+
"DEFAULT_RISK_OPTIONS",
|
|
224
|
+
"RISK_OPTION_SPEC",
|
|
225
|
+
"RiskOptionError",
|
|
226
|
+
"validate_risk_options",
|
|
227
|
+
"RiskDecision",
|
|
228
|
+
"RiskGuard",
|
|
229
|
+
"risk_path_applies",
|
|
230
|
+
"SentinelRiskMiddleware",
|
|
231
|
+
"RiskRequestInfo",
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
# --- risk guard 2.6 (core) ---
|
|
235
|
+
from .core.sentinel_counter import AsyncCounterStore
|
|
236
|
+
from .core.shared_counter import (
|
|
237
|
+
FIXED_WINDOW_INCR_LUA,
|
|
238
|
+
CounterStoreError,
|
|
239
|
+
MemoryAsyncCounterStore,
|
|
240
|
+
PrefilteredAsyncCounter,
|
|
241
|
+
RedisFixedWindowCounterStore,
|
|
242
|
+
SharedCountResult,
|
|
243
|
+
)
|
|
244
|
+
from .core.risk_options import MAX_POLICIES, POLICY_OVERRIDE_KEYS, effective_risk_options
|
|
245
|
+
from .core.risk_guard import ALLOWED_BOT_CAP_RULE, BOT_VERIFICATION_VALUES
|
|
246
|
+
from .adapters.risk_asgi import SCOPE_STATE_KEY as RISK_SCOPE_STATE_KEY
|
|
247
|
+
|
|
248
|
+
__all__ += [
|
|
249
|
+
"AsyncCounterStore",
|
|
250
|
+
"FIXED_WINDOW_INCR_LUA",
|
|
251
|
+
"CounterStoreError",
|
|
252
|
+
"MemoryAsyncCounterStore",
|
|
253
|
+
"PrefilteredAsyncCounter",
|
|
254
|
+
"RedisFixedWindowCounterStore",
|
|
255
|
+
"SharedCountResult",
|
|
256
|
+
"MAX_POLICIES",
|
|
257
|
+
"POLICY_OVERRIDE_KEYS",
|
|
258
|
+
"effective_risk_options",
|
|
259
|
+
"ALLOWED_BOT_CAP_RULE",
|
|
260
|
+
"BOT_VERIFICATION_VALUES",
|
|
261
|
+
"RISK_SCOPE_STATE_KEY",
|
|
262
|
+
]
|
|
263
|
+
|
|
264
|
+
# --- risk guard 2.6 (verify) ---
|
|
265
|
+
from .core.verified_bot import (
|
|
266
|
+
VERIFIED,
|
|
267
|
+
SPOOFED,
|
|
268
|
+
UNVERIFIED,
|
|
269
|
+
NA,
|
|
270
|
+
BOT_VERIFICATION_RESULTS,
|
|
271
|
+
VerifiedBotRegistryError,
|
|
272
|
+
VerifiedBotUsageError,
|
|
273
|
+
VerifiedBotEntry,
|
|
274
|
+
VerifiedBotRegistry,
|
|
275
|
+
load_default_registry as load_verified_bot_registry,
|
|
276
|
+
vendor_for as verified_bot_vendor_for,
|
|
277
|
+
vendor_for_classification as verified_bot_vendor_for_classification,
|
|
278
|
+
registry_stale as verified_bot_registry_stale,
|
|
279
|
+
DnsResolver,
|
|
280
|
+
AsyncioDnsResolver,
|
|
281
|
+
VerificationCache,
|
|
282
|
+
MemoryVerificationCache,
|
|
283
|
+
BotVerifier,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
__all__ += [
|
|
287
|
+
"VERIFIED",
|
|
288
|
+
"SPOOFED",
|
|
289
|
+
"UNVERIFIED",
|
|
290
|
+
"NA",
|
|
291
|
+
"BOT_VERIFICATION_RESULTS",
|
|
292
|
+
"VerifiedBotRegistryError",
|
|
293
|
+
"VerifiedBotUsageError",
|
|
294
|
+
"VerifiedBotEntry",
|
|
295
|
+
"VerifiedBotRegistry",
|
|
296
|
+
"load_verified_bot_registry",
|
|
297
|
+
"verified_bot_vendor_for",
|
|
298
|
+
"verified_bot_vendor_for_classification",
|
|
299
|
+
"verified_bot_registry_stale",
|
|
300
|
+
"DnsResolver",
|
|
301
|
+
"AsyncioDnsResolver",
|
|
302
|
+
"VerificationCache",
|
|
303
|
+
"MemoryVerificationCache",
|
|
304
|
+
"BotVerifier",
|
|
305
|
+
]
|
|
306
|
+
|
|
307
|
+
# --- 2.7 ---
|
|
308
|
+
from .core.bot_inventory import (
|
|
309
|
+
INVENTORY_ERROR_CODE,
|
|
310
|
+
INVENTORY_OBSERVE_LUA,
|
|
311
|
+
GENERIC_BOT_NAMES,
|
|
312
|
+
BotInventoryError,
|
|
313
|
+
BotInventoryStore,
|
|
314
|
+
BotObservation,
|
|
315
|
+
BotRecord,
|
|
316
|
+
Page as BotInventoryPage,
|
|
317
|
+
MemoryBotInventory,
|
|
318
|
+
RedisBotInventory,
|
|
319
|
+
bot_key,
|
|
320
|
+
ua_family,
|
|
321
|
+
vendor_ids as bot_vendor_ids,
|
|
322
|
+
should_record as inventory_should_record,
|
|
323
|
+
observation_from_user_agent,
|
|
324
|
+
)
|
|
325
|
+
from .core.risk_options import (
|
|
326
|
+
BOT_RULE_ACTIONS,
|
|
327
|
+
MAX_BOT_RULES,
|
|
328
|
+
bot_rule_key_kind,
|
|
329
|
+
resolve_bot_rule,
|
|
330
|
+
)
|
|
331
|
+
from .core.risk_guard import BOT_RULE_BLOCK, BOT_RULE_LIMIT, BOT_RULE_ALLOW_IGNORED_SPOOFED
|
|
332
|
+
|
|
333
|
+
__all__ += [
|
|
334
|
+
"INVENTORY_ERROR_CODE",
|
|
335
|
+
"INVENTORY_OBSERVE_LUA",
|
|
336
|
+
"GENERIC_BOT_NAMES",
|
|
337
|
+
"BotInventoryError",
|
|
338
|
+
"BotInventoryStore",
|
|
339
|
+
"BotObservation",
|
|
340
|
+
"BotRecord",
|
|
341
|
+
"BotInventoryPage",
|
|
342
|
+
"MemoryBotInventory",
|
|
343
|
+
"RedisBotInventory",
|
|
344
|
+
"bot_key",
|
|
345
|
+
"ua_family",
|
|
346
|
+
"bot_vendor_ids",
|
|
347
|
+
"inventory_should_record",
|
|
348
|
+
"observation_from_user_agent",
|
|
349
|
+
"BOT_RULE_ACTIONS",
|
|
350
|
+
"MAX_BOT_RULES",
|
|
351
|
+
"bot_rule_key_kind",
|
|
352
|
+
"resolve_bot_rule",
|
|
353
|
+
"BOT_RULE_BLOCK",
|
|
354
|
+
"BOT_RULE_LIMIT",
|
|
355
|
+
"BOT_RULE_ALLOW_IGNORED_SPOOFED",
|
|
356
|
+
]
|
|
357
|
+
|
|
358
|
+
# --- 2.7 (policy files, admin API and UI) ---
|
|
359
|
+
from .core.crawler_policy import (
|
|
360
|
+
CRAWLER_POLICY_ERROR_CODE,
|
|
361
|
+
ROBOTS_TOKENS,
|
|
362
|
+
CrawlerPolicyError,
|
|
363
|
+
LlmsLink,
|
|
364
|
+
LlmsSite,
|
|
365
|
+
RobotsGroup,
|
|
366
|
+
RobotsPlan,
|
|
367
|
+
SkippedBot,
|
|
368
|
+
crawl_delay_seconds,
|
|
369
|
+
render_llms_txt,
|
|
370
|
+
render_robots_txt,
|
|
371
|
+
robots_rules,
|
|
372
|
+
)
|
|
373
|
+
from .adapters.admin_api import (
|
|
374
|
+
AdminOptionalDependencyError,
|
|
375
|
+
MemoryOptionsStore,
|
|
376
|
+
OptionsStore,
|
|
377
|
+
create_admin_router,
|
|
378
|
+
)
|
|
379
|
+
from .adapters.admin_ui import render_admin_html
|
|
380
|
+
|
|
381
|
+
__all__ += [
|
|
382
|
+
"CRAWLER_POLICY_ERROR_CODE",
|
|
383
|
+
"ROBOTS_TOKENS",
|
|
384
|
+
"CrawlerPolicyError",
|
|
385
|
+
"LlmsLink",
|
|
386
|
+
"LlmsSite",
|
|
387
|
+
"RobotsGroup",
|
|
388
|
+
"RobotsPlan",
|
|
389
|
+
"SkippedBot",
|
|
390
|
+
"crawl_delay_seconds",
|
|
391
|
+
"render_llms_txt",
|
|
392
|
+
"render_robots_txt",
|
|
393
|
+
"robots_rules",
|
|
394
|
+
"AdminOptionalDependencyError",
|
|
395
|
+
"MemoryOptionsStore",
|
|
396
|
+
"OptionsStore",
|
|
397
|
+
"create_admin_router",
|
|
398
|
+
"render_admin_html",
|
|
399
|
+
]
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0 OR Commercial-License
|
|
3
|
+
"""
|
|
4
|
+
Ready-made admin API for the bot inventory and bot rules (FastAPI ``APIRouter``).
|
|
5
|
+
|
|
6
|
+
router = create_admin_router(
|
|
7
|
+
inventory=inventory, # BotInventoryStore (MemoryBotInventory / RedisBotInventory / your own)
|
|
8
|
+
options_store=MyOptionsStore(), # async get() -> dict | None ; async set(options, actor) -> None
|
|
9
|
+
read_dependency=require_viewer, # FastAPI dependency: returns the caller or raises 401/403
|
|
10
|
+
write_dependency=require_admin, # FastAPI dependency: returns the caller or raises 401/403
|
|
11
|
+
)
|
|
12
|
+
app.include_router(router, prefix="/sentinel-admin")
|
|
13
|
+
|
|
14
|
+
The SDK never creates authentication. Both dependencies are required arguments: a router cannot be built without the host
|
|
15
|
+
application deciding who may read and who may change rules. Rule changes go through ``validate_risk_options`` (invalid input is
|
|
16
|
+
rejected with 422, never repaired) and are persisted by *your* ``options_store`` - keep your own audit trail there.
|
|
17
|
+
|
|
18
|
+
Endpoints (relative to the mount prefix):
|
|
19
|
+
GET /summary counts, inventory health (overflow), can_write
|
|
20
|
+
GET /bots list/search the inventory (q, category, since_day, sort, desc, limit, offset)
|
|
21
|
+
GET /bots/{key} one bot with its day-by-day hits
|
|
22
|
+
GET /rules the current ``bot_rules``
|
|
23
|
+
PUT /rules/{rule_key} set a rule for a bot key, ``vendor:<id>`` or ``category:<CATEGORY>``
|
|
24
|
+
DELETE /rules/{rule_key} remove that rule
|
|
25
|
+
GET /robots.txt preview of the robots.txt that follows from the current rules
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional, Protocol, Sequence, Tuple, runtime_checkable
|
|
29
|
+
|
|
30
|
+
from ..core.bot_inventory import BotInventoryError, BotRecord, bot_key as make_bot_key, vendor_ids
|
|
31
|
+
from ..core.crawler_policy import CrawlerPolicyError, render_robots_txt, robots_rules
|
|
32
|
+
from ..core.risk_options import RiskOptionError, resolve_bot_rule, validate_risk_options
|
|
33
|
+
|
|
34
|
+
ADMIN_API_ERROR_CODE = "AMU_ERR_OPTIONAL_DEPENDENCY"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AdminOptionalDependencyError(ImportError):
|
|
38
|
+
"""FastAPI is not installed. The message starts with ``AMU_ERR_OPTIONAL_DEPENDENCY``."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@runtime_checkable
|
|
42
|
+
class OptionsStore(Protocol):
|
|
43
|
+
"""Where the host application keeps the guard options (the same dict it passes to ``SentinelRiskMiddleware``)."""
|
|
44
|
+
|
|
45
|
+
async def get(self) -> Optional[Dict[str, Any]]: ...
|
|
46
|
+
|
|
47
|
+
async def set(self, options: Dict[str, Any], actor: str) -> None: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MemoryOptionsStore:
|
|
51
|
+
"""Process-local options store for tests and single-process demos. Do not use it behind several workers."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, options: Optional[Dict[str, Any]] = None) -> None:
|
|
54
|
+
self.options: Optional[Dict[str, Any]] = dict(options) if options else None
|
|
55
|
+
self.history: List[Tuple[str, Dict[str, Any]]] = []
|
|
56
|
+
|
|
57
|
+
async def get(self) -> Optional[Dict[str, Any]]:
|
|
58
|
+
return dict(self.options) if self.options is not None else None
|
|
59
|
+
|
|
60
|
+
async def set(self, options: Dict[str, Any], actor: str) -> None:
|
|
61
|
+
self.options = dict(options)
|
|
62
|
+
self.history.append((actor, dict(options)))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _require_fastapi():
|
|
66
|
+
try:
|
|
67
|
+
import fastapi # noqa: WPS433
|
|
68
|
+
except ImportError as exc:
|
|
69
|
+
raise AdminOptionalDependencyError(
|
|
70
|
+
f"{ADMIN_API_ERROR_CODE}: create_admin_router needs FastAPI (pip install fastapi). "
|
|
71
|
+
"The core guard and inventory work without it."
|
|
72
|
+
) from exc
|
|
73
|
+
return fastapi
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _rule_for(record: BotRecord, rules: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
77
|
+
key, rule = resolve_bot_rule(
|
|
78
|
+
rules, bot_key=record.key, category=record.category, vendors=vendor_ids(record.vendor, record.name)
|
|
79
|
+
)
|
|
80
|
+
return {"key": key, **rule} if rule is not None else None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def create_admin_router(
|
|
84
|
+
*,
|
|
85
|
+
inventory: Any,
|
|
86
|
+
options_store: Any,
|
|
87
|
+
read_dependency: Callable[..., Any],
|
|
88
|
+
write_dependency: Callable[..., Any],
|
|
89
|
+
can_write: Optional[Callable[[Any], bool]] = None,
|
|
90
|
+
actor_label: Callable[[Any], str] = str,
|
|
91
|
+
robots_site: Optional[Dict[str, Any]] = None,
|
|
92
|
+
max_page: int = 500,
|
|
93
|
+
):
|
|
94
|
+
"""
|
|
95
|
+
Build the admin ``APIRouter``.
|
|
96
|
+
|
|
97
|
+
``can_write(actor) -> bool`` lets ``/summary`` tell the UI whether to show edit controls (None = unknown, the UI then shows them
|
|
98
|
+
and the server enforces ``write_dependency``). ``actor_label`` turns the caller returned by the dependency into the string passed
|
|
99
|
+
to ``options_store.set``. ``robots_site``: ``{"disallow_paths": [...], "sitemap_urls": [...], "default": "allow"|"disallow",
|
|
100
|
+
"default_rules": [("Allow"|"Disallow", path)]}`` for the ``/robots.txt`` preview.
|
|
101
|
+
"""
|
|
102
|
+
fastapi = _require_fastapi()
|
|
103
|
+
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
104
|
+
from fastapi.responses import PlainTextResponse
|
|
105
|
+
|
|
106
|
+
for name, store, methods in (("inventory", inventory, ("list", "get", "stats")), ("options_store", options_store, ("get", "set"))):
|
|
107
|
+
missing = [m for m in methods if not callable(getattr(store, m, None))]
|
|
108
|
+
if missing:
|
|
109
|
+
raise TypeError(f"AMU_ERR_ADMIN_API: {name} is missing {missing}")
|
|
110
|
+
if not callable(read_dependency) or not callable(write_dependency):
|
|
111
|
+
raise TypeError("AMU_ERR_ADMIN_API: read_dependency and write_dependency are required callables")
|
|
112
|
+
site = dict(robots_site or {})
|
|
113
|
+
router = APIRouter()
|
|
114
|
+
|
|
115
|
+
async def current_options() -> Dict[str, Any]:
|
|
116
|
+
return dict(await options_store.get() or {})
|
|
117
|
+
|
|
118
|
+
def rules_of(options: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
|
|
119
|
+
try:
|
|
120
|
+
return validate_risk_options(options)["bot_rules"]
|
|
121
|
+
except RiskOptionError as exc:
|
|
122
|
+
raise HTTPException(status_code=409, detail=f"AMU_ERR_ADMIN_OPTIONS: stored options are invalid: {exc}")
|
|
123
|
+
|
|
124
|
+
@router.get("/summary")
|
|
125
|
+
async def summary(actor: Any = Depends(read_dependency)) -> Dict[str, Any]:
|
|
126
|
+
stats = await inventory.stats()
|
|
127
|
+
rules = rules_of(await current_options())
|
|
128
|
+
by_category: Dict[str, int] = {}
|
|
129
|
+
page = await inventory.list(limit=max_page, offset=0, sort="hits")
|
|
130
|
+
for rec in page.items:
|
|
131
|
+
by_category[rec.category] = by_category.get(rec.category, 0) + 1
|
|
132
|
+
return {
|
|
133
|
+
"inventory": stats,
|
|
134
|
+
"categories": by_category,
|
|
135
|
+
"categories_partial": page.total > len(page.items),
|
|
136
|
+
"rules": len(rules),
|
|
137
|
+
"can_write": None if can_write is None else bool(can_write(actor)),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
@router.get("/bots")
|
|
141
|
+
async def list_bots(
|
|
142
|
+
q: Optional[str] = Query(None, max_length=100),
|
|
143
|
+
category: Optional[str] = Query(None, max_length=32),
|
|
144
|
+
since_day: Optional[str] = Query(None, max_length=10),
|
|
145
|
+
sort: str = Query("last_seen", max_length=20),
|
|
146
|
+
desc: bool = True,
|
|
147
|
+
limit: int = Query(100, ge=1),
|
|
148
|
+
offset: int = Query(0, ge=0),
|
|
149
|
+
actor: Any = Depends(read_dependency),
|
|
150
|
+
) -> Dict[str, Any]:
|
|
151
|
+
rules = rules_of(await current_options())
|
|
152
|
+
try:
|
|
153
|
+
page = await inventory.list(q=q, category=category, since_day=since_day, limit=min(limit, max_page), offset=offset, sort=sort, descending=desc)
|
|
154
|
+
except (BotInventoryError, TypeError, ValueError) as exc:
|
|
155
|
+
raise HTTPException(status_code=422, detail=str(exc))
|
|
156
|
+
out = page.to_dict()
|
|
157
|
+
out["items"] = [{**rec.to_dict(), "rule": _rule_for(rec, rules)} for rec in page.items]
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
@router.get("/bots/{key:path}")
|
|
161
|
+
async def get_bot(key: str, actor: Any = Depends(read_dependency)) -> Dict[str, Any]:
|
|
162
|
+
rec = await inventory.get(key)
|
|
163
|
+
if rec is None:
|
|
164
|
+
raise HTTPException(status_code=404, detail="AMU_ERR_BOT_NOT_FOUND")
|
|
165
|
+
return {**rec.to_dict(), "rule": _rule_for(rec, rules_of(await current_options()))}
|
|
166
|
+
|
|
167
|
+
@router.get("/rules")
|
|
168
|
+
async def get_rules(actor: Any = Depends(read_dependency)) -> Dict[str, Any]:
|
|
169
|
+
return {"rules": rules_of(await current_options())}
|
|
170
|
+
|
|
171
|
+
@router.put("/rules/{rule_key:path}")
|
|
172
|
+
async def put_rule(rule_key: str, body: Dict[str, Any], actor: Any = Depends(write_dependency)) -> Dict[str, Any]:
|
|
173
|
+
options = await current_options()
|
|
174
|
+
rules = dict(options.get("bot_rules") or {})
|
|
175
|
+
rules[rule_key] = body
|
|
176
|
+
candidate = {**options, "bot_rules": rules}
|
|
177
|
+
try:
|
|
178
|
+
validated = validate_risk_options(candidate)
|
|
179
|
+
except RiskOptionError as exc:
|
|
180
|
+
raise HTTPException(status_code=422, detail=str(exc))
|
|
181
|
+
await options_store.set({**options, "bot_rules": validated["bot_rules"]}, actor_label(actor))
|
|
182
|
+
return {"key": rule_key, **validated["bot_rules"][rule_key]}
|
|
183
|
+
|
|
184
|
+
@router.delete("/rules/{rule_key:path}")
|
|
185
|
+
async def delete_rule(rule_key: str, actor: Any = Depends(write_dependency)) -> Dict[str, Any]:
|
|
186
|
+
options = await current_options()
|
|
187
|
+
rules = dict(options.get("bot_rules") or {})
|
|
188
|
+
if rule_key not in rules:
|
|
189
|
+
raise HTTPException(status_code=404, detail="AMU_ERR_RULE_NOT_FOUND")
|
|
190
|
+
del rules[rule_key]
|
|
191
|
+
await options_store.set({**options, "bot_rules": rules}, actor_label(actor))
|
|
192
|
+
return {"removed": rule_key}
|
|
193
|
+
|
|
194
|
+
@router.get("/robots.txt", response_class=PlainTextResponse)
|
|
195
|
+
async def robots_preview(actor: Any = Depends(read_dependency)) -> str:
|
|
196
|
+
options = await current_options()
|
|
197
|
+
rules = rules_of(options)
|
|
198
|
+
try:
|
|
199
|
+
validated = validate_risk_options(options)
|
|
200
|
+
plan = robots_rules(
|
|
201
|
+
rules, default=site.get("default", "allow"), burst_threshold=validated["burst_threshold"]
|
|
202
|
+
)
|
|
203
|
+
return render_robots_txt(
|
|
204
|
+
plan,
|
|
205
|
+
disallow_paths=site.get("disallow_paths", ()),
|
|
206
|
+
sitemap_urls=site.get("sitemap_urls", ()),
|
|
207
|
+
default_rules=site.get("default_rules", ()),
|
|
208
|
+
)
|
|
209
|
+
except (CrawlerPolicyError, RiskOptionError) as exc:
|
|
210
|
+
raise HTTPException(status_code=422, detail=str(exc))
|
|
211
|
+
|
|
212
|
+
return router
|