Download src/shared/models/security.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/models/security.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/shared/models/security.py
-
curl -L -o security.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/models/security.py
16.4 kB
| """ | |
| Security Models for YAZ Care Platform | |
| Role-Based Access Control (RBAC) and audit logging for HIPAA compliance | |
| """ | |
| from datetime import UTC, datetime, timezone | |
| from enum import Enum | |
| from typing import Optional | |
| from uuid import uuid4 | |
| from sqlalchemy import ( | |
| JSON, | |
| Boolean, | |
| Column, | |
| DateTime, | |
| ForeignKey, | |
| Index, | |
| Integer, | |
| String, | |
| Text, | |
| UniqueConstraint, | |
| ) | |
| from sqlalchemy.dialects.postgresql import UUID as POSTGRES_UUID | |
| from sqlalchemy.orm import relationship | |
| from .base import AuditableModel, BaseModel, StandardModel | |
| class ResourceType(str, Enum): | |
| """Types of resources that can be protected""" | |
| PATIENT = "patient" | |
| SURGERY = "surgery" | |
| MEDICAL_RECORD = "medical_record" | |
| APPOINTMENT = "appointment" | |
| INSURANCE = "insurance" | |
| PRESCRIPTION = "prescription" | |
| LAB_RESULT = "lab_result" | |
| IMAGING = "imaging" | |
| USER = "user" | |
| ORGANIZATION = "organization" | |
| SYSTEM = "system" | |
| class ActionType(str, Enum): | |
| """Types of actions that can be performed""" | |
| CREATE = "create" | |
| READ = "read" | |
| UPDATE = "update" | |
| DELETE = "delete" | |
| APPROVE = "approve" | |
| SCHEDULE = "schedule" | |
| CANCEL = "cancel" | |
| EXPORT = "export" | |
| PRINT = "print" | |
| SHARE = "share" | |
| class SecurityEventType(str, Enum): | |
| """Types of security events for monitoring""" | |
| LOGIN_SUCCESS = "login_success" | |
| LOGIN_FAILURE = "login_failure" | |
| PASSWORD_CHANGE = "password_change" | |
| ACCOUNT_LOCKED = "account_locked" | |
| PERMISSION_DENIED = "permission_denied" | |
| SUSPICIOUS_ACCESS = "suspicious_access" | |
| DATA_EXPORT = "data_export" | |
| POLICY_VIOLATION = "policy_violation" | |
| class Role(AuditableModel): | |
| """Role definition for RBAC""" | |
| __tablename__ = "roles" | |
| name = Column(String(100), nullable=False, unique=True, index=True) | |
| description = Column(Text, nullable=True) | |
| is_system_role = Column(Boolean, default=False, nullable=False) | |
| is_active = Column(Boolean, default=True, nullable=False) | |
| # Permissions relationship | |
| permissions = relationship( | |
| "RolePermission", back_populates="role", cascade="all, delete-orphan" | |
| ) | |
| user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan") | |
| def __repr__(self): | |
| return f"<Role(name='{self.name}', active={self.is_active})>" | |
| class Permission(StandardModel): | |
| """Permission definition for fine-grained access control""" | |
| __tablename__ = "permissions" | |
| name = Column(String(100), nullable=False, unique=True, index=True) | |
| resource_type = Column(String(50), nullable=False, index=True) | |
| action = Column(String(50), nullable=False, index=True) | |
| description = Column(Text, nullable=True) | |
| # Additional context for permission | |
| conditions = Column(JSON, nullable=True) # Store conditions as JSON | |
| # Unique constraint on resource_type and action | |
| __table_args__ = ( | |
| UniqueConstraint( | |
| "resource_type", "action", "conditions", name="_resource_action_condition_uc" | |
| ), | |
| Index("idx_permission_resource_action", "resource_type", "action"), | |
| ) | |
| def __repr__(self): | |
| return f"<Permission(name='{self.name}', resource='{self.resource_type}', action='{self.action}')>" | |
| class RolePermission(StandardModel): | |
| """Many-to-many relationship between roles and permissions""" | |
| __tablename__ = "role_permissions" | |
| role_id = Column( | |
| POSTGRES_UUID(as_uuid=True), ForeignKey("roles.id", ondelete="CASCADE"), nullable=False | |
| ) | |
| permission_id = Column( | |
| POSTGRES_UUID(as_uuid=True), | |
| ForeignKey("permissions.id", ondelete="CASCADE"), | |
| nullable=False, | |
| ) | |
| # Additional permission context | |
| granted_by = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| granted_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False) | |
| expires_at = Column(DateTime, nullable=True) | |
| is_active = Column(Boolean, default=True, nullable=False) | |
| # Relationships | |
| role = relationship("Role", back_populates="permissions") | |
| permission = relationship("Permission") | |
| __table_args__ = ( | |
| UniqueConstraint("role_id", "permission_id", name="_role_permission_uc"), | |
| Index("idx_role_permission_active", "role_id", "permission_id", "is_active"), | |
| ) | |
| class UserRole(StandardModel): | |
| """User role assignments with context""" | |
| __tablename__ = "user_roles" | |
| user_id = Column( | |
| POSTGRES_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False | |
| ) | |
| role_id = Column( | |
| POSTGRES_UUID(as_uuid=True), ForeignKey("roles.id", ondelete="CASCADE"), nullable=False | |
| ) | |
| # Assignment context | |
| assigned_by = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| assigned_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False) | |
| expires_at = Column(DateTime, nullable=True) | |
| is_active = Column(Boolean, default=True, nullable=False) | |
| # Scope limitations | |
| scope_type = Column(String(50), nullable=True) # e.g., "organization", "department" | |
| scope_id = Column(String(100), nullable=True) # ID of the scope entity | |
| # Relationships | |
| role = relationship("Role", back_populates="user_roles") | |
| __table_args__ = ( | |
| UniqueConstraint( | |
| "user_id", "role_id", "scope_type", "scope_id", name="_user_role_scope_uc" | |
| ), | |
| Index("idx_user_role_active", "user_id", "role_id", "is_active"), | |
| ) | |
| class ApiKey(AuditableModel): | |
| """API key management for service-to-service authentication""" | |
| __tablename__ = "api_keys" | |
| key_id = Column(String(32), unique=True, nullable=False, index=True) | |
| key_hash = Column(String(128), nullable=False) # Store hashed key | |
| name = Column(String(100), nullable=False) | |
| description = Column(Text, nullable=True) | |
| # Owner and scope | |
| owner_id = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| service_name = Column(String(100), nullable=True) | |
| # Key properties | |
| is_active = Column(Boolean, default=True, nullable=False) | |
| last_used_at = Column(DateTime, nullable=True) | |
| usage_count = Column(Integer, default=0, nullable=False) | |
| # Expiration and limits | |
| expires_at = Column(DateTime, nullable=True) | |
| rate_limit_per_hour = Column(Integer, default=1000, nullable=False) | |
| # Permissions (JSON array of permission names) | |
| permissions = Column(JSON, nullable=True) | |
| allowed_ips = Column(JSON, nullable=True) # IP whitelist | |
| def __repr__(self): | |
| return f"<ApiKey(key_id='{self.key_id}', name='{self.name}', active={self.is_active})>" | |
| class AuditLog(BaseModel): | |
| """Comprehensive audit logging for HIPAA compliance""" | |
| __tablename__ = "audit_logs" | |
| # Who | |
| user_id = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| username = Column(String(100), nullable=True) | |
| api_key_id = Column(String(32), nullable=True) | |
| # What | |
| action = Column(String(100), nullable=False, index=True) | |
| resource_type = Column(String(50), nullable=False, index=True) | |
| resource_id = Column(String(100), nullable=True, index=True) | |
| # When | |
| timestamp = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, index=True) | |
| # Where | |
| ip_address = Column(String(45), nullable=True) # Support both IPv4 and IPv6 | |
| user_agent = Column(Text, nullable=True) | |
| session_id = Column(String(100), nullable=True) | |
| # How/Context | |
| method = Column(String(10), nullable=True) # HTTP method | |
| endpoint = Column(String(200), nullable=True) | |
| request_id = Column(String(100), nullable=True, index=True) | |
| # Details | |
| old_values = Column(JSON, nullable=True) # Before change | |
| new_values = Column(JSON, nullable=True) # After change | |
| audit_metadata = Column(JSON, nullable=True) # Additional context | |
| # Result | |
| success = Column(Boolean, nullable=False, index=True) | |
| error_message = Column(Text, nullable=True) | |
| response_code = Column(Integer, nullable=True) | |
| # Compliance flags | |
| contains_phi = Column(Boolean, default=False, nullable=False, index=True) | |
| requires_approval = Column(Boolean, default=False, nullable=False) | |
| approved_by = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| approved_at = Column(DateTime, nullable=True) | |
| __table_args__ = ( | |
| Index("idx_audit_user_timestamp", "user_id", "timestamp"), | |
| Index("idx_audit_resource_timestamp", "resource_type", "resource_id", "timestamp"), | |
| Index("idx_audit_phi_timestamp", "contains_phi", "timestamp"), | |
| Index("idx_audit_action_timestamp", "action", "timestamp"), | |
| ) | |
| def __repr__(self): | |
| return f"<AuditLog(user='{self.username}', action='{self.action}', resource='{self.resource_type}')>" | |
| class SecurityEvent(BaseModel): | |
| """Security events and alerts for monitoring""" | |
| __tablename__ = "security_events" | |
| event_type = Column(String(50), nullable=False, index=True) | |
| severity = Column( | |
| String(20), default="medium", nullable=False, index=True | |
| ) # low, medium, high, critical | |
| # Event details | |
| title = Column(String(200), nullable=False) | |
| description = Column(Text, nullable=True) | |
| # Associated entities | |
| user_id = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| session_id = Column(String(100), nullable=True) | |
| ip_address = Column(String(45), nullable=True) # Support both IPv4 and IPv6 | |
| # Event context | |
| timestamp = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, index=True) | |
| user_agent = Column(Text, nullable=True) | |
| request_details = Column(JSON, nullable=True) | |
| # Response and resolution | |
| is_resolved = Column(Boolean, default=False, nullable=False) | |
| resolved_by = Column(POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) | |
| resolved_at = Column(DateTime, nullable=True) | |
| resolution_notes = Column(Text, nullable=True) | |
| # Risk assessment | |
| risk_score = Column(Integer, default=0, nullable=False) # 0-100 | |
| automated_response = Column(String(100), nullable=True) # Action taken by system | |
| __table_args__ = ( | |
| Index("idx_security_event_type_timestamp", "event_type", "timestamp"), | |
| Index("idx_security_severity_timestamp", "severity", "timestamp"), | |
| Index("idx_security_unresolved", "is_resolved", "severity", "timestamp"), | |
| ) | |
| class DataAccessLog(BaseModel): | |
| """Specific logging for PHI/PII access (HIPAA requirement)""" | |
| __tablename__ = "data_access_logs" | |
| # Access details | |
| user_id = Column( | |
| POSTGRES_UUID(as_uuid=True), ForeignKey("users.id"), nullable=False, index=True | |
| ) | |
| patient_id = Column( | |
| POSTGRES_UUID(as_uuid=True), ForeignKey("patients.id"), nullable=True, index=True | |
| ) | |
| # Data accessed | |
| data_type = Column(String(100), nullable=False, index=True) # medical_record, lab_result, etc. | |
| data_id = Column(String(100), nullable=False, index=True) | |
| data_fields = Column(JSON, nullable=True) # Specific fields accessed | |
| # Access context | |
| access_timestamp = Column( | |
| DateTime, default=lambda: datetime.now(UTC), nullable=False, index=True | |
| ) | |
| access_purpose = Column(String(100), nullable=False) # treatment, payment, operations, research | |
| justification = Column(Text, nullable=True) | |
| # Technical details | |
| ip_address = Column(String(45), nullable=True) # Support both IPv4 and IPv6 | |
| session_id = Column(String(100), nullable=True) | |
| application = Column(String(50), nullable=False) # surgio, clinica, etc. | |
| # Compliance | |
| consent_obtained = Column(Boolean, nullable=True) | |
| minimum_necessary = Column(Boolean, default=True, nullable=False) | |
| retention_period = Column(Integer, nullable=True) # Days to retain this log | |
| __table_args__ = ( | |
| Index("idx_data_access_user_timestamp", "user_id", "access_timestamp"), | |
| Index("idx_data_access_patient_timestamp", "patient_id", "access_timestamp"), | |
| Index("idx_data_access_type_timestamp", "data_type", "access_timestamp"), | |
| ) | |
| # Default roles and permissions setup | |
| DEFAULT_ROLES = { | |
| "superuser": { | |
| "description": "System administrator with full access", | |
| "is_system_role": True, | |
| "permissions": ["*:*"], # All permissions | |
| }, | |
| "admin": { | |
| "description": "Organization administrator", | |
| "is_system_role": True, | |
| "permissions": [ | |
| "user:create", | |
| "user:read", | |
| "user:update", | |
| "user:delete", | |
| "organization:read", | |
| "organization:update", | |
| "system:read", | |
| ], | |
| }, | |
| "physician": { | |
| "description": "Licensed physician", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "patient:create", | |
| "patient:read", | |
| "patient:update", | |
| "medical_record:create", | |
| "medical_record:read", | |
| "medical_record:update", | |
| "appointment:create", | |
| "appointment:read", | |
| "appointment:update", | |
| "appointment:cancel", | |
| "prescription:create", | |
| "prescription:read", | |
| "prescription:update", | |
| "lab_result:read", | |
| "imaging:read", | |
| "surgery:create", | |
| "surgery:read", | |
| "surgery:update", | |
| "surgery:schedule", | |
| ], | |
| }, | |
| "nurse": { | |
| "description": "Registered nurse", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "patient:read", | |
| "patient:update", | |
| "medical_record:read", | |
| "medical_record:update", | |
| "appointment:read", | |
| "appointment:update", | |
| "prescription:read", | |
| "lab_result:read", | |
| "imaging:read", | |
| ], | |
| }, | |
| "surgeon": { | |
| "description": "Licensed surgeon", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "patient:read", | |
| "patient:update", | |
| "surgery:create", | |
| "surgery:read", | |
| "surgery:update", | |
| "surgery:schedule", | |
| "medical_record:read", | |
| "medical_record:update", | |
| "imaging:read", | |
| "lab_result:read", | |
| ], | |
| }, | |
| "researcher": { | |
| "description": "Medical researcher", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "patient:read", # De-identified only | |
| "medical_record:read", # De-identified only | |
| "lab_result:read", | |
| "imaging:read", | |
| "surgery:read", | |
| "system:export", | |
| ], | |
| }, | |
| "educator": { | |
| "description": "Medical educator", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "course:create", | |
| "course:read", | |
| "course:update", | |
| "curriculum:create", | |
| "curriculum:read", | |
| "curriculum:update", | |
| "assessment:create", | |
| "assessment:read", | |
| "assessment:update", | |
| ], | |
| }, | |
| "student": { | |
| "description": "Medical student", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "course:read", | |
| "curriculum:read", | |
| "assessment:read", | |
| "patient:read", # Limited, supervised access | |
| ], | |
| }, | |
| "insurance": { | |
| "description": "Insurance analyst", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "insurance:read", | |
| "insurance:update", | |
| "claim:create", | |
| "claim:read", | |
| "claim:update", | |
| "patient:read", # Limited to insurance info | |
| ], | |
| }, | |
| "logistics": { | |
| "description": "Logistics coordinator", | |
| "is_system_role": False, | |
| "permissions": [ | |
| "inventory:create", | |
| "inventory:read", | |
| "inventory:update", | |
| "supply_order:create", | |
| "supply_order:read", | |
| "supply_order:update", | |
| "shipment:create", | |
| "shipment:read", | |
| "shipment:update", | |
| ], | |
| }, | |
| } | |
| __all__ = [ | |
| "ResourceType", | |
| "ActionType", | |
| "SecurityEventType", | |
| "Role", | |
| "Permission", | |
| "RolePermission", | |
| "UserRole", | |
| "ApiKey", | |
| "AuditLog", | |
| "SecurityEvent", | |
| "DataAccessLog", | |
| "DEFAULT_ROLES", | |
| ] | |