# Security Documentation

## Overview

Comprehensive security implementation covering multi-tenancy, authentication, authorization, and data protection.

## Multi-Tenancy Security

### Data Isolation

**Implementation:**
- Global scopes on all tenant models
- Automatic `organization_id` filtering
- Middleware-based tenant context
- Database-level constraints

**Protected Models:**
All models with `HasTenantScope` trait:
- Employee, Department, Attendance, LeaveRequest
- Payroll, PayrollSettings, PayrollApproval
- PerformanceReview, PerformanceGoal
- TrainingEnrollment, TrainingRecommendation
- Application, Interview, JobOffer
- LoanRepayment, AuditLog
- ThemeSetting, ApplicationMessage

### Tenant Scope Trait

```php
trait HasTenantScope
{
    protected static function bootHasTenantScope()
    {
        // Auto-set organization_id on create
        static::creating(function ($model) {
            if (auth()->check() && !$model->organization_id) {
                $model->organization_id = auth()->user()->organization_id;
            }
        });

        // Filter by organization_id on all queries
        static::addGlobalScope('organization', function (Builder $builder) {
            if (auth()->check() && !auth()->user()->is_system_admin) {
                $builder->where('organization_id', auth()->user()->organization_id);
            }
        });
    }
}
```

### Middleware

**SetTenantContext** (`app/Http/Middleware/SetTenantContext.php`)
- Sets current organization in session
- Validates user belongs to organization
- Prevents cross-organization access

**TenantScopeMiddleware** (`app/Http/Middleware/TenantScopeMiddleware.php`)
- Enforces tenant scoping on routes
- Validates organization_id in requests
- Blocks unauthorized access attempts

**SystemAdminMiddleware** (`app/Http/Middleware/SystemAdminMiddleware.php`)
- Restricts system admin routes
- Validates `is_system_admin` flag
- Separate authentication context

## Authentication

### User Authentication

**Features:**
- Email/password authentication
- Email verification with OTP
- Password reset functionality
- Session management
- Remember me functionality

**Rate Limiting:**
- Login: 5 attempts per minute
- Password reset: 5 attempts per minute
- OTP requests: 60 seconds between requests

### Two-Factor Authentication (2FA)

**Implementation:**
- Optional 2FA for users
- TOTP-based (Time-based One-Time Password)
- Recovery codes for backup access
- QR code generation for easy setup

**Routes:**
```php
Route::get('/two-factor', [TwoFactorController::class, 'show']);
Route::post('/two-factor/enable', [TwoFactorController::class, 'enable']);
Route::delete('/two-factor/disable', [TwoFactorController::class, 'disable']);
Route::post('/two-factor/recovery-codes', [TwoFactorController::class, 'generateRecoveryCodes']);
```

### Account Security

**Features:**
- Account lockout after failed attempts
- Locked until timestamp
- Password complexity requirements
- Secure password hashing (bcrypt)

**User Model Fields:**
```php
'locked_until' => 'datetime',
'two_factor_secret' => 'encrypted',
'two_factor_recovery_codes' => 'encrypted:array',
'two_factor_confirmed_at' => 'datetime',
```

## Authorization

### Role-Based Access Control (RBAC)

**Spatie Permission Package:**
- Roles: org_admin, hr_manager, employee, etc.
- Permissions: manage_employees, view_payroll, etc.
- Role-permission assignments
- User-role assignments

**Middleware:**
```php
Route::middleware(['role:org_admin'])->group(function () {
    // Admin-only routes
});

Route::middleware(['permission:manage_employees'])->group(function () {
    // Permission-specific routes
});
```

### Organization-Level Permissions

**Scoping:**
- Roles scoped to organizations
- Permissions scoped to organizations
- No cross-organization role/permission access

**Implementation:**
```php
// Assign role within organization context
$user->assignRole('hr_manager');

// Check permission within organization
if ($user->can('manage_employees')) {
    // Authorized
}
```

## Data Protection

### Input Sanitization

**SanitizeInput Middleware** (`app/Http/Middleware/SanitizeInput.php`)
- Strips HTML tags from input
- Prevents XSS attacks
- Whitelist for allowed HTML fields
- Applied globally to all requests

### CSRF Protection

**VerifyCsrfToken Middleware:**
- Automatic CSRF token validation
- Token in all forms
- API routes excluded (use Sanctum)

### SQL Injection Prevention

**Eloquent ORM:**
- Parameterized queries
- Automatic escaping
- No raw SQL without bindings

### File Upload Security

**SecureFileUpload Middleware** (`app/Http/Middleware/SecureFileUpload.php`)
- File type validation
- File size limits
- Virus scanning (optional)
- Secure storage paths

### Security Headers

**SecurityHeaders Middleware** (`app/Http/Middleware/SecurityHeaders.php`)
```php
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000
Content-Security-Policy: default-src 'self'
```

## Audit Logging

### Activity Log

**Spatie Activity Log Package:**
- Tracks all important actions
- Records user, action, model, properties
- Searchable and filterable
- Organization-scoped

**Usage:**
```php
activity()
    ->performedOn($model)
    ->causedBy($user)
    ->withProperties(['key' => 'value'])
    ->log('Action description');
```

### Audit Trail

**AuditLog Model:**
- Custom audit logging
- Tracks data changes
- Before/after values
- IP address and user agent
- Organization-scoped

**Auditable Trait:**
```php
use Auditable;

protected $auditExcluded = ['password', 'remember_token'];
```

## Email Security

### OTP Verification

**Features:**
- Spatie One-Time Passwords package
- 6-digit secure codes
- 10-minute expiration
- Rate limiting
- Email delivery

**Security:**
- Cryptographically secure generation
- Single-use codes
- Automatic cleanup
- No code reuse

### Email Configuration

**Organization-Level:**
- Custom SMTP settings per organization
- Encrypted credentials
- Test before save
- Fallback to system email

**System-Level:**
- Default SMTP configuration
- Secure credential storage
- TLS/SSL encryption

## API Security

### Sanctum Authentication

**Features:**
- Token-based authentication
- Personal access tokens
- Token abilities/scopes
- Token expiration

**Usage:**
```php
Route::middleware('auth:sanctum')->group(function () {
    // Protected API routes
});
```

### Rate Limiting

**API Routes:**
- 60 requests per minute (default)
- Customizable per route
- IP-based limiting
- User-based limiting

## Subscription Security

### Access Control

**CheckSubscription Middleware:**
- Validates active subscription
- Checks subscription status
- Enforces feature limits
- Redirects to upgrade page

**CheckQuota Middleware:**
- Validates employee count
- Checks feature usage
- Enforces plan limits
- Prevents over-usage

### Payment Security

**M-Pesa Integration:**
- Secure callback URLs
- Request validation
- Transaction verification
- Encrypted credentials

## Best Practices

### Password Security
- Minimum 8 characters
- Bcrypt hashing
- No password reuse
- Secure reset process

### Session Security
- Secure session cookies
- HTTP-only cookies
- Session regeneration on login
- Automatic timeout

### Database Security
- Encrypted sensitive fields
- No plain text passwords
- Secure connection (SSL)
- Regular backups

### Code Security
- Input validation
- Output escaping
- Dependency updates
- Security patches

## Security Checklist

### Deployment
- [ ] Change default passwords
- [ ] Enable HTTPS
- [ ] Configure firewall
- [ ] Set up monitoring
- [ ] Enable logging
- [ ] Configure backups
- [ ] Test security measures

### Regular Maintenance
- [ ] Update dependencies
- [ ] Review audit logs
- [ ] Check failed login attempts
- [ ] Monitor suspicious activity
- [ ] Update security policies
- [ ] Train users on security

## Incident Response

### Security Breach
1. Identify affected systems
2. Isolate compromised accounts
3. Review audit logs
4. Reset credentials
5. Notify affected users
6. Document incident
7. Implement fixes

### Data Leak
1. Identify leaked data
2. Assess impact
3. Notify affected parties
4. Implement containment
5. Review access controls
6. Update security measures

## Compliance

### Data Protection
- GDPR compliance considerations
- Data retention policies
- Right to deletion
- Data export functionality

### Audit Requirements
- Activity logging
- Access tracking
- Change history
- Compliance reports

## Related Documentation

- [Multi-Tenancy](MULTI_TENANCY.md)
- [Activity Logging](ACTIVITY_LOG_INTEGRATION.md)
- [User Roles & Permissions](USER_ROLES_PERMISSIONS.md)
- [Onboarding System](ONBOARDING_SYSTEM.md)
