Spaces:
Sleeping
Sleeping
File size: 18,172 Bytes
e4abb85 c509b44 a477044 e4abb85 c509b44 e4abb85 a477044 e4abb85 a477044 e4abb85 a477044 e4abb85 c509b44 e4abb85 c509b44 e4abb85 c509b44 e4abb85 c509b44 a477044 c509b44 a477044 e4abb85 c509b44 a477044 e4abb85 a477044 e4abb85 a477044 e4abb85 |
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
import sqlite3
import time
import os
from pathlib import Path
from typing import List, Optional, Dict, Any
# Try to import Supabase client
try:
from supabase import create_client, Client
SUPABASE_AVAILABLE = True
except ImportError:
SUPABASE_AVAILABLE = False
Client = None
class RulesStore:
"""
Store for admin rules with support for both Supabase and SQLite.
Uses Supabase if configured, otherwise falls back to SQLite.
"""
def __init__(self, use_supabase: Optional[bool] = None, auto_create_table: bool = False):
"""
Initialize RulesStore.
Args:
use_supabase: If True, use Supabase; if False, use SQLite.
If None, auto-detect based on environment variables.
auto_create_table: If True, attempt to create Supabase table if it doesn't exist.
Default False to avoid blocking startup. Use create_table() method separately.
"""
self.use_supabase = use_supabase
self._table_verified = False
# Auto-detect if Supabase should be used
if self.use_supabase is None:
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = os.getenv("SUPABASE_SERVICE_KEY")
self.use_supabase = bool(supabase_url and supabase_key and SUPABASE_AVAILABLE)
if self.use_supabase:
# Initialize Supabase client
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = os.getenv("SUPABASE_SERVICE_KEY")
if not supabase_url or not supabase_key:
# Don't raise error, fall back to SQLite instead
print("⚠️ Supabase credentials missing. Falling back to SQLite.")
self.use_supabase = False
else:
try:
self.supabase_client = create_client(supabase_url, supabase_key)
self.table_name = "admin_rules"
# Only verify table existence, don't create during init
if auto_create_table:
self._ensure_supabase_table()
else:
# Quick check without blocking
self._quick_table_check()
except Exception as e:
print(f"⚠️ Failed to initialize Supabase client: {e}. Falling back to SQLite.")
self.use_supabase = False
if not self.use_supabase:
# Initialize SQLite
root_dir = Path(__file__).resolve().parents[3] # points to project root
data_dir = root_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
self.db_path = data_dir / "admin_rules.db"
self._init_db()
def _quick_table_check(self):
"""Quick non-blocking check if table exists."""
try:
self.supabase_client.table(self.table_name).select("id").limit(1).execute()
self._table_verified = True
except Exception:
# Table might not exist, but don't block startup
self._table_verified = False
def _ensure_supabase_table(self):
"""Ensure the Supabase table exists, create it if needed."""
try:
# Try to query the table to see if it exists
self.supabase_client.table(self.table_name).select("id").limit(1).execute()
# If we get here, table exists
self._table_verified = True
return True
except Exception as e:
error_str = str(e).lower()
if "relation" in error_str or "does not exist" in error_str or "not found" in error_str:
# Table doesn't exist, try to create it (non-blocking)
print(f"⚠️ Table '{self.table_name}' does not exist in Supabase.")
print(" Run 'python create_supabase_table.py' to create it, or create manually in Supabase SQL Editor.")
# Don't block startup - just log the issue
return False
else:
# Other error, assume table exists
self._table_verified = True
return True
def create_table_if_needed(self):
"""Public method to create table if needed. Can be called after startup."""
if not self.use_supabase:
return False
if self._table_verified:
return True
return self._create_supabase_table()
def _create_supabase_table(self) -> bool:
"""Create the admin_rules table in Supabase programmatically."""
try:
# Read SQL file
sql_file = Path(__file__).resolve().parents[3] / "supabase_admin_rules_table.sql"
if not sql_file.exists():
print(f" ⚠️ SQL file not found: {sql_file}")
self._show_manual_instructions()
return False
with open(sql_file, "r", encoding="utf-8") as f:
sql_content = f.read()
# Method 1: Try using psql if POSTGRESQL_URL is available (non-blocking with timeout)
postgres_url = os.getenv("POSTGRESQL_URL")
if postgres_url:
try:
import subprocess
print(" 🔧 Attempting to create table via psql...")
# Execute SQL using psql with timeout
result = subprocess.run(
["psql", postgres_url, "-c", sql_content],
capture_output=True,
text=True,
timeout=10 # Shorter timeout to avoid blocking
)
if result.returncode == 0:
print(" ✅ Table created successfully via psql!")
self._table_verified = True
return True
else:
print(f" ⚠️ psql returned error: {result.stderr[:200]}")
except FileNotFoundError:
print(" ⚠️ psql not found in PATH")
except subprocess.TimeoutExpired:
print(" ⚠️ psql timed out (table creation may still be in progress)")
except Exception as e:
print(f" ⚠️ psql method failed: {e}")
# Method 2: Try using Supabase REST API (if custom function exists)
try:
import httpx
# Try different possible RPC endpoints
endpoints = [
"/rest/v1/rpc/exec_sql",
"/rest/v1/rpc/execute_sql",
"/rest/v1/rpc/run_sql"
]
for endpoint in endpoints:
try:
response = httpx.post(
f"{os.getenv('SUPABASE_URL')}{endpoint}",
headers={
"apikey": os.getenv("SUPABASE_SERVICE_KEY"),
"Authorization": f"Bearer {os.getenv('SUPABASE_SERVICE_KEY')}",
"Content-Type": "application/json",
"Prefer": "return=representation"
},
json={"query": sql_content, "sql": sql_content},
timeout=10 # Shorter timeout
)
if response.status_code in [200, 201, 204]:
print(" ✅ Table created successfully via API!")
self._table_verified = True
return True
except Exception:
continue
except ImportError:
pass
except Exception as e:
print(f" ⚠️ API method failed: {e}")
# Method 3: Show manual instructions (don't block)
self._show_manual_instructions()
return False
except Exception as e:
print(f" ❌ Error: {e}")
self._show_manual_instructions()
return False
def _show_manual_instructions(self):
"""Show instructions for manual table creation."""
sql_file = Path(__file__).resolve().parents[3] / "supabase_admin_rules_table.sql"
print("\n 📝 Manual Setup Required:")
print(" 1. Go to: https://app.supabase.com → Your Project → SQL Editor")
print(" 2. Click 'New query'")
if sql_file.exists():
print(f" 3. Open file: {sql_file.name}")
print(" 4. Copy all SQL and paste into SQL Editor")
else:
print(" 3. Copy the SQL from supabase_admin_rules_table.sql")
print(" 5. Click 'Run' to execute")
print("\n 💡 After creating the table, restart your application.")
def _init_db(self):
with sqlite3.connect(self.db_path) as conn:
# Create table with regex pattern and severity support
conn.execute(
"""
CREATE TABLE IF NOT EXISTS admin_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tenant_id TEXT NOT NULL,
rule TEXT NOT NULL,
pattern TEXT,
severity TEXT DEFAULT 'medium',
description TEXT,
enabled BOOLEAN DEFAULT 1,
created_at INTEGER,
UNIQUE(tenant_id, rule)
)
"""
)
# Add new columns if they don't exist (for backward compatibility)
try:
conn.execute("ALTER TABLE admin_rules ADD COLUMN pattern TEXT")
except sqlite3.OperationalError:
pass # Column already exists
try:
conn.execute("ALTER TABLE admin_rules ADD COLUMN severity TEXT DEFAULT 'medium'")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE admin_rules ADD COLUMN description TEXT")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE admin_rules ADD COLUMN enabled BOOLEAN DEFAULT 1")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE admin_rules ADD COLUMN created_at INTEGER")
except sqlite3.OperationalError:
pass
conn.commit()
def get_rules(self, tenant_id: str) -> List[str]:
"""Get all rules as a list of rule text strings (backward compatibility)."""
if self.use_supabase:
try:
response = self.supabase_client.table(self.table_name)\
.select("rule")\
.eq("tenant_id", tenant_id)\
.eq("enabled", True)\
.order("id")\
.execute()
return [row["rule"] for row in response.data]
except Exception as e:
print(f"Error fetching rules from Supabase: {e}")
return []
else:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute(
"SELECT rule FROM admin_rules WHERE tenant_id = ? AND enabled = 1 ORDER BY id ASC",
(tenant_id,),
)
return [row[0] for row in cursor.fetchall()]
def get_rules_detailed(self, tenant_id: str) -> List[Dict[str, Any]]:
"""Get all rules with full metadata including pattern, severity, etc."""
if self.use_supabase:
try:
response = self.supabase_client.table(self.table_name)\
.select("*")\
.eq("tenant_id", tenant_id)\
.eq("enabled", True)\
.order("id")\
.execute()
# Convert to list of dicts and ensure created_at is a timestamp
rules = []
for row in response.data:
rule_dict = dict(row)
# Convert created_at to Unix timestamp if it's a string
if "created_at" in rule_dict and isinstance(rule_dict["created_at"], str):
try:
from datetime import datetime
dt = datetime.fromisoformat(rule_dict["created_at"].replace("Z", "+00:00"))
rule_dict["created_at"] = int(dt.timestamp())
except:
rule_dict["created_at"] = int(time.time())
rules.append(rule_dict)
return rules
except Exception as e:
print(f"Error fetching detailed rules from Supabase: {e}")
return []
else:
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"""SELECT id, tenant_id, rule, pattern, severity, description, enabled, created_at
FROM admin_rules WHERE tenant_id = ? AND enabled = 1 ORDER BY id ASC""",
(tenant_id,),
)
rows = cursor.fetchall()
return [dict(row) for row in rows]
def add_rule(
self,
tenant_id: str,
rule: str,
pattern: Optional[str] = None,
severity: str = "medium",
description: Optional[str] = None,
enabled: bool = True
) -> bool:
"""
Add a rule with optional regex pattern and severity.
If pattern is None, the rule text itself is used as the pattern.
"""
# If pattern not provided, use rule text as pattern
pattern_value = pattern or rule
description_value = description or rule
if self.use_supabase:
try:
# Use upsert to handle unique constraint
data = {
"tenant_id": tenant_id,
"rule": rule,
"pattern": pattern_value,
"severity": severity,
"description": description_value,
"enabled": enabled
}
# Supabase upsert - will insert or update based on unique constraint
response = self.supabase_client.table(self.table_name)\
.upsert(data)\
.execute()
return True
except Exception as e:
print(f"Error adding rule to Supabase: {e}")
return False
else:
try:
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"""INSERT OR IGNORE INTO admin_rules
(tenant_id, rule, pattern, severity, description, enabled, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(tenant_id, rule, pattern_value, severity, description_value, 1 if enabled else 0, int(time.time())),
)
conn.commit()
return True
except sqlite3.Error:
return False
def add_rules_bulk(self, tenant_id: str, rules: List[str]) -> List[str]:
added = []
if self.use_supabase:
try:
# Prepare bulk data
bulk_data = [
{
"tenant_id": tenant_id,
"rule": rule,
"pattern": rule, # Use rule text as pattern
"severity": "medium",
"description": rule,
"enabled": True
}
for rule in rules
]
# Upsert all rules at once
response = self.supabase_client.table(self.table_name)\
.upsert(bulk_data)\
.execute()
added = rules # All rules were attempted
except Exception as e:
print(f"Error adding bulk rules to Supabase: {e}")
# Fallback: try one by one
for rule in rules:
if self.add_rule(tenant_id, rule):
added.append(rule)
else:
with sqlite3.connect(self.db_path) as conn:
for rule in rules:
try:
conn.execute(
"INSERT OR IGNORE INTO admin_rules (tenant_id, rule) VALUES (?, ?)",
(tenant_id, rule),
)
added.append(rule)
except sqlite3.Error:
continue
conn.commit()
return added
def delete_rule(self, tenant_id: str, rule: str) -> bool:
if self.use_supabase:
try:
response = self.supabase_client.table(self.table_name)\
.delete()\
.eq("tenant_id", tenant_id)\
.eq("rule", rule)\
.execute()
# Check if any rows were deleted
return len(response.data) > 0 if response.data else False
except Exception as e:
print(f"Error deleting rule from Supabase: {e}")
return False
else:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute(
"DELETE FROM admin_rules WHERE tenant_id = ? AND rule = ?",
(tenant_id, rule),
)
conn.commit()
return cursor.rowcount > 0
|