Spaces:
Runtime error
Runtime error
BIM Query Deploy
Claude Opus 4.7 (1M context)
deploy: initial BIM Query API on Hugging Face Spaces
e6be672 Download app/intents/_deferred/security/handler.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/intents/_deferred/security/handler.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/intents/_deferred/security/handler.py
-
curl -L -o handler.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/intents/_deferred/security/handler.py
23.3 kB
| # 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 | |
| # ------------------------------------------------------------------ # | |
| 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), | |
| ) | |
| 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, | |
| ) | |
| 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), | |
| ) | |
| 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, | |
| ) | |
| 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"], | |
| } | |