Skip to content

A free open source IT asset/license management system

API/Settings: Added optional requirement for non-generic user agent

snipe7714179de8e7
diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php
index 5420152a41..1692602b2b 100644
--- a/app/Http/Controllers/SettingsController.php
+++ b/app/Http/Controllers/SettingsController.php
@@ -1151,11 +1151,47 @@ class SettingsController extends Controller
->where('oauth_clients.personal_access_client', true)
->count();
+ $setting = Setting::getSettings();
+ $blockApiUserAgents = (bool) old('block_api_user_agents', $setting?->block_api_user_agents);
+ $blockedApiUserAgents = old(
+ 'blocked_api_user_agents',
+ $setting?->blocked_api_user_agents ?? implode("\n", Setting::DEFAULT_BLOCKED_API_USER_AGENTS),
+ );
+ $blockBlankApiUserAgents = (bool) old('block_blank_api_user_agents', $setting?->block_blank_api_user_agents);
+
return view('settings.api', [
'personalAccessTokenCount' => $personalAccessTokenCount,
+ 'setting' => $setting,
+ 'blockApiUserAgents' => $blockApiUserAgents,
+ 'blockedApiUserAgents' => $blockedApiUserAgents,
+ 'blockBlankApiUserAgents' => $blockBlankApiUserAgents,
]);
}
+ /**
+ * Persist the API request-filter settings (User-Agent allow/block list)
+ * from the API settings page.
+ */
+ public function postApiRequestFilters(Request $request): RedirectResponse
+ {
+ if (is_null($setting = Setting::getSettings())) {
+ return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
+ }
+
+ $setting->block_api_user_agents = $request->boolean('block_api_user_agents');
+ $blockedUserAgents = trim((string) $request->input('blocked_api_user_agents', ''));
+ $setting->blocked_api_user_agents = $blockedUserAgents === '' ? null : $blockedUserAgents;
+ $setting->block_blank_api_user_agents = $request->boolean('block_blank_api_user_agents');
+
+ if ($setting->save()) {
+ return redirect()
+ ->to(route('settings.oauth.index').'#api-request-filters')
+ ->with('success', trans('admin/settings/message.update.success'));
+ }
+
+ return redirect()->back()->withInput()->withErrors($setting->getErrors());
+ }
+
/**
* Revoke a personal access token from the admin OAuth settings page.
*/
diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php
index 1774b4f9f7..ed573b3bfd 100644
--- a/app/Http/Kernel.php
+++ b/app/Http/Kernel.php
@@ -10,6 +10,7 @@ use App\Http\Middleware\CheckLocale;
use App\Http\Middleware\CheckPermissions;
use App\Http\Middleware\CheckUserIsActivated;
use App\Http\Middleware\EncryptCookies;
+use App\Http\Middleware\EnforceApiUserAgent;
use App\Http\Middleware\LogAuthedUserHeader;
use App\Http\Middleware\NoSessionStore;
use App\Http\Middleware\PreventBackHistory;
@@ -81,6 +82,7 @@ class Kernel extends HttpKernel
'api' => [
'auth:api',
+ EnforceApiUserAgent::class,
CheckLocale::class,
LogAuthedUserHeader::class,
SetPaginationDefaults::class,
diff --git a/app/Http/Middleware/EnforceApiUserAgent.php b/app/Http/Middleware/EnforceApiUserAgent.php
new file mode 100644
index 0000000000..10fbd9ed82
--- /dev/null
+++ b/app/Http/Middleware/EnforceApiUserAgent.php
@@ -0,0 +1,80 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Models\Setting;
+use Closure;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class EnforceApiUserAgent
+{
+ public function handle(Request $request, Closure $next): Response
+ {
+ $setting = Setting::getSettings();
+ $rawUserAgent = $request->header('User-Agent');
+ $userAgent = trim((string) $rawUserAgent);
+
+ // Blank-UA blocking is independent of the pattern-based master toggle: an admin
+ // can enable it on its own (or leave it off if they have an integration like Entra
+ // SCIM that legitimately sends a blank User-Agent).
+ if ($setting?->block_blank_api_user_agents && $userAgent === '') {
+ return $this->reject($rawUserAgent);
+ }
+
+ // Pattern-based blocking is gated behind block_api_user_agents so the textarea
+ // can be pre-populated with sensible defaults without auto-enabling blocking.
+ if (! $setting?->block_api_user_agents) {
+ return $next($request);
+ }
+
+ $patterns = $this->blockedPatterns($setting->blocked_api_user_agents);
+
+ if ($patterns === [] || $userAgent === '') {
+ return $next($request);
+ }
+
+ foreach ($patterns as $pattern) {
+ if (stripos($userAgent, $pattern) !== false) {
+ return $this->reject($rawUserAgent);
+ }
+ }
+
+ return $next($request);
+ }
+
+ /**
+ * Split the textarea contents into a clean list of patterns. Lines are
+ * trimmed and blanks are dropped so the textarea ergonomics (trailing
+ * newlines, accidental whitespace) don't accidentally match every UA.
+ *
+ * @return array<int, string>
+ */
+ private function blockedPatterns(?string $raw): array
+ {
+ if ($raw === null || trim($raw) === '') {
+ return [];
+ }
+
+ return array_values(array_filter(array_map(
+ 'trim',
+ preg_split('/\r\n|\r|\n/', $raw) ?: [],
+ ), fn (string $line) => $line !== ''));
+ }
+
+ /**
+ * Echo the original, untrimmed User-Agent header back to the caller so they
+ * can see exactly what the server saw. Null means the header was absent.
+ */
+ private function reject(?string $userAgent): JsonResponse
+ {
+ return new JsonResponse([
+ 'status' => 'error',
+ 'messages' => trans('admin/settings/general.blocked_api_user_agent_rejected'),
+ 'payload' => [
+ 'user_agent' => $userAgent,
+ ],
+ ], Response::HTTP_FORBIDDEN);
+ }
+}
diff --git a/app/Models/Setting.php b/app/Models/Setting.php
index bc5d1e856e..df9cc97cfa 100755
--- a/app/Models/Setting.php
+++ b/app/Models/Setting.php
@@ -73,6 +73,39 @@ class Setting extends Model
'label2_asset_logo' => 'boolean',
'require_checkinout_notes' => 'boolean',
'manager_view_enabled' => 'boolean',
+ 'block_api_user_agents' => 'boolean',
+ 'block_blank_api_user_agents' => 'boolean',
+ ];
+
+ /**
+ * Suggested defaults for the "blocked API User-Agent patterns" textarea.
+ *
+ * Substrings (matched case-insensitively against the request's User-Agent)
+ * that identify common scripted or default HTTP clients. New installs see
+ * this list as the pre-filled textarea value; admins can add, remove, or
+ * blank it out entirely. Browser-driven AJAX (snipeit.js, datatables,
+ * select2, etc.) carries the browser's own User-Agent and is unaffected.
+ */
+ public const DEFAULT_BLOCKED_API_USER_AGENTS = [
+ 'curl/',
+ 'wget/',
+ 'python-requests/',
+ 'python-urllib',
+ 'PostmanRuntime/',
+ 'insomnia/',
+ 'Go-http-client/',
+ 'okhttp/',
+ 'HTTPie/',
+ 'Apache-HttpClient/',
+ 'Java/',
+ 'Faraday',
+ 'http.rb/',
+ 'libwww-perl/',
+ 'Ruby',
+ 'node-fetch/',
+ 'axios/',
+ 'GuzzleHttp/',
+ 'RestSharp/',
];
/**
diff --git a/database/migrations/2026_06_23_000001_add_blocked_api_user_agents_to_settings.php b/database/migrations/2026_06_23_000001_add_blocked_api_user_agents_to_settings.php
new file mode 100644
index 0000000000..49cccbd48d
--- /dev/null
+++ b/database/migrations/2026_06_23_000001_add_blocked_api_user_agents_to_settings.php
@@ -0,0 +1,33 @@
+<?php
+
+use App\Models\Setting;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ Schema::table('settings', function (Blueprint $table) {
+ $table->boolean('block_api_user_agents')->default(false)->after('null_company_is_floater');
+ $table->text('blocked_api_user_agents')->nullable()->after('block_api_user_agents');
+ $table->boolean('block_blank_api_user_agents')->default(false)->after('blocked_api_user_agents');
+ });
+
+ // Seed the textarea with the suggested defaults so admins don't have to type the list
+ // out themselves. Blocking stays off until block_api_user_agents is toggled on, so
+ // existing integrations are unaffected by the upgrade.
+ DB::table('settings')->update([
+ 'blocked_api_user_agents' => implode("\n", Setting::DEFAULT_BLOCKED_API_USER_AGENTS),
+ ]);
+ }
+
+ public function down(): void
+ {
+ Schema::table('settings', function (Blueprint $table) {
+ $table->dropColumn(['block_api_user_agents', 'blocked_api_user_agents', 'block_blank_api_user_agents']);
+ });
+ }
+};
diff --git a/resources/lang/en-US/admin/settings/general.php b/resources/lang/en-US/admin/settings/general.php
index b03b7171bc..c16830bbd3 100644
--- a/resources/lang/en-US/admin/settings/general.php
+++ b/resources/lang/en-US/admin/settings/general.php
@@ -164,6 +164,14 @@ return [
'login_remote_user_text' => 'Remote User login options',
'login_remote_user_enabled_text' => 'Enable Login with Remote User Header',
'login_remote_user_enabled_help' => 'This option enables Authentication via the REMOTE_USER header according to the "Common Gateway Interface (rfc3875)"',
+ 'api_request_filters' => 'Request Filtering',
+ 'block_api_user_agents_text' => 'Block API requests by User-Agent',
+ 'block_api_user_agents_help' => 'When enabled, API requests whose User-Agent matches any of the patterns below will be rejected.',
+ 'blocked_api_user_agents_text' => 'Blocked API User-Agent patterns',
+ 'blocked_api_user_agents_help' => 'One pattern per line, matched as a case-insensitive substring of the request\'s User-Agent. The textarea is pre-filled with common scripted clients (curl, Postman, python-requests, etc.). Add, remove, or clear lines as needed. ',
+ 'block_blank_api_user_agents_text' => 'Also reject API requests with a blank User-Agent',
+ 'block_blank_api_user_agents_help' => 'When enabled, API requests that arrive without a User-Agent header (or with an empty one) are rejected. <strong>Leave this off if you have integrations that legitimately send an empty User-Agent, for example, Microsoft Entra ID SCIM provisioning.</strong>',
+ 'blocked_api_user_agent_rejected' => 'This API endpoint rejected the request based on its User-Agent.',
'login_common_disabled_text' => 'Disable other authentication mechanisms',
'login_common_disabled_help' => 'This option disables other authentication mechanisms. Just enable this option if you are sure that your REMOTE_USER login is already working',
'login_remote_user_custom_logout_url_text' => 'Custom logout URL',
diff --git a/resources/views/layouts/default.blade.php b/resources/views/layouts/default.blade.php
index ee1a266d45..371b271493 100644
--- a/resources/views/layouts/default.blade.php
+++ b/resources/views/layouts/default.blade.php
@@ -316,6 +316,7 @@
input[type="radio"]:disabled,
input[readonly],
textarea[readonly],
+ textarea:disabled,
.select2-container--default.select2-container--disabled .select2-selection--single,
.select2-container--default.select2-container--disabled .select2-selection--multiple,
.select2-container--default.select2-container--disabled .select2-selection__rendered,
diff --git a/resources/views/settings/api.blade.php b/resources/views/settings/api.blade.php
index 3e8b9311aa..4725d61972 100644
--- a/resources/views/settings/api.blade.php
+++ b/resources/views/settings/api.blade.php
@@ -14,6 +14,11 @@
<x-tabs>
<x-slot:tabnav>
+ <x-tabs.nav-item
+ name="api-request-filters"
+ :label="trans('admin/settings/general.api_request_filters')"
+ />
+
<x-tabs.nav-item
name="personal-access-tokens"
:label="trans('admin/settings/general.oauth_personal_access_tokens')"
@@ -32,6 +37,73 @@
</x-slot:tabnav>
<x-slot:tabpanes>
+ <x-tabs.pane name="api-request-filters">
+ <form class="form-horizontal" method="post" action="{{ route('settings.oauth.request_filters.save') }}" autocomplete="off">
+ {{ csrf_field() }}
+
+ <!-- Master: block by User-Agent -->
+ <div class="form-group {{ $errors->has('block_api_user_agents') ? 'error' : '' }}">
+ <div class="col-md-8 col-md-offset-3">
+ <label class="form-control">
+ <input type="hidden" name="block_api_user_agents" value="0"/>
+ <input type="checkbox" value="1" name="block_api_user_agents" id="block_api_user_agents" aria-controls="blocked_api_user_agents" @checked($blockApiUserAgents) />
+ <label for="block_api_user_agents">{{ trans('admin/settings/general.block_api_user_agents_text') }}</label>
+ </label>
+ <p class="help-block">
+ {{ trans('admin/settings/general.block_api_user_agents_help') }}
+ </p>
+ {!! $errors->first('block_api_user_agents', '<span class="alert-msg" aria-hidden="true">:message</span>') !!}
+ </div>
+ </div>
+
+ <!-- Blocked patterns textarea (enabled only when master is on) -->
+ <div class="form-group {{ $errors->has('blocked_api_user_agents') ? 'error' : '' }}">
+ <label for="blocked_api_user_agents" class="col-md-3 control-label">{{ trans('admin/settings/general.blocked_api_user_agents_text') }}</label>
+ <div class="col-md-5">
+ <textarea
+ class="form-control"
+ id="blocked_api_user_agents"
+ name="blocked_api_user_agents"
+ rows="10"
+ aria-describedby="blocked_api_user_agents_help"
+ @disabled(! $blockApiUserAgents)
+ >{{ $blockedApiUserAgents }}</textarea>
+ {!! $errors->first('blocked_api_user_agents', '<span class="alert-msg" aria-hidden="true">:message</span>') !!}
+
+ </div>
+ <div class="col-md-offset-3 col-md-8">
+ <p id="blocked_api_user_agents_help" class="help-block">
+ {{ trans('admin/settings/general.blocked_api_user_agents_help') }}
+ </p>
+ </div>
+ </div>
+
+ <!-- Reject blank User-Agents (independent toggle) -->
+ <div class="form-group {{ $errors->has('block_blank_api_user_agents') ? 'error' : '' }}">
+ <div class="col-md-8 col-md-offset-3">
+ <label class="form-control">
+ <input type="hidden" name="block_blank_api_user_agents" value="0"/>
+ <input type="checkbox" value="1" name="block_blank_api_user_agents" id="block_blank_api_user_agents" aria-label="block_blank_api_user_agents" @checked($blockBlankApiUserAgents) />
+ <label for="block_blank_api_user_agents">{{ trans('admin/settings/general.block_blank_api_user_agents_text') }}</label>
+ </label>
+ <p class="help-block">
+ <x-icon type="warning" class="text-warning"/>
+ {!! trans('admin/settings/general.block_blank_api_user_agents_help') !!}
+ </p>
+ {!! $errors->first('block_blank_api_user_agents', '<span class="alert-msg" aria-hidden="true">:message</span>') !!}
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="col-md-8 col-md-offset-3">
+ <button type="submit" class="btn btn-primary">
+ <x-icon type="checkmark"/> {{ trans('general.save') }}
+ </button>
+ </div>
+ </div>
+ </form>
+ </x-tabs.pane>
+
<x-tabs.pane name="authorized-applications">
<div class="oauth-tab-content">
<livewire:oauth-clients section="authorized-applications"/>
@@ -58,4 +130,22 @@
@section('moar_scripts')
@include ('partials.bootstrap-table', ['simple_view' => true])
+
+ <script nonce="{{ csrf_token() }}">
+ (function () {
+ var master = document.getElementById('block_api_user_agents');
+ var textarea = document.getElementById('blocked_api_user_agents');
+
+ if (!master || !textarea) {
+ return;
+ }
+
+ var sync = function () {
+ textarea.disabled = !master.checked;
+ };
+
+ master.addEventListener('change', sync);
+ sync();
+ })();
+ </script>
@endsection
diff --git a/routes/web.php b/routes/web.php
index 4f69d954a7..181c9d3149 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -237,6 +237,9 @@ Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'authorize:superuser
->breadcrumbs(fn (Trail $trail) => $trail->parent('settings.index')
->push(trans('admin/settings/general.oauth'), route('settings.oauth.index')));
+ Route::post('oauth/request-filters', [SettingsController::class, 'postApiRequestFilters'])
+ ->name('settings.oauth.request_filters.save');
+
Route::post('oauth/tokens/{token}/revoke', [SettingsController::class, 'revokePersonalAccessToken'])
->name('settings.oauth.tokens.revoke');
diff --git a/tests/Feature/Api/EnforceApiUserAgentTest.php b/tests/Feature/Api/EnforceApiUserAgentTest.php
new file mode 100644
index 0000000000..8b02da0e2c
--- /dev/null
+++ b/tests/Feature/Api/EnforceApiUserAgentTest.php
@@ -0,0 +1,152 @@
+<?php
+
+namespace Tests\Feature\Api;
+
+use App\Models\Setting;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+class EnforceApiUserAgentTest extends TestCase
+{
+ public function test_master_off_allows_matching_user_agents_to_pass()
+ {
+ // Master gate off — even with a populated pattern list, nothing should be blocked.
+ $this->settings->set([
+ 'block_api_user_agents' => '0',
+ 'blocked_api_user_agents' => "curl/\nPostmanRuntime/",
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', 'curl/8.5.0')
+ ->getJson(route('api.users.selectlist'))
+ ->assertOk();
+ }
+
+ public function test_master_on_blocks_matching_pattern_and_echoes_user_agent()
+ {
+ $this->settings->set([
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => "curl/\nPostmanRuntime/",
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', 'curl/8.5.0')
+ ->getJson(route('api.users.selectlist'))
+ ->assertForbidden()
+ ->assertJson([
+ 'status' => 'error',
+ 'payload' => ['user_agent' => 'curl/8.5.0'],
+ ]);
+ }
+
+ public function test_master_on_pattern_match_is_case_insensitive()
+ {
+ $this->settings->set([
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => 'curl/',
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', 'CURL/8.5.0')
+ ->getJson(route('api.users.selectlist'))
+ ->assertForbidden();
+ }
+
+ public function test_master_on_unmatched_user_agent_passes()
+ {
+ $this->settings->set([
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => "curl/\nPostmanRuntime/",
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0')
+ ->getJson(route('api.users.selectlist'))
+ ->assertOk();
+ }
+
+ public function test_master_on_blank_user_agent_passes_when_blank_blocking_is_off()
+ {
+ // The Entra SCIM scenario: pattern blocking is on, blanks are explicitly allowed.
+ $this->settings->set([
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => "curl/\nPostmanRuntime/",
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', '')
+ ->getJson(route('api.users.selectlist'))
+ ->assertOk();
+ }
+
+ public function test_blank_user_agent_blocked_when_blank_blocking_on_even_if_master_is_off()
+ {
+ // Blank blocking is independent of the master pattern gate.
+ $this->settings->set([
+ 'block_api_user_agents' => '0',
+ 'blocked_api_user_agents' => null,
+ 'block_blank_api_user_agents' => '1',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', '')
+ ->getJson(route('api.users.selectlist'))
+ ->assertForbidden()
+ ->assertJson([
+ 'status' => 'error',
+ 'payload' => ['user_agent' => ''],
+ ]);
+ }
+
+ public function test_whitespace_only_user_agent_treated_as_blank_and_echoed_verbatim()
+ {
+ $this->settings->set([
+ 'block_api_user_agents' => '0',
+ 'blocked_api_user_agents' => null,
+ 'block_blank_api_user_agents' => '1',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', ' ')
+ ->getJson(route('api.users.selectlist'))
+ ->assertForbidden()
+ ->assertJson([
+ 'payload' => ['user_agent' => ' '],
+ ]);
+ }
+
+ public function test_master_on_empty_pattern_lines_do_not_match_every_request()
+ {
+ // Without filtering, a blank line would be a zero-length substring that matches every UA.
+ $this->settings->set([
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => "curl/\n\n \n",
+ 'block_blank_api_user_agents' => '0',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->withHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0) Chrome/120.0.0.0')
+ ->getJson(route('api.users.selectlist'))
+ ->assertOk();
+ }
+
+ public function test_default_patterns_constant_is_non_empty()
+ {
+ $this->assertNotEmpty(Setting::DEFAULT_BLOCKED_API_USER_AGENTS);
+ $this->assertContains('curl/', Setting::DEFAULT_BLOCKED_API_USER_AGENTS);
+ }
+}
diff --git a/tests/Feature/Settings/ApiRequestFiltersTest.php b/tests/Feature/Settings/ApiRequestFiltersTest.php
new file mode 100644
index 0000000000..8caaa44c7c
--- /dev/null
+++ b/tests/Feature/Settings/ApiRequestFiltersTest.php
@@ -0,0 +1,106 @@
+<?php
+
+namespace Tests\Feature\Settings;
+
+use App\Models\Setting;
+use App\Models\User;
+use Tests\TestCase;
+
+class ApiRequestFiltersTest extends TestCase
+{
+ public function test_api_settings_page_requires_superuser()
+ {
+ $this->actingAs(User::factory()->create())
+ ->get(route('settings.oauth.index'))
+ ->assertForbidden();
+ }
+
+ public function test_api_request_filters_tab_renders_for_superuser()
+ {
+ $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('settings.oauth.index'))
+ ->assertOk()
+ ->assertSee('api-request-filters', false);
+ }
+
+ public function test_textarea_is_pre_filled_with_defaults_when_setting_is_null()
+ {
+ // Ensure the column starts unset.
+ Setting::getSettings()->forceFill(['blocked_api_user_agents' => null])->save();
+
+ $response = $this->actingAs(User::factory()->superuser()->create())
+ ->get(route('settings.oauth.index'))
+ ->assertOk();
+
+ $response->assertSee('curl/', false);
+ $response->assertSee('PostmanRuntime/', false);
+ }
+
+ public function test_post_persists_master_toggle_patterns_and_blank_flag()
+ {
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('settings.oauth.request_filters.save'), [
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => "curl/\nfoo-client/",
+ 'block_blank_api_user_agents' => '1',
+ ])
+ ->assertRedirect();
+
+ $fresh = Setting::getSettings()->fresh();
+ $this->assertTrue($fresh->block_api_user_agents);
+ $this->assertSame("curl/\nfoo-client/", $fresh->blocked_api_user_agents);
+ $this->assertTrue($fresh->block_blank_api_user_agents);
+ }
+
+ public function test_post_with_empty_textarea_clears_patterns_to_null()
+ {
+ Setting::getSettings()->forceFill(['blocked_api_user_agents' => 'curl/'])->save();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('settings.oauth.request_filters.save'), [
+ 'block_api_user_agents' => '1',
+ 'blocked_api_user_agents' => '',
+ 'block_blank_api_user_agents' => '0',
+ ])
+ ->assertRedirect();
+
+ $this->assertNull(Setting::getSettings()->fresh()->blocked_api_user_agents);
+ }
+
+ public function test_post_with_unchecked_master_persists_false_and_preserves_textarea()
+ {
+ // Saving with the master unchecked should turn blocking off but keep the textarea
+ // contents so the admin doesn't have to re-type the list to re-enable it later.
+ Setting::getSettings()->forceFill([
+ 'block_api_user_agents' => true,
+ 'blocked_api_user_agents' => "curl/\nfoo-client/",
+ ])->save();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('settings.oauth.request_filters.save'), [
+ // block_api_user_agents intentionally absent (unchecked + hidden=0 sentinel)
+ 'block_api_user_agents' => '0',
+ 'blocked_api_user_agents' => "curl/\nfoo-client/",
+ ])
+ ->assertRedirect();
+
+ $fresh = Setting::getSettings()->fresh();
+ $this->assertFalse($fresh->block_api_user_agents);
+ $this->assertSame("curl/\nfoo-client/", $fresh->blocked_api_user_agents);
+ }
+
+ public function test_post_without_blank_flag_treats_it_as_false()
+ {
+ Setting::getSettings()->forceFill(['block_blank_api_user_agents' => true])->save();
+
+ $this->actingAs(User::factory()->superuser()->create())
+ ->post(route('settings.oauth.request_filters.save'), [
+ 'block_api_user_agents' => '0',
+ 'blocked_api_user_agents' => '',
+ // block_blank_api_user_agents intentionally absent
+ ])
+ ->assertRedirect();
+
+ $this->assertFalse(Setting::getSettings()->fresh()->block_blank_api_user_agents);
+ }
+}