-
-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
Welcome to the Laravel Safeguard examples collection! This comprehensive guide provides practical examples and code samples for using Laravel Safeguard in various scenarios.
The simplest way to run a security check:
php artisan safeguard:check
Example Output:
π Laravel Safeguard Security Check
βββββββββββββββββββββββββββββββββββββββ
Environment: local
β
APP_KEY is set
β
Storage directories are writable
β
CSRF protection enabled
β οΈ APP_DEBUG is enabled (acceptable in local environment)
βββββββββββββββββββββββββββββββββββββββ
π― All checks passed! (4 checks)
Run checks for specific environments:
# Production environment checks
php artisan safeguard:check --env=production
# Staging environment checks
php artisan safeguard:check --env=staging
Get machine-readable output:
php artisan safeguard:check --format=json
Example JSON Output:
{
"status": "passed",
"environment": "local",
"checks": [
{
"rule": "app-key-is-set",
"status": "passed",
"message": "APP_KEY is properly set"
},
{
"rule": "app-debug-false-in-production",
"status": "warning",
"message": "APP_DEBUG is enabled (acceptable in local environment)"
}
],
"summary": {
"total": 4,
"passed": 3,
"failed": 0,
"warnings": 1
}
}
For production environments with strict security requirements:
<?php
// config/safeguard.php
return [
'rules' => [
// π Critical production rules
'app-debug-false-in-production' => true,
'app-key-is-set' => true,
'secure-cookies-in-production' => true,
'https-enforced-in-production' => true,
'env-file-permissions' => true,
'database-connection-encrypted' => true,
// π‘οΈ Security hardening
'password-policy-compliance' => true,
'session-security-settings' => true,
'csrf-enabled' => true,
// π Code security
'no-secrets-in-code' => true,
'sensitive-files-hidden' => true,
],
'environments' => [
'production' => [
'app-debug-false-in-production',
'secure-cookies-in-production',
'https-enforced-in-production',
'database-connection-encrypted',
'password-policy-compliance',
'no-secrets-in-code',
],
],
'required_env_vars' => [
'APP_KEY', 'APP_ENV', 'APP_DEBUG', 'APP_URL',
'DB_CONNECTION', 'DB_HOST', 'DB_DATABASE', 'DB_USERNAME', 'DB_PASSWORD',
'MAIL_MAILER', 'MAIL_HOST',
'SESSION_DRIVER', 'SESSION_LIFETIME',
],
];
For local development with relaxed rules:
<?php
// config/safeguard.php (development)
return [
'rules' => [
// π Essential rules only
'app-key-is-set' => true,
'storage-writable' => true,
'csrf-enabled' => true,
// π« Disable strict production rules
'app-debug-false-in-production' => false,
'https-enforced-in-production' => false,
'secure-cookies-in-production' => false,
// β οΈ Optional security checks
'no-secrets-in-code' => true, // Still good practice
],
'environments' => [
'local' => [
'app-key-is-set',
'storage-writable',
'csrf-enabled',
],
],
];
Optimized for continuous integration:
<?php
// config/safeguard.php (CI/CD)
return [
'rules' => [
'env-has-all-required-keys' => true,
'no-secrets-in-code' => true,
'app-key-is-set' => true,
'csrf-enabled' => true,
],
'scan_paths' => [
'app/',
'config/',
'routes/',
// Exclude tests for faster scanning
],
'performance' => [
'max_scan_files' => 5000,
'timeout_seconds' => 120,
'parallel_processing' => true,
],
];
<?php
// app/SafeguardRules/DatabaseSecurityRule.php
namespace App\SafeguardRules;
use Grazulex\LaravelSafeguard\Contracts\SecurityRule;
use Grazulex\LaravelSafeguard\Results\RuleResult;
class DatabaseSecurityRule implements SecurityRule
{
public function check(): RuleResult
{
$issues = [];
// Check if database connection is encrypted
$dbConfig = config('database.connections.' . config('database.default'));
if (!isset($dbConfig['options'][PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT])) {
$issues[] = 'Database connection is not configured with SSL verification';
}
// Check for default database credentials
if ($dbConfig['username'] === 'root' && empty($dbConfig['password'])) {
$issues[] = 'Using default database credentials (root with no password)';
}
return empty($issues)
? RuleResult::passed('Database security configuration is valid')
: RuleResult::failed('Database security issues found', $issues);
}
public function name(): string
{
return 'database-security-check';
}
public function description(): string
{
return 'Validates database connection security settings';
}
}
<?php
// app/SafeguardRules/ApiSecurityRule.php
namespace App\SafeguardRules;
use Grazulex\LaravelSafeguard\Contracts\SecurityRule;
use Grazulex\LaravelSafeguard\Results\RuleResult;
class ApiSecurityRule implements SecurityRule
{
public function check(): RuleResult
{
$issues = [];
// Check API rate limiting
if (!config('api.rate_limiting.enabled', false)) {
$issues[] = 'API rate limiting is not enabled';
}
// Check API authentication
$authMiddleware = config('api.middleware.auth', []);
if (empty($authMiddleware)) {
$issues[] = 'No authentication middleware configured for API routes';
}
// Check API versioning
if (!config('api.versioning.enabled', false)) {
$issues[] = 'API versioning is not enabled';
}
return empty($issues)
? RuleResult::passed('API security configuration is valid')
: RuleResult::failed('API security issues found', $issues);
}
public function name(): string
{
return 'api-security-check';
}
public function description(): string
{
return 'Validates API security configuration';
}
}
# .github/workflows/security.yml
name: Security Checks
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.3
extensions: mbstring, xml, ctype, iconv, intl, pdo_sqlite
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.example', '.env');"
- name: Install Dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: Generate key
run: php artisan key:generate
- name: Run Security Checks
run: php artisan safeguard:check --env=production --fail-on-error --format=json
- name: Upload Security Report
if: always()
uses: actions/upload-artifact@v3
with:
name: security-report
path: storage/logs/safeguard-report.json
# .gitlab-ci.yml
stages:
- test
- security
security_check:
stage: security
image: php:8.3-cli
before_script:
- apt-get update -yqq
- apt-get install -yqq git unzip
- curl -sS https://getcomposer.org/installer | php
- mv composer.phar /usr/local/bin/composer
- composer install --no-dev --optimize-autoloader
- cp .env.example .env
- php artisan key:generate
script:
- php artisan safeguard:check --env=production --fail-on-error
artifacts:
when: always
reports:
junit: storage/logs/safeguard-junit.xml
paths:
- storage/logs/safeguard-report.json
expire_in: 1 week
only:
- master
- develop
// Jenkinsfile
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Install Dependencies') {
steps {
sh 'composer install --no-dev --optimize-autoloader'
sh 'cp .env.example .env'
sh 'php artisan key:generate'
}
}
stage('Security Checks') {
steps {
sh 'php artisan safeguard:check --env=production --fail-on-error --format=json > security-report.json'
}
post {
always {
archiveArtifacts artifacts: 'security-report.json', fingerprint: true
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: '.',
reportFiles: 'security-report.html',
reportName: 'Security Report'
])
}
}
}
}
}
#!/bin/bash
# scripts/pre-deploy-security-check.sh
echo "π Running pre-deployment security checks..."
# Set environment to production for checks
export APP_ENV=production
# Run security checks
php artisan safeguard:check --env=production --fail-on-error
# Check exit code
if [ $? -eq 0 ]; then
echo "β
All security checks passed! Safe to deploy."
exit 0
else
echo "β Security issues found! Please fix before deploying."
echo ""
echo "To see detailed output:"
echo " php artisan safeguard:check --env=production --verbose"
echo ""
echo "To generate a report:"
echo " php artisan safeguard:check --env=production --format=json > security-report.json"
exit 1
fi
<?php
// scripts/generate-security-report.php
use Grazulex\LaravelSafeguard\SafeguardManager;
/**
* Generate a comprehensive security report
*/
$safeguard = new SafeguardManager();
$environments = ['local', 'staging', 'production'];
$report = [
'generated_at' => now()->toISOString(),
'environments' => []
];
foreach ($environments as $env) {
echo "Checking {$env} environment...\n";
$results = $safeguard->check($env);
$report['environments'][$env] = [
'status' => $results->passed() ? 'passed' : 'failed',
'checks' => $results->getResults(),
'summary' => [
'total' => $results->total(),
'passed' => $results->passed(),
'failed' => $results->failed(),
'warnings' => $results->warnings(),
]
];
}
// Save report
$reportPath = storage_path('reports/security-report-' . date('Y-m-d-H-i-s') . '.json');
file_put_contents($reportPath, json_encode($report, JSON_PRETTY_PRINT));
echo "Report saved to: {$reportPath}\n";
<?php
// app/Http/Middleware/SecurityCheckMiddleware.php
namespace App\Http\Middleware;
use Closure;
use Grazulex\LaravelSafeguard\SafeguardManager;
use Illuminate\Http\Request;
class SecurityCheckMiddleware
{
protected $safeguard;
public function __construct(SafeguardManager $safeguard)
{
$this->safeguard = $safeguard;
}
public function handle(Request $request, Closure $next)
{
// Run critical security checks on admin routes
if ($request->is('admin/*')) {
$criticalRules = [
'app-debug-false-in-production',
'csrf-enabled',
'secure-cookies-in-production',
];
$results = $this->safeguard->checkRules($criticalRules);
if ($results->hasCriticalIssues()) {
abort(503, 'Security configuration issues detected');
}
}
return $next($request);
}
}
<?php
// app/Console/Commands/SecurityReport.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Grazulex\LaravelSafeguard\SafeguardManager;
class SecurityReport extends Command
{
protected $signature = 'app:security-report {--email} {--format=cli}';
protected $description = 'Generate and optionally email a security report';
public function handle(SafeguardManager $safeguard)
{
$this->info('π Generating security report...');
$results = $safeguard->check();
if ($this->option('format') === 'json') {
$this->line(json_encode($results->toArray(), JSON_PRETTY_PRINT));
} else {
$this->displayResults($results);
}
if ($this->option('email')) {
$this->emailReport($results);
}
return $results->passed() ? 0 : 1;
}
private function displayResults($results)
{
foreach ($results->getResults() as $result) {
$icon = $result->passed() ? 'β
' : ($result->failed() ? 'β' : 'β οΈ');
$this->line("{$icon} {$result->message()}");
}
}
private function emailReport($results)
{
// Implementation for emailing the report
$this->info('π§ Security report sent via email');
}
}
<?php
// Configuration for e-commerce application
return [
'rules' => [
// Standard security
'app-debug-false-in-production' => true,
'csrf-enabled' => true,
'secure-cookies-in-production' => true,
// Payment security
'pci-compliance-check' => true,
'payment-gateway-ssl-verification' => true,
'sensitive-payment-data-encryption' => true,
// Customer data protection
'gdpr-compliance-check' => true,
'customer-data-encryption' => true,
'session-security-settings' => true,
],
];
<?php
// Configuration for API-only application
return [
'rules' => [
// API security
'api-rate-limiting-enabled' => true,
'api-authentication-required' => true,
'api-cors-properly-configured' => true,
'api-versioning-enabled' => true,
// Standard security
'app-debug-false-in-production' => true,
'database-connection-encrypted' => true,
'no-secrets-in-code' => true,
],
'scan_paths' => [
'app/Http/Controllers/Api/',
'app/Http/Middleware/',
'routes/api.php',
'config/cors.php',
],
];
# Run before every deployment
php artisan safeguard:check --env=production --fail-on-error
// In App\Console\Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('safeguard:check --env=production')
->daily()
->emailOutputTo('[email protected]');
}
# GitHub Actions for PR validation
on:
pull_request:
branches: [ main ]
jobs:
security:
runs-on: ubuntu-latest
steps:
# ... setup steps
- name: Security Check
run: php artisan safeguard:check --fail-on-error
- Check the π Rules Reference for all available security rules
- See ποΈ Custom Rules for creating your own security rules
- Visit π CI/CD Integration for more pipeline examples
- Read the βοΈ Configuration Guide for advanced setup options
Next Step: π Explore all available security rules
π Home | β‘ Quick Start | βοΈ Configuration | π Rules Reference
Laravel Safeguard - Configurable Security Checks for Laravel Applications
π Home | π¦ Installation | β‘ Quick Start | π‘ Examples | π Full Docs
Made with β€οΈ for the Laravel community
Β© 2025 - Laravel Safeguard by Grazulex