Files
timebank-cc-public/references/SECURITY_TESTING_PLAN.md
Ronald Huynen 2547717edb Initial commit
2026-03-23 21:37:59 +01:00

1070 lines
31 KiB
Markdown

# Comprehensive Security Testing Plan
**Application:** Timebank.cc Multi-Profile Time Banking Platform
**Last Updated:** 2026-01-09
**Status:** In Progress - Phase 1 Complete, Phase 2 Active
## Table of Contents
1. [Executive Summary](#executive-summary)
2. [Current Security Posture](#current-security-posture)
3. [Testing Areas](#testing-areas)
4. [Implementation Roadmap](#implementation-roadmap)
5. [Test Maintenance](#test-maintenance)
---
## Executive Summary
This document outlines a comprehensive security testing strategy for the Timebank.cc platform. The application has unique security requirements due to its multi-guard authentication system, financial transaction handling, and multi-profile architecture.
### Security Testing Objectives
- **Prevent unauthorized access** to profiles, accounts, and financial data
- **Validate authentication** across all 4 guard types (web, organization, bank, admin)
- **Test authorization** for profile switching, transactions, and administrative actions
- **Verify XSS protection** for user-generated and admin-generated content
- **Ensure CSRF protection** on all state-changing operations
- **Validate input sanitization** across all entry points
- **Test session security** including timeout policies and profile switching
- **Verify database security** especially transaction immutability
- **Test real-time features** for authentication and authorization
### Risk Classification
- **CRITICAL:** Database security, transaction integrity, authentication bypasses
- **HIGH:** Authorization bypasses, XSS vulnerabilities, session hijacking
- **MEDIUM:** CSRF bypasses, input validation, rate limiting
- **LOW:** Information disclosure, weak configurations
### Recent Audit Results (2026-01-09)
**Presence System & Profile Status Badges Audit**
- **Status:** ✅ APPROVED FOR PRODUCTION
- **Commits Tested:** 177f56ec, 9d69c337
- **Key Findings:**
- All IDOR protections from December 2025 maintained
- ProfileAuthorizationHelper integration intact
- Cross-guard attacks prevented
- Session manipulation blocked
- Public presence visibility is by design (not a vulnerability)
- **Full Report:** [SECURITY_AUDIT_PRESENCE_2026-01-09.md](/SECURITY_AUDIT_PRESENCE_2026-01-09.md)
---
## Current Security Posture
### Existing Security Controls
Based on `references/SECURITY_OVERVIEW.md` and code review:
#### Authentication & Authorization ✓
- Multi-guard authentication (web, organization, bank, admin)
- SwitchGuardTrait for secure profile switching
- Password re-authentication for elevated profiles
- Direct login routes with layered verification
- Email verification system
- Two-factor authentication (Jetstream)
- Session timeout policies per profile type
#### Input Validation ✓ (Partial)
- **IMPLEMENTED:**
- Search highlights sanitization (MainSearchBar.php:528)
- Post content sanitization (StringHelper::sanitizeHtml)
- CSRF protection on all routes (no exclusions)
- Hidden captcha for form submission timing
- **NEEDS MORE COVERAGE:**
- Profile name validation (tested manually, needs automated tests)
- Transaction amount validation (needs tests)
- File upload validation (needs tests)
- API input validation (needs tests)
#### Database Security ✓
- Transaction table has DELETE/UPDATE restrictions at MySQL user level
- Soft deletes on critical models
- Mass assignment protection via $fillable arrays
- Window functions for balance calculations (immutable)
#### Real-Time Security ✓
- Private WebSocket channels per user
- Multi-guard support in broadcasting
- Presence tracking with authentication checks
### Existing Test Coverage
#### Currently Tested ✓
1. **XSS Protection** (24 tests total)
- `tests/Feature/SearchXssProtectionTest.php` (8 tests)
- `tests/Feature/PostContentXssProtectionTest.php` (16 tests)
2. **Authentication** (Jetstream defaults)
- `tests/Feature/AuthenticationTest.php`
- `tests/Feature/RegistrationTest.php`
- `tests/Feature/PasswordResetTest.php`
- `tests/Feature/PasswordConfirmationTest.php`
- `tests/Feature/TwoFactorAuthenticationSettingsTest.php`
- `tests/Feature/EmailVerificationTest.php`
3. **User Management**
- `tests/Feature/ProfileInformationTest.php`
- `tests/Feature/DeleteAccountTest.php`
- `tests/Feature/BrowserSessionsTest.php`
4. **API Tokens**
- `tests/Feature/CreateApiTokenTest.php`
- `tests/Feature/DeleteApiTokenTest.php`
- `tests/Feature/ApiTokenPermissionsTest.php`
#### Not Covered Yet ⚠️
- Multi-guard authentication switching
- Organization/Bank/Admin login flows
- Profile ownership verification
- Transaction creation and authorization
- Permission-based access control
- File upload security
- Rate limiting and brute force protection
- SQL injection prevention
- Mass assignment vulnerabilities
- Information disclosure
- Session fixation attacks
- Insecure direct object references (IDOR)
- Business logic flaws
---
## Testing Areas
### 1. Authentication Security Tests
#### 1.1 Multi-Guard Authentication
**Priority: CRITICAL**
**File:** `tests/Feature/MultiGuardAuthenticationTest.php` (NEW)
**Test Cases:**
```php
// Basic guard authentication
test_user_can_authenticate_on_web_guard()
test_organization_manager_can_authenticate_on_organization_guard()
test_bank_manager_can_authenticate_on_bank_guard()
test_admin_can_authenticate_on_admin_guard()
// Guard isolation
test_only_one_elevated_guard_active_at_time()
test_web_guard_remains_active_with_elevated_guard()
test_switching_guard_logs_out_other_elevated_guards()
// Authentication failures
test_cannot_authenticate_with_invalid_credentials()
test_cannot_authenticate_on_wrong_guard()
test_authentication_fails_after_max_attempts()
test_lockout_duration_is_enforced()
```
#### 1.2 Profile Switching Security
**Priority: CRITICAL**
**File:** `tests/Feature/ProfileSwitchingSecurityTest.php` (NEW)
**Test Cases:**
```php
// Ownership verification
test_user_can_only_switch_to_owned_profiles()
test_cannot_switch_to_unowned_organization()
test_cannot_switch_to_unowned_bank()
test_cannot_switch_to_unowned_admin()
test_profile_switch_validates_relationship_pivot_tables()
// Profile switch flow
test_organization_switch_does_not_require_password()
test_bank_switch_requires_password()
test_admin_switch_requires_password()
test_invalid_password_prevents_profile_switch()
test_profile_switch_clears_session_variables()
// Session state management
test_active_guard_stored_in_session()
test_active_profile_stored_in_session()
test_profile_switch_broadcasts_event()
test_profile_switch_logged_in_activity_log()
// Edge cases
test_cannot_switch_to_nonexistent_profile()
test_cannot_switch_to_soft_deleted_profile()
test_session_fixation_prevented_on_profile_switch()
```
#### 1.3 Direct Login Routes
**Priority: HIGH**
**File:** `tests/Feature/DirectLoginRoutesSecurityTest.php` (NEW)
**Test Cases:**
```php
// Organization direct login
test_organization_direct_login_requires_user_authentication()
test_organization_direct_login_validates_ownership()
test_organization_direct_login_switches_guard()
test_organization_direct_login_redirects_to_intended_url()
test_organization_direct_login_rejects_invalid_intended_url()
// Bank direct login
test_bank_direct_login_requires_password()
test_bank_direct_login_validates_bank_manager_relationship()
test_bank_direct_login_fails_with_wrong_password()
// Admin direct login
test_admin_direct_login_requires_password()
test_admin_direct_login_validates_admin_user_relationship()
test_admin_direct_login_fails_for_non_admin_users()
// Security checks
test_direct_login_returns_404_for_nonexistent_profile()
test_direct_login_returns_403_for_unauthorized_profile()
test_direct_login_validates_intended_url_to_prevent_open_redirect()
test_direct_login_session_variables_cleared_after_completion()
```
#### 1.4 Session Security
**Priority: HIGH**
**File:** `tests/Feature/SessionSecurityTest.php` (NEW)
**Test Cases:**
```php
// Session timeout
test_inactive_user_logged_out_after_timeout()
test_inactive_elevated_profile_demoted_to_user_after_timeout()
test_activity_tracking_excludes_heartbeat_routes()
test_ajax_requests_receive_timeout_json_response()
test_timeout_duration_configurable_per_profile_type()
// Session fixation
test_session_regenerated_on_login()
test_session_regenerated_on_profile_switch()
test_session_regenerated_on_privilege_escalation()
// Session data protection
test_session_data_encrypted()
test_sensitive_data_not_stored_in_session()
test_session_cookie_has_httponly_flag()
test_session_cookie_has_secure_flag_in_production()
test_session_cookie_has_samesite_attribute()
```
---
### 2. Authorization Security Tests
#### 2.1 Permission-Based Access Control
**Priority: CRITICAL**
**File:** `tests/Feature/PermissionAuthorizationTest.php` (NEW)
**Test Cases:**
```php
// Spatie permissions integration
test_user_with_permission_can_access_protected_route()
test_user_without_permission_cannot_access_protected_route()
test_permission_naming_convention_enforced()
test_profile_specific_roles_correctly_assigned()
// Post management permissions
test_admin_with_manage_posts_can_create_post()
test_admin_without_manage_posts_cannot_create_post()
test_admin_can_only_edit_own_posts()
test_super_admin_can_edit_all_posts()
// Transaction permissions
test_bank_can_create_currency()
test_bank_can_remove_currency()
test_user_cannot_create_currency()
test_organization_cannot_create_currency()
test_transaction_type_permissions_enforced()
// User management permissions
test_admin_with_manage_users_can_view_user_list()
test_admin_without_manage_users_cannot_view_user_list()
test_admin_cannot_delete_other_admin_profiles()
```
#### 2.2 Resource Authorization
**Priority: HIGH**
**File:** `tests/Feature/ResourceAuthorizationTest.php` (NEW)
**Test Cases:**
```php
// Profile access
test_user_can_view_own_profile()
test_user_can_view_public_profiles()
test_user_cannot_view_private_profiles()
test_user_cannot_edit_other_user_profiles()
// Account access
test_user_can_view_own_account_balance()
test_user_cannot_view_other_user_account_balance()
test_bank_can_view_all_account_balances()
test_organization_balance_visibility_respects_config()
// Transaction access
test_user_can_view_own_transactions()
test_user_cannot_view_unrelated_transactions()
test_bank_can_view_all_transactions()
test_transaction_participants_can_view_shared_transaction()
// Post access
test_guest_can_view_published_posts()
test_user_can_view_published_posts()
test_admin_can_view_draft_posts()
test_user_cannot_view_draft_posts()
```
#### 2.3 Insecure Direct Object Reference (IDOR)
**Priority: CRITICAL**
**File:** `tests/Feature/IdorPreventionTest.php` (NEW)
**Test Cases:**
```php
// Profile IDOR
test_cannot_access_other_user_profile_by_id()
test_cannot_edit_other_organization_by_id()
test_cannot_delete_other_bank_by_id()
test_cannot_view_other_admin_details_by_id()
// Transaction IDOR
test_cannot_view_other_user_transaction_by_id()
test_cannot_modify_transaction_by_id()
test_cannot_delete_transaction_by_id()
// Account IDOR
test_cannot_view_other_account_balance_by_id()
test_cannot_modify_other_account_by_id()
// Message IDOR
test_cannot_read_other_user_messages_by_id()
test_cannot_send_message_as_other_user()
// Enumeration prevention
test_unauthorized_access_returns_403_not_404()
test_nonexistent_resource_returns_same_response_as_unauthorized()
```
---
### 3. Input Validation & Injection Tests
#### 3.1 XSS Protection (Enhanced)
**Priority: HIGH**
**File:** `tests/Feature/XssProtectionComprehensiveTest.php` (NEW)
**Test Cases:**
```php
// Content fields (beyond existing post/search tests)
test_profile_about_field_sanitizes_xss()
test_profile_motivation_field_sanitizes_xss()
test_organization_description_sanitizes_xss()
test_message_content_sanitizes_xss()
test_comment_content_sanitizes_xss()
test_category_name_sanitizes_xss()
test_tag_name_sanitizes_xss()
// Form fields
test_profile_name_rejects_html_tags()
test_email_field_validates_format()
test_url_fields_validate_format()
// File upload
test_uploaded_image_filename_sanitized()
test_uploaded_file_mime_type_validated()
test_svg_upload_sanitized_or_rejected()
// Rich text editors
test_quill_editor_output_sanitized()
test_trix_editor_output_sanitized()
// API responses
test_api_error_messages_escaped()
test_api_validation_errors_escaped()
```
#### 3.2 SQL Injection Prevention
**Priority: CRITICAL**
**File:** `tests/Feature/SqlInjectionPreventionTest.php` (NEW)
**Test Cases:**
```php
// Search inputs
test_search_query_uses_parameter_binding()
test_elasticsearch_query_escapes_special_characters()
test_search_filters_use_parameter_binding()
// Where clauses
test_profile_lookup_by_name_uses_parameter_binding()
test_transaction_filtering_uses_parameter_binding()
test_date_range_filters_use_parameter_binding()
// Order by clauses
test_sort_parameter_whitelisted()
test_invalid_sort_column_rejected()
test_sort_direction_validated()
// Raw queries
test_no_raw_queries_with_user_input()
test_raw_queries_use_parameter_binding()
// Mass assignment
test_guarded_attributes_not_fillable()
test_fillable_attributes_validated()
```
#### 3.3 Command Injection Prevention
**Priority: MEDIUM**
**File:** `tests/Feature/CommandInjectionPreventionTest.php` (NEW)
**Test Cases:**
```php
// File operations
test_file_paths_validated_and_sanitized()
test_cannot_access_files_outside_storage_directory()
test_file_deletion_validates_ownership()
// Image processing
test_image_resize_validates_dimensions()
test_image_filename_sanitized()
// Export operations
test_csv_export_escapes_formulas()
test_pdf_generation_sanitizes_input()
```
---
### 4. Transaction & Financial Security Tests
#### 4.1 Transaction Integrity
**Priority: CRITICAL**
**File:** `tests/Feature/TransactionIntegrityTest.php` (NEW)
**Test Cases:**
```php
// Transaction immutability
test_transaction_cannot_be_updated_after_creation()
test_transaction_cannot_be_deleted()
test_database_user_lacks_update_delete_permissions()
// Balance calculations
test_balance_calculated_correctly_with_window_functions()
test_balance_updates_reflect_immediately()
test_concurrent_transactions_maintain_consistency()
// Transaction validation
test_transaction_requires_valid_sender_account()
test_transaction_requires_valid_recipient_account()
test_transaction_amount_must_be_positive()
test_transaction_type_must_be_valid()
// Balance limits
test_user_balance_cannot_exceed_configured_limit()
test_organization_balance_limit_enforced()
test_bank_can_exceed_balance_limits_for_currency_creation()
test_negative_balance_allowed_within_limits()
```
#### 4.2 Transaction Authorization
**Priority: CRITICAL**
**File:** `tests/Feature/TransactionAuthorizationTest.php` (NEW)
**Test Cases:**
```php
// Transaction creation permissions
test_user_can_create_worked_time_transaction()
test_user_can_create_gift_transaction()
test_organization_can_create_donation_transaction()
test_bank_can_create_currency_creation_transaction()
test_bank_can_create_currency_removal_transaction()
test_user_cannot_create_currency_creation_transaction()
test_admin_cannot_create_transactions_without_account()
// Transaction type restrictions
test_transaction_type_configurable_per_profile()
test_unauthorized_transaction_type_rejected()
// Account ownership
test_can_only_send_from_owned_account()
test_cannot_send_from_other_user_account()
test_cannot_forge_transaction_sender()
// Transaction limits
test_transaction_amount_within_account_limit()
test_transaction_amount_does_not_exceed_sender_balance_plus_overdraft()
```
---
### 5. CSRF & Request Security Tests
#### 5.1 CSRF Protection
**Priority: HIGH**
**File:** `tests/Feature/CsrfProtectionTest.php` (NEW)
**Test Cases:**
```php
// POST requests
test_post_request_without_csrf_token_rejected()
test_post_request_with_invalid_csrf_token_rejected()
test_post_request_with_valid_csrf_token_accepted()
// PUT/PATCH requests
test_update_request_requires_csrf_token()
test_profile_update_requires_csrf_token()
// DELETE requests
test_delete_request_requires_csrf_token()
test_profile_deletion_requires_csrf_token()
// Livewire components
test_livewire_actions_protected_by_csrf()
test_livewire_form_submissions_protected()
// API routes (if using Sanctum CSRF)
test_api_routes_require_csrf_for_cookie_auth()
test_api_routes_accept_token_auth_without_csrf()
// Exclusions
test_no_routes_excluded_from_csrf_protection()
test_webhook_routes_use_signature_verification()
```
#### 5.2 Rate Limiting
**Priority: MEDIUM**
**File:** `tests/Feature/RateLimitingTest.php` (NEW)
**Test Cases:**
```php
// Authentication rate limiting
test_login_attempts_rate_limited()
test_password_reset_requests_rate_limited()
test_registration_rate_limited()
test_rate_limit_lockout_duration_enforced()
// API rate limiting
test_api_requests_rate_limited_per_user()
test_api_rate_limit_configurable()
test_rate_limit_headers_returned()
// Profile actions rate limiting
test_profile_creation_rate_limited()
test_message_sending_rate_limited()
test_transaction_creation_rate_limited()
// Search rate limiting
test_search_requests_rate_limited()
test_elasticsearch_queries_rate_limited()
```
---
### 6. File Upload Security Tests
#### 6.1 File Upload Validation
**Priority: HIGH**
**File:** `tests/Feature/FileUploadSecurityTest.php` (NEW)
**Test Cases:**
```php
// File type validation
test_only_allowed_image_types_accepted()
test_executable_files_rejected()
test_php_files_rejected()
test_svg_files_sanitized_or_rejected()
test_double_extension_files_rejected()
// File size validation
test_file_size_limit_enforced()
test_oversized_files_rejected()
test_profile_photo_size_limited()
// File content validation
test_mime_type_validated_by_content_not_extension()
test_image_dimensions_validated()
test_malicious_image_metadata_stripped()
// Filename sanitization
test_uploaded_filename_sanitized()
test_path_traversal_in_filename_prevented()
test_special_characters_in_filename_handled()
// Storage security
test_uploaded_files_stored_outside_webroot()
test_uploaded_files_not_directly_accessible()
test_file_serving_validates_authorization()
```
---
### 7. Real-Time Features Security Tests
#### 7.1 Presence System Security
**Priority: MEDIUM**
**File:** `tests/Feature/PresenceSystemSecurityTest.php` (NEW)
**Status:** ✅ Audited 2026-01-09 - See SECURITY_AUDIT_PRESENCE_2026-01-09.md
**Test Cases:**
```php
// Public visibility (by design)
test_presence_status_is_publicly_visible()
test_last_seen_timestamp_is_public()
test_any_user_can_query_any_profile_presence()
// Service security
test_presence_service_is_read_only()
test_no_write_operations_in_presence_service()
test_presence_uses_activity_log_immutable_records()
// Multi-guard isolation
test_cross_guard_presence_isolation()
test_presence_cache_keys_include_guard()
test_web_user_cannot_see_bank_guard_presence()
test_organization_presence_separate_from_user_presence()
// ProfileStatusBadge security
test_status_badge_shows_correct_guard_presence()
test_status_badge_handles_nonexistent_profile_gracefully()
test_status_badge_polls_every_30_seconds()
test_status_badge_does_not_expose_sensitive_data()
// Privacy controls (future)
test_optional_hide_online_status_setting()
test_hidden_status_returns_offline()
```
**Current Status:**
- ✅ Manual audit completed
- ⚠️ Public presence is by design (documented)
- ✅ Read-only operations prevent exploits
- ✅ Multi-guard isolation working correctly
- 📝 Automated tests to be added
#### 7.2 WebSocket Security
**Priority: HIGH**
**File:** `tests/Feature/WebSocketSecurityTest.php` (NEW)
**Test Cases:**
```php
// Authentication
test_websocket_connection_requires_authentication()
test_websocket_handshake_validates_token()
test_invalid_websocket_token_rejected()
// Channel authorization
test_private_channel_requires_authorization()
test_presence_channel_requires_authorization()
test_user_can_only_join_own_private_channel()
test_user_cannot_join_other_user_private_channel()
// Message authorization
test_can_only_send_messages_to_authorized_channels()
test_cannot_impersonate_other_users_in_messages()
// Presence tracking
test_presence_updates_authenticated()
test_presence_reflects_active_guard()
test_cannot_forge_presence_data()
```
#### 7.2 Broadcasting Security
**Priority: MEDIUM**
**File:** `tests/Feature/BroadcastingSecurityTest.php` (NEW)
**Test Cases:**
```php
// Event broadcasting
test_profile_switch_event_broadcasts_to_user_channel()
test_transaction_event_broadcasts_to_participant_channels()
test_message_event_broadcasts_to_authorized_users()
// Data sanitization
test_broadcast_data_does_not_include_sensitive_info()
test_password_not_included_in_broadcast()
test_email_not_included_in_broadcast()
test_only_necessary_profile_data_broadcast()
```
---
### 8. Business Logic Security Tests
#### 8.1 Profile Management Logic
**Priority: HIGH**
**File:** `tests/Feature/ProfileManagementSecurityTest.php` (NEW)
**Test Cases:**
```php
// Profile creation
test_profile_name_validation_prevents_reserved_words()
test_profile_name_validation_prevents_url_conflicts()
test_profile_name_uniqueness_enforced()
test_email_uniqueness_enforced()
// Profile deletion
test_profile_deletion_requires_authentication()
test_profile_deletion_validates_ownership()
test_profile_deletion_has_grace_period()
test_profile_deletion_clears_sensitive_data()
test_soft_deleted_profiles_not_searchable()
// Profile visibility
test_inactive_profiles_hidden_from_search()
test_private_profiles_not_publicly_visible()
test_profile_visibility_respects_config()
```
#### 8.2 Inactivity & Grace Period Logic
**Priority: MEDIUM**
**File:** `tests/Feature/InactivitySecurityTest.php` (NEW)
**Test Cases:**
```php
// Inactivity detection
test_profiles_marked_inactive_after_configured_period()
test_inactive_profiles_hidden_from_search()
test_inactive_profiles_hidden_from_messenger()
test_inactive_profiles_show_visual_indicator()
// Grace period
test_deleted_profiles_enter_grace_period()
test_grace_period_duration_configurable()
test_profiles_can_be_restored_during_grace_period()
test_profiles_permanently_deleted_after_grace_period()
test_restored_profiles_retain_original_data()
```
---
### 9. Information Disclosure Tests
#### 9.1 Error Message Security
**Priority: MEDIUM**
**File:** `tests/Feature/InformationDisclosureTest.php` (NEW)
**Test Cases:**
```php
// Error pages
test_production_errors_do_not_reveal_stack_traces()
test_production_errors_do_not_reveal_file_paths()
test_production_errors_do_not_reveal_database_info()
test_validation_errors_do_not_reveal_system_info()
// Authentication errors
test_login_error_does_not_reveal_if_email_exists()
test_password_reset_does_not_reveal_if_email_exists()
test_failed_auth_returns_generic_message()
// Authorization errors
test_unauthorized_access_returns_403_not_detailed_reason()
test_missing_permission_error_does_not_reveal_permission_names()
// API errors
test_api_errors_do_not_include_sensitive_data()
test_api_validation_errors_sanitized()
```
#### 9.2 Data Exposure
**Priority: MEDIUM**
**File:** `tests/Feature/DataExposurePreventionTest.php` (NEW)
**Test Cases:**
```php
// API responses
test_user_model_hides_password_in_json()
test_user_model_hides_remember_token_in_json()
test_api_responses_do_not_include_hidden_attributes()
// Profile data
test_private_email_not_exposed_in_public_profile()
test_profile_balance_visibility_respects_config()
test_soft_deleted_data_not_exposed()
// Search results
test_search_results_do_not_include_private_data()
test_inactive_profiles_not_in_search_results()
```
---
### 10. Email Security Tests
#### 10.1 Email Verification Security
**Priority: HIGH**
**File:** `tests/Feature/EmailVerificationSecurityTest.php` (NEW)
**Test Cases:**
```php
// Verification process
test_email_verification_requires_valid_hash()
test_email_verification_hash_uses_timing_safe_comparison()
test_expired_verification_links_rejected()
test_verification_link_single_use()
// Multi-profile verification
test_user_can_only_verify_own_email()
test_cannot_verify_email_for_unowned_profile()
test_profile_association_validated_before_verification()
```
#### 10.2 Email Content Security
**Priority: MEDIUM**
**File:** `tests/Feature/EmailContentSecurityTest.php` (NEW)
**Test Cases:**
```php
// Email rendering
test_email_content_sanitizes_user_input()
test_email_subject_sanitizes_user_input()
test_email_does_not_leak_sensitive_data()
// Transactional emails
test_transaction_notification_emails_sanitized()
test_password_reset_email_contains_secure_token()
test_email_unsubscribe_links_contain_secure_token()
```
---
## Implementation Roadmap
### Phase 1: Critical Security Tests (Week 1-2)
**Priority: Must implement before production deployment**
1. **Multi-Guard Authentication** (2 days)
- `MultiGuardAuthenticationTest.php`
- `ProfileSwitchingSecurityTest.php`
2. **Transaction Security** (3 days)
- `TransactionIntegrityTest.php`
- `TransactionAuthorizationTest.php`
3. **Authorization** (2 days)
- `PermissionAuthorizationTest.php`
- `IdorPreventionTest.php`
4. **SQL Injection Prevention** (1 day)
- `SqlInjectionPreventionTest.php`
### Phase 2: High Priority Tests (Week 3-4)
5. **Direct Login Routes** (1 day)
- `DirectLoginRoutesSecurityTest.php`
6. **Session Security** (2 days)
- `SessionSecurityTest.php`
7. **Resource Authorization** (2 days)
- `ResourceAuthorizationTest.php`
8. **XSS Protection Expansion** (1 day)
- `XssProtectionComprehensiveTest.php`
9. **CSRF Protection** (1 day)
- `CsrfProtectionTest.php`
10. **File Upload Security** (2 days)
- `FileUploadSecurityTest.php`
### Phase 3: Medium Priority Tests (Week 5-6)
11. **Rate Limiting** (1 day)
- `RateLimitingTest.php`
12. **WebSocket Security** (2 days)
- `WebSocketSecurityTest.php`
- `BroadcastingSecurityTest.php`
13. **Profile Management Logic** (2 days)
- `ProfileManagementSecurityTest.php`
- `InactivitySecurityTest.php`
14. **Information Disclosure** (1 day)
- `InformationDisclosureTest.php`
- `DataExposurePreventionTest.php`
15. **Email Security** (1 day)
- `EmailVerificationSecurityTest.php`
- `EmailContentSecurityTest.php`
16. **Command Injection** (1 day)
- `CommandInjectionPreventionTest.php`
### Phase 4: Ongoing Maintenance
- Run security test suite on every pull request
- Add new tests for new features before implementation
- Quarterly security audit and test review
- Annual penetration testing
---
## Test Maintenance
### Continuous Integration
```yaml
# .github/workflows/security-tests.yml
name: Security Tests
on: [pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run Security Tests
run: |
php artisan test --testsuite=Security
```
### Test Organization
```
tests/
├── Feature/
│ ├── Security/
│ │ ├── Authentication/
│ │ │ ├── MultiGuardAuthenticationTest.php
│ │ │ ├── ProfileSwitchingSecurityTest.php
│ │ │ ├── DirectLoginRoutesSecurityTest.php
│ │ │ └── SessionSecurityTest.php
│ │ ├── Authorization/
│ │ │ ├── PermissionAuthorizationTest.php
│ │ │ ├── ResourceAuthorizationTest.php
│ │ │ └── IdorPreventionTest.php
│ │ ├── InputValidation/
│ │ │ ├── XssProtectionComprehensiveTest.php
│ │ │ ├── SqlInjectionPreventionTest.php
│ │ │ └── CommandInjectionPreventionTest.php
│ │ ├── Financial/
│ │ │ ├── TransactionIntegrityTest.php
│ │ │ └── TransactionAuthorizationTest.php
│ │ ├── RequestSecurity/
│ │ │ ├── CsrfProtectionTest.php
│ │ │ └── RateLimitingTest.php
│ │ ├── FileUpload/
│ │ │ └── FileUploadSecurityTest.php
│ │ ├── RealTime/
│ │ │ ├── WebSocketSecurityTest.php
│ │ │ └── BroadcastingSecurityTest.php
│ │ ├── BusinessLogic/
│ │ │ ├── ProfileManagementSecurityTest.php
│ │ │ └── InactivitySecurityTest.php
│ │ ├── InformationDisclosure/
│ │ │ ├── InformationDisclosureTest.php
│ │ │ └── DataExposurePreventionTest.php
│ │ └── Email/
│ │ ├── EmailVerificationSecurityTest.php
│ │ └── EmailContentSecurityTest.php
│ └── ...existing tests...
```
### Running Security Tests
```bash
# Run all security tests
php artisan test tests/Feature/Security
# Run specific category
php artisan test tests/Feature/Security/Authentication
# Run with coverage
php artisan test tests/Feature/Security --coverage
# Run critical tests only
php artisan test --group=critical
```
### Test Tagging
```php
/**
* @test
* @group security
* @group critical
* @group authentication
*/
public function test_user_can_only_switch_to_owned_profiles()
{
// Test implementation
}
```
### Security Test Checklist Template
For each new feature, ensure:
- [ ] Authentication tests added
- [ ] Authorization tests added
- [ ] Input validation tests added
- [ ] XSS protection tests added
- [ ] CSRF protection verified
- [ ] SQL injection tests added (if applicable)
- [ ] IDOR tests added (if using IDs)
- [ ] Rate limiting tested (if applicable)
- [ ] File upload tests added (if applicable)
- [ ] Information disclosure tests added
- [ ] All tests pass in CI/CD
---
## Security Testing Tools
### Recommended Additional Tools
1. **Static Analysis**
- PHPStan (Level 8+)
- Psalm
- Laravel Shift Security Checker
2. **Dependency Scanning**
- `composer audit`
- Snyk
- Dependabot
3. **Dynamic Testing**
- OWASP ZAP
- Burp Suite Community Edition
- Nikto
4. **Code Quality**
- PHP_CodeSniffer with security rules
- PHPMD (PHP Mess Detector)
- SonarQube
### Security Monitoring
- Laravel Telescope for development
- Sentry for production error tracking
- Log analysis for suspicious patterns
- Activity log monitoring
---
## References
- **Application Security Docs:**
- `references/SECURITY_OVERVIEW.md` - Comprehensive security architecture
- `SECURITY_AUDIT_XSS.md` - XSS vulnerability audit and remediation
- `config/security.php` - Security configuration
- **Existing Tests:**
- `tests/Feature/SearchXssProtectionTest.php` - Search XSS protection (8 tests)
- `tests/Feature/PostContentXssProtectionTest.php` - Post content XSS (16 tests)
- `tests/Feature/AuthenticationTest.php` - Basic authentication tests
- **Standards:**
- OWASP Top 10 Web Application Security Risks
- Laravel Security Best Practices
- PHP Security Cheat Sheet
---
## Conclusion
This comprehensive security testing plan addresses all critical security areas of the Timebank.cc platform. The phased implementation approach ensures critical tests are written first, while allowing for gradual expansion of coverage.
**Key Success Metrics:**
- 100% of critical security tests passing
- No high-risk vulnerabilities in production
- All new features include security tests
- Security test suite runs on every PR
- Annual penetration test findings addressed
**Next Steps:**
1. Review and approve this testing plan
2. Begin Phase 1 implementation
3. Set up CI/CD for automated security testing
4. Schedule quarterly security reviews