Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Firewall Laravel Package

moox/firewall

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require moox/firewall
    php artisan vendor:publish --tag="firewall-config"
    

    Configure .env with:

    MOOX_FIREWALL_ENABLED=true
    MOOX_FIREWALL_WHITELIST=192.168.1.1,10.0.0.5
    
  2. First Use Case

    • Whitelist Access: Add your local/dev IP to MOOX_FIREWALL_WHITELIST (e.g., 127.0.0.1,192.168.x.x).
    • Test: Access your app—unwhitelisted IPs hit a block page; whitelisted IPs proceed normally.
    • Backdoor: Enable via MOOX_FIREWALL_BACKDOOR=true and set a token in config/firewall.php under backdoor.token.

Where to Look First

  • Config File: config/firewall.php (adjust whitelist, backdoor, and UI settings).
  • Middleware: Automatically registered if enabled=true (check app/Http/Kernel.php for Moox\Firewall\Http\Middleware\Firewall).
  • Backdoor Route: /firewall/backdoor (protected by token).

Implementation Patterns

Core Workflows

  1. IP Whitelisting

    • Dynamic Updates: Use a config cache or environment variables for runtime changes (e.g., config('firewall.whitelist')).
    • Subnet Support: Leverage moox/firewall's built-in CIDR notation (e.g., 192.168.1.0/24).
    • Integration with Auth:
      // In a controller/middleware
      if (!auth()->check() && !Firewall::isWhitelisted()) {
          abort(403);
      }
      
  2. Backdoor Usage

    • Token Management: Store the token securely (e.g., Laravel Vault or encrypted .env).
    • Temporary Access: Rotate tokens via config/firewall.php or a migration:
      // Example: Add a token column to a `firewall_tokens` table
      Schema::create('firewall_tokens', function (Blueprint $table) {
          $table->id();
          $table->string('token')->unique();
          $table->timestamps();
      });
      
    • Audit Logging: Extend the backdoor to log access attempts:
      // In a service provider
      Firewall::backdoor(function () {
          event(new FirewallBackdoorAccessed());
      });
      
  3. Filament Integration

    • Admin Panel Security: Whitelist Filament’s admin IP(s) in the config.
    • Custom Policies: Use Filament’s policy system to enforce firewall rules:
      // app/Policies/FilamentPolicy.php
      public function viewAny(User $user) {
          return Firewall::isWhitelisted() || $user->isAdmin();
      }
      

Advanced Patterns

  • Geoblocking: Combine with geoip2/geoip2 to block regions:
    use GeoIp2\Database\Reader;
    $reader = new Reader(file_get_contents('GeoLite2-City.mmdb'));
    $record = $reader->city(request()->ip());
    if ($record->country->isoCode === 'RU') {
        abort(403, 'Access denied from this region.');
    }
    
  • Rate Limiting: Pair with laravel-rate-limiting to throttle backdoor attempts:
    RateLimiter::for('firewall-backdoor')->limit(5)->perMinute();
    

Gotchas and Tips

Pitfalls

  1. Misconfigured Whitelists

    • Issue: Locking yourself out by removing all whitelisted IPs.
    • Fix: Always keep 127.0.0.1 in the whitelist for local testing. Use a secondary admin IP as a backup.
  2. Backdoor Token Exposure

    • Issue: Hardcoding tokens in config/firewall.php.
    • Fix: Use Laravel’s encrypted config or a secrets manager:
      // config/firewall.php
      'backdoor' => [
          'token' => env('FIREWALL_BACKDOOR_TOKEN'),
      ]
      
  3. Caching Headaches

    • Issue: Whitelist changes not reflecting due to cached config.
    • Fix: Clear config cache after updates:
      php artisan config:clear
      
  4. Proxy/Load Balancer IPs

    • Issue: Firewall blocking traffic from proxies (e.g., Cloudflare, Nginx).
    • Fix: Whitelist proxy IPs and use X-Forwarded-For header:
      // In FirewallServiceProvider
      $ip = request()->ip() ?? request()->header('X-Forwarded-For');
      

Debugging

  • Check Request IP:
    dd(request()->ip(), request()->server('REMOTE_ADDR'));
    
  • Bypass Firewall Temporarily: Add this to app/Http/Middleware/TrustProxies.php (for testing):
    protected $proxies = '*'; // Bypass all firewall checks
    
  • Log Blocked Attempts: Extend the middleware to log denied requests:
    // app/Http/Middleware/Firewall.php
    public function handle($request, Closure $next) {
        if (!$this->isWhitelisted($request->ip())) {
            Log::warning('Firewall blocked IP: ' . $request->ip());
            abort(403);
        }
        return $next($request);
    }
    

Extension Points

  1. Custom Block Page Override the default block view by publishing assets:

    php artisan vendor:publish --tag="firewall-views"
    

    Then modify resources/views/vendor/firewall/block.blade.php.

  2. Dynamic Whitelists Fetch IPs from an external source (e.g., database):

    // config/firewall.php
    'whitelist' => function () {
        return WhitelistedIp::where('active', true)->pluck('ip')->toArray();
    },
    
  3. Multi-Tenant Support Scope whitelists to tenants:

    // In a middleware
    $tenantIp = Tenant::find(request()->tenant)->whitelistedIps;
    if (!in_array(request()->ip(), $tenantIp)) {
        abort(403);
    }
    
  4. API-Specific Rules Apply firewall logic to API routes only:

    Route::middleware(['firewall', 'api'])->group(function () {
        // API routes here
    });
    

Pro Tips

  • Environment-Specific Configs: Use firewall.php overrides for staging/prod:

    // config/firewall.php
    'whitelist' => env('MOOX_FIREWALL_WHITELIST', []),
    

    Then set MOOX_FIREWALL_WHITELIST per environment.

  • Health Check Endpoint: Add a /health endpoint to verify firewall status:

    Route::get('/health', function () {
        return [
            'firewall' => Firewall::isWhitelisted() ? 'active' : 'blocked',
        ];
    });
    
  • CI/CD Integration: Temporarily disable the firewall in CI by setting:

    MOOX_FIREWALL_ENABLED=false
    

    in your .env.ci file.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours