File size: 8,162 Bytes
61f1cb2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | # sovereign_ultra_layer.py
# ---------------------------------------------------------------------
# Sovereign™ Ultra Layer (10 capabilities bundle)
# - Designed as a NON-INTRUSIVE plugin layer (no changes to core required)
# - Safe-by-default: if not wired, it does nothing.
# - When wired, it can gate requests, detect risky intent, and enforce policy.
# ---------------------------------------------------------------------
from __future__ import annotations
import time
import hashlib
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple, List
# -------------------------
# Capability Registry (10)
# -------------------------
CAPABILITIES = [
"Cognitive Deception", # Response Wrapper
"Intent Immunity", # Pre-Request Analyzer
"Temporal Reality Lock", # Execution Gate
"Model DNA + Genome", # Parallel Verifier
"One-Way Execution", # Output Transform
"AI Panic Mode", # Emergency Control
"Memory Poison Defense", # Memory Gateway
"Silent Refusal", # Response Policy
"Kill-Switch Mesh", # Control Plane
"ISF (Integrity Sentinel Fabric)", # Diamond capability (fabric-level integrity)
]
# -------------------------
# Configuration (safe defaults)
# -------------------------
@dataclass
class UltraConfig:
enabled: bool = True
# Hard safety defaults:
block_on_high_risk: bool = True
risk_threshold: float = 0.85
# Optional controls:
allowlist_roles: Tuple[str, ...] = ("admin", "security", "governance")
panic_mode: bool = False
# ISF toggles (kept lightweight):
isf_enabled: bool = True
isf_challenge_interval_sec: int = 0 # 0 => every request can be challenged if wired
# Performance: keep analysis cheap
max_text_scan: int = 3000
@dataclass
class UltraSignal:
timestamp: int
request_id: str
risk_score: float
flags: List[str] = field(default_factory=list)
action: str = "allow" # allow | refuse | panic_lock
notes: Dict[str, Any] = field(default_factory=dict)
def _now() -> int:
return int(time.time())
def _sha256(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def _clip(text: str, n: int) -> str:
if text is None:
return ""
return text[:n]
# -------------------------
# Lightweight Risk Heuristics (defensive)
# -------------------------
_RISK_KEYWORDS = [
"exploit", "bypass", "steal", "exfiltrate", "malware", "ransomware",
"phishing", "credential", "backdoor", "inject", "prompt injection",
"privilege escalation", "rootkit", "keylogger"
]
_HIGH_SENSITIVITY_CONTEXT = [
"bank", "central bank", "government", "defence", "critical infrastructure",
"classified", "top secret", "intel", "national security"
]
def _risk_score(text: str) -> Tuple[float, List[str]]:
"""
Very lightweight scoring.
This is NOT a full classifier; it's a safe, explainable heuristic layer.
"""
t = (text or "").lower()
flags: List[str] = []
score = 0.0
for kw in _RISK_KEYWORDS:
if kw in t:
flags.append(f"kw:{kw}")
score += 0.12
for kw in _HIGH_SENSITIVITY_CONTEXT:
if kw in t:
flags.append(f"context:{kw}")
score += 0.06
# Cap score into [0, 1]
score = max(0.0, min(1.0, score))
return score, flags
# -------------------------
# ISF (Integrity Sentinel Fabric) - minimal, non-invasive core
# -------------------------
@dataclass
class ISFState:
"""
Stores lightweight integrity 'beats' to detect unexpected execution drift
when wired into runtime.
"""
last_beat_ts: int = 0
last_beat_hash: str = ""
def isf_beat(state: ISFState, challenge_seed: str) -> ISFState:
"""
Creates a deterministic integrity beat.
When wired, caller can store/compare these beats to detect drift/tampering.
"""
ts = _now()
beat_payload = f"{challenge_seed}|{ts}"
beat_hash = _sha256(beat_payload)
state.last_beat_ts = ts
state.last_beat_hash = beat_hash
return state
def isf_verify(state: ISFState, expected_hash: str) -> bool:
"""
Verify that an expected beat hash matches current state.
"""
if not state.last_beat_hash:
return False
return state.last_beat_hash == expected_hash
# -------------------------
# Main Ultra Layer Entry Point
# -------------------------
@dataclass
class UltraResult:
allowed: bool
action: str
risk_score: float
flags: List[str]
# You can optionally modify/transform response downstream:
transformed_output: Optional[str] = None
# Signals for audit/logging:
signal: Optional[UltraSignal] = None
class SovereignUltraLayer:
"""
Plug-in layer to be called BEFORE and/or AFTER core operations.
If not used, it does nothing and cannot break Sovereign.
"""
def __init__(self, config: Optional[UltraConfig] = None):
self.config = config or UltraConfig()
self.isf_state = ISFState()
def pre_request(self, request_text: str, context: Optional[Dict[str, Any]] = None) -> UltraResult:
"""
Defensive gate: evaluates intent risk, handles panic mode, prepares ISF beat.
"""
if not self.config.enabled:
return UltraResult(True, "allow", 0.0, [])
ctx = context or {}
req_id = str(ctx.get("request_id") or _sha256(f"{request_text}|{_now()}")[:12])
# Panic mode = immediate lock unless allowlisted role
role = str(ctx.get("role") or "").lower()
if self.config.panic_mode and role not in self.config.allowlist_roles:
sig = UltraSignal(
timestamp=_now(),
request_id=req_id,
risk_score=1.0,
flags=["panic_mode"],
action="panic_lock",
notes={"role": role},
)
return UltraResult(False, "panic_lock", 1.0, ["panic_mode"], signal=sig)
scan_text = _clip(request_text, self.config.max_text_scan)
score, flags = _risk_score(scan_text)
# ISF beat (optional)
if self.config.isf_enabled:
# Challenge seed can include stable identifiers without exposing secrets
seed = f"SOVEREIGN|{ctx.get('deployment_env','unknown')}|{ctx.get('model_version','unknown')}"
self.isf_state = isf_beat(self.isf_state, seed)
action = "allow"
allowed = True
if self.config.block_on_high_risk and score >= self.config.risk_threshold:
action = "refuse"
allowed = False
flags = flags + ["risk:block_threshold"]
sig = UltraSignal(
timestamp=_now(),
request_id=req_id,
risk_score=score,
flags=flags,
action=action,
notes={
"capabilities": CAPABILITIES,
"isf_last_hash": self.isf_state.last_beat_hash if self.config.isf_enabled else None,
},
)
return UltraResult(allowed, action, score, flags, signal=sig)
def post_response(self, output_text: str, pre: UltraResult) -> UltraResult:
"""
Defensive output policy hook.
For now: "Silent Refusal" style if blocked; otherwise pass-through.
"""
if not self.config.enabled:
return UltraResult(True, "allow", 0.0, [], transformed_output=output_text)
if not pre.allowed:
# Silent refusal: minimal disclosure
return UltraResult(
False,
pre.action,
pre.risk_score,
pre.flags,
transformed_output="Request blocked by Sovereign policy.",
signal=pre.signal,
)
# Output transform hook (kept neutral/light)
return UltraResult(
True,
"allow",
pre.risk_score,
pre.flags,
transformed_output=output_text,
signal=pre.signal,
)
# Convenience singleton (optional use)
ULTRA_LAYER = SovereignUltraLayer()
|