# Timebank.cc Security Overview

This document provides a comprehensive overview of the authentication and security features implemented in the Timebank.cc application.

## Multi-Guard Authentication System

### Guard Architecture
The application implements a sophisticated 4-guard authentication system:

- **web**: Individual user accounts (`App\Models\User`) - Base authentication layer
- **organization**: Non-profit organization profiles (`App\Models\Organization`) 
- **bank**: Timebank operator profiles (`App\Models\Bank`)
- **admin**: Administrative profiles (`App\Models\Admin`)

### Profile Relationship Model
Each User can be associated with multiple elevated profiles through relationships:
```php
// User Model Relationships
$user->organizations()    // Many-to-many via organization_user table
$user->banksManaged()     // Many-to-many via bank_user table  
$user->admins()           // Many-to-many via admins_user table
```

### Guard Switching Mechanism

#### SwitchGuardTrait Implementation
Located in `app/Traits/SwitchGuardTrait.php`:

```php
function switchGuard($newGuard, $profile) {
    // Logout from all other elevated guards
    foreach (['admin', 'bank', 'organization'] as $guard) {
        if ($guard !== $newGuard) {
            Auth::guard($guard)->logout();
        }
    }
    Auth::guard($newGuard)->login($profile);
    session(['active_guard' => $newGuard]);
}
```

**Security Features**:
- **Mutual Exclusion**: Only one elevated guard active at a time
- **Base Guard Preservation**: 'web' guard remains active as foundation
- **Session State Management**: Active guard tracked in session

#### Profile Switch Flow
Complete authentication flow for elevated profiles:

1. **Intent Registration**: Target profile stored in session
2. **Relationship Verification**: System validates user association with target profile
3. **Password Re-Authentication**: Separate password verification required for elevated access
4. **Legacy Password Migration**: Automatic Cyclos password conversion if applicable
5. **Guard Switch**: Authentication state transition using SwitchGuardTrait
6. **Session Update**: Active profile context establishment
7. **Event Broadcasting**: Real-time profile switch notification

#### Direct Login Routes for Non-User Profiles
Secure direct links to elevated profile logins for use in emails and external communications:

**Route Structure:**
```php
// Organization
GET /organization/{organizationId}/login
Route name: 'organization.direct-login'

// Bank
GET /bank/{bankId}/login
Route name: 'bank.direct-login'

// Admin
GET /admin/{adminId}/login
Route name: 'admin.direct-login'
```

**Layered Authentication Flow:**
1. **Profile Existence Validation**: System verifies target profile exists (404 if not found)
2. **User Authentication Check**:
   - If user not authenticated on 'web' guard → redirect to user login
   - Stores return URL in `session('url.intended')` for post-login redirect
   - Custom `LoginResponse` allows redirect back to profile switch after user auth
3. **Relationship Authorization**: Verifies user owns/manages target profile (403 if denied)
4. **Profile Switch**:
   - **Organizations**: Direct guard switch without password (passwordless)
   - **Banks/Admins**: Sets session variables for profile password page
5. **Password Re-Authentication** (Banks/Admins only): Redirects to profile-specific password entry
6. **Guard Switch & Redirect**: Switches guard and redirects to intended URL or main page

**Security Features:**
- **Multi-Layer Verification**: Requires both user authentication AND profile relationship
- **Differentiated Authentication**:
  - **Organizations**: Passwordless switch (matches in-app profile switching behavior)
  - **Banks**: Separate password required for elevated financial privileges
  - **Admins**: Separate password required for administrative access
- **Session Isolation**: Each profile type uses dedicated session keys
- **Intended URL Validation**: Only allows redirects to profile login routes during user auth phase
- **Automatic Cleanup**: Session variables cleared after successful authentication
- **Access Control**:
  - Organizations: Verified via `organization_user` pivot table
  - Banks: Verified via `bank_managers` pivot table
  - Admins: Verified via `admin_user` pivot table

**Session Variables Used:**
```php
// Common for all types
'url.intended'                    // Laravel's intended URL (user login phase)
'intended_profile_switch_type'    // Target profile type (Organization|Bank|Admin)
'intended_profile_switch_id'      // Target profile ID

// Profile-specific final redirects
'organization_login_intended_url' // Post-organization-login destination
'bank_login_intended_url'         // Post-bank-login destination
'admin_login_intended_url'        // Post-admin-login destination
```

**Implementation Locations:**
- Controllers: `OrganizationLoginController`, `BankLoginController`, `AdminLoginController`
- Custom Response: `app/Http/Responses/LoginResponse.php` (handles user login redirects)
- Routes: `routes/web.php` (lines 434, 448, 462)
- Documentation: `references/PROFILE_DIRECT_LOGIN.md`

**Use Case Examples:**
```php
// Email notification to organization manager
route('organization.direct-login', [
    'organizationId' => $org->id,
    'intended' => route('event.approve', $event->id)
])

// Bank transaction alert
route('bank.direct-login', [
    'bankId' => $bank->id,
    'intended' => route('transaction.review', $tx->id)
])

// Admin moderation request
route('admin.direct-login', [
    'adminId' => $admin->id,
    'intended' => route('report.handle', $report->id)
])
```

This feature maintains the security principle of layered authentication while providing seamless deep-linking capabilities for email workflows.

### Session-Based Profile Management

#### Global Helper Functions
Located in `app/Helpers/ProfileHelper.php`:

- **getActiveProfile()**: Retrieves current active profile model from session
- **getActiveProfileType()**: Returns profile type name (User, Organization, Bank, Admin)
- **userOwnsProfile()**: Verifies user ownership of profile through relationships

#### Session Data Structure
Active profile information stored in encrypted session:
- Profile type (full class name)
- Profile ID and name
- Profile photo path
- Last activity timestamp
- Active guard identifier

### Custom Middleware Stack

#### SetActiveGuard Middleware
Ensures Laravel uses the correct guard for each request based on session state.

#### AuthAnyGuard Middleware
Validates authentication across multiple specified guards, redirecting to login if none are authenticated.

**Usage Pattern**: `middleware(['auth.any:admin,bank,organization,web'])`

### Template Security Integration

#### Custom Blade Directives
Registered in `AppServiceProvider.php`:

```blade
@profile('admin')
    <div>Admin-only content</div>
@endprofile

@usercan('manage users')
    <button>Manage Users</button>
@endusercan
```

These directives provide secure, session-aware template rendering based on active profile type and permissions.

## Database-Level Security

### Transaction Immutability
**Critical Financial Security** implemented at MySQL user permission level:

The application database user has restricted permissions where transactions can only be created (INSERT) and read (SELECT), but never modified (UPDATE) or deleted (DELETE). This ensures:

- All transactions are permanent once created
- Application cannot modify transaction history
- Complete financial audit trail maintained
- Prevents accidental or malicious transaction tampering

### Model Security Patterns
- **Mass Assignment Protection**: Models use selective `$fillable` arrays
- **Hidden Attributes**: Sensitive fields (passwords, tokens) hidden from serialization
- **Soft Deletes**: Critical models use soft deletion to preserve data integrity

## Session Security & Timeout Management

### Profile-Specific Timeout Policies
The system supports configurable timeout periods per profile type:
- Different timeout durations based on profile privilege level
- More privileged profiles can have shorter timeout periods
- Configurable through `config/timebank-cc.php`

### Timeout Security Features
Implemented in `CheckProfileInactivity` middleware:

#### Graduated Timeout Behavior
- **Standard Users**: Configurable full logout on timeout
- **Elevated Profiles**: Configurable graceful demotion to User profile
- **Security Principle**: Higher privilege levels can have shorter timeouts

#### Activity Tracking Exclusions
System excludes specific routes (heartbeat, livewire updates) from resetting activity timers to prevent artificial session extension.

#### AJAX-Aware Timeout Responses
Provides appropriate JSON responses for timeout events in AJAX requests with proper HTTP status codes.

### Session Encryption & Storage
- **Database Storage**: Sessions stored in database for scalability
- **Encryption**: All session data encrypted
- **Configurable Lifetime**: Base session lifetime configurable
- **Secure Cookies**: HTTPS-only and HttpOnly flags in production

## Livewire Method-Level Authorization

### Protection Against Direct Method Invocation Attacks

**Critical Security Feature** implemented across all admin management Livewire components to prevent unauthorized direct method calls.

#### The Vulnerability

Livewire components present a unique security challenge: the `mount()` method only executes once when the component loads. After that, any public method can be called directly via browser console:

```javascript
Livewire.find('component-id').call('methodName', parameters)
```

If authorization is only checked in `mount()`, attackers can bypass these checks by calling methods directly after the component loads.

#### The Solution: RequiresAdminAuthorization Trait

**File**: `app/Http/Livewire/Traits/RequiresAdminAuthorization.php`

All sensitive admin operations use this trait which provides:
- **ProfileAuthorizationHelper Integration**: Centralized authorization with database-level validation
- **Cross-Guard Attack Prevention**: Validates authenticated guard matches profile type
- **IDOR Prevention**: Prevents access to unauthorized profiles
- **Bank Level Validation**: Only central bank (level=0) can access admin functions
- **Performance Caching**: Request-scoped caching to avoid repeated checks

#### Protected Components (27 Methods)

1. **Posts/Manage.php** - 7 methods (create, edit, save, delete, undelete, publication control)
2. **Categories/Manage.php** - 4 methods (create, update, delete operations)
3. **Tags/Manage.php** - 3 methods (create, update, delete operations)
4. **Tags/Create.php** - 1 method (create)
5. **Profiles/Manage.php** - 5 methods (create, update, delete, restore, attach operations)
6. **Profiles/Create.php** - 1 method (create) - **Critical vulnerability fixed**
7. **Mailings/Manage.php** - 6 methods (create, save, send, delete operations) - **Bulk delete vulnerability fixed**

#### Usage Pattern

```php
public function sensitiveOperation($id)
{
    // CRITICAL: Authorize admin access at method level
    $this->authorizeAdminAccess();

    // Now safe to perform the sensitive operation
    Model::find($id)->update($data);
}
```

#### Documentation

See `references/LIVEWIRE_METHOD_AUTHORIZATION_SECURITY.md` for comprehensive documentation including:
- Complete method inventory
- Security architecture details
- Testing requirements
- Migration guide for new components

## Role-Based Access Control (RBAC)

### Spatie Permissions Integration
Advanced permission system with hierarchical roles:

#### Role Naming Convention
```php
// Pattern: {ProfileType}\{ProfileID}\{role-suffix}
"Admin\{id}\admin"
"Bank\{id}\bank-manager"
"Organization\{id}\organization-manager"
```

#### Permission Categories
Granular permissions for different functional areas:
- **Content Management**: Posts, categories, tags
- **Profile Management**: User profiles and accounts
- **Transaction Management**: Financial operations
- **System Administration**: Platform configuration

#### Permission Checking Implementation
Custom traits provide methods to verify permissions based on active profile context and role assignments.

## Input Validation & Protection

### CSRF Protection
- **Implementation**: Laravel's built-in `VerifyCsrfToken` middleware
- **Scope**: All state-changing requests protected
- **No Exclusions**: Maximum security with no CSRF bypass routes

### Hidden Captcha Protection
Time-based form submission validation:
- **Minimum Submission Time**: Prevents bot submissions
- **Maximum Submission Time**: Prevents abandoned form attacks
- **Configurable Timing**: Adjustable timing windows

### Form Validation Security
Multi-layer validation approach:

#### Authorization Verification
- Model class existence validation
- Profile existence verification
- User association checking through relationships
- Hash-based verification for sensitive operations

#### Hash-Based Security
- **Email Verification**: SHA1 hash comparison prevents URL tampering
- **Timing Attack Protection**: `hash_equals()` prevents timing analysis
- **Association Validation**: Users must own profiles to perform actions

## Legacy System Security

### Cyclos Password Migration
Secure migration from legacy Cyclos system:

- **Backward Compatibility**: Supports existing SHA256+salt passwords
- **Automatic Conversion**: Migrates to Laravel hashing on successful login
- **One-Time Migration**: Salt removed after conversion
- **Transparent Process**: Users unaware of password format changes

## Real-Time Security

### WebSocket Authentication
Integration with Laravel Reverb and WireChat:

#### Multi-Guard Support
WireChat configured to work with all 4 authentication guards, ensuring real-time features respect the multi-profile system.

#### Presence Tracking Security
- **Guard-Aware Tracking**: Presence system tracks which guard user is active on
- **Authentication Verification**: Presence updates only for authenticated users
- **Profile Context**: Presence reflects current active profile type

### Broadcasting Security
- **Private Channels**: User-specific channels prevent unauthorized access
- **Authentication Requirements**: Channels require proper authentication
- **Event Data Security**: Only necessary profile information broadcast

## Route Protection Strategies

### Layered Middleware Protection
Multiple middleware combinations for different security levels.

#### Multi-Guard Routes
Routes can specify multiple acceptable guards for flexible access control.

#### Guard-Specific Routes
Routes can require specific guard types for profile-type-restricted functionality.

#### Enhanced Security Routes
High-security routes can combine multiple middleware layers (authentication, session verification, email verification).

## Activity Logging & Monitoring

### Comprehensive Activity Tracking
Using Spatie ActivityLog package:

#### Profile Switch Logging
All profile switches logged with:
- Source and target profile information
- Timestamp and user context
- Previous login information
- Custom log categories

#### Selective Model Logging
Models configured to log only sensitive attribute changes to balance security with performance.

### Event Broadcasting System
Profile switches and security events broadcast through:
- **Private Channels**: User-specific channels prevent eavesdropping
- **Secure Event Data**: Minimal necessary information broadcast
- **Queue Processing**: Events processed through authenticated queue system

## Profile Inactivity Management

### Automated Inactivity Detection
Configurable inactivity policies for:
- **Search Visibility**: Hide inactive profiles from search results
- **Messenger Access**: Remove inactive profiles from chat searches
- **Profile Access**: Control profile page visibility
- **Labeling**: Visual indicators for inactive status

### Security Implications
- **Privacy Protection**: Inactive profiles automatically hidden
- **Reversible Process**: Profiles can be reactivated without data loss
- **Configurable Behavior**: All inactivity policies configurable

## Email Verification Security

### Multi-Profile Email Verification
Custom implementation supporting all profile types:

#### Association Verification
Strict verification that users own the profiles they're attempting to verify through proper relationship checking.

#### Hash Verification Security
Uses timing-attack-resistant hash comparison for email verification URLs.

## Security Configuration Framework

### Key Configuration Files
- `config/auth.php`: Multi-guard authentication setup
- `config/fortify.php`: Authentication feature configuration  
- `config/permission.php`: Role-based access control settings
- `config/hidden_captcha.php`: Bot protection timing configuration
- `config/timebank-cc.php`: Profile timeout and security policies

### Environment Security
- **Database User Restrictions**: Limited MySQL permissions for application user
- **Session Security**: Configurable encryption and storage options
- **Rate Limiting**: Configurable throttling for authentication attempts
- **Timeout Policies**: Profile-specific session timeout configuration

## Security Best Practices

### Defense in Depth
- **Multiple Authentication Layers**: Guards + middleware + permissions + database restrictions
- **Input Validation**: Request validation + model validation + business logic validation
- **Session Security**: Encryption + timeouts + activity tracking + CSRF protection

### Principle of Least Privilege
- **Minimal Permissions**: Roles contain only necessary permissions
- **Profile Isolation**: Elevated profiles automatically timeout to lower privilege
- **Relationship Verification**: Strict ownership checks before profile access

### Audit & Monitoring
- **Complete Activity Logging**: All profile actions tracked with configurable retention
- **Real-time Event Broadcasting**: Immediate notification of security events
- **Comprehensive Error Logging**: Detailed logging without exposing sensitive data

### Secure Defaults
- **Encrypted Sessions**: All session data encrypted by default
- **CSRF Protection**: Universal CSRF verification with no exclusions
- **Email Verification**: Configurable verification requirements
- **Password Confirmation**: Required for sensitive operations

This security framework provides robust protection for the time banking platform while maintaining flexibility through comprehensive configuration options.