# CODPartner Plugin - Security Documentation

## Security Improvements Made

This document outlines the security improvements implemented in the CODPartner plugin to address WordPress.org plugin review requirements.

### 1. Nonce Verification

**Problem Fixed**: Direct access to `$_GET` parameters without proper nonce verification.

**Solutions Implemented**:
- Added comprehensive nonce verification for all admin actions
- Created `CODPartner_Security` utility class for centralized security functions
- Implemented proper nonce checking in `handle_admin_actions()` method
- Removed unsafe direct `$_GET` access from templates

**Files Modified**:
- `templates/settings-page.php` - Removed direct `$_GET` access
- `includes/class-codpartner-admin.php` - Added secure action handling
- `includes/class-codpartner-security.php` - New security utility class

### 2. User Permission Checks

**Problem Fixed**: Missing or insufficient user capability checks.

**Solutions Implemented**:
- Added `current_user_can('manage_options')` checks before processing any admin actions
- Implemented capability verification in all admin methods
- Added permission checks in templates

**Security Functions Added**:
- `CODPartner_Security::verify_admin_capability()`
- `CODPartner_Security::verify_admin_action()`

### 3. Input Sanitization and Validation

**Problem Fixed**: Potential security vulnerabilities from unsanitized input.

**Solutions Implemented**:
- Created whitelist-based parameter sanitization
- Added comprehensive input validation for order data
- Implemented secure parameter handling with `get_sanitized_get_param()`

**Security Functions Added**:
- `CODPartner_Security::get_sanitized_get_param()`
- `CODPartner_Security::validate_order_data()`
- `CODPartner_Security::sanitize_api_response()`

### 4. Secure URL Generation

**Problem Fixed**: Manual URL construction without proper nonce integration.

**Solutions Implemented**:
- Created secure URL generation utility
- Implemented proper nonce integration in admin URLs
- Used WordPress-standard URL generation methods

**Security Functions Added**:
- `CODPartner_Security::create_admin_action_url()`

### 5. Security Event Logging

**Enhancement**: Added security event logging for monitoring and debugging.

**Features Implemented**:
- Security event logging with context
- OAuth validation logging
- Data validation failure logging

**Security Functions Added**:
- `CODPartner_Security::log_security_event()`
- `CODPartner_Security::validate_oauth_state()`

## Security Best Practices Followed

1. **Defense in Depth**: Multiple layers of security checks
2. **Principle of Least Privilege**: Only necessary permissions granted
3. **Input Validation**: All user input validated and sanitized
4. **Output Escaping**: All output properly escaped
5. **Nonce Verification**: All state-changing actions protected
6. **Capability Checks**: User permissions verified for all admin actions

## Code Examples

### Secure Action Handling
```php
public function handle_admin_actions() {
    // Check page context
    if ( ! $this->is_codpartner_settings_page() ) {
        return;
    }

    // Verify user permissions
    if ( ! CODPartner_Security::verify_admin_capability() ) {
        return;
    }

    // Get sanitized parameters
    $action = CODPartner_Security::get_sanitized_get_param( 'action' );
    $nonce = CODPartner_Security::get_sanitized_get_param( 'nonce' );

    // Verify nonce and handle action
    if ( 'disconnect' === $action ) {
        $this->handle_disconnect_action( $nonce );
    }
}
```

### Secure URL Generation
```php
$disconnect_url = CODPartner_Security::create_admin_action_url( 
    'disconnect', 
    'codpartner_disconnect' 
);
```

### Data Validation
```php
$validated_order_data = CODPartner_Security::validate_order_data( $order_data );
if ( false === $validated_order_data ) {
    // Handle validation failure
    return false;
}
```

## Testing Security

To test the security improvements:

1. **Nonce Verification**: Try accessing admin actions without proper nonces
2. **Permission Checks**: Test with users having insufficient capabilities
3. **Input Validation**: Submit malformed data to verify sanitization
4. **URL Tampering**: Attempt to modify action URLs manually

## Compliance

These improvements ensure compliance with:
- WordPress Plugin Review Guidelines
- WordPress Security Best Practices
- OWASP Web Application Security Standards
- WordPress Coding Standards

## Maintenance

Regular security maintenance should include:
- Reviewing and updating nonce implementations
- Auditing user permission checks
- Validating input sanitization methods
- Monitoring security event logs

# Security - Environment Variables Protection

## ⚠️ IMPORTANT: Use Environment Variables for Production

This plugin supports environment variables for secure credential management. **Environment variables are the most secure method** for storing sensitive credentials.

## Security Levels (Best to Worst)

### 1. **Environment Variables** (Most Secure) ✅
- Credentials stored in server environment
- Not visible in code or database
- Different credentials per environment
- Industry standard practice

### 2. **WordPress Constants** (Medium Security) ⚠️
- Stored in wp-config.php
- Visible to server administrators
- Good for development

### 3. **Hardcoded Values** (Least Secure) ❌
- Visible in plugin code
- Same for all installations
- Not recommended for production

## Setup Instructions

### Method 1: Environment Variables (Recommended)

#### For Apache (.htaccess)
```apache
SetEnv CODPARTNER_CLIENT_ID "your_client_id_here"
SetEnv CODPARTNER_CLIENT_SECRET "your_client_secret_here"
```

#### For Nginx (nginx.conf)
```nginx
fastcgi_param CODPARTNER_CLIENT_ID "your_client_id_here";
fastcgi_param CODPARTNER_CLIENT_SECRET "your_client_secret_here";
```

#### For PHP-FPM (php-fpm.conf)
```ini
env[CODPARTNER_CLIENT_ID] = your_client_id_here
env[CODPARTNER_CLIENT_SECRET] = your_client_secret_here
```

#### For Docker
```dockerfile
ENV CODPARTNER_CLIENT_ID=your_client_id_here
ENV CODPARTNER_CLIENT_SECRET=your_client_secret_here
```

#### For .env file (with dotenv)
```env
CODPARTNER_CLIENT_ID=your_client_id_here
CODPARTNER_CLIENT_SECRET=your_client_secret_here
```

### Method 2: WordPress Constants (wp-config.php)

```php
// CODPartner API Configuration
define( 'CODPARTNER_CLIENT_ID', 'your_client_id_here' );
define( 'CODPARTNER_CLIENT_SECRET', 'your_client_secret_here' );
```

### Method 3: WordPress Filters

```php
add_filter( 'codpartner_client_id', function() {
    return 'your_client_id_here';
});

add_filter( 'codpartner_client_secret', function() {
    return 'your_client_secret_here';
});
```

## How It Works

The plugin checks for credentials in this order:

1. **Environment Variables** (`$_ENV['CODPARTNER_CLIENT_ID']`)
2. **getenv() Function** (`getenv('CODPARTNER_CLIENT_ID')`)
3. **WordPress Constants** (`defined('CODPARTNER_CLIENT_ID')`)
4. **Fallback Values** (hardcoded, least secure)

## Security Benefits

### 🔒 **Environment Variables**
- ✅ Not visible in code
- ✅ Not stored in database
- ✅ Different per server/environment
- ✅ Can be encrypted at OS level
- ✅ Industry standard practice

### 🛡️ **Server Isolation**
- Each server can have different credentials
- Credentials not shared between environments
- Easy to rotate credentials per environment

### 🔄 **Easy Rotation**
- Change credentials without code changes
- Different credentials for dev/staging/production
- No need to update plugin files

## Production Deployment

### 1. Set Environment Variables
```bash
# On your production server
export CODPARTNER_CLIENT_ID="prod_client_id"
export CODPARTNER_CLIENT_SECRET="prod_client_secret"
```

### 2. Verify Configuration
The plugin will automatically use environment variables if available.

### 3. Test Connection
Check that the plugin connects successfully with environment credentials.

## Development vs Production

### Development
```env
CODPARTNER_CLIENT_ID=dev_client_id
CODPARTNER_CLIENT_SECRET=dev_client_secret
```

### Production
```env
CODPARTNER_CLIENT_ID=prod_client_id
CODPARTNER_CLIENT_SECRET=prod_client_secret
```

## Troubleshooting

### Check Environment Variables
```php
// Add this to wp-config.php temporarily for debugging
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
    error_log( 'CODPARTNER_CLIENT_ID: ' . ( $_ENV['CODPARTNER_CLIENT_ID'] ?? 'NOT SET' ) );
    error_log( 'CODPARTNER_CLIENT_SECRET: ' . ( $_ENV['CODPARTNER_CLIENT_SECRET'] ?? 'NOT SET' ) );
}
```

### Verify Plugin Detection
The plugin will automatically detect and use environment variables when available.

## Best Practices

1. **Always use environment variables in production**
2. **Never commit credentials to version control**
3. **Use different credentials per environment**
4. **Rotate credentials regularly**
5. **Limit access to environment variables**

## Support

For help setting up environment variables or security questions, contact the CODPartner team. 