Skip to content

About

This package provides a whitelist and blacklist feature to restrict access to your Laravel application and Filament admin panel. For additional functionality, please refer to the Laravel Firewall package.

Topics

Resources

Contributing

Stars

43 stars

Watchers

1 watching

Forks

Repository files navigation

Filament Firewall

Filament Firewall cover: IP rules, rate limiting, and auto-bans

PHP 8.3 | 8.4 Laravel 12 | 13 Filament 5 PHPStan Level 10 License MIT

Standalone, cache-first, Octane-safe, multi-panel & multi-tenant firewall for Laravel 12/13 and Filament 5.

Rebuilt from the ground up in v5.0 with zero third-party firewall dependencies:

  • Cache-first & Octane-safe: Compiled IPv4/IPv6 CIDR rules and auto-ban counters live in Laravel Cache (0 SQL queries on hot/attack paths; immediate cache invalidation when rules change; zero Set-Cookie / session touches so CDN edge caching stays intact).

  • Dual modes:

    • Protect mode (filament-firewall.protect): Default for public sites & apps — allows visitors while blocking deny rules, fail2ban auto-bans, scanner probes (wp-login.php, .env, .git, path traversal, etc.), and excessive origin traffic.
    • Allowlist mode (filament-firewall.allowlist / WhitelistRangeMiddleware): Deny-by-default for locking down /admin panels to office/VPN IPs.
  • IPv4 & IPv6 CIDR rules: /0–/32 (IPv4) and /0–/128 (IPv6), temporary bans (expires_at), notes, and a self-lockout guard preventing admins from banning their own IP.

  • Security headers (filament-firewall.headers): X-Content-Type-Options, Referrer-Policy, Permissions-Policy, HSTS (HTTPS only), and X-Frame-Options (skipped when Content-Security-Policy already defines frame-ancestors).

  • Multi-panel & multi-tenant native: Independent per-panel resource toggles, per-panel Gate/closure authorization (authorizeViewUsing / authorizeManageUsing), custom auth guards, and optional tenant/site scoping (scopeUsing + FilamentFirewall::resolveScopeUsing).

  • Pairs with solution-forest/filament-loginguard: Optionally auto-bans IPs at the firewall layer when LoginLockedOut fires.

  • Experimental, optional AI review: AI-scored triage of blocked traffic with an admin review queue, optional temporary auto-bans, and visitor unblock appeals. Uses laravel/ai or a logged-in local CLI. Off by default and can be switched with a Laravel Pennant flag (details).

Project site · Changelog

Version compatibility

Filament Firewall Filament Laravel
5.x (current) ^5.8 12.x, 13.x
4.x ^5.0 11.x, 12.x, 13.x
3.x ^4.0 11.x, 12.x, 13.x
2.x ^3.0 10.x, 11.x, 12.x
1.x ^2.0 9.x, 10.x

The legacy rows show which Laravel majors Composer resolves with the latest Git tag in each line. Filament and other dependencies can require a later patch release within a listed Laravel major.

Versions 1.x–4.x use Akaunting Laravel Firewall. If you are moving to the standalone v5 release, follow the upgrade guide.

Installation

composer require solution-forest/filament-firewall:^5.0
php artisan filament-firewall:install

Register the plugin on any Filament v5 panel:

use SolutionForest\FilamentFirewall\Enums\FirewallMode;
use SolutionForest\FilamentFirewall\FilamentFirewallPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugin(
            FilamentFirewallPlugin::make()
                ->protectPanel(FirewallMode::Protect, securityHeaders: true)
                ->authorizeViewUsing(fn ($user): bool => (bool) $user->is_super_admin)
                ->authorizeManageUsing(fn ($user): bool => (bool) $user->is_super_admin),
        );
}

Multi-tenant / multi-site scoping

// Scope HTTP middleware evaluation (e.g. in AppServiceProvider::boot):
FilamentFirewall::resolveScopeUsing(fn (Request $request): ?string => $site ? 'site:'.$site->id : null);

// Scope the Filament Resources to the active tenant:
FilamentFirewallPlugin::make()
    ->scopeUsing(fn (): ?string => Filament::getTenant() ? 'site:'.Filament::getTenant()->getKey() : null);

protectPanel() evaluates panel requests with the panel's scopeUsing() when set, otherwise with the global FilamentFirewall::resolveScopeUsing() resolver. Panel middleware runs before Filament identifies the tenant, so a scopeUsing() callback used for request evaluation should not rely solely on Filament::getTenant() (read the tenant from the route, e.g. request()->route('tenant'), if needed).

Authorization (secure by default)

Capability Nothing configured Configured
View rules & blocked requests Any authenticated panel user authorizeViewUsing() callback or authorization.view Gate ability
Manage (create/edit/delete rules, Ban/Allow IP actions) Denied (resources are read-only and show a notice) authorizeManageUsing() callback, authorization.manage Gate ability, or (fallback) the configured view callback/ability
// Per panel:
FilamentFirewallPlugin::make()
    ->authorizeManageUsing(fn ($user): bool => $user->hasRole('security-admin'));

// Or globally via Gate abilities in config/filament-firewall.php:
'authorization' => ['view' => 'view-firewall', 'manage' => 'manage-firewall'],

Behind a reverse proxy / CDN

Warning

bypass.ips defaults to 127.0.0.1 and ::1. If a reverse proxy runs on the same host (nginx, Caddy, Cloudflare Tunnel, a Docker ingress) and neither filament-firewall.trusted_proxies nor Laravel's TrustProxies is configured, every visitor appears as 127.0.0.1 and bypasses the firewall. Configure trusted proxies (or remove the loopback entries). The firewall logs a warning (at most once per hour, cache-throttled) when a bypass IP sends X-Forwarded-For from an untrusted peer.

X-Forwarded-For entries with ports (203.0.113.7:5555, [2001:db8::1]:443) are normalized exactly like Laravel's $request->ip().

Important

Laravel Cloud, or TrustProxies::at('*'). When the app trusts every proxy (Laravel's '*', which Laravel Cloud turns on automatically), $request->ip() is the left-most X-Forwarded-For entry, which the client controls. The firewall then ignores $request->ip(). It starts from the TCP peer (REMOTE_ADDR) and walks X-Forwarded-For right to left past filament-firewall.trusted_proxies only. Set that list to your load balancer and CDN ranges, for example private ranges plus Cloudflare's published ranges:

'trusted_proxies' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7', /* Cloudflare ranges… */],

If it is empty, every visitor resolves to your load balancer. The firewall logs a warning (at most once an hour) when this happens. A trusted proxy is never auto-banned.

Auto-ban, rate limiting & retention defaults

  • Auto-ban: 5 probe strikes in 10 minutes → 60-minute ban. IPv6 is banned per /64 (auto_ban.ipv6_prefix). Temporary bans are enforced from cache keys (not the per-request rule list), persisted as expiring rules (capped at auto_ban.max_persisted = 10,000 rows) and re-hydrated from the DB after a cache flush.
  • Rate limit: 120 requests / 60 s per IP on routes using filament-firewall.protect. Livewire endpoints (livewire/*, livewire-*/*) and panel requests protected via protectPanel() are excluded by default (rate_limit.except_paths, rate_limit.apply_to_panels) so admins polling behind one NAT IP are not throttled.
  • Probe detection inspects only the decoded path (?q=../docs is not a strike).
  • Blocked-request events are deduped per IP (per /64 for IPv6) and reason, capped at events.max_per_minute, and pruned after 30 days by the scheduled filament-firewall:cleanup (enabled by default; requires the Laravel scheduler).

Middleware aliases

  • filament-firewall.protect (ProtectWithFirewall) — Protect mode (public & app routes)
  • filament-firewall.allowlist (AllowlistFirewall / WhitelistRangeMiddleware) — Allowlist mode (admin/VPN routes)
  • filament-firewall.headers (SecurityHeaders) — HTTP security headers

Artisan commands

php artisan filament-firewall:unban 203.0.113.10 [--scope=site:1]
php artisan filament-firewall:cleanup [--days=30]
php artisan filament-firewall:ai-review [--scope=site:1] [--limit=20]   # optional AI review
php artisan filament-firewall:ai-test

Optional AI review (experimental)

Warning

The AI review is an experimental feature. Its configuration, database table, prompts and behaviour may change in minor releases until it is marked stable. It is off by default, AI verdicts are judgment calls rather than proof, and it never runs on the request path. Try it on a staging site first.

Turning it on and off

The master switch is FILAMENT_FIREWALL_AI_ENABLED. To switch the feature at runtime without a deploy (for example, per environment or during an incident), add a Laravel Pennant feature flag:

composer require laravel/pennant
FILAMENT_FIREWALL_AI_ENABLED=true
FILAMENT_FIREWALL_AI_FEATURE=filament-firewall-ai
use Laravel\Pennant\Feature;

// AppServiceProvider::boot(): off until you activate it.
Feature::define('filament-firewall-ai', fn (): bool => false);

// Turn it on or off (tinker, a command, or an admin action). The flag uses Pennant's global (null) scope, so
// it applies to web requests, the scheduler and queues alike.
Feature::for(null)->activate('filament-firewall-ai');
Feature::for(null)->deactivate('filament-firewall-ai');
  • AI is on only when FILAMENT_FIREWALL_AI_ENABLED=true and the Pennant feature is active. FILAMENT_FIREWALL_AI_ENABLED=false always wins.
  • When it is off, nothing is scheduled, the AI Review page and Ask AI are hidden, and blocked visitors see no appeal link. Existing reviews and AI bans stay in place until they expire or an admin lifts them.
  • The result is cached for ai.feature_cache_seconds (30s) so the firewall's request path never queries Pennant storage. Call app(\SolutionForest\FilamentFirewall\Ai\AiManager::class)->forgetFeatureCache() after toggling to apply the change immediately.
  • If FILAMENT_FIREWALL_AI_FEATURE is set but Pennant is not installed, AI stays off.

How it works

The firewall can ask an AI model to triage blocked traffic. It is off until you enable it and configure a connection. When it is on, a scheduled job (every 15 minutes by default) does the following:

  1. Groups recent blocked requests per IP (IPv6 per /64) and skips bypassed, trusted-proxy and allowlisted IPs.
  2. Sends the model a summary for each IP: block reasons, counts, the most requested paths (without query strings) and user agents.
  3. Stores the model's verdict (malicious / benign / unsure), confidence (0–100), a one-sentence summary and its evidence in filament_firewall_ai_reviews for admins to review.
  4. By default, temporarily bans an IP when the model rates it malicious with at least 90% confidence. These bans have the rule source ai and are capped per day. The AI never allowlists or unbans anyone.

It never runs on the request path. If the model times out, returns an error or hits the budget, the run is skipped and traffic is not affected.

AI calls go through laravel/ai, so any provider it supports works. Configure providers and keys in config/ai.php (php artisan vendor:publish --tag=ai-config), then enable the review:

OPENAI_API_KEY=sk-...                   # or ANTHROPIC_API_KEY, GEMINI_API_KEY, XAI_API_KEY, OPENROUTER_API_KEY, ...
FILAMENT_FIREWALL_AI_ENABLED=true
FILAMENT_FIREWALL_AI_PROVIDER=openai    # provider name from config/ai.php (default: ai.default)
FILAMENT_FIREWALL_AI_MODEL=             # optional; the provider's default text model when empty

To use an OpenAI-compatible gateway (LiteLLM, Cloudflare AI Gateway, an in-house gateway, vLLM, LM Studio), use laravel/ai's openai-compatible provider:

OPENAI_COMPATIBLE_URL=https://ai-gateway.example.com/v1
OPENAI_COMPATIBLE_API_KEY=...
FILAMENT_FIREWALL_AI_PROVIDER=openai-compatible
FILAMENT_FIREWALL_AI_MODEL=your-model
php artisan filament-firewall:ai-test      # check the connection (sends no traffic data)
php artisan filament-firewall:ai-review    # run a review now [--scope=site:1] [--global] [--limit=20]

Multi-model consensus

So that one model's mistake can't ban anyone, you can have several models review every IP and only auto-ban when enough of them agree:

// config/filament-firewall.php
'ai' => [
    'consensus' => [
        'enabled' => true, // or FILAMENT_FIREWALL_AI_CONSENSUS=true
        'models' => [
            ['provider' => 'openai'],                        // inline laravel/ai entries…
            ['provider' => 'anthropic', 'model' => null],
            ['provider' => 'gemini'],
            // 'cli',                                        // …or connection names from ai.connections
        ],
        'min_agree' => 2,
    ],
],
  • Every model gets the same prompt. An auto-ban needs at least min_agree models to vote malicious with confidence ≥ ai.auto_ban.min_confidence (90). One very confident model is never enough.
  • Without that agreement, the review is still saved with the majority verdict (a tie gives unsure) for an admin to decide. Nothing is banned.
  • The AI Review page shows the agreement next to the verdict (for example Malicious 94% · 2/3 agree), and the Evidence modal lists each model's vote and reasoning. Appeals and Ask AI use the same panel.
  • If a model fails, it only loses its vote, and the error names the model. The run stops only when every model fails.
  • Each model counts as one call against ai.budget.max_calls_per_day, so a three-model panel costs three times as much per batch. Calls run one after another.
  • Set min_agree to the number of models to require a unanimous decision. If min_agree is higher than the number of models that answered, nothing is auto-banned.

Local subscription login (CLI driver, experimental)

Instead of an API key, reviews can run through a coding-agent CLI that is already installed and logged in with your subscription on the server:

FILAMENT_FIREWALL_AI_CONNECTION=cli
FILAMENT_FIREWALL_AI_CLI=claude          # claude | codex | cursor | opencode | pi | grok
FILAMENT_FIREWALL_AI_CLI_MODEL=          # optional, passed with the CLI's model flag
Preset Log in once with Runs
claude claude login (Claude Code) claude --print --output-format json --tools "" --json-schema … (prompt on stdin)
codex codex login (Codex CLI) codex exec --sandbox read-only --output-schema … --output-last-message … -
cursor cursor-agent login cursor-agent --print --output-format json --mode ask --trust …
opencode opencode auth login (any provider, incl. xAI Grok OAuth) opencode run --pure --agent plan …
pi pi, then /login pi --print --no-tools --no-session --no-context-files …
grok grok login (xAI Grok Build, beta) grok exec … (headless flags may change; override command if needed)
  • Each call runs in a fresh, empty temporary directory, with tools disabled or read-only where the CLI supports it, and one call at a time. The driver only runs the binary and never reads the CLI's stored credentials.

  • The CLI must be logged in for the OS user that runs it: the scheduler user for ai-review, and the PHP-FPM user for Ask AI and appeal scoring. It doesn't work on serverless hosts such as Laravel Cloud or Vapor.

  • Calls are slower than an API (from a few seconds to about 90s for Cursor). timeout defaults to 180 seconds.

  • To use another CLI or different flags, set filament-firewall.ai.connections.cli.command to a list of arguments. It supports {prompt}, {schema}, {schema_file}, {output_file} and {model} placeholders, and the prompt goes on stdin when there's no {prompt}.

  • Subscriptions are meant for personal use. Check that your plan's terms allow automated server use, and prefer an API key or gateway for production.

  • Privacy. By default the model receives a keyed hash of each IP (HMAC with APP_KEY), not the address itself (ai.privacy.hash_ip). Admins still see the real IP. Request paths and, unless you turn off ai.privacy.send_user_agent, user agents are sent to the provider you configure.

  • Cost. IPs are sent in batches (ai.review.batch_size), an IP is not reviewed again within ai.review.reuse_verdict_hours, and ai.budget.max_calls_per_day caps model calls per day.

  • Prompt injection. Paths and user agents are controlled by attackers. They are passed to the model as quoted data, and its answer is validated against a schema. The worst case is a temporary, capped ban, and allowlisted, bypassed and trusted-proxy IPs are never banned.

  • Custom backends. Register a driver with app(AiManager::class)->extend('name', fn (array $config): AiDriver => ...) and reference it from a connection's driver key in filament-firewall.ai.connections.

  • Testing your app. Fake the model with laravel/ai: FirewallReviewAgent::fake([...]).

Human in the loop

ai.auto_ban.mode (FILAMENT_FIREWALL_AI_BAN_MODE) decides what happens when the AI is confident that an IP is malicious (and, with consensus, enough models agree):

Mode What the AI does What a human does
auto (default) Bans temporarily right away (auto_ban.duration_minutes, capped per day). Confirm ban to agree, Change ban to make it longer or permanent, or Unblock / Allow to undo it.
approve Blocks nothing. The review is marked Awaiting ban approval. Approve ban (choose the duration) or Reject ban.

Either way, the AI never allowlists or unbans anyone, and every decision records who made it and when. By default the AI Review page lists everything still waiting for a person: pending reviews, recommendations awaiting approval, and unconfirmed auto-bans. Set FILAMENT_FIREWALL_AI_AUTO_BAN=false to turn off both auto-bans and recommendations, so the AI only reports.

AI Review page and Ask AI

While AI is enabled, each panel gets an AI Review page next to Blocked Requests. Its badge counts the reviews that still need a human decision. Each row shows the AI verdict and confidence (for example Malicious 92%), the one-line summary, and the evidence behind it. Admins with manage permission can:

  • Ban / Approve ban / Change ban: ban the subject (the IPv4 address or the IPv6 /64) for the AI's duration, 7 days, 30 days, or permanently with a manual Deny rule.
  • Confirm ban: agree with an AI auto-ban and keep it as it is.
  • Unblock: lift the ban without allowlisting. This removes AI and other temporary bans, and any permanent rule created from that review.
  • Allow / Approve (for appeals): allowlist the IP permanently and lift any ban on it.
  • Dismiss / Reject ban / Reject (for appeals): close the review without blocking anything.

Ban, approve, confirm and dismiss also work as bulk actions. The self-lockout guard applies to every ban. Blocked Requests gets an Ask AI action that reviews one IP on demand: it looks back 24 hours and never auto-bans. To hide the page on a panel, use FilamentFirewallPlugin::make()->aiReviewsResource(false).

Visitor unblock appeals

When AI is enabled, a visitor blocked by a deny rule or a temporary ban (ai.appeals.reasons) sees a link in the 403 response. It opens a small form at /firewall/appeal (ai.appeals.path) where they can explain what they were doing.

  • The link is signed, expires after ai.appeals.link_ttl_minutes, and only works from the IP (or IPv6 /64) it was issued to. The form uses no session, cookies or CSRF token, and the path gets through the firewall on its own.
  • Each IP can send ai.appeals.max_per_ip_per_day appeals (default 1) and has at most one open appeal. A honeypot field drops simple bots.
  • The AI scores each appeal (is this a real person who was blocked by mistake?) after the response is sent, and the scheduled review catches anything missed. Appeals appear on the AI Review page with Approve and Reject. The AI never unblocks anyone. Only an admin's Approve does.
  • Signed links need correct absolute URLs. Behind a proxy, configure TrustProxies (or URL::forceScheme('https')) so the scheme and host match. Turn the feature off with FILAMENT_FIREWALL_AI_APPEALS=false.

Upgrading from v4.x

v5.0 is a standalone rewrite: akaunting/laravel-firewall is no longer used. Follow these steps in order.

  1. Update the Composer constraint

    composer require solution-forest/filament-firewall:^5.0

    If nothing else in your app uses akaunting/laravel-firewall, you may remove it afterwards (composer remove akaunting/laravel-firewall), together with its config/firewall.php.

  2. Publish and merge the new config

    php artisan vendor:publish --tag=filament-firewall-config --force

    The v4 config (models, resources, skip_whitelist_range) is replaced. Move any IPs from skip_whitelist_range into bypass.ips. Until you do, v5 still honours filament-firewall.skip_whitelist_range and akaunting's firewall.whitelist as bypass IPs, so nobody is locked out mid-upgrade.

  3. Run the migrations

    php artisan migrate

    This creates filament_firewall_rules and filament_firewall_events, then the import_v4_firewall_ips_into_filament_firewall_rules migration copies your v4 firewall_ips rows:

    • blocked = false → Allow rule, blocked = true → Deny rule;
    • ip and prefix_size are preserved; rows are imported as global rules (scope = null) with source v4_import; soft-deleted and invalid rows are skipped;
    • it is idempotent (safe to re-run) and never modifies or drops firewall_ips; drop it yourself once you have verified the import. Rolling the migration back removes only v4_import rules.

    If you publish migrations instead of letting the package run them, re-publish with php artisan vendor:publish --tag=filament-firewall-migrations so the import migration is included.

  4. Update code that used renamed APIs

    v4.x v5.0
    FilamentFirewall::withinWhitelist($ip) FilamentFirewall::withinAllowlist($ip, ?$scope)
    FilamentFirewall::withinBlackList($ip) FilamentFirewall::withinBlocklist($ip, ?$scope)
    getWhiteList() / getBlackList() / getFirewallIpModel() Query SolutionForest\FilamentFirewall\Models\FirewallRule (action = allow / deny)
    Models\Ip, FirewallIpResource Models\FirewallRule, FirewallRuleResource (+ FirewallEventResource)
    WhitelistRangeMiddleware Still available (alias of AllowlistFirewall, filament-firewall.allowlist)
    config('firewall.enabled') config('filament-firewall.enabled') / FILAMENT_FIREWALL_ENABLED
  5. Configure authorization (behaviour change)

    In v4 every panel user could manage the firewall. In v5, viewing requires an authenticated panel user and managing is denied until you configure authorizeManageUsing() (or authorizeViewUsing()) on the plugin or the authorization.manage / authorization.view Gate abilities. See Authorization.

  6. Review the new defaults (behaviour changes)

    • Localhost bypass: 127.0.0.1 / ::1 are bypassed. Behind a same-host reverse proxy configure trusted_proxies / TrustProxies first, otherwise everyone bypasses the firewall (see the warning above).
    • Rate limiting is on (120 req/min per IP) for routes using filament-firewall.protect; Livewire and panel requests are excluded by default.
    • Probe blocking & auto-ban are on: scanner paths (wp-login.php, .env, .git, …) return 404 and 5 strikes in 10 minutes ban the IP (IPv6: its /64) for 60 minutes.
    • HSTS: the filament-firewall.headers middleware (or protectPanel(..., securityHeaders: true)) sends Strict-Transport-Security: max-age=31536000; includeSubDomains on HTTPS responses. Set headers.strict_transport_security to null if any subdomain is not served over HTTPS.
    • Cleanup of expired rules and events older than 30 days is scheduled daily by default.
    • Unban (filament-firewall:unban, FilamentFirewall::unban()) only lifts temporary bans (auto_ban, loginguard, ban sources) in the given scope; manual Deny rules are removed in the UI.
  7. Allowlist panels: if you register the plugin with protectPanel(FirewallMode::Allowlist), make sure your office/VPN Allow rules were imported before deploying. The admin UI refuses to delete or edit the Allow rule that admits your own IP.

About

This package provides a whitelist and blacklist feature to restrict access to your Laravel application and Filament admin panel. For additional functionality, please refer to the Laravel Firewall package.

Topics

Resources

Contributing

Stars

43 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages