Compare commits
1 Commits
codex/crea
...
codex/upda
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0674dfa22 |
@@ -9,27 +9,26 @@ from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime, timedelta
|
||||
from loguru import logger
|
||||
|
||||
from services.database import get_user_db_path
|
||||
from services.token_crypto_service import TokenCryptoService
|
||||
|
||||
from services.database import get_user_db_path
|
||||
|
||||
class WixOAuthService:
|
||||
"""Manages Wix OAuth2 authentication flow and token storage."""
|
||||
|
||||
|
||||
def __init__(self, db_path: Optional[str] = None):
|
||||
self.db_path = db_path
|
||||
self.token_crypto = TokenCryptoService()
|
||||
|
||||
|
||||
def _get_db_path(self, user_id: str) -> str:
|
||||
if self.db_path:
|
||||
return self.db_path
|
||||
return get_user_db_path(user_id)
|
||||
|
||||
|
||||
def _init_db(self, user_id: str):
|
||||
"""Initialize database tables for OAuth tokens."""
|
||||
db_path = self._get_db_path(user_id)
|
||||
# Ensure directory exists
|
||||
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
||||
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
@@ -46,133 +45,168 @@ class WixOAuthService:
|
||||
member_id TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
token_key_version TEXT,
|
||||
token_key_reference TEXT
|
||||
is_active BOOLEAN DEFAULT TRUE
|
||||
)
|
||||
''')
|
||||
for column_name, column_def in [
|
||||
("token_key_version", "TEXT"),
|
||||
("token_key_reference", "TEXT"),
|
||||
]:
|
||||
try:
|
||||
cursor.execute(f"ALTER TABLE wix_oauth_tokens ADD COLUMN {column_name} {column_def}")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
conn.commit()
|
||||
|
||||
def store_tokens(self, user_id: str, access_token: str, refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None, token_type: str = 'bearer', scope: Optional[str] = None,
|
||||
site_id: Optional[str] = None, member_id: Optional[str] = None) -> bool:
|
||||
|
||||
def store_tokens(
|
||||
self,
|
||||
user_id: str,
|
||||
access_token: str,
|
||||
refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None,
|
||||
token_type: str = 'bearer',
|
||||
scope: Optional[str] = None,
|
||||
site_id: Optional[str] = None,
|
||||
member_id: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Store Wix OAuth tokens in the database.
|
||||
|
||||
Args:
|
||||
user_id: User ID (Clerk string)
|
||||
access_token: Access token from Wix
|
||||
refresh_token: Optional refresh token
|
||||
expires_in: Optional expiration time in seconds
|
||||
token_type: Token type (default: 'bearer')
|
||||
scope: Optional OAuth scope
|
||||
site_id: Optional Wix site ID
|
||||
member_id: Optional Wix member ID
|
||||
|
||||
Returns:
|
||||
True if tokens were stored successfully
|
||||
"""
|
||||
try:
|
||||
# Ensure DB is initialized for this user
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in) if expires_in else None
|
||||
encrypted_access_token, encrypted_refresh_token = self.token_crypto.encrypt_pair(access_token, refresh_token)
|
||||
|
||||
|
||||
expires_at = None
|
||||
if expires_in:
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in)
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO wix_oauth_tokens
|
||||
(user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, token_key_version, token_key_reference)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
user_id,
|
||||
encrypted_access_token,
|
||||
encrypted_refresh_token,
|
||||
token_type,
|
||||
expires_at,
|
||||
expires_in,
|
||||
scope,
|
||||
site_id,
|
||||
member_id,
|
||||
self.token_crypto.key_version,
|
||||
self.token_crypto.key_reference,
|
||||
))
|
||||
INSERT INTO wix_oauth_tokens
|
||||
(user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id))
|
||||
conn.commit()
|
||||
logger.info(f"Wix OAuth: Encrypted token stored for user {user_id}")
|
||||
logger.info(f"Wix OAuth: Token inserted into database for user {user_id}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error storing Wix tokens for user {user_id}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_user_tokens(self, user_id: str) -> List[Dict[str, Any]]:
|
||||
"""Get all active Wix token rows (encrypted values)."""
|
||||
"""Get all active Wix tokens for a user."""
|
||||
try:
|
||||
# Ensure database tables exist to prevent 'no such table' errors
|
||||
self._init_db(user_id)
|
||||
|
||||
db_path = self._get_db_path(user_id)
|
||||
if not os.path.exists(db_path):
|
||||
return []
|
||||
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at, token_key_version, token_key_reference
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ? AND is_active = TRUE AND (expires_at IS NULL OR expires_at > datetime('now'))
|
||||
ORDER BY created_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
return [{
|
||||
"id": row[0], "access_token": row[1], "refresh_token": row[2], "token_type": row[3],
|
||||
"expires_at": row[4], "expires_in": row[5], "scope": row[6], "site_id": row[7],
|
||||
"member_id": row[8], "created_at": row[9], "token_key_version": row[10],
|
||||
"token_key_reference": row[11]
|
||||
} for row in cursor.fetchall()]
|
||||
|
||||
tokens = []
|
||||
for row in cursor.fetchall():
|
||||
tokens.append({
|
||||
"id": row[0],
|
||||
"access_token": row[1],
|
||||
"refresh_token": row[2],
|
||||
"token_type": row[3],
|
||||
"expires_at": row[4],
|
||||
"expires_in": row[5],
|
||||
"scope": row[6],
|
||||
"site_id": row[7],
|
||||
"member_id": row[8],
|
||||
"created_at": row[9]
|
||||
})
|
||||
|
||||
return tokens
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting Wix tokens for user {user_id}: {e}")
|
||||
return []
|
||||
|
||||
def get_user_tokens_decrypted(self, user_id: str) -> List[Dict[str, Any]]:
|
||||
"""Decrypt tokens for integration managers and token refresh routines."""
|
||||
decrypted = []
|
||||
for token in self.get_user_tokens(user_id):
|
||||
token_copy = dict(token)
|
||||
token_copy["access_token"] = self.token_crypto.decrypt_token(token_copy.get("access_token"))
|
||||
token_copy["refresh_token"] = self.token_crypto.decrypt_token(token_copy.get("refresh_token"))
|
||||
decrypted.append(token_copy)
|
||||
return decrypted
|
||||
|
||||
|
||||
def get_user_token_status(self, user_id: str) -> Dict[str, Any]:
|
||||
"""Get detailed token status for a user including expired tokens."""
|
||||
try:
|
||||
# Ensure database tables exist to prevent 'no such table' errors
|
||||
self._init_db(user_id)
|
||||
|
||||
db_path = self._get_db_path(user_id)
|
||||
if not os.path.exists(db_path):
|
||||
return {"has_tokens": False, "has_active_tokens": False, "has_expired_tokens": False,
|
||||
"active_tokens": [], "expired_tokens": [], "total_tokens": 0, "last_token_date": None}
|
||||
return {
|
||||
"has_tokens": False,
|
||||
"has_active_tokens": False,
|
||||
"has_expired_tokens": False,
|
||||
"active_tokens": [],
|
||||
"expired_tokens": [],
|
||||
"total_tokens": 0,
|
||||
"last_token_date": None
|
||||
}
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Get all tokens (active and expired)
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id,
|
||||
created_at, is_active, token_key_version, token_key_reference
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at, is_active
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
all_tokens, active_tokens, expired_tokens = [], [], []
|
||||
|
||||
all_tokens = []
|
||||
active_tokens = []
|
||||
expired_tokens = []
|
||||
|
||||
for row in cursor.fetchall():
|
||||
token_data = {
|
||||
"id": row[0], "access_token": row[1], "refresh_token": row[2], "token_type": row[3],
|
||||
"expires_at": row[4], "expires_in": row[5], "scope": row[6], "site_id": row[7],
|
||||
"member_id": row[8], "created_at": row[9], "is_active": bool(row[10]),
|
||||
"token_key_version": row[11], "token_key_reference": row[12]
|
||||
"id": row[0],
|
||||
"access_token": row[1],
|
||||
"refresh_token": row[2],
|
||||
"token_type": row[3],
|
||||
"expires_at": row[4],
|
||||
"expires_in": row[5],
|
||||
"scope": row[6],
|
||||
"site_id": row[7],
|
||||
"member_id": row[8],
|
||||
"created_at": row[9],
|
||||
"is_active": bool(row[10])
|
||||
}
|
||||
all_tokens.append(token_data)
|
||||
|
||||
|
||||
# Determine expiry using robust parsing and is_active flag
|
||||
is_active_flag = bool(row[10])
|
||||
not_expired = False
|
||||
try:
|
||||
expires_at_val = row[4]
|
||||
if expires_at_val:
|
||||
# First try Python parsing
|
||||
try:
|
||||
dt = datetime.fromisoformat(expires_at_val) if isinstance(expires_at_val, str) else expires_at_val
|
||||
not_expired = dt > datetime.now()
|
||||
except Exception:
|
||||
# Fallback to SQLite comparison
|
||||
cursor.execute("SELECT datetime('now') < ?", (expires_at_val,))
|
||||
not_expired = cursor.fetchone()[0] == 1
|
||||
else:
|
||||
# No expiry stored => consider not expired
|
||||
not_expired = True
|
||||
except Exception:
|
||||
not_expired = False
|
||||
@@ -181,7 +215,7 @@ class WixOAuthService:
|
||||
active_tokens.append(token_data)
|
||||
else:
|
||||
expired_tokens.append(token_data)
|
||||
|
||||
|
||||
return {
|
||||
"has_tokens": len(all_tokens) > 0,
|
||||
"has_active_tokens": len(active_tokens) > 0,
|
||||
@@ -191,101 +225,81 @@ class WixOAuthService:
|
||||
"total_tokens": len(all_tokens),
|
||||
"last_token_date": all_tokens[0]["created_at"] if all_tokens else None
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting Wix token status for user {user_id}: {e}")
|
||||
return {"has_tokens": False, "has_active_tokens": False, "has_expired_tokens": False,
|
||||
"active_tokens": [], "expired_tokens": [], "total_tokens": 0, "last_token_date": None, "error": str(e)}
|
||||
|
||||
def update_tokens(self, user_id: str, access_token: str, refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None) -> bool:
|
||||
return {
|
||||
"has_tokens": False,
|
||||
"has_active_tokens": False,
|
||||
"has_expired_tokens": False,
|
||||
"active_tokens": [],
|
||||
"expired_tokens": [],
|
||||
"total_tokens": 0,
|
||||
"last_token_date": None,
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
def update_tokens(
|
||||
self,
|
||||
user_id: str,
|
||||
access_token: str,
|
||||
refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None
|
||||
) -> bool:
|
||||
"""Update tokens for a user (e.g., after refresh)."""
|
||||
try:
|
||||
# Ensure DB initialized for this user
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in) if expires_in else None
|
||||
encrypted_access_token = self.token_crypto.encrypt_token(access_token)
|
||||
encrypted_refresh_token = self.token_crypto.encrypt_token(refresh_token) if refresh_token else None
|
||||
|
||||
expires_at = None
|
||||
if expires_in:
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in)
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
if refresh_token:
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now'), token_key_version = ?, token_key_reference = ?
|
||||
WHERE user_id = ? AND (refresh_token = ? OR refresh_token = ?)
|
||||
''', (encrypted_access_token, encrypted_refresh_token, expires_at, expires_in,
|
||||
self.token_crypto.key_version, self.token_crypto.key_reference,
|
||||
user_id, encrypted_refresh_token, refresh_token))
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND refresh_token = ?
|
||||
''', (access_token, refresh_token, expires_at, expires_in, user_id, refresh_token))
|
||||
else:
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now'), token_key_version = ?, token_key_reference = ?
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND id = (SELECT id FROM wix_oauth_tokens WHERE user_id = ? ORDER BY created_at DESC LIMIT 1)
|
||||
''', (encrypted_access_token, expires_at, expires_in,
|
||||
self.token_crypto.key_version, self.token_crypto.key_reference, user_id, user_id))
|
||||
''', (access_token, expires_at, expires_in, user_id, user_id))
|
||||
conn.commit()
|
||||
logger.info(f"Wix OAuth: Encrypted tokens updated for user {user_id}")
|
||||
logger.info(f"Wix OAuth: Tokens updated for user {user_id}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating Wix tokens for user {user_id}: {e}")
|
||||
return False
|
||||
|
||||
def rotate_token_encryption(self, user_id: str, batch_size: int = 100) -> Dict[str, int]:
|
||||
"""Re-encrypt existing token rows in batches for key rotation."""
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
rotated, skipped, last_id = 0, 0, 0
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
while True:
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ? AND id > ?
|
||||
ORDER BY id ASC
|
||||
LIMIT ?
|
||||
''', (user_id, last_id, batch_size))
|
||||
rows = cursor.fetchall()
|
||||
if not rows:
|
||||
break
|
||||
|
||||
for row_id, enc_access, enc_refresh in rows:
|
||||
last_id = row_id
|
||||
try:
|
||||
plain_access = self.token_crypto.decrypt_token(enc_access)
|
||||
plain_refresh = self.token_crypto.decrypt_token(enc_refresh) if enc_refresh else None
|
||||
except Exception:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
new_access, new_refresh = self.token_crypto.encrypt_pair(plain_access, plain_refresh)
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, token_key_version = ?, token_key_reference = ?, updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
''', (new_access, new_refresh, self.token_crypto.key_version, self.token_crypto.key_reference, row_id))
|
||||
rotated += 1
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"Wix OAuth: Encryption rotation complete for user {user_id}; rotated={rotated}, skipped={skipped}")
|
||||
return {"rotated": rotated, "skipped": skipped}
|
||||
|
||||
|
||||
def revoke_token(self, user_id: str, token_id: int) -> bool:
|
||||
"""Revoke a Wix OAuth token."""
|
||||
try:
|
||||
db_path = self._get_db_path(user_id)
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
UPDATE wix_oauth_tokens
|
||||
SET is_active = FALSE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND id = ?
|
||||
''', (user_id, token_id))
|
||||
conn.commit()
|
||||
|
||||
if cursor.rowcount > 0:
|
||||
logger.info(f"Wix token {token_id} revoked for user {user_id}")
|
||||
return True
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error revoking Wix token: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -99,6 +99,58 @@ class OptimizationRecommendation:
|
||||
expires = datetime.utcnow().timestamp() + (7 * 24 * 60 * 60)
|
||||
self.expires_at = datetime.fromtimestamp(expires).isoformat()
|
||||
|
||||
|
||||
|
||||
@dataclass
|
||||
class EscalationVelocitySignal:
|
||||
"""Measured action velocity signal used for escalation tiering."""
|
||||
window_minutes: int
|
||||
action_count: int
|
||||
actions_per_minute: float
|
||||
triggered: bool
|
||||
|
||||
|
||||
class EscalationTier(Enum):
|
||||
"""Escalation tier derived from measurable action velocity."""
|
||||
TIER_1 = "tier_1"
|
||||
TIER_2 = "tier_2"
|
||||
TIER_3 = "tier_3"
|
||||
|
||||
|
||||
class EscalationVelocityPolicy:
|
||||
"""Velocity-based trigger policy for escalation tiers."""
|
||||
|
||||
def __init__(self):
|
||||
self.tier_thresholds = {
|
||||
EscalationTier.TIER_1: {"window_minutes": 15, "actions_per_minute": 0.8},
|
||||
EscalationTier.TIER_2: {"window_minutes": 10, "actions_per_minute": 1.5},
|
||||
EscalationTier.TIER_3: {"window_minutes": 5, "actions_per_minute": 3.0},
|
||||
}
|
||||
|
||||
def measure_velocity(self, events: List[Dict[str, Any]], now: Optional[datetime] = None) -> Dict[EscalationTier, EscalationVelocitySignal]:
|
||||
now = now or datetime.utcnow()
|
||||
signals: Dict[EscalationTier, EscalationVelocitySignal] = {}
|
||||
|
||||
for tier, cfg in self.tier_thresholds.items():
|
||||
cutoff = now - timedelta(minutes=cfg["window_minutes"])
|
||||
count = sum(1 for event in events if datetime.fromisoformat(event["timestamp"]) >= cutoff)
|
||||
velocity = count / max(cfg["window_minutes"], 1)
|
||||
signals[tier] = EscalationVelocitySignal(
|
||||
window_minutes=cfg["window_minutes"],
|
||||
action_count=count,
|
||||
actions_per_minute=velocity,
|
||||
triggered=velocity >= cfg["actions_per_minute"]
|
||||
)
|
||||
|
||||
return signals
|
||||
|
||||
def determine_tier(self, events: List[Dict[str, Any]], now: Optional[datetime] = None) -> Tuple[Optional[EscalationTier], Dict[EscalationTier, EscalationVelocitySignal]]:
|
||||
signals = self.measure_velocity(events, now=now)
|
||||
for tier in [EscalationTier.TIER_3, EscalationTier.TIER_2, EscalationTier.TIER_1]:
|
||||
if signals[tier].triggered:
|
||||
return tier, signals
|
||||
return None, signals
|
||||
|
||||
class AgentPerformanceMonitor:
|
||||
"""Main performance monitoring system for agents"""
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from enum import Enum
|
||||
|
||||
from utils.logger_utils import get_service_logger
|
||||
from services.database import get_session_for_user
|
||||
from services.intelligence.agents.performance_monitor import EscalationVelocityPolicy, EscalationTier
|
||||
|
||||
logger = get_service_logger(__name__)
|
||||
|
||||
@@ -84,6 +85,25 @@ class SafetyValidation:
|
||||
if self.validation_timestamp is None:
|
||||
self.validation_timestamp = datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
|
||||
@dataclass
|
||||
class EscalationDecision:
|
||||
"""Structured escalation payload for autonomous safety routing."""
|
||||
tier: str
|
||||
action: str
|
||||
confidence: float
|
||||
risk_class: str
|
||||
rationale: str
|
||||
velocity: Dict[str, Any]
|
||||
lockout_auto_edits: bool
|
||||
executor: Optional[str]
|
||||
created_at: str = None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.created_at is None:
|
||||
self.created_at = datetime.utcnow().isoformat()
|
||||
|
||||
class SafetyConstraintManager:
|
||||
"""Manages safety constraints for agent actions"""
|
||||
|
||||
@@ -92,6 +112,11 @@ class SafetyConstraintManager:
|
||||
self.constraints: Dict[str, SafetyConstraint] = {}
|
||||
self.action_history: List[Dict[str, Any]] = []
|
||||
self.violation_history: List[Dict[str, Any]] = []
|
||||
self.escalation_policy = EscalationVelocityPolicy()
|
||||
self.escalation_history: List[Dict[str, Any]] = []
|
||||
self.auto_edit_lockout = False
|
||||
self.executor_routes = {"tier_1": "autonomous_guardian_executor", "tier_2": "autonomous_recovery_executor"}
|
||||
self.alert_history: List[Dict[str, Any]] = []
|
||||
|
||||
# Initialize default constraints
|
||||
self._initialize_default_constraints()
|
||||
@@ -213,7 +238,7 @@ class SafetyConstraintManager:
|
||||
# Record in history
|
||||
await self._record_validation_history(action_data, is_valid, violations)
|
||||
|
||||
return SafetyValidation(
|
||||
validation = SafetyValidation(
|
||||
is_valid=is_valid,
|
||||
risk_level=risk_level,
|
||||
violations=violations,
|
||||
@@ -221,6 +246,10 @@ class SafetyConstraintManager:
|
||||
requires_approval=requires_approval,
|
||||
confidence_score=max(0.0, min(1.0, confidence_score))
|
||||
)
|
||||
escalation = await self.evaluate_escalation(action_data, validation)
|
||||
if escalation:
|
||||
recommendations.append(f"Escalation action: {escalation.action} ({escalation.tier})")
|
||||
return validation
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error validating action for user {self.user_id}: {e}")
|
||||
@@ -466,6 +495,97 @@ class SafetyConstraintManager:
|
||||
if len(self.violation_history) > 500:
|
||||
self.violation_history = self.violation_history[-500:]
|
||||
|
||||
async def evaluate_escalation(self, action_data: Dict[str, Any], validation: SafetyValidation) -> Optional[EscalationDecision]:
|
||||
"""Evaluate velocity-triggered escalation and produce structured decision payload."""
|
||||
if self.auto_edit_lockout:
|
||||
decision = EscalationDecision(
|
||||
tier=EscalationTier.TIER_3.value,
|
||||
action="lockout_enforced",
|
||||
confidence=1.0,
|
||||
risk_class=RiskLevel.CRITICAL.value,
|
||||
rationale="Tier 3 lockout already active; autonomous edits blocked until manual reset",
|
||||
velocity={},
|
||||
lockout_auto_edits=True,
|
||||
executor=None
|
||||
)
|
||||
await self._persist_escalation_decision(decision, action_data, outcome={"status": "blocked_by_lockout"})
|
||||
return decision
|
||||
|
||||
tier, signals = self.escalation_policy.determine_tier(self.action_history)
|
||||
if not tier:
|
||||
return None
|
||||
|
||||
risk_class_map = {EscalationTier.TIER_1: RiskLevel.MEDIUM.value, EscalationTier.TIER_2: RiskLevel.HIGH.value, EscalationTier.TIER_3: RiskLevel.CRITICAL.value}
|
||||
confidence = min(1.0, max(0.1, 0.55 + (len(validation.violations) * 0.05) + ((1 - validation.confidence_score) * 0.4)))
|
||||
|
||||
velocity_signal = signals[tier]
|
||||
velocity_payload = {
|
||||
"window_minutes": velocity_signal.window_minutes,
|
||||
"action_count": velocity_signal.action_count,
|
||||
"actions_per_minute": round(velocity_signal.actions_per_minute, 4),
|
||||
"threshold_actions_per_minute": self.escalation_policy.tier_thresholds[tier]["actions_per_minute"],
|
||||
}
|
||||
|
||||
executor = self.executor_routes.get(tier.value)
|
||||
action = "route_to_autonomous_executor" if tier in (EscalationTier.TIER_1, EscalationTier.TIER_2) else "lockout_autonomous_edits"
|
||||
rationale = f"{tier.value} triggered by velocity {velocity_payload['actions_per_minute']}/min over {velocity_signal.window_minutes}m window"
|
||||
|
||||
decision = EscalationDecision(
|
||||
tier=tier.value,
|
||||
action=action,
|
||||
confidence=round(confidence, 3),
|
||||
risk_class=risk_class_map[tier],
|
||||
rationale=rationale,
|
||||
velocity=velocity_payload,
|
||||
lockout_auto_edits=(tier == EscalationTier.TIER_3),
|
||||
executor=executor if tier != EscalationTier.TIER_3 else None
|
||||
)
|
||||
|
||||
outcome = await self._apply_escalation_decision(decision, action_data, validation)
|
||||
await self._persist_escalation_decision(decision, action_data, outcome=outcome)
|
||||
return decision
|
||||
|
||||
async def _apply_escalation_decision(self, decision: EscalationDecision, action_data: Dict[str, Any], validation: SafetyValidation) -> Dict[str, Any]:
|
||||
if decision.tier in (EscalationTier.TIER_1.value, EscalationTier.TIER_2.value):
|
||||
return {
|
||||
"status": "routed",
|
||||
"executor": decision.executor,
|
||||
"reason": decision.rationale
|
||||
}
|
||||
|
||||
self.auto_edit_lockout = True
|
||||
brief = {
|
||||
"type": "diagnostic_brief",
|
||||
"severity": "critical",
|
||||
"tier": decision.tier,
|
||||
"user_rationale": "Autonomous edits have been paused to protect account safety after sustained high-velocity actions.",
|
||||
"validation_violations": validation.violations,
|
||||
"action_type": action_data.get("action_type", "unknown"),
|
||||
"timestamp": datetime.utcnow().isoformat()
|
||||
}
|
||||
self.alert_history.append(brief)
|
||||
if len(self.alert_history) > 500:
|
||||
self.alert_history = self.alert_history[-500:]
|
||||
|
||||
return {"status": "lockout_enabled", "diagnostic_brief": brief}
|
||||
|
||||
async def _persist_escalation_decision(self, decision: EscalationDecision, action_data: Dict[str, Any], outcome: Dict[str, Any]):
|
||||
record = {
|
||||
"timestamp": datetime.utcnow().isoformat(),
|
||||
"decision": asdict(decision),
|
||||
"action_data": action_data,
|
||||
"outcome": outcome
|
||||
}
|
||||
self.escalation_history.append(record)
|
||||
if len(self.escalation_history) > 2000:
|
||||
self.escalation_history = self.escalation_history[-2000:]
|
||||
|
||||
def get_escalation_history(self, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
return self.escalation_history[-limit:] if self.escalation_history else []
|
||||
|
||||
def reset_auto_edit_lockout(self):
|
||||
self.auto_edit_lockout = False
|
||||
|
||||
def add_custom_constraint(self, constraint: SafetyConstraint):
|
||||
"""Add a custom safety constraint"""
|
||||
self.constraints[constraint.constraint_id] = constraint
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Service for encrypting/decrypting integration tokens with key version metadata."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class TokenCryptoService:
|
||||
"""Token encryption/decryption service with key version support."""
|
||||
|
||||
ENV_KEY = "ALWRITY_TOKEN_ENCRYPTION_KEY"
|
||||
ENV_KEY_VERSION = "ALWRITY_TOKEN_KEY_VERSION"
|
||||
|
||||
def __init__(self):
|
||||
raw_key = os.getenv(self.ENV_KEY, "")
|
||||
if raw_key:
|
||||
self._fernet_key = self._normalize_key(raw_key)
|
||||
else:
|
||||
self._fernet_key = self._derive_dev_key()
|
||||
self._fernet = Fernet(self._fernet_key)
|
||||
self._key_version = os.getenv(self.ENV_KEY_VERSION, "v1")
|
||||
self._key_reference = self._fingerprint(self._fernet_key)
|
||||
|
||||
@property
|
||||
def key_version(self) -> str:
|
||||
return self._key_version
|
||||
|
||||
@property
|
||||
def key_reference(self) -> str:
|
||||
return self._key_reference
|
||||
|
||||
def encrypt_token(self, token: Optional[str]) -> Optional[str]:
|
||||
if token is None:
|
||||
return None
|
||||
return self._fernet.encrypt(token.encode("utf-8")).decode("utf-8")
|
||||
|
||||
def decrypt_token(self, encrypted_token: Optional[str]) -> Optional[str]:
|
||||
if encrypted_token is None:
|
||||
return None
|
||||
try:
|
||||
return self._fernet.decrypt(encrypted_token.encode("utf-8")).decode("utf-8")
|
||||
except InvalidToken:
|
||||
logger.error("Token decryption failed due to invalid token/key")
|
||||
raise
|
||||
|
||||
def encrypt_pair(self, access_token: str, refresh_token: Optional[str]) -> Tuple[str, Optional[str]]:
|
||||
return self.encrypt_token(access_token), self.encrypt_token(refresh_token)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_key(raw_key: str) -> bytes:
|
||||
raw_key = raw_key.strip()
|
||||
if len(raw_key) == 44 and raw_key.endswith("="):
|
||||
return raw_key.encode("utf-8")
|
||||
digest = hashlib.sha256(raw_key.encode("utf-8")).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
@staticmethod
|
||||
def _derive_dev_key() -> bytes:
|
||||
seed = "alwrity-local-token-key"
|
||||
digest = hashlib.sha256(seed.encode("utf-8")).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint(key: bytes) -> str:
|
||||
return hashlib.sha256(key).hexdigest()[:16]
|
||||
Reference in New Issue
Block a user