File size: 9,920 Bytes
2f235a0
 
 
 
 
 
 
 
 
 
 
 
 
4dc66a3
2f235a0
20a1017
2f235a0
 
ef83e66
2f235a0
 
 
4dc66a3
ef83e66
2f235a0
20a1017
 
 
4dc66a3
 
 
 
 
 
 
 
2f235a0
 
 
 
4dc66a3
2f235a0
ef83e66
2f235a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc66a3
 
 
 
 
 
 
 
 
 
 
 
2f235a0
ef83e66
 
 
 
 
 
 
 
 
 
 
2f235a0
 
4dc66a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f235a0
 
 
 
 
 
 
 
 
ef83e66
2f235a0
 
 
 
 
 
 
ef83e66
 
 
2f235a0
 
 
 
 
 
ef83e66
 
2f235a0
 
 
 
 
 
 
 
 
 
ef83e66
 
2f235a0
 
 
 
ef83e66
 
 
2f235a0
 
 
 
 
 
 
 
ef83e66
 
 
 
 
 
 
 
 
 
 
 
 
 
2f235a0
 
 
 
 
 
 
 
 
 
 
20a1017
2f235a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef83e66
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# =============================================================
# File: backend/api/services/redflag_detector.py
# =============================================================
"""
Enterprise RedFlagDetector

- Loads per-tenant rules from Supabase REST (or you can swap to Postgres direct)
- Caches rules per tenant with TTL
- Performs regex and keyword matching
- Returns structured match objects with severity and rule metadata
- Sends notifications to Admin MCP or a webhook
"""

import hashlib
import os
import re
import time
from typing import List, Dict, Any, Optional

import httpx

from ..models.redflag import RedFlagRule, RedFlagMatch
from ..storage.rules_store import RulesStore
from .semantic_encoder import embed_text, cosine_similarity


class RedFlagDetector:

    def __init__(
        self,
        supabase_url: Optional[str] = None,
        supabase_key: Optional[str] = None,
        admin_mcp_url: Optional[str] = None,
        cache_ttl: int = 300,
        rules_store: Optional[RulesStore] = None,
    ):
        self.supabase_url = supabase_url or os.getenv("SUPABASE_URL")
        self.supabase_key = supabase_key or os.getenv("SUPABASE_SERVICE_KEY")
        self.admin_mcp_url = admin_mcp_url or os.getenv("ADMIN_MCP_URL")
        self.cache_ttl = cache_ttl
        self.rules_store = rules_store or RulesStore()
        self._rules_cache: Dict[str, Dict[str, Any]] = {}  # tenant_id -> {"fetched_at":ts, "rules":[...]}
        self._rule_embeddings: Dict[str, Dict[str, List[float]]] = {}
        self._client = httpx.AsyncClient(timeout=15)

    async def _fetch_rules_from_supabase(self, tenant_id: str) -> List[RedFlagRule]:
        # Expecting a table `redflag_rules` with columns: id, tenant_id, pattern, description, severity, source, enabled, keywords (json array)
        if not self.supabase_url or not self.supabase_key:
            return []

        url = self.supabase_url.rstrip("/") + "/rest/v1/redflag_rules"
        headers = {"apikey": self.supabase_key, "Authorization": f"Bearer {self.supabase_key}"}
        params = {"tenant_id": f"eq.{tenant_id}", "select": "*"}

        r = await self._client.get(url, headers=headers, params=params)
        r.raise_for_status()

        rows = r.json()

        rules: List[RedFlagRule] = []

        for row in rows:
            try:
                keywords = row.get("keywords") or []
                if isinstance(keywords, str):
                    # attempt to parse JSON-encoded string
                    try:
                        import json
                        keywords = json.loads(keywords)
                    except Exception:
                        keywords = []

                rules.append(
                    RedFlagRule(
                        id=str(row.get("id")),
                        pattern=row.get("pattern") or "",
                        description=row.get("description") or "",
                        severity=row.get("severity") or "medium",
                        source=row.get("source") or "admin",
                        enabled=row.get("enabled", True),
                        keywords=keywords or [],
                    )
                )
            except Exception:
                # skip invalid rows defensively
                continue

        return rules

    async def load_rules(self, tenant_id: str) -> List[RedFlagRule]:
        now = int(time.time())
        entry = self._rules_cache.get(tenant_id)

        if entry and now - entry["fetched_at"] < self.cache_ttl:
            return entry["rules"]

        rules: List[RedFlagRule] = []
        remote_rules: List[RedFlagRule] = []
        if self.supabase_url and self.supabase_key:
            try:
                remote_rules = await self._fetch_rules_from_supabase(tenant_id)
            except Exception:
                remote_rules = []

        local_rules = self._fetch_local_rules(tenant_id)
        rules.extend(remote_rules)
        rules.extend(local_rules)

        self._rules_cache[tenant_id] = {"fetched_at": now, "rules": rules}
        # Pre-compute embeddings for semantic scoring
        embed_map: Dict[str, List[float]] = {}
        for rule in rules:
            try:
                text_for_embedding = " ".join(
                    [piece for piece in [rule.description, rule.pattern] if piece]
                ).strip() or rule.id
                embed_map[rule.id] = embed_text(text_for_embedding)
            except Exception:
                embed_map[rule.id] = []
        self._rule_embeddings[tenant_id] = embed_map
        return rules

    def _fetch_local_rules(self, tenant_id: str) -> List[RedFlagRule]:
        if not self.rules_store:
            return []

        rows = self.rules_store.get_rules(tenant_id)
        rules: List[RedFlagRule] = []
        for raw in rows:
            text = (raw or "").strip()
            if not text:
                continue
            rule_id = hashlib.sha1(f"{tenant_id}:{text}".encode()).hexdigest()
            rules.append(
                RedFlagRule(
                    id=rule_id,
                    pattern=text,
                    description=text,
                    severity="high",
                    source="admin_local",
                    enabled=True,
                    keywords=[text.lower()] if len(text.split()) <= 6 else [],
                )
            )
        return rules

    async def check(self, tenant_id: str, text: str) -> List[RedFlagMatch]:
        """Return structured matches for the given tenant and text."""
        if not text:
            return []

        rules = await self.load_rules(tenant_id)
        matches: List[RedFlagMatch] = []

        text_lower = text.lower()
        text_vector = embed_text(text)

        for rule in rules:
            if not rule.enabled:
                continue

            matched = False
            matched_text = ""
            match_source = ""
            keyword_score = 0.0
            regex_score = 0.0

            # 1) Keyword quick-check (cheap)
            for kw in (rule.keywords or []):
                if kw and kw.lower() in text_lower:
                    matched = True
                    matched_text = kw
                    keyword_score = 0.8
                    match_source = "keyword"
                    break

            # 2) Regex check (more precise)
            if not matched and rule.pattern:
                try:
                    pat = re.compile(rule.pattern, re.IGNORECASE)
                    m = pat.search(text)
                    if m:
                        matched = True
                        matched_text = m.group(0)
                        regex_score = 1.0
                        match_source = "regex"
                except re.error:
                    # invalid regex; skip this rule
                    continue

            semantic_score = self._semantic_score(tenant_id, rule.id, text_vector)
            confidence = max(semantic_score, keyword_score, regex_score)

            if matched:
                matches.append(
                    RedFlagMatch(
                        rule_id=rule.id,
                        pattern=rule.pattern,
                        severity=rule.severity,
                        description=rule.description,
                        matched_text=matched_text,
                        confidence=round(confidence, 2),
                        explanation=self._build_explanation(rule, match_source, matched_text, confidence),
                    )
                )
            elif semantic_score >= 0.82:
                matches.append(
                    RedFlagMatch(
                        rule_id=rule.id,
                        pattern=rule.pattern,
                        severity=rule.severity,
                        description=rule.description,
                        matched_text=matched_text or "",
                        confidence=round(semantic_score, 2),
                        explanation=self._build_explanation(rule, "semantic", matched_text, semantic_score),
                    )
                )

        return matches

    async def notify_admin(self, tenant_id: str, violations: List[RedFlagMatch], source_payload: Optional[Dict[str, Any]] = None) -> None:
        """Notify the Admin MCP server (or a webhook) about the matches."""
        payload = {
            "tenant_id": tenant_id,
            "violations": [v.__dict__ for v in violations],
            "source": source_payload or {},
        }

        # 1) POST to Admin MCP /alert if configured
        if self.admin_mcp_url:
            try:
                await self._client.post(self.admin_mcp_url.rstrip("/") + "/alert", json=payload, timeout=10)
            except Exception:
                # swallow exceptions — notifications should not crash orchestration
                pass

        # 2) Optionally send to a Slack/Teams webhook
        webhook = os.getenv("ALERT_WEBHOOK")
        if webhook:
            try:
                await self._client.post(webhook, json={"text": f"Red-flag for tenant {tenant_id}", "details": payload}, timeout=10)
            except Exception:
                pass

    async def close(self):
        await self._client.aclose()

    def _semantic_score(self, tenant_id: str, rule_id: str, text_vector: List[float]) -> float:
        rule_vectors = self._rule_embeddings.get(tenant_id, {})
        rule_vector = rule_vectors.get(rule_id)
        if not rule_vector:
            return 0.0
        return cosine_similarity(rule_vector, text_vector)

    @staticmethod
    def _build_explanation(rule: RedFlagRule, source: str, matched_text: str, confidence: float) -> str:
        base = f"Matched rule '{rule.description or rule.id}' via {source or 'heuristics'}"
        if matched_text:
            base += f" on span \"{matched_text}\""
        return f"{base}. confidence={round(confidence, 2)}"