maigp-server 5.0.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.
- aigp_server/__init__.py +60 -0
- aigp_server/anticipation.py +75 -0
- aigp_server/au_rules.py +101 -0
- aigp_server/circuit_breaker.py +102 -0
- aigp_server/config.py +81 -0
- aigp_server/euai_rules.py +163 -0
- aigp_server/governance_engine.py +352 -0
- aigp_server/hmac_auth.py +54 -0
- aigp_server/ihl_rules.py +160 -0
- aigp_server/jp_rules.py +78 -0
- aigp_server/providers/__init__.py +0 -0
- aigp_server/providers/consent/__init__.py +5 -0
- aigp_server/providers/consent/consent_engine.py +80 -0
- aigp_server/providers/consent/static/__init__.py +0 -0
- aigp_server/providers/enforcement/__init__.py +6 -0
- aigp_server/providers/enforcement/azure/__init__.py +0 -0
- aigp_server/providers/enforcement/bedrock/__init__.py +0 -0
- aigp_server/providers/enforcement/enforcement_adapter_base.py +37 -0
- aigp_server/providers/enforcement/enforcement_adapter_factory.py +26 -0
- aigp_server/providers/enforcement/gcp/__init__.py +0 -0
- aigp_server/providers/key_store/__init__.py +7 -0
- aigp_server/providers/key_store/key_store_base.py +37 -0
- aigp_server/providers/key_store/key_store_factory.py +24 -0
- aigp_server/providers/key_store/kms/__init__.py +0 -0
- aigp_server/providers/key_store/local/__init__.py +0 -0
- aigp_server/providers/key_store/local/local_key_store.py +41 -0
- aigp_server/providers/pii/__init__.py +7 -0
- aigp_server/providers/pii/pii_detector_base.py +33 -0
- aigp_server/providers/pii/pii_detector_factory.py +24 -0
- aigp_server/providers/pii/presidio/__init__.py +0 -0
- aigp_server/providers/pii/regex/__init__.py +0 -0
- aigp_server/providers/pii/regex/regex_detector.py +39 -0
- aigp_server/providers/scope/__init__.py +6 -0
- aigp_server/providers/scope/circuit_breaker.py +102 -0
- aigp_server/providers/scope/scope_manager.py +99 -0
- aigp_server/providers/storage/__init__.py +9 -0
- aigp_server/providers/storage/dynamodb/__init__.py +0 -0
- aigp_server/providers/storage/memory/__init__.py +0 -0
- aigp_server/providers/storage/memory/memory_storage_provider.py +74 -0
- aigp_server/providers/storage/storage_provider_base.py +65 -0
- aigp_server/providers/storage/storage_provider_factory.py +27 -0
- aigp_server/routes.py +221 -0
- aigp_server/routes_v3.py +222 -0
- aigp_server/scope_manager.py +99 -0
- aigp_server/store.py +78 -0
- aigp_server/universal_rules.py +79 -0
- aigp_server/verification_engine.py +162 -0
- maigp_server-5.0.0.dist-info/METADATA +136 -0
- maigp_server-5.0.0.dist-info/RECORD +50 -0
- maigp_server-5.0.0.dist-info/WHEEL +4 -0
aigp_server/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""AIGP Server — Agentic Governance Engine with provider-based architecture.
|
|
2
|
+
|
|
3
|
+
Usage (new — config-driven):
|
|
4
|
+
from aigp_server import ServerConfig
|
|
5
|
+
|
|
6
|
+
config = ServerConfig(
|
|
7
|
+
storage={"provider": "memory"},
|
|
8
|
+
pii={"provider": "regex"},
|
|
9
|
+
key_store={"provider": "local"},
|
|
10
|
+
mode="ENFORCE",
|
|
11
|
+
)
|
|
12
|
+
components = config.build()
|
|
13
|
+
engine = GovernanceEngine(components.store, components.scope_mgr, components.circuit_breaker, mode="ENFORCE")
|
|
14
|
+
router = AigpRouter(engine, hmac_secret="...")
|
|
15
|
+
|
|
16
|
+
Usage (backward compat — still works):
|
|
17
|
+
from aigp_server import GovernanceEngine, GovernanceStore, AigpRouter
|
|
18
|
+
|
|
19
|
+
class MyStore(GovernanceStore): ...
|
|
20
|
+
store = MyStore()
|
|
21
|
+
engine = GovernanceEngine(store, ScopeEnvelopeManager(store), CircuitBreakerService(store))
|
|
22
|
+
router = AigpRouter(engine)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
__version__ = "0.2.0"
|
|
26
|
+
|
|
27
|
+
# Backward compat — original flat imports
|
|
28
|
+
from .governance_engine import GovernanceEngine
|
|
29
|
+
from .routes import AigpRouter
|
|
30
|
+
from .hmac_auth import verify_hmac, sign_request
|
|
31
|
+
|
|
32
|
+
# Provider-based (new)
|
|
33
|
+
from .providers.storage import StorageProviderBase, GovernanceStore
|
|
34
|
+
from .providers.scope import ScopeEnvelopeManager, CircuitBreakerService, TEMPLATES
|
|
35
|
+
from .providers.enforcement import EnforcementAdapterBase
|
|
36
|
+
from .providers.pii import PiiDetectorBase, PiiEntity
|
|
37
|
+
from .providers.key_store import KeyStoreBase
|
|
38
|
+
from .providers.consent import ConsentEngine, TokenMap
|
|
39
|
+
from .config import ServerConfig, ServerComponents
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
# Engine + Router
|
|
43
|
+
"GovernanceEngine", "AigpRouter",
|
|
44
|
+
# Auth
|
|
45
|
+
"verify_hmac", "sign_request",
|
|
46
|
+
# Storage
|
|
47
|
+
"StorageProviderBase", "GovernanceStore",
|
|
48
|
+
# Scope
|
|
49
|
+
"ScopeEnvelopeManager", "CircuitBreakerService", "TEMPLATES",
|
|
50
|
+
# Enforcement
|
|
51
|
+
"EnforcementAdapterBase",
|
|
52
|
+
# PII
|
|
53
|
+
"PiiDetectorBase", "PiiEntity",
|
|
54
|
+
# Key Store
|
|
55
|
+
"KeyStoreBase",
|
|
56
|
+
# Consent
|
|
57
|
+
"ConsentEngine", "TokenMap",
|
|
58
|
+
# Config
|
|
59
|
+
"ServerConfig", "ServerComponents",
|
|
60
|
+
]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Anticipation Store — manages ANTICIPATE lifecycle (RFC-032 Phase 1)."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from uuid import uuid4
|
|
5
|
+
|
|
6
|
+
from .providers.storage.storage_provider_base import StorageProviderBase
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AnticipationStore:
|
|
10
|
+
"""Stores and manages ANTICIPATE declarations with seal semantics."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, db: StorageProviderBase):
|
|
13
|
+
self._db = db
|
|
14
|
+
self._anticipations: dict[str, dict] = {} # anticipation_id → record
|
|
15
|
+
|
|
16
|
+
async def create(self, msg: dict) -> dict:
|
|
17
|
+
"""Create a new ANTICIPATE declaration. Returns the stored record."""
|
|
18
|
+
ant_id = msg.get("anticipation_id", f"ant-{uuid4().hex[:12]}")
|
|
19
|
+
record = {
|
|
20
|
+
"anticipation_id": ant_id,
|
|
21
|
+
"app_id": msg["app_id"],
|
|
22
|
+
"agent_id": msg["agent_id"],
|
|
23
|
+
"plan_id": msg.get("plan_id"),
|
|
24
|
+
"scope_envelope_id": msg.get("scope_envelope_id"),
|
|
25
|
+
"session_id": msg.get("session_id"),
|
|
26
|
+
"expectations": msg["expectations"],
|
|
27
|
+
"grading_policy": msg["grading_policy"],
|
|
28
|
+
"status": "OPEN",
|
|
29
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
30
|
+
"sealed_at": None,
|
|
31
|
+
}
|
|
32
|
+
self._anticipations[ant_id] = record
|
|
33
|
+
await self._db.put_audit(msg["agent_id"], "ANTICIPATE_CREATED", "OPEN", {"anticipation_id": ant_id})
|
|
34
|
+
return record
|
|
35
|
+
|
|
36
|
+
async def seal(self, anticipation_id: str) -> bool:
|
|
37
|
+
"""Seal an anticipation (immutable after first execution event). Returns True if sealed."""
|
|
38
|
+
record = self._anticipations.get(anticipation_id)
|
|
39
|
+
if not record or record["status"] != "OPEN":
|
|
40
|
+
return False
|
|
41
|
+
record["status"] = "SEALED"
|
|
42
|
+
record["sealed_at"] = datetime.now(timezone.utc).isoformat()
|
|
43
|
+
await self._db.put_audit(record["agent_id"], "ANTICIPATE_SEALED", "SEALED", {"anticipation_id": anticipation_id})
|
|
44
|
+
return True
|
|
45
|
+
|
|
46
|
+
def is_sealed(self, anticipation_id: str) -> bool:
|
|
47
|
+
record = self._anticipations.get(anticipation_id)
|
|
48
|
+
return record is not None and record["status"] == "SEALED"
|
|
49
|
+
|
|
50
|
+
def get(self, anticipation_id: str) -> dict | None:
|
|
51
|
+
return self._anticipations.get(anticipation_id)
|
|
52
|
+
|
|
53
|
+
def find_for_session(self, session_id: str) -> list[dict]:
|
|
54
|
+
return [r for r in self._anticipations.values() if r.get("session_id") == session_id]
|
|
55
|
+
|
|
56
|
+
def find_for_plan(self, plan_id: str) -> list[dict]:
|
|
57
|
+
return [r for r in self._anticipations.values() if r.get("plan_id") == plan_id]
|
|
58
|
+
|
|
59
|
+
async def seal_open_for_session(self, session_id: str) -> list[str]:
|
|
60
|
+
"""Seal all OPEN anticipations for a session. Returns sealed IDs."""
|
|
61
|
+
sealed = []
|
|
62
|
+
for record in self._anticipations.values():
|
|
63
|
+
if record.get("session_id") == session_id and record["status"] == "OPEN":
|
|
64
|
+
if await self.seal(record["anticipation_id"]):
|
|
65
|
+
sealed.append(record["anticipation_id"])
|
|
66
|
+
return sealed
|
|
67
|
+
|
|
68
|
+
async def seal_open_for_agent(self, agent_id: str) -> list[str]:
|
|
69
|
+
"""Seal all OPEN anticipations for an agent. Returns sealed IDs."""
|
|
70
|
+
sealed = []
|
|
71
|
+
for record in self._anticipations.values():
|
|
72
|
+
if record.get("agent_id") == agent_id and record["status"] == "OPEN":
|
|
73
|
+
if await self.seal(record["anticipation_id"]):
|
|
74
|
+
sealed.append(record["anticipation_id"])
|
|
75
|
+
return sealed
|
aigp_server/au_rules.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""AU Continental AI Strategy Rules — RFC-029 Wave 2.
|
|
2
|
+
|
|
3
|
+
These rules implement the African Union's Continental AI Strategy
|
|
4
|
+
requirements for data sovereignty, local benefit, cultural preservation,
|
|
5
|
+
inclusion, community consent, and equitable partnerships.
|
|
6
|
+
|
|
7
|
+
Legal basis: AU Continental AI Strategy (2024), Malabo Convention (2014).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
AU_RULES = [
|
|
15
|
+
{"id": "AU-001", "name": "DATA_RESIDENCY", "description": "African data must reside within declared jurisdiction unless cross-border framework is declared."},
|
|
16
|
+
{"id": "AU-002", "name": "LOCAL_BENEFIT", "description": "AI systems must demonstrate local benefit when local_first or ubuntu_principle is active."},
|
|
17
|
+
{"id": "AU-003", "name": "CULTURAL_PRESERVATION", "description": "Indigenous knowledge and cultural norms must be preserved."},
|
|
18
|
+
{"id": "AU-004", "name": "INCLUSION_MANDATE", "description": "Declared beneficiary groups must be served; exclusion is prohibited."},
|
|
19
|
+
{"id": "AU-005", "name": "COMMUNITY_CONSENT", "description": "Community consent is required when cultural_sensitivity.community_consent_required is true."},
|
|
20
|
+
{"id": "AU-006", "name": "EQUITABLE_PARTNERSHIP", "description": "Non-African providers must demonstrate equitable partnership with local entities."},
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
# AU member states (ISO 3166-1 alpha-2)
|
|
24
|
+
AU_MEMBER_STATES = {
|
|
25
|
+
"DZ", "AO", "BJ", "BW", "BF", "BI", "CV", "CM", "CF", "TD",
|
|
26
|
+
"KM", "CG", "CD", "CI", "DJ", "EG", "GQ", "ER", "SZ", "ET",
|
|
27
|
+
"GA", "GM", "GH", "GN", "GW", "KE", "LS", "LR", "LY", "MG",
|
|
28
|
+
"MW", "ML", "MR", "MU", "MZ", "NA", "NE", "NG", "RW", "ST",
|
|
29
|
+
"SN", "SC", "SL", "SO", "ZA", "SS", "SD", "TZ", "TG", "TN",
|
|
30
|
+
"UG", "ZM", "ZW",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def evaluate_au_rules(request: dict, context: dict) -> dict | None:
|
|
35
|
+
"""Evaluate AU Continental AI Strategy rules against a request.
|
|
36
|
+
|
|
37
|
+
Returns a DENY decision dict if a rule triggers, or None to allow.
|
|
38
|
+
"""
|
|
39
|
+
if not context or not context.get("active"):
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
data_sov = context.get("data_sovereignty", {})
|
|
43
|
+
cultural = context.get("cultural_sensitivity", {})
|
|
44
|
+
|
|
45
|
+
# AU-001: Data residency — if residency declared but request targets outside
|
|
46
|
+
if data_sov.get("residency"):
|
|
47
|
+
dest = request.get("data_destination", "")
|
|
48
|
+
if dest and dest not in AU_MEMBER_STATES and not data_sov.get("cross_border_framework"):
|
|
49
|
+
return _deny("AU-001", "DATA_RESIDENCY",
|
|
50
|
+
f"Data destination '{dest}' is outside AU member states without a declared cross-border framework.")
|
|
51
|
+
|
|
52
|
+
# AU-002: Local benefit — ubuntu_principle or local_first requires benefit declaration
|
|
53
|
+
if context.get("ubuntu_principle") or context.get("local_first"):
|
|
54
|
+
if not request.get("local_benefit_declared") and request.get("provider_jurisdiction"):
|
|
55
|
+
prov = request["provider_jurisdiction"]
|
|
56
|
+
if prov not in AU_MEMBER_STATES:
|
|
57
|
+
return _deny("AU-002", "LOCAL_BENEFIT",
|
|
58
|
+
f"Provider jurisdiction '{prov}' is non-African. local_benefit_declared required when ubuntu_principle/local_first is active.")
|
|
59
|
+
|
|
60
|
+
# AU-003: Cultural preservation
|
|
61
|
+
if cultural.get("indigenous_knowledge_preserved"):
|
|
62
|
+
if request.get("training_data_source") == "scraped" and not request.get("indigenous_consent"):
|
|
63
|
+
return _deny("AU-003", "CULTURAL_PRESERVATION",
|
|
64
|
+
"Scraped training data requires indigenous_consent when indigenous_knowledge_preserved is active.")
|
|
65
|
+
|
|
66
|
+
# AU-004: Inclusion mandate
|
|
67
|
+
beneficiaries = context.get("beneficiary_groups", [])
|
|
68
|
+
if beneficiaries and request.get("excluded_groups"):
|
|
69
|
+
excluded = set(request["excluded_groups"])
|
|
70
|
+
overlap = excluded & set(beneficiaries)
|
|
71
|
+
if overlap:
|
|
72
|
+
return _deny("AU-004", "INCLUSION_MANDATE",
|
|
73
|
+
f"Beneficiary groups {overlap} are explicitly excluded. Inclusion mandate violated.")
|
|
74
|
+
|
|
75
|
+
# AU-005: Community consent
|
|
76
|
+
if cultural.get("community_consent_required"):
|
|
77
|
+
if not request.get("community_consent_obtained"):
|
|
78
|
+
return _deny("AU-005", "COMMUNITY_CONSENT",
|
|
79
|
+
"community_consent_required is true but community_consent_obtained is missing from request.")
|
|
80
|
+
|
|
81
|
+
# AU-006: Equitable partnership
|
|
82
|
+
if request.get("provider_jurisdiction") and request["provider_jurisdiction"] not in AU_MEMBER_STATES:
|
|
83
|
+
if data_sov.get("african_data_for_african_benefit"):
|
|
84
|
+
if not request.get("partnership_declaration"):
|
|
85
|
+
return _deny("AU-006", "EQUITABLE_PARTNERSHIP",
|
|
86
|
+
"Non-African provider operating on African data must declare an equitable partnership.")
|
|
87
|
+
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _deny(rule_id: str, rule_name: str, reason: str) -> dict:
|
|
92
|
+
"""Construct an AU DENY decision. Non-overridable when context is active."""
|
|
93
|
+
logger.warning("AU DENY [%s]: %s", rule_id, reason)
|
|
94
|
+
return {
|
|
95
|
+
"decision": "DENY",
|
|
96
|
+
"reason": reason,
|
|
97
|
+
"au_rule": rule_id,
|
|
98
|
+
"au_rule_name": rule_name,
|
|
99
|
+
"non_derogable": True,
|
|
100
|
+
"override_allowed": False,
|
|
101
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Circuit Breaker — halts anomalous agents, cascades to delegation chains."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import datetime, timezone, timedelta
|
|
5
|
+
|
|
6
|
+
from .store import GovernanceStore
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
CLOSED, OPEN, HALF_OPEN = "CLOSED", "OPEN", "HALF_OPEN"
|
|
11
|
+
|
|
12
|
+
DEFAULT_CONFIG = {
|
|
13
|
+
"error_rate_threshold": 0.5,
|
|
14
|
+
"time_window_seconds": 60,
|
|
15
|
+
"cooldown_seconds": 30,
|
|
16
|
+
"max_probe_requests": 3,
|
|
17
|
+
"recovery_conditions": {"consecutive_successes": 3},
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _now() -> str:
|
|
22
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _expiry(seconds: int) -> str:
|
|
26
|
+
return (datetime.now(timezone.utc) + timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CircuitBreakerService:
|
|
30
|
+
def __init__(self, db: GovernanceStore):
|
|
31
|
+
self.db = db
|
|
32
|
+
|
|
33
|
+
async def is_open(self, agent_id: str) -> bool:
|
|
34
|
+
state = await self.db.get_circuit_breaker(agent_id)
|
|
35
|
+
if not state:
|
|
36
|
+
return False
|
|
37
|
+
if state.get("state") == OPEN:
|
|
38
|
+
if _now() > state.get("cooldown_until", ""):
|
|
39
|
+
await self.db.update_circuit_breaker(agent_id, {"state": HALF_OPEN})
|
|
40
|
+
return False
|
|
41
|
+
return True
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
async def get_state(self, agent_id: str) -> str:
|
|
45
|
+
state = await self.db.get_circuit_breaker(agent_id)
|
|
46
|
+
return state.get("state", CLOSED) if state else CLOSED
|
|
47
|
+
|
|
48
|
+
async def record_outcome(self, agent_id: str, success: bool):
|
|
49
|
+
state = await self.db.get_circuit_breaker(agent_id) or {
|
|
50
|
+
"state": CLOSED, "errors": 0, "total": 0, "consecutive_successes": 0,
|
|
51
|
+
}
|
|
52
|
+
state["total"] += 1
|
|
53
|
+
if not success:
|
|
54
|
+
state["errors"] += 1
|
|
55
|
+
state["consecutive_successes"] = 0
|
|
56
|
+
else:
|
|
57
|
+
state["consecutive_successes"] += 1
|
|
58
|
+
|
|
59
|
+
current = state.get("state", CLOSED)
|
|
60
|
+
config = await self._get_config(agent_id)
|
|
61
|
+
|
|
62
|
+
if current == CLOSED and state["total"] >= 5:
|
|
63
|
+
if state["errors"] / state["total"] > config["error_rate_threshold"]:
|
|
64
|
+
await self._trip(agent_id, config)
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
if current == HALF_OPEN and success:
|
|
68
|
+
if state["consecutive_successes"] >= config["recovery_conditions"]["consecutive_successes"]:
|
|
69
|
+
await self._reset(agent_id)
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
if current == HALF_OPEN and not success:
|
|
73
|
+
await self._trip(agent_id, config)
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
await self.db.put_circuit_breaker(agent_id, state)
|
|
77
|
+
|
|
78
|
+
async def manual_reset(self, agent_id: str):
|
|
79
|
+
await self._reset(agent_id)
|
|
80
|
+
|
|
81
|
+
async def _trip(self, agent_id: str, config: dict):
|
|
82
|
+
await self.db.put_circuit_breaker(agent_id, {
|
|
83
|
+
"state": OPEN,
|
|
84
|
+
"tripped_at": _now(),
|
|
85
|
+
"cooldown_until": _expiry(config["cooldown_seconds"]),
|
|
86
|
+
"errors": 0, "total": 0, "consecutive_successes": 0,
|
|
87
|
+
})
|
|
88
|
+
logger.warning("Circuit breaker TRIPPED for agent %s", agent_id)
|
|
89
|
+
# Cascade to delegates
|
|
90
|
+
for d in await self.db.get_delegates(agent_id):
|
|
91
|
+
if target := d.get("target_agent_id"):
|
|
92
|
+
await self._trip(target, config)
|
|
93
|
+
await self.db.put_task({"type": "CIRCUIT_BREAKER", "agent_id": agent_id, "status": "PENDING"})
|
|
94
|
+
|
|
95
|
+
async def _reset(self, agent_id: str):
|
|
96
|
+
await self.db.put_circuit_breaker(agent_id, {
|
|
97
|
+
"state": CLOSED, "errors": 0, "total": 0, "consecutive_successes": 0,
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
async def _get_config(self, agent_id: str) -> dict:
|
|
101
|
+
agent = await self.db.get_agent(agent_id)
|
|
102
|
+
return agent.get("circuit_breaker_config", DEFAULT_CONFIG) if agent else DEFAULT_CONFIG
|
aigp_server/config.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Server configuration — provider selection and initialization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .providers.storage import create as create_storage, StorageProviderBase
|
|
9
|
+
from .providers.scope import ScopeEnvelopeManager, CircuitBreakerService
|
|
10
|
+
from .providers.enforcement import create as create_enforcement, EnforcementAdapterBase
|
|
11
|
+
from .providers.pii import create as create_pii, PiiDetectorBase
|
|
12
|
+
from .providers.key_store import create as create_key_store, KeyStoreBase
|
|
13
|
+
from .providers.consent import ConsentEngine
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class ServerConfig:
|
|
18
|
+
"""Configuration for the AIGP governance server.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
config = ServerConfig(
|
|
22
|
+
storage={"provider": "memory"},
|
|
23
|
+
pii={"provider": "regex"},
|
|
24
|
+
key_store={"provider": "local"},
|
|
25
|
+
enforcement={"provider": "bedrock", "region": "us-east-1"},
|
|
26
|
+
mode="ENFORCE",
|
|
27
|
+
)
|
|
28
|
+
server = config.build()
|
|
29
|
+
"""
|
|
30
|
+
storage: dict = field(default_factory=lambda: {"provider": "memory"})
|
|
31
|
+
pii: dict = field(default_factory=lambda: {"provider": "regex"})
|
|
32
|
+
key_store: dict = field(default_factory=lambda: {"provider": "local"})
|
|
33
|
+
enforcement: dict | None = None
|
|
34
|
+
consent_default_tier: str = "STANDARD"
|
|
35
|
+
mode: str = "REPORT"
|
|
36
|
+
|
|
37
|
+
def build(self) -> "ServerComponents":
|
|
38
|
+
"""Build all server components from config."""
|
|
39
|
+
# Storage
|
|
40
|
+
storage_provider = self.storage.pop("provider", "memory")
|
|
41
|
+
store = create_storage(storage_provider, **self.storage)
|
|
42
|
+
|
|
43
|
+
# PII
|
|
44
|
+
pii_provider = self.pii.pop("provider", "regex")
|
|
45
|
+
pii = create_pii(pii_provider, **self.pii)
|
|
46
|
+
|
|
47
|
+
# Key store
|
|
48
|
+
ks_provider = self.key_store.pop("provider", "local")
|
|
49
|
+
key_store = create_key_store(ks_provider, **self.key_store)
|
|
50
|
+
|
|
51
|
+
# Consent engine
|
|
52
|
+
consent = ConsentEngine(pii, key_store, self.consent_default_tier)
|
|
53
|
+
|
|
54
|
+
# Enforcement (optional)
|
|
55
|
+
enforcement = None
|
|
56
|
+
if self.enforcement:
|
|
57
|
+
enf_provider = self.enforcement.pop("provider")
|
|
58
|
+
enforcement = create_enforcement(enf_provider, **self.enforcement)
|
|
59
|
+
|
|
60
|
+
# Scope + Circuit Breaker
|
|
61
|
+
scope_mgr = ScopeEnvelopeManager(store)
|
|
62
|
+
circuit_breaker = CircuitBreakerService(store)
|
|
63
|
+
|
|
64
|
+
return ServerComponents(
|
|
65
|
+
store=store, scope_mgr=scope_mgr, circuit_breaker=circuit_breaker,
|
|
66
|
+
consent=consent, pii=pii, key_store=key_store,
|
|
67
|
+
enforcement=enforcement, mode=self.mode,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class ServerComponents:
|
|
73
|
+
"""Fully initialized server components."""
|
|
74
|
+
store: StorageProviderBase
|
|
75
|
+
scope_mgr: ScopeEnvelopeManager
|
|
76
|
+
circuit_breaker: CircuitBreakerService
|
|
77
|
+
consent: ConsentEngine
|
|
78
|
+
pii: PiiDetectorBase
|
|
79
|
+
key_store: KeyStoreBase
|
|
80
|
+
enforcement: EnforcementAdapterBase | None
|
|
81
|
+
mode: str
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""EU AI Act Prohibited Practices & High-Risk Rules — RFC-028 Wave 2.
|
|
2
|
+
|
|
3
|
+
These rules implement Article 5 prohibited practices and high-risk
|
|
4
|
+
mandatory requirements. They are NON-DEROGABLE when EU AI Act
|
|
5
|
+
regulatory context is active.
|
|
6
|
+
|
|
7
|
+
Legal basis: Regulation (EU) 2024/1689 (EU AI Act).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
PROHIBITED_PRACTICES = [
|
|
15
|
+
{
|
|
16
|
+
"id": "EUAI-001",
|
|
17
|
+
"name": "SUBLIMINAL_MANIPULATION",
|
|
18
|
+
"article": "Art. 5(1)(a)",
|
|
19
|
+
"description": "AI that deploys subliminal techniques to materially distort behaviour.",
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"id": "EUAI-002",
|
|
23
|
+
"name": "EXPLOITATION_OF_VULNERABILITIES",
|
|
24
|
+
"article": "Art. 5(1)(a)",
|
|
25
|
+
"description": "AI exploiting vulnerabilities due to age, disability, or social/economic situation.",
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"id": "EUAI-003",
|
|
29
|
+
"name": "SOCIAL_SCORING",
|
|
30
|
+
"article": "Art. 5(1)(c)",
|
|
31
|
+
"description": "Social scoring by public authorities leading to detrimental treatment.",
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"id": "EUAI-004",
|
|
35
|
+
"name": "REAL_TIME_BIOMETRIC_ID",
|
|
36
|
+
"article": "Art. 5(1)(d)",
|
|
37
|
+
"description": "Real-time remote biometric identification in publicly accessible spaces for law enforcement.",
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"id": "EUAI-005",
|
|
41
|
+
"name": "PREDICTIVE_POLICING_PROFILING",
|
|
42
|
+
"article": "Art. 5(1)(d)",
|
|
43
|
+
"description": "AI for individual risk assessment predicting criminal offence based solely on profiling.",
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"id": "EUAI-006",
|
|
47
|
+
"name": "UNTARGETED_FACIAL_SCRAPING",
|
|
48
|
+
"article": "Art. 5(1)(e)",
|
|
49
|
+
"description": "Untargeted scraping of facial images from internet or CCTV for facial recognition databases.",
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"id": "EUAI-007",
|
|
53
|
+
"name": "EMOTION_INFERENCE_WORKPLACE",
|
|
54
|
+
"article": "Art. 5(1)(f)",
|
|
55
|
+
"description": "Inferring emotions in workplace or educational institutions except for safety/medical reasons.",
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"id": "EUAI-008",
|
|
59
|
+
"name": "BIOMETRIC_CATEGORISATION_SENSITIVE",
|
|
60
|
+
"article": "Art. 5(1)(g)",
|
|
61
|
+
"description": "Biometric categorisation to infer race, political opinions, trade union membership, religious beliefs, sex life or sexual orientation.",
|
|
62
|
+
},
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
HIGH_RISK_CHECKS = {
|
|
66
|
+
"fria_required": "Fundamental Rights Impact Assessment must be completed before deployment.",
|
|
67
|
+
"human_oversight_required": "Human oversight mechanism must be designated.",
|
|
68
|
+
"trace_mode_mandatory": "Logging/traceability mode must be active for high-risk systems.",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
_SUBLIMINAL_TECHNIQUES = {"subliminal", "dark_pattern", "subconscious", "manipulation"}
|
|
72
|
+
_VULNERABLE_GROUPS = {"minors", "children", "elderly", "disabled", "economically_disadvantaged"}
|
|
73
|
+
_SENSITIVE_BIOMETRIC_ATTRS = {"race", "ethnicity", "political_opinions", "trade_union", "religion", "sex_life", "sexual_orientation"}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def evaluate_euai_rules(request: dict, context: dict) -> dict | None:
|
|
77
|
+
"""Evaluate EU AI Act rules against a request.
|
|
78
|
+
|
|
79
|
+
Returns a DENY decision dict if a rule triggers, or None to allow
|
|
80
|
+
continuation to configurable policy evaluation.
|
|
81
|
+
"""
|
|
82
|
+
if not context or not context.get("active"):
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
technique = request.get("technique", "").lower()
|
|
86
|
+
use_case = request.get("use_case", "").lower()
|
|
87
|
+
target_group = request.get("target_group", "").lower()
|
|
88
|
+
data_source = request.get("data_source", "").lower()
|
|
89
|
+
data_type = request.get("data_type", "").lower()
|
|
90
|
+
req_context = request.get("context", "").lower()
|
|
91
|
+
inferred_attribute = request.get("inferred_attribute", "").lower()
|
|
92
|
+
location = request.get("location", "").lower()
|
|
93
|
+
purpose = request.get("purpose", "").lower()
|
|
94
|
+
|
|
95
|
+
# EUAI-001: Subliminal manipulation
|
|
96
|
+
if technique in _SUBLIMINAL_TECHNIQUES or "subliminal" in purpose:
|
|
97
|
+
return _deny("EUAI-001", "SUBLIMINAL_MANIPULATION",
|
|
98
|
+
"Subliminal techniques that materially distort behaviour are prohibited. (Art. 5(1)(a))")
|
|
99
|
+
|
|
100
|
+
# EUAI-002: Exploitation of vulnerabilities
|
|
101
|
+
if target_group in _VULNERABLE_GROUPS and technique in {"persuasion", "targeting", "manipulation", "nudging"}:
|
|
102
|
+
return _deny("EUAI-002", "EXPLOITATION_OF_VULNERABILITIES",
|
|
103
|
+
f"Exploiting vulnerabilities of group '{target_group}' is prohibited. (Art. 5(1)(a))")
|
|
104
|
+
|
|
105
|
+
# EUAI-003: Social scoring
|
|
106
|
+
if use_case in {"social_scoring", "citizen_scoring", "social_credit"} or (
|
|
107
|
+
purpose == "social_scoring" and req_context in {"public_authority", "government"}
|
|
108
|
+
):
|
|
109
|
+
return _deny("EUAI-003", "SOCIAL_SCORING",
|
|
110
|
+
"Social scoring by public authorities is prohibited. (Art. 5(1)(c))")
|
|
111
|
+
|
|
112
|
+
# EUAI-004: Real-time biometric identification
|
|
113
|
+
if (data_type in {"biometric", "facial"} and "real_time" in use_case
|
|
114
|
+
and location in {"public_space", "public", "publicly_accessible"}):
|
|
115
|
+
return _deny("EUAI-004", "REAL_TIME_BIOMETRIC_ID",
|
|
116
|
+
"Real-time remote biometric identification in public spaces is prohibited. (Art. 5(1)(d))")
|
|
117
|
+
|
|
118
|
+
# EUAI-005: Predictive policing based on profiling
|
|
119
|
+
if use_case in {"predictive_policing", "crime_prediction"} and technique in {"profiling", "risk_scoring"}:
|
|
120
|
+
return _deny("EUAI-005", "PREDICTIVE_POLICING_PROFILING",
|
|
121
|
+
"Predicting criminal offence based solely on profiling is prohibited. (Art. 5(1)(d))")
|
|
122
|
+
|
|
123
|
+
# EUAI-006: Untargeted facial scraping
|
|
124
|
+
if use_case in {"facial_scraping", "face_database"} and data_source in {"internet", "cctv", "web_scraping", "surveillance"}:
|
|
125
|
+
return _deny("EUAI-006", "UNTARGETED_FACIAL_SCRAPING",
|
|
126
|
+
"Untargeted scraping of facial images for recognition databases is prohibited. (Art. 5(1)(e))")
|
|
127
|
+
|
|
128
|
+
# EUAI-007: Emotion inference in workplace/education
|
|
129
|
+
if inferred_attribute in {"emotion", "emotions", "emotional_state"} and req_context in {"workplace", "education", "school"}:
|
|
130
|
+
return _deny("EUAI-007", "EMOTION_INFERENCE_WORKPLACE",
|
|
131
|
+
"Inferring emotions in workplace or educational settings is prohibited. (Art. 5(1)(f))")
|
|
132
|
+
|
|
133
|
+
# EUAI-008: Biometric categorisation of sensitive attributes
|
|
134
|
+
if data_type in {"biometric", "biometric_data"} and inferred_attribute in _SENSITIVE_BIOMETRIC_ATTRS:
|
|
135
|
+
return _deny("EUAI-008", "BIOMETRIC_CATEGORISATION_SENSITIVE",
|
|
136
|
+
f"Biometric categorisation to infer '{inferred_attribute}' is prohibited. (Art. 5(1)(g))")
|
|
137
|
+
|
|
138
|
+
# HIGH-RISK checks (if context marks system as high-risk)
|
|
139
|
+
if context.get("risk_level") == "high":
|
|
140
|
+
if not request.get("fria_completed"):
|
|
141
|
+
return _deny("EUAI-HR-001", "FRIA_REQUIRED",
|
|
142
|
+
HIGH_RISK_CHECKS["fria_required"])
|
|
143
|
+
if not request.get("human_oversight"):
|
|
144
|
+
return _deny("EUAI-HR-002", "HUMAN_OVERSIGHT_REQUIRED",
|
|
145
|
+
HIGH_RISK_CHECKS["human_oversight_required"])
|
|
146
|
+
if not request.get("trace_mode"):
|
|
147
|
+
return _deny("EUAI-HR-003", "TRACE_MODE_MANDATORY",
|
|
148
|
+
HIGH_RISK_CHECKS["trace_mode_mandatory"])
|
|
149
|
+
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _deny(rule_id: str, rule_name: str, reason: str) -> dict:
|
|
154
|
+
"""Construct an EU AI Act DENY decision. Non-overridable."""
|
|
155
|
+
logger.warning("EUAI DENY [%s]: %s", rule_id, reason)
|
|
156
|
+
return {
|
|
157
|
+
"decision": "DENY",
|
|
158
|
+
"reason": reason,
|
|
159
|
+
"euai_rule": rule_id,
|
|
160
|
+
"euai_rule_name": rule_name,
|
|
161
|
+
"non_derogable": True,
|
|
162
|
+
"override_allowed": False,
|
|
163
|
+
}
|