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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
Security intent plugin — PII scanning, access auditing, GDPR compliance, and data retention.
"""

import logging
import re
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta

from sqlalchemy.ext.asyncio import AsyncSession

from app.models import Project, Element
from app.schemas.intent import SingleQueryPlan, SingleQueryResult, MainIntent
from app.core.intent_system.base_plugin import BaseIntentPlugin
from app.core.intent_system.decorators import sub_intent

logger = logging.getLogger(__name__)


class SecurityIntentPlugin(BaseIntentPlugin):
    """Plugin for the SECURITY intent.

    Manages PII detection, access auditing, GDPR compliance,
    permission checks, and data retention policy compliance.
    """

    def __init__(self):
        super().__init__()
        self.intent_type = MainIntent.SECURITY
        self.supported_sub_intents = [
            "security.pii_scan",
            "security.access_audit",
            "security.gdpr",
            "security.permissions",
            "security.data_retention",
        ]

        # PII detection patterns
        self.pii_patterns = {
            "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
            "phone": r"\b(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b",
            "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
            "credit_card": r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b",
            "ip_address": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
            "passport": r"\b[A-Z]{1,2}\d{6,9}\b",
            "national_id": r"\b[A-Z]{2}\d{6,10}\b",
        }

        # GDPR requirements
        self.gdpr_requirements = [
            "data_minimization",
            "purpose_limitation",
            "storage_limitation",
            "accuracy",
            "integrity_confidentiality",
            "accountability",
            "lawfulness_fairness_transparency",
        ]

        # Access event types
        self.access_events = [
            "read",
            "create",
            "update",
            "delete",
            "export",
            "share",
            "download",
        ]

    # ------------------------------------------------------------------ #
    #  Sub-intent handlers
    # ------------------------------------------------------------------ #

    @sub_intent("security.pii_scan")
    async def handle_pii_scan(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Scan for personally identifiable information (PII) in element data."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )
        result = await session.execute(query)
        elements = result.scalars().all()

        # Scan for PII in element data
        pii_findings = await self._scan_elements_for_pii(elements)

        # Calculate risk score
        risk_score = self._calculate_pii_risk_score(pii_findings)

        total_detections = sum(f["count"] for f in pii_findings["findings"])
        affected_elements = len(pii_findings["affected_elements"])

        explanation = (
            f"PII scan completed for {len(elements)} elements. "
            f"Found {total_detections} potential PII instances in {affected_elements} elements. "
            f"Risk score: {risk_score}/100."
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"PII scan: {total_detections} detections in {affected_elements} elements",
            explanation=explanation,
            result_data={
                "pii_scan": pii_findings,
                "risk_score": risk_score,
                "risk_level": self._get_risk_level(risk_score),
                "recommendations": self._generate_pii_recommendations(pii_findings),
                "gdpr_implications": [
                    "PII data must be encrypted at rest",
                    "Access to PII must be logged",
                    "Data subject rights must be honored",
                    "Data breach notification may be required",
                ],
            },
            provenance=["database_query", "pii_pattern_matching"],
            elements_processed=len(elements),
        )

    @sub_intent("security.access_audit")
    async def handle_access_audit(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Perform access audit and log analysis."""
        audit_report = await self._generate_access_audit(project)

        total_events = audit_report["total_events"]
        unique_users = audit_report["unique_users"]
        suspicious_events = len(audit_report["suspicious_activities"])

        explanation = (
            f"Access audit for project {project.name}. "
            f"Analyzed {total_events} events from {unique_users} users. "
            f"Found {suspicious_events} suspicious activities."
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Access audit: {total_events} events, {suspicious_events} suspicious",
            explanation=explanation,
            result_data=audit_report,
            provenance=["access_log_analysis"],
            elements_processed=0,
        )

    @sub_intent("security.gdpr")
    async def handle_gdpr(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Perform GDPR compliance check."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )
        result = await session.execute(query)
        elements = result.scalars().all()

        gdpr_report = await self._generate_gdpr_report(project, elements)

        compliance_score = gdpr_report["compliance_score"]
        compliant_requirements = sum(1 for r in gdpr_report["requirements"] if r["compliant"])
        total_requirements = len(gdpr_report["requirements"])

        explanation = (
            f"GDPR compliance check for project {project.name}. "
            f"Compliance score: {compliance_score}%. "
            f"{compliant_requirements}/{total_requirements} requirements met."
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"GDPR compliance: {compliance_score}% ({compliant_requirements}/{total_requirements} requirements)",
            explanation=explanation,
            result_data=gdpr_report,
            provenance=["gdpr_compliance_check", "database_query"],
            elements_processed=len(elements),
        )

    @sub_intent("security.permissions")
    async def handle_permissions(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Audit user permissions and access controls."""
        permissions_report = await self._generate_permissions_audit(project)

        total_users = permissions_report["total_users"]
        over_privileged = len(permissions_report["over_privileged_users"])
        orphaned_permissions = len(permissions_report["orphaned_permissions"])

        explanation = (
            f"Permission audit for project {project.name}. "
            f"Analyzed {total_users} users. "
            f"Found {over_privileged} over-privileged users and {orphaned_permissions} orphaned permissions."
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Permission audit: {over_privileged} over-privileged, {orphaned_permissions} orphaned",
            explanation=explanation,
            result_data=permissions_report,
            provenance=["permission_audit"],
            elements_processed=0,
        )

    @sub_intent("security.data_retention")
    async def handle_data_retention(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None,
    ) -> SingleQueryResult:
        """Check data retention policy compliance."""
        query = await self.build_base_query(
            session=session,
            project=project,
            filter_groups=query_plan.filter_groups,
            scope=query_plan.scope,
        )
        result = await session.execute(query)
        elements = result.scalars().all()

        retention_report = await self._generate_retention_report(project, elements)

        expired_data = retention_report["expired_data_count"]
        expiring_soon = retention_report["expiring_soon_count"]

        explanation = (
            f"Data retention check for project {project.name}. "
            f"{expired_data} items past retention period, "
            f"{expiring_soon} expiring within 30 days."
        )

        return self.create_result(
            query_plan=query_plan,
            result_text=f"Data retention: {expired_data} expired, {expiring_soon} expiring soon",
            explanation=explanation,
            result_data=retention_report,
            provenance=["retention_policy_check", "database_query"],
            elements_processed=len(elements),
        )

    # ------------------------------------------------------------------ #
    #  Helper methods
    # ------------------------------------------------------------------ #

    async def _scan_elements_for_pii(self, elements: List[Element]) -> Dict[str, Any]:
        """Scan elements for PII using regex patterns."""
        findings = {
            pii_type: {"count": 0, "examples": []}
            for pii_type in self.pii_patterns.keys()
        }

        affected_elements = set()

        for element in elements:
            # Scan name field
            if element.name:
                for pii_type, pattern in self.pii_patterns.items():
                    matches = re.findall(pattern, element.name)
                    if matches:
                        findings[pii_type]["count"] += len(matches)
                        findings[pii_type]["examples"].append({
                            "element_id": element.ifc_global_id,
                            "element_name": element.name[:50],  # Truncate for safety
                            "location": "name",
                            "match_count": len(matches),
                        })
                        affected_elements.add(element.ifc_global_id)

            # In real implementation, would also scan custom properties

        return {
            "findings": [
                {"type": pii_type, "count": data["count"], "examples": data["examples"][:5]}
                for pii_type, data in findings.items()
                if data["count"] > 0
            ],
            "affected_elements": list(affected_elements),
            "total_elements_scanned": len(elements),
        }

    def _calculate_pii_risk_score(self, pii_findings: Dict[str, Any]) -> int:
        """Calculate risk score based on PII findings (0-100)."""
        if not pii_findings["findings"]:
            return 0

        # Weight different PII types by severity
        severity_weights = {
            "email": 30,
            "phone": 25,
            "ssn": 100,
            "credit_card": 100,
            "ip_address": 10,
            "passport": 90,
            "national_id": 80,
        }

        total_weighted_score = 0
        for finding in pii_findings["findings"]:
            pii_type = finding["type"]
            count = finding["count"]
            weight = severity_weights.get(pii_type, 20)
            total_weighted_score += min(count * weight, 100)  # Cap per type

        # Normalize to 0-100
        risk_score = min(total_weighted_score // len(pii_findings["findings"]), 100)
        return risk_score

    def _get_risk_level(self, risk_score: int) -> str:
        """Get risk level from score."""
        if risk_score >= 80:
            return "CRITICAL"
        elif risk_score >= 60:
            return "HIGH"
        elif risk_score >= 40:
            return "MEDIUM"
        elif risk_score >= 20:
            return "LOW"
        else:
            return "MINIMAL"

    def _generate_pii_recommendations(self, pii_findings: Dict[str, Any]) -> List[str]:
        """Generate recommendations based on PII findings."""
        recommendations = []

        if pii_findings["findings"]:
            recommendations.append("Immediately remove or redact all PII from element names")
            recommendations.append("Enable encryption at rest for the database")
            recommendations.append("Implement access logging for PII-containing elements")
            recommendations.append("Conduct GDPR data protection impact assessment (DPIA)")
            recommendations.append("Establish data minimization policies")
            recommendations.append("Train staff on PII handling procedures")

        return recommendations

    async def _generate_access_audit(self, project: Project) -> Dict[str, Any]:
        """Generate access audit report (mock data for demonstration)."""
        # In real implementation, would query actual access logs
        access_events_list = [
            {
                "timestamp": (datetime.now() - timedelta(hours=i)).isoformat(),
                "user_id": f"user_{(i % 5) + 1}",
                "event_type": self.access_events[i % len(self.access_events)],
                "ip_address": f"192.168.1.{(i % 254) + 1}",
                "success": i % 10 != 0,  # 10% failure rate
                "resource": f"element_{i}",
            }
            for i in range(100)
        ]

        # Detect suspicious activities
        suspicious = [
            {
                "timestamp": (datetime.now() - timedelta(hours=2)).isoformat(),
                "user_id": "user_3",
                "reason": "Multiple failed login attempts",
                "severity": "HIGH",
                "event_count": 15,
            },
            {
                "timestamp": (datetime.now() - timedelta(hours=5)).isoformat(),
                "user_id": "user_5",
                "reason": "Access from unusual location (IP: 103.24.15.42)",
                "severity": "MEDIUM",
                "event_count": 3,
            },
            {
                "timestamp": (datetime.now() - timedelta(hours=1)).isoformat(),
                "user_id": "user_2",
                "reason": "Bulk data export outside business hours",
                "severity": "HIGH",
                "event_count": 1,
            },
        ]

        return {
            "project_id": project.id,
            "project_name": project.name,
            "total_events": len(access_events_list),
            "unique_users": 5,
            "time_range": {
                "start": (datetime.now() - timedelta(days=7)).isoformat(),
                "end": datetime.now().isoformat(),
            },
            "events_by_type": {
                event_type: sum(1 for e in access_events_list if e["event_type"] == event_type)
                for event_type in self.access_events
            },
            "suspicious_activities": suspicious,
            "failed_access_attempts": sum(1 for e in access_events_list if not e["success"]),
            "unique_ip_addresses": 50,
        }

    async def _generate_gdpr_report(self, project: Project, elements: List[Element]) -> Dict[str, Any]:
        """Generate GDPR compliance report."""
        requirements_status = []

        for requirement in self.gdpr_requirements:
            # Mock compliance status (in real implementation, would check actual compliance)
            compliant = requirement not in ["storage_limitation", "accountability"]

            requirements_status.append({
                "requirement": requirement,
                "requirement_name": requirement.replace("_", " ").title(),
                "compliant": compliant,
                "description": self._get_gdpr_requirement_description(requirement),
                "evidence": "Automated checks passed" if compliant else "Manual review required",
                "action_needed": None if compliant else f"Review {requirement} implementation",
            })

        compliant_count = sum(1 for r in requirements_status if r["compliant"])
        compliance_score = int((compliant_count / len(requirements_status)) * 100)

        return {
            "project_id": project.id,
            "project_name": project.name,
            "compliance_score": compliance_score,
            "requirements": requirements_status,
            "data_processing_activities": [
                "Element data storage and retrieval",
                "IFC file processing",
                "Query processing and analysis",
                "Export and reporting",
            ],
            "legal_basis": "Legitimate interest - BIM data management",
            "data_protection_officer": "dpo@example.com",
            "last_dpia_date": (datetime.now() - timedelta(days=180)).isoformat(),
            "next_review_date": (datetime.now() + timedelta(days=185)).isoformat(),
        }

    def _get_gdpr_requirement_description(self, requirement: str) -> str:
        """Get description for GDPR requirement."""
        descriptions = {
            "data_minimization": "Only collect and process necessary data",
            "purpose_limitation": "Use data only for specified purposes",
            "storage_limitation": "Retain data only as long as necessary",
            "accuracy": "Ensure data is accurate and up to date",
            "integrity_confidentiality": "Secure data with appropriate measures",
            "accountability": "Demonstrate compliance with GDPR",
            "lawfulness_fairness_transparency": "Process data lawfully and transparently",
        }
        return descriptions.get(requirement, "GDPR compliance requirement")

    async def _generate_permissions_audit(self, project: Project) -> Dict[str, Any]:
        """Generate permissions audit report."""
        # Mock permission data
        users = [
            {
                "user_id": "user_1",
                "username": "admin@example.com",
                "roles": ["admin", "editor", "viewer"],
                "permissions": ["read", "write", "delete", "share", "export"],
                "last_access": (datetime.now() - timedelta(hours=2)).isoformat(),
                "over_privileged": True,
            },
            {
                "user_id": "user_2",
                "username": "editor@example.com",
                "roles": ["editor", "viewer"],
                "permissions": ["read", "write", "export"],
                "last_access": (datetime.now() - timedelta(hours=5)).isoformat(),
                "over_privileged": False,
            },
            {
                "user_id": "user_3",
                "username": "inactive@example.com",
                "roles": ["viewer"],
                "permissions": ["read"],
                "last_access": (datetime.now() - timedelta(days=120)).isoformat(),
                "over_privileged": False,
            },
        ]

        over_privileged = [u for u in users if u["over_privileged"]]
        inactive_users = [
            u for u in users
            if (datetime.now() - datetime.fromisoformat(u["last_access"])).days > 90
        ]

        return {
            "project_id": project.id,
            "project_name": project.name,
            "total_users": len(users),
            "users": users,
            "over_privileged_users": over_privileged,
            "inactive_users": inactive_users,
            "orphaned_permissions": [
                {
                    "permission_id": "perm_123",
                    "resource": "deleted_element_456",
                    "reason": "Resource no longer exists",
                },
            ],
            "recommendations": [
                "Review admin role assignments",
                "Remove inactive user permissions (90+ days)",
                "Implement principle of least privilege",
                "Enable MFA for admin users",
            ],
        }

    async def _generate_retention_report(self, project: Project, elements: List[Element]) -> Dict[str, Any]:
        """Generate data retention policy report."""
        # Mock retention policy: 7 years for project data
        retention_period_days = 7 * 365

        # Count elements by age
        now = datetime.now()
        expired_data = []
        expiring_soon = []

        for element in elements[:50]:  # Sample first 50
            if element.created_at:
                age_days = (now - element.created_at).days

                if age_days > retention_period_days:
                    expired_data.append({
                        "element_id": element.ifc_global_id,
                        "created_at": element.created_at.isoformat(),
                        "age_days": age_days,
                    })
                elif age_days > (retention_period_days - 30):
                    expiring_soon.append({
                        "element_id": element.ifc_global_id,
                        "created_at": element.created_at.isoformat(),
                        "days_until_expiry": retention_period_days - age_days,
                    })

        return {
            "project_id": project.id,
            "project_name": project.name,
            "retention_policy": {
                "period_days": retention_period_days,
                "period_years": 7,
                "policy_type": "rolling",
            },
            "expired_data_count": len(expired_data),
            "expired_data": expired_data[:10],  # First 10 examples
            "expiring_soon_count": len(expiring_soon),
            "expiring_soon": expiring_soon[:10],
            "total_elements_checked": len(elements),
            "recommendations": [
                "Archive expired data to cold storage",
                "Notify stakeholders of expiring data",
                "Implement automated data deletion workflows",
                "Document data retention decisions",
            ] if expired_data or expiring_soon else ["No action needed - all data within retention period"],
        }